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;
92 id avf_audio_delegate;
98 int capture_mouse_clicks;
100 int drop_late_frames;
104 int video_device_index;
105 int video_stream_index;
106 int audio_device_index;
107 int audio_stream_index;
109 char *video_filename;
110 char *audio_filename;
112 int num_video_devices;
115 int audio_bits_per_sample;
118 int audio_signed_integer;
120 int audio_non_interleaved;
122 int32_t *audio_buffer;
123 int audio_buffer_size;
125 enum AVPixelFormat pixel_format;
127 AVCaptureSession *capture_session;
128 AVCaptureVideoDataOutput *video_output;
129 AVCaptureAudioDataOutput *audio_output;
130 CMSampleBufferRef current_frame;
131 CMSampleBufferRef current_audio_frame;
133 AVCaptureDevice *observed_device;
134 AVCaptureDeviceTransportControlsPlaybackMode observed_mode;
138 static void lock_frames(AVFContext* ctx)
140 pthread_mutex_lock(&ctx->frame_lock);
143 static void unlock_frames(AVFContext* ctx)
145 pthread_mutex_unlock(&ctx->frame_lock);
148 /** FrameReciever class - delegate for AVCaptureSession
150 @interface AVFFrameReceiver : NSObject
152 AVFContext* _context;
155 - (id)initWithContext:(AVFContext*)context;
157 - (void) captureOutput:(AVCaptureOutput *)captureOutput
158 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
159 fromConnection:(AVCaptureConnection *)connection;
163 @implementation AVFFrameReceiver
165 - (id)initWithContext:(AVFContext*)context
167 if (self = [super init]) {
170 // start observing if a device is set for it
171 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
172 if (_context->observed_device) {
173 NSString *keyPath = NSStringFromSelector(@selector(transportControlsPlaybackMode));
174 NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew;
176 [_context->observed_device addObserver: self
187 // stop observing if a device is set for it
188 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
189 if (_context->observed_device) {
190 NSString *keyPath = NSStringFromSelector(@selector(transportControlsPlaybackMode));
191 [_context->observed_device removeObserver: self forKeyPath: keyPath];
197 - (void)observeValueForKeyPath:(NSString *)keyPath
199 change:(NSDictionary *)change
200 context:(void *)context {
201 if (context == _context) {
202 AVCaptureDeviceTransportControlsPlaybackMode mode =
203 [change[NSKeyValueChangeNewKey] integerValue];
205 if (mode != _context->observed_mode) {
206 if (mode == AVCaptureDeviceTransportControlsNotPlayingMode) {
207 _context->observed_quit = 1;
209 _context->observed_mode = mode;
212 [super observeValueForKeyPath: keyPath
219 - (void) captureOutput:(AVCaptureOutput *)captureOutput
220 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
221 fromConnection:(AVCaptureConnection *)connection
223 lock_frames(_context);
225 if (_context->current_frame != nil) {
226 CFRelease(_context->current_frame);
229 _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
231 unlock_frames(_context);
233 ++_context->frames_captured;
238 /** AudioReciever class - delegate for AVCaptureSession
240 @interface AVFAudioReceiver : NSObject
242 AVFContext* _context;
245 - (id)initWithContext:(AVFContext*)context;
247 - (void) captureOutput:(AVCaptureOutput *)captureOutput
248 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
249 fromConnection:(AVCaptureConnection *)connection;
253 @implementation AVFAudioReceiver
255 - (id)initWithContext:(AVFContext*)context
257 if (self = [super init]) {
263 - (void) captureOutput:(AVCaptureOutput *)captureOutput
264 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
265 fromConnection:(AVCaptureConnection *)connection
267 lock_frames(_context);
269 if (_context->current_audio_frame != nil) {
270 CFRelease(_context->current_audio_frame);
273 _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
275 unlock_frames(_context);
277 ++_context->audio_frames_captured;
282 static void destroy_context(AVFContext* ctx)
284 [ctx->capture_session stopRunning];
286 [ctx->capture_session release];
287 [ctx->video_output release];
288 [ctx->audio_output release];
289 [ctx->avf_delegate release];
290 [ctx->avf_audio_delegate release];
292 ctx->capture_session = NULL;
293 ctx->video_output = NULL;
294 ctx->audio_output = NULL;
295 ctx->avf_delegate = NULL;
296 ctx->avf_audio_delegate = NULL;
298 av_freep(&ctx->audio_buffer);
300 pthread_mutex_destroy(&ctx->frame_lock);
302 if (ctx->current_frame) {
303 CFRelease(ctx->current_frame);
307 static void parse_device_name(AVFormatContext *s)
309 AVFContext *ctx = (AVFContext*)s->priv_data;
310 char *tmp = av_strdup(s->url);
314 ctx->video_filename = av_strtok(tmp, ":", &save);
315 ctx->audio_filename = av_strtok(NULL, ":", &save);
317 ctx->audio_filename = av_strtok(tmp, ":", &save);
322 * Configure the video device.
324 * Configure the video device using a run-time approach to access properties
325 * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
326 * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
328 * The NSUndefinedKeyException must be handled by the caller of this function.
331 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
333 AVFContext *ctx = (AVFContext*)s->priv_data;
335 double framerate = av_q2d(ctx->framerate);
336 NSObject *range = nil;
337 NSObject *format = nil;
338 NSObject *selected_range = nil;
339 NSObject *selected_format = nil;
341 // try to configure format by formats list
342 // might raise an exception if no format list is given
343 // (then fallback to default, no configuration)
345 for (format in [video_device valueForKey:@"formats"]) {
346 CMFormatDescriptionRef formatDescription;
347 CMVideoDimensions dimensions;
349 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
350 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
352 if ((ctx->width == 0 && ctx->height == 0) ||
353 (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
355 selected_format = format;
357 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
358 double max_framerate;
360 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
361 if (fabs (framerate - max_framerate) < 0.01) {
362 selected_range = range;
369 if (!selected_format) {
370 av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device.\n",
371 ctx->width, ctx->height);
372 goto unsupported_format;
375 if (!selected_range) {
376 av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device.\n",
378 if (ctx->video_is_muxed) {
379 av_log(s, AV_LOG_ERROR, "Falling back to default.\n");
381 goto unsupported_format;
385 if ([video_device lockForConfiguration:NULL] == YES) {
386 if (selected_format) {
387 [video_device setValue:selected_format forKey:@"activeFormat"];
389 if (selected_range) {
390 NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
391 [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
392 [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
395 av_log(s, AV_LOG_ERROR, "Could not lock device for configuration.\n");
396 return AVERROR(EINVAL);
398 } @catch(NSException *e) {
399 av_log(ctx, AV_LOG_WARNING, "Configuration of video device failed, falling back to default.\n");
406 av_log(s, AV_LOG_ERROR, "Supported modes:\n");
407 for (format in [video_device valueForKey:@"formats"]) {
408 CMFormatDescriptionRef formatDescription;
409 CMVideoDimensions dimensions;
411 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
412 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
414 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
415 double min_framerate;
416 double max_framerate;
418 [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
419 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
420 av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
421 dimensions.width, dimensions.height,
422 min_framerate, max_framerate);
425 return AVERROR(EINVAL);
428 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
430 AVFContext *ctx = (AVFContext*)s->priv_data;
432 NSError *error = nil;
433 AVCaptureInput* capture_input = nil;
434 struct AVFPixelFormatSpec pxl_fmt_spec;
435 NSNumber *pixel_format;
436 NSDictionary *capture_dict;
437 dispatch_queue_t queue;
439 if (ctx->video_device_index < ctx->num_video_devices) {
440 capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
442 capture_input = (AVCaptureInput*) video_device;
445 if (!capture_input) {
446 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
447 [[error localizedDescription] UTF8String]);
451 if ([ctx->capture_session canAddInput:capture_input]) {
452 [ctx->capture_session addInput:capture_input];
454 av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
459 ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
461 if (!ctx->video_output) {
462 av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
466 // Configure device framerate and video size
468 if ((ret = configure_video_device(s, video_device)) < 0) {
471 } @catch (NSException *exception) {
472 if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
473 av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
474 return AVERROR_EXTERNAL;
478 // select pixel format
479 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
481 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
482 if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
483 pxl_fmt_spec = avf_pixel_formats[i];
488 // check if selected pixel format is supported by AVFoundation
489 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
490 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
491 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
495 // check if the pixel format is available for this device
496 if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
497 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
498 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
500 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
502 av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
503 for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
504 struct AVFPixelFormatSpec pxl_fmt_dummy;
505 pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
506 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
507 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
508 pxl_fmt_dummy = avf_pixel_formats[i];
513 if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
514 av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
516 // select first supported pixel format instead of user selected (or default) pixel format
517 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
518 pxl_fmt_spec = pxl_fmt_dummy;
523 // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
524 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
527 av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
528 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
532 // set videoSettings to an empty dict for receiving raw data of muxed devices
533 if (ctx->capture_raw_data) {
534 ctx->pixel_format = pxl_fmt_spec.ff_id;
535 ctx->video_output.videoSettings = @{ };
537 ctx->pixel_format = pxl_fmt_spec.ff_id;
538 pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
539 capture_dict = [NSDictionary dictionaryWithObject:pixel_format
540 forKey:(id)kCVPixelBufferPixelFormatTypeKey];
542 [ctx->video_output setVideoSettings:capture_dict];
544 [ctx->video_output setAlwaysDiscardsLateVideoFrames:ctx->drop_late_frames];
546 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
547 // check for transport control support and set observer device if supported
548 int trans_ctrl = [video_device transportControlsSupported];
549 AVCaptureDeviceTransportControlsPlaybackMode trans_mode = [video_device transportControlsPlaybackMode];
552 ctx->observed_mode = trans_mode;
553 ctx->observed_device = video_device;
557 ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
559 queue = dispatch_queue_create("avf_queue", NULL);
560 [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
561 dispatch_release(queue);
563 if ([ctx->capture_session canAddOutput:ctx->video_output]) {
564 [ctx->capture_session addOutput:ctx->video_output];
566 av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
573 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
575 AVFContext *ctx = (AVFContext*)s->priv_data;
576 NSError *error = nil;
577 AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
578 dispatch_queue_t queue;
580 if (!audio_dev_input) {
581 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
582 [[error localizedDescription] UTF8String]);
586 if ([ctx->capture_session canAddInput:audio_dev_input]) {
587 [ctx->capture_session addInput:audio_dev_input];
589 av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
594 ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
596 if (!ctx->audio_output) {
597 av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
601 ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
603 queue = dispatch_queue_create("avf_audio_queue", NULL);
604 [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
605 dispatch_release(queue);
607 if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
608 [ctx->capture_session addOutput:ctx->audio_output];
610 av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
617 static int get_video_config(AVFormatContext *s)
619 AVFContext *ctx = (AVFContext*)s->priv_data;
620 CVImageBufferRef image_buffer;
621 CMBlockBufferRef block_buffer;
622 CGSize image_buffer_size;
623 AVStream* stream = avformat_new_stream(s, NULL);
629 // Take stream info from the first frame.
630 while (ctx->frames_captured < 1) {
631 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
636 ctx->video_stream_index = stream->index;
638 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
640 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
641 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
644 image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
646 stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
647 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
648 stream->codecpar->width = (int)image_buffer_size.width;
649 stream->codecpar->height = (int)image_buffer_size.height;
650 stream->codecpar->format = ctx->pixel_format;
652 stream->codecpar->codec_id = AV_CODEC_ID_DVVIDEO;
653 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
654 stream->codecpar->format = ctx->pixel_format;
657 CFRelease(ctx->current_frame);
658 ctx->current_frame = nil;
665 static int get_audio_config(AVFormatContext *s)
667 AVFContext *ctx = (AVFContext*)s->priv_data;
668 CMFormatDescriptionRef format_desc;
669 AVStream* stream = avformat_new_stream(s, NULL);
675 // Take stream info from the first frame.
676 while (ctx->audio_frames_captured < 1) {
677 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
682 ctx->audio_stream_index = stream->index;
684 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
686 format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
687 const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
690 av_log(s, AV_LOG_ERROR, "audio format not available\n");
694 stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
695 stream->codecpar->sample_rate = basic_desc->mSampleRate;
696 stream->codecpar->channels = basic_desc->mChannelsPerFrame;
697 stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
699 ctx->audio_channels = basic_desc->mChannelsPerFrame;
700 ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
701 ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
702 ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
703 ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
704 ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
705 ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
707 if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
709 ctx->audio_bits_per_sample == 32 &&
711 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
712 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
713 ctx->audio_signed_integer &&
714 ctx->audio_bits_per_sample == 16 &&
716 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
717 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
718 ctx->audio_signed_integer &&
719 ctx->audio_bits_per_sample == 24 &&
721 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
722 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
723 ctx->audio_signed_integer &&
724 ctx->audio_bits_per_sample == 32 &&
726 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
728 av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
732 if (ctx->audio_non_interleaved) {
733 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
734 ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
735 ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
736 if (!ctx->audio_buffer) {
737 av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
742 CFRelease(ctx->current_audio_frame);
743 ctx->current_audio_frame = nil;
750 static int avf_read_header(AVFormatContext *s)
752 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
753 int capture_screen = 0;
754 uint32_t num_screens = 0;
755 AVFContext *ctx = (AVFContext*)s->priv_data;
756 AVCaptureDevice *video_device = nil;
757 AVCaptureDevice *audio_device = nil;
758 // Find capture device
759 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
760 NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
762 ctx->num_video_devices = [devices count] + [devices_muxed count];
763 ctx->first_pts = av_gettime();
764 ctx->first_audio_pts = av_gettime();
766 pthread_mutex_init(&ctx->frame_lock, NULL);
768 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
769 CGGetActiveDisplayList(0, NULL, &num_screens);
772 // List devices if requested
773 if (ctx->list_devices) {
775 av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
776 for (AVCaptureDevice *device in devices) {
777 const char *name = [[device localizedName] UTF8String];
778 index = [devices indexOfObject:device];
779 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
781 for (AVCaptureDevice *device in devices_muxed) {
782 const char *name = [[device localizedName] UTF8String];
783 index = [devices count] + [devices_muxed indexOfObject:device];
784 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
786 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
787 if (num_screens > 0) {
788 CGDirectDisplayID screens[num_screens];
789 CGGetActiveDisplayList(num_screens, screens, &num_screens);
790 for (int i = 0; i < num_screens; i++) {
791 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", ctx->num_video_devices + i, i);
796 av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
797 devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
798 for (AVCaptureDevice *device in devices) {
799 const char *name = [[device localizedName] UTF8String];
800 int index = [devices indexOfObject:device];
801 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
806 // parse input filename for video and audio device
807 parse_device_name(s);
809 // check for device index given in filename
810 if (ctx->video_device_index == -1 && ctx->video_filename) {
811 sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
813 if (ctx->audio_device_index == -1 && ctx->audio_filename) {
814 sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
817 if (ctx->video_device_index >= 0) {
818 if (ctx->video_device_index < ctx->num_video_devices) {
819 if (ctx->video_device_index < [devices count]) {
820 video_device = [devices objectAtIndex:ctx->video_device_index];
822 video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
823 ctx->video_is_muxed = 1;
825 } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
826 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
827 CGDirectDisplayID screens[num_screens];
828 CGGetActiveDisplayList(num_screens, screens, &num_screens);
829 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
831 if (ctx->framerate.num > 0) {
832 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
835 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
836 if (ctx->capture_cursor) {
837 capture_screen_input.capturesCursor = YES;
839 capture_screen_input.capturesCursor = NO;
843 if (ctx->capture_mouse_clicks) {
844 capture_screen_input.capturesMouseClicks = YES;
846 capture_screen_input.capturesMouseClicks = NO;
849 video_device = (AVCaptureDevice*) capture_screen_input;
853 av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
856 } else if (ctx->video_filename &&
857 strncmp(ctx->video_filename, "none", 4)) {
858 if (!strncmp(ctx->video_filename, "default", 7)) {
859 video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
861 // looking for video inputs
862 for (AVCaptureDevice *device in devices) {
863 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
864 video_device = device;
868 // looking for muxed inputs
869 for (AVCaptureDevice *device in devices_muxed) {
870 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
871 video_device = device;
872 ctx->video_is_muxed = 1;
877 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
878 // looking for screen inputs
881 if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
882 CGDirectDisplayID screens[num_screens];
883 CGGetActiveDisplayList(num_screens, screens, &num_screens);
884 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
885 video_device = (AVCaptureDevice*) capture_screen_input;
886 ctx->video_device_index = ctx->num_video_devices + idx;
889 if (ctx->framerate.num > 0) {
890 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
893 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
894 if (ctx->capture_cursor) {
895 capture_screen_input.capturesCursor = YES;
897 capture_screen_input.capturesCursor = NO;
901 if (ctx->capture_mouse_clicks) {
902 capture_screen_input.capturesMouseClicks = YES;
904 capture_screen_input.capturesMouseClicks = NO;
912 av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
918 if (ctx->audio_device_index >= 0) {
919 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
921 if (ctx->audio_device_index >= [devices count]) {
922 av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
926 audio_device = [devices objectAtIndex:ctx->audio_device_index];
927 } else if (ctx->audio_filename &&
928 strncmp(ctx->audio_filename, "none", 4)) {
929 if (!strncmp(ctx->audio_filename, "default", 7)) {
930 audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
932 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
934 for (AVCaptureDevice *device in devices) {
935 if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
936 audio_device = device;
943 av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
948 // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
949 if (!video_device && !audio_device) {
950 av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
955 if (ctx->video_device_index < ctx->num_video_devices) {
956 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
958 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
962 av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
965 // Initialize capture session
966 ctx->capture_session = [[AVCaptureSession alloc] init];
968 if (video_device && add_video_device(s, video_device)) {
971 if (audio_device && add_audio_device(s, audio_device)) {
974 [ctx->capture_session startRunning];
976 /* Unlock device configuration only after the session is started so it
977 * does not reset the capture formats */
978 if (!capture_screen) {
979 [video_device unlockForConfiguration];
982 if (video_device && get_video_config(s)) {
987 if (audio_device && get_audio_config(s)) {
996 destroy_context(ctx);
1000 static int copy_cvpixelbuffer(AVFormatContext *s,
1001 CVPixelBufferRef image_buffer,
1004 AVFContext *ctx = s->priv_data;
1005 int src_linesize[4];
1006 const uint8_t *src_data[4];
1007 int width = CVPixelBufferGetWidth(image_buffer);
1008 int height = CVPixelBufferGetHeight(image_buffer);
1011 memset(src_linesize, 0, sizeof(src_linesize));
1012 memset(src_data, 0, sizeof(src_data));
1014 status = CVPixelBufferLockBaseAddress(image_buffer, 0);
1015 if (status != kCVReturnSuccess) {
1016 av_log(s, AV_LOG_ERROR, "Could not lock base address: %d (%dx%d)\n", status, width, height);
1017 return AVERROR_EXTERNAL;
1020 if (CVPixelBufferIsPlanar(image_buffer)) {
1021 size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
1023 for(i = 0; i < plane_count; i++){
1024 src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
1025 src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
1028 src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
1029 src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
1032 status = av_image_copy_to_buffer(pkt->data, pkt->size,
1033 src_data, src_linesize,
1034 ctx->pixel_format, width, height, 1);
1038 CVPixelBufferUnlockBaseAddress(image_buffer, 0);
1043 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
1045 AVFContext* ctx = (AVFContext*)s->priv_data;
1048 CVImageBufferRef image_buffer;
1049 CMBlockBufferRef block_buffer;
1052 if (ctx->current_frame != nil) {
1056 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
1057 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
1059 if (image_buffer != nil) {
1060 length = (int)CVPixelBufferGetDataSize(image_buffer);
1061 } else if (block_buffer != nil) {
1062 length = (int)CMBlockBufferGetDataLength(block_buffer);
1064 return AVERROR(EINVAL);
1067 if (av_new_packet(pkt, length) < 0) {
1068 return AVERROR(EIO);
1072 CMSampleTimingInfo timing_info;
1074 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
1075 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1076 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1079 pkt->stream_index = ctx->video_stream_index;
1080 pkt->flags |= AV_PKT_FLAG_KEY;
1083 status = copy_cvpixelbuffer(s, image_buffer, pkt);
1086 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1087 if (ret != kCMBlockBufferNoErr) {
1088 status = AVERROR(EIO);
1091 CFRelease(ctx->current_frame);
1092 ctx->current_frame = nil;
1096 } else if (ctx->current_audio_frame != nil) {
1097 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
1098 int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
1100 if (!block_buffer || !block_buffer_size) {
1101 return AVERROR(EIO);
1104 if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
1105 return AVERROR_BUFFER_TOO_SMALL;
1108 if (av_new_packet(pkt, block_buffer_size) < 0) {
1109 return AVERROR(EIO);
1113 CMSampleTimingInfo timing_info;
1115 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
1116 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1117 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1120 pkt->stream_index = ctx->audio_stream_index;
1121 pkt->flags |= AV_PKT_FLAG_KEY;
1123 if (ctx->audio_non_interleaved) {
1124 int sample, c, shift, num_samples;
1126 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
1127 if (ret != kCMBlockBufferNoErr) {
1128 return AVERROR(EIO);
1131 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
1133 // transform decoded frame into output format
1134 #define INTERLEAVE_OUTPUT(bps) \
1136 int##bps##_t **src; \
1137 int##bps##_t *dest; \
1138 src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
1139 if (!src) return AVERROR(EIO); \
1140 for (c = 0; c < ctx->audio_channels; c++) { \
1141 src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1143 dest = (int##bps##_t*)pkt->data; \
1144 shift = bps - ctx->audio_bits_per_sample; \
1145 for (sample = 0; sample < num_samples; sample++) \
1146 for (c = 0; c < ctx->audio_channels; c++) \
1147 *dest++ = src[c][sample] << shift; \
1151 if (ctx->audio_bits_per_sample <= 16) {
1152 INTERLEAVE_OUTPUT(16)
1154 INTERLEAVE_OUTPUT(32)
1157 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1158 if (ret != kCMBlockBufferNoErr) {
1159 return AVERROR(EIO);
1163 CFRelease(ctx->current_audio_frame);
1164 ctx->current_audio_frame = nil;
1168 if (ctx->observed_quit) {
1171 return AVERROR(EAGAIN);
1176 } while (!pkt->data);
1181 static int avf_close(AVFormatContext *s)
1183 AVFContext* ctx = (AVFContext*)s->priv_data;
1184 destroy_context(ctx);
1188 static const AVOption options[] = {
1189 { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1190 { "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 },
1191 { "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 },
1192 { "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},
1193 { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1194 { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
1195 { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1196 { "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 },
1197 { "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 },
1198 { "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 },
1203 static const AVClass avf_class = {
1204 .class_name = "AVFoundation indev",
1205 .item_name = av_default_item_name,
1207 .version = LIBAVUTIL_VERSION_INT,
1208 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
1211 AVInputFormat ff_avfoundation_demuxer = {
1212 .name = "avfoundation",
1213 .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
1214 .priv_data_size = sizeof(AVFContext),
1215 .read_header = avf_read_header,
1216 .read_packet = avf_read_packet,
1217 .read_close = avf_close,
1218 .flags = AVFMT_NOFILE,
1219 .priv_class = &avf_class,