21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
44 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
48 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
52 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
57 #if !HAVE_KVTQPMODULATIONLEVEL_DEFAULT
62 #ifndef TARGET_CPU_ARM64
63 # define TARGET_CPU_ARM64 0
67 size_t parameterSetIndex,
68 const uint8_t **parameterSetPointerOut,
69 size_t *parameterSetSizeOut,
70 size_t *parameterSetCountOut,
71 int *NALUnitHeaderLengthOut);
144 #define GET_SYM(symbol, defaultVal) \
146 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
148 compat_keys.symbol = CFSTR(defaultVal); \
150 compat_keys.symbol = *handle; \
156 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
159 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
200 "TargetQualityForAlpha");
202 "PrioritizeEncodingSpeedOverQuality");
207 "EnableHardwareAcceleratedVideoEncoder");
209 "RequireHardwareAcceleratedVideoEncoder");
211 "EnableLowLatencyRateControl");
214 "MaximizePowerEfficiency");
216 "ReferenceBufferCount");
222 #define H264_PROFILE_CONSTRAINED_HIGH (AV_PROFILE_H264_HIGH | AV_PROFILE_H264_CONSTRAINED)
301 CFRelease(
info->cm_buffer);
309 CFStringRef encoder_id =
NULL;
311 CFIndex length, max_size;
322 length = CFStringGetLength(encoder_id);
323 max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
326 CFRelease(encoder_id);
330 CFStringGetCString(encoder_id,
333 kCFStringEncodingUTF8);
336 CFRelease(encoder_id);
343 CFStringRef profile_level,
344 CFNumberRef gamma_level,
345 CFDictionaryRef enc_info,
346 CFDictionaryRef pixel_buffer_info);
450 *buf =
info->cm_buffer;
478 CMSampleBufferRef sample_buffer,
485 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
486 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
488 if (length_code_size > 4)
491 while (
offset < src_size) {
501 if (
status != kCMBlockBufferNoErr) {
505 for (
i = 0;
i < length_code_size;
i++) {
507 box_len |= size_buf[
i];
510 curr_src_len = box_len + length_code_size;
522 double alpha_quality)
537 return MKBETAG(
'a',
'p',
'c',
'o');
539 return MKBETAG(
'a',
'p',
'c',
's');
541 return MKBETAG(
'a',
'p',
'c',
'n');
543 return MKBETAG(
'a',
'p',
'c',
'h');
545 return MKBETAG(
'a',
'p',
'4',
'h');
547 return MKBETAG(
'a',
'p',
'4',
'x');
554 desc->log2_chroma_w == 0))
555 return MKBETAG(
'a',
'p',
'4',
'h');
557 return MKBETAG(
'a',
'p',
'c',
'n');
573 CMVideoFormatDescriptionRef vid_fmt,
577 size_t total_size = 0;
579 int is_count_bad = 0;
594 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
608 if (
i > 0 && is_count_bad)
status = 0;
627 CMVideoFormatDescriptionRef vid_fmt,
633 int is_count_bad = 0;
651 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
663 if (
i > 0 && is_count_bad)
status = 0;
669 if (dst_size < next_offset) {
692 CMVideoFormatDescriptionRef vid_fmt;
696 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
722 CFDataRef
data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
723 if (
data && CFGetTypeID(
data) == CFDataGetTypeID()) {
724 CFIndex
size = CFDataGetLength(
data);
740 void *sourceFrameCtx,
742 VTEncodeInfoFlags
flags,
743 CMSampleBufferRef sample_buffer)
762 if (!sample_buffer) {
766 CFRetain(sample_buffer);
767 info->cm_buffer = sample_buffer;
783 CMSampleBufferRef sample_buffer,
787 CMVideoFormatDescriptionRef vid_fmt;
791 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
819 CFStringRef *profile_level_val)
829 *profile_level_val =
NULL;
836 switch (vtctx->
level) {
837 case 0: *profile_level_val =
838 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
839 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
840 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
841 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
842 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
843 case 40: *profile_level_val =
844 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
845 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
846 case 42: *profile_level_val =
847 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
848 case 50: *profile_level_val =
849 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
850 case 51: *profile_level_val =
851 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
852 case 52: *profile_level_val =
853 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
858 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel;
860 if (vtctx->
level != 0) {
863 "Level is auto-selected when constrained-baseline "
864 "profile is used. The output may be encoded with a "
865 "different level.\n");
870 switch (vtctx->
level) {
871 case 0: *profile_level_val =
872 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
873 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
874 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
875 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
876 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
877 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
878 case 42: *profile_level_val =
880 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
881 case 51: *profile_level_val =
883 case 52: *profile_level_val =
889 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedHigh_AutoLevel;
891 if (vtctx->
level != 0) {
894 "Level is auto-selected when constrained-high profile "
895 "is used. The output may be encoded with a different "
901 switch (vtctx->
level) {
902 case 0: *profile_level_val =
903 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
904 case 30: *profile_level_val =
906 case 31: *profile_level_val =
908 case 32: *profile_level_val =
910 case 40: *profile_level_val =
912 case 41: *profile_level_val =
914 case 42: *profile_level_val =
916 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
917 case 51: *profile_level_val =
919 case 52: *profile_level_val =
924 switch (vtctx->
level) {
925 case 0: *profile_level_val =
926 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
927 case 50: *profile_level_val =
928 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
933 if (!*profile_level_val) {
948 CFStringRef *profile_level_val)
957 *profile_level_val =
NULL;
971 "main profile with %d bit input\n",
bit_depth);
978 "Invalid main10 profile with %d bit input\n",
bit_depth);
987 compat_keys.kVTProfileLevel_HEVC_Main42210_AutoLevel;
991 if (!*profile_level_val) {
1002 int* av_pixel_format,
1005 const char *range_name;
1011 if (*av_pixel_format)
1016 "Could not get pixel format for color format '%s' range '%s'.\n",
1018 range_name ? range_name :
"Unknown");
1027 CFDictionarySetValue(dict,
1028 kCVImageBufferColorPrimariesKey,
1033 CFDictionarySetValue(dict,
1034 kCVImageBufferTransferFunctionKey,
1039 CFDictionarySetValue(dict,
1040 kCVImageBufferYCbCrMatrixKey,
1046 CFMutableDictionaryRef* dict)
1048 CFNumberRef cv_color_format_num =
NULL;
1049 CFNumberRef width_num =
NULL;
1050 CFNumberRef height_num =
NULL;
1051 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1052 int cv_color_format;
1060 pixel_buffer_info = CFDictionaryCreateMutable(
1061 kCFAllocatorDefault,
1063 &kCFCopyStringDictionaryKeyCallBacks,
1064 &kCFTypeDictionaryValueCallBacks);
1066 if (!pixel_buffer_info)
goto pbinfo_nomem;
1068 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
1069 kCFNumberSInt32Type,
1071 if (!cv_color_format_num)
goto pbinfo_nomem;
1073 CFDictionarySetValue(pixel_buffer_info,
1074 kCVPixelBufferPixelFormatTypeKey,
1075 cv_color_format_num);
1078 width_num = CFNumberCreate(kCFAllocatorDefault,
1079 kCFNumberSInt32Type,
1081 if (!width_num)
goto pbinfo_nomem;
1083 CFDictionarySetValue(pixel_buffer_info,
1084 kCVPixelBufferWidthKey,
1088 height_num = CFNumberCreate(kCFAllocatorDefault,
1089 kCFNumberSInt32Type,
1091 if (!height_num)
goto pbinfo_nomem;
1093 CFDictionarySetValue(pixel_buffer_info,
1094 kCVPixelBufferHeightKey,
1100 *dict = pixel_buffer_info;
1107 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
1113 CFNumberRef *gamma_level)
1117 *gamma_level =
NULL;
1125 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1137 const char *print_option_name,
1143 if (
status == kVTPropertyNotSupportedErr) {
1146 "This device does not support the %s option. Value ignored.\n",
1148 }
else if (
status != 0) {
1151 "Error setting %s: Error %d\n",
1159 const char* print_option_name,
1161 CFNumberRef value_cfnum = CFNumberCreate(kCFAllocatorDefault,
1165 if (value_cfnum ==
NULL) {
1171 CFRelease(value_cfnum);
1178 CFStringRef profile_level,
1179 CFNumberRef gamma_level,
1180 CFDictionaryRef enc_info,
1181 CFDictionaryRef pixel_buffer_info,
1182 bool constant_bit_rate,
1183 VTCompressionSessionRef *session)
1189 CFNumberRef bit_rate_num;
1190 CFNumberRef quality_num;
1191 CFNumberRef bytes_per_second;
1192 CFNumberRef one_second;
1193 CFArrayRef data_rate_limits;
1194 int64_t bytes_per_second_value = 0;
1198 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1204 kCFAllocatorDefault,
1212 #if !TARGET_OS_IPHONE
1214 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1221 #if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
1222 if (__builtin_available(macOS 10.13, *)) {
1227 status = VTCopySupportedPropertyDictionaryForEncoder(avctx->
width,
1246 av_log(avctx,
AV_LOG_ERROR,
"Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1252 quality_num = CFNumberCreate(kCFAllocatorDefault,
1253 kCFNumberFloat32Type,
1255 if (!quality_num)
return AVERROR(ENOMEM);
1258 kVTCompressionPropertyKey_Quality,
1260 CFRelease(quality_num);
1262 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1263 kCFNumberSInt32Type,
1265 if (!bit_rate_num)
return AVERROR(ENOMEM);
1267 if (constant_bit_rate) {
1269 compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1271 if (
status == kVTPropertyNotSupportedErr) {
1272 av_log(avctx,
AV_LOG_ERROR,
"Error: -constant_bit_rate true is not supported by the encoder.\n");
1277 kVTCompressionPropertyKey_AverageBitRate,
1281 CFRelease(bit_rate_num);
1291 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1292 vtctx->
prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1294 av_log(avctx,
AV_LOG_WARNING,
"PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1300 bytes_per_second_value = max_rate >> 3;
1301 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1302 kCFNumberSInt64Type,
1303 &bytes_per_second_value);
1304 if (!bytes_per_second) {
1307 one_second_value = 1;
1308 one_second = CFNumberCreate(kCFAllocatorDefault,
1309 kCFNumberSInt64Type,
1312 CFRelease(bytes_per_second);
1315 nums[0] = (
void *)bytes_per_second;
1316 nums[1] = (
void *)one_second;
1317 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1318 (
const void **)nums,
1320 &kCFTypeArrayCallBacks);
1322 if (!data_rate_limits) {
1323 CFRelease(bytes_per_second);
1324 CFRelease(one_second);
1328 kVTCompressionPropertyKey_DataRateLimits,
1331 CFRelease(bytes_per_second);
1332 CFRelease(one_second);
1333 CFRelease(data_rate_limits);
1347 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1348 kCFNumberDoubleType,
1350 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1353 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1355 CFRelease(alpha_quality_num);
1360 "Error setting alpha quality: %d\n",
1366 if (profile_level) {
1368 kVTCompressionPropertyKey_ProfileLevel,
1371 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n",
status);
1376 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1384 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1386 CFRelease(interval);
1396 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1399 if (
status == kVTPropertyNotSupportedErr) {
1400 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1408 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1411 if (
status == kVTPropertyNotSupportedErr) {
1412 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1421 CFMutableDictionaryRef par;
1428 num = CFNumberCreate(kCFAllocatorDefault,
1432 den = CFNumberCreate(kCFAllocatorDefault,
1438 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1440 &kCFCopyStringDictionaryKeyCallBacks,
1441 &kCFTypeDictionaryValueCallBacks);
1443 if (!par || !num || !den) {
1444 if (par) CFRelease(par);
1445 if (num) CFRelease(num);
1446 if (den) CFRelease(den);
1451 CFDictionarySetValue(
1453 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1456 CFDictionarySetValue(
1458 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1462 kVTCompressionPropertyKey_PixelAspectRatio,
1472 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1484 kVTCompressionPropertyKey_TransferFunction,
1495 kVTCompressionPropertyKey_YCbCrMatrix,
1506 kVTCompressionPropertyKey_ColorPrimaries,
1516 kCVImageBufferGammaLevelKey,
1526 kVTCompressionPropertyKey_AllowFrameReordering,
1541 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1552 vtctx->
realtime ? kCFBooleanTrue : kCFBooleanFalse);
1561 compat_keys.kVTCompressionPropertyKey_AllowOpenGOP,
1566 if (avctx->
qmin >= 0) {
1568 compat_keys.kVTCompressionPropertyKey_MinAllowedFrameQP,
1577 if (avctx->
qmax >= 0) {
1579 compat_keys.kVTCompressionPropertyKey_MaxAllowedFrameQP,
1590 kVTCompressionPropertyKey_MaxH264SliceBytes,
1601 compat_keys.kVTCompressionPropertyKey_MaximizePowerEfficiency,
1608 compat_keys.kVTCompressionPropertyKey_ReferenceBufferCount,
1619 compat_keys.kVTCompressionPropertyKey_SpatialAdaptiveQPLevel,
1624 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1635 CFMutableDictionaryRef enc_info;
1636 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1639 CFStringRef profile_level =
NULL;
1640 CFNumberRef gamma_level =
NULL;
1649 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1651 if (__builtin_available(macOS 10.10, *)) {
1652 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1664 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1669 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1684 enc_info = CFDictionaryCreateMutable(
1685 kCFAllocatorDefault,
1687 &kCFCopyStringDictionaryKeyCallBacks,
1688 &kCFTypeDictionaryValueCallBacks
1691 if (!enc_info)
return AVERROR(ENOMEM);
1693 #if !TARGET_OS_IPHONE
1695 CFDictionarySetValue(enc_info,
1696 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1699 CFDictionarySetValue(enc_info,
1700 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1703 CFDictionarySetValue(enc_info,
1704 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1711 CFDictionarySetValue(enc_info,
1712 compat_keys.kVTVideoEncoderSpecification_EnableLowLatencyRateControl,
1752 CFRelease(gamma_level);
1754 if (pixel_buffer_info)
1755 CFRelease(pixel_buffer_info);
1757 CFRelease(enc_info);
1765 CFBooleanRef has_b_frames_cfbool;
1780 kVTCompressionPropertyKey_AllowFrameReordering,
1781 kCFAllocatorDefault,
1782 &has_b_frames_cfbool);
1784 if (!
status && has_b_frames_cfbool) {
1787 if (CFBooleanGetValue(has_b_frames_cfbool))
1791 CFRelease(has_b_frames_cfbool);
1800 CFArrayRef attachments;
1801 CFDictionaryRef attachment;
1802 CFBooleanRef not_sync;
1805 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1806 len = !attachments ? 0 : CFArrayGetCount(attachments);
1809 *is_key_frame =
true;
1813 attachment = CFArrayGetValueAtIndex(attachments, 0);
1815 if (CFDictionaryGetValueIfPresent(attachment,
1816 kCMSampleAttachmentKey_NotSync,
1817 (
const void **)¬_sync))
1819 *is_key_frame = !CFBooleanGetValue(not_sync);
1821 *is_key_frame =
true;
1842 size_t sei_payload_size = 0;
1843 uint8_t *nal_start = nal_data;
1849 nal_type = *nal_data & 0x1F;
1856 if (nal_data[nal_size - 1] == 0x80)
1859 while (nal_size > 0 && *nal_data > 0) {
1863 }
while (nal_size > 0 && *nal_data == 0xFF);
1871 sei_payload_size += *nal_data;
1874 }
while (nal_size > 0 && *nal_data == 0xFF);
1876 if (nal_size < sei_payload_size) {
1881 nal_data += sei_payload_size;
1882 nal_size -= sei_payload_size;
1885 *sei_end = nal_data;
1887 return nal_data - nal_start + 1;
1907 uint8_t* dst_end =
dst + dst_size;
1908 const uint8_t* src_end =
src + src_size;
1909 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1911 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1922 int insert_ep3_byte = *
src <= 3;
1923 if (insert_ep3_byte) {
1941 wrote_bytes =
dst - dst_start;
1944 return -wrote_bytes;
1954 uint8_t *sei_start =
dst;
1955 size_t remaining_sei_size =
sei->size;
1956 size_t remaining_dst_size = dst_size;
1961 if (!remaining_dst_size)
1964 while (sei_type && remaining_dst_size != 0) {
1965 int sei_byte = sei_type > 255 ? 255 : sei_type;
1968 sei_type -= sei_byte;
1970 remaining_dst_size--;
1976 while (remaining_sei_size && remaining_dst_size != 0) {
1977 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1980 remaining_sei_size -= size_byte;
1982 remaining_dst_size--;
1985 if (remaining_dst_size < sei->
size)
1988 header_bytes =
dst - sei_start;
1996 if (bytes_written < 0)
1999 bytes_written += header_bytes;
2000 return bytes_written;
2024 size_t length_code_size,
2025 CMSampleBufferRef sample_buffer,
2030 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2031 size_t remaining_src_size = src_size;
2032 size_t remaining_dst_size = dst_size;
2033 size_t src_offset = 0;
2036 uint8_t size_buf[4];
2038 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
2040 if (length_code_size > 4) {
2044 while (remaining_src_size > 0) {
2045 size_t curr_src_len;
2046 size_t curr_dst_len;
2062 src_offset + length_code_size,
2073 for (
i = 0;
i < length_code_size;
i++) {
2075 box_len |= size_buf[
i];
2088 remaining_dst_size--;
2093 remaining_dst_size);
2095 if (wrote_bytes < 0)
2098 remaining_dst_size -= wrote_bytes;
2099 dst_data += wrote_bytes;
2101 if (remaining_dst_size <= 0)
2107 remaining_dst_size--;
2112 curr_src_len = box_len + length_code_size;
2115 if (remaining_src_size < curr_src_len) {
2119 if (remaining_dst_size < curr_dst_len) {
2127 src_offset + length_code_size,
2142 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
2143 if (old_sei_length < 0)
2149 remaining_dst_size - old_sei_length);
2150 if (wrote_bytes < 0)
2153 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
2156 new_sei[wrote_bytes++] = 0x80;
2157 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
2159 dst_data += extra_bytes;
2160 remaining_dst_size -= extra_bytes;
2165 src_offset += curr_src_len;
2166 dst_data += curr_dst_len;
2168 remaining_src_size -= curr_src_len;
2169 remaining_dst_size -= curr_dst_len;
2190 if ((
sei->size % 255) == 0)
2193 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
2198 CMSampleBufferRef sample_buffer,
2207 size_t length_code_size;
2208 size_t header_size = 0;
2210 size_t out_buf_size;
2211 size_t sei_nalu_size = 0;
2217 CMVideoFormatDescriptionRef vid_fmt;
2228 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2246 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
2249 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2250 out_buf_size = header_size +
2253 nalu_count * ((int)
sizeof(
start_code) - (int)length_code_size);
2279 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2285 len = CMBlockBufferGetDataLength(buf);
2302 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2303 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2305 if (CMTIME_IS_INVALID(dts)) {
2317 pkt->
dts = dts.value / time_base_num - dts_delta;
2334 size_t *contiguous_buf_size)
2338 int av_format =
frame->format;
2351 if (range_guessed) {
2356 "Color range not set for %s. Using MPEG range.\n",
2363 for (
i = 0;
i <
desc->nb_components;
i++) {
2364 int p =
desc->comp[
i].plane;
2366 bool isAlpha = hasAlpha && (p + 1 == *plane_count);
2367 bool isChroma = (p != 0) && !isAlpha;
2368 int shiftw = isChroma ?
desc->log2_chroma_w : 0;
2369 int shifth = isChroma ?
desc->log2_chroma_h : 0;
2370 widths[p] = (avctx->
width + ((1 << shiftw) >> 1)) >> shiftw;
2371 heights[p] = (avctx->
height + ((1 << shifth) >> 1)) >> shifth;
2372 strides[p] =
frame->linesize[p];
2375 *contiguous_buf_size = 0;
2376 for (
i = 0;
i < *plane_count;
i++) {
2377 if (
i < *plane_count - 1 &&
2378 frame->data[
i] + strides[
i] * heights[
i] !=
frame->data[
i + 1]) {
2379 *contiguous_buf_size = 0;
2383 *contiguous_buf_size += strides[
i] * heights[
i];
2392 CVPixelBufferRef cv_img,
2393 const size_t *plane_strides,
2394 const size_t *plane_rows)
2406 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2411 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2416 if (CVPixelBufferIsPlanar(cv_img)) {
2417 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2419 if (
i == plane_count) {
2420 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2423 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2429 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2430 src_addr = (uint8_t*)
frame->data[
i];
2431 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2432 src_stride = plane_strides[
i];
2433 rows = plane_rows[
i];
2435 if (dst_stride == src_stride) {
2436 memcpy(dst_addr, src_addr, src_stride * rows);
2438 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2440 for (j = 0; j < rows; j++) {
2441 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2446 if (
frame->data[1]) {
2447 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2450 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2456 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2457 src_addr = (uint8_t*)
frame->data[0];
2458 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2459 src_stride = plane_strides[0];
2460 rows = plane_rows[0];
2462 if (dst_stride == src_stride) {
2463 memcpy(dst_addr, src_addr, src_stride * rows);
2465 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2467 for (j = 0; j < rows; j++) {
2468 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2473 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2484 CVPixelBufferRef *cv_img,
2493 size_t contiguous_buf_size;
2494 CVPixelBufferPoolRef pix_buf_pool;
2500 *cv_img = (CVPixelBufferRef)
frame->data[3];
2504 if (
frame->buf[0]) {
2513 memset(widths, 0,
sizeof(widths));
2514 memset(heights, 0,
sizeof(heights));
2515 memset(strides, 0,
sizeof(strides));
2525 &contiguous_buf_size
2532 "Error: Cannot convert format %d color_range %d: %d\n",
2541 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2542 if (!pix_buf_pool) {
2549 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2550 if (vtstatus == kVTInvalidSessionErr) {
2555 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2557 if (!pix_buf_pool) {
2563 "kVTInvalidSessionErr error.\n");
2566 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2587 CFDictionaryRef* dict_out)
2589 CFDictionaryRef dict =
NULL;
2591 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2592 const void *vals[] = { kCFBooleanTrue };
2594 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2595 if(!dict)
return AVERROR(ENOMEM);
2607 CFDictionaryRef frame_dict =
NULL;
2608 CVPixelBufferRef cv_img =
NULL;
2626 if (vtctx->
a53_cc && side_data && side_data->
size) {
2635 status = VTCompressionSessionEncodeFrame(
2654 CFRelease(frame_dict);
2672 CMSampleBufferRef buf =
NULL;
2711 if (
status)
goto end_nopkt;
2712 if (!buf)
goto end_nopkt;
2717 if (
status)
goto end_nopkt;
2729 CFStringRef profile_level,
2730 CFNumberRef gamma_level,
2731 CFDictionaryRef enc_info,
2732 CFDictionaryRef pixel_buffer_info)
2736 CVPixelBufferPoolRef pool =
NULL;
2737 CVPixelBufferRef pix_buf =
NULL;
2739 CMSampleBufferRef buf =
NULL;
2756 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2763 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2767 if(
status != kCVReturnSuccess){
2785 "Error sending frame for extradata: %d\n",
2812 CVPixelBufferRelease(pix_buf);
2840 VTCompressionSessionCompleteFrames(vtctx->
session,
2871 #ifdef kCFCoreFoundationVersionNumber10_7
2876 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2879 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2882 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2885 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2888 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2891 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2894 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2901 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2902 #define COMMON_OPTIONS \
2903 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2904 { .i64 = 0 }, 0, 1, VE }, \
2905 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2906 { .i64 = 0 }, 0, 1, VE }, \
2907 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2908 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2909 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2910 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2911 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2912 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2913 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2914 { .i64 = -1 }, -1, 1, VE }, \
2915 { "power_efficient", "Set to 1 to enable more power-efficient encoding if supported.", \
2916 OFFSET(power_efficient), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2917 { "spatial_aq", "Set to 1 to enable spatial AQ if supported.", \
2918 OFFSET(spatialaq), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2919 { "max_ref_frames", \
2920 "Sets the maximum number of reference frames. This only has an effect when the value is less than the maximum allowed by the profile/level.", \
2921 OFFSET(max_ref_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
2928 #define OFFSET(x) offsetof(VTEncContext, x)
2939 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2940 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2941 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2942 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2943 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2944 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2945 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2946 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2947 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2948 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2958 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2959 {
"max_slice_bytes",
"Set the maximum number of bytes in an H.264 slice.",
OFFSET(max_slice_bytes),
AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX,
VE },
2979 .
p.
name =
"h264_videotoolbox",
3002 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
3004 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
3018 .
p.
name =
"hevc_videotoolbox",
3033 .p.wrapper_name =
"videotoolbox",
3059 .
p.
name =
"prores_videotoolbox",
3074 .p.wrapper_name =
"videotoolbox",