2 * copyright (c) 2015 Rick Kern <kernrj@gmail.com>
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 #include <VideoToolbox/VideoToolbox.h>
22 #include <CoreVideo/CoreVideo.h>
23 #include <CoreMedia/CoreMedia.h>
24 #include <TargetConditionals.h>
25 #include <Availability.h>
27 #include "libavutil/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/atomic.h"
30 #include "libavutil/avstring.h"
31 #include "libavcodec/avcodec.h"
32 #include "libavutil/pixdesc.h"
39 //These symbols may not be present
41 CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020;
42 CFStringRef kCVImageBufferTransferFunction_ITU_R_2020;
43 CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020;
45 CFStringRef kVTCompressionPropertyKey_H264EntropyMode;
46 CFStringRef kVTH264EntropyMode_CAVLC;
47 CFStringRef kVTH264EntropyMode_CABAC;
49 CFStringRef kVTProfileLevel_H264_Baseline_4_0;
50 CFStringRef kVTProfileLevel_H264_Baseline_4_2;
51 CFStringRef kVTProfileLevel_H264_Baseline_5_0;
52 CFStringRef kVTProfileLevel_H264_Baseline_5_1;
53 CFStringRef kVTProfileLevel_H264_Baseline_5_2;
54 CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel;
55 CFStringRef kVTProfileLevel_H264_Main_4_2;
56 CFStringRef kVTProfileLevel_H264_Main_5_1;
57 CFStringRef kVTProfileLevel_H264_Main_5_2;
58 CFStringRef kVTProfileLevel_H264_Main_AutoLevel;
59 CFStringRef kVTProfileLevel_H264_High_3_0;
60 CFStringRef kVTProfileLevel_H264_High_3_1;
61 CFStringRef kVTProfileLevel_H264_High_3_2;
62 CFStringRef kVTProfileLevel_H264_High_4_0;
63 CFStringRef kVTProfileLevel_H264_High_4_1;
64 CFStringRef kVTProfileLevel_H264_High_4_2;
65 CFStringRef kVTProfileLevel_H264_High_5_1;
66 CFStringRef kVTProfileLevel_H264_High_5_2;
67 CFStringRef kVTProfileLevel_H264_High_AutoLevel;
69 CFStringRef kVTCompressionPropertyKey_RealTime;
71 CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder;
72 CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder;
75 #define GET_SYM(symbol, defaultVal) \
77 CFStringRef cfstr = *(CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
79 compat_keys.symbol = CFSTR(defaultVal); \
81 compat_keys.symbol = cfstr; \
84 static pthread_once_t once_ctrl = PTHREAD_ONCE_INIT;
86 static void loadVTEncSymbols(){
87 GET_SYM(kCVImageBufferColorPrimaries_ITU_R_2020, "ITU_R_2020");
88 GET_SYM(kCVImageBufferTransferFunction_ITU_R_2020, "ITU_R_2020");
89 GET_SYM(kCVImageBufferYCbCrMatrix_ITU_R_2020, "ITU_R_2020");
91 GET_SYM(kVTCompressionPropertyKey_H264EntropyMode, "H264EntropyMode");
92 GET_SYM(kVTH264EntropyMode_CAVLC, "CAVLC");
93 GET_SYM(kVTH264EntropyMode_CABAC, "CABAC");
95 GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
96 GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
97 GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
98 GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
99 GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
100 GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
101 GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
102 GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
103 GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
104 GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
105 GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
106 GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
107 GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
108 GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
109 GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
110 GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
111 GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
112 GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
113 GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
115 GET_SYM(kVTCompressionPropertyKey_RealTime, "RealTime");
117 GET_SYM(kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
118 "EnableHardwareAcceleratedVideoEncoder");
119 GET_SYM(kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
120 "RequireHardwareAcceleratedVideoEncoder");
123 typedef enum VT_H264Profile {
131 typedef enum VTH264Entropy{
137 static const uint8_t start_code[] = { 0, 0, 0, 1 };
139 typedef struct ExtraSEI {
144 typedef struct BufNode {
145 CMSampleBufferRef cm_buffer;
147 struct BufNode* next;
151 typedef struct VTEncContext {
153 VTCompressionSessionRef session;
154 CFStringRef ycbcr_matrix;
155 CFStringRef color_primaries;
156 CFStringRef transfer_function;
158 pthread_mutex_t lock;
159 pthread_cond_t cv_sample_sent;
166 int64_t frame_ct_out;
176 int64_t frames_before;
177 int64_t frames_after;
183 bool warned_color_range;
187 static int vtenc_populate_extradata(AVCodecContext *avctx,
188 CMVideoCodecType codec_type,
189 CFStringRef profile_level,
190 CFNumberRef gamma_level,
191 CFDictionaryRef enc_info,
192 CFDictionaryRef pixel_buffer_info);
195 * NULL-safe release of *refPtr, and sets value to NULL.
197 static void vt_release_num(CFNumberRef* refPtr){
206 static void set_async_error(VTEncContext *vtctx, int err)
210 pthread_mutex_lock(&vtctx->lock);
212 vtctx->async_error = err;
214 info = vtctx->q_head;
215 vtctx->q_head = vtctx->q_tail = NULL;
218 BufNode *next = info->next;
219 CFRelease(info->cm_buffer);
224 pthread_mutex_unlock(&vtctx->lock);
227 static void clear_frame_queue(VTEncContext *vtctx)
229 set_async_error(vtctx, 0);
232 static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
236 pthread_mutex_lock(&vtctx->lock);
238 if (vtctx->async_error) {
239 pthread_mutex_unlock(&vtctx->lock);
240 return vtctx->async_error;
243 if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
246 pthread_mutex_unlock(&vtctx->lock);
250 while (!vtctx->q_head && !vtctx->async_error && wait) {
251 pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
254 if (!vtctx->q_head) {
255 pthread_mutex_unlock(&vtctx->lock);
260 info = vtctx->q_head;
261 vtctx->q_head = vtctx->q_head->next;
262 if (!vtctx->q_head) {
263 vtctx->q_tail = NULL;
266 pthread_mutex_unlock(&vtctx->lock);
268 *buf = info->cm_buffer;
271 } else if (info->sei) {
272 if (info->sei->data) av_free(info->sei->data);
277 vtctx->frame_ct_out++;
282 static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
284 BufNode *info = av_malloc(sizeof(BufNode));
286 set_async_error(vtctx, AVERROR(ENOMEM));
291 info->cm_buffer = buffer;
295 pthread_mutex_lock(&vtctx->lock);
296 pthread_cond_signal(&vtctx->cv_sample_sent);
298 if (!vtctx->q_head) {
299 vtctx->q_head = info;
301 vtctx->q_tail->next = info;
304 vtctx->q_tail = info;
306 pthread_mutex_unlock(&vtctx->lock);
309 static int count_nalus(size_t length_code_size,
310 CMSampleBufferRef sample_buffer,
317 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
318 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
320 if (length_code_size > 4)
321 return AVERROR_INVALIDDATA;
323 while (offset < src_size) {
328 status = CMBlockBufferCopyDataBytes(block,
333 for (i = 0; i < length_code_size; i++) {
335 box_len |= size_buf[i];
338 curr_src_len = box_len + length_code_size;
339 offset += curr_src_len;
348 static CMVideoCodecType get_cm_codec_type(enum AVCodecID id)
351 case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
357 * Get the parameter sets from a CMSampleBufferRef.
358 * @param dst If *dst isn't NULL, the parameters are copied into existing
359 * memory. *dst_size must be set accordingly when *dst != NULL.
360 * If *dst is NULL, it will be allocated.
361 * In all cases, *dst_size is set to the number of bytes used starting
364 static int get_params_size(
365 AVCodecContext *avctx,
366 CMVideoFormatDescriptionRef vid_fmt,
369 size_t total_size = 0;
371 int is_count_bad = 0;
374 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
386 for (i = 0; i < ps_count || is_count_bad; i++) {
389 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
397 * When ps_count is invalid, status != 0 ends the loop normally
398 * unless we didn't get any parameter sets.
400 if (i > 0 && is_count_bad) status = 0;
405 total_size += ps_size + sizeof(start_code);
409 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
410 return AVERROR_EXTERNAL;
417 static int copy_param_sets(
418 AVCodecContext *avctx,
419 CMVideoFormatDescriptionRef vid_fmt,
424 int is_count_bad = 0;
429 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
442 for (i = 0; i < ps_count || is_count_bad; i++) {
447 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
454 if (i > 0 && is_count_bad) status = 0;
459 next_offset = offset + sizeof(start_code) + ps_size;
460 if (dst_size < next_offset) {
461 av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
462 return AVERROR_BUFFER_TOO_SMALL;
465 memcpy(dst + offset, start_code, sizeof(start_code));
466 offset += sizeof(start_code);
468 memcpy(dst + offset, ps, ps_size);
469 offset = next_offset;
473 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
474 return AVERROR_EXTERNAL;
480 static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
482 CMVideoFormatDescriptionRef vid_fmt;
486 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
488 av_log(avctx, AV_LOG_ERROR, "No video format.\n");
489 return AVERROR_EXTERNAL;
492 status = get_params_size(avctx, vid_fmt, &total_size);
494 av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
498 avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
499 if (!avctx->extradata) {
500 return AVERROR(ENOMEM);
502 avctx->extradata_size = total_size;
504 status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
507 av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
514 static void vtenc_output_callback(
516 void *sourceFrameCtx,
518 VTEncodeInfoFlags flags,
519 CMSampleBufferRef sample_buffer)
521 AVCodecContext *avctx = ctx;
522 VTEncContext *vtctx = avctx->priv_data;
523 ExtraSEI *sei = sourceFrameCtx;
525 if (vtctx->async_error) {
526 if(sample_buffer) CFRelease(sample_buffer);
530 if (status || !sample_buffer) {
531 av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
532 set_async_error(vtctx, AVERROR_EXTERNAL);
536 if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
537 int set_status = set_extradata(avctx, sample_buffer);
539 set_async_error(vtctx, set_status);
544 vtenc_q_push(vtctx, sample_buffer, sei);
547 static int get_length_code_size(
548 AVCodecContext *avctx,
549 CMSampleBufferRef sample_buffer,
552 CMVideoFormatDescriptionRef vid_fmt;
556 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
558 av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
559 return AVERROR_EXTERNAL;
562 status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(vid_fmt,
569 av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
570 return AVERROR_EXTERNAL;
578 * Returns true on success.
580 * If profile_level_val is NULL and this method returns true, don't specify the
581 * profile/level to the encoder.
583 static bool get_vt_profile_level(AVCodecContext *avctx,
584 CFStringRef *profile_level_val)
586 VTEncContext *vtctx = avctx->priv_data;
587 int64_t profile = vtctx->profile;
589 if (profile == H264_PROF_AUTO && vtctx->level) {
590 //Need to pick a profile if level is not auto-selected.
591 profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;
594 *profile_level_val = NULL;
600 case H264_PROF_BASELINE:
601 switch (vtctx->level) {
602 case 0: *profile_level_val =
603 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
604 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
605 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
606 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
607 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
608 case 40: *profile_level_val =
609 compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
610 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
611 case 42: *profile_level_val =
612 compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
613 case 50: *profile_level_val =
614 compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
615 case 51: *profile_level_val =
616 compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
617 case 52: *profile_level_val =
618 compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
623 switch (vtctx->level) {
624 case 0: *profile_level_val =
625 compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
626 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
627 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
628 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
629 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
630 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
631 case 42: *profile_level_val =
632 compat_keys.kVTProfileLevel_H264_Main_4_2; break;
633 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
634 case 51: *profile_level_val =
635 compat_keys.kVTProfileLevel_H264_Main_5_1; break;
636 case 52: *profile_level_val =
637 compat_keys.kVTProfileLevel_H264_Main_5_2; break;
642 switch (vtctx->level) {
643 case 0: *profile_level_val =
644 compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
645 case 30: *profile_level_val =
646 compat_keys.kVTProfileLevel_H264_High_3_0; break;
647 case 31: *profile_level_val =
648 compat_keys.kVTProfileLevel_H264_High_3_1; break;
649 case 32: *profile_level_val =
650 compat_keys.kVTProfileLevel_H264_High_3_2; break;
651 case 40: *profile_level_val =
652 compat_keys.kVTProfileLevel_H264_High_4_0; break;
653 case 41: *profile_level_val =
654 compat_keys.kVTProfileLevel_H264_High_4_1; break;
655 case 42: *profile_level_val =
656 compat_keys.kVTProfileLevel_H264_High_4_2; break;
657 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
658 case 51: *profile_level_val =
659 compat_keys.kVTProfileLevel_H264_High_5_1; break;
660 case 52: *profile_level_val =
661 compat_keys.kVTProfileLevel_H264_High_5_2; break;
666 if (!*profile_level_val) {
667 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
674 static int get_cv_pixel_format(AVCodecContext* avctx,
675 enum AVPixelFormat fmt,
676 enum AVColorRange range,
677 int* av_pixel_format,
680 if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
681 range != AVCOL_RANGE_JPEG;
683 //MPEG range is used when no range is set
684 if (fmt == AV_PIX_FMT_NV12) {
685 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
686 kCVPixelFormatType_420YpCbCr8BiPlanarFullRange :
687 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange;
688 } else if (fmt == AV_PIX_FMT_YUV420P) {
689 *av_pixel_format = range == AVCOL_RANGE_JPEG ?
690 kCVPixelFormatType_420YpCbCr8PlanarFullRange :
691 kCVPixelFormatType_420YpCbCr8Planar;
693 return AVERROR(EINVAL);
699 static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
700 VTEncContext *vtctx = avctx->priv_data;
702 if (vtctx->color_primaries) {
703 CFDictionarySetValue(dict,
704 kCVImageBufferColorPrimariesKey,
705 vtctx->color_primaries);
708 if (vtctx->transfer_function) {
709 CFDictionarySetValue(dict,
710 kCVImageBufferTransferFunctionKey,
711 vtctx->transfer_function);
714 if (vtctx->ycbcr_matrix) {
715 CFDictionarySetValue(dict,
716 kCVImageBufferYCbCrMatrixKey,
717 vtctx->ycbcr_matrix);
721 static int create_cv_pixel_buffer_info(AVCodecContext* avctx,
722 CFMutableDictionaryRef* dict)
724 CFNumberRef cv_color_format_num = NULL;
725 CFNumberRef width_num = NULL;
726 CFNumberRef height_num = NULL;
727 CFMutableDictionaryRef pixel_buffer_info = NULL;
729 int status = get_cv_pixel_format(avctx,
734 if (status) return status;
736 pixel_buffer_info = CFDictionaryCreateMutable(
739 &kCFCopyStringDictionaryKeyCallBacks,
740 &kCFTypeDictionaryValueCallBacks);
742 if (!pixel_buffer_info) goto pbinfo_nomem;
744 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
747 if (!cv_color_format_num) goto pbinfo_nomem;
749 CFDictionarySetValue(pixel_buffer_info,
750 kCVPixelBufferPixelFormatTypeKey,
751 cv_color_format_num);
752 vt_release_num(&cv_color_format_num);
754 width_num = CFNumberCreate(kCFAllocatorDefault,
757 if (!width_num) return AVERROR(ENOMEM);
759 CFDictionarySetValue(pixel_buffer_info,
760 kCVPixelBufferWidthKey,
762 vt_release_num(&width_num);
764 height_num = CFNumberCreate(kCFAllocatorDefault,
767 if (!height_num) goto pbinfo_nomem;
769 CFDictionarySetValue(pixel_buffer_info,
770 kCVPixelBufferHeightKey,
772 vt_release_num(&height_num);
774 add_color_attr(avctx, pixel_buffer_info);
776 *dict = pixel_buffer_info;
780 vt_release_num(&cv_color_format_num);
781 vt_release_num(&width_num);
782 vt_release_num(&height_num);
783 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
785 return AVERROR(ENOMEM);
788 static int get_cv_color_primaries(AVCodecContext *avctx,
789 CFStringRef *primaries)
791 enum AVColorPrimaries pri = avctx->color_primaries;
793 case AVCOL_PRI_UNSPECIFIED:
797 case AVCOL_PRI_BT709:
798 *primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
801 case AVCOL_PRI_BT2020:
802 *primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
806 av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
814 static int get_cv_transfer_function(AVCodecContext *avctx,
815 CFStringRef *transfer_fnc,
816 CFNumberRef *gamma_level)
818 enum AVColorTransferCharacteristic trc = avctx->color_trc;
823 case AVCOL_TRC_UNSPECIFIED:
824 *transfer_fnc = NULL;
827 case AVCOL_TRC_BT709:
828 *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
831 case AVCOL_TRC_SMPTE240M:
832 *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;
835 case AVCOL_TRC_GAMMA22:
837 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
838 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
841 case AVCOL_TRC_GAMMA28:
843 *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;
844 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
847 case AVCOL_TRC_BT2020_10:
848 case AVCOL_TRC_BT2020_12:
849 *transfer_fnc = compat_keys.kCVImageBufferTransferFunction_ITU_R_2020;
853 av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));
860 static int get_cv_ycbcr_matrix(AVCodecContext *avctx, CFStringRef *matrix) {
861 switch(avctx->colorspace) {
862 case AVCOL_SPC_BT709:
863 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_709_2;
866 case AVCOL_SPC_UNSPECIFIED:
870 case AVCOL_SPC_BT470BG:
871 case AVCOL_SPC_SMPTE170M:
872 *matrix = kCVImageBufferYCbCrMatrix_ITU_R_601_4;
875 case AVCOL_SPC_SMPTE240M:
876 *matrix = kCVImageBufferYCbCrMatrix_SMPTE_240M_1995;
879 case AVCOL_SPC_BT2020_NCL:
880 *matrix = compat_keys.kCVImageBufferYCbCrMatrix_ITU_R_2020;
884 av_log(avctx, AV_LOG_ERROR, "Color space %s is not supported.\n", av_color_space_name(avctx->colorspace));
891 static int vtenc_create_encoder(AVCodecContext *avctx,
892 CMVideoCodecType codec_type,
893 CFStringRef profile_level,
894 CFNumberRef gamma_level,
895 CFDictionaryRef enc_info,
896 CFDictionaryRef pixel_buffer_info,
897 VTCompressionSessionRef *session)
899 VTEncContext *vtctx = avctx->priv_data;
900 SInt32 bit_rate = avctx->bit_rate;
901 CFNumberRef bit_rate_num;
903 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
910 vtenc_output_callback,
914 if (status || !vtctx->session) {
915 av_log(avctx, AV_LOG_ERROR, "Error: cannot create compression session: %d\n", status);
917 #if !TARGET_OS_IPHONE
918 if (!vtctx->allow_sw) {
919 av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
923 return AVERROR_EXTERNAL;
926 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
929 if (!bit_rate_num) return AVERROR(ENOMEM);
931 status = VTSessionSetProperty(vtctx->session,
932 kVTCompressionPropertyKey_AverageBitRate,
934 CFRelease(bit_rate_num);
937 av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
938 return AVERROR_EXTERNAL;
942 status = VTSessionSetProperty(vtctx->session,
943 kVTCompressionPropertyKey_ProfileLevel,
946 av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d\n", status);
950 if (avctx->gop_size > 0) {
951 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
955 return AVERROR(ENOMEM);
958 status = VTSessionSetProperty(vtctx->session,
959 kVTCompressionPropertyKey_MaxKeyFrameInterval,
964 av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
965 return AVERROR_EXTERNAL;
969 if (vtctx->frames_before) {
970 status = VTSessionSetProperty(vtctx->session,
971 kVTCompressionPropertyKey_MoreFramesBeforeStart,
974 if (status == kVTPropertyNotSupportedErr) {
975 av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
977 av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
981 if (vtctx->frames_after) {
982 status = VTSessionSetProperty(vtctx->session,
983 kVTCompressionPropertyKey_MoreFramesAfterEnd,
986 if (status == kVTPropertyNotSupportedErr) {
987 av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
989 av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
993 if (avctx->sample_aspect_ratio.num != 0) {
996 CFMutableDictionaryRef par;
997 AVRational *avpar = &avctx->sample_aspect_ratio;
999 av_reduce(&avpar->num, &avpar->den,
1000 avpar->num, avpar->den,
1003 num = CFNumberCreate(kCFAllocatorDefault,
1007 den = CFNumberCreate(kCFAllocatorDefault,
1013 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1015 &kCFCopyStringDictionaryKeyCallBacks,
1016 &kCFTypeDictionaryValueCallBacks);
1018 if (!par || !num || !den) {
1019 if (par) CFRelease(par);
1020 if (num) CFRelease(num);
1021 if (den) CFRelease(den);
1023 return AVERROR(ENOMEM);
1026 CFDictionarySetValue(
1028 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1031 CFDictionarySetValue(
1033 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1036 status = VTSessionSetProperty(vtctx->session,
1037 kVTCompressionPropertyKey_PixelAspectRatio,
1047 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1048 avctx->sample_aspect_ratio.num,
1049 avctx->sample_aspect_ratio.den,
1052 return AVERROR_EXTERNAL;
1057 if (vtctx->transfer_function) {
1058 status = VTSessionSetProperty(vtctx->session,
1059 kVTCompressionPropertyKey_TransferFunction,
1060 vtctx->transfer_function);
1063 av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1068 if (vtctx->ycbcr_matrix) {
1069 status = VTSessionSetProperty(vtctx->session,
1070 kVTCompressionPropertyKey_YCbCrMatrix,
1071 vtctx->ycbcr_matrix);
1074 av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1079 if (vtctx->color_primaries) {
1080 status = VTSessionSetProperty(vtctx->session,
1081 kVTCompressionPropertyKey_ColorPrimaries,
1082 vtctx->color_primaries);
1085 av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1090 status = VTSessionSetProperty(vtctx->session,
1091 kCVImageBufferGammaLevelKey,
1095 av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1099 if (!vtctx->has_b_frames) {
1100 status = VTSessionSetProperty(vtctx->session,
1101 kVTCompressionPropertyKey_AllowFrameReordering,
1105 av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1106 return AVERROR_EXTERNAL;
1110 if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1111 CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1112 compat_keys.kVTH264EntropyMode_CABAC:
1113 compat_keys.kVTH264EntropyMode_CAVLC;
1115 status = VTSessionSetProperty(vtctx->session,
1116 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1120 av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1124 if (vtctx->realtime) {
1125 status = VTSessionSetProperty(vtctx->session,
1126 compat_keys.kVTCompressionPropertyKey_RealTime,
1130 av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1134 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1136 av_log(avctx, AV_LOG_ERROR, "Error: cannot prepare encoder: %d\n", status);
1137 return AVERROR_EXTERNAL;
1143 static av_cold int vtenc_init(AVCodecContext *avctx)
1145 CFMutableDictionaryRef enc_info;
1146 CFMutableDictionaryRef pixel_buffer_info;
1147 CMVideoCodecType codec_type;
1148 VTEncContext *vtctx = avctx->priv_data;
1149 CFStringRef profile_level;
1150 CFBooleanRef has_b_frames_cfbool;
1151 CFNumberRef gamma_level = NULL;
1154 pthread_once(&once_ctrl, loadVTEncSymbols);
1156 codec_type = get_cm_codec_type(avctx->codec_id);
1158 av_log(avctx, AV_LOG_ERROR, "Error: no mapping for AVCodecID %d\n", avctx->codec_id);
1159 return AVERROR(EINVAL);
1162 vtctx->has_b_frames = avctx->max_b_frames > 0;
1163 if(vtctx->has_b_frames && vtctx->profile == H264_PROF_BASELINE){
1164 av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1165 vtctx->has_b_frames = false;
1168 if (vtctx->entropy == VT_CABAC && vtctx->profile == H264_PROF_BASELINE) {
1169 av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1170 vtctx->entropy = VT_ENTROPY_NOT_SET;
1173 if (!get_vt_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1175 vtctx->session = NULL;
1177 enc_info = CFDictionaryCreateMutable(
1178 kCFAllocatorDefault,
1180 &kCFCopyStringDictionaryKeyCallBacks,
1181 &kCFTypeDictionaryValueCallBacks
1184 if (!enc_info) return AVERROR(ENOMEM);
1186 #if !TARGET_OS_IPHONE
1187 if (!vtctx->allow_sw) {
1188 CFDictionarySetValue(enc_info,
1189 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1192 CFDictionarySetValue(enc_info,
1193 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1198 if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1199 status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1203 pixel_buffer_info = NULL;
1206 pthread_mutex_init(&vtctx->lock, NULL);
1207 pthread_cond_init(&vtctx->cv_sample_sent, NULL);
1208 vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1210 get_cv_transfer_function(avctx, &vtctx->transfer_function, &gamma_level);
1211 get_cv_ycbcr_matrix(avctx, &vtctx->ycbcr_matrix);
1212 get_cv_color_primaries(avctx, &vtctx->color_primaries);
1215 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1216 status = vtenc_populate_extradata(avctx,
1226 status = vtenc_create_encoder(avctx,
1237 status = VTSessionCopyProperty(vtctx->session,
1238 kVTCompressionPropertyKey_AllowFrameReordering,
1239 kCFAllocatorDefault,
1240 &has_b_frames_cfbool);
1243 //Some devices don't output B-frames for main profile, even if requested.
1244 vtctx->has_b_frames = CFBooleanGetValue(has_b_frames_cfbool);
1245 CFRelease(has_b_frames_cfbool);
1247 avctx->has_b_frames = vtctx->has_b_frames;
1251 CFRelease(gamma_level);
1253 if (pixel_buffer_info)
1254 CFRelease(pixel_buffer_info);
1256 CFRelease(enc_info);
1261 static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1263 CFArrayRef attachments;
1264 CFDictionaryRef attachment;
1265 CFBooleanRef not_sync;
1268 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1269 len = !attachments ? 0 : CFArrayGetCount(attachments);
1272 *is_key_frame = true;
1276 attachment = CFArrayGetValueAtIndex(attachments, 0);
1278 if (CFDictionaryGetValueIfPresent(attachment,
1279 kCMSampleAttachmentKey_NotSync,
1280 (const void **)¬_sync))
1282 *is_key_frame = !CFBooleanGetValue(not_sync);
1284 *is_key_frame = true;
1288 static int is_post_sei_nal_type(int nal_type){
1289 return nal_type != H264_NAL_SEI &&
1290 nal_type != H264_NAL_SPS &&
1291 nal_type != H264_NAL_PPS &&
1292 nal_type != H264_NAL_AUD;
1296 * Finds the sei message start/size of type find_sei_type.
1297 * If more than one of that type exists, the last one is returned.
1299 static int find_sei_end(AVCodecContext *avctx,
1305 size_t sei_payload_size = 0;
1306 int sei_payload_type = 0;
1308 uint8_t *nal_start = nal_data;
1313 nal_type = *nal_data & 0x1F;
1314 if (nal_type != H264_NAL_SEI)
1320 if (nal_data[nal_size - 1] == 0x80)
1323 while (nal_size > 0 && *nal_data > 0) {
1325 sei_payload_type += *nal_data;
1328 } while (nal_size > 0 && *nal_data == 0xFF);
1331 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1332 return AVERROR_INVALIDDATA;
1336 sei_payload_size += *nal_data;
1339 } while (nal_size > 0 && *nal_data == 0xFF);
1341 if (nal_size < sei_payload_size) {
1342 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1343 return AVERROR_INVALIDDATA;
1346 nal_data += sei_payload_size;
1347 nal_size -= sei_payload_size;
1350 *sei_end = nal_data;
1352 return nal_data - nal_start + 1;
1356 * Copies the data inserting emulation prevention bytes as needed.
1357 * Existing data in the destination can be taken into account by providing
1358 * dst with a dst_offset > 0.
1360 * @return The number of bytes copied on success. On failure, the negative of
1361 * the number of bytes needed to copy src is returned.
1363 static int copy_emulation_prev(const uint8_t *src,
1372 uint8_t* dst_end = dst + dst_size;
1373 const uint8_t* src_end = src + src_size;
1374 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1376 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1385 for (; src < src_end; src++, dst++) {
1387 int insert_ep3_byte = *src <= 3;
1388 if (insert_ep3_byte) {
1406 wrote_bytes = dst - dst_start;
1409 return -wrote_bytes;
1414 static int write_sei(const ExtraSEI *sei,
1419 uint8_t *sei_start = dst;
1420 size_t remaining_sei_size = sei->size;
1421 size_t remaining_dst_size = dst_size;
1426 if (!remaining_dst_size)
1427 return AVERROR_BUFFER_TOO_SMALL;
1429 while (sei_type && remaining_dst_size != 0) {
1430 int sei_byte = sei_type > 255 ? 255 : sei_type;
1433 sei_type -= sei_byte;
1435 remaining_dst_size--;
1439 return AVERROR_BUFFER_TOO_SMALL;
1441 while (remaining_sei_size && remaining_dst_size != 0) {
1442 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
1445 remaining_sei_size -= size_byte;
1447 remaining_dst_size--;
1450 if (remaining_dst_size < sei->size)
1451 return AVERROR_BUFFER_TOO_SMALL;
1453 header_bytes = dst - sei_start;
1455 offset = header_bytes;
1456 bytes_written = copy_emulation_prev(sei->data,
1461 if (bytes_written < 0)
1462 return AVERROR_BUFFER_TOO_SMALL;
1464 bytes_written += header_bytes;
1465 return bytes_written;
1469 * Copies NAL units and replaces length codes with
1470 * H.264 Annex B start codes. On failure, the contents of
1471 * dst_data may have been modified.
1473 * @param length_code_size Byte length of each length code
1474 * @param sample_buffer NAL units prefixed with length codes.
1475 * @param sei Optional A53 closed captions SEI data.
1476 * @param dst_data Must be zeroed before calling this function.
1477 * Contains the copied NAL units prefixed with
1478 * start codes when the function returns
1480 * @param dst_size Length of dst_data
1481 * @return 0 on success
1482 * AVERROR_INVALIDDATA if length_code_size is invalid
1483 * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
1484 * or if a length_code in src_data specifies data beyond
1485 * the end of its buffer.
1487 static int copy_replace_length_codes(
1488 AVCodecContext *avctx,
1489 size_t length_code_size,
1490 CMSampleBufferRef sample_buffer,
1495 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1496 size_t remaining_src_size = src_size;
1497 size_t remaining_dst_size = dst_size;
1498 size_t src_offset = 0;
1501 uint8_t size_buf[4];
1503 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
1505 if (length_code_size > 4) {
1506 return AVERROR_INVALIDDATA;
1509 while (remaining_src_size > 0) {
1510 size_t curr_src_len;
1511 size_t curr_dst_len;
1517 status = CMBlockBufferCopyDataBytes(block,
1522 av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
1523 return AVERROR_EXTERNAL;
1526 status = CMBlockBufferCopyDataBytes(block,
1527 src_offset + length_code_size,
1532 av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
1533 return AVERROR_EXTERNAL;
1538 for (i = 0; i < length_code_size; i++) {
1540 box_len |= size_buf[i];
1543 if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
1544 //No SEI NAL unit - insert.
1547 memcpy(dst_data, start_code, sizeof(start_code));
1548 dst_data += sizeof(start_code);
1549 remaining_dst_size -= sizeof(start_code);
1551 *dst_data = H264_NAL_SEI;
1553 remaining_dst_size--;
1555 wrote_bytes = write_sei(sei,
1556 SEI_TYPE_USER_DATA_REGISTERED,
1558 remaining_dst_size);
1560 if (wrote_bytes < 0)
1563 remaining_dst_size -= wrote_bytes;
1564 dst_data += wrote_bytes;
1566 if (remaining_dst_size <= 0)
1567 return AVERROR_BUFFER_TOO_SMALL;
1572 remaining_dst_size--;
1577 curr_src_len = box_len + length_code_size;
1578 curr_dst_len = box_len + sizeof(start_code);
1580 if (remaining_src_size < curr_src_len) {
1581 return AVERROR_BUFFER_TOO_SMALL;
1584 if (remaining_dst_size < curr_dst_len) {
1585 return AVERROR_BUFFER_TOO_SMALL;
1588 dst_box = dst_data + sizeof(start_code);
1590 memcpy(dst_data, start_code, sizeof(start_code));
1591 status = CMBlockBufferCopyDataBytes(block,
1592 src_offset + length_code_size,
1597 av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
1598 return AVERROR_EXTERNAL;
1601 if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
1602 //Found SEI NAL unit - append.
1607 old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
1608 if (old_sei_length < 0)
1611 wrote_bytes = write_sei(sei,
1612 SEI_TYPE_USER_DATA_REGISTERED,
1614 remaining_dst_size - old_sei_length);
1615 if (wrote_bytes < 0)
1618 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
1619 return AVERROR_BUFFER_TOO_SMALL;
1621 new_sei[wrote_bytes++] = 0x80;
1622 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
1624 dst_data += extra_bytes;
1625 remaining_dst_size -= extra_bytes;
1630 src_offset += curr_src_len;
1631 dst_data += curr_dst_len;
1633 remaining_src_size -= curr_src_len;
1634 remaining_dst_size -= curr_dst_len;
1641 * Returns a sufficient number of bytes to contain the sei data.
1642 * It may be greater than the minimum required.
1644 static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
1649 copied_size = -copy_emulation_prev(sei->data,
1655 if ((sei->size % 255) == 0) //may result in an extra byte
1658 return copied_size + sei->size / 255 + 1 + type / 255 + 1;
1661 static int vtenc_cm_to_avpacket(
1662 AVCodecContext *avctx,
1663 CMSampleBufferRef sample_buffer,
1667 VTEncContext *vtctx = avctx->priv_data;
1672 size_t length_code_size;
1673 size_t header_size = 0;
1675 size_t out_buf_size;
1676 size_t sei_nalu_size = 0;
1678 int64_t time_base_num;
1682 CMVideoFormatDescriptionRef vid_fmt;
1685 vtenc_get_frame_info(sample_buffer, &is_key_frame);
1686 status = get_length_code_size(avctx, sample_buffer, &length_code_size);
1687 if (status) return status;
1689 add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
1692 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
1694 av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
1695 return AVERROR_EXTERNAL;
1698 int status = get_params_size(avctx, vid_fmt, &header_size);
1699 if (status) return status;
1702 status = count_nalus(length_code_size, sample_buffer, &nalu_count);
1707 size_t msg_size = get_sei_msg_bytes(sei,
1708 SEI_TYPE_USER_DATA_REGISTERED);
1710 sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
1713 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
1714 out_buf_size = header_size +
1717 nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
1719 status = ff_alloc_packet2(avctx, pkt, out_buf_size, out_buf_size);
1724 status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
1725 if(status) return status;
1728 status = copy_replace_length_codes(
1733 pkt->data + header_size,
1734 pkt->size - header_size
1738 av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
1743 pkt->flags |= AV_PKT_FLAG_KEY;
1746 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
1747 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
1749 if (CMTIME_IS_INVALID(dts)) {
1750 if (!vtctx->has_b_frames) {
1753 av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
1754 return AVERROR_EXTERNAL;
1758 dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
1759 time_base_num = avctx->time_base.num;
1760 pkt->pts = pts.value / time_base_num;
1761 pkt->dts = dts.value / time_base_num - dts_delta;
1762 pkt->size = out_buf_size;
1768 * contiguous_buf_size is 0 if not contiguous, and the size of the buffer
1769 * containing all planes if so.
1771 static int get_cv_pixel_info(
1772 AVCodecContext *avctx,
1773 const AVFrame *frame,
1779 size_t *contiguous_buf_size)
1781 VTEncContext *vtctx = avctx->priv_data;
1782 int av_format = frame->format;
1783 int av_color_range = av_frame_get_color_range(frame);
1788 status = get_cv_pixel_format(avctx, av_format, av_color_range, color, &range_guessed);
1792 "Could not get pixel format for color format '%s' range '%s'.\n",
1793 av_get_pix_fmt_name(av_format),
1794 av_color_range > AVCOL_RANGE_UNSPECIFIED &&
1795 av_color_range < AVCOL_RANGE_NB ?
1796 av_color_range_name(av_color_range) :
1799 return AVERROR(EINVAL);
1802 if (range_guessed) {
1803 if (!vtctx->warned_color_range) {
1804 vtctx->warned_color_range = true;
1807 "Color range not set for %s. Using MPEG range.\n",
1808 av_get_pix_fmt_name(av_format));
1811 av_log(avctx, AV_LOG_WARNING, "");
1814 switch (av_format) {
1815 case AV_PIX_FMT_NV12:
1818 widths [0] = avctx->width;
1819 heights[0] = avctx->height;
1820 strides[0] = frame ? frame->linesize[0] : avctx->width;
1822 widths [1] = (avctx->width + 1) / 2;
1823 heights[1] = (avctx->height + 1) / 2;
1824 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) & -2;
1827 case AV_PIX_FMT_YUV420P:
1830 widths [0] = avctx->width;
1831 heights[0] = avctx->height;
1832 strides[0] = frame ? frame->linesize[0] : avctx->width;
1834 widths [1] = (avctx->width + 1) / 2;
1835 heights[1] = (avctx->height + 1) / 2;
1836 strides[1] = frame ? frame->linesize[1] : (avctx->width + 1) / 2;
1838 widths [2] = (avctx->width + 1) / 2;
1839 heights[2] = (avctx->height + 1) / 2;
1840 strides[2] = frame ? frame->linesize[2] : (avctx->width + 1) / 2;
1847 "Could not get frame format info for color %d range %d.\n",
1851 return AVERROR(EINVAL);
1854 *contiguous_buf_size = 0;
1855 for (i = 0; i < *plane_count; i++) {
1856 if (i < *plane_count - 1 &&
1857 frame->data[i] + strides[i] * heights[i] != frame->data[i + 1]) {
1858 *contiguous_buf_size = 0;
1862 *contiguous_buf_size += strides[i] * heights[i];
1868 #if !TARGET_OS_IPHONE
1869 //Not used on iOS - frame is always copied.
1870 static void free_avframe(
1875 const void *plane_addresses[])
1877 AVFrame *frame = release_ctx;
1878 av_frame_free(&frame);
1881 //Not used on OSX - frame is never copied.
1882 static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx,
1883 const AVFrame *frame,
1884 CVPixelBufferRef cv_img,
1885 const size_t *plane_strides,
1886 const size_t *plane_rows)
1898 status = CVPixelBufferLockBaseAddress(cv_img, 0);
1903 "Error: Could not lock base address of CVPixelBuffer: %d.\n",
1908 if (CVPixelBufferIsPlanar(cv_img)) {
1909 plane_count = CVPixelBufferGetPlaneCount(cv_img);
1910 for (i = 0; frame->data[i]; i++) {
1911 if (i == plane_count) {
1912 CVPixelBufferUnlockBaseAddress(cv_img, 0);
1915 "Error: different number of planes in AVFrame and CVPixelBuffer.\n"
1918 return AVERROR_EXTERNAL;
1921 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
1922 src_addr = (uint8_t*)frame->data[i];
1923 dst_stride = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
1924 src_stride = plane_strides[i];
1925 rows = plane_rows[i];
1927 if (dst_stride == src_stride) {
1928 memcpy(dst_addr, src_addr, src_stride * rows);
1930 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
1932 for (j = 0; j < rows; j++) {
1933 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
1938 if (frame->data[1]) {
1939 CVPixelBufferUnlockBaseAddress(cv_img, 0);
1942 "Error: different number of planes in AVFrame and non-planar CVPixelBuffer.\n"
1945 return AVERROR_EXTERNAL;
1948 dst_addr = (uint8_t*)CVPixelBufferGetBaseAddress(cv_img);
1949 src_addr = (uint8_t*)frame->data[0];
1950 dst_stride = CVPixelBufferGetBytesPerRow(cv_img);
1951 src_stride = plane_strides[0];
1952 rows = plane_rows[0];
1954 if (dst_stride == src_stride) {
1955 memcpy(dst_addr, src_addr, src_stride * rows);
1957 copy_bytes = dst_stride < src_stride ? dst_stride : src_stride;
1959 for (j = 0; j < rows; j++) {
1960 memcpy(dst_addr + j * dst_stride, src_addr + j * src_stride, copy_bytes);
1965 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
1967 av_log(avctx, AV_LOG_ERROR, "Error: Could not unlock CVPixelBuffer base address: %d.\n", status);
1968 return AVERROR_EXTERNAL;
1973 #endif //!TARGET_OS_IPHONE
1975 static int create_cv_pixel_buffer(AVCodecContext *avctx,
1976 const AVFrame *frame,
1977 CVPixelBufferRef *cv_img)
1981 size_t widths [AV_NUM_DATA_POINTERS];
1982 size_t heights[AV_NUM_DATA_POINTERS];
1983 size_t strides[AV_NUM_DATA_POINTERS];
1985 size_t contiguous_buf_size;
1986 #if TARGET_OS_IPHONE
1987 CVPixelBufferPoolRef pix_buf_pool;
1988 VTEncContext* vtctx = avctx->priv_data;
1990 CFMutableDictionaryRef pix_buf_attachments = CFDictionaryCreateMutable(
1991 kCFAllocatorDefault,
1993 &kCFCopyStringDictionaryKeyCallBacks,
1994 &kCFTypeDictionaryValueCallBacks);
1996 if (!pix_buf_attachments) return AVERROR(ENOMEM);
1999 if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2000 av_assert0(frame->format == AV_PIX_FMT_VIDEOTOOLBOX);
2002 *cv_img = (CVPixelBufferRef)frame->data[3];
2003 av_assert0(*cv_img);
2009 memset(widths, 0, sizeof(widths));
2010 memset(heights, 0, sizeof(heights));
2011 memset(strides, 0, sizeof(strides));
2013 status = get_cv_pixel_info(
2021 &contiguous_buf_size
2028 "Error: Cannot convert format %d color_range %d: %d\n",
2030 av_frame_get_color_range(frame),
2034 return AVERROR_EXTERNAL;
2037 #if TARGET_OS_IPHONE
2038 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2039 if (!pix_buf_pool) {
2040 av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2041 return AVERROR_EXTERNAL;
2044 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2050 av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2051 return AVERROR_EXTERNAL;
2054 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img, strides, heights);
2061 AVFrame *enc_frame = av_frame_alloc();
2062 if (!enc_frame) return AVERROR(ENOMEM);
2064 status = av_frame_ref(enc_frame, frame);
2066 av_frame_free(&enc_frame);
2070 status = CVPixelBufferCreateWithPlanarBytes(
2071 kCFAllocatorDefault,
2076 contiguous_buf_size,
2078 (void **)enc_frame->data,
2088 add_color_attr(avctx, pix_buf_attachments);
2089 CVBufferSetAttachments(*cv_img, pix_buf_attachments, kCVAttachmentMode_ShouldPropagate);
2090 CFRelease(pix_buf_attachments);
2093 av_log(avctx, AV_LOG_ERROR, "Error: Could not create CVPixelBuffer: %d\n", status);
2094 return AVERROR_EXTERNAL;
2101 static int create_encoder_dict_h264(const AVFrame *frame,
2102 CFDictionaryRef* dict_out)
2104 CFDictionaryRef dict = NULL;
2105 if (frame->pict_type == AV_PICTURE_TYPE_I) {
2106 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2107 const void *vals[] = { kCFBooleanTrue };
2109 dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2110 if(!dict) return AVERROR(ENOMEM);
2117 static int vtenc_send_frame(AVCodecContext *avctx,
2118 VTEncContext *vtctx,
2119 const AVFrame *frame)
2122 CFDictionaryRef frame_dict;
2123 CVPixelBufferRef cv_img = NULL;
2124 AVFrameSideData *side_data = NULL;
2125 ExtraSEI *sei = NULL;
2126 int status = create_cv_pixel_buffer(avctx, frame, &cv_img);
2128 if (status) return status;
2130 status = create_encoder_dict_h264(frame, &frame_dict);
2136 side_data = av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC);
2137 if (vtctx->a53_cc && side_data && side_data->size) {
2138 sei = av_mallocz(sizeof(*sei));
2140 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2142 int ret = ff_alloc_a53_sei(frame, 0, &sei->data, &sei->size);
2144 av_log(avctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2151 time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2152 status = VTCompressionSessionEncodeFrame(
2162 if (frame_dict) CFRelease(frame_dict);
2166 av_log(avctx, AV_LOG_ERROR, "Error: cannot encode frame: %d\n", status);
2167 return AVERROR_EXTERNAL;
2173 static av_cold int vtenc_frame(
2174 AVCodecContext *avctx,
2176 const AVFrame *frame,
2179 VTEncContext *vtctx = avctx->priv_data;
2182 CMSampleBufferRef buf = NULL;
2183 ExtraSEI *sei = NULL;
2186 status = vtenc_send_frame(avctx, vtctx, frame);
2189 status = AVERROR_EXTERNAL;
2193 if (vtctx->frame_ct_in == 0) {
2194 vtctx->first_pts = frame->pts;
2195 } else if(vtctx->frame_ct_in == 1 && vtctx->has_b_frames) {
2196 vtctx->dts_delta = frame->pts - vtctx->first_pts;
2199 vtctx->frame_ct_in++;
2200 } else if(!vtctx->flushing) {
2201 vtctx->flushing = true;
2203 status = VTCompressionSessionCompleteFrames(vtctx->session,
2207 av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2208 status = AVERROR_EXTERNAL;
2214 get_frame = vtctx->dts_delta >= 0 || !frame;
2220 status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2221 if (status) goto end_nopkt;
2222 if (!buf) goto end_nopkt;
2224 status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei);
2226 if (sei->data) av_free(sei->data);
2230 if (status) goto end_nopkt;
2236 av_packet_unref(pkt);
2240 static int vtenc_populate_extradata(AVCodecContext *avctx,
2241 CMVideoCodecType codec_type,
2242 CFStringRef profile_level,
2243 CFNumberRef gamma_level,
2244 CFDictionaryRef enc_info,
2245 CFDictionaryRef pixel_buffer_info)
2247 VTEncContext *vtctx = avctx->priv_data;
2248 AVFrame *frame = av_frame_alloc();
2249 int y_size = avctx->width * avctx->height;
2250 int chroma_size = (avctx->width / 2) * (avctx->height / 2);
2251 CMSampleBufferRef buf = NULL;
2255 return AVERROR(ENOMEM);
2257 frame->buf[0] = av_buffer_alloc(y_size + 2 * chroma_size);
2260 status = AVERROR(ENOMEM);
2264 status = vtenc_create_encoder(avctx,
2274 frame->data[0] = frame->buf[0]->data;
2275 memset(frame->data[0], 0, y_size);
2277 frame->data[1] = frame->buf[0]->data + y_size;
2278 memset(frame->data[1], 128, chroma_size);
2281 if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
2282 frame->data[2] = frame->buf[0]->data + y_size + chroma_size;
2283 memset(frame->data[2], 128, chroma_size);
2286 frame->linesize[0] = avctx->width;
2288 if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
2289 frame->linesize[1] =
2290 frame->linesize[2] = (avctx->width + 1) / 2;
2292 frame->linesize[1] = (avctx->width + 1) / 2;
2295 frame->format = avctx->pix_fmt;
2296 frame->width = avctx->width;
2297 frame->height = avctx->height;
2298 av_frame_set_colorspace(frame, avctx->colorspace);
2299 av_frame_set_color_range(frame, avctx->color_range);
2300 frame->color_trc = avctx->color_trc;
2301 frame->color_primaries = avctx->color_primaries;
2304 status = vtenc_send_frame(avctx, vtctx, frame);
2306 av_log(avctx, AV_LOG_ERROR, "Error sending frame: %d\n", status);
2310 //Populates extradata - output frames are flushed and param sets are available.
2311 status = VTCompressionSessionCompleteFrames(vtctx->session,
2317 status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2319 av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2329 CFRelease(vtctx->session);
2331 vtctx->session = NULL;
2332 vtctx->frame_ct_out = 0;
2334 av_frame_unref(frame);
2335 av_frame_free(&frame);
2337 av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2342 static av_cold int vtenc_close(AVCodecContext *avctx)
2344 VTEncContext *vtctx = avctx->priv_data;
2346 if(!vtctx->session) return 0;
2348 VTCompressionSessionCompleteFrames(vtctx->session,
2350 clear_frame_queue(vtctx);
2351 pthread_cond_destroy(&vtctx->cv_sample_sent);
2352 pthread_mutex_destroy(&vtctx->lock);
2353 CFRelease(vtctx->session);
2354 vtctx->session = NULL;
2356 if (vtctx->color_primaries) {
2357 CFRelease(vtctx->color_primaries);
2358 vtctx->color_primaries = NULL;
2361 if (vtctx->transfer_function) {
2362 CFRelease(vtctx->transfer_function);
2363 vtctx->transfer_function = NULL;
2366 if (vtctx->ycbcr_matrix) {
2367 CFRelease(vtctx->ycbcr_matrix);
2368 vtctx->ycbcr_matrix = NULL;
2374 static const enum AVPixelFormat pix_fmts[] = {
2375 AV_PIX_FMT_VIDEOTOOLBOX,
2381 #define OFFSET(x) offsetof(VTEncContext, x)
2382 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2383 static const AVOption options[] = {
2384 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = H264_PROF_AUTO }, H264_PROF_AUTO, H264_PROF_COUNT, VE, "profile" },
2385 { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_BASELINE }, INT_MIN, INT_MAX, VE, "profile" },
2386 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_MAIN }, INT_MIN, INT_MAX, VE, "profile" },
2387 { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROF_HIGH }, INT_MIN, INT_MAX, VE, "profile" },
2389 { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, "level" },
2390 { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, "level" },
2391 { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, "level" },
2392 { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, "level" },
2393 { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, "level" },
2394 { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, "level" },
2395 { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, "level" },
2396 { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, "level" },
2397 { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, "level" },
2398 { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, "level" },
2399 { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, "level" },
2401 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL,
2402 { .i64 = 0 }, 0, 1, VE },
2404 { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, "coder" },
2405 { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2406 { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, "coder" },
2407 { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2408 { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, "coder" },
2410 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).",
2411 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2413 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.",
2414 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2415 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.",
2416 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2418 { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2423 static const AVClass h264_videotoolbox_class = {
2424 .class_name = "h264_videotoolbox",
2425 .item_name = av_default_item_name,
2427 .version = LIBAVUTIL_VERSION_INT,
2430 AVCodec ff_h264_videotoolbox_encoder = {
2431 .name = "h264_videotoolbox",
2432 .long_name = NULL_IF_CONFIG_SMALL("VideoToolbox H.264 Encoder"),
2433 .type = AVMEDIA_TYPE_VIDEO,
2434 .id = AV_CODEC_ID_H264,
2435 .priv_data_size = sizeof(VTEncContext),
2436 .pix_fmts = pix_fmts,
2438 .encode2 = vtenc_frame,
2439 .close = vtenc_close,
2440 .capabilities = AV_CODEC_CAP_DELAY,
2441 .priv_class = &h264_videotoolbox_class,
2442 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE |
2443 FF_CODEC_CAP_INIT_CLEANUP,