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