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
43 size_t parameterSetIndex,
44 const uint8_t **parameterSetPointerOut,
45 size_t *parameterSetSizeOut,
46 size_t *parameterSetCountOut,
47 int *NALUnitHeaderLengthOut);
90 #define GET_SYM(symbol, defaultVal) \
92 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
94 compat_keys.symbol = CFSTR(defaultVal); \
96 compat_keys.symbol = *handle; \
102 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
105 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
142 "EnableHardwareAcceleratedVideoEncoder");
144 "RequireHardwareAcceleratedVideoEncoder");
222 CFStringRef profile_level,
223 CFNumberRef gamma_level,
224 CFDictionaryRef enc_info,
225 CFDictionaryRef pixel_buffer_info);
304 }
else if (info->
sei) {
343 CMSampleBufferRef sample_buffer,
350 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
351 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
353 if (length_code_size > 4)
356 while (offset < src_size) {
361 status = CMBlockBufferCopyDataBytes(block,
366 for (i = 0; i < length_code_size; i++) {
368 box_len |= size_buf[i];
371 curr_src_len = box_len + length_code_size;
372 offset += curr_src_len;
400 CMVideoFormatDescriptionRef vid_fmt,
404 size_t total_size = 0;
406 int is_count_bad = 0;
421 for (i = 0; i < ps_count || is_count_bad; i++) {
435 if (i > 0 && is_count_bad) status = 0;
454 CMVideoFormatDescriptionRef vid_fmt,
460 int is_count_bad = 0;
478 for (i = 0; i < ps_count || is_count_bad; i++) {
490 if (i > 0 && is_count_bad) status = 0;
495 next_offset = offset +
sizeof(
start_code) + ps_size;
496 if (dst_size < next_offset) {
504 memcpy(dst + offset, ps, ps_size);
505 offset = next_offset;
518 CMVideoFormatDescriptionRef vid_fmt;
522 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
552 void *sourceFrameCtx,
554 VTEncodeInfoFlags
flags,
555 CMSampleBufferRef sample_buffer)
562 if(sample_buffer) CFRelease(sample_buffer);
566 if (status || !sample_buffer) {
585 CMSampleBufferRef sample_buffer,
589 CMVideoFormatDescriptionRef vid_fmt;
593 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
621 CFStringRef *profile_level_val)
631 *profile_level_val =
NULL;
638 switch (vtctx->
level) {
639 case 0: *profile_level_val =
640 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
641 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
642 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
643 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
644 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
645 case 40: *profile_level_val =
646 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
647 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
648 case 42: *profile_level_val =
649 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
650 case 50: *profile_level_val =
651 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
652 case 51: *profile_level_val =
653 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
654 case 52: *profile_level_val =
655 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
660 switch (vtctx->
level) {
661 case 0: *profile_level_val =
662 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
663 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
664 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
665 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
666 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
667 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
668 case 42: *profile_level_val =
670 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
671 case 51: *profile_level_val =
673 case 52: *profile_level_val =
679 switch (vtctx->
level) {
680 case 0: *profile_level_val =
681 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
682 case 30: *profile_level_val =
684 case 31: *profile_level_val =
686 case 32: *profile_level_val =
688 case 40: *profile_level_val =
690 case 41: *profile_level_val =
692 case 42: *profile_level_val =
694 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
695 case 51: *profile_level_val =
697 case 52: *profile_level_val =
703 if (!*profile_level_val) {
718 CFStringRef *profile_level_val)
723 *profile_level_val =
NULL;
738 if (!*profile_level_val) {
749 int* av_pixel_format,
758 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
759 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
762 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
763 kCVPixelFormatType_420YpCbCr8Planar;
775 CFDictionarySetValue(dict,
776 kCVImageBufferColorPrimariesKey,
781 CFDictionarySetValue(dict,
782 kCVImageBufferTransferFunctionKey,
787 CFDictionarySetValue(dict,
788 kCVImageBufferYCbCrMatrixKey,
794 CFMutableDictionaryRef* dict)
796 CFNumberRef cv_color_format_num =
NULL;
797 CFNumberRef width_num =
NULL;
798 CFNumberRef height_num =
NULL;
799 CFMutableDictionaryRef pixel_buffer_info =
NULL;
806 if (status)
return status;
808 pixel_buffer_info = CFDictionaryCreateMutable(
811 &kCFCopyStringDictionaryKeyCallBacks,
812 &kCFTypeDictionaryValueCallBacks);
814 if (!pixel_buffer_info)
goto pbinfo_nomem;
816 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
819 if (!cv_color_format_num)
goto pbinfo_nomem;
821 CFDictionarySetValue(pixel_buffer_info,
822 kCVPixelBufferPixelFormatTypeKey,
823 cv_color_format_num);
826 width_num = CFNumberCreate(kCFAllocatorDefault,
829 if (!width_num)
return AVERROR(ENOMEM);
831 CFDictionarySetValue(pixel_buffer_info,
832 kCVPixelBufferWidthKey,
836 height_num = CFNumberCreate(kCFAllocatorDefault,
839 if (!height_num)
goto pbinfo_nomem;
841 CFDictionarySetValue(pixel_buffer_info,
842 kCVPixelBufferHeightKey,
848 *dict = pixel_buffer_info;
855 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
861 CFStringRef *primaries)
870 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
874 *primaries =
compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
887 CFStringRef *transfer_fnc,
888 CFNumberRef *gamma_level)
896 *transfer_fnc =
NULL;
900 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
904 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
909 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
910 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
915 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
916 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
921 *transfer_fnc =
compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
935 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
944 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
948 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
952 *matrix =
compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
965 CFStringRef profile_level,
966 CFNumberRef gamma_level,
967 CFDictionaryRef enc_info,
968 CFDictionaryRef pixel_buffer_info,
969 VTCompressionSessionRef *session)
974 CFNumberRef bit_rate_num;
975 CFNumberRef bytes_per_second;
976 CFNumberRef one_second;
977 CFArrayRef data_rate_limits;
978 int64_t bytes_per_second_value = 0;
979 int64_t one_second_value = 0;
982 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
993 if (status || !vtctx->
session) {
994 av_log(avctx,
AV_LOG_ERROR,
"Error: cannot create compression session: %d\n", status);
996 #if !TARGET_OS_IPHONE
998 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1005 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1006 kCFNumberSInt32Type,
1008 if (!bit_rate_num)
return AVERROR(ENOMEM);
1010 status = VTSessionSetProperty(vtctx->
session,
1011 kVTCompressionPropertyKey_AverageBitRate,
1013 CFRelease(bit_rate_num);
1022 bytes_per_second_value = max_rate >> 3;
1023 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1024 kCFNumberSInt64Type,
1025 &bytes_per_second_value);
1026 if (!bytes_per_second) {
1029 one_second_value = 1;
1030 one_second = CFNumberCreate(kCFAllocatorDefault,
1031 kCFNumberSInt64Type,
1034 CFRelease(bytes_per_second);
1037 nums[0] = (
void *)bytes_per_second;
1038 nums[1] = (
void *)one_second;
1039 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1040 (
const void **)nums,
1042 &kCFTypeArrayCallBacks);
1044 if (!data_rate_limits) {
1045 CFRelease(bytes_per_second);
1046 CFRelease(one_second);
1049 status = VTSessionSetProperty(vtctx->
session,
1050 kVTCompressionPropertyKey_DataRateLimits,
1053 CFRelease(bytes_per_second);
1054 CFRelease(one_second);
1055 CFRelease(data_rate_limits);
1065 if (profile_level) {
1066 status = VTSessionSetProperty(vtctx->
session,
1067 kVTCompressionPropertyKey_ProfileLevel,
1076 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1083 status = VTSessionSetProperty(vtctx->
session,
1084 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1086 CFRelease(interval);
1089 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'max key-frame interval' property: %d\n", status);
1095 status = VTSessionSetProperty(vtctx->
session,
1096 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1099 if (status == kVTPropertyNotSupportedErr) {
1100 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1101 }
else if (status) {
1107 status = VTSessionSetProperty(vtctx->
session,
1108 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1111 if (status == kVTPropertyNotSupportedErr) {
1112 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1113 }
else if (status) {
1121 CFMutableDictionaryRef par;
1128 num = CFNumberCreate(kCFAllocatorDefault,
1132 den = CFNumberCreate(kCFAllocatorDefault,
1138 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1140 &kCFCopyStringDictionaryKeyCallBacks,
1141 &kCFTypeDictionaryValueCallBacks);
1143 if (!par || !num || !den) {
1144 if (par) CFRelease(par);
1145 if (num) CFRelease(num);
1146 if (den) CFRelease(den);
1151 CFDictionarySetValue(
1153 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1156 CFDictionarySetValue(
1158 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1161 status = VTSessionSetProperty(vtctx->
session,
1162 kVTCompressionPropertyKey_PixelAspectRatio,
1172 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1183 status = VTSessionSetProperty(vtctx->
session,
1184 kVTCompressionPropertyKey_TransferFunction,
1194 status = VTSessionSetProperty(vtctx->
session,
1195 kVTCompressionPropertyKey_YCbCrMatrix,
1205 status = VTSessionSetProperty(vtctx->
session,
1206 kVTCompressionPropertyKey_ColorPrimaries,
1215 status = VTSessionSetProperty(vtctx->
session,
1216 kCVImageBufferGammaLevelKey,
1225 status = VTSessionSetProperty(vtctx->
session,
1226 kVTCompressionPropertyKey_AllowFrameReordering,
1230 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'allow frame reordering' property: %d\n", status);
1240 status = VTSessionSetProperty(vtctx->
session,
1241 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1250 status = VTSessionSetProperty(vtctx->
session,
1259 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1270 CFMutableDictionaryRef enc_info;
1271 CFMutableDictionaryRef pixel_buffer_info;
1274 CFStringRef profile_level;
1275 CFNumberRef gamma_level =
NULL;
1291 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1296 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1307 enc_info = CFDictionaryCreateMutable(
1308 kCFAllocatorDefault,
1310 &kCFCopyStringDictionaryKeyCallBacks,
1311 &kCFTypeDictionaryValueCallBacks
1314 if (!enc_info)
return AVERROR(ENOMEM);
1316 #if !TARGET_OS_IPHONE
1318 CFDictionarySetValue(enc_info,
1319 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1322 CFDictionarySetValue(enc_info,
1323 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1333 pixel_buffer_info =
NULL;
1364 CFRelease(gamma_level);
1366 if (pixel_buffer_info)
1367 CFRelease(pixel_buffer_info);
1369 CFRelease(enc_info);
1377 CFBooleanRef has_b_frames_cfbool;
1387 if (status)
return status;
1389 status = VTSessionCopyProperty(vtctx->
session,
1390 kVTCompressionPropertyKey_AllowFrameReordering,
1391 kCFAllocatorDefault,
1392 &has_b_frames_cfbool);
1394 if (!status && has_b_frames_cfbool) {
1396 vtctx->
has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1397 CFRelease(has_b_frames_cfbool);
1406 CFArrayRef attachments;
1407 CFDictionaryRef attachment;
1408 CFBooleanRef not_sync;
1411 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer,
false);
1412 len = !attachments ? 0 : CFArrayGetCount(attachments);
1415 *is_key_frame =
true;
1419 attachment = CFArrayGetValueAtIndex(attachments, 0);
1421 if (CFDictionaryGetValueIfPresent(attachment,
1422 kCMSampleAttachmentKey_NotSync,
1423 (
const void **)¬_sync))
1425 *is_key_frame = !CFBooleanGetValue(not_sync);
1427 *is_key_frame =
true;
1448 size_t sei_payload_size = 0;
1449 int sei_payload_type = 0;
1451 uint8_t *nal_start = nal_data;
1456 nal_type = *nal_data & 0x1F;
1463 if (nal_data[nal_size - 1] == 0x80)
1466 while (nal_size > 0 && *nal_data > 0) {
1468 sei_payload_type += *nal_data;
1471 }
while (nal_size > 0 && *nal_data == 0xFF);
1479 sei_payload_size += *nal_data;
1482 }
while (nal_size > 0 && *nal_data == 0xFF);
1484 if (nal_size < sei_payload_size) {
1489 nal_data += sei_payload_size;
1490 nal_size -= sei_payload_size;
1493 *sei_end = nal_data;
1495 return nal_data - nal_start + 1;
1515 uint8_t* dst_end = dst + dst_size;
1516 const uint8_t* src_end = src + src_size;
1517 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1519 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1528 for (; src < src_end; src++, dst++) {
1530 int insert_ep3_byte = *src <= 3;
1531 if (insert_ep3_byte) {
1549 wrote_bytes = dst - dst_start;
1552 return -wrote_bytes;
1563 size_t remaining_sei_size = sei->
size;
1564 size_t remaining_dst_size = dst_size;
1569 if (!remaining_dst_size)
1572 while (sei_type && remaining_dst_size != 0) {
1573 int sei_byte = sei_type > 255 ? 255 : sei_type;
1576 sei_type -= sei_byte;
1578 remaining_dst_size--;
1584 while (remaining_sei_size && remaining_dst_size != 0) {
1585 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1588 remaining_sei_size -= size_byte;
1590 remaining_dst_size--;
1593 if (remaining_dst_size < sei->
size)
1596 header_bytes = dst - sei_start;
1598 offset = header_bytes;
1604 if (bytes_written < 0)
1607 bytes_written += header_bytes;
1608 return bytes_written;
1632 size_t length_code_size,
1633 CMSampleBufferRef sample_buffer,
1638 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1639 size_t remaining_src_size = src_size;
1640 size_t remaining_dst_size = dst_size;
1641 size_t src_offset = 0;
1646 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1648 if (length_code_size > 4) {
1652 while (remaining_src_size > 0) {
1653 size_t curr_src_len;
1654 size_t curr_dst_len;
1660 status = CMBlockBufferCopyDataBytes(block,
1669 status = CMBlockBufferCopyDataBytes(block,
1670 src_offset + length_code_size,
1681 for (i = 0; i < length_code_size; i++) {
1683 box_len |= size_buf[i];
1696 remaining_dst_size--;
1701 remaining_dst_size);
1703 if (wrote_bytes < 0)
1706 remaining_dst_size -= wrote_bytes;
1707 dst_data += wrote_bytes;
1709 if (remaining_dst_size <= 0)
1715 remaining_dst_size--;
1720 curr_src_len = box_len + length_code_size;
1723 if (remaining_src_size < curr_src_len) {
1727 if (remaining_dst_size < curr_dst_len) {
1734 status = CMBlockBufferCopyDataBytes(block,
1735 src_offset + length_code_size,
1750 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1751 if (old_sei_length < 0)
1757 remaining_dst_size - old_sei_length);
1758 if (wrote_bytes < 0)
1761 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1764 new_sei[wrote_bytes++] = 0x80;
1765 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1767 dst_data += extra_bytes;
1768 remaining_dst_size -= extra_bytes;
1773 src_offset += curr_src_len;
1774 dst_data += curr_dst_len;
1776 remaining_src_size -= curr_src_len;
1777 remaining_dst_size -= curr_dst_len;
1798 if ((sei->
size % 255) == 0)
1801 return copied_size + sei->
size / 255 + 1 + type / 255 + 1;
1806 CMSampleBufferRef sample_buffer,
1815 size_t length_code_size;
1816 size_t header_size = 0;
1818 size_t out_buf_size;
1819 size_t sei_nalu_size = 0;
1821 int64_t time_base_num;
1825 CMVideoFormatDescriptionRef vid_fmt;
1830 if (status)
return status;
1835 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1842 if (status)
return status;
1845 status =
count_nalus(length_code_size, sample_buffer, &nalu_count);
1853 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
1856 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1857 out_buf_size = header_size +
1868 if(status)
return status;
1876 pkt->
data + header_size,
1877 pkt->
size - header_size
1889 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1890 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1892 if (CMTIME_IS_INVALID(dts)) {
1903 pkt->
pts = pts.value / time_base_num;
1904 pkt->
dts = dts.value / time_base_num - dts_delta;
1905 pkt->
size = out_buf_size;
1922 size_t *contiguous_buf_size)
1925 int av_format = frame->
format;
1935 "Could not get pixel format for color format '%s' range '%s'.\n",
1945 if (range_guessed) {
1950 "Color range not set for %s. Using MPEG range.\n",
1955 switch (av_format) {
1959 widths [0] = avctx->
width;
1960 heights[0] = avctx->
height;
1963 widths [1] = (avctx->
width + 1) / 2;
1964 heights[1] = (avctx->
height + 1) / 2;
1965 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) & -2;
1971 widths [0] = avctx->
width;
1972 heights[0] = avctx->
height;
1975 widths [1] = (avctx->
width + 1) / 2;
1976 heights[1] = (avctx->
height + 1) / 2;
1977 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) / 2;
1979 widths [2] = (avctx->
width + 1) / 2;
1980 heights[2] = (avctx->
height + 1) / 2;
1981 strides[2] = frame ? frame->
linesize[2] : (avctx->
width + 1) / 2;
1988 "Could not get frame format info for color %d range %d.\n",
1995 *contiguous_buf_size = 0;
1996 for (i = 0; i < *plane_count; i++) {
1997 if (i < *plane_count - 1 &&
1998 frame->
data[i] + strides[i] * heights[i] != frame->
data[i + 1]) {
1999 *contiguous_buf_size = 0;
2003 *contiguous_buf_size += strides[i] * heights[i];
2009 #if !TARGET_OS_IPHONE
2016 const void *plane_addresses[])
2025 CVPixelBufferRef cv_img,
2026 const size_t *plane_strides,
2027 const size_t *plane_rows)
2039 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2044 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
2049 if (CVPixelBufferIsPlanar(cv_img)) {
2050 plane_count = CVPixelBufferGetPlaneCount(cv_img);
2051 for (i = 0; frame->
data[i]; i++) {
2052 if (i == plane_count) {
2053 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2056 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
2062 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2064 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2065 src_stride = plane_strides[i];
2066 rows = plane_rows[i];
2068 if (dst_stride == src_stride) {
2069 memcpy(dst_addr, src_addr, src_stride * rows);
2071 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2073 for (j = 0; j < rows; j++) {
2074 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2079 if (frame->
data[1]) {
2080 CVPixelBufferUnlockBaseAddress(cv_img, 0);
2083 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
2089 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
2091 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
2092 src_stride = plane_strides[0];
2093 rows = plane_rows[0];
2095 if (dst_stride == src_stride) {
2096 memcpy(dst_addr, src_addr, src_stride * rows);
2098 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2100 for (j = 0; j < rows; j++) {
2101 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2106 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2108 av_log(avctx,
AV_LOG_ERROR,
"Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2118 CVPixelBufferRef *cv_img)
2126 size_t contiguous_buf_size;
2127 #if TARGET_OS_IPHONE
2128 CVPixelBufferPoolRef pix_buf_pool;
2131 CFMutableDictionaryRef pix_buf_attachments = CFDictionaryCreateMutable(
2132 kCFAllocatorDefault,
2134 &kCFCopyStringDictionaryKeyCallBacks,
2135 &kCFTypeDictionaryValueCallBacks);
2137 if (!pix_buf_attachments)
return AVERROR(ENOMEM);
2143 *cv_img = (CVPixelBufferRef)frame->
data[3];
2150 memset(widths, 0,
sizeof(widths));
2151 memset(heights, 0,
sizeof(heights));
2152 memset(strides, 0,
sizeof(strides));
2162 &contiguous_buf_size
2169 "Error: Cannot convert format %d color_range %d: %d\n",
2178 #if TARGET_OS_IPHONE
2179 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2180 if (!pix_buf_pool) {
2187 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
2188 if (vtstatus == kVTInvalidSessionErr) {
2193 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2195 if (!pix_buf_pool) {
2201 "kVTInvalidSessionErr error.\n");
2204 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2210 av_log(avctx,
AV_LOG_ERROR,
"Could not create pixel buffer from pool: %d.\n", status);
2214 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2222 if (!enc_frame)
return AVERROR(ENOMEM);
2230 status = CVPixelBufferCreateWithPlanarBytes(
2231 kCFAllocatorDefault,
2236 contiguous_buf_size,
2238 (
void **)enc_frame->
data,
2249 CVBufferSetAttachments(*cv_img, pix_buf_attachments, kCVAttachmentMode_ShouldPropagate);
2250 CFRelease(pix_buf_attachments);
2262 CFDictionaryRef* dict_out)
2264 CFDictionaryRef dict =
NULL;
2266 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2267 const void *vals[] = { kCFBooleanTrue };
2269 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2270 if(!dict)
return AVERROR(ENOMEM);
2282 CFDictionaryRef frame_dict;
2283 CVPixelBufferRef cv_img =
NULL;
2288 if (status)
return status;
2297 if (vtctx->
a53_cc && side_data && side_data->
size) {
2312 status = VTCompressionSessionEncodeFrame(
2322 if (frame_dict) CFRelease(frame_dict);
2363 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2381 if (status)
goto end_nopkt;
2382 if (!buf)
goto end_nopkt;
2390 if (status)
goto end_nopkt;
2402 CFStringRef profile_level,
2403 CFNumberRef gamma_level,
2404 CFDictionaryRef enc_info,
2405 CFDictionaryRef pixel_buffer_info)
2410 int chroma_size = (avctx->
width / 2) * (avctx->
height / 2);
2435 memset(frame->
data[0], 0, y_size);
2438 memset(frame->
data[1], 128, chroma_size);
2442 frame->
data[2] = frame->
buf[0]->
data + y_size + chroma_size;
2443 memset(frame->
data[2], 128, chroma_size);
2471 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2511 VTCompressionSessionCompleteFrames(vtctx->
session,
2542 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2543 #define COMMON_OPTIONS \
2544 { "allow_sw", "Allow software encoding", OFFSET(allow_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)
2561 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2562 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2563 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2564 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2565 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2566 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2567 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2568 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2569 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2570 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2592 .
name =
"h264_videotoolbox",
2597 .pix_fmts = pix_fmts,
2602 .priv_class = &h264_videotoolbox_class,
2624 .
name =
"hevc_videotoolbox",
2629 .pix_fmts = pix_fmts,
2634 .priv_class = &hevc_videotoolbox_class,
2637 .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)
ptrdiff_t const GLvoid * data
#define AV_LOG_WARNING
Something somehow does not look correct.
int64_t bit_rate
the average bitrate
#define LIBAVUTIL_VERSION_INT
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
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.
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
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...
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
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
int av_frame_ref(AVFrame *dst, const AVFrame *src)
Set up a new reference to the data described by the source frame.
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.
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.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
#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_*.
enum AVColorSpace colorspace
YUV colorspace type.
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().
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)
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.
AVBufferRef * av_buffer_alloc(int size)
Allocate an AVBuffer of the given size using av_malloc().
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.
uint8_t * data
The data buffer.
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
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
#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
enum AVColorPrimaries color_primaries
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.
enum AVColorTransferCharacteristic color_trc
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