/
videotoolboxenc.c
2848 lines (2381 loc) · 95.2 KB
/
videotoolboxenc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* copyright (c) 2015 Rick Kern <kernrj@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <VideoToolbox/VideoToolbox.h>
#include <CoreVideo/CoreVideo.h>
#include <CoreMedia/CoreMedia.h>
#include <TargetConditionals.h>
#include <Availability.h>
#include "avcodec.h"
#include "libavutil/opt.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavcodec/avcodec.h"
#include "libavutil/pixdesc.h"
#include "libavutil/hwcontext_videotoolbox.h"
#include "codec_internal.h"
#include "internal.h"
#include <pthread.h>
#include "atsc_a53.h"
#include "encode.h"
#include "h264.h"
#include "h264_sei.h"
#include <dlfcn.h>
#if !HAVE_KCMVIDEOCODECTYPE_HEVC
enum { kCMVideoCodecType_HEVC = 'hvc1' };
#endif
#if !HAVE_KCMVIDEOCODECTYPE_HEVCWITHALPHA
enum { kCMVideoCodecType_HEVCWithAlpha = 'muxa' };
#endif
#if !HAVE_KCVPIXELFORMATTYPE_420YPCBCR10BIPLANARVIDEORANGE
enum { kCVPixelFormatType_420YpCbCr10BiPlanarFullRange = 'xf20' };
enum { kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange = 'x420' };
#endif
#ifndef TARGET_CPU_ARM64
# define TARGET_CPU_ARM64 0
#endif
typedef OSStatus (*getParameterSetAtIndex)(CMFormatDescriptionRef videoDesc,
size_t parameterSetIndex,
const uint8_t **parameterSetPointerOut,
size_t *parameterSetSizeOut,
size_t *parameterSetCountOut,
int *NALUnitHeaderLengthOut);
//These symbols may not be present
static struct{
CFStringRef kCVImageBufferColorPrimaries_ITU_R_2020;
CFStringRef kCVImageBufferTransferFunction_ITU_R_2020;
CFStringRef kCVImageBufferYCbCrMatrix_ITU_R_2020;
CFStringRef kVTCompressionPropertyKey_H264EntropyMode;
CFStringRef kVTH264EntropyMode_CAVLC;
CFStringRef kVTH264EntropyMode_CABAC;
CFStringRef kVTProfileLevel_H264_Baseline_4_0;
CFStringRef kVTProfileLevel_H264_Baseline_4_2;
CFStringRef kVTProfileLevel_H264_Baseline_5_0;
CFStringRef kVTProfileLevel_H264_Baseline_5_1;
CFStringRef kVTProfileLevel_H264_Baseline_5_2;
CFStringRef kVTProfileLevel_H264_Baseline_AutoLevel;
CFStringRef kVTProfileLevel_H264_Main_4_2;
CFStringRef kVTProfileLevel_H264_Main_5_1;
CFStringRef kVTProfileLevel_H264_Main_5_2;
CFStringRef kVTProfileLevel_H264_Main_AutoLevel;
CFStringRef kVTProfileLevel_H264_High_3_0;
CFStringRef kVTProfileLevel_H264_High_3_1;
CFStringRef kVTProfileLevel_H264_High_3_2;
CFStringRef kVTProfileLevel_H264_High_4_0;
CFStringRef kVTProfileLevel_H264_High_4_1;
CFStringRef kVTProfileLevel_H264_High_4_2;
CFStringRef kVTProfileLevel_H264_High_5_1;
CFStringRef kVTProfileLevel_H264_High_5_2;
CFStringRef kVTProfileLevel_H264_High_AutoLevel;
CFStringRef kVTProfileLevel_H264_Extended_5_0;
CFStringRef kVTProfileLevel_H264_Extended_AutoLevel;
CFStringRef kVTProfileLevel_HEVC_Main_AutoLevel;
CFStringRef kVTProfileLevel_HEVC_Main10_AutoLevel;
CFStringRef kVTCompressionPropertyKey_RealTime;
CFStringRef kVTCompressionPropertyKey_TargetQualityForAlpha;
CFStringRef kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality;
CFStringRef kVTCompressionPropertyKey_ConstantBitRate;
CFStringRef kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder;
CFStringRef kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder;
getParameterSetAtIndex CMVideoFormatDescriptionGetHEVCParameterSetAtIndex;
} compat_keys;
#define GET_SYM(symbol, defaultVal) \
do{ \
CFStringRef* handle = (CFStringRef*)dlsym(RTLD_DEFAULT, #symbol); \
if(!handle) \
compat_keys.symbol = CFSTR(defaultVal); \
else \
compat_keys.symbol = *handle; \
}while(0)
static pthread_once_t once_ctrl = PTHREAD_ONCE_INIT;
static void loadVTEncSymbols(){
compat_keys.CMVideoFormatDescriptionGetHEVCParameterSetAtIndex =
(getParameterSetAtIndex)dlsym(
RTLD_DEFAULT,
"CMVideoFormatDescriptionGetHEVCParameterSetAtIndex"
);
GET_SYM(kCVImageBufferColorPrimaries_ITU_R_2020, "ITU_R_2020");
GET_SYM(kCVImageBufferTransferFunction_ITU_R_2020, "ITU_R_2020");
GET_SYM(kCVImageBufferYCbCrMatrix_ITU_R_2020, "ITU_R_2020");
GET_SYM(kVTCompressionPropertyKey_H264EntropyMode, "H264EntropyMode");
GET_SYM(kVTH264EntropyMode_CAVLC, "CAVLC");
GET_SYM(kVTH264EntropyMode_CABAC, "CABAC");
GET_SYM(kVTProfileLevel_H264_Baseline_4_0, "H264_Baseline_4_0");
GET_SYM(kVTProfileLevel_H264_Baseline_4_2, "H264_Baseline_4_2");
GET_SYM(kVTProfileLevel_H264_Baseline_5_0, "H264_Baseline_5_0");
GET_SYM(kVTProfileLevel_H264_Baseline_5_1, "H264_Baseline_5_1");
GET_SYM(kVTProfileLevel_H264_Baseline_5_2, "H264_Baseline_5_2");
GET_SYM(kVTProfileLevel_H264_Baseline_AutoLevel, "H264_Baseline_AutoLevel");
GET_SYM(kVTProfileLevel_H264_Main_4_2, "H264_Main_4_2");
GET_SYM(kVTProfileLevel_H264_Main_5_1, "H264_Main_5_1");
GET_SYM(kVTProfileLevel_H264_Main_5_2, "H264_Main_5_2");
GET_SYM(kVTProfileLevel_H264_Main_AutoLevel, "H264_Main_AutoLevel");
GET_SYM(kVTProfileLevel_H264_High_3_0, "H264_High_3_0");
GET_SYM(kVTProfileLevel_H264_High_3_1, "H264_High_3_1");
GET_SYM(kVTProfileLevel_H264_High_3_2, "H264_High_3_2");
GET_SYM(kVTProfileLevel_H264_High_4_0, "H264_High_4_0");
GET_SYM(kVTProfileLevel_H264_High_4_1, "H264_High_4_1");
GET_SYM(kVTProfileLevel_H264_High_4_2, "H264_High_4_2");
GET_SYM(kVTProfileLevel_H264_High_5_1, "H264_High_5_1");
GET_SYM(kVTProfileLevel_H264_High_5_2, "H264_High_5_2");
GET_SYM(kVTProfileLevel_H264_High_AutoLevel, "H264_High_AutoLevel");
GET_SYM(kVTProfileLevel_H264_Extended_5_0, "H264_Extended_5_0");
GET_SYM(kVTProfileLevel_H264_Extended_AutoLevel, "H264_Extended_AutoLevel");
GET_SYM(kVTProfileLevel_HEVC_Main_AutoLevel, "HEVC_Main_AutoLevel");
GET_SYM(kVTProfileLevel_HEVC_Main10_AutoLevel, "HEVC_Main10_AutoLevel");
GET_SYM(kVTCompressionPropertyKey_RealTime, "RealTime");
GET_SYM(kVTCompressionPropertyKey_TargetQualityForAlpha,
"TargetQualityForAlpha");
GET_SYM(kVTCompressionPropertyKey_PrioritizeEncodingSpeedOverQuality,
"PrioritizeEncodingSpeedOverQuality");
GET_SYM(kVTCompressionPropertyKey_ConstantBitRate, "ConstantBitRate");
GET_SYM(kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder,
"EnableHardwareAcceleratedVideoEncoder");
GET_SYM(kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder,
"RequireHardwareAcceleratedVideoEncoder");
}
typedef enum VT_H264Profile {
H264_PROF_AUTO,
H264_PROF_BASELINE,
H264_PROF_MAIN,
H264_PROF_HIGH,
H264_PROF_EXTENDED,
H264_PROF_COUNT
} VT_H264Profile;
typedef enum VTH264Entropy{
VT_ENTROPY_NOT_SET,
VT_CAVLC,
VT_CABAC
} VTH264Entropy;
typedef enum VT_HEVCProfile {
HEVC_PROF_AUTO,
HEVC_PROF_MAIN,
HEVC_PROF_MAIN10,
HEVC_PROF_COUNT
} VT_HEVCProfile;
static const uint8_t start_code[] = { 0, 0, 0, 1 };
typedef struct ExtraSEI {
void *data;
size_t size;
} ExtraSEI;
typedef struct BufNode {
CMSampleBufferRef cm_buffer;
ExtraSEI *sei;
struct BufNode* next;
int error;
} BufNode;
typedef struct VTEncContext {
AVClass *class;
enum AVCodecID codec_id;
VTCompressionSessionRef session;
CFStringRef ycbcr_matrix;
CFStringRef color_primaries;
CFStringRef transfer_function;
getParameterSetAtIndex get_param_set_func;
pthread_mutex_t lock;
pthread_cond_t cv_sample_sent;
int async_error;
BufNode *q_head;
BufNode *q_tail;
int64_t frame_ct_out;
int64_t frame_ct_in;
int64_t first_pts;
int64_t dts_delta;
int64_t profile;
int level;
int entropy;
int realtime;
int frames_before;
int frames_after;
bool constant_bit_rate;
int allow_sw;
int require_sw;
double alpha_quality;
int prio_speed;
bool flushing;
int has_b_frames;
bool warned_color_range;
/* can't be bool type since AVOption will access it as int */
int a53_cc;
} VTEncContext;
static int vtenc_populate_extradata(AVCodecContext *avctx,
CMVideoCodecType codec_type,
CFStringRef profile_level,
CFNumberRef gamma_level,
CFDictionaryRef enc_info,
CFDictionaryRef pixel_buffer_info);
/**
* NULL-safe release of *refPtr, and sets value to NULL.
*/
static void vt_release_num(CFNumberRef* refPtr){
if (!*refPtr) {
return;
}
CFRelease(*refPtr);
*refPtr = NULL;
}
static void set_async_error(VTEncContext *vtctx, int err)
{
BufNode *info;
pthread_mutex_lock(&vtctx->lock);
vtctx->async_error = err;
info = vtctx->q_head;
vtctx->q_head = vtctx->q_tail = NULL;
while (info) {
BufNode *next = info->next;
CFRelease(info->cm_buffer);
av_free(info);
info = next;
}
pthread_mutex_unlock(&vtctx->lock);
}
static void clear_frame_queue(VTEncContext *vtctx)
{
set_async_error(vtctx, 0);
}
static int vtenc_q_pop(VTEncContext *vtctx, bool wait, CMSampleBufferRef *buf, ExtraSEI **sei)
{
BufNode *info;
pthread_mutex_lock(&vtctx->lock);
if (vtctx->async_error) {
pthread_mutex_unlock(&vtctx->lock);
return vtctx->async_error;
}
if (vtctx->flushing && vtctx->frame_ct_in == vtctx->frame_ct_out) {
*buf = NULL;
pthread_mutex_unlock(&vtctx->lock);
return 0;
}
while (!vtctx->q_head && !vtctx->async_error && wait && !vtctx->flushing) {
pthread_cond_wait(&vtctx->cv_sample_sent, &vtctx->lock);
}
if (!vtctx->q_head) {
pthread_mutex_unlock(&vtctx->lock);
*buf = NULL;
return 0;
}
info = vtctx->q_head;
vtctx->q_head = vtctx->q_head->next;
if (!vtctx->q_head) {
vtctx->q_tail = NULL;
}
vtctx->frame_ct_out++;
pthread_mutex_unlock(&vtctx->lock);
*buf = info->cm_buffer;
if (sei && *buf) {
*sei = info->sei;
} else if (info->sei) {
if (info->sei->data) av_free(info->sei->data);
av_free(info->sei);
}
av_free(info);
return 0;
}
static void vtenc_q_push(VTEncContext *vtctx, CMSampleBufferRef buffer, ExtraSEI *sei)
{
BufNode *info = av_malloc(sizeof(BufNode));
if (!info) {
set_async_error(vtctx, AVERROR(ENOMEM));
return;
}
CFRetain(buffer);
info->cm_buffer = buffer;
info->sei = sei;
info->next = NULL;
pthread_mutex_lock(&vtctx->lock);
if (!vtctx->q_head) {
vtctx->q_head = info;
} else {
vtctx->q_tail->next = info;
}
vtctx->q_tail = info;
pthread_cond_signal(&vtctx->cv_sample_sent);
pthread_mutex_unlock(&vtctx->lock);
}
static int count_nalus(size_t length_code_size,
CMSampleBufferRef sample_buffer,
int *count)
{
size_t offset = 0;
int status;
int nalu_ct = 0;
uint8_t size_buf[4];
size_t src_size = CMSampleBufferGetTotalSampleSize(sample_buffer);
CMBlockBufferRef block = CMSampleBufferGetDataBuffer(sample_buffer);
if (length_code_size > 4)
return AVERROR_INVALIDDATA;
while (offset < src_size) {
size_t curr_src_len;
size_t box_len = 0;
size_t i;
status = CMBlockBufferCopyDataBytes(block,
offset,
length_code_size,
size_buf);
if (status != kCMBlockBufferNoErr) {
return AVERROR_EXTERNAL;
}
for (i = 0; i < length_code_size; i++) {
box_len <<= 8;
box_len |= size_buf[i];
}
curr_src_len = box_len + length_code_size;
offset += curr_src_len;
nalu_ct++;
}
*count = nalu_ct;
return 0;
}
static CMVideoCodecType get_cm_codec_type(AVCodecContext *avctx,
int64_t profile,
double alpha_quality)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt == AV_PIX_FMT_VIDEOTOOLBOX ? avctx->sw_pix_fmt : avctx->pix_fmt);
switch (avctx->codec_id) {
case AV_CODEC_ID_H264: return kCMVideoCodecType_H264;
case AV_CODEC_ID_HEVC:
if (desc && (desc->flags & AV_PIX_FMT_FLAG_ALPHA) && alpha_quality > 0.0) {
return kCMVideoCodecType_HEVCWithAlpha;
}
return kCMVideoCodecType_HEVC;
case AV_CODEC_ID_PRORES:
switch (profile) {
case FF_PROFILE_PRORES_PROXY:
return MKBETAG('a','p','c','o'); // kCMVideoCodecType_AppleProRes422Proxy
case FF_PROFILE_PRORES_LT:
return MKBETAG('a','p','c','s'); // kCMVideoCodecType_AppleProRes422LT
case FF_PROFILE_PRORES_STANDARD:
return MKBETAG('a','p','c','n'); // kCMVideoCodecType_AppleProRes422
case FF_PROFILE_PRORES_HQ:
return MKBETAG('a','p','c','h'); // kCMVideoCodecType_AppleProRes422HQ
case FF_PROFILE_PRORES_4444:
return MKBETAG('a','p','4','h'); // kCMVideoCodecType_AppleProRes4444
case FF_PROFILE_PRORES_XQ:
return MKBETAG('a','p','4','x'); // kCMVideoCodecType_AppleProRes4444XQ
default:
av_log(avctx, AV_LOG_ERROR, "Unknown profile ID: %"PRId64", using auto\n", profile);
case FF_PROFILE_UNKNOWN:
if (desc &&
((desc->flags & AV_PIX_FMT_FLAG_ALPHA) ||
desc->log2_chroma_w == 0))
return MKBETAG('a','p','4','h'); // kCMVideoCodecType_AppleProRes4444
else
return MKBETAG('a','p','c','n'); // kCMVideoCodecType_AppleProRes422
}
default: return 0;
}
}
/**
* Get the parameter sets from a CMSampleBufferRef.
* @param dst If *dst isn't NULL, the parameters are copied into existing
* memory. *dst_size must be set accordingly when *dst != NULL.
* If *dst is NULL, it will be allocated.
* In all cases, *dst_size is set to the number of bytes used starting
* at *dst.
*/
static int get_params_size(
AVCodecContext *avctx,
CMVideoFormatDescriptionRef vid_fmt,
size_t *size)
{
VTEncContext *vtctx = avctx->priv_data;
size_t total_size = 0;
size_t ps_count;
int is_count_bad = 0;
size_t i;
int status;
status = vtctx->get_param_set_func(vid_fmt,
0,
NULL,
NULL,
&ps_count,
NULL);
if (status) {
is_count_bad = 1;
ps_count = 0;
status = 0;
}
for (i = 0; i < ps_count || is_count_bad; i++) {
const uint8_t *ps;
size_t ps_size;
status = vtctx->get_param_set_func(vid_fmt,
i,
&ps,
&ps_size,
NULL,
NULL);
if (status) {
/*
* When ps_count is invalid, status != 0 ends the loop normally
* unless we didn't get any parameter sets.
*/
if (i > 0 && is_count_bad) status = 0;
break;
}
total_size += ps_size + sizeof(start_code);
}
if (status) {
av_log(avctx, AV_LOG_ERROR, "Error getting parameter set sizes: %d\n", status);
return AVERROR_EXTERNAL;
}
*size = total_size;
return 0;
}
static int copy_param_sets(
AVCodecContext *avctx,
CMVideoFormatDescriptionRef vid_fmt,
uint8_t *dst,
size_t dst_size)
{
VTEncContext *vtctx = avctx->priv_data;
size_t ps_count;
int is_count_bad = 0;
int status;
size_t offset = 0;
size_t i;
status = vtctx->get_param_set_func(vid_fmt,
0,
NULL,
NULL,
&ps_count,
NULL);
if (status) {
is_count_bad = 1;
ps_count = 0;
status = 0;
}
for (i = 0; i < ps_count || is_count_bad; i++) {
const uint8_t *ps;
size_t ps_size;
size_t next_offset;
status = vtctx->get_param_set_func(vid_fmt,
i,
&ps,
&ps_size,
NULL,
NULL);
if (status) {
if (i > 0 && is_count_bad) status = 0;
break;
}
next_offset = offset + sizeof(start_code) + ps_size;
if (dst_size < next_offset) {
av_log(avctx, AV_LOG_ERROR, "Error: buffer too small for parameter sets.\n");
return AVERROR_BUFFER_TOO_SMALL;
}
memcpy(dst + offset, start_code, sizeof(start_code));
offset += sizeof(start_code);
memcpy(dst + offset, ps, ps_size);
offset = next_offset;
}
if (status) {
av_log(avctx, AV_LOG_ERROR, "Error getting parameter set data: %d\n", status);
return AVERROR_EXTERNAL;
}
return 0;
}
static int set_extradata(AVCodecContext *avctx, CMSampleBufferRef sample_buffer)
{
VTEncContext *vtctx = avctx->priv_data;
CMVideoFormatDescriptionRef vid_fmt;
size_t total_size;
int status;
vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
if (!vid_fmt) {
av_log(avctx, AV_LOG_ERROR, "No video format.\n");
return AVERROR_EXTERNAL;
}
if (vtctx->get_param_set_func) {
status = get_params_size(avctx, vid_fmt, &total_size);
if (status) {
av_log(avctx, AV_LOG_ERROR, "Could not get parameter sets.\n");
return status;
}
avctx->extradata = av_mallocz(total_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!avctx->extradata) {
return AVERROR(ENOMEM);
}
avctx->extradata_size = total_size;
status = copy_param_sets(avctx, vid_fmt, avctx->extradata, total_size);
if (status) {
av_log(avctx, AV_LOG_ERROR, "Could not copy param sets.\n");
return status;
}
} else {
CFDataRef data = CMFormatDescriptionGetExtension(vid_fmt, kCMFormatDescriptionExtension_VerbatimSampleDescription);
if (data && CFGetTypeID(data) == CFDataGetTypeID()) {
CFIndex size = CFDataGetLength(data);
avctx->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!avctx->extradata)
return AVERROR(ENOMEM);
avctx->extradata_size = size;
CFDataGetBytes(data, CFRangeMake(0, size), avctx->extradata);
}
}
return 0;
}
static void vtenc_output_callback(
void *ctx,
void *sourceFrameCtx,
OSStatus status,
VTEncodeInfoFlags flags,
CMSampleBufferRef sample_buffer)
{
AVCodecContext *avctx = ctx;
VTEncContext *vtctx = avctx->priv_data;
ExtraSEI *sei = sourceFrameCtx;
if (vtctx->async_error) {
return;
}
if (status) {
av_log(avctx, AV_LOG_ERROR, "Error encoding frame: %d\n", (int)status);
set_async_error(vtctx, AVERROR_EXTERNAL);
return;
}
if (!sample_buffer) {
return;
}
if (!avctx->extradata && (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
int set_status = set_extradata(avctx, sample_buffer);
if (set_status) {
set_async_error(vtctx, set_status);
return;
}
}
vtenc_q_push(vtctx, sample_buffer, sei);
}
static int get_length_code_size(
AVCodecContext *avctx,
CMSampleBufferRef sample_buffer,
size_t *size)
{
VTEncContext *vtctx = avctx->priv_data;
CMVideoFormatDescriptionRef vid_fmt;
int isize;
int status;
vid_fmt = CMSampleBufferGetFormatDescription(sample_buffer);
if (!vid_fmt) {
av_log(avctx, AV_LOG_ERROR, "Error getting buffer format description.\n");
return AVERROR_EXTERNAL;
}
status = vtctx->get_param_set_func(vid_fmt,
0,
NULL,
NULL,
NULL,
&isize);
if (status) {
av_log(avctx, AV_LOG_ERROR, "Error getting length code size: %d\n", status);
return AVERROR_EXTERNAL;
}
*size = isize;
return 0;
}
/*
* Returns true on success.
*
* If profile_level_val is NULL and this method returns true, don't specify the
* profile/level to the encoder.
*/
static bool get_vt_h264_profile_level(AVCodecContext *avctx,
CFStringRef *profile_level_val)
{
VTEncContext *vtctx = avctx->priv_data;
int64_t profile = vtctx->profile;
if (profile == H264_PROF_AUTO && vtctx->level) {
//Need to pick a profile if level is not auto-selected.
profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;
}
*profile_level_val = NULL;
switch (profile) {
case H264_PROF_AUTO:
return true;
case H264_PROF_BASELINE:
switch (vtctx->level) {
case 0: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Baseline_AutoLevel; break;
case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3; break;
case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0; break;
case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1; break;
case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2; break;
case 40: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Baseline_4_0; break;
case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1; break;
case 42: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Baseline_4_2; break;
case 50: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Baseline_5_0; break;
case 51: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Baseline_5_1; break;
case 52: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Baseline_5_2; break;
}
break;
case H264_PROF_MAIN:
switch (vtctx->level) {
case 0: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Main_AutoLevel; break;
case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0; break;
case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1; break;
case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2; break;
case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0; break;
case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1; break;
case 42: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Main_4_2; break;
case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0; break;
case 51: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Main_5_1; break;
case 52: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Main_5_2; break;
}
break;
case H264_PROF_HIGH:
switch (vtctx->level) {
case 0: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_AutoLevel; break;
case 30: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_3_0; break;
case 31: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_3_1; break;
case 32: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_3_2; break;
case 40: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_4_0; break;
case 41: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_4_1; break;
case 42: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_4_2; break;
case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0; break;
case 51: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_5_1; break;
case 52: *profile_level_val =
compat_keys.kVTProfileLevel_H264_High_5_2; break;
}
break;
case H264_PROF_EXTENDED:
switch (vtctx->level) {
case 0: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Extended_AutoLevel; break;
case 50: *profile_level_val =
compat_keys.kVTProfileLevel_H264_Extended_5_0; break;
}
break;
}
if (!*profile_level_val) {
av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
return false;
}
return true;
}
/*
* Returns true on success.
*
* If profile_level_val is NULL and this method returns true, don't specify the
* profile/level to the encoder.
*/
static bool get_vt_hevc_profile_level(AVCodecContext *avctx,
CFStringRef *profile_level_val)
{
VTEncContext *vtctx = avctx->priv_data;
int64_t profile = vtctx->profile;
*profile_level_val = NULL;
switch (profile) {
case HEVC_PROF_AUTO:
return true;
case HEVC_PROF_MAIN:
*profile_level_val =
compat_keys.kVTProfileLevel_HEVC_Main_AutoLevel;
break;
case HEVC_PROF_MAIN10:
*profile_level_val =
compat_keys.kVTProfileLevel_HEVC_Main10_AutoLevel;
break;
}
if (!*profile_level_val) {
av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");
return false;
}
return true;
}
static int get_cv_pixel_format(AVCodecContext* avctx,
enum AVPixelFormat fmt,
enum AVColorRange range,
int* av_pixel_format,
int* range_guessed)
{
if (range_guessed) *range_guessed = range != AVCOL_RANGE_MPEG &&
range != AVCOL_RANGE_JPEG;
//MPEG range is used when no range is set
*av_pixel_format = av_map_videotoolbox_format_from_pixfmt2(fmt, range == AVCOL_RANGE_JPEG);
return *av_pixel_format ? 0 : AVERROR(EINVAL);
}
static void add_color_attr(AVCodecContext *avctx, CFMutableDictionaryRef dict) {
VTEncContext *vtctx = avctx->priv_data;
if (vtctx->color_primaries) {
CFDictionarySetValue(dict,
kCVImageBufferColorPrimariesKey,
vtctx->color_primaries);
}
if (vtctx->transfer_function) {
CFDictionarySetValue(dict,
kCVImageBufferTransferFunctionKey,
vtctx->transfer_function);
}
if (vtctx->ycbcr_matrix) {
CFDictionarySetValue(dict,
kCVImageBufferYCbCrMatrixKey,
vtctx->ycbcr_matrix);
}
}
static int create_cv_pixel_buffer_info(AVCodecContext* avctx,
CFMutableDictionaryRef* dict)
{
CFNumberRef cv_color_format_num = NULL;
CFNumberRef width_num = NULL;
CFNumberRef height_num = NULL;
CFMutableDictionaryRef pixel_buffer_info = NULL;
int cv_color_format;
int status = get_cv_pixel_format(avctx,
avctx->pix_fmt,
avctx->color_range,
&cv_color_format,
NULL);
if (status) return status;
pixel_buffer_info = CFDictionaryCreateMutable(
kCFAllocatorDefault,
20,
&kCFCopyStringDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (!pixel_buffer_info) goto pbinfo_nomem;
cv_color_format_num = CFNumberCreate(kCFAllocatorDefault,
kCFNumberSInt32Type,
&cv_color_format);
if (!cv_color_format_num) goto pbinfo_nomem;
CFDictionarySetValue(pixel_buffer_info,
kCVPixelBufferPixelFormatTypeKey,
cv_color_format_num);
vt_release_num(&cv_color_format_num);
width_num = CFNumberCreate(kCFAllocatorDefault,
kCFNumberSInt32Type,
&avctx->width);
if (!width_num) goto pbinfo_nomem;
CFDictionarySetValue(pixel_buffer_info,
kCVPixelBufferWidthKey,
width_num);
vt_release_num(&width_num);
height_num = CFNumberCreate(kCFAllocatorDefault,
kCFNumberSInt32Type,
&avctx->height);
if (!height_num) goto pbinfo_nomem;
CFDictionarySetValue(pixel_buffer_info,
kCVPixelBufferHeightKey,
height_num);
vt_release_num(&height_num);
add_color_attr(avctx, pixel_buffer_info);
*dict = pixel_buffer_info;
return 0;
pbinfo_nomem:
vt_release_num(&cv_color_format_num);
vt_release_num(&width_num);
vt_release_num(&height_num);
if (pixel_buffer_info) CFRelease(pixel_buffer_info);
return AVERROR(ENOMEM);
}
static int get_cv_color_primaries(AVCodecContext *avctx,
CFStringRef *primaries)
{
enum AVColorPrimaries pri = avctx->color_primaries;
switch (pri) {
case AVCOL_PRI_UNSPECIFIED:
*primaries = NULL;
break;
case AVCOL_PRI_BT470BG:
*primaries = kCVImageBufferColorPrimaries_EBU_3213;
break;
case AVCOL_PRI_SMPTE170M:
*primaries = kCVImageBufferColorPrimaries_SMPTE_C;
break;
case AVCOL_PRI_BT709:
*primaries = kCVImageBufferColorPrimaries_ITU_R_709_2;
break;
case AVCOL_PRI_BT2020:
*primaries = compat_keys.kCVImageBufferColorPrimaries_ITU_R_2020;
break;
default:
av_log(avctx, AV_LOG_ERROR, "Color primaries %s is not supported.\n", av_color_primaries_name(pri));
*primaries = NULL;
return -1;
}
return 0;
}
static int get_cv_transfer_function(AVCodecContext *avctx,
CFStringRef *transfer_fnc,
CFNumberRef *gamma_level)
{
enum AVColorTransferCharacteristic trc = avctx->color_trc;
Float32 gamma;
*gamma_level = NULL;
switch (trc) {
case AVCOL_TRC_UNSPECIFIED:
*transfer_fnc = NULL;
break;
case AVCOL_TRC_BT709:
*transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;
break;
case AVCOL_TRC_SMPTE240M:
*transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;