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