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")
40 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
41 enum { kCMVideoCodecType_HEVC = 'hvc1' };
44 #define VIDEOTOOLBOX_ESDS_EXTRADATA_PADDING 12
46 static void videotoolbox_buffer_release(void *opaque, uint8_t *data)
48 CVPixelBufferRef cv_buffer = *(CVPixelBufferRef *)data;
49 CVPixelBufferRelease(cv_buffer);
54 static int videotoolbox_buffer_copy(VTContext *vtctx,
55 const uint8_t *buffer,
60 tmp = av_fast_realloc(vtctx->bitstream,
61 &vtctx->allocated_size,
65 return AVERROR(ENOMEM);
67 vtctx->bitstream = tmp;
68 memcpy(vtctx->bitstream, buffer, size);
69 vtctx->bitstream_size = size;
74 static int videotoolbox_postproc_frame(void *avctx, AVFrame *frame)
76 CVPixelBufferRef ref = *(CVPixelBufferRef *)frame->buf[0]->data;
79 av_log(avctx, AV_LOG_ERROR, "No frame decoded?\n");
80 av_frame_unref(frame);
81 return AVERROR_EXTERNAL;
84 frame->data[3] = (uint8_t*)ref;
89 int ff_videotoolbox_alloc_frame(AVCodecContext *avctx, AVFrame *frame)
91 size_t size = sizeof(CVPixelBufferRef);
93 AVBufferRef *buf = NULL;
94 int ret = ff_attach_decode_data(frame);
99 data = av_mallocz(size);
101 return AVERROR(ENOMEM);
102 buf = av_buffer_create(data, size, videotoolbox_buffer_release, NULL, 0);
105 return AVERROR(ENOMEM);
109 fdd = (FrameDecodeData*)frame->private_ref->data;
110 fdd->post_process = videotoolbox_postproc_frame;
112 frame->width = avctx->width;
113 frame->height = avctx->height;
114 frame->format = avctx->pix_fmt;
119 #define AV_W8(p, v) *(p) = (v)
121 CFDataRef ff_videotoolbox_avcc_extradata_create(AVCodecContext *avctx)
123 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
124 H264Context *h = avctx->priv_data;
125 CFDataRef data = NULL;
127 int vt_extradata_size = 6 + 2 + h->ps.sps->data_size + 3 + h->ps.pps->data_size;
128 uint8_t *vt_extradata = av_malloc(vt_extradata_size);
134 AV_W8(p + 0, 1); /* version */
135 AV_W8(p + 1, h->ps.sps->data[1]); /* profile */
136 AV_W8(p + 2, h->ps.sps->data[2]); /* profile compat */
137 AV_W8(p + 3, h->ps.sps->data[3]); /* level */
138 AV_W8(p + 4, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 3 (11) */
139 AV_W8(p + 5, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
140 AV_WB16(p + 6, h->ps.sps->data_size);
141 memcpy(p + 8, h->ps.sps->data, h->ps.sps->data_size);
142 p += 8 + h->ps.sps->data_size;
143 AV_W8(p + 0, 1); /* number of pps */
144 AV_WB16(p + 1, h->ps.pps->data_size);
145 memcpy(p + 3, h->ps.pps->data, h->ps.pps->data_size);
147 p += 3 + h->ps.pps->data_size;
148 av_assert0(p - vt_extradata == vt_extradata_size);
150 // save sps header (profile/level) used to create decoder session,
151 // so we can detect changes and recreate it.
153 memcpy(vtctx->sps, h->ps.sps->data + 1, 3);
155 data = CFDataCreate(kCFAllocatorDefault, vt_extradata, vt_extradata_size);
156 av_free(vt_extradata);
160 CFDataRef ff_videotoolbox_hvcc_extradata_create(AVCodecContext *avctx)
162 HEVCContext *h = avctx->priv_data;
163 const HEVCVPS *vps = (const HEVCVPS *)h->ps.vps_list[0]->data;
164 const HEVCSPS *sps = (const HEVCSPS *)h->ps.sps_list[0]->data;
166 const HEVCPPS *pps = h->ps.pps;
167 PTLCommon ptlc = vps->ptl.general_ptl;
169 uint8_t parallelismType;
170 CFDataRef data = NULL;
172 int vt_extradata_size = 23 + 5 + vps->data_size + 5 + sps->data_size + 3;
173 uint8_t *vt_extradata;
175 for (i = 0; i < HEVC_MAX_PPS_COUNT; i++) {
176 if (h->ps.pps_list[i]) {
177 const HEVCPPS *pps = (const HEVCPPS *)h->ps.pps_list[i]->data;
178 vt_extradata_size += 2 + pps->data_size;
183 vt_extradata = av_malloc(vt_extradata_size);
188 /* unsigned int(8) configurationVersion = 1; */
192 * unsigned int(2) general_profile_space;
193 * unsigned int(1) general_tier_flag;
194 * unsigned int(5) general_profile_idc;
196 AV_W8(p + 1, ptlc.profile_space << 6 |
197 ptlc.tier_flag << 5 |
200 /* unsigned int(32) general_profile_compatibility_flags; */
201 memcpy(p + 2, ptlc.profile_compatibility_flag, 4);
203 /* unsigned int(48) general_constraint_indicator_flags; */
204 AV_W8(p + 6, ptlc.progressive_source_flag << 7 |
205 ptlc.interlaced_source_flag << 6 |
206 ptlc.non_packed_constraint_flag << 5 |
207 ptlc.frame_only_constraint_flag << 4);
211 /* unsigned int(8) general_level_idc; */
212 AV_W8(p + 12, ptlc.level_idc);
215 * bit(4) reserved = ‘1111’b;
216 * unsigned int(12) min_spatial_segmentation_idc;
218 AV_W8(p + 13, 0xf0 | (vui.min_spatial_segmentation_idc >> 4));
219 AV_W8(p + 14, vui.min_spatial_segmentation_idc & 0xff);
222 * bit(6) reserved = ‘111111’b;
223 * unsigned int(2) parallelismType;
225 if (!vui.min_spatial_segmentation_idc)
227 else if (pps->entropy_coding_sync_enabled_flag && pps->tiles_enabled_flag)
229 else if (pps->entropy_coding_sync_enabled_flag)
231 else if (pps->tiles_enabled_flag)
235 AV_W8(p + 15, 0xfc | parallelismType);
238 * bit(6) reserved = ‘111111’b;
239 * unsigned int(2) chromaFormat;
241 AV_W8(p + 16, sps->chroma_format_idc | 0xfc);
244 * bit(5) reserved = ‘11111’b;
245 * unsigned int(3) bitDepthLumaMinus8;
247 AV_W8(p + 17, (sps->bit_depth - 8) | 0xfc);
250 * bit(5) reserved = ‘11111’b;
251 * unsigned int(3) bitDepthChromaMinus8;
253 AV_W8(p + 18, (sps->bit_depth_chroma - 8) | 0xfc);
255 /* bit(16) avgFrameRate; */
259 * bit(2) constantFrameRate;
260 * bit(3) numTemporalLayers;
261 * bit(1) temporalIdNested;
262 * unsigned int(2) lengthSizeMinusOne;
264 AV_W8(p + 21, 0 << 6 |
265 sps->max_sub_layers << 3 |
266 sps->temporal_id_nesting_flag << 2 |
269 /* unsigned int(8) numOfArrays; */
275 * bit(1) array_completeness;
276 * unsigned int(1) reserved = 0;
277 * unsigned int(6) NAL_unit_type;
280 HEVC_NAL_VPS & 0x3f);
281 /* unsigned int(16) numNalus; */
283 /* unsigned int(16) nalUnitLength; */
284 AV_WB16(p + 3, vps->data_size);
285 /* bit(8*nalUnitLength) nalUnit; */
286 memcpy(p + 5, vps->data, vps->data_size);
287 p += 5 + vps->data_size;
291 HEVC_NAL_SPS & 0x3f);
293 AV_WB16(p + 3, sps->data_size);
294 memcpy(p + 5, sps->data, sps->data_size);
295 p += 5 + sps->data_size;
299 HEVC_NAL_PPS & 0x3f);
300 AV_WB16(p + 1, num_pps);
302 for (i = 0; i < HEVC_MAX_PPS_COUNT; i++) {
303 if (h->ps.pps_list[i]) {
304 const HEVCPPS *pps = (const HEVCPPS *)h->ps.pps_list[i]->data;
305 AV_WB16(p, pps->data_size);
306 memcpy(p + 2, pps->data, pps->data_size);
307 p += 2 + pps->data_size;
311 av_assert0(p - vt_extradata == vt_extradata_size);
313 data = CFDataCreate(kCFAllocatorDefault, vt_extradata, vt_extradata_size);
314 av_free(vt_extradata);
318 static int videotoolbox_set_frame(AVCodecContext *avctx, AVFrame *frame)
320 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
321 if (!frame->buf[0] || frame->data[3]) {
322 av_log(avctx, AV_LOG_ERROR, "videotoolbox: invalid state\n");
323 av_frame_unref(frame);
324 return AVERROR_EXTERNAL;
327 CVPixelBufferRef *ref = (CVPixelBufferRef *)frame->buf[0]->data;
330 av_log(avctx, AV_LOG_ERROR, "videotoolbox: frame already set?\n");
331 av_frame_unref(frame);
332 return AVERROR_EXTERNAL;
341 int ff_videotoolbox_h264_start_frame(AVCodecContext *avctx,
342 const uint8_t *buffer,
345 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
346 H264Context *h = avctx->priv_data;
348 if (h->is_avc == 1) {
349 return videotoolbox_buffer_copy(vtctx, buffer, size);
355 static int videotoolbox_h264_decode_params(AVCodecContext *avctx,
357 const uint8_t *buffer,
360 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
361 H264Context *h = avctx->priv_data;
363 // save sps header (profile/level) used to create decoder session
365 memcpy(vtctx->sps, h->ps.sps->data + 1, 3);
367 if (type == H264_NAL_SPS) {
368 if (size > 4 && memcmp(vtctx->sps, buffer + 1, 3) != 0) {
369 vtctx->reconfig_needed = true;
370 memcpy(vtctx->sps, buffer + 1, 3);
374 // pass-through SPS/PPS changes to the decoder
375 return ff_videotoolbox_h264_decode_slice(avctx, buffer, size);
378 int ff_videotoolbox_h264_decode_slice(AVCodecContext *avctx,
379 const uint8_t *buffer,
382 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
383 H264Context *h = avctx->priv_data;
389 tmp = av_fast_realloc(vtctx->bitstream,
390 &vtctx->allocated_size,
391 vtctx->bitstream_size+size+4);
393 return AVERROR(ENOMEM);
395 vtctx->bitstream = tmp;
397 AV_WB32(vtctx->bitstream + vtctx->bitstream_size, size);
398 memcpy(vtctx->bitstream + vtctx->bitstream_size + 4, buffer, size);
400 vtctx->bitstream_size += size + 4;
405 int ff_videotoolbox_uninit(AVCodecContext *avctx)
407 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
409 av_freep(&vtctx->bitstream);
411 CVPixelBufferRelease(vtctx->frame);
417 #if CONFIG_VIDEOTOOLBOX
418 // Return the AVVideotoolboxContext that matters currently. Where it comes from
419 // depends on the API used.
420 static AVVideotoolboxContext *videotoolbox_get_context(AVCodecContext *avctx)
422 // Somewhat tricky because the user can call av_videotoolbox_default_free()
423 // at any time, even when the codec is closed.
424 if (avctx->internal && avctx->internal->hwaccel_priv_data) {
425 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
427 return vtctx->vt_ctx;
429 return avctx->hwaccel_context;
432 static int videotoolbox_buffer_create(AVCodecContext *avctx, AVFrame *frame)
434 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
435 CVPixelBufferRef pixbuf = (CVPixelBufferRef)vtctx->frame;
436 OSType pixel_format = CVPixelBufferGetPixelFormatType(pixbuf);
437 enum AVPixelFormat sw_format = av_map_videotoolbox_format_to_pixfmt(pixel_format);
438 int width = CVPixelBufferGetWidth(pixbuf);
439 int height = CVPixelBufferGetHeight(pixbuf);
440 AVHWFramesContext *cached_frames;
443 ret = videotoolbox_set_frame(avctx, frame);
447 // Old API code path.
448 if (!vtctx->cached_hw_frames_ctx)
451 cached_frames = (AVHWFramesContext*)vtctx->cached_hw_frames_ctx->data;
453 if (cached_frames->sw_format != sw_format ||
454 cached_frames->width != width ||
455 cached_frames->height != height) {
456 AVBufferRef *hw_frames_ctx = av_hwframe_ctx_alloc(cached_frames->device_ref);
457 AVHWFramesContext *hw_frames;
459 return AVERROR(ENOMEM);
461 hw_frames = (AVHWFramesContext*)hw_frames_ctx->data;
462 hw_frames->format = cached_frames->format;
463 hw_frames->sw_format = sw_format;
464 hw_frames->width = width;
465 hw_frames->height = height;
467 ret = av_hwframe_ctx_init(hw_frames_ctx);
469 av_buffer_unref(&hw_frames_ctx);
473 av_buffer_unref(&vtctx->cached_hw_frames_ctx);
474 vtctx->cached_hw_frames_ctx = hw_frames_ctx;
477 av_buffer_unref(&frame->hw_frames_ctx);
478 frame->hw_frames_ctx = av_buffer_ref(vtctx->cached_hw_frames_ctx);
479 if (!frame->hw_frames_ctx)
480 return AVERROR(ENOMEM);
485 static void videotoolbox_write_mp4_descr_length(PutByteContext *pb, int length)
490 for (i = 3; i >= 0; i--) {
491 b = (length >> (i * 7)) & 0x7F;
495 bytestream2_put_byteu(pb, b);
499 static CFDataRef videotoolbox_esds_extradata_create(AVCodecContext *avctx)
502 uint8_t *rw_extradata;
504 int full_size = 3 + 5 + 13 + 5 + avctx->extradata_size + 3;
505 // ES_DescrTag data + DecoderConfigDescrTag + data + DecSpecificInfoTag + size + SLConfigDescriptor
506 int config_size = 13 + 5 + avctx->extradata_size;
509 if (!(rw_extradata = av_mallocz(full_size + VIDEOTOOLBOX_ESDS_EXTRADATA_PADDING)))
512 bytestream2_init_writer(&pb, rw_extradata, full_size + VIDEOTOOLBOX_ESDS_EXTRADATA_PADDING);
513 bytestream2_put_byteu(&pb, 0); // version
514 bytestream2_put_ne24(&pb, 0); // flags
516 // elementary stream descriptor
517 bytestream2_put_byteu(&pb, 0x03); // ES_DescrTag
518 videotoolbox_write_mp4_descr_length(&pb, full_size);
519 bytestream2_put_ne16(&pb, 0); // esid
520 bytestream2_put_byteu(&pb, 0); // stream priority (0-32)
522 // decoder configuration descriptor
523 bytestream2_put_byteu(&pb, 0x04); // DecoderConfigDescrTag
524 videotoolbox_write_mp4_descr_length(&pb, config_size);
525 bytestream2_put_byteu(&pb, 32); // object type indication. 32 = AV_CODEC_ID_MPEG4
526 bytestream2_put_byteu(&pb, 0x11); // stream type
527 bytestream2_put_ne24(&pb, 0); // buffer size
528 bytestream2_put_ne32(&pb, 0); // max bitrate
529 bytestream2_put_ne32(&pb, 0); // avg bitrate
531 // decoder specific descriptor
532 bytestream2_put_byteu(&pb, 0x05); ///< DecSpecificInfoTag
533 videotoolbox_write_mp4_descr_length(&pb, avctx->extradata_size);
535 bytestream2_put_buffer(&pb, avctx->extradata, avctx->extradata_size);
537 // SLConfigDescriptor
538 bytestream2_put_byteu(&pb, 0x06); // SLConfigDescrTag
539 bytestream2_put_byteu(&pb, 0x01); // length
540 bytestream2_put_byteu(&pb, 0x02); //
542 s = bytestream2_size_p(&pb);
544 data = CFDataCreate(kCFAllocatorDefault, rw_extradata, s);
546 av_freep(&rw_extradata);
550 static CMSampleBufferRef videotoolbox_sample_buffer_create(CMFormatDescriptionRef fmt_desc,
555 CMBlockBufferRef block_buf;
556 CMSampleBufferRef sample_buf;
561 status = CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault,// structureAllocator
562 buffer, // memoryBlock
564 kCFAllocatorNull, // blockAllocator
565 NULL, // customBlockSource
572 status = CMSampleBufferCreate(kCFAllocatorDefault, // allocator
573 block_buf, // dataBuffer
575 0, // makeDataReadyCallback
576 0, // makeDataReadyRefcon
577 fmt_desc, // formatDescription
579 0, // numSampleTimingEntries
580 NULL, // sampleTimingArray
581 0, // numSampleSizeEntries
582 NULL, // sampleSizeArray
587 CFRelease(block_buf);
592 static void videotoolbox_decoder_callback(void *opaque,
593 void *sourceFrameRefCon,
595 VTDecodeInfoFlags flags,
596 CVImageBufferRef image_buffer,
600 AVCodecContext *avctx = opaque;
601 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
604 CVPixelBufferRelease(vtctx->frame);
609 av_log(NULL, AV_LOG_DEBUG, "vt decoder cb: output image buffer is null\n");
613 vtctx->frame = CVPixelBufferRetain(image_buffer);
616 static OSStatus videotoolbox_session_decode_frame(AVCodecContext *avctx)
619 CMSampleBufferRef sample_buf;
620 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
621 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
623 sample_buf = videotoolbox_sample_buffer_create(videotoolbox->cm_fmt_desc,
625 vtctx->bitstream_size);
630 status = VTDecompressionSessionDecodeFrame(videotoolbox->session,
633 NULL, // sourceFrameRefCon
636 status = VTDecompressionSessionWaitForAsynchronousFrames(videotoolbox->session);
638 CFRelease(sample_buf);
643 static CMVideoFormatDescriptionRef videotoolbox_format_desc_create(CMVideoCodecType codec_type,
644 CFDictionaryRef decoder_spec,
648 CMFormatDescriptionRef cm_fmt_desc;
651 status = CMVideoFormatDescriptionCreate(kCFAllocatorDefault,
655 decoder_spec, // Dictionary of extension
664 static CFDictionaryRef videotoolbox_buffer_attributes_create(int width,
668 CFMutableDictionaryRef buffer_attributes;
669 CFMutableDictionaryRef io_surface_properties;
670 CFNumberRef cv_pix_fmt;
674 w = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width);
675 h = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height);
676 cv_pix_fmt = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pix_fmt);
678 buffer_attributes = CFDictionaryCreateMutable(kCFAllocatorDefault,
680 &kCFTypeDictionaryKeyCallBacks,
681 &kCFTypeDictionaryValueCallBacks);
682 io_surface_properties = CFDictionaryCreateMutable(kCFAllocatorDefault,
684 &kCFTypeDictionaryKeyCallBacks,
685 &kCFTypeDictionaryValueCallBacks);
688 CFDictionarySetValue(buffer_attributes, kCVPixelBufferPixelFormatTypeKey, cv_pix_fmt);
689 CFDictionarySetValue(buffer_attributes, kCVPixelBufferIOSurfacePropertiesKey, io_surface_properties);
690 CFDictionarySetValue(buffer_attributes, kCVPixelBufferWidthKey, w);
691 CFDictionarySetValue(buffer_attributes, kCVPixelBufferHeightKey, h);
693 CFDictionarySetValue(buffer_attributes, kCVPixelBufferOpenGLESCompatibilityKey, kCFBooleanTrue);
695 CFDictionarySetValue(buffer_attributes, kCVPixelBufferIOSurfaceOpenGLTextureCompatibilityKey, kCFBooleanTrue);
698 CFRelease(io_surface_properties);
699 CFRelease(cv_pix_fmt);
703 return buffer_attributes;
706 static CFDictionaryRef videotoolbox_decoder_config_create(CMVideoCodecType codec_type,
707 AVCodecContext *avctx)
709 CFMutableDictionaryRef config_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
711 &kCFTypeDictionaryKeyCallBacks,
712 &kCFTypeDictionaryValueCallBacks);
714 CFDictionarySetValue(config_info,
715 kVTVideoDecoderSpecification_RequireHardwareAcceleratedVideoDecoder,
718 CFMutableDictionaryRef avc_info;
719 CFDataRef data = NULL;
721 avc_info = CFDictionaryCreateMutable(kCFAllocatorDefault,
723 &kCFTypeDictionaryKeyCallBacks,
724 &kCFTypeDictionaryValueCallBacks);
726 switch (codec_type) {
727 case kCMVideoCodecType_MPEG4Video :
728 if (avctx->extradata_size)
729 data = videotoolbox_esds_extradata_create(avctx);
731 CFDictionarySetValue(avc_info, CFSTR("esds"), data);
733 case kCMVideoCodecType_H264 :
734 data = ff_videotoolbox_avcc_extradata_create(avctx);
736 CFDictionarySetValue(avc_info, CFSTR("avcC"), data);
738 case kCMVideoCodecType_HEVC :
739 data = ff_videotoolbox_hvcc_extradata_create(avctx);
741 CFDictionarySetValue(avc_info, CFSTR("hvcC"), data);
747 CFDictionarySetValue(config_info,
748 kCMFormatDescriptionExtension_SampleDescriptionExtensionAtoms,
758 static int videotoolbox_start(AVCodecContext *avctx)
760 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
762 VTDecompressionOutputCallbackRecord decoder_cb;
763 CFDictionaryRef decoder_spec;
764 CFDictionaryRef buf_attr;
767 av_log(avctx, AV_LOG_ERROR, "hwaccel context is not set\n");
771 switch( avctx->codec_id ) {
772 case AV_CODEC_ID_H263 :
773 videotoolbox->cm_codec_type = kCMVideoCodecType_H263;
775 case AV_CODEC_ID_H264 :
776 videotoolbox->cm_codec_type = kCMVideoCodecType_H264;
778 case AV_CODEC_ID_HEVC :
779 videotoolbox->cm_codec_type = kCMVideoCodecType_HEVC;
781 case AV_CODEC_ID_MPEG1VIDEO :
782 videotoolbox->cm_codec_type = kCMVideoCodecType_MPEG1Video;
784 case AV_CODEC_ID_MPEG2VIDEO :
785 videotoolbox->cm_codec_type = kCMVideoCodecType_MPEG2Video;
787 case AV_CODEC_ID_MPEG4 :
788 videotoolbox->cm_codec_type = kCMVideoCodecType_MPEG4Video;
794 decoder_spec = videotoolbox_decoder_config_create(videotoolbox->cm_codec_type, avctx);
797 av_log(avctx, AV_LOG_ERROR, "decoder specification creation failed\n");
801 videotoolbox->cm_fmt_desc = videotoolbox_format_desc_create(videotoolbox->cm_codec_type,
805 if (!videotoolbox->cm_fmt_desc) {
807 CFRelease(decoder_spec);
809 av_log(avctx, AV_LOG_ERROR, "format description creation failed\n");
813 buf_attr = videotoolbox_buffer_attributes_create(avctx->width,
815 videotoolbox->cv_pix_fmt_type);
817 decoder_cb.decompressionOutputCallback = videotoolbox_decoder_callback;
818 decoder_cb.decompressionOutputRefCon = avctx;
820 status = VTDecompressionSessionCreate(NULL, // allocator
821 videotoolbox->cm_fmt_desc, // videoFormatDescription
822 decoder_spec, // videoDecoderSpecification
823 buf_attr, // destinationImageBufferAttributes
824 &decoder_cb, // outputCallback
825 &videotoolbox->session); // decompressionSessionOut
828 CFRelease(decoder_spec);
833 case kVTVideoDecoderNotAvailableNowErr:
834 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox session not available.\n");
835 return AVERROR(ENOSYS);
836 case kVTVideoDecoderUnsupportedDataFormatErr:
837 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox does not support this format.\n");
838 return AVERROR(ENOSYS);
839 case kVTVideoDecoderMalfunctionErr:
840 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox malfunction.\n");
841 return AVERROR(EINVAL);
842 case kVTVideoDecoderBadDataErr:
843 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox reported invalid data.\n");
844 return AVERROR_INVALIDDATA;
848 av_log(avctx, AV_LOG_VERBOSE, "Unknown VideoToolbox session creation error %u\n", (unsigned)status);
849 return AVERROR_UNKNOWN;
853 static void videotoolbox_stop(AVCodecContext *avctx)
855 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
859 if (videotoolbox->cm_fmt_desc) {
860 CFRelease(videotoolbox->cm_fmt_desc);
861 videotoolbox->cm_fmt_desc = NULL;
864 if (videotoolbox->session) {
865 VTDecompressionSessionInvalidate(videotoolbox->session);
866 CFRelease(videotoolbox->session);
867 videotoolbox->session = NULL;
871 static const char *videotoolbox_error_string(OSStatus status)
874 case kVTVideoDecoderBadDataErr:
876 case kVTVideoDecoderMalfunctionErr:
877 return "decoder malfunction";
878 case kVTInvalidSessionErr:
879 return "invalid session";
884 static int videotoolbox_common_end_frame(AVCodecContext *avctx, AVFrame *frame)
887 AVVideotoolboxContext *videotoolbox = videotoolbox_get_context(avctx);
888 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
890 if (vtctx->reconfig_needed == true) {
891 vtctx->reconfig_needed = false;
892 av_log(avctx, AV_LOG_VERBOSE, "VideoToolbox decoder needs reconfig, restarting..\n");
893 videotoolbox_stop(avctx);
894 if (videotoolbox_start(avctx) != 0) {
895 return AVERROR_EXTERNAL;
899 if (!videotoolbox->session || !vtctx->bitstream || !vtctx->bitstream_size)
900 return AVERROR_INVALIDDATA;
902 status = videotoolbox_session_decode_frame(avctx);
903 if (status != noErr) {
904 if (status == kVTVideoDecoderMalfunctionErr || status == kVTInvalidSessionErr)
905 vtctx->reconfig_needed = true;
906 av_log(avctx, AV_LOG_ERROR, "Failed to decode frame (%s, %d)\n", videotoolbox_error_string(status), (int)status);
907 return AVERROR_UNKNOWN;
911 vtctx->reconfig_needed = true;
912 return AVERROR_UNKNOWN;
915 return videotoolbox_buffer_create(avctx, frame);
918 static int videotoolbox_h264_end_frame(AVCodecContext *avctx)
920 H264Context *h = avctx->priv_data;
921 AVFrame *frame = h->cur_pic_ptr->f;
922 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
923 int ret = videotoolbox_common_end_frame(avctx, frame);
924 vtctx->bitstream_size = 0;
928 static int videotoolbox_hevc_decode_params(AVCodecContext *avctx,
930 const uint8_t *buffer,
933 return ff_videotoolbox_h264_decode_slice(avctx, buffer, size);
936 static int videotoolbox_hevc_end_frame(AVCodecContext *avctx)
938 HEVCContext *h = avctx->priv_data;
939 AVFrame *frame = h->ref->frame;
940 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
943 ret = videotoolbox_common_end_frame(avctx, frame);
944 vtctx->bitstream_size = 0;
948 static int videotoolbox_mpeg_start_frame(AVCodecContext *avctx,
949 const uint8_t *buffer,
952 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
954 return videotoolbox_buffer_copy(vtctx, buffer, size);
957 static int videotoolbox_mpeg_decode_slice(AVCodecContext *avctx,
958 const uint8_t *buffer,
964 static int videotoolbox_mpeg_end_frame(AVCodecContext *avctx)
966 MpegEncContext *s = avctx->priv_data;
967 AVFrame *frame = s->current_picture_ptr->f;
969 return videotoolbox_common_end_frame(avctx, frame);
972 static int videotoolbox_uninit(AVCodecContext *avctx)
974 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
978 ff_videotoolbox_uninit(avctx);
981 videotoolbox_stop(avctx);
983 av_buffer_unref(&vtctx->cached_hw_frames_ctx);
984 av_freep(&vtctx->vt_ctx);
989 static int videotoolbox_common_init(AVCodecContext *avctx)
991 VTContext *vtctx = avctx->internal->hwaccel_priv_data;
992 AVHWFramesContext *hw_frames;
995 // Old API - do nothing.
996 if (avctx->hwaccel_context)
999 if (!avctx->hw_frames_ctx && !avctx->hw_device_ctx) {
1000 av_log(avctx, AV_LOG_ERROR,
1001 "Either hw_frames_ctx or hw_device_ctx must be set.\n");
1002 return AVERROR(EINVAL);
1005 vtctx->vt_ctx = av_videotoolbox_alloc_context();
1006 if (!vtctx->vt_ctx) {
1007 err = AVERROR(ENOMEM);
1011 if (avctx->hw_frames_ctx) {
1012 hw_frames = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1014 avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
1015 if (!avctx->hw_frames_ctx) {
1016 err = AVERROR(ENOMEM);
1020 hw_frames = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1021 hw_frames->format = AV_PIX_FMT_VIDEOTOOLBOX;
1022 hw_frames->sw_format = AV_PIX_FMT_NV12; // same as av_videotoolbox_alloc_context()
1023 hw_frames->width = avctx->width;
1024 hw_frames->height = avctx->height;
1026 err = av_hwframe_ctx_init(avctx->hw_frames_ctx);
1028 av_buffer_unref(&avctx->hw_frames_ctx);
1033 vtctx->cached_hw_frames_ctx = av_buffer_ref(avctx->hw_frames_ctx);
1034 if (!vtctx->cached_hw_frames_ctx) {
1035 err = AVERROR(ENOMEM);
1039 vtctx->vt_ctx->cv_pix_fmt_type =
1040 av_map_videotoolbox_format_from_pixfmt(hw_frames->sw_format);
1041 if (!vtctx->vt_ctx->cv_pix_fmt_type) {
1042 av_log(avctx, AV_LOG_ERROR, "Unknown sw_format.\n");
1043 err = AVERROR(EINVAL);
1047 err = videotoolbox_start(avctx);
1054 videotoolbox_uninit(avctx);
1058 static int videotoolbox_frame_params(AVCodecContext *avctx,
1059 AVBufferRef *hw_frames_ctx)
1061 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
1063 frames_ctx->format = AV_PIX_FMT_VIDEOTOOLBOX;
1064 frames_ctx->width = avctx->coded_width;
1065 frames_ctx->height = avctx->coded_height;
1066 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1071 const AVHWAccel ff_h263_videotoolbox_hwaccel = {
1072 .name = "h263_videotoolbox",
1073 .type = AVMEDIA_TYPE_VIDEO,
1074 .id = AV_CODEC_ID_H263,
1075 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1076 .alloc_frame = ff_videotoolbox_alloc_frame,
1077 .start_frame = videotoolbox_mpeg_start_frame,
1078 .decode_slice = videotoolbox_mpeg_decode_slice,
1079 .end_frame = videotoolbox_mpeg_end_frame,
1080 .frame_params = videotoolbox_frame_params,
1081 .init = videotoolbox_common_init,
1082 .uninit = videotoolbox_uninit,
1083 .priv_data_size = sizeof(VTContext),
1086 const AVHWAccel ff_hevc_videotoolbox_hwaccel = {
1087 .name = "hevc_videotoolbox",
1088 .type = AVMEDIA_TYPE_VIDEO,
1089 .id = AV_CODEC_ID_HEVC,
1090 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1091 .alloc_frame = ff_videotoolbox_alloc_frame,
1092 .start_frame = ff_videotoolbox_h264_start_frame,
1093 .decode_slice = ff_videotoolbox_h264_decode_slice,
1094 .decode_params = videotoolbox_hevc_decode_params,
1095 .end_frame = videotoolbox_hevc_end_frame,
1096 .frame_params = videotoolbox_frame_params,
1097 .init = videotoolbox_common_init,
1098 .uninit = ff_videotoolbox_uninit,
1099 .priv_data_size = sizeof(VTContext),
1102 const AVHWAccel ff_h264_videotoolbox_hwaccel = {
1103 .name = "h264_videotoolbox",
1104 .type = AVMEDIA_TYPE_VIDEO,
1105 .id = AV_CODEC_ID_H264,
1106 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1107 .alloc_frame = ff_videotoolbox_alloc_frame,
1108 .start_frame = ff_videotoolbox_h264_start_frame,
1109 .decode_slice = ff_videotoolbox_h264_decode_slice,
1110 .decode_params = videotoolbox_h264_decode_params,
1111 .end_frame = videotoolbox_h264_end_frame,
1112 .frame_params = videotoolbox_frame_params,
1113 .init = videotoolbox_common_init,
1114 .uninit = videotoolbox_uninit,
1115 .priv_data_size = sizeof(VTContext),
1118 const AVHWAccel ff_mpeg1_videotoolbox_hwaccel = {
1119 .name = "mpeg1_videotoolbox",
1120 .type = AVMEDIA_TYPE_VIDEO,
1121 .id = AV_CODEC_ID_MPEG1VIDEO,
1122 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1123 .alloc_frame = ff_videotoolbox_alloc_frame,
1124 .start_frame = videotoolbox_mpeg_start_frame,
1125 .decode_slice = videotoolbox_mpeg_decode_slice,
1126 .end_frame = videotoolbox_mpeg_end_frame,
1127 .frame_params = videotoolbox_frame_params,
1128 .init = videotoolbox_common_init,
1129 .uninit = videotoolbox_uninit,
1130 .priv_data_size = sizeof(VTContext),
1133 const AVHWAccel ff_mpeg2_videotoolbox_hwaccel = {
1134 .name = "mpeg2_videotoolbox",
1135 .type = AVMEDIA_TYPE_VIDEO,
1136 .id = AV_CODEC_ID_MPEG2VIDEO,
1137 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1138 .alloc_frame = ff_videotoolbox_alloc_frame,
1139 .start_frame = videotoolbox_mpeg_start_frame,
1140 .decode_slice = videotoolbox_mpeg_decode_slice,
1141 .end_frame = videotoolbox_mpeg_end_frame,
1142 .frame_params = videotoolbox_frame_params,
1143 .init = videotoolbox_common_init,
1144 .uninit = videotoolbox_uninit,
1145 .priv_data_size = sizeof(VTContext),
1148 const AVHWAccel ff_mpeg4_videotoolbox_hwaccel = {
1149 .name = "mpeg4_videotoolbox",
1150 .type = AVMEDIA_TYPE_VIDEO,
1151 .id = AV_CODEC_ID_MPEG4,
1152 .pix_fmt = AV_PIX_FMT_VIDEOTOOLBOX,
1153 .alloc_frame = ff_videotoolbox_alloc_frame,
1154 .start_frame = videotoolbox_mpeg_start_frame,
1155 .decode_slice = videotoolbox_mpeg_decode_slice,
1156 .end_frame = videotoolbox_mpeg_end_frame,
1157 .frame_params = videotoolbox_frame_params,
1158 .init = videotoolbox_common_init,
1159 .uninit = videotoolbox_uninit,
1160 .priv_data_size = sizeof(VTContext),
1163 AVVideotoolboxContext *av_videotoolbox_alloc_context(void)
1165 AVVideotoolboxContext *ret = av_mallocz(sizeof(*ret));
1168 ret->output_callback = videotoolbox_decoder_callback;
1169 ret->cv_pix_fmt_type = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
1175 int av_videotoolbox_default_init(AVCodecContext *avctx)
1177 return av_videotoolbox_default_init2(avctx, NULL);
1180 int av_videotoolbox_default_init2(AVCodecContext *avctx, AVVideotoolboxContext *vtctx)
1182 avctx->hwaccel_context = vtctx ?: av_videotoolbox_alloc_context();
1183 if (!avctx->hwaccel_context)
1184 return AVERROR(ENOMEM);
1185 return videotoolbox_start(avctx);
1188 void av_videotoolbox_default_free(AVCodecContext *avctx)
1191 videotoolbox_stop(avctx);
1192 av_freep(&avctx->hwaccel_context);
1194 #endif /* CONFIG_VIDEOTOOLBOX */