libavdevice/avfoundation.m
d2417061
 /*
  * AVFoundation input device
  * Copyright (c) 2014 Thilo Borgmann <thilo.borgmann@mail.de>
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 /**
  * @file
  * AVFoundation input device
  * @author Thilo Borgmann <thilo.borgmann@mail.de>
  */
 
 #import <AVFoundation/AVFoundation.h>
 #include <pthread.h>
 
 #include "libavutil/pixdesc.h"
 #include "libavutil/opt.h"
48c29883
 #include "libavutil/avstring.h"
d2417061
 #include "libavformat/internal.h"
 #include "libavutil/internal.h"
573a77a1
 #include "libavutil/parseutils.h"
d2417061
 #include "libavutil/time.h"
 #include "avdevice.h"
 
f2254e36
 static const int avf_time_base = 1000000;
d2417061
 
 static const AVRational avf_time_base_q = {
     .num = 1,
     .den = avf_time_base
 };
 
ffe6ecc4
 struct AVFPixelFormatSpec {
     enum AVPixelFormat ff_id;
     OSType avf_id;
 };
 
 static const struct AVFPixelFormatSpec avf_pixel_formats[] = {
     { AV_PIX_FMT_MONOBLACK,    kCVPixelFormatType_1Monochrome },
     { AV_PIX_FMT_RGB555BE,     kCVPixelFormatType_16BE555 },
     { AV_PIX_FMT_RGB555LE,     kCVPixelFormatType_16LE555 },
     { AV_PIX_FMT_RGB565BE,     kCVPixelFormatType_16BE565 },
     { AV_PIX_FMT_RGB565LE,     kCVPixelFormatType_16LE565 },
     { AV_PIX_FMT_RGB24,        kCVPixelFormatType_24RGB },
     { AV_PIX_FMT_BGR24,        kCVPixelFormatType_24BGR },
     { AV_PIX_FMT_0RGB,         kCVPixelFormatType_32ARGB },
     { AV_PIX_FMT_BGR0,         kCVPixelFormatType_32BGRA },
     { AV_PIX_FMT_0BGR,         kCVPixelFormatType_32ABGR },
     { AV_PIX_FMT_RGB0,         kCVPixelFormatType_32RGBA },
     { AV_PIX_FMT_BGR48BE,      kCVPixelFormatType_48RGB },
     { AV_PIX_FMT_UYVY422,      kCVPixelFormatType_422YpCbCr8 },
     { AV_PIX_FMT_YUVA444P,     kCVPixelFormatType_4444YpCbCrA8R },
     { AV_PIX_FMT_YUVA444P16LE, kCVPixelFormatType_4444AYpCbCr16 },
     { AV_PIX_FMT_YUV444P,      kCVPixelFormatType_444YpCbCr8 },
     { AV_PIX_FMT_YUV422P16,    kCVPixelFormatType_422YpCbCr16 },
     { AV_PIX_FMT_YUV422P10,    kCVPixelFormatType_422YpCbCr10 },
     { AV_PIX_FMT_YUV444P10,    kCVPixelFormatType_444YpCbCr10 },
     { AV_PIX_FMT_YUV420P,      kCVPixelFormatType_420YpCbCr8Planar },
     { AV_PIX_FMT_NV12,         kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange },
     { AV_PIX_FMT_YUYV422,      kCVPixelFormatType_422YpCbCr8_yuvs },
88bf1689
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
ffe6ecc4
     { AV_PIX_FMT_GRAY8,        kCVPixelFormatType_OneComponent8 },
04980dbe
 #endif
ffe6ecc4
     { AV_PIX_FMT_NONE, 0 }
 };
 
d2417061
 typedef struct
 {
     AVClass*        class;
 
     int             frames_captured;
dd16a0d8
     int             audio_frames_captured;
d2417061
     int64_t         first_pts;
dd16a0d8
     int64_t         first_audio_pts;
d2417061
     pthread_mutex_t frame_lock;
     pthread_cond_t  frame_wait_cond;
     id              avf_delegate;
dd16a0d8
     id              avf_audio_delegate;
d2417061
 
573a77a1
     AVRational      framerate;
     int             width, height;
 
c908cae7
     int             capture_cursor;
021b0237
     int             capture_mouse_clicks;
c908cae7
 
d2417061
     int             list_devices;
     int             video_device_index;
92827e18
     int             video_stream_index;
dd16a0d8
     int             audio_device_index;
     int             audio_stream_index;
 
     char            *video_filename;
     char            *audio_filename;
 
a6555f88
     int             num_video_devices;
 
dd16a0d8
     int             audio_channels;
     int             audio_bits_per_sample;
     int             audio_float;
     int             audio_be;
     int             audio_signed_integer;
     int             audio_packed;
     int             audio_non_interleaved;
 
     int32_t         *audio_buffer;
     int             audio_buffer_size;
 
ffe6ecc4
     enum AVPixelFormat pixel_format;
d2417061
 
     AVCaptureSession         *capture_session;
     AVCaptureVideoDataOutput *video_output;
dd16a0d8
     AVCaptureAudioDataOutput *audio_output;
d2417061
     CMSampleBufferRef         current_frame;
dd16a0d8
     CMSampleBufferRef         current_audio_frame;
d2417061
 } AVFContext;
 
 static void lock_frames(AVFContext* ctx)
 {
     pthread_mutex_lock(&ctx->frame_lock);
 }
 
 static void unlock_frames(AVFContext* ctx)
 {
     pthread_mutex_unlock(&ctx->frame_lock);
 }
 
 /** FrameReciever class - delegate for AVCaptureSession
  */
 @interface AVFFrameReceiver : NSObject
 {
     AVFContext* _context;
 }
 
 - (id)initWithContext:(AVFContext*)context;
 
 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
          fromConnection:(AVCaptureConnection *)connection;
 
 @end
 
 @implementation AVFFrameReceiver
 
 - (id)initWithContext:(AVFContext*)context
 {
     if (self = [super init]) {
         _context = context;
     }
     return self;
 }
 
 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
   didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
          fromConnection:(AVCaptureConnection *)connection
 {
     lock_frames(_context);
 
     if (_context->current_frame != nil) {
         CFRelease(_context->current_frame);
     }
 
     _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
 
     pthread_cond_signal(&_context->frame_wait_cond);
 
     unlock_frames(_context);
 
     ++_context->frames_captured;
 }
 
 @end
 
dd16a0d8
 /** AudioReciever class - delegate for AVCaptureSession
  */
 @interface AVFAudioReceiver : NSObject
 {
     AVFContext* _context;
 }
 
 - (id)initWithContext:(AVFContext*)context;
 
 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
   didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
          fromConnection:(AVCaptureConnection *)connection;
 
 @end
 
 @implementation AVFAudioReceiver
 
 - (id)initWithContext:(AVFContext*)context
 {
     if (self = [super init]) {
         _context = context;
     }
     return self;
 }
 
 - (void)  captureOutput:(AVCaptureOutput *)captureOutput
   didOutputSampleBuffer:(CMSampleBufferRef)audioFrame
          fromConnection:(AVCaptureConnection *)connection
 {
     lock_frames(_context);
 
     if (_context->current_audio_frame != nil) {
         CFRelease(_context->current_audio_frame);
     }
 
     _context->current_audio_frame = (CMSampleBufferRef)CFRetain(audioFrame);
 
     pthread_cond_signal(&_context->frame_wait_cond);
 
     unlock_frames(_context);
 
     ++_context->audio_frames_captured;
 }
 
 @end
 
d2417061
 static void destroy_context(AVFContext* ctx)
 {
     [ctx->capture_session stopRunning];
 
     [ctx->capture_session release];
     [ctx->video_output    release];
dd16a0d8
     [ctx->audio_output    release];
d2417061
     [ctx->avf_delegate    release];
dd16a0d8
     [ctx->avf_audio_delegate release];
d2417061
 
     ctx->capture_session = NULL;
     ctx->video_output    = NULL;
dd16a0d8
     ctx->audio_output    = NULL;
d2417061
     ctx->avf_delegate    = NULL;
dd16a0d8
     ctx->avf_audio_delegate = NULL;
 
     av_freep(&ctx->audio_buffer);
d2417061
 
     pthread_mutex_destroy(&ctx->frame_lock);
     pthread_cond_destroy(&ctx->frame_wait_cond);
 
     if (ctx->current_frame) {
         CFRelease(ctx->current_frame);
     }
 }
 
dd16a0d8
 static void parse_device_name(AVFormatContext *s)
 {
     AVFContext *ctx = (AVFContext*)s->priv_data;
     char *tmp = av_strdup(s->filename);
48c29883
     char *save;
dd16a0d8
 
     if (tmp[0] != ':') {
48c29883
         ctx->video_filename = av_strtok(tmp,  ":", &save);
         ctx->audio_filename = av_strtok(NULL, ":", &save);
dd16a0d8
     } else {
48c29883
         ctx->audio_filename = av_strtok(tmp,  ":", &save);
dd16a0d8
     }
 }
 
573a77a1
 /**
  * Configure the video device.
  *
  * Configure the video device using a run-time approach to access properties
  * since formats, activeFormat are available since  iOS >= 7.0 or OSX >= 10.7
  * and activeVideoMaxFrameDuration is available since i0S >= 7.0 and OSX >= 10.9.
  *
  * The NSUndefinedKeyException must be handled by the caller of this function.
  *
  */
 static int configure_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
 {
     AVFContext *ctx = (AVFContext*)s->priv_data;
 
     double framerate = av_q2d(ctx->framerate);
     NSObject *range = nil;
     NSObject *format = nil;
     NSObject *selected_range = nil;
     NSObject *selected_format = nil;
 
     for (format in [video_device valueForKey:@"formats"]) {
         CMFormatDescriptionRef formatDescription;
         CMVideoDimensions dimensions;
 
         formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
         dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
 
         if ((ctx->width == 0 && ctx->height == 0) ||
             (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
 
             selected_format = format;
 
             for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
                 double max_framerate;
 
                 [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
                 if (fabs (framerate - max_framerate) < 0.01) {
                     selected_range = range;
                     break;
                 }
             }
         }
     }
 
     if (!selected_format) {
         av_log(s, AV_LOG_ERROR, "Selected video size (%dx%d) is not supported by the device\n",
             ctx->width, ctx->height);
         goto unsupported_format;
     }
 
     if (!selected_range) {
         av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device\n",
             framerate);
         goto unsupported_format;
     }
 
     if ([video_device lockForConfiguration:NULL] == YES) {
         NSValue *min_frame_duration = [selected_range valueForKey:@"minFrameDuration"];
 
         [video_device setValue:selected_format forKey:@"activeFormat"];
         [video_device setValue:min_frame_duration forKey:@"activeVideoMinFrameDuration"];
         [video_device setValue:min_frame_duration forKey:@"activeVideoMaxFrameDuration"];
     } else {
         av_log(s, AV_LOG_ERROR, "Could not lock device for configuration");
         return AVERROR(EINVAL);
     }
 
     return 0;
 
 unsupported_format:
 
     av_log(s, AV_LOG_ERROR, "Supported modes:\n");
     for (format in [video_device valueForKey:@"formats"]) {
         CMFormatDescriptionRef formatDescription;
         CMVideoDimensions dimensions;
 
         formatDescription = (CMFormatDescriptionRef) [format performSelector:@selector(formatDescription)];
         dimensions = CMVideoFormatDescriptionGetDimensions(formatDescription);
 
         for (range in [format valueForKey:@"videoSupportedFrameRateRanges"]) {
             double min_framerate;
             double max_framerate;
 
             [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
             [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
             av_log(s, AV_LOG_ERROR, "  %dx%d@[%f %f]fps\n",
                 dimensions.width, dimensions.height,
                 min_framerate, max_framerate);
         }
     }
     return AVERROR(EINVAL);
 }
 
a69c70e1
 static int add_video_device(AVFormatContext *s, AVCaptureDevice *video_device)
d2417061
 {
a69c70e1
     AVFContext *ctx = (AVFContext*)s->priv_data;
573a77a1
     int ret;
a69c70e1
     NSError *error  = nil;
a6555f88
     AVCaptureInput* capture_input = nil;
87b3c6e2
     struct AVFPixelFormatSpec pxl_fmt_spec;
     NSNumber *pixel_format;
     NSDictionary *capture_dict;
     dispatch_queue_t queue;
a6555f88
 
     if (ctx->video_device_index < ctx->num_video_devices) {
         capture_input = (AVCaptureInput*) [[[AVCaptureDeviceInput alloc] initWithDevice:video_device error:&error] autorelease];
     } else {
         capture_input = (AVCaptureInput*) video_device;
     }
d2417061
 
a6555f88
     if (!capture_input) {
d2417061
         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
                [[error localizedDescription] UTF8String]);
a69c70e1
         return 1;
d2417061
     }
 
a6555f88
     if ([ctx->capture_session canAddInput:capture_input]) {
         [ctx->capture_session addInput:capture_input];
d2417061
     } else {
         av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
a69c70e1
         return 1;
d2417061
     }
 
     // Attaching output
     ctx->video_output = [[AVCaptureVideoDataOutput alloc] init];
 
     if (!ctx->video_output) {
         av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
a69c70e1
         return 1;
d2417061
     }
 
573a77a1
     // Configure device framerate and video size
     @try {
         if ((ret = configure_video_device(s, video_device)) < 0) {
             return ret;
         }
     } @catch (NSException *exception) {
         if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
63167a6b
           av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
573a77a1
           return AVERROR_EXTERNAL;
         }
     }
 
ffe6ecc4
     // select pixel format
     pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
 
     for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
         if (ctx->pixel_format == avf_pixel_formats[i].ff_id) {
             pxl_fmt_spec = avf_pixel_formats[i];
             break;
         }
     }
 
     // check if selected pixel format is supported by AVFoundation
     if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFoundation.\n",
                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
a69c70e1
         return 1;
ffe6ecc4
     }
 
     // check if the pixel format is available for this device
     if ([[ctx->video_output availableVideoCVPixelFormatTypes] indexOfObject:[NSNumber numberWithInt:pxl_fmt_spec.avf_id]] == NSNotFound) {
         av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by the input device.\n",
                av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
 
         pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
 
         av_log(s, AV_LOG_ERROR, "Supported pixel formats:\n");
         for (NSNumber *pxl_fmt in [ctx->video_output availableVideoCVPixelFormatTypes]) {
             struct AVFPixelFormatSpec pxl_fmt_dummy;
             pxl_fmt_dummy.ff_id = AV_PIX_FMT_NONE;
             for (int i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
                 if ([pxl_fmt intValue] == avf_pixel_formats[i].avf_id) {
                     pxl_fmt_dummy = avf_pixel_formats[i];
                     break;
                 }
             }
 
             if (pxl_fmt_dummy.ff_id != AV_PIX_FMT_NONE) {
                 av_log(s, AV_LOG_ERROR, "  %s\n", av_get_pix_fmt_name(pxl_fmt_dummy.ff_id));
 
                 // select first supported pixel format instead of user selected (or default) pixel format
                 if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
                     pxl_fmt_spec = pxl_fmt_dummy;
                 }
             }
         }
 
         // fail if there is no appropriate pixel format or print a warning about overriding the pixel format
         if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
a69c70e1
             return 1;
ffe6ecc4
         } else {
             av_log(s, AV_LOG_WARNING, "Overriding selected pixel format to use %s instead.\n",
                    av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
         }
     }
 
a69c70e1
     ctx->pixel_format          = pxl_fmt_spec.ff_id;
87b3c6e2
     pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
     capture_dict = [NSDictionary dictionaryWithObject:pixel_format
d2417061
                                                forKey:(id)kCVPixelBufferPixelFormatTypeKey];
 
     [ctx->video_output setVideoSettings:capture_dict];
     [ctx->video_output setAlwaysDiscardsLateVideoFrames:YES];
 
     ctx->avf_delegate = [[AVFFrameReceiver alloc] initWithContext:ctx];
 
87b3c6e2
     queue = dispatch_queue_create("avf_queue", NULL);
d2417061
     [ctx->video_output setSampleBufferDelegate:ctx->avf_delegate queue:queue];
     dispatch_release(queue);
 
     if ([ctx->capture_session canAddOutput:ctx->video_output]) {
         [ctx->capture_session addOutput:ctx->video_output];
     } else {
         av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
a69c70e1
         return 1;
d2417061
     }
 
a69c70e1
     return 0;
 }
 
dd16a0d8
 static int add_audio_device(AVFormatContext *s, AVCaptureDevice *audio_device)
 {
     AVFContext *ctx = (AVFContext*)s->priv_data;
     NSError *error  = nil;
     AVCaptureDeviceInput* audio_dev_input = [[[AVCaptureDeviceInput alloc] initWithDevice:audio_device error:&error] autorelease];
87b3c6e2
     dispatch_queue_t queue;
dd16a0d8
 
     if (!audio_dev_input) {
         av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
                [[error localizedDescription] UTF8String]);
         return 1;
     }
 
     if ([ctx->capture_session canAddInput:audio_dev_input]) {
         [ctx->capture_session addInput:audio_dev_input];
     } else {
         av_log(s, AV_LOG_ERROR, "can't add audio input to capture session\n");
         return 1;
     }
 
     // Attaching output
     ctx->audio_output = [[AVCaptureAudioDataOutput alloc] init];
 
     if (!ctx->audio_output) {
         av_log(s, AV_LOG_ERROR, "Failed to init AV audio output\n");
         return 1;
     }
 
     ctx->avf_audio_delegate = [[AVFAudioReceiver alloc] initWithContext:ctx];
 
87b3c6e2
     queue = dispatch_queue_create("avf_audio_queue", NULL);
dd16a0d8
     [ctx->audio_output setSampleBufferDelegate:ctx->avf_audio_delegate queue:queue];
     dispatch_release(queue);
 
     if ([ctx->capture_session canAddOutput:ctx->audio_output]) {
         [ctx->capture_session addOutput:ctx->audio_output];
     } else {
         av_log(s, AV_LOG_ERROR, "adding audio output to capture session failed\n");
         return 1;
     }
 
     return 0;
 }
 
a69c70e1
 static int get_video_config(AVFormatContext *s)
 {
     AVFContext *ctx = (AVFContext*)s->priv_data;
87b3c6e2
     CVImageBufferRef image_buffer;
     CGSize image_buffer_size;
     AVStream* stream = avformat_new_stream(s, NULL);
 
     if (!stream) {
         return 1;
     }
d2417061
 
     // Take stream info from the first frame.
     while (ctx->frames_captured < 1) {
         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
     }
 
     lock_frames(ctx);
 
92827e18
     ctx->video_stream_index = stream->index;
 
d2417061
     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
 
87b3c6e2
     image_buffer      = CMSampleBufferGetImageBuffer(ctx->current_frame);
     image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
d2417061
 
     stream->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
     stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     stream->codec->width      = (int)image_buffer_size.width;
     stream->codec->height     = (int)image_buffer_size.height;
a69c70e1
     stream->codec->pix_fmt    = ctx->pixel_format;
d2417061
 
     CFRelease(ctx->current_frame);
     ctx->current_frame = nil;
 
     unlock_frames(ctx);
a69c70e1
 
     return 0;
 }
 
dd16a0d8
 static int get_audio_config(AVFormatContext *s)
 {
     AVFContext *ctx = (AVFContext*)s->priv_data;
87b3c6e2
     CMFormatDescriptionRef format_desc;
     AVStream* stream = avformat_new_stream(s, NULL);
 
     if (!stream) {
         return 1;
     }
dd16a0d8
 
     // Take stream info from the first frame.
     while (ctx->audio_frames_captured < 1) {
         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
     }
 
     lock_frames(ctx);
 
     ctx->audio_stream_index = stream->index;
 
     avpriv_set_pts_info(stream, 64, 1, avf_time_base);
 
87b3c6e2
     format_desc = CMSampleBufferGetFormatDescription(ctx->current_audio_frame);
dd16a0d8
     const AudioStreamBasicDescription *basic_desc = CMAudioFormatDescriptionGetStreamBasicDescription(format_desc);
 
     if (!basic_desc) {
         av_log(s, AV_LOG_ERROR, "audio format not available\n");
         return 1;
     }
 
     stream->codec->codec_type     = AVMEDIA_TYPE_AUDIO;
     stream->codec->sample_rate    = basic_desc->mSampleRate;
     stream->codec->channels       = basic_desc->mChannelsPerFrame;
     stream->codec->channel_layout = av_get_default_channel_layout(stream->codec->channels);
 
     ctx->audio_channels        = basic_desc->mChannelsPerFrame;
     ctx->audio_bits_per_sample = basic_desc->mBitsPerChannel;
     ctx->audio_float           = basic_desc->mFormatFlags & kAudioFormatFlagIsFloat;
     ctx->audio_be              = basic_desc->mFormatFlags & kAudioFormatFlagIsBigEndian;
     ctx->audio_signed_integer  = basic_desc->mFormatFlags & kAudioFormatFlagIsSignedInteger;
     ctx->audio_packed          = basic_desc->mFormatFlags & kAudioFormatFlagIsPacked;
     ctx->audio_non_interleaved = basic_desc->mFormatFlags & kAudioFormatFlagIsNonInterleaved;
 
     if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
         ctx->audio_float &&
23e48326
         ctx->audio_bits_per_sample == 32 &&
dd16a0d8
         ctx->audio_packed) {
         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_F32BE : AV_CODEC_ID_PCM_F32LE;
23e48326
     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
         ctx->audio_signed_integer &&
         ctx->audio_bits_per_sample == 16 &&
         ctx->audio_packed) {
         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S16BE : AV_CODEC_ID_PCM_S16LE;
98d19ca8
     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
         ctx->audio_signed_integer &&
         ctx->audio_bits_per_sample == 24 &&
         ctx->audio_packed) {
         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;
     } else if (basic_desc->mFormatID == kAudioFormatLinearPCM &&
         ctx->audio_signed_integer &&
         ctx->audio_bits_per_sample == 32 &&
         ctx->audio_packed) {
         stream->codec->codec_id = ctx->audio_be ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE;
dd16a0d8
     } else {
         av_log(s, AV_LOG_ERROR, "audio format is not supported\n");
         return 1;
     }
 
     if (ctx->audio_non_interleaved) {
         CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
         ctx->audio_buffer_size        = CMBlockBufferGetDataLength(block_buffer);
         ctx->audio_buffer             = av_malloc(ctx->audio_buffer_size);
         if (!ctx->audio_buffer) {
             av_log(s, AV_LOG_ERROR, "error allocating audio buffer\n");
             return 1;
         }
     }
 
     CFRelease(ctx->current_audio_frame);
     ctx->current_audio_frame = nil;
 
     unlock_frames(ctx);
 
     return 0;
 }
 
a69c70e1
 static int avf_read_header(AVFormatContext *s)
 {
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
573a77a1
     int capture_screen      = 0;
87b3c6e2
     uint32_t num_screens    = 0;
a69c70e1
     AVFContext *ctx         = (AVFContext*)s->priv_data;
87b3c6e2
     AVCaptureDevice *video_device = nil;
     AVCaptureDevice *audio_device = nil;
     // Find capture device
     NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
     ctx->num_video_devices = [devices count];
 
a69c70e1
     ctx->first_pts          = av_gettime();
dd16a0d8
     ctx->first_audio_pts    = av_gettime();
a69c70e1
 
     pthread_mutex_init(&ctx->frame_lock, NULL);
     pthread_cond_init(&ctx->frame_wait_cond, NULL);
 
88bf1689
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
a6555f88
     CGGetActiveDisplayList(0, NULL, &num_screens);
ed2e97ce
 #endif
a6555f88
 
a69c70e1
     // List devices if requested
     if (ctx->list_devices) {
a6555f88
         int index = 0;
87b3c6e2
         av_log(ctx, AV_LOG_INFO, "AVFoundation video devices:\n");
a69c70e1
         for (AVCaptureDevice *device in devices) {
             const char *name = [[device localizedName] UTF8String];
a6555f88
             index            = [devices indexOfObject:device];
a69c70e1
             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
a6555f88
             index++;
a69c70e1
         }
88bf1689
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
a6555f88
         if (num_screens > 0) {
             CGDirectDisplayID screens[num_screens];
             CGGetActiveDisplayList(num_screens, screens, &num_screens);
             for (int i = 0; i < num_screens; i++) {
                 av_log(ctx, AV_LOG_INFO, "[%d] Capture screen %d\n", index + i, i);
             }
         }
ed2e97ce
 #endif
a6555f88
 
dd16a0d8
         av_log(ctx, AV_LOG_INFO, "AVFoundation audio devices:\n");
         devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
         for (AVCaptureDevice *device in devices) {
             const char *name = [[device localizedName] UTF8String];
             int index  = [devices indexOfObject:device];
             av_log(ctx, AV_LOG_INFO, "[%d] %s\n", index, name);
         }
          goto fail;
a69c70e1
     }
 
dd16a0d8
     // parse input filename for video and audio device
     parse_device_name(s);
a69c70e1
 
     // check for device index given in filename
dd16a0d8
     if (ctx->video_device_index == -1 && ctx->video_filename) {
         sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
     }
     if (ctx->audio_device_index == -1 && ctx->audio_filename) {
         sscanf(ctx->audio_filename, "%d", &ctx->audio_device_index);
a69c70e1
     }
 
     if (ctx->video_device_index >= 0) {
a6555f88
         if (ctx->video_device_index < ctx->num_video_devices) {
87b3c6e2
             video_device = [devices objectAtIndex:ctx->video_device_index];
a6555f88
         } else if (ctx->video_device_index < ctx->num_video_devices + num_screens) {
88bf1689
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
a6555f88
             CGDirectDisplayID screens[num_screens];
             CGGetActiveDisplayList(num_screens, screens, &num_screens);
             AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[ctx->video_device_index - ctx->num_video_devices]] autorelease];
573a77a1
 
             if (ctx->framerate.num > 0) {
                 capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
             }
 
c908cae7
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
             if (ctx->capture_cursor) {
                 capture_screen_input.capturesCursor = YES;
             } else {
                 capture_screen_input.capturesCursor = NO;
             }
 #endif
 
021b0237
             if (ctx->capture_mouse_clicks) {
                 capture_screen_input.capturesMouseClicks = YES;
             } else {
                 capture_screen_input.capturesMouseClicks = NO;
             }
 
a6555f88
             video_device = (AVCaptureDevice*) capture_screen_input;
573a77a1
             capture_screen = 1;
ed2e97ce
 #endif
a6555f88
          } else {
a69c70e1
             av_log(ctx, AV_LOG_ERROR, "Invalid device index\n");
             goto fail;
         }
dd16a0d8
     } else if (ctx->video_filename &&
20453342
                strncmp(ctx->video_filename, "none", 4)) {
         if (!strncmp(ctx->video_filename, "default", 7)) {
             video_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
         } else {
a6555f88
         // looking for video inputs
87b3c6e2
         for (AVCaptureDevice *device in devices) {
dd16a0d8
             if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
a69c70e1
                 video_device = device;
                 break;
             }
         }
 
88bf1689
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
a6555f88
         // looking for screen inputs
         if (!video_device) {
             int idx;
             if(sscanf(ctx->video_filename, "Capture screen %d", &idx) && idx < num_screens) {
                 CGDirectDisplayID screens[num_screens];
                 CGGetActiveDisplayList(num_screens, screens, &num_screens);
                 AVCaptureScreenInput* capture_screen_input = [[[AVCaptureScreenInput alloc] initWithDisplayID:screens[idx]] autorelease];
                 video_device = (AVCaptureDevice*) capture_screen_input;
                 ctx->video_device_index = ctx->num_video_devices + idx;
573a77a1
                 capture_screen = 1;
 
                 if (ctx->framerate.num > 0) {
                     capture_screen_input.minFrameDuration = CMTimeMake(ctx->framerate.den, ctx->framerate.num);
                 }
c908cae7
 
 #if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
                 if (ctx->capture_cursor) {
                     capture_screen_input.capturesCursor = YES;
                 } else {
                     capture_screen_input.capturesCursor = NO;
                 }
 #endif
021b0237
 
                 if (ctx->capture_mouse_clicks) {
                     capture_screen_input.capturesMouseClicks = YES;
                 } else {
                     capture_screen_input.capturesMouseClicks = NO;
                 }
a6555f88
             }
         }
ed2e97ce
 #endif
20453342
         }
a6555f88
 
a69c70e1
         if (!video_device) {
             av_log(ctx, AV_LOG_ERROR, "Video device not found\n");
             goto fail;
         }
     }
 
dd16a0d8
     // get audio device
     if (ctx->audio_device_index >= 0) {
         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
a69c70e1
 
dd16a0d8
         if (ctx->audio_device_index >= [devices count]) {
             av_log(ctx, AV_LOG_ERROR, "Invalid audio device index\n");
a69c70e1
             goto fail;
         }
dd16a0d8
 
         audio_device = [devices objectAtIndex:ctx->audio_device_index];
     } else if (ctx->audio_filename &&
20453342
                strncmp(ctx->audio_filename, "none", 4)) {
         if (!strncmp(ctx->audio_filename, "default", 7)) {
             audio_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
         } else {
dd16a0d8
         NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio];
 
         for (AVCaptureDevice *device in devices) {
             if (!strncmp(ctx->audio_filename, [[device localizedName] UTF8String], strlen(ctx->audio_filename))) {
                 audio_device = device;
                 break;
             }
         }
20453342
         }
dd16a0d8
 
         if (!audio_device) {
             av_log(ctx, AV_LOG_ERROR, "Audio device not found\n");
              goto fail;
         }
a69c70e1
     }
 
dd16a0d8
     // Video nor Audio capture device not found, looking for AVMediaTypeVideo/Audio
     if (!video_device && !audio_device) {
         av_log(s, AV_LOG_ERROR, "No AV capture device found\n");
         goto fail;
     }
 
     if (video_device) {
a6555f88
         if (ctx->video_device_index < ctx->num_video_devices) {
             av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
         } else {
             av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device description] UTF8String]);
         }
dd16a0d8
     }
     if (audio_device) {
         av_log(s, AV_LOG_DEBUG, "audio device '%s' opened\n", [[audio_device localizedName] UTF8String]);
     }
a69c70e1
 
     // Initialize capture session
     ctx->capture_session = [[AVCaptureSession alloc] init];
 
dd16a0d8
     if (video_device && add_video_device(s, video_device)) {
a69c70e1
         goto fail;
     }
dd16a0d8
     if (audio_device && add_audio_device(s, audio_device)) {
     }
a69c70e1
 
     [ctx->capture_session startRunning];
 
573a77a1
     /* Unlock device configuration only after the session is started so it
      * does not reset the capture formats */
     if (!capture_screen) {
         [video_device unlockForConfiguration];
     }
 
dd16a0d8
     if (video_device && get_video_config(s)) {
         goto fail;
     }
 
     // set audio stream
     if (audio_device && get_audio_config(s)) {
a69c70e1
         goto fail;
     }
 
d2417061
     [pool release];
     return 0;
 
 fail:
     [pool release];
     destroy_context(ctx);
     return AVERROR(EIO);
 }
 
 static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     AVFContext* ctx = (AVFContext*)s->priv_data;
 
     do {
87b3c6e2
         CVImageBufferRef image_buffer;
d2417061
         lock_frames(ctx);
 
87b3c6e2
         image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
d2417061
 
         if (ctx->current_frame != nil) {
87b3c6e2
             void *data;
d2417061
             if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
                 return AVERROR(EIO);
             }
 
cf16b459
             CMItemCount count;
             CMSampleTimingInfo timing_info;
 
             if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_frame, 1, &timing_info, &count) == noErr) {
                 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
                 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
             }
 
92827e18
             pkt->stream_index  = ctx->video_stream_index;
d2417061
             pkt->flags        |= AV_PKT_FLAG_KEY;
 
             CVPixelBufferLockBaseAddress(image_buffer, 0);
 
87b3c6e2
             data = CVPixelBufferGetBaseAddress(image_buffer);
d2417061
             memcpy(pkt->data, data, pkt->size);
 
             CVPixelBufferUnlockBaseAddress(image_buffer, 0);
             CFRelease(ctx->current_frame);
             ctx->current_frame = nil;
dd16a0d8
         } else if (ctx->current_audio_frame != nil) {
             CMBlockBufferRef block_buffer = CMSampleBufferGetDataBuffer(ctx->current_audio_frame);
             int block_buffer_size         = CMBlockBufferGetDataLength(block_buffer);
 
             if (!block_buffer || !block_buffer_size) {
                 return AVERROR(EIO);
             }
 
             if (ctx->audio_non_interleaved && block_buffer_size > ctx->audio_buffer_size) {
                 return AVERROR_BUFFER_TOO_SMALL;
             }
 
             if (av_new_packet(pkt, block_buffer_size) < 0) {
                 return AVERROR(EIO);
             }
 
cf16b459
             CMItemCount count;
             CMSampleTimingInfo timing_info;
 
             if (CMSampleBufferGetOutputSampleTimingInfoArray(ctx->current_audio_frame, 1, &timing_info, &count) == noErr) {
                 AVRational timebase_q = av_make_q(1, timing_info.presentationTimeStamp.timescale);
                 pkt->pts = pkt->dts = av_rescale_q(timing_info.presentationTimeStamp.value, timebase_q, avf_time_base_q);
             }
dd16a0d8
 
             pkt->stream_index  = ctx->audio_stream_index;
             pkt->flags        |= AV_PKT_FLAG_KEY;
 
             if (ctx->audio_non_interleaved) {
87b3c6e2
                 int sample, c, shift, num_samples;
dd16a0d8
 
                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, ctx->audio_buffer);
                 if (ret != kCMBlockBufferNoErr) {
                     return AVERROR(EIO);
                 }
 
87b3c6e2
                 num_samples = pkt->size / (ctx->audio_channels * (ctx->audio_bits_per_sample >> 3));
dd16a0d8
 
                 // transform decoded frame into output format
                 #define INTERLEAVE_OUTPUT(bps)                                         \
                 {                                                                      \
                     int##bps##_t **src;                                                \
                     int##bps##_t *dest;                                                \
                     src = av_malloc(ctx->audio_channels * sizeof(int##bps##_t*));      \
                     if (!src) return AVERROR(EIO);                                     \
                     for (c = 0; c < ctx->audio_channels; c++) {                        \
                         src[c] = ((int##bps##_t*)ctx->audio_buffer) + c * num_samples; \
                     }                                                                  \
                     dest  = (int##bps##_t*)pkt->data;                                  \
                     shift = bps - ctx->audio_bits_per_sample;                          \
                     for (sample = 0; sample < num_samples; sample++)                   \
                         for (c = 0; c < ctx->audio_channels; c++)                      \
                             *dest++ = src[c][sample] << shift;                         \
                     av_freep(&src);                                                    \
                 }
 
                 if (ctx->audio_bits_per_sample <= 16) {
                     INTERLEAVE_OUTPUT(16)
                 } else {
                     INTERLEAVE_OUTPUT(32)
                 }
             } else {
                 OSStatus ret = CMBlockBufferCopyDataBytes(block_buffer, 0, pkt->size, pkt->data);
                 if (ret != kCMBlockBufferNoErr) {
                     return AVERROR(EIO);
                 }
             }
 
             CFRelease(ctx->current_audio_frame);
             ctx->current_audio_frame = nil;
d2417061
         } else {
             pkt->data = NULL;
             pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
         }
 
         unlock_frames(ctx);
     } while (!pkt->data);
 
     return 0;
 }
 
 static int avf_close(AVFormatContext *s)
 {
     AVFContext* ctx = (AVFContext*)s->priv_data;
     destroy_context(ctx);
     return 0;
 }
 
 static const AVOption options[] = {
     { "list_devices", "list available devices", offsetof(AVFContext, list_devices), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
     { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
     { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_devices" },
     { "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 },
dd16a0d8
     { "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 },
ffe6ecc4
     { "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},
573a77a1
     { "framerate", "set frame rate", offsetof(AVFContext, framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "ntsc"}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
     { "video_size", "set video size", offsetof(AVFContext, width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
c908cae7
     { "capture_cursor", "capture the screen cursor", offsetof(AVFContext, capture_cursor), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM },
021b0237
     { "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 },
 
d2417061
     { NULL },
 };
 
 static const AVClass avf_class = {
     .class_name = "AVFoundation input device",
     .item_name  = av_default_item_name,
     .option     = options,
     .version    = LIBAVUTIL_VERSION_INT,
86b7821e
     .category   = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
d2417061
 };
 
 AVInputFormat ff_avfoundation_demuxer = {
     .name           = "avfoundation",
     .long_name      = NULL_IF_CONFIG_SMALL("AVFoundation input device"),
     .priv_data_size = sizeof(AVFContext),
     .read_header    = avf_read_header,
     .read_packet    = avf_read_packet,
     .read_close     = avf_close,
     .flags          = AVFMT_NOFILE,
     .priv_class     = &avf_class,
 };