-
Notifications
You must be signed in to change notification settings - Fork 54
/
FFAudioTrack_Analog.m
516 lines (468 loc) · 15.4 KB
/
FFAudioTrack_Analog.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//
// Movist
//
// Copyright 2006 ~ 2008 Yong-Hoe Kim, Cheol Ju. All rights reserved.
// Yong-Hoe Kim <[email protected]>
// Cheol Ju <[email protected]>
//
// This file is part of Movist.
//
// Movist is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// Movist is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#import "FFTrack.h"
#import "MMovie_FFMPEG.h"
/*
@interface AUCallbackInfo : NSObject
{
MMovie_FFmpeg* _movie;
int _streamId;
}
@end
*/
#define _USE_AUDIO_DATA_FLOAT_BIT
@interface AudioDataQueue : NSObject
{
int _bitRate;
UInt8* _data;
NSRecursiveLock* _mutex;
double _time;
unsigned int _capacity;
unsigned int _front;
unsigned int _rear;
}
@end
@implementation AudioDataQueue
- (id)initWithCapacity:(unsigned int)capacity
{
//TRACE(@"%s %d", __PRETTY_FUNCTION__, capacity);
self = [super init];
if (self) {
_data = malloc(sizeof(UInt8) * capacity);
_mutex = [[NSRecursiveLock alloc] init];
_capacity = capacity;
_front = 0;
_rear = 0;
}
return self;
}
- (void)dealloc
{
//TRACE(@"%s", __PRETTY_FUNCTION__);
free(_data);
[_mutex release];
[super dealloc];
}
- (void)clear
{
[_mutex lock];
_rear = _front;
[_mutex unlock];
}
- (BOOL)isEmpty { return (_front == _rear); }
- (BOOL)isFull { return (_front == (_rear + 1) % _capacity); }
- (int)bitRate { return _bitRate; }
- (int)dataSize
{
[_mutex lock];
int size = (_capacity + _rear - _front) % _capacity;
[_mutex unlock];
return size;
}
- (int)freeSize
{
return _capacity - 1 - [self dataSize];
}
- (void)setBitRate:(int)bitRate
{
_bitRate = bitRate;
}
- (BOOL)putData:(UInt8*)data size:(int)size time:(double)time
{
[_mutex lock];
if ([self freeSize] < size) {
[_mutex unlock];
return FALSE;
}
int i;
int rear = _rear;
for (i = 0; i < size; i++) {
_data[rear] = data[i];
rear = (rear + 1) % _capacity;
}
_time = time + 1. * size / _bitRate;
_rear = rear;
[_mutex unlock];
return TRUE;
}
- (BOOL)getData:(UInt8*)data size:(int)size time:(double*)time
{
[_mutex lock];
if ([self dataSize] < size) {
[_mutex unlock];
return FALSE;
}
*time = _time - 1. * ([self dataSize] - size)/ _bitRate;
int i;
for (i = 0; i < size; i++) {
data[i] = _data[_front];
_front = (_front + 1) % _capacity;
}
[_mutex unlock];
return TRUE;
}
- (void)removeDataDuring:(double)dt channelNumber:(int)channelNumber time:(double*)time
{
int size = dt * _bitRate;
int sizeUnit = channelNumber * sizeof(_data[0]);
size = size / sizeUnit * sizeUnit;
[_mutex lock];
int dataSize = [self dataSize];
if (dataSize < size) {
size = dataSize;
}
_front = (_front + size) % _capacity;
*time = _time - 1. * ([self dataSize] - size) / _bitRate;
[_mutex unlock];
//TRACE(@"data removed %f", dt);
}
- (void)getFirstTime:(double*)time
{
[_mutex lock];
*time = _time - 1. * [self dataSize] / _bitRate;
[_mutex unlock];
}
- (double)lastTime
{
return _time;
}
@end
////////////////////////////////////////////////////////////////////////////////
#pragma mark -
static OSStatus audioProc(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags,
const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber,
UInt32 inNumberFrames, AudioBufferList* ioData);
@implementation FFAudioTrack (Analog)
- (BOOL)initAudioUnit
{
if (_stream->codec->sample_fmt != SAMPLE_FMT_S16) {
TRACE(@"audio sample format is not signed short\n");
return false;
}
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
AudioComponent component = AudioComponentFindNext(0, &desc);
if (!component) {
TRACE(@"AudioComponentFindNext() failed");
return FALSE;
}
OSStatus err = AudioComponentInstanceNew(component, &_audioUnit);
if (!component) {
TRACE(@"AudioComponentInstanceNew() failed : %ld\n", err);
return FALSE;
}
AURenderCallbackStruct input;
input.inputProc = audioProc;
input.inputProcRefCon = self;
err = AudioUnitSetProperty(_audioUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input,
0, &input, sizeof(input));
if (err != noErr) {
TRACE(@"AudioUnitSetProperty(callback) failed : %ld\n", err);
return FALSE;
}
AVCodecContext* context = _stream->codec;
#ifdef _USE_AUDIO_DATA_FLOAT_BIT
UInt32 formatFlags = kAudioFormatFlagsNativeFloatPacked
| kAudioFormatFlagIsNonInterleaved;
UInt32 bytesPerPacket = 4;
UInt32 bytesPerFrame = 4;
UInt32 bitsPerChannel = 32;
#else
UInt32 formatFlags = kLinearPCMFormatFlagIsSignedInteger
| kAudioFormatFlagsNativeEndian
| kLinearPCMFormatFlagIsPacked
| kAudioFormatFlagIsNonInterleaved;
UInt32 bytesPerPacket = 2;
UInt32 bytesPerFrame = 2;
UInt32 bitsPerChannel = 16;
#endif
AudioStreamBasicDescription streamFormat;
streamFormat.mSampleRate = context->sample_rate;
streamFormat.mFormatID = kAudioFormatLinearPCM;
streamFormat.mFormatFlags = formatFlags;
streamFormat.mBytesPerPacket = bytesPerPacket;
streamFormat.mFramesPerPacket = 1;
streamFormat.mBytesPerFrame = bytesPerFrame;
streamFormat.mChannelsPerFrame = context->channels;
streamFormat.mBitsPerChannel = bitsPerChannel;
err = AudioUnitSetProperty(_audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0, &streamFormat, sizeof(streamFormat));
if (err != noErr) {
TRACE(@"AudioUnitSetProperty(streamFormat) failed : %ld\n", err);
return FALSE;
}
// Initialize unit
err = AudioUnitInitialize(_audioUnit);
if (err) {
TRACE(@"AudioUnitInitialize=%ld", err);
return FALSE;
}
Float64 outSampleRate;
UInt32 size = sizeof(Float64);
err = AudioUnitGetProperty(_audioUnit,
kAudioUnitProperty_SampleRate,
kAudioUnitScope_Output,
0, &outSampleRate, &size);
if (err) {
TRACE(@"AudioUnitSetProperty-GF=%4.4s, %ld", (char*)&err, err);
return FALSE;
}
return TRUE;
}
- (BOOL)initAnalogAudio:(int*)errorCode
{
// create audio unit
if (![self initAudioUnit]) {
*errorCode = ERROR_FFMPEG_AUDIO_UNIT_CREATE_FAILED;
return FALSE;
}
_volume = DEFAULT_VOLUME;
_speakerCount = 2;
// init playback
unsigned int queueCapacity = AVCODEC_MAX_AUDIO_FRAME_SIZE * 20 * 5;
_dataQueue = [[AudioDataQueue alloc] initWithCapacity:queueCapacity];
AVCodecContext* context = _stream->codec;
[_dataQueue setBitRate:sizeof(int16_t) * context->sample_rate * context->channels];
_nextDecodedTime = 0;
_nextAudioPts = 0;
return TRUE;
}
- (void)cleanupAnalogAudio
{
if (_audioUnit) {
//[self stopAudio];
while (AudioUnitUninitialize(_audioUnit) != 0) {
assert(FALSE);
}
while (AudioComponentInstanceDispose(_audioUnit) != 0) {
assert(FALSE);
}
_audioUnit = 0;
}
[_dataQueue clear];
[_dataQueue release];
_dataQueue = 0;
_running = FALSE;
}
- (void)startAnalogAudio
{
TRACE(@"%s", __PRETTY_FUNCTION__);
_running = TRUE;
while (AudioOutputUnitStart(_audioUnit) != 0) {
assert(FALSE);
//[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
}
- (void)stopAnalogAudio
{
while (AudioOutputUnitStop(_audioUnit) != 0) {
//assert(FALSE);
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
}
- (void)decodePacket:(AVPacket*)packet
{
AVCodecContext* context = _stream->codec;
if (packet->data == s_flushPacket.data) {
avcodec_flush_buffers(context);
return;
}
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
UInt8* packetPtr = packet->data;
int packetSize = packet->size;
int dataSize, decodedSize;
int64_t pts, nextPts;
double decodedTime;
BOOL newPacket = true;
int got_frame = 0;
//TRACE(@"dts = %lld * %lf = %lf", packet->dts, PTS_TO_SEC, 1. * packet->dts * PTS_TO_SEC);
while (0 < packetSize) {
dataSize = 0;
decodedSize = avcodec_decode_audio4(context, _decodedFrame, &got_frame, packet);
if (decodedSize < 0) {
TRACE(@"decodedSize < 0");
break;
}
packetPtr += decodedSize;
packetSize -= decodedSize;
if (newPacket) {
newPacket = FALSE;
if (packet->dts != AV_NOPTS_VALUE) {
pts = packet->dts;
nextPts = pts;
}
else {
//TRACE(@"packet.dts == AV_NOPTS_VALUE");
pts = _nextAudioPts;
//assert(FALSE);
}
}
dataSize = _decodedFrame->nb_samples * _stream->codec->request_channels * av_get_bytes_per_sample(_stream->codec->sample_fmt);
if (dataSize > 0) {
nextPts = pts + 1. * dataSize / [_dataQueue bitRate] / PTS_TO_SEC;
}
decodedTime = 1. * pts * PTS_TO_SEC - _startTime;
pts = nextPts;
if (0 < dataSize) {
if (AVCODEC_MAX_AUDIO_FRAME_SIZE < dataSize) {
TRACE(@"AVCODEC_MAX_AUDIO_FRAME_SIZE < dataSize");
assert(FALSE);
}
while (![_movie quitRequested] && [_dataQueue freeSize] < dataSize) {
if ([_movie reservedCommand] == COMMAND_SEEK || ![self isEnabled]) {
break;
}
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
}
[_dataQueue putData:(UInt8*)_decodedFrame->data[0] size:dataSize time:decodedTime];
_nextAudioPts = nextPts;
}
}
if (packet->data) {
av_free_packet(packet);
}
[pool release];
}
- (void)clearAnalogDataQueue
{
[_dataQueue clear];
[self decodePacket:&s_flushPacket];
_nextDecodedTime = 0;
}
#ifdef _USE_AUDIO_DATA_FLOAT_BIT
#define AUDIO_DATA_TYPE float
#else
#define AUDIO_DATA_TYPE int16_t
#endif
- (void)makeEmpty:(AUDIO_DATA_TYPE**)buf channelNumber:(int)channelNumber bufSize:(int)bufSize
{
int i;
for (i = 0; i < channelNumber; i++) {
memset(buf[i], 0, bufSize * sizeof(AUDIO_DATA_TYPE));
}
}
- (void)nextAudio:(const AudioTimeStamp*)timeStamp busNumber:(UInt32)busNumber
frameNumber:(UInt32)frameNumber audioData:(AudioBufferList*)ioData
{
const int MAX_AUDIO_CHANNEL_SIZE = 8;
const int AUDIO_BUF_SIZE = 44000 * MAX_AUDIO_CHANNEL_SIZE / 10;
int i, j;
int frameSize = sizeof(int16_t); // int16
int channelNumber = ioData->mNumberBuffers;
int requestSize = frameNumber * frameSize * channelNumber;
if (AUDIO_BUF_SIZE < requestSize) {
TRACE(@"AUDIO_BUF_SIZE(%d) < requestSize(%d)", AUDIO_BUF_SIZE, requestSize);
return;
//assert(requestSize < AUDIO_BUF_SIZE);
}
AUDIO_DATA_TYPE* dst[MAX_AUDIO_CHANNEL_SIZE];
for (i = 0; i < channelNumber; i++) {
dst[i] = ioData->mBuffers[i].mData;
assert(ioData->mBuffers[i].mDataByteSize == 4 * frameNumber);
assert(ioData->mBuffers[i].mNumberChannels == 1);
}
_dataPoppingStarted = TRUE;
if (![self isEnabled] ||
[_movie quitRequested] ||
[_movie reservedCommand] != COMMAND_NONE ||
[_movie isPlayLocked] ||
[_movie command] != COMMAND_PLAY ||
0 == [_movie hostTime0point] ||
[_dataQueue dataSize] < requestSize) {
[self makeEmpty:dst channelNumber:channelNumber bufSize:frameNumber];
[_dataQueue getFirstTime:&_nextDecodedTime];
[_movie audioTrack:self avFineTuningTime:0];
//double hostTime = 1. * timeStamp->mHostTime / [_movie hostTimeFreq];
//double currentTime = hostTime - [_movie hostTime0point];
//TRACE(@"currentTime(%f) audioTime %f make empty", currentTime, _nextDecodedTime);
_dataPoppingStarted = FALSE;
return;
}
double hostTime = 1. * timeStamp->mHostTime / [_movie hostTimeFreq];
double currentTime = hostTime - [_movie hostTime0point];
[_dataQueue getFirstTime:&_nextDecodedTime];
double dt = _nextDecodedTime - currentTime;
if (dt < -0.2 || 0.2 < dt) {
if (dt < 0) {
[_dataQueue removeDataDuring:-dt channelNumber:channelNumber time:&_nextDecodedTime];
//TRACE(@"remove dt:%f", dt);
if ([_dataQueue dataSize] < requestSize) {
[self makeEmpty:dst channelNumber:channelNumber bufSize:frameNumber];
[_movie audioTrack:self avFineTuningTime:0];
//TRACE(@"currentTime(%f) audioTime %f dt:%f", currentTime, _nextDecodedTime, dt);
_dataPoppingStarted = FALSE;
return;
}
dt = 0;
}
else {
[self makeEmpty:dst channelNumber:channelNumber bufSize:frameNumber];
[_movie audioTrack:self avFineTuningTime:0];
//TRACE(@"currentTime(%f) audioTime %f dt:%f", currentTime, _nextDecodedTime, dt);
_dataPoppingStarted = FALSE;
return;
}
}
else if (-0.01 < dt && dt < 0.01) {
dt = 0;
}
[_movie audioTrack:self avFineTuningTime:dt];
//TRACE(@"currentTime(%f) audioTime %f", currentTime, _nextDecodedTime);
int16_t audioBuf[AUDIO_BUF_SIZE];
[_dataQueue getData:(UInt8*)audioBuf size:requestSize time:&_nextDecodedTime];
float volume = [_movie muted] ? 0 : _volume;
for (i = 0; i < frameNumber; i++) {
for (j = 0; j < channelNumber; j++) {
#ifdef _USE_AUDIO_DATA_FLOAT_BIT
dst[j][i] = 1. * volume * audioBuf[channelNumber * i + j] / INT16_MAX;
#else
dst[j][i] = audioBuf[channelNumber * i + j];
#endif
}
}
if (_speakerCount == 2 && channelNumber == 6) {
for (i = 0; i < frameNumber; i++) {
dst[0][i] += dst[4][i] + (dst[2][i] + dst[3][i]) / 2;
dst[1][i] = 0;;
//dst[1][i] += dst[5][i] + (dst[2][i] + dst[3][i]) / 2;
}
}
_dataPoppingStarted = FALSE;
}
@end
static OSStatus audioProc(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags,
const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber,
UInt32 inNumberFrames, AudioBufferList* ioData)
{
[(FFAudioTrack*)inRefCon nextAudio:inTimeStamp busNumber:inBusNumber
frameNumber:inNumberFrames audioData:ioData];
return noErr;
}