21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
39 # define kCVImageBufferColorPrimaries_ITU_R_2020 CFSTR("ITU_R_2020")
40 # define kCVImageBufferTransferFunction_ITU_R_2020 CFSTR("ITU_R_2020")
41 # define kCVImageBufferYCbCrMatrix_ITU_R_2020 CFSTR("ITU_R_2020")
110 CFStringRef profile_level,
111 CFNumberRef gamma_level,
112 CFDictionaryRef enc_info,
113 CFDictionaryRef pixel_buffer_info);
192 }
else if (info->
sei) {
231 CMSampleBufferRef sample_buffer,
238 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
239 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
241 if (length_code_size > 4)
244 while (offset < src_size) {
249 status = CMBlockBufferCopyDataBytes(block,
254 for (i = 0; i < length_code_size; i++) {
256 box_len |= size_buf[i];
259 curr_src_len = box_len + length_code_size;
260 offset += curr_src_len;
287 CMVideoFormatDescriptionRef vid_fmt,
290 size_t total_size = 0;
292 int is_count_bad = 0;
295 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
307 for (i = 0; i < ps_count || is_count_bad; i++) {
310 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
321 if (i > 0 && is_count_bad) status = 0;
340 CMVideoFormatDescriptionRef vid_fmt,
345 int is_count_bad = 0;
350 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
363 for (i = 0; i < ps_count || is_count_bad; i++) {
368 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
375 if (i > 0 && is_count_bad) status = 0;
380 next_offset = offset +
sizeof(
start_code) + ps_size;
381 if (dst_size < next_offset) {
389 memcpy(dst + offset, ps, ps_size);
390 offset = next_offset;
403 CMVideoFormatDescriptionRef vid_fmt;
407 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
437 void *sourceFrameCtx,
439 VTEncodeInfoFlags
flags,
440 CMSampleBufferRef sample_buffer)
447 if(sample_buffer) CFRelease(sample_buffer);
451 if (status || !sample_buffer) {
470 CMSampleBufferRef sample_buffer,
473 CMVideoFormatDescriptionRef vid_fmt;
477 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
483 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
505 CFStringRef *profile_level_val)
515 *profile_level_val =
NULL;
522 switch (vtctx->
level) {
523 case 0: *profile_level_val = kVTProfileLevel_H264_Baseline_AutoLevel;
break;
524 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;
break;
525 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;
break;
526 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;
break;
527 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;
break;
528 case 40: *profile_level_val = kVTProfileLevel_H264_Baseline_4_0;
break;
529 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;
break;
530 case 42: *profile_level_val = kVTProfileLevel_H264_Baseline_4_2;
break;
531 case 50: *profile_level_val = kVTProfileLevel_H264_Baseline_5_0;
break;
532 case 51: *profile_level_val = kVTProfileLevel_H264_Baseline_5_1;
break;
533 case 52: *profile_level_val = kVTProfileLevel_H264_Baseline_5_2;
break;
538 switch (vtctx->
level) {
539 case 0: *profile_level_val = kVTProfileLevel_H264_Main_AutoLevel;
break;
540 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;
break;
541 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;
break;
542 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;
break;
543 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;
break;
544 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;
break;
545 case 42: *profile_level_val = kVTProfileLevel_H264_Main_4_2;
break;
546 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;
break;
547 case 51: *profile_level_val = kVTProfileLevel_H264_Main_5_1;
break;
548 case 52: *profile_level_val = kVTProfileLevel_H264_Main_5_2;
break;
553 switch (vtctx->
level) {
554 case 0: *profile_level_val = kVTProfileLevel_H264_High_AutoLevel;
break;
555 case 30: *profile_level_val = kVTProfileLevel_H264_High_3_0;
break;
556 case 31: *profile_level_val = kVTProfileLevel_H264_High_3_1;
break;
557 case 32: *profile_level_val = kVTProfileLevel_H264_High_3_2;
break;
558 case 40: *profile_level_val = kVTProfileLevel_H264_High_4_0;
break;
559 case 41: *profile_level_val = kVTProfileLevel_H264_High_4_1;
break;
560 case 42: *profile_level_val = kVTProfileLevel_H264_High_4_2;
break;
561 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;
break;
562 case 51: *profile_level_val = kVTProfileLevel_H264_High_5_1;
break;
563 case 52: *profile_level_val = kVTProfileLevel_H264_High_5_2;
break;
568 if (!*profile_level_val) {
579 int* av_pixel_format,
588 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
589 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
592 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
593 kCVPixelFormatType_420YpCbCr8Planar;
605 CFDictionarySetValue(dict,
606 kCVImageBufferColorPrimariesKey,
611 CFDictionarySetValue(dict,
612 kCVImageBufferTransferFunctionKey,
617 CFDictionarySetValue(dict,
618 kCVImageBufferYCbCrMatrixKey,
624 CFMutableDictionaryRef* dict)
626 CFNumberRef cv_color_format_num =
NULL;
627 CFNumberRef width_num =
NULL;
628 CFNumberRef height_num =
NULL;
629 CFMutableDictionaryRef pixel_buffer_info =
NULL;
636 if (status)
return status;
638 pixel_buffer_info = CFDictionaryCreateMutable(
641 &kCFCopyStringDictionaryKeyCallBacks,
642 &kCFTypeDictionaryValueCallBacks);
644 if (!pixel_buffer_info)
goto pbinfo_nomem;
646 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
649 if (!cv_color_format_num)
goto pbinfo_nomem;
651 CFDictionarySetValue(pixel_buffer_info,
652 kCVPixelBufferPixelFormatTypeKey,
653 cv_color_format_num);
656 width_num = CFNumberCreate(kCFAllocatorDefault,
659 if (!width_num)
return AVERROR(ENOMEM);
661 CFDictionarySetValue(pixel_buffer_info,
662 kCVPixelBufferWidthKey,
666 height_num = CFNumberCreate(kCFAllocatorDefault,
669 if (!height_num)
goto pbinfo_nomem;
671 CFDictionarySetValue(pixel_buffer_info,
672 kCVPixelBufferHeightKey,
678 *dict = pixel_buffer_info;
685 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
691 CFStringRef *primaries)
700 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
717 CFStringRef *transfer_fnc,
718 CFNumberRef *gamma_level)
726 *transfer_fnc =
NULL;
730 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
734 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
739 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
740 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
745 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
746 *gamma_level = CFNumberCreate(
NULL, kCFNumberFloat32Type, &gamma);
765 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
774 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
778 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
795 CFStringRef profile_level,
796 CFNumberRef gamma_level,
797 CFDictionaryRef enc_info,
798 CFDictionaryRef pixel_buffer_info,
799 VTCompressionSessionRef *session)
803 CFNumberRef bit_rate_num;
805 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
816 if (status || !vtctx->
session) {
817 av_log(avctx,
AV_LOG_ERROR,
"Error: cannot create compression session: %d\n", status);
819 #if !TARGET_OS_IPHONE
821 av_log(avctx,
AV_LOG_ERROR,
"Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
828 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
831 if (!bit_rate_num)
return AVERROR(ENOMEM);
833 status = VTSessionSetProperty(vtctx->
session,
834 kVTCompressionPropertyKey_AverageBitRate,
836 CFRelease(bit_rate_num);
844 status = VTSessionSetProperty(vtctx->
session,
845 kVTCompressionPropertyKey_ProfileLevel,
854 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
861 status = VTSessionSetProperty(vtctx->
session,
862 kVTCompressionPropertyKey_MaxKeyFrameInterval,
867 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'max key-frame interval' property: %d\n", status);
873 status = VTSessionSetProperty(vtctx->
session,
874 kVTCompressionPropertyKey_MoreFramesBeforeStart,
877 if (status == kVTPropertyNotSupportedErr) {
878 av_log(avctx,
AV_LOG_WARNING,
"frames_before property is not supported on this device. Ignoring.\n");
885 status = VTSessionSetProperty(vtctx->
session,
886 kVTCompressionPropertyKey_MoreFramesAfterEnd,
889 if (status == kVTPropertyNotSupportedErr) {
890 av_log(avctx,
AV_LOG_WARNING,
"frames_after property is not supported on this device. Ignoring.\n");
899 CFMutableDictionaryRef par;
906 num = CFNumberCreate(kCFAllocatorDefault,
910 den = CFNumberCreate(kCFAllocatorDefault,
916 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
918 &kCFCopyStringDictionaryKeyCallBacks,
919 &kCFTypeDictionaryValueCallBacks);
921 if (!par || !num || !den) {
922 if (par) CFRelease(par);
923 if (num) CFRelease(num);
924 if (den) CFRelease(den);
929 CFDictionarySetValue(
931 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
934 CFDictionarySetValue(
936 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
939 status = VTSessionSetProperty(vtctx->
session,
940 kVTCompressionPropertyKey_PixelAspectRatio,
950 "Error setting pixel aspect ratio to %d:%d: %d.\n",
961 status = VTSessionSetProperty(vtctx->
session,
962 kVTCompressionPropertyKey_TransferFunction,
972 status = VTSessionSetProperty(vtctx->
session,
973 kVTCompressionPropertyKey_YCbCrMatrix,
983 status = VTSessionSetProperty(vtctx->
session,
984 kVTCompressionPropertyKey_ColorPrimaries,
993 status = VTSessionSetProperty(vtctx->
session,
994 kCVImageBufferGammaLevelKey,
1003 status = VTSessionSetProperty(vtctx->
session,
1004 kVTCompressionPropertyKey_AllowFrameReordering,
1008 av_log(avctx,
AV_LOG_ERROR,
"Error setting 'allow frame reordering' property: %d\n", status);
1015 kVTH264EntropyMode_CABAC:
1016 kVTH264EntropyMode_CAVLC;
1018 status = VTSessionSetProperty(vtctx->
session,
1019 kVTCompressionPropertyKey_H264EntropyMode,
1029 status = VTSessionSetProperty(vtctx->
session,
1030 kVTCompressionPropertyKey_RealTime,
1038 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->
session);
1049 CFMutableDictionaryRef enc_info;
1050 CFMutableDictionaryRef pixel_buffer_info;
1053 CFStringRef profile_level;
1054 CFBooleanRef has_b_frames_cfbool;
1055 CFNumberRef gamma_level =
NULL;
1066 av_log(avctx,
AV_LOG_WARNING,
"Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1071 av_log(avctx,
AV_LOG_WARNING,
"CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1079 enc_info = CFDictionaryCreateMutable(
1080 kCFAllocatorDefault,
1082 &kCFCopyStringDictionaryKeyCallBacks,
1083 &kCFTypeDictionaryValueCallBacks
1086 if (!enc_info)
return AVERROR(ENOMEM);
1088 #if !TARGET_OS_IPHONE
1090 CFDictionarySetValue(enc_info, kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder, kCFBooleanTrue);
1092 CFDictionarySetValue(enc_info, kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder, kCFBooleanTrue);
1101 pixel_buffer_info =
NULL;
1135 status = VTSessionCopyProperty(vtctx->
session,
1136 kVTCompressionPropertyKey_AllowFrameReordering,
1137 kCFAllocatorDefault,
1138 &has_b_frames_cfbool);
1142 vtctx->
has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1143 CFRelease(has_b_frames_cfbool);
1149 CFRelease(gamma_level);
1151 if (pixel_buffer_info)
1152 CFRelease(pixel_buffer_info);
1154 CFRelease(enc_info);
1161 CFArrayRef attachments;
1162 CFDictionaryRef attachment;
1163 CFBooleanRef not_sync;
1166 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer,
false);
1167 len = !attachments ? 0 : CFArrayGetCount(attachments);
1170 *is_key_frame =
true;
1174 attachment = CFArrayGetValueAtIndex(attachments, 0);
1176 if (CFDictionaryGetValueIfPresent(attachment,
1177 kCMSampleAttachmentKey_NotSync,
1178 (
const void **)¬_sync))
1180 *is_key_frame = !CFBooleanGetValue(not_sync);
1182 *is_key_frame =
true;
1203 size_t sei_payload_size = 0;
1204 int sei_payload_type = 0;
1206 uint8_t *nal_start = nal_data;
1211 nal_type = *nal_data & 0x1F;
1218 if (nal_data[nal_size - 1] == 0x80)
1221 while (nal_size > 0 && *nal_data > 0) {
1223 sei_payload_type += *nal_data;
1226 }
while (nal_size > 0 && *nal_data == 0xFF);
1234 sei_payload_size += *nal_data;
1237 }
while (nal_size > 0 && *nal_data == 0xFF);
1239 if (nal_size < sei_payload_size) {
1244 nal_data += sei_payload_size;
1245 nal_size -= sei_payload_size;
1248 *sei_end = nal_data;
1250 return nal_data - nal_start + 1;
1270 uint8_t* dst_end = dst + dst_size;
1271 const uint8_t* src_end = src + src_size;
1272 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1274 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1283 for (; src < src_end; src++, dst++) {
1285 int insert_ep3_byte = *src <= 3;
1286 if (insert_ep3_byte) {
1304 wrote_bytes = dst - dst_start;
1307 return -wrote_bytes;
1318 size_t remaining_sei_size = sei->
size;
1319 size_t remaining_dst_size = dst_size;
1324 if (!remaining_dst_size)
1327 while (sei_type && remaining_dst_size != 0) {
1328 int sei_byte = sei_type > 255 ? 255 : sei_type;
1331 sei_type -= sei_byte;
1333 remaining_dst_size--;
1339 while (remaining_sei_size && remaining_dst_size != 0) {
1340 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1343 remaining_sei_size -= size_byte;
1345 remaining_dst_size--;
1348 if (remaining_dst_size < sei->
size)
1351 header_bytes = dst - sei_start;
1353 offset = header_bytes;
1359 if (bytes_written < 0)
1362 bytes_written += header_bytes;
1363 return bytes_written;
1387 size_t length_code_size,
1388 CMSampleBufferRef sample_buffer,
1393 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1394 size_t remaining_src_size = src_size;
1395 size_t remaining_dst_size = dst_size;
1396 size_t src_offset = 0;
1401 CMBlockBufferRef
block = CMSampleBufferGetDataBuffer(sample_buffer);
1403 if (length_code_size > 4) {
1407 while (remaining_src_size > 0) {
1408 size_t curr_src_len;
1409 size_t curr_dst_len;
1415 status = CMBlockBufferCopyDataBytes(block,
1424 status = CMBlockBufferCopyDataBytes(block,
1425 src_offset + length_code_size,
1436 for (i = 0; i < length_code_size; i++) {
1438 box_len |= size_buf[i];
1451 remaining_dst_size--;
1456 remaining_dst_size);
1458 if (wrote_bytes < 0)
1461 remaining_dst_size -= wrote_bytes;
1462 dst_data += wrote_bytes;
1464 if (remaining_dst_size <= 0)
1470 remaining_dst_size--;
1475 curr_src_len = box_len + length_code_size;
1478 if (remaining_src_size < curr_src_len) {
1482 if (remaining_dst_size < curr_dst_len) {
1489 status = CMBlockBufferCopyDataBytes(block,
1490 src_offset + length_code_size,
1505 old_sei_length =
find_sei_end(avctx, dst_box, box_len, &new_sei);
1506 if (old_sei_length < 0)
1512 remaining_dst_size - old_sei_length);
1513 if (wrote_bytes < 0)
1516 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1519 new_sei[wrote_bytes++] = 0x80;
1520 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1522 dst_data += extra_bytes;
1523 remaining_dst_size -= extra_bytes;
1528 src_offset += curr_src_len;
1529 dst_data += curr_dst_len;
1531 remaining_src_size -= curr_src_len;
1532 remaining_dst_size -= curr_dst_len;
1553 if ((sei->
size % 255) == 0)
1556 return copied_size + sei->
size / 255 + 1 + type / 255 + 1;
1561 CMSampleBufferRef sample_buffer,
1570 size_t length_code_size;
1571 size_t header_size = 0;
1573 size_t out_buf_size;
1574 size_t sei_nalu_size = 0;
1576 int64_t time_base_num;
1580 CMVideoFormatDescriptionRef vid_fmt;
1585 if (status)
return status;
1590 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1597 if (status)
return status;
1600 status =
count_nalus(length_code_size, sample_buffer, &nalu_count);
1608 sei_nalu_size =
sizeof(
start_code) + 1 + msg_size + 1;
1611 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1612 out_buf_size = header_size +
1615 nalu_count * ((int)
sizeof(
start_code) - (int)length_code_size);
1623 if(status)
return status;
1631 pkt->
data + header_size,
1632 pkt->
size - header_size
1644 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1645 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1647 if (CMTIME_IS_INVALID(dts)) {
1658 pkt->
pts = pts.value / time_base_num;
1659 pkt->
dts = dts.value / time_base_num - dts_delta;
1660 pkt->
size = out_buf_size;
1677 size_t *contiguous_buf_size)
1680 int av_format = frame->
format;
1690 "Could not get pixel format for color format '%s' range '%s'.\n",
1700 if (range_guessed) {
1705 "Color range not set for %s. Using MPEG range.\n",
1712 switch (av_format) {
1716 widths [0] = avctx->
width;
1717 heights[0] = avctx->
height;
1720 widths [1] = (avctx->
width + 1) / 2;
1721 heights[1] = (avctx->
height + 1) / 2;
1722 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) & -2;
1728 widths [0] = avctx->
width;
1729 heights[0] = avctx->
height;
1732 widths [1] = (avctx->
width + 1) / 2;
1733 heights[1] = (avctx->
height + 1) / 2;
1734 strides[1] = frame ? frame->
linesize[1] : (avctx->
width + 1) / 2;
1736 widths [2] = (avctx->
width + 1) / 2;
1737 heights[2] = (avctx->
height + 1) / 2;
1738 strides[2] = frame ? frame->
linesize[2] : (avctx->
width + 1) / 2;
1745 "Could not get frame format info for color %d range %d.\n",
1752 *contiguous_buf_size = 0;
1753 for (i = 0; i < *plane_count; i++) {
1754 if (i < *plane_count - 1 &&
1755 frame->
data[i] + strides[i] * heights[i] != frame->
data[i + 1]) {
1756 *contiguous_buf_size = 0;
1760 *contiguous_buf_size += strides[i] * heights[i];
1766 #if !TARGET_OS_IPHONE
1773 const void *plane_addresses[])
1782 CVPixelBufferRef cv_img,
1783 const size_t *plane_strides,
1784 const size_t *plane_rows)
1796 status = CVPixelBufferLockBaseAddress(cv_img, 0);
1801 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
1806 if (CVPixelBufferIsPlanar(cv_img)) {
1807 plane_count = CVPixelBufferGetPlaneCount(cv_img);
1808 for (i = 0; frame->
data[i]; i++) {
1809 if (i == plane_count) {
1810 CVPixelBufferUnlockBaseAddress(cv_img, 0);
1813 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
1819 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
1821 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
1822 src_stride = plane_strides[i];
1823 rows = plane_rows[i];
1825 if (dst_stride == src_stride) {
1826 memcpy(dst_addr, src_addr, src_stride * rows);
1828 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
1830 for (j = 0; j < rows; j++) {
1831 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
1836 if (frame->
data[1]) {
1837 CVPixelBufferUnlockBaseAddress(cv_img, 0);
1840 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
1846 dst_addr = (
uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
1848 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
1849 src_stride = plane_strides[0];
1850 rows = plane_rows[0];
1852 if (dst_stride == src_stride) {
1853 memcpy(dst_addr, src_addr, src_stride * rows);
1855 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
1857 for (j = 0; j < rows; j++) {
1858 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
1863 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
1865 av_log(avctx,
AV_LOG_ERROR,
"Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
1875 CVPixelBufferRef *cv_img)
1883 size_t contiguous_buf_size;
1884 #if TARGET_OS_IPHONE
1885 CVPixelBufferPoolRef pix_buf_pool;
1888 CFMutableDictionaryRef pix_buf_attachments = CFDictionaryCreateMutable(
1889 kCFAllocatorDefault,
1891 &kCFCopyStringDictionaryKeyCallBacks,
1892 &kCFTypeDictionaryValueCallBacks);
1894 if (!pix_buf_attachments)
return AVERROR(ENOMEM);
1900 *cv_img = (CVPixelBufferRef)frame->
data[3];
1907 memset(widths, 0,
sizeof(widths));
1908 memset(heights, 0,
sizeof(heights));
1909 memset(strides, 0,
sizeof(strides));
1919 &contiguous_buf_size
1926 "Error: Cannot convert format %d color_range %d: %d\n",
1935 #if TARGET_OS_IPHONE
1936 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->
session);
1937 if (!pix_buf_pool) {
1942 status = CVPixelBufferPoolCreatePixelBuffer(
NULL,
1948 av_log(avctx,
AV_LOG_ERROR,
"Could not create pixel buffer from pool: %d.\n", status);
1952 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
1960 if (!enc_frame)
return AVERROR(ENOMEM);
1968 status = CVPixelBufferCreateWithPlanarBytes(
1969 kCFAllocatorDefault,
1974 contiguous_buf_size,
1976 (
void **)enc_frame->
data,
1987 CVBufferSetAttachments(*cv_img, pix_buf_attachments, kCVAttachmentMode_ShouldPropagate);
1988 CFRelease(pix_buf_attachments);
2000 CFDictionaryRef* dict_out)
2002 CFDictionaryRef dict =
NULL;
2004 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2005 const void *vals[] = { kCFBooleanTrue };
2007 dict = CFDictionaryCreate(
NULL, keys, vals, 1,
NULL,
NULL);
2008 if(!dict)
return AVERROR(ENOMEM);
2020 CFDictionaryRef frame_dict;
2021 CVPixelBufferRef cv_img =
NULL;
2026 if (status)
return status;
2035 if (vtctx->
a53_cc && side_data && side_data->
size) {
2050 status = VTCompressionSessionEncodeFrame(
2060 if (frame_dict) CFRelease(frame_dict);
2101 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2119 if (status)
goto end_nopkt;
2120 if (!buf)
goto end_nopkt;
2128 if (status)
goto end_nopkt;
2140 CFStringRef profile_level,
2141 CFNumberRef gamma_level,
2142 CFDictionaryRef enc_info,
2143 CFDictionaryRef pixel_buffer_info)
2148 int chroma_size = (avctx->
width / 2) * (avctx->
height / 2);
2173 memset(frame->
data[0], 0, y_size);
2176 memset(frame->
data[1], 128, chroma_size);
2180 frame->
data[2] = frame->
buf[0]->
data + y_size + chroma_size;
2181 memset(frame->
data[2], 128, chroma_size);
2209 status = VTCompressionSessionCompleteFrames(vtctx->
session,
2246 VTCompressionSessionCompleteFrames(vtctx->
session,
2279 #define OFFSET(x) offsetof(VTEncContext, x)
2280 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2288 {
"1.3",
"Level 1.3, only available with Baseline Profile", 0,
AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX,
VE,
"level" },
2289 {
"3.0",
"Level 3.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX,
VE,
"level" },
2290 {
"3.1",
"Level 3.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX,
VE,
"level" },
2291 {
"3.2",
"Level 3.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX,
VE,
"level" },
2292 {
"4.0",
"Level 4.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX,
VE,
"level" },
2293 {
"4.1",
"Level 4.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX,
VE,
"level" },
2294 {
"4.2",
"Level 4.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX,
VE,
"level" },
2295 {
"5.0",
"Level 5.0", 0,
AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX,
VE,
"level" },
2296 {
"5.1",
"Level 5.1", 0,
AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX,
VE,
"level" },
2297 {
"5.2",
"Level 5.2", 0,
AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX,
VE,
"level" },
2300 { .i64 = 0 }, 0, 1,
VE },
2308 {
"realtime",
"Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).",
2311 {
"frames_before",
"Other frames will come before the frames in this session. This helps smooth concatenation issues.",
2313 {
"frames_after",
"Other frames will come after the frames in this session. This helps smooth concatenation issues.",
2329 .
name =
"h264_videotoolbox",
2334 .pix_fmts = pix_fmts,
2339 .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.
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
enum AVColorRange av_frame_get_color_range(const AVFrame *frame)
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.
#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.
void av_frame_set_color_range(AVFrame *frame, enum AVColorRange val)
H.264 common definitions.
AVCodecID
Identify the syntax and semantics of the bitstream.
int width
width and height of the video frame
#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.
void av_frame_set_colorspace(AVFrame *frame, enum AVColorSpace val)
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
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().
const char * name
Name of the codec implementation.
registered user data as specified by Rec. ITU-T T.35
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)
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.
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
Check AVPacket size and/or allocate data.
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...
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
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
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
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.
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...