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"
38 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
39 enum { kCMVideoCodecType_HEVC = 'hvc1' };
42 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
43 enum { kCVPixelFormatType_420YpCbCr10BiPlanarFullRange = 'xf20' };
44 enum { kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange = 'x420' };
47 typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
48 size_t parameterSetIndex,
49 const uint8_t **parameterSetPointerOut,
50 size_t *parameterSetSizeOut,
51 size_t *parameterSetCountOut,
52 int *NALUnitHeaderLengthOut);
54 //These symbols may not be present
56 CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020;
57 CFStringRef kCVImageBufferTransferFunction_ITU_R_2020;
58 CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020;
60 CFStringRef kVTCompressionPropertyKey_H264EntropyMode;
61 CFStringRef kVTH264EntropyMode_CAVLC;
62 CFStringRef kVTH264EntropyMode_CABAC;
64 CFStringRef kVTProfileLevel_H264_Baseline_4_0;
65 CFStringRef kVTProfileLevel_H264_Baseline_4_2;
66 CFStringRef kVTProfileLevel_H264_Baseline_5_0;
67 CFStringRef kVTProfileLevel_H264_Baseline_5_1;
68 CFStringRef kVTProfileLevel_H264_Baseline_5_2;
69 CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel;
70 CFStringRef kVTProfileLevel_H264_Main_4_2;
71 CFStringRef kVTProfileLevel_H264_Main_5_1;
72 CFStringRef kVTProfileLevel_H264_Main_5_2;
73 CFStringRef kVTProfileLevel_H264_Main_AutoLevel;
74 CFStringRef kVTProfileLevel_H264_High_3_0;
75 CFStringRef kVTProfileLevel_H264_High_3_1;
76 CFStringRef kVTProfileLevel_H264_High_3_2;
77 CFStringRef kVTProfileLevel_H264_High_4_0;
78 CFStringRef kVTProfileLevel_H264_High_4_1;
79 CFStringRef kVTProfileLevel_H264_High_4_2;
80 CFStringRef kVTProfileLevel_H264_High_5_1;
81 CFStringRef kVTProfileLevel_H264_High_5_2;
82 CFStringRef kVTProfileLevel_H264_High_AutoLevel;
83 CFStringRef kVTProfileLevel_H264_Extended_5_0;
84 CFStringRef kVTProfileLevel_H264_Extended_AutoLevel;
86 CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel;
87 CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel;
89 CFStringRef kVTCompressionPropertyKey_RealTime;
91 CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder;
92 CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder;
94 getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
97 #define GET_SYM(symbol, defaultVal) \
99 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
101 compat_keys.symbol = CFSTR(defaultVal); \
103 compat_keys.symbol = *handle; \
106 static pthread_once_t once_ctrl = PTHREAD_ONCE_INIT;
108 static void loadVTEncSymbols(){
109 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
110 (getParameterSetAtIndex)dlsym(
112 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
115 GET_SYM(kCVImageBufferColorPrimaries_ITU_R_2020, "ITU_R_2020");
116 GET_SYM(kCVImageBufferTransferFunction_ITU_R_2020, "ITU_R_2020");
117 GET_SYM(kCVImageBufferYCbCrMatrix_ITU_R_2020, "ITU_R_2020");
119 GET_SYM(kVTCompressionPropertyKey_H264EntropyMode, "H264EntropyMode");
120 GET_SYM(kVTH264EntropyMode_CAVLC, "CAVLC");
121 GET_SYM(kVTH264EntropyMode_CABAC, "CABAC");
123 GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
124 GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
125 GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
126 GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
127 GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
128 GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
129 GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
130 GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
131 GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
132 GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
133 GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
134 GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
135 GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
136 GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
137 GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
138 GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
139 GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
140 GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
141 GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
142 GET_SYM(kVTProfileLevel_H264_Extended_5_0, "H264_Extended_5_0");
143 GET_SYM(kVTProfileLevel_H264_Extended_AutoLevel, "H264_Extended_AutoLevel");
145 GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
146 GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
148 GET_SYM(kVTCompressionPropertyKey_RealTime, "RealTime");
150 GET_SYM(kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
151 "EnableHardwareAcceleratedVideoEncoder");
152 GET_SYM(kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
153 "RequireHardwareAcceleratedVideoEncoder");
156 typedef enum VT_H264Profile {
165 typedef enum VTH264Entropy{
171 typedef enum VT_HEVCProfile {
178 static const uint8_t start_code[] = { 0, 0, 0, 1 };
180 typedef struct ExtraSEI {
185 typedef struct BufNode {
186 CMSampleBufferRef cm_buffer;
188 struct BufNode* next;
192 typedef struct VTEncContext {
194 enum AVCodecID codec_id;
195 VTCompressionSessionRef session;
196 CFStringRef ycbcr_matrix;
197 CFStringRef color_primaries;
198 CFStringRef transfer_function;
199 getParameterSetAtIndex get_param_set_func;
201 pthread_mutex_t lock;
202 pthread_cond_t cv_sample_sent;
209 int64_t frame_ct_out;
219 int64_t frames_before;
220 int64_t frames_after;
227 bool warned_color_range;
231 static int vtenc_populate_extradata(AVCodecContext *avctx,
232 CMVideoCodecType codec_type,
233 CFStringRef profile_level,
234 CFNumberRef gamma_level,
235 CFDictionaryRef enc_info,
236 CFDictionaryRef pixel_buffer_info);
239 * NULL-safe release of *refPtr, and sets value to NULL.
241 static void vt_release_num(CFNumberRef* refPtr){
250 static void set_async_error(VTEncContext *vtctx, int err)
254 pthread_mutex_lock(&vtctx->lock);
256 vtctx->async_error = err;
258 info = vtctx->q_head;
259 vtctx->q_head = vtctx->q_tail = NULL;
262 BufNode *next = info->next;
263 CFRelease(info->cm_buffer);
268 pthread_mutex_unlock(&vtctx->lock);
271 static void clear_frame_queue(VTEncContext *vtctx)
273 set_async_error(vtctx, 0);
276 static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
280 pthread_mutex_lock(&vtctx->lock);
282 if (vtctx->async_error) {
283 pthread_mutex_unlock(&vtctx->lock);
284 return vtctx->async_error;
287 if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
290 pthread_mutex_unlock(&vtctx->lock);
294 while (!vtctx->q_head && !vtctx->async_error && wait) {
295 pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
298 if (!vtctx->q_head) {
299 pthread_mutex_unlock(&vtctx->lock);
304 info = vtctx->q_head;
305 vtctx->q_head = vtctx->q_head->next;
306 if (!vtctx->q_head) {
307 vtctx->q_tail = NULL;
310 pthread_mutex_unlock(&vtctx->lock);
312 *buf = info->cm_buffer;
315 } else if (info->sei) {
316 if (info->sei->data) av_free(info->sei->data);
321 vtctx->frame_ct_out++;
326 static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
328 BufNode *info = av_malloc(sizeof(BufNode));
330 set_async_error(vtctx, AVERROR(ENOMEM));
335 info->cm_buffer = buffer;
339 pthread_mutex_lock(&vtctx->lock);
340 pthread_cond_signal(&vtctx->cv_sample_sent);
342 if (!vtctx->q_head) {
343 vtctx->q_head = info;
345 vtctx->q_tail->next = info;
348 vtctx->q_tail = info;
350 pthread_mutex_unlock(&vtctx->lock);
353 static int count_nalus(size_t length_code_size,
354 CMSampleBufferRef sample_buffer,
361 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
362 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
364 if (length_code_size > 4)
365 return AVERROR_INVALIDDATA;
367 while (offset < src_size) {
372 status = CMBlockBufferCopyDataBytes(block,
377 for (i = 0; i < length_code_size; i++) {
379 box_len |= size_buf[i];
382 curr_src_len = box_len + length_code_size;
383 offset += curr_src_len;
392 static CMVideoCodecType get_cm_codec_type(enum AVCodecID id)
395 case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
396 case AV_CODEC_ID_HEVC: return kCMVideoCodecType_HEVC;
402 * Get the parameter sets from a CMSampleBufferRef.
403 * @param dst If *dst isn't NULL, the parameters are copied into existing
404 * memory. *dst_size must be set accordingly when *dst != NULL.
405 * If *dst is NULL, it will be allocated.
406 * In all cases, *dst_size is set to the number of bytes used starting
409 static int get_params_size(
410 AVCodecContext *avctx,
411 CMVideoFormatDescriptionRef vid_fmt,
414 VTEncContext *vtctx = avctx->priv_data;
415 size_t total_size = 0;
417 int is_count_bad = 0;
420 status = vtctx->get_param_set_func(vid_fmt,
432 for (i = 0; i < ps_count || is_count_bad; i++) {
435 status = vtctx->get_param_set_func(vid_fmt,
443 * When ps_count is invalid, status != 0 ends the loop normally
444 * unless we didn't get any parameter sets.
446 if (i > 0 && is_count_bad) status = 0;
451 total_size += ps_size + sizeof(start_code);
455 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
456 return AVERROR_EXTERNAL;
463 static int copy_param_sets(
464 AVCodecContext *avctx,
465 CMVideoFormatDescriptionRef vid_fmt,
469 VTEncContext *vtctx = avctx->priv_data;
471 int is_count_bad = 0;
476 status = vtctx->get_param_set_func(vid_fmt,
489 for (i = 0; i < ps_count || is_count_bad; i++) {
494 status = vtctx->get_param_set_func(vid_fmt,
501 if (i > 0 && is_count_bad) status = 0;
506 next_offset = offset + sizeof(start_code) + ps_size;
507 if (dst_size < next_offset) {
508 av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
509 return AVERROR_BUFFER_TOO_SMALL;
512 memcpy(dst + offset, start_code, sizeof(start_code));
513 offset += sizeof(start_code);
515 memcpy(dst + offset, ps, ps_size);
516 offset = next_offset;
520 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
521 return AVERROR_EXTERNAL;
527 static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
529 CMVideoFormatDescriptionRef vid_fmt;
533 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
535 av_log(avctx, AV_LOG_ERROR, "No video format.\n");
536 return AVERROR_EXTERNAL;
539 status = get_params_size(avctx, vid_fmt, &total_size);
541 av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
545 avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
546 if (!avctx->extradata) {
547 return AVERROR(ENOMEM);
549 avctx->extradata_size = total_size;
551 status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
554 av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
561 static void vtenc_output_callback(
563 void *sourceFrameCtx,
565 VTEncodeInfoFlags flags,
566 CMSampleBufferRef sample_buffer)
568 AVCodecContext *avctx = ctx;
569 VTEncContext *vtctx = avctx->priv_data;
570 ExtraSEI *sei = sourceFrameCtx;
572 if (vtctx->async_error) {
573 if(sample_buffer) CFRelease(sample_buffer);
578 av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
579 set_async_error(vtctx, AVERROR_EXTERNAL);
583 if (!sample_buffer) {
587 if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
588 int set_status = set_extradata(avctx, sample_buffer);
590 set_async_error(vtctx, set_status);
595 vtenc_q_push(vtctx, sample_buffer, sei);
598 static int get_length_code_size(
599 AVCodecContext *avctx,
600 CMSampleBufferRef sample_buffer,
603 VTEncContext *vtctx = avctx->priv_data;
604 CMVideoFormatDescriptionRef vid_fmt;
608 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
610 av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
611 return AVERROR_EXTERNAL;
614 status = vtctx->get_param_set_func(vid_fmt,
621 av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
622 return AVERROR_EXTERNAL;
630 * Returns true on success.
632 * If profile_level_val is NULL and this method returns true, don't specify the
633 * profile/level to the encoder.
635 static bool get_vt_h264_profile_level(AVCodecContext *avctx,
636 CFStringRef *profile_level_val)
638 VTEncContext *vtctx = avctx->priv_data;
639 int64_t profile = vtctx->profile;
641 if (profile == H264_PROF_AUTO && vtctx->level) {
642 //Need to pick a profile if level is not auto-selected.
643 profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;
646 *profile_level_val = NULL;
652 case H264_PROF_BASELINE:
653 switch (vtctx->level) {
654 case 0: *profile_level_val =
655 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
656 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
657 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
658 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
659 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
660 case 40: *profile_level_val =
661 compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
662 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
663 case 42: *profile_level_val =
664 compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
665 case 50: *profile_level_val =
666 compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
667 case 51: *profile_level_val =
668 compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
669 case 52: *profile_level_val =
670 compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
675 switch (vtctx->level) {
676 case 0: *profile_level_val =
677 compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
678 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
679 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
680 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
681 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
682 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
683 case 42: *profile_level_val =
684 compat_keys.kVTProfileLevel_H264_Main_4_2; break;
685 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
686 case 51: *profile_level_val =
687 compat_keys.kVTProfileLevel_H264_Main_5_1; break;
688 case 52: *profile_level_val =
689 compat_keys.kVTProfileLevel_H264_Main_5_2; break;
694 switch (vtctx->level) {
695 case 0: *profile_level_val =
696 compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
697 case 30: *profile_level_val =
698 compat_keys.kVTProfileLevel_H264_High_3_0; break;
699 case 31: *profile_level_val =
700 compat_keys.kVTProfileLevel_H264_High_3_1; break;
701 case 32: *profile_level_val =
702 compat_keys.kVTProfileLevel_H264_High_3_2; break;
703 case 40: *profile_level_val =
704 compat_keys.kVTProfileLevel_H264_High_4_0; break;
705 case 41: *profile_level_val =
706 compat_keys.kVTProfileLevel_H264_High_4_1; break;
707 case 42: *profile_level_val =
708 compat_keys.kVTProfileLevel_H264_High_4_2; break;
709 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
710 case 51: *profile_level_val =
711 compat_keys.kVTProfileLevel_H264_High_5_1; break;
712 case 52: *profile_level_val =
713 compat_keys.kVTProfileLevel_H264_High_5_2; break;
716 case H264_PROF_EXTENDED:
717 switch (vtctx->level) {
718 case 0: *profile_level_val =
719 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel; break;
720 case 50: *profile_level_val =
721 compat_keys.kVTProfileLevel_H264_Extended_5_0; break;
726 if (!*profile_level_val) {
727 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
735 * Returns true on success.
737 * If profile_level_val is NULL and this method returns true, don't specify the
738 * profile/level to the encoder.
740 static bool get_vt_hevc_profile_level(AVCodecContext *avctx,
741 CFStringRef *profile_level_val)
743 VTEncContext *vtctx = avctx->priv_data;
744 int64_t profile = vtctx->profile;
746 *profile_level_val = NULL;
753 compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
755 case HEVC_PROF_MAIN10:
757 compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
761 if (!*profile_level_val) {
762 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
769 static int get_cv_pixel_format(AVCodecContext* avctx,
770 enum AVPixelFormat fmt,
771 enum AVColorRange range,
772 int* av_pixel_format,
775 if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
776 range != AVCOL_RANGE_JPEG;
778 //MPEG range is used when no range is set
779 if (fmt == AV_PIX_FMT_NV12) {
780 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
781 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
782 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
783 } else if (fmt == AV_PIX_FMT_YUV420P) {
784 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
785 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
786 kCVPixelFormatType_420YpCbCr8Planar;
787 } else if (fmt == AV_PIX_FMT_P010LE) {
788 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
789 kCVPixelFormatType_420YpCbCr10BiPlanarFullRange :
790 kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
791 *av_pixel_format = kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
793 return AVERROR(EINVAL);
799 static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
800 VTEncContext *vtctx = avctx->priv_data;
802 if (vtctx->color_primaries) {
803 CFDictionarySetValue(dict,
804 kCVImageBufferColorPrimariesKey,
805 vtctx->color_primaries);
808 if (vtctx->transfer_function) {
809 CFDictionarySetValue(dict,
810 kCVImageBufferTransferFunctionKey,
811 vtctx->transfer_function);
814 if (vtctx->ycbcr_matrix) {
815 CFDictionarySetValue(dict,
816 kCVImageBufferYCbCrMatrixKey,
817 vtctx->ycbcr_matrix);
821 static int create_cv_pixel_buffer_info(AVCodecContext* avctx,
822 CFMutableDictionaryRef* dict)
824 CFNumberRef cv_color_format_num = NULL;
825 CFNumberRef width_num = NULL;
826 CFNumberRef height_num = NULL;
827 CFMutableDictionaryRef pixel_buffer_info = NULL;
829 int status = get_cv_pixel_format(avctx,
834 if (status) return status;
836 pixel_buffer_info = CFDictionaryCreateMutable(
839 &kCFCopyStringDictionaryKeyCallBacks,
840 &kCFTypeDictionaryValueCallBacks);
842 if (!pixel_buffer_info) goto pbinfo_nomem;
844 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
847 if (!cv_color_format_num) goto pbinfo_nomem;
849 CFDictionarySetValue(pixel_buffer_info,
850 kCVPixelBufferPixelFormatTypeKey,
851 cv_color_format_num);
852 vt_release_num(&cv_color_format_num);
854 width_num = CFNumberCreate(kCFAllocatorDefault,
857 if (!width_num) return AVERROR(ENOMEM);
859 CFDictionarySetValue(pixel_buffer_info,
860 kCVPixelBufferWidthKey,
862 vt_release_num(&width_num);
864 height_num = CFNumberCreate(kCFAllocatorDefault,
867 if (!height_num) goto pbinfo_nomem;
869 CFDictionarySetValue(pixel_buffer_info,
870 kCVPixelBufferHeightKey,
872 vt_release_num(&height_num);
874 add_color_attr(avctx, pixel_buffer_info);
876 *dict = pixel_buffer_info;
880 vt_release_num(&cv_color_format_num);
881 vt_release_num(&width_num);
882 vt_release_num(&height_num);
883 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
885 return AVERROR(ENOMEM);
888 static int get_cv_color_primaries(AVCodecContext *avctx,
889 CFStringRef *primaries)
891 enum AVColorPrimaries pri = avctx->color_primaries;
893 case AVCOL_PRI_UNSPECIFIED:
897 case AVCOL_PRI_BT470BG:
898 *primaries = kCVImageBufferColorPrimaries_EBU_3213;
901 case AVCOL_PRI_SMPTE170M:
902 *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
905 case AVCOL_PRI_BT709:
906 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
909 case AVCOL_PRI_BT2020:
910 *primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
914 av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
922 static int get_cv_transfer_function(AVCodecContext *avctx,
923 CFStringRef *transfer_fnc,
924 CFNumberRef *gamma_level)
926 enum AVColorTransferCharacteristic trc = avctx->color_trc;
931 case AVCOL_TRC_UNSPECIFIED:
932 *transfer_fnc = NULL;
935 case AVCOL_TRC_BT709:
936 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
939 case AVCOL_TRC_SMPTE240M:
940 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
943 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ
944 case AVCOL_TRC_SMPTE2084:
945 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
948 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR
949 case AVCOL_TRC_LINEAR:
950 *transfer_fnc = kCVImageBufferTransferFunction_Linear;
953 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG
954 case AVCOL_TRC_ARIB_STD_B67:
955 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
959 case AVCOL_TRC_GAMMA22:
961 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
962 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
965 case AVCOL_TRC_GAMMA28:
967 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
968 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
971 case AVCOL_TRC_BT2020_10:
972 case AVCOL_TRC_BT2020_12:
973 *transfer_fnc = compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
977 *transfer_fnc = NULL;
978 av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));
985 static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix) {
986 switch(avctx->colorspace) {
987 case AVCOL_SPC_BT709:
988 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
991 case AVCOL_SPC_UNSPECIFIED:
995 case AVCOL_SPC_BT470BG:
996 case AVCOL_SPC_SMPTE170M:
997 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1000 case AVCOL_SPC_SMPTE240M:
1001 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1004 case AVCOL_SPC_BT2020_NCL:
1005 *matrix = compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
1009 av_log(avctx, AV_LOG_ERROR, "Color space %s is not supported.\n", av_color_space_name(avctx->colorspace));
1016 static int vtenc_create_encoder(AVCodecContext *avctx,
1017 CMVideoCodecType codec_type,
1018 CFStringRef profile_level,
1019 CFNumberRef gamma_level,
1020 CFDictionaryRef enc_info,
1021 CFDictionaryRef pixel_buffer_info,
1022 VTCompressionSessionRef *session)
1024 VTEncContext *vtctx = avctx->priv_data;
1025 SInt32 bit_rate = avctx->bit_rate;
1026 SInt32 max_rate = avctx->rc_max_rate;
1027 CFNumberRef bit_rate_num;
1028 CFNumberRef bytes_per_second;
1029 CFNumberRef one_second;
1030 CFArrayRef data_rate_limits;
1031 int64_t bytes_per_second_value = 0;
1032 int64_t one_second_value = 0;
1035 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1041 kCFAllocatorDefault,
1042 vtenc_output_callback,
1046 if (status || !vtctx->session) {
1047 av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
1049 #if !TARGET_OS_IPHONE
1050 if (!vtctx->allow_sw) {
1051 av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1055 return AVERROR_EXTERNAL;
1058 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1059 kCFNumberSInt32Type,
1061 if (!bit_rate_num) return AVERROR(ENOMEM);
1063 status = VTSessionSetProperty(vtctx->session,
1064 kVTCompressionPropertyKey_AverageBitRate,
1066 CFRelease(bit_rate_num);
1069 av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
1070 return AVERROR_EXTERNAL;
1073 if (vtctx->codec_id == AV_CODEC_ID_H264 && max_rate > 0) {
1074 // kVTCompressionPropertyKey_DataRateLimits is not available for HEVC
1075 bytes_per_second_value = max_rate >> 3;
1076 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1077 kCFNumberSInt64Type,
1078 &bytes_per_second_value);
1079 if (!bytes_per_second) {
1080 return AVERROR(ENOMEM);
1082 one_second_value = 1;
1083 one_second = CFNumberCreate(kCFAllocatorDefault,
1084 kCFNumberSInt64Type,
1087 CFRelease(bytes_per_second);
1088 return AVERROR(ENOMEM);
1090 nums[0] = (void *)bytes_per_second;
1091 nums[1] = (void *)one_second;
1092 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1093 (const void **)nums,
1095 &kCFTypeArrayCallBacks);
1097 if (!data_rate_limits) {
1098 CFRelease(bytes_per_second);
1099 CFRelease(one_second);
1100 return AVERROR(ENOMEM);
1102 status = VTSessionSetProperty(vtctx->session,
1103 kVTCompressionPropertyKey_DataRateLimits,
1106 CFRelease(bytes_per_second);
1107 CFRelease(one_second);
1108 CFRelease(data_rate_limits);
1111 av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
1112 return AVERROR_EXTERNAL;
1116 if (vtctx->codec_id == AV_CODEC_ID_H264) {
1117 // kVTCompressionPropertyKey_ProfileLevel is not available for HEVC
1118 if (profile_level) {
1119 status = VTSessionSetProperty(vtctx->session,
1120 kVTCompressionPropertyKey_ProfileLevel,
1123 av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1128 if (avctx->gop_size > 0) {
1129 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1133 return AVERROR(ENOMEM);
1136 status = VTSessionSetProperty(vtctx->session,
1137 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1139 CFRelease(interval);
1142 av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
1143 return AVERROR_EXTERNAL;
1147 if (vtctx->frames_before) {
1148 status = VTSessionSetProperty(vtctx->session,
1149 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1152 if (status == kVTPropertyNotSupportedErr) {
1153 av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
1154 } else if (status) {
1155 av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
1159 if (vtctx->frames_after) {
1160 status = VTSessionSetProperty(vtctx->session,
1161 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1164 if (status == kVTPropertyNotSupportedErr) {
1165 av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
1166 } else if (status) {
1167 av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
1171 if (avctx->sample_aspect_ratio.num != 0) {
1174 CFMutableDictionaryRef par;
1175 AVRational *avpar = &avctx->sample_aspect_ratio;
1177 av_reduce(&avpar->num, &avpar->den,
1178 avpar->num, avpar->den,
1181 num = CFNumberCreate(kCFAllocatorDefault,
1185 den = CFNumberCreate(kCFAllocatorDefault,
1191 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1193 &kCFCopyStringDictionaryKeyCallBacks,
1194 &kCFTypeDictionaryValueCallBacks);
1196 if (!par || !num || !den) {
1197 if (par) CFRelease(par);
1198 if (num) CFRelease(num);
1199 if (den) CFRelease(den);
1201 return AVERROR(ENOMEM);
1204 CFDictionarySetValue(
1206 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1209 CFDictionarySetValue(
1211 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1214 status = VTSessionSetProperty(vtctx->session,
1215 kVTCompressionPropertyKey_PixelAspectRatio,
1225 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1226 avctx->sample_aspect_ratio.num,
1227 avctx->sample_aspect_ratio.den,
1230 return AVERROR_EXTERNAL;
1235 if (vtctx->transfer_function) {
1236 status = VTSessionSetProperty(vtctx->session,
1237 kVTCompressionPropertyKey_TransferFunction,
1238 vtctx->transfer_function);
1241 av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1246 if (vtctx->ycbcr_matrix) {
1247 status = VTSessionSetProperty(vtctx->session,
1248 kVTCompressionPropertyKey_YCbCrMatrix,
1249 vtctx->ycbcr_matrix);
1252 av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1257 if (vtctx->color_primaries) {
1258 status = VTSessionSetProperty(vtctx->session,
1259 kVTCompressionPropertyKey_ColorPrimaries,
1260 vtctx->color_primaries);
1263 av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1268 status = VTSessionSetProperty(vtctx->session,
1269 kCVImageBufferGammaLevelKey,
1273 av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1277 if (!vtctx->has_b_frames) {
1278 status = VTSessionSetProperty(vtctx->session,
1279 kVTCompressionPropertyKey_AllowFrameReordering,
1283 av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1284 return AVERROR_EXTERNAL;
1288 if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1289 CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1290 compat_keys.kVTH264EntropyMode_CABAC:
1291 compat_keys.kVTH264EntropyMode_CAVLC;
1293 status = VTSessionSetProperty(vtctx->session,
1294 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1298 av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1302 if (vtctx->realtime) {
1303 status = VTSessionSetProperty(vtctx->session,
1304 compat_keys.kVTCompressionPropertyKey_RealTime,
1308 av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1312 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1314 av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
1315 return AVERROR_EXTERNAL;
1321 static int vtenc_configure_encoder(AVCodecContext *avctx)
1323 CFMutableDictionaryRef enc_info;
1324 CFMutableDictionaryRef pixel_buffer_info;
1325 CMVideoCodecType codec_type;
1326 VTEncContext *vtctx = avctx->priv_data;
1327 CFStringRef profile_level;
1328 CFNumberRef gamma_level = NULL;
1331 codec_type = get_cm_codec_type(avctx->codec_id);
1333 av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
1334 return AVERROR(EINVAL);
1337 vtctx->codec_id = avctx->codec_id;
1339 if (vtctx->codec_id == AV_CODEC_ID_H264) {
1340 vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
1342 vtctx->has_b_frames = avctx->max_b_frames > 0;
1343 if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){
1344 av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1345 vtctx->has_b_frames = false;
1348 if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {
1349 av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1350 vtctx->entropy = VT_ENTROPY_NOT_SET;
1353 if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1355 vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
1356 if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
1357 if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1360 enc_info = CFDictionaryCreateMutable(
1361 kCFAllocatorDefault,
1363 &kCFCopyStringDictionaryKeyCallBacks,
1364 &kCFTypeDictionaryValueCallBacks
1367 if (!enc_info) return AVERROR(ENOMEM);
1369 #if !TARGET_OS_IPHONE
1370 if(vtctx->require_sw) {
1371 CFDictionarySetValue(enc_info,
1372 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1374 } else if (!vtctx->allow_sw) {
1375 CFDictionarySetValue(enc_info,
1376 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1379 CFDictionarySetValue(enc_info,
1380 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1385 if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1386 status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1390 pixel_buffer_info = NULL;
1393 vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1395 get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);
1396 get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);
1397 get_cv_color_primaries(avctx, &vtctx->color_primaries);
1400 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1401 status = vtenc_populate_extradata(avctx,
1411 status = vtenc_create_encoder(avctx,
1421 CFRelease(gamma_level);
1423 if (pixel_buffer_info)
1424 CFRelease(pixel_buffer_info);
1426 CFRelease(enc_info);
1431 static av_cold int vtenc_init(AVCodecContext *avctx)
1433 VTEncContext *vtctx = avctx->priv_data;
1434 CFBooleanRef has_b_frames_cfbool;
1437 pthread_once(&once_ctrl, loadVTEncSymbols);
1439 pthread_mutex_init(&vtctx->lock, NULL);
1440 pthread_cond_init(&vtctx->cv_sample_sent, NULL);
1442 vtctx->session = NULL;
1443 status = vtenc_configure_encoder(avctx);
1444 if (status) return status;
1446 status = VTSessionCopyProperty(vtctx->session,
1447 kVTCompressionPropertyKey_AllowFrameReordering,
1448 kCFAllocatorDefault,
1449 &has_b_frames_cfbool);
1451 if (!status && has_b_frames_cfbool) {
1452 //Some devices don't output B-frames for main profile, even if requested.
1453 vtctx->has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1454 CFRelease(has_b_frames_cfbool);
1456 avctx->has_b_frames = vtctx->has_b_frames;
1461 static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1463 CFArrayRef attachments;
1464 CFDictionaryRef attachment;
1465 CFBooleanRef not_sync;
1468 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1469 len = !attachments ? 0 : CFArrayGetCount(attachments);
1472 *is_key_frame = true;
1476 attachment = CFArrayGetValueAtIndex(attachments, 0);
1478 if (CFDictionaryGetValueIfPresent(attachment,
1479 kCMSampleAttachmentKey_NotSync,
1480 (const void **)¬_sync))
1482 *is_key_frame = !CFBooleanGetValue(not_sync);
1484 *is_key_frame = true;
1488 static int is_post_sei_nal_type(int nal_type){
1489 return nal_type != H264_NAL_SEI &&
1490 nal_type != H264_NAL_SPS &&
1491 nal_type != H264_NAL_PPS &&
1492 nal_type != H264_NAL_AUD;
1496 * Finds the sei message start/size of type find_sei_type.
1497 * If more than one of that type exists, the last one is returned.
1499 static int find_sei_end(AVCodecContext *avctx,
1505 size_t sei_payload_size = 0;
1506 int sei_payload_type = 0;
1508 uint8_t *nal_start = nal_data;
1513 nal_type = *nal_data & 0x1F;
1514 if (nal_type != H264_NAL_SEI)
1520 if (nal_data[nal_size - 1] == 0x80)
1523 while (nal_size > 0 && *nal_data > 0) {
1525 sei_payload_type += *nal_data;
1528 } while (nal_size > 0 && *nal_data == 0xFF);
1531 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1532 return AVERROR_INVALIDDATA;
1536 sei_payload_size += *nal_data;
1539 } while (nal_size > 0 && *nal_data == 0xFF);
1541 if (nal_size < sei_payload_size) {
1542 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1543 return AVERROR_INVALIDDATA;
1546 nal_data += sei_payload_size;
1547 nal_size -= sei_payload_size;
1550 *sei_end = nal_data;
1552 return nal_data - nal_start + 1;
1556 * Copies the data inserting emulation prevention bytes as needed.
1557 * Existing data in the destination can be taken into account by providing
1558 * dst with a dst_offset > 0.
1560 * @return The number of bytes copied on success. On failure, the negative of
1561 * the number of bytes needed to copy src is returned.
1563 static int copy_emulation_prev(const uint8_t *src,
1572 uint8_t* dst_end = dst + dst_size;
1573 const uint8_t* src_end = src + src_size;
1574 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1576 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1585 for (; src < src_end; src++, dst++) {
1587 int insert_ep3_byte = *src <= 3;
1588 if (insert_ep3_byte) {
1606 wrote_bytes = dst - dst_start;
1609 return -wrote_bytes;
1614 static int write_sei(const ExtraSEI *sei,
1619 uint8_t *sei_start = dst;
1620 size_t remaining_sei_size = sei->size;
1621 size_t remaining_dst_size = dst_size;
1626 if (!remaining_dst_size)
1627 return AVERROR_BUFFER_TOO_SMALL;
1629 while (sei_type && remaining_dst_size != 0) {
1630 int sei_byte = sei_type > 255 ? 255 : sei_type;
1633 sei_type -= sei_byte;
1635 remaining_dst_size--;
1639 return AVERROR_BUFFER_TOO_SMALL;
1641 while (remaining_sei_size && remaining_dst_size != 0) {
1642 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1645 remaining_sei_size -= size_byte;
1647 remaining_dst_size--;
1650 if (remaining_dst_size < sei->size)
1651 return AVERROR_BUFFER_TOO_SMALL;
1653 header_bytes = dst - sei_start;
1655 offset = header_bytes;
1656 bytes_written = copy_emulation_prev(sei->data,
1661 if (bytes_written < 0)
1662 return AVERROR_BUFFER_TOO_SMALL;
1664 bytes_written += header_bytes;
1665 return bytes_written;
1669 * Copies NAL units and replaces length codes with
1670 * H.264 Annex B start codes. On failure, the contents of
1671 * dst_data may have been modified.
1673 * @param length_code_size Byte length of each length code
1674 * @param sample_buffer NAL units prefixed with length codes.
1675 * @param sei Optional A53 closed captions SEI data.
1676 * @param dst_data Must be zeroed before calling this function.
1677 * Contains the copied NAL units prefixed with
1678 * start codes when the function returns
1680 * @param dst_size Length of dst_data
1681 * @return 0 on success
1682 * AVERROR_INVALIDDATA if length_code_size is invalid
1683 * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
1684 * or if a length_code in src_data specifies data beyond
1685 * the end of its buffer.
1687 static int copy_replace_length_codes(
1688 AVCodecContext *avctx,
1689 size_t length_code_size,
1690 CMSampleBufferRef sample_buffer,
1695 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1696 size_t remaining_src_size = src_size;
1697 size_t remaining_dst_size = dst_size;
1698 size_t src_offset = 0;
1701 uint8_t size_buf[4];
1703 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
1705 if (length_code_size > 4) {
1706 return AVERROR_INVALIDDATA;
1709 while (remaining_src_size > 0) {
1710 size_t curr_src_len;
1711 size_t curr_dst_len;
1717 status = CMBlockBufferCopyDataBytes(block,
1722 av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
1723 return AVERROR_EXTERNAL;
1726 status = CMBlockBufferCopyDataBytes(block,
1727 src_offset + length_code_size,
1732 av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
1733 return AVERROR_EXTERNAL;
1738 for (i = 0; i < length_code_size; i++) {
1740 box_len |= size_buf[i];
1743 if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
1744 //No SEI NAL unit - insert.
1747 memcpy(dst_data, start_code, sizeof(start_code));
1748 dst_data += sizeof(start_code);
1749 remaining_dst_size -= sizeof(start_code);
1751 *dst_data = H264_NAL_SEI;
1753 remaining_dst_size--;
1755 wrote_bytes = write_sei(sei,
1756 H264_SEI_TYPE_USER_DATA_REGISTERED,
1758 remaining_dst_size);
1760 if (wrote_bytes < 0)
1763 remaining_dst_size -= wrote_bytes;
1764 dst_data += wrote_bytes;
1766 if (remaining_dst_size <= 0)
1767 return AVERROR_BUFFER_TOO_SMALL;
1772 remaining_dst_size--;
1777 curr_src_len = box_len + length_code_size;
1778 curr_dst_len = box_len + sizeof(start_code);
1780 if (remaining_src_size < curr_src_len) {
1781 return AVERROR_BUFFER_TOO_SMALL;
1784 if (remaining_dst_size < curr_dst_len) {
1785 return AVERROR_BUFFER_TOO_SMALL;
1788 dst_box = dst_data + sizeof(start_code);
1790 memcpy(dst_data, start_code, sizeof(start_code));
1791 status = CMBlockBufferCopyDataBytes(block,
1792 src_offset + length_code_size,
1797 av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
1798 return AVERROR_EXTERNAL;
1801 if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
1802 //Found SEI NAL unit - append.
1807 old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
1808 if (old_sei_length < 0)
1811 wrote_bytes = write_sei(sei,
1812 H264_SEI_TYPE_USER_DATA_REGISTERED,
1814 remaining_dst_size - old_sei_length);
1815 if (wrote_bytes < 0)
1818 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1819 return AVERROR_BUFFER_TOO_SMALL;
1821 new_sei[wrote_bytes++] = 0x80;
1822 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1824 dst_data += extra_bytes;
1825 remaining_dst_size -= extra_bytes;
1830 src_offset += curr_src_len;
1831 dst_data += curr_dst_len;
1833 remaining_src_size -= curr_src_len;
1834 remaining_dst_size -= curr_dst_len;
1841 * Returns a sufficient number of bytes to contain the sei data.
1842 * It may be greater than the minimum required.
1844 static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
1849 copied_size = -copy_emulation_prev(sei->data,
1855 if ((sei->size % 255) == 0) //may result in an extra byte
1858 return copied_size + sei->size / 255 + 1 + type / 255 + 1;
1861 static int vtenc_cm_to_avpacket(
1862 AVCodecContext *avctx,
1863 CMSampleBufferRef sample_buffer,
1867 VTEncContext *vtctx = avctx->priv_data;
1872 size_t length_code_size;
1873 size_t header_size = 0;
1875 size_t out_buf_size;
1876 size_t sei_nalu_size = 0;
1878 int64_t time_base_num;
1882 CMVideoFormatDescriptionRef vid_fmt;
1885 vtenc_get_frame_info(sample_buffer, &is_key_frame);
1886 status = get_length_code_size(avctx, sample_buffer, &length_code_size);
1887 if (status) return status;
1889 add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
1892 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1894 av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
1895 return AVERROR_EXTERNAL;
1898 int status = get_params_size(avctx, vid_fmt, &header_size);
1899 if (status) return status;
1902 status = count_nalus(length_code_size, sample_buffer, &nalu_count);
1907 size_t msg_size = get_sei_msg_bytes(sei,
1908 H264_SEI_TYPE_USER_DATA_REGISTERED);
1910 sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
1913 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1914 out_buf_size = header_size +
1917 nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
1919 status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);
1924 status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
1925 if(status) return status;
1928 status = copy_replace_length_codes(
1933 pkt->data + header_size,
1934 pkt->size - header_size
1938 av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
1943 pkt->flags |= AV_PKT_FLAG_KEY;
1946 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1947 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1949 if (CMTIME_IS_INVALID(dts)) {
1950 if (!vtctx->has_b_frames) {
1953 av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
1954 return AVERROR_EXTERNAL;
1958 dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
1959 time_base_num = avctx->time_base.num;
1960 pkt->pts = pts.value / time_base_num;
1961 pkt->dts = dts.value / time_base_num - dts_delta;
1962 pkt->size = out_buf_size;
1968 * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
1969 * containing all planes if so.
1971 static int get_cv_pixel_info(
1972 AVCodecContext *avctx,
1973 const AVFrame *frame,
1979 size_t *contiguous_buf_size)
1981 VTEncContext *vtctx = avctx->priv_data;
1982 int av_format = frame->format;
1983 int av_color_range = frame->color_range;
1988 status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
1992 "Could not get pixel format for color format '%s' range '%s'.\n",
1993 av_get_pix_fmt_name(av_format),
1994 av_color_range > AVCOL_RANGE_UNSPECIFIED &&
1995 av_color_range < AVCOL_RANGE_NB ?
1996 av_color_range_name(av_color_range) :
1999 return AVERROR(EINVAL);
2002 if (range_guessed) {
2003 if (!vtctx->warned_color_range) {
2004 vtctx->warned_color_range = true;
2007 "Color range not set for %s. Using MPEG range.\n",
2008 av_get_pix_fmt_name(av_format));
2012 switch (av_format) {
2013 case AV_PIX_FMT_NV12:
2016 widths [0] = avctx->width;
2017 heights[0] = avctx->height;
2018 strides[0] = frame ? frame->linesize[0] : avctx->width;
2020 widths [1] = (avctx->width + 1) / 2;
2021 heights[1] = (avctx->height + 1) / 2;
2022 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) & -2;
2025 case AV_PIX_FMT_YUV420P:
2028 widths [0] = avctx->width;
2029 heights[0] = avctx->height;
2030 strides[0] = frame ? frame->linesize[0] : avctx->width;
2032 widths [1] = (avctx->width + 1) / 2;
2033 heights[1] = (avctx->height + 1) / 2;
2034 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) / 2;
2036 widths [2] = (avctx->width + 1) / 2;
2037 heights[2] = (avctx->height + 1) / 2;
2038 strides[2] = frame ? frame->linesize[2] : (avctx->width + 1) / 2;
2041 case AV_PIX_FMT_P010LE:
2043 widths[0] = avctx->width;
2044 heights[0] = avctx->height;
2045 strides[0] = frame ? frame->linesize[0] : (avctx->width * 2 + 63) & -64;
2047 widths[1] = (avctx->width + 1) / 2;
2048 heights[1] = (avctx->height + 1) / 2;
2049 strides[1] = frame ? frame->linesize[1] : ((avctx->width + 1) / 2 + 63) & -64;
2056 "Could not get frame format info for color %d range %d.\n",
2060 return AVERROR(EINVAL);
2063 *contiguous_buf_size = 0;
2064 for (i = 0; i < *plane_count; i++) {
2065 if (i < *plane_count - 1 &&
2066 frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
2067 *contiguous_buf_size = 0;
2071 *contiguous_buf_size += strides[i] * heights[i];
2077 //Not used on OSX - frame is never copied.
2078 static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx,
2079 const AVFrame *frame,
2080 CVPixelBufferRef cv_img,
2081 const size_t *plane_strides,
2082 const size_t *plane_rows)
2094 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2099 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2104 if (CVPixelBufferIsPlanar(cv_img)) {
2105 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2106 for (i = 0; frame->data[i]; i++) {
2107 if (i == plane_count) {
2108 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2111 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2114 return AVERROR_EXTERNAL;
2117 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2118 src_addr = (uint8_t*)frame->data[i];
2119 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2120 src_stride = plane_strides[i];
2121 rows = plane_rows[i];
2123 if (dst_stride == src_stride) {
2124 memcpy(dst_addr, src_addr, src_stride * rows);
2126 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2128 for (j = 0; j < rows; j++) {
2129 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2134 if (frame->data[1]) {
2135 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2138 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2141 return AVERROR_EXTERNAL;
2144 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2145 src_addr = (uint8_t*)frame->data[0];
2146 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2147 src_stride = plane_strides[0];
2148 rows = plane_rows[0];
2150 if (dst_stride == src_stride) {
2151 memcpy(dst_addr, src_addr, src_stride * rows);
2153 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2155 for (j = 0; j < rows; j++) {
2156 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2161 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2163 av_log(avctx, AV_LOG_ERROR, "Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2164 return AVERROR_EXTERNAL;
2170 static int create_cv_pixel_buffer(AVCodecContext *avctx,
2171 const AVFrame *frame,
2172 CVPixelBufferRef *cv_img)
2176 size_t widths [AV_NUM_DATA_POINTERS];
2177 size_t heights[AV_NUM_DATA_POINTERS];
2178 size_t strides[AV_NUM_DATA_POINTERS];
2180 size_t contiguous_buf_size;
2181 CVPixelBufferPoolRef pix_buf_pool;
2182 VTEncContext* vtctx = avctx->priv_data;
2184 if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2185 av_assert0(frame->format == AV_PIX_FMT_VIDEOTOOLBOX);
2187 *cv_img = (CVPixelBufferRef)frame->data[3];
2188 av_assert0(*cv_img);
2194 memset(widths, 0, sizeof(widths));
2195 memset(heights, 0, sizeof(heights));
2196 memset(strides, 0, sizeof(strides));
2198 status = get_cv_pixel_info(
2206 &contiguous_buf_size
2213 "Error: Cannot convert format %d color_range %d: %d\n",
2219 return AVERROR_EXTERNAL;
2222 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2223 if (!pix_buf_pool) {
2224 /* On iOS, the VT session is invalidated when the APP switches from
2225 * foreground to background and vice versa. Fetch the actual error code
2226 * of the VT session to detect that case and restart the VT session
2230 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
2231 if (vtstatus == kVTInvalidSessionErr) {
2232 CFRelease(vtctx->session);
2233 vtctx->session = NULL;
2234 status = vtenc_configure_encoder(avctx);
2236 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2238 if (!pix_buf_pool) {
2239 av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2240 return AVERROR_EXTERNAL;
2243 av_log(avctx, AV_LOG_WARNING, "VT session restarted because of a "
2244 "kVTInvalidSessionErr error.\n");
2247 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2253 av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2254 return AVERROR_EXTERNAL;
2257 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2267 static int create_encoder_dict_h264(const AVFrame *frame,
2268 CFDictionaryRef* dict_out)
2270 CFDictionaryRef dict = NULL;
2271 if (frame->pict_type == AV_PICTURE_TYPE_I) {
2272 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2273 const void *vals[] = { kCFBooleanTrue };
2275 dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2276 if(!dict) return AVERROR(ENOMEM);
2283 static int vtenc_send_frame(AVCodecContext *avctx,
2284 VTEncContext *vtctx,
2285 const AVFrame *frame)
2288 CFDictionaryRef frame_dict;
2289 CVPixelBufferRef cv_img = NULL;
2290 AVFrameSideData *side_data = NULL;
2291 ExtraSEI *sei = NULL;
2292 int status = create_cv_pixel_buffer(avctx, frame, &cv_img);
2294 if (status) return status;
2296 status = create_encoder_dict_h264(frame, &frame_dict);
2302 side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
2303 if (vtctx->a53_cc && side_data && side_data->size) {
2304 sei = av_mallocz(sizeof(*sei));
2306 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2308 int ret = ff_alloc_a53_sei(frame, 0, &sei->data, &sei->size);
2310 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2317 time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2318 status = VTCompressionSessionEncodeFrame(
2328 if (frame_dict) CFRelease(frame_dict);
2332 av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
2333 return AVERROR_EXTERNAL;
2339 static av_cold int vtenc_frame(
2340 AVCodecContext *avctx,
2342 const AVFrame *frame,
2345 VTEncContext *vtctx = avctx->priv_data;
2348 CMSampleBufferRef buf = NULL;
2349 ExtraSEI *sei = NULL;
2352 status = vtenc_send_frame(avctx, vtctx, frame);
2355 status = AVERROR_EXTERNAL;
2359 if (vtctx->frame_ct_in == 0) {
2360 vtctx->first_pts = frame->pts;
2361 } else if(vtctx->frame_ct_in == 1 && vtctx->has_b_frames) {
2362 vtctx->dts_delta = frame->pts - vtctx->first_pts;
2365 vtctx->frame_ct_in++;
2366 } else if(!vtctx->flushing) {
2367 vtctx->flushing = true;
2369 status = VTCompressionSessionCompleteFrames(vtctx->session,
2373 av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2374 status = AVERROR_EXTERNAL;
2380 get_frame = vtctx->dts_delta >= 0 || !frame;
2386 status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2387 if (status) goto end_nopkt;
2388 if (!buf) goto end_nopkt;
2390 status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei);
2392 if (sei->data) av_free(sei->data);
2396 if (status) goto end_nopkt;
2402 av_packet_unref(pkt);
2406 static int vtenc_populate_extradata(AVCodecContext *avctx,
2407 CMVideoCodecType codec_type,
2408 CFStringRef profile_level,
2409 CFNumberRef gamma_level,
2410 CFDictionaryRef enc_info,
2411 CFDictionaryRef pixel_buffer_info)
2413 VTEncContext *vtctx = avctx->priv_data;
2415 CVPixelBufferPoolRef pool = NULL;
2416 CVPixelBufferRef pix_buf = NULL;
2418 CMSampleBufferRef buf = NULL;
2420 status = vtenc_create_encoder(avctx,
2430 pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2432 av_log(avctx, AV_LOG_ERROR, "Error getting pixel buffer pool.\n");
2436 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2440 if(status != kCVReturnSuccess){
2441 av_log(avctx, AV_LOG_ERROR, "Error creating frame from pool: %d\n", status);
2445 time = CMTimeMake(0, avctx->time_base.den);
2446 status = VTCompressionSessionEncodeFrame(vtctx->session,
2457 "Error sending frame for extradata: %d\n",
2463 //Populates extradata - output frames are flushed and param sets are available.
2464 status = VTCompressionSessionCompleteFrames(vtctx->session,
2470 status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2472 av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2482 CFRelease(vtctx->session);
2484 vtctx->session = NULL;
2485 vtctx->frame_ct_out = 0;
2487 av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2492 static av_cold int vtenc_close(AVCodecContext *avctx)
2494 VTEncContext *vtctx = avctx->priv_data;
2496 pthread_cond_destroy(&vtctx->cv_sample_sent);
2497 pthread_mutex_destroy(&vtctx->lock);
2499 if(!vtctx->session) return 0;
2501 VTCompressionSessionCompleteFrames(vtctx->session,
2503 clear_frame_queue(vtctx);
2504 CFRelease(vtctx->session);
2505 vtctx->session = NULL;
2507 if (vtctx->color_primaries) {
2508 CFRelease(vtctx->color_primaries);
2509 vtctx->color_primaries = NULL;
2512 if (vtctx->transfer_function) {
2513 CFRelease(vtctx->transfer_function);
2514 vtctx->transfer_function = NULL;
2517 if (vtctx->ycbcr_matrix) {
2518 CFRelease(vtctx->ycbcr_matrix);
2519 vtctx->ycbcr_matrix = NULL;
2525 static const enum AVPixelFormat avc_pix_fmts[] = {
2526 AV_PIX_FMT_VIDEOTOOLBOX,
2532 static const enum AVPixelFormat hevc_pix_fmts[] = {
2533 AV_PIX_FMT_VIDEOTOOLBOX,
2540 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2541 #define COMMON_OPTIONS \
2542 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2543 { .i64 = 0 }, 0, 1, VE }, \
2544 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2545 { .i64 = 0 }, 0, 1, VE }, \
2546 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2547 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2548 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2549 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2550 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2551 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2553 #define OFFSET(x) offsetof(VTEncContext, x)
2554 static const AVOption h264_options[] = {
2555 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = H264_PROF_AUTO }, H264_PROF_AUTO, H264_PROF_COUNT, VE, "profile" },
2556 { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_BASELINE }, INT_MIN, INT_MAX, VE, "profile" },
2557 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2558 { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_HIGH }, INT_MIN, INT_MAX, VE, "profile" },
2559 { "extended", "Extend Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_EXTENDED }, INT_MIN, INT_MAX, VE, "profile" },
2561 { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, "level" },
2562 { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, "level" },
2563 { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, "level" },
2564 { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, "level" },
2565 { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, "level" },
2566 { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, "level" },
2567 { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, "level" },
2568 { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, "level" },
2569 { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, "level" },
2570 { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, "level" },
2571 { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, "level" },
2573 { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, "coder" },
2574 { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2575 { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2576 { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2577 { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2579 { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2585 static const AVClass h264_videotoolbox_class = {
2586 .class_name = "h264_videotoolbox",
2587 .item_name = av_default_item_name,
2588 .option = h264_options,
2589 .version = LIBAVUTIL_VERSION_INT,
2592 AVCodec ff_h264_videotoolbox_encoder = {
2593 .name = "h264_videotoolbox",
2594 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.264 Encoder"),
2595 .type = AVMEDIA_TYPE_VIDEO,
2596 .id = AV_CODEC_ID_H264,
2597 .priv_data_size = sizeof(VTEncContext),
2598 .pix_fmts = avc_pix_fmts,
2600 .encode2 = vtenc_frame,
2601 .close = vtenc_close,
2602 .capabilities = AV_CODEC_CAP_DELAY,
2603 .priv_class = &h264_videotoolbox_class,
2604 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2605 FF_CODEC_CAP_INIT_CLEANUP,
2608 static const AVOption hevc_options[] = {
2609 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = HEVC_PROF_AUTO }, HEVC_PROF_AUTO, HEVC_PROF_COUNT, VE, "profile" },
2610 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2611 { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN10 }, INT_MIN, INT_MAX, VE, "profile" },
2617 static const AVClass hevc_videotoolbox_class = {
2618 .class_name = "hevc_videotoolbox",
2619 .item_name = av_default_item_name,
2620 .option = hevc_options,
2621 .version = LIBAVUTIL_VERSION_INT,
2624 AVCodec ff_hevc_videotoolbox_encoder = {
2625 .name = "hevc_videotoolbox",
2626 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.265 Encoder"),
2627 .type = AVMEDIA_TYPE_VIDEO,
2628 .id = AV_CODEC_ID_HEVC,
2629 .priv_data_size = sizeof(VTEncContext),
2630 .pix_fmts = hevc_pix_fmts,
2632 .encode2 = vtenc_frame,
2633 .close = vtenc_close,
2634 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
2635 .priv_class = &hevc_videotoolbox_class,
2636 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2637 FF_CODEC_CAP_INIT_CLEANUP,
2638 .wrapper_name = "videotoolbox",