2 * copyright (c) 2015 Rick Kern <kernrj@gmail.com>
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
27 #include "libavutil/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavcodec/avcodec.h"
31 #include "libavutil/pixdesc.h"
39 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
40 enum { kCMVideoCodecType_HEVC = 'hvc1' };
43 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
44 enum { kCVPixelFormatType_420YpCbCr10BiPlanarFullRange = 'xf20' };
45 enum { kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange = 'x420' };
48 typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
49 size_t parameterSetIndex,
50 const uint8_t **parameterSetPointerOut,
51 size_t *parameterSetSizeOut,
52 size_t *parameterSetCountOut,
53 int *NALUnitHeaderLengthOut);
55 //These symbols may not be present
57 CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020;
58 CFStringRef kCVImageBufferTransferFunction_ITU_R_2020;
59 CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020;
61 CFStringRef kVTCompressionPropertyKey_H264EntropyMode;
62 CFStringRef kVTH264EntropyMode_CAVLC;
63 CFStringRef kVTH264EntropyMode_CABAC;
65 CFStringRef kVTProfileLevel_H264_Baseline_4_0;
66 CFStringRef kVTProfileLevel_H264_Baseline_4_2;
67 CFStringRef kVTProfileLevel_H264_Baseline_5_0;
68 CFStringRef kVTProfileLevel_H264_Baseline_5_1;
69 CFStringRef kVTProfileLevel_H264_Baseline_5_2;
70 CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel;
71 CFStringRef kVTProfileLevel_H264_Main_4_2;
72 CFStringRef kVTProfileLevel_H264_Main_5_1;
73 CFStringRef kVTProfileLevel_H264_Main_5_2;
74 CFStringRef kVTProfileLevel_H264_Main_AutoLevel;
75 CFStringRef kVTProfileLevel_H264_High_3_0;
76 CFStringRef kVTProfileLevel_H264_High_3_1;
77 CFStringRef kVTProfileLevel_H264_High_3_2;
78 CFStringRef kVTProfileLevel_H264_High_4_0;
79 CFStringRef kVTProfileLevel_H264_High_4_1;
80 CFStringRef kVTProfileLevel_H264_High_4_2;
81 CFStringRef kVTProfileLevel_H264_High_5_1;
82 CFStringRef kVTProfileLevel_H264_High_5_2;
83 CFStringRef kVTProfileLevel_H264_High_AutoLevel;
84 CFStringRef kVTProfileLevel_H264_Extended_5_0;
85 CFStringRef kVTProfileLevel_H264_Extended_AutoLevel;
87 CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel;
88 CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel;
90 CFStringRef kVTCompressionPropertyKey_RealTime;
92 CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder;
93 CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder;
95 getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
98 #define GET_SYM(symbol, defaultVal) \
100 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
102 compat_keys.symbol = CFSTR(defaultVal); \
104 compat_keys.symbol = *handle; \
107 static pthread_once_t once_ctrl = PTHREAD_ONCE_INIT;
109 static void loadVTEncSymbols(){
110 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
111 (getParameterSetAtIndex)dlsym(
113 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
116 GET_SYM(kCVImageBufferColorPrimaries_ITU_R_2020, "ITU_R_2020");
117 GET_SYM(kCVImageBufferTransferFunction_ITU_R_2020, "ITU_R_2020");
118 GET_SYM(kCVImageBufferYCbCrMatrix_ITU_R_2020, "ITU_R_2020");
120 GET_SYM(kVTCompressionPropertyKey_H264EntropyMode, "H264EntropyMode");
121 GET_SYM(kVTH264EntropyMode_CAVLC, "CAVLC");
122 GET_SYM(kVTH264EntropyMode_CABAC, "CABAC");
124 GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
125 GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
126 GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
127 GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
128 GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
129 GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
130 GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
131 GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
132 GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
133 GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
134 GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
135 GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
136 GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
137 GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
138 GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
139 GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
140 GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
141 GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
142 GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
143 GET_SYM(kVTProfileLevel_H264_Extended_5_0, "H264_Extended_5_0");
144 GET_SYM(kVTProfileLevel_H264_Extended_AutoLevel, "H264_Extended_AutoLevel");
146 GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
147 GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
149 GET_SYM(kVTCompressionPropertyKey_RealTime, "RealTime");
151 GET_SYM(kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
152 "EnableHardwareAcceleratedVideoEncoder");
153 GET_SYM(kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
154 "RequireHardwareAcceleratedVideoEncoder");
157 typedef enum VT_H264Profile {
166 typedef enum VTH264Entropy{
172 typedef enum VT_HEVCProfile {
179 static const uint8_t start_code[] = { 0, 0, 0, 1 };
181 typedef struct ExtraSEI {
186 typedef struct BufNode {
187 CMSampleBufferRef cm_buffer;
189 struct BufNode* next;
193 typedef struct VTEncContext {
195 enum AVCodecID codec_id;
196 VTCompressionSessionRef session;
197 CFStringRef ycbcr_matrix;
198 CFStringRef color_primaries;
199 CFStringRef transfer_function;
200 getParameterSetAtIndex get_param_set_func;
202 pthread_mutex_t lock;
203 pthread_cond_t cv_sample_sent;
210 int64_t frame_ct_out;
220 int64_t frames_before;
221 int64_t frames_after;
228 bool warned_color_range;
230 /* can't be bool type since AVOption will access it as int */
234 static int vtenc_populate_extradata(AVCodecContext *avctx,
235 CMVideoCodecType codec_type,
236 CFStringRef profile_level,
237 CFNumberRef gamma_level,
238 CFDictionaryRef enc_info,
239 CFDictionaryRef pixel_buffer_info);
242 * NULL-safe release of *refPtr, and sets value to NULL.
244 static void vt_release_num(CFNumberRef* refPtr){
253 static void set_async_error(VTEncContext *vtctx, int err)
257 pthread_mutex_lock(&vtctx->lock);
259 vtctx->async_error = err;
261 info = vtctx->q_head;
262 vtctx->q_head = vtctx->q_tail = NULL;
265 BufNode *next = info->next;
266 CFRelease(info->cm_buffer);
271 pthread_mutex_unlock(&vtctx->lock);
274 static void clear_frame_queue(VTEncContext *vtctx)
276 set_async_error(vtctx, 0);
279 static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
283 pthread_mutex_lock(&vtctx->lock);
285 if (vtctx->async_error) {
286 pthread_mutex_unlock(&vtctx->lock);
287 return vtctx->async_error;
290 if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
293 pthread_mutex_unlock(&vtctx->lock);
297 while (!vtctx->q_head && !vtctx->async_error && wait && !vtctx->flushing) {
298 pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
301 if (!vtctx->q_head) {
302 pthread_mutex_unlock(&vtctx->lock);
307 info = vtctx->q_head;
308 vtctx->q_head = vtctx->q_head->next;
309 if (!vtctx->q_head) {
310 vtctx->q_tail = NULL;
313 vtctx->frame_ct_out++;
314 pthread_mutex_unlock(&vtctx->lock);
316 *buf = info->cm_buffer;
319 } else if (info->sei) {
320 if (info->sei->data) av_free(info->sei->data);
329 static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
331 BufNode *info = av_malloc(sizeof(BufNode));
333 set_async_error(vtctx, AVERROR(ENOMEM));
338 info->cm_buffer = buffer;
342 pthread_mutex_lock(&vtctx->lock);
344 if (!vtctx->q_head) {
345 vtctx->q_head = info;
347 vtctx->q_tail->next = info;
350 vtctx->q_tail = info;
352 pthread_cond_signal(&vtctx->cv_sample_sent);
353 pthread_mutex_unlock(&vtctx->lock);
356 static int count_nalus(size_t length_code_size,
357 CMSampleBufferRef sample_buffer,
364 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
365 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
367 if (length_code_size > 4)
368 return AVERROR_INVALIDDATA;
370 while (offset < src_size) {
375 status = CMBlockBufferCopyDataBytes(block,
380 for (i = 0; i < length_code_size; i++) {
382 box_len |= size_buf[i];
385 curr_src_len = box_len + length_code_size;
386 offset += curr_src_len;
395 static CMVideoCodecType get_cm_codec_type(enum AVCodecID id)
398 case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
399 case AV_CODEC_ID_HEVC: return kCMVideoCodecType_HEVC;
405 * Get the parameter sets from a CMSampleBufferRef.
406 * @param dst If *dst isn't NULL, the parameters are copied into existing
407 * memory. *dst_size must be set accordingly when *dst != NULL.
408 * If *dst is NULL, it will be allocated.
409 * In all cases, *dst_size is set to the number of bytes used starting
412 static int get_params_size(
413 AVCodecContext *avctx,
414 CMVideoFormatDescriptionRef vid_fmt,
417 VTEncContext *vtctx = avctx->priv_data;
418 size_t total_size = 0;
420 int is_count_bad = 0;
423 status = vtctx->get_param_set_func(vid_fmt,
435 for (i = 0; i < ps_count || is_count_bad; i++) {
438 status = vtctx->get_param_set_func(vid_fmt,
446 * When ps_count is invalid, status != 0 ends the loop normally
447 * unless we didn't get any parameter sets.
449 if (i > 0 && is_count_bad) status = 0;
454 total_size += ps_size + sizeof(start_code);
458 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
459 return AVERROR_EXTERNAL;
466 static int copy_param_sets(
467 AVCodecContext *avctx,
468 CMVideoFormatDescriptionRef vid_fmt,
472 VTEncContext *vtctx = avctx->priv_data;
474 int is_count_bad = 0;
479 status = vtctx->get_param_set_func(vid_fmt,
492 for (i = 0; i < ps_count || is_count_bad; i++) {
497 status = vtctx->get_param_set_func(vid_fmt,
504 if (i > 0 && is_count_bad) status = 0;
509 next_offset = offset + sizeof(start_code) + ps_size;
510 if (dst_size < next_offset) {
511 av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
512 return AVERROR_BUFFER_TOO_SMALL;
515 memcpy(dst + offset, start_code, sizeof(start_code));
516 offset += sizeof(start_code);
518 memcpy(dst + offset, ps, ps_size);
519 offset = next_offset;
523 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
524 return AVERROR_EXTERNAL;
530 static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
532 CMVideoFormatDescriptionRef vid_fmt;
536 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
538 av_log(avctx, AV_LOG_ERROR, "No video format.\n");
539 return AVERROR_EXTERNAL;
542 status = get_params_size(avctx, vid_fmt, &total_size);
544 av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
548 avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
549 if (!avctx->extradata) {
550 return AVERROR(ENOMEM);
552 avctx->extradata_size = total_size;
554 status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
557 av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
564 static void vtenc_output_callback(
566 void *sourceFrameCtx,
568 VTEncodeInfoFlags flags,
569 CMSampleBufferRef sample_buffer)
571 AVCodecContext *avctx = ctx;
572 VTEncContext *vtctx = avctx->priv_data;
573 ExtraSEI *sei = sourceFrameCtx;
575 if (vtctx->async_error) {
580 av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
581 set_async_error(vtctx, AVERROR_EXTERNAL);
585 if (!sample_buffer) {
589 if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
590 int set_status = set_extradata(avctx, sample_buffer);
592 set_async_error(vtctx, set_status);
597 vtenc_q_push(vtctx, sample_buffer, sei);
600 static int get_length_code_size(
601 AVCodecContext *avctx,
602 CMSampleBufferRef sample_buffer,
605 VTEncContext *vtctx = avctx->priv_data;
606 CMVideoFormatDescriptionRef vid_fmt;
610 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
612 av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
613 return AVERROR_EXTERNAL;
616 status = vtctx->get_param_set_func(vid_fmt,
623 av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
624 return AVERROR_EXTERNAL;
632 * Returns true on success.
634 * If profile_level_val is NULL and this method returns true, don't specify the
635 * profile/level to the encoder.
637 static bool get_vt_h264_profile_level(AVCodecContext *avctx,
638 CFStringRef *profile_level_val)
640 VTEncContext *vtctx = avctx->priv_data;
641 int64_t profile = vtctx->profile;
643 if (profile == H264_PROF_AUTO && vtctx->level) {
644 //Need to pick a profile if level is not auto-selected.
645 profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;
648 *profile_level_val = NULL;
654 case H264_PROF_BASELINE:
655 switch (vtctx->level) {
656 case 0: *profile_level_val =
657 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
658 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
659 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
660 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
661 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
662 case 40: *profile_level_val =
663 compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
664 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
665 case 42: *profile_level_val =
666 compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
667 case 50: *profile_level_val =
668 compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
669 case 51: *profile_level_val =
670 compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
671 case 52: *profile_level_val =
672 compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
677 switch (vtctx->level) {
678 case 0: *profile_level_val =
679 compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
680 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
681 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
682 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
683 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
684 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
685 case 42: *profile_level_val =
686 compat_keys.kVTProfileLevel_H264_Main_4_2; break;
687 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
688 case 51: *profile_level_val =
689 compat_keys.kVTProfileLevel_H264_Main_5_1; break;
690 case 52: *profile_level_val =
691 compat_keys.kVTProfileLevel_H264_Main_5_2; break;
696 switch (vtctx->level) {
697 case 0: *profile_level_val =
698 compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
699 case 30: *profile_level_val =
700 compat_keys.kVTProfileLevel_H264_High_3_0; break;
701 case 31: *profile_level_val =
702 compat_keys.kVTProfileLevel_H264_High_3_1; break;
703 case 32: *profile_level_val =
704 compat_keys.kVTProfileLevel_H264_High_3_2; break;
705 case 40: *profile_level_val =
706 compat_keys.kVTProfileLevel_H264_High_4_0; break;
707 case 41: *profile_level_val =
708 compat_keys.kVTProfileLevel_H264_High_4_1; break;
709 case 42: *profile_level_val =
710 compat_keys.kVTProfileLevel_H264_High_4_2; break;
711 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
712 case 51: *profile_level_val =
713 compat_keys.kVTProfileLevel_H264_High_5_1; break;
714 case 52: *profile_level_val =
715 compat_keys.kVTProfileLevel_H264_High_5_2; break;
718 case H264_PROF_EXTENDED:
719 switch (vtctx->level) {
720 case 0: *profile_level_val =
721 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel; break;
722 case 50: *profile_level_val =
723 compat_keys.kVTProfileLevel_H264_Extended_5_0; break;
728 if (!*profile_level_val) {
729 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
737 * Returns true on success.
739 * If profile_level_val is NULL and this method returns true, don't specify the
740 * profile/level to the encoder.
742 static bool get_vt_hevc_profile_level(AVCodecContext *avctx,
743 CFStringRef *profile_level_val)
745 VTEncContext *vtctx = avctx->priv_data;
746 int64_t profile = vtctx->profile;
748 *profile_level_val = NULL;
755 compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
757 case HEVC_PROF_MAIN10:
759 compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
763 if (!*profile_level_val) {
764 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
771 static int get_cv_pixel_format(AVCodecContext* avctx,
772 enum AVPixelFormat fmt,
773 enum AVColorRange range,
774 int* av_pixel_format,
777 if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
778 range != AVCOL_RANGE_JPEG;
780 //MPEG range is used when no range is set
781 if (fmt == AV_PIX_FMT_NV12) {
782 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
783 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
784 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
785 } else if (fmt == AV_PIX_FMT_YUV420P) {
786 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
787 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
788 kCVPixelFormatType_420YpCbCr8Planar;
789 } else if (fmt == AV_PIX_FMT_P010LE) {
790 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
791 kCVPixelFormatType_420YpCbCr10BiPlanarFullRange :
792 kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
794 return AVERROR(EINVAL);
800 static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
801 VTEncContext *vtctx = avctx->priv_data;
803 if (vtctx->color_primaries) {
804 CFDictionarySetValue(dict,
805 kCVImageBufferColorPrimariesKey,
806 vtctx->color_primaries);
809 if (vtctx->transfer_function) {
810 CFDictionarySetValue(dict,
811 kCVImageBufferTransferFunctionKey,
812 vtctx->transfer_function);
815 if (vtctx->ycbcr_matrix) {
816 CFDictionarySetValue(dict,
817 kCVImageBufferYCbCrMatrixKey,
818 vtctx->ycbcr_matrix);
822 static int create_cv_pixel_buffer_info(AVCodecContext* avctx,
823 CFMutableDictionaryRef* dict)
825 CFNumberRef cv_color_format_num = NULL;
826 CFNumberRef width_num = NULL;
827 CFNumberRef height_num = NULL;
828 CFMutableDictionaryRef pixel_buffer_info = NULL;
830 int status = get_cv_pixel_format(avctx,
835 if (status) return status;
837 pixel_buffer_info = CFDictionaryCreateMutable(
840 &kCFCopyStringDictionaryKeyCallBacks,
841 &kCFTypeDictionaryValueCallBacks);
843 if (!pixel_buffer_info) goto pbinfo_nomem;
845 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
848 if (!cv_color_format_num) goto pbinfo_nomem;
850 CFDictionarySetValue(pixel_buffer_info,
851 kCVPixelBufferPixelFormatTypeKey,
852 cv_color_format_num);
853 vt_release_num(&cv_color_format_num);
855 width_num = CFNumberCreate(kCFAllocatorDefault,
858 if (!width_num) return AVERROR(ENOMEM);
860 CFDictionarySetValue(pixel_buffer_info,
861 kCVPixelBufferWidthKey,
863 vt_release_num(&width_num);
865 height_num = CFNumberCreate(kCFAllocatorDefault,
868 if (!height_num) goto pbinfo_nomem;
870 CFDictionarySetValue(pixel_buffer_info,
871 kCVPixelBufferHeightKey,
873 vt_release_num(&height_num);
875 add_color_attr(avctx, pixel_buffer_info);
877 *dict = pixel_buffer_info;
881 vt_release_num(&cv_color_format_num);
882 vt_release_num(&width_num);
883 vt_release_num(&height_num);
884 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
886 return AVERROR(ENOMEM);
889 static int get_cv_color_primaries(AVCodecContext *avctx,
890 CFStringRef *primaries)
892 enum AVColorPrimaries pri = avctx->color_primaries;
894 case AVCOL_PRI_UNSPECIFIED:
898 case AVCOL_PRI_BT470BG:
899 *primaries = kCVImageBufferColorPrimaries_EBU_3213;
902 case AVCOL_PRI_SMPTE170M:
903 *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
906 case AVCOL_PRI_BT709:
907 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
910 case AVCOL_PRI_BT2020:
911 *primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
915 av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
923 static int get_cv_transfer_function(AVCodecContext *avctx,
924 CFStringRef *transfer_fnc,
925 CFNumberRef *gamma_level)
927 enum AVColorTransferCharacteristic trc = avctx->color_trc;
932 case AVCOL_TRC_UNSPECIFIED:
933 *transfer_fnc = NULL;
936 case AVCOL_TRC_BT709:
937 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
940 case AVCOL_TRC_SMPTE240M:
941 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
944 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ
945 case AVCOL_TRC_SMPTE2084:
946 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
949 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR
950 case AVCOL_TRC_LINEAR:
951 *transfer_fnc = kCVImageBufferTransferFunction_Linear;
954 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG
955 case AVCOL_TRC_ARIB_STD_B67:
956 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
960 case AVCOL_TRC_GAMMA22:
962 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
963 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
966 case AVCOL_TRC_GAMMA28:
968 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
969 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
972 case AVCOL_TRC_BT2020_10:
973 case AVCOL_TRC_BT2020_12:
974 *transfer_fnc = compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
978 *transfer_fnc = NULL;
979 av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));
986 static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix) {
987 switch(avctx->colorspace) {
988 case AVCOL_SPC_BT709:
989 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
992 case AVCOL_SPC_UNSPECIFIED:
996 case AVCOL_SPC_BT470BG:
997 case AVCOL_SPC_SMPTE170M:
998 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1001 case AVCOL_SPC_SMPTE240M:
1002 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1005 case AVCOL_SPC_BT2020_NCL:
1006 *matrix = compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
1010 av_log(avctx, AV_LOG_ERROR, "Color space %s is not supported.\n", av_color_space_name(avctx->colorspace));
1017 static int vtenc_create_encoder(AVCodecContext *avctx,
1018 CMVideoCodecType codec_type,
1019 CFStringRef profile_level,
1020 CFNumberRef gamma_level,
1021 CFDictionaryRef enc_info,
1022 CFDictionaryRef pixel_buffer_info,
1023 VTCompressionSessionRef *session)
1025 VTEncContext *vtctx = avctx->priv_data;
1026 SInt32 bit_rate = avctx->bit_rate;
1027 SInt32 max_rate = avctx->rc_max_rate;
1028 CFNumberRef bit_rate_num;
1029 CFNumberRef bytes_per_second;
1030 CFNumberRef one_second;
1031 CFArrayRef data_rate_limits;
1032 int64_t bytes_per_second_value = 0;
1033 int64_t one_second_value = 0;
1036 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1042 kCFAllocatorDefault,
1043 vtenc_output_callback,
1047 if (status || !vtctx->session) {
1048 av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
1050 #if !TARGET_OS_IPHONE
1051 if (!vtctx->allow_sw) {
1052 av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1056 return AVERROR_EXTERNAL;
1059 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1060 kCFNumberSInt32Type,
1062 if (!bit_rate_num) return AVERROR(ENOMEM);
1064 status = VTSessionSetProperty(vtctx->session,
1065 kVTCompressionPropertyKey_AverageBitRate,
1067 CFRelease(bit_rate_num);
1070 av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
1071 return AVERROR_EXTERNAL;
1074 if (vtctx->codec_id == AV_CODEC_ID_H264 && max_rate > 0) {
1075 // kVTCompressionPropertyKey_DataRateLimits is not available for HEVC
1076 bytes_per_second_value = max_rate >> 3;
1077 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1078 kCFNumberSInt64Type,
1079 &bytes_per_second_value);
1080 if (!bytes_per_second) {
1081 return AVERROR(ENOMEM);
1083 one_second_value = 1;
1084 one_second = CFNumberCreate(kCFAllocatorDefault,
1085 kCFNumberSInt64Type,
1088 CFRelease(bytes_per_second);
1089 return AVERROR(ENOMEM);
1091 nums[0] = (void *)bytes_per_second;
1092 nums[1] = (void *)one_second;
1093 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1094 (const void **)nums,
1096 &kCFTypeArrayCallBacks);
1098 if (!data_rate_limits) {
1099 CFRelease(bytes_per_second);
1100 CFRelease(one_second);
1101 return AVERROR(ENOMEM);
1103 status = VTSessionSetProperty(vtctx->session,
1104 kVTCompressionPropertyKey_DataRateLimits,
1107 CFRelease(bytes_per_second);
1108 CFRelease(one_second);
1109 CFRelease(data_rate_limits);
1112 av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
1113 return AVERROR_EXTERNAL;
1117 if (profile_level) {
1118 status = VTSessionSetProperty(vtctx->session,
1119 kVTCompressionPropertyKey_ProfileLevel,
1122 av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1126 if (avctx->gop_size > 0) {
1127 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1131 return AVERROR(ENOMEM);
1134 status = VTSessionSetProperty(vtctx->session,
1135 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1137 CFRelease(interval);
1140 av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
1141 return AVERROR_EXTERNAL;
1145 if (vtctx->frames_before) {
1146 status = VTSessionSetProperty(vtctx->session,
1147 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1150 if (status == kVTPropertyNotSupportedErr) {
1151 av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
1152 } else if (status) {
1153 av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
1157 if (vtctx->frames_after) {
1158 status = VTSessionSetProperty(vtctx->session,
1159 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1162 if (status == kVTPropertyNotSupportedErr) {
1163 av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
1164 } else if (status) {
1165 av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
1169 if (avctx->sample_aspect_ratio.num != 0) {
1172 CFMutableDictionaryRef par;
1173 AVRational *avpar = &avctx->sample_aspect_ratio;
1175 av_reduce(&avpar->num, &avpar->den,
1176 avpar->num, avpar->den,
1179 num = CFNumberCreate(kCFAllocatorDefault,
1183 den = CFNumberCreate(kCFAllocatorDefault,
1189 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1191 &kCFCopyStringDictionaryKeyCallBacks,
1192 &kCFTypeDictionaryValueCallBacks);
1194 if (!par || !num || !den) {
1195 if (par) CFRelease(par);
1196 if (num) CFRelease(num);
1197 if (den) CFRelease(den);
1199 return AVERROR(ENOMEM);
1202 CFDictionarySetValue(
1204 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1207 CFDictionarySetValue(
1209 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1212 status = VTSessionSetProperty(vtctx->session,
1213 kVTCompressionPropertyKey_PixelAspectRatio,
1223 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1224 avctx->sample_aspect_ratio.num,
1225 avctx->sample_aspect_ratio.den,
1228 return AVERROR_EXTERNAL;
1233 if (vtctx->transfer_function) {
1234 status = VTSessionSetProperty(vtctx->session,
1235 kVTCompressionPropertyKey_TransferFunction,
1236 vtctx->transfer_function);
1239 av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1244 if (vtctx->ycbcr_matrix) {
1245 status = VTSessionSetProperty(vtctx->session,
1246 kVTCompressionPropertyKey_YCbCrMatrix,
1247 vtctx->ycbcr_matrix);
1250 av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1255 if (vtctx->color_primaries) {
1256 status = VTSessionSetProperty(vtctx->session,
1257 kVTCompressionPropertyKey_ColorPrimaries,
1258 vtctx->color_primaries);
1261 av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1266 status = VTSessionSetProperty(vtctx->session,
1267 kCVImageBufferGammaLevelKey,
1271 av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1275 if (!vtctx->has_b_frames) {
1276 status = VTSessionSetProperty(vtctx->session,
1277 kVTCompressionPropertyKey_AllowFrameReordering,
1281 av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1282 return AVERROR_EXTERNAL;
1286 if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1287 CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1288 compat_keys.kVTH264EntropyMode_CABAC:
1289 compat_keys.kVTH264EntropyMode_CAVLC;
1291 status = VTSessionSetProperty(vtctx->session,
1292 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1296 av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1300 if (vtctx->realtime) {
1301 status = VTSessionSetProperty(vtctx->session,
1302 compat_keys.kVTCompressionPropertyKey_RealTime,
1306 av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1310 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1312 av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
1313 return AVERROR_EXTERNAL;
1319 static int vtenc_configure_encoder(AVCodecContext *avctx)
1321 CFMutableDictionaryRef enc_info;
1322 CFMutableDictionaryRef pixel_buffer_info;
1323 CMVideoCodecType codec_type;
1324 VTEncContext *vtctx = avctx->priv_data;
1325 CFStringRef profile_level;
1326 CFNumberRef gamma_level = NULL;
1329 codec_type = get_cm_codec_type(avctx->codec_id);
1331 av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
1332 return AVERROR(EINVAL);
1335 vtctx->codec_id = avctx->codec_id;
1337 if (vtctx->codec_id == AV_CODEC_ID_H264) {
1338 vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
1340 vtctx->has_b_frames = avctx->max_b_frames > 0;
1341 if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){
1342 av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1343 vtctx->has_b_frames = false;
1346 if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {
1347 av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1348 vtctx->entropy = VT_ENTROPY_NOT_SET;
1351 if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1353 vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
1354 if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
1355 if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1358 enc_info = CFDictionaryCreateMutable(
1359 kCFAllocatorDefault,
1361 &kCFCopyStringDictionaryKeyCallBacks,
1362 &kCFTypeDictionaryValueCallBacks
1365 if (!enc_info) return AVERROR(ENOMEM);
1367 #if !TARGET_OS_IPHONE
1368 if(vtctx->require_sw) {
1369 CFDictionarySetValue(enc_info,
1370 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1372 } else if (!vtctx->allow_sw) {
1373 CFDictionarySetValue(enc_info,
1374 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1377 CFDictionarySetValue(enc_info,
1378 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1383 if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1384 status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1388 pixel_buffer_info = NULL;
1391 vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1393 get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);
1394 get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);
1395 get_cv_color_primaries(avctx, &vtctx->color_primaries);
1398 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1399 status = vtenc_populate_extradata(avctx,
1409 status = vtenc_create_encoder(avctx,
1419 CFRelease(gamma_level);
1421 if (pixel_buffer_info)
1422 CFRelease(pixel_buffer_info);
1424 CFRelease(enc_info);
1429 static av_cold int vtenc_init(AVCodecContext *avctx)
1431 VTEncContext *vtctx = avctx->priv_data;
1432 CFBooleanRef has_b_frames_cfbool;
1435 pthread_once(&once_ctrl, loadVTEncSymbols);
1437 pthread_mutex_init(&vtctx->lock, NULL);
1438 pthread_cond_init(&vtctx->cv_sample_sent, NULL);
1440 vtctx->session = NULL;
1441 status = vtenc_configure_encoder(avctx);
1442 if (status) return status;
1444 status = VTSessionCopyProperty(vtctx->session,
1445 kVTCompressionPropertyKey_AllowFrameReordering,
1446 kCFAllocatorDefault,
1447 &has_b_frames_cfbool);
1449 if (!status && has_b_frames_cfbool) {
1450 //Some devices don't output B-frames for main profile, even if requested.
1451 vtctx->has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1452 CFRelease(has_b_frames_cfbool);
1454 avctx->has_b_frames = vtctx->has_b_frames;
1459 static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1461 CFArrayRef attachments;
1462 CFDictionaryRef attachment;
1463 CFBooleanRef not_sync;
1466 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1467 len = !attachments ? 0 : CFArrayGetCount(attachments);
1470 *is_key_frame = true;
1474 attachment = CFArrayGetValueAtIndex(attachments, 0);
1476 if (CFDictionaryGetValueIfPresent(attachment,
1477 kCMSampleAttachmentKey_NotSync,
1478 (const void **)¬_sync))
1480 *is_key_frame = !CFBooleanGetValue(not_sync);
1482 *is_key_frame = true;
1486 static int is_post_sei_nal_type(int nal_type){
1487 return nal_type != H264_NAL_SEI &&
1488 nal_type != H264_NAL_SPS &&
1489 nal_type != H264_NAL_PPS &&
1490 nal_type != H264_NAL_AUD;
1494 * Finds the sei message start/size of type find_sei_type.
1495 * If more than one of that type exists, the last one is returned.
1497 static int find_sei_end(AVCodecContext *avctx,
1503 size_t sei_payload_size = 0;
1504 int sei_payload_type = 0;
1506 uint8_t *nal_start = nal_data;
1511 nal_type = *nal_data & 0x1F;
1512 if (nal_type != H264_NAL_SEI)
1518 if (nal_data[nal_size - 1] == 0x80)
1521 while (nal_size > 0 && *nal_data > 0) {
1523 sei_payload_type += *nal_data;
1526 } while (nal_size > 0 && *nal_data == 0xFF);
1529 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1530 return AVERROR_INVALIDDATA;
1534 sei_payload_size += *nal_data;
1537 } while (nal_size > 0 && *nal_data == 0xFF);
1539 if (nal_size < sei_payload_size) {
1540 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1541 return AVERROR_INVALIDDATA;
1544 nal_data += sei_payload_size;
1545 nal_size -= sei_payload_size;
1548 *sei_end = nal_data;
1550 return nal_data - nal_start + 1;
1554 * Copies the data inserting emulation prevention bytes as needed.
1555 * Existing data in the destination can be taken into account by providing
1556 * dst with a dst_offset > 0.
1558 * @return The number of bytes copied on success. On failure, the negative of
1559 * the number of bytes needed to copy src is returned.
1561 static int copy_emulation_prev(const uint8_t *src,
1570 uint8_t* dst_end = dst + dst_size;
1571 const uint8_t* src_end = src + src_size;
1572 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1574 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1583 for (; src < src_end; src++, dst++) {
1585 int insert_ep3_byte = *src <= 3;
1586 if (insert_ep3_byte) {
1604 wrote_bytes = dst - dst_start;
1607 return -wrote_bytes;
1612 static int write_sei(const ExtraSEI *sei,
1617 uint8_t *sei_start = dst;
1618 size_t remaining_sei_size = sei->size;
1619 size_t remaining_dst_size = dst_size;
1624 if (!remaining_dst_size)
1625 return AVERROR_BUFFER_TOO_SMALL;
1627 while (sei_type && remaining_dst_size != 0) {
1628 int sei_byte = sei_type > 255 ? 255 : sei_type;
1631 sei_type -= sei_byte;
1633 remaining_dst_size--;
1637 return AVERROR_BUFFER_TOO_SMALL;
1639 while (remaining_sei_size && remaining_dst_size != 0) {
1640 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1643 remaining_sei_size -= size_byte;
1645 remaining_dst_size--;
1648 if (remaining_dst_size < sei->size)
1649 return AVERROR_BUFFER_TOO_SMALL;
1651 header_bytes = dst - sei_start;
1653 offset = header_bytes;
1654 bytes_written = copy_emulation_prev(sei->data,
1659 if (bytes_written < 0)
1660 return AVERROR_BUFFER_TOO_SMALL;
1662 bytes_written += header_bytes;
1663 return bytes_written;
1667 * Copies NAL units and replaces length codes with
1668 * H.264 Annex B start codes. On failure, the contents of
1669 * dst_data may have been modified.
1671 * @param length_code_size Byte length of each length code
1672 * @param sample_buffer NAL units prefixed with length codes.
1673 * @param sei Optional A53 closed captions SEI data.
1674 * @param dst_data Must be zeroed before calling this function.
1675 * Contains the copied NAL units prefixed with
1676 * start codes when the function returns
1678 * @param dst_size Length of dst_data
1679 * @return 0 on success
1680 * AVERROR_INVALIDDATA if length_code_size is invalid
1681 * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
1682 * or if a length_code in src_data specifies data beyond
1683 * the end of its buffer.
1685 static int copy_replace_length_codes(
1686 AVCodecContext *avctx,
1687 size_t length_code_size,
1688 CMSampleBufferRef sample_buffer,
1693 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1694 size_t remaining_src_size = src_size;
1695 size_t remaining_dst_size = dst_size;
1696 size_t src_offset = 0;
1699 uint8_t size_buf[4];
1701 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
1703 if (length_code_size > 4) {
1704 return AVERROR_INVALIDDATA;
1707 while (remaining_src_size > 0) {
1708 size_t curr_src_len;
1709 size_t curr_dst_len;
1715 status = CMBlockBufferCopyDataBytes(block,
1720 av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
1721 return AVERROR_EXTERNAL;
1724 status = CMBlockBufferCopyDataBytes(block,
1725 src_offset + length_code_size,
1730 av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
1731 return AVERROR_EXTERNAL;
1736 for (i = 0; i < length_code_size; i++) {
1738 box_len |= size_buf[i];
1741 if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
1742 //No SEI NAL unit - insert.
1745 memcpy(dst_data, start_code, sizeof(start_code));
1746 dst_data += sizeof(start_code);
1747 remaining_dst_size -= sizeof(start_code);
1749 *dst_data = H264_NAL_SEI;
1751 remaining_dst_size--;
1753 wrote_bytes = write_sei(sei,
1754 H264_SEI_TYPE_USER_DATA_REGISTERED,
1756 remaining_dst_size);
1758 if (wrote_bytes < 0)
1761 remaining_dst_size -= wrote_bytes;
1762 dst_data += wrote_bytes;
1764 if (remaining_dst_size <= 0)
1765 return AVERROR_BUFFER_TOO_SMALL;
1770 remaining_dst_size--;
1775 curr_src_len = box_len + length_code_size;
1776 curr_dst_len = box_len + sizeof(start_code);
1778 if (remaining_src_size < curr_src_len) {
1779 return AVERROR_BUFFER_TOO_SMALL;
1782 if (remaining_dst_size < curr_dst_len) {
1783 return AVERROR_BUFFER_TOO_SMALL;
1786 dst_box = dst_data + sizeof(start_code);
1788 memcpy(dst_data, start_code, sizeof(start_code));
1789 status = CMBlockBufferCopyDataBytes(block,
1790 src_offset + length_code_size,
1795 av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
1796 return AVERROR_EXTERNAL;
1799 if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
1800 //Found SEI NAL unit - append.
1805 old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
1806 if (old_sei_length < 0)
1809 wrote_bytes = write_sei(sei,
1810 H264_SEI_TYPE_USER_DATA_REGISTERED,
1812 remaining_dst_size - old_sei_length);
1813 if (wrote_bytes < 0)
1816 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1817 return AVERROR_BUFFER_TOO_SMALL;
1819 new_sei[wrote_bytes++] = 0x80;
1820 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1822 dst_data += extra_bytes;
1823 remaining_dst_size -= extra_bytes;
1828 src_offset += curr_src_len;
1829 dst_data += curr_dst_len;
1831 remaining_src_size -= curr_src_len;
1832 remaining_dst_size -= curr_dst_len;
1839 * Returns a sufficient number of bytes to contain the sei data.
1840 * It may be greater than the minimum required.
1842 static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
1847 copied_size = -copy_emulation_prev(sei->data,
1853 if ((sei->size % 255) == 0) //may result in an extra byte
1856 return copied_size + sei->size / 255 + 1 + type / 255 + 1;
1859 static int vtenc_cm_to_avpacket(
1860 AVCodecContext *avctx,
1861 CMSampleBufferRef sample_buffer,
1865 VTEncContext *vtctx = avctx->priv_data;
1870 size_t length_code_size;
1871 size_t header_size = 0;
1873 size_t out_buf_size;
1874 size_t sei_nalu_size = 0;
1876 int64_t time_base_num;
1880 CMVideoFormatDescriptionRef vid_fmt;
1883 vtenc_get_frame_info(sample_buffer, &is_key_frame);
1884 status = get_length_code_size(avctx, sample_buffer, &length_code_size);
1885 if (status) return status;
1887 add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
1890 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1892 av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
1893 return AVERROR_EXTERNAL;
1896 int status = get_params_size(avctx, vid_fmt, &header_size);
1897 if (status) return status;
1900 status = count_nalus(length_code_size, sample_buffer, &nalu_count);
1905 size_t msg_size = get_sei_msg_bytes(sei,
1906 H264_SEI_TYPE_USER_DATA_REGISTERED);
1908 sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
1911 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1912 out_buf_size = header_size +
1915 nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
1917 status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);
1922 status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
1923 if(status) return status;
1926 status = copy_replace_length_codes(
1931 pkt->data + header_size,
1932 pkt->size - header_size
1936 av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
1941 pkt->flags |= AV_PKT_FLAG_KEY;
1944 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1945 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1947 if (CMTIME_IS_INVALID(dts)) {
1948 if (!vtctx->has_b_frames) {
1951 av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
1952 return AVERROR_EXTERNAL;
1956 dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
1957 time_base_num = avctx->time_base.num;
1958 pkt->pts = pts.value / time_base_num;
1959 pkt->dts = dts.value / time_base_num - dts_delta;
1960 pkt->size = out_buf_size;
1966 * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
1967 * containing all planes if so.
1969 static int get_cv_pixel_info(
1970 AVCodecContext *avctx,
1971 const AVFrame *frame,
1977 size_t *contiguous_buf_size)
1979 VTEncContext *vtctx = avctx->priv_data;
1980 int av_format = frame->format;
1981 int av_color_range = frame->color_range;
1986 status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
1990 "Could not get pixel format for color format '%s' range '%s'.\n",
1991 av_get_pix_fmt_name(av_format),
1992 av_color_range > AVCOL_RANGE_UNSPECIFIED &&
1993 av_color_range < AVCOL_RANGE_NB ?
1994 av_color_range_name(av_color_range) :
1997 return AVERROR(EINVAL);
2000 if (range_guessed) {
2001 if (!vtctx->warned_color_range) {
2002 vtctx->warned_color_range = true;
2005 "Color range not set for %s. Using MPEG range.\n",
2006 av_get_pix_fmt_name(av_format));
2010 switch (av_format) {
2011 case AV_PIX_FMT_NV12:
2014 widths [0] = avctx->width;
2015 heights[0] = avctx->height;
2016 strides[0] = frame ? frame->linesize[0] : avctx->width;
2018 widths [1] = (avctx->width + 1) / 2;
2019 heights[1] = (avctx->height + 1) / 2;
2020 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) & -2;
2023 case AV_PIX_FMT_YUV420P:
2026 widths [0] = avctx->width;
2027 heights[0] = avctx->height;
2028 strides[0] = frame ? frame->linesize[0] : avctx->width;
2030 widths [1] = (avctx->width + 1) / 2;
2031 heights[1] = (avctx->height + 1) / 2;
2032 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) / 2;
2034 widths [2] = (avctx->width + 1) / 2;
2035 heights[2] = (avctx->height + 1) / 2;
2036 strides[2] = frame ? frame->linesize[2] : (avctx->width + 1) / 2;
2039 case AV_PIX_FMT_P010LE:
2041 widths[0] = avctx->width;
2042 heights[0] = avctx->height;
2043 strides[0] = frame ? frame->linesize[0] : (avctx->width * 2 + 63) & -64;
2045 widths[1] = (avctx->width + 1) / 2;
2046 heights[1] = (avctx->height + 1) / 2;
2047 strides[1] = frame ? frame->linesize[1] : ((avctx->width + 1) / 2 + 63) & -64;
2054 "Could not get frame format info for color %d range %d.\n",
2058 return AVERROR(EINVAL);
2061 *contiguous_buf_size = 0;
2062 for (i = 0; i < *plane_count; i++) {
2063 if (i < *plane_count - 1 &&
2064 frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
2065 *contiguous_buf_size = 0;
2069 *contiguous_buf_size += strides[i] * heights[i];
2075 //Not used on OSX - frame is never copied.
2076 static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx,
2077 const AVFrame *frame,
2078 CVPixelBufferRef cv_img,
2079 const size_t *plane_strides,
2080 const size_t *plane_rows)
2092 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2097 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2102 if (CVPixelBufferIsPlanar(cv_img)) {
2103 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2104 for (i = 0; frame->data[i]; i++) {
2105 if (i == plane_count) {
2106 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2109 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2112 return AVERROR_EXTERNAL;
2115 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2116 src_addr = (uint8_t*)frame->data[i];
2117 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2118 src_stride = plane_strides[i];
2119 rows = plane_rows[i];
2121 if (dst_stride == src_stride) {
2122 memcpy(dst_addr, src_addr, src_stride * rows);
2124 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2126 for (j = 0; j < rows; j++) {
2127 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2132 if (frame->data[1]) {
2133 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2136 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2139 return AVERROR_EXTERNAL;
2142 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2143 src_addr = (uint8_t*)frame->data[0];
2144 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2145 src_stride = plane_strides[0];
2146 rows = plane_rows[0];
2148 if (dst_stride == src_stride) {
2149 memcpy(dst_addr, src_addr, src_stride * rows);
2151 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2153 for (j = 0; j < rows; j++) {
2154 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2159 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2161 av_log(avctx, AV_LOG_ERROR, "Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2162 return AVERROR_EXTERNAL;
2168 static int create_cv_pixel_buffer(AVCodecContext *avctx,
2169 const AVFrame *frame,
2170 CVPixelBufferRef *cv_img)
2174 size_t widths [AV_NUM_DATA_POINTERS];
2175 size_t heights[AV_NUM_DATA_POINTERS];
2176 size_t strides[AV_NUM_DATA_POINTERS];
2178 size_t contiguous_buf_size;
2179 CVPixelBufferPoolRef pix_buf_pool;
2180 VTEncContext* vtctx = avctx->priv_data;
2182 if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2183 av_assert0(frame->format == AV_PIX_FMT_VIDEOTOOLBOX);
2185 *cv_img = (CVPixelBufferRef)frame->data[3];
2186 av_assert0(*cv_img);
2192 memset(widths, 0, sizeof(widths));
2193 memset(heights, 0, sizeof(heights));
2194 memset(strides, 0, sizeof(strides));
2196 status = get_cv_pixel_info(
2204 &contiguous_buf_size
2211 "Error: Cannot convert format %d color_range %d: %d\n",
2217 return AVERROR_EXTERNAL;
2220 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2221 if (!pix_buf_pool) {
2222 /* On iOS, the VT session is invalidated when the APP switches from
2223 * foreground to background and vice versa. Fetch the actual error code
2224 * of the VT session to detect that case and restart the VT session
2228 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
2229 if (vtstatus == kVTInvalidSessionErr) {
2230 CFRelease(vtctx->session);
2231 vtctx->session = NULL;
2232 status = vtenc_configure_encoder(avctx);
2234 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2236 if (!pix_buf_pool) {
2237 av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2238 return AVERROR_EXTERNAL;
2241 av_log(avctx, AV_LOG_WARNING, "VT session restarted because of a "
2242 "kVTInvalidSessionErr error.\n");
2245 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2251 av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2252 return AVERROR_EXTERNAL;
2255 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2265 static int create_encoder_dict_h264(const AVFrame *frame,
2266 CFDictionaryRef* dict_out)
2268 CFDictionaryRef dict = NULL;
2269 if (frame->pict_type == AV_PICTURE_TYPE_I) {
2270 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2271 const void *vals[] = { kCFBooleanTrue };
2273 dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2274 if(!dict) return AVERROR(ENOMEM);
2281 static int vtenc_send_frame(AVCodecContext *avctx,
2282 VTEncContext *vtctx,
2283 const AVFrame *frame)
2286 CFDictionaryRef frame_dict;
2287 CVPixelBufferRef cv_img = NULL;
2288 AVFrameSideData *side_data = NULL;
2289 ExtraSEI *sei = NULL;
2290 int status = create_cv_pixel_buffer(avctx, frame, &cv_img);
2292 if (status) return status;
2294 status = create_encoder_dict_h264(frame, &frame_dict);
2300 side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
2301 if (vtctx->a53_cc && side_data && side_data->size) {
2302 sei = av_mallocz(sizeof(*sei));
2304 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2306 int ret = ff_alloc_a53_sei(frame, 0, &sei->data, &sei->size);
2308 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2315 time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2316 status = VTCompressionSessionEncodeFrame(
2326 if (frame_dict) CFRelease(frame_dict);
2330 av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
2331 return AVERROR_EXTERNAL;
2337 static av_cold int vtenc_frame(
2338 AVCodecContext *avctx,
2340 const AVFrame *frame,
2343 VTEncContext *vtctx = avctx->priv_data;
2346 CMSampleBufferRef buf = NULL;
2347 ExtraSEI *sei = NULL;
2350 status = vtenc_send_frame(avctx, vtctx, frame);
2353 status = AVERROR_EXTERNAL;
2357 if (vtctx->frame_ct_in == 0) {
2358 vtctx->first_pts = frame->pts;
2359 } else if(vtctx->frame_ct_in == 1 && vtctx->has_b_frames) {
2360 vtctx->dts_delta = frame->pts - vtctx->first_pts;
2363 vtctx->frame_ct_in++;
2364 } else if(!vtctx->flushing) {
2365 vtctx->flushing = true;
2367 status = VTCompressionSessionCompleteFrames(vtctx->session,
2371 av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2372 status = AVERROR_EXTERNAL;
2378 get_frame = vtctx->dts_delta >= 0 || !frame;
2384 status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2385 if (status) goto end_nopkt;
2386 if (!buf) goto end_nopkt;
2388 status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei);
2390 if (sei->data) av_free(sei->data);
2394 if (status) goto end_nopkt;
2400 av_packet_unref(pkt);
2404 static int vtenc_populate_extradata(AVCodecContext *avctx,
2405 CMVideoCodecType codec_type,
2406 CFStringRef profile_level,
2407 CFNumberRef gamma_level,
2408 CFDictionaryRef enc_info,
2409 CFDictionaryRef pixel_buffer_info)
2411 VTEncContext *vtctx = avctx->priv_data;
2413 CVPixelBufferPoolRef pool = NULL;
2414 CVPixelBufferRef pix_buf = NULL;
2416 CMSampleBufferRef buf = NULL;
2418 status = vtenc_create_encoder(avctx,
2428 pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2430 av_log(avctx, AV_LOG_ERROR, "Error getting pixel buffer pool.\n");
2434 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2438 if(status != kCVReturnSuccess){
2439 av_log(avctx, AV_LOG_ERROR, "Error creating frame from pool: %d\n", status);
2443 time = CMTimeMake(0, avctx->time_base.den);
2444 status = VTCompressionSessionEncodeFrame(vtctx->session,
2455 "Error sending frame for extradata: %d\n",
2461 //Populates extradata - output frames are flushed and param sets are available.
2462 status = VTCompressionSessionCompleteFrames(vtctx->session,
2468 status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2470 av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2480 CFRelease(vtctx->session);
2482 vtctx->session = NULL;
2483 vtctx->frame_ct_out = 0;
2485 av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2490 static av_cold int vtenc_close(AVCodecContext *avctx)
2492 VTEncContext *vtctx = avctx->priv_data;
2494 if(!vtctx->session) {
2495 pthread_cond_destroy(&vtctx->cv_sample_sent);
2496 pthread_mutex_destroy(&vtctx->lock);
2500 VTCompressionSessionCompleteFrames(vtctx->session,
2502 clear_frame_queue(vtctx);
2503 pthread_cond_destroy(&vtctx->cv_sample_sent);
2504 pthread_mutex_destroy(&vtctx->lock);
2505 CFRelease(vtctx->session);
2506 vtctx->session = NULL;
2508 if (vtctx->color_primaries) {
2509 CFRelease(vtctx->color_primaries);
2510 vtctx->color_primaries = NULL;
2513 if (vtctx->transfer_function) {
2514 CFRelease(vtctx->transfer_function);
2515 vtctx->transfer_function = NULL;
2518 if (vtctx->ycbcr_matrix) {
2519 CFRelease(vtctx->ycbcr_matrix);
2520 vtctx->ycbcr_matrix = NULL;
2526 static const enum AVPixelFormat avc_pix_fmts[] = {
2527 AV_PIX_FMT_VIDEOTOOLBOX,
2533 static const enum AVPixelFormat hevc_pix_fmts[] = {
2534 AV_PIX_FMT_VIDEOTOOLBOX,
2541 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2542 #define COMMON_OPTIONS \
2543 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2544 { .i64 = 0 }, 0, 1, VE }, \
2545 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2546 { .i64 = 0 }, 0, 1, VE }, \
2547 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2548 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2549 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2550 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2551 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2552 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2554 #define OFFSET(x) offsetof(VTEncContext, x)
2555 static const AVOption h264_options[] = {
2556 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = H264_PROF_AUTO }, H264_PROF_AUTO, H264_PROF_COUNT, VE, "profile" },
2557 { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_BASELINE }, INT_MIN, INT_MAX, VE, "profile" },
2558 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2559 { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_HIGH }, INT_MIN, INT_MAX, VE, "profile" },
2560 { "extended", "Extend Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_EXTENDED }, INT_MIN, INT_MAX, VE, "profile" },
2562 { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, "level" },
2563 { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, "level" },
2564 { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, "level" },
2565 { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, "level" },
2566 { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, "level" },
2567 { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, "level" },
2568 { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, "level" },
2569 { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, "level" },
2570 { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, "level" },
2571 { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, "level" },
2572 { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, "level" },
2574 { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, "coder" },
2575 { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2576 { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2577 { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2578 { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2580 { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2586 static const AVClass h264_videotoolbox_class = {
2587 .class_name = "h264_videotoolbox",
2588 .item_name = av_default_item_name,
2589 .option = h264_options,
2590 .version = LIBAVUTIL_VERSION_INT,
2593 AVCodec ff_h264_videotoolbox_encoder = {
2594 .name = "h264_videotoolbox",
2595 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.264 Encoder"),
2596 .type = AVMEDIA_TYPE_VIDEO,
2597 .id = AV_CODEC_ID_H264,
2598 .priv_data_size = sizeof(VTEncContext),
2599 .pix_fmts = avc_pix_fmts,
2601 .encode2 = vtenc_frame,
2602 .close = vtenc_close,
2603 .capabilities = AV_CODEC_CAP_DELAY,
2604 .priv_class = &h264_videotoolbox_class,
2605 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2606 FF_CODEC_CAP_INIT_CLEANUP,
2609 static const AVOption hevc_options[] = {
2610 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = HEVC_PROF_AUTO }, HEVC_PROF_AUTO, HEVC_PROF_COUNT, VE, "profile" },
2611 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2612 { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN10 }, INT_MIN, INT_MAX, VE, "profile" },
2618 static const AVClass hevc_videotoolbox_class = {
2619 .class_name = "hevc_videotoolbox",
2620 .item_name = av_default_item_name,
2621 .option = hevc_options,
2622 .version = LIBAVUTIL_VERSION_INT,
2625 AVCodec ff_hevc_videotoolbox_encoder = {
2626 .name = "hevc_videotoolbox",
2627 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.265 Encoder"),
2628 .type = AVMEDIA_TYPE_VIDEO,
2629 .id = AV_CODEC_ID_HEVC,
2630 .priv_data_size = sizeof(VTEncContext),
2631 .pix_fmts = hevc_pix_fmts,
2633 .encode2 = vtenc_frame,
2634 .close = vtenc_close,
2635 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
2636 .priv_class = &hevc_videotoolbox_class,
2637 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2638 FF_CODEC_CAP_INIT_CLEANUP,
2639 .wrapper_name = "videotoolbox",