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