2 * copyright (c) 2015 Rick Kern <kernrj@gmail.com>
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
27 #include "libavutil/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavcodec/avcodec.h"
31 #include "libavutil/pixdesc.h"
39 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
40 enum { kCMVideoCodecType_HEVC = 'hvc1' };
43 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
44 enum { kCMVideoCodecType_HEVCWithAlpha = 'muxa' };
47 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
48 enum { kCVPixelFormatType_420YpCbCr10BiPlanarFullRange = 'xf20' };
49 enum { kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange = 'x420' };
52 typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
53 size_t parameterSetIndex,
54 const uint8_t **parameterSetPointerOut,
55 size_t *parameterSetSizeOut,
56 size_t *parameterSetCountOut,
57 int *NALUnitHeaderLengthOut);
59 //These symbols may not be present
61 CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020;
62 CFStringRef kCVImageBufferTransferFunction_ITU_R_2020;
63 CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020;
65 CFStringRef kVTCompressionPropertyKey_H264EntropyMode;
66 CFStringRef kVTH264EntropyMode_CAVLC;
67 CFStringRef kVTH264EntropyMode_CABAC;
69 CFStringRef kVTProfileLevel_H264_Baseline_4_0;
70 CFStringRef kVTProfileLevel_H264_Baseline_4_2;
71 CFStringRef kVTProfileLevel_H264_Baseline_5_0;
72 CFStringRef kVTProfileLevel_H264_Baseline_5_1;
73 CFStringRef kVTProfileLevel_H264_Baseline_5_2;
74 CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel;
75 CFStringRef kVTProfileLevel_H264_Main_4_2;
76 CFStringRef kVTProfileLevel_H264_Main_5_1;
77 CFStringRef kVTProfileLevel_H264_Main_5_2;
78 CFStringRef kVTProfileLevel_H264_Main_AutoLevel;
79 CFStringRef kVTProfileLevel_H264_High_3_0;
80 CFStringRef kVTProfileLevel_H264_High_3_1;
81 CFStringRef kVTProfileLevel_H264_High_3_2;
82 CFStringRef kVTProfileLevel_H264_High_4_0;
83 CFStringRef kVTProfileLevel_H264_High_4_1;
84 CFStringRef kVTProfileLevel_H264_High_4_2;
85 CFStringRef kVTProfileLevel_H264_High_5_1;
86 CFStringRef kVTProfileLevel_H264_High_5_2;
87 CFStringRef kVTProfileLevel_H264_High_AutoLevel;
88 CFStringRef kVTProfileLevel_H264_Extended_5_0;
89 CFStringRef kVTProfileLevel_H264_Extended_AutoLevel;
91 CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel;
92 CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel;
94 CFStringRef kVTCompressionPropertyKey_RealTime;
95 CFStringRef kVTCompressionPropertyKey_TargetQualityForAlpha;
97 CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder;
98 CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder;
100 getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
103 #define GET_SYM(symbol, defaultVal) \
105 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
107 compat_keys.symbol = CFSTR(defaultVal); \
109 compat_keys.symbol = *handle; \
112 static pthread_once_t once_ctrl = PTHREAD_ONCE_INIT;
114 static void loadVTEncSymbols(){
115 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
116 (getParameterSetAtIndex)dlsym(
118 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
121 GET_SYM(kCVImageBufferColorPrimaries_ITU_R_2020, "ITU_R_2020");
122 GET_SYM(kCVImageBufferTransferFunction_ITU_R_2020, "ITU_R_2020");
123 GET_SYM(kCVImageBufferYCbCrMatrix_ITU_R_2020, "ITU_R_2020");
125 GET_SYM(kVTCompressionPropertyKey_H264EntropyMode, "H264EntropyMode");
126 GET_SYM(kVTH264EntropyMode_CAVLC, "CAVLC");
127 GET_SYM(kVTH264EntropyMode_CABAC, "CABAC");
129 GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
130 GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
131 GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
132 GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
133 GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
134 GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
135 GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
136 GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
137 GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
138 GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
139 GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
140 GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
141 GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
142 GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
143 GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
144 GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
145 GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
146 GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
147 GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
148 GET_SYM(kVTProfileLevel_H264_Extended_5_0, "H264_Extended_5_0");
149 GET_SYM(kVTProfileLevel_H264_Extended_AutoLevel, "H264_Extended_AutoLevel");
151 GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
152 GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
154 GET_SYM(kVTCompressionPropertyKey_RealTime, "RealTime");
155 GET_SYM(kVTCompressionPropertyKey_TargetQualityForAlpha,
156 "TargetQualityForAlpha");
158 GET_SYM(kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
159 "EnableHardwareAcceleratedVideoEncoder");
160 GET_SYM(kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
161 "RequireHardwareAcceleratedVideoEncoder");
164 typedef enum VT_H264Profile {
173 typedef enum VTH264Entropy{
179 typedef enum VT_HEVCProfile {
186 static const uint8_t start_code[] = { 0, 0, 0, 1 };
188 typedef struct ExtraSEI {
193 typedef struct BufNode {
194 CMSampleBufferRef cm_buffer;
196 struct BufNode* next;
200 typedef struct VTEncContext {
202 enum AVCodecID codec_id;
203 VTCompressionSessionRef session;
204 CFStringRef ycbcr_matrix;
205 CFStringRef color_primaries;
206 CFStringRef transfer_function;
207 getParameterSetAtIndex get_param_set_func;
209 pthread_mutex_t lock;
210 pthread_cond_t cv_sample_sent;
217 int64_t frame_ct_out;
227 int64_t frames_before;
228 int64_t frames_after;
232 double alpha_quality;
236 bool warned_color_range;
238 /* can't be bool type since AVOption will access it as int */
242 static int vtenc_populate_extradata(AVCodecContext *avctx,
243 CMVideoCodecType codec_type,
244 CFStringRef profile_level,
245 CFNumberRef gamma_level,
246 CFDictionaryRef enc_info,
247 CFDictionaryRef pixel_buffer_info);
250 * NULL-safe release of *refPtr, and sets value to NULL.
252 static void vt_release_num(CFNumberRef* refPtr){
261 static void set_async_error(VTEncContext *vtctx, int err)
265 pthread_mutex_lock(&vtctx->lock);
267 vtctx->async_error = err;
269 info = vtctx->q_head;
270 vtctx->q_head = vtctx->q_tail = NULL;
273 BufNode *next = info->next;
274 CFRelease(info->cm_buffer);
279 pthread_mutex_unlock(&vtctx->lock);
282 static void clear_frame_queue(VTEncContext *vtctx)
284 set_async_error(vtctx, 0);
287 static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
291 pthread_mutex_lock(&vtctx->lock);
293 if (vtctx->async_error) {
294 pthread_mutex_unlock(&vtctx->lock);
295 return vtctx->async_error;
298 if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
301 pthread_mutex_unlock(&vtctx->lock);
305 while (!vtctx->q_head && !vtctx->async_error && wait && !vtctx->flushing) {
306 pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
309 if (!vtctx->q_head) {
310 pthread_mutex_unlock(&vtctx->lock);
315 info = vtctx->q_head;
316 vtctx->q_head = vtctx->q_head->next;
317 if (!vtctx->q_head) {
318 vtctx->q_tail = NULL;
321 vtctx->frame_ct_out++;
322 pthread_mutex_unlock(&vtctx->lock);
324 *buf = info->cm_buffer;
327 } else if (info->sei) {
328 if (info->sei->data) av_free(info->sei->data);
337 static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
339 BufNode *info = av_malloc(sizeof(BufNode));
341 set_async_error(vtctx, AVERROR(ENOMEM));
346 info->cm_buffer = buffer;
350 pthread_mutex_lock(&vtctx->lock);
352 if (!vtctx->q_head) {
353 vtctx->q_head = info;
355 vtctx->q_tail->next = info;
358 vtctx->q_tail = info;
360 pthread_cond_signal(&vtctx->cv_sample_sent);
361 pthread_mutex_unlock(&vtctx->lock);
364 static int count_nalus(size_t length_code_size,
365 CMSampleBufferRef sample_buffer,
372 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
373 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
375 if (length_code_size > 4)
376 return AVERROR_INVALIDDATA;
378 while (offset < src_size) {
383 status = CMBlockBufferCopyDataBytes(block,
388 for (i = 0; i < length_code_size; i++) {
390 box_len |= size_buf[i];
393 curr_src_len = box_len + length_code_size;
394 offset += curr_src_len;
403 static CMVideoCodecType get_cm_codec_type(enum AVCodecID id,
404 enum AVPixelFormat fmt,
405 double alpha_quality)
408 case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
409 case AV_CODEC_ID_HEVC:
410 if (fmt == AV_PIX_FMT_BGRA && alpha_quality > 0.0) {
411 return kCMVideoCodecType_HEVCWithAlpha;
413 return kCMVideoCodecType_HEVC;
419 * Get the parameter sets from a CMSampleBufferRef.
420 * @param dst If *dst isn't NULL, the parameters are copied into existing
421 * memory. *dst_size must be set accordingly when *dst != NULL.
422 * If *dst is NULL, it will be allocated.
423 * In all cases, *dst_size is set to the number of bytes used starting
426 static int get_params_size(
427 AVCodecContext *avctx,
428 CMVideoFormatDescriptionRef vid_fmt,
431 VTEncContext *vtctx = avctx->priv_data;
432 size_t total_size = 0;
434 int is_count_bad = 0;
437 status = vtctx->get_param_set_func(vid_fmt,
449 for (i = 0; i < ps_count || is_count_bad; i++) {
452 status = vtctx->get_param_set_func(vid_fmt,
460 * When ps_count is invalid, status != 0 ends the loop normally
461 * unless we didn't get any parameter sets.
463 if (i > 0 && is_count_bad) status = 0;
468 total_size += ps_size + sizeof(start_code);
472 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
473 return AVERROR_EXTERNAL;
480 static int copy_param_sets(
481 AVCodecContext *avctx,
482 CMVideoFormatDescriptionRef vid_fmt,
486 VTEncContext *vtctx = avctx->priv_data;
488 int is_count_bad = 0;
493 status = vtctx->get_param_set_func(vid_fmt,
506 for (i = 0; i < ps_count || is_count_bad; i++) {
511 status = vtctx->get_param_set_func(vid_fmt,
518 if (i > 0 && is_count_bad) status = 0;
523 next_offset = offset + sizeof(start_code) + ps_size;
524 if (dst_size < next_offset) {
525 av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
526 return AVERROR_BUFFER_TOO_SMALL;
529 memcpy(dst + offset, start_code, sizeof(start_code));
530 offset += sizeof(start_code);
532 memcpy(dst + offset, ps, ps_size);
533 offset = next_offset;
537 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
538 return AVERROR_EXTERNAL;
544 static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
546 CMVideoFormatDescriptionRef vid_fmt;
550 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
552 av_log(avctx, AV_LOG_ERROR, "No video format.\n");
553 return AVERROR_EXTERNAL;
556 status = get_params_size(avctx, vid_fmt, &total_size);
558 av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
562 avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
563 if (!avctx->extradata) {
564 return AVERROR(ENOMEM);
566 avctx->extradata_size = total_size;
568 status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
571 av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
578 static void vtenc_output_callback(
580 void *sourceFrameCtx,
582 VTEncodeInfoFlags flags,
583 CMSampleBufferRef sample_buffer)
585 AVCodecContext *avctx = ctx;
586 VTEncContext *vtctx = avctx->priv_data;
587 ExtraSEI *sei = sourceFrameCtx;
589 if (vtctx->async_error) {
594 av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
595 set_async_error(vtctx, AVERROR_EXTERNAL);
599 if (!sample_buffer) {
603 if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
604 int set_status = set_extradata(avctx, sample_buffer);
606 set_async_error(vtctx, set_status);
611 vtenc_q_push(vtctx, sample_buffer, sei);
614 static int get_length_code_size(
615 AVCodecContext *avctx,
616 CMSampleBufferRef sample_buffer,
619 VTEncContext *vtctx = avctx->priv_data;
620 CMVideoFormatDescriptionRef vid_fmt;
624 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
626 av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
627 return AVERROR_EXTERNAL;
630 status = vtctx->get_param_set_func(vid_fmt,
637 av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
638 return AVERROR_EXTERNAL;
646 * Returns true on success.
648 * If profile_level_val is NULL and this method returns true, don't specify the
649 * profile/level to the encoder.
651 static bool get_vt_h264_profile_level(AVCodecContext *avctx,
652 CFStringRef *profile_level_val)
654 VTEncContext *vtctx = avctx->priv_data;
655 int64_t profile = vtctx->profile;
657 if (profile == H264_PROF_AUTO && vtctx->level) {
658 //Need to pick a profile if level is not auto-selected.
659 profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;
662 *profile_level_val = NULL;
668 case H264_PROF_BASELINE:
669 switch (vtctx->level) {
670 case 0: *profile_level_val =
671 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
672 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
673 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
674 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
675 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
676 case 40: *profile_level_val =
677 compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
678 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
679 case 42: *profile_level_val =
680 compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
681 case 50: *profile_level_val =
682 compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
683 case 51: *profile_level_val =
684 compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
685 case 52: *profile_level_val =
686 compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
691 switch (vtctx->level) {
692 case 0: *profile_level_val =
693 compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
694 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
695 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
696 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
697 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
698 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
699 case 42: *profile_level_val =
700 compat_keys.kVTProfileLevel_H264_Main_4_2; break;
701 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
702 case 51: *profile_level_val =
703 compat_keys.kVTProfileLevel_H264_Main_5_1; break;
704 case 52: *profile_level_val =
705 compat_keys.kVTProfileLevel_H264_Main_5_2; break;
710 switch (vtctx->level) {
711 case 0: *profile_level_val =
712 compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
713 case 30: *profile_level_val =
714 compat_keys.kVTProfileLevel_H264_High_3_0; break;
715 case 31: *profile_level_val =
716 compat_keys.kVTProfileLevel_H264_High_3_1; break;
717 case 32: *profile_level_val =
718 compat_keys.kVTProfileLevel_H264_High_3_2; break;
719 case 40: *profile_level_val =
720 compat_keys.kVTProfileLevel_H264_High_4_0; break;
721 case 41: *profile_level_val =
722 compat_keys.kVTProfileLevel_H264_High_4_1; break;
723 case 42: *profile_level_val =
724 compat_keys.kVTProfileLevel_H264_High_4_2; break;
725 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
726 case 51: *profile_level_val =
727 compat_keys.kVTProfileLevel_H264_High_5_1; break;
728 case 52: *profile_level_val =
729 compat_keys.kVTProfileLevel_H264_High_5_2; break;
732 case H264_PROF_EXTENDED:
733 switch (vtctx->level) {
734 case 0: *profile_level_val =
735 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel; break;
736 case 50: *profile_level_val =
737 compat_keys.kVTProfileLevel_H264_Extended_5_0; break;
742 if (!*profile_level_val) {
743 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
751 * Returns true on success.
753 * If profile_level_val is NULL and this method returns true, don't specify the
754 * profile/level to the encoder.
756 static bool get_vt_hevc_profile_level(AVCodecContext *avctx,
757 CFStringRef *profile_level_val)
759 VTEncContext *vtctx = avctx->priv_data;
760 int64_t profile = vtctx->profile;
762 *profile_level_val = NULL;
769 compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
771 case HEVC_PROF_MAIN10:
773 compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
777 if (!*profile_level_val) {
778 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
785 static int get_cv_pixel_format(AVCodecContext* avctx,
786 enum AVPixelFormat fmt,
787 enum AVColorRange range,
788 int* av_pixel_format,
791 if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
792 range != AVCOL_RANGE_JPEG;
794 //MPEG range is used when no range is set
795 if (fmt == AV_PIX_FMT_NV12) {
796 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
797 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
798 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
799 } else if (fmt == AV_PIX_FMT_YUV420P) {
800 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
801 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
802 kCVPixelFormatType_420YpCbCr8Planar;
803 } else if (fmt == AV_PIX_FMT_BGRA) {
804 *av_pixel_format = kCVPixelFormatType_32BGRA;
805 } else if (fmt == AV_PIX_FMT_P010LE) {
806 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
807 kCVPixelFormatType_420YpCbCr10BiPlanarFullRange :
808 kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange;
810 return AVERROR(EINVAL);
816 static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
817 VTEncContext *vtctx = avctx->priv_data;
819 if (vtctx->color_primaries) {
820 CFDictionarySetValue(dict,
821 kCVImageBufferColorPrimariesKey,
822 vtctx->color_primaries);
825 if (vtctx->transfer_function) {
826 CFDictionarySetValue(dict,
827 kCVImageBufferTransferFunctionKey,
828 vtctx->transfer_function);
831 if (vtctx->ycbcr_matrix) {
832 CFDictionarySetValue(dict,
833 kCVImageBufferYCbCrMatrixKey,
834 vtctx->ycbcr_matrix);
838 static int create_cv_pixel_buffer_info(AVCodecContext* avctx,
839 CFMutableDictionaryRef* dict)
841 CFNumberRef cv_color_format_num = NULL;
842 CFNumberRef width_num = NULL;
843 CFNumberRef height_num = NULL;
844 CFMutableDictionaryRef pixel_buffer_info = NULL;
846 int status = get_cv_pixel_format(avctx,
851 if (status) return status;
853 pixel_buffer_info = CFDictionaryCreateMutable(
856 &kCFCopyStringDictionaryKeyCallBacks,
857 &kCFTypeDictionaryValueCallBacks);
859 if (!pixel_buffer_info) goto pbinfo_nomem;
861 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
864 if (!cv_color_format_num) goto pbinfo_nomem;
866 CFDictionarySetValue(pixel_buffer_info,
867 kCVPixelBufferPixelFormatTypeKey,
868 cv_color_format_num);
869 vt_release_num(&cv_color_format_num);
871 width_num = CFNumberCreate(kCFAllocatorDefault,
874 if (!width_num) return AVERROR(ENOMEM);
876 CFDictionarySetValue(pixel_buffer_info,
877 kCVPixelBufferWidthKey,
879 vt_release_num(&width_num);
881 height_num = CFNumberCreate(kCFAllocatorDefault,
884 if (!height_num) goto pbinfo_nomem;
886 CFDictionarySetValue(pixel_buffer_info,
887 kCVPixelBufferHeightKey,
889 vt_release_num(&height_num);
891 add_color_attr(avctx, pixel_buffer_info);
893 *dict = pixel_buffer_info;
897 vt_release_num(&cv_color_format_num);
898 vt_release_num(&width_num);
899 vt_release_num(&height_num);
900 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
902 return AVERROR(ENOMEM);
905 static int get_cv_color_primaries(AVCodecContext *avctx,
906 CFStringRef *primaries)
908 enum AVColorPrimaries pri = avctx->color_primaries;
910 case AVCOL_PRI_UNSPECIFIED:
914 case AVCOL_PRI_BT470BG:
915 *primaries = kCVImageBufferColorPrimaries_EBU_3213;
918 case AVCOL_PRI_SMPTE170M:
919 *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
922 case AVCOL_PRI_BT709:
923 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
926 case AVCOL_PRI_BT2020:
927 *primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
931 av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
939 static int get_cv_transfer_function(AVCodecContext *avctx,
940 CFStringRef *transfer_fnc,
941 CFNumberRef *gamma_level)
943 enum AVColorTransferCharacteristic trc = avctx->color_trc;
948 case AVCOL_TRC_UNSPECIFIED:
949 *transfer_fnc = NULL;
952 case AVCOL_TRC_BT709:
953 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
956 case AVCOL_TRC_SMPTE240M:
957 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
960 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ
961 case AVCOL_TRC_SMPTE2084:
962 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
965 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR
966 case AVCOL_TRC_LINEAR:
967 *transfer_fnc = kCVImageBufferTransferFunction_Linear;
970 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG
971 case AVCOL_TRC_ARIB_STD_B67:
972 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
976 case AVCOL_TRC_GAMMA22:
978 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
979 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
982 case AVCOL_TRC_GAMMA28:
984 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
985 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
988 case AVCOL_TRC_BT2020_10:
989 case AVCOL_TRC_BT2020_12:
990 *transfer_fnc = compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
994 *transfer_fnc = NULL;
995 av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));
1002 static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix) {
1003 switch(avctx->colorspace) {
1004 case AVCOL_SPC_BT709:
1005 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
1008 case AVCOL_SPC_UNSPECIFIED:
1012 case AVCOL_SPC_BT470BG:
1013 case AVCOL_SPC_SMPTE170M:
1014 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1017 case AVCOL_SPC_SMPTE240M:
1018 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1021 case AVCOL_SPC_BT2020_NCL:
1022 *matrix = compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
1026 av_log(avctx, AV_LOG_ERROR, "Color space %s is not supported.\n", av_color_space_name(avctx->colorspace));
1033 // constant quality only on Macs with Apple Silicon
1034 static bool vtenc_qscale_enabled(void)
1036 return TARGET_OS_OSX && TARGET_CPU_ARM64;
1039 static int vtenc_create_encoder(AVCodecContext *avctx,
1040 CMVideoCodecType codec_type,
1041 CFStringRef profile_level,
1042 CFNumberRef gamma_level,
1043 CFDictionaryRef enc_info,
1044 CFDictionaryRef pixel_buffer_info,
1045 VTCompressionSessionRef *session)
1047 VTEncContext *vtctx = avctx->priv_data;
1048 SInt32 bit_rate = avctx->bit_rate;
1049 SInt32 max_rate = avctx->rc_max_rate;
1050 Float32 quality = avctx->global_quality / FF_QP2LAMBDA;
1051 CFNumberRef bit_rate_num;
1052 CFNumberRef quality_num;
1053 CFNumberRef bytes_per_second;
1054 CFNumberRef one_second;
1055 CFArrayRef data_rate_limits;
1056 int64_t bytes_per_second_value = 0;
1057 int64_t one_second_value = 0;
1060 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1066 kCFAllocatorDefault,
1067 vtenc_output_callback,
1071 if (status || !vtctx->session) {
1072 av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
1074 #if !TARGET_OS_IPHONE
1075 if (!vtctx->allow_sw) {
1076 av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1080 return AVERROR_EXTERNAL;
1083 if (avctx->flags & AV_CODEC_FLAG_QSCALE && !vtenc_qscale_enabled()) {
1084 av_log(avctx, AV_LOG_ERROR, "Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1085 return AVERROR_EXTERNAL;
1088 if (avctx->flags & AV_CODEC_FLAG_QSCALE) {
1089 quality = quality >= 100 ? 1.0 : quality / 100;
1090 quality_num = CFNumberCreate(kCFAllocatorDefault,
1091 kCFNumberFloat32Type,
1093 if (!quality_num) return AVERROR(ENOMEM);
1095 status = VTSessionSetProperty(vtctx->session,
1096 kVTCompressionPropertyKey_Quality,
1098 CFRelease(quality_num);
1100 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1101 kCFNumberSInt32Type,
1103 if (!bit_rate_num) return AVERROR(ENOMEM);
1105 status = VTSessionSetProperty(vtctx->session,
1106 kVTCompressionPropertyKey_AverageBitRate,
1108 CFRelease(bit_rate_num);
1112 av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
1113 return AVERROR_EXTERNAL;
1116 if (vtctx->codec_id == AV_CODEC_ID_H264 && max_rate > 0) {
1117 // kVTCompressionPropertyKey_DataRateLimits is not available for HEVC
1118 bytes_per_second_value = max_rate >> 3;
1119 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1120 kCFNumberSInt64Type,
1121 &bytes_per_second_value);
1122 if (!bytes_per_second) {
1123 return AVERROR(ENOMEM);
1125 one_second_value = 1;
1126 one_second = CFNumberCreate(kCFAllocatorDefault,
1127 kCFNumberSInt64Type,
1130 CFRelease(bytes_per_second);
1131 return AVERROR(ENOMEM);
1133 nums[0] = (void *)bytes_per_second;
1134 nums[1] = (void *)one_second;
1135 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1136 (const void **)nums,
1138 &kCFTypeArrayCallBacks);
1140 if (!data_rate_limits) {
1141 CFRelease(bytes_per_second);
1142 CFRelease(one_second);
1143 return AVERROR(ENOMEM);
1145 status = VTSessionSetProperty(vtctx->session,
1146 kVTCompressionPropertyKey_DataRateLimits,
1149 CFRelease(bytes_per_second);
1150 CFRelease(one_second);
1151 CFRelease(data_rate_limits);
1154 av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
1155 return AVERROR_EXTERNAL;
1159 if (vtctx->codec_id == AV_CODEC_ID_HEVC) {
1160 if (avctx->pix_fmt == AV_PIX_FMT_BGRA && vtctx->alpha_quality > 0.0) {
1161 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1162 kCFNumberDoubleType,
1163 &vtctx->alpha_quality);
1164 if (!alpha_quality_num) return AVERROR(ENOMEM);
1166 status = VTSessionSetProperty(vtctx->session,
1167 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1169 CFRelease(alpha_quality_num);
1173 if (profile_level) {
1174 status = VTSessionSetProperty(vtctx->session,
1175 kVTCompressionPropertyKey_ProfileLevel,
1178 av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1182 if (avctx->gop_size > 0) {
1183 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1187 return AVERROR(ENOMEM);
1190 status = VTSessionSetProperty(vtctx->session,
1191 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1193 CFRelease(interval);
1196 av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
1197 return AVERROR_EXTERNAL;
1201 if (vtctx->frames_before) {
1202 status = VTSessionSetProperty(vtctx->session,
1203 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1206 if (status == kVTPropertyNotSupportedErr) {
1207 av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
1208 } else if (status) {
1209 av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
1213 if (vtctx->frames_after) {
1214 status = VTSessionSetProperty(vtctx->session,
1215 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1218 if (status == kVTPropertyNotSupportedErr) {
1219 av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
1220 } else if (status) {
1221 av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
1225 if (avctx->sample_aspect_ratio.num != 0) {
1228 CFMutableDictionaryRef par;
1229 AVRational *avpar = &avctx->sample_aspect_ratio;
1231 av_reduce(&avpar->num, &avpar->den,
1232 avpar->num, avpar->den,
1235 num = CFNumberCreate(kCFAllocatorDefault,
1239 den = CFNumberCreate(kCFAllocatorDefault,
1245 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1247 &kCFCopyStringDictionaryKeyCallBacks,
1248 &kCFTypeDictionaryValueCallBacks);
1250 if (!par || !num || !den) {
1251 if (par) CFRelease(par);
1252 if (num) CFRelease(num);
1253 if (den) CFRelease(den);
1255 return AVERROR(ENOMEM);
1258 CFDictionarySetValue(
1260 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1263 CFDictionarySetValue(
1265 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1268 status = VTSessionSetProperty(vtctx->session,
1269 kVTCompressionPropertyKey_PixelAspectRatio,
1279 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1280 avctx->sample_aspect_ratio.num,
1281 avctx->sample_aspect_ratio.den,
1284 return AVERROR_EXTERNAL;
1289 if (vtctx->transfer_function) {
1290 status = VTSessionSetProperty(vtctx->session,
1291 kVTCompressionPropertyKey_TransferFunction,
1292 vtctx->transfer_function);
1295 av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1300 if (vtctx->ycbcr_matrix) {
1301 status = VTSessionSetProperty(vtctx->session,
1302 kVTCompressionPropertyKey_YCbCrMatrix,
1303 vtctx->ycbcr_matrix);
1306 av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1311 if (vtctx->color_primaries) {
1312 status = VTSessionSetProperty(vtctx->session,
1313 kVTCompressionPropertyKey_ColorPrimaries,
1314 vtctx->color_primaries);
1317 av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1322 status = VTSessionSetProperty(vtctx->session,
1323 kCVImageBufferGammaLevelKey,
1327 av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1331 if (!vtctx->has_b_frames) {
1332 status = VTSessionSetProperty(vtctx->session,
1333 kVTCompressionPropertyKey_AllowFrameReordering,
1337 av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1338 return AVERROR_EXTERNAL;
1342 if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1343 CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1344 compat_keys.kVTH264EntropyMode_CABAC:
1345 compat_keys.kVTH264EntropyMode_CAVLC;
1347 status = VTSessionSetProperty(vtctx->session,
1348 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1352 av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1356 if (vtctx->realtime) {
1357 status = VTSessionSetProperty(vtctx->session,
1358 compat_keys.kVTCompressionPropertyKey_RealTime,
1362 av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1366 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1368 av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
1369 return AVERROR_EXTERNAL;
1375 static int vtenc_configure_encoder(AVCodecContext *avctx)
1377 CFMutableDictionaryRef enc_info;
1378 CFMutableDictionaryRef pixel_buffer_info;
1379 CMVideoCodecType codec_type;
1380 VTEncContext *vtctx = avctx->priv_data;
1381 CFStringRef profile_level;
1382 CFNumberRef gamma_level = NULL;
1385 codec_type = get_cm_codec_type(avctx->codec_id, avctx->pix_fmt, vtctx->alpha_quality);
1387 av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
1388 return AVERROR(EINVAL);
1391 vtctx->codec_id = avctx->codec_id;
1392 avctx->max_b_frames = 16;
1394 if (vtctx->codec_id == AV_CODEC_ID_H264) {
1395 vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
1397 vtctx->has_b_frames = avctx->max_b_frames > 0;
1398 if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){
1399 av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1400 vtctx->has_b_frames = 0;
1403 if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {
1404 av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1405 vtctx->entropy = VT_ENTROPY_NOT_SET;
1408 if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1410 vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
1411 if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
1412 if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1413 // HEVC has b-byramid
1414 vtctx->has_b_frames = avctx->max_b_frames > 0 ? 2 : 0;
1417 enc_info = CFDictionaryCreateMutable(
1418 kCFAllocatorDefault,
1420 &kCFCopyStringDictionaryKeyCallBacks,
1421 &kCFTypeDictionaryValueCallBacks
1424 if (!enc_info) return AVERROR(ENOMEM);
1426 #if !TARGET_OS_IPHONE
1427 if(vtctx->require_sw) {
1428 CFDictionarySetValue(enc_info,
1429 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1431 } else if (!vtctx->allow_sw) {
1432 CFDictionarySetValue(enc_info,
1433 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1436 CFDictionarySetValue(enc_info,
1437 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1442 if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1443 status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1447 pixel_buffer_info = NULL;
1450 vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1452 get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);
1453 get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);
1454 get_cv_color_primaries(avctx, &vtctx->color_primaries);
1457 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1458 status = vtenc_populate_extradata(avctx,
1468 status = vtenc_create_encoder(avctx,
1478 CFRelease(gamma_level);
1480 if (pixel_buffer_info)
1481 CFRelease(pixel_buffer_info);
1483 CFRelease(enc_info);
1488 static av_cold int vtenc_init(AVCodecContext *avctx)
1490 VTEncContext *vtctx = avctx->priv_data;
1491 CFBooleanRef has_b_frames_cfbool;
1494 pthread_once(&once_ctrl, loadVTEncSymbols);
1496 pthread_mutex_init(&vtctx->lock, NULL);
1497 pthread_cond_init(&vtctx->cv_sample_sent, NULL);
1499 vtctx->session = NULL;
1500 status = vtenc_configure_encoder(avctx);
1501 if (status) return status;
1503 status = VTSessionCopyProperty(vtctx->session,
1504 kVTCompressionPropertyKey_AllowFrameReordering,
1505 kCFAllocatorDefault,
1506 &has_b_frames_cfbool);
1508 if (!status && has_b_frames_cfbool) {
1509 //Some devices don't output B-frames for main profile, even if requested.
1510 // HEVC has b-pyramid
1511 vtctx->has_b_frames = (CFBooleanGetValue(has_b_frames_cfbool) && avctx->codec_id == AV_CODEC_ID_HEVC) ? 2 : 1;
1512 CFRelease(has_b_frames_cfbool);
1514 avctx->has_b_frames = vtctx->has_b_frames;
1519 static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1521 CFArrayRef attachments;
1522 CFDictionaryRef attachment;
1523 CFBooleanRef not_sync;
1526 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1527 len = !attachments ? 0 : CFArrayGetCount(attachments);
1530 *is_key_frame = true;
1534 attachment = CFArrayGetValueAtIndex(attachments, 0);
1536 if (CFDictionaryGetValueIfPresent(attachment,
1537 kCMSampleAttachmentKey_NotSync,
1538 (const void **)¬_sync))
1540 *is_key_frame = !CFBooleanGetValue(not_sync);
1542 *is_key_frame = true;
1546 static int is_post_sei_nal_type(int nal_type){
1547 return nal_type != H264_NAL_SEI &&
1548 nal_type != H264_NAL_SPS &&
1549 nal_type != H264_NAL_PPS &&
1550 nal_type != H264_NAL_AUD;
1554 * Finds the sei message start/size of type find_sei_type.
1555 * If more than one of that type exists, the last one is returned.
1557 static int find_sei_end(AVCodecContext *avctx,
1563 size_t sei_payload_size = 0;
1564 int sei_payload_type = 0;
1566 uint8_t *nal_start = nal_data;
1571 nal_type = *nal_data & 0x1F;
1572 if (nal_type != H264_NAL_SEI)
1578 if (nal_data[nal_size - 1] == 0x80)
1581 while (nal_size > 0 && *nal_data > 0) {
1583 sei_payload_type += *nal_data;
1586 } while (nal_size > 0 && *nal_data == 0xFF);
1589 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1590 return AVERROR_INVALIDDATA;
1594 sei_payload_size += *nal_data;
1597 } while (nal_size > 0 && *nal_data == 0xFF);
1599 if (nal_size < sei_payload_size) {
1600 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1601 return AVERROR_INVALIDDATA;
1604 nal_data += sei_payload_size;
1605 nal_size -= sei_payload_size;
1608 *sei_end = nal_data;
1610 return nal_data - nal_start + 1;
1614 * Copies the data inserting emulation prevention bytes as needed.
1615 * Existing data in the destination can be taken into account by providing
1616 * dst with a dst_offset > 0.
1618 * @return The number of bytes copied on success. On failure, the negative of
1619 * the number of bytes needed to copy src is returned.
1621 static int copy_emulation_prev(const uint8_t *src,
1630 uint8_t* dst_end = dst + dst_size;
1631 const uint8_t* src_end = src + src_size;
1632 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1634 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1643 for (; src < src_end; src++, dst++) {
1645 int insert_ep3_byte = *src <= 3;
1646 if (insert_ep3_byte) {
1664 wrote_bytes = dst - dst_start;
1667 return -wrote_bytes;
1672 static int write_sei(const ExtraSEI *sei,
1677 uint8_t *sei_start = dst;
1678 size_t remaining_sei_size = sei->size;
1679 size_t remaining_dst_size = dst_size;
1684 if (!remaining_dst_size)
1685 return AVERROR_BUFFER_TOO_SMALL;
1687 while (sei_type && remaining_dst_size != 0) {
1688 int sei_byte = sei_type > 255 ? 255 : sei_type;
1691 sei_type -= sei_byte;
1693 remaining_dst_size--;
1697 return AVERROR_BUFFER_TOO_SMALL;
1699 while (remaining_sei_size && remaining_dst_size != 0) {
1700 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1703 remaining_sei_size -= size_byte;
1705 remaining_dst_size--;
1708 if (remaining_dst_size < sei->size)
1709 return AVERROR_BUFFER_TOO_SMALL;
1711 header_bytes = dst - sei_start;
1713 offset = header_bytes;
1714 bytes_written = copy_emulation_prev(sei->data,
1719 if (bytes_written < 0)
1720 return AVERROR_BUFFER_TOO_SMALL;
1722 bytes_written += header_bytes;
1723 return bytes_written;
1727 * Copies NAL units and replaces length codes with
1728 * H.264 Annex B start codes. On failure, the contents of
1729 * dst_data may have been modified.
1731 * @param length_code_size Byte length of each length code
1732 * @param sample_buffer NAL units prefixed with length codes.
1733 * @param sei Optional A53 closed captions SEI data.
1734 * @param dst_data Must be zeroed before calling this function.
1735 * Contains the copied NAL units prefixed with
1736 * start codes when the function returns
1738 * @param dst_size Length of dst_data
1739 * @return 0 on success
1740 * AVERROR_INVALIDDATA if length_code_size is invalid
1741 * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
1742 * or if a length_code in src_data specifies data beyond
1743 * the end of its buffer.
1745 static int copy_replace_length_codes(
1746 AVCodecContext *avctx,
1747 size_t length_code_size,
1748 CMSampleBufferRef sample_buffer,
1753 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1754 size_t remaining_src_size = src_size;
1755 size_t remaining_dst_size = dst_size;
1756 size_t src_offset = 0;
1759 uint8_t size_buf[4];
1761 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
1763 if (length_code_size > 4) {
1764 return AVERROR_INVALIDDATA;
1767 while (remaining_src_size > 0) {
1768 size_t curr_src_len;
1769 size_t curr_dst_len;
1775 status = CMBlockBufferCopyDataBytes(block,
1780 av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
1781 return AVERROR_EXTERNAL;
1784 status = CMBlockBufferCopyDataBytes(block,
1785 src_offset + length_code_size,
1790 av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
1791 return AVERROR_EXTERNAL;
1796 for (i = 0; i < length_code_size; i++) {
1798 box_len |= size_buf[i];
1801 if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
1802 //No SEI NAL unit - insert.
1805 memcpy(dst_data, start_code, sizeof(start_code));
1806 dst_data += sizeof(start_code);
1807 remaining_dst_size -= sizeof(start_code);
1809 *dst_data = H264_NAL_SEI;
1811 remaining_dst_size--;
1813 wrote_bytes = write_sei(sei,
1814 SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35,
1816 remaining_dst_size);
1818 if (wrote_bytes < 0)
1821 remaining_dst_size -= wrote_bytes;
1822 dst_data += wrote_bytes;
1824 if (remaining_dst_size <= 0)
1825 return AVERROR_BUFFER_TOO_SMALL;
1830 remaining_dst_size--;
1835 curr_src_len = box_len + length_code_size;
1836 curr_dst_len = box_len + sizeof(start_code);
1838 if (remaining_src_size < curr_src_len) {
1839 return AVERROR_BUFFER_TOO_SMALL;
1842 if (remaining_dst_size < curr_dst_len) {
1843 return AVERROR_BUFFER_TOO_SMALL;
1846 dst_box = dst_data + sizeof(start_code);
1848 memcpy(dst_data, start_code, sizeof(start_code));
1849 status = CMBlockBufferCopyDataBytes(block,
1850 src_offset + length_code_size,
1855 av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
1856 return AVERROR_EXTERNAL;
1859 if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
1860 //Found SEI NAL unit - append.
1865 old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
1866 if (old_sei_length < 0)
1869 wrote_bytes = write_sei(sei,
1870 SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35,
1872 remaining_dst_size - old_sei_length);
1873 if (wrote_bytes < 0)
1876 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1877 return AVERROR_BUFFER_TOO_SMALL;
1879 new_sei[wrote_bytes++] = 0x80;
1880 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1882 dst_data += extra_bytes;
1883 remaining_dst_size -= extra_bytes;
1888 src_offset += curr_src_len;
1889 dst_data += curr_dst_len;
1891 remaining_src_size -= curr_src_len;
1892 remaining_dst_size -= curr_dst_len;
1899 * Returns a sufficient number of bytes to contain the sei data.
1900 * It may be greater than the minimum required.
1902 static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
1907 copied_size = -copy_emulation_prev(sei->data,
1913 if ((sei->size % 255) == 0) //may result in an extra byte
1916 return copied_size + sei->size / 255 + 1 + type / 255 + 1;
1919 static int vtenc_cm_to_avpacket(
1920 AVCodecContext *avctx,
1921 CMSampleBufferRef sample_buffer,
1925 VTEncContext *vtctx = avctx->priv_data;
1930 size_t length_code_size;
1931 size_t header_size = 0;
1933 size_t out_buf_size;
1934 size_t sei_nalu_size = 0;
1936 int64_t time_base_num;
1940 CMVideoFormatDescriptionRef vid_fmt;
1943 vtenc_get_frame_info(sample_buffer, &is_key_frame);
1944 status = get_length_code_size(avctx, sample_buffer, &length_code_size);
1945 if (status) return status;
1947 add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
1950 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1952 av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
1953 return AVERROR_EXTERNAL;
1956 int status = get_params_size(avctx, vid_fmt, &header_size);
1957 if (status) return status;
1960 status = count_nalus(length_code_size, sample_buffer, &nalu_count);
1965 size_t msg_size = get_sei_msg_bytes(sei,
1966 SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35);
1968 sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
1971 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1972 out_buf_size = header_size +
1975 nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
1977 status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);
1982 status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
1983 if(status) return status;
1986 status = copy_replace_length_codes(
1991 pkt->data + header_size,
1992 pkt->size - header_size
1996 av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
2001 pkt->flags |= AV_PKT_FLAG_KEY;
2004 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2005 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2007 if (CMTIME_IS_INVALID(dts)) {
2008 if (!vtctx->has_b_frames) {
2011 av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
2012 return AVERROR_EXTERNAL;
2016 dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
2017 time_base_num = avctx->time_base.num;
2018 pkt->pts = pts.value / time_base_num;
2019 pkt->dts = dts.value / time_base_num - dts_delta;
2020 pkt->size = out_buf_size;
2026 * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
2027 * containing all planes if so.
2029 static int get_cv_pixel_info(
2030 AVCodecContext *avctx,
2031 const AVFrame *frame,
2037 size_t *contiguous_buf_size)
2039 VTEncContext *vtctx = avctx->priv_data;
2040 int av_format = frame->format;
2041 int av_color_range = frame->color_range;
2046 status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
2050 "Could not get pixel format for color format '%s' range '%s'.\n",
2051 av_get_pix_fmt_name(av_format),
2052 av_color_range > AVCOL_RANGE_UNSPECIFIED &&
2053 av_color_range < AVCOL_RANGE_NB ?
2054 av_color_range_name(av_color_range) :
2057 return AVERROR(EINVAL);
2060 if (range_guessed) {
2061 if (!vtctx->warned_color_range) {
2062 vtctx->warned_color_range = true;
2065 "Color range not set for %s. Using MPEG range.\n",
2066 av_get_pix_fmt_name(av_format));
2070 switch (av_format) {
2071 case AV_PIX_FMT_NV12:
2074 widths [0] = avctx->width;
2075 heights[0] = avctx->height;
2076 strides[0] = frame ? frame->linesize[0] : avctx->width;
2078 widths [1] = (avctx->width + 1) / 2;
2079 heights[1] = (avctx->height + 1) / 2;
2080 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) & -2;
2083 case AV_PIX_FMT_YUV420P:
2086 widths [0] = avctx->width;
2087 heights[0] = avctx->height;
2088 strides[0] = frame ? frame->linesize[0] : avctx->width;
2090 widths [1] = (avctx->width + 1) / 2;
2091 heights[1] = (avctx->height + 1) / 2;
2092 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) / 2;
2094 widths [2] = (avctx->width + 1) / 2;
2095 heights[2] = (avctx->height + 1) / 2;
2096 strides[2] = frame ? frame->linesize[2] : (avctx->width + 1) / 2;
2099 case AV_PIX_FMT_BGRA:
2102 widths [0] = avctx->width;
2103 heights[0] = avctx->height;
2104 strides[0] = frame ? frame->linesize[0] : avctx->width * 4;
2107 case AV_PIX_FMT_P010LE:
2109 widths[0] = avctx->width;
2110 heights[0] = avctx->height;
2111 strides[0] = frame ? frame->linesize[0] : (avctx->width * 2 + 63) & -64;
2113 widths[1] = (avctx->width + 1) / 2;
2114 heights[1] = (avctx->height + 1) / 2;
2115 strides[1] = frame ? frame->linesize[1] : ((avctx->width + 1) / 2 + 63) & -64;
2122 "Could not get frame format info for color %d range %d.\n",
2126 return AVERROR(EINVAL);
2129 *contiguous_buf_size = 0;
2130 for (i = 0; i < *plane_count; i++) {
2131 if (i < *plane_count - 1 &&
2132 frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
2133 *contiguous_buf_size = 0;
2137 *contiguous_buf_size += strides[i] * heights[i];
2143 //Not used on OSX - frame is never copied.
2144 static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx,
2145 const AVFrame *frame,
2146 CVPixelBufferRef cv_img,
2147 const size_t *plane_strides,
2148 const size_t *plane_rows)
2160 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2165 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2170 if (CVPixelBufferIsPlanar(cv_img)) {
2171 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2172 for (i = 0; frame->data[i]; i++) {
2173 if (i == plane_count) {
2174 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2177 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2180 return AVERROR_EXTERNAL;
2183 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2184 src_addr = (uint8_t*)frame->data[i];
2185 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2186 src_stride = plane_strides[i];
2187 rows = plane_rows[i];
2189 if (dst_stride == src_stride) {
2190 memcpy(dst_addr, src_addr, src_stride * rows);
2192 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2194 for (j = 0; j < rows; j++) {
2195 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2200 if (frame->data[1]) {
2201 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2204 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2207 return AVERROR_EXTERNAL;
2210 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2211 src_addr = (uint8_t*)frame->data[0];
2212 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2213 src_stride = plane_strides[0];
2214 rows = plane_rows[0];
2216 if (dst_stride == src_stride) {
2217 memcpy(dst_addr, src_addr, src_stride * rows);
2219 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2221 for (j = 0; j < rows; j++) {
2222 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2227 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2229 av_log(avctx, AV_LOG_ERROR, "Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2230 return AVERROR_EXTERNAL;
2236 static int create_cv_pixel_buffer(AVCodecContext *avctx,
2237 const AVFrame *frame,
2238 CVPixelBufferRef *cv_img)
2242 size_t widths [AV_NUM_DATA_POINTERS];
2243 size_t heights[AV_NUM_DATA_POINTERS];
2244 size_t strides[AV_NUM_DATA_POINTERS];
2246 size_t contiguous_buf_size;
2247 CVPixelBufferPoolRef pix_buf_pool;
2248 VTEncContext* vtctx = avctx->priv_data;
2250 if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2251 av_assert0(frame->format == AV_PIX_FMT_VIDEOTOOLBOX);
2253 *cv_img = (CVPixelBufferRef)frame->data[3];
2254 av_assert0(*cv_img);
2260 memset(widths, 0, sizeof(widths));
2261 memset(heights, 0, sizeof(heights));
2262 memset(strides, 0, sizeof(strides));
2264 status = get_cv_pixel_info(
2272 &contiguous_buf_size
2279 "Error: Cannot convert format %d color_range %d: %d\n",
2285 return AVERROR_EXTERNAL;
2288 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2289 if (!pix_buf_pool) {
2290 /* On iOS, the VT session is invalidated when the APP switches from
2291 * foreground to background and vice versa. Fetch the actual error code
2292 * of the VT session to detect that case and restart the VT session
2296 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
2297 if (vtstatus == kVTInvalidSessionErr) {
2298 CFRelease(vtctx->session);
2299 vtctx->session = NULL;
2300 status = vtenc_configure_encoder(avctx);
2302 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2304 if (!pix_buf_pool) {
2305 av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2306 return AVERROR_EXTERNAL;
2309 av_log(avctx, AV_LOG_WARNING, "VT session restarted because of a "
2310 "kVTInvalidSessionErr error.\n");
2313 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2319 av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2320 return AVERROR_EXTERNAL;
2323 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2333 static int create_encoder_dict_h264(const AVFrame *frame,
2334 CFDictionaryRef* dict_out)
2336 CFDictionaryRef dict = NULL;
2337 if (frame->pict_type == AV_PICTURE_TYPE_I) {
2338 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2339 const void *vals[] = { kCFBooleanTrue };
2341 dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2342 if(!dict) return AVERROR(ENOMEM);
2349 static int vtenc_send_frame(AVCodecContext *avctx,
2350 VTEncContext *vtctx,
2351 const AVFrame *frame)
2354 CFDictionaryRef frame_dict;
2355 CVPixelBufferRef cv_img = NULL;
2356 AVFrameSideData *side_data = NULL;
2357 ExtraSEI *sei = NULL;
2358 int status = create_cv_pixel_buffer(avctx, frame, &cv_img);
2360 if (status) return status;
2362 status = create_encoder_dict_h264(frame, &frame_dict);
2368 side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
2369 if (vtctx->a53_cc && side_data && side_data->size) {
2370 sei = av_mallocz(sizeof(*sei));
2372 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2374 int ret = ff_alloc_a53_sei(frame, 0, &sei->data, &sei->size);
2376 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2383 time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2384 status = VTCompressionSessionEncodeFrame(
2394 if (frame_dict) CFRelease(frame_dict);
2398 av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
2399 return AVERROR_EXTERNAL;
2405 static av_cold int vtenc_frame(
2406 AVCodecContext *avctx,
2408 const AVFrame *frame,
2411 VTEncContext *vtctx = avctx->priv_data;
2414 CMSampleBufferRef buf = NULL;
2415 ExtraSEI *sei = NULL;
2418 status = vtenc_send_frame(avctx, vtctx, frame);
2421 status = AVERROR_EXTERNAL;
2425 if (vtctx->frame_ct_in == 0) {
2426 vtctx->first_pts = frame->pts;
2427 } else if(vtctx->frame_ct_in == vtctx->has_b_frames) {
2428 vtctx->dts_delta = frame->pts - vtctx->first_pts;
2431 vtctx->frame_ct_in++;
2432 } else if(!vtctx->flushing) {
2433 vtctx->flushing = true;
2435 status = VTCompressionSessionCompleteFrames(vtctx->session,
2439 av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2440 status = AVERROR_EXTERNAL;
2446 get_frame = vtctx->dts_delta >= 0 || !frame;
2452 status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2453 if (status) goto end_nopkt;
2454 if (!buf) goto end_nopkt;
2456 status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei);
2458 if (sei->data) av_free(sei->data);
2462 if (status) goto end_nopkt;
2468 av_packet_unref(pkt);
2472 static int vtenc_populate_extradata(AVCodecContext *avctx,
2473 CMVideoCodecType codec_type,
2474 CFStringRef profile_level,
2475 CFNumberRef gamma_level,
2476 CFDictionaryRef enc_info,
2477 CFDictionaryRef pixel_buffer_info)
2479 VTEncContext *vtctx = avctx->priv_data;
2481 CVPixelBufferPoolRef pool = NULL;
2482 CVPixelBufferRef pix_buf = NULL;
2484 CMSampleBufferRef buf = NULL;
2486 status = vtenc_create_encoder(avctx,
2496 pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2498 av_log(avctx, AV_LOG_ERROR, "Error getting pixel buffer pool.\n");
2502 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2506 if(status != kCVReturnSuccess){
2507 av_log(avctx, AV_LOG_ERROR, "Error creating frame from pool: %d\n", status);
2511 time = CMTimeMake(0, avctx->time_base.den);
2512 status = VTCompressionSessionEncodeFrame(vtctx->session,
2523 "Error sending frame for extradata: %d\n",
2529 //Populates extradata - output frames are flushed and param sets are available.
2530 status = VTCompressionSessionCompleteFrames(vtctx->session,
2536 status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2538 av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2548 CFRelease(vtctx->session);
2550 vtctx->session = NULL;
2551 vtctx->frame_ct_out = 0;
2553 av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2558 static av_cold int vtenc_close(AVCodecContext *avctx)
2560 VTEncContext *vtctx = avctx->priv_data;
2562 if(!vtctx->session) {
2563 pthread_cond_destroy(&vtctx->cv_sample_sent);
2564 pthread_mutex_destroy(&vtctx->lock);
2568 VTCompressionSessionCompleteFrames(vtctx->session,
2570 clear_frame_queue(vtctx);
2571 pthread_cond_destroy(&vtctx->cv_sample_sent);
2572 pthread_mutex_destroy(&vtctx->lock);
2573 CFRelease(vtctx->session);
2574 vtctx->session = NULL;
2576 if (vtctx->color_primaries) {
2577 CFRelease(vtctx->color_primaries);
2578 vtctx->color_primaries = NULL;
2581 if (vtctx->transfer_function) {
2582 CFRelease(vtctx->transfer_function);
2583 vtctx->transfer_function = NULL;
2586 if (vtctx->ycbcr_matrix) {
2587 CFRelease(vtctx->ycbcr_matrix);
2588 vtctx->ycbcr_matrix = NULL;
2594 static const enum AVPixelFormat avc_pix_fmts[] = {
2595 AV_PIX_FMT_VIDEOTOOLBOX,
2601 static const enum AVPixelFormat hevc_pix_fmts[] = {
2602 AV_PIX_FMT_VIDEOTOOLBOX,
2610 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2611 #define COMMON_OPTIONS \
2612 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2613 { .i64 = 0 }, 0, 1, VE }, \
2614 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2615 { .i64 = 0 }, 0, 1, VE }, \
2616 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2617 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2618 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2619 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2620 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2621 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2623 #define OFFSET(x) offsetof(VTEncContext, x)
2624 static const AVOption h264_options[] = {
2625 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = H264_PROF_AUTO }, H264_PROF_AUTO, H264_PROF_COUNT, VE, "profile" },
2626 { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_BASELINE }, INT_MIN, INT_MAX, VE, "profile" },
2627 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2628 { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_HIGH }, INT_MIN, INT_MAX, VE, "profile" },
2629 { "extended", "Extend Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_EXTENDED }, INT_MIN, INT_MAX, VE, "profile" },
2631 { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, "level" },
2632 { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, "level" },
2633 { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, "level" },
2634 { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, "level" },
2635 { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, "level" },
2636 { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, "level" },
2637 { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, "level" },
2638 { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, "level" },
2639 { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, "level" },
2640 { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, "level" },
2641 { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, "level" },
2643 { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, "coder" },
2644 { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2645 { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2646 { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2647 { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2649 { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2655 static const AVClass h264_videotoolbox_class = {
2656 .class_name = "h264_videotoolbox",
2657 .item_name = av_default_item_name,
2658 .option = h264_options,
2659 .version = LIBAVUTIL_VERSION_INT,
2662 const AVCodec ff_h264_videotoolbox_encoder = {
2663 .name = "h264_videotoolbox",
2664 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.264 Encoder"),
2665 .type = AVMEDIA_TYPE_VIDEO,
2666 .id = AV_CODEC_ID_H264,
2667 .priv_data_size = sizeof(VTEncContext),
2668 .pix_fmts = avc_pix_fmts,
2670 .encode2 = vtenc_frame,
2671 .close = vtenc_close,
2672 .capabilities = AV_CODEC_CAP_DELAY,
2673 .priv_class = &h264_videotoolbox_class,
2674 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2675 FF_CODEC_CAP_INIT_CLEANUP,
2678 static const AVOption hevc_options[] = {
2679 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = HEVC_PROF_AUTO }, HEVC_PROF_AUTO, HEVC_PROF_COUNT, VE, "profile" },
2680 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2681 { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = HEVC_PROF_MAIN10 }, INT_MIN, INT_MAX, VE, "profile" },
2683 { "alpha_quality", "Compression quality for the alpha channel", OFFSET(alpha_quality), AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0, VE },
2689 static const AVClass hevc_videotoolbox_class = {
2690 .class_name = "hevc_videotoolbox",
2691 .item_name = av_default_item_name,
2692 .option = hevc_options,
2693 .version = LIBAVUTIL_VERSION_INT,
2696 const AVCodec ff_hevc_videotoolbox_encoder = {
2697 .name = "hevc_videotoolbox",
2698 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.265 Encoder"),
2699 .type = AVMEDIA_TYPE_VIDEO,
2700 .id = AV_CODEC_ID_HEVC,
2701 .priv_data_size = sizeof(VTEncContext),
2702 .pix_fmts = hevc_pix_fmts,
2704 .encode2 = vtenc_frame,
2705 .close = vtenc_close,
2706 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE,
2707 .priv_class = &hevc_videotoolbox_class,
2708 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2709 FF_CODEC_CAP_INIT_CLEANUP,
2710 .wrapper_name = "videotoolbox",