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;
84 CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel;
85 CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel;
87 CFStringRef kVTCompressionPropertyKey_RealTime;
89 CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder;
90 CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder;
92 getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
95 #define GET_SYM(symbol, defaultVal) \
97 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
99 compat_keys.symbol = CFSTR(defaultVal); \
101 compat_keys.symbol = *handle; \
104 static pthread_once_t once_ctrl = PTHREAD_ONCE_INIT;
106 static void loadVTEncSymbols(){
107 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
108 (getParameterSetAtIndex)dlsym(
110 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
113 GET_SYM(kCVImageBufferColorPrimaries_ITU_R_2020, "ITU_R_2020");
114 GET_SYM(kCVImageBufferTransferFunction_ITU_R_2020, "ITU_R_2020");
115 GET_SYM(kCVImageBufferYCbCrMatrix_ITU_R_2020, "ITU_R_2020");
117 GET_SYM(kVTCompressionPropertyKey_H264EntropyMode, "H264EntropyMode");
118 GET_SYM(kVTH264EntropyMode_CAVLC, "CAVLC");
119 GET_SYM(kVTH264EntropyMode_CABAC, "CABAC");
121 GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
122 GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
123 GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
124 GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
125 GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
126 GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
127 GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
128 GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
129 GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
130 GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
131 GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
132 GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
133 GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
134 GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
135 GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
136 GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
137 GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
138 GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
139 GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
141 GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
142 GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
144 GET_SYM(kVTCompressionPropertyKey_RealTime, "RealTime");
146 GET_SYM(kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
147 "EnableHardwareAcceleratedVideoEncoder");
148 GET_SYM(kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
149 "RequireHardwareAcceleratedVideoEncoder");
152 typedef enum VT_H264Profile {
160 typedef enum VTH264Entropy{
166 typedef enum VT_HEVCProfile {
173 static const uint8_t start_code[] = { 0, 0, 0, 1 };
175 typedef struct ExtraSEI {
180 typedef struct BufNode {
181 CMSampleBufferRef cm_buffer;
183 struct BufNode* next;
187 typedef struct VTEncContext {
189 enum AVCodecID codec_id;
190 VTCompressionSessionRef session;
191 CFStringRef ycbcr_matrix;
192 CFStringRef color_primaries;
193 CFStringRef transfer_function;
194 getParameterSetAtIndex get_param_set_func;
196 pthread_mutex_t lock;
197 pthread_cond_t cv_sample_sent;
204 int64_t frame_ct_out;
214 int64_t frames_before;
215 int64_t frames_after;
222 bool warned_color_range;
226 static int vtenc_populate_extradata(AVCodecContext *avctx,
227 CMVideoCodecType codec_type,
228 CFStringRef profile_level,
229 CFNumberRef gamma_level,
230 CFDictionaryRef enc_info,
231 CFDictionaryRef pixel_buffer_info);
234 * NULL-safe release of *refPtr, and sets value to NULL.
236 static void vt_release_num(CFNumberRef* refPtr){
245 static void set_async_error(VTEncContext *vtctx, int err)
249 pthread_mutex_lock(&vtctx->lock);
251 vtctx->async_error = err;
253 info = vtctx->q_head;
254 vtctx->q_head = vtctx->q_tail = NULL;
257 BufNode *next = info->next;
258 CFRelease(info->cm_buffer);
263 pthread_mutex_unlock(&vtctx->lock);
266 static void clear_frame_queue(VTEncContext *vtctx)
268 set_async_error(vtctx, 0);
271 static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
275 pthread_mutex_lock(&vtctx->lock);
277 if (vtctx->async_error) {
278 pthread_mutex_unlock(&vtctx->lock);
279 return vtctx->async_error;
282 if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
285 pthread_mutex_unlock(&vtctx->lock);
289 while (!vtctx->q_head && !vtctx->async_error && wait) {
290 pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
293 if (!vtctx->q_head) {
294 pthread_mutex_unlock(&vtctx->lock);
299 info = vtctx->q_head;
300 vtctx->q_head = vtctx->q_head->next;
301 if (!vtctx->q_head) {
302 vtctx->q_tail = NULL;
305 pthread_mutex_unlock(&vtctx->lock);
307 *buf = info->cm_buffer;
310 } else if (info->sei) {
311 if (info->sei->data) av_free(info->sei->data);
316 vtctx->frame_ct_out++;
321 static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
323 BufNode *info = av_malloc(sizeof(BufNode));
325 set_async_error(vtctx, AVERROR(ENOMEM));
330 info->cm_buffer = buffer;
334 pthread_mutex_lock(&vtctx->lock);
335 pthread_cond_signal(&vtctx->cv_sample_sent);
337 if (!vtctx->q_head) {
338 vtctx->q_head = info;
340 vtctx->q_tail->next = info;
343 vtctx->q_tail = info;
345 pthread_mutex_unlock(&vtctx->lock);
348 static int count_nalus(size_t length_code_size,
349 CMSampleBufferRef sample_buffer,
356 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
357 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
359 if (length_code_size > 4)
360 return AVERROR_INVALIDDATA;
362 while (offset < src_size) {
367 status = CMBlockBufferCopyDataBytes(block,
372 for (i = 0; i < length_code_size; i++) {
374 box_len |= size_buf[i];
377 curr_src_len = box_len + length_code_size;
378 offset += curr_src_len;
387 static CMVideoCodecType get_cm_codec_type(enum AVCodecID id)
390 case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
391 case AV_CODEC_ID_HEVC: return kCMVideoCodecType_HEVC;
397 * Get the parameter sets from a CMSampleBufferRef.
398 * @param dst If *dst isn't NULL, the parameters are copied into existing
399 * memory. *dst_size must be set accordingly when *dst != NULL.
400 * If *dst is NULL, it will be allocated.
401 * In all cases, *dst_size is set to the number of bytes used starting
404 static int get_params_size(
405 AVCodecContext *avctx,
406 CMVideoFormatDescriptionRef vid_fmt,
409 VTEncContext *vtctx = avctx->priv_data;
410 size_t total_size = 0;
412 int is_count_bad = 0;
415 status = vtctx->get_param_set_func(vid_fmt,
427 for (i = 0; i < ps_count || is_count_bad; i++) {
430 status = vtctx->get_param_set_func(vid_fmt,
438 * When ps_count is invalid, status != 0 ends the loop normally
439 * unless we didn't get any parameter sets.
441 if (i > 0 && is_count_bad) status = 0;
446 total_size += ps_size + sizeof(start_code);
450 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
451 return AVERROR_EXTERNAL;
458 static int copy_param_sets(
459 AVCodecContext *avctx,
460 CMVideoFormatDescriptionRef vid_fmt,
464 VTEncContext *vtctx = avctx->priv_data;
466 int is_count_bad = 0;
471 status = vtctx->get_param_set_func(vid_fmt,
484 for (i = 0; i < ps_count || is_count_bad; i++) {
489 status = vtctx->get_param_set_func(vid_fmt,
496 if (i > 0 && is_count_bad) status = 0;
501 next_offset = offset + sizeof(start_code) + ps_size;
502 if (dst_size < next_offset) {
503 av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
504 return AVERROR_BUFFER_TOO_SMALL;
507 memcpy(dst + offset, start_code, sizeof(start_code));
508 offset += sizeof(start_code);
510 memcpy(dst + offset, ps, ps_size);
511 offset = next_offset;
515 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
516 return AVERROR_EXTERNAL;
522 static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
524 CMVideoFormatDescriptionRef vid_fmt;
528 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
530 av_log(avctx, AV_LOG_ERROR, "No video format.\n");
531 return AVERROR_EXTERNAL;
534 status = get_params_size(avctx, vid_fmt, &total_size);
536 av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
540 avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
541 if (!avctx->extradata) {
542 return AVERROR(ENOMEM);
544 avctx->extradata_size = total_size;
546 status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
549 av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
556 static void vtenc_output_callback(
558 void *sourceFrameCtx,
560 VTEncodeInfoFlags flags,
561 CMSampleBufferRef sample_buffer)
563 AVCodecContext *avctx = ctx;
564 VTEncContext *vtctx = avctx->priv_data;
565 ExtraSEI *sei = sourceFrameCtx;
567 if (vtctx->async_error) {
568 if(sample_buffer) CFRelease(sample_buffer);
572 if (status || !sample_buffer) {
573 av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
574 set_async_error(vtctx, AVERROR_EXTERNAL);
578 if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
579 int set_status = set_extradata(avctx, sample_buffer);
581 set_async_error(vtctx, set_status);
586 vtenc_q_push(vtctx, sample_buffer, sei);
589 static int get_length_code_size(
590 AVCodecContext *avctx,
591 CMSampleBufferRef sample_buffer,
594 VTEncContext *vtctx = avctx->priv_data;
595 CMVideoFormatDescriptionRef vid_fmt;
599 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
601 av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
602 return AVERROR_EXTERNAL;
605 status = vtctx->get_param_set_func(vid_fmt,
612 av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
613 return AVERROR_EXTERNAL;
621 * Returns true on success.
623 * If profile_level_val is NULL and this method returns true, don't specify the
624 * profile/level to the encoder.
626 static bool get_vt_h264_profile_level(AVCodecContext *avctx,
627 CFStringRef *profile_level_val)
629 VTEncContext *vtctx = avctx->priv_data;
630 int64_t profile = vtctx->profile;
632 if (profile == H264_PROF_AUTO && vtctx->level) {
633 //Need to pick a profile if level is not auto-selected.
634 profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;
637 *profile_level_val = NULL;
643 case H264_PROF_BASELINE:
644 switch (vtctx->level) {
645 case 0: *profile_level_val =
646 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
647 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
648 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
649 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
650 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
651 case 40: *profile_level_val =
652 compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
653 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
654 case 42: *profile_level_val =
655 compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
656 case 50: *profile_level_val =
657 compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
658 case 51: *profile_level_val =
659 compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
660 case 52: *profile_level_val =
661 compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
666 switch (vtctx->level) {
667 case 0: *profile_level_val =
668 compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
669 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
670 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
671 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
672 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
673 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
674 case 42: *profile_level_val =
675 compat_keys.kVTProfileLevel_H264_Main_4_2; break;
676 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
677 case 51: *profile_level_val =
678 compat_keys.kVTProfileLevel_H264_Main_5_1; break;
679 case 52: *profile_level_val =
680 compat_keys.kVTProfileLevel_H264_Main_5_2; break;
685 switch (vtctx->level) {
686 case 0: *profile_level_val =
687 compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
688 case 30: *profile_level_val =
689 compat_keys.kVTProfileLevel_H264_High_3_0; break;
690 case 31: *profile_level_val =
691 compat_keys.kVTProfileLevel_H264_High_3_1; break;
692 case 32: *profile_level_val =
693 compat_keys.kVTProfileLevel_H264_High_3_2; break;
694 case 40: *profile_level_val =
695 compat_keys.kVTProfileLevel_H264_High_4_0; break;
696 case 41: *profile_level_val =
697 compat_keys.kVTProfileLevel_H264_High_4_1; break;
698 case 42: *profile_level_val =
699 compat_keys.kVTProfileLevel_H264_High_4_2; break;
700 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
701 case 51: *profile_level_val =
702 compat_keys.kVTProfileLevel_H264_High_5_1; break;
703 case 52: *profile_level_val =
704 compat_keys.kVTProfileLevel_H264_High_5_2; break;
709 if (!*profile_level_val) {
710 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
718 * Returns true on success.
720 * If profile_level_val is NULL and this method returns true, don't specify the
721 * profile/level to the encoder.
723 static bool get_vt_hevc_profile_level(AVCodecContext *avctx,
724 CFStringRef *profile_level_val)
726 VTEncContext *vtctx = avctx->priv_data;
727 int64_t profile = vtctx->profile;
729 *profile_level_val = NULL;
736 compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
738 case HEVC_PROF_MAIN10:
740 compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
744 if (!*profile_level_val) {
745 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
752 static int get_cv_pixel_format(AVCodecContext* avctx,
753 enum AVPixelFormat fmt,
754 enum AVColorRange range,
755 int* av_pixel_format,
758 if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
759 range != AVCOL_RANGE_JPEG;
761 //MPEG range is used when no range is set
762 if (fmt == AV_PIX_FMT_NV12) {
763 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
764 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
765 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
766 } else if (fmt == AV_PIX_FMT_YUV420P) {
767 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
768 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
769 kCVPixelFormatType_420YpCbCr8Planar;
770 } else if (fmt == AV_PIX_FMT_P010LE) {
771 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
772 kCVPixelFormatType_420YpCbCr10BiPlanarFullRange :
773 kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
774 *av_pixel_format = kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
776 return AVERROR(EINVAL);
782 static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
783 VTEncContext *vtctx = avctx->priv_data;
785 if (vtctx->color_primaries) {
786 CFDictionarySetValue(dict,
787 kCVImageBufferColorPrimariesKey,
788 vtctx->color_primaries);
791 if (vtctx->transfer_function) {
792 CFDictionarySetValue(dict,
793 kCVImageBufferTransferFunctionKey,
794 vtctx->transfer_function);
797 if (vtctx->ycbcr_matrix) {
798 CFDictionarySetValue(dict,
799 kCVImageBufferYCbCrMatrixKey,
800 vtctx->ycbcr_matrix);
804 static int create_cv_pixel_buffer_info(AVCodecContext* avctx,
805 CFMutableDictionaryRef* dict)
807 CFNumberRef cv_color_format_num = NULL;
808 CFNumberRef width_num = NULL;
809 CFNumberRef height_num = NULL;
810 CFMutableDictionaryRef pixel_buffer_info = NULL;
812 int status = get_cv_pixel_format(avctx,
817 if (status) return status;
819 pixel_buffer_info = CFDictionaryCreateMutable(
822 &kCFCopyStringDictionaryKeyCallBacks,
823 &kCFTypeDictionaryValueCallBacks);
825 if (!pixel_buffer_info) goto pbinfo_nomem;
827 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
830 if (!cv_color_format_num) goto pbinfo_nomem;
832 CFDictionarySetValue(pixel_buffer_info,
833 kCVPixelBufferPixelFormatTypeKey,
834 cv_color_format_num);
835 vt_release_num(&cv_color_format_num);
837 width_num = CFNumberCreate(kCFAllocatorDefault,
840 if (!width_num) return AVERROR(ENOMEM);
842 CFDictionarySetValue(pixel_buffer_info,
843 kCVPixelBufferWidthKey,
845 vt_release_num(&width_num);
847 height_num = CFNumberCreate(kCFAllocatorDefault,
850 if (!height_num) goto pbinfo_nomem;
852 CFDictionarySetValue(pixel_buffer_info,
853 kCVPixelBufferHeightKey,
855 vt_release_num(&height_num);
857 add_color_attr(avctx, pixel_buffer_info);
859 *dict = pixel_buffer_info;
863 vt_release_num(&cv_color_format_num);
864 vt_release_num(&width_num);
865 vt_release_num(&height_num);
866 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
868 return AVERROR(ENOMEM);
871 static int get_cv_color_primaries(AVCodecContext *avctx,
872 CFStringRef *primaries)
874 enum AVColorPrimaries pri = avctx->color_primaries;
876 case AVCOL_PRI_UNSPECIFIED:
880 case AVCOL_PRI_BT709:
881 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
884 case AVCOL_PRI_BT2020:
885 *primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
889 av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
897 static int get_cv_transfer_function(AVCodecContext *avctx,
898 CFStringRef *transfer_fnc,
899 CFNumberRef *gamma_level)
901 enum AVColorTransferCharacteristic trc = avctx->color_trc;
906 case AVCOL_TRC_UNSPECIFIED:
907 *transfer_fnc = NULL;
910 case AVCOL_TRC_BT709:
911 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
914 case AVCOL_TRC_SMPTE240M:
915 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
918 case AVCOL_TRC_GAMMA22:
920 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
921 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
924 case AVCOL_TRC_GAMMA28:
926 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
927 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
930 case AVCOL_TRC_BT2020_10:
931 case AVCOL_TRC_BT2020_12:
932 *transfer_fnc = compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
936 av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));
943 static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix) {
944 switch(avctx->colorspace) {
945 case AVCOL_SPC_BT709:
946 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
949 case AVCOL_SPC_UNSPECIFIED:
953 case AVCOL_SPC_BT470BG:
954 case AVCOL_SPC_SMPTE170M:
955 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
958 case AVCOL_SPC_SMPTE240M:
959 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
962 case AVCOL_SPC_BT2020_NCL:
963 *matrix = compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
967 av_log(avctx, AV_LOG_ERROR, "Color space %s is not supported.\n", av_color_space_name(avctx->colorspace));
974 static int vtenc_create_encoder(AVCodecContext *avctx,
975 CMVideoCodecType codec_type,
976 CFStringRef profile_level,
977 CFNumberRef gamma_level,
978 CFDictionaryRef enc_info,
979 CFDictionaryRef pixel_buffer_info,
980 VTCompressionSessionRef *session)
982 VTEncContext *vtctx = avctx->priv_data;
983 SInt32 bit_rate = avctx->bit_rate;
984 SInt32 max_rate = avctx->rc_max_rate;
985 CFNumberRef bit_rate_num;
986 CFNumberRef bytes_per_second;
987 CFNumberRef one_second;
988 CFArrayRef data_rate_limits;
989 int64_t bytes_per_second_value = 0;
990 int64_t one_second_value = 0;
993 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1000 vtenc_output_callback,
1004 if (status || !vtctx->session) {
1005 av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
1007 #if !TARGET_OS_IPHONE
1008 if (!vtctx->allow_sw) {
1009 av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1013 return AVERROR_EXTERNAL;
1016 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1017 kCFNumberSInt32Type,
1019 if (!bit_rate_num) return AVERROR(ENOMEM);
1021 status = VTSessionSetProperty(vtctx->session,
1022 kVTCompressionPropertyKey_AverageBitRate,
1024 CFRelease(bit_rate_num);
1027 av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
1028 return AVERROR_EXTERNAL;
1031 if (vtctx->codec_id == AV_CODEC_ID_H264 && max_rate > 0) {
1032 // kVTCompressionPropertyKey_DataRateLimits is not available for HEVC
1033 bytes_per_second_value = max_rate >> 3;
1034 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1035 kCFNumberSInt64Type,
1036 &bytes_per_second_value);
1037 if (!bytes_per_second) {
1038 return AVERROR(ENOMEM);
1040 one_second_value = 1;
1041 one_second = CFNumberCreate(kCFAllocatorDefault,
1042 kCFNumberSInt64Type,
1045 CFRelease(bytes_per_second);
1046 return AVERROR(ENOMEM);
1048 nums[0] = (void *)bytes_per_second;
1049 nums[1] = (void *)one_second;
1050 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1051 (const void **)nums,
1053 &kCFTypeArrayCallBacks);
1055 if (!data_rate_limits) {
1056 CFRelease(bytes_per_second);
1057 CFRelease(one_second);
1058 return AVERROR(ENOMEM);
1060 status = VTSessionSetProperty(vtctx->session,
1061 kVTCompressionPropertyKey_DataRateLimits,
1064 CFRelease(bytes_per_second);
1065 CFRelease(one_second);
1066 CFRelease(data_rate_limits);
1069 av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
1070 return AVERROR_EXTERNAL;
1074 if (vtctx->codec_id == AV_CODEC_ID_H264) {
1075 // kVTCompressionPropertyKey_ProfileLevel is not available for HEVC
1076 if (profile_level) {
1077 status = VTSessionSetProperty(vtctx->session,
1078 kVTCompressionPropertyKey_ProfileLevel,
1081 av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d\n", status);
1086 if (avctx->gop_size > 0) {
1087 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1091 return AVERROR(ENOMEM);
1094 status = VTSessionSetProperty(vtctx->session,
1095 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1097 CFRelease(interval);
1100 av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
1101 return AVERROR_EXTERNAL;
1105 if (vtctx->frames_before) {
1106 status = VTSessionSetProperty(vtctx->session,
1107 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1110 if (status == kVTPropertyNotSupportedErr) {
1111 av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
1112 } else if (status) {
1113 av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
1117 if (vtctx->frames_after) {
1118 status = VTSessionSetProperty(vtctx->session,
1119 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1122 if (status == kVTPropertyNotSupportedErr) {
1123 av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
1124 } else if (status) {
1125 av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
1129 if (avctx->sample_aspect_ratio.num != 0) {
1132 CFMutableDictionaryRef par;
1133 AVRational *avpar = &avctx->sample_aspect_ratio;
1135 av_reduce(&avpar->num, &avpar->den,
1136 avpar->num, avpar->den,
1139 num = CFNumberCreate(kCFAllocatorDefault,
1143 den = CFNumberCreate(kCFAllocatorDefault,
1149 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1151 &kCFCopyStringDictionaryKeyCallBacks,
1152 &kCFTypeDictionaryValueCallBacks);
1154 if (!par || !num || !den) {
1155 if (par) CFRelease(par);
1156 if (num) CFRelease(num);
1157 if (den) CFRelease(den);
1159 return AVERROR(ENOMEM);
1162 CFDictionarySetValue(
1164 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1167 CFDictionarySetValue(
1169 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1172 status = VTSessionSetProperty(vtctx->session,
1173 kVTCompressionPropertyKey_PixelAspectRatio,
1183 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1184 avctx->sample_aspect_ratio.num,
1185 avctx->sample_aspect_ratio.den,
1188 return AVERROR_EXTERNAL;
1193 if (vtctx->transfer_function) {
1194 status = VTSessionSetProperty(vtctx->session,
1195 kVTCompressionPropertyKey_TransferFunction,
1196 vtctx->transfer_function);
1199 av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1204 if (vtctx->ycbcr_matrix) {
1205 status = VTSessionSetProperty(vtctx->session,
1206 kVTCompressionPropertyKey_YCbCrMatrix,
1207 vtctx->ycbcr_matrix);
1210 av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1215 if (vtctx->color_primaries) {
1216 status = VTSessionSetProperty(vtctx->session,
1217 kVTCompressionPropertyKey_ColorPrimaries,
1218 vtctx->color_primaries);
1221 av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1226 status = VTSessionSetProperty(vtctx->session,
1227 kCVImageBufferGammaLevelKey,
1231 av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1235 if (!vtctx->has_b_frames) {
1236 status = VTSessionSetProperty(vtctx->session,
1237 kVTCompressionPropertyKey_AllowFrameReordering,
1241 av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1242 return AVERROR_EXTERNAL;
1246 if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1247 CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1248 compat_keys.kVTH264EntropyMode_CABAC:
1249 compat_keys.kVTH264EntropyMode_CAVLC;
1251 status = VTSessionSetProperty(vtctx->session,
1252 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1256 av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1260 if (vtctx->realtime) {
1261 status = VTSessionSetProperty(vtctx->session,
1262 compat_keys.kVTCompressionPropertyKey_RealTime,
1266 av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1270 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1272 av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
1273 return AVERROR_EXTERNAL;
1279 static int vtenc_configure_encoder(AVCodecContext *avctx)
1281 CFMutableDictionaryRef enc_info;
1282 CFMutableDictionaryRef pixel_buffer_info;
1283 CMVideoCodecType codec_type;
1284 VTEncContext *vtctx = avctx->priv_data;
1285 CFStringRef profile_level;
1286 CFNumberRef gamma_level = NULL;
1289 codec_type = get_cm_codec_type(avctx->codec_id);
1291 av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
1292 return AVERROR(EINVAL);
1295 vtctx->codec_id = avctx->codec_id;
1297 if (vtctx->codec_id == AV_CODEC_ID_H264) {
1298 vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
1300 vtctx->has_b_frames = avctx->max_b_frames > 0;
1301 if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){
1302 av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1303 vtctx->has_b_frames = false;
1306 if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {
1307 av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1308 vtctx->entropy = VT_ENTROPY_NOT_SET;
1311 if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1313 vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
1314 if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
1315 if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1318 enc_info = CFDictionaryCreateMutable(
1319 kCFAllocatorDefault,
1321 &kCFCopyStringDictionaryKeyCallBacks,
1322 &kCFTypeDictionaryValueCallBacks
1325 if (!enc_info) return AVERROR(ENOMEM);
1327 #if !TARGET_OS_IPHONE
1328 if(vtctx->require_sw) {
1329 CFDictionarySetValue(enc_info,
1330 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1332 } else if (!vtctx->allow_sw) {
1333 CFDictionarySetValue(enc_info,
1334 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1337 CFDictionarySetValue(enc_info,
1338 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1343 if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1344 status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1348 pixel_buffer_info = NULL;
1351 vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1353 get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);
1354 get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);
1355 get_cv_color_primaries(avctx, &vtctx->color_primaries);
1358 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1359 status = vtenc_populate_extradata(avctx,
1369 status = vtenc_create_encoder(avctx,
1379 CFRelease(gamma_level);
1381 if (pixel_buffer_info)
1382 CFRelease(pixel_buffer_info);
1384 CFRelease(enc_info);
1389 static av_cold int vtenc_init(AVCodecContext *avctx)
1391 VTEncContext *vtctx = avctx->priv_data;
1392 CFBooleanRef has_b_frames_cfbool;
1395 pthread_once(&once_ctrl, loadVTEncSymbols);
1397 pthread_mutex_init(&vtctx->lock, NULL);
1398 pthread_cond_init(&vtctx->cv_sample_sent, NULL);
1400 vtctx->session = NULL;
1401 status = vtenc_configure_encoder(avctx);
1402 if (status) return status;
1404 status = VTSessionCopyProperty(vtctx->session,
1405 kVTCompressionPropertyKey_AllowFrameReordering,
1406 kCFAllocatorDefault,
1407 &has_b_frames_cfbool);
1409 if (!status && has_b_frames_cfbool) {
1410 //Some devices don't output B-frames for main profile, even if requested.
1411 vtctx->has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1412 CFRelease(has_b_frames_cfbool);
1414 avctx->has_b_frames = vtctx->has_b_frames;
1419 static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1421 CFArrayRef attachments;
1422 CFDictionaryRef attachment;
1423 CFBooleanRef not_sync;
1426 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1427 len = !attachments ? 0 : CFArrayGetCount(attachments);
1430 *is_key_frame = true;
1434 attachment = CFArrayGetValueAtIndex(attachments, 0);
1436 if (CFDictionaryGetValueIfPresent(attachment,
1437 kCMSampleAttachmentKey_NotSync,
1438 (const void **)¬_sync))
1440 *is_key_frame = !CFBooleanGetValue(not_sync);
1442 *is_key_frame = true;
1446 static int is_post_sei_nal_type(int nal_type){
1447 return nal_type != H264_NAL_SEI &&
1448 nal_type != H264_NAL_SPS &&
1449 nal_type != H264_NAL_PPS &&
1450 nal_type != H264_NAL_AUD;
1454 * Finds the sei message start/size of type find_sei_type.
1455 * If more than one of that type exists, the last one is returned.
1457 static int find_sei_end(AVCodecContext *avctx,
1463 size_t sei_payload_size = 0;
1464 int sei_payload_type = 0;
1466 uint8_t *nal_start = nal_data;
1471 nal_type = *nal_data & 0x1F;
1472 if (nal_type != H264_NAL_SEI)
1478 if (nal_data[nal_size - 1] == 0x80)
1481 while (nal_size > 0 && *nal_data > 0) {
1483 sei_payload_type += *nal_data;
1486 } while (nal_size > 0 && *nal_data == 0xFF);
1489 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1490 return AVERROR_INVALIDDATA;
1494 sei_payload_size += *nal_data;
1497 } while (nal_size > 0 && *nal_data == 0xFF);
1499 if (nal_size < sei_payload_size) {
1500 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1501 return AVERROR_INVALIDDATA;
1504 nal_data += sei_payload_size;
1505 nal_size -= sei_payload_size;
1508 *sei_end = nal_data;
1510 return nal_data - nal_start + 1;
1514 * Copies the data inserting emulation prevention bytes as needed.
1515 * Existing data in the destination can be taken into account by providing
1516 * dst with a dst_offset > 0.
1518 * @return The number of bytes copied on success. On failure, the negative of
1519 * the number of bytes needed to copy src is returned.
1521 static int copy_emulation_prev(const uint8_t *src,
1530 uint8_t* dst_end = dst + dst_size;
1531 const uint8_t* src_end = src + src_size;
1532 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1534 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1543 for (; src < src_end; src++, dst++) {
1545 int insert_ep3_byte = *src <= 3;
1546 if (insert_ep3_byte) {
1564 wrote_bytes = dst - dst_start;
1567 return -wrote_bytes;
1572 static int write_sei(const ExtraSEI *sei,
1577 uint8_t *sei_start = dst;
1578 size_t remaining_sei_size = sei->size;
1579 size_t remaining_dst_size = dst_size;
1584 if (!remaining_dst_size)
1585 return AVERROR_BUFFER_TOO_SMALL;
1587 while (sei_type && remaining_dst_size != 0) {
1588 int sei_byte = sei_type > 255 ? 255 : sei_type;
1591 sei_type -= sei_byte;
1593 remaining_dst_size--;
1597 return AVERROR_BUFFER_TOO_SMALL;
1599 while (remaining_sei_size && remaining_dst_size != 0) {
1600 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1603 remaining_sei_size -= size_byte;
1605 remaining_dst_size--;
1608 if (remaining_dst_size < sei->size)
1609 return AVERROR_BUFFER_TOO_SMALL;
1611 header_bytes = dst - sei_start;
1613 offset = header_bytes;
1614 bytes_written = copy_emulation_prev(sei->data,
1619 if (bytes_written < 0)
1620 return AVERROR_BUFFER_TOO_SMALL;
1622 bytes_written += header_bytes;
1623 return bytes_written;
1627 * Copies NAL units and replaces length codes with
1628 * H.264 Annex B start codes. On failure, the contents of
1629 * dst_data may have been modified.
1631 * @param length_code_size Byte length of each length code
1632 * @param sample_buffer NAL units prefixed with length codes.
1633 * @param sei Optional A53 closed captions SEI data.
1634 * @param dst_data Must be zeroed before calling this function.
1635 * Contains the copied NAL units prefixed with
1636 * start codes when the function returns
1638 * @param dst_size Length of dst_data
1639 * @return 0 on success
1640 * AVERROR_INVALIDDATA if length_code_size is invalid
1641 * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
1642 * or if a length_code in src_data specifies data beyond
1643 * the end of its buffer.
1645 static int copy_replace_length_codes(
1646 AVCodecContext *avctx,
1647 size_t length_code_size,
1648 CMSampleBufferRef sample_buffer,
1653 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1654 size_t remaining_src_size = src_size;
1655 size_t remaining_dst_size = dst_size;
1656 size_t src_offset = 0;
1659 uint8_t size_buf[4];
1661 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
1663 if (length_code_size > 4) {
1664 return AVERROR_INVALIDDATA;
1667 while (remaining_src_size > 0) {
1668 size_t curr_src_len;
1669 size_t curr_dst_len;
1675 status = CMBlockBufferCopyDataBytes(block,
1680 av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
1681 return AVERROR_EXTERNAL;
1684 status = CMBlockBufferCopyDataBytes(block,
1685 src_offset + length_code_size,
1690 av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
1691 return AVERROR_EXTERNAL;
1696 for (i = 0; i < length_code_size; i++) {
1698 box_len |= size_buf[i];
1701 if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
1702 //No SEI NAL unit - insert.
1705 memcpy(dst_data, start_code, sizeof(start_code));
1706 dst_data += sizeof(start_code);
1707 remaining_dst_size -= sizeof(start_code);
1709 *dst_data = H264_NAL_SEI;
1711 remaining_dst_size--;
1713 wrote_bytes = write_sei(sei,
1714 H264_SEI_TYPE_USER_DATA_REGISTERED,
1716 remaining_dst_size);
1718 if (wrote_bytes < 0)
1721 remaining_dst_size -= wrote_bytes;
1722 dst_data += wrote_bytes;
1724 if (remaining_dst_size <= 0)
1725 return AVERROR_BUFFER_TOO_SMALL;
1730 remaining_dst_size--;
1735 curr_src_len = box_len + length_code_size;
1736 curr_dst_len = box_len + sizeof(start_code);
1738 if (remaining_src_size < curr_src_len) {
1739 return AVERROR_BUFFER_TOO_SMALL;
1742 if (remaining_dst_size < curr_dst_len) {
1743 return AVERROR_BUFFER_TOO_SMALL;
1746 dst_box = dst_data + sizeof(start_code);
1748 memcpy(dst_data, start_code, sizeof(start_code));
1749 status = CMBlockBufferCopyDataBytes(block,
1750 src_offset + length_code_size,
1755 av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
1756 return AVERROR_EXTERNAL;
1759 if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
1760 //Found SEI NAL unit - append.
1765 old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
1766 if (old_sei_length < 0)
1769 wrote_bytes = write_sei(sei,
1770 H264_SEI_TYPE_USER_DATA_REGISTERED,
1772 remaining_dst_size - old_sei_length);
1773 if (wrote_bytes < 0)
1776 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1777 return AVERROR_BUFFER_TOO_SMALL;
1779 new_sei[wrote_bytes++] = 0x80;
1780 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1782 dst_data += extra_bytes;
1783 remaining_dst_size -= extra_bytes;
1788 src_offset += curr_src_len;
1789 dst_data += curr_dst_len;
1791 remaining_src_size -= curr_src_len;
1792 remaining_dst_size -= curr_dst_len;
1799 * Returns a sufficient number of bytes to contain the sei data.
1800 * It may be greater than the minimum required.
1802 static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
1807 copied_size = -copy_emulation_prev(sei->data,
1813 if ((sei->size % 255) == 0) //may result in an extra byte
1816 return copied_size + sei->size / 255 + 1 + type / 255 + 1;
1819 static int vtenc_cm_to_avpacket(
1820 AVCodecContext *avctx,
1821 CMSampleBufferRef sample_buffer,
1825 VTEncContext *vtctx = avctx->priv_data;
1830 size_t length_code_size;
1831 size_t header_size = 0;
1833 size_t out_buf_size;
1834 size_t sei_nalu_size = 0;
1836 int64_t time_base_num;
1840 CMVideoFormatDescriptionRef vid_fmt;
1843 vtenc_get_frame_info(sample_buffer, &is_key_frame);
1844 status = get_length_code_size(avctx, sample_buffer, &length_code_size);
1845 if (status) return status;
1847 add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
1850 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1852 av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
1853 return AVERROR_EXTERNAL;
1856 int status = get_params_size(avctx, vid_fmt, &header_size);
1857 if (status) return status;
1860 status = count_nalus(length_code_size, sample_buffer, &nalu_count);
1865 size_t msg_size = get_sei_msg_bytes(sei,
1866 H264_SEI_TYPE_USER_DATA_REGISTERED);
1868 sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
1871 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1872 out_buf_size = header_size +
1875 nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
1877 status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);
1882 status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
1883 if(status) return status;
1886 status = copy_replace_length_codes(
1891 pkt->data + header_size,
1892 pkt->size - header_size
1896 av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
1901 pkt->flags |= AV_PKT_FLAG_KEY;
1904 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1905 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1907 if (CMTIME_IS_INVALID(dts)) {
1908 if (!vtctx->has_b_frames) {
1911 av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
1912 return AVERROR_EXTERNAL;
1916 dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
1917 time_base_num = avctx->time_base.num;
1918 pkt->pts = pts.value / time_base_num;
1919 pkt->dts = dts.value / time_base_num - dts_delta;
1920 pkt->size = out_buf_size;
1926 * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
1927 * containing all planes if so.
1929 static int get_cv_pixel_info(
1930 AVCodecContext *avctx,
1931 const AVFrame *frame,
1937 size_t *contiguous_buf_size)
1939 VTEncContext *vtctx = avctx->priv_data;
1940 int av_format = frame->format;
1941 int av_color_range = frame->color_range;
1946 status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
1950 "Could not get pixel format for color format '%s' range '%s'.\n",
1951 av_get_pix_fmt_name(av_format),
1952 av_color_range > AVCOL_RANGE_UNSPECIFIED &&
1953 av_color_range < AVCOL_RANGE_NB ?
1954 av_color_range_name(av_color_range) :
1957 return AVERROR(EINVAL);
1960 if (range_guessed) {
1961 if (!vtctx->warned_color_range) {
1962 vtctx->warned_color_range = true;
1965 "Color range not set for %s. Using MPEG range.\n",
1966 av_get_pix_fmt_name(av_format));
1970 switch (av_format) {
1971 case AV_PIX_FMT_NV12:
1974 widths [0] = avctx->width;
1975 heights[0] = avctx->height;
1976 strides[0] = frame ? frame->linesize[0] : avctx->width;
1978 widths [1] = (avctx->width + 1) / 2;
1979 heights[1] = (avctx->height + 1) / 2;
1980 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) & -2;
1983 case AV_PIX_FMT_YUV420P:
1986 widths [0] = avctx->width;
1987 heights[0] = avctx->height;
1988 strides[0] = frame ? frame->linesize[0] : avctx->width;
1990 widths [1] = (avctx->width + 1) / 2;
1991 heights[1] = (avctx->height + 1) / 2;
1992 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) / 2;
1994 widths [2] = (avctx->width + 1) / 2;
1995 heights[2] = (avctx->height + 1) / 2;
1996 strides[2] = frame ? frame->linesize[2] : (avctx->width + 1) / 2;
1999 case AV_PIX_FMT_P010LE:
2001 widths[0] = avctx->width;
2002 heights[0] = avctx->height;
2003 strides[0] = frame ? frame->linesize[0] : (avctx->width * 2 + 63) & -64;
2005 widths[1] = (avctx->width + 1) / 2;
2006 heights[1] = (avctx->height + 1) / 2;
2007 strides[1] = frame ? frame->linesize[1] : ((avctx->width + 1) / 2 + 63) & -64;
2014 "Could not get frame format info for color %d range %d.\n",
2018 return AVERROR(EINVAL);
2021 *contiguous_buf_size = 0;
2022 for (i = 0; i < *plane_count; i++) {
2023 if (i < *plane_count - 1 &&
2024 frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
2025 *contiguous_buf_size = 0;
2029 *contiguous_buf_size += strides[i] * heights[i];
2035 //Not used on OSX - frame is never copied.
2036 static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx,
2037 const AVFrame *frame,
2038 CVPixelBufferRef cv_img,
2039 const size_t *plane_strides,
2040 const size_t *plane_rows)
2052 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2057 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2062 if (CVPixelBufferIsPlanar(cv_img)) {
2063 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2064 for (i = 0; frame->data[i]; i++) {
2065 if (i == plane_count) {
2066 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2069 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2072 return AVERROR_EXTERNAL;
2075 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2076 src_addr = (uint8_t*)frame->data[i];
2077 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2078 src_stride = plane_strides[i];
2079 rows = plane_rows[i];
2081 if (dst_stride == src_stride) {
2082 memcpy(dst_addr, src_addr, src_stride * rows);
2084 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2086 for (j = 0; j < rows; j++) {
2087 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2092 if (frame->data[1]) {
2093 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2096 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2099 return AVERROR_EXTERNAL;
2102 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2103 src_addr = (uint8_t*)frame->data[0];
2104 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2105 src_stride = plane_strides[0];
2106 rows = plane_rows[0];
2108 if (dst_stride == src_stride) {
2109 memcpy(dst_addr, src_addr, src_stride * rows);
2111 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2113 for (j = 0; j < rows; j++) {
2114 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2119 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2121 av_log(avctx, AV_LOG_ERROR, "Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2122 return AVERROR_EXTERNAL;
2128 static int create_cv_pixel_buffer(AVCodecContext *avctx,
2129 const AVFrame *frame,
2130 CVPixelBufferRef *cv_img)
2134 size_t widths [AV_NUM_DATA_POINTERS];
2135 size_t heights[AV_NUM_DATA_POINTERS];
2136 size_t strides[AV_NUM_DATA_POINTERS];
2138 size_t contiguous_buf_size;
2139 CVPixelBufferPoolRef pix_buf_pool;
2140 VTEncContext* vtctx = avctx->priv_data;
2142 if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2143 av_assert0(frame->format == AV_PIX_FMT_VIDEOTOOLBOX);
2145 *cv_img = (CVPixelBufferRef)frame->data[3];
2146 av_assert0(*cv_img);
2152 memset(widths, 0, sizeof(widths));
2153 memset(heights, 0, sizeof(heights));
2154 memset(strides, 0, sizeof(strides));
2156 status = get_cv_pixel_info(
2164 &contiguous_buf_size
2171 "Error: Cannot convert format %d color_range %d: %d\n",
2177 return AVERROR_EXTERNAL;
2180 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2181 if (!pix_buf_pool) {
2182 /* On iOS, the VT session is invalidated when the APP switches from
2183 * foreground to background and vice versa. Fetch the actual error code
2184 * of the VT session to detect that case and restart the VT session
2188 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
2189 if (vtstatus == kVTInvalidSessionErr) {
2190 CFRelease(vtctx->session);
2191 vtctx->session = NULL;
2192 status = vtenc_configure_encoder(avctx);
2194 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2196 if (!pix_buf_pool) {
2197 av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2198 return AVERROR_EXTERNAL;
2201 av_log(avctx, AV_LOG_WARNING, "VT session restarted because of a "
2202 "kVTInvalidSessionErr error.\n");
2205 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2211 av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2212 return AVERROR_EXTERNAL;
2215 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2225 static int create_encoder_dict_h264(const AVFrame *frame,
2226 CFDictionaryRef* dict_out)
2228 CFDictionaryRef dict = NULL;
2229 if (frame->pict_type == AV_PICTURE_TYPE_I) {
2230 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2231 const void *vals[] = { kCFBooleanTrue };
2233 dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2234 if(!dict) return AVERROR(ENOMEM);
2241 static int vtenc_send_frame(AVCodecContext *avctx,
2242 VTEncContext *vtctx,
2243 const AVFrame *frame)
2246 CFDictionaryRef frame_dict;
2247 CVPixelBufferRef cv_img = NULL;
2248 AVFrameSideData *side_data = NULL;
2249 ExtraSEI *sei = NULL;
2250 int status = create_cv_pixel_buffer(avctx, frame, &cv_img);
2252 if (status) return status;
2254 status = create_encoder_dict_h264(frame, &frame_dict);
2260 side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
2261 if (vtctx->a53_cc && side_data && side_data->size) {
2262 sei = av_mallocz(sizeof(*sei));
2264 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2266 int ret = ff_alloc_a53_sei(frame, 0, &sei->data, &sei->size);
2268 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2275 time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2276 status = VTCompressionSessionEncodeFrame(
2286 if (frame_dict) CFRelease(frame_dict);
2290 av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
2291 return AVERROR_EXTERNAL;
2297 static av_cold int vtenc_frame(
2298 AVCodecContext *avctx,
2300 const AVFrame *frame,
2303 VTEncContext *vtctx = avctx->priv_data;
2306 CMSampleBufferRef buf = NULL;
2307 ExtraSEI *sei = NULL;
2310 status = vtenc_send_frame(avctx, vtctx, frame);
2313 status = AVERROR_EXTERNAL;
2317 if (vtctx->frame_ct_in == 0) {
2318 vtctx->first_pts = frame->pts;
2319 } else if(vtctx->frame_ct_in == 1 && vtctx->has_b_frames) {
2320 vtctx->dts_delta = frame->pts - vtctx->first_pts;
2323 vtctx->frame_ct_in++;
2324 } else if(!vtctx->flushing) {
2325 vtctx->flushing = true;
2327 status = VTCompressionSessionCompleteFrames(vtctx->session,
2331 av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2332 status = AVERROR_EXTERNAL;
2338 get_frame = vtctx->dts_delta >= 0 || !frame;
2344 status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2345 if (status) goto end_nopkt;
2346 if (!buf) goto end_nopkt;
2348 status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei);
2350 if (sei->data) av_free(sei->data);
2354 if (status) goto end_nopkt;
2360 av_packet_unref(pkt);
2364 static int vtenc_populate_extradata(AVCodecContext *avctx,
2365 CMVideoCodecType codec_type,
2366 CFStringRef profile_level,
2367 CFNumberRef gamma_level,
2368 CFDictionaryRef enc_info,
2369 CFDictionaryRef pixel_buffer_info)
2371 VTEncContext *vtctx = avctx->priv_data;
2373 CVPixelBufferPoolRef pool = NULL;
2374 CVPixelBufferRef pix_buf = NULL;
2376 CMSampleBufferRef buf = NULL;
2378 status = vtenc_create_encoder(avctx,
2388 pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2390 av_log(avctx, AV_LOG_ERROR, "Error getting pixel buffer pool.\n");
2394 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2398 if(status != kCVReturnSuccess){
2399 av_log(avctx, AV_LOG_ERROR, "Error creating frame from pool: %d\n", status);
2403 time = CMTimeMake(0, avctx->time_base.den);
2404 status = VTCompressionSessionEncodeFrame(vtctx->session,
2415 "Error sending frame for extradata: %d\n",
2421 //Populates extradata - output frames are flushed and param sets are available.
2422 status = VTCompressionSessionCompleteFrames(vtctx->session,
2428 status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2430 av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2440 CFRelease(vtctx->session);
2442 vtctx->session = NULL;
2443 vtctx->frame_ct_out = 0;
2445 av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2450 static av_cold int vtenc_close(AVCodecContext *avctx)
2452 VTEncContext *vtctx = avctx->priv_data;
2454 pthread_cond_destroy(&vtctx->cv_sample_sent);
2455 pthread_mutex_destroy(&vtctx->lock);
2457 if(!vtctx->session) return 0;
2459 VTCompressionSessionCompleteFrames(vtctx->session,
2461 clear_frame_queue(vtctx);
2462 CFRelease(vtctx->session);
2463 vtctx->session = NULL;
2465 if (vtctx->color_primaries) {
2466 CFRelease(vtctx->color_primaries);
2467 vtctx->color_primaries = NULL;
2470 if (vtctx->transfer_function) {
2471 CFRelease(vtctx->transfer_function);
2472 vtctx->transfer_function = NULL;
2475 if (vtctx->ycbcr_matrix) {
2476 CFRelease(vtctx->ycbcr_matrix);
2477 vtctx->ycbcr_matrix = NULL;
2483 static const enum AVPixelFormat avc_pix_fmts[] = {
2484 AV_PIX_FMT_VIDEOTOOLBOX,
2490 static const enum AVPixelFormat hevc_pix_fmts[] = {
2491 AV_PIX_FMT_VIDEOTOOLBOX,
2498 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2499 #define COMMON_OPTIONS \
2500 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2501 { .i64 = 0 }, 0, 1, VE }, \
2502 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2503 { .i64 = 0 }, 0, 1, VE }, \
2504 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2505 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2506 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2507 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2508 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2509 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2511 #define OFFSET(x) offsetof(VTEncContext, x)
2512 static const AVOption h264_options[] = {
2513 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = H264_PROF_AUTO }, H264_PROF_AUTO, H264_PROF_COUNT, VE, "profile" },
2514 { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_BASELINE }, INT_MIN, INT_MAX, VE, "profile" },
2515 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2516 { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_HIGH }, INT_MIN, INT_MAX, VE, "profile" },
2518 { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, "level" },
2519 { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, "level" },
2520 { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, "level" },
2521 { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, "level" },
2522 { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, "level" },
2523 { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, "level" },
2524 { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, "level" },
2525 { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, "level" },
2526 { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, "level" },
2527 { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, "level" },
2528 { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, "level" },
2530 { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, "coder" },
2531 { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2532 { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2533 { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2534 { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2536 { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2542 static const AVClass h264_videotoolbox_class = {
2543 .class_name = "h264_videotoolbox",
2544 .item_name = av_default_item_name,
2545 .option = h264_options,
2546 .version = LIBAVUTIL_VERSION_INT,
2549 AVCodec ff_h264_videotoolbox_encoder = {
2550 .name = "h264_videotoolbox",
2551 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.264 Encoder"),
2552 .type = AVMEDIA_TYPE_VIDEO,
2553 .id = AV_CODEC_ID_H264,
2554 .priv_data_size = sizeof(VTEncContext),
2555 .pix_fmts = avc_pix_fmts,
2557 .encode2 = vtenc_frame,
2558 .close = vtenc_close,
2559 .capabilities = AV_CODEC_CAP_DELAY,
2560 .priv_class = &h264_videotoolbox_class,
2561 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2562 FF_CODEC_CAP_INIT_CLEANUP,
2565 static const AVOption hevc_options[] = {
2566 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = HEVC_PROF_AUTO }, HEVC_PROF_AUTO, HEVC_PROF_COUNT, VE, "profile" },
2567 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2568 { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN10 }, INT_MIN, INT_MAX, VE, "profile" },
2574 static const AVClass hevc_videotoolbox_class = {
2575 .class_name = "hevc_videotoolbox",
2576 .item_name = av_default_item_name,
2577 .option = hevc_options,
2578 .version = LIBAVUTIL_VERSION_INT,
2581 AVCodec ff_hevc_videotoolbox_encoder = {
2582 .name = "hevc_videotoolbox",
2583 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.265 Encoder"),
2584 .type = AVMEDIA_TYPE_VIDEO,
2585 .id = AV_CODEC_ID_HEVC,
2586 .priv_data_size = sizeof(VTEncContext),
2587 .pix_fmts = hevc_pix_fmts,
2589 .encode2 = vtenc_frame,
2590 .close = vtenc_close,
2591 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
2592 .priv_class = &hevc_videotoolbox_class,
2593 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2594 FF_CODEC_CAP_INIT_CLEANUP,
2595 .wrapper_name = "videotoolbox",