21 #include <Availability.h>
22 #include <CoreMedia/CoreMedia.h>
23 #include <CoreVideo/CoreVideo.h>
26 #include <TargetConditionals.h>
27 #include <VideoToolbox/VideoToolbox.h>
45 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
49 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
53 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
58 #if !HAVE_KVTQPMODULATIONLEVEL_DEFAULT
63 #ifndef TARGET_CPU_ARM64
64 # define TARGET_CPU_ARM64 0
68 size_t parameterSetIndex,
69 const uint8_t **parameterSetPointerOut,
70 size_t *parameterSetSizeOut,
71 size_t *parameterSetCountOut,
72 int *NALUnitHeaderLengthOut);
145 #define GET_SYM(symbol, defaultVal) \
147 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
149 compat_keys.symbol = CFSTR(defaultVal); \
151 compat_keys.symbol = *handle; \
157 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
160 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
201 "TargetQualityForAlpha");
203 "PrioritizeEncodingSpeedOverQuality");
208 "EnableHardwareAcceleratedVideoEncoder");
210 "RequireHardwareAcceleratedVideoEncoder");
212 "EnableLowLatencyRateControl");
215 "MaximizePowerEfficiency");
217 "ReferenceBufferCount");
223 #define H264_PROFILE_CONSTRAINED_HIGH (AV_PROFILE_H264_HIGH | AV_PROFILE_H264_CONSTRAINED)
302 CFRelease(
info->cm_buffer);
310 CFStringRef encoder_id =
NULL;
312 CFIndex length, max_size;
323 length = CFStringGetLength(encoder_id);
324 max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
327 CFRelease(encoder_id);
331 CFStringGetCString(encoder_id,
334 kCFStringEncodingUTF8);
337 CFRelease(encoder_id);
344 CFStringRef profile_level,
345 CFNumberRef gamma_level,
346 CFDictionaryRef enc_info,
347 CFDictionaryRef pixel_buffer_info);
451 *buf =
info->cm_buffer;
479 CMSampleBufferRef sample_buffer,
486 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
487 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
489 if (length_code_size > 4)
492 while (
offset < src_size) {
502 if (
status != kCMBlockBufferNoErr) {
506 for (
i = 0;
i < length_code_size;
i++) {
508 box_len |= size_buf[
i];
511 curr_src_len = box_len + length_code_size;
523 double alpha_quality)
538 return MKBETAG(
'a',
'p',
'c',
'o');
540 return MKBETAG(
'a',
'p',
'c',
's');
542 return MKBETAG(
'a',
'p',
'c',
'n');
544 return MKBETAG(
'a',
'p',
'c',
'h');
546 return MKBETAG(
'a',
'p',
'4',
'h');
548 return MKBETAG(
'a',
'p',
'4',
'x');
556 desc->log2_chroma_w == 0))
557 return MKBETAG(
'a',
'p',
'4',
'h');
559 return MKBETAG(
'a',
'p',
'c',
'n');
575 CMVideoFormatDescriptionRef vid_fmt,
579 size_t total_size = 0;
581 int is_count_bad = 0;
596 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
610 if (
i > 0 && is_count_bad)
status = 0;
629 CMVideoFormatDescriptionRef vid_fmt,
635 int is_count_bad = 0;
653 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
665 if (
i > 0 && is_count_bad)
status = 0;
671 if (dst_size < next_offset) {
694 CMVideoFormatDescriptionRef vid_fmt;
698 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
724 CFDataRef
data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
725 if (
data && CFGetTypeID(
data) == CFDataGetTypeID()) {
726 CFIndex
size = CFDataGetLength(
data);
742 void *sourceFrameCtx,
744 VTEncodeInfoFlags
flags,
745 CMSampleBufferRef sample_buffer)
764 if (!sample_buffer) {
768 CFRetain(sample_buffer);
769 info->cm_buffer = sample_buffer;
785 CMSampleBufferRef sample_buffer,
789 CMVideoFormatDescriptionRef vid_fmt;
793 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
821 CFStringRef *profile_level_val)
831 *profile_level_val =
NULL;
838 switch (vtctx->
level) {
839 case 0: *profile_level_val =
840 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
841 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
842 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
843 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
844 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
845 case 40: *profile_level_val =
846 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
847 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
848 case 42: *profile_level_val =
849 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
850 case 50: *profile_level_val =
851 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
852 case 51: *profile_level_val =
853 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
854 case 52: *profile_level_val =
855 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
860 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel;
862 if (vtctx->
level != 0) {
865 "Level is auto-selected when constrained-baseline "
866 "profile is used. The output may be encoded with a "
867 "different level.\n");
872 switch (vtctx->
level) {
873 case 0: *profile_level_val =
874 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
875 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
876 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
877 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
878 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
879 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
880 case 42: *profile_level_val =
882 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
883 case 51: *profile_level_val =
885 case 52: *profile_level_val =
891 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedHigh_AutoLevel;
893 if (vtctx->
level != 0) {
896 "Level is auto-selected when constrained-high profile "
897 "is used. The output may be encoded with a different "
903 switch (vtctx->
level) {
904 case 0: *profile_level_val =
905 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
906 case 30: *profile_level_val =
908 case 31: *profile_level_val =
910 case 32: *profile_level_val =
912 case 40: *profile_level_val =
914 case 41: *profile_level_val =
916 case 42: *profile_level_val =
918 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
919 case 51: *profile_level_val =
921 case 52: *profile_level_val =
926 switch (vtctx->
level) {
927 case 0: *profile_level_val =
928 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
929 case 50: *profile_level_val =
930 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
935 if (!*profile_level_val) {
950 CFStringRef *profile_level_val)
959 *profile_level_val =
NULL;
973 "main profile with %d bit input\n",
bit_depth);
980 "Invalid main10 profile with %d bit input\n",
bit_depth);
989 compat_keys.kVTProfileLevel_HEVC_Main42210_AutoLevel;
993 if (!*profile_level_val) {
1004 int* av_pixel_format,
1007 const char *range_name;
1013 if (*av_pixel_format)
1018 "Could not get pixel format for color format '%s' range '%s'.\n",
1020 range_name ? range_name :
"Unknown");
1029 CFDictionarySetValue(dict,
1030 kCVImageBufferColorPrimariesKey,
1035 CFDictionarySetValue(dict,
1036 kCVImageBufferTransferFunctionKey,
1041 CFDictionarySetValue(dict,
1042 kCVImageBufferYCbCrMatrixKey,
1048 CFMutableDictionaryRef* dict)
1050 CFNumberRef cv_color_format_num =
NULL;
1051 CFNumberRef width_num =
NULL;
1052 CFNumberRef height_num =
NULL;
1053 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1054 int cv_color_format;
1062 pixel_buffer_info = CFDictionaryCreateMutable(
1063 kCFAllocatorDefault,
1065 &kCFCopyStringDictionaryKeyCallBacks,
1066 &kCFTypeDictionaryValueCallBacks);
1068 if (!pixel_buffer_info)
goto pbinfo_nomem;
1070 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
1071 kCFNumberSInt32Type,
1073 if (!cv_color_format_num)
goto pbinfo_nomem;
1075 CFDictionarySetValue(pixel_buffer_info,
1076 kCVPixelBufferPixelFormatTypeKey,
1077 cv_color_format_num);
1080 width_num = CFNumberCreate(kCFAllocatorDefault,
1081 kCFNumberSInt32Type,
1083 if (!width_num)
goto pbinfo_nomem;
1085 CFDictionarySetValue(pixel_buffer_info,
1086 kCVPixelBufferWidthKey,
1090 height_num = CFNumberCreate(kCFAllocatorDefault,
1091 kCFNumberSInt32Type,
1093 if (!height_num)
goto pbinfo_nomem;
1095 CFDictionarySetValue(pixel_buffer_info,
1096 kCVPixelBufferHeightKey,
1102 *dict = pixel_buffer_info;
1109 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
1115 CFNumberRef *gamma_level)
1119 *gamma_level =
NULL;
1127 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1139 const char *print_option_name,
1145 if (
status == kVTPropertyNotSupportedErr) {
1148 "This device does not support the %s option. Value ignored.\n",
1150 }
else if (
status != 0) {
1153 "Error setting %s: Error %d\n",
1161 const char* print_option_name,
1163 CFNumberRef value_cfnum = CFNumberCreate(kCFAllocatorDefault,
1167 if (value_cfnum ==
NULL) {
1173 CFRelease(value_cfnum);
1180 CFStringRef profile_level,
1181 CFNumberRef gamma_level,
1182 CFDictionaryRef enc_info,
1183 CFDictionaryRef pixel_buffer_info,
1184 bool constant_bit_rate,
1185 VTCompressionSessionRef *session)
1190 CFNumberRef bit_rate_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, iOS 11.0, *)) {
1227 status = VTCopySupportedPropertyDictionaryForEncoder(avctx->
width,
1246 av_log(avctx,
AV_LOG_ERROR,
"-q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1254 CFNumberRef quality_num = CFNumberCreate(kCFAllocatorDefault,
1255 kCFNumberFloat32Type,
1257 if (!quality_num)
return AVERROR(ENOMEM);
1260 kVTCompressionPropertyKey_Quality,
1262 CFRelease(quality_num);
1264 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1265 kCFNumberSInt32Type,
1267 if (!bit_rate_num)
return AVERROR(ENOMEM);
1269 if (constant_bit_rate) {
1271 compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1273 if (
status == kVTPropertyNotSupportedErr) {
1274 av_log(avctx,
AV_LOG_ERROR,
"-constant_bit_rate true is not supported by the encoder.\n");
1279 kVTCompressionPropertyKey_AverageBitRate,
1283 CFRelease(bit_rate_num);
1293 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1294 vtctx->
prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1296 av_log(avctx,
AV_LOG_WARNING,
"PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1302 bytes_per_second_value = max_rate >> 3;
1303 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1304 kCFNumberSInt64Type,
1305 &bytes_per_second_value);
1306 if (!bytes_per_second) {
1309 one_second_value = 1;
1310 one_second = CFNumberCreate(kCFAllocatorDefault,
1311 kCFNumberSInt64Type,
1314 CFRelease(bytes_per_second);
1317 nums[0] = (
void *)bytes_per_second;
1318 nums[1] = (
void *)one_second;
1319 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1320 (
const void **)nums,
1322 &kCFTypeArrayCallBacks);
1324 if (!data_rate_limits) {
1325 CFRelease(bytes_per_second);
1326 CFRelease(one_second);
1330 kVTCompressionPropertyKey_DataRateLimits,
1333 CFRelease(bytes_per_second);
1334 CFRelease(one_second);
1335 CFRelease(data_rate_limits);
1351 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1352 kCFNumberDoubleType,
1354 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1357 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1359 CFRelease(alpha_quality_num);
1364 "Error setting alpha quality: %d\n",
1370 if (profile_level) {
1372 kVTCompressionPropertyKey_ProfileLevel,
1375 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n",
status);
1380 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1388 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1390 CFRelease(interval);
1400 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1403 if (
status == kVTPropertyNotSupportedErr) {
1404 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1412 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1415 if (
status == kVTPropertyNotSupportedErr) {
1416 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1425 CFMutableDictionaryRef par;
1432 num = CFNumberCreate(kCFAllocatorDefault,
1436 den = CFNumberCreate(kCFAllocatorDefault,
1442 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1444 &kCFCopyStringDictionaryKeyCallBacks,
1445 &kCFTypeDictionaryValueCallBacks);
1447 if (!par || !num || !den) {
1448 if (par) CFRelease(par);
1449 if (num) CFRelease(num);
1450 if (den) CFRelease(den);
1455 CFDictionarySetValue(
1457 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1460 CFDictionarySetValue(
1462 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1466 kVTCompressionPropertyKey_PixelAspectRatio,
1476 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1488 kVTCompressionPropertyKey_TransferFunction,
1499 kVTCompressionPropertyKey_YCbCrMatrix,
1510 kVTCompressionPropertyKey_ColorPrimaries,
1520 kCVImageBufferGammaLevelKey,
1530 kVTCompressionPropertyKey_AllowFrameReordering,
1545 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1556 vtctx->
realtime ? kCFBooleanTrue : kCFBooleanFalse);
1565 compat_keys.kVTCompressionPropertyKey_AllowOpenGOP,
1570 if (avctx->
qmin >= 0) {
1572 compat_keys.kVTCompressionPropertyKey_MinAllowedFrameQP,
1581 if (avctx->
qmax >= 0) {
1583 compat_keys.kVTCompressionPropertyKey_MaxAllowedFrameQP,
1594 kVTCompressionPropertyKey_MaxH264SliceBytes,
1605 compat_keys.kVTCompressionPropertyKey_MaximizePowerEfficiency,
1612 compat_keys.kVTCompressionPropertyKey_ReferenceBufferCount,
1623 compat_keys.kVTCompressionPropertyKey_SpatialAdaptiveQPLevel,
1628 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1639 CFMutableDictionaryRef enc_info;
1640 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1643 CFStringRef profile_level =
NULL;
1644 CFNumberRef gamma_level =
NULL;
1653 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1655 if (__builtin_available(macOS 10.10, *)) {
1656 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1668 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1673 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1688 enc_info = CFDictionaryCreateMutable(
1689 kCFAllocatorDefault,
1691 &kCFCopyStringDictionaryKeyCallBacks,
1692 &kCFTypeDictionaryValueCallBacks
1695 if (!enc_info)
return AVERROR(ENOMEM);
1697 #if !TARGET_OS_IPHONE
1699 CFDictionarySetValue(enc_info,
1700 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1703 CFDictionarySetValue(enc_info,
1704 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1707 CFDictionarySetValue(enc_info,
1708 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1718 "please specify bitrate explicitly\n");
1722 CFDictionarySetValue(enc_info,
1723 compat_keys.kVTVideoEncoderSpecification_EnableLowLatencyRateControl,
1763 CFRelease(gamma_level);
1765 if (pixel_buffer_info)
1766 CFRelease(pixel_buffer_info);
1768 CFRelease(enc_info);
1776 CFBooleanRef has_b_frames_cfbool;
1791 kVTCompressionPropertyKey_AllowFrameReordering,
1792 kCFAllocatorDefault,
1793 &has_b_frames_cfbool);
1795 if (!
status && has_b_frames_cfbool) {
1798 if (CFBooleanGetValue(has_b_frames_cfbool))
1802 CFRelease(has_b_frames_cfbool);
1811 CFArrayRef attachments;
1812 CFDictionaryRef attachment;
1813 CFBooleanRef not_sync;
1816 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1817 len = !attachments ? 0 : CFArrayGetCount(attachments);
1820 *is_key_frame =
true;
1824 attachment = CFArrayGetValueAtIndex(attachments, 0);
1826 if (CFDictionaryGetValueIfPresent(attachment,
1827 kCMSampleAttachmentKey_NotSync,
1828 (
const void **)¬_sync))
1830 *is_key_frame = !CFBooleanGetValue(not_sync);
1832 *is_key_frame =
true;
1853 size_t sei_payload_size = 0;
1854 uint8_t *nal_start = nal_data;
1860 nal_type = *nal_data & 0x1F;
1867 if (nal_data[nal_size - 1] == 0x80)
1870 while (nal_size > 0 && *nal_data > 0) {
1874 }
while (nal_size > 0 && *nal_data == 0xFF);
1882 sei_payload_size += *nal_data;
1885 }
while (nal_size > 0 && *nal_data == 0xFF);
1887 if (nal_size < sei_payload_size) {
1892 nal_data += sei_payload_size;
1893 nal_size -= sei_payload_size;
1896 *sei_end = nal_data;
1898 return nal_data - nal_start + 1;
1918 uint8_t* dst_end =
dst + dst_size;
1919 const uint8_t* src_end =
src + src_size;
1920 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1922 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1933 int insert_ep3_byte = *
src <= 3;
1934 if (insert_ep3_byte) {
1952 wrote_bytes =
dst - dst_start;
1955 return -wrote_bytes;
1965 uint8_t *sei_start =
dst;
1966 size_t remaining_sei_size =
sei->size;
1967 size_t remaining_dst_size = dst_size;
1972 if (!remaining_dst_size)
1975 while (sei_type && remaining_dst_size != 0) {
1976 int sei_byte = sei_type > 255 ? 255 : sei_type;
1979 sei_type -= sei_byte;
1981 remaining_dst_size--;
1987 while (remaining_sei_size && remaining_dst_size != 0) {
1988 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1991 remaining_sei_size -= size_byte;
1993 remaining_dst_size--;
1996 if (remaining_dst_size < sei->
size)
1999 header_bytes =
dst - sei_start;
2007 if (bytes_written < 0)
2010 bytes_written += header_bytes;
2011 return bytes_written;
2035 size_t length_code_size,
2036 CMSampleBufferRef sample_buffer,
2041 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2042 size_t remaining_src_size = src_size;
2043 size_t remaining_dst_size = dst_size;
2044 size_t src_offset = 0;
2047 uint8_t size_buf[4];
2049 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
2051 if (length_code_size > 4) {
2055 while (remaining_src_size > 0) {
2056 size_t curr_src_len;
2057 size_t curr_dst_len;
2073 src_offset + length_code_size,
2084 for (
i = 0;
i < length_code_size;
i++) {
2086 box_len |= size_buf[
i];
2099 remaining_dst_size--;
2104 remaining_dst_size);
2106 if (wrote_bytes < 0)
2109 remaining_dst_size -= wrote_bytes;
2110 dst_data += wrote_bytes;
2112 if (remaining_dst_size <= 0)
2118 remaining_dst_size--;
2123 curr_src_len = box_len + length_code_size;
2126 if (remaining_src_size < curr_src_len) {
2130 if (remaining_dst_size < curr_dst_len) {
2138 src_offset + length_code_size,
2153 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
2154 if (old_sei_length < 0)
2155 return old_sei_length;
2160 remaining_dst_size - old_sei_length);
2161 if (wrote_bytes < 0)
2164 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
2167 new_sei[wrote_bytes++] = 0x80;
2168 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
2170 dst_data += extra_bytes;
2171 remaining_dst_size -= extra_bytes;
2176 src_offset += curr_src_len;
2177 dst_data += curr_dst_len;
2179 remaining_src_size -= curr_src_len;
2180 remaining_dst_size -= curr_dst_len;
2201 if ((
sei->size % 255) == 0)
2204 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
2209 CMSampleBufferRef sample_buffer,
2218 size_t length_code_size;
2219 size_t header_size = 0;
2221 size_t out_buf_size;
2222 size_t sei_nalu_size = 0;
2228 CMVideoFormatDescriptionRef vid_fmt;
2239 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2257 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
2260 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2261 out_buf_size = header_size +
2264 nalu_count * ((int)
sizeof(
start_code) - (int)length_code_size);
2290 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2296 len = CMBlockBufferGetDataLength(buf);
2313 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2314 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2316 if (CMTIME_IS_INVALID(dts)) {
2328 pkt->
dts = dts.value / time_base_num - dts_delta;
2335 CVPixelBufferRef cv_img)
2340 size_t num_cv_plane = CVPixelBufferIsPlanar(cv_img) ?
2341 CVPixelBufferGetPlaneCount(cv_img) : 1;
2342 if (num_planes != num_cv_plane) {
2344 "Different number of planes in AVFrame and CVPixelBuffer.\n");
2348 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2354 int dst_stride[4] = {0};
2355 uint8_t *dst_addr[4] = {0};
2356 for (
int i = 0;
i < num_planes;
i++) {
2357 dst_addr[
i] = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2358 dst_stride[
i] = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2363 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2374 CVPixelBufferRef *cv_img,
2378 CVPixelBufferPoolRef pix_buf_pool;
2384 *cv_img = (CVPixelBufferRef)
frame->data[3];
2388 if (
frame->buf[0]) {
2399 &(
int) {0}, &range_guessed);
2405 if (range_guessed) {
2413 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2414 if (!pix_buf_pool) {
2421 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2422 if (vtstatus == kVTInvalidSessionErr) {
2427 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2429 if (!pix_buf_pool) {
2435 "kVTInvalidSessionErr error.\n");
2438 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2459 CFDictionaryRef* dict_out)
2461 CFDictionaryRef dict =
NULL;
2463 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2464 const void *vals[] = { kCFBooleanTrue };
2466 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2467 if(!dict)
return AVERROR(ENOMEM);
2479 CFDictionaryRef frame_dict =
NULL;
2480 CVPixelBufferRef cv_img =
NULL;
2498 if (vtctx->
a53_cc && side_data && side_data->
size) {
2507 status = VTCompressionSessionEncodeFrame(
2526 CFRelease(frame_dict);
2544 CMSampleBufferRef buf =
NULL;
2583 if (
status)
goto end_nopkt;
2584 if (!buf)
goto end_nopkt;
2589 if (
status)
goto end_nopkt;
2601 CFStringRef profile_level,
2602 CFNumberRef gamma_level,
2603 CFDictionaryRef enc_info,
2604 CFDictionaryRef pixel_buffer_info)
2608 CVPixelBufferPoolRef pool =
NULL;
2609 CVPixelBufferRef pix_buf =
NULL;
2611 CMSampleBufferRef buf =
NULL;
2628 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2635 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2639 if(
status != kCVReturnSuccess){
2657 "Error sending frame for extradata: %d\n",
2684 CVPixelBufferRelease(pix_buf);
2712 VTCompressionSessionCompleteFrames(vtctx->
session,
2744 #ifdef kCFCoreFoundationVersionNumber10_7
2749 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2752 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2755 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2758 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2761 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2764 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2767 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2774 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2775 #define COMMON_OPTIONS \
2776 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2777 { .i64 = 0 }, 0, 1, VE }, \
2778 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2779 { .i64 = 0 }, 0, 1, VE }, \
2780 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2781 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2782 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2783 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2784 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2785 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2786 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2787 { .i64 = -1 }, -1, 1, VE }, \
2788 { "power_efficient", "Set to 1 to enable more power-efficient encoding if supported.", \
2789 OFFSET(power_efficient), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2790 { "spatial_aq", "Set to 1 to enable spatial AQ if supported.", \
2791 OFFSET(spatialaq), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2792 { "max_ref_frames", \
2793 "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.", \
2794 OFFSET(max_ref_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
2801 #define OFFSET(x) offsetof(VTEncContext, x)
2812 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2813 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2814 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2815 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2816 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2817 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2818 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2819 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2820 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2821 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2831 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2832 {
"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 },
2852 .
p.
name =
"h264_videotoolbox",
2866 .p.wrapper_name =
"videotoolbox",
2877 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
2879 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2893 .
p.
name =
"hevc_videotoolbox",
2908 .p.wrapper_name =
"videotoolbox",
2934 .
p.
name =
"prores_videotoolbox",
2949 .p.wrapper_name =
"videotoolbox",