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);
95 #define GET_SYM(symbol, defaultVal) \ 97 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \ 99 compat_keys.symbol = CFSTR(defaultVal); \ 101 compat_keys.symbol = *handle; \ 107 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
110 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex" 147 "EnableHardwareAcceleratedVideoEncoder");
149 "RequireHardwareAcceleratedVideoEncoder");
228 CFStringRef profile_level,
229 CFNumberRef gamma_level,
230 CFDictionaryRef enc_info,
231 CFDictionaryRef pixel_buffer_info);
310 }
else if (info->
sei) {
349 CMSampleBufferRef sample_buffer,
356 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
357 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
359 if (length_code_size > 4)
362 while (offset < src_size) {
367 status = CMBlockBufferCopyDataBytes(block,
372 for (i = 0; i < length_code_size; i++) {
374 box_len |= size_buf[
i];
377 curr_src_len = box_len + length_code_size;
378 offset += curr_src_len;
406 CMVideoFormatDescriptionRef vid_fmt,
410 size_t total_size = 0;
412 int is_count_bad = 0;
427 for (i = 0; i < ps_count || is_count_bad; i++) {
441 if (i > 0 && is_count_bad) status = 0;
460 CMVideoFormatDescriptionRef vid_fmt,
466 int is_count_bad = 0;
484 for (i = 0; i < ps_count || is_count_bad; i++) {
496 if (i > 0 && is_count_bad) status = 0;
501 next_offset = offset +
sizeof(
start_code) + ps_size;
502 if (dst_size < next_offset) {
510 memcpy(dst + offset, ps, ps_size);
511 offset = next_offset;
524 CMVideoFormatDescriptionRef vid_fmt;
528 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
558 void *sourceFrameCtx,
560 VTEncodeInfoFlags
flags,
561 CMSampleBufferRef sample_buffer)
568 if(sample_buffer) CFRelease(sample_buffer);
572 if (status || !sample_buffer) {
591 CMSampleBufferRef sample_buffer,
595 CMVideoFormatDescriptionRef vid_fmt;
599 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
627 CFStringRef *profile_level_val)
637 *profile_level_val =
NULL;
644 switch (vtctx->
level) {
645 case 0: *profile_level_val =
646 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
647 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
648 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
649 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
650 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
651 case 40: *profile_level_val =
652 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
653 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
654 case 42: *profile_level_val =
655 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
656 case 50: *profile_level_val =
657 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
658 case 51: *profile_level_val =
659 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
660 case 52: *profile_level_val =
661 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
666 switch (vtctx->
level) {
667 case 0: *profile_level_val =
668 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
669 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
670 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
671 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
672 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
673 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
674 case 42: *profile_level_val =
676 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
677 case 51: *profile_level_val =
679 case 52: *profile_level_val =
685 switch (vtctx->
level) {
686 case 0: *profile_level_val =
687 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
688 case 30: *profile_level_val =
690 case 31: *profile_level_val =
692 case 32: *profile_level_val =
694 case 40: *profile_level_val =
696 case 41: *profile_level_val =
698 case 42: *profile_level_val =
700 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
701 case 51: *profile_level_val =
703 case 52: *profile_level_val =
709 if (!*profile_level_val) {
724 CFStringRef *profile_level_val)
729 *profile_level_val =
NULL;
744 if (!*profile_level_val) {
755 int* av_pixel_format,
764 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
765 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
768 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
769 kCVPixelFormatType_420YpCbCr8Planar;
786 CFDictionarySetValue(dict,
787 kCVImageBufferColorPrimariesKey,
792 CFDictionarySetValue(dict,
793 kCVImageBufferTransferFunctionKey,
798 CFDictionarySetValue(dict,
799 kCVImageBufferYCbCrMatrixKey,
805 CFMutableDictionaryRef* dict)
807 CFNumberRef cv_color_format_num =
NULL;
808 CFNumberRef width_num =
NULL;
809 CFNumberRef height_num =
NULL;
810 CFMutableDictionaryRef pixel_buffer_info =
NULL;
817 if (status)
return status;
819 pixel_buffer_info = CFDictionaryCreateMutable(
822 &kCFCopyStringDictionaryKeyCallBacks,
823 &kCFTypeDictionaryValueCallBacks);
825 if (!pixel_buffer_info)
goto pbinfo_nomem;
827 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
830 if (!cv_color_format_num)
goto pbinfo_nomem;
832 CFDictionarySetValue(pixel_buffer_info,
833 kCVPixelBufferPixelFormatTypeKey,
834 cv_color_format_num);
837 width_num = CFNumberCreate(kCFAllocatorDefault,
840 if (!width_num)
return AVERROR(ENOMEM);
842 CFDictionarySetValue(pixel_buffer_info,
843 kCVPixelBufferWidthKey,
847 height_num = CFNumberCreate(kCFAllocatorDefault,
850 if (!height_num)
goto pbinfo_nomem;
852 CFDictionarySetValue(pixel_buffer_info,
853 kCVPixelBufferHeightKey,
859 *dict = pixel_buffer_info;
866 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
872 CFStringRef *primaries)
881 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
885 *primaries =
compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
898 CFStringRef *transfer_fnc,
899 CFNumberRef *gamma_level)
907 *transfer_fnc =
NULL;
911 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
915 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
920 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
921 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
926 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
927 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
932 *transfer_fnc =
compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
946 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
955 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
959 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
963 *matrix =
compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
976 CFStringRef profile_level,
977 CFNumberRef gamma_level,
978 CFDictionaryRef enc_info,
979 CFDictionaryRef pixel_buffer_info,
980 VTCompressionSessionRef *session)
985 CFNumberRef bit_rate_num;
986 CFNumberRef bytes_per_second;
987 CFNumberRef one_second;
988 CFArrayRef data_rate_limits;
989 int64_t bytes_per_second_value = 0;
990 int64_t one_second_value = 0;
993 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1004 if (status || !vtctx->
session) {
1005 av_log(avctx,
AV_LOG_ERROR,
"Error: cannot create compression session: %d\n", status);
1007 #if !TARGET_OS_IPHONE 1009 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1016 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1017 kCFNumberSInt32Type,
1019 if (!bit_rate_num)
return AVERROR(ENOMEM);
1021 status = VTSessionSetProperty(vtctx->
session,
1022 kVTCompressionPropertyKey_AverageBitRate,
1024 CFRelease(bit_rate_num);
1033 bytes_per_second_value = max_rate >> 3;
1034 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1035 kCFNumberSInt64Type,
1036 &bytes_per_second_value);
1037 if (!bytes_per_second) {
1040 one_second_value = 1;
1041 one_second = CFNumberCreate(kCFAllocatorDefault,
1042 kCFNumberSInt64Type,
1045 CFRelease(bytes_per_second);
1048 nums[0] = (
void *)bytes_per_second;
1049 nums[1] = (
void *)one_second;
1050 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1051 (
const void **)nums,
1053 &kCFTypeArrayCallBacks);
1055 if (!data_rate_limits) {
1056 CFRelease(bytes_per_second);
1057 CFRelease(one_second);
1060 status = VTSessionSetProperty(vtctx->
session,
1061 kVTCompressionPropertyKey_DataRateLimits,
1064 CFRelease(bytes_per_second);
1065 CFRelease(one_second);
1066 CFRelease(data_rate_limits);
1076 if (profile_level) {
1077 status = VTSessionSetProperty(vtctx->
session,
1078 kVTCompressionPropertyKey_ProfileLevel,
1087 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1094 status = VTSessionSetProperty(vtctx->
session,
1095 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1097 CFRelease(interval);
1100 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'max key-frame interval' property: %d\n", status);
1106 status = VTSessionSetProperty(vtctx->
session,
1107 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1110 if (status == kVTPropertyNotSupportedErr) {
1111 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1112 }
else if (status) {
1118 status = VTSessionSetProperty(vtctx->
session,
1119 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1122 if (status == kVTPropertyNotSupportedErr) {
1123 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1124 }
else if (status) {
1132 CFMutableDictionaryRef par;
1139 num = CFNumberCreate(kCFAllocatorDefault,
1143 den = CFNumberCreate(kCFAllocatorDefault,
1149 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1151 &kCFCopyStringDictionaryKeyCallBacks,
1152 &kCFTypeDictionaryValueCallBacks);
1154 if (!par || !num || !den) {
1155 if (par) CFRelease(par);
1156 if (num) CFRelease(num);
1157 if (den) CFRelease(den);
1162 CFDictionarySetValue(
1164 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1167 CFDictionarySetValue(
1169 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1172 status = VTSessionSetProperty(vtctx->
session,
1173 kVTCompressionPropertyKey_PixelAspectRatio,
1183 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1194 status = VTSessionSetProperty(vtctx->
session,
1195 kVTCompressionPropertyKey_TransferFunction,
1205 status = VTSessionSetProperty(vtctx->
session,
1206 kVTCompressionPropertyKey_YCbCrMatrix,
1216 status = VTSessionSetProperty(vtctx->
session,
1217 kVTCompressionPropertyKey_ColorPrimaries,
1226 status = VTSessionSetProperty(vtctx->
session,
1227 kCVImageBufferGammaLevelKey,
1236 status = VTSessionSetProperty(vtctx->
session,
1237 kVTCompressionPropertyKey_AllowFrameReordering,
1241 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'allow frame reordering' property: %d\n", status);
1251 status = VTSessionSetProperty(vtctx->
session,
1252 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1261 status = VTSessionSetProperty(vtctx->
session,
1270 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1281 CFMutableDictionaryRef enc_info;
1282 CFMutableDictionaryRef pixel_buffer_info;
1285 CFStringRef profile_level;
1286 CFNumberRef gamma_level =
NULL;
1302 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1307 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1318 enc_info = CFDictionaryCreateMutable(
1319 kCFAllocatorDefault,
1321 &kCFCopyStringDictionaryKeyCallBacks,
1322 &kCFTypeDictionaryValueCallBacks
1325 if (!enc_info)
return AVERROR(ENOMEM);
1327 #if !TARGET_OS_IPHONE 1329 CFDictionarySetValue(enc_info,
1330 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1333 CFDictionarySetValue(enc_info,
1334 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1337 CFDictionarySetValue(enc_info,
1338 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1348 pixel_buffer_info =
NULL;
1379 CFRelease(gamma_level);
1381 if (pixel_buffer_info)
1382 CFRelease(pixel_buffer_info);
1384 CFRelease(enc_info);
1392 CFBooleanRef has_b_frames_cfbool;
1402 if (status)
return status;
1404 status = VTSessionCopyProperty(vtctx->
session,
1405 kVTCompressionPropertyKey_AllowFrameReordering,
1406 kCFAllocatorDefault,
1407 &has_b_frames_cfbool);
1409 if (!status && has_b_frames_cfbool) {
1411 vtctx->
has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1412 CFRelease(has_b_frames_cfbool);
1421 CFArrayRef attachments;
1422 CFDictionaryRef attachment;
1423 CFBooleanRef not_sync;
1426 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer,
false);
1427 len = !attachments ? 0 : CFArrayGetCount(attachments);
1430 *is_key_frame =
true;
1434 attachment = CFArrayGetValueAtIndex(attachments, 0);
1436 if (CFDictionaryGetValueIfPresent(attachment,
1437 kCMSampleAttachmentKey_NotSync,
1438 (
const void **)¬_sync))
1440 *is_key_frame = !CFBooleanGetValue(not_sync);
1442 *is_key_frame =
true;
1463 size_t sei_payload_size = 0;
1464 int sei_payload_type = 0;
1466 uint8_t *nal_start = nal_data;
1471 nal_type = *nal_data & 0x1F;
1478 if (nal_data[nal_size - 1] == 0x80)
1481 while (nal_size > 0 && *nal_data > 0) {
1483 sei_payload_type += *nal_data;
1486 }
while (nal_size > 0 && *nal_data == 0xFF);
1494 sei_payload_size += *nal_data;
1497 }
while (nal_size > 0 && *nal_data == 0xFF);
1499 if (nal_size < sei_payload_size) {
1504 nal_data += sei_payload_size;
1505 nal_size -= sei_payload_size;
1508 *sei_end = nal_data;
1510 return nal_data - nal_start + 1;
1530 uint8_t* dst_end = dst + dst_size;
1531 const uint8_t* src_end = src + src_size;
1532 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1534 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1543 for (; src < src_end; src++, dst++) {
1545 int insert_ep3_byte = *src <= 3;
1546 if (insert_ep3_byte) {
1564 wrote_bytes = dst - dst_start;
1567 return -wrote_bytes;
1578 size_t remaining_sei_size = sei->
size;
1579 size_t remaining_dst_size = dst_size;
1584 if (!remaining_dst_size)
1587 while (sei_type && remaining_dst_size != 0) {
1588 int sei_byte = sei_type > 255 ? 255 : sei_type;
1591 sei_type -= sei_byte;
1593 remaining_dst_size--;
1599 while (remaining_sei_size && remaining_dst_size != 0) {
1600 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1603 remaining_sei_size -= size_byte;
1605 remaining_dst_size--;
1608 if (remaining_dst_size < sei->
size)
1611 header_bytes = dst - sei_start;
1613 offset = header_bytes;
1619 if (bytes_written < 0)
1622 bytes_written += header_bytes;
1623 return bytes_written;
1647 size_t length_code_size,
1648 CMSampleBufferRef sample_buffer,
1653 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1654 size_t remaining_src_size = src_size;
1655 size_t remaining_dst_size = dst_size;
1656 size_t src_offset = 0;
1661 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1663 if (length_code_size > 4) {
1667 while (remaining_src_size > 0) {
1668 size_t curr_src_len;
1669 size_t curr_dst_len;
1675 status = CMBlockBufferCopyDataBytes(block,
1684 status = CMBlockBufferCopyDataBytes(block,
1685 src_offset + length_code_size,
1696 for (i = 0; i < length_code_size; i++) {
1698 box_len |= size_buf[
i];
1711 remaining_dst_size--;
1716 remaining_dst_size);
1718 if (wrote_bytes < 0)
1721 remaining_dst_size -= wrote_bytes;
1722 dst_data += wrote_bytes;
1724 if (remaining_dst_size <= 0)
1730 remaining_dst_size--;
1735 curr_src_len = box_len + length_code_size;
1738 if (remaining_src_size < curr_src_len) {
1742 if (remaining_dst_size < curr_dst_len) {
1749 status = CMBlockBufferCopyDataBytes(block,
1750 src_offset + length_code_size,
1765 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1766 if (old_sei_length < 0)
1772 remaining_dst_size - old_sei_length);
1773 if (wrote_bytes < 0)
1776 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1779 new_sei[wrote_bytes++] = 0x80;
1780 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1782 dst_data += extra_bytes;
1783 remaining_dst_size -= extra_bytes;
1788 src_offset += curr_src_len;
1789 dst_data += curr_dst_len;
1791 remaining_src_size -= curr_src_len;
1792 remaining_dst_size -= curr_dst_len;
1813 if ((sei->
size % 255) == 0)
1816 return copied_size + sei->
size / 255 + 1 + type / 255 + 1;
1821 CMSampleBufferRef sample_buffer,
1830 size_t length_code_size;
1831 size_t header_size = 0;
1833 size_t out_buf_size;
1834 size_t sei_nalu_size = 0;
1836 int64_t time_base_num;
1840 CMVideoFormatDescriptionRef vid_fmt;
1845 if (status)
return status;
1850 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1857 if (status)
return status;
1860 status =
count_nalus(length_code_size, sample_buffer, &nalu_count);
1868 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
1871 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1872 out_buf_size = header_size +
1883 if(status)
return status;
1891 pkt->
data + header_size,
1892 pkt->
size - header_size
1904 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1905 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1907 if (CMTIME_IS_INVALID(dts)) {
1918 pkt->
pts = pts.value / time_base_num;
1919 pkt->
dts = dts.value / time_base_num - dts_delta;
1920 pkt->
size = out_buf_size;
1937 size_t *contiguous_buf_size)
1940 int av_format = frame->
format;
1950 "Could not get pixel format for color format '%s' range '%s'.\n",
1960 if (range_guessed) {
1965 "Color range not set for %s. Using MPEG range.\n",
1970 switch (av_format) {
1974 widths [0] = avctx->
width;
1975 heights[0] = avctx->
height;
1978 widths [1] = (avctx->
width + 1) / 2;
1979 heights[1] = (avctx->
height + 1) / 2;
1980 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) & -2;
1986 widths [0] = avctx->
width;
1987 heights[0] = avctx->
height;
1990 widths [1] = (avctx->
width + 1) / 2;
1991 heights[1] = (avctx->
height + 1) / 2;
1992 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) / 2;
1994 widths [2] = (avctx->
width + 1) / 2;
1995 heights[2] = (avctx->
height + 1) / 2;
1996 strides[2] = frame ? frame->
linesize[2] : (avctx->
width + 1) / 2;
2001 widths[0] = avctx->
width;
2002 heights[0] = avctx->
height;
2003 strides[0] = frame ? frame->
linesize[0] : (avctx->
width * 2 + 63) & -64;
2005 widths[1] = (avctx->
width + 1) / 2;
2006 heights[1] = (avctx->
height + 1) / 2;
2007 strides[1] = frame ? frame->
linesize[1] : ((avctx->
width + 1) / 2 + 63) & -64;
2014 "Could not get frame format info for color %d range %d.\n",
2021 *contiguous_buf_size = 0;
2022 for (i = 0; i < *plane_count; i++) {
2023 if (i < *plane_count - 1 &&
2024 frame->
data[i] + strides[i] * heights[i] != frame->
data[i + 1]) {
2025 *contiguous_buf_size = 0;
2029 *contiguous_buf_size += strides[
i] * heights[
i];
2038 CVPixelBufferRef cv_img,
2039 const size_t *plane_strides,
2040 const size_t *plane_rows)
2052 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2057 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2062 if (CVPixelBufferIsPlanar(cv_img)) {
2063 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2064 for (i = 0; frame->
data[
i]; i++) {
2065 if (i == plane_count) {
2066 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2069 "Error: different number of planes in AVFrame and CVPixelBuffer.\n" 2075 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2077 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2078 src_stride = plane_strides[
i];
2079 rows = plane_rows[
i];
2081 if (dst_stride == src_stride) {
2082 memcpy(dst_addr, src_addr, src_stride * rows);
2084 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2086 for (j = 0; j < rows; j++) {
2087 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2092 if (frame->
data[1]) {
2093 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2096 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n" 2102 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2104 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2105 src_stride = plane_strides[0];
2106 rows = plane_rows[0];
2108 if (dst_stride == src_stride) {
2109 memcpy(dst_addr, src_addr, src_stride * rows);
2111 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2113 for (j = 0; j < rows; j++) {
2114 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2119 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2121 av_log(avctx,
AV_LOG_ERROR,
"Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2130 CVPixelBufferRef *cv_img)
2138 size_t contiguous_buf_size;
2139 CVPixelBufferPoolRef pix_buf_pool;
2145 *cv_img = (CVPixelBufferRef)frame->
data[3];
2152 memset(widths, 0,
sizeof(widths));
2153 memset(heights, 0,
sizeof(heights));
2154 memset(strides, 0,
sizeof(strides));
2164 &contiguous_buf_size
2171 "Error: Cannot convert format %d color_range %d: %d\n",
2180 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2181 if (!pix_buf_pool) {
2188 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2189 if (vtstatus == kVTInvalidSessionErr) {
2194 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2196 if (!pix_buf_pool) {
2202 "kVTInvalidSessionErr error.\n");
2205 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2211 av_log(avctx,
AV_LOG_ERROR,
"Could not create pixel buffer from pool: %d.\n", status);
2226 CFDictionaryRef* dict_out)
2228 CFDictionaryRef dict =
NULL;
2230 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2231 const void *vals[] = { kCFBooleanTrue };
2233 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2234 if(!dict)
return AVERROR(ENOMEM);
2246 CFDictionaryRef frame_dict;
2247 CVPixelBufferRef cv_img =
NULL;
2252 if (status)
return status;
2261 if (vtctx->
a53_cc && side_data && side_data->
size) {
2276 status = VTCompressionSessionEncodeFrame(
2286 if (frame_dict) CFRelease(frame_dict);
2327 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2345 if (status)
goto end_nopkt;
2346 if (!buf)
goto end_nopkt;
2354 if (status)
goto end_nopkt;
2366 CFStringRef profile_level,
2367 CFNumberRef gamma_level,
2368 CFDictionaryRef enc_info,
2369 CFDictionaryRef pixel_buffer_info)
2373 CVPixelBufferPoolRef pool =
NULL;
2374 CVPixelBufferRef pix_buf =
NULL;
2388 pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2394 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2398 if(status != kCVReturnSuccess){
2404 status = VTCompressionSessionEncodeFrame(vtctx->
session,
2415 "Error sending frame for extradata: %d\n",
2422 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2459 VTCompressionSessionCompleteFrames(vtctx->
session,
2498 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM 2499 #define COMMON_OPTIONS \ 2500 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \ 2501 { .i64 = 0 }, 0, 1, VE }, \ 2502 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \ 2503 { .i64 = 0 }, 0, 1, VE }, \ 2504 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \ 2505 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \ 2506 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \ 2507 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \ 2508 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \ 2509 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, 2511 #define OFFSET(x) offsetof(VTEncContext, x) 2519 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2520 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2521 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2522 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2523 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2524 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2525 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2526 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2527 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2528 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2550 .
name =
"h264_videotoolbox",
2560 .priv_class = &h264_videotoolbox_class,
2582 .
name =
"hevc_videotoolbox",
2592 .priv_class = &hevc_videotoolbox_class,
2595 .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)
#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
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.
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...
#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...
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