21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
42 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
46 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
50 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
55 #ifndef TARGET_CPU_ARM64
56 # define TARGET_CPU_ARM64 0
60 size_t parameterSetIndex,
61 const uint8_t **parameterSetPointerOut,
62 size_t *parameterSetSizeOut,
63 size_t *parameterSetCountOut,
64 int *NALUnitHeaderLengthOut);
134 #define GET_SYM(symbol, defaultVal) \
136 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
138 compat_keys.symbol = CFSTR(defaultVal); \
140 compat_keys.symbol = *handle; \
146 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
149 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
189 "TargetQualityForAlpha");
191 "PrioritizeEncodingSpeedOverQuality");
195 "EnableHardwareAcceleratedVideoEncoder");
197 "RequireHardwareAcceleratedVideoEncoder");
199 "EnableLowLatencyRateControl");
202 "MaximizePowerEfficiency");
204 "ReferenceBufferCount");
209 #define H264_PROFILE_CONSTRAINED_HIGH (AV_PROFILE_H264_HIGH | AV_PROFILE_H264_CONSTRAINED)
282 CFStringRef profile_level,
283 CFNumberRef gamma_level,
284 CFDictionaryRef enc_info,
285 CFDictionaryRef pixel_buffer_info);
312 CFRelease(
info->cm_buffer);
390 *buf =
info->cm_buffer;
393 }
else if (
info->sei) {
431 CMSampleBufferRef sample_buffer,
438 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
439 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
441 if (length_code_size > 4)
444 while (
offset < src_size) {
454 if (
status != kCMBlockBufferNoErr) {
458 for (
i = 0;
i < length_code_size;
i++) {
460 box_len |= size_buf[
i];
463 curr_src_len = box_len + length_code_size;
475 double alpha_quality)
488 return MKBETAG(
'a',
'p',
'c',
'o');
490 return MKBETAG(
'a',
'p',
'c',
's');
492 return MKBETAG(
'a',
'p',
'c',
'n');
494 return MKBETAG(
'a',
'p',
'c',
'h');
496 return MKBETAG(
'a',
'p',
'4',
'h');
498 return MKBETAG(
'a',
'p',
'4',
'x');
505 desc->log2_chroma_w == 0))
506 return MKBETAG(
'a',
'p',
'4',
'h');
508 return MKBETAG(
'a',
'p',
'c',
'n');
524 CMVideoFormatDescriptionRef vid_fmt,
528 size_t total_size = 0;
530 int is_count_bad = 0;
545 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
559 if (
i > 0 && is_count_bad)
status = 0;
578 CMVideoFormatDescriptionRef vid_fmt,
584 int is_count_bad = 0;
602 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
614 if (
i > 0 && is_count_bad)
status = 0;
620 if (dst_size < next_offset) {
628 memcpy(dst +
offset, ps, ps_size);
643 CMVideoFormatDescriptionRef vid_fmt;
647 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
673 CFDataRef
data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
674 if (
data && CFGetTypeID(
data) == CFDataGetTypeID()) {
675 CFIndex
size = CFDataGetLength(
data);
691 void *sourceFrameCtx,
693 VTEncodeInfoFlags
flags,
694 CMSampleBufferRef sample_buffer)
710 if (!sample_buffer) {
727 CMSampleBufferRef sample_buffer,
731 CMVideoFormatDescriptionRef vid_fmt;
735 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
763 CFStringRef *profile_level_val)
773 *profile_level_val =
NULL;
780 switch (vtctx->
level) {
781 case 0: *profile_level_val =
782 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
783 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
784 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
785 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
786 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
787 case 40: *profile_level_val =
788 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
789 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
790 case 42: *profile_level_val =
791 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
792 case 50: *profile_level_val =
793 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
794 case 51: *profile_level_val =
795 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
796 case 52: *profile_level_val =
797 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
802 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel;
804 if (vtctx->
level != 0) {
807 "Level is auto-selected when constrained-baseline "
808 "profile is used. The output may be encoded with a "
809 "different level.\n");
814 switch (vtctx->
level) {
815 case 0: *profile_level_val =
816 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
817 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
818 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
819 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
820 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
821 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
822 case 42: *profile_level_val =
824 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
825 case 51: *profile_level_val =
827 case 52: *profile_level_val =
833 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedHigh_AutoLevel;
835 if (vtctx->
level != 0) {
838 "Level is auto-selected when constrained-high profile "
839 "is used. The output may be encoded with a different "
845 switch (vtctx->
level) {
846 case 0: *profile_level_val =
847 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
848 case 30: *profile_level_val =
850 case 31: *profile_level_val =
852 case 32: *profile_level_val =
854 case 40: *profile_level_val =
856 case 41: *profile_level_val =
858 case 42: *profile_level_val =
860 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
861 case 51: *profile_level_val =
863 case 52: *profile_level_val =
868 switch (vtctx->
level) {
869 case 0: *profile_level_val =
870 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
871 case 50: *profile_level_val =
872 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
877 if (!*profile_level_val) {
892 CFStringRef *profile_level_val)
897 *profile_level_val =
NULL;
912 if (!*profile_level_val) {
923 int* av_pixel_format,
926 const char *range_name;
932 if (*av_pixel_format)
937 "Could not get pixel format for color format '%s' range '%s'.\n",
939 range_name ? range_name :
"Unknown");
948 CFDictionarySetValue(dict,
949 kCVImageBufferColorPrimariesKey,
954 CFDictionarySetValue(dict,
955 kCVImageBufferTransferFunctionKey,
960 CFDictionarySetValue(dict,
961 kCVImageBufferYCbCrMatrixKey,
967 CFMutableDictionaryRef* dict)
969 CFNumberRef cv_color_format_num =
NULL;
970 CFNumberRef width_num =
NULL;
971 CFNumberRef height_num =
NULL;
972 CFMutableDictionaryRef pixel_buffer_info =
NULL;
981 pixel_buffer_info = CFDictionaryCreateMutable(
984 &kCFCopyStringDictionaryKeyCallBacks,
985 &kCFTypeDictionaryValueCallBacks);
987 if (!pixel_buffer_info)
goto pbinfo_nomem;
989 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
992 if (!cv_color_format_num)
goto pbinfo_nomem;
994 CFDictionarySetValue(pixel_buffer_info,
995 kCVPixelBufferPixelFormatTypeKey,
996 cv_color_format_num);
999 width_num = CFNumberCreate(kCFAllocatorDefault,
1000 kCFNumberSInt32Type,
1002 if (!width_num)
goto pbinfo_nomem;
1004 CFDictionarySetValue(pixel_buffer_info,
1005 kCVPixelBufferWidthKey,
1009 height_num = CFNumberCreate(kCFAllocatorDefault,
1010 kCFNumberSInt32Type,
1012 if (!height_num)
goto pbinfo_nomem;
1014 CFDictionarySetValue(pixel_buffer_info,
1015 kCVPixelBufferHeightKey,
1021 *dict = pixel_buffer_info;
1028 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
1034 CFNumberRef *gamma_level)
1038 *gamma_level =
NULL;
1046 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1058 const char *print_option_name,
1064 if (
status == kVTPropertyNotSupportedErr) {
1067 "This device does not support the %s option. Value ignored.\n",
1069 }
else if (
status != 0) {
1072 "Error setting %s: Error %d\n",
1080 const char* print_option_name,
1082 CFNumberRef value_cfnum = CFNumberCreate(kCFAllocatorDefault,
1086 if (value_cfnum ==
NULL) {
1092 CFRelease(value_cfnum);
1099 CFStringRef profile_level,
1100 CFNumberRef gamma_level,
1101 CFDictionaryRef enc_info,
1102 CFDictionaryRef pixel_buffer_info,
1103 bool constant_bit_rate,
1104 VTCompressionSessionRef *session)
1110 CFNumberRef bit_rate_num;
1111 CFNumberRef quality_num;
1112 CFNumberRef bytes_per_second;
1113 CFNumberRef one_second;
1114 CFArrayRef data_rate_limits;
1115 int64_t bytes_per_second_value = 0;
1116 int64_t one_second_value = 0;
1119 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1125 kCFAllocatorDefault,
1133 #if !TARGET_OS_IPHONE
1135 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1142 #if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
1143 if (__builtin_available(macOS 10.13, *)) {
1144 status = VTCopySupportedPropertyDictionaryForEncoder(avctx->
width,
1160 CFStringRef encoderID =
NULL;
1162 kVTCompressionPropertyKey_EncoderID,
1163 kCFAllocatorDefault,
1166 CFIndex length = CFStringGetLength(encoderID);
1167 CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
1170 CFRelease(encoderID);
1174 CFStringGetCString(encoderID,
1177 kCFStringEncodingUTF8);
1182 if (encoderID !=
NULL)
1183 CFRelease(encoderID);
1187 av_log(avctx,
AV_LOG_ERROR,
"Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1193 quality_num = CFNumberCreate(kCFAllocatorDefault,
1194 kCFNumberFloat32Type,
1196 if (!quality_num)
return AVERROR(ENOMEM);
1199 kVTCompressionPropertyKey_Quality,
1201 CFRelease(quality_num);
1203 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1204 kCFNumberSInt32Type,
1206 if (!bit_rate_num)
return AVERROR(ENOMEM);
1208 if (constant_bit_rate) {
1210 compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1212 if (
status == kVTPropertyNotSupportedErr) {
1213 av_log(avctx,
AV_LOG_ERROR,
"Error: -constant_bit_rate true is not supported by the encoder.\n");
1218 kVTCompressionPropertyKey_AverageBitRate,
1222 CFRelease(bit_rate_num);
1232 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1233 vtctx->
prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1235 av_log(avctx,
AV_LOG_WARNING,
"PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1241 bytes_per_second_value = max_rate >> 3;
1242 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1243 kCFNumberSInt64Type,
1244 &bytes_per_second_value);
1245 if (!bytes_per_second) {
1248 one_second_value = 1;
1249 one_second = CFNumberCreate(kCFAllocatorDefault,
1250 kCFNumberSInt64Type,
1253 CFRelease(bytes_per_second);
1256 nums[0] = (
void *)bytes_per_second;
1257 nums[1] = (
void *)one_second;
1258 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1259 (
const void **)nums,
1261 &kCFTypeArrayCallBacks);
1263 if (!data_rate_limits) {
1264 CFRelease(bytes_per_second);
1265 CFRelease(one_second);
1269 kVTCompressionPropertyKey_DataRateLimits,
1272 CFRelease(bytes_per_second);
1273 CFRelease(one_second);
1274 CFRelease(data_rate_limits);
1288 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1289 kCFNumberDoubleType,
1291 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1294 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1296 CFRelease(alpha_quality_num);
1301 "Error setting alpha quality: %d\n",
1307 if (profile_level) {
1309 kVTCompressionPropertyKey_ProfileLevel,
1312 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n",
status);
1317 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1325 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1327 CFRelease(interval);
1337 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1340 if (
status == kVTPropertyNotSupportedErr) {
1341 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1349 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1352 if (
status == kVTPropertyNotSupportedErr) {
1353 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1362 CFMutableDictionaryRef par;
1369 num = CFNumberCreate(kCFAllocatorDefault,
1373 den = CFNumberCreate(kCFAllocatorDefault,
1379 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1381 &kCFCopyStringDictionaryKeyCallBacks,
1382 &kCFTypeDictionaryValueCallBacks);
1384 if (!par || !num || !den) {
1385 if (par) CFRelease(par);
1386 if (num) CFRelease(num);
1387 if (den) CFRelease(den);
1392 CFDictionarySetValue(
1394 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1397 CFDictionarySetValue(
1399 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1403 kVTCompressionPropertyKey_PixelAspectRatio,
1413 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1425 kVTCompressionPropertyKey_TransferFunction,
1436 kVTCompressionPropertyKey_YCbCrMatrix,
1447 kVTCompressionPropertyKey_ColorPrimaries,
1457 kCVImageBufferGammaLevelKey,
1467 kVTCompressionPropertyKey_AllowFrameReordering,
1482 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1493 vtctx->
realtime ? kCFBooleanTrue : kCFBooleanFalse);
1502 compat_keys.kVTCompressionPropertyKey_AllowOpenGOP,
1507 if (avctx->
qmin >= 0) {
1509 compat_keys.kVTCompressionPropertyKey_MinAllowedFrameQP,
1518 if (avctx->
qmax >= 0) {
1520 compat_keys.kVTCompressionPropertyKey_MaxAllowedFrameQP,
1531 kVTCompressionPropertyKey_MaxH264SliceBytes,
1542 compat_keys.kVTCompressionPropertyKey_MaximizePowerEfficiency,
1549 compat_keys.kVTCompressionPropertyKey_ReferenceBufferCount,
1558 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1569 CFMutableDictionaryRef enc_info;
1570 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1573 CFStringRef profile_level =
NULL;
1574 CFNumberRef gamma_level =
NULL;
1583 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1585 if (__builtin_available(macOS 10.10, *)) {
1586 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1598 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1603 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1618 enc_info = CFDictionaryCreateMutable(
1619 kCFAllocatorDefault,
1621 &kCFCopyStringDictionaryKeyCallBacks,
1622 &kCFTypeDictionaryValueCallBacks
1625 if (!enc_info)
return AVERROR(ENOMEM);
1627 #if !TARGET_OS_IPHONE
1629 CFDictionarySetValue(enc_info,
1630 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1633 CFDictionarySetValue(enc_info,
1634 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1637 CFDictionarySetValue(enc_info,
1638 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1645 CFDictionarySetValue(enc_info,
1646 compat_keys.kVTVideoEncoderSpecification_EnableLowLatencyRateControl,
1686 CFRelease(gamma_level);
1688 if (pixel_buffer_info)
1689 CFRelease(pixel_buffer_info);
1691 CFRelease(enc_info);
1699 CFBooleanRef has_b_frames_cfbool;
1714 kVTCompressionPropertyKey_AllowFrameReordering,
1715 kCFAllocatorDefault,
1716 &has_b_frames_cfbool);
1718 if (!
status && has_b_frames_cfbool) {
1721 if (CFBooleanGetValue(has_b_frames_cfbool))
1725 CFRelease(has_b_frames_cfbool);
1734 CFArrayRef attachments;
1735 CFDictionaryRef attachment;
1736 CFBooleanRef not_sync;
1739 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1740 len = !attachments ? 0 : CFArrayGetCount(attachments);
1743 *is_key_frame =
true;
1747 attachment = CFArrayGetValueAtIndex(attachments, 0);
1749 if (CFDictionaryGetValueIfPresent(attachment,
1750 kCMSampleAttachmentKey_NotSync,
1751 (
const void **)¬_sync))
1753 *is_key_frame = !CFBooleanGetValue(not_sync);
1755 *is_key_frame =
true;
1776 size_t sei_payload_size = 0;
1777 uint8_t *nal_start = nal_data;
1783 nal_type = *nal_data & 0x1F;
1790 if (nal_data[nal_size - 1] == 0x80)
1793 while (nal_size > 0 && *nal_data > 0) {
1797 }
while (nal_size > 0 && *nal_data == 0xFF);
1805 sei_payload_size += *nal_data;
1808 }
while (nal_size > 0 && *nal_data == 0xFF);
1810 if (nal_size < sei_payload_size) {
1815 nal_data += sei_payload_size;
1816 nal_size -= sei_payload_size;
1819 *sei_end = nal_data;
1821 return nal_data - nal_start + 1;
1841 uint8_t* dst_end = dst + dst_size;
1842 const uint8_t* src_end =
src + src_size;
1843 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1845 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1854 for (;
src < src_end;
src++, dst++) {
1856 int insert_ep3_byte = *
src <= 3;
1857 if (insert_ep3_byte) {
1875 wrote_bytes = dst - dst_start;
1878 return -wrote_bytes;
1888 uint8_t *sei_start = dst;
1889 size_t remaining_sei_size =
sei->size;
1890 size_t remaining_dst_size = dst_size;
1895 if (!remaining_dst_size)
1898 while (sei_type && remaining_dst_size != 0) {
1899 int sei_byte = sei_type > 255 ? 255 : sei_type;
1902 sei_type -= sei_byte;
1904 remaining_dst_size--;
1910 while (remaining_sei_size && remaining_dst_size != 0) {
1911 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1914 remaining_sei_size -= size_byte;
1916 remaining_dst_size--;
1919 if (remaining_dst_size < sei->
size)
1922 header_bytes = dst - sei_start;
1930 if (bytes_written < 0)
1933 bytes_written += header_bytes;
1934 return bytes_written;
1958 size_t length_code_size,
1959 CMSampleBufferRef sample_buffer,
1964 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1965 size_t remaining_src_size = src_size;
1966 size_t remaining_dst_size = dst_size;
1967 size_t src_offset = 0;
1970 uint8_t size_buf[4];
1972 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1974 if (length_code_size > 4) {
1978 while (remaining_src_size > 0) {
1979 size_t curr_src_len;
1980 size_t curr_dst_len;
1996 src_offset + length_code_size,
2007 for (
i = 0;
i < length_code_size;
i++) {
2009 box_len |= size_buf[
i];
2022 remaining_dst_size--;
2027 remaining_dst_size);
2029 if (wrote_bytes < 0)
2032 remaining_dst_size -= wrote_bytes;
2033 dst_data += wrote_bytes;
2035 if (remaining_dst_size <= 0)
2041 remaining_dst_size--;
2046 curr_src_len = box_len + length_code_size;
2049 if (remaining_src_size < curr_src_len) {
2053 if (remaining_dst_size < curr_dst_len) {
2061 src_offset + length_code_size,
2076 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
2077 if (old_sei_length < 0)
2083 remaining_dst_size - old_sei_length);
2084 if (wrote_bytes < 0)
2087 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
2090 new_sei[wrote_bytes++] = 0x80;
2091 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
2093 dst_data += extra_bytes;
2094 remaining_dst_size -= extra_bytes;
2099 src_offset += curr_src_len;
2100 dst_data += curr_dst_len;
2102 remaining_src_size -= curr_src_len;
2103 remaining_dst_size -= curr_dst_len;
2124 if ((
sei->size % 255) == 0)
2127 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
2132 CMSampleBufferRef sample_buffer,
2141 size_t length_code_size;
2142 size_t header_size = 0;
2144 size_t out_buf_size;
2145 size_t sei_nalu_size = 0;
2147 int64_t time_base_num;
2151 CMVideoFormatDescriptionRef vid_fmt;
2162 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2180 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
2183 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2184 out_buf_size = header_size +
2213 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2219 len = CMBlockBufferGetDataLength(buf);
2236 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2237 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2239 if (CMTIME_IS_INVALID(dts)) {
2251 pkt->
dts = dts.value / time_base_num - dts_delta;
2268 size_t *contiguous_buf_size)
2272 int av_format =
frame->format;
2273 int av_color_range =
frame->color_range;
2285 if (range_guessed) {
2290 "Color range not set for %s. Using MPEG range.\n",
2297 for (
i = 0;
i <
desc->nb_components;
i++) {
2298 int p =
desc->comp[
i].plane;
2300 bool isAlpha = hasAlpha && (p + 1 == *plane_count);
2301 bool isChroma = (p != 0) && !isAlpha;
2302 int shiftw = isChroma ?
desc->log2_chroma_w : 0;
2303 int shifth = isChroma ?
desc->log2_chroma_h : 0;
2304 widths[p] = (avctx->
width + ((1 << shiftw) >> 1)) >> shiftw;
2305 heights[p] = (avctx->
height + ((1 << shifth) >> 1)) >> shifth;
2306 strides[p] =
frame->linesize[p];
2309 *contiguous_buf_size = 0;
2310 for (
i = 0;
i < *plane_count;
i++) {
2311 if (
i < *plane_count - 1 &&
2312 frame->data[
i] + strides[
i] * heights[
i] !=
frame->data[
i + 1]) {
2313 *contiguous_buf_size = 0;
2317 *contiguous_buf_size += strides[
i] * heights[
i];
2326 CVPixelBufferRef cv_img,
2327 const size_t *plane_strides,
2328 const size_t *plane_rows)
2340 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2345 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2350 if (CVPixelBufferIsPlanar(cv_img)) {
2351 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2353 if (
i == plane_count) {
2354 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2357 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2363 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2364 src_addr = (uint8_t*)
frame->data[
i];
2365 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2366 src_stride = plane_strides[
i];
2367 rows = plane_rows[
i];
2369 if (dst_stride == src_stride) {
2370 memcpy(dst_addr, src_addr, src_stride * rows);
2372 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2374 for (j = 0; j < rows; j++) {
2375 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2380 if (
frame->data[1]) {
2381 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2384 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2390 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2391 src_addr = (uint8_t*)
frame->data[0];
2392 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2393 src_stride = plane_strides[0];
2394 rows = plane_rows[0];
2396 if (dst_stride == src_stride) {
2397 memcpy(dst_addr, src_addr, src_stride * rows);
2399 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2401 for (j = 0; j < rows; j++) {
2402 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2407 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2418 CVPixelBufferRef *cv_img)
2426 size_t contiguous_buf_size;
2427 CVPixelBufferPoolRef pix_buf_pool;
2433 *cv_img = (CVPixelBufferRef)
frame->data[3];
2440 memset(widths, 0,
sizeof(widths));
2441 memset(heights, 0,
sizeof(heights));
2442 memset(strides, 0,
sizeof(strides));
2452 &contiguous_buf_size
2459 "Error: Cannot convert format %d color_range %d: %d\n",
2468 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2469 if (!pix_buf_pool) {
2476 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2477 if (vtstatus == kVTInvalidSessionErr) {
2482 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2484 if (!pix_buf_pool) {
2490 "kVTInvalidSessionErr error.\n");
2493 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2514 CFDictionaryRef* dict_out)
2516 CFDictionaryRef dict =
NULL;
2518 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2519 const void *vals[] = { kCFBooleanTrue };
2521 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2522 if(!dict)
return AVERROR(ENOMEM);
2534 CFDictionaryRef frame_dict;
2535 CVPixelBufferRef cv_img =
NULL;
2550 if (vtctx->
a53_cc && side_data && side_data->
size) {
2566 status = VTCompressionSessionEncodeFrame(
2576 if (frame_dict) CFRelease(frame_dict);
2596 CMSampleBufferRef buf =
NULL;
2635 if (
status)
goto end_nopkt;
2636 if (!buf)
goto end_nopkt;
2644 if (
status)
goto end_nopkt;
2656 CFStringRef profile_level,
2657 CFNumberRef gamma_level,
2658 CFDictionaryRef enc_info,
2659 CFDictionaryRef pixel_buffer_info)
2663 CVPixelBufferPoolRef pool =
NULL;
2664 CVPixelBufferRef pix_buf =
NULL;
2666 CMSampleBufferRef buf =
NULL;
2679 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2686 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2690 if(
status != kCVReturnSuccess){
2708 "Error sending frame for extradata: %d\n",
2734 CVPixelBufferRelease(pix_buf);
2753 VTCompressionSessionCompleteFrames(vtctx->
session,
2783 #ifdef kCFCoreFoundationVersionNumber10_7
2788 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2791 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2794 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2797 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2800 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2803 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2806 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2813 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2814 #define COMMON_OPTIONS \
2815 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2816 { .i64 = 0 }, 0, 1, VE }, \
2817 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2818 { .i64 = 0 }, 0, 1, VE }, \
2819 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2820 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2821 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2822 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2823 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2824 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2825 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2826 { .i64 = -1 }, -1, 1, VE }, \
2827 { "power_efficient", "Set to 1 to enable more power-efficient encoding if supported.", \
2828 OFFSET(power_efficient), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2829 { "max_ref_frames", \
2830 "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.", \
2831 OFFSET(max_ref_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
2833 #define OFFSET(x) offsetof(VTEncContext, x)
2844 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2845 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2846 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2847 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2848 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2849 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2850 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2851 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2852 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2853 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2863 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2864 {
"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 },
2877 .
p.
name =
"h264_videotoolbox",
2896 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
2898 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2912 .
p.
name =
"hevc_videotoolbox",
2925 .p.wrapper_name =
"videotoolbox",
2950 .
p.
name =
"prores_videotoolbox",
2963 .p.wrapper_name =
"videotoolbox",