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;
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;
134 AVCaptureDevice *observed_device;
135 AVCaptureDeviceTransportControlsPlaybackMode observed_mode;
139 static void lock_frames(AVFContext* ctx)
141 pthread_mutex_lock(&ctx->frame_lock);
144 static void unlock_frames(AVFContext* ctx)
146 pthread_mutex_unlock(&ctx->frame_lock);
149 /** FrameReciever class - delegate for AVCaptureSession
151 @interface AVFFrameReceiver : NSObject
153 AVFContext* _context;
156 - (id)initWithContext:(AVFContext*)context;
158 - (void) captureOutput:(AVCaptureOutput *)captureOutput
159 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
160 fromConnection:(AVCaptureConnection *)connection;
164 @implementation AVFFrameReceiver
166 - (id)initWithContext:(AVFContext*)context
168 if (self = [super init]) {
171 // start observing if a device is set for it
172 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
173 if (_context->observed_device) {
174 NSString *keyPath = NSStringFromSelector(@selector(transportControlsPlaybackMode));
175 NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew;
177 [_context->observed_device addObserver: self
188 // stop observing if a device is set for it
189 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
190 if (_context->observed_device) {
191 NSString *keyPath = NSStringFromSelector(@selector(transportControlsPlaybackMode));
192 [_context->observed_device removeObserver: self forKeyPath: keyPath];
198 - (void)observeValueForKeyPath:(NSString *)keyPath
200 change:(NSDictionary *)change
201 context:(void *)context {
202 if (context == _context) {
203 AVCaptureDeviceTransportControlsPlaybackMode mode =
204 [change[NSKeyValueChangeNewKey] integerValue];
206 if (mode != _context->observed_mode) {
207 if (mode == AVCaptureDeviceTransportControlsNotPlayingMode) {
208 _context->observed_quit = 1;
210 _context->observed_mode = mode;
213 [super observeValueForKeyPath: keyPath
220 - (void) captureOutput:(AVCaptureOutput *)captureOutput
221 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
222 fromConnection:(AVCaptureConnection *)connection
224 lock_frames(_context);
226 if (_context->current_frame != nil) {
227 CFRelease(_context->current_frame);
230 _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
232 unlock_frames(_context);
234 ++_context->frames_captured;
239 /** AudioReciever class - delegate for AVCaptureSession
241 @interface AVFAudioReceiver : NSObject
243 AVFContext* _context;
246 - (id)initWithContext:(AVFContext*)context;
248 - (void) captureOutput:(AVCaptureOutput *)captureOutput
249 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
250 fromConnection:(AVCaptureConnection *)connection;
254 @implementation AVFAudioReceiver
256 - (id)initWithContext:(AVFContext*)context
258 if (self = [super init]) {
264 - (void) captureOutput:(AVCaptureOutput *)captureOutput
265 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
266 fromConnection:(AVCaptureConnection *)connection
268 lock_frames(_context);
270 if (_context->current_audio_frame != nil) {
271 CFRelease(_context->current_audio_frame);
274 _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
276 unlock_frames(_context);
278 ++_context->audio_frames_captured;
283 static void destroy_context(AVFContext* ctx)
285 [ctx->capture_session stopRunning];
287 [ctx->capture_session release];
288 [ctx->video_output release];
289 [ctx->audio_output release];
290 [ctx->avf_delegate release];
291 [ctx->avf_audio_delegate release];
293 ctx->capture_session = NULL;
294 ctx->video_output = NULL;
295 ctx->audio_output = NULL;
296 ctx->avf_delegate = NULL;
297 ctx->avf_audio_delegate = NULL;
299 av_freep(&ctx->audio_buffer);
301 pthread_mutex_destroy(&ctx->frame_lock);
303 if (ctx->current_frame) {
304 CFRelease(ctx->current_frame);
308 static void parse_device_name(AVFormatContext *s)
310 AVFContext *ctx = (AVFContext*)s->priv_data;
311 char *tmp = av_strdup(s->url);
315 ctx->video_filename = av_strtok(tmp, ":", &save);
316 ctx->audio_filename = av_strtok(NULL, ":", &save);
318 ctx->audio_filename = av_strtok(tmp, ":", &save);
323 * Configure the video device.
325 * Configure the video device using a run-time approach to access properties
326 * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
327 * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
329 * The NSUndefinedKeyException must be handled by the caller of this function.
332 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
334 AVFContext *ctx = (AVFContext*)s->priv_data;
336 double framerate = av_q2d(ctx->framerate);
337 NSObject *range = nil;
338 NSObject *format = nil;
339 NSObject *selected_range = nil;
340 NSObject *selected_format = nil;
342 // try to configure format by formats list
343 // might raise an exception if no format list is given
344 // (then fallback to default, no configuration)
346 for (format in [video_device valueForKey:@"formats"]) {
347 CMFormatDescriptionRef formatDescription;
348 CMVideoDimensions dimensions;
350 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
351 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
353 if ((ctx->width == 0 && ctx->height == 0) ||
354 (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
356 selected_format = format;
358 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
359 double max_framerate;
361 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
362 if (fabs (framerate - max_framerate) < 0.01) {
363 selected_range = range;
370 if (!selected_format) {
371 av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device.\n",
372 ctx->width, ctx->height);
373 goto unsupported_format;
376 if (!selected_range) {
377 av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device.\n",
379 if (ctx->video_is_muxed) {
380 av_log(s, AV_LOG_ERROR, "Falling back to default.\n");
382 goto unsupported_format;
386 if ([video_device lockForConfiguration:NULL] == YES) {
387 if (selected_format) {
388 [video_device setValue:selected_format forKey:@"activeFormat"];
390 if (selected_range) {
391 NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
392 [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
393 [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
396 av_log(s, AV_LOG_ERROR, "Could not lock device for configuration.\n");
397 return AVERROR(EINVAL);
399 } @catch(NSException *e) {
400 av_log(ctx, AV_LOG_WARNING, "Configuration of video device failed, falling back to default.\n");
407 av_log(s, AV_LOG_ERROR, "Supported modes:\n");
408 for (format in [video_device valueForKey:@"formats"]) {
409 CMFormatDescriptionRef formatDescription;
410 CMVideoDimensions dimensions;
412 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
413 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
415 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
416 double min_framerate;
417 double max_framerate;
419 [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
420 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
421 av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
422 dimensions.width, dimensions.height,
423 min_framerate, max_framerate);
426 return AVERROR(EINVAL);
429 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
431 AVFContext *ctx = (AVFContext*)s->priv_data;
433 NSError *error = nil;
434 AVCaptureInput* capture_input = nil;
435 struct AVFPixelFormatSpec pxl_fmt_spec;
436 NSNumber *pixel_format;
437 NSDictionary *capture_dict;
438 dispatch_queue_t queue;
440 if (ctx->video_device_index < ctx->num_video_devices) {
441 capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
443 capture_input = (AVCaptureInput*) video_device;
446 if (!capture_input) {
447 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
448 [[error localizedDescription] UTF8String]);
452 if ([ctx->capture_session canAddInput:capture_input]) {
453 [ctx->capture_session addInput:capture_input];
455 av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
460 ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
462 if (!ctx->video_output) {
463 av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
467 // Configure device framerate and video size
469 if ((ret = configure_video_device(s, video_device)) < 0) {
472 } @catch (NSException *exception) {
473 if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
474 av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
475 return AVERROR_EXTERNAL;
479 // select pixel format
480 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
482 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
483 if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
484 pxl_fmt_spec = avf_pixel_formats[i];
489 // check if selected pixel format is supported by AVFoundation
490 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
491 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
492 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
496 // check if the pixel format is available for this device
497 if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
498 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
499 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
501 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
503 av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
504 for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
505 struct AVFPixelFormatSpec pxl_fmt_dummy;
506 pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
507 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
508 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
509 pxl_fmt_dummy = avf_pixel_formats[i];
514 if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
515 av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
517 // select first supported pixel format instead of user selected (or default) pixel format
518 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
519 pxl_fmt_spec = pxl_fmt_dummy;
524 // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
525 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
528 av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
529 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
533 // set videoSettings to an empty dict for receiving raw data of muxed devices
534 if (ctx->capture_raw_data) {
535 ctx->pixel_format = pxl_fmt_spec.ff_id;
536 ctx->video_output.videoSettings = @{ };
538 ctx->pixel_format = pxl_fmt_spec.ff_id;
539 pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
540 capture_dict = [NSDictionary dictionaryWithObject:pixel_format
541 forKey:(id)kCVPixelBufferPixelFormatTypeKey];
543 [ctx->video_output setVideoSettings:capture_dict];
545 [ctx->video_output setAlwaysDiscardsLateVideoFrames:ctx->drop_late_frames];
547 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
548 // check for transport control support and set observer device if supported
549 if (!ctx->video_is_screen) {
550 int trans_ctrl = [video_device transportControlsSupported];
551 AVCaptureDeviceTransportControlsPlaybackMode trans_mode = [video_device transportControlsPlaybackMode];
554 ctx->observed_mode = trans_mode;
555 ctx->observed_device = video_device;
560 ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
562 queue = dispatch_queue_create("avf_queue", NULL);
563 [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
564 dispatch_release(queue);
566 if ([ctx->capture_session canAddOutput:ctx->video_output]) {
567 [ctx->capture_session addOutput:ctx->video_output];
569 av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
576 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
578 AVFContext *ctx = (AVFContext*)s->priv_data;
579 NSError *error = nil;
580 AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
581 dispatch_queue_t queue;
583 if (!audio_dev_input) {
584 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
585 [[error localizedDescription] UTF8String]);
589 if ([ctx->capture_session canAddInput:audio_dev_input]) {
590 [ctx->capture_session addInput:audio_dev_input];
592 av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
597 ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
599 if (!ctx->audio_output) {
600 av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
604 ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
606 queue = dispatch_queue_create("avf_audio_queue", NULL);
607 [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
608 dispatch_release(queue);
610 if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
611 [ctx->capture_session addOutput:ctx->audio_output];
613 av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
620 static int get_video_config(AVFormatContext *s)
622 AVFContext *ctx = (AVFContext*)s->priv_data;
623 CVImageBufferRef image_buffer;
624 CMBlockBufferRef block_buffer;
625 CGSize image_buffer_size;
626 AVStream* stream = avformat_new_stream(s, NULL);
632 // Take stream info from the first frame.
633 while (ctx->frames_captured < 1) {
634 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
639 ctx->video_stream_index = stream->index;
641 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
643 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
644 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
647 image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
649 stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
650 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
651 stream->codecpar->width = (int)image_buffer_size.width;
652 stream->codecpar->height = (int)image_buffer_size.height;
653 stream->codecpar->format = ctx->pixel_format;
655 stream->codecpar->codec_id = AV_CODEC_ID_DVVIDEO;
656 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
657 stream->codecpar->format = ctx->pixel_format;
660 CFRelease(ctx->current_frame);
661 ctx->current_frame = nil;
668 static int get_audio_config(AVFormatContext *s)
670 AVFContext *ctx = (AVFContext*)s->priv_data;
671 CMFormatDescriptionRef format_desc;
672 AVStream* stream = avformat_new_stream(s, NULL);
678 // Take stream info from the first frame.
679 while (ctx->audio_frames_captured < 1) {
680 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
685 ctx->audio_stream_index = stream->index;
687 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
689 format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
690 const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
693 av_log(s, AV_LOG_ERROR, "audio format not available\n");
697 stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
698 stream->codecpar->sample_rate = basic_desc->mSampleRate;
699 stream->codecpar->channels = basic_desc->mChannelsPerFrame;
700 stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
702 ctx->audio_channels = basic_desc->mChannelsPerFrame;
703 ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
704 ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
705 ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
706 ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
707 ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
708 ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
710 if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
712 ctx->audio_bits_per_sample == 32 &&
714 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
715 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
716 ctx->audio_signed_integer &&
717 ctx->audio_bits_per_sample == 16 &&
719 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
720 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
721 ctx->audio_signed_integer &&
722 ctx->audio_bits_per_sample == 24 &&
724 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
725 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
726 ctx->audio_signed_integer &&
727 ctx->audio_bits_per_sample == 32 &&
729 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
731 av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
735 if (ctx->audio_non_interleaved) {
736 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
737 ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
738 ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
739 if (!ctx->audio_buffer) {
740 av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
745 CFRelease(ctx->current_audio_frame);
746 ctx->current_audio_frame = nil;
753 static int avf_read_header(AVFormatContext *s)
755 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
756 uint32_t num_screens = 0;
757 AVFContext *ctx = (AVFContext*)s->priv_data;
758 AVCaptureDevice *video_device = nil;
759 AVCaptureDevice *audio_device = nil;
760 // Find capture device
761 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
762 NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
764 ctx->num_video_devices = [devices count] + [devices_muxed count];
765 ctx->first_pts = av_gettime();
766 ctx->first_audio_pts = av_gettime();
768 pthread_mutex_init(&ctx->frame_lock, NULL);
770 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
771 CGGetActiveDisplayList(0, NULL, &num_screens);
774 // List devices if requested
775 if (ctx->list_devices) {
777 av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
778 for (AVCaptureDevice *device in devices) {
779 const char *name = [[device localizedName] UTF8String];
780 index = [devices indexOfObject:device];
781 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
783 for (AVCaptureDevice *device in devices_muxed) {
784 const char *name = [[device localizedName] UTF8String];
785 index = [devices count] + [devices_muxed indexOfObject:device];
786 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
788 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
789 if (num_screens > 0) {
790 CGDirectDisplayID screens[num_screens];
791 CGGetActiveDisplayList(num_screens, screens, &num_screens);
792 for (int i = 0; i < num_screens; i++) {
793 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", ctx->num_video_devices + i, i);
798 av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
799 devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
800 for (AVCaptureDevice *device in devices) {
801 const char *name = [[device localizedName] UTF8String];
802 int index = [devices indexOfObject:device];
803 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
808 // parse input filename for video and audio device
809 parse_device_name(s);
811 // check for device index given in filename
812 if (ctx->video_device_index == -1 && ctx->video_filename) {
813 sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
815 if (ctx->audio_device_index == -1 && ctx->audio_filename) {
816 sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
819 if (ctx->video_device_index >= 0) {
820 if (ctx->video_device_index < ctx->num_video_devices) {
821 if (ctx->video_device_index < [devices count]) {
822 video_device = [devices objectAtIndex:ctx->video_device_index];
824 video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
825 ctx->video_is_muxed = 1;
827 } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
828 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
829 CGDirectDisplayID screens[num_screens];
830 CGGetActiveDisplayList(num_screens, screens, &num_screens);
831 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
833 if (ctx->framerate.num > 0) {
834 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
837 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
838 if (ctx->capture_cursor) {
839 capture_screen_input.capturesCursor = YES;
841 capture_screen_input.capturesCursor = NO;
845 if (ctx->capture_mouse_clicks) {
846 capture_screen_input.capturesMouseClicks = YES;
848 capture_screen_input.capturesMouseClicks = NO;
851 video_device = (AVCaptureDevice*) capture_screen_input;
852 ctx->video_is_screen = 1;
855 av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
858 } else if (ctx->video_filename &&
859 strncmp(ctx->video_filename, "none", 4)) {
860 if (!strncmp(ctx->video_filename, "default", 7)) {
861 video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
863 // looking for video inputs
864 for (AVCaptureDevice *device in devices) {
865 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
866 video_device = device;
870 // looking for muxed inputs
871 for (AVCaptureDevice *device in devices_muxed) {
872 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
873 video_device = device;
874 ctx->video_is_muxed = 1;
879 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
880 // looking for screen inputs
883 if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
884 CGDirectDisplayID screens[num_screens];
885 CGGetActiveDisplayList(num_screens, screens, &num_screens);
886 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
887 video_device = (AVCaptureDevice*) capture_screen_input;
888 ctx->video_device_index = ctx->num_video_devices + idx;
889 ctx->video_is_screen = 1;
891 if (ctx->framerate.num > 0) {
892 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
895 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
896 if (ctx->capture_cursor) {
897 capture_screen_input.capturesCursor = YES;
899 capture_screen_input.capturesCursor = NO;
903 if (ctx->capture_mouse_clicks) {
904 capture_screen_input.capturesMouseClicks = YES;
906 capture_screen_input.capturesMouseClicks = NO;
914 av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
920 if (ctx->audio_device_index >= 0) {
921 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
923 if (ctx->audio_device_index >= [devices count]) {
924 av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
928 audio_device = [devices objectAtIndex:ctx->audio_device_index];
929 } else if (ctx->audio_filename &&
930 strncmp(ctx->audio_filename, "none", 4)) {
931 if (!strncmp(ctx->audio_filename, "default", 7)) {
932 audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
934 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
936 for (AVCaptureDevice *device in devices) {
937 if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
938 audio_device = device;
945 av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
950 // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
951 if (!video_device && !audio_device) {
952 av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
957 if (ctx->video_device_index < ctx->num_video_devices) {
958 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
960 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
964 av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
967 // Initialize capture session
968 ctx->capture_session = [[AVCaptureSession alloc] init];
970 if (video_device && add_video_device(s, video_device)) {
973 if (audio_device && add_audio_device(s, audio_device)) {
976 [ctx->capture_session startRunning];
978 /* Unlock device configuration only after the session is started so it
979 * does not reset the capture formats */
980 if (!ctx->video_is_screen) {
981 [video_device unlockForConfiguration];
984 if (video_device && get_video_config(s)) {
989 if (audio_device && get_audio_config(s)) {
998 destroy_context(ctx);
1002 static int copy_cvpixelbuffer(AVFormatContext *s,
1003 CVPixelBufferRef image_buffer,
1006 AVFContext *ctx = s->priv_data;
1007 int src_linesize[4];
1008 const uint8_t *src_data[4];
1009 int width = CVPixelBufferGetWidth(image_buffer);
1010 int height = CVPixelBufferGetHeight(image_buffer);
1013 memset(src_linesize, 0, sizeof(src_linesize));
1014 memset(src_data, 0, sizeof(src_data));
1016 status = CVPixelBufferLockBaseAddress(image_buffer, 0);
1017 if (status != kCVReturnSuccess) {
1018 av_log(s, AV_LOG_ERROR, "Could not lock base address: %d (%dx%d)\n", status, width, height);
1019 return AVERROR_EXTERNAL;
1022 if (CVPixelBufferIsPlanar(image_buffer)) {
1023 size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
1025 for(i = 0; i < plane_count; i++){
1026 src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
1027 src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
1030 src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
1031 src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
1034 status = av_image_copy_to_buffer(pkt->data, pkt->size,
1035 src_data, src_linesize,
1036 ctx->pixel_format, width, height, 1);
1040 CVPixelBufferUnlockBaseAddress(image_buffer, 0);
1045 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
1047 AVFContext* ctx = (AVFContext*)s->priv_data;
1050 CVImageBufferRef image_buffer;
1051 CMBlockBufferRef block_buffer;
1054 if (ctx->current_frame != nil) {
1058 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
1059 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
1061 if (image_buffer != nil) {
1062 length = (int)CVPixelBufferGetDataSize(image_buffer);
1063 } else if (block_buffer != nil) {
1064 length = (int)CMBlockBufferGetDataLength(block_buffer);
1066 return AVERROR(EINVAL);
1069 if (av_new_packet(pkt, length) < 0) {
1070 return AVERROR(EIO);
1074 CMSampleTimingInfo timing_info;
1076 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
1077 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1078 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1081 pkt->stream_index = ctx->video_stream_index;
1082 pkt->flags |= AV_PKT_FLAG_KEY;
1085 status = copy_cvpixelbuffer(s, image_buffer, pkt);
1088 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1089 if (ret != kCMBlockBufferNoErr) {
1090 status = AVERROR(EIO);
1093 CFRelease(ctx->current_frame);
1094 ctx->current_frame = nil;
1098 } else if (ctx->current_audio_frame != nil) {
1099 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
1100 int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
1102 if (!block_buffer || !block_buffer_size) {
1103 return AVERROR(EIO);
1106 if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
1107 return AVERROR_BUFFER_TOO_SMALL;
1110 if (av_new_packet(pkt, block_buffer_size) < 0) {
1111 return AVERROR(EIO);
1115 CMSampleTimingInfo timing_info;
1117 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
1118 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1119 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1122 pkt->stream_index = ctx->audio_stream_index;
1123 pkt->flags |= AV_PKT_FLAG_KEY;
1125 if (ctx->audio_non_interleaved) {
1126 int sample, c, shift, num_samples;
1128 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
1129 if (ret != kCMBlockBufferNoErr) {
1130 return AVERROR(EIO);
1133 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
1135 // transform decoded frame into output format
1136 #define INTERLEAVE_OUTPUT(bps) \
1138 int##bps##_t **src; \
1139 int##bps##_t *dest; \
1140 src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
1141 if (!src) return AVERROR(EIO); \
1142 for (c = 0; c < ctx->audio_channels; c++) { \
1143 src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1145 dest = (int##bps##_t*)pkt->data; \
1146 shift = bps - ctx->audio_bits_per_sample; \
1147 for (sample = 0; sample < num_samples; sample++) \
1148 for (c = 0; c < ctx->audio_channels; c++) \
1149 *dest++ = src[c][sample] << shift; \
1153 if (ctx->audio_bits_per_sample <= 16) {
1154 INTERLEAVE_OUTPUT(16)
1156 INTERLEAVE_OUTPUT(32)
1159 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1160 if (ret != kCMBlockBufferNoErr) {
1161 return AVERROR(EIO);
1165 CFRelease(ctx->current_audio_frame);
1166 ctx->current_audio_frame = nil;
1170 if (ctx->observed_quit) {
1173 return AVERROR(EAGAIN);
1178 } while (!pkt->data);
1183 static int avf_close(AVFormatContext *s)
1185 AVFContext* ctx = (AVFContext*)s->priv_data;
1186 destroy_context(ctx);
1190 static const AVOption options[] = {
1191 { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1192 { "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 },
1193 { "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 },
1194 { "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},
1195 { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1196 { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
1197 { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1198 { "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 },
1199 { "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 },
1200 { "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 },
1205 static const AVClass avf_class = {
1206 .class_name = "AVFoundation indev",
1207 .item_name = av_default_item_name,
1209 .version = LIBAVUTIL_VERSION_INT,
1210 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
1213 AVInputFormat ff_avfoundation_demuxer = {
1214 .name = "avfoundation",
1215 .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
1216 .priv_data_size = sizeof(AVFContext),
1217 .read_header = avf_read_header,
1218 .read_packet = avf_read_packet,
1219 .read_close = avf_close,
1220 .flags = AVFMT_NOFILE,
1221 .priv_class = &avf_class,