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;
102 int video_device_index;
103 int video_stream_index;
104 int audio_device_index;
105 int audio_stream_index;
107 char *video_filename;
108 char *audio_filename;
110 int num_video_devices;
113 int audio_bits_per_sample;
116 int audio_signed_integer;
118 int audio_non_interleaved;
120 int32_t *audio_buffer;
121 int audio_buffer_size;
123 enum AVPixelFormat pixel_format;
125 AVCaptureSession *capture_session;
126 AVCaptureVideoDataOutput *video_output;
127 AVCaptureAudioDataOutput *audio_output;
128 CMSampleBufferRef current_frame;
129 CMSampleBufferRef current_audio_frame;
132 static void lock_frames(AVFContext* ctx)
134 pthread_mutex_lock(&ctx->frame_lock);
137 static void unlock_frames(AVFContext* ctx)
139 pthread_mutex_unlock(&ctx->frame_lock);
142 /** FrameReciever class - delegate for AVCaptureSession
144 @interface AVFFrameReceiver : NSObject
146 AVFContext* _context;
149 - (id)initWithContext:(AVFContext*)context;
151 - (void) captureOutput:(AVCaptureOutput *)captureOutput
152 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
153 fromConnection:(AVCaptureConnection *)connection;
157 @implementation AVFFrameReceiver
159 - (id)initWithContext:(AVFContext*)context
161 if (self = [super init]) {
167 - (void) captureOutput:(AVCaptureOutput *)captureOutput
168 didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
169 fromConnection:(AVCaptureConnection *)connection
171 lock_frames(_context);
173 if (_context->current_frame != nil) {
174 CFRelease(_context->current_frame);
177 _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
179 pthread_cond_signal(&_context->frame_wait_cond);
181 unlock_frames(_context);
183 ++_context->frames_captured;
188 /** AudioReciever class - delegate for AVCaptureSession
190 @interface AVFAudioReceiver : NSObject
192 AVFContext* _context;
195 - (id)initWithContext:(AVFContext*)context;
197 - (void) captureOutput:(AVCaptureOutput *)captureOutput
198 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
199 fromConnection:(AVCaptureConnection *)connection;
203 @implementation AVFAudioReceiver
205 - (id)initWithContext:(AVFContext*)context
207 if (self = [super init]) {
213 - (void) captureOutput:(AVCaptureOutput *)captureOutput
214 didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
215 fromConnection:(AVCaptureConnection *)connection
217 lock_frames(_context);
219 if (_context->current_audio_frame != nil) {
220 CFRelease(_context->current_audio_frame);
223 _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
225 pthread_cond_signal(&_context->frame_wait_cond);
227 unlock_frames(_context);
229 ++_context->audio_frames_captured;
234 static void destroy_context(AVFContext* ctx)
236 [ctx->capture_session stopRunning];
238 [ctx->capture_session release];
239 [ctx->video_output release];
240 [ctx->audio_output release];
241 [ctx->avf_delegate release];
242 [ctx->avf_audio_delegate release];
244 ctx->capture_session = NULL;
245 ctx->video_output = NULL;
246 ctx->audio_output = NULL;
247 ctx->avf_delegate = NULL;
248 ctx->avf_audio_delegate = NULL;
250 av_freep(&ctx->audio_buffer);
252 pthread_mutex_destroy(&ctx->frame_lock);
253 pthread_cond_destroy(&ctx->frame_wait_cond);
255 if (ctx->current_frame) {
256 CFRelease(ctx->current_frame);
260 static void parse_device_name(AVFormatContext *s)
262 AVFContext *ctx = (AVFContext*)s->priv_data;
263 char *tmp = av_strdup(s->url);
267 ctx->video_filename = av_strtok(tmp, ":", &save);
268 ctx->audio_filename = av_strtok(NULL, ":", &save);
270 ctx->audio_filename = av_strtok(tmp, ":", &save);
275 * Configure the video device.
277 * Configure the video device using a run-time approach to access properties
278 * since formats, activeFormat are available since iOS >= 7.0 or OSX >= 10.7
279 * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
281 * The NSUndefinedKeyException must be handled by the caller of this function.
284 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
286 AVFContext *ctx = (AVFContext*)s->priv_data;
288 double framerate = av_q2d(ctx->framerate);
289 NSObject *range = nil;
290 NSObject *format = nil;
291 NSObject *selected_range = nil;
292 NSObject *selected_format = nil;
294 for (format in [video_device valueForKey:@"formats"]) {
295 CMFormatDescriptionRef formatDescription;
296 CMVideoDimensions dimensions;
298 formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
299 dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
301 if ((ctx->width == 0 && ctx->height == 0) ||
302 (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
304 selected_format = format;
306 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
307 double max_framerate;
309 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
310 if (fabs (framerate - max_framerate) < 0.01) {
311 selected_range = range;
318 if (!selected_format) {
319 av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device\n",
320 ctx->width, ctx->height);
321 goto unsupported_format;
324 if (!selected_range) {
325 av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device\n",
327 goto unsupported_format;
330 if ([video_device lockForConfiguration:NULL] == YES) {
331 NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
333 [video_device setValue:selected_format forKey:@"activeFormat"];
334 [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
335 [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
337 av_log(s, AV_LOG_ERROR, "Could not lock device for configuration");
338 return AVERROR(EINVAL);
345 av_log(s, AV_LOG_ERROR, "Supported modes:\n");
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 for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
354 double min_framerate;
355 double max_framerate;
357 [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
358 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
359 av_log(s, AV_LOG_ERROR, " %dx%d@[%f %f]fps\n",
360 dimensions.width, dimensions.height,
361 min_framerate, max_framerate);
364 return AVERROR(EINVAL);
367 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
369 AVFContext *ctx = (AVFContext*)s->priv_data;
371 NSError *error = nil;
372 AVCaptureInput* capture_input = nil;
373 struct AVFPixelFormatSpec pxl_fmt_spec;
374 NSNumber *pixel_format;
375 NSDictionary *capture_dict;
376 dispatch_queue_t queue;
378 if (ctx->video_device_index < ctx->num_video_devices) {
379 capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
381 capture_input = (AVCaptureInput*) video_device;
384 if (!capture_input) {
385 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
386 [[error localizedDescription] UTF8String]);
390 if ([ctx->capture_session canAddInput:capture_input]) {
391 [ctx->capture_session addInput:capture_input];
393 av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
398 ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
400 if (!ctx->video_output) {
401 av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
405 // Configure device framerate and video size
407 if ((ret = configure_video_device(s, video_device)) < 0) {
410 } @catch (NSException *exception) {
411 if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
412 av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
413 return AVERROR_EXTERNAL;
417 // select pixel format
418 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
420 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
421 if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
422 pxl_fmt_spec = avf_pixel_formats[i];
427 // check if selected pixel format is supported by AVFoundation
428 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
429 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
430 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
434 // check if the pixel format is available for this device
435 if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
436 av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
437 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
439 pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
441 av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
442 for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
443 struct AVFPixelFormatSpec pxl_fmt_dummy;
444 pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
445 for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
446 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
447 pxl_fmt_dummy = avf_pixel_formats[i];
452 if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
453 av_log(s, AV_LOG_ERROR, " %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
455 // select first supported pixel format instead of user selected (or default) pixel format
456 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
457 pxl_fmt_spec = pxl_fmt_dummy;
462 // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
463 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
466 av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
467 av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
471 ctx->pixel_format = pxl_fmt_spec.ff_id;
472 pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
473 capture_dict = [NSDictionary dictionaryWithObject:pixel_format
474 forKey:(id)kCVPixelBufferPixelFormatTypeKey];
476 [ctx->video_output setVideoSettings:capture_dict];
477 [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
479 ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
481 queue = dispatch_queue_create("avf_queue", NULL);
482 [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
483 dispatch_release(queue);
485 if ([ctx->capture_session canAddOutput:ctx->video_output]) {
486 [ctx->capture_session addOutput:ctx->video_output];
488 av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
495 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
497 AVFContext *ctx = (AVFContext*)s->priv_data;
498 NSError *error = nil;
499 AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
500 dispatch_queue_t queue;
502 if (!audio_dev_input) {
503 av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
504 [[error localizedDescription] UTF8String]);
508 if ([ctx->capture_session canAddInput:audio_dev_input]) {
509 [ctx->capture_session addInput:audio_dev_input];
511 av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
516 ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
518 if (!ctx->audio_output) {
519 av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
523 ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
525 queue = dispatch_queue_create("avf_audio_queue", NULL);
526 [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
527 dispatch_release(queue);
529 if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
530 [ctx->capture_session addOutput:ctx->audio_output];
532 av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
539 static int get_video_config(AVFormatContext *s)
541 AVFContext *ctx = (AVFContext*)s->priv_data;
542 CVImageBufferRef image_buffer;
543 CGSize image_buffer_size;
544 AVStream* stream = avformat_new_stream(s, NULL);
550 // Take stream info from the first frame.
551 while (ctx->frames_captured < 1) {
552 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
557 ctx->video_stream_index = stream->index;
559 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
561 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
562 image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
564 stream->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
565 stream->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
566 stream->codecpar->width = (int)image_buffer_size.width;
567 stream->codecpar->height = (int)image_buffer_size.height;
568 stream->codecpar->format = ctx->pixel_format;
570 CFRelease(ctx->current_frame);
571 ctx->current_frame = nil;
578 static int get_audio_config(AVFormatContext *s)
580 AVFContext *ctx = (AVFContext*)s->priv_data;
581 CMFormatDescriptionRef format_desc;
582 AVStream* stream = avformat_new_stream(s, NULL);
588 // Take stream info from the first frame.
589 while (ctx->audio_frames_captured < 1) {
590 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
595 ctx->audio_stream_index = stream->index;
597 avpriv_set_pts_info(stream, 64, 1, avf_time_base);
599 format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
600 const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
603 av_log(s, AV_LOG_ERROR, "audio format not available\n");
607 stream->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
608 stream->codecpar->sample_rate = basic_desc->mSampleRate;
609 stream->codecpar->channels = basic_desc->mChannelsPerFrame;
610 stream->codecpar->channel_layout = av_get_default_channel_layout(stream->codecpar->channels);
612 ctx->audio_channels = basic_desc->mChannelsPerFrame;
613 ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
614 ctx->audio_float = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
615 ctx->audio_be = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
616 ctx->audio_signed_integer = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
617 ctx->audio_packed = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
618 ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
620 if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
622 ctx->audio_bits_per_sample == 32 &&
624 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
625 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
626 ctx->audio_signed_integer &&
627 ctx->audio_bits_per_sample == 16 &&
629 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
630 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
631 ctx->audio_signed_integer &&
632 ctx->audio_bits_per_sample == 24 &&
634 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
635 } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
636 ctx->audio_signed_integer &&
637 ctx->audio_bits_per_sample == 32 &&
639 stream->codecpar->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
641 av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
645 if (ctx->audio_non_interleaved) {
646 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
647 ctx->audio_buffer_size = CMBlockBufferGetDataLength(block_buffer);
648 ctx->audio_buffer = av_malloc(ctx->audio_buffer_size);
649 if (!ctx->audio_buffer) {
650 av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
655 CFRelease(ctx->current_audio_frame);
656 ctx->current_audio_frame = nil;
663 static int avf_read_header(AVFormatContext *s)
665 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
666 int capture_screen = 0;
667 uint32_t num_screens = 0;
668 AVFContext *ctx = (AVFContext*)s->priv_data;
669 AVCaptureDevice *video_device = nil;
670 AVCaptureDevice *audio_device = nil;
671 // Find capture device
672 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
673 ctx->num_video_devices = [devices count];
675 ctx->first_pts = av_gettime();
676 ctx->first_audio_pts = av_gettime();
678 pthread_mutex_init(&ctx->frame_lock, NULL);
679 pthread_cond_init(&ctx->frame_wait_cond, NULL);
681 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
682 CGGetActiveDisplayList(0, NULL, &num_screens);
685 // List devices if requested
686 if (ctx->list_devices) {
688 av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
689 for (AVCaptureDevice *device in devices) {
690 const char *name = [[device localizedName] UTF8String];
691 index = [devices indexOfObject:device];
692 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
695 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
696 if (num_screens > 0) {
697 CGDirectDisplayID screens[num_screens];
698 CGGetActiveDisplayList(num_screens, screens, &num_screens);
699 for (int i = 0; i < num_screens; i++) {
700 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", index + i, i);
705 av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
706 devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
707 for (AVCaptureDevice *device in devices) {
708 const char *name = [[device localizedName] UTF8String];
709 int index = [devices indexOfObject:device];
710 av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
715 // parse input filename for video and audio device
716 parse_device_name(s);
718 // check for device index given in filename
719 if (ctx->video_device_index == -1 && ctx->video_filename) {
720 sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
722 if (ctx->audio_device_index == -1 && ctx->audio_filename) {
723 sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
726 if (ctx->video_device_index >= 0) {
727 if (ctx->video_device_index < ctx->num_video_devices) {
728 video_device = [devices objectAtIndex:ctx->video_device_index];
729 } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
730 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
731 CGDirectDisplayID screens[num_screens];
732 CGGetActiveDisplayList(num_screens, screens, &num_screens);
733 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
735 if (ctx->framerate.num > 0) {
736 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
739 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
740 if (ctx->capture_cursor) {
741 capture_screen_input.capturesCursor = YES;
743 capture_screen_input.capturesCursor = NO;
747 if (ctx->capture_mouse_clicks) {
748 capture_screen_input.capturesMouseClicks = YES;
750 capture_screen_input.capturesMouseClicks = NO;
753 video_device = (AVCaptureDevice*) capture_screen_input;
757 av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
760 } else if (ctx->video_filename &&
761 strncmp(ctx->video_filename, "none", 4)) {
762 if (!strncmp(ctx->video_filename, "default", 7)) {
763 video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
765 // looking for video inputs
766 for (AVCaptureDevice *device in devices) {
767 if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
768 video_device = device;
773 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
774 // looking for screen inputs
777 if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
778 CGDirectDisplayID screens[num_screens];
779 CGGetActiveDisplayList(num_screens, screens, &num_screens);
780 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
781 video_device = (AVCaptureDevice*) capture_screen_input;
782 ctx->video_device_index = ctx->num_video_devices + idx;
785 if (ctx->framerate.num > 0) {
786 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
789 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
790 if (ctx->capture_cursor) {
791 capture_screen_input.capturesCursor = YES;
793 capture_screen_input.capturesCursor = NO;
797 if (ctx->capture_mouse_clicks) {
798 capture_screen_input.capturesMouseClicks = YES;
800 capture_screen_input.capturesMouseClicks = NO;
808 av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
814 if (ctx->audio_device_index >= 0) {
815 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
817 if (ctx->audio_device_index >= [devices count]) {
818 av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
822 audio_device = [devices objectAtIndex:ctx->audio_device_index];
823 } else if (ctx->audio_filename &&
824 strncmp(ctx->audio_filename, "none", 4)) {
825 if (!strncmp(ctx->audio_filename, "default", 7)) {
826 audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
828 NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
830 for (AVCaptureDevice *device in devices) {
831 if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
832 audio_device = device;
839 av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
844 // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
845 if (!video_device && !audio_device) {
846 av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
851 if (ctx->video_device_index < ctx->num_video_devices) {
852 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
854 av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
858 av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
861 // Initialize capture session
862 ctx->capture_session = [[AVCaptureSession alloc] init];
864 if (video_device && add_video_device(s, video_device)) {
867 if (audio_device && add_audio_device(s, audio_device)) {
870 [ctx->capture_session startRunning];
872 /* Unlock device configuration only after the session is started so it
873 * does not reset the capture formats */
874 if (!capture_screen) {
875 [video_device unlockForConfiguration];
878 if (video_device && get_video_config(s)) {
883 if (audio_device && get_audio_config(s)) {
892 destroy_context(ctx);
896 static int copy_cvpixelbuffer(AVFormatContext *s,
897 CVPixelBufferRef image_buffer,
900 AVFContext *ctx = s->priv_data;
902 const uint8_t *src_data[4];
903 int width = CVPixelBufferGetWidth(image_buffer);
904 int height = CVPixelBufferGetHeight(image_buffer);
907 memset(src_linesize, 0, sizeof(src_linesize));
908 memset(src_data, 0, sizeof(src_data));
910 status = CVPixelBufferLockBaseAddress(image_buffer, 0);
911 if (status != kCVReturnSuccess) {
912 av_log(s, AV_LOG_ERROR, "Could not lock base address: %d\n", status);
913 return AVERROR_EXTERNAL;
916 if (CVPixelBufferIsPlanar(image_buffer)) {
917 size_t plane_count = CVPixelBufferGetPlaneCount(image_buffer);
919 for(i = 0; i < plane_count; i++){
920 src_linesize[i] = CVPixelBufferGetBytesPerRowOfPlane(image_buffer, i);
921 src_data[i] = CVPixelBufferGetBaseAddressOfPlane(image_buffer, i);
924 src_linesize[0] = CVPixelBufferGetBytesPerRow(image_buffer);
925 src_data[0] = CVPixelBufferGetBaseAddress(image_buffer);
928 status = av_image_copy_to_buffer(pkt->data, pkt->size,
929 src_data, src_linesize,
930 ctx->pixel_format, width, height, 1);
934 CVPixelBufferUnlockBaseAddress(image_buffer, 0);
939 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
941 AVFContext* ctx = (AVFContext*)s->priv_data;
944 CVImageBufferRef image_buffer;
947 image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
949 if (ctx->current_frame != nil) {
951 if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
956 CMSampleTimingInfo timing_info;
958 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
959 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
960 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
963 pkt->stream_index = ctx->video_stream_index;
964 pkt->flags |= AV_PKT_FLAG_KEY;
966 status = copy_cvpixelbuffer(s, image_buffer, pkt);
967 CFRelease(ctx->current_frame);
968 ctx->current_frame = nil;
972 } else if (ctx->current_audio_frame != nil) {
973 CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
974 int block_buffer_size = CMBlockBufferGetDataLength(block_buffer);
976 if (!block_buffer || !block_buffer_size) {
980 if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
981 return AVERROR_BUFFER_TOO_SMALL;
984 if (av_new_packet(pkt, block_buffer_size) < 0) {
989 CMSampleTimingInfo timing_info;
991 if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
992 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
993 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
996 pkt->stream_index = ctx->audio_stream_index;
997 pkt->flags |= AV_PKT_FLAG_KEY;
999 if (ctx->audio_non_interleaved) {
1000 int sample, c, shift, num_samples;
1002 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
1003 if (ret != kCMBlockBufferNoErr) {
1004 return AVERROR(EIO);
1007 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
1009 // transform decoded frame into output format
1010 #define INTERLEAVE_OUTPUT(bps) \
1012 int##bps##_t **src; \
1013 int##bps##_t *dest; \
1014 src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*)); \
1015 if (!src) return AVERROR(EIO); \
1016 for (c = 0; c < ctx->audio_channels; c++) { \
1017 src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
1019 dest = (int##bps##_t*)pkt->data; \
1020 shift = bps - ctx->audio_bits_per_sample; \
1021 for (sample = 0; sample < num_samples; sample++) \
1022 for (c = 0; c < ctx->audio_channels; c++) \
1023 *dest++ = src[c][sample] << shift; \
1027 if (ctx->audio_bits_per_sample <= 16) {
1028 INTERLEAVE_OUTPUT(16)
1030 INTERLEAVE_OUTPUT(32)
1033 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
1034 if (ret != kCMBlockBufferNoErr) {
1035 return AVERROR(EIO);
1039 CFRelease(ctx->current_audio_frame);
1040 ctx->current_audio_frame = nil;
1043 pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
1047 } while (!pkt->data);
1052 static int avf_close(AVFormatContext *s)
1054 AVFContext* ctx = (AVFContext*)s->priv_data;
1055 destroy_context(ctx);
1059 static const AVOption options[] = {
1060 { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
1061 { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
1062 { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
1063 { "video_device_index", "select video device by index for devices with same name (starts at 0)", offsetof(AVFContext, video_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1064 { "audio_device_index", "select audio device by index for devices with same name (starts at 0)", offsetof(AVFContext, audio_device_index), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1065 { "pixel_format", "set pixel format", offsetof(AVFContext, pixel_format), AV_OPT_TYPE_PIXEL_FMT, {.i64 = AV_PIX_FMT_YUV420P}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM},
1066 { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
1067 { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
1068 { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1069 { "capture_mouse_clicks", "capture the screen mouse clicks", offsetof(AVFContext, capture_mouse_clicks), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
1074 static const AVClass avf_class = {
1075 .class_name = "AVFoundation input device",
1076 .item_name = av_default_item_name,
1078 .version = LIBAVUTIL_VERSION_INT,
1079 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
1082 AVInputFormat ff_avfoundation_demuxer = {
1083 .name = "avfoundation",
1084 .long_name = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
1085 .priv_data_size = sizeof(AVFContext),
1086 .read_header = avf_read_header,
1087 .read_packet = avf_read_packet,
1088 .read_close = avf_close,
1089 .flags = AVFMT_NOFILE,
1090 .priv_class = &avf_class,