FFmpeg
Loading...
Searching...
No Matches
videotoolboxenc.c
Go to the documentation of this file.
1/*
2 * copyright (c) 2015 Rick Kern <kernrj@gmail.com>
3 *
4 * This file is part of FFmpeg.
5 *
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.
10 *
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.
15 *
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
19 */
20
21#include <Availability.h>
22#include <CoreMedia/CoreMedia.h>
23#include <CoreVideo/CoreVideo.h>
24#include <dlfcn.h>
25#include <pthread.h>
26#include <TargetConditionals.h>
27#include <VideoToolbox/VideoToolbox.h>
28
30#include "libavutil/avassert.h"
31#include "libavutil/imgutils.h"
32#include "libavutil/mem.h"
33#include "libavutil/opt.h"
34#include "libavutil/pixdesc.h"
36
37#include "atsc_a53.h"
38#include "codec_internal.h"
39#include "encode.h"
40#include "h264.h"
41#include "h264_sei.h"
42#include "hwconfig.h"
43#include "internal.h"
44
45#if !HAVE_KCMVIDEOCODECTYPE_HEVC
46enum { kCMVideoCodecType_HEVC = 'hvc1' };
47#endif
48
49#if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
51#endif
52
53#if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
56#endif
57
58#if !HAVE_KVTQPMODULATIONLEVEL_DEFAULT
61#endif
62
63#ifndef TARGET_CPU_ARM64
64# define TARGET_CPU_ARM64 0
65#endif
66
67/*
68 * Upper bound of the reorder depth of VideoToolbox H.264 and HEVC
69 * output, in frames. The encoder shifts the decode timestamps
70 * VideoToolbox reports by the pts distance of this many frames, and
71 * the value is published as AVCodecContext.has_b_frames; understating
72 * it outputs frames with dts greater than pts.
73 *
74 * The VideoToolbox API does not report the depth, so the value was
75 * measured from encoder output on macOS 15 (Apple silicon). It bounds
76 * the real depth instead of matching it everywhere: the software
77 * H.264 encoder (require_sw) reorders by one frame, and untested
78 * devices may reorder less. Keeping one value for every encoder is
79 * safe because overstating only shifts dts earlier, and it is simpler
80 * than branching per encoder.
81 */
82#define REORDER_DELAY 2
83
84typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
85 size_t parameterSetIndex,
86 const uint8_t **parameterSetPointerOut,
87 size_t *parameterSetSizeOut,
88 size_t *parameterSetCountOut,
89 int *NALUnitHeaderLengthOut);
90
91/*
92 * Symbols that aren't available in MacOS 10.8 and iOS 8.0 need to be accessed
93 * from compat_keys, or it will cause compiler errors when compiling for older
94 * OS versions.
95 *
96 * For example, kVTCompressionPropertyKey_H264EntropyMode was added in
97 * MacOS 10.9. If this constant were used directly, a compiler would generate
98 * an error when it has access to the MacOS 10.8 headers, but does not have
99 * 10.9 headers.
100 *
101 * Runtime errors will still occur when unknown keys are set. A warning is
102 * logged and encoding continues where possible.
103 *
104 * When adding new symbols, they should be loaded/set in loadVTEncSymbols().
105 */
106static struct{
110
114
138
142
149
158
161
162#define GET_SYM(symbol, defaultVal) \
163do{ \
164 CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
165 if(!handle) \
166 compat_keys.symbol = CFSTR(defaultVal); \
167 else \
168 compat_keys.symbol = *handle; \
169}while(0)
170
172
173static void loadVTEncSymbols(void){
174 compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
176 RTLD_DEFAULT,
177 "CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
178 );
179
183
187
188 GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
189 GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
190 GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
191 GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
192 GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
193 GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
194 GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
195 GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
196 GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
197 GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
198 GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
199 GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
200 GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
201 GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
202 GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
203 GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
204 GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
205 GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
206 GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
207 GET_SYM(kVTProfileLevel_H264_Extended_5_0, "H264_Extended_5_0");
208 GET_SYM(kVTProfileLevel_H264_Extended_AutoLevel, "H264_Extended_AutoLevel");
209 GET_SYM(kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel, "H264_ConstrainedBaseline_AutoLevel");
210 GET_SYM(kVTProfileLevel_H264_ConstrainedHigh_AutoLevel, "H264_ConstrainedHigh_AutoLevel");
211
212 GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
213 GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
214 GET_SYM(kVTProfileLevel_HEVC_Main42210_AutoLevel, "HEVC_Main42210_AutoLevel");
215
218 "TargetQualityForAlpha");
220 "PrioritizeEncodingSpeedOverQuality");
223
225 "EnableHardwareAcceleratedVideoEncoder");
227 "RequireHardwareAcceleratedVideoEncoder");
229 "EnableLowLatencyRateControl");
232 "MaximizePowerEfficiency");
234 "ReferenceBufferCount");
238}
239
240#define H264_PROFILE_CONSTRAINED_HIGH (AV_PROFILE_H264_HIGH | AV_PROFILE_H264_CONSTRAINED)
241
247
248static const uint8_t start_code[] = { 0, 0, 0, 1 };
249
250typedef struct ExtraSEI {
251 void *data;
252 size_t size;
253} ExtraSEI;
254
255typedef struct BufNode {
256 CMSampleBufferRef cm_buffer;
259 struct BufNode* next;
260} BufNode;
261
262typedef struct VTEncContext {
263 AVClass *class;
265 VTCompressionSessionRef session;
266 CFDictionaryRef supported_props;
267 CFStringRef ycbcr_matrix;
268 CFStringRef color_primaries;
269 CFStringRef transfer_function;
271
274
276
279
280 /* Nodes handed to VideoToolbox and not reported back yet. */
282
285
288
290 int level;
296
301
305
306 /* can't be bool type since AVOption will access it as int */
308
314
315static void vtenc_free_buf_node(BufNode *info)
316{
317 if (!info)
318 return;
319
320 av_free(info->sei.data);
321 if (info->cm_buffer)
322 CFRelease(info->cm_buffer);
324 av_free(info);
325}
326
328{
329 VTEncContext *vtctx = avctx->priv_data;
330 CFStringRef encoder_id = NULL;
331 int status;
332 CFIndex length, max_size;
333 char *name;
334
335 status = VTSessionCopyProperty(vtctx->session,
336 compat_keys.kVTCompressionPropertyKey_EncoderID,
337 kCFAllocatorDefault,
338 &encoder_id);
339 // OK if not supported
340 if (status != noErr)
341 return 0;
342
343 length = CFStringGetLength(encoder_id);
344 max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
345 name = av_malloc(max_size);
346 if (!name) {
347 CFRelease(encoder_id);
348 return AVERROR(ENOMEM);
349 }
350
351 CFStringGetCString(encoder_id,
352 name,
353 max_size,
354 kCFStringEncodingUTF8);
355 av_log(avctx, AV_LOG_DEBUG, "Init the encoder: %s\n", name);
356 av_freep(&name);
357 CFRelease(encoder_id);
358
359 return 0;
360}
361
363 CMVideoCodecType codec_type,
364 CFStringRef profile_level,
365 CFNumberRef gamma_level,
366 CFDictionaryRef enc_info,
367 CFDictionaryRef pixel_buffer_info);
368
369/**
370 * NULL-safe release of *refPtr, and sets value to NULL.
371 */
372static void vt_release_num(CFNumberRef* refPtr){
373 if (!*refPtr) {
374 return;
375 }
376
377 CFRelease(*refPtr);
378 *refPtr = NULL;
379}
380
381static void set_async_error(VTEncContext *vtctx, int err)
382{
383 BufNode *info;
384
385 pthread_mutex_lock(&vtctx->lock);
386
387 vtctx->async_error = err;
388
389 info = vtctx->q_head;
390 vtctx->q_head = vtctx->q_tail = NULL;
391
392 while (info) {
393 BufNode *next = info->next;
395 info = next;
396 }
397
398 pthread_mutex_unlock(&vtctx->lock);
399}
400
402{
403 set_async_error(vtctx, 0);
404}
405
407{
408 BufNode *info;
409
410 pthread_mutex_lock(&vtctx->lock);
411
412 while (vtctx->submitted_head) {
413 info = vtctx->submitted_head->next;
415 vtctx->submitted_head = info;
416 }
417
418 pthread_mutex_unlock(&vtctx->lock);
419}
420
421static void vtenc_reset(VTEncContext *vtctx)
422{
423 if (vtctx->session) {
424 /* The session may be retained elsewhere; invalidate before
425 * release so teardown is deterministic.
426 */
427 VTCompressionSessionInvalidate(vtctx->session);
428 CFRelease(vtctx->session);
429 vtctx->session = NULL;
430 }
431
433
434 if (vtctx->supported_props) {
435 CFRelease(vtctx->supported_props);
436 vtctx->supported_props = NULL;
437 }
438
439 /* The colorimetry fields hold references borrowed from CoreVideo (Get
440 * semantics). Releasing them would free CoreVideo's cached string for
441 * codepoints without a constant name, and later lookups of the same
442 * codepoint would hand out a dangling pointer.
443 */
444 vtctx->color_primaries = NULL;
445 vtctx->transfer_function = NULL;
446 vtctx->ycbcr_matrix = NULL;
447}
448
449static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI *sei)
450{
451 BufNode *info;
452
453 pthread_mutex_lock(&vtctx->lock);
454
455 if (vtctx->async_error) {
456 pthread_mutex_unlock(&vtctx->lock);
457 return vtctx->async_error;
458 }
459
460 if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
461 *buf = NULL;
462
463 pthread_mutex_unlock(&vtctx->lock);
464 return 0;
465 }
466
467 while (!vtctx->q_head && !vtctx->async_error && wait && !vtctx->flushing) {
468 pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
469 }
470
471 if (!vtctx->q_head) {
472 pthread_mutex_unlock(&vtctx->lock);
473 *buf = NULL;
474 return 0;
475 }
476
477 info = vtctx->q_head;
478 vtctx->q_head = vtctx->q_head->next;
479 if (!vtctx->q_head) {
480 vtctx->q_tail = NULL;
481 }
482
483 vtctx->frame_ct_out++;
484 pthread_mutex_unlock(&vtctx->lock);
485
486 *buf = info->cm_buffer;
487 info->cm_buffer = NULL;
488 if (sei && *buf) {
489 *sei = info->sei;
490 info->sei = (ExtraSEI) {0};
491 }
493
494 return 0;
495}
496
497static void vtenc_q_push(VTEncContext *vtctx, BufNode *info)
498{
499 pthread_mutex_lock(&vtctx->lock);
500
501 if (!vtctx->q_head) {
502 vtctx->q_head = info;
503 } else {
504 vtctx->q_tail->next = info;
505 }
506
507 vtctx->q_tail = info;
508
510 pthread_mutex_unlock(&vtctx->lock);
511}
512
513static void vtenc_submitted_add(VTEncContext *vtctx, BufNode *info)
514{
515 pthread_mutex_lock(&vtctx->lock);
516
517 info->next = vtctx->submitted_head;
518 vtctx->submitted_head = info;
519
520 pthread_mutex_unlock(&vtctx->lock);
521}
522
523static BufNode *vtenc_submitted_remove(VTEncContext *vtctx, void *refcon)
524{
525 BufNode **link;
526 BufNode *info;
527
528 pthread_mutex_lock(&vtctx->lock);
529
530 link = &vtctx->submitted_head;
531 while (*link && *link != refcon)
532 link = &(*link)->next;
533 info = *link;
534 if (info) {
535 *link = info->next;
536 info->next = NULL;
537 }
538
539 pthread_mutex_unlock(&vtctx->lock);
540
541 return info;
542}
543
544static int count_nalus(size_t length_code_size,
545 CMSampleBufferRef sample_buffer,
546 int *count)
547{
548 size_t offset = 0;
549 int status;
550 int nalu_ct = 0;
551 uint8_t size_buf[4];
552 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
553 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
554
555 if (length_code_size > 4)
556 return AVERROR_INVALIDDATA;
557
558 while (offset < src_size) {
559 size_t curr_src_len;
560 size_t box_len = 0;
561 size_t i;
562
563 status = CMBlockBufferCopyDataBytes(block,
564 offset,
565 length_code_size,
566 size_buf);
567
568 if (status != kCMBlockBufferNoErr) {
569 return AVERROR_EXTERNAL;
570 }
571
572 for (i = 0; i < length_code_size; i++) {
573 box_len <<= 8;
574 box_len |= size_buf[i];
575 }
576
577 curr_src_len = box_len + length_code_size;
578 offset += curr_src_len;
579
580 nalu_ct++;
581 }
582
583 *count = nalu_ct;
584 return 0;
585}
586
587static CMVideoCodecType get_cm_codec_type(AVCodecContext *avctx,
588 int profile,
589 double alpha_quality)
590{
592 switch (avctx->codec_id) {
593 case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
594 case AV_CODEC_ID_HEVC:
595 if (desc && (desc->flags & AV_PIX_FMT_FLAG_ALPHA) && alpha_quality > 0.0) {
597 }
600 if (desc && (desc->flags & AV_PIX_FMT_FLAG_ALPHA))
601 avctx->bits_per_coded_sample = 32;
602 switch (profile) {
604 return MKBETAG('a','p','c','o'); // kCMVideoCodecType_AppleProRes422Proxy
606 return MKBETAG('a','p','c','s'); // kCMVideoCodecType_AppleProRes422LT
608 return MKBETAG('a','p','c','n'); // kCMVideoCodecType_AppleProRes422
610 return MKBETAG('a','p','c','h'); // kCMVideoCodecType_AppleProRes422HQ
612 return MKBETAG('a','p','4','h'); // kCMVideoCodecType_AppleProRes4444
614 return MKBETAG('a','p','4','x'); // kCMVideoCodecType_AppleProRes4444XQ
615
616 default:
617 av_log(avctx, AV_LOG_ERROR, "Unknown profile ID: %d, using auto\n", profile);
620 if (desc &&
621 ((desc->flags & AV_PIX_FMT_FLAG_ALPHA) ||
622 desc->log2_chroma_w == 0))
623 return MKBETAG('a','p','4','h'); // kCMVideoCodecType_AppleProRes4444
624 else
625 return MKBETAG('a','p','c','n'); // kCMVideoCodecType_AppleProRes422
626 }
627 default: return 0;
628 }
629}
630
631/**
632 * Get the parameter sets from a CMSampleBufferRef.
633 * @param dst If *dst isn't NULL, the parameters are copied into existing
634 * memory. *dst_size must be set accordingly when *dst != NULL.
635 * If *dst is NULL, it will be allocated.
636 * In all cases, *dst_size is set to the number of bytes used starting
637 * at *dst.
638 */
640 AVCodecContext *avctx,
641 CMVideoFormatDescriptionRef vid_fmt,
642 size_t *size)
643{
644 VTEncContext *vtctx = avctx->priv_data;
645 size_t total_size = 0;
646 size_t ps_count;
647 int is_count_bad = 0;
648 size_t i;
649 int status;
650 status = vtctx->get_param_set_func(vid_fmt,
651 0,
652 NULL,
653 NULL,
654 &ps_count,
655 NULL);
656 if (status) {
657 is_count_bad = 1;
658 ps_count = 0;
659 status = 0;
660 }
661
662 for (i = 0; i < ps_count || is_count_bad; i++) {
663 const uint8_t *ps;
664 size_t ps_size;
665 status = vtctx->get_param_set_func(vid_fmt,
666 i,
667 &ps,
668 &ps_size,
669 NULL,
670 NULL);
671 if (status) {
672 /*
673 * When ps_count is invalid, status != 0 ends the loop normally
674 * unless we didn't get any parameter sets.
675 */
676 if (i > 0 && is_count_bad) status = 0;
677
678 break;
679 }
680
681 total_size += ps_size + sizeof(start_code);
682 }
683
684 if (status) {
685 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
686 return AVERROR_EXTERNAL;
687 }
688
689 *size = total_size;
690 return 0;
691}
692
694 AVCodecContext *avctx,
695 CMVideoFormatDescriptionRef vid_fmt,
696 uint8_t *dst,
697 size_t dst_size)
698{
699 VTEncContext *vtctx = avctx->priv_data;
700 size_t ps_count;
701 int is_count_bad = 0;
702 int status;
703 size_t offset = 0;
704 size_t i;
705
706 status = vtctx->get_param_set_func(vid_fmt,
707 0,
708 NULL,
709 NULL,
710 &ps_count,
711 NULL);
712 if (status) {
713 is_count_bad = 1;
714 ps_count = 0;
715 status = 0;
716 }
717
718
719 for (i = 0; i < ps_count || is_count_bad; i++) {
720 const uint8_t *ps;
721 size_t ps_size;
722 size_t next_offset;
723
724 status = vtctx->get_param_set_func(vid_fmt,
725 i,
726 &ps,
727 &ps_size,
728 NULL,
729 NULL);
730 if (status) {
731 if (i > 0 && is_count_bad) status = 0;
732
733 break;
734 }
735
736 next_offset = offset + sizeof(start_code) + ps_size;
737 if (dst_size < next_offset) {
738 av_log(avctx, AV_LOG_ERROR, "Buffer too small for parameter sets.\n");
740 }
741
742 memcpy(dst + offset, start_code, sizeof(start_code));
743 offset += sizeof(start_code);
744
745 memcpy(dst + offset, ps, ps_size);
746 offset = next_offset;
747 }
748
749 if (status) {
750 av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
751 return AVERROR_EXTERNAL;
752 }
753
754 return 0;
755}
756
757static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
758{
759 VTEncContext *vtctx = avctx->priv_data;
760 CMVideoFormatDescriptionRef vid_fmt;
761 size_t total_size;
762 int status;
763
764 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
765 if (!vid_fmt) {
766 av_log(avctx, AV_LOG_ERROR, "No video format.\n");
767 return AVERROR_EXTERNAL;
768 }
769
770 if (vtctx->get_param_set_func) {
771 status = get_params_size(avctx, vid_fmt, &total_size);
772 if (status) {
773 av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
774 return status;
775 }
776
778 if (!avctx->extradata) {
779 return AVERROR(ENOMEM);
780 }
781 avctx->extradata_size = total_size;
782
783 status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
784
785 if (status) {
786 av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
787 return status;
788 }
789 } else {
790 CFDataRef data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
791 if (data && CFGetTypeID(data) == CFDataGetTypeID()) {
792 CFIndex size = CFDataGetLength(data);
793
795 if (!avctx->extradata)
796 return AVERROR(ENOMEM);
797 avctx->extradata_size = size;
798
799 CFDataGetBytes(data, CFRangeMake(0, size), avctx->extradata);
800 }
801 }
802
803 return 0;
804}
805
807 void *ctx,
808 void *sourceFrameCtx,
809 OSStatus status,
810 VTEncodeInfoFlags flags,
811 CMSampleBufferRef sample_buffer)
812{
813 AVCodecContext *avctx = ctx;
814 VTEncContext *vtctx = avctx->priv_data;
815 BufNode *info;
816
817 info = vtenc_submitted_remove(vtctx, sourceFrameCtx);
818 /* The node may already be gone if the session was reset. */
819 if (!info)
820 return;
821
823 if (vtctx->async_error) {
825 return;
826 }
827
828 if (status) {
830 av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
832 return;
833 }
834
835 if (!sample_buffer) {
837 return;
838 }
839
840 CFRetain(sample_buffer);
841 info->cm_buffer = sample_buffer;
842
843 if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
844 int set_status = set_extradata(avctx, sample_buffer);
845 if (set_status) {
847 set_async_error(vtctx, set_status);
848 return;
849 }
850 }
851
852 vtenc_q_push(vtctx, info);
853}
854
856 AVCodecContext *avctx,
857 CMSampleBufferRef sample_buffer,
858 size_t *size)
859{
860 VTEncContext *vtctx = avctx->priv_data;
861 CMVideoFormatDescriptionRef vid_fmt;
862 int isize;
863 int status;
864
865 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
866 if (!vid_fmt) {
867 av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
868 return AVERROR_EXTERNAL;
869 }
870
871 status = vtctx->get_param_set_func(vid_fmt,
872 0,
873 NULL,
874 NULL,
875 NULL,
876 &isize);
877 if (status) {
878 av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
879 return AVERROR_EXTERNAL;
880 }
881
882 *size = isize;
883 return 0;
884}
885
886/*
887 * Returns true on success.
888 *
889 * If profile_level_val is NULL and this method returns true, don't specify the
890 * profile/level to the encoder.
891 */
893 CFStringRef *profile_level_val)
894{
895 VTEncContext *vtctx = avctx->priv_data;
896 int profile = vtctx->profile;
897
898 if (profile == AV_PROFILE_UNKNOWN && vtctx->level) {
899 //Need to pick a profile if level is not auto-selected.
901 }
902
903 *profile_level_val = NULL;
904
905 switch (profile) {
907 return true;
908
910 switch (vtctx->level) {
911 case 0: *profile_level_val =
912 compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
913 case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
914 case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
915 case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
916 case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
917 case 40: *profile_level_val =
918 compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
919 case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
920 case 42: *profile_level_val =
921 compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
922 case 50: *profile_level_val =
923 compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
924 case 51: *profile_level_val =
925 compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
926 case 52: *profile_level_val =
927 compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
928 }
929 break;
930
932 *profile_level_val = compat_keys.kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel;
933
934 if (vtctx->level != 0) {
935 av_log(avctx,
937 "Level is auto-selected when constrained-baseline "
938 "profile is used. The output may be encoded with a "
939 "different level.\n");
940 }
941 break;
942
944 switch (vtctx->level) {
945 case 0: *profile_level_val =
946 compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
947 case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
948 case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
949 case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
950 case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
951 case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
952 case 42: *profile_level_val =
953 compat_keys.kVTProfileLevel_H264_Main_4_2; break;
954 case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
955 case 51: *profile_level_val =
956 compat_keys.kVTProfileLevel_H264_Main_5_1; break;
957 case 52: *profile_level_val =
958 compat_keys.kVTProfileLevel_H264_Main_5_2; break;
959 }
960 break;
961
963 *profile_level_val = compat_keys.kVTProfileLevel_H264_ConstrainedHigh_AutoLevel;
964
965 if (vtctx->level != 0) {
966 av_log(avctx,
968 "Level is auto-selected when constrained-high profile "
969 "is used. The output may be encoded with a different "
970 "level.\n");
971 }
972 break;
973
975 switch (vtctx->level) {
976 case 0: *profile_level_val =
977 compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
978 case 30: *profile_level_val =
979 compat_keys.kVTProfileLevel_H264_High_3_0; break;
980 case 31: *profile_level_val =
981 compat_keys.kVTProfileLevel_H264_High_3_1; break;
982 case 32: *profile_level_val =
983 compat_keys.kVTProfileLevel_H264_High_3_2; break;
984 case 40: *profile_level_val =
985 compat_keys.kVTProfileLevel_H264_High_4_0; break;
986 case 41: *profile_level_val =
987 compat_keys.kVTProfileLevel_H264_High_4_1; break;
988 case 42: *profile_level_val =
989 compat_keys.kVTProfileLevel_H264_High_4_2; break;
990 case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
991 case 51: *profile_level_val =
992 compat_keys.kVTProfileLevel_H264_High_5_1; break;
993 case 52: *profile_level_val =
994 compat_keys.kVTProfileLevel_H264_High_5_2; break;
995 }
996 break;
998 switch (vtctx->level) {
999 case 0: *profile_level_val =
1000 compat_keys.kVTProfileLevel_H264_Extended_AutoLevel; break;
1001 case 50: *profile_level_val =
1002 compat_keys.kVTProfileLevel_H264_Extended_5_0; break;
1003 }
1004 break;
1005 }
1006
1007 if (!*profile_level_val) {
1008 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
1009 return false;
1010 }
1011
1012 return true;
1013}
1014
1015/*
1016 * Returns true on success.
1017 *
1018 * If profile_level_val is NULL and this method returns true, don't specify the
1019 * profile/level to the encoder.
1020 */
1022 CFStringRef *profile_level_val)
1023{
1024 VTEncContext *vtctx = avctx->priv_data;
1025 int profile = vtctx->profile;
1027 avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX ? avctx->sw_pix_fmt
1028 : avctx->pix_fmt);
1029 int bit_depth = desc ? desc->comp[0].depth : 0;
1030
1031 *profile_level_val = NULL;
1032
1033 switch (profile) {
1034 case AV_PROFILE_UNKNOWN:
1035 // Set profile automatically if user don't specify
1036 if (bit_depth == 10) {
1037 *profile_level_val =
1038 compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
1039 break;
1040 }
1041 return true;
1043 if (bit_depth > 0 && bit_depth != 8)
1044 av_log(avctx, AV_LOG_WARNING,
1045 "main profile with %d bit input\n", bit_depth);
1046 *profile_level_val =
1047 compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
1048 break;
1050 if (bit_depth > 0 && bit_depth != 10) {
1051 av_log(avctx, AV_LOG_ERROR,
1052 "Invalid main10 profile with %d bit input\n", bit_depth);
1053 return false;
1054 }
1055 *profile_level_val =
1056 compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
1057 break;
1059 // only main42210 is supported, omit depth and chroma subsampling
1060 *profile_level_val =
1061 compat_keys.kVTProfileLevel_HEVC_Main42210_AutoLevel;
1062 break;
1063 }
1064
1065 if (!*profile_level_val) {
1066 av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
1067 return false;
1068 }
1069
1070 return true;
1071}
1072
1074 enum AVPixelFormat fmt,
1075 enum AVColorRange range,
1076 int* av_pixel_format,
1077 int* range_guessed)
1078{
1079 const char *range_name;
1080 if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
1082
1083 //MPEG range is used when no range is set
1085 if (*av_pixel_format)
1086 return 0;
1087
1088 range_name = av_color_range_name(range);
1089 av_log(avctx, AV_LOG_ERROR,
1090 "Could not get pixel format for color format '%s' range '%s'.\n",
1092 range_name ? range_name : "Unknown");
1093
1094 return AVERROR(EINVAL);
1095}
1096
1097static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
1098 VTEncContext *vtctx = avctx->priv_data;
1099
1100 if (vtctx->color_primaries) {
1101 CFDictionarySetValue(dict,
1102 kCVImageBufferColorPrimariesKey,
1103 vtctx->color_primaries);
1104 }
1105
1106 if (vtctx->transfer_function) {
1107 CFDictionarySetValue(dict,
1108 kCVImageBufferTransferFunctionKey,
1109 vtctx->transfer_function);
1110 }
1111
1112 if (vtctx->ycbcr_matrix) {
1113 CFDictionarySetValue(dict,
1114 kCVImageBufferYCbCrMatrixKey,
1115 vtctx->ycbcr_matrix);
1116 }
1117}
1118
1120 CFMutableDictionaryRef* dict)
1121{
1122 CFNumberRef cv_color_format_num = NULL;
1123 CFNumberRef width_num = NULL;
1124 CFNumberRef height_num = NULL;
1125 CFMutableDictionaryRef pixel_buffer_info = NULL;
1126 int cv_color_format;
1127 int status = get_cv_pixel_format(avctx,
1128 avctx->pix_fmt,
1129 avctx->color_range,
1130 &cv_color_format,
1131 NULL);
1132 if (status) return status;
1133
1134 pixel_buffer_info = CFDictionaryCreateMutable(
1135 kCFAllocatorDefault,
1136 20,
1137 &kCFCopyStringDictionaryKeyCallBacks,
1138 &kCFTypeDictionaryValueCallBacks);
1139
1140 if (!pixel_buffer_info) goto pbinfo_nomem;
1141
1142 cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
1143 kCFNumberSInt32Type,
1144 &cv_color_format);
1145 if (!cv_color_format_num) goto pbinfo_nomem;
1146
1147 CFDictionarySetValue(pixel_buffer_info,
1148 kCVPixelBufferPixelFormatTypeKey,
1149 cv_color_format_num);
1150 vt_release_num(&cv_color_format_num);
1151
1152 width_num = CFNumberCreate(kCFAllocatorDefault,
1153 kCFNumberSInt32Type,
1154 &avctx->width);
1155 if (!width_num) goto pbinfo_nomem;
1156
1157 CFDictionarySetValue(pixel_buffer_info,
1158 kCVPixelBufferWidthKey,
1159 width_num);
1160 vt_release_num(&width_num);
1161
1162 height_num = CFNumberCreate(kCFAllocatorDefault,
1163 kCFNumberSInt32Type,
1164 &avctx->height);
1165 if (!height_num) goto pbinfo_nomem;
1166
1167 CFDictionarySetValue(pixel_buffer_info,
1168 kCVPixelBufferHeightKey,
1169 height_num);
1170 vt_release_num(&height_num);
1171
1172 add_color_attr(avctx, pixel_buffer_info);
1173
1174 *dict = pixel_buffer_info;
1175 return 0;
1176
1177pbinfo_nomem:
1178 vt_release_num(&cv_color_format_num);
1179 vt_release_num(&width_num);
1180 vt_release_num(&height_num);
1181 if (pixel_buffer_info) CFRelease(pixel_buffer_info);
1182
1183 return AVERROR(ENOMEM);
1184}
1185
1187 CFNumberRef *gamma_level)
1188{
1189 enum AVColorTransferCharacteristic trc = avctx->color_trc;
1190 Float32 gamma = 0;
1191 *gamma_level = NULL;
1192
1193 if (trc == AVCOL_TRC_GAMMA22)
1194 gamma = 2.2;
1195 else if (trc == AVCOL_TRC_GAMMA28)
1196 gamma = 2.8;
1197
1198 if (gamma != 0)
1199 *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);
1200 return 0;
1201}
1202
1203// constant quality only on Macs with Apple Silicon
1204static bool vtenc_qscale_enabled(void)
1205{
1206 return !TARGET_OS_IPHONE && TARGET_CPU_ARM64;
1207}
1208
1210 CFStringRef key,
1211 const char *print_option_name,
1212 CFTypeRef value) {
1213 int status;
1214 VTEncContext *vtctx = avctx->priv_data;
1215
1216 status = VTSessionSetProperty(vtctx->session, key, value);
1217 if (status == kVTPropertyNotSupportedErr) {
1218 av_log(avctx,
1220 "This device does not support the %s option. Value ignored.\n",
1221 print_option_name);
1222 } else if (status != 0) {
1223 av_log(avctx,
1225 "Error setting %s: Error %d\n",
1226 print_option_name,
1227 status);
1228 }
1229}
1230
1232 CFStringRef key,
1233 const char* print_option_name,
1234 int value) {
1235 CFNumberRef value_cfnum = CFNumberCreate(kCFAllocatorDefault,
1236 kCFNumberIntType,
1237 &value);
1238
1239 if (value_cfnum == NULL) {
1240 return AVERROR(ENOMEM);
1241 }
1242
1243 set_encoder_property_or_log(avctx, key, print_option_name, value_cfnum);
1244
1245 CFRelease(value_cfnum);
1246
1247 return 0;
1248}
1249
1251 CMVideoCodecType codec_type,
1252 CFStringRef profile_level,
1253 CFNumberRef gamma_level,
1254 CFDictionaryRef enc_info,
1255 CFDictionaryRef pixel_buffer_info,
1256 bool constant_bit_rate,
1257 VTCompressionSessionRef *session)
1258{
1259 VTEncContext *vtctx = avctx->priv_data;
1260 SInt32 bit_rate = avctx->bit_rate;
1261 SInt32 max_rate = avctx->rc_max_rate;
1262 CFNumberRef bit_rate_num;
1263 CFNumberRef bytes_per_second;
1264 CFNumberRef one_second;
1265 CFArrayRef data_rate_limits;
1266 int64_t bytes_per_second_value = 0;
1267 int64_t one_second_value = 0;
1268 void *nums[2];
1269
1270 int status = VTCompressionSessionCreate(kCFAllocatorDefault,
1271 avctx->width,
1272 avctx->height,
1273 codec_type,
1274 enc_info,
1275 pixel_buffer_info,
1276 kCFAllocatorDefault,
1278 avctx,
1279 session);
1280
1281 if (status || !vtctx->session) {
1282 av_log(avctx, AV_LOG_ERROR, "Cannot create compression session: %d\n", status);
1283
1284#if !TARGET_OS_IPHONE
1285 if (!vtctx->allow_sw) {
1286 av_log(avctx, AV_LOG_ERROR, "Try -allow_sw 1. The hardware encoder may be busy, or not supported.\n");
1287 }
1288#endif
1289
1290 return AVERROR_EXTERNAL;
1291 }
1292
1293#if defined (MAC_OS_X_VERSION_10_13) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_13)
1294 if (__builtin_available(macOS 10.13, iOS 11.0, *)) {
1295 if (vtctx->supported_props) {
1296 CFRelease(vtctx->supported_props);
1297 vtctx->supported_props = NULL;
1298 }
1299 status = VTCopySupportedPropertyDictionaryForEncoder(avctx->width,
1300 avctx->height,
1301 codec_type,
1302 enc_info,
1303 NULL,
1304 &vtctx->supported_props);
1305
1306 if (status != noErr) {
1307 av_log(avctx, AV_LOG_ERROR,"Error retrieving the supported property dictionary err=%"PRId64"\n", (int64_t)status);
1308 return AVERROR_EXTERNAL;
1309 }
1310 }
1311#endif
1312
1313 status = vt_dump_encoder(avctx);
1314 if (status < 0)
1315 return status;
1316
1317 if (avctx->flags & AV_CODEC_FLAG_QSCALE && !vtenc_qscale_enabled()) {
1318 av_log(avctx, AV_LOG_ERROR, "-q:v qscale not available for encoder. Use -b:v bitrate instead.\n");
1319 return AVERROR_EXTERNAL;
1320 }
1321
1322 if (avctx->flags & AV_CODEC_FLAG_QSCALE || avctx->global_quality > 0) {
1323 float factor = (avctx->flags & AV_CODEC_FLAG_QSCALE) ?
1324 FF_QP2LAMBDA * 100.0f : 100.0f;
1325 Float32 quality = fminf(avctx->global_quality / factor, 1.0f);
1326 CFNumberRef quality_num = CFNumberCreate(kCFAllocatorDefault,
1327 kCFNumberFloat32Type,
1328 &quality);
1329 if (!quality_num) return AVERROR(ENOMEM);
1330
1331 status = VTSessionSetProperty(vtctx->session,
1332 kVTCompressionPropertyKey_Quality,
1333 quality_num);
1334 CFRelease(quality_num);
1335 } else if (avctx->codec_id != AV_CODEC_ID_PRORES) {
1336 bit_rate_num = CFNumberCreate(kCFAllocatorDefault,
1337 kCFNumberSInt32Type,
1338 &bit_rate);
1339 if (!bit_rate_num) return AVERROR(ENOMEM);
1340
1341 if (constant_bit_rate) {
1342 status = VTSessionSetProperty(vtctx->session,
1343 compat_keys.kVTCompressionPropertyKey_ConstantBitRate,
1344 bit_rate_num);
1345 if (status == kVTPropertyNotSupportedErr) {
1346 av_log(avctx, AV_LOG_ERROR, "-constant_bit_rate true is not supported by the encoder.\n");
1347 CFRelease(bit_rate_num);
1348 return AVERROR_EXTERNAL;
1349 }
1350 } else {
1351 status = VTSessionSetProperty(vtctx->session,
1352 kVTCompressionPropertyKey_AverageBitRate,
1353 bit_rate_num);
1354 }
1355
1356 CFRelease(bit_rate_num);
1357 }
1358
1359 if (status) {
1360 av_log(avctx, AV_LOG_ERROR, "Error setting bitrate property: %d\n", status);
1361 return AVERROR_EXTERNAL;
1362 }
1363
1364 if (vtctx->prio_speed >= 0) {
1365 status = VTSessionSetProperty(vtctx->session,
1366 compat_keys.kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
1367 vtctx->prio_speed ? kCFBooleanTrue : kCFBooleanFalse);
1368 if (status) {
1369 av_log(avctx, AV_LOG_WARNING, "PrioritizeEncodingSpeedOverQuality property is not supported on this device. Ignoring.\n");
1370 }
1371 }
1372
1373 if ((vtctx->codec_id == AV_CODEC_ID_H264 || vtctx->codec_id == AV_CODEC_ID_HEVC)
1374 && max_rate > 0) {
1375 bytes_per_second_value = max_rate >> 3;
1376 bytes_per_second = CFNumberCreate(kCFAllocatorDefault,
1377 kCFNumberSInt64Type,
1378 &bytes_per_second_value);
1379 if (!bytes_per_second) {
1380 return AVERROR(ENOMEM);
1381 }
1382 one_second_value = 1;
1383 one_second = CFNumberCreate(kCFAllocatorDefault,
1384 kCFNumberSInt64Type,
1385 &one_second_value);
1386 if (!one_second) {
1387 CFRelease(bytes_per_second);
1388 return AVERROR(ENOMEM);
1389 }
1390 nums[0] = (void *)bytes_per_second;
1391 nums[1] = (void *)one_second;
1392 data_rate_limits = CFArrayCreate(kCFAllocatorDefault,
1393 (const void **)nums,
1394 2,
1395 &kCFTypeArrayCallBacks);
1396
1397 if (!data_rate_limits) {
1398 CFRelease(bytes_per_second);
1399 CFRelease(one_second);
1400 return AVERROR(ENOMEM);
1401 }
1402 status = VTSessionSetProperty(vtctx->session,
1403 kVTCompressionPropertyKey_DataRateLimits,
1404 data_rate_limits);
1405
1406 CFRelease(bytes_per_second);
1407 CFRelease(one_second);
1408 CFRelease(data_rate_limits);
1409
1410 if (status) {
1411 av_log(avctx, AV_LOG_ERROR, "Error setting max bitrate property: %d\n", status);
1412 // kVTCompressionPropertyKey_DataRateLimits is available for HEVC
1413 // now but not on old release. There is no document about since
1414 // when. So ignore the error if it failed for hevc.
1415 if (vtctx->codec_id != AV_CODEC_ID_HEVC)
1416 return AVERROR_EXTERNAL;
1417 }
1418 }
1419
1420 if (vtctx->codec_id == AV_CODEC_ID_HEVC && vtctx->alpha_quality > 0.0) {
1421 const AVPixFmtDescriptor *descriptor = av_pix_fmt_desc_get(avctx->pix_fmt);
1422
1423 if (descriptor->flags & AV_PIX_FMT_FLAG_ALPHA) {
1424 CFNumberRef alpha_quality_num = CFNumberCreate(kCFAllocatorDefault,
1425 kCFNumberDoubleType,
1426 &vtctx->alpha_quality);
1427 if (!alpha_quality_num) return AVERROR(ENOMEM);
1428
1429 status = VTSessionSetProperty(vtctx->session,
1430 compat_keys.kVTCompressionPropertyKey_TargetQualityForAlpha,
1431 alpha_quality_num);
1432 CFRelease(alpha_quality_num);
1433
1434 if (status) {
1435 av_log(avctx,
1437 "Error setting alpha quality: %d\n",
1438 status);
1439 }
1440 }
1441 }
1442
1443 if (profile_level) {
1444 status = VTSessionSetProperty(vtctx->session,
1445 kVTCompressionPropertyKey_ProfileLevel,
1446 profile_level);
1447 if (status) {
1448 av_log(avctx, AV_LOG_ERROR, "Error setting profile/level property: %d. Output will be encoded using a supported profile/level combination.\n", status);
1449 }
1450 }
1451
1452 if (avctx->gop_size > 0 && avctx->codec_id != AV_CODEC_ID_PRORES) {
1453 CFNumberRef interval = CFNumberCreate(kCFAllocatorDefault,
1454 kCFNumberIntType,
1455 &avctx->gop_size);
1456 if (!interval) {
1457 return AVERROR(ENOMEM);
1458 }
1459
1460 status = VTSessionSetProperty(vtctx->session,
1461 kVTCompressionPropertyKey_MaxKeyFrameInterval,
1462 interval);
1463 CFRelease(interval);
1464
1465 if (status) {
1466 av_log(avctx, AV_LOG_ERROR, "Error setting 'max key-frame interval' property: %d\n", status);
1467 return AVERROR_EXTERNAL;
1468 }
1469 }
1470
1471 if (vtctx->frames_before) {
1472 status = VTSessionSetProperty(vtctx->session,
1473 kVTCompressionPropertyKey_MoreFramesBeforeStart,
1474 kCFBooleanTrue);
1475
1476 if (status == kVTPropertyNotSupportedErr) {
1477 av_log(avctx, AV_LOG_WARNING, "frames_before property is not supported on this device. Ignoring.\n");
1478 } else if (status) {
1479 av_log(avctx, AV_LOG_ERROR, "Error setting frames_before property: %d\n", status);
1480 }
1481 }
1482
1483 if (vtctx->frames_after) {
1484 status = VTSessionSetProperty(vtctx->session,
1485 kVTCompressionPropertyKey_MoreFramesAfterEnd,
1486 kCFBooleanTrue);
1487
1488 if (status == kVTPropertyNotSupportedErr) {
1489 av_log(avctx, AV_LOG_WARNING, "frames_after property is not supported on this device. Ignoring.\n");
1490 } else if (status) {
1491 av_log(avctx, AV_LOG_ERROR, "Error setting frames_after property: %d\n", status);
1492 }
1493 }
1494
1495 if (avctx->sample_aspect_ratio.num != 0) {
1496 CFNumberRef num;
1497 CFNumberRef den;
1498 CFMutableDictionaryRef par;
1499 AVRational *avpar = &avctx->sample_aspect_ratio;
1500
1501 av_reduce(&avpar->num, &avpar->den,
1502 avpar->num, avpar->den,
1503 0xFFFFFFFF);
1504
1505 num = CFNumberCreate(kCFAllocatorDefault,
1506 kCFNumberIntType,
1507 &avpar->num);
1508
1509 den = CFNumberCreate(kCFAllocatorDefault,
1510 kCFNumberIntType,
1511 &avpar->den);
1512
1513
1514
1515 par = CFDictionaryCreateMutable(kCFAllocatorDefault,
1516 2,
1517 &kCFCopyStringDictionaryKeyCallBacks,
1518 &kCFTypeDictionaryValueCallBacks);
1519
1520 if (!par || !num || !den) {
1521 if (par) CFRelease(par);
1522 if (num) CFRelease(num);
1523 if (den) CFRelease(den);
1524
1525 return AVERROR(ENOMEM);
1526 }
1527
1528 CFDictionarySetValue(
1529 par,
1530 kCMFormatDescriptionKey_PixelAspectRatioHorizontalSpacing,
1531 num);
1532
1533 CFDictionarySetValue(
1534 par,
1535 kCMFormatDescriptionKey_PixelAspectRatioVerticalSpacing,
1536 den);
1537
1538 status = VTSessionSetProperty(vtctx->session,
1539 kVTCompressionPropertyKey_PixelAspectRatio,
1540 par);
1541
1542 CFRelease(par);
1543 CFRelease(num);
1544 CFRelease(den);
1545
1546 if (status) {
1547 av_log(avctx,
1549 "Error setting pixel aspect ratio to %d:%d: %d.\n",
1550 avctx->sample_aspect_ratio.num,
1551 avctx->sample_aspect_ratio.den,
1552 status);
1553
1554 return AVERROR_EXTERNAL;
1555 }
1556 }
1557
1558
1559 if (vtctx->transfer_function) {
1560 status = VTSessionSetProperty(vtctx->session,
1561 kVTCompressionPropertyKey_TransferFunction,
1562 vtctx->transfer_function);
1563
1564 if (status) {
1565 av_log(avctx, AV_LOG_WARNING, "Could not set transfer function: %d\n", status);
1566 }
1567 }
1568
1569
1570 if (vtctx->ycbcr_matrix) {
1571 status = VTSessionSetProperty(vtctx->session,
1572 kVTCompressionPropertyKey_YCbCrMatrix,
1573 vtctx->ycbcr_matrix);
1574
1575 if (status) {
1576 av_log(avctx, AV_LOG_WARNING, "Could not set ycbcr matrix: %d\n", status);
1577 }
1578 }
1579
1580
1581 if (vtctx->color_primaries) {
1582 status = VTSessionSetProperty(vtctx->session,
1583 kVTCompressionPropertyKey_ColorPrimaries,
1584 vtctx->color_primaries);
1585
1586 if (status) {
1587 av_log(avctx, AV_LOG_WARNING, "Could not set color primaries: %d\n", status);
1588 }
1589 }
1590
1591 if (gamma_level) {
1592 status = VTSessionSetProperty(vtctx->session,
1593 kCVImageBufferGammaLevelKey,
1594 gamma_level);
1595
1596 if (status) {
1597 av_log(avctx, AV_LOG_WARNING, "Could not set gamma level: %d\n", status);
1598 }
1599 }
1600
1601 if (!vtctx->has_b_frames && avctx->codec_id != AV_CODEC_ID_PRORES) {
1602 status = VTSessionSetProperty(vtctx->session,
1603 kVTCompressionPropertyKey_AllowFrameReordering,
1604 kCFBooleanFalse);
1605
1606 if (status) {
1607 av_log(avctx, AV_LOG_ERROR, "Error setting 'allow frame reordering' property: %d\n", status);
1608 return AVERROR_EXTERNAL;
1609 }
1610 }
1611
1612 if (vtctx->entropy != VT_ENTROPY_NOT_SET) {
1613 CFStringRef entropy = vtctx->entropy == VT_CABAC ?
1614 compat_keys.kVTH264EntropyMode_CABAC:
1615 compat_keys.kVTH264EntropyMode_CAVLC;
1616
1617 status = VTSessionSetProperty(vtctx->session,
1618 compat_keys.kVTCompressionPropertyKey_H264EntropyMode,
1619 entropy);
1620
1621 if (status) {
1622 av_log(avctx, AV_LOG_ERROR, "Error setting entropy property: %d\n", status);
1623 }
1624 }
1625
1626 if (vtctx->realtime >= 0) {
1627 status = VTSessionSetProperty(vtctx->session,
1628 compat_keys.kVTCompressionPropertyKey_RealTime,
1629 vtctx->realtime ? kCFBooleanTrue : kCFBooleanFalse);
1630
1631 if (status) {
1632 av_log(avctx, AV_LOG_ERROR, "Error setting realtime property: %d\n", status);
1633 }
1634 }
1635
1636 if ((avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) != 0) {
1638 compat_keys.kVTCompressionPropertyKey_AllowOpenGOP,
1639 "AllowOpenGop",
1640 kCFBooleanFalse);
1641 }
1642
1643 if (avctx->qmin >= 0) {
1644 status = set_encoder_int_property_or_log(avctx,
1645 compat_keys.kVTCompressionPropertyKey_MinAllowedFrameQP,
1646 "qmin",
1647 avctx->qmin);
1648
1649 if (status != 0) {
1650 return status;
1651 }
1652 }
1653
1654 if (avctx->qmax >= 0) {
1655 status = set_encoder_int_property_or_log(avctx,
1656 compat_keys.kVTCompressionPropertyKey_MaxAllowedFrameQP,
1657 "qmax",
1658 avctx->qmax);
1659
1660 if (status != 0) {
1661 return status;
1662 }
1663 }
1664
1665 if (vtctx->max_slice_bytes >= 0 && avctx->codec_id == AV_CODEC_ID_H264) {
1666 status = set_encoder_int_property_or_log(avctx,
1667 kVTCompressionPropertyKey_MaxH264SliceBytes,
1668 "max_slice_bytes",
1669 vtctx->max_slice_bytes);
1670
1671 if (status != 0) {
1672 return status;
1673 }
1674 }
1675
1676 if (vtctx->power_efficient >= 0) {
1678 compat_keys.kVTCompressionPropertyKey_MaximizePowerEfficiency,
1679 "power_efficient",
1680 vtctx->power_efficient ? kCFBooleanTrue : kCFBooleanFalse);
1681 }
1682
1683 if (vtctx->max_ref_frames > 0) {
1684 status = set_encoder_int_property_or_log(avctx,
1685 compat_keys.kVTCompressionPropertyKey_ReferenceBufferCount,
1686 "max_ref_frames",
1687 vtctx->max_ref_frames);
1688
1689 if (status != 0) {
1690 return status;
1691 }
1692 }
1693
1694 if (vtctx->spatialaq >= 0) {
1696 compat_keys.kVTCompressionPropertyKey_SpatialAdaptiveQPLevel,
1697 "spatialaq",
1699 }
1700
1701 status = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
1702 if (status) {
1703 av_log(avctx, AV_LOG_ERROR, "Cannot prepare encoder: %d\n", status);
1704 return AVERROR_EXTERNAL;
1705 }
1706
1707 return 0;
1708}
1709
1711{
1712 CFMutableDictionaryRef enc_info;
1713 CFMutableDictionaryRef pixel_buffer_info = NULL;
1714 CMVideoCodecType codec_type;
1715 VTEncContext *vtctx = avctx->priv_data;
1716 CFStringRef profile_level = NULL;
1717 CFNumberRef gamma_level = NULL;
1718 int status;
1719
1720 codec_type = get_cm_codec_type(avctx, vtctx->profile, vtctx->alpha_quality);
1721 if (!codec_type) {
1722 av_log(avctx, AV_LOG_ERROR, "No mapping for AVCodecID %d\n", avctx->codec_id);
1723 return AVERROR(EINVAL);
1724 }
1725
1726#if defined(MAC_OS_X_VERSION_10_9) && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9)
1727 if (avctx->codec_id == AV_CODEC_ID_PRORES) {
1728 if (__builtin_available(macOS 10.10, *)) {
1729 VTRegisterProfessionalVideoWorkflowVideoEncoders();
1730 }
1731 }
1732#endif
1733
1734 vtctx->codec_id = avctx->codec_id;
1735
1736 if (vtctx->codec_id == AV_CODEC_ID_H264) {
1737 vtctx->get_param_set_func = CMVideoFormatDescriptionGetH264ParameterSetAtIndex;
1738
1739 vtctx->has_b_frames = avctx->max_b_frames > 0 ? REORDER_DELAY : 0;
1740 if(vtctx->has_b_frames && (0xFF & vtctx->profile) == AV_PROFILE_H264_BASELINE){
1741 av_log(avctx, AV_LOG_WARNING, "Cannot use B-frames with baseline profile. Output will not contain B-frames.\n");
1742 vtctx->has_b_frames = 0;
1743 }
1744
1745 if (vtctx->entropy == VT_CABAC && (0xFF & vtctx->profile) == AV_PROFILE_H264_BASELINE) {
1746 av_log(avctx, AV_LOG_WARNING, "CABAC entropy requires 'main' or 'high' profile, but baseline was requested. Encode will not use CABAC entropy.\n");
1747 vtctx->entropy = VT_ENTROPY_NOT_SET;
1748 }
1749
1750 if (!get_vt_h264_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1751 } else if (vtctx->codec_id == AV_CODEC_ID_HEVC) {
1752 vtctx->get_param_set_func = compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
1753 if (!vtctx->get_param_set_func) return AVERROR(EINVAL);
1754 if (!get_vt_hevc_profile_level(avctx, &profile_level)) return AVERROR(EINVAL);
1755 vtctx->has_b_frames = avctx->max_b_frames > 0 ? REORDER_DELAY : 0;
1756 } else if (vtctx->codec_id == AV_CODEC_ID_PRORES) {
1758 }
1759
1760 enc_info = CFDictionaryCreateMutable(
1761 kCFAllocatorDefault,
1762 20,
1763 &kCFCopyStringDictionaryKeyCallBacks,
1764 &kCFTypeDictionaryValueCallBacks
1765 );
1766
1767 if (!enc_info) return AVERROR(ENOMEM);
1768
1769#if !TARGET_OS_IPHONE
1770 if(vtctx->require_sw) {
1771 CFDictionarySetValue(enc_info,
1772 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1773 kCFBooleanFalse);
1774 } else if (!vtctx->allow_sw) {
1775 CFDictionarySetValue(enc_info,
1776 compat_keys.kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
1777 kCFBooleanTrue);
1778 } else {
1779 CFDictionarySetValue(enc_info,
1780 compat_keys.kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
1781 kCFBooleanTrue);
1782 }
1783#endif
1784
1785 // low-latency mode: eliminate frame reordering, follow a one-in-one-out encoding mode
1786 if ((avctx->flags & AV_CODEC_FLAG_LOW_DELAY) &&
1787 ((avctx->codec_id == AV_CODEC_ID_H264) || (TARGET_CPU_ARM64 && avctx->codec_id == AV_CODEC_ID_HEVC))) {
1788 if (!avctx->bit_rate) {
1789 av_log(avctx, AV_LOG_ERROR, "Doesn't support automatic bitrate in low_delay mode, "
1790 "please specify bitrate explicitly\n");
1791 status = AVERROR(EINVAL);
1792 goto init_cleanup;
1793 }
1794 CFDictionarySetValue(enc_info,
1795 compat_keys.kVTVideoEncoderSpecification_EnableLowLatencyRateControl,
1796 kCFBooleanTrue);
1797 }
1798
1799 if (avctx->pix_fmt != AV_PIX_FMT_VIDEOTOOLBOX) {
1800 status = create_cv_pixel_buffer_info(avctx, &pixel_buffer_info);
1801 if (status)
1802 goto init_cleanup;
1803 }
1804
1805 vtctx->dts_delta = vtctx->has_b_frames ? -1 : 0;
1806
1807 get_cv_gamma(avctx, &gamma_level);
1811
1812
1813 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1814 status = vtenc_populate_extradata(avctx,
1815 codec_type,
1816 profile_level,
1817 gamma_level,
1818 enc_info,
1819 pixel_buffer_info);
1820 if (status)
1821 goto init_cleanup;
1822 }
1823
1824 status = vtenc_create_encoder(avctx,
1825 codec_type,
1826 profile_level,
1827 gamma_level,
1828 enc_info,
1829 pixel_buffer_info,
1830 vtctx->constant_bit_rate,
1831 &vtctx->session);
1832
1833init_cleanup:
1834 if (gamma_level)
1835 CFRelease(gamma_level);
1836
1837 if (pixel_buffer_info)
1838 CFRelease(pixel_buffer_info);
1839
1840 CFRelease(enc_info);
1841
1842 return status;
1843}
1844
1846{
1847 VTEncContext *vtctx = avctx->priv_data;
1848 CFBooleanRef has_b_frames_cfbool;
1849 int status;
1850
1852
1853 pthread_mutex_init(&vtctx->lock, NULL);
1855
1856 // It can happen when user set avctx->profile directly.
1857 if (vtctx->profile == AV_PROFILE_UNKNOWN)
1858 vtctx->profile = avctx->profile;
1859 status = vtenc_configure_encoder(avctx);
1860 if (status) return status;
1861
1862 status = VTSessionCopyProperty(vtctx->session,
1863 kVTCompressionPropertyKey_AllowFrameReordering,
1864 kCFAllocatorDefault,
1865 &has_b_frames_cfbool);
1866
1867 if (!status && has_b_frames_cfbool) {
1868 //Some devices don't output B-frames for main profile, even if requested.
1869 if (CFBooleanGetValue(has_b_frames_cfbool))
1870 vtctx->has_b_frames = REORDER_DELAY;
1871 else
1872 vtctx->has_b_frames = 0;
1873 CFRelease(has_b_frames_cfbool);
1874 }
1875 avctx->has_b_frames = vtctx->has_b_frames;
1876
1877 return 0;
1878}
1879
1880static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
1881{
1882 CFArrayRef attachments;
1883 CFDictionaryRef attachment;
1884 CFBooleanRef not_sync;
1885 CFIndex len;
1886
1887 attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false);
1888 len = !attachments ? 0 : CFArrayGetCount(attachments);
1889
1890 if (!len) {
1891 *is_key_frame = true;
1892 return;
1893 }
1894
1895 attachment = CFArrayGetValueAtIndex(attachments, 0);
1896
1897 if (CFDictionaryGetValueIfPresent(attachment,
1898 kCMSampleAttachmentKey_NotSync,
1899 (const void **)&not_sync))
1900 {
1901 *is_key_frame = !CFBooleanGetValue(not_sync);
1902 } else {
1903 *is_key_frame = true;
1904 }
1905}
1906
1907static int is_post_sei_nal_type(int nal_type){
1908 return nal_type != H264_NAL_SEI &&
1909 nal_type != H264_NAL_SPS &&
1910 nal_type != H264_NAL_PPS &&
1911 nal_type != H264_NAL_AUD;
1912}
1913
1914/*
1915 * Finds the sei message start/size of type find_sei_type.
1916 * If more than one of that type exists, the last one is returned.
1917 */
1919 uint8_t *nal_data,
1920 size_t nal_size,
1921 uint8_t **sei_end)
1922{
1923 int nal_type;
1924 size_t sei_payload_size = 0;
1925 uint8_t *nal_start = nal_data;
1926 *sei_end = NULL;
1927
1928 if (!nal_size)
1929 return 0;
1930
1931 nal_type = *nal_data & 0x1F;
1932 if (nal_type != H264_NAL_SEI)
1933 return 0;
1934
1935 nal_data++;
1936 nal_size--;
1937
1938 if (nal_data[nal_size - 1] == 0x80)
1939 nal_size--;
1940
1941 while (nal_size > 0 && *nal_data > 0) {
1942 do{
1943 nal_data++;
1944 nal_size--;
1945 } while (nal_size > 0 && *nal_data == 0xFF);
1946
1947 if (!nal_size) {
1948 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing type.\n");
1949 return AVERROR_INVALIDDATA;
1950 }
1951
1952 do{
1953 sei_payload_size += *nal_data;
1954 nal_data++;
1955 nal_size--;
1956 } while (nal_size > 0 && *nal_data == 0xFF);
1957
1958 if (nal_size < sei_payload_size) {
1959 av_log(avctx, AV_LOG_ERROR, "Unexpected end of SEI NAL Unit parsing size.\n");
1960 return AVERROR_INVALIDDATA;
1961 }
1962
1963 nal_data += sei_payload_size;
1964 nal_size -= sei_payload_size;
1965 }
1966
1967 *sei_end = nal_data;
1968
1969 return nal_data - nal_start + 1;
1970}
1971
1972/**
1973 * Copies the data inserting emulation prevention bytes as needed.
1974 * Existing data in the destination can be taken into account by providing
1975 * dst with a dst_offset > 0.
1976 *
1977 * @return The number of bytes copied on success. On failure, the negative of
1978 * the number of bytes needed to copy src is returned.
1979 */
1980static int copy_emulation_prev(const uint8_t *src,
1981 size_t src_size,
1982 uint8_t *dst,
1983 ssize_t dst_offset,
1984 size_t dst_size)
1985{
1986 int zeros = 0;
1987 int wrote_bytes;
1988 uint8_t* dst_start;
1989 uint8_t* dst_end = dst + dst_size;
1990 const uint8_t* src_end = src + src_size;
1991 int start_at = dst_offset > 2 ? dst_offset - 2 : 0;
1992 int i;
1993 for (i = start_at; i < dst_offset && i < dst_size; i++) {
1994 if (!dst[i])
1995 zeros++;
1996 else
1997 zeros = 0;
1998 }
1999
2000 dst += dst_offset;
2001 dst_start = dst;
2002 for (; src < src_end; src++, dst++) {
2003 if (zeros == 2) {
2004 int insert_ep3_byte = *src <= 3;
2005 if (insert_ep3_byte) {
2006 if (dst < dst_end)
2007 *dst = 3;
2008 dst++;
2009 }
2010
2011 zeros = 0;
2012 }
2013
2014 if (dst < dst_end)
2015 *dst = *src;
2016
2017 if (!*src)
2018 zeros++;
2019 else
2020 zeros = 0;
2021 }
2022
2023 wrote_bytes = dst - dst_start;
2024
2025 if (dst > dst_end)
2026 return -wrote_bytes;
2027
2028 return wrote_bytes;
2029}
2030
2031static int write_sei(const ExtraSEI *sei,
2032 int sei_type,
2033 uint8_t *dst,
2034 size_t dst_size)
2035{
2036 uint8_t *sei_start = dst;
2037 size_t remaining_sei_size = sei->size;
2038 size_t remaining_dst_size = dst_size;
2039 int header_bytes;
2040 int bytes_written;
2041 ssize_t offset;
2042
2043 if (!remaining_dst_size)
2045
2046 while (sei_type && remaining_dst_size != 0) {
2047 int sei_byte = sei_type > 255 ? 255 : sei_type;
2048 *dst = sei_byte;
2049
2050 sei_type -= sei_byte;
2051 dst++;
2052 remaining_dst_size--;
2053 }
2054
2055 if (!dst_size)
2057
2058 while (remaining_sei_size && remaining_dst_size != 0) {
2059 int size_byte = remaining_sei_size > 255 ? 255 : remaining_sei_size;
2060 *dst = size_byte;
2061
2062 remaining_sei_size -= size_byte;
2063 dst++;
2064 remaining_dst_size--;
2065 }
2066
2067 if (remaining_dst_size < sei->size)
2069
2070 header_bytes = dst - sei_start;
2071
2072 offset = header_bytes;
2073 bytes_written = copy_emulation_prev(sei->data,
2074 sei->size,
2075 sei_start,
2076 offset,
2077 dst_size);
2078 if (bytes_written < 0)
2080
2081 bytes_written += header_bytes;
2082 return bytes_written;
2083}
2084
2085/**
2086 * Copies NAL units and replaces length codes with
2087 * H.264 Annex B start codes. On failure, the contents of
2088 * dst_data may have been modified.
2089 *
2090 * @param length_code_size Byte length of each length code
2091 * @param sample_buffer NAL units prefixed with length codes.
2092 * @param sei Optional A53 closed captions SEI data.
2093 * @param dst_data Must be zeroed before calling this function.
2094 * Contains the copied NAL units prefixed with
2095 * start codes when the function returns
2096 * successfully.
2097 * @param dst_size Length of dst_data
2098 * @return 0 on success
2099 * AVERROR_INVALIDDATA if length_code_size is invalid
2100 * AVERROR_BUFFER_TOO_SMALL if dst_data is too small
2101 * or if a length_code in src_data specifies data beyond
2102 * the end of its buffer.
2103 */
2105 AVCodecContext *avctx,
2106 size_t length_code_size,
2107 CMSampleBufferRef sample_buffer,
2108 ExtraSEI *sei,
2109 uint8_t *dst_data,
2110 size_t dst_size)
2111{
2112 size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2113 size_t remaining_src_size = src_size;
2114 size_t remaining_dst_size = dst_size;
2115 size_t src_offset = 0;
2116 int wrote_sei = 0;
2117 int status;
2118 uint8_t size_buf[4];
2119 uint8_t nal_type;
2120 CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
2121
2122 if (length_code_size > 4) {
2123 return AVERROR_INVALIDDATA;
2124 }
2125
2126 while (remaining_src_size > 0) {
2127 size_t curr_src_len;
2128 size_t curr_dst_len;
2129 size_t box_len = 0;
2130 size_t i;
2131
2132 uint8_t *dst_box;
2133
2134 status = CMBlockBufferCopyDataBytes(block,
2135 src_offset,
2136 length_code_size,
2137 size_buf);
2138 if (status) {
2139 av_log(avctx, AV_LOG_ERROR, "Cannot copy length: %d\n", status);
2140 return AVERROR_EXTERNAL;
2141 }
2142
2143 status = CMBlockBufferCopyDataBytes(block,
2144 src_offset + length_code_size,
2145 1,
2146 &nal_type);
2147
2148 if (status) {
2149 av_log(avctx, AV_LOG_ERROR, "Cannot copy type: %d\n", status);
2150 return AVERROR_EXTERNAL;
2151 }
2152
2153 nal_type &= 0x1F;
2154
2155 for (i = 0; i < length_code_size; i++) {
2156 box_len <<= 8;
2157 box_len |= size_buf[i];
2158 }
2159
2160 if (sei && !wrote_sei && is_post_sei_nal_type(nal_type)) {
2161 //No SEI NAL unit - insert.
2162 int wrote_bytes;
2163
2164 memcpy(dst_data, start_code, sizeof(start_code));
2165 dst_data += sizeof(start_code);
2166 remaining_dst_size -= sizeof(start_code);
2167
2168 *dst_data = H264_NAL_SEI;
2169 dst_data++;
2170 remaining_dst_size--;
2171
2172 wrote_bytes = write_sei(sei,
2174 dst_data,
2175 remaining_dst_size);
2176
2177 if (wrote_bytes < 0)
2178 return wrote_bytes;
2179
2180 remaining_dst_size -= wrote_bytes;
2181 dst_data += wrote_bytes;
2182
2183 if (remaining_dst_size <= 0)
2185
2186 *dst_data = 0x80;
2187
2188 dst_data++;
2189 remaining_dst_size--;
2190
2191 wrote_sei = 1;
2192 }
2193
2194 curr_src_len = box_len + length_code_size;
2195 curr_dst_len = box_len + sizeof(start_code);
2196
2197 if (remaining_src_size < curr_src_len) {
2199 }
2200
2201 if (remaining_dst_size < curr_dst_len) {
2203 }
2204
2205 dst_box = dst_data + sizeof(start_code);
2206
2207 memcpy(dst_data, start_code, sizeof(start_code));
2208 status = CMBlockBufferCopyDataBytes(block,
2209 src_offset + length_code_size,
2210 box_len,
2211 dst_box);
2212
2213 if (status) {
2214 av_log(avctx, AV_LOG_ERROR, "Cannot copy data: %d\n", status);
2215 return AVERROR_EXTERNAL;
2216 }
2217
2218 if (sei && !wrote_sei && nal_type == H264_NAL_SEI) {
2219 //Found SEI NAL unit - append.
2220 int wrote_bytes;
2221 int old_sei_length;
2222 int extra_bytes;
2223 uint8_t *new_sei;
2224 old_sei_length = find_sei_end(avctx, dst_box, box_len, &new_sei);
2225 if (old_sei_length < 0)
2226 return old_sei_length;
2227
2228 wrote_bytes = write_sei(sei,
2230 new_sei,
2231 remaining_dst_size - old_sei_length);
2232 if (wrote_bytes < 0)
2233 return wrote_bytes;
2234
2235 if (new_sei + wrote_bytes >= dst_data + remaining_dst_size)
2237
2238 new_sei[wrote_bytes++] = 0x80;
2239 extra_bytes = wrote_bytes - (dst_box + box_len - new_sei);
2240
2241 dst_data += extra_bytes;
2242 remaining_dst_size -= extra_bytes;
2243
2244 wrote_sei = 1;
2245 }
2246
2247 src_offset += curr_src_len;
2248 dst_data += curr_dst_len;
2249
2250 remaining_src_size -= curr_src_len;
2251 remaining_dst_size -= curr_dst_len;
2252 }
2253
2254 return 0;
2255}
2256
2257/**
2258 * Returns a sufficient number of bytes to contain the sei data.
2259 * It may be greater than the minimum required.
2260 */
2261static int get_sei_msg_bytes(const ExtraSEI* sei, int type){
2262 int copied_size;
2263 if (sei->size == 0)
2264 return 0;
2265
2266 copied_size = -copy_emulation_prev(sei->data,
2267 sei->size,
2268 NULL,
2269 0,
2270 0);
2271
2272 if ((sei->size % 255) == 0) //may result in an extra byte
2273 copied_size++;
2274
2275 return copied_size + sei->size / 255 + 1 + type / 255 + 1;
2276}
2277
2279 AVCodecContext *avctx,
2280 CMSampleBufferRef sample_buffer,
2281 AVPacket *pkt,
2282 ExtraSEI *sei)
2283{
2284 VTEncContext *vtctx = avctx->priv_data;
2285
2286 int status;
2287 bool is_key_frame;
2288 bool add_header;
2289 size_t length_code_size;
2290 size_t header_size = 0;
2291 size_t in_buf_size;
2292 size_t out_buf_size;
2293 size_t sei_nalu_size = 0;
2294 int64_t dts_delta;
2295 int nalu_count;
2296 CMTime pts;
2297 CMTime dts;
2298 CMVideoFormatDescriptionRef vid_fmt;
2299
2300 vtenc_get_frame_info(sample_buffer, &is_key_frame);
2301
2302 if (vtctx->get_param_set_func) {
2303 status = get_length_code_size(avctx, sample_buffer, &length_code_size);
2304 if (status) return status;
2305
2306 add_header = is_key_frame && !(avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER);
2307
2308 if (add_header) {
2309 vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
2310 if (!vid_fmt) {
2311 av_log(avctx, AV_LOG_ERROR, "Cannot get format description.\n");
2312 return AVERROR_EXTERNAL;
2313 }
2314
2315 status = get_params_size(avctx, vid_fmt, &header_size);
2316 if (status) return status;
2317 }
2318
2319 status = count_nalus(length_code_size, sample_buffer, &nalu_count);
2320 if(status)
2321 return status;
2322
2323 if (sei) {
2324 size_t msg_size = get_sei_msg_bytes(sei,
2326
2327 sei_nalu_size = sizeof(start_code) + 1 + msg_size + 1;
2328 }
2329
2330 in_buf_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
2331 out_buf_size = header_size +
2332 in_buf_size +
2333 sei_nalu_size +
2334 nalu_count * ((int)sizeof(start_code) - (int)length_code_size);
2335
2336 status = ff_get_encode_buffer(avctx, pkt, out_buf_size, 0);
2337 if (status < 0)
2338 return status;
2339
2340 if (add_header) {
2341 status = copy_param_sets(avctx, vid_fmt, pkt->data, out_buf_size);
2342 if(status) return status;
2343 }
2344
2346 avctx,
2347 length_code_size,
2348 sample_buffer,
2349 sei,
2350 pkt->data + header_size,
2351 pkt->size - header_size
2352 );
2353
2354 if (status) {
2355 av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
2356 return status;
2357 }
2358 } else {
2359 size_t len;
2360 CMBlockBufferRef buf = CMSampleBufferGetDataBuffer(sample_buffer);
2361 if (!buf) {
2362 av_log(avctx, AV_LOG_ERROR, "Error getting block buffer\n");
2363 return AVERROR_EXTERNAL;
2364 }
2365
2366 len = CMBlockBufferGetDataLength(buf);
2367
2368 status = ff_get_encode_buffer(avctx, pkt, len, 0);
2369 if (status < 0)
2370 return status;
2371
2372 status = CMBlockBufferCopyDataBytes(buf, 0, len, pkt->data);
2373 if (status) {
2374 av_log(avctx, AV_LOG_ERROR, "Error copying packet data: %d\n", status);
2375 return AVERROR_EXTERNAL;
2376 }
2377 }
2378
2379 if (is_key_frame) {
2380 pkt->flags |= AV_PKT_FLAG_KEY;
2381 }
2382
2383 pts = CMSampleBufferGetPresentationTimeStamp(sample_buffer);
2384 dts = CMSampleBufferGetDecodeTimeStamp (sample_buffer);
2385
2386 if (CMTIME_IS_INVALID(pts)) {
2387 av_log(avctx, AV_LOG_ERROR, "PTS is invalid.\n");
2388 return AVERROR_EXTERNAL;
2389 }
2390
2391 if (CMTIME_IS_INVALID(dts)) {
2392 if (!vtctx->has_b_frames) {
2393 dts = pts;
2394 } else {
2395 av_log(avctx, AV_LOG_ERROR, "DTS is invalid.\n");
2396 return AVERROR_EXTERNAL;
2397 }
2398 }
2399
2400 dts_delta = vtctx->dts_delta >= 0 ? vtctx->dts_delta : 0;
2401 pkt->pts = av_rescale_q(pts.value, (AVRational){1, pts.timescale}, avctx->time_base);
2402 pkt->dts = av_rescale_q(dts.value, (AVRational){1, dts.timescale}, avctx->time_base)
2403 - dts_delta;
2404
2405 return 0;
2406}
2407
2409 const AVFrame *frame,
2410 CVPixelBufferRef cv_img)
2411{
2412 int status;
2413
2414 int num_planes = av_pix_fmt_count_planes(frame->format);
2415 size_t num_cv_plane = CVPixelBufferIsPlanar(cv_img) ?
2416 CVPixelBufferGetPlaneCount(cv_img) : 1;
2417 if (num_planes != num_cv_plane) {
2418 av_log(avctx, AV_LOG_ERROR,
2419 "Different number of planes in AVFrame and CVPixelBuffer.\n");
2420 return AVERROR_BUG;
2421 }
2422
2423 status = CVPixelBufferLockBaseAddress(cv_img, 0);
2424 if (status) {
2425 av_log(avctx, AV_LOG_ERROR, "Could not lock base address of CVPixelBuffer: %d.\n", status);
2426 return AVERROR_EXTERNAL;
2427 }
2428
2429 int dst_stride[4] = {0};
2430 uint8_t *dst_addr[4] = {0};
2431 for (int i = 0; i < num_planes; i++) {
2432 dst_addr[i] = (uint8_t*)CVPixelBufferGetBaseAddressOfPlane(cv_img, i);
2433 dst_stride[i] = CVPixelBufferGetBytesPerRowOfPlane(cv_img, i);
2434 }
2435 av_image_copy2(dst_addr, dst_stride, frame->data, frame->linesize,
2436 frame->format, frame->width, frame->height);
2437
2438 status = CVPixelBufferUnlockBaseAddress(cv_img, 0);
2439 if (status) {
2440 av_log(avctx, AV_LOG_ERROR, "Could not unlock CVPixelBuffer base address: %d.\n", status);
2441 return AVERROR_EXTERNAL;
2442 }
2443
2444 return 0;
2445}
2446
2448 const AVFrame *frame,
2449 CVPixelBufferRef *cv_img,
2450 BufNode *node)
2451{
2452 int status;
2453 CVPixelBufferPoolRef pix_buf_pool;
2454 VTEncContext* vtctx = avctx->priv_data;
2455
2456 if (avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX) {
2458
2459 *cv_img = (CVPixelBufferRef)frame->data[3];
2460 av_assert0(*cv_img);
2461
2462 CFRetain(*cv_img);
2463 if (frame->buf[0]) {
2464 node->frame_buf = av_buffer_ref(frame->buf[0]);
2465 if (!node->frame_buf)
2466 return AVERROR(ENOMEM);
2467 }
2468
2469 return 0;
2470 }
2471
2472 int range_guessed;
2473 status = get_cv_pixel_format(avctx, frame->format, avctx->color_range,
2474 &(int) {0}, &range_guessed);
2475 if (status) {
2476 av_log(avctx, AV_LOG_ERROR, "Cannot convert format %d color_range %d: %d\n",
2477 frame->format, frame->color_range, status);
2478 return status;
2479 }
2480 if (range_guessed) {
2481 if (!vtctx->warned_color_range) {
2482 vtctx->warned_color_range = true;
2483 av_log(avctx, AV_LOG_WARNING, "Color range not set for %s. Using MPEG range.\n",
2484 av_get_pix_fmt_name(frame->format));
2485 }
2486 }
2487
2488 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2489 if (!pix_buf_pool) {
2490 /* On iOS, the VT session is invalidated when the APP switches from
2491 * foreground to background and vice versa. Fetch the actual error code
2492 * of the VT session to detect that case and restart the VT session
2493 * accordingly. */
2494 OSStatus vtstatus;
2495
2496 vtstatus = VTCompressionSessionPrepareToEncodeFrames(vtctx->session);
2497 if (vtstatus == kVTInvalidSessionErr) {
2498 vtenc_reset(vtctx);
2499
2500 status = vtenc_configure_encoder(avctx);
2501 if (status == 0)
2502 pix_buf_pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2503 }
2504 if (!pix_buf_pool) {
2505 av_log(avctx, AV_LOG_ERROR, "Could not get pixel buffer pool.\n");
2506 return AVERROR_EXTERNAL;
2507 }
2508 else
2509 av_log(avctx, AV_LOG_WARNING, "VT session restarted because of a "
2510 "kVTInvalidSessionErr error.\n");
2511 }
2512
2513 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2514 pix_buf_pool,
2515 cv_img);
2516
2517
2518 if (status) {
2519 av_log(avctx, AV_LOG_ERROR, "Could not create pixel buffer from pool: %d.\n", status);
2520 return AVERROR_EXTERNAL;
2521 }
2522
2523 status = copy_avframe_to_pixel_buffer(avctx, frame, *cv_img);
2524 if (status) {
2525 CFRelease(*cv_img);
2526 *cv_img = NULL;
2527 return status;
2528 }
2529
2530 return 0;
2531}
2532
2534 CFDictionaryRef* dict_out)
2535{
2536 CFDictionaryRef dict = NULL;
2537 if (frame->pict_type == AV_PICTURE_TYPE_I) {
2538 const void *keys[] = { kVTEncodeFrameOptionKey_ForceKeyFrame };
2539 const void *vals[] = { kCFBooleanTrue };
2540
2541 dict = CFDictionaryCreate(NULL, keys, vals, 1, NULL, NULL);
2542 if(!dict) return AVERROR(ENOMEM);
2543 }
2544
2545 *dict_out = dict;
2546 return 0;
2547}
2548
2550 VTEncContext *vtctx,
2551 const AVFrame *frame)
2552{
2553 CMTime time;
2554 CFDictionaryRef frame_dict = NULL;
2555 CVPixelBufferRef cv_img = NULL;
2556 AVFrameSideData *side_data = NULL;
2557 BufNode *node = av_mallocz(sizeof(*node));
2558 int status;
2559
2560 if (!node)
2561 return AVERROR(ENOMEM);
2562
2563 status = create_cv_pixel_buffer(avctx, frame, &cv_img, node);
2564 if (status)
2565 goto out;
2566
2567 status = create_encoder_dict(frame, &frame_dict);
2568 if (status)
2569 goto out;
2570
2571#if CONFIG_ATSC_A53
2573 if (vtctx->a53_cc && side_data && side_data->size) {
2574 status = ff_alloc_a53_sei(frame, 0, &node->sei.data, &node->sei.size);
2575 if (status < 0) {
2576 goto out;
2577 }
2578 }
2579#endif
2580
2581 time = CMTimeMake(frame->pts * avctx->time_base.num, avctx->time_base.den);
2582
2583 vtenc_submitted_add(vtctx, node);
2584
2585 status = VTCompressionSessionEncodeFrame(
2586 vtctx->session,
2587 cv_img,
2588 time,
2589 kCMTimeInvalid,
2590 frame_dict,
2591 node,
2592 NULL
2593 );
2594 /* The submitted list owns the node even when EncodeFrame() fails. */
2595 node = NULL;
2596
2597 if (status) {
2598 av_log(avctx, AV_LOG_ERROR, "Cannot encode frame: %d\n", status);
2599 status = AVERROR_EXTERNAL;
2600 goto out;
2601 }
2602
2603out:
2604 if (frame_dict)
2605 CFRelease(frame_dict);
2606 if (cv_img)
2607 CFRelease(cv_img);
2608 if (status)
2609 vtenc_free_buf_node(node);
2610
2611 return status;
2612}
2613
2615 AVCodecContext *avctx,
2616 AVPacket *pkt,
2617 const AVFrame *frame,
2618 int *got_packet)
2619{
2620 VTEncContext *vtctx = avctx->priv_data;
2621 bool get_frame;
2622 int status;
2623 CMSampleBufferRef buf = NULL;
2624 ExtraSEI sei = {0};
2625
2626 if (frame) {
2627 status = vtenc_send_frame(avctx, vtctx, frame);
2628
2629 if (status) {
2630 status = AVERROR_EXTERNAL;
2631 goto end_nopkt;
2632 }
2633
2634 if (vtctx->frame_ct_in == 0) {
2635 vtctx->first_pts = frame->pts;
2636 } else if(vtctx->frame_ct_in == vtctx->has_b_frames) {
2637 vtctx->dts_delta = frame->pts - vtctx->first_pts;
2638 }
2639
2640 vtctx->frame_ct_in++;
2641 } else if(!vtctx->flushing) {
2642 vtctx->flushing = true;
2643
2644 status = VTCompressionSessionCompleteFrames(vtctx->session,
2645 kCMTimeIndefinite);
2646
2647 if (status) {
2648 av_log(avctx, AV_LOG_ERROR, "Error flushing frames: %d\n", status);
2649 status = AVERROR_EXTERNAL;
2650 goto end_nopkt;
2651 }
2652 }
2653
2654 *got_packet = 0;
2655 get_frame = vtctx->dts_delta >= 0 || !frame;
2656 if (!get_frame) {
2657 status = 0;
2658 goto end_nopkt;
2659 }
2660
2661 status = vtenc_q_pop(vtctx, !frame, &buf, &sei);
2662 if (status) goto end_nopkt;
2663 if (!buf) goto end_nopkt;
2664
2665 status = vtenc_cm_to_avpacket(avctx, buf, pkt, sei.data ? &sei : NULL);
2666 av_free(sei.data);
2667 CFRelease(buf);
2668 if (status) goto end_nopkt;
2669
2670 *got_packet = 1;
2671 return 0;
2672
2673end_nopkt:
2675 return status;
2676}
2677
2679 CMVideoCodecType codec_type,
2680 CFStringRef profile_level,
2681 CFNumberRef gamma_level,
2682 CFDictionaryRef enc_info,
2683 CFDictionaryRef pixel_buffer_info)
2684{
2685 VTEncContext *vtctx = avctx->priv_data;
2686 int status;
2687 CVPixelBufferPoolRef pool = NULL;
2688 CVPixelBufferRef pix_buf = NULL;
2689 CMTime time;
2690 CMSampleBufferRef buf = NULL;
2691 BufNode *node = av_mallocz(sizeof(*node));
2692
2693 if (!node)
2694 return AVERROR(ENOMEM);
2695
2696 status = vtenc_create_encoder(avctx,
2697 codec_type,
2698 profile_level,
2699 gamma_level,
2700 enc_info,
2701 pixel_buffer_info,
2702 vtctx->constant_bit_rate,
2703 &vtctx->session);
2704 if (status)
2705 goto pe_cleanup;
2706
2707 pool = VTCompressionSessionGetPixelBufferPool(vtctx->session);
2708 if(!pool){
2709 av_log(avctx, AV_LOG_ERROR, "Error getting pixel buffer pool.\n");
2710 status = AVERROR_EXTERNAL;
2711 goto pe_cleanup;
2712 }
2713
2714 status = CVPixelBufferPoolCreatePixelBuffer(NULL,
2715 pool,
2716 &pix_buf);
2717
2718 if(status != kCVReturnSuccess){
2719 av_log(avctx, AV_LOG_ERROR, "Error creating frame from pool: %d\n", status);
2720 status = AVERROR_EXTERNAL;
2721 goto pe_cleanup;
2722 }
2723
2724 time = CMTimeMake(0, avctx->time_base.den);
2725
2726 vtenc_submitted_add(vtctx, node);
2727
2728 status = VTCompressionSessionEncodeFrame(vtctx->session,
2729 pix_buf,
2730 time,
2731 kCMTimeInvalid,
2732 NULL,
2733 node,
2734 NULL);
2735 node = NULL;
2736
2737 if (status) {
2738 av_log(avctx,
2740 "Error sending frame for extradata: %d\n",
2741 status);
2742 status = AVERROR_EXTERNAL;
2743 goto pe_cleanup;
2744 }
2745
2746 //Populates extradata - output frames are flushed and param sets are available.
2747 status = VTCompressionSessionCompleteFrames(vtctx->session,
2748 kCMTimeIndefinite);
2749
2750 if (status) {
2751 status = AVERROR_EXTERNAL;
2752 goto pe_cleanup;
2753 }
2754
2755 status = vtenc_q_pop(vtctx, 0, &buf, NULL);
2756 if (status) {
2757 av_log(avctx, AV_LOG_ERROR, "popping: %d\n", status);
2758 goto pe_cleanup;
2759 }
2760
2761 if (!buf) {
2762 // VideoToolbox reports a dropped frame as success with no buffer.
2763 av_log(avctx, AV_LOG_ERROR, "Extradata frame dropped, no param sets\n");
2764 status = AVERROR_EXTERNAL;
2765 goto pe_cleanup;
2766 }
2767
2768 CFRelease(buf);
2769
2770pe_cleanup:
2771 CVPixelBufferRelease(pix_buf);
2772
2773 if (status) {
2774 vtenc_reset(vtctx);
2775 } else if (vtctx->session) {
2776 CFRelease(vtctx->session);
2777 vtctx->session = NULL;
2778 }
2779
2780 vtctx->frame_ct_out = 0;
2781
2782 av_assert0(status != 0 || (avctx->extradata && avctx->extradata_size > 0));
2783 // NULL once the node was submitted, so a set node must be freed.
2784 vtenc_free_buf_node(node);
2785
2786 return status;
2787}
2788
2790{
2791 VTEncContext *vtctx = avctx->priv_data;
2792
2793 if (vtctx->session) {
2794 /* Drain pending frames before reset discards their nodes. */
2795 VTCompressionSessionCompleteFrames(vtctx->session,
2796 kCMTimeIndefinite);
2797 }
2798
2799 vtenc_reset(vtctx);
2800
2801 clear_frame_queue(vtctx);
2802
2804 pthread_mutex_destroy(&vtctx->lock);
2805
2806 return 0;
2807}
2808
2815
2826
2827static const enum AVPixelFormat prores_pix_fmts[] = {
2830#ifdef kCFCoreFoundationVersionNumber10_7
2833#endif
2835#if HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
2837#endif
2838#if HAVE_KCVPIXELFORMATTYPE_422YPCBCR8BIPLANARVIDEORANGE
2840#endif
2841#if HAVE_KCVPIXELFORMATTYPE_422YPCBCR10BIPLANARVIDEORANGE
2843#endif
2844#if HAVE_KCVPIXELFORMATTYPE_422YPCBCR16BIPLANARVIDEORANGE
2846#endif
2847#if HAVE_KCVPIXELFORMATTYPE_444YPCBCR8BIPLANARVIDEORANGE
2849#endif
2850#if HAVE_KCVPIXELFORMATTYPE_444YPCBCR10BIPLANARVIDEORANGE
2852#endif
2853#if HAVE_KCVPIXELFORMATTYPE_444YPCBCR16BIPLANARVIDEORANGE
2855#endif
2858};
2859
2860#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
2861#define COMMON_OPTIONS \
2862 { "allow_sw", "Allow software encoding", OFFSET(allow_sw), AV_OPT_TYPE_BOOL, \
2863 { .i64 = 0 }, 0, 1, VE }, \
2864 { "require_sw", "Require software encoding", OFFSET(require_sw), AV_OPT_TYPE_BOOL, \
2865 { .i64 = 0 }, 0, 1, VE }, \
2866 { "realtime", "Hint that encoding should happen in real-time if not faster (e.g. capturing from camera).", \
2867 OFFSET(realtime), AV_OPT_TYPE_BOOL, { .i64 = 0 }, -1, 1, VE }, \
2868 { "frames_before", "Other frames will come before the frames in this session. This helps smooth concatenation issues.", \
2869 OFFSET(frames_before), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2870 { "frames_after", "Other frames will come after the frames in this session. This helps smooth concatenation issues.", \
2871 OFFSET(frames_after), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE }, \
2872 { "prio_speed", "prioritize encoding speed", OFFSET(prio_speed), AV_OPT_TYPE_BOOL, \
2873 { .i64 = -1 }, -1, 1, VE }, \
2874 { "power_efficient", "Set to 1 to enable more power-efficient encoding if supported.", \
2875 OFFSET(power_efficient), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2876 { "spatial_aq", "Set to 1 to enable spatial AQ if supported.", \
2877 OFFSET(spatialaq), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE }, \
2878 { "max_ref_frames", \
2879 "Sets the maximum number of reference frames. This only has an effect when the value is less than the maximum allowed by the profile/level.", \
2880 OFFSET(max_ref_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
2881
2883 HW_CONFIG_ENCODER_FRAMES(VIDEOTOOLBOX, VIDEOTOOLBOX),
2884 NULL,
2885};
2886
2887#define OFFSET(x) offsetof(VTEncContext, x)
2888static const AVOption h264_options[] = {
2889 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = AV_PROFILE_UNKNOWN }, AV_PROFILE_UNKNOWN, INT_MAX, VE, .unit = "profile" },
2890 { "baseline", "Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_BASELINE }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2891 { "constrained_baseline", "Constrained Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_CONSTRAINED_BASELINE }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2892 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_MAIN }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2893 { "high", "High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_HIGH }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2894 { "constrained_high", "Constrained High Profile", 0, AV_OPT_TYPE_CONST, { .i64 = H264_PROFILE_CONSTRAINED_HIGH }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2895 { "extended", "Extend Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_H264_EXTENDED }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2896
2897 { "level", "Level", OFFSET(level), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 52, VE, .unit = "level" },
2898 { "1.3", "Level 1.3, only available with Baseline Profile", 0, AV_OPT_TYPE_CONST, { .i64 = 13 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2899 { "3.0", "Level 3.0", 0, AV_OPT_TYPE_CONST, { .i64 = 30 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2900 { "3.1", "Level 3.1", 0, AV_OPT_TYPE_CONST, { .i64 = 31 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2901 { "3.2", "Level 3.2", 0, AV_OPT_TYPE_CONST, { .i64 = 32 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2902 { "4.0", "Level 4.0", 0, AV_OPT_TYPE_CONST, { .i64 = 40 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2903 { "4.1", "Level 4.1", 0, AV_OPT_TYPE_CONST, { .i64 = 41 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2904 { "4.2", "Level 4.2", 0, AV_OPT_TYPE_CONST, { .i64 = 42 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2905 { "5.0", "Level 5.0", 0, AV_OPT_TYPE_CONST, { .i64 = 50 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2906 { "5.1", "Level 5.1", 0, AV_OPT_TYPE_CONST, { .i64 = 51 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2907 { "5.2", "Level 5.2", 0, AV_OPT_TYPE_CONST, { .i64 = 52 }, INT_MIN, INT_MAX, VE, .unit = "level" },
2908
2909 { "coder", "Entropy coding", OFFSET(entropy), AV_OPT_TYPE_INT, { .i64 = VT_ENTROPY_NOT_SET }, VT_ENTROPY_NOT_SET, VT_CABAC, VE, .unit = "coder" },
2910 { "cavlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2911 { "vlc", "CAVLC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CAVLC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2912 { "cabac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2913 { "ac", "CABAC entropy coding", 0, AV_OPT_TYPE_CONST, { .i64 = VT_CABAC }, INT_MIN, INT_MAX, VE, .unit = "coder" },
2914
2915 { "a53cc", "Use A53 Closed Captions (if available)", OFFSET(a53_cc), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, VE },
2916
2917 { "constant_bit_rate", "Require constant bit rate (macOS 13 or newer)", OFFSET(constant_bit_rate), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2918 { "max_slice_bytes", "Set the maximum number of bytes in an H.264 slice.", OFFSET(max_slice_bytes), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, VE },
2920 { NULL },
2921};
2922
2923static const FFCodecDefault vt_defaults[] = {
2924 {"b", "0"},
2925 {"qmin", "-1"},
2926 {"qmax", "-1"},
2927 {NULL},
2928};
2929
2931 .class_name = "h264_videotoolbox",
2932 .item_name = av_default_item_name,
2933 .option = h264_options,
2934 .version = LIBAVUTIL_VERSION_INT,
2935};
2936
2938 .p.name = "h264_videotoolbox",
2939 CODEC_LONG_NAME("VideoToolbox H.264 Encoder"),
2940 .p.type = AVMEDIA_TYPE_VIDEO,
2941 .p.id = AV_CODEC_ID_H264,
2942 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
2944 .priv_data_size = sizeof(VTEncContext),
2946 .defaults = vt_defaults,
2947 .init = vtenc_init,
2949 .close = vtenc_close,
2950 .p.priv_class = &h264_videotoolbox_class,
2951 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
2952 .p.wrapper_name = "videotoolbox",
2953 .hw_configs = vt_encode_hw_configs,
2954};
2955
2956static const AVOption hevc_options[] = {
2957 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = AV_PROFILE_UNKNOWN }, AV_PROFILE_UNKNOWN, INT_MAX, VE, .unit = "profile" },
2958 { "main", "Main Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_MAIN }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2959 { "main10", "Main10 Profile", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_MAIN_10 }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2960 { "main42210","Main 4:2:2 10 Profile",0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_REXT }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2961 { "rext", "Main 4:2:2 10 Profile",0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_HEVC_REXT }, INT_MIN, INT_MAX, VE, .unit = "profile" },
2962
2963 { "alpha_quality", "Compression quality for the alpha channel", OFFSET(alpha_quality), AV_OPT_TYPE_DOUBLE, { .dbl = 0.0 }, 0.0, 1.0, VE },
2964
2965 { "constant_bit_rate", "Require constant bit rate (macOS 13 or newer)", OFFSET(constant_bit_rate), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
2966
2968 { NULL },
2969};
2970
2972 .class_name = "hevc_videotoolbox",
2973 .item_name = av_default_item_name,
2974 .option = hevc_options,
2975 .version = LIBAVUTIL_VERSION_INT,
2976};
2977
2979 .p.name = "hevc_videotoolbox",
2980 CODEC_LONG_NAME("VideoToolbox H.265 Encoder"),
2981 .p.type = AVMEDIA_TYPE_VIDEO,
2982 .p.id = AV_CODEC_ID_HEVC,
2983 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
2985 .priv_data_size = sizeof(VTEncContext),
2987 .defaults = vt_defaults,
2988 .color_ranges = AVCOL_RANGE_MPEG | AVCOL_RANGE_JPEG,
2989 .init = vtenc_init,
2991 .close = vtenc_close,
2992 .p.priv_class = &hevc_videotoolbox_class,
2993 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
2994 .p.wrapper_name = "videotoolbox",
2995 .hw_configs = vt_encode_hw_configs,
2996};
2997
2998static const AVOption prores_options[] = {
2999 { "profile", "Profile", OFFSET(profile), AV_OPT_TYPE_INT, { .i64 = AV_PROFILE_UNKNOWN }, AV_PROFILE_UNKNOWN, AV_PROFILE_PRORES_XQ, VE, .unit = "profile" },
3000 { "auto", "Automatically determine based on input format", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_UNKNOWN }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3001 { "proxy", "ProRes 422 Proxy", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_PROXY }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3002 { "lt", "ProRes 422 LT", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_LT }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3003 { "standard", "ProRes 422", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_STANDARD }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3004 { "hq", "ProRes 422 HQ", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_HQ }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3005 { "4444", "ProRes 4444", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_4444 }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3006 { "xq", "ProRes 4444 XQ", 0, AV_OPT_TYPE_CONST, { .i64 = AV_PROFILE_PRORES_XQ }, INT_MIN, INT_MAX, VE, .unit = "profile" },
3007
3009 { NULL },
3010};
3011
3013 .class_name = "prores_videotoolbox",
3014 .item_name = av_default_item_name,
3015 .option = prores_options,
3016 .version = LIBAVUTIL_VERSION_INT,
3017};
3018
3020 .p.name = "prores_videotoolbox",
3021 CODEC_LONG_NAME("VideoToolbox ProRes Encoder"),
3022 .p.type = AVMEDIA_TYPE_VIDEO,
3023 .p.id = AV_CODEC_ID_PRORES,
3024 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
3026 .priv_data_size = sizeof(VTEncContext),
3028 .defaults = vt_defaults,
3029 .color_ranges = AVCOL_RANGE_MPEG | AVCOL_RANGE_JPEG,
3030 .init = vtenc_init,
3032 .close = vtenc_close,
3033 .p.priv_class = &prores_videotoolbox_class,
3034 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP,
3035 .p.wrapper_name = "videotoolbox",
3036 .hw_configs = vt_encode_hw_configs,
3037};
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:97
static void bit_depth(AudioStatsContext *s, const uint64_t *const mask, uint8_t *depth)
Definition af_astats.c:246
const FFCodec ff_h264_videotoolbox_encoder
const FFCodec ff_hevc_videotoolbox_encoder
const FFCodec ff_prores_videotoolbox_encoder
#define VE
Definition amfenc_av1.c:30
static FILE * out
static AVFormatContext * ctx
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.
Definition atsc_a53.c:26
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
static int FUNC sei(CodedBitstreamContext *ctx, RWContext *rw, H264RawSEI *current)
#define CODEC_PIXFMTS_ARRAY(array)
#define FF_CODEC_ENCODE_CB(func)
#define CODEC_LONG_NAME(str)
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static int16_t block[64]
Definition dct.c:125
#define AV_PROFILE_PRORES_STANDARD
Definition defs.h:197
#define AV_PROFILE_PRORES_4444
Definition defs.h:199
#define AV_PROFILE_H264_MAIN
Definition defs.h:126
#define AV_PROFILE_PRORES_LT
Definition defs.h:196
#define AV_PROFILE_H264_EXTENDED
Definition defs.h:127
#define AV_PROFILE_UNKNOWN
Definition defs.h:65
#define AV_PROFILE_PRORES_PROXY
Definition defs.h:195
#define AV_PROFILE_HEVC_REXT
Definition defs.h:176
#define AV_PROFILE_HEVC_MAIN
Definition defs.h:173
#define AV_PROFILE_HEVC_MAIN_10
Definition defs.h:174
#define AV_PROFILE_H264_HIGH
Definition defs.h:128
#define AV_PROFILE_H264_CONSTRAINED_BASELINE
Definition defs.h:125
#define AV_PROFILE_PRORES_XQ
Definition defs.h:200
#define AV_PROFILE_PRORES_HQ
Definition defs.h:198
#define AV_PROFILE_H264_BASELINE
Definition defs.h:124
static AVPacket * pkt
static AVFrame * frame
float fminf(float, float)
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
Definition encode.c:107
double value
Definition eval.c:102
const char * key
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition opt.h:298
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_DOUBLE
Underlying C type is double.
Definition opt.h:266
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition codec.h:79
#define AV_CODEC_FLAG_CLOSED_GOP
Definition avcodec.h:332
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition codec.h:49
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition avcodec.h:213
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition avcodec.h:318
#define AV_CODEC_FLAG_LOW_DELAY
Force low delay.
Definition avcodec.h:314
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition codec_id.h:47
#define AV_CODEC_CAP_HYBRID
Codec is potentially backed by a hardware implementation, but not necessarily.
Definition codec.h:140
@ AV_CODEC_ID_H264
Definition codec_id.h:77
@ AV_CODEC_ID_HEVC
Definition codec_id.h:223
@ AV_CODEC_ID_PRORES
Definition codec_id.h:198
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition packet.c:435
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:657
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition buffer.c:140
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition buffer.c:104
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
Definition error.h:53
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition error.h:59
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition error.h:52
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
Definition frame.c:662
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
Definition frame.h:59
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:247
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition rational.c:35
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
static void av_image_copy2(uint8_t *const dst_data[4], const int dst_linesizes[4], uint8_t *const src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Wrapper around av_image_copy() to workaround the limitation that the conversion from uint8_t * const ...
Definition imgutils.h:184
@ AV_PICTURE_TYPE_I
Intra.
Definition avutil.h:278
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
H.264 common definitions.
@ H264_NAL_PPS
Definition h264.h:42
@ H264_NAL_SPS
Definition h264.h:41
@ H264_NAL_SEI
Definition h264.h:40
@ H264_NAL_AUD
Definition h264.h:43
#define HW_CONFIG_ENCODER_FRAMES(format, device_type_)
Definition hwconfig.h:100
CFStringRef av_map_videotoolbox_color_matrix_from_av(enum AVColorSpace space)
Convert an AVColorSpace to a VideoToolbox/CoreVideo color matrix string.
CFStringRef av_map_videotoolbox_color_primaries_from_av(enum AVColorPrimaries pri)
Convert an AVColorPrimaries to a VideoToolbox/CoreVideo color primaries string.
uint32_t av_map_videotoolbox_format_from_pixfmt2(enum AVPixelFormat pix_fmt, bool full_range)
Same as av_map_videotoolbox_format_from_pixfmt function, but can map and return full range pixel form...
CFStringRef av_map_videotoolbox_color_trc_from_av(enum AVColorTransferCharacteristic trc)
Convert an AVColorTransferCharacteristic to a VideoToolbox/CoreVideo color transfer function string.
An API-specific header for AV_HWDEVICE_TYPE_VIDEOTOOLBOX.
misc image utilities
enum MPFType type
Definition jpegmpfenc.c:55
unsigned offset
Definition libaomenc.c:812
static const AVOption h264_options[]
Definition h264dec.c:1179
common internal api header.
static const int factor[16]
Definition vf_pp7.c:98
Macro definitions for various function/variable attributes.
#define av_fallthrough
Definition attributes.h:67
#define av_cold
Definition attributes.h:117
const char * desc
Definition libsvtav1.c:110
#define COMMON_OPTIONS
Definition libvpxenc.c:1988
#define MKBETAG(a, b, c, d)
Definition macros.h:56
enum AVColorRange range
static enum AVPixelFormat avc_pix_fmts[]
Memory handling functions.
const char data[16]
Definition mxf.c:155
int profile
Definition mxfenc.c:2405
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
Definition os2threads.h:158
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition os2threads.h:119
static av_always_inline int pthread_cond_destroy(pthread_cond_t *cond)
Definition os2threads.h:150
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition os2threads.h:104
#define PTHREAD_ONCE_INIT
Definition os2threads.h:71
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition os2threads.h:139
static av_always_inline int pthread_once(pthread_once_t *once_control, void(*init_routine)(void))
Definition os2threads.h:216
_fmutex pthread_mutex_t
Definition os2threads.h:53
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
Definition os2threads.h:132
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition os2threads.h:198
static av_always_inline int pthread_mutex_destroy(pthread_mutex_t *mutex)
Definition os2threads.h:112
int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt)
Definition pixdesc.c:3524
const char * av_color_range_name(enum AVColorRange range)
Definition pixdesc.c:3800
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.
Definition pixdesc.c:3404
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition pixdesc.c:3484
#define AV_PIX_FMT_FLAG_ALPHA
The pixel format has an alpha channel.
Definition pixdesc.h:147
AVColorRange
Visual content value range.
Definition pixfmt.h:757
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
Definition pixfmt.h:775
@ AVCOL_RANGE_JPEG
Full range content.
Definition pixfmt.h:792
#define AV_PIX_FMT_P210
Definition pixfmt.h:627
#define AV_PIX_FMT_P216
Definition pixfmt.h:631
#define AV_PIX_FMT_P010
Definition pixfmt.h:613
#define AV_PIX_FMT_P410
Definition pixfmt.h:628
AVPixelFormat
Pixel format.
Definition pixfmt.h:71
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition pixfmt.h:96
@ AV_PIX_FMT_NONE
Definition pixfmt.h:72
@ AV_PIX_FMT_P010LE
like NV12, with 10bpp per component, data in the high bits, zeros in the low bits,...
Definition pixfmt.h:307
@ AV_PIX_FMT_VIDEOTOOLBOX
hardware decoding through Videotoolbox
Definition pixfmt.h:305
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition pixfmt.h:73
@ AV_PIX_FMT_BGRA
packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
Definition pixfmt.h:102
@ AV_PIX_FMT_UYVY422
packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
Definition pixfmt.h:88
@ AV_PIX_FMT_NV24
planar YUV 4:4:4, 24bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition pixfmt.h:371
@ AV_PIX_FMT_NV16
interleaved chroma YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition pixfmt.h:198
@ AV_PIX_FMT_AYUV
packed AYUV 4:4:4:4, 32bpp (1 Cr & Cb sample per 1x1 Y & A samples), AYUVAYUV...
Definition pixfmt.h:442
#define AV_PIX_FMT_P416
Definition pixfmt.h:632
AVColorTransferCharacteristic
Color Transfer Characteristic.
Definition pixfmt.h:677
@ AVCOL_TRC_GAMMA22
also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
Definition pixfmt.h:682
@ AVCOL_TRC_GAMMA28
also ITU-R BT470BG
Definition pixfmt.h:683
#define AV_PIX_FMT_AYUV64
Definition pixfmt.h:612
const char * name
Definition qsvenc.c:142
#define av_bswap32
Definition bswap.h:47
enum AVMediaType codec_type
Definition rtp.c:37
@ SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35
Definition sei.h:34
A reference to a data buffer.
Definition buffer.h:82
Describe the class of an AVClass context structure.
Definition log.h:76
main external API structure.
Definition avcodec.h:443
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:644
int width
picture width / height.
Definition avcodec.h:605
enum AVPixelFormat sw_pix_fmt
Nominal unaccelerated pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:651
int global_quality
Global quality for codecs which cannot change it per frame.
Definition avcodec.h:1240
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition avcodec.h:685
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition avcodec.h:468
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition avcodec.h:658
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...
Definition avcodec.h:785
int qmin
minimum quantizer
Definition avcodec.h:1257
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition avcodec.h:629
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition avcodec.h:1574
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition avcodec.h:713
int64_t bit_rate
the average bitrate
Definition avcodec.h:493
int profile
profile
Definition avcodec.h:1646
enum AVColorSpace colorspace
YUV colorspace type.
Definition avcodec.h:672
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition avcodec.h:1025
int64_t rc_max_rate
maximum bitrate
Definition avcodec.h:1293
int qmax
maximum quantizer
Definition avcodec.h:1264
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition avcodec.h:665
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:547
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition avcodec.h:526
enum AVCodecID codec_id
Definition avcodec.h:453
int extradata_size
Definition avcodec.h:527
void * priv_data
Definition avcodec.h:470
Structure to hold side data for an AVFrame.
Definition frame.h:334
size_t size
Definition frame.h:337
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:587
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition pixdesc.h:69
uint64_t flags
Combination of AV_PIX_FMT_FLAG_... flags.
Definition pixdesc.h:94
Rational number (pair of numerator and denominator).
Definition rational.h:58
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
ExtraSEI sei
AVBufferRef * frame_buf
CMSampleBufferRef cm_buffer
struct BufNode * next
pthread_cond_t cv_sample_sent
CFStringRef transfer_function
BufNode * submitted_head
getParameterSetAtIndex get_param_set_func
CFStringRef ycbcr_matrix
CFDictionaryRef supported_props
enum AVCodecID codec_id
pthread_mutex_t lock
VTCompressionSessionRef session
CFStringRef color_primaries
uint8_t level
Definition svq3.c:208
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
#define src
Definition vp8dsp.c:248
int num
Definition error.c:23
static char buffer[20]
Definition seek.c:33
static int64_t pts
int size
static int get_frame(AVFilterContext *ctx, int is_second)
Definition vf_nnedi.c:592
@ kCMVideoCodecType_HEVC
static int create_cv_pixel_buffer(AVCodecContext *avctx, const AVFrame *frame, CVPixelBufferRef *cv_img, BufNode *node)
CFStringRef kVTCompressionPropertyKey_ConstantBitRate
static int write_sei(const ExtraSEI *sei, int sei_type, uint8_t *dst, size_t dst_size)
static const AVClass prores_videotoolbox_class
static const AVClass h264_videotoolbox_class
CFStringRef kVTCompressionPropertyKey_MaximizePowerEfficiency
CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder
static int copy_avframe_to_pixel_buffer(AVCodecContext *avctx, const AVFrame *frame, CVPixelBufferRef cv_img)
@ kCMVideoCodecType_HEVCWithAlpha
static av_cold int vtenc_init(AVCodecContext *avctx)
CFStringRef kVTProfileLevel_H264_High_4_0
CFStringRef kVTCompressionPropertyKey_ReferenceBufferCount
CFStringRef kVTProfileLevel_H264_Main_5_2
@ kVTQPModulationLevel_Default
static struct @270163022166130316376344224307060235304065252011 compat_keys
static int create_cv_pixel_buffer_info(AVCodecContext *avctx, CFMutableDictionaryRef *dict)
static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020
@ kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange
#define REORDER_DELAY
static int is_post_sei_nal_type(int nal_type)
CFStringRef kVTProfileLevel_H264_High_3_0
static int set_encoder_int_property_or_log(AVCodecContext *avctx, CFStringRef key, const char *print_option_name, int value)
CFStringRef kVTProfileLevel_H264_Main_5_1
CFStringRef kVTProfileLevel_H264_Baseline_4_2
static void vtenc_output_callback(void *ctx, void *sourceFrameCtx, OSStatus status, VTEncodeInfoFlags flags, CMSampleBufferRef sample_buffer)
CFStringRef kVTProfileLevel_H264_High_4_1
static void set_async_error(VTEncContext *vtctx, int err)
static av_cold int vtenc_frame(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet)
static BufNode * vtenc_submitted_remove(VTEncContext *vtctx, void *refcon)
getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex
CFStringRef kVTCompressionPropertyKey_RealTime
CFStringRef kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality
static int vtenc_create_encoder(AVCodecContext *avctx, CMVideoCodecType codec_type, CFStringRef profile_level, CFNumberRef gamma_level, CFDictionaryRef enc_info, CFDictionaryRef pixel_buffer_info, bool constant_bit_rate, VTCompressionSessionRef *session)
CFStringRef kVTProfileLevel_H264_ConstrainedHigh_AutoLevel
CFStringRef kVTProfileLevel_HEVC_Main42210_AutoLevel
CFStringRef kVTProfileLevel_H264_Baseline_5_1
CFStringRef kVTProfileLevel_H264_High_3_1
static int copy_emulation_prev(const uint8_t *src, size_t src_size, uint8_t *dst, ssize_t dst_offset, size_t dst_size)
Copies the data inserting emulation prevention bytes as needed.
static CMVideoCodecType get_cm_codec_type(AVCodecContext *avctx, int profile, double alpha_quality)
static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict)
static void clear_frame_queue(VTEncContext *vtctx)
CFStringRef kVTH264EntropyMode_CAVLC
static pthread_once_t once_ctrl
#define H264_PROFILE_CONSTRAINED_HIGH
static const FFCodecDefault vt_defaults[]
static bool get_vt_h264_profile_level(AVCodecContext *avctx, CFStringRef *profile_level_val)
static int vtenc_send_frame(AVCodecContext *avctx, VTEncContext *vtctx, const AVFrame *frame)
CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder
CFStringRef kVTProfileLevel_H264_Baseline_5_2
static void vt_release_num(CFNumberRef *refPtr)
NULL-safe release of *refPtr, and sets value to NULL.
static const AVOption hevc_options[]
static void vtenc_submitted_add(VTEncContext *vtctx, BufNode *info)
static enum AVPixelFormat hevc_pix_fmts[]
static bool get_vt_hevc_profile_level(AVCodecContext *avctx, CFStringRef *profile_level_val)
static int vt_dump_encoder(AVCodecContext *avctx)
static void vtenc_get_frame_info(CMSampleBufferRef buffer, bool *is_key_frame)
static int vtenc_cm_to_avpacket(AVCodecContext *avctx, CMSampleBufferRef sample_buffer, AVPacket *pkt, ExtraSEI *sei)
CFStringRef kVTProfileLevel_H264_High_4_2
CFStringRef kVTProfileLevel_H264_High_3_2
OSStatus(* getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc, size_t parameterSetIndex, const uint8_t **parameterSetPointerOut, size_t *parameterSetSizeOut, size_t *parameterSetCountOut, int *NALUnitHeaderLengthOut)
static void vtenc_q_push(VTEncContext *vtctx, BufNode *info)
@ kVTQPModulationLevel_Disable
static int find_sei_end(AVCodecContext *avctx, uint8_t *nal_data, size_t nal_size, uint8_t **sei_end)
CFStringRef kVTProfileLevel_H264_Baseline_4_0
CFStringRef kVTProfileLevel_H264_Extended_AutoLevel
static void set_encoder_property_or_log(AVCodecContext *avctx, CFStringRef key, const char *print_option_name, CFTypeRef value)
CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020
VTH264Entropy
@ VT_CAVLC
@ VT_ENTROPY_NOT_SET
@ VT_CABAC
static const uint8_t start_code[]
static int create_encoder_dict(const AVFrame *frame, CFDictionaryRef *dict_out)
CFStringRef kVTCompressionPropertyKey_EncoderID
CFStringRef kVTCompressionPropertyKey_MinAllowedFrameQP
CFStringRef kVTCompressionPropertyKey_SpatialAdaptiveQPLevel
static int copy_param_sets(AVCodecContext *avctx, CMVideoFormatDescriptionRef vid_fmt, uint8_t *dst, size_t dst_size)
static bool vtenc_qscale_enabled(void)
CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel
static int get_cv_gamma(AVCodecContext *avctx, CFNumberRef *gamma_level)
static void vtenc_reset(VTEncContext *vtctx)
CFStringRef kCVImageBufferTransferFunction_ITU_R_2020
CFStringRef kVTVideoEncoderSpecification_EnableLowLatencyRateControl
static int count_nalus(size_t length_code_size, CMSampleBufferRef sample_buffer, int *count)
CFStringRef kVTProfileLevel_H264_High_AutoLevel
static int get_length_code_size(AVCodecContext *avctx, CMSampleBufferRef sample_buffer, size_t *size)
static av_cold int vtenc_close(AVCodecContext *avctx)
CFStringRef kVTCompressionPropertyKey_H264EntropyMode
static int vtenc_populate_extradata(AVCodecContext *avctx, CMVideoCodecType codec_type, CFStringRef profile_level, CFNumberRef gamma_level, CFDictionaryRef enc_info, CFDictionaryRef pixel_buffer_info)
CFStringRef kVTH264EntropyMode_CABAC
CFStringRef kVTProfileLevel_H264_Main_AutoLevel
static const AVClass hevc_videotoolbox_class
static void vtenc_submitted_clear(VTEncContext *vtctx)
#define OFFSET(x)
static enum AVPixelFormat prores_pix_fmts[]
CFStringRef kVTCompressionPropertyKey_TargetQualityForAlpha
#define TARGET_CPU_ARM64
static const AVCodecHWConfigInternal *const vt_encode_hw_configs[]
static int copy_replace_length_codes(AVCodecContext *avctx, size_t length_code_size, CMSampleBufferRef sample_buffer, ExtraSEI *sei, uint8_t *dst_data, size_t dst_size)
Copies NAL units and replaces length codes with H.264 Annex B start codes.
static void loadVTEncSymbols(void)
static int get_cv_pixel_format(AVCodecContext *avctx, enum AVPixelFormat fmt, enum AVColorRange range, int *av_pixel_format, int *range_guessed)
CFStringRef kVTProfileLevel_H264_High_5_2
CFStringRef kVTProfileLevel_H264_High_5_1
static int get_sei_msg_bytes(const ExtraSEI *sei, int type)
Returns a sufficient number of bytes to contain the sei data.
#define GET_SYM(symbol, defaultVal)
static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI *sei)
static int get_params_size(AVCodecContext *avctx, CMVideoFormatDescriptionRef vid_fmt, size_t *size)
Get the parameter sets from a CMSampleBufferRef.
CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel
CFStringRef kVTCompressionPropertyKey_MaxAllowedFrameQP
CFStringRef kVTCompressionPropertyKey_AllowOpenGOP
CFStringRef kVTProfileLevel_H264_Baseline_5_0
CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel
@ kCVPixelFormatType_420YpCbCr10BiPlanarFullRange
static int vtenc_configure_encoder(AVCodecContext *avctx)
CFStringRef kVTProfileLevel_H264_Main_4_2
static void vtenc_free_buf_node(BufNode *info)
CFStringRef kVTProfileLevel_H264_ConstrainedBaseline_AutoLevel
static const AVOption prores_options[]
CFStringRef kVTProfileLevel_H264_Extended_5_0
static const uint8_t quality[]
Definition vmixdec.c:58
int len