Skip to content
Snippets Groups Projects
Commit 762ce5d1 authored by Alexandre Lision's avatar Alexandre Lision Committed by gerrit2
Browse files

video: use ffmpeg on OSX

Switch to ffmpeg for video processing on OSX.
FFmpeg provides hardware acceleration for video decoding

Change-Id: Ic1136ac7c4f4917c1250a4ea732775c47a6e6c39
parent bd90c365
No related branches found
No related tags found
No related merge requests found
From 89c14d7f3ff21ad53db6e4b3a87edfd8c5d99422 Mon Sep 17 00:00:00 2001
From: Thilo Borgmann <thilo.borgmann@mail.de>
Date: Wed, 9 Dec 2015 12:41:18 +0100
Subject: [PATCH 1/2] lavd: add avfcapture device.
This device is copied from lavd/avfoundation with dropped support for audio and screen capturing.
This device is Apple ARC (automatic reference counting) compatible.
---
configure | 5 +
libavdevice/Makefile | 3 +
libavdevice/alldevices.c | 1 +
libavdevice/avfcapture.m | 719 +++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 728 insertions(+)
create mode 100644 libavdevice/avfcapture.m
diff --git a/configure b/configure
index a30d831..83c4e7e 100755
--- a/configure
+++ b/configure
@@ -2692,6 +2692,8 @@ alsa_indev_deps="alsa_asoundlib_h snd_pcm_htimestamp"
alsa_outdev_deps="alsa_asoundlib_h"
avfoundation_indev_extralibs="-framework CoreVideo -framework Foundation -framework AVFoundation -framework CoreMedia"
avfoundation_indev_select="avfoundation"
+avfcapture_indev_extralibs="-fobjc-arc -framework CoreVideo -framework Foundation -framework AVFoundation -framework CoreMedia"
+avfcapture_indev_select="avfcapture"
bktr_indev_deps_any="dev_bktr_ioctl_bt848_h machine_ioctl_bt848_h dev_video_bktr_ioctl_bt848_h dev_ic_bt8xx_h"
caca_outdev_deps="libcaca"
decklink_outdev_deps="decklink pthreads"
@@ -5328,6 +5330,9 @@ done
enabled avfoundation_indev && { check_header_oc AVFoundation/AVFoundation.h || disable avfoundation_indev; }
enabled avfoundation_indev && { check_lib2 CoreGraphics/CoreGraphics.h CGGetActiveDisplayList -framework CoreGraphics ||
check_lib2 ApplicationServices/ApplicationServices.h CGGetActiveDisplayList -framework ApplicationServices; }
+enabled avfcapture_indev && { check_header_objcc AVFoundation/AVFoundation.h || disable avfcapture_indev; }
+enabled avfcapture_indev && { check_lib2 CoreGraphics/CoreGraphics.h CGGetActiveDisplayList -framework CoreGraphics ||
+ check_lib2 ApplicationServices/ApplicationServices.h CGGetActiveDisplayList -framework ApplicationServices; }
enabled avisynth && { { check_lib2 "windows.h" LoadLibrary; } ||
{ check_lib2 "dlfcn.h" dlopen -ldl; } ||
die "ERROR: LoadLibrary/dlopen not found for avisynth"; }
diff --git a/libavdevice/Makefile b/libavdevice/Makefile
index f57ec0b..f25afb4 100644
--- a/libavdevice/Makefile
+++ b/libavdevice/Makefile
@@ -9,10 +9,13 @@ OBJS = alldevices.o \
avdevice.o \
utils.o \
+$(SUBDIR)avfoundation2.o: CFLAGS += -fobjc-arc
+
# input/output devices
OBJS-$(CONFIG_ALSA_INDEV) += alsa_dec.o alsa.o timefilter.o
OBJS-$(CONFIG_ALSA_OUTDEV) += alsa_enc.o alsa.o
OBJS-$(CONFIG_AVFOUNDATION_INDEV) += avfoundation.o
+OBJS-$(CONFIG_AVFCAPTURE_INDEV) += avfcapture.o
OBJS-$(CONFIG_BKTR_INDEV) += bktr.o
OBJS-$(CONFIG_CACA_OUTDEV) += caca.o
OBJS-$(CONFIG_DECKLINK_OUTDEV) += decklink_enc.o decklink_enc_c.o decklink_common.o
diff --git a/libavdevice/alldevices.c b/libavdevice/alldevices.c
index 26aecf2..5eef252 100644
--- a/libavdevice/alldevices.c
+++ b/libavdevice/alldevices.c
@@ -48,6 +48,7 @@ void avdevice_register_all(void)
/* devices */
REGISTER_INOUTDEV(ALSA, alsa);
REGISTER_INDEV (AVFOUNDATION, avfoundation);
+ REGISTER_INDEV (AVFCAPTURE, avfcapture);
REGISTER_INDEV (BKTR, bktr);
REGISTER_OUTDEV (CACA, caca);
REGISTER_INOUTDEV(DECKLINK, decklink);
diff --git a/libavdevice/avfcapture.m b/libavdevice/avfcapture.m
new file mode 100644
index 0000000..5ee2e0f
--- /dev/null
+++ b/libavdevice/avfcapture.m
@@ -0,0 +1,719 @@
+/*
+ * AVFcapture input device
+ * Copyright (c) 2015 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
+ * AVFcapture input device
+ * @author Thilo Borgmann <thilo.borgmann@mail.de>
+ */
+
+#import <AVFoundation/AVFoundation.h>
+#import <ObjC/runtime.h>
+#include <pthread.h>
+
+#include "libavutil/pixdesc.h"
+#include "libavutil/opt.h"
+#include "libavutil/avstring.h"
+#include "libavformat/internal.h"
+#include "libavutil/internal.h"
+#include "libavutil/parseutils.h"
+#include "libavutil/time.h"
+#include "avdevice.h"
+
+static const int avf_time_base = 1000000;
+
+static const AVRational avf_time_base_q = {
+ .num = 1,
+ .den = avf_time_base
+};
+
+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 },
+#if !TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
+ { AV_PIX_FMT_GRAY8, kCVPixelFormatType_OneComponent8 },
+#endif
+ { AV_PIX_FMT_NONE, 0 }
+};
+
+typedef struct
+{
+ AVClass *class;
+
+ int frames_captured;
+ int64_t first_pts;
+ pthread_mutex_t frame_lock;
+ pthread_cond_t frame_wait_cond;
+ CFTypeRef avf_delegate; // AVFFrameReceiver2
+
+ AVRational framerate;
+ int width, height;
+
+ int list_devices;
+ int list_pixel_formats;
+ int list_device_modes;
+ int video_device_index;
+ int video_stream_index;
+
+ char *video_filename;
+
+ int num_video_devices;
+
+ enum AVPixelFormat pixel_format;
+
+ CFTypeRef capture_session; // AVCaptureSession*
+ CFTypeRef video_output; // AVCaptureVideoDataOutput*
+ CMSampleBufferRef current_frame;
+} 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 AVFFrameReceiver2 : NSObject
+{
+ AVFContext *_context;
+}
+
+- (id)initWithContext:(AVFContext*)context;
+
+- (void) captureOutput:(AVCaptureOutput*)captureOutput
+ didOutputSampleBuffer:(CMSampleBufferRef)videoFrame
+ fromConnection:(AVCaptureConnection*)connection;
+
+@end
+
+@implementation AVFFrameReceiver2
+
+- (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 != NULL) {
+ CFRelease(_context->current_frame);
+ }
+
+ _context->current_frame = (CMSampleBufferRef)CFRetain(videoFrame);
+
+ pthread_cond_signal(&_context->frame_wait_cond);
+
+ unlock_frames(_context);
+
+ ++_context->frames_captured;
+}
+
+@end
+
+static struct AVFPixelFormatSpec pxl_fmt_from_avf_id(OSType avf_id)
+{
+ struct AVFPixelFormatSpec ret = {AV_PIX_FMT_NONE, 0};
+ int i;
+
+ for (i = 0; avf_pixel_formats[i].ff_id != AV_PIX_FMT_NONE; i++) {
+ if (avf_id == avf_pixel_formats[i].avf_id) {
+ return avf_pixel_formats[i];
+ }
+ }
+
+ return ret;
+}
+
+static void list_devices(AVFormatContext *s, NSString *prefix, NSArray *devices)
+{
+ av_log(s, AV_LOG_INFO, "%s\n", [prefix UTF8String]);
+
+ int index = 0;
+ for (AVCaptureDevice *device in devices) {
+ const char *name = [[device localizedName] UTF8String];
+ const char *uid = [[device uniqueID] UTF8String];
+ index = [devices indexOfObject:device];
+ av_log(s, AV_LOG_INFO, "[%d] %s: %s\n", index, uid, name);
+
+ if (av_log_get_level() >= AV_LOG_VERBOSE) {
+ for (AVCaptureDeviceFormat *format in device.formats) {
+ av_log(s, AV_LOG_VERBOSE, "\t%s\n",
+ [[NSString stringWithFormat: @"%@", format] UTF8String]);
+ }
+ }
+ index++;
+ }
+}
+
+static void list_pixel_formats(AVFormatContext *s, NSString *prefix, NSArray *formats)
+{
+ av_log(s, AV_LOG_INFO, "%s\n", [prefix UTF8String]);
+
+ for (NSNumber *format in formats) {
+ struct AVFPixelFormatSpec fmt = pxl_fmt_from_avf_id([format intValue]);
+ if (fmt.ff_id != AV_PIX_FMT_NONE) {
+ av_log(s, AV_LOG_INFO, "\t%s\n", av_get_pix_fmt_name(fmt.ff_id));
+ }
+ }
+}
+
+static void list_device_modes(AVFormatContext *s, AVCaptureDevice *video_device)
+{
+ av_log(s, AV_LOG_INFO, "Supported modes for device \"%s\":\n", [[video_device localizedName] UTF8String]);
+
+ for (AVCaptureDeviceFormat *format in [video_device formats]) {
+ CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription);
+
+ for (AVFrameRateRange *range in format.videoSupportedFrameRateRanges) {
+ double min_framerate;
+ double max_framerate;
+
+ [[range valueForKey:@"minFrameRate"] getValue:&min_framerate];
+ [[range valueForKey:@"maxFrameRate"] getValue:&max_framerate];
+ av_log(s, AV_LOG_INFO, "\t%dx%d@[%f %f]fps\n",
+ dimensions.width, dimensions.height,
+ min_framerate, max_framerate);
+ }
+ }
+}
+
+static void destroy_context(AVFContext *ctx)
+{
+#define SaveCFRelease(ptr) { \
+ if (ptr) { \
+ CFRelease(ptr); \
+ ptr = NULL; \
+ } \
+}
+ if (ctx->capture_session) {
+ [(__bridge AVCaptureSession*)ctx->capture_session stopRunning];
+ }
+
+ SaveCFRelease(ctx->capture_session);
+ SaveCFRelease(ctx->video_output);
+ SaveCFRelease(ctx->avf_delegate);
+ SaveCFRelease(ctx->current_frame);
+
+ pthread_mutex_destroy(&ctx->frame_lock);
+ pthread_cond_destroy(&ctx->frame_wait_cond);
+#undef SaveRelease
+}
+
+/**
+ * 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);
+ AVFrameRateRange *selected_range = NULL;
+ AVCaptureDeviceFormat *selected_format = NULL;
+ double epsilon = 0.0001;
+
+ for (AVCaptureDeviceFormat *format in [video_device formats]) {
+ CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(format.formatDescription);
+
+ if ((ctx->width == 0 && ctx->height == 0) ||
+ (dimensions.width == ctx->width && dimensions.height == ctx->height)) {
+ selected_format = format;
+
+ for (AVFrameRateRange *range in format.videoSupportedFrameRateRanges) {
+ if (range.minFrameRate <= (framerate + epsilon) &&
+ range.maxFrameRate >= (framerate - epsilon)) {
+ selected_range = range;
+ ctx->width = dimensions.width;
+ ctx->height = dimensions.height;
+ 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);
+ return AVERROR(EINVAL);
+ } else {
+ av_log(s, AV_LOG_DEBUG, "Setting video size to %dx%d\n",
+ ctx->width, ctx->height);
+ }
+
+ if (!selected_range) {
+ av_log(s, AV_LOG_ERROR, "Selected framerate (%f) is not supported by the device\n",
+ framerate);
+ return AVERROR(EINVAL);
+ } else {
+ av_log(s, AV_LOG_INFO, "Setting framerate to %f\n",
+ framerate);
+ }
+
+ if ([video_device lockForConfiguration:NULL] == YES) {
+ [video_device setActiveFormat : selected_format];
+ if (selected_range.minFrameRate == selected_range.maxFrameRate) {
+ //CMTimeMake(int64_t value, int32_t timescale) does not allow to use a Float64 as a timescale
+ //Some camera have extremely precise rate values and rounding them does not work
+ // if a range support only one value, use this value instead of the passed framerate
+ //(which may have been round up and will cause failure)
+ [video_device setActiveVideoMinFrameDuration : selected_range.minFrameDuration];
+ [video_device setActiveVideoMaxFrameDuration : selected_range.maxFrameDuration];
+ } else {
+ [video_device setActiveVideoMinFrameDuration : CMTimeMake(1, framerate)];
+ [video_device setActiveVideoMaxFrameDuration : CMTimeMake(1, framerate)];
+ }
+ } else {
+ av_log(s, AV_LOG_ERROR, "Could not lock device for configuration");
+ return AVERROR(EIO);
+ }
+
+ return 0;
+}
+
+static AVCaptureDevice* get_video_device(AVFormatContext *s, NSArray *devices)
+{
+ AVFContext *ctx = (AVFContext*)s->priv_data;
+
+ ctx->video_filename = av_strdup(s->filename);
+
+ // getting video device by filename
+ if (ctx->video_filename) {
+ if (!strncmp(ctx->video_filename, "default", 7)) {
+ return [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
+ } else if (strlen(ctx->video_filename)) {
+ // getting video device by localized name
+ for (AVCaptureDevice *device in devices) {
+ if (!strncmp(ctx->video_filename, [[device localizedName] UTF8String], strlen(ctx->video_filename))) {
+ return device;
+ }
+ }
+ // getting video device by uinique ID
+ for (AVCaptureDevice *device in devices) {
+ if (!strncmp(ctx->video_filename, [[device uniqueID] UTF8String], strlen(ctx->video_filename))) {
+ return device;
+ }
+ }
+ }
+ }
+
+ // check for device index given in filename
+ if (ctx->video_device_index == -1 && ctx->video_filename) {
+ sscanf(ctx->video_filename, "%d", &ctx->video_device_index);
+ }
+
+ // getting video device by index
+ if (ctx->video_device_index >= 0) {
+ if (ctx->video_device_index < ctx->num_video_devices) {
+ return [devices objectAtIndex:ctx->video_device_index];
+ } else {
+ av_log(s, AV_LOG_ERROR, "Invalid device index\n");
+ }
+ }
+
+ av_log(s, AV_LOG_ERROR, "Video device not found\n");
+
+ return NULL;
+}
+
+static int add_video_input(AVFormatContext *s, AVCaptureDevice *video_device)
+{
+ AVFContext *ctx = (AVFContext*)s->priv_data;
+ AVCaptureSession *capture_session = (__bridge AVCaptureSession*)ctx->capture_session;
+ AVCaptureInput *capture_input = NULL;
+ NSError *error = NULL;
+ int ret;
+
+ // Create input
+ capture_input = (AVCaptureInput*) [AVCaptureDeviceInput deviceInputWithDevice:video_device error:&error];
+
+ if (!capture_input) {
+ av_log(s, AV_LOG_ERROR, "Failed to create AV capture input device: %s\n",
+ [[error localizedDescription] UTF8String]);
+ return 1;
+ }
+
+ // Configure device framerate and video size
+ @try {
+ ret = configure_video_device(s, video_device);
+ if (ret == AVERROR(EINVAL)) {
+ list_device_modes(s, video_device);
+ }
+ if (ret < 0) {
+ return ret;
+ }
+ } @catch (NSException *exception) {
+ if (![[exception name] isEqualToString:NSUndefinedKeyException]) {
+ av_log (s, AV_LOG_ERROR, "An error occurred: %s", [exception.reason UTF8String]);
+ return AVERROR_EXTERNAL;
+ }
+ }
+
+ // Attach input to capture session
+ if ([capture_session canAddInput:capture_input]) {
+ [capture_session addInput:capture_input];
+ } else {
+ av_log(s, AV_LOG_ERROR, "can't add video input to capture session\n");
+ return 1;
+ }
+
+ return 0;
+}
+
+static int add_video_output(AVFormatContext *s)
+{
+ AVFContext *ctx = (AVFContext*)s->priv_data;
+ struct AVFPixelFormatSpec pxl_fmt_spec;
+ NSNumber *pixel_format;
+ NSDictionary *capture_dict;
+ dispatch_queue_t queue;
+
+ AVCaptureSession *capture_session = (__bridge AVCaptureSession*)ctx->capture_session;
+ AVCaptureVideoDataOutput *video_output = NULL;
+
+ // creating output
+ ctx->video_output = CFBridgingRetain([[AVCaptureVideoDataOutput alloc] init]);
+ video_output = (__bridge AVCaptureVideoDataOutput*)ctx->video_output;
+
+ if (!video_output) {
+ av_log(s, AV_LOG_ERROR, "Failed to init AV video output\n");
+ return 1;
+ }
+
+ // 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 AVFcapture
+ if (pxl_fmt_spec.ff_id == AV_PIX_FMT_NONE) {
+ av_log(s, AV_LOG_ERROR, "Selected pixel format (%s) is not supported by AVFcapture.\n",
+ av_get_pix_fmt_name(pxl_fmt_spec.ff_id));
+ return 1;
+ }
+
+ // check if the pixel format is available for this output
+ // if not, try to detect a valid format for overriding
+ if ([[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));
+
+ // list available formats
+ NSArray *formats = [video_output availableVideoCVPixelFormatTypes];
+ list_pixel_formats(s, @"Supported pixel formats:", formats);
+
+ // search for a valid format for overriding user choice
+ pxl_fmt_spec.ff_id = AV_PIX_FMT_NONE;
+ for (NSNumber *format in formats) {
+ struct AVFPixelFormatSpec fmt = pxl_fmt_from_avf_id([format intValue]);
+ if (fmt.ff_id != AV_PIX_FMT_NONE) {
+ pxl_fmt_spec = fmt;
+ break;
+ }
+ }
+
+ // 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) {
+ return 1;
+ } 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));
+ }
+ }
+
+ // set final pixel format for the output
+ ctx->pixel_format = pxl_fmt_spec.ff_id;
+ pixel_format = [NSNumber numberWithUnsignedInt:pxl_fmt_spec.avf_id];
+ capture_dict = [NSDictionary dictionaryWithObject:pixel_format
+ forKey:(id)kCVPixelBufferPixelFormatTypeKey];
+
+ [video_output setVideoSettings:capture_dict];
+ [video_output setAlwaysDiscardsLateVideoFrames:YES];
+
+ // create delegate instance and dispatch queue
+ ctx->avf_delegate = CFBridgingRetain([[AVFFrameReceiver2 alloc] initWithContext:ctx]);
+
+ queue = dispatch_queue_create("avf2_queue", NULL);
+ [video_output setSampleBufferDelegate:(__bridge id)ctx->avf_delegate queue:queue];
+
+ // attaching output to capture session
+ if ([capture_session canAddOutput:video_output]) {
+ [capture_session addOutput:video_output];
+ } else {
+ av_log(s, AV_LOG_ERROR, "can't add video output to capture session\n");
+ return 1;
+ }
+
+ return 0;
+}
+
+static int get_video_config(AVFormatContext *s)
+{
+ AVFContext *ctx = (AVFContext*)s->priv_data;
+
+ AVStream *stream = avformat_new_stream(s, NULL);
+
+ CVImageBufferRef image_buffer;
+ CGSize image_buffer_size;
+
+ if (!stream) {
+ return 1;
+ }
+
+ // Take stream info from the first frame.
+ while (ctx->frames_captured < 1) {
+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
+ }
+
+ lock_frames(ctx);
+
+ ctx->video_stream_index = stream->index;
+
+ avpriv_set_pts_info(stream, 64, 1, avf_time_base);
+
+ image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
+ image_buffer_size = CVImageBufferGetEncodedSize(image_buffer);
+
+ 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;
+ stream->codec->pix_fmt = ctx->pixel_format;
+
+ CFRelease(ctx->current_frame);
+ ctx->current_frame = NULL;
+
+ unlock_frames(ctx);
+ return 0;
+}
+
+static int avf_read_header(AVFormatContext *s)
+{
+#define FAIL { \
+ destroy_context(ctx); \
+ return AVERROR(EIO); \
+}
+ AVFContext *ctx = (AVFContext*)s->priv_data;
+
+ AVCaptureDevice *video_device = NULL;
+
+ // Find capture device
+ NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
+ ctx->num_video_devices = [devices count];
+ ctx->first_pts = av_gettime();
+
+ pthread_mutex_init(&ctx->frame_lock, NULL);
+ pthread_cond_init(&ctx->frame_wait_cond, NULL);
+
+ // List devices if requested
+ if (ctx->list_devices) {
+ list_devices(s, @"AVFcapture video devices:", devices);
+ FAIL;
+ }
+
+ // List pixel formats if requested
+ if (ctx->list_pixel_formats) {
+ AVCaptureVideoDataOutput *video_output = [[AVCaptureVideoDataOutput alloc] init];
+ NSArray *formats = [video_output availableVideoCVPixelFormatTypes];
+ list_pixel_formats(s, @"AVFcapture pixel formats:", formats);
+ FAIL;
+ }
+
+ // Select video device by index, localized name or unique ID
+ video_device = get_video_device(s, devices);
+
+ if (!video_device) {
+ FAIL;
+ }
+
+ av_log(s, AV_LOG_DEBUG, "'%s' opened\n", [[video_device localizedName] UTF8String]);
+
+ // List device modes if requested
+ if (ctx->list_device_modes) {
+ list_device_modes(s, video_device);
+ FAIL;
+ }
+
+ // Initialize capture session
+ ctx->capture_session = CFBridgingRetain([[AVCaptureSession alloc] init]);
+
+ // Adding video input to capture session
+ if (add_video_input(s, video_device)) {
+ FAIL;
+ }
+
+ // Adding video output to capture session
+ if (add_video_output(s)) {
+ FAIL;
+ }
+
+ // Start the capture session
+ [(__bridge AVCaptureSession*)ctx->capture_session startRunning];
+
+ // Unlock device configuration only after the session is started so it
+ // does not reset the capture formats
+ [video_device unlockForConfiguration];
+
+ // Get the final video device configuration by run-time approach
+ if (get_video_config(s)) {
+ FAIL;
+ }
+
+#undef FAIL
+
+ return 0;
+}
+
+static int avf_read_packet(AVFormatContext *s, AVPacket *pkt)
+{
+ AVFContext *ctx = (AVFContext*)s->priv_data;
+
+ do {
+ CVImageBufferRef image_buffer;
+ lock_frames(ctx);
+
+ image_buffer = CMSampleBufferGetImageBuffer(ctx->current_frame);
+
+ if (ctx->current_frame != NULL) {
+ void *data;
+ if (av_new_packet(pkt, (int)CVPixelBufferGetDataSize(image_buffer)) < 0) {
+ return AVERROR(EIO);
+ }
+
+ 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);
+ }
+
+ pkt->stream_index = ctx->video_stream_index;
+ pkt->flags |= AV_PKT_FLAG_KEY;
+
+ CVPixelBufferLockBaseAddress(image_buffer, 0);
+
+ data = CVPixelBufferGetBaseAddress(image_buffer);
+ memcpy(pkt->data, data, pkt->size);
+
+ CVPixelBufferUnlockBaseAddress(image_buffer, 0);
+ CFRelease(ctx->current_frame);
+ ctx->current_frame = NULL;
+ } 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" },
+ { "list_pixel_formats", "list available formats", offsetof(AVFContext, list_pixel_formats), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_pixel_formats" },
+ { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_pixel_formats" },
+ { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_pixel_formats" },
+ { "list_device_modes", "list available modes of a device", offsetof(AVFContext, list_device_modes), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, AV_OPT_FLAG_DECODING_PARAM, "list_device_modes" },
+ { "true", "", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_device_modes" },
+ { "false", "", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM, "list_device_modes" },
+ { "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 },
+ { "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},
+ { "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 },
+ { NULL },
+};
+
+static const AVClass avf_class = {
+ .class_name = "AVFcapture input device",
+ .item_name = av_default_item_name,
+ .option = options,
+ .version = LIBAVUTIL_VERSION_INT,
+ .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
+};
+
+AVInputFormat ff_avfcapture_demuxer = {
+ .name = "avfcapture",
+ .long_name = NULL_IF_CONFIG_SMALL("AVFcapture 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,
+};
--
2.8.2
This diff is collapsed.
......@@ -86,6 +86,8 @@ FFMPEGCONF += \
--enable-encoder=tiff \
--enable-decoder=tiff
DEPS_ffmpeg = iconv zlib x264 vpx opus speex $(DEPS_vpx)
ifdef HAVE_WIN32
FFMPEGCONF += \
--enable-indev=dshow \
......@@ -192,6 +194,8 @@ ifdef HAVE_IOS
endif
ifdef HAVE_MACOSX
$(APPLY) $(SRC)/ffmpeg/clock_gettime.patch
$(APPLY) $(SRC)/ffmpeg/0004-add-avfcapture-device.patch
$(APPLY) $(SRC)/ffmpeg/0005-add-avfgrab-device.patch
endif
$(MOVE)
......
......@@ -96,8 +96,8 @@ VideoDeviceImpl::getDeviceParams() const
{
DeviceParams params;
params.name = [[avDevice_ localizedName] UTF8String];
params.input = "[" + device + "]";
params.format = "avfoundation";
params.input = device;
params.format = "avfcapture";
params.width = current_size_.first;
params.height = current_size_.second;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment