forked from mooncatventures-group/ffmpegDecoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFrameExtractor.m
More file actions
executable file
·392 lines (300 loc) · 11.3 KB
/
FrameExtractor.m
File metadata and controls
executable file
·392 lines (300 loc) · 11.3 KB
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
//
// Video.m
// iFrameExtractor
//
#import "FrameExtractor.h"
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
@interface FrameExtractor (private)
-(void)convertFrameToRGB;
-(UIImage *)imageFromAVPicture:(AVPicture)pict width:(int)width height:(int)height;
-(void)savePicture:(AVPicture)pFrame width:(int)width height:(int)height index:(int)iFrame;
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image size:(CGSize) size;
-(CGImageRef)CGImageRefFromAVPicture:(AVPicture)pict width:(int)width height:(int)height;
-(CMSampleBufferRef) cmSampleBufferFromCGImage: (CGImageRef) image size:(CGSize) size;
-(void)setupScaler;
@end
@implementation FrameExtractor
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
AVFrame *pFrame;
AVPicture picture;
int videoStream;
struct SwsContext *img_convert_ctx;
@synthesize outputWidth, outputHeight;
@synthesize cgimageDelegate;
@synthesize pvpixelDelegate;
@synthesize cmsampleDelegate;
-(void)setOutputWidth:(int)newValue {
if (outputWidth == newValue) return;
outputWidth = newValue;
[self setupScaler];
}
-(void)setOutputHeight:(int)newValue {
if (outputHeight == newValue) return;
outputHeight = newValue;
[self setupScaler];
}
-(UIImage *)currentImage {
if (!pFrame->data[0]) return nil;
[self convertFrameToRGB];
return [self imageFromAVPicture:picture width:outputWidth height:outputHeight];
}
-(CVPixelBufferRef)cvPixelBufferRef {
if (!pFrame->data[0]) return nil;
[self convertFrameToRGB];
CGImageRef cgImage = [self CGImageRefFromAVPicture:picture width:outputWidth height:outputHeight];
return [self pixelBufferFromCGImage:cgImage size:CGSizeMake(outputWidth, outputHeight)];
}
-(CMSampleBufferRef)cmSampleBufferRef {
if (!pFrame->data[0]) return nil;
[self convertFrameToRGB];
CGImageRef cgImage = [self CGImageRefFromAVPicture:picture width:outputWidth height:outputHeight];
return [self cmSampleBufferFromCGImage:cgImage size:CGSizeMake(outputWidth, outputHeight)];
}
-(double)duration {
return (double)pFormatCtx->duration / AV_TIME_BASE;
}
-(int)sourceWidth {
return pCodecCtx->width;
}
-(int)sourceHeight {
return pCodecCtx->height;
}
-(id)initWithVideo:(NSString *)moviePath {
if (!(self=[super init])) return nil;
AVCodec *pCodec;
// Register all formats and codecs
avcodec_register_all();
av_register_all();
// Open video file
// if(av_open_input_file(&pFormatCtx, "rtsp://a2047.v1412b.c1412.g.vq.akamaistream.net/5/2047/1412/1_h264_350/1a1a1ae555c531960166d//f4dbc3095c327960d7be756b71b49aa1576e344addb3ead1a497aaedf11/8848125_1_350.mov", NULL, 0, NULL)!=0)
// goto initError; // Couldn't open file
if(av_open_input_file(&pFormatCtx, [moviePath UTF8String], NULL, 0, NULL)!=0)
goto initError; // Couldn't open file
// Retrieve stream information
if(av_find_stream_info(pFormatCtx)<0)
goto initError; // Couldn't find stream information
// Find the first video stream
videoStream=-1;
for(int i=0; i<pFormatCtx->nb_streams; i++)
if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
{
videoStream=i;
break;
}
if(videoStream==-1)
goto initError; // Didn't find a video stream
// Get a pointer to the codec context for the video stream
pCodecCtx=pFormatCtx->streams[videoStream]->codec;
// Find the decoder for the video stream
pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
if(pCodec==NULL)
goto initError; // Codec not found
// Open codec
if(avcodec_open(pCodecCtx, pCodec)<0)
goto initError; // Could not open codec
// Allocate video frame
pFrame=avcodec_alloc_frame();
outputWidth = pCodecCtx->width;
self.outputHeight = pCodecCtx->height;
return self;
initError:
[self release];
NSLog(@"an error occurred");
return nil;
}
-(void)setupScaler {
// Release old picture and scaler
avpicture_free(&picture);
sws_freeContext(img_convert_ctx);
// Allocate RGB picture
avpicture_alloc(&picture, PIX_FMT_RGB24, outputWidth, outputHeight);
// Setup scaler
static int sws_flags = SWS_FAST_BILINEAR;
img_convert_ctx = sws_getContext(pCodecCtx->width,
pCodecCtx->height,
pCodecCtx->pix_fmt,
outputWidth,
outputHeight,
PIX_FMT_RGB24,
sws_flags, NULL, NULL, NULL);
}
-(void)seekTime:(double)seconds {
AVRational timeBase = pFormatCtx->streams[videoStream]->time_base;
int64_t targetFrame = (int64_t)((double)timeBase.den / timeBase.num * seconds);
avformat_seek_file(pFormatCtx, videoStream, targetFrame, targetFrame, targetFrame, AVSEEK_FLAG_FRAME);
avcodec_flush_buffers(pCodecCtx);
}
-(void)dealloc {
// Free scaler
sws_freeContext(img_convert_ctx);
// Free RGB picture
avpicture_free(&picture);
// Free the YUV frame
av_free(pFrame);
// Close the codec
if (pCodecCtx) avcodec_close(pCodecCtx);
// Close the video file
if (pFormatCtx) av_close_input_file(pFormatCtx);
[super dealloc];
}
-(BOOL)stepFrame {
AVPacket packet;
int frameFinished=0;
while(!frameFinished && av_read_frame(pFormatCtx, &packet)>=0) {
// Is this a packet from the video stream?
if(packet.stream_index==videoStream) {
// Decode video frame
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
}
// Free the packet that was allocated by av_read_frame
av_free_packet(&packet);
}
return frameFinished!=0;
}
-(void)convertFrameToRGB {
sws_scale (img_convert_ctx, pFrame->data, pFrame->linesize,
0, pCodecCtx->height,
picture.data, picture.linesize);
}
-(UIImage *)imageFromAVPicture:(AVPicture)pict width:(int)width height:(int)height {
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, pict.data[0], pict.linesize[0]*height,kCFAllocatorNull);
CGDataProviderRef provider = CGDataProviderCreateWithCFData(data);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageRef cgImage = CGImageCreate(width,
height,
8,
24,
pict.linesize[0],
colorSpace,
bitmapInfo,
provider,
NULL,
NO,
kCGRenderingIntentDefault);
CGColorSpaceRelease(colorSpace);
UIImage *image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
CGDataProviderRelease(provider);
CFRelease(data);
return image;
}
-(CGImageRef)CGImageRefFromAVPicture:(AVPicture)pict width:(int)width height:(int)height {
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, pict.data[0], pict.linesize[0]*height,kCFAllocatorNull);
CGDataProviderRef provider = CGDataProviderCreateWithCFData(data);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageRef cgImage = CGImageCreate(width,
height,
8,
24,
pict.linesize[0],
colorSpace,
bitmapInfo,
provider,
NULL,
NO,
kCGRenderingIntentDefault);
return cgImage;
}
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image size:(CGSize) size
{
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
[NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
nil];
CVPixelBufferRef pxbuffer = NULL;
CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, size.width,
size.height, kCVPixelFormatType_32ARGB, (CFDictionaryRef) options,
&pxbuffer);
NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
CVPixelBufferLockBaseAddress(pxbuffer, 0);
void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
NSParameterAssert(pxdata != NULL);
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pxdata, size.width,
size.height, 8, 4*size.width, rgbColorSpace,
kCGImageAlphaNoneSkipFirst);
NSParameterAssert(context);
CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
CGImageGetHeight(image)), image);
CGColorSpaceRelease(rgbColorSpace);
CGContextRelease(context);
CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
return pxbuffer;
}
- (CMSampleBufferRef) cmSampleBufferFromCGImage: (CGImageRef) image size:(CGSize) size
{
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
[NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
nil];
CVPixelBufferRef pxbuffer = NULL;
CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, size.width,
size.height, kCVPixelFormatType_32ARGB, (CFDictionaryRef) options,
&pxbuffer);
NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
CVPixelBufferLockBaseAddress(pxbuffer, 0);
void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
NSParameterAssert(pxdata != NULL);
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pxdata, size.width,
size.height, 8, 4*size.width, rgbColorSpace,
kCGImageAlphaNoneSkipFirst);
NSParameterAssert(context);
CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
CGImageGetHeight(image)), image);
CGColorSpaceRelease(rgbColorSpace);
CGContextRelease(context);
CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
CMVideoFormatDescriptionRef videoInfo = NULL;
CMSampleBufferRef sampleBuffer = NULL;
CMSampleBufferCreateForImageBuffer(kCFAllocatorDefault,
pxbuffer, true, NULL, NULL, videoInfo, NULL, &sampleBuffer);
return sampleBuffer;
}
-(void)setupCgimageSession {
lastFrameTime = -1;
// seek to 0.0 seconds
[self seekTime:0.0];
NSLog(@"setting timer");
[NSTimer scheduledTimerWithTimeInterval:kPollingInterval
target:self
selector:@selector(displayNextImageBuffer:)
userInfo:nil
repeats:YES];
}
-(void)displayNextImageBuffer:(NSTimer *)timer {
[cgimageDelegate didOutputCGImageBuffer:timer];
}
-(void)setupPVimageSession {
lastFrameTime = -1;
// seek to 0.0 seconds
[self seekTime:0.0];
[NSTimer scheduledTimerWithTimeInterval:kPollingInterval
target:self
selector:@selector(displayNextPVBuffer:)
userInfo:nil
repeats:YES];
}
-(void)displayNextPVBuffer:(NSTimer *)timer {
[pvpixelDelegate didOutputPixelBuffer:timer];
}
-(void)setupCmsampleSession {
lastFrameTime = -1;
// seek to 0.0 seconds
[self seekTime:0.0];
[NSTimer scheduledTimerWithTimeInterval:kPollingInterval
target:self
selector:@selector(displayNextCMSampleBuffer:)
userInfo:nil
repeats:YES];
}
-(void)displayNextCMSampleBuffer:(NSTimer *)timer {
[cmsampleDelegate didOutputSampleBuffer:timer];
}
@end