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);
111 #define GET_SYM(symbol, defaultVal) \
113 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
115 compat_keys.symbol = CFSTR(defaultVal); \
117 compat_keys.symbol = *handle; \
123 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
126 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
164 "TargetQualityForAlpha");
166 "PrioritizeEncodingSpeedOverQuality");
169 "EnableHardwareAcceleratedVideoEncoder");
171 "RequireHardwareAcceleratedVideoEncoder");
255 CFStringRef profile_level,
256 CFNumberRef gamma_level,
257 CFDictionaryRef enc_info,
258 CFDictionaryRef pixel_buffer_info);
285 CFRelease(
info->cm_buffer);
335 *buf =
info->cm_buffer;
338 }
else if (
info->sei) {
376 CMSampleBufferRef sample_buffer,
383 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
384 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
386 if (length_code_size > 4)
389 while (
offset < src_size) {
399 for (
i = 0;
i < length_code_size;
i++) {
401 box_len |= size_buf[
i];
404 curr_src_len = box_len + length_code_size;
416 double alpha_quality)
429 return MKBETAG(
'a',
'p',
'c',
'o');
431 return MKBETAG(
'a',
'p',
'c',
's');
433 return MKBETAG(
'a',
'p',
'c',
'n');
435 return MKBETAG(
'a',
'p',
'c',
'h');
437 return MKBETAG(
'a',
'p',
'4',
'h');
439 return MKBETAG(
'a',
'p',
'4',
'x');
446 desc->log2_chroma_w == 0))
447 return MKBETAG(
'a',
'p',
'4',
'h');
449 return MKBETAG(
'a',
'p',
'c',
'n');
465 CMVideoFormatDescriptionRef vid_fmt,
469 size_t total_size = 0;
471 int is_count_bad = 0;
486 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
500 if (
i > 0 && is_count_bad)
status = 0;
519 CMVideoFormatDescriptionRef vid_fmt,
525 int is_count_bad = 0;
543 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
555 if (
i > 0 && is_count_bad)
status = 0;
561 if (dst_size < next_offset) {
569 memcpy(dst +
offset, ps, ps_size);
584 CMVideoFormatDescriptionRef vid_fmt;
588 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
614 CFDataRef
data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
615 if (
data && CFGetTypeID(
data) == CFDataGetTypeID()) {
616 CFIndex
size = CFDataGetLength(
data);
632 void *sourceFrameCtx,
634 VTEncodeInfoFlags
flags,
635 CMSampleBufferRef sample_buffer)
651 if (!sample_buffer) {
668 CMSampleBufferRef sample_buffer,
672 CMVideoFormatDescriptionRef vid_fmt;
676 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
704 CFStringRef *profile_level_val)
714 *profile_level_val =
NULL;
721 switch (vtctx->
level) {
722 case 0: *profile_level_val =
723 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
724 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
725 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
726 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
727 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
728 case 40: *profile_level_val =
729 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
730 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
731 case 42: *profile_level_val =
732 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
733 case 50: *profile_level_val =
734 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
735 case 51: *profile_level_val =
736 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
737 case 52: *profile_level_val =
738 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
743 switch (vtctx->
level) {
744 case 0: *profile_level_val =
745 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
746 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
747 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
748 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
749 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
750 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
751 case 42: *profile_level_val =
753 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
754 case 51: *profile_level_val =
756 case 52: *profile_level_val =
762 switch (vtctx->
level) {
763 case 0: *profile_level_val =
764 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
765 case 30: *profile_level_val =
767 case 31: *profile_level_val =
769 case 32: *profile_level_val =
771 case 40: *profile_level_val =
773 case 41: *profile_level_val =
775 case 42: *profile_level_val =
777 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
778 case 51: *profile_level_val =
780 case 52: *profile_level_val =
785 switch (vtctx->
level) {
786 case 0: *profile_level_val =
787 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
788 case 50: *profile_level_val =
789 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
794 if (!*profile_level_val) {
809 CFStringRef *profile_level_val)
814 *profile_level_val =
NULL;
829 if (!*profile_level_val) {
840 int* av_pixel_format,
849 return *av_pixel_format ? 0 :
AVERROR(EINVAL);
856 CFDictionarySetValue(dict,
857 kCVImageBufferColorPrimariesKey,
862 CFDictionarySetValue(dict,
863 kCVImageBufferTransferFunctionKey,
868 CFDictionarySetValue(dict,
869 kCVImageBufferYCbCrMatrixKey,
875 CFMutableDictionaryRef* dict)
877 CFNumberRef cv_color_format_num =
NULL;
878 CFNumberRef width_num =
NULL;
879 CFNumberRef height_num =
NULL;
880 CFMutableDictionaryRef pixel_buffer_info =
NULL;
889 pixel_buffer_info = CFDictionaryCreateMutable(
892 &kCFCopyStringDictionaryKeyCallBacks,
893 &kCFTypeDictionaryValueCallBacks);
895 if (!pixel_buffer_info)
goto pbinfo_nomem;
897 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
900 if (!cv_color_format_num)
goto pbinfo_nomem;
902 CFDictionarySetValue(pixel_buffer_info,
903 kCVPixelBufferPixelFormatTypeKey,
904 cv_color_format_num);
907 width_num = CFNumberCreate(kCFAllocatorDefault,
910 if (!width_num)
goto pbinfo_nomem;
912 CFDictionarySetValue(pixel_buffer_info,
913 kCVPixelBufferWidthKey,
917 height_num = CFNumberCreate(kCFAllocatorDefault,
920 if (!height_num)
goto pbinfo_nomem;
922 CFDictionarySetValue(pixel_buffer_info,
923 kCVPixelBufferHeightKey,
929 *dict = pixel_buffer_info;
936 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
942 CFStringRef *primaries)
951 *primaries = kCVImageBufferColorPrimaries_EBU_3213;
955 *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
959 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
963 *primaries =
compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
976 CFStringRef *transfer_fnc,
977 CFNumberRef *gamma_level)
985 *transfer_fnc =
NULL;
989 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
993 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
996 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ
998 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
1001 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR
1003 *transfer_fnc = kCVImageBufferTransferFunction_Linear;
1006 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG
1008 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
1014 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
1015 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1020 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
1021 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
1026 *transfer_fnc =
compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
1030 *transfer_fnc =
NULL;
1041 *
matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
1051 *
matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1055 *
matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1078 CFStringRef profile_level,
1079 CFNumberRef gamma_level,
1080 CFDictionaryRef enc_info,
1081 CFDictionaryRef pixel_buffer_info,
1082 VTCompressionSessionRef *session)
1088 CFNumberRef bit_rate_num;
1089 CFNumberRef quality_num;
1090 CFNumberRef bytes_per_second;
1091 CFNumberRef one_second;
1092 CFArrayRef data_rate_limits;
1093 int64_t bytes_per_second_value = 0;
1094 int64_t one_second_value = 0;
1097 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1103 kCFAllocatorDefault,
1111 #if !TARGET_OS_IPHONE
1113 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1121 av_log(avctx,
AV_LOG_ERROR,
"Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1127 quality_num = CFNumberCreate(kCFAllocatorDefault,
1128 kCFNumberFloat32Type,
1130 if (!quality_num)
return AVERROR(ENOMEM);
1133 kVTCompressionPropertyKey_Quality,
1135 CFRelease(quality_num);
1137 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1138 kCFNumberSInt32Type,
1140 if (!bit_rate_num)
return AVERROR(ENOMEM);
1143 kVTCompressionPropertyKey_AverageBitRate,
1145 CFRelease(bit_rate_num);
1155 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1156 vtctx->
prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1158 av_log(avctx,
AV_LOG_WARNING,
"PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1164 bytes_per_second_value = max_rate >> 3;
1165 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1166 kCFNumberSInt64Type,
1167 &bytes_per_second_value);
1168 if (!bytes_per_second) {
1171 one_second_value = 1;
1172 one_second = CFNumberCreate(kCFAllocatorDefault,
1173 kCFNumberSInt64Type,
1176 CFRelease(bytes_per_second);
1179 nums[0] = (
void *)bytes_per_second;
1180 nums[1] = (
void *)one_second;
1181 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1182 (
const void **)nums,
1184 &kCFTypeArrayCallBacks);
1186 if (!data_rate_limits) {
1187 CFRelease(bytes_per_second);
1188 CFRelease(one_second);
1192 kVTCompressionPropertyKey_DataRateLimits,
1195 CFRelease(bytes_per_second);
1196 CFRelease(one_second);
1197 CFRelease(data_rate_limits);
1211 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1212 kCFNumberDoubleType,
1214 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1217 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1219 CFRelease(alpha_quality_num);
1223 if (profile_level) {
1225 kVTCompressionPropertyKey_ProfileLevel,
1228 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n",
status);
1233 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1241 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1243 CFRelease(interval);
1253 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1256 if (
status == kVTPropertyNotSupportedErr) {
1257 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1265 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1268 if (
status == kVTPropertyNotSupportedErr) {
1269 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1278 CFMutableDictionaryRef par;
1285 num = CFNumberCreate(kCFAllocatorDefault,
1289 den = CFNumberCreate(kCFAllocatorDefault,
1295 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1297 &kCFCopyStringDictionaryKeyCallBacks,
1298 &kCFTypeDictionaryValueCallBacks);
1300 if (!par || !num || !den) {
1301 if (par) CFRelease(par);
1302 if (num) CFRelease(num);
1303 if (den) CFRelease(den);
1308 CFDictionarySetValue(
1310 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1313 CFDictionarySetValue(
1315 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1319 kVTCompressionPropertyKey_PixelAspectRatio,
1329 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1341 kVTCompressionPropertyKey_TransferFunction,
1352 kVTCompressionPropertyKey_YCbCrMatrix,
1363 kVTCompressionPropertyKey_ColorPrimaries,
1373 kCVImageBufferGammaLevelKey,
1383 kVTCompressionPropertyKey_AllowFrameReordering,
1398 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1409 vtctx->
realtime ? kCFBooleanTrue : kCFBooleanFalse);
1416 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1427 CFMutableDictionaryRef enc_info;
1428 CFMutableDictionaryRef pixel_buffer_info;
1431 CFStringRef profile_level =
NULL;
1432 CFNumberRef gamma_level =
NULL;
1441 #if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1443 if (__builtin_available(macOS 10.10, *)) {
1444 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1456 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1461 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1476 enc_info = CFDictionaryCreateMutable(
1477 kCFAllocatorDefault,
1479 &kCFCopyStringDictionaryKeyCallBacks,
1480 &kCFTypeDictionaryValueCallBacks
1483 if (!enc_info)
return AVERROR(ENOMEM);
1485 #if !TARGET_OS_IPHONE
1487 CFDictionarySetValue(enc_info,
1488 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1491 CFDictionarySetValue(enc_info,
1492 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1495 CFDictionarySetValue(enc_info,
1496 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1506 pixel_buffer_info =
NULL;
1537 CFRelease(gamma_level);
1539 if (pixel_buffer_info)
1540 CFRelease(pixel_buffer_info);
1542 CFRelease(enc_info);
1550 CFBooleanRef has_b_frames_cfbool;
1563 kVTCompressionPropertyKey_AllowFrameReordering,
1564 kCFAllocatorDefault,
1565 &has_b_frames_cfbool);
1567 if (!
status && has_b_frames_cfbool) {
1570 if (CFBooleanGetValue(has_b_frames_cfbool))
1574 CFRelease(has_b_frames_cfbool);
1583 CFArrayRef attachments;
1584 CFDictionaryRef attachment;
1585 CFBooleanRef not_sync;
1588 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1589 len = !attachments ? 0 : CFArrayGetCount(attachments);
1592 *is_key_frame =
true;
1596 attachment = CFArrayGetValueAtIndex(attachments, 0);
1598 if (CFDictionaryGetValueIfPresent(attachment,
1599 kCMSampleAttachmentKey_NotSync,
1600 (
const void **)¬_sync))
1602 *is_key_frame = !CFBooleanGetValue(not_sync);
1604 *is_key_frame =
true;
1625 size_t sei_payload_size = 0;
1626 int sei_payload_type = 0;
1628 uint8_t *nal_start = nal_data;
1633 nal_type = *nal_data & 0x1F;
1640 if (nal_data[nal_size - 1] == 0x80)
1643 while (nal_size > 0 && *nal_data > 0) {
1645 sei_payload_type += *nal_data;
1648 }
while (nal_size > 0 && *nal_data == 0xFF);
1656 sei_payload_size += *nal_data;
1659 }
while (nal_size > 0 && *nal_data == 0xFF);
1661 if (nal_size < sei_payload_size) {
1666 nal_data += sei_payload_size;
1667 nal_size -= sei_payload_size;
1670 *sei_end = nal_data;
1672 return nal_data - nal_start + 1;
1692 uint8_t* dst_end = dst + dst_size;
1693 const uint8_t* src_end =
src + src_size;
1694 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1696 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1705 for (;
src < src_end;
src++, dst++) {
1707 int insert_ep3_byte = *
src <= 3;
1708 if (insert_ep3_byte) {
1726 wrote_bytes = dst - dst_start;
1729 return -wrote_bytes;
1739 uint8_t *sei_start = dst;
1740 size_t remaining_sei_size =
sei->size;
1741 size_t remaining_dst_size = dst_size;
1746 if (!remaining_dst_size)
1749 while (sei_type && remaining_dst_size != 0) {
1750 int sei_byte = sei_type > 255 ? 255 : sei_type;
1753 sei_type -= sei_byte;
1755 remaining_dst_size--;
1761 while (remaining_sei_size && remaining_dst_size != 0) {
1762 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1765 remaining_sei_size -= size_byte;
1767 remaining_dst_size--;
1770 if (remaining_dst_size < sei->
size)
1773 header_bytes = dst - sei_start;
1781 if (bytes_written < 0)
1784 bytes_written += header_bytes;
1785 return bytes_written;
1809 size_t length_code_size,
1810 CMSampleBufferRef sample_buffer,
1815 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1816 size_t remaining_src_size = src_size;
1817 size_t remaining_dst_size = dst_size;
1818 size_t src_offset = 0;
1821 uint8_t size_buf[4];
1823 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1825 if (length_code_size > 4) {
1829 while (remaining_src_size > 0) {
1830 size_t curr_src_len;
1831 size_t curr_dst_len;
1847 src_offset + length_code_size,
1858 for (
i = 0;
i < length_code_size;
i++) {
1860 box_len |= size_buf[
i];
1873 remaining_dst_size--;
1878 remaining_dst_size);
1880 if (wrote_bytes < 0)
1883 remaining_dst_size -= wrote_bytes;
1884 dst_data += wrote_bytes;
1886 if (remaining_dst_size <= 0)
1892 remaining_dst_size--;
1897 curr_src_len = box_len + length_code_size;
1900 if (remaining_src_size < curr_src_len) {
1904 if (remaining_dst_size < curr_dst_len) {
1912 src_offset + length_code_size,
1927 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1928 if (old_sei_length < 0)
1934 remaining_dst_size - old_sei_length);
1935 if (wrote_bytes < 0)
1938 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1941 new_sei[wrote_bytes++] = 0x80;
1942 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1944 dst_data += extra_bytes;
1945 remaining_dst_size -= extra_bytes;
1950 src_offset += curr_src_len;
1951 dst_data += curr_dst_len;
1953 remaining_src_size -= curr_src_len;
1954 remaining_dst_size -= curr_dst_len;
1975 if ((
sei->size % 255) == 0)
1978 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
1983 CMSampleBufferRef sample_buffer,
1992 size_t length_code_size;
1993 size_t header_size = 0;
1995 size_t out_buf_size;
1996 size_t sei_nalu_size = 0;
1998 int64_t time_base_num;
2002 CMVideoFormatDescriptionRef vid_fmt;
2013 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2031 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
2034 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2035 out_buf_size = header_size +
2064 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2070 len = CMBlockBufferGetDataLength(buf);
2087 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2088 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2090 if (CMTIME_IS_INVALID(dts)) {
2102 pkt->
dts = dts.value / time_base_num - dts_delta;
2119 size_t *contiguous_buf_size)
2123 int av_format =
frame->format;
2124 int av_color_range =
frame->color_range;
2136 "Could not get pixel format for color format '%s' range '%s'.\n",
2146 if (range_guessed) {
2151 "Color range not set for %s. Using MPEG range.\n",
2158 for (
i = 0;
i <
desc->nb_components;
i++) {
2159 int p =
desc->comp[
i].plane;
2161 bool isAlpha = hasAlpha && (p + 1 == *plane_count);
2162 bool isChroma = (p != 0) && !isAlpha;
2163 int shiftw = isChroma ?
desc->log2_chroma_w : 0;
2164 int shifth = isChroma ?
desc->log2_chroma_h : 0;
2165 widths[p] = (avctx->
width + ((1 << shiftw) >> 1)) >> shiftw;
2166 heights[p] = (avctx->
height + ((1 << shifth) >> 1)) >> shifth;
2167 strides[p] =
frame->linesize[p];
2170 *contiguous_buf_size = 0;
2171 for (
i = 0;
i < *plane_count;
i++) {
2172 if (
i < *plane_count - 1 &&
2173 frame->data[
i] + strides[
i] * heights[
i] !=
frame->data[
i + 1]) {
2174 *contiguous_buf_size = 0;
2178 *contiguous_buf_size += strides[
i] * heights[
i];
2187 CVPixelBufferRef cv_img,
2188 const size_t *plane_strides,
2189 const size_t *plane_rows)
2201 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2206 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2211 if (CVPixelBufferIsPlanar(cv_img)) {
2212 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2214 if (
i == plane_count) {
2215 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2218 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2224 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2225 src_addr = (uint8_t*)
frame->data[
i];
2226 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2227 src_stride = plane_strides[
i];
2228 rows = plane_rows[
i];
2230 if (dst_stride == src_stride) {
2231 memcpy(dst_addr, src_addr, src_stride * rows);
2233 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2235 for (j = 0; j < rows; j++) {
2236 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2241 if (
frame->data[1]) {
2242 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2245 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2251 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2252 src_addr = (uint8_t*)
frame->data[0];
2253 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2254 src_stride = plane_strides[0];
2255 rows = plane_rows[0];
2257 if (dst_stride == src_stride) {
2258 memcpy(dst_addr, src_addr, src_stride * rows);
2260 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2262 for (j = 0; j < rows; j++) {
2263 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2268 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2279 CVPixelBufferRef *cv_img)
2287 size_t contiguous_buf_size;
2288 CVPixelBufferPoolRef pix_buf_pool;
2294 *cv_img = (CVPixelBufferRef)
frame->data[3];
2301 memset(widths, 0,
sizeof(widths));
2302 memset(heights, 0,
sizeof(heights));
2303 memset(strides, 0,
sizeof(strides));
2313 &contiguous_buf_size
2320 "Error: Cannot convert format %d color_range %d: %d\n",
2329 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2330 if (!pix_buf_pool) {
2337 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2338 if (vtstatus == kVTInvalidSessionErr) {
2343 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2345 if (!pix_buf_pool) {
2351 "kVTInvalidSessionErr error.\n");
2354 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2375 CFDictionaryRef* dict_out)
2377 CFDictionaryRef dict =
NULL;
2379 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2380 const void *vals[] = { kCFBooleanTrue };
2382 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2383 if(!dict)
return AVERROR(ENOMEM);
2395 CFDictionaryRef frame_dict;
2396 CVPixelBufferRef cv_img =
NULL;
2411 if (vtctx->
a53_cc && side_data && side_data->
size) {
2427 status = VTCompressionSessionEncodeFrame(
2437 if (frame_dict) CFRelease(frame_dict);
2457 CMSampleBufferRef buf =
NULL;
2496 if (
status)
goto end_nopkt;
2497 if (!buf)
goto end_nopkt;
2505 if (
status)
goto end_nopkt;
2517 CFStringRef profile_level,
2518 CFNumberRef gamma_level,
2519 CFDictionaryRef enc_info,
2520 CFDictionaryRef pixel_buffer_info)
2524 CVPixelBufferPoolRef pool =
NULL;
2525 CVPixelBufferRef pix_buf =
NULL;
2527 CMSampleBufferRef buf =
NULL;
2539 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2545 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2549 if(
status != kCVReturnSuccess){
2566 "Error sending frame for extradata: %d\n",
2590 CVPixelBufferRelease(pix_buf);
2612 VTCompressionSessionCompleteFrames(vtctx->
session,
2657 #ifdef kCFCoreFoundationVersionNumber10_7
2662 #if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2665 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2668 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2671 #if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2674 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2677 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2680 #if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2687 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2688 #define COMMON_OPTIONS \
2689 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2690 { .i64 = 0 }, 0, 1, VE }, \
2691 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2692 { .i64 = 0 }, 0, 1, VE }, \
2693 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2694 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2695 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2696 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2697 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2698 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2699 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2700 { .i64 = -1 }, -1, 1, VE }, \
2702 #define OFFSET(x) offsetof(VTEncContext, x)
2711 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2712 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2713 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2714 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2715 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2716 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2717 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2718 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2719 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2720 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2742 .
p.
name =
"h264_videotoolbox",
2762 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
2776 .
p.
name =
"hevc_videotoolbox",
2790 .p.wrapper_name =
"videotoolbox",
2815 .
p.
name =
"prores_videotoolbox",
2829 .p.wrapper_name =
"videotoolbox",