]> git.sesse.net Git - ffmpeg/blob - libavdevice/avfoundation.m
lavc/libopenh264enc: set slice_mode option to deprecated
[ffmpeg] / libavdevice / avfoundation.m
1 /*
2  * AVFoundation input device
3  * Copyright (c) 2014 Thilo Borgmann <thilo.borgmann@mail.de>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * AVFoundation input device
25  * @author Thilo Borgmann <thilo.borgmann@mail.de>
26  */
27
28 #import <AVFoundation/AVFoundation.h>
29 #include <pthread.h>
30
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/avstring.h"
34 #include "libavformat/internal.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/time.h"
38 #include "libavutil/imgutils.h"
39 #include "avdevice.h"
40
41 static const int avf_time_base = 1000000;
42
43 static const AVRational avf_time_base_q = {
44     .num = 1,
45     .den = avf_time_base
46 };
47
48 struct AVFPixelFormatSpec {
49     enum AVPixelFormat ff_id;
50     OSType avf_id;
51 };
52
53 static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
54     { AV_PIX_FMT_MONOBLACK,    kCVPixelFormatType_1Monochrome },
55     { AV_PIX_FMT_RGB555BE,     kCVPixelFormatType_16BE555 },
56     { AV_PIX_FMT_RGB555LE,     kCVPixelFormatType_16LE555 },
57     { AV_PIX_FMT_RGB565BE,     kCVPixelFormatType_16BE565 },
58     { AV_PIX_FMT_RGB565LE,     kCVPixelFormatType_16LE565 },
59     { AV_PIX_FMT_RGB24,        kCVPixelFormatType_24RGB },
60     { AV_PIX_FMT_BGR24,        kCVPixelFormatType_24BGR },
61     { AV_PIX_FMT_0RGB,         kCVPixelFormatType_32ARGB },
62     { AV_PIX_FMT_BGR0,         kCVPixelFormatType_32BGRA },
63     { AV_PIX_FMT_0BGR,         kCVPixelFormatType_32ABGR },
64     { AV_PIX_FMT_RGB0,         kCVPixelFormatType_32RGBA },
65     { AV_PIX_FMT_BGR48BE,      kCVPixelFormatType_48RGB },
66     { AV_PIX_FMT_UYVY422,      kCVPixelFormatType_422YpCbCr8 },
67     { AV_PIX_FMT_YUVA444P,     kCVPixelFormatType_4444YpCbCrA8R },
68     { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
69     { AV_PIX_FMT_YUV444P,      kCVPixelFormatType_444YpCbCr8 },
70     { AV_PIX_FMT_YUV422P16,    kCVPixelFormatType_422YpCbCr16 },
71     { AV_PIX_FMT_YUV422P10,    kCVPixelFormatType_422YpCbCr10 },
72     { AV_PIX_FMT_YUV444P10,    kCVPixelFormatType_444YpCbCr10 },
73     { AV_PIX_FMT_YUV420P,      kCVPixelFormatType_420YpCbCr8Planar },
74     { AV_PIX_FMT_NV12,         kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
75     { AV_PIX_FMT_YUYV422,      kCVPixelFormatType_422YpCbCr8_yuvs },
76 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
77     { AV_PIX_FMT_GRAY8,        kCVPixelFormatType_OneComponent8 },
78 #endif
79     { AV_PIX_FMT_NONE, 0 }
80 };
81
82 typedef struct
83 {
84     AVClass*        class;
85
86     int             frames_captured;
87     int             audio_frames_captured;
88     int64_t         first_pts;
89     int64_t         first_audio_pts;
90     pthread_mutex_t frame_lock;
91     id              avf_delegate;
92     id              avf_audio_delegate;
93
94     AVRational      framerate;
95     int             width, height;
96
97     int             capture_cursor;
98     int             capture_mouse_clicks;
99     int             capture_raw_data;
100     int             drop_late_frames;
101     int             video_is_muxed;
102     int             video_is_screen;
103
104     int             list_devices;
105     int             video_device_index;
106     int             video_stream_index;
107     int             audio_device_index;
108     int             audio_stream_index;
109
110     char            *video_filename;
111     char            *audio_filename;
112
113     int             num_video_devices;
114
115     int             audio_channels;
116     int             audio_bits_per_sample;
117     int             audio_float;
118     int             audio_be;
119     int             audio_signed_integer;
120     int             audio_packed;
121     int             audio_non_interleaved;
122
123     int32_t         *audio_buffer;
124     int             audio_buffer_size;
125
126     enum AVPixelFormat pixel_format;
127
128     AVCaptureSession         *capture_session;
129     AVCaptureVideoDataOutput *video_output;
130     AVCaptureAudioDataOutput *audio_output;
131     CMSampleBufferRef         current_frame;
132     CMSampleBufferRef         current_audio_frame;
133
134     AVCaptureDevice          *observed_device;
135     AVCaptureDeviceTransportControlsPlaybackMode observed_mode;
136     int                      observed_quit;
137 } AVFContext;
138
139 static void lock_frames(AVFContext* ctx)
140 {
141     pthread_mutex_lock(&ctx->frame_lock);
142 }
143
144 static void unlock_frames(AVFContext* ctx)
145 {
146     pthread_mutex_unlock(&ctx->frame_lock);
147 }
148
149 /** FrameReciever class - delegate for AVCaptureSession
150  */
151 @interface AVFFrameReceiver : NSObject
152 {
153     AVFContext* _context;
154 }
155
156 - (id)initWithContext:(AVFContext*)context;
157
158 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
159   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
160          fromConnection:(AVCaptureConnection *)connection;
161
162 @end
163
164 @implementation AVFFrameReceiver
165
166 - (id)initWithContext:(AVFContext*)context
167 {
168     if (self = [super init]) {
169         _context = context;
170
171         // start observing if a device is set for it
172 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
173         if (_context->observed_device) {
174             NSString *keyPath = NSStringFromSelector(@selector(transportControlsPlaybackMode));
175             NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew;
176
177             [_context->observed_device addObserver: self
178                                         forKeyPath: keyPath
179                                            options: options
180                                            context: _context];
181         }
182 #endif
183     }
184     return self;
185 }
186
187 - (void)dealloc {
188     // stop observing if a device is set for it
189 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
190     if (_context->observed_device) {
191         NSString *keyPath = NSStringFromSelector(@selector(transportControlsPlaybackMode));
192         [_context->observed_device removeObserver: self forKeyPath: keyPath];
193     }
194 #endif
195     [super dealloc];
196 }
197
198 - (void)observeValueForKeyPath:(NSString *)keyPath
199                       ofObject:(id)object
200                         change:(NSDictionary *)change
201                        context:(void *)context {
202     if (context == _context) {
203         AVCaptureDeviceTransportControlsPlaybackMode mode =
204             [change[NSKeyValueChangeNewKey] integerValue];
205
206         if (mode != _context->observed_mode) {
207             if (mode == AVCaptureDeviceTransportControlsNotPlayingMode) {
208                 _context->observed_quit = 1;
209             }
210             _context->observed_mode = mode;
211         }
212     } else {
213         [super observeValueForKeyPath: keyPath
214                              ofObject: object
215                                change: change
216                               context: context];
217     }
218 }
219
220 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
221   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
222          fromConnection:(AVCaptureConnection *)connection
223 {
224     lock_frames(_context);
225
226     if (_context->current_frame != nil) {
227         CFRelease(_context->current_frame);
228     }
229
230     _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
231
232     unlock_frames(_context);
233
234     ++_context->frames_captured;
235 }
236
237 @end
238
239 /** AudioReciever class - delegate for AVCaptureSession
240  */
241 @interface AVFAudioReceiver : NSObject
242 {
243     AVFContext* _context;
244 }
245
246 - (id)initWithContext:(AVFContext*)context;
247
248 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
249   didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
250          fromConnection:(AVCaptureConnection *)connection;
251
252 @end
253
254 @implementation AVFAudioReceiver
255
256 - (id)initWithContext:(AVFContext*)context
257 {
258     if (self = [super init]) {
259         _context = context;
260     }
261     return self;
262 }
263
264 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
265   didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
266          fromConnection:(AVCaptureConnection *)connection
267 {
268     lock_frames(_context);
269
270     if (_context->current_audio_frame != nil) {
271         CFRelease(_context->current_audio_frame);
272     }
273
274     _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
275
276     unlock_frames(_context);
277
278     ++_context->audio_frames_captured;
279 }
280
281 @end
282
283 static void destroy_context(AVFContext* ctx)
284 {
285     [ctx->capture_session stopRunning];
286
287     [ctx->capture_session release];
288     [ctx->video_output    release];
289     [ctx->audio_output    release];
290     [ctx->avf_delegate    release];
291     [ctx->avf_audio_delegate release];
292
293     ctx->capture_session = NULL;
294     ctx->video_output    = NULL;
295     ctx->audio_output    = NULL;
296     ctx->avf_delegate    = NULL;
297     ctx->avf_audio_delegate = NULL;
298
299     av_freep(&ctx->audio_buffer);
300
301     pthread_mutex_destroy(&ctx->frame_lock);
302
303     if (ctx->current_frame) {
304         CFRelease(ctx->current_frame);
305     }
306 }
307
308 static void parse_device_name(AVFormatContext *s)
309 {
310     AVFContext *ctx = (AVFContext*)s->priv_data;
311     char *tmp = av_strdup(s->url);
312     char *save;
313
314     if (tmp[0] != ':') {
315         ctx->video_filename = av_strtok(tmp,  ":", &save);
316         ctx->audio_filename = av_strtok(NULL, ":", &save);
317     } else {
318         ctx->audio_filename = av_strtok(tmp,  ":", &save);
319     }
320 }
321
322 /**
323  * Configure the video device.
324  *
325  * Configure the video device using a run-time approach to access properties
326  * since formats, activeFormat are available since  iOS >= 7.0 or OSX >= 10.7
327  * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
328  *
329  * The NSUndefinedKeyException must be handled by the caller of this function.
330  *
331  */
332 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
333 {
334     AVFContext *ctx = (AVFContext*)s->priv_data;
335
336     double framerate = av_q2d(ctx->framerate);
337     NSObject *range = nil;
338     NSObject *format = nil;
339     NSObject *selected_range = nil;
340     NSObject *selected_format = nil;
341
342     // try to configure format by formats list
343     // might raise an exception if no format list is given
344     // (then fallback to default, no configuration)
345     @try {
346         for (format in [video_device valueForKey:@"formats"]) {
347             CMFormatDescriptionRef formatDescription;
348             CMVideoDimensions dimensions;
349
350             formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
351             dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
352
353             if ((ctx->width == 0 && ctx->height == 0) ||
354                 (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
355
356                 selected_format = format;
357
358                 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
359                     double max_framerate;
360
361                     [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
362                     if (fabs (framerate - max_framerate) < 0.01) {
363                         selected_range = range;
364                         break;
365                     }
366                 }
367             }
368         }
369
370         if (!selected_format) {
371             av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device.\n",
372                 ctx->width, ctx->height);
373             goto unsupported_format;
374         }
375
376         if (!selected_range) {
377             av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device.\n",
378                 framerate);
379             if (ctx->video_is_muxed) {
380                 av_log(s, AV_LOG_ERROR, "Falling back to default.\n");
381             } else {
382                 goto unsupported_format;
383             }
384         }
385
386         if ([video_device lockForConfiguration:NULL] == YES) {
387             if (selected_format) {
388                 [video_device setValue:selected_format forKey:@"activeFormat"];
389             }
390             if (selected_range) {
391                 NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
392                 [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
393                 [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
394             }
395         } else {
396             av_log(s, AV_LOG_ERROR, "Could not lock device for configuration.\n");
397             return AVERROR(EINVAL);
398         }
399     } @catch(NSException *e) {
400         av_log(ctx, AV_LOG_WARNING, "Configuration of video device failed, falling back to default.\n");
401     }
402
403     return 0;
404
405 unsupported_format:
406
407     av_log(s, AV_LOG_ERROR, "Supported modes:\n");
408     for (format in [video_device valueForKey:@"formats"]) {
409         CMFormatDescriptionRef formatDescription;
410         CMVideoDimensions dimensions;
411
412         formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
413         dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
414
415         for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
416             double min_framerate;
417             double max_framerate;
418
419             [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
420             [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
421             av_log(s, AV_LOG_ERROR, "  %dx%d@[%f %f]fps\n",
422                 dimensions.width, dimensions.height,
423                 min_framerate, max_framerate);
424         }
425     }
426     return AVERROR(EINVAL);
427 }
428
429 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
430 {
431     AVFContext *ctx = (AVFContext*)s->priv_data;
432     int ret;
433     NSError *error  = nil;
434     AVCaptureInput* capture_input = nil;
435     struct AVFPixelFormatSpec pxl_fmt_spec;
436     NSNumber *pixel_format;
437     NSDictionary *capture_dict;
438     dispatch_queue_t queue;
439
440     if (ctx->video_device_index < ctx->num_video_devices) {
441         capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
442     } else {
443         capture_input = (AVCaptureInput*) video_device;
444     }
445
446     if (!capture_input) {
447         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
448                [[error localizedDescription] UTF8String]);
449         return 1;
450     }
451
452     if ([ctx->capture_session canAddInput:capture_input]) {
453         [ctx->capture_session addInput:capture_input];
454     } else {
455         av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
456         return 1;
457     }
458
459     // Attaching output
460     ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
461
462     if (!ctx->video_output) {
463         av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
464         return 1;
465     }
466
467     // Configure device framerate and video size
468     @try {
469         if ((ret = configure_video_device(s, video_device)) < 0) {
470             return ret;
471         }
472     } @catch (NSException *exception) {
473         if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
474           av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
475           return AVERROR_EXTERNAL;
476         }
477     }
478
479     // select pixel format
480     pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
481
482     for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
483         if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
484             pxl_fmt_spec = avf_pixel_formats[i];
485             break;
486         }
487     }
488
489     // check if selected pixel format is supported by AVFoundation
490     if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
491         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
492                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
493         return 1;
494     }
495
496     // check if the pixel format is available for this device
497     if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
498         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
499                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
500
501         pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
502
503         av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
504         for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
505             struct AVFPixelFormatSpec pxl_fmt_dummy;
506             pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
507             for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
508                 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
509                     pxl_fmt_dummy = avf_pixel_formats[i];
510                     break;
511                 }
512             }
513
514             if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
515                 av_log(s, AV_LOG_ERROR, "  %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
516
517                 // select first supported pixel format instead of user selected (or default) pixel format
518                 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
519                     pxl_fmt_spec = pxl_fmt_dummy;
520                 }
521             }
522         }
523
524         // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
525         if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
526             return 1;
527         } else {
528             av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
529                    av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
530         }
531     }
532
533     // set videoSettings to an empty dict for receiving raw data of muxed devices
534     if (ctx->capture_raw_data) {
535         ctx->pixel_format = pxl_fmt_spec.ff_id;
536         ctx->video_output.videoSettings = @{ };
537     } else {
538         ctx->pixel_format = pxl_fmt_spec.ff_id;
539         pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
540         capture_dict = [NSDictionary dictionaryWithObject:pixel_format
541                                                    forKey:(id)kCVPixelBufferPixelFormatTypeKey];
542
543         [ctx->video_output setVideoSettings:capture_dict];
544     }
545     [ctx->video_output setAlwaysDiscardsLateVideoFrames:ctx->drop_late_frames];
546
547 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
548     // check for transport control support and set observer device if supported
549     if (!ctx->video_is_screen) {
550         int trans_ctrl = [video_device transportControlsSupported];
551         AVCaptureDeviceTransportControlsPlaybackMode trans_mode = [video_device transportControlsPlaybackMode];
552
553         if (trans_ctrl) {
554             ctx->observed_mode   = trans_mode;
555             ctx->observed_device = video_device;
556         }
557     }
558 #endif
559
560     ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
561
562     queue = dispatch_queue_create("avf_queue", NULL);
563     [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
564     dispatch_release(queue);
565
566     if ([ctx->capture_session canAddOutput:ctx->video_output]) {
567         [ctx->capture_session addOutput:ctx->video_output];
568     } else {
569         av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
570         return 1;
571     }
572
573     return 0;
574 }
575
576 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
577 {
578     AVFContext *ctx = (AVFContext*)s->priv_data;
579     NSError *error  = nil;
580     AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
581     dispatch_queue_t queue;
582
583     if (!audio_dev_input) {
584         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
585                [[error localizedDescription] UTF8String]);
586         return 1;
587     }
588
589     if ([ctx->capture_session canAddInput:audio_dev_input]) {
590         [ctx->capture_session addInput:audio_dev_input];
591     } else {
592         av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
593         return 1;
594     }
595
596     // Attaching output
597     ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
598
599     if (!ctx->audio_output) {
600         av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
601         return 1;
602     }
603
604     ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
605
606     queue = dispatch_queue_create("avf_audio_queue", NULL);
607     [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
608     dispatch_release(queue);
609
610     if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
611         [ctx->capture_session addOutput:ctx->audio_output];
612     } else {
613         av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
614         return 1;
615     }
616
617     return 0;
618 }
619
620 static int get_video_config(AVFormatContext *s)
621 {
622     AVFContext *ctx = (AVFContext*)s->priv_data;
623     CVImageBufferRef image_buffer;
624     CMBlockBufferRef block_buffer;
625     CGSize image_buffer_size;
626     AVStream* stream = avformat_new_stream(s, NULL);
627
628     if (!stream) {
629         return 1;
630     }
631
632     // Take stream info from the first frame.
633     while (ctx->frames_captured < 1) {
634         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
635     }
636
637     lock_frames(ctx);
638
639     ctx->video_stream_index = stream->index;
640
641     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
642
643     image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
644     block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
645
646     if (image_buffer) {
647         image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
648
649         stream->codecpar->codec_id   = AV_CODEC_ID_RAWVIDEO;
650         stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
651         stream->codecpar->width      = (int)image_buffer_size.width;
652         stream->codecpar->height     = (int)image_buffer_size.height;
653         stream->codecpar->format     = ctx->pixel_format;
654     } else {
655         stream->codecpar->codec_id   = AV_CODEC_ID_DVVIDEO;
656         stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
657         stream->codecpar->format     = ctx->pixel_format;
658     }
659
660     CFRelease(ctx->current_frame);
661     ctx->current_frame = nil;
662
663     unlock_frames(ctx);
664
665     return 0;
666 }
667
668 static int get_audio_config(AVFormatContext *s)
669 {
670     AVFContext *ctx = (AVFContext*)s->priv_data;
671     CMFormatDescriptionRef format_desc;
672     AVStream* stream = avformat_new_stream(s, NULL);
673
674     if (!stream) {
675         return 1;
676     }
677
678     // Take stream info from the first frame.
679     while (ctx->audio_frames_captured < 1) {
680         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
681     }
682
683     lock_frames(ctx);
684
685     ctx->audio_stream_index = stream->index;
686
687     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
688
689     format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
690     const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
691
692     if (!basic_desc) {
693         av_log(s, AV_LOG_ERROR, "audio format not available\n");
694         return 1;
695     }
696
697     stream->codecpar->codec_type     = AVMEDIA_TYPE_AUDIO;
698     stream->codecpar->sample_rate    = basic_desc->mSampleRate;
699     stream->codecpar->channels       = basic_desc->mChannelsPerFrame;
700     stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
701
702     ctx->audio_channels        = basic_desc->mChannelsPerFrame;
703     ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
704     ctx->audio_float           = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
705     ctx->audio_be              = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
706     ctx->audio_signed_integer  = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
707     ctx->audio_packed          = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
708     ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
709
710     if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
711         ctx->audio_float &&
712         ctx->audio_bits_per_sample == 32 &&
713         ctx->audio_packed) {
714         stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
715     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
716         ctx->audio_signed_integer &&
717         ctx->audio_bits_per_sample == 16 &&
718         ctx->audio_packed) {
719         stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
720     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
721         ctx->audio_signed_integer &&
722         ctx->audio_bits_per_sample == 24 &&
723         ctx->audio_packed) {
724         stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
725     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
726         ctx->audio_signed_integer &&
727         ctx->audio_bits_per_sample == 32 &&
728         ctx->audio_packed) {
729         stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
730     } else {
731         av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
732         return 1;
733     }
734
735     if (ctx->audio_non_interleaved) {
736         CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
737         ctx->audio_buffer_size        = CMBlockBufferGetDataLength(block_buffer);
738         ctx->audio_buffer             = av_malloc(ctx->audio_buffer_size);
739         if (!ctx->audio_buffer) {
740             av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
741             return 1;
742         }
743     }
744
745     CFRelease(ctx->current_audio_frame);
746     ctx->current_audio_frame = nil;
747
748     unlock_frames(ctx);
749
750     return 0;
751 }
752
753 static int avf_read_header(AVFormatContext *s)
754 {
755     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
756     uint32_t num_screens    = 0;
757     AVFContext *ctx         = (AVFContext*)s->priv_data;
758     AVCaptureDevice *video_device = nil;
759     AVCaptureDevice *audio_device = nil;
760     // Find capture device
761     NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
762     NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
763
764     ctx->num_video_devices = [devices count] + [devices_muxed count];
765     ctx->first_pts          = av_gettime();
766     ctx->first_audio_pts    = av_gettime();
767
768     pthread_mutex_init(&ctx->frame_lock, NULL);
769
770 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
771     CGGetActiveDisplayList(0, NULL, &num_screens);
772 #endif
773
774     // List devices if requested
775     if (ctx->list_devices) {
776         int index = 0;
777         av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
778         for (AVCaptureDevice *device in devices) {
779             const char *name = [[device localizedName] UTF8String];
780             index            = [devices indexOfObject:device];
781             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
782         }
783         for (AVCaptureDevice *device in devices_muxed) {
784             const char *name = [[device localizedName] UTF8String];
785             index            = [devices count] + [devices_muxed indexOfObject:device];
786             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
787         }
788 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
789         if (num_screens > 0) {
790             CGDirectDisplayID screens[num_screens];
791             CGGetActiveDisplayList(num_screens, screens, &num_screens);
792             for (int i = 0; i < num_screens; i++) {
793                 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", ctx->num_video_devices + i, i);
794             }
795         }
796 #endif
797
798         av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
799         devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
800         for (AVCaptureDevice *device in devices) {
801             const char *name = [[device localizedName] UTF8String];
802             int index  = [devices indexOfObject:device];
803             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
804         }
805          goto fail;
806     }
807
808     // parse input filename for video and audio device
809     parse_device_name(s);
810
811     // check for device index given in filename
812     if (ctx->video_device_index == -1 && ctx->video_filename) {
813         sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
814     }
815     if (ctx->audio_device_index == -1 && ctx->audio_filename) {
816         sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
817     }
818
819     if (ctx->video_device_index >= 0) {
820         if (ctx->video_device_index < ctx->num_video_devices) {
821             if (ctx->video_device_index < [devices count]) {
822                 video_device = [devices objectAtIndex:ctx->video_device_index];
823             } else {
824                 video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
825                 ctx->video_is_muxed = 1;
826             }
827         } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
828 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
829             CGDirectDisplayID screens[num_screens];
830             CGGetActiveDisplayList(num_screens, screens, &num_screens);
831             AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
832
833             if (ctx->framerate.num > 0) {
834                 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
835             }
836
837 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
838             if (ctx->capture_cursor) {
839                 capture_screen_input.capturesCursor = YES;
840             } else {
841                 capture_screen_input.capturesCursor = NO;
842             }
843 #endif
844
845             if (ctx->capture_mouse_clicks) {
846                 capture_screen_input.capturesMouseClicks = YES;
847             } else {
848                 capture_screen_input.capturesMouseClicks = NO;
849             }
850
851             video_device = (AVCaptureDevice*) capture_screen_input;
852             ctx->video_is_screen = 1;
853 #endif
854          } else {
855             av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
856             goto fail;
857         }
858     } else if (ctx->video_filename &&
859                strncmp(ctx->video_filename, "none", 4)) {
860         if (!strncmp(ctx->video_filename, "default", 7)) {
861             video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
862         } else {
863         // looking for video inputs
864         for (AVCaptureDevice *device in devices) {
865             if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
866                 video_device = device;
867                 break;
868             }
869         }
870         // looking for muxed inputs
871         for (AVCaptureDevice *device in devices_muxed) {
872             if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
873                 video_device = device;
874                 ctx->video_is_muxed = 1;
875                 break;
876             }
877         }
878
879 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
880         // looking for screen inputs
881         if (!video_device) {
882             int idx;
883             if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
884                 CGDirectDisplayID screens[num_screens];
885                 CGGetActiveDisplayList(num_screens, screens, &num_screens);
886                 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
887                 video_device = (AVCaptureDevice*) capture_screen_input;
888                 ctx->video_device_index = ctx->num_video_devices + idx;
889                 ctx->video_is_screen = 1;
890
891                 if (ctx->framerate.num > 0) {
892                     capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
893                 }
894
895 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
896                 if (ctx->capture_cursor) {
897                     capture_screen_input.capturesCursor = YES;
898                 } else {
899                     capture_screen_input.capturesCursor = NO;
900                 }
901 #endif
902
903                 if (ctx->capture_mouse_clicks) {
904                     capture_screen_input.capturesMouseClicks = YES;
905                 } else {
906                     capture_screen_input.capturesMouseClicks = NO;
907                 }
908             }
909         }
910 #endif
911         }
912
913         if (!video_device) {
914             av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
915             goto fail;
916         }
917     }
918
919     // get audio device
920     if (ctx->audio_device_index >= 0) {
921         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
922
923         if (ctx->audio_device_index >= [devices count]) {
924             av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
925             goto fail;
926         }
927
928         audio_device = [devices objectAtIndex:ctx->audio_device_index];
929     } else if (ctx->audio_filename &&
930                strncmp(ctx->audio_filename, "none", 4)) {
931         if (!strncmp(ctx->audio_filename, "default", 7)) {
932             audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
933         } else {
934         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
935
936         for (AVCaptureDevice *device in devices) {
937             if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
938                 audio_device = device;
939                 break;
940             }
941         }
942         }
943
944         if (!audio_device) {
945             av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
946              goto fail;
947         }
948     }
949
950     // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
951     if (!video_device && !audio_device) {
952         av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
953         goto fail;
954     }
955
956     if (video_device) {
957         if (ctx->video_device_index < ctx->num_video_devices) {
958             av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
959         } else {
960             av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
961         }
962     }
963     if (audio_device) {
964         av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
965     }
966
967     // Initialize capture session
968     ctx->capture_session = [[AVCaptureSession alloc] init];
969
970     if (video_device && add_video_device(s, video_device)) {
971         goto fail;
972     }
973     if (audio_device && add_audio_device(s, audio_device)) {
974     }
975
976     [ctx->capture_session startRunning];
977
978     /* Unlock device configuration only after the session is started so it
979      * does not reset the capture formats */
980     if (!ctx->video_is_screen) {
981         [video_device unlockForConfiguration];
982     }
983
984     if (video_device && get_video_config(s)) {
985         goto fail;
986     }
987
988     // set audio stream
989     if (audio_device && get_audio_config(s)) {
990         goto fail;
991     }
992
993     [pool release];
994     return 0;
995
996 fail:
997     [pool release];
998     destroy_context(ctx);
999     return AVERROR(EIO);
1000 }
1001
1002 static int copy_cvpixelbuffer(AVFormatContext *s,
1003                                CVPixelBufferRef image_buffer,
1004                                AVPacket *pkt)
1005 {
1006     AVFContext *ctx = s->priv_data;
1007     int src_linesize[4];
1008     const uint8_t *src_data[4];
1009     int width  = CVPixelBufferGetWidth(image_buffer);
1010     int height = CVPixelBufferGetHeight(image_buffer);
1011     int status;
1012
1013     memset(src_linesize, 0, sizeof(src_linesize));
1014     memset(src_data, 0, sizeof(src_data));
1015
1016     status = CVPixelBufferLockBaseAddress(image_buffer, 0);
1017     if (status != kCVReturnSuccess) {
1018         av_log(s, AV_LOG_ERROR, "Could not lock base address: %d (%dx%d)\n", status, width, height);
1019         return AVERROR_EXTERNAL;
1020     }
1021
1022     if (CVPixelBufferIsPlanar(image_buffer)) {
1023         size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
1024         int i;
1025         for(i = 0; i < plane_count; i++){
1026             src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
1027             src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
1028         }
1029     } else {
1030         src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
1031         src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
1032     }
1033
1034     status = av_image_copy_to_buffer(pkt->data, pkt->size,
1035                                      src_data, src_linesize,
1036                                      ctx->pixel_format, width, height, 1);
1037
1038
1039
1040     CVPixelBufferUnlockBaseAddress(image_buffer, 0);
1041
1042     return status;
1043 }
1044
1045 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
1046 {
1047     AVFContext* ctx = (AVFContext*)s->priv_data;
1048
1049     do {
1050         CVImageBufferRef image_buffer;
1051         CMBlockBufferRef block_buffer;
1052         lock_frames(ctx);
1053
1054         if (ctx->current_frame != nil) {
1055             int status;
1056             int length = 0;
1057
1058             image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
1059             block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
1060
1061             if (image_buffer != nil) {
1062                 length = (int)CVPixelBufferGetDataSize(image_buffer);
1063             } else if (block_buffer != nil) {
1064                 length = (int)CMBlockBufferGetDataLength(block_buffer);
1065             } else  {
1066                 return AVERROR(EINVAL);
1067             }
1068
1069             if (av_new_packet(pkt, length) < 0) {
1070                 return AVERROR(EIO);
1071             }
1072
1073             CMItemCount count;
1074             CMSampleTimingInfo timing_info;
1075
1076             if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
1077                 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1078                 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1079             }
1080
1081             pkt->stream_index  = ctx->video_stream_index;
1082             pkt->flags        |= AV_PKT_FLAG_KEY;
1083
1084             if (image_buffer) {
1085                 status = copy_cvpixelbuffer(s, image_buffer, pkt);
1086             } else {
1087                 status = 0;
1088                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1089                 if (ret != kCMBlockBufferNoErr) {
1090                     status = AVERROR(EIO);
1091                 }
1092              }
1093             CFRelease(ctx->current_frame);
1094             ctx->current_frame = nil;
1095
1096             if (status < 0)
1097                 return status;
1098         } else if (ctx->current_audio_frame != nil) {
1099             CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
1100             int block_buffer_size         = CMBlockBufferGetDataLength(block_buffer);
1101
1102             if (!block_buffer || !block_buffer_size) {
1103                 return AVERROR(EIO);
1104             }
1105
1106             if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
1107                 return AVERROR_BUFFER_TOO_SMALL;
1108             }
1109
1110             if (av_new_packet(pkt, block_buffer_size) < 0) {
1111                 return AVERROR(EIO);
1112             }
1113
1114             CMItemCount count;
1115             CMSampleTimingInfo timing_info;
1116
1117             if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
1118                 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1119                 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1120             }
1121
1122             pkt->stream_index  = ctx->audio_stream_index;
1123             pkt->flags        |= AV_PKT_FLAG_KEY;
1124
1125             if (ctx->audio_non_interleaved) {
1126                 int sample, c, shift, num_samples;
1127
1128                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
1129                 if (ret != kCMBlockBufferNoErr) {
1130                     return AVERROR(EIO);
1131                 }
1132
1133                 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
1134
1135                 // transform decoded frame into output format
1136                 #define INTERLEAVE_OUTPUT(bps)                                         \
1137                 {                                                                      \
1138                     int##bps##_t **src;                                                \
1139                     int##bps##_t *dest;                                                \
1140                     src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*));      \
1141                     if (!src) return AVERROR(EIO);                                     \
1142                     for (c = 0; c < ctx->audio_channels; c++) {                        \
1143                         src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1144                     }                                                                  \
1145                     dest  = (int##bps##_t*)pkt->data;                                  \
1146                     shift = bps - ctx->audio_bits_per_sample;                          \
1147                     for (sample = 0; sample < num_samples; sample++)                   \
1148                         for (c = 0; c < ctx->audio_channels; c++)                      \
1149                             *dest++ = src[c][sample] << shift;                         \
1150                     av_freep(&src);                                                    \
1151                 }
1152
1153                 if (ctx->audio_bits_per_sample <= 16) {
1154                     INTERLEAVE_OUTPUT(16)
1155                 } else {
1156                     INTERLEAVE_OUTPUT(32)
1157                 }
1158             } else {
1159                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1160                 if (ret != kCMBlockBufferNoErr) {
1161                     return AVERROR(EIO);
1162                 }
1163             }
1164
1165             CFRelease(ctx->current_audio_frame);
1166             ctx->current_audio_frame = nil;
1167         } else {
1168             pkt->data = NULL;
1169             unlock_frames(ctx);
1170             if (ctx->observed_quit) {
1171                 return AVERROR_EOF;
1172             } else {
1173                 return AVERROR(EAGAIN);
1174             }
1175         }
1176
1177         unlock_frames(ctx);
1178     } while (!pkt->data);
1179
1180     return 0;
1181 }
1182
1183 static int avf_close(AVFormatContext *s)
1184 {
1185     AVFContext* ctx = (AVFContext*)s->priv_data;
1186     destroy_context(ctx);
1187     return 0;
1188 }
1189
1190 static const AVOption options[] = {
1191     { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1192     { "video_device_index", "select video device by index for devices with same name (starts at 0)", offsetof(AVFContext, video_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1193     { "audio_device_index", "select audio device by index for devices with same name (starts at 0)", offsetof(AVFContext, audio_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1194     { "pixel_format", "set pixel format", offsetof(AVFContext, pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_YUV420P}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM},
1195     { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1196     { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
1197     { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1198     { "capture_mouse_clicks", "capture the screen mouse clicks", offsetof(AVFContext, capture_mouse_clicks), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1199     { "capture_raw_data", "capture the raw data from device connection", offsetof(AVFContext, capture_raw_data), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1200     { "drop_late_frames", "drop frames that are available later than expected", offsetof(AVFContext, drop_late_frames), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1201
1202     { NULL },
1203 };
1204
1205 static const AVClass avf_class = {
1206     .class_name = "AVFoundation indev",
1207     .item_name  = av_default_item_name,
1208     .option     = options,
1209     .version    = LIBAVUTIL_VERSION_INT,
1210     .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
1211 };
1212
1213 AVInputFormat ff_avfoundation_demuxer = {
1214     .name           = "avfoundation",
1215     .long_name      = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
1216     .priv_data_size = sizeof(AVFContext),
1217     .read_header    = avf_read_header,
1218     .read_packet    = avf_read_packet,
1219     .read_close     = avf_close,
1220     .flags          = AVFMT_NOFILE,
1221     .priv_class     = &avf_class,
1222 };