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);
143 #define GET_SYM(symbol, defaultVal) \
145 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
147 compat_keys.symbol = CFSTR(defaultVal); \
149 compat_keys.symbol = *handle; \
155 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
158 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
198 "TargetQualityForAlpha");
200 "PrioritizeEncodingSpeedOverQuality");
205 "EnableHardwareAcceleratedVideoEncoder");
207 "RequireHardwareAcceleratedVideoEncoder");
209 "EnableLowLatencyRateControl");
212 "MaximizePowerEfficiency");
214 "ReferenceBufferCount");
220 #define H264_PROFILE_CONSTRAINED_HIGH (AV_PROFILE_H264_HIGH | AV_PROFILE_H264_CONSTRAINED)
299 CFRelease(
info->cm_buffer);
307 CFStringRef encoder_id =
NULL;
309 CFIndex length, max_size;
320 length = CFStringGetLength(encoder_id);
321 max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
324 CFRelease(encoder_id);
328 CFStringGetCString(encoder_id,
331 kCFStringEncodingUTF8);
334 CFRelease(encoder_id);
341 CFStringRef profile_level,
342 CFNumberRef gamma_level,
343 CFDictionaryRef enc_info,
344 CFDictionaryRef pixel_buffer_info);
448 *buf =
info->cm_buffer;
476 CMSampleBufferRef sample_buffer,
483 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
484 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
486 if (length_code_size > 4)
489 while (
offset < src_size) {
499 if (
status != kCMBlockBufferNoErr) {
503 for (
i = 0;
i < length_code_size;
i++) {
505 box_len |= size_buf[
i];
508 curr_src_len = box_len + length_code_size;
520 double alpha_quality)
535 return MKBETAG(
'a',
'p',
'c',
'o');
537 return MKBETAG(
'a',
'p',
'c',
's');
539 return MKBETAG(
'a',
'p',
'c',
'n');
541 return MKBETAG(
'a',
'p',
'c',
'h');
543 return MKBETAG(
'a',
'p',
'4',
'h');
545 return MKBETAG(
'a',
'p',
'4',
'x');
552 desc->log2_chroma_w == 0))
553 return MKBETAG(
'a',
'p',
'4',
'h');
555 return MKBETAG(
'a',
'p',
'c',
'n');
571 CMVideoFormatDescriptionRef vid_fmt,
575 size_t total_size = 0;
577 int is_count_bad = 0;
592 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
606 if (
i > 0 && is_count_bad)
status = 0;
625 CMVideoFormatDescriptionRef vid_fmt,
631 int is_count_bad = 0;
649 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
661 if (
i > 0 && is_count_bad)
status = 0;
667 if (dst_size < next_offset) {
690 CMVideoFormatDescriptionRef vid_fmt;
694 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
720 CFDataRef
data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
721 if (
data && CFGetTypeID(
data) == CFDataGetTypeID()) {
722 CFIndex
size = CFDataGetLength(
data);
738 void *sourceFrameCtx,
740 VTEncodeInfoFlags
flags,
741 CMSampleBufferRef sample_buffer)
760 if (!sample_buffer) {
764 CFRetain(sample_buffer);
765 info->cm_buffer = sample_buffer;
781 CMSampleBufferRef sample_buffer,
785 CMVideoFormatDescriptionRef vid_fmt;
789 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
817 CFStringRef *profile_level_val)
827 *profile_level_val =
NULL;
834 switch (vtctx->
level) {
835 case 0: *profile_level_val =
836 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
837 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
838 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
839 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
840 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
841 case 40: *profile_level_val =
842 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
843 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
844 case 42: *profile_level_val =
845 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
846 case 50: *profile_level_val =
847 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
848 case 51: *profile_level_val =
849 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
850 case 52: *profile_level_val =
851 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
856 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel;
858 if (vtctx->
level != 0) {
861 "Level is auto-selected when constrained-baseline "
862 "profile is used. The output may be encoded with a "
863 "different level.\n");
868 switch (vtctx->
level) {
869 case 0: *profile_level_val =
870 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
871 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
872 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
873 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
874 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
875 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
876 case 42: *profile_level_val =
878 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
879 case 51: *profile_level_val =
881 case 52: *profile_level_val =
887 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedHigh_AutoLevel;
889 if (vtctx->
level != 0) {
892 "Level is auto-selected when constrained-high profile "
893 "is used. The output may be encoded with a different "
899 switch (vtctx->
level) {
900 case 0: *profile_level_val =
901 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
902 case 30: *profile_level_val =
904 case 31: *profile_level_val =
906 case 32: *profile_level_val =
908 case 40: *profile_level_val =
910 case 41: *profile_level_val =
912 case 42: *profile_level_val =
914 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
915 case 51: *profile_level_val =
917 case 52: *profile_level_val =
922 switch (vtctx->
level) {
923 case 0: *profile_level_val =
924 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
925 case 50: *profile_level_val =
926 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
931 if (!*profile_level_val) {
946 CFStringRef *profile_level_val)
955 *profile_level_val =
NULL;
969 "main profile with %d bit input\n",
bit_depth);
976 "Invalid main10 profile with %d bit input\n",
bit_depth);
984 if (!*profile_level_val) {
995 int* av_pixel_format,
998 const char *range_name;
1004 if (*av_pixel_format)
1009 "Could not get pixel format for color format '%s' range '%s'.\n",
1011 range_name ? range_name :
"Unknown");
1020 CFDictionarySetValue(dict,
1021 kCVImageBufferColorPrimariesKey,
1026 CFDictionarySetValue(dict,
1027 kCVImageBufferTransferFunctionKey,
1032 CFDictionarySetValue(dict,
1033 kCVImageBufferYCbCrMatrixKey,
1039 CFMutableDictionaryRef* dict)
1041 CFNumberRef cv_color_format_num =
NULL;
1042 CFNumberRef width_num =
NULL;
1043 CFNumberRef height_num =
NULL;
1044 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1045 int cv_color_format;
1053 pixel_buffer_info = CFDictionaryCreateMutable(
1054 kCFAllocatorDefault,
1056 &kCFCopyStringDictionaryKeyCallBacks,
1057 &kCFTypeDictionaryValueCallBacks);
1059 if (!pixel_buffer_info)
goto pbinfo_nomem;
1061 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
1062 kCFNumberSInt32Type,
1064 if (!cv_color_format_num)
goto pbinfo_nomem;
1066 CFDictionarySetValue(pixel_buffer_info,
1067 kCVPixelBufferPixelFormatTypeKey,
1068 cv_color_format_num);
1071 width_num = CFNumberCreate(kCFAllocatorDefault,
1072 kCFNumberSInt32Type,
1074 if (!width_num)
goto pbinfo_nomem;
1076 CFDictionarySetValue(pixel_buffer_info,
1077 kCVPixelBufferWidthKey,
1081 height_num = CFNumberCreate(kCFAllocatorDefault,
1082 kCFNumberSInt32Type,
1084 if (!height_num)
goto pbinfo_nomem;
1086 CFDictionarySetValue(pixel_buffer_info,
1087 kCVPixelBufferHeightKey,
1093 *dict = pixel_buffer_info;
1100 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
1106 CFNumberRef *gamma_level)
1110 *gamma_level =
NULL;
1118 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1130 const char *print_option_name,
1136 if (
status == kVTPropertyNotSupportedErr) {
1139 "This device does not support the %s option. Value ignored.\n",
1141 }
else if (
status != 0) {
1144 "Error setting %s: Error %d\n",
1152 const char* print_option_name,
1154 CFNumberRef value_cfnum = CFNumberCreate(kCFAllocatorDefault,
1158 if (value_cfnum ==
NULL) {
1164 CFRelease(value_cfnum);
1171 CFStringRef profile_level,
1172 CFNumberRef gamma_level,
1173 CFDictionaryRef enc_info,
1174 CFDictionaryRef pixel_buffer_info,
1175 bool constant_bit_rate,
1176 VTCompressionSessionRef *session)
1182 CFNumberRef bit_rate_num;
1183 CFNumberRef quality_num;
1184 CFNumberRef bytes_per_second;
1185 CFNumberRef one_second;
1186 CFArrayRef data_rate_limits;
1187 int64_t bytes_per_second_value = 0;
1191 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1197 kCFAllocatorDefault,
1205 #if !TARGET_OS_IPHONE
1207 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1214 #if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
1215 if (__builtin_available(macOS 10.13, *)) {
1220 status = VTCopySupportedPropertyDictionaryForEncoder(avctx->
width,
1239 av_log(avctx,
AV_LOG_ERROR,
"Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1245 quality_num = CFNumberCreate(kCFAllocatorDefault,
1246 kCFNumberFloat32Type,
1248 if (!quality_num)
return AVERROR(ENOMEM);
1251 kVTCompressionPropertyKey_Quality,
1253 CFRelease(quality_num);
1255 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1256 kCFNumberSInt32Type,
1258 if (!bit_rate_num)
return AVERROR(ENOMEM);
1260 if (constant_bit_rate) {
1262 compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1264 if (
status == kVTPropertyNotSupportedErr) {
1265 av_log(avctx,
AV_LOG_ERROR,
"Error: -constant_bit_rate true is not supported by the encoder.\n");
1270 kVTCompressionPropertyKey_AverageBitRate,
1274 CFRelease(bit_rate_num);
1284 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1285 vtctx->
prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1287 av_log(avctx,
AV_LOG_WARNING,
"PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1293 bytes_per_second_value = max_rate >> 3;
1294 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1295 kCFNumberSInt64Type,
1296 &bytes_per_second_value);
1297 if (!bytes_per_second) {
1300 one_second_value = 1;
1301 one_second = CFNumberCreate(kCFAllocatorDefault,
1302 kCFNumberSInt64Type,
1305 CFRelease(bytes_per_second);
1308 nums[0] = (
void *)bytes_per_second;
1309 nums[1] = (
void *)one_second;
1310 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1311 (
const void **)nums,
1313 &kCFTypeArrayCallBacks);
1315 if (!data_rate_limits) {
1316 CFRelease(bytes_per_second);
1317 CFRelease(one_second);
1321 kVTCompressionPropertyKey_DataRateLimits,
1324 CFRelease(bytes_per_second);
1325 CFRelease(one_second);
1326 CFRelease(data_rate_limits);
1340 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1341 kCFNumberDoubleType,
1343 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1346 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1348 CFRelease(alpha_quality_num);
1353 "Error setting alpha quality: %d\n",
1359 if (profile_level) {
1361 kVTCompressionPropertyKey_ProfileLevel,
1364 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n",
status);
1369 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1377 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1379 CFRelease(interval);
1389 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1392 if (
status == kVTPropertyNotSupportedErr) {
1393 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1401 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1404 if (
status == kVTPropertyNotSupportedErr) {
1405 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1414 CFMutableDictionaryRef par;
1421 num = CFNumberCreate(kCFAllocatorDefault,
1425 den = CFNumberCreate(kCFAllocatorDefault,
1431 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1433 &kCFCopyStringDictionaryKeyCallBacks,
1434 &kCFTypeDictionaryValueCallBacks);
1436 if (!par || !num || !den) {
1437 if (par) CFRelease(par);
1438 if (num) CFRelease(num);
1439 if (den) CFRelease(den);
1444 CFDictionarySetValue(
1446 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1449 CFDictionarySetValue(
1451 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1455 kVTCompressionPropertyKey_PixelAspectRatio,
1465 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1477 kVTCompressionPropertyKey_TransferFunction,
1488 kVTCompressionPropertyKey_YCbCrMatrix,
1499 kVTCompressionPropertyKey_ColorPrimaries,
1509 kCVImageBufferGammaLevelKey,
1519 kVTCompressionPropertyKey_AllowFrameReordering,
1534 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1545 vtctx->
realtime ? kCFBooleanTrue : kCFBooleanFalse);
1554 compat_keys.kVTCompressionPropertyKey_AllowOpenGOP,
1559 if (avctx->
qmin >= 0) {
1561 compat_keys.kVTCompressionPropertyKey_MinAllowedFrameQP,
1570 if (avctx->
qmax >= 0) {
1572 compat_keys.kVTCompressionPropertyKey_MaxAllowedFrameQP,
1583 kVTCompressionPropertyKey_MaxH264SliceBytes,
1594 compat_keys.kVTCompressionPropertyKey_MaximizePowerEfficiency,
1601 compat_keys.kVTCompressionPropertyKey_ReferenceBufferCount,
1612 compat_keys.kVTCompressionPropertyKey_SpatialAdaptiveQPLevel,
1617 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1628 CFMutableDictionaryRef enc_info;
1629 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1632 CFStringRef profile_level =
NULL;
1633 CFNumberRef gamma_level =
NULL;
1642 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1644 if (__builtin_available(macOS 10.10, *)) {
1645 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1657 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1662 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1677 enc_info = CFDictionaryCreateMutable(
1678 kCFAllocatorDefault,
1680 &kCFCopyStringDictionaryKeyCallBacks,
1681 &kCFTypeDictionaryValueCallBacks
1684 if (!enc_info)
return AVERROR(ENOMEM);
1686 #if !TARGET_OS_IPHONE
1688 CFDictionarySetValue(enc_info,
1689 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1692 CFDictionarySetValue(enc_info,
1693 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1696 CFDictionarySetValue(enc_info,
1697 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1704 CFDictionarySetValue(enc_info,
1705 compat_keys.kVTVideoEncoderSpecification_EnableLowLatencyRateControl,
1745 CFRelease(gamma_level);
1747 if (pixel_buffer_info)
1748 CFRelease(pixel_buffer_info);
1750 CFRelease(enc_info);
1758 CFBooleanRef has_b_frames_cfbool;
1773 kVTCompressionPropertyKey_AllowFrameReordering,
1774 kCFAllocatorDefault,
1775 &has_b_frames_cfbool);
1777 if (!
status && has_b_frames_cfbool) {
1780 if (CFBooleanGetValue(has_b_frames_cfbool))
1784 CFRelease(has_b_frames_cfbool);
1793 CFArrayRef attachments;
1794 CFDictionaryRef attachment;
1795 CFBooleanRef not_sync;
1798 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1799 len = !attachments ? 0 : CFArrayGetCount(attachments);
1802 *is_key_frame =
true;
1806 attachment = CFArrayGetValueAtIndex(attachments, 0);
1808 if (CFDictionaryGetValueIfPresent(attachment,
1809 kCMSampleAttachmentKey_NotSync,
1810 (
const void **)¬_sync))
1812 *is_key_frame = !CFBooleanGetValue(not_sync);
1814 *is_key_frame =
true;
1835 size_t sei_payload_size = 0;
1836 uint8_t *nal_start = nal_data;
1842 nal_type = *nal_data & 0x1F;
1849 if (nal_data[nal_size - 1] == 0x80)
1852 while (nal_size > 0 && *nal_data > 0) {
1856 }
while (nal_size > 0 && *nal_data == 0xFF);
1864 sei_payload_size += *nal_data;
1867 }
while (nal_size > 0 && *nal_data == 0xFF);
1869 if (nal_size < sei_payload_size) {
1874 nal_data += sei_payload_size;
1875 nal_size -= sei_payload_size;
1878 *sei_end = nal_data;
1880 return nal_data - nal_start + 1;
1900 uint8_t* dst_end =
dst + dst_size;
1901 const uint8_t* src_end =
src + src_size;
1902 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1904 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1915 int insert_ep3_byte = *
src <= 3;
1916 if (insert_ep3_byte) {
1934 wrote_bytes =
dst - dst_start;
1937 return -wrote_bytes;
1947 uint8_t *sei_start =
dst;
1948 size_t remaining_sei_size =
sei->size;
1949 size_t remaining_dst_size = dst_size;
1954 if (!remaining_dst_size)
1957 while (sei_type && remaining_dst_size != 0) {
1958 int sei_byte = sei_type > 255 ? 255 : sei_type;
1961 sei_type -= sei_byte;
1963 remaining_dst_size--;
1969 while (remaining_sei_size && remaining_dst_size != 0) {
1970 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1973 remaining_sei_size -= size_byte;
1975 remaining_dst_size--;
1978 if (remaining_dst_size < sei->
size)
1981 header_bytes =
dst - sei_start;
1989 if (bytes_written < 0)
1992 bytes_written += header_bytes;
1993 return bytes_written;
2017 size_t length_code_size,
2018 CMSampleBufferRef sample_buffer,
2023 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2024 size_t remaining_src_size = src_size;
2025 size_t remaining_dst_size = dst_size;
2026 size_t src_offset = 0;
2029 uint8_t size_buf[4];
2031 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
2033 if (length_code_size > 4) {
2037 while (remaining_src_size > 0) {
2038 size_t curr_src_len;
2039 size_t curr_dst_len;
2055 src_offset + length_code_size,
2066 for (
i = 0;
i < length_code_size;
i++) {
2068 box_len |= size_buf[
i];
2081 remaining_dst_size--;
2086 remaining_dst_size);
2088 if (wrote_bytes < 0)
2091 remaining_dst_size -= wrote_bytes;
2092 dst_data += wrote_bytes;
2094 if (remaining_dst_size <= 0)
2100 remaining_dst_size--;
2105 curr_src_len = box_len + length_code_size;
2108 if (remaining_src_size < curr_src_len) {
2112 if (remaining_dst_size < curr_dst_len) {
2120 src_offset + length_code_size,
2135 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
2136 if (old_sei_length < 0)
2142 remaining_dst_size - old_sei_length);
2143 if (wrote_bytes < 0)
2146 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
2149 new_sei[wrote_bytes++] = 0x80;
2150 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
2152 dst_data += extra_bytes;
2153 remaining_dst_size -= extra_bytes;
2158 src_offset += curr_src_len;
2159 dst_data += curr_dst_len;
2161 remaining_src_size -= curr_src_len;
2162 remaining_dst_size -= curr_dst_len;
2183 if ((
sei->size % 255) == 0)
2186 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
2191 CMSampleBufferRef sample_buffer,
2200 size_t length_code_size;
2201 size_t header_size = 0;
2203 size_t out_buf_size;
2204 size_t sei_nalu_size = 0;
2210 CMVideoFormatDescriptionRef vid_fmt;
2221 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2239 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
2242 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2243 out_buf_size = header_size +
2246 nalu_count * ((int)
sizeof(
start_code) - (int)length_code_size);
2272 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2278 len = CMBlockBufferGetDataLength(buf);
2295 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2296 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2298 if (CMTIME_IS_INVALID(dts)) {
2310 pkt->
dts = dts.value / time_base_num - dts_delta;
2327 size_t *contiguous_buf_size)
2331 int av_format =
frame->format;
2344 if (range_guessed) {
2349 "Color range not set for %s. Using MPEG range.\n",
2356 for (
i = 0;
i <
desc->nb_components;
i++) {
2357 int p =
desc->comp[
i].plane;
2359 bool isAlpha = hasAlpha && (p + 1 == *plane_count);
2360 bool isChroma = (p != 0) && !isAlpha;
2361 int shiftw = isChroma ?
desc->log2_chroma_w : 0;
2362 int shifth = isChroma ?
desc->log2_chroma_h : 0;
2363 widths[p] = (avctx->
width + ((1 << shiftw) >> 1)) >> shiftw;
2364 heights[p] = (avctx->
height + ((1 << shifth) >> 1)) >> shifth;
2365 strides[p] =
frame->linesize[p];
2368 *contiguous_buf_size = 0;
2369 for (
i = 0;
i < *plane_count;
i++) {
2370 if (
i < *plane_count - 1 &&
2371 frame->data[
i] + strides[
i] * heights[
i] !=
frame->data[
i + 1]) {
2372 *contiguous_buf_size = 0;
2376 *contiguous_buf_size += strides[
i] * heights[
i];
2385 CVPixelBufferRef cv_img,
2386 const size_t *plane_strides,
2387 const size_t *plane_rows)
2399 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2404 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2409 if (CVPixelBufferIsPlanar(cv_img)) {
2410 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2412 if (
i == plane_count) {
2413 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2416 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2422 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2423 src_addr = (uint8_t*)
frame->data[
i];
2424 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2425 src_stride = plane_strides[
i];
2426 rows = plane_rows[
i];
2428 if (dst_stride == src_stride) {
2429 memcpy(dst_addr, src_addr, src_stride * rows);
2431 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2433 for (j = 0; j < rows; j++) {
2434 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2439 if (
frame->data[1]) {
2440 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2443 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2449 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2450 src_addr = (uint8_t*)
frame->data[0];
2451 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2452 src_stride = plane_strides[0];
2453 rows = plane_rows[0];
2455 if (dst_stride == src_stride) {
2456 memcpy(dst_addr, src_addr, src_stride * rows);
2458 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2460 for (j = 0; j < rows; j++) {
2461 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2466 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2477 CVPixelBufferRef *cv_img,
2486 size_t contiguous_buf_size;
2487 CVPixelBufferPoolRef pix_buf_pool;
2493 *cv_img = (CVPixelBufferRef)
frame->data[3];
2497 if (
frame->buf[0]) {
2506 memset(widths, 0,
sizeof(widths));
2507 memset(heights, 0,
sizeof(heights));
2508 memset(strides, 0,
sizeof(strides));
2518 &contiguous_buf_size
2525 "Error: Cannot convert format %d color_range %d: %d\n",
2534 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2535 if (!pix_buf_pool) {
2542 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2543 if (vtstatus == kVTInvalidSessionErr) {
2548 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2550 if (!pix_buf_pool) {
2556 "kVTInvalidSessionErr error.\n");
2559 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2580 CFDictionaryRef* dict_out)
2582 CFDictionaryRef dict =
NULL;
2584 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2585 const void *vals[] = { kCFBooleanTrue };
2587 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2588 if(!dict)
return AVERROR(ENOMEM);
2600 CFDictionaryRef frame_dict =
NULL;
2601 CVPixelBufferRef cv_img =
NULL;
2619 if (vtctx->
a53_cc && side_data && side_data->
size) {
2628 status = VTCompressionSessionEncodeFrame(
2647 CFRelease(frame_dict);
2665 CMSampleBufferRef buf =
NULL;
2704 if (
status)
goto end_nopkt;
2705 if (!buf)
goto end_nopkt;
2710 if (
status)
goto end_nopkt;
2722 CFStringRef profile_level,
2723 CFNumberRef gamma_level,
2724 CFDictionaryRef enc_info,
2725 CFDictionaryRef pixel_buffer_info)
2729 CVPixelBufferPoolRef pool =
NULL;
2730 CVPixelBufferRef pix_buf =
NULL;
2732 CMSampleBufferRef buf =
NULL;
2749 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2756 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2760 if(
status != kCVReturnSuccess){
2778 "Error sending frame for extradata: %d\n",
2805 CVPixelBufferRelease(pix_buf);
2833 VTCompressionSessionCompleteFrames(vtctx->
session,
2863 #ifdef kCFCoreFoundationVersionNumber10_7
2868 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2871 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2874 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2877 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2880 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2883 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2886 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2893 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2894 #define COMMON_OPTIONS \
2895 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2896 { .i64 = 0 }, 0, 1, VE }, \
2897 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2898 { .i64 = 0 }, 0, 1, VE }, \
2899 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2900 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2901 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2902 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2903 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2904 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2905 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2906 { .i64 = -1 }, -1, 1, VE }, \
2907 { "power_efficient", "Set to 1 to enable more power-efficient encoding if supported.", \
2908 OFFSET(power_efficient), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2909 { "spatial_aq", "Set to 1 to enable spatial AQ if supported.", \
2910 OFFSET(spatialaq), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2911 { "max_ref_frames", \
2912 "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.", \
2913 OFFSET(max_ref_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
2920 #define OFFSET(x) offsetof(VTEncContext, x)
2931 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2932 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2933 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2934 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2935 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2936 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2937 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2938 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2939 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2940 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE, .unit =
"level" },
2950 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2951 {
"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 },
2971 .
p.
name =
"h264_videotoolbox",
2992 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
2994 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
3008 .
p.
name =
"hevc_videotoolbox",
3023 .p.wrapper_name =
"videotoolbox",
3049 .
p.
name =
"prores_videotoolbox",
3064 .p.wrapper_name =
"videotoolbox",