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;
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;
134 static void lock_frames(AVFContext* ctx)
136 pthread_mutex_lock(&ctx->frame_lock);
139 static void unlock_frames(AVFContext* ctx)
141 pthread_mutex_unlock(&ctx->frame_lock);
144 /** FrameReciever class - delegate for AVCaptureSession
146 @interface AVFFrameReceiver : NSObject
148 AVFContext* _context;
151 - (id)initWithContext:(AVFContext*)context;
153 - (void) captureOutput:(AVCaptureOutput *)captureOutput
154 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
155 fromConnection:(AVCaptureConnection *)connection;
159 @implementation AVFFrameReceiver
161 - (id)initWithContext:(AVFContext*)context
163 if (self = [super init]) {
169 - (void) captureOutput:(AVCaptureOutput *)captureOutput
170 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
171 fromConnection:(AVCaptureConnection *)connection
173 lock_frames(_context);
175 if (_context->current_frame != nil) {
176 CFRelease(_context->current_frame);
179 _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
181 pthread_cond_signal(&_context->frame_wait_cond);
183 unlock_frames(_context);
185 ++_context->frames_captured;
190 /** AudioReciever class - delegate for AVCaptureSession
192 @interface AVFAudioReceiver : NSObject
194 AVFContext* _context;
197 - (id)initWithContext:(AVFContext*)context;
199 - (void) captureOutput:(AVCaptureOutput *)captureOutput
200 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
201 fromConnection:(AVCaptureConnection *)connection;
205 @implementation AVFAudioReceiver
207 - (id)initWithContext:(AVFContext*)context
209 if (self = [super init]) {
215 - (void) captureOutput:(AVCaptureOutput *)captureOutput
216 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
217 fromConnection:(AVCaptureConnection *)connection
219 lock_frames(_context);
221 if (_context->current_audio_frame != nil) {
222 CFRelease(_context->current_audio_frame);
225 _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
227 pthread_cond_signal(&_context->frame_wait_cond);
229 unlock_frames(_context);
231 ++_context->audio_frames_captured;
236 static void destroy_context(AVFContext* ctx)
238 [ctx->capture_session stopRunning];
240 [ctx->capture_session release];
241 [ctx->video_output release];
242 [ctx->audio_output release];
243 [ctx->avf_delegate release];
244 [ctx->avf_audio_delegate release];
246 ctx->capture_session = NULL;
247 ctx->video_output = NULL;
248 ctx->audio_output = NULL;
249 ctx->avf_delegate = NULL;
250 ctx->avf_audio_delegate = NULL;
252 av_freep(&ctx->audio_buffer);
254 pthread_mutex_destroy(&ctx->frame_lock);
255 pthread_cond_destroy(&ctx->frame_wait_cond);
257 if (ctx->current_frame) {
258 CFRelease(ctx->current_frame);
262 static void parse_device_name(AVFormatContext *s)
264 AVFContext *ctx = (AVFContext*)s->priv_data;
265 char *tmp = av_strdup(s->url);
269 ctx->video_filename = av_strtok(tmp, ":", &save);
270 ctx->audio_filename = av_strtok(NULL, ":", &save);
272 ctx->audio_filename = av_strtok(tmp, ":", &save);
277 * Configure the video device.
279 * Configure the video device using a run-time approach to access properties
280 * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
281 * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
283 * The NSUndefinedKeyException must be handled by the caller of this function.
286 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
288 AVFContext *ctx = (AVFContext*)s->priv_data;
290 double framerate = av_q2d(ctx->framerate);
291 NSObject *range = nil;
292 NSObject *format = nil;
293 NSObject *selected_range = nil;
294 NSObject *selected_format = nil;
296 // try to configure format by formats list
297 // might raise an exception if no format list is given
298 // (then fallback to default, no configuration)
300 for (format in [video_device valueForKey:@"formats"]) {
301 CMFormatDescriptionRef formatDescription;
302 CMVideoDimensions dimensions;
304 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
305 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
307 if ((ctx->width == 0 && ctx->height == 0) ||
308 (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
310 selected_format = format;
312 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
313 double max_framerate;
315 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
316 if (fabs (framerate - max_framerate) < 0.01) {
317 selected_range = range;
324 if (!selected_format) {
325 av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device.\n",
326 ctx->width, ctx->height);
327 goto unsupported_format;
330 if (!selected_range) {
331 av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device.\n",
333 if (ctx->video_is_muxed) {
334 av_log(s, AV_LOG_ERROR, "Falling back to default.\n");
336 goto unsupported_format;
340 if ([video_device lockForConfiguration:NULL] == YES) {
341 if (selected_format) {
342 [video_device setValue:selected_format forKey:@"activeFormat"];
344 if (selected_range) {
345 NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
346 [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
347 [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
350 av_log(s, AV_LOG_ERROR, "Could not lock device for configuration.\n");
351 return AVERROR(EINVAL);
353 } @catch(NSException *e) {
354 av_log(ctx, AV_LOG_WARNING, "Configuration of video device failed, falling back to default.\n");
361 av_log(s, AV_LOG_ERROR, "Supported modes:\n");
362 for (format in [video_device valueForKey:@"formats"]) {
363 CMFormatDescriptionRef formatDescription;
364 CMVideoDimensions dimensions;
366 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
367 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
369 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
370 double min_framerate;
371 double max_framerate;
373 [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
374 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
375 av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
376 dimensions.width, dimensions.height,
377 min_framerate, max_framerate);
380 return AVERROR(EINVAL);
383 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
385 AVFContext *ctx = (AVFContext*)s->priv_data;
387 NSError *error = nil;
388 AVCaptureInput* capture_input = nil;
389 struct AVFPixelFormatSpec pxl_fmt_spec;
390 NSNumber *pixel_format;
391 NSDictionary *capture_dict;
392 dispatch_queue_t queue;
394 if (ctx->video_device_index < ctx->num_video_devices) {
395 capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
397 capture_input = (AVCaptureInput*) video_device;
400 if (!capture_input) {
401 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
402 [[error localizedDescription] UTF8String]);
406 if ([ctx->capture_session canAddInput:capture_input]) {
407 [ctx->capture_session addInput:capture_input];
409 av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
414 ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
416 if (!ctx->video_output) {
417 av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
421 // Configure device framerate and video size
423 if ((ret = configure_video_device(s, video_device)) < 0) {
426 } @catch (NSException *exception) {
427 if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
428 av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
429 return AVERROR_EXTERNAL;
433 // select pixel format
434 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
436 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
437 if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
438 pxl_fmt_spec = avf_pixel_formats[i];
443 // check if selected pixel format is supported by AVFoundation
444 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
445 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
446 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
450 // check if the pixel format is available for this device
451 if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
452 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
453 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
455 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
457 av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
458 for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
459 struct AVFPixelFormatSpec pxl_fmt_dummy;
460 pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
461 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
462 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
463 pxl_fmt_dummy = avf_pixel_formats[i];
468 if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
469 av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
471 // select first supported pixel format instead of user selected (or default) pixel format
472 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
473 pxl_fmt_spec = pxl_fmt_dummy;
478 // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
479 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
482 av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
483 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
487 // set videoSettings to an empty dict for receiving raw data of muxed devices
488 if (ctx->capture_raw_data) {
489 ctx->pixel_format = pxl_fmt_spec.ff_id;
490 ctx->video_output.videoSettings = @{ };
492 ctx->pixel_format = pxl_fmt_spec.ff_id;
493 pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
494 capture_dict = [NSDictionary dictionaryWithObject:pixel_format
495 forKey:(id)kCVPixelBufferPixelFormatTypeKey];
497 [ctx->video_output setVideoSettings:capture_dict];
499 [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
501 ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
503 queue = dispatch_queue_create("avf_queue", NULL);
504 [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
505 dispatch_release(queue);
507 if ([ctx->capture_session canAddOutput:ctx->video_output]) {
508 [ctx->capture_session addOutput:ctx->video_output];
510 av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
517 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
519 AVFContext *ctx = (AVFContext*)s->priv_data;
520 NSError *error = nil;
521 AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
522 dispatch_queue_t queue;
524 if (!audio_dev_input) {
525 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
526 [[error localizedDescription] UTF8String]);
530 if ([ctx->capture_session canAddInput:audio_dev_input]) {
531 [ctx->capture_session addInput:audio_dev_input];
533 av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
538 ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
540 if (!ctx->audio_output) {
541 av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
545 ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
547 queue = dispatch_queue_create("avf_audio_queue", NULL);
548 [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
549 dispatch_release(queue);
551 if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
552 [ctx->capture_session addOutput:ctx->audio_output];
554 av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
561 static int get_video_config(AVFormatContext *s)
563 AVFContext *ctx = (AVFContext*)s->priv_data;
564 CVImageBufferRef image_buffer;
565 CMBlockBufferRef block_buffer;
566 CGSize image_buffer_size;
567 AVStream* stream = avformat_new_stream(s, NULL);
573 // Take stream info from the first frame.
574 while (ctx->frames_captured < 1) {
575 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
580 ctx->video_stream_index = stream->index;
582 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
584 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
585 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
588 image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
590 stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
591 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
592 stream->codecpar->width = (int)image_buffer_size.width;
593 stream->codecpar->height = (int)image_buffer_size.height;
594 stream->codecpar->format = ctx->pixel_format;
596 stream->codecpar->codec_id = AV_CODEC_ID_DVVIDEO;
597 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
598 stream->codecpar->format = ctx->pixel_format;
601 CFRelease(ctx->current_frame);
602 ctx->current_frame = nil;
609 static int get_audio_config(AVFormatContext *s)
611 AVFContext *ctx = (AVFContext*)s->priv_data;
612 CMFormatDescriptionRef format_desc;
613 AVStream* stream = avformat_new_stream(s, NULL);
619 // Take stream info from the first frame.
620 while (ctx->audio_frames_captured < 1) {
621 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
626 ctx->audio_stream_index = stream->index;
628 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
630 format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
631 const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
634 av_log(s, AV_LOG_ERROR, "audio format not available\n");
638 stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
639 stream->codecpar->sample_rate = basic_desc->mSampleRate;
640 stream->codecpar->channels = basic_desc->mChannelsPerFrame;
641 stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
643 ctx->audio_channels = basic_desc->mChannelsPerFrame;
644 ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
645 ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
646 ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
647 ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
648 ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
649 ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
651 if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
653 ctx->audio_bits_per_sample == 32 &&
655 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
656 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
657 ctx->audio_signed_integer &&
658 ctx->audio_bits_per_sample == 16 &&
660 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
661 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
662 ctx->audio_signed_integer &&
663 ctx->audio_bits_per_sample == 24 &&
665 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
666 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
667 ctx->audio_signed_integer &&
668 ctx->audio_bits_per_sample == 32 &&
670 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
672 av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
676 if (ctx->audio_non_interleaved) {
677 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
678 ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
679 ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
680 if (!ctx->audio_buffer) {
681 av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
686 CFRelease(ctx->current_audio_frame);
687 ctx->current_audio_frame = nil;
694 static int avf_read_header(AVFormatContext *s)
696 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
697 int capture_screen = 0;
698 uint32_t num_screens = 0;
699 AVFContext *ctx = (AVFContext*)s->priv_data;
700 AVCaptureDevice *video_device = nil;
701 AVCaptureDevice *audio_device = nil;
702 // Find capture device
703 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
704 NSArray *devices_muxed = [AVCaptureDevice devicesWithMediaType:AVMediaTypeMuxed];
706 ctx->num_video_devices = [devices count] + [devices_muxed count];
707 ctx->first_pts = av_gettime();
708 ctx->first_audio_pts = av_gettime();
710 pthread_mutex_init(&ctx->frame_lock, NULL);
711 pthread_cond_init(&ctx->frame_wait_cond, NULL);
713 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
714 CGGetActiveDisplayList(0, NULL, &num_screens);
717 // List devices if requested
718 if (ctx->list_devices) {
720 av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
721 for (AVCaptureDevice *device in devices) {
722 const char *name = [[device localizedName] UTF8String];
723 index = [devices indexOfObject:device];
724 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
726 for (AVCaptureDevice *device in devices_muxed) {
727 const char *name = [[device localizedName] UTF8String];
728 index = [devices count] + [devices_muxed indexOfObject:device];
729 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
731 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
732 if (num_screens > 0) {
733 CGDirectDisplayID screens[num_screens];
734 CGGetActiveDisplayList(num_screens, screens, &num_screens);
735 for (int i = 0; i < num_screens; i++) {
736 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", ctx->num_video_devices + i, i);
741 av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
742 devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
743 for (AVCaptureDevice *device in devices) {
744 const char *name = [[device localizedName] UTF8String];
745 int index = [devices indexOfObject:device];
746 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
751 // parse input filename for video and audio device
752 parse_device_name(s);
754 // check for device index given in filename
755 if (ctx->video_device_index == -1 && ctx->video_filename) {
756 sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
758 if (ctx->audio_device_index == -1 && ctx->audio_filename) {
759 sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
762 if (ctx->video_device_index >= 0) {
763 if (ctx->video_device_index < ctx->num_video_devices) {
764 if (ctx->video_device_index < [devices count]) {
765 video_device = [devices objectAtIndex:ctx->video_device_index];
767 video_device = [devices_muxed objectAtIndex:(ctx->video_device_index - [devices count])];
768 ctx->video_is_muxed = 1;
770 } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
771 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
772 CGDirectDisplayID screens[num_screens];
773 CGGetActiveDisplayList(num_screens, screens, &num_screens);
774 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
776 if (ctx->framerate.num > 0) {
777 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
780 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
781 if (ctx->capture_cursor) {
782 capture_screen_input.capturesCursor = YES;
784 capture_screen_input.capturesCursor = NO;
788 if (ctx->capture_mouse_clicks) {
789 capture_screen_input.capturesMouseClicks = YES;
791 capture_screen_input.capturesMouseClicks = NO;
794 video_device = (AVCaptureDevice*) capture_screen_input;
798 av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
801 } else if (ctx->video_filename &&
802 strncmp(ctx->video_filename, "none", 4)) {
803 if (!strncmp(ctx->video_filename, "default", 7)) {
804 video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
806 // looking for video inputs
807 for (AVCaptureDevice *device in devices) {
808 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
809 video_device = device;
813 // looking for muxed inputs
814 for (AVCaptureDevice *device in devices_muxed) {
815 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
816 video_device = device;
817 ctx->video_is_muxed = 1;
822 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
823 // looking for screen inputs
826 if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
827 CGDirectDisplayID screens[num_screens];
828 CGGetActiveDisplayList(num_screens, screens, &num_screens);
829 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
830 video_device = (AVCaptureDevice*) capture_screen_input;
831 ctx->video_device_index = ctx->num_video_devices + idx;
834 if (ctx->framerate.num > 0) {
835 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
838 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
839 if (ctx->capture_cursor) {
840 capture_screen_input.capturesCursor = YES;
842 capture_screen_input.capturesCursor = NO;
846 if (ctx->capture_mouse_clicks) {
847 capture_screen_input.capturesMouseClicks = YES;
849 capture_screen_input.capturesMouseClicks = NO;
857 av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
863 if (ctx->audio_device_index >= 0) {
864 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
866 if (ctx->audio_device_index >= [devices count]) {
867 av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
871 audio_device = [devices objectAtIndex:ctx->audio_device_index];
872 } else if (ctx->audio_filename &&
873 strncmp(ctx->audio_filename, "none", 4)) {
874 if (!strncmp(ctx->audio_filename, "default", 7)) {
875 audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
877 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
879 for (AVCaptureDevice *device in devices) {
880 if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
881 audio_device = device;
888 av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
893 // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
894 if (!video_device && !audio_device) {
895 av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
900 if (ctx->video_device_index < ctx->num_video_devices) {
901 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
903 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
907 av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
910 // Initialize capture session
911 ctx->capture_session = [[AVCaptureSession alloc] init];
913 if (video_device && add_video_device(s, video_device)) {
916 if (audio_device && add_audio_device(s, audio_device)) {
919 [ctx->capture_session startRunning];
921 /* Unlock device configuration only after the session is started so it
922 * does not reset the capture formats */
923 if (!capture_screen) {
924 [video_device unlockForConfiguration];
927 if (video_device && get_video_config(s)) {
932 if (audio_device && get_audio_config(s)) {
941 destroy_context(ctx);
945 static int copy_cvpixelbuffer(AVFormatContext *s,
946 CVPixelBufferRef image_buffer,
949 AVFContext *ctx = s->priv_data;
951 const uint8_t *src_data[4];
952 int width = CVPixelBufferGetWidth(image_buffer);
953 int height = CVPixelBufferGetHeight(image_buffer);
956 memset(src_linesize, 0, sizeof(src_linesize));
957 memset(src_data, 0, sizeof(src_data));
959 status = CVPixelBufferLockBaseAddress(image_buffer, 0);
960 if (status != kCVReturnSuccess) {
961 av_log(s, AV_LOG_ERROR, "Could not lock base address: %d (%dx%d)\n", status, width, height);
962 return AVERROR_EXTERNAL;
965 if (CVPixelBufferIsPlanar(image_buffer)) {
966 size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
968 for(i = 0; i < plane_count; i++){
969 src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
970 src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
973 src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
974 src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
977 status = av_image_copy_to_buffer(pkt->data, pkt->size,
978 src_data, src_linesize,
979 ctx->pixel_format, width, height, 1);
983 CVPixelBufferUnlockBaseAddress(image_buffer, 0);
988 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
990 AVFContext* ctx = (AVFContext*)s->priv_data;
993 CVImageBufferRef image_buffer;
994 CMBlockBufferRef block_buffer;
997 if (ctx->current_frame != nil) {
1001 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
1002 block_buffer = CMSampleBufferGetDataBuffer(ctx->current_frame);
1004 if (image_buffer != nil) {
1005 length = (int)CVPixelBufferGetDataSize(image_buffer);
1006 } else if (block_buffer != nil) {
1007 length = (int)CMBlockBufferGetDataLength(block_buffer);
1009 return AVERROR(EINVAL);
1012 if (av_new_packet(pkt, length) < 0) {
1013 return AVERROR(EIO);
1017 CMSampleTimingInfo timing_info;
1019 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
1020 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1021 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1024 pkt->stream_index = ctx->video_stream_index;
1025 pkt->flags |= AV_PKT_FLAG_KEY;
1028 status = copy_cvpixelbuffer(s, image_buffer, pkt);
1031 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1032 if (ret != kCMBlockBufferNoErr) {
1033 status = AVERROR(EIO);
1036 CFRelease(ctx->current_frame);
1037 ctx->current_frame = nil;
1041 } else if (ctx->current_audio_frame != nil) {
1042 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
1043 int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
1045 if (!block_buffer || !block_buffer_size) {
1046 return AVERROR(EIO);
1049 if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
1050 return AVERROR_BUFFER_TOO_SMALL;
1053 if (av_new_packet(pkt, block_buffer_size) < 0) {
1054 return AVERROR(EIO);
1058 CMSampleTimingInfo timing_info;
1060 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
1061 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
1062 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
1065 pkt->stream_index = ctx->audio_stream_index;
1066 pkt->flags |= AV_PKT_FLAG_KEY;
1068 if (ctx->audio_non_interleaved) {
1069 int sample, c, shift, num_samples;
1071 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
1072 if (ret != kCMBlockBufferNoErr) {
1073 return AVERROR(EIO);
1076 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
1078 // transform decoded frame into output format
1079 #define INTERLEAVE_OUTPUT(bps) \
1081 int##bps##_t **src; \
1082 int##bps##_t *dest; \
1083 src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
1084 if (!src) return AVERROR(EIO); \
1085 for (c = 0; c < ctx->audio_channels; c++) { \
1086 src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1088 dest = (int##bps##_t*)pkt->data; \
1089 shift = bps - ctx->audio_bits_per_sample; \
1090 for (sample = 0; sample < num_samples; sample++) \
1091 for (c = 0; c < ctx->audio_channels; c++) \
1092 *dest++ = src[c][sample] << shift; \
1096 if (ctx->audio_bits_per_sample <= 16) {
1097 INTERLEAVE_OUTPUT(16)
1099 INTERLEAVE_OUTPUT(32)
1102 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1103 if (ret != kCMBlockBufferNoErr) {
1104 return AVERROR(EIO);
1108 CFRelease(ctx->current_audio_frame);
1109 ctx->current_audio_frame = nil;
1112 pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
1116 } while (!pkt->data);
1121 static int avf_close(AVFormatContext *s)
1123 AVFContext* ctx = (AVFContext*)s->priv_data;
1124 destroy_context(ctx);
1128 static const AVOption options[] = {
1129 { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1130 { "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 },
1131 { "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 },
1132 { "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},
1133 { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1134 { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
1135 { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1136 { "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 },
1137 { "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 },
1142 static const AVClass avf_class = {
1143 .class_name = "AVFoundation indev",
1144 .item_name = av_default_item_name,
1146 .version = LIBAVUTIL_VERSION_INT,
1147 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
1150 AVInputFormat ff_avfoundation_demuxer = {
1151 .name = "avfoundation",
1152 .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
1153 .priv_data_size = sizeof(AVFContext),
1154 .read_header = avf_read_header,
1155 .read_packet = avf_read_packet,
1156 .read_close = avf_close,
1157 .flags = AVFMT_NOFILE,
1158 .priv_class = &avf_class,