21 #include <VideoToolbox/VideoToolbox.h> 22 #include <CoreVideo/CoreVideo.h> 23 #include <CoreMedia/CoreMedia.h> 24 #include <TargetConditionals.h> 25 #include <Availability.h> 38 #if !HAVE_KCMVIDEOCODECTYPE_HEVC 42 #if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE 48 size_t parameterSetIndex,
49 const uint8_t **parameterSetPointerOut,
50 size_t *parameterSetSizeOut,
51 size_t *parameterSetCountOut,
52 int *NALUnitHeaderLengthOut);
97 #define GET_SYM(symbol, defaultVal) \ 99 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \ 101 compat_keys.symbol = CFSTR(defaultVal); \ 103 compat_keys.symbol = *handle; \ 109 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
112 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex" 151 "EnableHardwareAcceleratedVideoEncoder");
153 "RequireHardwareAcceleratedVideoEncoder");
233 CFStringRef profile_level,
234 CFNumberRef gamma_level,
235 CFDictionaryRef enc_info,
236 CFDictionaryRef pixel_buffer_info);
315 }
else if (info->
sei) {
354 CMSampleBufferRef sample_buffer,
361 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
362 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
364 if (length_code_size > 4)
367 while (offset < src_size) {
372 status = CMBlockBufferCopyDataBytes(block,
377 for (i = 0; i < length_code_size; i++) {
379 box_len |= size_buf[
i];
382 curr_src_len = box_len + length_code_size;
383 offset += curr_src_len;
411 CMVideoFormatDescriptionRef vid_fmt,
415 size_t total_size = 0;
417 int is_count_bad = 0;
432 for (i = 0; i < ps_count || is_count_bad; i++) {
446 if (i > 0 && is_count_bad) status = 0;
465 CMVideoFormatDescriptionRef vid_fmt,
471 int is_count_bad = 0;
489 for (i = 0; i < ps_count || is_count_bad; i++) {
501 if (i > 0 && is_count_bad) status = 0;
506 next_offset = offset +
sizeof(
start_code) + ps_size;
507 if (dst_size < next_offset) {
515 memcpy(dst + offset, ps, ps_size);
516 offset = next_offset;
529 CMVideoFormatDescriptionRef vid_fmt;
533 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
563 void *sourceFrameCtx,
565 VTEncodeInfoFlags
flags,
566 CMSampleBufferRef sample_buffer)
573 if(sample_buffer) CFRelease(sample_buffer);
583 if (!sample_buffer) {
600 CMSampleBufferRef sample_buffer,
604 CMVideoFormatDescriptionRef vid_fmt;
608 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
636 CFStringRef *profile_level_val)
646 *profile_level_val =
NULL;
653 switch (vtctx->
level) {
654 case 0: *profile_level_val =
655 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
656 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
657 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
658 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
659 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
660 case 40: *profile_level_val =
661 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
662 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
663 case 42: *profile_level_val =
664 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
665 case 50: *profile_level_val =
666 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
667 case 51: *profile_level_val =
668 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
669 case 52: *profile_level_val =
670 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
675 switch (vtctx->
level) {
676 case 0: *profile_level_val =
677 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
678 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
679 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
680 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
681 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
682 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
683 case 42: *profile_level_val =
685 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
686 case 51: *profile_level_val =
688 case 52: *profile_level_val =
694 switch (vtctx->
level) {
695 case 0: *profile_level_val =
696 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
697 case 30: *profile_level_val =
699 case 31: *profile_level_val =
701 case 32: *profile_level_val =
703 case 40: *profile_level_val =
705 case 41: *profile_level_val =
707 case 42: *profile_level_val =
709 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
710 case 51: *profile_level_val =
712 case 52: *profile_level_val =
717 switch (vtctx->
level) {
718 case 0: *profile_level_val =
719 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel;
break;
720 case 50: *profile_level_val =
721 compat_keys.kVTProfileLevel_H264_Extended_5_0;
break;
726 if (!*profile_level_val) {
741 CFStringRef *profile_level_val)
746 *profile_level_val =
NULL;
761 if (!*profile_level_val) {
772 int* av_pixel_format,
781 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
782 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
785 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
786 kCVPixelFormatType_420YpCbCr8Planar;
803 CFDictionarySetValue(dict,
804 kCVImageBufferColorPrimariesKey,
809 CFDictionarySetValue(dict,
810 kCVImageBufferTransferFunctionKey,
815 CFDictionarySetValue(dict,
816 kCVImageBufferYCbCrMatrixKey,
822 CFMutableDictionaryRef* dict)
824 CFNumberRef cv_color_format_num =
NULL;
825 CFNumberRef width_num =
NULL;
826 CFNumberRef height_num =
NULL;
827 CFMutableDictionaryRef pixel_buffer_info =
NULL;
834 if (status)
return status;
836 pixel_buffer_info = CFDictionaryCreateMutable(
839 &kCFCopyStringDictionaryKeyCallBacks,
840 &kCFTypeDictionaryValueCallBacks);
842 if (!pixel_buffer_info)
goto pbinfo_nomem;
844 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
847 if (!cv_color_format_num)
goto pbinfo_nomem;
849 CFDictionarySetValue(pixel_buffer_info,
850 kCVPixelBufferPixelFormatTypeKey,
851 cv_color_format_num);
854 width_num = CFNumberCreate(kCFAllocatorDefault,
857 if (!width_num)
return AVERROR(ENOMEM);
859 CFDictionarySetValue(pixel_buffer_info,
860 kCVPixelBufferWidthKey,
864 height_num = CFNumberCreate(kCFAllocatorDefault,
867 if (!height_num)
goto pbinfo_nomem;
869 CFDictionarySetValue(pixel_buffer_info,
870 kCVPixelBufferHeightKey,
876 *dict = pixel_buffer_info;
883 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
889 CFStringRef *primaries)
898 *primaries = kCVImageBufferColorPrimaries_EBU_3213;
902 *primaries = kCVImageBufferColorPrimaries_SMPTE_C;
906 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
910 *primaries =
compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
923 CFStringRef *transfer_fnc,
924 CFNumberRef *gamma_level)
932 *transfer_fnc =
NULL;
936 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
940 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
943 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_SMPTE_ST_2084_PQ 945 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_ST_2084_PQ;
948 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_LINEAR 950 *transfer_fnc = kCVImageBufferTransferFunction_Linear;
953 #if HAVE_KCVIMAGEBUFFERTRANSFERFUNCTION_ITU_R_2100_HLG 955 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2100_HLG;
961 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
962 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
967 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
968 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
973 *transfer_fnc =
compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
977 *transfer_fnc =
NULL;
988 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
997 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
1001 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
1005 *matrix =
compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
1018 CFStringRef profile_level,
1019 CFNumberRef gamma_level,
1020 CFDictionaryRef enc_info,
1021 CFDictionaryRef pixel_buffer_info,
1022 VTCompressionSessionRef *session)
1027 CFNumberRef bit_rate_num;
1028 CFNumberRef bytes_per_second;
1029 CFNumberRef one_second;
1030 CFArrayRef data_rate_limits;
1031 int64_t bytes_per_second_value = 0;
1035 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1041 kCFAllocatorDefault,
1046 if (status || !vtctx->
session) {
1047 av_log(avctx,
AV_LOG_ERROR,
"Error: cannot create compression session: %d\n", status);
1049 #if !TARGET_OS_IPHONE 1051 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1058 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1059 kCFNumberSInt32Type,
1061 if (!bit_rate_num)
return AVERROR(ENOMEM);
1063 status = VTSessionSetProperty(vtctx->
session,
1064 kVTCompressionPropertyKey_AverageBitRate,
1066 CFRelease(bit_rate_num);
1075 bytes_per_second_value = max_rate >> 3;
1076 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1077 kCFNumberSInt64Type,
1078 &bytes_per_second_value);
1079 if (!bytes_per_second) {
1082 one_second_value = 1;
1083 one_second = CFNumberCreate(kCFAllocatorDefault,
1084 kCFNumberSInt64Type,
1087 CFRelease(bytes_per_second);
1090 nums[0] = (
void *)bytes_per_second;
1091 nums[1] = (
void *)one_second;
1092 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1093 (
const void **)nums,
1095 &kCFTypeArrayCallBacks);
1097 if (!data_rate_limits) {
1098 CFRelease(bytes_per_second);
1099 CFRelease(one_second);
1102 status = VTSessionSetProperty(vtctx->
session,
1103 kVTCompressionPropertyKey_DataRateLimits,
1106 CFRelease(bytes_per_second);
1107 CFRelease(one_second);
1108 CFRelease(data_rate_limits);
1118 if (profile_level) {
1119 status = VTSessionSetProperty(vtctx->
session,
1120 kVTCompressionPropertyKey_ProfileLevel,
1123 av_log(avctx,
AV_LOG_ERROR,
"Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1129 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1136 status = VTSessionSetProperty(vtctx->
session,
1137 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1139 CFRelease(interval);
1142 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'max key-frame interval' property: %d\n", status);
1148 status = VTSessionSetProperty(vtctx->
session,
1149 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1152 if (status == kVTPropertyNotSupportedErr) {
1153 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1154 }
else if (status) {
1160 status = VTSessionSetProperty(vtctx->
session,
1161 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1164 if (status == kVTPropertyNotSupportedErr) {
1165 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1166 }
else if (status) {
1174 CFMutableDictionaryRef par;
1181 num = CFNumberCreate(kCFAllocatorDefault,
1185 den = CFNumberCreate(kCFAllocatorDefault,
1191 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1193 &kCFCopyStringDictionaryKeyCallBacks,
1194 &kCFTypeDictionaryValueCallBacks);
1196 if (!par || !num || !den) {
1197 if (par) CFRelease(par);
1198 if (num) CFRelease(num);
1199 if (den) CFRelease(den);
1204 CFDictionarySetValue(
1206 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1209 CFDictionarySetValue(
1211 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1214 status = VTSessionSetProperty(vtctx->
session,
1215 kVTCompressionPropertyKey_PixelAspectRatio,
1225 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1236 status = VTSessionSetProperty(vtctx->
session,
1237 kVTCompressionPropertyKey_TransferFunction,
1247 status = VTSessionSetProperty(vtctx->
session,
1248 kVTCompressionPropertyKey_YCbCrMatrix,
1258 status = VTSessionSetProperty(vtctx->
session,
1259 kVTCompressionPropertyKey_ColorPrimaries,
1268 status = VTSessionSetProperty(vtctx->
session,
1269 kCVImageBufferGammaLevelKey,
1278 status = VTSessionSetProperty(vtctx->
session,
1279 kVTCompressionPropertyKey_AllowFrameReordering,
1283 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'allow frame reordering' property: %d\n", status);
1293 status = VTSessionSetProperty(vtctx->
session,
1294 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1303 status = VTSessionSetProperty(vtctx->
session,
1312 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1323 CFMutableDictionaryRef enc_info;
1324 CFMutableDictionaryRef pixel_buffer_info;
1327 CFStringRef profile_level;
1328 CFNumberRef gamma_level =
NULL;
1344 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1349 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1360 enc_info = CFDictionaryCreateMutable(
1361 kCFAllocatorDefault,
1363 &kCFCopyStringDictionaryKeyCallBacks,
1364 &kCFTypeDictionaryValueCallBacks
1367 if (!enc_info)
return AVERROR(ENOMEM);
1369 #if !TARGET_OS_IPHONE 1371 CFDictionarySetValue(enc_info,
1372 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1375 CFDictionarySetValue(enc_info,
1376 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1379 CFDictionarySetValue(enc_info,
1380 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1390 pixel_buffer_info =
NULL;
1421 CFRelease(gamma_level);
1423 if (pixel_buffer_info)
1424 CFRelease(pixel_buffer_info);
1426 CFRelease(enc_info);
1434 CFBooleanRef has_b_frames_cfbool;
1444 if (status)
return status;
1446 status = VTSessionCopyProperty(vtctx->
session,
1447 kVTCompressionPropertyKey_AllowFrameReordering,
1448 kCFAllocatorDefault,
1449 &has_b_frames_cfbool);
1451 if (!status && has_b_frames_cfbool) {
1453 vtctx->
has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1454 CFRelease(has_b_frames_cfbool);
1463 CFArrayRef attachments;
1464 CFDictionaryRef attachment;
1465 CFBooleanRef not_sync;
1468 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer,
false);
1469 len = !attachments ? 0 : CFArrayGetCount(attachments);
1472 *is_key_frame =
true;
1476 attachment = CFArrayGetValueAtIndex(attachments, 0);
1478 if (CFDictionaryGetValueIfPresent(attachment,
1479 kCMSampleAttachmentKey_NotSync,
1480 (
const void **)¬_sync))
1482 *is_key_frame = !CFBooleanGetValue(not_sync);
1484 *is_key_frame =
true;
1505 size_t sei_payload_size = 0;
1506 int sei_payload_type = 0;
1508 uint8_t *nal_start = nal_data;
1513 nal_type = *nal_data & 0x1F;
1520 if (nal_data[nal_size - 1] == 0x80)
1523 while (nal_size > 0 && *nal_data > 0) {
1525 sei_payload_type += *nal_data;
1528 }
while (nal_size > 0 && *nal_data == 0xFF);
1536 sei_payload_size += *nal_data;
1539 }
while (nal_size > 0 && *nal_data == 0xFF);
1541 if (nal_size < sei_payload_size) {
1546 nal_data += sei_payload_size;
1547 nal_size -= sei_payload_size;
1550 *sei_end = nal_data;
1552 return nal_data - nal_start + 1;
1572 uint8_t* dst_end = dst + dst_size;
1573 const uint8_t* src_end = src + src_size;
1574 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1576 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1585 for (; src < src_end; src++, dst++) {
1587 int insert_ep3_byte = *src <= 3;
1588 if (insert_ep3_byte) {
1606 wrote_bytes = dst - dst_start;
1609 return -wrote_bytes;
1620 size_t remaining_sei_size = sei->
size;
1621 size_t remaining_dst_size = dst_size;
1626 if (!remaining_dst_size)
1629 while (sei_type && remaining_dst_size != 0) {
1630 int sei_byte = sei_type > 255 ? 255 : sei_type;
1633 sei_type -= sei_byte;
1635 remaining_dst_size--;
1641 while (remaining_sei_size && remaining_dst_size != 0) {
1642 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1645 remaining_sei_size -= size_byte;
1647 remaining_dst_size--;
1650 if (remaining_dst_size < sei->
size)
1653 header_bytes = dst - sei_start;
1655 offset = header_bytes;
1661 if (bytes_written < 0)
1664 bytes_written += header_bytes;
1665 return bytes_written;
1689 size_t length_code_size,
1690 CMSampleBufferRef sample_buffer,
1695 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1696 size_t remaining_src_size = src_size;
1697 size_t remaining_dst_size = dst_size;
1698 size_t src_offset = 0;
1703 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1705 if (length_code_size > 4) {
1709 while (remaining_src_size > 0) {
1710 size_t curr_src_len;
1711 size_t curr_dst_len;
1717 status = CMBlockBufferCopyDataBytes(block,
1726 status = CMBlockBufferCopyDataBytes(block,
1727 src_offset + length_code_size,
1738 for (i = 0; i < length_code_size; i++) {
1740 box_len |= size_buf[
i];
1753 remaining_dst_size--;
1758 remaining_dst_size);
1760 if (wrote_bytes < 0)
1763 remaining_dst_size -= wrote_bytes;
1764 dst_data += wrote_bytes;
1766 if (remaining_dst_size <= 0)
1772 remaining_dst_size--;
1777 curr_src_len = box_len + length_code_size;
1780 if (remaining_src_size < curr_src_len) {
1784 if (remaining_dst_size < curr_dst_len) {
1791 status = CMBlockBufferCopyDataBytes(block,
1792 src_offset + length_code_size,
1807 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1808 if (old_sei_length < 0)
1814 remaining_dst_size - old_sei_length);
1815 if (wrote_bytes < 0)
1818 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1821 new_sei[wrote_bytes++] = 0x80;
1822 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1824 dst_data += extra_bytes;
1825 remaining_dst_size -= extra_bytes;
1830 src_offset += curr_src_len;
1831 dst_data += curr_dst_len;
1833 remaining_src_size -= curr_src_len;
1834 remaining_dst_size -= curr_dst_len;
1855 if ((sei->
size % 255) == 0)
1858 return copied_size + sei->
size / 255 + 1 + type / 255 + 1;
1863 CMSampleBufferRef sample_buffer,
1872 size_t length_code_size;
1873 size_t header_size = 0;
1875 size_t out_buf_size;
1876 size_t sei_nalu_size = 0;
1882 CMVideoFormatDescriptionRef vid_fmt;
1887 if (status)
return status;
1892 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1899 if (status)
return status;
1902 status =
count_nalus(length_code_size, sample_buffer, &nalu_count);
1910 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
1913 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1914 out_buf_size = header_size +
1925 if(status)
return status;
1933 pkt->
data + header_size,
1934 pkt->
size - header_size
1946 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1947 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1949 if (CMTIME_IS_INVALID(dts)) {
1960 pkt->
pts = pts.value / time_base_num;
1961 pkt->
dts = dts.value / time_base_num - dts_delta;
1962 pkt->
size = out_buf_size;
1979 size_t *contiguous_buf_size)
1982 int av_format = frame->
format;
1992 "Could not get pixel format for color format '%s' range '%s'.\n",
2002 if (range_guessed) {
2007 "Color range not set for %s. Using MPEG range.\n",
2012 switch (av_format) {
2016 widths [0] = avctx->
width;
2017 heights[0] = avctx->
height;
2020 widths [1] = (avctx->
width + 1) / 2;
2021 heights[1] = (avctx->
height + 1) / 2;
2022 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) & -2;
2028 widths [0] = avctx->
width;
2029 heights[0] = avctx->
height;
2032 widths [1] = (avctx->
width + 1) / 2;
2033 heights[1] = (avctx->
height + 1) / 2;
2034 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) / 2;
2036 widths [2] = (avctx->
width + 1) / 2;
2037 heights[2] = (avctx->
height + 1) / 2;
2038 strides[2] = frame ? frame->
linesize[2] : (avctx->
width + 1) / 2;
2043 widths[0] = avctx->
width;
2044 heights[0] = avctx->
height;
2045 strides[0] = frame ? frame->
linesize[0] : (avctx->
width * 2 + 63) & -64;
2047 widths[1] = (avctx->
width + 1) / 2;
2048 heights[1] = (avctx->
height + 1) / 2;
2049 strides[1] = frame ? frame->
linesize[1] : ((avctx->
width + 1) / 2 + 63) & -64;
2056 "Could not get frame format info for color %d range %d.\n",
2063 *contiguous_buf_size = 0;
2064 for (i = 0; i < *plane_count; i++) {
2065 if (i < *plane_count - 1 &&
2066 frame->
data[i] + strides[i] * heights[i] != frame->
data[i + 1]) {
2067 *contiguous_buf_size = 0;
2071 *contiguous_buf_size += strides[
i] * heights[
i];
2080 CVPixelBufferRef cv_img,
2081 const size_t *plane_strides,
2082 const size_t *plane_rows)
2094 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2099 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2104 if (CVPixelBufferIsPlanar(cv_img)) {
2105 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2106 for (i = 0; frame->
data[
i]; i++) {
2107 if (i == plane_count) {
2108 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2111 "Error: different number of planes in AVFrame and CVPixelBuffer.\n" 2117 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2119 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2120 src_stride = plane_strides[
i];
2121 rows = plane_rows[
i];
2123 if (dst_stride == src_stride) {
2124 memcpy(dst_addr, src_addr, src_stride * rows);
2126 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2128 for (j = 0; j < rows; j++) {
2129 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2134 if (frame->
data[1]) {
2135 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2138 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n" 2144 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2146 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2147 src_stride = plane_strides[0];
2148 rows = plane_rows[0];
2150 if (dst_stride == src_stride) {
2151 memcpy(dst_addr, src_addr, src_stride * rows);
2153 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2155 for (j = 0; j < rows; j++) {
2156 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2161 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2163 av_log(avctx,
AV_LOG_ERROR,
"Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2172 CVPixelBufferRef *cv_img)
2180 size_t contiguous_buf_size;
2181 CVPixelBufferPoolRef pix_buf_pool;
2187 *cv_img = (CVPixelBufferRef)frame->
data[3];
2194 memset(widths, 0,
sizeof(widths));
2195 memset(heights, 0,
sizeof(heights));
2196 memset(strides, 0,
sizeof(strides));
2206 &contiguous_buf_size
2213 "Error: Cannot convert format %d color_range %d: %d\n",
2222 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2223 if (!pix_buf_pool) {
2230 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2231 if (vtstatus == kVTInvalidSessionErr) {
2236 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2238 if (!pix_buf_pool) {
2244 "kVTInvalidSessionErr error.\n");
2247 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2253 av_log(avctx,
AV_LOG_ERROR,
"Could not create pixel buffer from pool: %d.\n", status);
2268 CFDictionaryRef* dict_out)
2270 CFDictionaryRef dict =
NULL;
2272 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2273 const void *vals[] = { kCFBooleanTrue };
2275 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2276 if(!dict)
return AVERROR(ENOMEM);
2288 CFDictionaryRef frame_dict;
2289 CVPixelBufferRef cv_img =
NULL;
2294 if (status)
return status;
2303 if (vtctx->
a53_cc && side_data && side_data->
size) {
2318 status = VTCompressionSessionEncodeFrame(
2328 if (frame_dict) CFRelease(frame_dict);
2348 CMSampleBufferRef buf =
NULL;
2369 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2387 if (status)
goto end_nopkt;
2388 if (!buf)
goto end_nopkt;
2396 if (status)
goto end_nopkt;
2408 CFStringRef profile_level,
2409 CFNumberRef gamma_level,
2410 CFDictionaryRef enc_info,
2411 CFDictionaryRef pixel_buffer_info)
2415 CVPixelBufferPoolRef pool =
NULL;
2416 CVPixelBufferRef pix_buf =
NULL;
2418 CMSampleBufferRef buf =
NULL;
2430 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2436 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2440 if(status != kCVReturnSuccess){
2446 status = VTCompressionSessionEncodeFrame(vtctx->
session,
2457 "Error sending frame for extradata: %d\n",
2464 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2501 VTCompressionSessionCompleteFrames(vtctx->
session,
2540 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM 2541 #define COMMON_OPTIONS \ 2542 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \ 2543 { .i64 = 0 }, 0, 1, VE }, \ 2544 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \ 2545 { .i64 = 0 }, 0, 1, VE }, \ 2546 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \ 2547 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \ 2548 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \ 2549 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \ 2550 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \ 2551 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, 2553 #define OFFSET(x) offsetof(VTEncContext, x) 2562 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2563 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2564 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2565 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2566 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2567 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2568 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2569 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2570 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2571 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2593 .
name =
"h264_videotoolbox",
2603 .priv_class = &h264_videotoolbox_class,
2625 .
name =
"hevc_videotoolbox",
2635 .priv_class = &hevc_videotoolbox_class,
2638 .wrapper_name =
"videotoolbox",
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
ITU-R BT2020 for 12-bit system.
also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
#define AV_NUM_DATA_POINTERS
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
pthread_cond_t cv_sample_sent
This structure describes decoded (raw) audio or video data.
#define pthread_mutex_lock(a)
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
"Linear transfer characteristics"
#define AV_LOG_WARNING
Something somehow does not look correct.
int64_t bit_rate
the average bitrate
#define LIBAVUTIL_VERSION_INT
hardware decoding through Videotoolbox
static av_cold int init(AVCodecContext *avctx)
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...
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601 ...
#define AV_CODEC_CAP_HARDWARE
Codec is backed by a hardware implementation.
enum AVColorRange color_range
MPEG vs JPEG YUV range.
const char * av_default_item_name(void *ptr)
Return the context name.
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel...
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
enum AVMediaType codec_type
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
AVColorTransferCharacteristic
Color Transfer Characteristic.
functionally identical to above
const char * av_color_space_name(enum AVColorSpace space)
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
#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_assert0(cond)
assert() equivalent, that is always enabled.
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
Check AVPacket size and/or allocate data.
#define FF_CODEC_CAP_INIT_THREADSAFE
The codec does not modify any global variables in the init function, allowing to call the init functi...
static const uint32_t color[16+AV_CLASS_CATEGORY_NB]
const char * av_color_range_name(enum AVColorRange range)
also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Structure to hold side data for an AVFrame.
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
AVColorRange
MPEG vs JPEG YUV range.
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
AVColorPrimaries
Chromaticity coordinates of the source primaries.
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
H.264 common definitions.
#define i(width, name, range_min, range_max)
AVCodecID
Identify the syntax and semantics of the bitstream.
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
int has_b_frames
Size of the frame reordering buffer in the decoder.
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
enum AVColorRange color_range
MPEG vs JPEG YUV range.
ATSC A53 Part 4 Closed Captions.
int flags
AV_CODEC_FLAG_*.
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B
simple assert() macros that are a bit more flexible than ISO C assert().
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
const char * name
Name of the codec implementation.
static const uint8_t offset[127][2]
static int get_frame(AVFilterContext *ctx, int is_second)
int flags
A combination of AV_PKT_FLAG values.
const char * av_color_primaries_name(enum AVColorPrimaries primaries)
VTCompressionSessionRef session
CFStringRef color_primaries
SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems.
enum AVPictureType pict_type
Picture type of the frame.
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
CMSampleBufferRef cm_buffer
int width
picture width / height.
ITU-R BT2020 non-constant luminance system.
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
#define pthread_mutex_unlock(a)
like NV12, with 10bpp per component, data in the high bits, zeros in the low bits, little-endian
the normal 2^n-1 "JPEG" YUV ranges
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Libavcodec external API header.
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
main external API structure.
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Describe the class of an AVClass context structure.
CFStringRef transfer_function
enum AVColorSpace colorspace
YUV colorspace type.
Rational number (pair of numerator and denominator).
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
registered user data as specified by Rec. ITU-T T.35
static enum AVPixelFormat pix_fmts[]
#define flags(name, subs,...)
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
the normal 219*2^(n-8) "MPEG" YUV ranges
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
getParameterSetAtIndex get_param_set_func
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
common internal api header.
const char * av_color_transfer_name(enum AVColorTransferCharacteristic transfer)
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
static int FUNC() sei(CodedBitstreamContext *ctx, RWContext *rw, H264RawSEI *current)
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
ARIB STD-B67, known as "Hybrid log-gamma".
#define PTHREAD_ONCE_INIT
ITU-R BT2020 for 10-bit system.
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
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.
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.
#define AVERROR_EXTERNAL
Generic error in an external library.
AVPixelFormat
Pixel format.
This structure stores compressed data.
static av_always_inline int pthread_once(pthread_once_t *once_control, void(*init_routine)(void))
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
int64_t rc_max_rate
maximum bitrate