[FFmpeg-devel] iSight camera support

Stefano Sabatini stefasab at gmail.com
Thu Oct 31 09:02:37 CET 2013


On date Tuesday 2013-10-29 22:53:11 -0400, Vadim Kalinsky encoded:
> 
> On 2013-10-29, at 7:26 PM, Lukasz M <lukasz.m.luki at gmail.com> wrote:
> 
> Thanks for your comments, Lukasz
> 
> > On 28 October 2013 21:21, Vadim Kalinsky <vadim at kalinsky.ru> wrote:
> > 
> > I'm not Mac developer, but iOS and also don't know QTKit, but have few
> > remarsk after quick look
> > 
> > In general you should fix formatting and styles. It is messy.
> 
> I tried to keep Objective-C "camel case" style in Objective-C code.
> 
> > It would be easier to review when you squash patches. Last one adds new
> > line only. :)
> 
> 
> I created the patch from github pull request, seems like this feature doesn't work well there.
> 
> New patch attached.
> 

> diff --git a/common.mak b/common.mak


Please send a git format-patch patch, this way it will contain
authorship information and it will be easier to apply.

> index 6479b08..fae2a70 100644
> --- a/common.mak
> +++ b/common.mak
> @@ -49,6 +49,9 @@ COMPILE_S = $(call COMPILE,AS)
>  
>  %.o: %.cpp
>  	$(COMPILE_CXX)
> +	
> +%.o: %.m
> +	$(COMPILE_C)
>  
>  %.s: %.c
>  	$(CC) $(CPPFLAGS) $(CFLAGS) -S -o $@ $<
> diff --git a/configure b/configure
> index cb6318b..0964cd7 100755
> --- a/configure
> +++ b/configure
> @@ -249,6 +249,7 @@ External library support:
>    --enable-opencl          enable OpenCL code
>    --enable-openssl         enable openssl [no]
>    --enable-x11grab         enable X11 grabbing [no]
> +  --enable-isight          enable iSight camera support [autodetect]
>    --disable-zlib           disable zlib [autodetect]
>  
>  Advanced options (experts only):
> @@ -2129,6 +2130,8 @@ dv1394_indev_deps="dv1394"
>  dv1394_indev_select="dv_demuxer"
>  fbdev_indev_deps="linux_fb_h"
>  fbdev_outdev_deps="linux_fb_h"
> +isight_indev_extralibs="-framework QTKit -framework Foundation -framework QuartzCore"
> +isight_indev_select="isight"
>  iec61883_indev_deps="libiec61883"
>  jack_indev_deps="jack_jack_h sem_timedwait"
>  lavfi_indev_deps="avfilter"
> @@ -4228,6 +4231,7 @@ enabled avisynth          && { { check_lib2 "windows.h" LoadLibrary; } ||
>  enabled fontconfig        && require_pkg_config fontconfig "fontconfig/fontconfig.h" FcInit
>  enabled frei0r            && { check_header frei0r.h || die "ERROR: frei0r.h header not found"; }
>  enabled gnutls            && require_pkg_config gnutls gnutls/gnutls.h gnutls_global_init
> +enabled isight_indev      && { check_header QTKit/QTKit.h || disable isight_indev; }
>  enabled ladspa            && { check_header ladspa.h || die "ERROR: ladspa.h header not found"; }
>  enabled libiec61883       && require libiec61883 libiec61883/iec61883.h iec61883_cmp_connect -lraw1394 -lavc1394 -lrom1394 -liec61883
>  enabled libaacplus        && require "libaacplus >= 2.0.0" aacplus.h aacplusEncOpen -laacplus
> diff --git a/libavdevice/Makefile b/libavdevice/Makefile
> index 21ca954..eac65ff 100644
> --- a/libavdevice/Makefile
> +++ b/libavdevice/Makefile
> @@ -47,6 +47,8 @@ OBJS-$(CONFIG_VFWCAP_INDEV)              += vfwcap.o
>  OBJS-$(CONFIG_X11GRAB_INDEV)             += x11grab.o
>  OBJS-$(CONFIG_XV_OUTDEV)                 += xv.o
>  
> +OBJS-$(CONFIG_ISIGHT_INDEV)              += isight.o

Alphabetical order.

> +
>  # external libraries
>  OBJS-$(CONFIG_LIBCDIO_INDEV)             += libcdio.o
>  OBJS-$(CONFIG_LIBDC1394_INDEV)           += libdc1394.o
> diff --git a/libavdevice/alldevices.c b/libavdevice/alldevices.c
> index 5178f30..1a3a450 100644
> --- a/libavdevice/alldevices.c
> +++ b/libavdevice/alldevices.c
> @@ -50,6 +50,7 @@ void avdevice_register_all(void)
>      REGISTER_INDEV   (BKTR,             bktr);
>      REGISTER_OUTDEV  (CACA,             caca);
>      REGISTER_INDEV   (DSHOW,            dshow);
> +    REGISTER_INDEV   (ISIGHT,           isight);
>      REGISTER_INDEV   (DV1394,           dv1394);
>      REGISTER_INOUTDEV(FBDEV,            fbdev);
>      REGISTER_INDEV   (IEC61883,         iec61883);

Same here.

> diff --git a/libavdevice/isight.m b/libavdevice/isight.m
> new file mode 100644
> index 0000000..991028f
> --- /dev/null
> +++ b/libavdevice/isight.m
> @@ -0,0 +1,320 @@
> +/*
> + * iSight capture device
> + * Copyright (c) 2013 Vadim Kalinsky <vadim at kalinsky.ru>
> + *
> + * 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
> + */
> +
> +#import <QTKit/QTkit.h>
> +#include <pthread.h>
> +
> +#include "libavutil/pixdesc.h"
> +#include "libavutil/opt.h"
> +#include "libavformat/internal.h"
> +#include "libavutil/internal.h"
> +#include "libavutil/time.h"
> +#include "avdevice.h"
> +
> +const int kISightTimeBase = 100;
> +
> +const AVRational kISightTimeBase_q = {
> +    .num = 1,
> +    .den = kISightTimeBase
> +};
> +
> +typedef struct
> +{
> +    AVClass*        class;
> +    
> +    float           frame_rate;
> +    int             frames_captured;
> +    int64_t         first_pts;
> +    pthread_mutex_t frame_lock;
> +    pthread_cond_t  frame_wait_cond;
> +    id              qt_delegate;
> +    
> +    QTCaptureSession*                 capture_session;
> +    QTCaptureDecompressedVideoOutput* video_output;
> +    CVImageBufferRef                  current_frame;
> +} CaptureContext;
> +
> +
> +static void lock_frames(CaptureContext* ctx)
> +{
> +    pthread_mutex_lock(&ctx->frame_lock);
> +}
> +
> +static void unlock_frames(CaptureContext* ctx)
> +{
> +    pthread_mutex_unlock(&ctx->frame_lock);
> +}
> +
> +
> +// FrameReciever class - delegate for QTCaptureSession
> + at interface FFMPEG_FrameReceiver : NSObject
> +{
> +    CaptureContext* _context;
> +}
> +
> +- (id)initWithContext:(CaptureContext*)context;
> +
> +- (void)captureOutput:(QTCaptureOutput *)captureOutput
> +  didOutputVideoFrame:(CVImageBufferRef)videoFrame
> +     withSampleBuffer:(QTSampleBuffer *)sampleBuffer
> +       fromConnection:(QTCaptureConnection *)connection;
> +
> + at end
> +
> + at implementation FFMPEG_FrameReceiver
> +
> +- (id)initWithContext:(CaptureContext*)context
> +{
> +    if( self = [super init] )

nit: here and below, we favor if_(self = [super init]) style

> +    {
> +        _context = context;
> +    }
> +    return self;
> +}
> +
> +- (void)captureOutput:(QTCaptureOutput *)captureOutput
> +  didOutputVideoFrame:(CVImageBufferRef)videoFrame
> +     withSampleBuffer:(QTSampleBuffer *)sampleBuffer
> +       fromConnection:(QTCaptureConnection *)connection
> +{
> +    lock_frames(_context);
> +    if( _context->current_frame != nil )
> +    {
> +        CVBufferRelease(_context->current_frame);
> +    }
> +    
> +    _context->current_frame = CVBufferRetain(videoFrame);
> +    
> +    pthread_cond_signal(&_context->frame_wait_cond);
> +    
> +    unlock_frames(_context);
> +    
> +    ++_context->frames_captured;
> +}
> +
> + at end
> +
> +
> +static void destroy_context( CaptureContext* ctx )
> +{
> +    [ctx->capture_session stopRunning];
> +    
> +    [ctx->capture_session release];
> +    [ctx->video_output    release];
> +    [ctx->qt_delegate     release];
> +    
> +    ctx->capture_session = NULL;
> +    ctx->video_output    = NULL;
> +    ctx->qt_delegate     = NULL;
> +    
> +    pthread_mutex_destroy(&ctx->frame_lock);
> +    pthread_cond_destroy(&ctx->frame_wait_cond);
> +    
> +    if( ctx->current_frame )
> +        CVBufferRelease(ctx->current_frame);
> +}
> +
> +static int isight_read_header(AVFormatContext *s)
> +{
> +    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
> +    
> +    CaptureContext* ctx = (CaptureContext*)s->priv_data;
> +    
> +    ctx->current_frame   = NULL;
> +    ctx->capture_session = NULL;
> +    ctx->qt_delegate     = NULL;
> +    ctx->video_output    = NULL;
> +    ctx->frames_captured = 0;
> +    ctx->first_pts       = av_gettime();
> +    
> +    pthread_mutex_init(&ctx->frame_lock, NULL);
> +    pthread_cond_init(&ctx->frame_wait_cond, NULL);
> +
> +    // Find capture device
> +    QTCaptureDevice *video_device = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeMuxed];

Note: no need to specify a device name? What if several video devices
are available?

> +    
> +    BOOL success = [video_device open:nil];
> +    
> +    // Video capture device not found, looking for QTMediaTypeVideo
> +    if (!success) {
> +        video_device = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo];
> +        success = [video_device open:nil];
> +    }
> +    
> +    if( !success )
> +    {
> +        av_log( s, AV_LOG_ERROR, "can't find QT capture device\n" );

Nit: "Could not find ...\n"

(rationale: first character capitalized, no contractions, and we tend
to favor past tense)

> +        goto fail;
> +    }

> +    NSString* dev_display_name = [video_device localizedDisplayName];
> +    av_log( s, AV_LOG_DEBUG, "'%s' opened\n", [dev_display_name UTF8String] );
> +    
> +    // Initialize capture session
> +    ctx->capture_session = [[QTCaptureSession alloc] init];
> +    
> +    QTCaptureDeviceInput* capture_dev_input = [[[QTCaptureDeviceInput alloc] initWithDevice:video_device] autorelease];
> +    success = [ctx->capture_session addInput:capture_dev_input error:nil];
> +    if( !success )
> +    {
> +        av_log( s, AV_LOG_ERROR, "can't add QT capture device to session\n" );

Could not find...

> +        goto fail;
> +    }
> +    
> +    // Attaching output
> +    ctx->video_output = [[QTCaptureDecompressedVideoOutput alloc] init];
> +    
> +    NSDictionary *captureDictionary = [NSDictionary dictionaryWithObject:
> +                                       [NSNumber numberWithUnsignedInt:kCVPixelFormatType_24RGB]
> +                                       forKey:(id)kCVPixelBufferPixelFormatTypeKey];
> +    
> +    [ctx->video_output setPixelBufferAttributes:captureDictionary];
> +    
> +     ctx->qt_delegate = [[FFMPEG_FrameReceiver alloc] initWithContext:ctx];
> +    [ctx->video_output setDelegate:ctx->qt_delegate];
> +    [ctx->video_output setAutomaticallyDropsLateVideoFrames:YES];
> +    [ctx->video_output setMinimumVideoFrameInterval:1.0/ctx->frame_rate];
> +    
> +    success = [ctx->capture_session addOutput:ctx->video_output error:nil];
> +    
> +    if( !success )
> +    {
> +        av_log( s, AV_LOG_ERROR, "can't add video output to capture session\n" );
> +        goto fail;
> +    }
> +    
> +    
> +    [ctx->capture_session startRunning];
> +    
> +    
> +    // Take stream info from the first frame.
> +    while( ctx->frames_captured < 1 )
> +    {
> +        CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, YES);
> +    }
> +    
> +    lock_frames(ctx);
> +    
> +    size_t frame_width  = CVPixelBufferGetWidth(ctx->current_frame);
> +    size_t frame_height = CVPixelBufferGetHeight(ctx->current_frame);
> +    
> +    CVBufferRelease(ctx->current_frame);
> +    ctx->current_frame = nil;
> +    
> +    unlock_frames(ctx);
> +    
> +    AVStream* stream = avformat_new_stream(s, NULL);
> +    avpriv_set_pts_info( stream, 64, 1, kISightTimeBase );
> +    
> +    stream->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;
> +    stream->codec->codec_type = AVMEDIA_TYPE_VIDEO;
> +    stream->codec->width      = (int)frame_width;
> +    stream->codec->height     = (int)frame_height;

> +    stream->codec->pix_fmt    = PIX_FMT_RGB24;

AV_PIX_FMT_RGB24

> +    
> +    s->start_time = 0;
> +    
> +    [pool release];
> +    
> +    return 0;
> +    
> +fail:
> +    [pool release];
> +    
> +    destroy_context(ctx);
> +    
> +    return -1;

return AVERROR(EIO);

> +}
> +
> +static int isight_read_packet(AVFormatContext *s, AVPacket *pkt)
> +{
> +    CaptureContext* ctx = (CaptureContext*)s->priv_data;
> +    
> +    do
> +    {
> +        lock_frames(ctx);
> +        

> +        if( ctx->current_frame != nil )
> +        {

style:
if_(...) {
...
} else {
...
}

> +            CVPixelBufferLockBaseAddress(ctx->current_frame, 0);
> +            
> +            av_new_packet(pkt, (int)CVPixelBufferGetDataSize(ctx->current_frame));
> +            pkt->pts = pkt->dts = av_rescale_q(av_gettime() - ctx->first_pts, AV_TIME_BASE_Q, kISightTimeBase_q);
> +            pkt->stream_index = 0;
> +            pkt->flags |= AV_PKT_FLAG_KEY;
> +            
> +            void* data = CVPixelBufferGetBaseAddress(ctx->current_frame);
> +            memcpy( pkt->data, data, pkt->size );
> +                         
> +            CVPixelBufferUnlockBaseAddress(ctx->current_frame, 0);
> +            CVBufferRelease(ctx->current_frame);
> +            ctx->current_frame = nil;
> +        }
> +        else
> +        {
> +            pkt->data = NULL;
> +        }
> +        

> +        if( pkt->data == NULL )

style: we tend to prefer if (!pkt->data)

> +        {
> +            pthread_cond_wait(&ctx->frame_wait_cond, &ctx->frame_lock);
> +        }
> +        
> +        unlock_frames(ctx);
> +    }
> +    while( pkt->data == NULL );
> +    
> +    return 0;
> +}
> +
> +static int isight_close(AVFormatContext *s)
> +{
> +    CaptureContext* ctx = (CaptureContext*)s->priv_data;
> +    

> +    av_log(s, AV_LOG_DEBUG, "isight_close\n");

I think you can drop this

> +    
> +    destroy_context(ctx);
> +
> +    return 0;
> +}
> +
> +static const AVOption options[] = {
> +    { "frame_rate", "", offsetof(CaptureContext, frame_rate), AV_OPT_TYPE_FLOAT, { .dbl = 30.0 }, 0.1, 30.0, AV_OPT_FLAG_VIDEO_PARAM, NULL },

missing help ("set frame rate")

Also you should probably use AV_OPT_TYPE_VIDEO_RATE.

> +    { NULL },
> +};
> +
> +static const AVClass isight_class = {
> +    .class_name = "iSight camera",
> +    .item_name  = av_default_item_name,
> +    .option     = options,
> +    .version    = LIBAVUTIL_VERSION_INT,
> +};
> +
> +AVInputFormat ff_isight_demuxer = {
> +    .name           = "isight",
> +    .long_name      = NULL_IF_CONFIG_SMALL("Macbook/iMac embedded camera capture"),
> +    .priv_data_size = sizeof(CaptureContext),
> +    .read_header    = isight_read_header,
> +    .read_packet    = isight_read_packet,
> +    .read_close     = isight_close,
> +    .flags          = AVFMT_NOFILE,
> +    .priv_class     = &isight_class,
> +};

Do you mind adding some docs to doc/indevs.texi?

Also you could add your name to MAINTAINERS if you plan to maintain
this device.
-- 
FFmpeg = Fundamental and Friendly Multipurpose Philosofic Educated Guide


More information about the ffmpeg-devel mailing list