21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
74 #define GET_SYM(symbol, defaultVal) \
76 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
78 compat_keys.symbol = CFSTR(defaultVal); \
80 compat_keys.symbol = *handle; \
117 "EnableHardwareAcceleratedVideoEncoder");
119 "RequireHardwareAcceleratedVideoEncoder");
188 CFStringRef profile_level,
189 CFNumberRef gamma_level,
190 CFDictionaryRef enc_info,
191 CFDictionaryRef pixel_buffer_info);
270 }
else if (info->
sei) {
309 CMSampleBufferRef sample_buffer,
316 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
317 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
319 if (length_code_size > 4)
322 while (offset < src_size) {
327 status = CMBlockBufferCopyDataBytes(block,
332 for (i = 0; i < length_code_size; i++) {
334 box_len |= size_buf[i];
337 curr_src_len = box_len + length_code_size;
338 offset += curr_src_len;
365 CMVideoFormatDescriptionRef vid_fmt,
368 size_t total_size = 0;
370 int is_count_bad = 0;
373 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
385 for (i = 0; i < ps_count || is_count_bad; i++) {
388 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
399 if (i > 0 && is_count_bad) status = 0;
418 CMVideoFormatDescriptionRef vid_fmt,
423 int is_count_bad = 0;
428 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
441 for (i = 0; i < ps_count || is_count_bad; i++) {
446 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
453 if (i > 0 && is_count_bad) status = 0;
458 next_offset = offset +
sizeof(
start_code) + ps_size;
459 if (dst_size < next_offset) {
467 memcpy(dst + offset, ps, ps_size);
468 offset = next_offset;
481 CMVideoFormatDescriptionRef vid_fmt;
485 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
515 void *sourceFrameCtx,
517 VTEncodeInfoFlags
flags,
518 CMSampleBufferRef sample_buffer)
525 if(sample_buffer) CFRelease(sample_buffer);
529 if (status || !sample_buffer) {
548 CMSampleBufferRef sample_buffer,
551 CMVideoFormatDescriptionRef vid_fmt;
555 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
561 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
583 CFStringRef *profile_level_val)
593 *profile_level_val =
NULL;
600 switch (vtctx->
level) {
601 case 0: *profile_level_val =
602 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel;
break;
603 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
604 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
605 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
606 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
607 case 40: *profile_level_val =
608 compat_keys.kVTProfileLevel_H264_Baseline_4_0;
break;
609 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
610 case 42: *profile_level_val =
611 compat_keys.kVTProfileLevel_H264_Baseline_4_2;
break;
612 case 50: *profile_level_val =
613 compat_keys.kVTProfileLevel_H264_Baseline_5_0;
break;
614 case 51: *profile_level_val =
615 compat_keys.kVTProfileLevel_H264_Baseline_5_1;
break;
616 case 52: *profile_level_val =
617 compat_keys.kVTProfileLevel_H264_Baseline_5_2;
break;
622 switch (vtctx->
level) {
623 case 0: *profile_level_val =
624 compat_keys.kVTProfileLevel_H264_Main_AutoLevel;
break;
625 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
626 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
627 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
628 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
629 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
630 case 42: *profile_level_val =
632 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
633 case 51: *profile_level_val =
635 case 52: *profile_level_val =
641 switch (vtctx->
level) {
642 case 0: *profile_level_val =
643 compat_keys.kVTProfileLevel_H264_High_AutoLevel;
break;
644 case 30: *profile_level_val =
646 case 31: *profile_level_val =
648 case 32: *profile_level_val =
650 case 40: *profile_level_val =
652 case 41: *profile_level_val =
654 case 42: *profile_level_val =
656 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
657 case 51: *profile_level_val =
659 case 52: *profile_level_val =
665 if (!*profile_level_val) {
676 int* av_pixel_format,
685 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
686 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
689 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
690 kCVPixelFormatType_420YpCbCr8Planar;
702 CFDictionarySetValue(dict,
703 kCVImageBufferColorPrimariesKey,
708 CFDictionarySetValue(dict,
709 kCVImageBufferTransferFunctionKey,
714 CFDictionarySetValue(dict,
715 kCVImageBufferYCbCrMatrixKey,
721 CFMutableDictionaryRef* dict)
723 CFNumberRef cv_color_format_num =
NULL;
724 CFNumberRef width_num =
NULL;
725 CFNumberRef height_num =
NULL;
726 CFMutableDictionaryRef pixel_buffer_info =
NULL;
733 if (status)
return status;
735 pixel_buffer_info = CFDictionaryCreateMutable(
738 &kCFCopyStringDictionaryKeyCallBacks,
739 &kCFTypeDictionaryValueCallBacks);
741 if (!pixel_buffer_info)
goto pbinfo_nomem;
743 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
746 if (!cv_color_format_num)
goto pbinfo_nomem;
748 CFDictionarySetValue(pixel_buffer_info,
749 kCVPixelBufferPixelFormatTypeKey,
750 cv_color_format_num);
753 width_num = CFNumberCreate(kCFAllocatorDefault,
756 if (!width_num)
return AVERROR(ENOMEM);
758 CFDictionarySetValue(pixel_buffer_info,
759 kCVPixelBufferWidthKey,
763 height_num = CFNumberCreate(kCFAllocatorDefault,
766 if (!height_num)
goto pbinfo_nomem;
768 CFDictionarySetValue(pixel_buffer_info,
769 kCVPixelBufferHeightKey,
775 *dict = pixel_buffer_info;
782 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
788 CFStringRef *primaries)
797 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
801 *primaries =
compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
814 CFStringRef *transfer_fnc,
815 CFNumberRef *gamma_level)
823 *transfer_fnc =
NULL;
827 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
831 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
836 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
837 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
842 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
843 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
848 *transfer_fnc =
compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
862 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
871 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
875 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
879 *matrix =
compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
892 CFStringRef profile_level,
893 CFNumberRef gamma_level,
894 CFDictionaryRef enc_info,
895 CFDictionaryRef pixel_buffer_info,
896 VTCompressionSessionRef *session)
901 CFNumberRef bit_rate_num;
902 CFNumberRef bytes_per_second;
903 CFNumberRef one_second;
904 CFArrayRef data_rate_limits;
905 int64_t bytes_per_second_value = 0;
906 int64_t one_second_value = 0;
909 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
920 if (status || !vtctx->
session) {
921 av_log(avctx,
AV_LOG_ERROR,
"Error: cannot create compression session: %d\n", status);
923 #if !TARGET_OS_IPHONE
925 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
932 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
935 if (!bit_rate_num)
return AVERROR(ENOMEM);
937 status = VTSessionSetProperty(vtctx->
session,
938 kVTCompressionPropertyKey_AverageBitRate,
940 CFRelease(bit_rate_num);
947 bytes_per_second_value = max_rate >> 3;
948 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
950 &bytes_per_second_value);
951 if (!bytes_per_second) {
954 one_second_value = 1;
955 one_second = CFNumberCreate(kCFAllocatorDefault,
959 CFRelease(bytes_per_second);
962 nums[0] = bytes_per_second;
963 nums[1] = one_second;
964 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
967 &kCFTypeArrayCallBacks);
969 if (!data_rate_limits) {
970 CFRelease(bytes_per_second);
971 CFRelease(one_second);
974 status = VTSessionSetProperty(vtctx->
session,
975 kVTCompressionPropertyKey_DataRateLimits,
978 CFRelease(bytes_per_second);
979 CFRelease(one_second);
980 CFRelease(data_rate_limits);
988 status = VTSessionSetProperty(vtctx->
session,
989 kVTCompressionPropertyKey_ProfileLevel,
997 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1004 status = VTSessionSetProperty(vtctx->
session,
1005 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1007 CFRelease(interval);
1010 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'max key-frame interval' property: %d\n", status);
1016 status = VTSessionSetProperty(vtctx->
session,
1017 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1020 if (status == kVTPropertyNotSupportedErr) {
1021 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
1022 }
else if (status) {
1028 status = VTSessionSetProperty(vtctx->
session,
1029 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1032 if (status == kVTPropertyNotSupportedErr) {
1033 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
1034 }
else if (status) {
1042 CFMutableDictionaryRef par;
1049 num = CFNumberCreate(kCFAllocatorDefault,
1053 den = CFNumberCreate(kCFAllocatorDefault,
1059 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1061 &kCFCopyStringDictionaryKeyCallBacks,
1062 &kCFTypeDictionaryValueCallBacks);
1064 if (!par || !num || !den) {
1065 if (par) CFRelease(par);
1066 if (num) CFRelease(num);
1067 if (den) CFRelease(den);
1072 CFDictionarySetValue(
1074 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1077 CFDictionarySetValue(
1079 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1082 status = VTSessionSetProperty(vtctx->
session,
1083 kVTCompressionPropertyKey_PixelAspectRatio,
1093 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1104 status = VTSessionSetProperty(vtctx->
session,
1105 kVTCompressionPropertyKey_TransferFunction,
1115 status = VTSessionSetProperty(vtctx->
session,
1116 kVTCompressionPropertyKey_YCbCrMatrix,
1126 status = VTSessionSetProperty(vtctx->
session,
1127 kVTCompressionPropertyKey_ColorPrimaries,
1136 status = VTSessionSetProperty(vtctx->
session,
1137 kCVImageBufferGammaLevelKey,
1146 status = VTSessionSetProperty(vtctx->
session,
1147 kVTCompressionPropertyKey_AllowFrameReordering,
1151 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'allow frame reordering' property: %d\n", status);
1161 status = VTSessionSetProperty(vtctx->
session,
1162 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1171 status = VTSessionSetProperty(vtctx->
session,
1180 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1191 CFMutableDictionaryRef enc_info;
1192 CFMutableDictionaryRef pixel_buffer_info;
1195 CFStringRef profile_level;
1196 CFBooleanRef has_b_frames_cfbool;
1197 CFNumberRef gamma_level =
NULL;
1210 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1215 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1223 enc_info = CFDictionaryCreateMutable(
1224 kCFAllocatorDefault,
1226 &kCFCopyStringDictionaryKeyCallBacks,
1227 &kCFTypeDictionaryValueCallBacks
1230 if (!enc_info)
return AVERROR(ENOMEM);
1232 #if !TARGET_OS_IPHONE
1234 CFDictionarySetValue(enc_info,
1235 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1238 CFDictionarySetValue(enc_info,
1239 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1249 pixel_buffer_info =
NULL;
1283 status = VTSessionCopyProperty(vtctx->
session,
1284 kVTCompressionPropertyKey_AllowFrameReordering,
1285 kCFAllocatorDefault,
1286 &has_b_frames_cfbool);
1288 if (!status && has_b_frames_cfbool) {
1290 vtctx->
has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1291 CFRelease(has_b_frames_cfbool);
1297 CFRelease(gamma_level);
1299 if (pixel_buffer_info)
1300 CFRelease(pixel_buffer_info);
1302 CFRelease(enc_info);
1309 CFArrayRef attachments;
1310 CFDictionaryRef attachment;
1311 CFBooleanRef not_sync;
1314 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer,
false);
1315 len = !attachments ? 0 : CFArrayGetCount(attachments);
1318 *is_key_frame =
true;
1322 attachment = CFArrayGetValueAtIndex(attachments, 0);
1324 if (CFDictionaryGetValueIfPresent(attachment,
1325 kCMSampleAttachmentKey_NotSync,
1326 (
const void **)¬_sync))
1328 *is_key_frame = !CFBooleanGetValue(not_sync);
1330 *is_key_frame =
true;
1351 size_t sei_payload_size = 0;
1352 int sei_payload_type = 0;
1354 uint8_t *nal_start = nal_data;
1359 nal_type = *nal_data & 0x1F;
1366 if (nal_data[nal_size - 1] == 0x80)
1369 while (nal_size > 0 && *nal_data > 0) {
1371 sei_payload_type += *nal_data;
1374 }
while (nal_size > 0 && *nal_data == 0xFF);
1382 sei_payload_size += *nal_data;
1385 }
while (nal_size > 0 && *nal_data == 0xFF);
1387 if (nal_size < sei_payload_size) {
1392 nal_data += sei_payload_size;
1393 nal_size -= sei_payload_size;
1396 *sei_end = nal_data;
1398 return nal_data - nal_start + 1;
1418 uint8_t* dst_end = dst + dst_size;
1419 const uint8_t* src_end = src + src_size;
1420 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1422 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1431 for (; src < src_end; src++, dst++) {
1433 int insert_ep3_byte = *src <= 3;
1434 if (insert_ep3_byte) {
1452 wrote_bytes = dst - dst_start;
1455 return -wrote_bytes;
1466 size_t remaining_sei_size = sei->
size;
1467 size_t remaining_dst_size = dst_size;
1472 if (!remaining_dst_size)
1475 while (sei_type && remaining_dst_size != 0) {
1476 int sei_byte = sei_type > 255 ? 255 : sei_type;
1479 sei_type -= sei_byte;
1481 remaining_dst_size--;
1487 while (remaining_sei_size && remaining_dst_size != 0) {
1488 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1491 remaining_sei_size -= size_byte;
1493 remaining_dst_size--;
1496 if (remaining_dst_size < sei->
size)
1499 header_bytes = dst - sei_start;
1501 offset = header_bytes;
1507 if (bytes_written < 0)
1510 bytes_written += header_bytes;
1511 return bytes_written;
1535 size_t length_code_size,
1536 CMSampleBufferRef sample_buffer,
1541 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1542 size_t remaining_src_size = src_size;
1543 size_t remaining_dst_size = dst_size;
1544 size_t src_offset = 0;
1549 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1551 if (length_code_size > 4) {
1555 while (remaining_src_size > 0) {
1556 size_t curr_src_len;
1557 size_t curr_dst_len;
1563 status = CMBlockBufferCopyDataBytes(block,
1572 status = CMBlockBufferCopyDataBytes(block,
1573 src_offset + length_code_size,
1584 for (i = 0; i < length_code_size; i++) {
1586 box_len |= size_buf[i];
1599 remaining_dst_size--;
1604 remaining_dst_size);
1606 if (wrote_bytes < 0)
1609 remaining_dst_size -= wrote_bytes;
1610 dst_data += wrote_bytes;
1612 if (remaining_dst_size <= 0)
1618 remaining_dst_size--;
1623 curr_src_len = box_len + length_code_size;
1626 if (remaining_src_size < curr_src_len) {
1630 if (remaining_dst_size < curr_dst_len) {
1637 status = CMBlockBufferCopyDataBytes(block,
1638 src_offset + length_code_size,
1653 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1654 if (old_sei_length < 0)
1660 remaining_dst_size - old_sei_length);
1661 if (wrote_bytes < 0)
1664 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1667 new_sei[wrote_bytes++] = 0x80;
1668 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1670 dst_data += extra_bytes;
1671 remaining_dst_size -= extra_bytes;
1676 src_offset += curr_src_len;
1677 dst_data += curr_dst_len;
1679 remaining_src_size -= curr_src_len;
1680 remaining_dst_size -= curr_dst_len;
1701 if ((sei->
size % 255) == 0)
1704 return copied_size + sei->
size / 255 + 1 + type / 255 + 1;
1709 CMSampleBufferRef sample_buffer,
1718 size_t length_code_size;
1719 size_t header_size = 0;
1721 size_t out_buf_size;
1722 size_t sei_nalu_size = 0;
1724 int64_t time_base_num;
1728 CMVideoFormatDescriptionRef vid_fmt;
1733 if (status)
return status;
1738 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1745 if (status)
return status;
1748 status =
count_nalus(length_code_size, sample_buffer, &nalu_count);
1756 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
1759 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1760 out_buf_size = header_size +
1771 if(status)
return status;
1779 pkt->
data + header_size,
1780 pkt->
size - header_size
1792 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1793 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1795 if (CMTIME_IS_INVALID(dts)) {
1806 pkt->
pts = pts.value / time_base_num;
1807 pkt->
dts = dts.value / time_base_num - dts_delta;
1808 pkt->
size = out_buf_size;
1825 size_t *contiguous_buf_size)
1828 int av_format = frame->
format;
1838 "Could not get pixel format for color format '%s' range '%s'.\n",
1848 if (range_guessed) {
1853 "Color range not set for %s. Using MPEG range.\n",
1860 switch (av_format) {
1864 widths [0] = avctx->
width;
1865 heights[0] = avctx->
height;
1868 widths [1] = (avctx->
width + 1) / 2;
1869 heights[1] = (avctx->
height + 1) / 2;
1870 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) & -2;
1876 widths [0] = avctx->
width;
1877 heights[0] = avctx->
height;
1880 widths [1] = (avctx->
width + 1) / 2;
1881 heights[1] = (avctx->
height + 1) / 2;
1882 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) / 2;
1884 widths [2] = (avctx->
width + 1) / 2;
1885 heights[2] = (avctx->
height + 1) / 2;
1886 strides[2] = frame ? frame->
linesize[2] : (avctx->
width + 1) / 2;
1893 "Could not get frame format info for color %d range %d.\n",
1900 *contiguous_buf_size = 0;
1901 for (i = 0; i < *plane_count; i++) {
1902 if (i < *plane_count - 1 &&
1903 frame->
data[i] + strides[i] * heights[i] != frame->
data[i + 1]) {
1904 *contiguous_buf_size = 0;
1908 *contiguous_buf_size += strides[i] * heights[i];
1914 #if !TARGET_OS_IPHONE
1921 const void *plane_addresses[])
1930 CVPixelBufferRef cv_img,
1931 const size_t *plane_strides,
1932 const size_t *plane_rows)
1944 status = CVPixelBufferLockBaseAddress(cv_img, 0);
1949 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
1954 if (CVPixelBufferIsPlanar(cv_img)) {
1955 plane_count = CVPixelBufferGetPlaneCount(cv_img);
1956 for (i = 0; frame->
data[i]; i++) {
1957 if (i == plane_count) {
1958 CVPixelBufferUnlockBaseAddress(cv_img, 0);
1961 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
1967 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
1969 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
1970 src_stride = plane_strides[i];
1971 rows = plane_rows[i];
1973 if (dst_stride == src_stride) {
1974 memcpy(dst_addr, src_addr, src_stride * rows);
1976 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
1978 for (j = 0; j < rows; j++) {
1979 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
1984 if (frame->
data[1]) {
1985 CVPixelBufferUnlockBaseAddress(cv_img, 0);
1988 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
1994 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
1996 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
1997 src_stride = plane_strides[0];
1998 rows = plane_rows[0];
2000 if (dst_stride == src_stride) {
2001 memcpy(dst_addr, src_addr, src_stride * rows);
2003 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
2005 for (j = 0; j < rows; j++) {
2006 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
2011 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2013 av_log(avctx,
AV_LOG_ERROR,
"Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
2023 CVPixelBufferRef *cv_img)
2031 size_t contiguous_buf_size;
2032 #if TARGET_OS_IPHONE
2033 CVPixelBufferPoolRef pix_buf_pool;
2036 CFMutableDictionaryRef pix_buf_attachments = CFDictionaryCreateMutable(
2037 kCFAllocatorDefault,
2039 &kCFCopyStringDictionaryKeyCallBacks,
2040 &kCFTypeDictionaryValueCallBacks);
2042 if (!pix_buf_attachments)
return AVERROR(ENOMEM);
2048 *cv_img = (CVPixelBufferRef)frame->
data[3];
2055 memset(widths, 0,
sizeof(widths));
2056 memset(heights, 0,
sizeof(heights));
2057 memset(strides, 0,
sizeof(strides));
2067 &contiguous_buf_size
2074 "Error: Cannot convert format %d color_range %d: %d\n",
2083 #if TARGET_OS_IPHONE
2084 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
2085 if (!pix_buf_pool) {
2090 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
2096 av_log(avctx,
AV_LOG_ERROR,
"Could not create pixel buffer from pool: %d.\n", status);
2100 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2108 if (!enc_frame)
return AVERROR(ENOMEM);
2116 status = CVPixelBufferCreateWithPlanarBytes(
2117 kCFAllocatorDefault,
2122 contiguous_buf_size,
2124 (
void **)enc_frame->
data,
2135 CVBufferSetAttachments(*cv_img, pix_buf_attachments, kCVAttachmentMode_ShouldPropagate);
2136 CFRelease(pix_buf_attachments);
2148 CFDictionaryRef* dict_out)
2150 CFDictionaryRef dict =
NULL;
2152 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2153 const void *vals[] = { kCFBooleanTrue };
2155 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2156 if(!dict)
return AVERROR(ENOMEM);
2168 CFDictionaryRef frame_dict;
2169 CVPixelBufferRef cv_img =
NULL;
2174 if (status)
return status;
2183 if (vtctx->
a53_cc && side_data && side_data->
size) {
2198 status = VTCompressionSessionEncodeFrame(
2208 if (frame_dict) CFRelease(frame_dict);
2249 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2267 if (status)
goto end_nopkt;
2268 if (!buf)
goto end_nopkt;
2276 if (status)
goto end_nopkt;
2288 CFStringRef profile_level,
2289 CFNumberRef gamma_level,
2290 CFDictionaryRef enc_info,
2291 CFDictionaryRef pixel_buffer_info)
2296 int chroma_size = (avctx->
width / 2) * (avctx->
height / 2);
2321 memset(frame->
data[0], 0, y_size);
2324 memset(frame->
data[1], 128, chroma_size);
2328 frame->
data[2] = frame->
buf[0]->
data + y_size + chroma_size;
2329 memset(frame->
data[2], 128, chroma_size);
2357 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2394 VTCompressionSessionCompleteFrames(vtctx->
session,
2427 #define OFFSET(x) offsetof(VTEncContext, x)
2428 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2436 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2437 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2438 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2439 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2440 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2441 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2442 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2443 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2444 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2445 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2448 { .i64 = 0 }, 0, 1,
VE },
2456 {
"realtime",
"Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).",
2459 {
"frames_before",
"Other frames will come before the frames in this session. This helps smooth concatenation issues.",
2461 {
"frames_after",
"Other frames will come after the frames in this session. This helps smooth concatenation issues.",
2477 .
name =
"h264_videotoolbox",
2482 .pix_fmts = pix_fmts,
2487 .priv_class = &h264_videotoolbox_class,
#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 ...
enum AVColorRange color_range
MPEG vs JPEG YUV range.
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.
static int64_t pts
Global timestamp for the audio frames.
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
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)
#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