21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
39 #if !HAVE_KCMVIDEOCODECTYPE_HEVC
43 #if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
47 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
52 #ifndef TARGET_CPU_ARM64
53 # define TARGET_CPU_ARM64 0
57 size_t parameterSetIndex,
58 const uint8_t **parameterSetPointerOut,
59 size_t *parameterSetSizeOut,
60 size_t *parameterSetCountOut,
61 int *NALUnitHeaderLengthOut);
107 #define GET_SYM(symbol, defaultVal) \
109 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
111 compat_keys.symbol = CFSTR(defaultVal); \
113 compat_keys.symbol = *handle; \
119 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
122 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
160 "TargetQualityForAlpha");
163 "EnableHardwareAcceleratedVideoEncoder");
165 "RequireHardwareAcceleratedVideoEncoder");
248 CFStringRef profile_level,
249 CFNumberRef gamma_level,
250 CFDictionaryRef enc_info,
251 CFDictionaryRef pixel_buffer_info);
331 }
else if (info->
sei) {
369 CMSampleBufferRef sample_buffer,
376 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
377 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
379 if (length_code_size > 4)
382 while (
offset < src_size) {
387 status = CMBlockBufferCopyDataBytes(
block,
392 if (status != kCMBlockBufferNoErr) {
396 for (
i = 0;
i < length_code_size;
i++) {
398 box_len |= size_buf[
i];
401 curr_src_len = box_len + length_code_size;
413 double alpha_quality)
436 CMVideoFormatDescriptionRef vid_fmt,
440 size_t total_size = 0;
442 int is_count_bad = 0;
457 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
471 if (
i > 0 && is_count_bad) status = 0;
490 CMVideoFormatDescriptionRef vid_fmt,
496 int is_count_bad = 0;
514 for (
i = 0;
i < ps_count || is_count_bad;
i++) {
526 if (
i > 0 && is_count_bad) status = 0;
532 if (dst_size < next_offset) {
540 memcpy(dst +
offset, ps, ps_size);
554 CMVideoFormatDescriptionRef vid_fmt;
558 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
588 void *sourceFrameCtx,
590 VTEncodeInfoFlags
flags,
591 CMSampleBufferRef sample_buffer)
607 if (!sample_buffer) {
624 CMSampleBufferRef sample_buffer,
628 CMVideoFormatDescriptionRef vid_fmt;
632 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
660 CFStringRef *profile_level_val)
670 *profile_level_val =
NULL;
677 switch (vtctx->
level) {
678 case 0: *profile_level_val =
679 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
680 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
681 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
682 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
683 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
684 case 40: *profile_level_val =
685 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
686 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
687 case 42: *profile_level_val =
688 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
689 case 50: *profile_level_val =
690 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
691 case 51: *profile_level_val =
692 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
693 case 52: *profile_level_val =
694 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
699 switch (vtctx->
level) {
700 case 0: *profile_level_val =
701 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
702 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
703 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
704 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
705 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
706 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
707 case 42: *profile_level_val =
709 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
710 case 51: *profile_level_val =
712 case 52: *profile_level_val =
718 switch (vtctx->
level) {
719 case 0: *profile_level_val =
720 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
721 case 30: *profile_level_val =
723 case 31: *profile_level_val =
725 case 32: *profile_level_val =
727 case 40: *profile_level_val =
729 case 41: *profile_level_val =
731 case 42: *profile_level_val =
733 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
734 case 51: *profile_level_val =
736 case 52: *profile_level_val =
741 switch (vtctx->
level) {
742 case 0: *profile_level_val =
743 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
744 case 50: *profile_level_val =
745 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
750 if (!*profile_level_val) {
765 CFStringRef *profile_level_val)
770 *profile_level_val =
NULL;
785 if (!*profile_level_val) {
796 int* av_pixel_format,
805 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
806 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
809 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
810 kCVPixelFormatType_420YpCbCr8Planar;
812 *av_pixel_format = kCVPixelFormatType_32BGRA;
828 CFDictionarySetValue(dict,
829 kCVImageBufferColorPrimariesKey,
834 CFDictionarySetValue(dict,
835 kCVImageBufferTransferFunctionKey,
840 CFDictionarySetValue(dict,
841 kCVImageBufferYCbCrMatrixKey,
847 CFMutableDictionaryRef* dict)
849 CFNumberRef cv_color_format_num =
NULL;
850 CFNumberRef width_num =
NULL;
851 CFNumberRef height_num =
NULL;
852 CFMutableDictionaryRef pixel_buffer_info =
NULL;
859 if (status)
return status;
861 pixel_buffer_info = CFDictionaryCreateMutable(
864 &kCFCopyStringDictionaryKeyCallBacks,
865 &kCFTypeDictionaryValueCallBacks);
867 if (!pixel_buffer_info)
goto pbinfo_nomem;
869 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
872 if (!cv_color_format_num)
goto pbinfo_nomem;
874 CFDictionarySetValue(pixel_buffer_info,
875 kCVPixelBufferPixelFormatTypeKey,
876 cv_color_format_num);
879 width_num = CFNumberCreate(kCFAllocatorDefault,
882 if (!width_num)
return AVERROR(ENOMEM);
884 CFDictionarySetValue(pixel_buffer_info,
885 kCVPixelBufferWidthKey,
889 height_num = CFNumberCreate(kCFAllocatorDefault,
892 if (!height_num)
goto pbinfo_nomem;
894 CFDictionarySetValue(pixel_buffer_info,
895 kCVPixelBufferHeightKey,
901 *dict = pixel_buffer_info;
908 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
914 CFStringRef *primaries)
923 *primaries = kCVImageBufferColorPrimaries_EBU_3213;
927 *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
931 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
935 *primaries =
compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
948 CFStringRef *transfer_fnc,
949 CFNumberRef *gamma_level)
957 *transfer_fnc =
NULL;
961 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
965 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
968 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ
970 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
973 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR
975 *transfer_fnc = kCVImageBufferTransferFunction_Linear;
978 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG
980 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
986 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
987 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
992 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
993 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
998 *transfer_fnc =
compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
1002 *transfer_fnc =
NULL;
1013 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
1023 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1027 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1031 *matrix =
compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
1050 CFStringRef profile_level,
1051 CFNumberRef gamma_level,
1052 CFDictionaryRef enc_info,
1053 CFDictionaryRef pixel_buffer_info,
1054 VTCompressionSessionRef *session)
1059 CFNumberRef bit_rate_num;
1060 CFNumberRef bytes_per_second;
1061 CFNumberRef one_second;
1062 CFArrayRef data_rate_limits;
1063 int64_t bytes_per_second_value = 0;
1067 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1073 kCFAllocatorDefault,
1078 if (status || !vtctx->
session) {
1079 av_log(avctx,
AV_LOG_ERROR,
"Error: cannot create compression session: %d\n", status);
1081 #if !TARGET_OS_IPHONE
1083 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1091 av_log(avctx,
AV_LOG_ERROR,
"Error: -q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1097 CFNumberRef quality_num = CFNumberCreate(kCFAllocatorDefault,
1098 kCFNumberFloat32Type,
1100 if (!quality_num)
return AVERROR(ENOMEM);
1102 status = VTSessionSetProperty(vtctx->
session,
1103 kVTCompressionPropertyKey_Quality,
1105 CFRelease(quality_num);
1107 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1108 kCFNumberSInt32Type,
1110 if (!bit_rate_num)
return AVERROR(ENOMEM);
1112 status = VTSessionSetProperty(vtctx->
session,
1113 kVTCompressionPropertyKey_AverageBitRate,
1115 CFRelease(bit_rate_num);
1125 bytes_per_second_value = max_rate >> 3;
1126 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1127 kCFNumberSInt64Type,
1128 &bytes_per_second_value);
1129 if (!bytes_per_second) {
1132 one_second_value = 1;
1133 one_second = CFNumberCreate(kCFAllocatorDefault,
1134 kCFNumberSInt64Type,
1137 CFRelease(bytes_per_second);
1140 nums[0] = (
void *)bytes_per_second;
1141 nums[1] = (
void *)one_second;
1142 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1143 (
const void **)nums,
1145 &kCFTypeArrayCallBacks);
1147 if (!data_rate_limits) {
1148 CFRelease(bytes_per_second);
1149 CFRelease(one_second);
1152 status = VTSessionSetProperty(vtctx->
session,
1153 kVTCompressionPropertyKey_DataRateLimits,
1156 CFRelease(bytes_per_second);
1157 CFRelease(one_second);
1158 CFRelease(data_rate_limits);
1168 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1169 kCFNumberDoubleType,
1171 if (!alpha_quality_num)
return AVERROR(ENOMEM);
1173 status = VTSessionSetProperty(vtctx->
session,
1174 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1176 CFRelease(alpha_quality_num);
1180 if (profile_level) {
1181 status = VTSessionSetProperty(vtctx->
session,
1182 kVTCompressionPropertyKey_ProfileLevel,
1185 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1190 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1197 status = VTSessionSetProperty(vtctx->
session,
1198 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1200 CFRelease(interval);
1203 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'max key-frame interval' property: %d\n", status);
1209 status = VTSessionSetProperty(vtctx->
session,
1210 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1213 if (status == kVTPropertyNotSupportedErr) {
1214 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1215 }
else if (status) {
1221 status = VTSessionSetProperty(vtctx->
session,
1222 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1225 if (status == kVTPropertyNotSupportedErr) {
1226 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1227 }
else if (status) {
1235 CFMutableDictionaryRef par;
1242 num = CFNumberCreate(kCFAllocatorDefault,
1246 den = CFNumberCreate(kCFAllocatorDefault,
1252 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1254 &kCFCopyStringDictionaryKeyCallBacks,
1255 &kCFTypeDictionaryValueCallBacks);
1257 if (!par || !num || !den) {
1258 if (par) CFRelease(par);
1259 if (num) CFRelease(num);
1260 if (den) CFRelease(den);
1265 CFDictionarySetValue(
1267 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1270 CFDictionarySetValue(
1272 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1275 status = VTSessionSetProperty(vtctx->
session,
1276 kVTCompressionPropertyKey_PixelAspectRatio,
1286 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1297 status = VTSessionSetProperty(vtctx->
session,
1298 kVTCompressionPropertyKey_TransferFunction,
1308 status = VTSessionSetProperty(vtctx->
session,
1309 kVTCompressionPropertyKey_YCbCrMatrix,
1319 status = VTSessionSetProperty(vtctx->
session,
1320 kVTCompressionPropertyKey_ColorPrimaries,
1329 status = VTSessionSetProperty(vtctx->
session,
1330 kCVImageBufferGammaLevelKey,
1339 status = VTSessionSetProperty(vtctx->
session,
1340 kVTCompressionPropertyKey_AllowFrameReordering,
1344 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'allow frame reordering' property: %d\n", status);
1354 status = VTSessionSetProperty(vtctx->
session,
1355 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1364 status = VTSessionSetProperty(vtctx->
session,
1373 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1384 CFMutableDictionaryRef enc_info;
1385 CFMutableDictionaryRef pixel_buffer_info =
NULL;
1388 CFStringRef profile_level;
1389 CFNumberRef gamma_level =
NULL;
1405 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1410 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1423 enc_info = CFDictionaryCreateMutable(
1424 kCFAllocatorDefault,
1426 &kCFCopyStringDictionaryKeyCallBacks,
1427 &kCFTypeDictionaryValueCallBacks
1430 if (!enc_info)
return AVERROR(ENOMEM);
1432 #if !TARGET_OS_IPHONE
1434 CFDictionarySetValue(enc_info,
1435 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1438 CFDictionarySetValue(enc_info,
1439 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1442 CFDictionarySetValue(enc_info,
1443 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1482 CFRelease(gamma_level);
1484 if (pixel_buffer_info)
1485 CFRelease(pixel_buffer_info);
1487 CFRelease(enc_info);
1495 CFBooleanRef has_b_frames_cfbool;
1505 if (status)
return status;
1507 status = VTSessionCopyProperty(vtctx->
session,
1508 kVTCompressionPropertyKey_AllowFrameReordering,
1509 kCFAllocatorDefault,
1510 &has_b_frames_cfbool);
1512 if (!status && has_b_frames_cfbool) {
1515 if (CFBooleanGetValue(has_b_frames_cfbool))
1519 CFRelease(has_b_frames_cfbool);
1528 CFArrayRef attachments;
1529 CFDictionaryRef attachment;
1530 CFBooleanRef not_sync;
1533 attachments = CMSampleBufferGetSampleAttachmentsArray(
buffer,
false);
1534 len = !attachments ? 0 : CFArrayGetCount(attachments);
1537 *is_key_frame =
true;
1541 attachment = CFArrayGetValueAtIndex(attachments, 0);
1543 if (CFDictionaryGetValueIfPresent(attachment,
1544 kCMSampleAttachmentKey_NotSync,
1545 (
const void **)¬_sync))
1547 *is_key_frame = !CFBooleanGetValue(not_sync);
1549 *is_key_frame =
true;
1570 size_t sei_payload_size = 0;
1572 uint8_t *nal_start = nal_data;
1577 nal_type = *nal_data & 0x1F;
1584 if (nal_data[nal_size - 1] == 0x80)
1587 while (nal_size > 0 && *nal_data > 0) {
1591 }
while (nal_size > 0 && *nal_data == 0xFF);
1599 sei_payload_size += *nal_data;
1602 }
while (nal_size > 0 && *nal_data == 0xFF);
1604 if (nal_size < sei_payload_size) {
1609 nal_data += sei_payload_size;
1610 nal_size -= sei_payload_size;
1613 *sei_end = nal_data;
1615 return nal_data - nal_start + 1;
1635 uint8_t* dst_end = dst + dst_size;
1637 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1639 for (
i = start_at;
i < dst_offset &&
i < dst_size;
i++) {
1648 for (;
src < src_end;
src++, dst++) {
1650 int insert_ep3_byte = *
src <= 3;
1651 if (insert_ep3_byte) {
1669 wrote_bytes = dst - dst_start;
1672 return -wrote_bytes;
1683 size_t remaining_sei_size =
sei->size;
1684 size_t remaining_dst_size = dst_size;
1689 if (!remaining_dst_size)
1692 while (sei_type && remaining_dst_size != 0) {
1693 int sei_byte = sei_type > 255 ? 255 : sei_type;
1696 sei_type -= sei_byte;
1698 remaining_dst_size--;
1704 while (remaining_sei_size && remaining_dst_size != 0) {
1705 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1708 remaining_sei_size -= size_byte;
1710 remaining_dst_size--;
1713 if (remaining_dst_size < sei->
size)
1716 header_bytes = dst - sei_start;
1724 if (bytes_written < 0)
1727 bytes_written += header_bytes;
1728 return bytes_written;
1752 size_t length_code_size,
1753 CMSampleBufferRef sample_buffer,
1758 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1759 size_t remaining_src_size = src_size;
1760 size_t remaining_dst_size = dst_size;
1761 size_t src_offset = 0;
1766 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1768 if (length_code_size > 4) {
1772 while (remaining_src_size > 0) {
1773 size_t curr_src_len;
1774 size_t curr_dst_len;
1780 status = CMBlockBufferCopyDataBytes(
block,
1789 status = CMBlockBufferCopyDataBytes(
block,
1790 src_offset + length_code_size,
1801 for (
i = 0;
i < length_code_size;
i++) {
1803 box_len |= size_buf[
i];
1816 remaining_dst_size--;
1821 remaining_dst_size);
1823 if (wrote_bytes < 0)
1826 remaining_dst_size -= wrote_bytes;
1827 dst_data += wrote_bytes;
1829 if (remaining_dst_size <= 0)
1835 remaining_dst_size--;
1840 curr_src_len = box_len + length_code_size;
1843 if (remaining_src_size < curr_src_len) {
1847 if (remaining_dst_size < curr_dst_len) {
1854 status = CMBlockBufferCopyDataBytes(
block,
1855 src_offset + length_code_size,
1870 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1871 if (old_sei_length < 0)
1872 return old_sei_length;
1877 remaining_dst_size - old_sei_length);
1878 if (wrote_bytes < 0)
1881 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1884 new_sei[wrote_bytes++] = 0x80;
1885 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1887 dst_data += extra_bytes;
1888 remaining_dst_size -= extra_bytes;
1893 src_offset += curr_src_len;
1894 dst_data += curr_dst_len;
1896 remaining_src_size -= curr_src_len;
1897 remaining_dst_size -= curr_dst_len;
1918 if ((
sei->size % 255) == 0)
1921 return copied_size +
sei->size / 255 + 1 +
type / 255 + 1;
1926 CMSampleBufferRef sample_buffer,
1935 size_t length_code_size;
1936 size_t header_size = 0;
1938 size_t out_buf_size;
1939 size_t sei_nalu_size = 0;
1945 CMVideoFormatDescriptionRef vid_fmt;
1950 if (status)
return status;
1955 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1962 if (status)
return status;
1965 status =
count_nalus(length_code_size, sample_buffer, &nalu_count);
1973 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
1976 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1977 out_buf_size = header_size +
1988 if(status)
return status;
2009 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2010 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2012 if (CMTIME_IS_INVALID(dts)) {
2024 pkt->
dts = dts.value / time_base_num - dts_delta;
2042 size_t *contiguous_buf_size)
2055 "Could not get pixel format for color format '%s' range '%s'.\n",
2065 if (range_guessed) {
2070 "Color range not set for %s. Using MPEG range.\n",
2075 switch (av_format) {
2079 widths [0] = avctx->
width;
2080 heights[0] = avctx->
height;
2083 widths [1] = (avctx->
width + 1) / 2;
2084 heights[1] = (avctx->
height + 1) / 2;
2091 widths [0] = avctx->
width;
2092 heights[0] = avctx->
height;
2095 widths [1] = (avctx->
width + 1) / 2;
2096 heights[1] = (avctx->
height + 1) / 2;
2099 widths [2] = (avctx->
width + 1) / 2;
2100 heights[2] = (avctx->
height + 1) / 2;
2107 widths [0] = avctx->
width;
2108 heights[0] = avctx->
height;
2114 widths[0] = avctx->
width;
2115 heights[0] = avctx->
height;
2118 widths[1] = (avctx->
width + 1) / 2;
2119 heights[1] = (avctx->
height + 1) / 2;
2127 "Could not get frame format info for color %d range %d.\n",
2134 *contiguous_buf_size = 0;
2135 for (
i = 0;
i < *plane_count;
i++) {
2136 if (
i < *plane_count - 1 &&
2138 *contiguous_buf_size = 0;
2142 *contiguous_buf_size += strides[
i] * heights[
i];
2151 CVPixelBufferRef cv_img,
2152 const size_t *plane_strides,
2153 const size_t *plane_rows)
2165 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2167 av_log(avctx,
AV_LOG_ERROR,
"Could not lock base address of CVPixelBuffer: %d.\n", status);
2171 if (CVPixelBufferIsPlanar(cv_img)) {
2172 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2174 if (
i == plane_count) {
2175 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2178 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2184 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img,
i);
2186 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img,
i);
2187 src_stride = plane_strides[
i];
2188 rows = plane_rows[
i];
2190 if (dst_stride == src_stride) {
2191 memcpy(dst_addr, src_addr, src_stride * rows);
2193 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2195 for (j = 0; j < rows; j++) {
2196 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2202 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2205 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2211 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2213 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2214 src_stride = plane_strides[0];
2215 rows = plane_rows[0];
2217 if (dst_stride == src_stride) {
2218 memcpy(dst_addr, src_addr, src_stride * rows);
2220 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2222 for (j = 0; j < rows; j++) {
2223 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2228 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2230 av_log(avctx,
AV_LOG_ERROR,
"Could not unlock CVPixelBuffer base address: %d.\n", status);
2239 CVPixelBufferRef *cv_img)
2247 size_t contiguous_buf_size;
2248 CVPixelBufferPoolRef pix_buf_pool;
2254 *cv_img = (CVPixelBufferRef)
frame->
data[3];
2261 memset(widths, 0,
sizeof(widths));
2262 memset(heights, 0,
sizeof(heights));
2263 memset(strides, 0,
sizeof(strides));
2273 &contiguous_buf_size
2280 "Error: Cannot convert format %d color_range %d: %d\n",
2289 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2290 if (!pix_buf_pool) {
2297 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2298 if (vtstatus == kVTInvalidSessionErr) {
2303 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2305 if (!pix_buf_pool) {
2311 "kVTInvalidSessionErr error.\n");
2314 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2320 av_log(avctx,
AV_LOG_ERROR,
"Could not create pixel buffer from pool: %d.\n", status);
2335 CFDictionaryRef* dict_out)
2337 CFDictionaryRef dict =
NULL;
2339 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2340 const void *vals[] = { kCFBooleanTrue };
2342 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2343 if(!dict)
return AVERROR(ENOMEM);
2355 CFDictionaryRef frame_dict;
2356 CVPixelBufferRef cv_img =
NULL;
2361 if (status)
return status;
2370 if (vtctx->
a53_cc && side_data && side_data->
size) {
2385 status = VTCompressionSessionEncodeFrame(
2395 if (frame_dict) CFRelease(frame_dict);
2415 CMSampleBufferRef buf =
NULL;
2436 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2454 if (status)
goto end_nopkt;
2455 if (!buf)
goto end_nopkt;
2463 if (status)
goto end_nopkt;
2475 CFStringRef profile_level,
2476 CFNumberRef gamma_level,
2477 CFDictionaryRef enc_info,
2478 CFDictionaryRef pixel_buffer_info)
2482 CVPixelBufferPoolRef pool =
NULL;
2483 CVPixelBufferRef pix_buf =
NULL;
2485 CMSampleBufferRef buf =
NULL;
2497 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2504 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2508 if(status != kCVReturnSuccess){
2515 status = VTCompressionSessionEncodeFrame(vtctx->
session,
2526 "Error sending frame for extradata: %d\n",
2533 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2557 CVPixelBufferRelease(pix_buf);
2579 VTCompressionSessionCompleteFrames(vtctx->
session,
2621 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2622 #define COMMON_OPTIONS \
2623 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2624 { .i64 = 0 }, 0, 1, VE }, \
2625 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2626 { .i64 = 0 }, 0, 1, VE }, \
2627 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2628 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2629 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2630 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2631 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2632 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2634 #define OFFSET(x) offsetof(VTEncContext, x)
2643 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2644 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2645 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2646 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2647 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2648 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2649 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2650 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2651 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2652 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2674 .
name =
"h264_videotoolbox",
2694 {
"alpha_quality",
"Compression quality for the alpha channel",
OFFSET(alpha_quality),
AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0,
VE },
2708 .
name =
"hevc_videotoolbox",
2721 .wrapper_name =
"videotoolbox",
int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len, void **data, size_t *sei_size)
Check AVFrame for A53 side data and allocate and fill SEI message with A53 info.
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Libavcodec external API header.
static av_cold int init(AVCodecContext *avctx)
#define flags(name, subs,...)
static int FUNC() sei(CodedBitstreamContext *ctx, RWContext *rw, H264RawSEI *current)
float fminf(float, float)
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
Check AVPacket size and/or allocate data.
#define pthread_mutex_lock(a)
#define pthread_mutex_unlock(a)
#define AV_NUM_DATA_POINTERS
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
AVCodecID
Identify the syntax and semantics of the bitstream.
#define AV_CODEC_CAP_HARDWARE
Codec is backed by a hardware implementation.
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
#define AVERROR_EXTERNAL
Generic error in an external library.
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
#define AV_LOG_WARNING
Something somehow does not look correct.
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
const char * av_default_item_name(void *ptr)
Return the context name.
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
@ AV_PICTURE_TYPE_I
Intra.
#define LIBAVUTIL_VERSION_INT
H.264 common definitions.
#define FF_CODEC_CAP_INIT_THREADSAFE
The codec does not modify any global variables in the init function, allowing to call the init functi...
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
common internal API header
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
static enum AVPixelFormat pix_fmts[]
static const uint32_t color[16+AV_CLASS_CATEGORY_NB]
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
#define PTHREAD_ONCE_INIT
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
static av_always_inline int pthread_once(pthread_once_t *once_control, void(*init_routine)(void))
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
const char * av_color_transfer_name(enum AVColorTransferCharacteristic transfer)
const char * av_color_range_name(enum AVColorRange range)
const char * av_color_space_name(enum AVColorSpace space)
const char * av_color_primaries_name(enum AVColorPrimaries primaries)
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
AVColorRange
Visual content value range.
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
@ AVCOL_RANGE_UNSPECIFIED
@ AVCOL_RANGE_NB
Not part of ABI.
@ AVCOL_RANGE_JPEG
Full range content.
AVPixelFormat
Pixel format.
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
@ AV_PIX_FMT_P010LE
like NV12, with 10bpp per component, data in the high bits, zeros in the low bits,...
@ AV_PIX_FMT_VIDEOTOOLBOX
hardware decoding through Videotoolbox
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
@ AV_PIX_FMT_BGRA
packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
AVColorPrimaries
Chromaticity coordinates of the source primaries.
@ AVCOL_PRI_BT470BG
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM
@ AVCOL_PRI_BT709
also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B
@ AVCOL_PRI_SMPTE170M
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
@ AVCOL_PRI_BT2020
ITU-R BT2020.
AVColorTransferCharacteristic
Color Transfer Characteristic.
@ AVCOL_TRC_SMPTE2084
SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems.
@ AVCOL_TRC_GAMMA22
also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
@ AVCOL_TRC_LINEAR
"Linear transfer characteristics"
@ AVCOL_TRC_GAMMA28
also ITU-R BT470BG
@ AVCOL_TRC_ARIB_STD_B67
ARIB STD-B67, known as "Hybrid log-gamma".
@ AVCOL_TRC_BT2020_12
ITU-R BT2020 for 12-bit system.
@ AVCOL_TRC_BT2020_10
ITU-R BT2020 for 10-bit system.
@ AVCOL_TRC_BT709
also ITU-R BT1361
@ AVCOL_SPC_BT709
also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
@ AVCOL_SPC_BT470BG
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
@ AVCOL_SPC_RGB
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB)
@ AVCOL_SPC_BT2020_NCL
ITU-R BT2020 non-constant luminance system.
@ AVCOL_SPC_SMPTE170M
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
@ AVCOL_SPC_SMPTE240M
functionally identical to above
enum AVMediaType codec_type
@ SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35
Describe the class of an AVClass context structure.
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
main external API structure.
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
int width
picture width / height.
int global_quality
Global quality for codecs which cannot change it per frame.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
int max_b_frames
maximum number of B-frames between non-B-frames Note: The output will be delayed by max_b_frames+1 re...
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
int has_b_frames
Size of the frame reordering buffer in the decoder.
int64_t bit_rate
the average bitrate
enum AVColorSpace colorspace
YUV colorspace type.
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
int64_t rc_max_rate
maximum bitrate
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
int flags
AV_CODEC_FLAG_*.
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
const char * name
Name of the codec implementation.
Structure to hold side data for an AVFrame.
This structure describes decoded (raw) audio or video data.
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
enum AVPictureType pict_type
Picture type of the frame.
This structure stores compressed data.
int flags
A combination of AV_PKT_FLAG values.
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Rational number (pair of numerator and denominator).
CMSampleBufferRef cm_buffer
pthread_cond_t cv_sample_sent
CFStringRef transfer_function
getParameterSetAtIndex get_param_set_func
VTCompressionSessionRef session
CFStringRef color_primaries
static int get_frame(AVFilterContext *ctx, int is_second)
static const uint8_t offset[127][2]