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