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);
112 #define GET_SYM(symbol, defaultVal) \
114 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
116 compat_keys.symbol = CFSTR(defaultVal); \
118 compat_keys.symbol = *handle; \
124 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
127 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
165 "TargetQualityForAlpha");
167 "PrioritizeEncodingSpeedOverQuality");
171 "EnableHardwareAcceleratedVideoEncoder");
173 "RequireHardwareAcceleratedVideoEncoder");
258 CFStringRef profile_level,
259 CFNumberRef gamma_level,
260 CFDictionaryRef enc_info,
261 CFDictionaryRef pixel_buffer_info);
288 CFRelease(
info->cm_buffer);
338 *buf =
info->cm_buffer;
341 }
else if (
info->sei) {
379 CMSampleBufferRef sample_buffer,
386 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
387 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
389 if (length_code_size > 4)
392 while (
offset < src_size) {
402 if (
status != kCMBlockBufferNoErr) {
406 for (
i = 0;
i < length_code_size;
i++) {
408 box_len |= size_buf[
i];
411 curr_src_len = box_len + length_code_size;
423 double alpha_quality)
436 return MKBETAG(
'a',
'p',
'c',
'o');
438 return MKBETAG(
'a',
'p',
'c',
's');
440 return MKBETAG(
'a',
'p',
'c',
'n');
442 return MKBETAG(
'a',
'p',
'c',
'h');
444 return MKBETAG(
'a',
'p',
'4',
'h');
446 return MKBETAG(
'a',
'p',
'4',
'x');
453 desc->log2_chroma_w == 0))
454 return MKBETAG(
'a',
'p',
'4',
'h');
456 return MKBETAG(
'a',
'p',
'c',
'n');
472 CMVideoFormatDescriptionRef vid_fmt,
476 size_t total_size = 0;
478 int is_count_bad = 0;
493 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
507 if (
i > 0 && is_count_bad)
status = 0;
526 CMVideoFormatDescriptionRef vid_fmt,
532 int is_count_bad = 0;
550 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
562 if (
i > 0 && is_count_bad)
status = 0;
568 if (dst_size < next_offset) {
576 memcpy(dst +
offset, ps, ps_size);
591 CMVideoFormatDescriptionRef vid_fmt;
595 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
621 CFDataRef
data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
622 if (
data && CFGetTypeID(
data) == CFDataGetTypeID()) {
623 CFIndex
size = CFDataGetLength(
data);
639 void *sourceFrameCtx,
641 VTEncodeInfoFlags
flags,
642 CMSampleBufferRef sample_buffer)
658 if (!sample_buffer) {
675 CMSampleBufferRef sample_buffer,
679 CMVideoFormatDescriptionRef vid_fmt;
683 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
711 CFStringRef *profile_level_val)
721 *profile_level_val =
NULL;
728 switch (vtctx->
level) {
729 case 0: *profile_level_val =
730 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
731 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
732 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
733 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
734 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
735 case 40: *profile_level_val =
736 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
737 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
738 case 42: *profile_level_val =
739 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
740 case 50: *profile_level_val =
741 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
742 case 51: *profile_level_val =
743 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
744 case 52: *profile_level_val =
745 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
750 switch (vtctx->
level) {
751 case 0: *profile_level_val =
752 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
753 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
754 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
755 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
756 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
757 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
758 case 42: *profile_level_val =
760 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
761 case 51: *profile_level_val =
763 case 52: *profile_level_val =
769 switch (vtctx->
level) {
770 case 0: *profile_level_val =
771 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
772 case 30: *profile_level_val =
774 case 31: *profile_level_val =
776 case 32: *profile_level_val =
778 case 40: *profile_level_val =
780 case 41: *profile_level_val =
782 case 42: *profile_level_val =
784 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
785 case 51: *profile_level_val =
787 case 52: *profile_level_val =
792 switch (vtctx->
level) {
793 case 0: *profile_level_val =
794 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
795 case 50: *profile_level_val =
796 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
801 if (!*profile_level_val) {
816 CFStringRef *profile_level_val)
821 *profile_level_val =
NULL;
836 if (!*profile_level_val) {
847 int* av_pixel_format,
850 const char *range_name;
856 if (*av_pixel_format)
861 "Could not get pixel format for color format '%s' range '%s'.\n",
863 range_name ? range_name :
"Unknown");
872 CFDictionarySetValue(dict,
873 kCVImageBufferColorPrimariesKey,
878 CFDictionarySetValue(dict,
879 kCVImageBufferTransferFunctionKey,
884 CFDictionarySetValue(dict,
885 kCVImageBufferYCbCrMatrixKey,
891 CFMutableDictionaryRef* dict)
893 CFNumberRef cv_color_format_num =
NULL;
894 CFNumberRef width_num =
NULL;
895 CFNumberRef height_num =
NULL;
896 CFMutableDictionaryRef pixel_buffer_info =
NULL;
905 pixel_buffer_info = CFDictionaryCreateMutable(
908 &kCFCopyStringDictionaryKeyCallBacks,
909 &kCFTypeDictionaryValueCallBacks);
911 if (!pixel_buffer_info)
goto pbinfo_nomem;
913 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
916 if (!cv_color_format_num)
goto pbinfo_nomem;
918 CFDictionarySetValue(pixel_buffer_info,
919 kCVPixelBufferPixelFormatTypeKey,
920 cv_color_format_num);
923 width_num = CFNumberCreate(kCFAllocatorDefault,
926 if (!width_num)
goto pbinfo_nomem;
928 CFDictionarySetValue(pixel_buffer_info,
929 kCVPixelBufferWidthKey,
933 height_num = CFNumberCreate(kCFAllocatorDefault,
936 if (!height_num)
goto pbinfo_nomem;
938 CFDictionarySetValue(pixel_buffer_info,
939 kCVPixelBufferHeightKey,
945 *dict = pixel_buffer_info;
952 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
958 CFStringRef *primaries)
967 *primaries = kCVImageBufferColorPrimaries_EBU_3213;
971 *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
975 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
979 *primaries =
compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
992 CFStringRef *transfer_fnc,
993 CFNumberRef *gamma_level)
1001 *transfer_fnc =
NULL;
1005 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
1009 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
1012 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ
1014 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
1017 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR
1019 *transfer_fnc = kCVImageBufferTransferFunction_Linear;
1022 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG
1024 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
1030 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
1031 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1036 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
1037 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1042 *transfer_fnc =
compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
1046 *transfer_fnc =
NULL;
1057 *
matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
1067 *
matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1071 *
matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1094 CFStringRef profile_level,
1095 CFNumberRef gamma_level,
1096 CFDictionaryRef enc_info,
1097 CFDictionaryRef pixel_buffer_info,
1098 bool constant_bit_rate,
1099 VTCompressionSessionRef *session)
1105 CFNumberRef bit_rate_num;
1106 CFNumberRef quality_num;
1107 CFNumberRef bytes_per_second;
1108 CFNumberRef one_second;
1109 CFArrayRef data_rate_limits;
1110 int64_t bytes_per_second_value = 0;
1111 int64_t one_second_value = 0;
1114 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1120 kCFAllocatorDefault,
1128 #if !TARGET_OS_IPHONE
1130 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1138 av_log(avctx,
AV_LOG_ERROR,
"Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1144 quality_num = CFNumberCreate(kCFAllocatorDefault,
1145 kCFNumberFloat32Type,
1147 if (!quality_num)
return AVERROR(ENOMEM);
1150 kVTCompressionPropertyKey_Quality,
1152 CFRelease(quality_num);
1154 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1155 kCFNumberSInt32Type,
1157 if (!bit_rate_num)
return AVERROR(ENOMEM);
1159 if (constant_bit_rate) {
1161 compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1163 if (
status == kVTPropertyNotSupportedErr) {
1164 av_log(avctx,
AV_LOG_ERROR,
"Error: -constant_bit_rate true is not supported by the encoder.\n");
1169 kVTCompressionPropertyKey_AverageBitRate,
1173 CFRelease(bit_rate_num);
1183 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1184 vtctx->
prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1186 av_log(avctx,
AV_LOG_WARNING,
"PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1192 bytes_per_second_value = max_rate >> 3;
1193 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1194 kCFNumberSInt64Type,
1195 &bytes_per_second_value);
1196 if (!bytes_per_second) {
1199 one_second_value = 1;
1200 one_second = CFNumberCreate(kCFAllocatorDefault,
1201 kCFNumberSInt64Type,
1204 CFRelease(bytes_per_second);
1207 nums[0] = (
void *)bytes_per_second;
1208 nums[1] = (
void *)one_second;
1209 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1210 (
const void **)nums,
1212 &kCFTypeArrayCallBacks);
1214 if (!data_rate_limits) {
1215 CFRelease(bytes_per_second);
1216 CFRelease(one_second);
1220 kVTCompressionPropertyKey_DataRateLimits,
1223 CFRelease(bytes_per_second);
1224 CFRelease(one_second);
1225 CFRelease(data_rate_limits);
1239 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1240 kCFNumberDoubleType,
1242 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1245 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1247 CFRelease(alpha_quality_num);
1251 if (profile_level) {
1253 kVTCompressionPropertyKey_ProfileLevel,
1256 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n",
status);
1261 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1269 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1271 CFRelease(interval);
1281 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1284 if (
status == kVTPropertyNotSupportedErr) {
1285 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1293 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1296 if (
status == kVTPropertyNotSupportedErr) {
1297 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1306 CFMutableDictionaryRef par;
1313 num = CFNumberCreate(kCFAllocatorDefault,
1317 den = CFNumberCreate(kCFAllocatorDefault,
1323 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1325 &kCFCopyStringDictionaryKeyCallBacks,
1326 &kCFTypeDictionaryValueCallBacks);
1328 if (!par || !num || !den) {
1329 if (par) CFRelease(par);
1330 if (num) CFRelease(num);
1331 if (den) CFRelease(den);
1336 CFDictionarySetValue(
1338 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1341 CFDictionarySetValue(
1343 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1347 kVTCompressionPropertyKey_PixelAspectRatio,
1357 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1369 kVTCompressionPropertyKey_TransferFunction,
1380 kVTCompressionPropertyKey_YCbCrMatrix,
1391 kVTCompressionPropertyKey_ColorPrimaries,
1401 kCVImageBufferGammaLevelKey,
1411 kVTCompressionPropertyKey_AllowFrameReordering,
1426 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1437 vtctx->
realtime ? kCFBooleanTrue : kCFBooleanFalse);
1444 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1455 CFMutableDictionaryRef enc_info;
1456 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1459 CFStringRef profile_level =
NULL;
1460 CFNumberRef gamma_level =
NULL;
1469 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1471 if (__builtin_available(macOS 10.10, *)) {
1472 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1484 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1489 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1504 enc_info = CFDictionaryCreateMutable(
1505 kCFAllocatorDefault,
1507 &kCFCopyStringDictionaryKeyCallBacks,
1508 &kCFTypeDictionaryValueCallBacks
1511 if (!enc_info)
return AVERROR(ENOMEM);
1513 #if !TARGET_OS_IPHONE
1515 CFDictionarySetValue(enc_info,
1516 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1519 CFDictionarySetValue(enc_info,
1520 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1523 CFDictionarySetValue(enc_info,
1524 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1564 CFRelease(gamma_level);
1566 if (pixel_buffer_info)
1567 CFRelease(pixel_buffer_info);
1569 CFRelease(enc_info);
1577 CFBooleanRef has_b_frames_cfbool;
1590 kVTCompressionPropertyKey_AllowFrameReordering,
1591 kCFAllocatorDefault,
1592 &has_b_frames_cfbool);
1594 if (!
status && has_b_frames_cfbool) {
1597 if (CFBooleanGetValue(has_b_frames_cfbool))
1601 CFRelease(has_b_frames_cfbool);
1610 CFArrayRef attachments;
1611 CFDictionaryRef attachment;
1612 CFBooleanRef not_sync;
1615 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1616 len = !attachments ? 0 : CFArrayGetCount(attachments);
1619 *is_key_frame =
true;
1623 attachment = CFArrayGetValueAtIndex(attachments, 0);
1625 if (CFDictionaryGetValueIfPresent(attachment,
1626 kCMSampleAttachmentKey_NotSync,
1627 (
const void **)¬_sync))
1629 *is_key_frame = !CFBooleanGetValue(not_sync);
1631 *is_key_frame =
true;
1652 size_t sei_payload_size = 0;
1654 uint8_t *nal_start = nal_data;
1659 nal_type = *nal_data & 0x1F;
1666 if (nal_data[nal_size - 1] == 0x80)
1669 while (nal_size > 0 && *nal_data > 0) {
1673 }
while (nal_size > 0 && *nal_data == 0xFF);
1681 sei_payload_size += *nal_data;
1684 }
while (nal_size > 0 && *nal_data == 0xFF);
1686 if (nal_size < sei_payload_size) {
1691 nal_data += sei_payload_size;
1692 nal_size -= sei_payload_size;
1695 *sei_end = nal_data;
1697 return nal_data - nal_start + 1;
1717 uint8_t* dst_end = dst + dst_size;
1718 const uint8_t* src_end =
src + src_size;
1719 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1721 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1730 for (;
src < src_end;
src++, dst++) {
1732 int insert_ep3_byte = *
src <= 3;
1733 if (insert_ep3_byte) {
1751 wrote_bytes = dst - dst_start;
1754 return -wrote_bytes;
1764 uint8_t *sei_start = dst;
1765 size_t remaining_sei_size =
sei->size;
1766 size_t remaining_dst_size = dst_size;
1771 if (!remaining_dst_size)
1774 while (sei_type && remaining_dst_size != 0) {
1775 int sei_byte = sei_type > 255 ? 255 : sei_type;
1778 sei_type -= sei_byte;
1780 remaining_dst_size--;
1786 while (remaining_sei_size && remaining_dst_size != 0) {
1787 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1790 remaining_sei_size -= size_byte;
1792 remaining_dst_size--;
1795 if (remaining_dst_size < sei->
size)
1798 header_bytes = dst - sei_start;
1806 if (bytes_written < 0)
1809 bytes_written += header_bytes;
1810 return bytes_written;
1834 size_t length_code_size,
1835 CMSampleBufferRef sample_buffer,
1840 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1841 size_t remaining_src_size = src_size;
1842 size_t remaining_dst_size = dst_size;
1843 size_t src_offset = 0;
1846 uint8_t size_buf[4];
1848 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1850 if (length_code_size > 4) {
1854 while (remaining_src_size > 0) {
1855 size_t curr_src_len;
1856 size_t curr_dst_len;
1872 src_offset + length_code_size,
1883 for (
i = 0;
i < length_code_size;
i++) {
1885 box_len |= size_buf[
i];
1898 remaining_dst_size--;
1903 remaining_dst_size);
1905 if (wrote_bytes < 0)
1908 remaining_dst_size -= wrote_bytes;
1909 dst_data += wrote_bytes;
1911 if (remaining_dst_size <= 0)
1917 remaining_dst_size--;
1922 curr_src_len = box_len + length_code_size;
1925 if (remaining_src_size < curr_src_len) {
1929 if (remaining_dst_size < curr_dst_len) {
1937 src_offset + length_code_size,
1952 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1953 if (old_sei_length < 0)
1959 remaining_dst_size - old_sei_length);
1960 if (wrote_bytes < 0)
1963 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1966 new_sei[wrote_bytes++] = 0x80;
1967 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1969 dst_data += extra_bytes;
1970 remaining_dst_size -= extra_bytes;
1975 src_offset += curr_src_len;
1976 dst_data += curr_dst_len;
1978 remaining_src_size -= curr_src_len;
1979 remaining_dst_size -= curr_dst_len;
2000 if ((
sei->size % 255) == 0)
2003 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
2008 CMSampleBufferRef sample_buffer,
2017 size_t length_code_size;
2018 size_t header_size = 0;
2020 size_t out_buf_size;
2021 size_t sei_nalu_size = 0;
2023 int64_t time_base_num;
2027 CMVideoFormatDescriptionRef vid_fmt;
2038 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2056 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
2059 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2060 out_buf_size = header_size +
2089 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2095 len = CMBlockBufferGetDataLength(buf);
2112 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2113 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2115 if (CMTIME_IS_INVALID(dts)) {
2127 pkt->
dts = dts.value / time_base_num - dts_delta;
2144 size_t *contiguous_buf_size)
2148 int av_format =
frame->format;
2149 int av_color_range =
frame->color_range;
2161 if (range_guessed) {
2166 "Color range not set for %s. Using MPEG range.\n",
2173 for (
i = 0;
i <
desc->nb_components;
i++) {
2174 int p =
desc->comp[
i].plane;
2176 bool isAlpha = hasAlpha && (p + 1 == *plane_count);
2177 bool isChroma = (p != 0) && !isAlpha;
2178 int shiftw = isChroma ?
desc->log2_chroma_w : 0;
2179 int shifth = isChroma ?
desc->log2_chroma_h : 0;
2180 widths[p] = (avctx->
width + ((1 << shiftw) >> 1)) >> shiftw;
2181 heights[p] = (avctx->
height + ((1 << shifth) >> 1)) >> shifth;
2182 strides[p] =
frame->linesize[p];
2185 *contiguous_buf_size = 0;
2186 for (
i = 0;
i < *plane_count;
i++) {
2187 if (
i < *plane_count - 1 &&
2188 frame->data[
i] + strides[
i] * heights[
i] !=
frame->data[
i + 1]) {
2189 *contiguous_buf_size = 0;
2193 *contiguous_buf_size += strides[
i] * heights[
i];
2202 CVPixelBufferRef cv_img,
2203 const size_t *plane_strides,
2204 const size_t *plane_rows)
2216 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2221 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2226 if (CVPixelBufferIsPlanar(cv_img)) {
2227 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2229 if (
i == plane_count) {
2230 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2233 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2239 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2240 src_addr = (uint8_t*)
frame->data[
i];
2241 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2242 src_stride = plane_strides[
i];
2243 rows = plane_rows[
i];
2245 if (dst_stride == src_stride) {
2246 memcpy(dst_addr, src_addr, src_stride * rows);
2248 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2250 for (j = 0; j < rows; j++) {
2251 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2256 if (
frame->data[1]) {
2257 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2260 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2266 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2267 src_addr = (uint8_t*)
frame->data[0];
2268 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2269 src_stride = plane_strides[0];
2270 rows = plane_rows[0];
2272 if (dst_stride == src_stride) {
2273 memcpy(dst_addr, src_addr, src_stride * rows);
2275 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2277 for (j = 0; j < rows; j++) {
2278 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2283 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2294 CVPixelBufferRef *cv_img)
2302 size_t contiguous_buf_size;
2303 CVPixelBufferPoolRef pix_buf_pool;
2309 *cv_img = (CVPixelBufferRef)
frame->data[3];
2316 memset(widths, 0,
sizeof(widths));
2317 memset(heights, 0,
sizeof(heights));
2318 memset(strides, 0,
sizeof(strides));
2328 &contiguous_buf_size
2335 "Error: Cannot convert format %d color_range %d: %d\n",
2344 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2345 if (!pix_buf_pool) {
2352 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2353 if (vtstatus == kVTInvalidSessionErr) {
2358 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2360 if (!pix_buf_pool) {
2366 "kVTInvalidSessionErr error.\n");
2369 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2390 CFDictionaryRef* dict_out)
2392 CFDictionaryRef dict =
NULL;
2394 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2395 const void *vals[] = { kCFBooleanTrue };
2397 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2398 if(!dict)
return AVERROR(ENOMEM);
2410 CFDictionaryRef frame_dict;
2411 CVPixelBufferRef cv_img =
NULL;
2426 if (vtctx->
a53_cc && side_data && side_data->
size) {
2442 status = VTCompressionSessionEncodeFrame(
2452 if (frame_dict) CFRelease(frame_dict);
2472 CMSampleBufferRef buf =
NULL;
2511 if (
status)
goto end_nopkt;
2512 if (!buf)
goto end_nopkt;
2520 if (
status)
goto end_nopkt;
2532 CFStringRef profile_level,
2533 CFNumberRef gamma_level,
2534 CFDictionaryRef enc_info,
2535 CFDictionaryRef pixel_buffer_info)
2539 CVPixelBufferPoolRef pool =
NULL;
2540 CVPixelBufferRef pix_buf =
NULL;
2542 CMSampleBufferRef buf =
NULL;
2555 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2562 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2566 if(
status != kCVReturnSuccess){
2584 "Error sending frame for extradata: %d\n",
2610 CVPixelBufferRelease(pix_buf);
2632 VTCompressionSessionCompleteFrames(vtctx->
session,
2677 #ifdef kCFCoreFoundationVersionNumber10_7
2682 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2685 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2688 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2691 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2694 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2697 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2700 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2707 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2708 #define COMMON_OPTIONS \
2709 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2710 { .i64 = 0 }, 0, 1, VE }, \
2711 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2712 { .i64 = 0 }, 0, 1, VE }, \
2713 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2714 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2715 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2716 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2717 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2718 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2719 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2720 { .i64 = -1 }, -1, 1, VE }, \
2722 #define OFFSET(x) offsetof(VTEncContext, x)
2731 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2732 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2733 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2734 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2735 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2736 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2737 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2738 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2739 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2740 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2750 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2764 .
p.
name =
"h264_videotoolbox",
2783 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
2785 {
"constant_bit_rate",
"Require constant bit rate (macOS 13 or newer)",
OFFSET(constant_bit_rate),
AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1,
VE },
2799 .
p.
name =
"hevc_videotoolbox",
2812 .p.wrapper_name =
"videotoolbox",
2837 .
p.
name =
"prores_videotoolbox",
2850 .p.wrapper_name =
"videotoolbox",