forked from samiamwork/Movist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFFVideoTrack.m
618 lines (541 loc) · 15.8 KB
/
FFVideoTrack.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//
// 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 PacketQueue : NSObject
{
AVPacket* _packet;
unsigned int _capacity;
unsigned int _front;
unsigned int _rear;
NSRecursiveLock* _mutex;
}
- (id)initWithCapacity:(unsigned int)capacity;
- (void)clear;
- (BOOL)isEmpty;
- (BOOL)isFull;
- (BOOL)putPacket:(const AVPacket*)packet;
- (BOOL)getPacket:(AVPacket*)packet;
@end
////////////////////////////////////////////////////////////////////////////////
#pragma mark -
@implementation PacketQueue
- (id)initWithCapacity:(unsigned int)capacity
{
//TRACE(@"%s %d", __PRETTY_FUNCTION__, capacity);
self = [super init];
if (self) {
_packet = malloc(sizeof(AVPacket) * capacity);
_capacity = capacity;
_front = 0;
_rear = 0;
_mutex = [[NSRecursiveLock alloc] init];
}
return self;
}
- (void)dealloc
{
//TRACE(@"%s", __PRETTY_FUNCTION__);
[self clear];
free(_packet);
[_mutex release];
[super dealloc];
}
- (BOOL)isEmpty { return (_front == _rear); }
- (BOOL)isFull { return (_front == (_rear + 1) % _capacity); }
- (void)clear
{
[_mutex lock];
unsigned int i;
for (i = _front; i != _rear; i = (i + 1) % _capacity) {
av_free_packet(&_packet[i]);
}
_rear = _front;
[_mutex unlock];
}
- (BOOL)putPacket:(const AVPacket*)packet
{
//TRACE(@"%s", __PRETTY_FUNCTION__);
if ([self isFull]) {
return FALSE;
}
_packet[_rear] = *packet;
_rear = (_rear + 1) % _capacity;
return TRUE;
}
- (BOOL)getPacket:(AVPacket*)packet
{
//TRACE(@"%s", __PRETTY_FUNCTION__);
[_mutex lock];
if ([self isEmpty]) {
[_mutex unlock];
return FALSE;
}
*packet = _packet[_front];
_front = (_front + 1) % _capacity;
[_mutex unlock];
return TRUE;
}
@end
////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#define RGB_PIXEL_FORMAT PIX_FMT_YUYV422
//#undef RGB_PIXEL_FORMAT
//#define RGB_PIXEL_FORMAT PIX_FMT_BGRA // PIX_FMT_ARGB is not supported by ffmpeg
@interface ImageQueue : NSObject
{
CVPixelBufferRef* _pixelBuffer;
AVFrame** _frame;
double* _time;
unsigned int _capacity;
unsigned int _front;
unsigned int _rear;
BOOL _full;
NSRecursiveLock* _mutex;
}
@end
@implementation ImageQueue
- (id)initWithCapacity:(unsigned int)capacity width:(int)width height:(int)height
{
self = [super init];
if (!self) {
return 0;
}
_pixelBuffer = (CVPixelBufferRef*)malloc(sizeof(CVPixelBufferRef) * capacity);
_frame = (AVFrame**)malloc(sizeof(AVFrame*) * capacity);
_time = (double*)malloc(sizeof(double) * capacity);
_capacity = capacity;
_front = _rear = 0;
_full = FALSE;
int bufWidth = width;
if (isSystemTiger()) {
bufWidth += 37;
if (bufWidth < 512) {
bufWidth = 512 + 37;
}
}
bufWidth = (bufWidth + 31) / 32 * 32;
int bufSize = avpicture_get_size(RGB_PIXEL_FORMAT, bufWidth , height);
int i, ret;
for (i = 0; i < _capacity; i++) {
_frame[i] = avcodec_alloc_frame();
if (_frame[i] == 0) {
TRACE(@"ERROR_FFMPEG_FRAME_ALLOCATE_FAILED");
[self release];
return nil;
}
avpicture_fill((AVPicture*)_frame[i], malloc(bufSize),
RGB_PIXEL_FORMAT, bufWidth, height);
ret = CVPixelBufferCreateWithBytes(0, width, height, k2vuyPixelFormat,
_frame[i]->data[0], _frame[i]->linesize[0],
0, 0, 0, &_pixelBuffer[i]);
if (ret != kCVReturnSuccess) {
// TODO: clean up our mess
TRACE(@"kCVPixelBufferCreateWithBytes() failed : %d", ret);
[self release];
return nil;
}
}
_mutex = [[NSRecursiveLock alloc] init];
return self;
}
- (void)dealloc
{
[_mutex release];
int i;
for (i = 0; i < _capacity; i++) {
if (_frame[i]) {
CVOpenGLTextureRelease(_pixelBuffer[i]);
free(_frame[i]->data[0]);
av_free(_frame[i]);
_frame[i] = 0;
}
}
free(_pixelBuffer);
free(_frame);
free(_time);
[super dealloc];
}
- (int)capacity
{
return _capacity;
}
- (int)count
{
return (_capacity + _rear - _front) % _capacity;
}
- (BOOL)isEmpty
{
return (_front == _rear && !_full);
}
- (BOOL)isFull
{
return (_front == _rear && _full);
}
- (void)clear
{
[_mutex lock];
_rear = _front;
[_mutex unlock];
}
- (AVFrame*)front
{
return _frame[_front];
}
- (AVFrame*)back
{
return _frame[_rear];
}
- (CVPixelBufferRef)pixelBuffer
{
return _pixelBuffer[_front];
}
- (double)time
{
return _time[_front];
}
- (void)enqueue:(AVFrame*)frame time:(double)time
{
_time[_rear] = time;
_rear = (_rear + 1) % _capacity;
if (_rear == _front) {
_full = TRUE;
}
}
- (void)dequeue
{
_front = (_front + 1) % _capacity;
_full = FALSE;
}
- (void)lock
{
[_mutex lock];
}
- (void)unlock
{
[_mutex unlock];
}
@end
////////////////////////////////////////////////////////////////////////////////
#pragma mark -
@implementation FFVideoTrack
+ (id)videoTrackWithAVStream:(AVStream*)stream index:(int)index
{
return [[[FFVideoTrack alloc] initWithAVStream:stream index:index] autorelease];
}
- (BOOL)initTrack:(int*)errorCode videoQueueCapacity:(int)videoQueueCapacity
useFastDecoding:(BOOL)useFastDecoding
{
_enabled = FALSE;
_running = FALSE;
// context->coded_width/height can be reset by -initContext.
// so, we should remember them before -initContext.
AVCodecContext* context = _stream->codec;
float width = context->coded_width;
float height= context->coded_height;
// FIXME: temp. impl for convenience.
if (useFastDecoding) {
context->flags2 |= CODEC_FLAG2_FAST;
}
if (![super initTrack:errorCode]) {
return FALSE;
}
// allocate frame
_frame = avcodec_alloc_frame();
if (_frame == 0) {
*errorCode = ERROR_FFMPEG_FRAME_ALLOCATE_FAILED;
return FALSE;
}
#if !MOVIST_USE_SWSCALE
OSType qtPixFmt = ColorConversionDstForPixFmt(_stream->codec->pix_fmt);
ColorConversionFindFor(&_colorConvFunc, _stream->codec->pix_fmt, _frame, qtPixFmt);
#else
// init sw-scaler context
_scalerContext = sws_getContext(width, height, context->pix_fmt,
width, height, PIX_FMT_UYVY422,
SWS_FAST_BILINEAR, 0, 0, 0);
if (!_scalerContext) {
TRACE(@"cannot initialize conversion context");
*errorCode = ERROR_FFMPEG_SW_SCALER_INIT_FAILED;
return FALSE;
}
#endif
// init playback
_packetQueue = [[PacketQueue alloc] initWithCapacity:30 * 5]; // 30 fps * 5 sec.
_imageQueue = [[ImageQueue alloc] initWithCapacity:videoQueueCapacity
width:width height:height];
_useFrameDrop = _stream->r_frame_rate.num / _stream->r_frame_rate.den > 30;
_frameInterval = 1. * _stream->r_frame_rate.den / _stream->r_frame_rate.num;
_decodeStarted = FALSE;
_nextFrameTime = 0;
_nextFramePts = 0;
_running = TRUE;
[NSThread detachNewThreadSelector:@selector(decodeThreadFunc:)
toTarget:self withObject:nil];
return TRUE;
}
- (BOOL)setOpenGLContext:(NSOpenGLContext*)openGLContext
pixelFormat:(NSOpenGLPixelFormat*)openGLPixelFormat
error:(NSError**)error
{
CVReturn cvRet = CVOpenGLTextureCacheCreate(0, 0,
[openGLContext CGLContextObj],
[openGLPixelFormat CGLPixelFormatObj],
0, &_textureCache);
if (cvRet != kCVReturnSuccess) {
//TRACE(@"CVOpenGLTextureCacheCreate() failed: %d", cvRet);
if (error) {
NSDictionary* dict =
[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:cvRet]
forKey:@"returnCode"];
*error = [NSError errorWithDomain:@"FFVideoTrack"
code:ERROR_VISUAL_CONTEXT_CREATE_FAILED
userInfo:dict];
}
return FALSE;
}
return TRUE;
}
- (void)cleanupTrack
{
assert(!_running);
# if MOVIST_USE_SWSCALE
if (_scalerContext) {
av_free(_scalerContext);
_scalerContext = 0;
}
# endif
if (_frame) {
av_free(_frame);
_frame = 0;
}
if (_textureCache) {
CVOpenGLTextureCacheRelease(_textureCache);
_textureCache = nil;
}
[_imageQueue release];
[_packetQueue release];
_packetQueue = 0;
[super cleanupTrack];
}
- (BOOL)isIndexComplete
{
return _stream->nb_index_entries == _stream->nb_frames ||
128 < _stream->nb_index_entries;
}
- (BOOL)isQueueEmpty
{
return [_packetQueue isEmpty];
}
- (BOOL)isQueueFull
{
return [_packetQueue isFull];
}
- (BOOL)isDecodeStarted
{
return _decodeStarted;
}
- (void)enablePtsAdjust:(BOOL)enable
{
_needPtsAdjust = enable;
}
- (double)decodePacket
{
AVPacket packetInst;
AVPacket* packet = &packetInst;
if (![_packetQueue getPacket:packet]) {
//TRACE(@"%s no more packet", __PRETTY_FUNCTION__);
return -1;
}
if (packet->stream_index != _streamIndex) {
TRACE(@"%s invalid stream_index %d", __PRETTY_FUNCTION__, packet->stream_index);
if (packet->data != s_flushPacket.data) {
av_free_packet(packet);
}
return -1;
}
assert(packet->stream_index == _streamIndex);
if (packet->data == s_flushPacket.data) {
TRACE(@"%s avcodec_flush_buffers", __PRETTY_FUNCTION__);
avcodec_flush_buffers(_stream->codec);
return -1;
}
int gotFrame;
int bytesDecoded = avcodec_decode_video2(_stream->codec, _frame,
&gotFrame, packet);
av_free_packet(packet);
if (bytesDecoded < 0) {
TRACE(@"%s error while decoding frame", __PRETTY_FUNCTION__);
return -1;
}
if (!gotFrame) {
TRACE(@"%s incomplete decoded frame", __PRETTY_FUNCTION__);
return -1;
}
int64_t pts = 0;
if (packet->dts != AV_NOPTS_VALUE) {
pts = packet->dts;
}
else if (_frame->opaque && *(uint64_t*)_frame->opaque != AV_NOPTS_VALUE) {
pts = *(uint64_t*)_frame->opaque;
}
double time = (double)(pts) * av_q2d(_stream->time_base) - _startTime;
//TRACE(@"[%s] frame flag %d pts %lld dts %lld pos %lld time %f", __PRETTY_FUNCTION__,
// _frame->pict_type,
// packet.pts, packet.dts,
// packet.pos, time);
return time;
}
- (BOOL)convertImage:(AVFrame*) frame
{
#if !MOVIST_USE_SWSCALE
unsigned width = [_movie encodedSize].width;
unsigned height = [_movie encodedSize].height;
_colorConvFunc.convert(_frame, frame->data[0], frame->linesize[0], width, height);
#else
// sw-scaler should be used under GPL only!
int ret = sws_scale(_scalerContext,
(const uint8_t* const*)_frame->data, _frame->linesize,
0, [_movie encodedSize].height,
frame->data, frame->linesize);
if (ret < 0) {
TRACE(@"%s sws_scale() failed : %d", __PRETTY_FUNCTION__, ret);
return FALSE;
}
#endif
return TRUE;
}
- (void)clearQueue
{
[_packetQueue clear];
[self putPacket:&s_flushPacket];
[_imageQueue clear];
}
- (void)putPacket:(AVPacket*)packet
{
av_dup_packet(packet);
[_packetQueue putPacket:packet];
}
- (void)decodeThreadFunc:(id)anObject
{
/*
TRACE(@"cur thread priority %f", [NSThread threadPriority]);
[NSThread setThreadPriority:0.9];
TRACE(@"set thread priority %f", [NSThread threadPriority]);
*/
NSAutoreleasePool* pool;
while (![_movie quitRequested]) {
pool = [[NSAutoreleasePool alloc] init];
_decodeStarted = TRUE;
if ([_imageQueue capacity] - 3 <= [_imageQueue count] ||
[_movie isPlayLocked] ||
![_movie canDecodeVideo]) {
_decodeStarted = FALSE;
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
[pool release];
continue;
}
double frameTime = [self decodePacket];
if (frameTime < 0) {
[pool release];
_decodeStarted = FALSE;
continue;
}
AVFrame* frame = [_imageQueue back];
[self convertImage:frame];
[_imageQueue enqueue:frame time:frameTime];
[_movie videoTrack:self decodedTime:frameTime];
_decodeStarted = FALSE;
[pool release];
}
_running = FALSE;
}
- (BOOL)isNewImageAvailable:(double)hostTime
hostTime0point:(double*)hostTime0point
{
if ([_imageQueue isEmpty]) {
//TRACE(@"not decoded %f", hostTime - *hostTime0point);
return FALSE;
}
// If we're not actievly playing then we're going to give them
// whatever we have at the front of the queue
if (hostTime < 0.0)
return TRUE;
// Check the time of the next image in the queue
// If the time requested is farther than a half a second from
// the image time assume we're getting out of sync and just
// adjust the host zero time so that the host time matches up
// with the current image time
double requestedTime = hostTime - *hostTime0point;
double imageTime = [_imageQueue time];
if (imageTime + 0.5 < requestedTime || requestedTime + 0.5 < imageTime) {
TRACE(@"reset av sync %f %f", requestedTime, imageTime);
*hostTime0point = hostTime - imageTime;
requestedTime = imageTime;
}
if (requestedTime < imageTime) {
//TRACE(@"wait %f < %f", current, imageTime);
return FALSE;
}
//TRACE(@"draw %f %f", current, imageTime);
return TRUE;
}
- (CVOpenGLTextureRef)nextImage:(double)hostTime
currentTime:(double*)currentTime
hostTime0point:(double*)hostTime0point
{
CVOpenGLTextureRef texture = NULL;
_dataPoppingStarted = TRUE;
if ([_movie isPlayLocked]) {
_dataPoppingStarted = FALSE;
return 0;
}
[_imageQueue lock];
CVPixelBufferRef pixelBuffer = NULL;
while ([self isNewImageAvailable:hostTime hostTime0point:hostTime0point])
{
pixelBuffer = [_imageQueue pixelBuffer];
*currentTime = [_imageQueue time];
if (hostTime >= 0.0)
{
[_imageQueue dequeue];
[[NSNotificationCenter defaultCenter]
postNotificationName:MMovieCurrentTimeNotification object:_movie];
}
else
break;
}
if (pixelBuffer)
{
int ret = CVOpenGLTextureCacheCreateTextureFromImage(0, _textureCache,
pixelBuffer, 0, &texture);
if (ret != kCVReturnSuccess) {
TRACE(@"CVOpenGLTextureCacheCreateTextureFromImage() failed : %d", ret);
}
CVOpenGLTextureCacheFlush(_textureCache, 0);
}
[_imageQueue unlock];
_dataPoppingStarted = FALSE;
return texture;
}
@end