]> git.sesse.net Git - ffmpeg/blob - libavdevice/avfoundation.m
Merge commit 'faab8f9fcb4ffeb967dc6872c0f1e9da719106ce'
[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/time.h"
37 #include "avdevice.h"
38
39 static const int avf_time_base = 1000000;
40
41 static const AVRational avf_time_base_q = {
42     .num = 1,
43     .den = avf_time_base
44 };
45
46 struct AVFPixelFormatSpec {
47     enum AVPixelFormat ff_id;
48     OSType avf_id;
49 };
50
51 static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
52     { AV_PIX_FMT_MONOBLACK,    kCVPixelFormatType_1Monochrome },
53     { AV_PIX_FMT_RGB555BE,     kCVPixelFormatType_16BE555 },
54     { AV_PIX_FMT_RGB555LE,     kCVPixelFormatType_16LE555 },
55     { AV_PIX_FMT_RGB565BE,     kCVPixelFormatType_16BE565 },
56     { AV_PIX_FMT_RGB565LE,     kCVPixelFormatType_16LE565 },
57     { AV_PIX_FMT_RGB24,        kCVPixelFormatType_24RGB },
58     { AV_PIX_FMT_BGR24,        kCVPixelFormatType_24BGR },
59     { AV_PIX_FMT_0RGB,         kCVPixelFormatType_32ARGB },
60     { AV_PIX_FMT_BGR0,         kCVPixelFormatType_32BGRA },
61     { AV_PIX_FMT_0BGR,         kCVPixelFormatType_32ABGR },
62     { AV_PIX_FMT_RGB0,         kCVPixelFormatType_32RGBA },
63     { AV_PIX_FMT_BGR48BE,      kCVPixelFormatType_48RGB },
64     { AV_PIX_FMT_UYVY422,      kCVPixelFormatType_422YpCbCr8 },
65     { AV_PIX_FMT_YUVA444P,     kCVPixelFormatType_4444YpCbCrA8R },
66     { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
67     { AV_PIX_FMT_YUV444P,      kCVPixelFormatType_444YpCbCr8 },
68     { AV_PIX_FMT_YUV422P16,    kCVPixelFormatType_422YpCbCr16 },
69     { AV_PIX_FMT_YUV422P10,    kCVPixelFormatType_422YpCbCr10 },
70     { AV_PIX_FMT_YUV444P10,    kCVPixelFormatType_444YpCbCr10 },
71     { AV_PIX_FMT_YUV420P,      kCVPixelFormatType_420YpCbCr8Planar },
72     { AV_PIX_FMT_NV12,         kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
73     { AV_PIX_FMT_YUYV422,      kCVPixelFormatType_422YpCbCr8_yuvs },
74 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
75     { AV_PIX_FMT_GRAY8,        kCVPixelFormatType_OneComponent8 },
76 #endif
77     { AV_PIX_FMT_NONE, 0 }
78 };
79
80 typedef struct
81 {
82     AVClass*        class;
83
84     int             frames_captured;
85     int             audio_frames_captured;
86     int64_t         first_pts;
87     int64_t         first_audio_pts;
88     pthread_mutex_t frame_lock;
89     pthread_cond_t  frame_wait_cond;
90     id              avf_delegate;
91     id              avf_audio_delegate;
92
93     int             list_devices;
94     int             video_device_index;
95     int             video_stream_index;
96     int             audio_device_index;
97     int             audio_stream_index;
98
99     char            *video_filename;
100     char            *audio_filename;
101
102     int             num_video_devices;
103
104     int             audio_channels;
105     int             audio_bits_per_sample;
106     int             audio_float;
107     int             audio_be;
108     int             audio_signed_integer;
109     int             audio_packed;
110     int             audio_non_interleaved;
111
112     int32_t         *audio_buffer;
113     int             audio_buffer_size;
114
115     enum AVPixelFormat pixel_format;
116
117     AVCaptureSession         *capture_session;
118     AVCaptureVideoDataOutput *video_output;
119     AVCaptureAudioDataOutput *audio_output;
120     CMSampleBufferRef         current_frame;
121     CMSampleBufferRef         current_audio_frame;
122 } AVFContext;
123
124 static void lock_frames(AVFContext* ctx)
125 {
126     pthread_mutex_lock(&ctx->frame_lock);
127 }
128
129 static void unlock_frames(AVFContext* ctx)
130 {
131     pthread_mutex_unlock(&ctx->frame_lock);
132 }
133
134 /** FrameReciever class - delegate for AVCaptureSession
135  */
136 @interface AVFFrameReceiver : NSObject
137 {
138     AVFContext* _context;
139 }
140
141 - (id)initWithContext:(AVFContext*)context;
142
143 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
144   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
145          fromConnection:(AVCaptureConnection *)connection;
146
147 @end
148
149 @implementation AVFFrameReceiver
150
151 - (id)initWithContext:(AVFContext*)context
152 {
153     if (self = [super init]) {
154         _context = context;
155     }
156     return self;
157 }
158
159 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
160   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
161          fromConnection:(AVCaptureConnection *)connection
162 {
163     lock_frames(_context);
164
165     if (_context->current_frame != nil) {
166         CFRelease(_context->current_frame);
167     }
168
169     _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
170
171     pthread_cond_signal(&_context->frame_wait_cond);
172
173     unlock_frames(_context);
174
175     ++_context->frames_captured;
176 }
177
178 @end
179
180 /** AudioReciever class - delegate for AVCaptureSession
181  */
182 @interface AVFAudioReceiver : NSObject
183 {
184     AVFContext* _context;
185 }
186
187 - (id)initWithContext:(AVFContext*)context;
188
189 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
190   didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
191          fromConnection:(AVCaptureConnection *)connection;
192
193 @end
194
195 @implementation AVFAudioReceiver
196
197 - (id)initWithContext:(AVFContext*)context
198 {
199     if (self = [super init]) {
200         _context = context;
201     }
202     return self;
203 }
204
205 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
206   didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
207          fromConnection:(AVCaptureConnection *)connection
208 {
209     lock_frames(_context);
210
211     if (_context->current_audio_frame != nil) {
212         CFRelease(_context->current_audio_frame);
213     }
214
215     _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
216
217     pthread_cond_signal(&_context->frame_wait_cond);
218
219     unlock_frames(_context);
220
221     ++_context->audio_frames_captured;
222 }
223
224 @end
225
226 static void destroy_context(AVFContext* ctx)
227 {
228     [ctx->capture_session stopRunning];
229
230     [ctx->capture_session release];
231     [ctx->video_output    release];
232     [ctx->audio_output    release];
233     [ctx->avf_delegate    release];
234     [ctx->avf_audio_delegate release];
235
236     ctx->capture_session = NULL;
237     ctx->video_output    = NULL;
238     ctx->audio_output    = NULL;
239     ctx->avf_delegate    = NULL;
240     ctx->avf_audio_delegate = NULL;
241
242     av_freep(&ctx->audio_buffer);
243
244     pthread_mutex_destroy(&ctx->frame_lock);
245     pthread_cond_destroy(&ctx->frame_wait_cond);
246
247     if (ctx->current_frame) {
248         CFRelease(ctx->current_frame);
249     }
250 }
251
252 static void parse_device_name(AVFormatContext *s)
253 {
254     AVFContext *ctx = (AVFContext*)s->priv_data;
255     char *tmp = av_strdup(s->filename);
256     char *save;
257
258     if (tmp[0] != ':') {
259         ctx->video_filename = av_strtok(tmp,  ":", &save);
260         ctx->audio_filename = av_strtok(NULL, ":", &save);
261     } else {
262         ctx->audio_filename = av_strtok(tmp,  ":", &save);
263     }
264 }
265
266 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
267 {
268     AVFContext *ctx = (AVFContext*)s->priv_data;
269     NSError *error  = nil;
270     AVCaptureInput* capture_input = nil;
271     struct AVFPixelFormatSpec pxl_fmt_spec;
272     NSNumber *pixel_format;
273     NSDictionary *capture_dict;
274     dispatch_queue_t queue;
275
276     if (ctx->video_device_index < ctx->num_video_devices) {
277         capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
278     } else {
279         capture_input = (AVCaptureInput*) video_device;
280     }
281
282     if (!capture_input) {
283         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
284                [[error localizedDescription] UTF8String]);
285         return 1;
286     }
287
288     if ([ctx->capture_session canAddInput:capture_input]) {
289         [ctx->capture_session addInput:capture_input];
290     } else {
291         av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
292         return 1;
293     }
294
295     // Attaching output
296     ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
297
298     if (!ctx->video_output) {
299         av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
300         return 1;
301     }
302
303     // select pixel format
304     pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
305
306     for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
307         if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
308             pxl_fmt_spec = avf_pixel_formats[i];
309             break;
310         }
311     }
312
313     // check if selected pixel format is supported by AVFoundation
314     if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
315         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
316                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
317         return 1;
318     }
319
320     // check if the pixel format is available for this device
321     if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
322         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
323                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
324
325         pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
326
327         av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
328         for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
329             struct AVFPixelFormatSpec pxl_fmt_dummy;
330             pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
331             for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
332                 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
333                     pxl_fmt_dummy = avf_pixel_formats[i];
334                     break;
335                 }
336             }
337
338             if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
339                 av_log(s, AV_LOG_ERROR, "  %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
340
341                 // select first supported pixel format instead of user selected (or default) pixel format
342                 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
343                     pxl_fmt_spec = pxl_fmt_dummy;
344                 }
345             }
346         }
347
348         // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
349         if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
350             return 1;
351         } else {
352             av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
353                    av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
354         }
355     }
356
357     ctx->pixel_format          = pxl_fmt_spec.ff_id;
358     pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
359     capture_dict = [NSDictionary dictionaryWithObject:pixel_format
360                                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];
361
362     [ctx->video_output setVideoSettings:capture_dict];
363     [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
364
365     ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
366
367     queue = dispatch_queue_create("avf_queue", NULL);
368     [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
369     dispatch_release(queue);
370
371     if ([ctx->capture_session canAddOutput:ctx->video_output]) {
372         [ctx->capture_session addOutput:ctx->video_output];
373     } else {
374         av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
375         return 1;
376     }
377
378     return 0;
379 }
380
381 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
382 {
383     AVFContext *ctx = (AVFContext*)s->priv_data;
384     NSError *error  = nil;
385     AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
386     dispatch_queue_t queue;
387
388     if (!audio_dev_input) {
389         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
390                [[error localizedDescription] UTF8String]);
391         return 1;
392     }
393
394     if ([ctx->capture_session canAddInput:audio_dev_input]) {
395         [ctx->capture_session addInput:audio_dev_input];
396     } else {
397         av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
398         return 1;
399     }
400
401     // Attaching output
402     ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
403
404     if (!ctx->audio_output) {
405         av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
406         return 1;
407     }
408
409     ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
410
411     queue = dispatch_queue_create("avf_audio_queue", NULL);
412     [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
413     dispatch_release(queue);
414
415     if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
416         [ctx->capture_session addOutput:ctx->audio_output];
417     } else {
418         av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
419         return 1;
420     }
421
422     return 0;
423 }
424
425 static int get_video_config(AVFormatContext *s)
426 {
427     AVFContext *ctx = (AVFContext*)s->priv_data;
428     CVImageBufferRef image_buffer;
429     CGSize image_buffer_size;
430     AVStream* stream = avformat_new_stream(s, NULL);
431
432     if (!stream) {
433         return 1;
434     }
435
436     // Take stream info from the first frame.
437     while (ctx->frames_captured < 1) {
438         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
439     }
440
441     lock_frames(ctx);
442
443     ctx->video_stream_index = stream->index;
444
445     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
446
447     image_buffer      = CMSampleBufferGetImageBuffer(ctx->current_frame);
448     image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
449
450     stream->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
451     stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
452     stream->codec->width      = (int)image_buffer_size.width;
453     stream->codec->height     = (int)image_buffer_size.height;
454     stream->codec->pix_fmt    = ctx->pixel_format;
455
456     CFRelease(ctx->current_frame);
457     ctx->current_frame = nil;
458
459     unlock_frames(ctx);
460
461     return 0;
462 }
463
464 static int get_audio_config(AVFormatContext *s)
465 {
466     AVFContext *ctx = (AVFContext*)s->priv_data;
467     CMFormatDescriptionRef format_desc;
468     AVStream* stream = avformat_new_stream(s, NULL);
469
470     if (!stream) {
471         return 1;
472     }
473
474     // Take stream info from the first frame.
475     while (ctx->audio_frames_captured < 1) {
476         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
477     }
478
479     lock_frames(ctx);
480
481     ctx->audio_stream_index = stream->index;
482
483     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
484
485     format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
486     const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
487
488     if (!basic_desc) {
489         av_log(s, AV_LOG_ERROR, "audio format not available\n");
490         return 1;
491     }
492
493     stream->codec->codec_type     = AVMEDIA_TYPE_AUDIO;
494     stream->codec->sample_rate    = basic_desc->mSampleRate;
495     stream->codec->channels       = basic_desc->mChannelsPerFrame;
496     stream->codec->channel_layout = av_get_default_channel_layout(stream->codec->channels);
497
498     ctx->audio_channels        = basic_desc->mChannelsPerFrame;
499     ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
500     ctx->audio_float           = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
501     ctx->audio_be              = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
502     ctx->audio_signed_integer  = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
503     ctx->audio_packed          = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
504     ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
505
506     if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
507         ctx->audio_float &&
508         ctx->audio_bits_per_sample == 32 &&
509         ctx->audio_packed) {
510         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
511     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
512         ctx->audio_signed_integer &&
513         ctx->audio_bits_per_sample == 16 &&
514         ctx->audio_packed) {
515         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
516     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
517         ctx->audio_signed_integer &&
518         ctx->audio_bits_per_sample == 24 &&
519         ctx->audio_packed) {
520         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
521     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
522         ctx->audio_signed_integer &&
523         ctx->audio_bits_per_sample == 32 &&
524         ctx->audio_packed) {
525         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
526     } else {
527         av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
528         return 1;
529     }
530
531     if (ctx->audio_non_interleaved) {
532         CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
533         ctx->audio_buffer_size        = CMBlockBufferGetDataLength(block_buffer);
534         ctx->audio_buffer             = av_malloc(ctx->audio_buffer_size);
535         if (!ctx->audio_buffer) {
536             av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
537             return 1;
538         }
539     }
540
541     CFRelease(ctx->current_audio_frame);
542     ctx->current_audio_frame = nil;
543
544     unlock_frames(ctx);
545
546     return 0;
547 }
548
549 static int avf_read_header(AVFormatContext *s)
550 {
551     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
552     uint32_t num_screens    = 0;
553     AVFContext *ctx         = (AVFContext*)s->priv_data;
554     AVCaptureDevice *video_device = nil;
555     AVCaptureDevice *audio_device = nil;
556     // Find capture device
557     NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
558     ctx->num_video_devices = [devices count];
559
560     ctx->first_pts          = av_gettime();
561     ctx->first_audio_pts    = av_gettime();
562
563     pthread_mutex_init(&ctx->frame_lock, NULL);
564     pthread_cond_init(&ctx->frame_wait_cond, NULL);
565
566 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
567     CGGetActiveDisplayList(0, NULL, &num_screens);
568 #endif
569
570     // List devices if requested
571     if (ctx->list_devices) {
572         int index = 0;
573         av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
574         for (AVCaptureDevice *device in devices) {
575             const char *name = [[device localizedName] UTF8String];
576             index            = [devices indexOfObject:device];
577             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
578             index++;
579         }
580 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
581         if (num_screens > 0) {
582             CGDirectDisplayID screens[num_screens];
583             CGGetActiveDisplayList(num_screens, screens, &num_screens);
584             for (int i = 0; i < num_screens; i++) {
585                 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", index + i, i);
586             }
587         }
588 #endif
589
590         av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
591         devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
592         for (AVCaptureDevice *device in devices) {
593             const char *name = [[device localizedName] UTF8String];
594             int index  = [devices indexOfObject:device];
595             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
596         }
597          goto fail;
598     }
599
600     // parse input filename for video and audio device
601     parse_device_name(s);
602
603     // check for device index given in filename
604     if (ctx->video_device_index == -1 && ctx->video_filename) {
605         sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
606     }
607     if (ctx->audio_device_index == -1 && ctx->audio_filename) {
608         sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
609     }
610
611     if (ctx->video_device_index >= 0) {
612         if (ctx->video_device_index < ctx->num_video_devices) {
613             video_device = [devices objectAtIndex:ctx->video_device_index];
614         } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
615 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
616             CGDirectDisplayID screens[num_screens];
617             CGGetActiveDisplayList(num_screens, screens, &num_screens);
618             AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
619             video_device = (AVCaptureDevice*) capture_screen_input;
620 #endif
621          } else {
622             av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
623             goto fail;
624         }
625     } else if (ctx->video_filename &&
626                strncmp(ctx->video_filename, "none", 4)) {
627         if (!strncmp(ctx->video_filename, "default", 7)) {
628             video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
629         } else {
630         // looking for video inputs
631         for (AVCaptureDevice *device in devices) {
632             if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
633                 video_device = device;
634                 break;
635             }
636         }
637
638 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
639         // looking for screen inputs
640         if (!video_device) {
641             int idx;
642             if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
643                 CGDirectDisplayID screens[num_screens];
644                 CGGetActiveDisplayList(num_screens, screens, &num_screens);
645                 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
646                 video_device = (AVCaptureDevice*) capture_screen_input;
647                 ctx->video_device_index = ctx->num_video_devices + idx;
648             }
649         }
650 #endif
651         }
652
653         if (!video_device) {
654             av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
655             goto fail;
656         }
657     }
658
659     // get audio device
660     if (ctx->audio_device_index >= 0) {
661         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
662
663         if (ctx->audio_device_index >= [devices count]) {
664             av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
665             goto fail;
666         }
667
668         audio_device = [devices objectAtIndex:ctx->audio_device_index];
669     } else if (ctx->audio_filename &&
670                strncmp(ctx->audio_filename, "none", 4)) {
671         if (!strncmp(ctx->audio_filename, "default", 7)) {
672             audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
673         } else {
674         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
675
676         for (AVCaptureDevice *device in devices) {
677             if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
678                 audio_device = device;
679                 break;
680             }
681         }
682         }
683
684         if (!audio_device) {
685             av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
686              goto fail;
687         }
688     }
689
690     // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
691     if (!video_device && !audio_device) {
692         av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
693         goto fail;
694     }
695
696     if (video_device) {
697         if (ctx->video_device_index < ctx->num_video_devices) {
698             av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
699         } else {
700             av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
701         }
702     }
703     if (audio_device) {
704         av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
705     }
706
707     // Initialize capture session
708     ctx->capture_session = [[AVCaptureSession alloc] init];
709
710     if (video_device && add_video_device(s, video_device)) {
711         goto fail;
712     }
713     if (audio_device && add_audio_device(s, audio_device)) {
714     }
715
716     [ctx->capture_session startRunning];
717
718     if (video_device && get_video_config(s)) {
719         goto fail;
720     }
721
722     // set audio stream
723     if (audio_device && get_audio_config(s)) {
724         goto fail;
725     }
726
727     [pool release];
728     return 0;
729
730 fail:
731     [pool release];
732     destroy_context(ctx);
733     return AVERROR(EIO);
734 }
735
736 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
737 {
738     AVFContext* ctx = (AVFContext*)s->priv_data;
739
740     do {
741         CVImageBufferRef image_buffer;
742         lock_frames(ctx);
743
744         image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
745
746         if (ctx->current_frame != nil) {
747             void *data;
748             if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
749                 return AVERROR(EIO);
750             }
751
752             pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts,
753                                                AV_TIME_BASE_Q,
754                                                avf_time_base_q);
755             pkt->stream_index  = ctx->video_stream_index;
756             pkt->flags        |= AV_PKT_FLAG_KEY;
757
758             CVPixelBufferLockBaseAddress(image_buffer, 0);
759
760             data = CVPixelBufferGetBaseAddress(image_buffer);
761             memcpy(pkt->data, data, pkt->size);
762
763             CVPixelBufferUnlockBaseAddress(image_buffer, 0);
764             CFRelease(ctx->current_frame);
765             ctx->current_frame = nil;
766         } else if (ctx->current_audio_frame != nil) {
767             CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
768             int block_buffer_size         = CMBlockBufferGetDataLength(block_buffer);
769
770             if (!block_buffer || !block_buffer_size) {
771                 return AVERROR(EIO);
772             }
773
774             if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
775                 return AVERROR_BUFFER_TOO_SMALL;
776             }
777
778             if (av_new_packet(pkt, block_buffer_size) < 0) {
779                 return AVERROR(EIO);
780             }
781
782             pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_audio_pts,
783                                                AV_TIME_BASE_Q,
784                                                avf_time_base_q);
785
786             pkt->stream_index  = ctx->audio_stream_index;
787             pkt->flags        |= AV_PKT_FLAG_KEY;
788
789             if (ctx->audio_non_interleaved) {
790                 int sample, c, shift, num_samples;
791
792                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
793                 if (ret != kCMBlockBufferNoErr) {
794                     return AVERROR(EIO);
795                 }
796
797                 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
798
799                 // transform decoded frame into output format
800                 #define INTERLEAVE_OUTPUT(bps)                                         \
801                 {                                                                      \
802                     int##bps##_t **src;                                                \
803                     int##bps##_t *dest;                                                \
804                     src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*));      \
805                     if (!src) return AVERROR(EIO);                                     \
806                     for (c = 0; c < ctx->audio_channels; c++) {                        \
807                         src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
808                     }                                                                  \
809                     dest  = (int##bps##_t*)pkt->data;                                  \
810                     shift = bps - ctx->audio_bits_per_sample;                          \
811                     for (sample = 0; sample < num_samples; sample++)                   \
812                         for (c = 0; c < ctx->audio_channels; c++)                      \
813                             *dest++ = src[c][sample] << shift;                         \
814                     av_freep(&src);                                                    \
815                 }
816
817                 if (ctx->audio_bits_per_sample <= 16) {
818                     INTERLEAVE_OUTPUT(16)
819                 } else {
820                     INTERLEAVE_OUTPUT(32)
821                 }
822             } else {
823                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
824                 if (ret != kCMBlockBufferNoErr) {
825                     return AVERROR(EIO);
826                 }
827             }
828
829             CFRelease(ctx->current_audio_frame);
830             ctx->current_audio_frame = nil;
831         } else {
832             pkt->data = NULL;
833             pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
834         }
835
836         unlock_frames(ctx);
837     } while (!pkt->data);
838
839     return 0;
840 }
841
842 static int avf_close(AVFormatContext *s)
843 {
844     AVFContext* ctx = (AVFContext*)s->priv_data;
845     destroy_context(ctx);
846     return 0;
847 }
848
849 static const AVOption options[] = {
850     { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
851     { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
852     { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
853     { "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 },
854     { "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 },
855     { "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},
856     { NULL },
857 };
858
859 static const AVClass avf_class = {
860     .class_name = "AVFoundation input device",
861     .item_name  = av_default_item_name,
862     .option     = options,
863     .version    = LIBAVUTIL_VERSION_INT,
864     .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
865 };
866
867 AVInputFormat ff_avfoundation_demuxer = {
868     .name           = "avfoundation",
869     .long_name      = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
870     .priv_data_size = sizeof(AVFContext),
871     .read_header    = avf_read_header,
872     .read_packet    = avf_read_packet,
873     .read_close     = avf_close,
874     .flags          = AVFMT_NOFILE,
875     .priv_class     = &avf_class,
876 };