[FFmpeg-devel] [PATCH] hwaccel: add VideoToolbox support.

Sebastien Zwickert dilaroga at gmail.com
Sun Sep 23 15:35:09 CEST 2012


---
 Changelog                 |    1 +
 MAINTAINERS               |    1 +
 configure                 |   12 +
 libavcodec/Makefile       |    7 +
 libavcodec/allcodecs.c    |    4 +
 libavcodec/h264.c         |    1 +
 libavcodec/mpeg12.c       |    3 +
 libavcodec/mpegvideo.c    |    1 +
 libavcodec/version.h      |    2 +-
 libavcodec/videotoolbox.c |  560 +++++++++++++++++++++++++++++++++++++++++++++
 libavcodec/videotoolbox.h |  128 +++++++++++
 libavutil/pixdesc.c       |    6 +
 libavutil/pixfmt.h        |    1 +
 13 files changed, 726 insertions(+), 1 deletion(-)
 create mode 100644 libavcodec/videotoolbox.c
 create mode 100644 libavcodec/videotoolbox.h

diff --git a/Changelog b/Changelog
index e8ea679..0d8b604 100644
--- a/Changelog
+++ b/Changelog
@@ -63,6 +63,7 @@ version next:
 - Smooth Streaming live segmenter muxer
 - F4V muxer
 - sendcmd and asendcmd filters
+- OS X VideoToolbox support
 
 
 version 0.11:
diff --git a/MAINTAINERS b/MAINTAINERS
index 1860b6e..a68956b 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -257,6 +257,7 @@ Hardware acceleration:
   libstagefright.cpp                    Mohamed Naufal
   vaapi*                                Gwenole Beauchesne
   vda*                                  Sebastien Zwickert
+  videotoolbox*                         Sebastien Zwickert
   vdpau*                                Carl Eugen Hoyos
 
 
diff --git a/configure b/configure
index c001c5f..13c40a5 100755
--- a/configure
+++ b/configure
@@ -133,6 +133,7 @@ Component options:
   --enable-dxva2           enable DXVA2 code
   --enable-vaapi           enable VAAPI code [autodetect]
   --enable-vda             enable VDA code   [autodetect]
+  --enable-videotoolbox    enable VideoToolbox code [autodetect]
   --enable-vdpau           enable VDPAU code [autodetect]
 
 Individual component options:
@@ -1175,6 +1176,7 @@ CONFIG_LIST="
     vda
     vdpau
     version3
+    videotoolbox
     xmm_clobber_test
     x11grab
     zlib
@@ -1608,6 +1610,7 @@ h261_encoder_select="aandcttables mpegvideoenc"
 h263_decoder_select="error_resilience h263_parser mpegvideo"
 h263_encoder_select="aandcttables error_resilience mpegvideoenc"
 h263_vaapi_hwaccel_select="vaapi h263_decoder"
+h263_videotoolbox_hwaccel_select="videotoolbox h263_decoder"
 h263i_decoder_select="h263_decoder"
 h263p_encoder_select="h263_encoder"
 h264_crystalhd_decoder_select="crystalhd h264_mp4toannexb_bsf h264_parser"
@@ -1619,6 +1622,7 @@ h264_vda_decoder_select="vda h264_parser h264_decoder"
 h264_vda_hwaccel_deps="VideoDecodeAcceleration_VDADecoder_h pthreads"
 h264_vda_hwaccel_select="vda h264_decoder"
 h264_vdpau_decoder_select="vdpau h264_decoder"
+h264_videotoolbox_hwaccel_select="videotoolbox h264_decoder"
 huffyuv_encoder_select="huffman"
 iac_decoder_select="fft mdct sinewin"
 imc_decoder_select="fft mdct sinewin"
@@ -1653,6 +1657,7 @@ mpeg2_dxva2_hwaccel_deps="dxva2api_h"
 mpeg2_dxva2_hwaccel_select="dxva2 mpeg2video_decoder"
 mpeg2_vdpau_hwaccel_select="vdpau mpeg2video_decoder"
 mpeg2_vaapi_hwaccel_select="vaapi mpeg2video_decoder"
+mpeg2_videotoolbox_hwaccel_select="videotoolbox mpeg2video_decoder"
 mpeg2video_decoder_select="error_resilience mpegvideo"
 mpeg2video_encoder_select="aandcttables error_resilience mpegvideoenc"
 mpeg4_crystalhd_decoder_select="crystalhd"
@@ -1660,6 +1665,7 @@ mpeg4_decoder_select="h263_decoder mpeg4video_parser"
 mpeg4_encoder_select="h263_encoder"
 mpeg4_vaapi_hwaccel_select="vaapi mpeg4_decoder"
 mpeg4_vdpau_decoder_select="vdpau mpeg4_decoder"
+mpeg4_videotoolbox_hwaccel_select="videotoolbox mpeg4_decoder"
 msmpeg4_crystalhd_decoder_select="crystalhd"
 msmpeg4v1_decoder_select="h263_decoder"
 msmpeg4v1_encoder_select="h263_encoder"
@@ -1741,6 +1747,7 @@ crystalhd_deps="libcrystalhd_libcrystalhd_if_h"
 vaapi_deps="va_va_h"
 vda_deps="VideoDecodeAcceleration_VDADecoder_h pthreads"
 vdpau_deps="vdpau_vdpau_h vdpau_vdpau_x11_h"
+videotoolbox_deps="VideoToolbox_VideoToolbox_h"
 
 # parsers
 h264_parser_select="error_resilience golomb h264dsp h264pred mpegvideo"
@@ -3564,6 +3571,11 @@ if ! disabled vda; then
     fi
 fi
 
+# check for VideoToolbox header
+if ! disabled videotoolbox && check_header VideoToolbox/VideoToolbox.h; then
+    enable videotoolbox && add_extralibs -framework CoreFoundation -framework VideoToolbox -framework CoreMedia -framework QuartzCore
+fi
+
 if ! disabled w32threads && ! enabled pthreads; then
     check_func _beginthreadex && enable w32threads
 fi
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index dd881b6..820b8a2 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -11,6 +11,7 @@ HEADERS = avcodec.h                                                     \
           vda.h                                                         \
           vdpau.h                                                       \
           version.h                                                     \
+          videotoolbox.h                                                \
           xvmc.h                                                        \
 
 OBJS = allcodecs.o                                                      \
@@ -66,6 +67,7 @@ OBJS-$(CONFIG_RDFT)                    += rdft.o $(RDFT-OBJS-yes)
 OBJS-$(CONFIG_SINEWIN)                 += sinewin.o
 OBJS-$(CONFIG_VAAPI)                   += vaapi.o
 OBJS-$(CONFIG_VDPAU)                   += vdpau.o
+OBJS-$(CONFIG_VIDEOTOOLBOX)            += videotoolbox.o
 OBJS-$(CONFIG_VP3DSP)                  += vp3dsp.o
 
 # decoders/encoders/hardware accelerators
@@ -208,6 +210,7 @@ OBJS-$(CONFIG_H263_DECODER)            += h263dec.o h263.o ituh263dec.o        \
                                           mpeg4video.o mpeg4videodec.o flvdec.o\
                                           intelh263dec.o
 OBJS-$(CONFIG_H263_VAAPI_HWACCEL)      += vaapi_mpeg4.o
+OBJS-$(CONFIG_H263_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o
 OBJS-$(CONFIG_H263_ENCODER)            += mpeg4videoenc.o mpeg4video.o  \
                                           h263.o ituh263enc.o flvenc.o
 OBJS-$(CONFIG_H264_DECODER)            += h264.o                               \
@@ -218,6 +221,7 @@ OBJS-$(CONFIG_H264_DXVA2_HWACCEL)      += dxva2_h264.o
 OBJS-$(CONFIG_H264_VAAPI_HWACCEL)      += vaapi_h264.o
 OBJS-$(CONFIG_H264_VDA_HWACCEL)        += vda_h264.o
 OBJS-$(CONFIG_H264_VDA_DECODER)        += vda_h264_dec.o
+OBJS-$(CONFIG_H264_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o
 OBJS-$(CONFIG_HUFFYUV_DECODER)         += huffyuv.o
 OBJS-$(CONFIG_HUFFYUV_ENCODER)         += huffyuv.o
 OBJS-$(CONFIG_IAC_DECODER)             += imc.o
@@ -291,10 +295,12 @@ OBJS-$(CONFIG_MPEG1VIDEO_ENCODER)      += mpeg12enc.o mpeg12.o          \
                                           timecode.o
 OBJS-$(CONFIG_MPEG2_DXVA2_HWACCEL)     += dxva2_mpeg2.o
 OBJS-$(CONFIG_MPEG2_VAAPI_HWACCEL)     += vaapi_mpeg2.o
+OBJS-$(CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o
 OBJS-$(CONFIG_MPEG2VIDEO_DECODER)      += mpeg12.o mpeg12data.o
 OBJS-$(CONFIG_MPEG2VIDEO_ENCODER)      += mpeg12enc.o mpeg12.o          \
                                           timecode.o
 OBJS-$(CONFIG_MPEG4_VAAPI_HWACCEL)     += vaapi_mpeg4.o
+OBJS-$(CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o
 OBJS-$(CONFIG_MSMPEG4V1_DECODER)       += msmpeg4.o msmpeg4data.o
 OBJS-$(CONFIG_MSMPEG4V2_DECODER)       += msmpeg4.o msmpeg4data.o h263dec.o \
                                           h263.o ituh263dec.o mpeg4videodec.o
@@ -768,6 +774,7 @@ SKIPHEADERS-$(CONFIG_MPEG_XVMC_DECODER) += xvmc.h
 SKIPHEADERS-$(CONFIG_VAAPI)            += vaapi_internal.h
 SKIPHEADERS-$(CONFIG_VDA)              += vda.h
 SKIPHEADERS-$(CONFIG_VDPAU)            += vdpau.h
+SKIPHEADERS-$(CONFIG_VIDEOTOOLBOX)     += videotoolbox.h
 SKIPHEADERS-$(HAVE_OS2THREADS)         += os2threads.h
 SKIPHEADERS-$(HAVE_W32THREADS)         += w32pthreads.h
 
diff --git a/libavcodec/allcodecs.c b/libavcodec/allcodecs.c
index 8806c6a..f72aa35 100644
--- a/libavcodec/allcodecs.c
+++ b/libavcodec/allcodecs.c
@@ -56,14 +56,18 @@ void avcodec_register_all(void)
 
     /* hardware accelerators */
     REGISTER_HWACCEL (H263_VAAPI, h263_vaapi);
+    REGISTER_HWACCEL (H263_VIDEOTOOLBOX, h263_videotoolbox);
     REGISTER_HWACCEL (H264_DXVA2, h264_dxva2);
     REGISTER_HWACCEL (H264_VAAPI, h264_vaapi);
     REGISTER_HWACCEL (H264_VDA, h264_vda);
+    REGISTER_HWACCEL (H264_VIDEOTOOLBOX, h264_videotoolbox);
     REGISTER_HWACCEL (MPEG1_VDPAU, mpeg1_vdpau);
     REGISTER_HWACCEL (MPEG2_DXVA2, mpeg2_dxva2);
     REGISTER_HWACCEL (MPEG2_VAAPI, mpeg2_vaapi);
     REGISTER_HWACCEL (MPEG2_VDPAU, mpeg2_vdpau);
+    REGISTER_HWACCEL (MPEG2_VIDEOTOOLBOX, mpeg2_videotoolbox);
     REGISTER_HWACCEL (MPEG4_VAAPI, mpeg4_vaapi);
+    REGISTER_HWACCEL (MPEG4_VIDEOTOOLBOX, mpeg4_videotoolbox);
     REGISTER_HWACCEL (VC1_DXVA2, vc1_dxva2);
     REGISTER_HWACCEL (VC1_VAAPI, vc1_vaapi);
     REGISTER_HWACCEL (WMV3_DXVA2, wmv3_dxva2);
diff --git a/libavcodec/h264.c b/libavcodec/h264.c
index 713fda7..27cb80f 100644
--- a/libavcodec/h264.c
+++ b/libavcodec/h264.c
@@ -70,6 +70,7 @@ static const enum PixelFormat hwaccel_pixfmt_list_h264_jpeg_420[] = {
     PIX_FMT_DXVA2_VLD,
     PIX_FMT_VAAPI_VLD,
     PIX_FMT_VDA_VLD,
+    PIX_FMT_VIDEOTOOLBOX_VLD,
     PIX_FMT_YUVJ420P,
     PIX_FMT_NONE
 };
diff --git a/libavcodec/mpeg12.c b/libavcodec/mpeg12.c
index 1bf857e..07cd7de 100644
--- a/libavcodec/mpeg12.c
+++ b/libavcodec/mpeg12.c
@@ -1203,6 +1203,9 @@ static const enum PixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
 #if CONFIG_MPEG2_VAAPI_HWACCEL
     PIX_FMT_VAAPI_VLD,
 #endif
+#if CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL
+    PIX_FMT_VIDEOTOOLBOX_VLD,
+#endif
     PIX_FMT_YUV420P,
     PIX_FMT_NONE
 };
diff --git a/libavcodec/mpegvideo.c b/libavcodec/mpegvideo.c
index 9e1f67c..22c4cac 100644
--- a/libavcodec/mpegvideo.c
+++ b/libavcodec/mpegvideo.c
@@ -134,6 +134,7 @@ const enum PixelFormat ff_hwaccel_pixfmt_list_420[] = {
     PIX_FMT_DXVA2_VLD,
     PIX_FMT_VAAPI_VLD,
     PIX_FMT_VDA_VLD,
+    PIX_FMT_VIDEOTOOLBOX_VLD,
     PIX_FMT_YUV420P,
     PIX_FMT_NONE
 };
diff --git a/libavcodec/version.h b/libavcodec/version.h
index 7a779e6..c1d0b76 100644
--- a/libavcodec/version.h
+++ b/libavcodec/version.h
@@ -27,7 +27,7 @@
  */
 
 #define LIBAVCODEC_VERSION_MAJOR 54
-#define LIBAVCODEC_VERSION_MINOR 57
+#define LIBAVCODEC_VERSION_MINOR 58
 #define LIBAVCODEC_VERSION_MICRO 100
 
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
diff --git a/libavcodec/videotoolbox.c b/libavcodec/videotoolbox.c
new file mode 100644
index 0000000..8740f05
--- /dev/null
+++ b/libavcodec/videotoolbox.c
@@ -0,0 +1,560 @@
+/*
+ * VideoToolbox hardware acceleration
+ *
+ * copyright (c) 2012 Sebastien Zwickert
+ *
+ * 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
+ */
+
+#include "videotoolbox.h"
+#include "libavutil/avutil.h"
+#include "bytestream.h"
+#include "h264.h"
+#include "mpegvideo.h"
+
+static void videotoolbox_write_mp4_descr_length(PutByteContext *pb, int length)
+{
+    int i;
+    uint8_t b;
+
+    for (i = 3; i >= 0; i--) {
+        b = (length >> (i * 7)) & 0x7F;
+        if (i != 0)
+            b |= 0x80;
+
+        bytestream2_put_byteu(pb, b);
+    }
+}
+
+static CFDataRef videotoolbox_esds_extradata_create(AVCodecContext *avctx)
+{
+    CFDataRef data;
+    uint8_t *rw_extradata;
+    PutByteContext pb;
+    int full_size = 3 + 5 + 13 + 5 + avctx->extradata_size + 3;
+    // ES_DescrTag data + DecoderConfigDescrTag + data + DecSpecificInfoTag + size + SLConfigDescriptor
+    int config_size = 13 + 5 + avctx->extradata_size;
+    int padding = 12;
+    int s;
+
+    if (!(rw_extradata = av_mallocz(full_size + padding)))
+        return NULL;
+
+    bytestream2_init_writer(&pb, rw_extradata, full_size + padding);
+    bytestream2_put_byteu(&pb, 0);        // version
+    bytestream2_put_ne24(&pb, 0);         // flags
+
+    // elementary stream descriptor
+    bytestream2_put_byteu(&pb, 0x03);     // ES_DescrTag
+    videotoolbox_write_mp4_descr_length(&pb, full_size);
+    bytestream2_put_ne16(&pb, 0);         // esid
+    bytestream2_put_byteu(&pb, 0);        // stream priority (0-32)
+
+    // decoder configuration descriptor
+    bytestream2_put_byteu(&pb, 0x04);     // DecoderConfigDescrTag
+    videotoolbox_write_mp4_descr_length(&pb, config_size);
+    bytestream2_put_byteu(&pb, 32);       // object type indication. 32 = CODEC_ID_MPEG4
+    bytestream2_put_byteu(&pb, 0x11);     // stream type
+    bytestream2_put_ne24(&pb, 0);         // buffer size
+    bytestream2_put_ne32(&pb, 0);         // max bitrate
+    bytestream2_put_ne32(&pb, 0);         // avg bitrate
+
+    // decoder specific descriptor
+    bytestream2_put_byteu(&pb, 0x05);     ///< DecSpecificInfoTag
+    videotoolbox_write_mp4_descr_length(&pb, avctx->extradata_size);
+
+    bytestream2_put_buffer(&pb, avctx->extradata, avctx->extradata_size);
+
+    // SLConfigDescriptor
+    bytestream2_put_byteu(&pb, 0x06);     // SLConfigDescrTag
+    bytestream2_put_byteu(&pb, 0x01);     // length
+    bytestream2_put_byteu(&pb, 0x02);     //
+
+    s = bytestream2_size_p(&pb);
+
+    data = CFDataCreate(kCFAllocatorDefault, rw_extradata, s);
+
+    av_freep(&rw_extradata);
+    return data;
+}
+
+static CFDataRef videotoolbox_avcc_extradata_create(AVCodecContext *avctx)
+{
+    CFDataRef data;
+    /* Each VCL NAL in the bistream sent to the decoder
+     * is preceded by a 4 bytes length header.
+     * Change the avcC atom header if needed, to signal headers of 4 bytes. */
+    if (avctx->extradata_size >= 4 && (avctx->extradata[4] & 0x03) != 0x03) {
+        uint8_t *rw_extradata;
+
+        if (!(rw_extradata = av_malloc(avctx->extradata_size)))
+            return NULL;
+
+        memcpy(rw_extradata, avctx->extradata, avctx->extradata_size);
+
+        rw_extradata[4] |= 0x03;
+
+        data = CFDataCreate(kCFAllocatorDefault, rw_extradata, avctx->extradata_size);
+
+        av_freep(&rw_extradata);
+    } else {
+        data = CFDataCreate(kCFAllocatorDefault, avctx->extradata, avctx->extradata_size);
+    }
+
+    return data;
+}
+
+static CMSampleBufferRef videotoolbox_sample_buffer_create(CMFormatDescriptionRef fmt_desc,
+                                                           void *buffer,
+                                                           int size)
+{
+    OSStatus status;
+    CMBlockBufferRef  block_buf;
+    CMSampleBufferRef sample_buf;
+
+    block_buf  = NULL;
+    sample_buf = NULL;
+
+    status = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault,// structureAllocator
+                                                buffer,             // memoryBlock
+                                                size,               // blockLength
+                                                kCFAllocatorNull,   // blockAllocator
+                                                NULL,               // customBlockSource
+                                                0,                  // offsetToData
+                                                size,               // dataLength
+                                                0,                  // flags
+                                                &block_buf);
+
+    if (!status) {
+        status = CMSampleBufferCreate(kCFAllocatorDefault,  // allocator
+                                      block_buf,            // dataBuffer
+                                      TRUE,                 // dataReady
+                                      0,                    // makeDataReadyCallback
+                                      0,                    // makeDataReadyRefcon
+                                      fmt_desc,             // formatDescription
+                                      1,                    // numSamples
+                                      0,                    // numSampleTimingEntries
+                                      NULL,                 // sampleTimingArray
+                                      0,                    // numSampleSizeEntries
+                                      NULL,                 // sampleSizeArray
+                                      &sample_buf);
+    }
+
+    if (block_buf)
+        CFRelease(block_buf);
+
+    return sample_buf;
+}
+
+static void videotoolbox_bitstream_release(struct videotoolbox_context *vt_ctx)
+{
+    av_freep(&vt_ctx->priv_bitstream);
+    vt_ctx->priv_bitstream_size = 0;
+}
+
+static void videotoolbox_decoder_callback(void *vt_hw_ctx,
+                                          void *sourceFrameRefCon,
+                                          OSStatus status,
+                                          VTDecodeInfoFlags flags,
+                                          CVImageBufferRef image_buffer,
+                                          CMTime pts,
+                                          CMTime duration)
+{
+    struct videotoolbox_context *vt_ctx = vt_hw_ctx;
+    vt_ctx->cv_buffer = NULL;
+
+    if (!image_buffer) {
+        av_log(NULL, AV_LOG_DEBUG, "vt decoder cb: output image buffer is null\n");
+        return;
+    }
+
+    if (vt_ctx->cv_pix_fmt != CVPixelBufferGetPixelFormatType(image_buffer)) {
+        av_log(NULL, AV_LOG_DEBUG, "vt decoder cb: output pixel format error\n");
+        return;
+    }
+
+    vt_ctx->cv_buffer = CVPixelBufferRetain(image_buffer);
+}
+
+static OSStatus videotoolbox_session_decode_frame(struct videotoolbox_context *vt_ctx)
+{
+    OSStatus status;
+    CMSampleBufferRef sample_buf;
+
+    sample_buf = videotoolbox_sample_buffer_create(vt_ctx->cm_fmt_desc,
+                                                   vt_ctx->priv_bitstream,
+                                                   vt_ctx->priv_bitstream_size);
+
+    if (!sample_buf)
+        return -1;
+
+    status = VTDecompressionSessionDecodeFrame(vt_ctx->session,
+                                               sample_buf,
+                                               0,               // decodeFlags
+                                               NULL,            // sourceFrameRefCon
+                                               0);              // infoFlagsOut
+    if (status == noErr)
+        status = VTDecompressionSessionWaitForAsynchronousFrames(vt_ctx->session);
+
+    CFRelease(sample_buf);
+
+    return status;
+}
+
+static int videotoolbox_buffer_copy(struct videotoolbox_context *vt_ctx,
+                                    const uint8_t *buffer,
+                                    uint32_t size)
+{
+    av_fast_malloc(&vt_ctx->priv_bitstream,
+                   &vt_ctx->priv_allocated_size,
+                   size);
+
+    if (!vt_ctx->priv_bitstream)
+        return AVERROR(ENOMEM);
+
+    memcpy(vt_ctx->priv_bitstream, buffer, size);
+
+    vt_ctx->priv_bitstream_size = size;
+
+    return 0;
+}
+
+static int videotoolbox_h264_start_frame(AVCodecContext *avctx,
+                                         av_unused const uint8_t *buffer,
+                                         av_unused uint32_t size)
+{
+    struct videotoolbox_context *vt_ctx = avctx->hwaccel_context;
+
+    if (!vt_ctx->session)
+        return -1;
+
+    vt_ctx->priv_bitstream_size = 0;
+
+    return 0;
+}
+
+static int videotoolbox_h264_decode_slice(AVCodecContext *avctx,
+                                          const uint8_t *buffer,
+                                          uint32_t size)
+{
+    struct videotoolbox_context *vt_ctx = avctx->hwaccel_context;
+    void *tmp;
+
+    if (!vt_ctx->session)
+        return -1;
+
+    tmp = av_fast_realloc(vt_ctx->priv_bitstream,
+                          &vt_ctx->priv_allocated_size,
+                          vt_ctx->priv_bitstream_size+size+4);
+    if (!tmp)
+        return AVERROR(ENOMEM);
+
+    vt_ctx->priv_bitstream = tmp;
+
+    AV_WB32(vt_ctx->priv_bitstream + vt_ctx->priv_bitstream_size, size);
+    memcpy(vt_ctx->priv_bitstream + vt_ctx->priv_bitstream_size + 4, buffer, size);
+
+    vt_ctx->priv_bitstream_size += size + 4;
+
+    return 0;
+}
+
+static int videotoolbox_mpeg_start_frame(AVCodecContext *avctx,
+                                         const uint8_t *buffer,
+                                         uint32_t size)
+{
+    struct videotoolbox_context *vt_ctx = avctx->hwaccel_context;
+
+    if (!vt_ctx->session)
+        return -1;
+
+    return videotoolbox_buffer_copy(vt_ctx, buffer, size);
+}
+
+static int videotoolbox_mpeg_decode_slice(AVCodecContext *avctx,
+                                          const uint8_t *buffer,
+                                          uint32_t size)
+{
+    struct videotoolbox_context *vt_ctx = avctx->hwaccel_context;
+
+    if (!vt_ctx->session)
+        return -1;
+
+    return 0;
+}
+
+static int videotoolbox_end_frame(AVCodecContext *avctx)
+{
+    int status;
+    struct videotoolbox_context *vt_ctx = avctx->hwaccel_context;
+    MpegEncContext *s = avctx->priv_data;
+    AVFrame *frame = &s->current_picture_ptr->f;
+
+    if (!vt_ctx->session || !vt_ctx->priv_bitstream)
+        return -1;
+
+    status = videotoolbox_session_decode_frame(vt_ctx);
+
+    if (status) {
+        av_log(avctx, AV_LOG_ERROR, "Failed to decode frame (%d)\n", status);
+        return status;
+    }
+
+    frame->data[3] = (void*)vt_ctx->cv_buffer;
+
+    return status;
+}
+
+static CFDictionaryRef videotoolbox_decoder_config_create(CMVideoCodecType codec_type,
+                                                          AVCodecContext *avctx)
+{
+    CFMutableDictionaryRef config_info = NULL;
+    if (avctx->extradata_size) {
+        CFMutableDictionaryRef avc_info;
+        CFDataRef data;
+
+        config_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
+                                                1,
+                                                &kCFTypeDictionaryKeyCallBacks,
+                                                &kCFTypeDictionaryValueCallBacks);
+        avc_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
+                                             1,
+                                             &kCFTypeDictionaryKeyCallBacks,
+                                             &kCFTypeDictionaryValueCallBacks);
+
+        switch (codec_type) {
+        case kCMVideoCodecType_MPEG4Video :
+            data = videotoolbox_esds_extradata_create(avctx);
+            if (data)
+                CFDictionarySetValue(avc_info, CFSTR("esds"), data);
+            break;
+        case kCMVideoCodecType_H264 :
+            data = videotoolbox_avcc_extradata_create(avctx);
+            if (data)
+                CFDictionarySetValue(avc_info, CFSTR("avcC"), data);
+            break;
+        default:
+            break;
+        }
+
+        CFDictionarySetValue(config_info,
+                             kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms,
+                             avc_info);
+
+        if (data)
+            CFRelease(data);
+        CFRelease(avc_info);
+    }
+    return config_info;
+}
+
+static CFDictionaryRef videotoolbox_buffer_attributes_create(int width,
+                                                             int height,
+                                                             OSType pix_fmt)
+{
+    CFMutableDictionaryRef buffer_attributes;
+    CFMutableDictionaryRef io_surface_properties;
+    CFNumberRef cv_pix_fmt;
+    CFNumberRef w;
+    CFNumberRef h;
+
+    w = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width);
+    h = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height);
+    cv_pix_fmt = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pix_fmt);
+
+    buffer_attributes = CFDictionaryCreateMutable(kCFAllocatorDefault,
+                                                  4,
+                                                  &kCFTypeDictionaryKeyCallBacks,
+                                                  &kCFTypeDictionaryValueCallBacks);
+    io_surface_properties = CFDictionaryCreateMutable(kCFAllocatorDefault,
+                                                      0,
+                                                      &kCFTypeDictionaryKeyCallBacks,
+                                                      &kCFTypeDictionaryValueCallBacks);
+    CFDictionarySetValue(buffer_attributes,
+                         kCVPixelBufferPixelFormatTypeKey,
+                         cv_pix_fmt);
+    CFDictionarySetValue(buffer_attributes,
+                         kCVPixelBufferIOSurfacePropertiesKey,
+                         io_surface_properties);
+    CFDictionarySetValue(buffer_attributes,
+                         kCVPixelBufferWidthKey,
+                         w);
+    CFDictionarySetValue(buffer_attributes,
+                         kCVPixelBufferHeightKey,
+                         h);
+
+    CFRelease(io_surface_properties);
+    CFRelease(cv_pix_fmt);
+    CFRelease(w);
+    CFRelease(h);
+
+    return buffer_attributes;
+}
+
+static CMVideoFormatDescriptionRef videotoolbox_format_desc_create(CMVideoCodecType codec_type,
+                                                                   CFDictionaryRef decoder_spec,
+                                                                   int width,
+                                                                   int height)
+{
+    CMFormatDescriptionRef cm_fmt_desc;
+    OSStatus status;
+
+    status = CMVideoFormatDescriptionCreate(kCFAllocatorDefault,
+                                            codec_type,
+                                            width,
+                                            height,
+                                            decoder_spec, // Dictionary of extension
+                                            &cm_fmt_desc);
+
+    if (status)
+        return NULL;
+
+    return cm_fmt_desc;
+}
+
+int ff_videotoolbox_session_create(AVCodecContext *avctx,
+                                   OSType pix_fmt,
+                                   int width,
+                                   int height)
+{
+    OSStatus status;
+    VTDecompressionOutputCallbackRecord decoder_cb;
+    struct videotoolbox_context *vt_ctx = avctx->hwaccel_context;
+    CFDictionaryRef decoder_spec;
+    CFDictionaryRef buf_attr;
+
+    if (!vt_ctx) {
+        av_log(avctx, AV_LOG_ERROR, "hwaccel context is not set\n");
+        return -1;
+    }
+
+    switch( avctx->codec_id ) {
+    case AV_CODEC_ID_H264 :
+        vt_ctx->cm_codec_type = kCMVideoCodecType_H264;
+        break;
+    case AV_CODEC_ID_MPEG2VIDEO :
+        vt_ctx->cm_codec_type = kCMVideoCodecType_MPEG2Video;
+        break;
+    case AV_CODEC_ID_MPEG4 :
+    case AV_CODEC_ID_H263 :
+        vt_ctx->cm_codec_type = kCMVideoCodecType_MPEG4Video;
+        break;
+    default :
+        break;
+    }
+
+    vt_ctx->cv_pix_fmt = pix_fmt;
+
+    decoder_spec = videotoolbox_decoder_config_create(vt_ctx->cm_codec_type,
+                                                      avctx);
+    vt_ctx->cm_fmt_desc = videotoolbox_format_desc_create(vt_ctx->cm_codec_type,
+                                                          decoder_spec,
+                                                          width,
+                                                          height);
+    if (!vt_ctx->cm_fmt_desc) {
+        if (decoder_spec)
+            CFRelease(decoder_spec);
+
+        av_log(avctx, AV_LOG_ERROR, "format description creation failed\n");
+        return -1;
+    }
+
+    buf_attr = videotoolbox_buffer_attributes_create(width,
+                                                     height,
+                                                     vt_ctx->cv_pix_fmt);
+
+    decoder_cb.decompressionOutputCallback = videotoolbox_decoder_callback;
+    decoder_cb.decompressionOutputRefCon   = vt_ctx;
+
+    status = VTDecompressionSessionCreate(NULL,                // allocator
+                                          vt_ctx->cm_fmt_desc, // videoFormatDescription
+                                          decoder_spec,        // videoDecoderSpecification
+                                          buf_attr,            // destinationImageBufferAttributes
+                                          &decoder_cb,         // outputCallback
+                                          &vt_ctx->session);   // decompressionSessionOut
+
+    if (decoder_spec)
+        CFRelease(decoder_spec);
+    if (buf_attr)
+        CFRelease(buf_attr);
+
+    return status;
+}
+
+void ff_videotoolbox_session_invalidate(AVCodecContext *avctx)
+{
+    struct videotoolbox_context *vt_ctx = avctx->hwaccel_context;
+
+    if (!vt_ctx)
+        return;
+
+    if (vt_ctx->cm_fmt_desc)
+        CFRelease(vt_ctx->cm_fmt_desc);
+
+    if (vt_ctx->session)
+        VTDecompressionSessionInvalidate(vt_ctx->session);
+
+    videotoolbox_bitstream_release(vt_ctx);
+}
+
+#if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
+AVHWAccel ff_h264_videotoolbox_hwaccel = {
+    .name           = "h264_videotoolbox",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = CODEC_ID_H264,
+    .pix_fmt        = PIX_FMT_VIDEOTOOLBOX_VLD,
+    .start_frame    = videotoolbox_h264_start_frame,
+    .decode_slice   = videotoolbox_h264_decode_slice,
+    .end_frame      = videotoolbox_end_frame,
+};
+#endif
+
+#if CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL
+AVHWAccel ff_mpeg2_videotoolbox_hwaccel = {
+    .name           = "mpeg2_videotoolbox",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_MPEG2VIDEO,
+    .pix_fmt        = PIX_FMT_VIDEOTOOLBOX_VLD,
+    .start_frame    = videotoolbox_mpeg_start_frame,
+    .decode_slice   = videotoolbox_mpeg_decode_slice,
+    .end_frame      = videotoolbox_end_frame,
+};
+#endif
+
+#if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL
+AVHWAccel ff_mpeg4_videotoolbox_hwaccel = {
+    .name           = "mpeg4_videotoolbox",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_MPEG4,
+    .pix_fmt        = PIX_FMT_VIDEOTOOLBOX_VLD,
+    .start_frame    = videotoolbox_mpeg_start_frame,
+    .decode_slice   = videotoolbox_mpeg_decode_slice,
+    .end_frame      = videotoolbox_end_frame,
+};
+#endif
+
+#if CONFIG_H263_VIDEOTOOLBOX_HWACCEL
+AVHWAccel ff_h263_videotoolbox_hwaccel = {
+    .name           = "h263_videotoolbox",
+    .type           = AVMEDIA_TYPE_VIDEO,
+    .id             = AV_CODEC_ID_H263,
+    .pix_fmt        = PIX_FMT_VIDEOTOOLBOX_VLD,
+    .start_frame    = videotoolbox_mpeg_start_frame,
+    .decode_slice   = videotoolbox_mpeg_decode_slice,
+    .end_frame      = videotoolbox_end_frame,
+};
+#endif
diff --git a/libavcodec/videotoolbox.h b/libavcodec/videotoolbox.h
new file mode 100644
index 0000000..325a89b
--- /dev/null
+++ b/libavcodec/videotoolbox.h
@@ -0,0 +1,128 @@
+/*
+ * VideoToolbox hardware acceleration
+ *
+ * copyright (c) 2012 Sebastien Zwickert
+ *
+ * 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
+ */
+
+#ifndef AVCODEC_VIDEOTOOLBOX_H
+#define AVCODEC_VIDEOTOOLBOX_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_videotoolbox
+ * Public libavcodec VideoToolbox header.
+ */
+
+#include <stdint.h>
+
+#define Picture QuickdrawPicture
+#include <VideoToolbox/VideoToolbox.h>
+#undef Picture
+
+#include "libavcodec/avcodec.h"
+
+/**
+ * This structure is used to provide the necessary configuration and data
+ * to the VideoToolbox FFmpeg HWAccel implementation.
+ *
+ * The application must make it available as AVCodecContext.hwaccel_context.
+ */
+struct videotoolbox_context {
+    /**
+     * VideoToolbox decompression session.
+     *
+     * - encoding: unused.
+     * - decoding: Set/Unset by libavcodec.
+     */
+    VTDecompressionSessionRef   session;
+
+    /**
+     * The type of video compression.
+     *
+     * - encoding: unused.
+     * - decoding: Set/Unset by user.
+     */
+    int                 cm_codec_type;
+
+    /**
+     * The pixel format for output image buffers.
+     *
+     * - encoding: unused.
+     * - decoding: Set/Unset by user.
+     */
+    OSType              cv_pix_fmt;
+
+    /**
+     * The video format description.
+     *
+     * encoding: unused.
+     * decoding: Set by user. Unset by libavcodec.
+     */
+    CMVideoFormatDescriptionRef cm_fmt_desc;
+
+    /**
+     * The Core Video pixel buffer that contains the current image data.
+     *
+     * encoding: unused.
+     * decoding: Set by libavcodec. Unset by user.
+     */
+    CVImageBufferRef	cv_buffer;
+
+    /**
+     * The current bitstream buffer.
+     */
+    uint8_t             *priv_bitstream;
+
+    /**
+     * The current size of the bitstream.
+     */
+    int                 priv_bitstream_size;
+
+    /**
+     * The allocated size used for fast reallocation.
+     */
+    int                 priv_allocated_size;
+};
+
+/**
+ * Create a decompression session.
+ *
+ * @param avctx         the codec context
+ * @param pix_fmt       the pixel format of output image
+ * @param width         the width of encoded video
+ * @param height        the height of encoded video
+ * @return status
+ */
+int ff_videotoolbox_session_create(AVCodecContext *avctx,
+                                   OSType pix_fmt,
+                                   int width,
+                                   int height);
+
+/**
+ * Destroy a decompression session.
+ *
+ * @param avctx         the codec context
+ */
+void ff_videotoolbox_session_invalidate(AVCodecContext *avctx);
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_VIDEOTOOLBOX_H */
diff --git a/libavutil/pixdesc.c b/libavutil/pixdesc.c
index d64d300..6bdf5c1 100644
--- a/libavutil/pixdesc.c
+++ b/libavutil/pixdesc.c
@@ -1274,6 +1274,12 @@ const AVPixFmtDescriptor av_pix_fmt_descriptors[PIX_FMT_NB] = {
         .log2_chroma_h = 1,
         .flags = PIX_FMT_HWACCEL,
     },
+    [PIX_FMT_VIDEOTOOLBOX_VLD] = {
+        .name = "videotoolbox_vld",
+        .log2_chroma_w = 1,
+        .log2_chroma_h = 1,
+        .flags = PIX_FMT_HWACCEL,
+    },
     [PIX_FMT_GRAY8A] = {
         .name = "gray8a",
         .nb_components = 2,
diff --git a/libavutil/pixfmt.h b/libavutil/pixfmt.h
index fa771bc..36cdcdf 100644
--- a/libavutil/pixfmt.h
+++ b/libavutil/pixfmt.h
@@ -201,6 +201,7 @@ enum PixelFormat {
     PIX_FMT_GBRP12LE,    ///< planar GBR 4:4:4 36bpp, little endian
     PIX_FMT_GBRP14BE,    ///< planar GBR 4:4:4 42bpp, big endian
     PIX_FMT_GBRP14LE,    ///< planar GBR 4:4:4 42bpp, little endian
+    PIX_FMT_VIDEOTOOLBOX_VLD, ///< hardware decoding through VideoToolbox
 
     PIX_FMT_NB,        ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
 };
-- 
1.7.9.6 (Apple Git-31.1)



More information about the ffmpeg-devel mailing list