2 * AVFoundation input device
3 * Copyright (c) 2014 Thilo Borgmann <thilo.borgmann@mail.de>
5 * This file is part of FFmpeg.
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.
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.
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
24 * AVFoundation input device
25 * @author Thilo Borgmann <thilo.borgmann@mail.de>
28 #import <AVFoundation/AVFoundation.h>
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"
41 static const int avf_time_base = 1000000;
43 static const AVRational avf_time_base_q = {
48 struct AVFPixelFormatSpec {
49 enum AVPixelFormat ff_id;
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 },
79 { AV_PIX_FMT_NONE, 0 }
87 int audio_frames_captured;
89 int64_t first_audio_pts;
90 pthread_mutex_t frame_lock;
91 pthread_cond_t frame_wait_cond;
93 id avf_audio_delegate;
99 int capture_mouse_clicks;
100 int capture_raw_data;
101 int drop_late_frames;
105 int video_device_index;
106 int video_stream_index;
107 int audio_device_index;
108 int audio_stream_index;
110 char *video_filename;
111 char *audio_filename;
113 int num_video_devices;
116 int audio_bits_per_sample;
119 int audio_signed_integer;
121 int audio_non_interleaved;
123 int32_t *audio_buffer;
124 int audio_buffer_size;
126 enum AVPixelFormat pixel_format;
128 AVCaptureSession *capture_session;
129 AVCaptureVideoDataOutput *video_output;
130 AVCaptureAudioDataOutput *audio_output;
131 CMSampleBufferRef current_frame;
132 CMSampleBufferRef current_audio_frame;
135 static void lock_frames(AVFContext* ctx)
137 pthread_mutex_lock(&ctx->frame_lock);
140 static void unlock_frames(AVFContext* ctx)
142 pthread_mutex_unlock(&ctx->frame_lock);
145 /** FrameReciever class - delegate for AVCaptureSession
147 @interface AVFFrameReceiver : NSObject
149 AVFContext* _context;
152 - (id)initWithContext:(AVFContext*)context;
154 - (void) captureOutput:(AVCaptureOutput *)captureOutput
155 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
156 fromConnection:(AVCaptureConnection *)connection;
160 @implementation AVFFrameReceiver
162 - (id)initWithContext:(AVFContext*)context
164 if (self = [super init]) {
170 - (void) captureOutput:(AVCaptureOutput *)captureOutput
171 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
172 fromConnection:(AVCaptureConnection *)connection
174 lock_frames(_context);
176 if (_context->current_frame != nil) {
177 CFRelease(_context->current_frame);
180 _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
182 pthread_cond_signal(&_context->frame_wait_cond);
184 unlock_frames(_context);
186 ++_context->frames_captured;
191 /** AudioReciever class - delegate for AVCaptureSession
193 @interface AVFAudioReceiver : NSObject
195 AVFContext* _context;
198 - (id)initWithContext:(AVFContext*)context;
200 - (void) captureOutput:(AVCaptureOutput *)captureOutput
201 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
202 fromConnection:(AVCaptureConnection *)connection;
206 @implementation AVFAudioReceiver
208 - (id)initWithContext:(AVFContext*)context
210 if (self = [super init]) {
216 - (void) captureOutput:(AVCaptureOutput *)captureOutput
217 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
218 fromConnection:(AVCaptureConnection *)connection
220 lock_frames(_context);
222 if (_context->current_audio_frame != nil) {
223 CFRelease(_context->current_audio_frame);
226 _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
228 pthread_cond_signal(&_context->frame_wait_cond);
230 unlock_frames(_context);
232 ++_context->audio_frames_captured;
237 static void destroy_context(AVFContext* ctx)
239 [ctx->capture_session stopRunning];
241 [ctx->capture_session release];
242 [ctx->video_output release];
243 [ctx->audio_output release];
244 [ctx->avf_delegate release];
245 [ctx->avf_audio_delegate release];
247 ctx->capture_session = NULL;
248 ctx->video_output = NULL;
249 ctx->audio_output = NULL;
250 ctx->avf_delegate = NULL;
251 ctx->avf_audio_delegate = NULL;
253 av_freep(&ctx->audio_buffer);
255 pthread_mutex_destroy(&ctx->frame_lock);
256 pthread_cond_destroy(&ctx->frame_wait_cond);
258 if (ctx->current_frame) {
259 CFRelease(ctx->current_frame);
263 static void parse_device_name(AVFormatContext *s)
265 AVFContext *ctx = (AVFContext*)s->priv_data;
266 char *tmp = av_strdup(s->url);
270 ctx->video_filename = av_strtok(tmp, ":", &save);
271 ctx->audio_filename = av_strtok(NULL, ":", &save);
273 ctx->audio_filename = av_strtok(tmp, ":", &save);
278 * Configure the video device.
280 * Configure the video device using a run-time approach to access properties
281 * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
282 * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
284 * The NSUndefinedKeyException must be handled by the caller of this function.
287 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
289 AVFContext *ctx = (AVFContext*)s->priv_data;
291 double framerate = av_q2d(ctx->framerate);
292 NSObject *range = nil;
293 NSObject *format = nil;
294 NSObject *selected_range = nil;
295 NSObject *selected_format = nil;
297 // try to configure format by formats list
298 // might raise an exception if no format list is given
299 // (then fallback to default, no configuration)
301 for (format in [video_device valueForKey:@"formats"]) {
302 CMFormatDescriptionRef formatDescription;
303 CMVideoDimensions dimensions;
305 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
306 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
308 if ((ctx->width == 0 && ctx->height == 0) ||
309 (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
311 selected_format = format;
313 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
314 double max_framerate;
316 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
317 if (fabs (framerate - max_framerate) < 0.01) {
318 selected_range = range;
325 if (!selected_format) {
326 av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device.\n",
327 ctx->width, ctx->height);
328 goto unsupported_format;
331 if (!selected_range) {
332 av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device.\n",
334 if (ctx->video_is_muxed) {
335 av_log(s, AV_LOG_ERROR, "Falling back to default.\n");
337 goto unsupported_format;
341 if ([video_device lockForConfiguration:NULL] == YES) {
342 if (selected_format) {
343 [video_device setValue:selected_format forKey:@"activeFormat"];
345 if (selected_range) {
346 NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
347 [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
348 [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
351 av_log(s, AV_LOG_ERROR, "Could not lock device for configuration.\n");
352 return AVERROR(EINVAL);
354 } @catch(NSException *e) {
355 av_log(ctx, AV_LOG_WARNING, "Configuration of video device failed, falling back to default.\n");
362 av_log(s, AV_LOG_ERROR, "Supported modes:\n");
363 for (format in [video_device valueForKey:@"formats"]) {
364 CMFormatDescriptionRef formatDescription;
365 CMVideoDimensions dimensions;
367 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
368 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
370 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
371 double min_framerate;
372 double max_framerate;
374 [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
375 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
376 av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
377 dimensions.width, dimensions.height,
378 min_framerate, max_framerate);
381 return AVERROR(EINVAL);
384 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
386 AVFContext *ctx = (AVFContext*)s->priv_data;
388 NSError *error = nil;
389 AVCaptureInput* capture_input = nil;
390 struct AVFPixelFormatSpec pxl_fmt_spec;
391 NSNumber *pixel_format;
392 NSDictionary *capture_dict;
393 dispatch_queue_t queue;
395 if (ctx->video_device_index < ctx->num_video_devices) {
396 capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
398 capture_input = (AVCaptureInput*) video_device;
401 if (!capture_input) {
402 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
403 [[error localizedDescription] UTF8String]);
407 if ([ctx->capture_session canAddInput:capture_input]) {
408 [ctx->capture_session addInput:capture_input];
410 av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
415 ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
417 if (!ctx->video_output) {
418 av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
422 // Configure device framerate and video size
424 if ((ret = configure_video_device(s, video_device)) < 0) {
427 } @catch (NSException *exception) {
428 if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
429 av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
430 return AVERROR_EXTERNAL;
434 // select pixel format
435 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
437 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
438 if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
439 pxl_fmt_spec = avf_pixel_formats[i];
444 // check if selected pixel format is supported by AVFoundation
445 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
446 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
447 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
451 // check if the pixel format is available for this device
452 if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
453 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
454 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
456 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
458 av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
459 for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
460 struct AVFPixelFormatSpec pxl_fmt_dummy;
461 pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
462 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
463 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
464 pxl_fmt_dummy = avf_pixel_formats[i];
469 if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
470 av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
472 // select first supported pixel format instead of user selected (or default) pixel format
473 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
474 pxl_fmt_spec = pxl_fmt_dummy;
479 // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
480 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
483 av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
484 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
488 // set videoSettings to an empty dict for receiving raw data of muxed devices
489 if (ctx->capture_raw_data) {
490 ctx->pixel_format = pxl_fmt_spec.ff_id;
491 ctx->video_output.videoSettings = @{ };
493 ctx->pixel_format = pxl_fmt_spec.ff_id;
494 pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
495 capture_dict = [NSDictionary dictionaryWithObject:pixel_format
496 forKey:(id)kCVPixelBufferPixelFormatTypeKey];
498 [ctx->video_output setVideoSettings:capture_dict];
500 [ctx->video_output setAlwaysDiscardsLateVideoFrames:ctx->drop_late_frames];
502 ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
504 queue = dispatch_queue_create("avf_queue", NULL);
505 [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
506 dispatch_release(queue);
508 if ([ctx->capture_session canAddOutput:ctx->video_output]) {
509 [ctx->capture_session addOutput:ctx->video_output];
511 av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
518 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
520 AVFContext *ctx = (AVFContext*)s->priv_data;
521 NSError *error = nil;
522 AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
523 dispatch_queue_t queue;
525 if (!audio_dev_input) {
526 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
527 [[error localizedDescription] UTF8String]);
531 if ([ctx->capture_session canAddInput:audio_dev_input]) {
532 [ctx->capture_session addInput:audio_dev_input];
534 av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
539 ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
541 if (!ctx->audio_output) {
542 av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
546 ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
548 queue = dispatch_queue_create("avf_audio_queue", NULL);
549 [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
550 dispatch_release(queue);
552 if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
553 [ctx->capture_session addOutput:ctx->audio_output];
555 av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
562 static int get_video_config(AVFormatContext *s)
564 AVFContext *ctx = (AVFContext*)s->priv_data;
565 CVImageBufferRef image_buffer;
566 CMBlockBufferRef block_buffer;
567 CGSize image_buffer_size;
568 AVStream* stream = avformat_new_stream(s, NULL);
574 // Take stream info from the first frame.
575 while (ctx->frames_captured < 1) {
576 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
581 ctx->video_stream_index = stream->index;
583 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
585 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
586 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
589 image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
591 stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
592 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
593 stream->codecpar->width = (int)image_buffer_size.width;
594 stream->codecpar->height = (int)image_buffer_size.height;
595 stream->codecpar->format = ctx->pixel_format;
597 stream->codecpar->codec_id = AV_CODEC_ID_DVVIDEO;
598 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
599 stream->codecpar->format = ctx->pixel_format;
602 CFRelease(ctx->current_frame);
603 ctx->current_frame = nil;
610 static int get_audio_config(AVFormatContext *s)
612 AVFContext *ctx = (AVFContext*)s->priv_data;
613 CMFormatDescriptionRef format_desc;
614 AVStream* stream = avformat_new_stream(s, NULL);
620 // Take stream info from the first frame.
621 while (ctx->audio_frames_captured < 1) {
622 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
627 ctx->audio_stream_index = stream->index;
629 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
631 format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
632 const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
635 av_log(s, AV_LOG_ERROR, "audio format not available\n");
639 stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
640 stream->codecpar->sample_rate = basic_desc->mSampleRate;
641 stream->codecpar->channels = basic_desc->mChannelsPerFrame;
642 stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
644 ctx->audio_channels = basic_desc->mChannelsPerFrame;
645 ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
646 ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
647 ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
648 ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
649 ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
650 ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
652 if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
654 ctx->audio_bits_per_sample == 32 &&
656 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
657 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
658 ctx->audio_signed_integer &&
659 ctx->audio_bits_per_sample == 16 &&
661 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
662 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
663 ctx->audio_signed_integer &&
664 ctx->audio_bits_per_sample == 24 &&
666 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
667 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
668 ctx->audio_signed_integer &&
669 ctx->audio_bits_per_sample == 32 &&
671 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
673 av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
677 if (ctx->audio_non_interleaved) {
678 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
679 ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
680 ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
681 if (!ctx->audio_buffer) {
682 av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
687 CFRelease(ctx->current_audio_frame);
688 ctx->current_audio_frame = nil;
695 static int avf_read_header(AVFormatContext *s)
697 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
698 int capture_screen = 0;
699 uint32_t num_screens = 0;
700 AVFContext *ctx = (AVFContext*)s->priv_data;
701 AVCaptureDevice *video_device = nil;
702 AVCaptureDevice *audio_device = nil;
703 // Find capture device
704 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
705 NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
707 ctx->num_video_devices = [devices count] + [devices_muxed count];
708 ctx->first_pts = av_gettime();
709 ctx->first_audio_pts = av_gettime();
711 pthread_mutex_init(&ctx->frame_lock, NULL);
712 pthread_cond_init(&ctx->frame_wait_cond, NULL);
714 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
715 CGGetActiveDisplayList(0, NULL, &num_screens);
718 // List devices if requested
719 if (ctx->list_devices) {
721 av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
722 for (AVCaptureDevice *device in devices) {
723 const char *name = [[device localizedName] UTF8String];
724 index = [devices indexOfObject:device];
725 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
727 for (AVCaptureDevice *device in devices_muxed) {
728 const char *name = [[device localizedName] UTF8String];
729 index = [devices count] + [devices_muxed indexOfObject:device];
730 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
732 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
733 if (num_screens > 0) {
734 CGDirectDisplayID screens[num_screens];
735 CGGetActiveDisplayList(num_screens, screens, &num_screens);
736 for (int i = 0; i < num_screens; i++) {
737 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", ctx->num_video_devices + i, i);
742 av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
743 devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
744 for (AVCaptureDevice *device in devices) {
745 const char *name = [[device localizedName] UTF8String];
746 int index = [devices indexOfObject:device];
747 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
752 // parse input filename for video and audio device
753 parse_device_name(s);
755 // check for device index given in filename
756 if (ctx->video_device_index == -1 && ctx->video_filename) {
757 sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
759 if (ctx->audio_device_index == -1 && ctx->audio_filename) {
760 sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
763 if (ctx->video_device_index >= 0) {
764 if (ctx->video_device_index < ctx->num_video_devices) {
765 if (ctx->video_device_index < [devices count]) {
766 video_device = [devices objectAtIndex:ctx->video_device_index];
768 video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
769 ctx->video_is_muxed = 1;
771 } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
772 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
773 CGDirectDisplayID screens[num_screens];
774 CGGetActiveDisplayList(num_screens, screens, &num_screens);
775 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
777 if (ctx->framerate.num > 0) {
778 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
781 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
782 if (ctx->capture_cursor) {
783 capture_screen_input.capturesCursor = YES;
785 capture_screen_input.capturesCursor = NO;
789 if (ctx->capture_mouse_clicks) {
790 capture_screen_input.capturesMouseClicks = YES;
792 capture_screen_input.capturesMouseClicks = NO;
795 video_device = (AVCaptureDevice*) capture_screen_input;
799 av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
802 } else if (ctx->video_filename &&
803 strncmp(ctx->video_filename, "none", 4)) {
804 if (!strncmp(ctx->video_filename, "default", 7)) {
805 video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
807 // looking for video inputs
808 for (AVCaptureDevice *device in devices) {
809 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
810 video_device = device;
814 // looking for muxed inputs
815 for (AVCaptureDevice *device in devices_muxed) {
816 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
817 video_device = device;
818 ctx->video_is_muxed = 1;
823 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
824 // looking for screen inputs
827 if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
828 CGDirectDisplayID screens[num_screens];
829 CGGetActiveDisplayList(num_screens, screens, &num_screens);
830 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
831 video_device = (AVCaptureDevice*) capture_screen_input;
832 ctx->video_device_index = ctx->num_video_devices + idx;
835 if (ctx->framerate.num > 0) {
836 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
839 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
840 if (ctx->capture_cursor) {
841 capture_screen_input.capturesCursor = YES;
843 capture_screen_input.capturesCursor = NO;
847 if (ctx->capture_mouse_clicks) {
848 capture_screen_input.capturesMouseClicks = YES;
850 capture_screen_input.capturesMouseClicks = NO;
858 av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
864 if (ctx->audio_device_index >= 0) {
865 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
867 if (ctx->audio_device_index >= [devices count]) {
868 av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
872 audio_device = [devices objectAtIndex:ctx->audio_device_index];
873 } else if (ctx->audio_filename &&
874 strncmp(ctx->audio_filename, "none", 4)) {
875 if (!strncmp(ctx->audio_filename, "default", 7)) {
876 audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
878 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
880 for (AVCaptureDevice *device in devices) {
881 if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
882 audio_device = device;
889 av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
894 // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
895 if (!video_device && !audio_device) {
896 av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
901 if (ctx->video_device_index < ctx->num_video_devices) {
902 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
904 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
908 av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
911 // Initialize capture session
912 ctx->capture_session = [[AVCaptureSession alloc] init];
914 if (video_device && add_video_device(s, video_device)) {
917 if (audio_device && add_audio_device(s, audio_device)) {
920 [ctx->capture_session startRunning];
922 /* Unlock device configuration only after the session is started so it
923 * does not reset the capture formats */
924 if (!capture_screen) {
925 [video_device unlockForConfiguration];
928 if (video_device && get_video_config(s)) {
933 if (audio_device && get_audio_config(s)) {
942 destroy_context(ctx);
946 static int copy_cvpixelbuffer(AVFormatContext *s,
947 CVPixelBufferRef image_buffer,
950 AVFContext *ctx = s->priv_data;
952 const uint8_t *src_data[4];
953 int width = CVPixelBufferGetWidth(image_buffer);
954 int height = CVPixelBufferGetHeight(image_buffer);
957 memset(src_linesize, 0, sizeof(src_linesize));
958 memset(src_data, 0, sizeof(src_data));
960 status = CVPixelBufferLockBaseAddress(image_buffer, 0);
961 if (status != kCVReturnSuccess) {
962 av_log(s, AV_LOG_ERROR, "Could not lock base address: %d (%dx%d)\n", status, width, height);
963 return AVERROR_EXTERNAL;
966 if (CVPixelBufferIsPlanar(image_buffer)) {
967 size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
969 for(i = 0; i < plane_count; i++){
970 src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
971 src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
974 src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
975 src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
978 status = av_image_copy_to_buffer(pkt->data, pkt->size,
979 src_data, src_linesize,
980 ctx->pixel_format, width, height, 1);
984 CVPixelBufferUnlockBaseAddress(image_buffer, 0);
989 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
991 AVFContext* ctx = (AVFContext*)s->priv_data;
994 CVImageBufferRef image_buffer;
995 CMBlockBufferRef block_buffer;
998 if (ctx->current_frame != nil) {
1002 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
1003 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
1005 if (image_buffer != nil) {
1006 length = (int)CVPixelBufferGetDataSize(image_buffer);
1007 } else if (block_buffer != nil) {
1008 length = (int)CMBlockBufferGetDataLength(block_buffer);
1010 return AVERROR(EINVAL);
1013 if (av_new_packet(pkt, length) < 0) {
1014 return AVERROR(EIO);
1018 CMSampleTimingInfo timing_info;
1020 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
1021 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1022 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1025 pkt->stream_index = ctx->video_stream_index;
1026 pkt->flags |= AV_PKT_FLAG_KEY;
1029 status = copy_cvpixelbuffer(s, image_buffer, pkt);
1032 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1033 if (ret != kCMBlockBufferNoErr) {
1034 status = AVERROR(EIO);
1037 CFRelease(ctx->current_frame);
1038 ctx->current_frame = nil;
1042 } else if (ctx->current_audio_frame != nil) {
1043 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
1044 int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
1046 if (!block_buffer || !block_buffer_size) {
1047 return AVERROR(EIO);
1050 if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
1051 return AVERROR_BUFFER_TOO_SMALL;
1054 if (av_new_packet(pkt, block_buffer_size) < 0) {
1055 return AVERROR(EIO);
1059 CMSampleTimingInfo timing_info;
1061 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
1062 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1063 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1066 pkt->stream_index = ctx->audio_stream_index;
1067 pkt->flags |= AV_PKT_FLAG_KEY;
1069 if (ctx->audio_non_interleaved) {
1070 int sample, c, shift, num_samples;
1072 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
1073 if (ret != kCMBlockBufferNoErr) {
1074 return AVERROR(EIO);
1077 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
1079 // transform decoded frame into output format
1080 #define INTERLEAVE_OUTPUT(bps) \
1082 int##bps##_t **src; \
1083 int##bps##_t *dest; \
1084 src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
1085 if (!src) return AVERROR(EIO); \
1086 for (c = 0; c < ctx->audio_channels; c++) { \
1087 src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1089 dest = (int##bps##_t*)pkt->data; \
1090 shift = bps - ctx->audio_bits_per_sample; \
1091 for (sample = 0; sample < num_samples; sample++) \
1092 for (c = 0; c < ctx->audio_channels; c++) \
1093 *dest++ = src[c][sample] << shift; \
1097 if (ctx->audio_bits_per_sample <= 16) {
1098 INTERLEAVE_OUTPUT(16)
1100 INTERLEAVE_OUTPUT(32)
1103 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1104 if (ret != kCMBlockBufferNoErr) {
1105 return AVERROR(EIO);
1109 CFRelease(ctx->current_audio_frame);
1110 ctx->current_audio_frame = nil;
1113 pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
1117 } while (!pkt->data);
1122 static int avf_close(AVFormatContext *s)
1124 AVFContext* ctx = (AVFContext*)s->priv_data;
1125 destroy_context(ctx);
1129 static const AVOption options[] = {
1130 { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1131 { "video_device_index", "select video device by index for devices with same name (starts at 0)", offsetof(AVFContext, video_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1132 { "audio_device_index", "select audio device by index for devices with same name (starts at 0)", offsetof(AVFContext, audio_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1133 { "pixel_format", "set pixel format", offsetof(AVFContext, pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_YUV420P}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM},
1134 { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1135 { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
1136 { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1137 { "capture_mouse_clicks", "capture the screen mouse clicks", offsetof(AVFContext, capture_mouse_clicks), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1138 { "capture_raw_data", "capture the raw data from device connection", offsetof(AVFContext, capture_raw_data), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1139 { "drop_late_frames", "drop frames that are available later than expected", offsetof(AVFContext, drop_late_frames), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1144 static const AVClass avf_class = {
1145 .class_name = "AVFoundation indev",
1146 .item_name = av_default_item_name,
1148 .version = LIBAVUTIL_VERSION_INT,
1149 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
1152 AVInputFormat ff_avfoundation_demuxer = {
1153 .name = "avfoundation",
1154 .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
1155 .priv_data_size = sizeof(AVFContext),
1156 .read_header = avf_read_header,
1157 .read_packet = avf_read_packet,
1158 .read_close = avf_close,
1159 .flags = AVFMT_NOFILE,
1160 .priv_class = &avf_class,