2 * Videotoolbox hardware acceleration
4 * copyright (c) 2012 Sebastien Zwickert
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 #include "videotoolbox.h"
25 #include "libavutil/hwcontext_videotoolbox.h"
26 #include "vt_internal.h"
27 #include "libavutil/avutil.h"
28 #include "libavutil/hwcontext.h"
29 #include "bytestream.h"
33 #include "mpegvideo.h"
34 #include <TargetConditionals.h>
36 #ifndef kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder
37 # define kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder CFSTR("RequireHardwareAcceleratedVideoDecoder")
39 #ifndef kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder
40 # define kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder CFSTR("EnableHardwareAcceleratedVideoDecoder")
43 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
44 enum { kCMVideoCodecType_HEVC = 'hvc1' };
47 #define VIDEOTOOLBOX_ESDS_EXTRADATA_PADDING 12
49 typedef struct VTHWFrame {
50 CVPixelBufferRef pixbuf;
51 AVBufferRef *hw_frames_ctx;
54 static void videotoolbox_buffer_release(void *opaque, uint8_t *data)
56 VTHWFrame *ref = (VTHWFrame *)data;
57 av_buffer_unref(&ref->hw_frames_ctx);
58 CVPixelBufferRelease(ref->pixbuf);
63 static int videotoolbox_buffer_copy(VTContext *vtctx,
64 const uint8_t *buffer,
69 tmp = av_fast_realloc(vtctx->bitstream,
70 &vtctx->allocated_size,
74 return AVERROR(ENOMEM);
76 vtctx->bitstream = tmp;
77 memcpy(vtctx->bitstream, buffer, size);
78 vtctx->bitstream_size = size;
83 static int videotoolbox_postproc_frame(void *avctx, AVFrame *frame)
85 VTHWFrame *ref = (VTHWFrame *)frame->buf[0]->data;
88 av_log(avctx, AV_LOG_ERROR, "No frame decoded?\n");
89 av_frame_unref(frame);
90 return AVERROR_EXTERNAL;
93 frame->data[3] = (uint8_t*)ref->pixbuf;
95 if (ref->hw_frames_ctx) {
96 av_buffer_unref(&frame->hw_frames_ctx);
97 frame->hw_frames_ctx = av_buffer_ref(ref->hw_frames_ctx);
98 if (!frame->hw_frames_ctx)
99 return AVERROR(ENOMEM);
105 int ff_videotoolbox_alloc_frame(AVCodecContext *avctx, AVFrame *frame)
107 size_t size = sizeof(VTHWFrame);
108 uint8_t *data = NULL;
109 AVBufferRef *buf = NULL;
110 int ret = ff_attach_decode_data(frame);
111 FrameDecodeData *fdd;
115 data = av_mallocz(size);
117 return AVERROR(ENOMEM);
118 buf = av_buffer_create(data, size, videotoolbox_buffer_release, NULL, 0);
121 return AVERROR(ENOMEM);
125 fdd = (FrameDecodeData*)frame->private_ref->data;
126 fdd->post_process = videotoolbox_postproc_frame;
128 frame->width = avctx->width;
129 frame->height = avctx->height;
130 frame->format = avctx->pix_fmt;
135 #define AV_W8(p, v) *(p) = (v)
137 CFDataRef ff_videotoolbox_avcc_extradata_create(AVCodecContext *avctx)
139 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
140 H264Context *h = avctx->priv_data;
141 CFDataRef data = NULL;
143 int vt_extradata_size = 6 + 2 + h->ps.sps->data_size + 3 + h->ps.pps->data_size;
144 uint8_t *vt_extradata = av_malloc(vt_extradata_size);
150 AV_W8(p + 0, 1); /* version */
151 AV_W8(p + 1, h->ps.sps->data[1]); /* profile */
152 AV_W8(p + 2, h->ps.sps->data[2]); /* profile compat */
153 AV_W8(p + 3, h->ps.sps->data[3]); /* level */
154 AV_W8(p + 4, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 3 (11) */
155 AV_W8(p + 5, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
156 AV_WB16(p + 6, h->ps.sps->data_size);
157 memcpy(p + 8, h->ps.sps->data, h->ps.sps->data_size);
158 p += 8 + h->ps.sps->data_size;
159 AV_W8(p + 0, 1); /* number of pps */
160 AV_WB16(p + 1, h->ps.pps->data_size);
161 memcpy(p + 3, h->ps.pps->data, h->ps.pps->data_size);
163 p += 3 + h->ps.pps->data_size;
164 av_assert0(p - vt_extradata == vt_extradata_size);
166 // save sps header (profile/level) used to create decoder session,
167 // so we can detect changes and recreate it.
169 memcpy(vtctx->sps, h->ps.sps->data + 1, 3);
171 data = CFDataCreate(kCFAllocatorDefault, vt_extradata, vt_extradata_size);
172 av_free(vt_extradata);
176 CFDataRef ff_videotoolbox_hvcc_extradata_create(AVCodecContext *avctx)
178 HEVCContext *h = avctx->priv_data;
179 int i, num_vps = 0, num_sps = 0, num_pps = 0;
180 const HEVCVPS *vps = h->ps.vps;
181 const HEVCSPS *sps = h->ps.sps;
182 const HEVCPPS *pps = h->ps.pps;
183 PTLCommon ptlc = vps->ptl.general_ptl;
185 uint8_t parallelismType;
186 CFDataRef data = NULL;
188 int vt_extradata_size = 23 + 3 + 3 + 3;
189 uint8_t *vt_extradata;
191 #define COUNT_SIZE_PS(T, t) \
192 for (i = 0; i < HEVC_MAX_##T##PS_COUNT; i++) { \
193 if (h->ps.t##ps_list[i]) { \
194 const HEVC##T##PS *lps = (const HEVC##T##PS *)h->ps.t##ps_list[i]->data; \
195 vt_extradata_size += 2 + lps->data_size; \
204 vt_extradata = av_malloc(vt_extradata_size);
209 /* unsigned int(8) configurationVersion = 1; */
213 * unsigned int(2) general_profile_space;
214 * unsigned int(1) general_tier_flag;
215 * unsigned int(5) general_profile_idc;
217 AV_W8(p + 1, ptlc.profile_space << 6 |
218 ptlc.tier_flag << 5 |
221 /* unsigned int(32) general_profile_compatibility_flags; */
222 memcpy(p + 2, ptlc.profile_compatibility_flag, 4);
224 /* unsigned int(48) general_constraint_indicator_flags; */
225 AV_W8(p + 6, ptlc.progressive_source_flag << 7 |
226 ptlc.interlaced_source_flag << 6 |
227 ptlc.non_packed_constraint_flag << 5 |
228 ptlc.frame_only_constraint_flag << 4);
232 /* unsigned int(8) general_level_idc; */
233 AV_W8(p + 12, ptlc.level_idc);
236 * bit(4) reserved = ‘1111’b;
237 * unsigned int(12) min_spatial_segmentation_idc;
239 AV_W8(p + 13, 0xf0 | (vui.min_spatial_segmentation_idc >> 4));
240 AV_W8(p + 14, vui.min_spatial_segmentation_idc & 0xff);
243 * bit(6) reserved = ‘111111’b;
244 * unsigned int(2) parallelismType;
246 if (!vui.min_spatial_segmentation_idc)
248 else if (pps->entropy_coding_sync_enabled_flag && pps->tiles_enabled_flag)
250 else if (pps->entropy_coding_sync_enabled_flag)
252 else if (pps->tiles_enabled_flag)
256 AV_W8(p + 15, 0xfc | parallelismType);
259 * bit(6) reserved = ‘111111’b;
260 * unsigned int(2) chromaFormat;
262 AV_W8(p + 16, sps->chroma_format_idc | 0xfc);
265 * bit(5) reserved = ‘11111’b;
266 * unsigned int(3) bitDepthLumaMinus8;
268 AV_W8(p + 17, (sps->bit_depth - 8) | 0xfc);
271 * bit(5) reserved = ‘11111’b;
272 * unsigned int(3) bitDepthChromaMinus8;
274 AV_W8(p + 18, (sps->bit_depth_chroma - 8) | 0xfc);
276 /* bit(16) avgFrameRate; */
280 * bit(2) constantFrameRate;
281 * bit(3) numTemporalLayers;
282 * bit(1) temporalIdNested;
283 * unsigned int(2) lengthSizeMinusOne;
285 AV_W8(p + 21, 0 << 6 |
286 sps->max_sub_layers << 3 |
287 sps->temporal_id_nesting_flag << 2 |
290 /* unsigned int(8) numOfArrays; */
295 #define APPEND_PS(T, t) \
297 * bit(1) array_completeness; \
298 * unsigned int(1) reserved = 0; \
299 * unsigned int(6) NAL_unit_type; \
302 HEVC_NAL_##T##PS & 0x3f); \
303 /* unsigned int(16) numNalus; */ \
304 AV_WB16(p + 1, num_##t##ps); \
306 for (i = 0; i < HEVC_MAX_##T##PS_COUNT; i++) { \
307 if (h->ps.t##ps_list[i]) { \
308 const HEVC##T##PS *lps = (const HEVC##T##PS *)h->ps.t##ps_list[i]->data; \
309 /* unsigned int(16) nalUnitLength; */ \
310 AV_WB16(p, lps->data_size); \
311 /* bit(8*nalUnitLength) nalUnit; */ \
312 memcpy(p + 2, lps->data, lps->data_size); \
313 p += 2 + lps->data_size; \
321 av_assert0(p - vt_extradata == vt_extradata_size);
323 data = CFDataCreate(kCFAllocatorDefault, vt_extradata, vt_extradata_size);
324 av_free(vt_extradata);
328 int ff_videotoolbox_h264_start_frame(AVCodecContext *avctx,
329 const uint8_t *buffer,
332 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
333 H264Context *h = avctx->priv_data;
335 if (h->is_avc == 1) {
336 return videotoolbox_buffer_copy(vtctx, buffer, size);
342 static int videotoolbox_h264_decode_params(AVCodecContext *avctx,
344 const uint8_t *buffer,
347 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
348 H264Context *h = avctx->priv_data;
350 // save sps header (profile/level) used to create decoder session
352 memcpy(vtctx->sps, h->ps.sps->data + 1, 3);
354 if (type == H264_NAL_SPS) {
355 if (size > 4 && memcmp(vtctx->sps, buffer + 1, 3) != 0) {
356 vtctx->reconfig_needed = true;
357 memcpy(vtctx->sps, buffer + 1, 3);
361 // pass-through SPS/PPS changes to the decoder
362 return ff_videotoolbox_h264_decode_slice(avctx, buffer, size);
365 static int videotoolbox_common_decode_slice(AVCodecContext *avctx,
366 const uint8_t *buffer,
369 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
372 tmp = av_fast_realloc(vtctx->bitstream,
373 &vtctx->allocated_size,
374 vtctx->bitstream_size+size+4);
376 return AVERROR(ENOMEM);
378 vtctx->bitstream = tmp;
380 AV_WB32(vtctx->bitstream + vtctx->bitstream_size, size);
381 memcpy(vtctx->bitstream + vtctx->bitstream_size + 4, buffer, size);
383 vtctx->bitstream_size += size + 4;
388 int ff_videotoolbox_h264_decode_slice(AVCodecContext *avctx,
389 const uint8_t *buffer,
392 H264Context *h = avctx->priv_data;
397 return videotoolbox_common_decode_slice(avctx, buffer, size);
400 int ff_videotoolbox_uninit(AVCodecContext *avctx)
402 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
404 av_freep(&vtctx->bitstream);
406 CVPixelBufferRelease(vtctx->frame);
412 #if CONFIG_VIDEOTOOLBOX
413 // Return the AVVideotoolboxContext that matters currently. Where it comes from
414 // depends on the API used.
415 static AVVideotoolboxContext *videotoolbox_get_context(AVCodecContext *avctx)
417 // Somewhat tricky because the user can call av_videotoolbox_default_free()
418 // at any time, even when the codec is closed.
419 if (avctx->internal && avctx->internal->hwaccel_priv_data) {
420 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
422 return vtctx->vt_ctx;
424 return avctx->hwaccel_context;
427 static int videotoolbox_buffer_create(AVCodecContext *avctx, AVFrame *frame)
429 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
430 CVPixelBufferRef pixbuf = (CVPixelBufferRef)vtctx->frame;
431 OSType pixel_format = CVPixelBufferGetPixelFormatType(pixbuf);
432 enum AVPixelFormat sw_format = av_map_videotoolbox_format_to_pixfmt(pixel_format);
433 int width = CVPixelBufferGetWidth(pixbuf);
434 int height = CVPixelBufferGetHeight(pixbuf);
435 AVHWFramesContext *cached_frames;
439 if (!frame->buf[0] || frame->data[3]) {
440 av_log(avctx, AV_LOG_ERROR, "videotoolbox: invalid state\n");
441 av_frame_unref(frame);
442 return AVERROR_EXTERNAL;
445 ref = (VTHWFrame *)frame->buf[0]->data;
448 CVPixelBufferRelease(ref->pixbuf);
449 ref->pixbuf = vtctx->frame;
452 // Old API code path.
453 if (!vtctx->cached_hw_frames_ctx)
456 cached_frames = (AVHWFramesContext*)vtctx->cached_hw_frames_ctx->data;
458 if (cached_frames->sw_format != sw_format ||
459 cached_frames->width != width ||
460 cached_frames->height != height) {
461 AVBufferRef *hw_frames_ctx = av_hwframe_ctx_alloc(cached_frames->device_ref);
462 AVHWFramesContext *hw_frames;
464 return AVERROR(ENOMEM);
466 hw_frames = (AVHWFramesContext*)hw_frames_ctx->data;
467 hw_frames->format = cached_frames->format;
468 hw_frames->sw_format = sw_format;
469 hw_frames->width = width;
470 hw_frames->height = height;
472 ret = av_hwframe_ctx_init(hw_frames_ctx);
474 av_buffer_unref(&hw_frames_ctx);
478 av_buffer_unref(&vtctx->cached_hw_frames_ctx);
479 vtctx->cached_hw_frames_ctx = hw_frames_ctx;
482 av_buffer_unref(&ref->hw_frames_ctx);
483 ref->hw_frames_ctx = av_buffer_ref(vtctx->cached_hw_frames_ctx);
484 if (!ref->hw_frames_ctx)
485 return AVERROR(ENOMEM);
490 static void videotoolbox_write_mp4_descr_length(PutByteContext *pb, int length)
495 for (i = 3; i >= 0; i--) {
496 b = (length >> (i * 7)) & 0x7F;
500 bytestream2_put_byteu(pb, b);
504 static CFDataRef videotoolbox_esds_extradata_create(AVCodecContext *avctx)
507 uint8_t *rw_extradata;
509 int full_size = 3 + 5 + 13 + 5 + avctx->extradata_size + 3;
510 // ES_DescrTag data + DecoderConfigDescrTag + data + DecSpecificInfoTag + size + SLConfigDescriptor
511 int config_size = 13 + 5 + avctx->extradata_size;
514 if (!(rw_extradata = av_mallocz(full_size + VIDEOTOOLBOX_ESDS_EXTRADATA_PADDING)))
517 bytestream2_init_writer(&pb, rw_extradata, full_size + VIDEOTOOLBOX_ESDS_EXTRADATA_PADDING);
518 bytestream2_put_byteu(&pb, 0); // version
519 bytestream2_put_ne24(&pb, 0); // flags
521 // elementary stream descriptor
522 bytestream2_put_byteu(&pb, 0x03); // ES_DescrTag
523 videotoolbox_write_mp4_descr_length(&pb, full_size);
524 bytestream2_put_ne16(&pb, 0); // esid
525 bytestream2_put_byteu(&pb, 0); // stream priority (0-32)
527 // decoder configuration descriptor
528 bytestream2_put_byteu(&pb, 0x04); // DecoderConfigDescrTag
529 videotoolbox_write_mp4_descr_length(&pb, config_size);
530 bytestream2_put_byteu(&pb, 32); // object type indication. 32 = AV_CODEC_ID_MPEG4
531 bytestream2_put_byteu(&pb, 0x11); // stream type
532 bytestream2_put_ne24(&pb, 0); // buffer size
533 bytestream2_put_ne32(&pb, 0); // max bitrate
534 bytestream2_put_ne32(&pb, 0); // avg bitrate
536 // decoder specific descriptor
537 bytestream2_put_byteu(&pb, 0x05); ///< DecSpecificInfoTag
538 videotoolbox_write_mp4_descr_length(&pb, avctx->extradata_size);
540 bytestream2_put_buffer(&pb, avctx->extradata, avctx->extradata_size);
542 // SLConfigDescriptor
543 bytestream2_put_byteu(&pb, 0x06); // SLConfigDescrTag
544 bytestream2_put_byteu(&pb, 0x01); // length
545 bytestream2_put_byteu(&pb, 0x02); //
547 s = bytestream2_size_p(&pb);
549 data = CFDataCreate(kCFAllocatorDefault, rw_extradata, s);
551 av_freep(&rw_extradata);
555 static CMSampleBufferRef videotoolbox_sample_buffer_create(CMFormatDescriptionRef fmt_desc,
560 CMBlockBufferRef block_buf;
561 CMSampleBufferRef sample_buf;
566 status = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault,// structureAllocator
567 buffer, // memoryBlock
569 kCFAllocatorNull, // blockAllocator
570 NULL, // customBlockSource
577 status = CMSampleBufferCreate(kCFAllocatorDefault, // allocator
578 block_buf, // dataBuffer
580 0, // makeDataReadyCallback
581 0, // makeDataReadyRefcon
582 fmt_desc, // formatDescription
584 0, // numSampleTimingEntries
585 NULL, // sampleTimingArray
586 0, // numSampleSizeEntries
587 NULL, // sampleSizeArray
592 CFRelease(block_buf);
597 static void videotoolbox_decoder_callback(void *opaque,
598 void *sourceFrameRefCon,
600 VTDecodeInfoFlags flags,
601 CVImageBufferRef image_buffer,
605 AVCodecContext *avctx = opaque;
606 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
609 CVPixelBufferRelease(vtctx->frame);
614 av_log(NULL, AV_LOG_DEBUG, "vt decoder cb: output image buffer is null\n");
618 vtctx->frame = CVPixelBufferRetain(image_buffer);
621 static OSStatus videotoolbox_session_decode_frame(AVCodecContext *avctx)
624 CMSampleBufferRef sample_buf;
625 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
626 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
628 sample_buf = videotoolbox_sample_buffer_create(videotoolbox->cm_fmt_desc,
630 vtctx->bitstream_size);
635 status = VTDecompressionSessionDecodeFrame(videotoolbox->session,
638 NULL, // sourceFrameRefCon
641 status = VTDecompressionSessionWaitForAsynchronousFrames(videotoolbox->session);
643 CFRelease(sample_buf);
648 static CMVideoFormatDescriptionRef videotoolbox_format_desc_create(CMVideoCodecType codec_type,
649 CFDictionaryRef decoder_spec,
653 CMFormatDescriptionRef cm_fmt_desc;
656 status = CMVideoFormatDescriptionCreate(kCFAllocatorDefault,
660 decoder_spec, // Dictionary of extension
669 static CFDictionaryRef videotoolbox_buffer_attributes_create(int width,
673 CFMutableDictionaryRef buffer_attributes;
674 CFMutableDictionaryRef io_surface_properties;
675 CFNumberRef cv_pix_fmt;
679 w = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width);
680 h = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height);
681 cv_pix_fmt = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pix_fmt);
683 buffer_attributes = CFDictionaryCreateMutable(kCFAllocatorDefault,
685 &kCFTypeDictionaryKeyCallBacks,
686 &kCFTypeDictionaryValueCallBacks);
687 io_surface_properties = CFDictionaryCreateMutable(kCFAllocatorDefault,
689 &kCFTypeDictionaryKeyCallBacks,
690 &kCFTypeDictionaryValueCallBacks);
693 CFDictionarySetValue(buffer_attributes, kCVPixelBufferPixelFormatTypeKey, cv_pix_fmt);
694 CFDictionarySetValue(buffer_attributes, kCVPixelBufferIOSurfacePropertiesKey, io_surface_properties);
695 CFDictionarySetValue(buffer_attributes, kCVPixelBufferWidthKey, w);
696 CFDictionarySetValue(buffer_attributes, kCVPixelBufferHeightKey, h);
698 CFDictionarySetValue(buffer_attributes, kCVPixelBufferOpenGLESCompatibilityKey, kCFBooleanTrue);
700 CFDictionarySetValue(buffer_attributes, kCVPixelBufferIOSurfaceOpenGLTextureCompatibilityKey, kCFBooleanTrue);
703 CFRelease(io_surface_properties);
704 CFRelease(cv_pix_fmt);
708 return buffer_attributes;
711 static CFDictionaryRef videotoolbox_decoder_config_create(CMVideoCodecType codec_type,
712 AVCodecContext *avctx)
714 CFMutableDictionaryRef config_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
716 &kCFTypeDictionaryKeyCallBacks,
717 &kCFTypeDictionaryValueCallBacks);
719 CFDictionarySetValue(config_info,
720 codec_type == kCMVideoCodecType_HEVC ?
721 kVTVideoDecoderSpecification_EnableHardwareAcceleratedVideoDecoder :
722 kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder,
725 CFMutableDictionaryRef avc_info;
726 CFDataRef data = NULL;
728 avc_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
730 &kCFTypeDictionaryKeyCallBacks,
731 &kCFTypeDictionaryValueCallBacks);
733 switch (codec_type) {
734 case kCMVideoCodecType_MPEG4Video :
735 if (avctx->extradata_size)
736 data = videotoolbox_esds_extradata_create(avctx);
738 CFDictionarySetValue(avc_info, CFSTR("esds"), data);
740 case kCMVideoCodecType_H264 :
741 data = ff_videotoolbox_avcc_extradata_create(avctx);
743 CFDictionarySetValue(avc_info, CFSTR("avcC"), data);
745 case kCMVideoCodecType_HEVC :
746 data = ff_videotoolbox_hvcc_extradata_create(avctx);
748 CFDictionarySetValue(avc_info, CFSTR("hvcC"), data);
754 CFDictionarySetValue(config_info,
755 kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms,
765 static int videotoolbox_start(AVCodecContext *avctx)
767 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
769 VTDecompressionOutputCallbackRecord decoder_cb;
770 CFDictionaryRef decoder_spec;
771 CFDictionaryRef buf_attr;
774 av_log(avctx, AV_LOG_ERROR, "hwaccel context is not set\n");
778 switch( avctx->codec_id ) {
779 case AV_CODEC_ID_H263 :
780 videotoolbox->cm_codec_type = kCMVideoCodecType_H263;
782 case AV_CODEC_ID_H264 :
783 videotoolbox->cm_codec_type = kCMVideoCodecType_H264;
785 case AV_CODEC_ID_HEVC :
786 videotoolbox->cm_codec_type = kCMVideoCodecType_HEVC;
788 case AV_CODEC_ID_MPEG1VIDEO :
789 videotoolbox->cm_codec_type = kCMVideoCodecType_MPEG1Video;
791 case AV_CODEC_ID_MPEG2VIDEO :
792 videotoolbox->cm_codec_type = kCMVideoCodecType_MPEG2Video;
794 case AV_CODEC_ID_MPEG4 :
795 videotoolbox->cm_codec_type = kCMVideoCodecType_MPEG4Video;
801 decoder_spec = videotoolbox_decoder_config_create(videotoolbox->cm_codec_type, avctx);
804 av_log(avctx, AV_LOG_ERROR, "decoder specification creation failed\n");
808 videotoolbox->cm_fmt_desc = videotoolbox_format_desc_create(videotoolbox->cm_codec_type,
812 if (!videotoolbox->cm_fmt_desc) {
814 CFRelease(decoder_spec);
816 av_log(avctx, AV_LOG_ERROR, "format description creation failed\n");
820 buf_attr = videotoolbox_buffer_attributes_create(avctx->width,
822 videotoolbox->cv_pix_fmt_type);
824 decoder_cb.decompressionOutputCallback = videotoolbox_decoder_callback;
825 decoder_cb.decompressionOutputRefCon = avctx;
827 status = VTDecompressionSessionCreate(NULL, // allocator
828 videotoolbox->cm_fmt_desc, // videoFormatDescription
829 decoder_spec, // videoDecoderSpecification
830 buf_attr, // destinationImageBufferAttributes
831 &decoder_cb, // outputCallback
832 &videotoolbox->session); // decompressionSessionOut
835 CFRelease(decoder_spec);
840 case kVTVideoDecoderNotAvailableNowErr:
841 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox session not available.\n");
842 return AVERROR(ENOSYS);
843 case kVTVideoDecoderUnsupportedDataFormatErr:
844 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox does not support this format.\n");
845 return AVERROR(ENOSYS);
846 case kVTCouldNotFindVideoDecoderErr:
847 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox decoder for this format not found.\n");
848 return AVERROR(ENOSYS);
849 case kVTVideoDecoderMalfunctionErr:
850 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox malfunction.\n");
851 return AVERROR(EINVAL);
852 case kVTVideoDecoderBadDataErr:
853 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox reported invalid data.\n");
854 return AVERROR_INVALIDDATA;
858 av_log(avctx, AV_LOG_VERBOSE, "Unknown VideoToolbox session creation error %d\n", (int)status);
859 return AVERROR_UNKNOWN;
863 static void videotoolbox_stop(AVCodecContext *avctx)
865 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
869 if (videotoolbox->cm_fmt_desc) {
870 CFRelease(videotoolbox->cm_fmt_desc);
871 videotoolbox->cm_fmt_desc = NULL;
874 if (videotoolbox->session) {
875 VTDecompressionSessionInvalidate(videotoolbox->session);
876 CFRelease(videotoolbox->session);
877 videotoolbox->session = NULL;
881 static const char *videotoolbox_error_string(OSStatus status)
884 case kVTVideoDecoderBadDataErr:
886 case kVTVideoDecoderMalfunctionErr:
887 return "decoder malfunction";
888 case kVTInvalidSessionErr:
889 return "invalid session";
894 static int videotoolbox_common_end_frame(AVCodecContext *avctx, AVFrame *frame)
897 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
898 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
900 frame->crop_right = 0;
901 frame->crop_left = 0;
903 frame->crop_bottom = 0;
905 if (vtctx->reconfig_needed == true) {
906 vtctx->reconfig_needed = false;
907 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox decoder needs reconfig, restarting..\n");
908 videotoolbox_stop(avctx);
909 if (videotoolbox_start(avctx) != 0) {
910 return AVERROR_EXTERNAL;
914 if (!videotoolbox->session || !vtctx->bitstream || !vtctx->bitstream_size)
915 return AVERROR_INVALIDDATA;
917 status = videotoolbox_session_decode_frame(avctx);
918 if (status != noErr) {
919 if (status == kVTVideoDecoderMalfunctionErr || status == kVTInvalidSessionErr)
920 vtctx->reconfig_needed = true;
921 av_log(avctx, AV_LOG_ERROR, "Failed to decode frame (%s, %d)\n", videotoolbox_error_string(status), (int)status);
922 return AVERROR_UNKNOWN;
926 vtctx->reconfig_needed = true;
927 return AVERROR_UNKNOWN;
930 return videotoolbox_buffer_create(avctx, frame);
933 static int videotoolbox_h264_end_frame(AVCodecContext *avctx)
935 H264Context *h = avctx->priv_data;
936 AVFrame *frame = h->cur_pic_ptr->f;
937 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
938 int ret = videotoolbox_common_end_frame(avctx, frame);
939 vtctx->bitstream_size = 0;
943 static int videotoolbox_hevc_start_frame(AVCodecContext *avctx,
944 const uint8_t *buffer,
950 static int videotoolbox_hevc_decode_slice(AVCodecContext *avctx,
951 const uint8_t *buffer,
954 return videotoolbox_common_decode_slice(avctx, buffer, size);
958 static int videotoolbox_hevc_decode_params(AVCodecContext *avctx,
960 const uint8_t *buffer,
963 return videotoolbox_common_decode_slice(avctx, buffer, size);
966 static int videotoolbox_hevc_end_frame(AVCodecContext *avctx)
968 HEVCContext *h = avctx->priv_data;
969 AVFrame *frame = h->ref->frame;
970 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
972 h->output_frame->crop_right = 0;
973 h->output_frame->crop_left = 0;
974 h->output_frame->crop_top = 0;
975 h->output_frame->crop_bottom = 0;
977 int ret = videotoolbox_common_end_frame(avctx, frame);
978 vtctx->bitstream_size = 0;
982 static int videotoolbox_mpeg_start_frame(AVCodecContext *avctx,
983 const uint8_t *buffer,
986 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
988 return videotoolbox_buffer_copy(vtctx, buffer, size);
991 static int videotoolbox_mpeg_decode_slice(AVCodecContext *avctx,
992 const uint8_t *buffer,
998 static int videotoolbox_mpeg_end_frame(AVCodecContext *avctx)
1000 MpegEncContext *s = avctx->priv_data;
1001 AVFrame *frame = s->current_picture_ptr->f;
1003 return videotoolbox_common_end_frame(avctx, frame);
1006 static int videotoolbox_uninit(AVCodecContext *avctx)
1008 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
1012 ff_videotoolbox_uninit(avctx);
1015 videotoolbox_stop(avctx);
1017 av_buffer_unref(&vtctx->cached_hw_frames_ctx);
1018 av_freep(&vtctx->vt_ctx);
1023 static int videotoolbox_common_init(AVCodecContext *avctx)
1025 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
1026 AVHWFramesContext *hw_frames;
1029 // Old API - do nothing.
1030 if (avctx->hwaccel_context)
1033 if (!avctx->hw_frames_ctx && !avctx->hw_device_ctx) {
1034 av_log(avctx, AV_LOG_ERROR,
1035 "Either hw_frames_ctx or hw_device_ctx must be set.\n");
1036 return AVERROR(EINVAL);
1039 vtctx->vt_ctx = av_videotoolbox_alloc_context();
1040 if (!vtctx->vt_ctx) {
1041 err = AVERROR(ENOMEM);
1045 if (avctx->hw_frames_ctx) {
1046 hw_frames = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1048 avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
1049 if (!avctx->hw_frames_ctx) {
1050 err = AVERROR(ENOMEM);
1054 hw_frames = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1055 hw_frames->format = AV_PIX_FMT_VIDEOTOOLBOX;
1056 hw_frames->sw_format = AV_PIX_FMT_NV12; // same as av_videotoolbox_alloc_context()
1057 hw_frames->width = avctx->width;
1058 hw_frames->height = avctx->height;
1060 err = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1062 av_buffer_unref(&avctx->hw_frames_ctx);
1067 vtctx->cached_hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
1068 if (!vtctx->cached_hw_frames_ctx) {
1069 err = AVERROR(ENOMEM);
1073 vtctx->vt_ctx->cv_pix_fmt_type =
1074 av_map_videotoolbox_format_from_pixfmt(hw_frames->sw_format);
1075 if (!vtctx->vt_ctx->cv_pix_fmt_type) {
1076 av_log(avctx, AV_LOG_ERROR, "Unknown sw_format.\n");
1077 err = AVERROR(EINVAL);
1081 err = videotoolbox_start(avctx);
1088 videotoolbox_uninit(avctx);
1092 static int videotoolbox_frame_params(AVCodecContext *avctx,
1093 AVBufferRef *hw_frames_ctx)
1095 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
1097 frames_ctx->format = AV_PIX_FMT_VIDEOTOOLBOX;
1098 frames_ctx->width = avctx->coded_width;
1099 frames_ctx->height = avctx->coded_height;
1100 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1105 const AVHWAccel ff_h263_videotoolbox_hwaccel = {
1106 .name = "h263_videotoolbox",
1107 .type = AVMEDIA_TYPE_VIDEO,
1108 .id = AV_CODEC_ID_H263,
1109 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1110 .alloc_frame = ff_videotoolbox_alloc_frame,
1111 .start_frame = videotoolbox_mpeg_start_frame,
1112 .decode_slice = videotoolbox_mpeg_decode_slice,
1113 .end_frame = videotoolbox_mpeg_end_frame,
1114 .frame_params = videotoolbox_frame_params,
1115 .init = videotoolbox_common_init,
1116 .uninit = videotoolbox_uninit,
1117 .priv_data_size = sizeof(VTContext),
1120 const AVHWAccel ff_hevc_videotoolbox_hwaccel = {
1121 .name = "hevc_videotoolbox",
1122 .type = AVMEDIA_TYPE_VIDEO,
1123 .id = AV_CODEC_ID_HEVC,
1124 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1125 .alloc_frame = ff_videotoolbox_alloc_frame,
1126 .start_frame = videotoolbox_hevc_start_frame,
1127 .decode_slice = videotoolbox_hevc_decode_slice,
1128 .decode_params = videotoolbox_hevc_decode_params,
1129 .end_frame = videotoolbox_hevc_end_frame,
1130 .frame_params = videotoolbox_frame_params,
1131 .init = videotoolbox_common_init,
1132 .uninit = ff_videotoolbox_uninit,
1133 .priv_data_size = sizeof(VTContext),
1136 const AVHWAccel ff_h264_videotoolbox_hwaccel = {
1137 .name = "h264_videotoolbox",
1138 .type = AVMEDIA_TYPE_VIDEO,
1139 .id = AV_CODEC_ID_H264,
1140 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1141 .alloc_frame = ff_videotoolbox_alloc_frame,
1142 .start_frame = ff_videotoolbox_h264_start_frame,
1143 .decode_slice = ff_videotoolbox_h264_decode_slice,
1144 .decode_params = videotoolbox_h264_decode_params,
1145 .end_frame = videotoolbox_h264_end_frame,
1146 .frame_params = videotoolbox_frame_params,
1147 .init = videotoolbox_common_init,
1148 .uninit = videotoolbox_uninit,
1149 .priv_data_size = sizeof(VTContext),
1152 const AVHWAccel ff_mpeg1_videotoolbox_hwaccel = {
1153 .name = "mpeg1_videotoolbox",
1154 .type = AVMEDIA_TYPE_VIDEO,
1155 .id = AV_CODEC_ID_MPEG1VIDEO,
1156 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1157 .alloc_frame = ff_videotoolbox_alloc_frame,
1158 .start_frame = videotoolbox_mpeg_start_frame,
1159 .decode_slice = videotoolbox_mpeg_decode_slice,
1160 .end_frame = videotoolbox_mpeg_end_frame,
1161 .frame_params = videotoolbox_frame_params,
1162 .init = videotoolbox_common_init,
1163 .uninit = videotoolbox_uninit,
1164 .priv_data_size = sizeof(VTContext),
1167 const AVHWAccel ff_mpeg2_videotoolbox_hwaccel = {
1168 .name = "mpeg2_videotoolbox",
1169 .type = AVMEDIA_TYPE_VIDEO,
1170 .id = AV_CODEC_ID_MPEG2VIDEO,
1171 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1172 .alloc_frame = ff_videotoolbox_alloc_frame,
1173 .start_frame = videotoolbox_mpeg_start_frame,
1174 .decode_slice = videotoolbox_mpeg_decode_slice,
1175 .end_frame = videotoolbox_mpeg_end_frame,
1176 .frame_params = videotoolbox_frame_params,
1177 .init = videotoolbox_common_init,
1178 .uninit = videotoolbox_uninit,
1179 .priv_data_size = sizeof(VTContext),
1182 const AVHWAccel ff_mpeg4_videotoolbox_hwaccel = {
1183 .name = "mpeg4_videotoolbox",
1184 .type = AVMEDIA_TYPE_VIDEO,
1185 .id = AV_CODEC_ID_MPEG4,
1186 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1187 .alloc_frame = ff_videotoolbox_alloc_frame,
1188 .start_frame = videotoolbox_mpeg_start_frame,
1189 .decode_slice = videotoolbox_mpeg_decode_slice,
1190 .end_frame = videotoolbox_mpeg_end_frame,
1191 .frame_params = videotoolbox_frame_params,
1192 .init = videotoolbox_common_init,
1193 .uninit = videotoolbox_uninit,
1194 .priv_data_size = sizeof(VTContext),
1197 AVVideotoolboxContext *av_videotoolbox_alloc_context(void)
1199 AVVideotoolboxContext *ret = av_mallocz(sizeof(*ret));
1202 ret->output_callback = videotoolbox_decoder_callback;
1203 ret->cv_pix_fmt_type = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
1209 int av_videotoolbox_default_init(AVCodecContext *avctx)
1211 return av_videotoolbox_default_init2(avctx, NULL);
1214 int av_videotoolbox_default_init2(AVCodecContext *avctx, AVVideotoolboxContext *vtctx)
1216 avctx->hwaccel_context = vtctx ?: av_videotoolbox_alloc_context();
1217 if (!avctx->hwaccel_context)
1218 return AVERROR(ENOMEM);
1219 return videotoolbox_start(avctx);
1222 void av_videotoolbox_default_free(AVCodecContext *avctx)
1225 videotoolbox_stop(avctx);
1226 av_freep(&avctx->hwaccel_context);
1228 #endif /* CONFIG_VIDEOTOOLBOX */