21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
43 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
47 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
51 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
56 #ifndef TARGET_CPU_ARM64
57 # define TARGET_CPU_ARM64 0
61 size_t parameterSetIndex,
62 const uint8_t **parameterSetPointerOut,
63 size_t *parameterSetSizeOut,
64 size_t *parameterSetCountOut,
65 int *NALUnitHeaderLengthOut);
135 #define GET_SYM(symbol, defaultVal) \
137 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
139 compat_keys.symbol = CFSTR(defaultVal); \
141 compat_keys.symbol = *handle; \
147 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
150 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
190 "TargetQualityForAlpha");
192 "PrioritizeEncodingSpeedOverQuality");
196 "EnableHardwareAcceleratedVideoEncoder");
198 "RequireHardwareAcceleratedVideoEncoder");
200 "EnableLowLatencyRateControl");
203 "MaximizePowerEfficiency");
205 "ReferenceBufferCount");
210 #define H264_PROFILE_CONSTRAINED_HIGH (AV_PROFILE_H264_HIGH | AV_PROFILE_H264_CONSTRAINED)
283 CFStringRef profile_level,
284 CFNumberRef gamma_level,
285 CFDictionaryRef enc_info,
286 CFDictionaryRef pixel_buffer_info);
313 CFRelease(
info->cm_buffer);
391 *buf =
info->cm_buffer;
394 }
else if (
info->sei) {
432 CMSampleBufferRef sample_buffer,
439 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
440 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
442 if (length_code_size > 4)
445 while (
offset < src_size) {
455 if (
status != kCMBlockBufferNoErr) {
459 for (
i = 0;
i < length_code_size;
i++) {
461 box_len |= size_buf[
i];
464 curr_src_len = box_len + length_code_size;
476 double alpha_quality)
489 return MKBETAG(
'a',
'p',
'c',
'o');
491 return MKBETAG(
'a',
'p',
'c',
's');
493 return MKBETAG(
'a',
'p',
'c',
'n');
495 return MKBETAG(
'a',
'p',
'c',
'h');
497 return MKBETAG(
'a',
'p',
'4',
'h');
499 return MKBETAG(
'a',
'p',
'4',
'x');
506 desc->log2_chroma_w == 0))
507 return MKBETAG(
'a',
'p',
'4',
'h');
509 return MKBETAG(
'a',
'p',
'c',
'n');
525 CMVideoFormatDescriptionRef vid_fmt,
529 size_t total_size = 0;
531 int is_count_bad = 0;
546 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
560 if (
i > 0 && is_count_bad)
status = 0;
579 CMVideoFormatDescriptionRef vid_fmt,
585 int is_count_bad = 0;
603 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
615 if (
i > 0 && is_count_bad)
status = 0;
621 if (dst_size < next_offset) {
629 memcpy(dst +
offset, ps, ps_size);
644 CMVideoFormatDescriptionRef vid_fmt;
648 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
674 CFDataRef
data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
675 if (
data && CFGetTypeID(
data) == CFDataGetTypeID()) {
676 CFIndex
size = CFDataGetLength(
data);
692 void *sourceFrameCtx,
694 VTEncodeInfoFlags
flags,
695 CMSampleBufferRef sample_buffer)
711 if (!sample_buffer) {
728 CMSampleBufferRef sample_buffer,
732 CMVideoFormatDescriptionRef vid_fmt;
736 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
764 CFStringRef *profile_level_val)
774 *profile_level_val =
NULL;
781 switch (vtctx->
level) {
782 case 0: *profile_level_val =
783 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
784 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
785 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
786 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
787 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
788 case 40: *profile_level_val =
789 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
790 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
791 case 42: *profile_level_val =
792 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
793 case 50: *profile_level_val =
794 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
795 case 51: *profile_level_val =
796 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
797 case 52: *profile_level_val =
798 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
803 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel;
805 if (vtctx->
level != 0) {
808 "Level is auto-selected when constrained-baseline "
809 "profile is used. The output may be encoded with a "
810 "different level.\n");
815 switch (vtctx->
level) {
816 case 0: *profile_level_val =
817 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
818 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
819 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
820 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
821 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
822 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
823 case 42: *profile_level_val =
825 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
826 case 51: *profile_level_val =
828 case 52: *profile_level_val =
834 *profile_level_val =
compat_keys.kVTProfileLevel_H264_ConstrainedHigh_AutoLevel;
836 if (vtctx->
level != 0) {
839 "Level is auto-selected when constrained-high profile "
840 "is used. The output may be encoded with a different "
846 switch (vtctx->
level) {
847 case 0: *profile_level_val =
848 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
849 case 30: *profile_level_val =
851 case 31: *profile_level_val =
853 case 32: *profile_level_val =
855 case 40: *profile_level_val =
857 case 41: *profile_level_val =
859 case 42: *profile_level_val =
861 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
862 case 51: *profile_level_val =
864 case 52: *profile_level_val =
869 switch (vtctx->
level) {
870 case 0: *profile_level_val =
871 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
872 case 50: *profile_level_val =
873 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
878 if (!*profile_level_val) {
893 CFStringRef *profile_level_val)
902 *profile_level_val =
NULL;
916 "main profile with %d bit input\n",
bit_depth);
923 "Invalid main10 profile with %d bit input\n",
bit_depth);
931 if (!*profile_level_val) {
942 int* av_pixel_format,
945 const char *range_name;
951 if (*av_pixel_format)
956 "Could not get pixel format for color format '%s' range '%s'.\n",
958 range_name ? range_name :
"Unknown");
967 CFDictionarySetValue(dict,
968 kCVImageBufferColorPrimariesKey,
973 CFDictionarySetValue(dict,
974 kCVImageBufferTransferFunctionKey,
979 CFDictionarySetValue(dict,
980 kCVImageBufferYCbCrMatrixKey,
986 CFMutableDictionaryRef* dict)
988 CFNumberRef cv_color_format_num =
NULL;
989 CFNumberRef width_num =
NULL;
990 CFNumberRef height_num =
NULL;
991 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1000 pixel_buffer_info = CFDictionaryCreateMutable(
1001 kCFAllocatorDefault,
1003 &kCFCopyStringDictionaryKeyCallBacks,
1004 &kCFTypeDictionaryValueCallBacks);
1006 if (!pixel_buffer_info)
goto pbinfo_nomem;
1008 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
1009 kCFNumberSInt32Type,
1011 if (!cv_color_format_num)
goto pbinfo_nomem;
1013 CFDictionarySetValue(pixel_buffer_info,
1014 kCVPixelBufferPixelFormatTypeKey,
1015 cv_color_format_num);
1018 width_num = CFNumberCreate(kCFAllocatorDefault,
1019 kCFNumberSInt32Type,
1021 if (!width_num)
goto pbinfo_nomem;
1023 CFDictionarySetValue(pixel_buffer_info,
1024 kCVPixelBufferWidthKey,
1028 height_num = CFNumberCreate(kCFAllocatorDefault,
1029 kCFNumberSInt32Type,
1031 if (!height_num)
goto pbinfo_nomem;
1033 CFDictionarySetValue(pixel_buffer_info,
1034 kCVPixelBufferHeightKey,
1040 *dict = pixel_buffer_info;
1047 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
1053 CFNumberRef *gamma_level)
1057 *gamma_level =
NULL;
1065 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1077 const char *print_option_name,
1083 if (
status == kVTPropertyNotSupportedErr) {
1086 "This device does not support the %s option. Value ignored.\n",
1088 }
else if (
status != 0) {
1091 "Error setting %s: Error %d\n",
1099 const char* print_option_name,
1101 CFNumberRef value_cfnum = CFNumberCreate(kCFAllocatorDefault,
1105 if (value_cfnum ==
NULL) {
1111 CFRelease(value_cfnum);
1118 CFStringRef profile_level,
1119 CFNumberRef gamma_level,
1120 CFDictionaryRef enc_info,
1121 CFDictionaryRef pixel_buffer_info,
1122 bool constant_bit_rate,
1123 VTCompressionSessionRef *session)
1129 CFNumberRef bit_rate_num;
1130 CFNumberRef quality_num;
1131 CFNumberRef bytes_per_second;
1132 CFNumberRef one_second;
1133 CFArrayRef data_rate_limits;
1134 int64_t bytes_per_second_value = 0;
1135 int64_t one_second_value = 0;
1138 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1144 kCFAllocatorDefault,
1152 #if !TARGET_OS_IPHONE
1154 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1161 #if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
1162 if (__builtin_available(macOS 10.13, *)) {
1163 status = VTCopySupportedPropertyDictionaryForEncoder(avctx->
width,
1179 CFStringRef encoderID =
NULL;
1181 kVTCompressionPropertyKey_EncoderID,
1182 kCFAllocatorDefault,
1185 CFIndex length = CFStringGetLength(encoderID);
1186 CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
1189 CFRelease(encoderID);
1193 CFStringGetCString(encoderID,
1196 kCFStringEncodingUTF8);
1201 if (encoderID !=
NULL)
1202 CFRelease(encoderID);
1206 av_log(avctx,
AV_LOG_ERROR,
"Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1212 quality_num = CFNumberCreate(kCFAllocatorDefault,
1213 kCFNumberFloat32Type,
1215 if (!quality_num)
return AVERROR(ENOMEM);
1218 kVTCompressionPropertyKey_Quality,
1220 CFRelease(quality_num);
1222 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1223 kCFNumberSInt32Type,
1225 if (!bit_rate_num)
return AVERROR(ENOMEM);
1227 if (constant_bit_rate) {
1229 compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1231 if (
status == kVTPropertyNotSupportedErr) {
1232 av_log(avctx,
AV_LOG_ERROR,
"Error: -constant_bit_rate true is not supported by the encoder.\n");
1237 kVTCompressionPropertyKey_AverageBitRate,
1241 CFRelease(bit_rate_num);
1251 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1252 vtctx->
prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1254 av_log(avctx,
AV_LOG_WARNING,
"PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1260 bytes_per_second_value = max_rate >> 3;
1261 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1262 kCFNumberSInt64Type,
1263 &bytes_per_second_value);
1264 if (!bytes_per_second) {
1267 one_second_value = 1;
1268 one_second = CFNumberCreate(kCFAllocatorDefault,
1269 kCFNumberSInt64Type,
1272 CFRelease(bytes_per_second);
1275 nums[0] = (
void *)bytes_per_second;
1276 nums[1] = (
void *)one_second;
1277 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1278 (
const void **)nums,
1280 &kCFTypeArrayCallBacks);
1282 if (!data_rate_limits) {
1283 CFRelease(bytes_per_second);
1284 CFRelease(one_second);
1288 kVTCompressionPropertyKey_DataRateLimits,
1291 CFRelease(bytes_per_second);
1292 CFRelease(one_second);
1293 CFRelease(data_rate_limits);
1307 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1308 kCFNumberDoubleType,
1310 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1313 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1315 CFRelease(alpha_quality_num);
1320 "Error setting alpha quality: %d\n",
1326 if (profile_level) {
1328 kVTCompressionPropertyKey_ProfileLevel,
1331 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n",
status);
1336 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1344 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1346 CFRelease(interval);
1356 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1359 if (
status == kVTPropertyNotSupportedErr) {
1360 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1368 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1371 if (
status == kVTPropertyNotSupportedErr) {
1372 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1381 CFMutableDictionaryRef par;
1388 num = CFNumberCreate(kCFAllocatorDefault,
1392 den = CFNumberCreate(kCFAllocatorDefault,
1398 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1400 &kCFCopyStringDictionaryKeyCallBacks,
1401 &kCFTypeDictionaryValueCallBacks);
1403 if (!par || !num || !den) {
1404 if (par) CFRelease(par);
1405 if (num) CFRelease(num);
1406 if (den) CFRelease(den);
1411 CFDictionarySetValue(
1413 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1416 CFDictionarySetValue(
1418 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1422 kVTCompressionPropertyKey_PixelAspectRatio,
1432 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1444 kVTCompressionPropertyKey_TransferFunction,
1455 kVTCompressionPropertyKey_YCbCrMatrix,
1466 kVTCompressionPropertyKey_ColorPrimaries,
1476 kCVImageBufferGammaLevelKey,
1486 kVTCompressionPropertyKey_AllowFrameReordering,
1501 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1512 vtctx->
realtime ? kCFBooleanTrue : kCFBooleanFalse);
1521 compat_keys.kVTCompressionPropertyKey_AllowOpenGOP,
1526 if (avctx->
qmin >= 0) {
1528 compat_keys.kVTCompressionPropertyKey_MinAllowedFrameQP,
1537 if (avctx->
qmax >= 0) {
1539 compat_keys.kVTCompressionPropertyKey_MaxAllowedFrameQP,
1550 kVTCompressionPropertyKey_MaxH264SliceBytes,
1561 compat_keys.kVTCompressionPropertyKey_MaximizePowerEfficiency,
1568 compat_keys.kVTCompressionPropertyKey_ReferenceBufferCount,
1577 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1588 CFMutableDictionaryRef enc_info;
1589 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1592 CFStringRef profile_level =
NULL;
1593 CFNumberRef gamma_level =
NULL;
1602 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1604 if (__builtin_available(macOS 10.10, *)) {
1605 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1617 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1622 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1637 enc_info = CFDictionaryCreateMutable(
1638 kCFAllocatorDefault,
1640 &kCFCopyStringDictionaryKeyCallBacks,
1641 &kCFTypeDictionaryValueCallBacks
1644 if (!enc_info)
return AVERROR(ENOMEM);
1646 #if !TARGET_OS_IPHONE
1648 CFDictionarySetValue(enc_info,
1649 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1652 CFDictionarySetValue(enc_info,
1653 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1656 CFDictionarySetValue(enc_info,
1657 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1664 CFDictionarySetValue(enc_info,
1665 compat_keys.kVTVideoEncoderSpecification_EnableLowLatencyRateControl,
1705 CFRelease(gamma_level);
1707 if (pixel_buffer_info)
1708 CFRelease(pixel_buffer_info);
1710 CFRelease(enc_info);
1718 CFBooleanRef has_b_frames_cfbool;
1733 kVTCompressionPropertyKey_AllowFrameReordering,
1734 kCFAllocatorDefault,
1735 &has_b_frames_cfbool);
1737 if (!
status && has_b_frames_cfbool) {
1740 if (CFBooleanGetValue(has_b_frames_cfbool))
1744 CFRelease(has_b_frames_cfbool);
1753 CFArrayRef attachments;
1754 CFDictionaryRef attachment;
1755 CFBooleanRef not_sync;
1758 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1759 len = !attachments ? 0 : CFArrayGetCount(attachments);
1762 *is_key_frame =
true;
1766 attachment = CFArrayGetValueAtIndex(attachments, 0);
1768 if (CFDictionaryGetValueIfPresent(attachment,
1769 kCMSampleAttachmentKey_NotSync,
1770 (
const void **)¬_sync))
1772 *is_key_frame = !CFBooleanGetValue(not_sync);
1774 *is_key_frame =
true;
1795 size_t sei_payload_size = 0;
1796 uint8_t *nal_start = nal_data;
1802 nal_type = *nal_data & 0x1F;
1809 if (nal_data[nal_size - 1] == 0x80)
1812 while (nal_size > 0 && *nal_data > 0) {
1816 }
while (nal_size > 0 && *nal_data == 0xFF);
1824 sei_payload_size += *nal_data;
1827 }
while (nal_size > 0 && *nal_data == 0xFF);
1829 if (nal_size < sei_payload_size) {
1834 nal_data += sei_payload_size;
1835 nal_size -= sei_payload_size;
1838 *sei_end = nal_data;
1840 return nal_data - nal_start + 1;
1860 uint8_t* dst_end = dst + dst_size;
1861 const uint8_t* src_end =
src + src_size;
1862 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1864 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1873 for (;
src < src_end;
src++, dst++) {
1875 int insert_ep3_byte = *
src <= 3;
1876 if (insert_ep3_byte) {
1894 wrote_bytes = dst - dst_start;
1897 return -wrote_bytes;
1907 uint8_t *sei_start = dst;
1908 size_t remaining_sei_size =
sei->size;
1909 size_t remaining_dst_size = dst_size;
1914 if (!remaining_dst_size)
1917 while (sei_type && remaining_dst_size != 0) {
1918 int sei_byte = sei_type > 255 ? 255 : sei_type;
1921 sei_type -= sei_byte;
1923 remaining_dst_size--;
1929 while (remaining_sei_size && remaining_dst_size != 0) {
1930 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1933 remaining_sei_size -= size_byte;
1935 remaining_dst_size--;
1938 if (remaining_dst_size < sei->
size)
1941 header_bytes = dst - sei_start;
1949 if (bytes_written < 0)
1952 bytes_written += header_bytes;
1953 return bytes_written;
1977 size_t length_code_size,
1978 CMSampleBufferRef sample_buffer,
1983 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1984 size_t remaining_src_size = src_size;
1985 size_t remaining_dst_size = dst_size;
1986 size_t src_offset = 0;
1989 uint8_t size_buf[4];
1991 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1993 if (length_code_size > 4) {
1997 while (remaining_src_size > 0) {
1998 size_t curr_src_len;
1999 size_t curr_dst_len;
2015 src_offset + length_code_size,
2026 for (
i = 0;
i < length_code_size;
i++) {
2028 box_len |= size_buf[
i];
2041 remaining_dst_size--;
2046 remaining_dst_size);
2048 if (wrote_bytes < 0)
2051 remaining_dst_size -= wrote_bytes;
2052 dst_data += wrote_bytes;
2054 if (remaining_dst_size <= 0)
2060 remaining_dst_size--;
2065 curr_src_len = box_len + length_code_size;
2068 if (remaining_src_size < curr_src_len) {
2072 if (remaining_dst_size < curr_dst_len) {
2080 src_offset + length_code_size,
2095 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
2096 if (old_sei_length < 0)
2102 remaining_dst_size - old_sei_length);
2103 if (wrote_bytes < 0)
2106 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
2109 new_sei[wrote_bytes++] = 0x80;
2110 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
2112 dst_data += extra_bytes;
2113 remaining_dst_size -= extra_bytes;
2118 src_offset += curr_src_len;
2119 dst_data += curr_dst_len;
2121 remaining_src_size -= curr_src_len;
2122 remaining_dst_size -= curr_dst_len;
2143 if ((
sei->size % 255) == 0)
2146 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
2151 CMSampleBufferRef sample_buffer,
2160 size_t length_code_size;
2161 size_t header_size = 0;
2163 size_t out_buf_size;
2164 size_t sei_nalu_size = 0;
2166 int64_t time_base_num;
2170 CMVideoFormatDescriptionRef vid_fmt;
2181 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2199 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
2202 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2203 out_buf_size = header_size +
2232 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2238 len = CMBlockBufferGetDataLength(buf);
2255 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2256 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2258 if (CMTIME_IS_INVALID(dts)) {
2270 pkt->
dts = dts.value / time_base_num - dts_delta;
2287 size_t *contiguous_buf_size)
2304 if (range_guessed) {
2309 "Color range not set for %s. Using MPEG range.\n",
2316 for (
i = 0;
i <
desc->nb_components;
i++) {
2317 int p =
desc->comp[
i].plane;
2319 bool isAlpha = hasAlpha && (p + 1 == *plane_count);
2320 bool isChroma = (p != 0) && !isAlpha;
2321 int shiftw = isChroma ?
desc->log2_chroma_w : 0;
2322 int shifth = isChroma ?
desc->log2_chroma_h : 0;
2323 widths[p] = (avctx->
width + ((1 << shiftw) >> 1)) >> shiftw;
2324 heights[p] = (avctx->
height + ((1 << shifth) >> 1)) >> shifth;
2328 *contiguous_buf_size = 0;
2329 for (
i = 0;
i < *plane_count;
i++) {
2330 if (
i < *plane_count - 1 &&
2332 *contiguous_buf_size = 0;
2336 *contiguous_buf_size += strides[
i] * heights[
i];
2345 CVPixelBufferRef cv_img,
2346 const size_t *plane_strides,
2347 const size_t *plane_rows)
2359 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2364 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2369 if (CVPixelBufferIsPlanar(cv_img)) {
2370 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2372 if (
i == plane_count) {
2373 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2376 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2382 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2384 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2385 src_stride = plane_strides[
i];
2386 rows = plane_rows[
i];
2388 if (dst_stride == src_stride) {
2389 memcpy(dst_addr, src_addr, src_stride * rows);
2391 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2393 for (j = 0; j < rows; j++) {
2394 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2400 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2403 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2409 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2411 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2412 src_stride = plane_strides[0];
2413 rows = plane_rows[0];
2415 if (dst_stride == src_stride) {
2416 memcpy(dst_addr, src_addr, src_stride * rows);
2418 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2420 for (j = 0; j < rows; j++) {
2421 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2426 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2437 CVPixelBufferRef *cv_img)
2445 size_t contiguous_buf_size;
2446 CVPixelBufferPoolRef pix_buf_pool;
2452 *cv_img = (CVPixelBufferRef)
frame->
data[3];
2459 memset(widths, 0,
sizeof(widths));
2460 memset(heights, 0,
sizeof(heights));
2461 memset(strides, 0,
sizeof(strides));
2471 &contiguous_buf_size
2478 "Error: Cannot convert format %d color_range %d: %d\n",
2487 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2488 if (!pix_buf_pool) {
2495 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2496 if (vtstatus == kVTInvalidSessionErr) {
2501 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2503 if (!pix_buf_pool) {
2509 "kVTInvalidSessionErr error.\n");
2512 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2533 CFDictionaryRef* dict_out)
2535 CFDictionaryRef dict =
NULL;
2537 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2538 const void *vals[] = { kCFBooleanTrue };
2540 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2541 if(!dict)
return AVERROR(ENOMEM);
2553 CFDictionaryRef frame_dict;
2554 CVPixelBufferRef cv_img =
NULL;
2569 if (vtctx->
a53_cc && side_data && side_data->
size) {
2585 status = VTCompressionSessionEncodeFrame(
2595 if (frame_dict) CFRelease(frame_dict);
2615 CMSampleBufferRef buf =
NULL;
2654 if (
status)
goto end_nopkt;
2655 if (!buf)
goto end_nopkt;
2663 if (
status)
goto end_nopkt;
2675 CFStringRef profile_level,
2676 CFNumberRef gamma_level,
2677 CFDictionaryRef enc_info,
2678 CFDictionaryRef pixel_buffer_info)
2682 CVPixelBufferPoolRef pool =
NULL;
2683 CVPixelBufferRef pix_buf =
NULL;
2685 CMSampleBufferRef buf =
NULL;
2698 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2705 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2709 if(
status != kCVReturnSuccess){
2727 "Error sending frame for extradata: %d\n",
2753 CVPixelBufferRelease(pix_buf);
2772 VTCompressionSessionCompleteFrames(vtctx->
session,
2802 #ifdef kCFCoreFoundationVersionNumber10_7
2807 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2810 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2813 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2816 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2819 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2822 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2825 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2832 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2833 #define COMMON_OPTIONS \
2834 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2835 { .i64 = 0 }, 0, 1, VE }, \
2836 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2837 { .i64 = 0 }, 0, 1, VE }, \
2838 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2839 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2840 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2841 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2842 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2843 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2844 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2845 { .i64 = -1 }, -1, 1, VE }, \
2846 { "power_efficient", "Set to 1 to enable more power-efficient encoding if supported.", \
2847 OFFSET(power_efficient), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2848 { "max_ref_frames", \
2849 "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.", \
2850 OFFSET(max_ref_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
2857 #define OFFSET(x) offsetof(VTEncContext, x)
2868 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2869 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2870 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2871 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2872 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2873 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2874 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2875 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2876 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2877 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2887 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2888 {
"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 },
2901 .
p.
name =
"h264_videotoolbox",
2921 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
2923 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2937 .
p.
name =
"hevc_videotoolbox",
2950 .p.wrapper_name =
"videotoolbox",
2976 .
p.
name =
"prores_videotoolbox",
2989 .p.wrapper_name =
"videotoolbox",