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