-
Notifications
You must be signed in to change notification settings - Fork 1
/
ffmpeg_opt.c
4418 lines (3923 loc) · 197 KB
/
ffmpeg_opt.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
/*
* ffmpeg option parsing
*
* 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 <stdint.h>
#include "ffmpeg.h"
#include "cmdutils.h"
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavfilter/avfilter.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/avutil.h"
#include "libavutil/channel_layout.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/fifo.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavutil/parseutils.h"
#include "libavutil/pixdesc.h"
#include "libavutil/pixfmt.h"
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
/**
* @brief 这里看到,MATCH_PER_STREAM_OPT的作用是,遍历用户所有的编解码器名字所属的音视频类型是否都与该流st的st->codecpar->codec_type一样,
* 如果存在一个不一样,那么程序直接退出;否则符合,当用户输入多个编解码器名字时,只会取最后一个编解码器名字作为返回.
* 例如用户传入:-vcodec libx265 -vcodec libx264,此时假设st是视频流,虽然h265,h264都是属于视频流类型的编解码器,但是只会返回用户最后一个
* 编解码器名字,即outvar="libx264"作为传出参数
*/
#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
{\
int i, ret;\
for (i = 0; i < o->nb_ ## name; i++) {\
char *spec = o->name[i].specifier;\
if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
outvar = o->name[i].u.type;\
else if (ret < 0)\
exit_program(1);\
}\
}
#define MATCH_PER_TYPE_OPT(name, type, outvar, fmtctx, mediatype)\
{\
int i;\
for (i = 0; i < o->nb_ ## name; i++) {\
char *spec = o->name[i].specifier;\
if (!strcmp(spec, mediatype))\
outvar = o->name[i].u.type;\
}\
}
const HWAccel hwaccels[] = {
#if CONFIG_VIDEOTOOLBOX
{ "videotoolbox", videotoolbox_init, HWACCEL_VIDEOTOOLBOX, AV_PIX_FMT_VIDEOTOOLBOX },
#endif
#if CONFIG_LIBMFX
{ "qsv", qsv_init, HWACCEL_QSV, AV_PIX_FMT_QSV },
#endif
#if CONFIG_CUVID
{ "cuvid", cuvid_init, HWACCEL_CUVID, AV_PIX_FMT_CUDA },
#endif
{ 0 },
};
AVBufferRef *hw_device_ctx;
HWDevice *filter_hw_device;
char *vstats_filename;
char *sdp_filename;
float audio_drift_threshold = 0.1;
float dts_delta_threshold = 10;
float dts_error_threshold = 3600*30; // dts错误阈值,默认30小时.帧能被解码的最大阈值大小?
int audio_volume = 256; // -vol选项,默认256
int audio_sync_method = 0; // 音频同步方法.默认0
int video_sync_method = VSYNC_AUTO;
float frame_drop_threshold = 0;
int do_deinterlace = 0; // -deinterlace选项,默认0.
int do_benchmark = 0;
int do_benchmark_all = 0; // -benchmark_all选项,默认0
int do_hex_dump = 0;
int do_pkt_dump = 0;
int copy_ts = 0; // copy timestamps,默认0
int start_at_zero = 0; // 使用copy_ts时,将输入时间戳移至0开始,默认0
int copy_tb = -1;
int debug_ts = 0; // 是否打印相关时间戳.-debug_ts选项
int exit_on_error = 0; // xerror选项,默认是0
int abort_on_flags = 0;
int print_stats = -1; // -stats选项,默认-1,在编码期间打印进度报告.
int qp_hist = 0; // -qphist选项,默认0,显示QP直方图
int stdin_interaction = 1; // 可认为是否是交互模式.除pipe、以及/dev/stdin值为0,其它例如普通文件、实时流都是1
int frame_bits_per_raw_sample = 0;
float max_error_rate = 2.0/3;
int filter_nbthreads = 0; // -filter_threads选项,默认0,非复杂过滤器线程数.
int filter_complex_nbthreads = 0; // -filter_complex_threads选项,默认0,复杂过滤器线程数.
int vstats_version = 2; // -vstats_version选项, 默认2, 要使用的vstats格式的版本
static int intra_only = 0;
static int file_overwrite = 0; // -y选项,重写输出文件,即覆盖该输出文件。0=不重写,1=重写,
// 不过为0时且no_file_overwrite=0时会在终端询问用户是否重写
static int no_file_overwrite = 0; // -n选项,不重写输出文件。0=不重写,1=重写
static int do_psnr = 0;
static int input_sync;
static int input_stream_potentially_available = 0;// 标记,=1代表该输入文件可能是可用的
static int ignore_unknown_streams = 0;
static int copy_unknown_streams = 0;
static int find_stream_info = 1;
void tyy_print_AVDirnary(AVDictionary *d){
if(!d){
return;
}
AVDictionaryEntry *t = NULL;
while((t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX))){
printf("tyy_print_AVDirnary, t->key: %s, t->value: %s\n", t->key, t->value);
}
}
static void uninit_options(OptionsContext *o)
{
const OptionDef *po = options;
int i;
/* all OPT_SPEC and OPT_STRING can be freed in generic way */
while (po->name) {
void *dst = (uint8_t*)o + po->u.off;
// 1. 保存在SpecifierOpt结构的,需要被释放
if (po->flags & OPT_SPEC) {
SpecifierOpt **so = dst;
int i, *count = (int*)(so + 1);
for (i = 0; i < *count; i++) {
av_freep(&(*so)[i].specifier);
if (po->flags & OPT_STRING)
av_freep(&(*so)[i].u.str);
}
av_freep(so);
*count = 0;
} else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
// 2. 具有OPT_OFFSET标志且是字符串,同样需要被释放
av_freep(dst);
po++;
}
for (i = 0; i < o->nb_stream_maps; i++)
av_freep(&o->stream_maps[i].linklabel);
av_freep(&o->stream_maps);
av_freep(&o->audio_channel_maps);
av_freep(&o->streamid_map);
av_freep(&o->attachments);
}
static void init_options(OptionsContext *o)
{
memset(o, 0, sizeof(*o));
o->stop_time = INT64_MAX;
o->mux_max_delay = 0.7;
o->start_time = AV_NOPTS_VALUE;
o->start_time_eof = AV_NOPTS_VALUE;
o->recording_time = INT64_MAX;
o->limit_filesize = UINT64_MAX;
o->chapters_input_file = INT_MAX;
o->accurate_seek = 1;
}
static int show_hwaccels(void *optctx, const char *opt, const char *arg)
{
enum AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
int i;
printf("Hardware acceleration methods:\n");
while ((type = av_hwdevice_iterate_types(type)) !=
AV_HWDEVICE_TYPE_NONE)
printf("%s\n", av_hwdevice_get_type_name(type));
for (i = 0; hwaccels[i].name; i++)
printf("%s\n", hwaccels[i].name);
printf("\n");
return 0;
}
/**
* @brief 将传进来的字典内的键值对,去掉流说明符后,设置到新的字典进行返回,传进来的字典内容保持不变。
* @param dict 原字典
* @return 返回一个新的没有流说明符的字典
*/
/* return a copy of the input with the stream specifiers removed from the keys-返回输入的副本,并从键中删除流说明符 */
static AVDictionary *strip_specifiers(AVDictionary *dict)
{
AVDictionaryEntry *e = NULL;
AVDictionary *ret = NULL;
while ((e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))) {
char *p = strchr(e->key, ':');
/*将流说明符去掉.例如e->key="b:v",p是指向":v"的,那么*p=0后,e->key="b"*/
if (p)
*p = 0;
/*所以这里设置到ret的,必定是去掉流说明符"v"的(冒号是分隔符当然也会去掉),例如e->key="b",e->value="128K"*/
av_dict_set(&ret, e->key, e->value, 0);
/*上面设置完毕后,将该p指向的地址恢复为分隔符":",此时会恢复原来的值:e->key="b:v"*/
if (p)
*p = ':';
}
return ret;
}
// 中止指定的条件标志
static int opt_abort_on(void *optctx, const char *opt, const char *arg)
{
static const AVOption opts[] = {
{ "abort_on" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
{ "empty_output" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = ABORT_ON_FLAG_EMPTY_OUTPUT }, .unit = "flags" },
{ NULL },
};
static const AVClass class = {
.class_name = "",
.item_name = av_default_item_name,
.option = opts,
.version = LIBAVUTIL_VERSION_INT,
};
const AVClass *pclass = &class;
return av_opt_eval_flags(&pclass, &opts[0], arg, &abort_on_flags);// 使用参3给参4赋值.
}
static int opt_sameq(void *optctx, const char *opt, const char *arg)
{
av_log(NULL, AV_LOG_ERROR, "Option '%s' was removed. "
"If you are looking for an option to preserve the quality (which is not "
"what -%s was for), use -qscale 0 or an equivalent quality factor option.\n",
opt, opt);
return AVERROR(EINVAL);
}
static int opt_video_channel(void *optctx, const char *opt, const char *arg)
{
av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
return opt_default(optctx, "channel", arg);
}
static int opt_video_standard(void *optctx, const char *opt, const char *arg)
{
av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
return opt_default(optctx, "standard", arg);
}
static int opt_audio_codec(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
return parse_option(o, "codec:a", arg, options);
}
static int opt_video_codec(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
return parse_option(o, "codec:v", arg, options);
}
static int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
return parse_option(o, "codec:s", arg, options);
}
static int opt_data_codec(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
return parse_option(o, "codec:d", arg, options);
}
static int opt_map(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
StreamMap *m = NULL;
int i, negative = 0, file_idx, disabled = 0;
int sync_file_idx = -1, sync_stream_idx = 0;
char *p, *sync;
char *map;
char *allow_unused;
if (*arg == '-') {
negative = 1;
arg++;
}
map = av_strdup(arg);
if (!map)
return AVERROR(ENOMEM);
/* parse sync stream first, just pick first matching stream */
if (sync = strchr(map, ',')) {
*sync = 0;
sync_file_idx = strtol(sync + 1, &sync, 0);
if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
exit_program(1);
}
if (*sync)
sync++;
for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
if (check_stream_specifier(input_files[sync_file_idx]->ctx,
input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
sync_stream_idx = i;
break;
}
if (i == input_files[sync_file_idx]->nb_streams) {
av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
"match any streams.\n", arg);
exit_program(1);
}
if (input_streams[input_files[sync_file_idx]->ist_index + sync_stream_idx]->user_set_discard == AVDISCARD_ALL) {
av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s matches a disabled input "
"stream.\n", arg);
exit_program(1);
}
}
if (map[0] == '[') {
/* this mapping refers to lavfi output */
const char *c = map + 1;
GROW_ARRAY(o->stream_maps, o->nb_stream_maps);
m = &o->stream_maps[o->nb_stream_maps - 1];
m->linklabel = av_get_token(&c, "]");
if (!m->linklabel) {
av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
exit_program(1);
}
} else {
if (allow_unused = strchr(map, '?'))
*allow_unused = 0;
file_idx = strtol(map, &p, 0);
if (file_idx >= nb_input_files || file_idx < 0) {
av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
exit_program(1);
}
if (negative)
/* disable some already defined maps */
for (i = 0; i < o->nb_stream_maps; i++) {
m = &o->stream_maps[i];
if (file_idx == m->file_index &&
check_stream_specifier(input_files[m->file_index]->ctx,
input_files[m->file_index]->ctx->streams[m->stream_index],
*p == ':' ? p + 1 : p) > 0)
m->disabled = 1;
}
else
for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
*p == ':' ? p + 1 : p) <= 0)
continue;
if (input_streams[input_files[file_idx]->ist_index + i]->user_set_discard == AVDISCARD_ALL) {
disabled = 1;
continue;
}
GROW_ARRAY(o->stream_maps, o->nb_stream_maps);
m = &o->stream_maps[o->nb_stream_maps - 1];
m->file_index = file_idx;
m->stream_index = i;
if (sync_file_idx >= 0) {
m->sync_file_index = sync_file_idx;
m->sync_stream_index = sync_stream_idx;
} else {
m->sync_file_index = file_idx;
m->sync_stream_index = i;
}
}
}
if (!m) {
if (allow_unused) {
av_log(NULL, AV_LOG_VERBOSE, "Stream map '%s' matches no streams; ignoring.\n", arg);
} else if (disabled) {
av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches disabled streams.\n"
"To ignore this, add a trailing '?' to the map.\n", arg);
exit_program(1);
} else {
av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n"
"To ignore this, add a trailing '?' to the map.\n", arg);
exit_program(1);
}
}
av_freep(&map);
return 0;
}
static int opt_attach(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
GROW_ARRAY(o->attachments, o->nb_attachments);
o->attachments[o->nb_attachments - 1] = arg;
return 0;
}
static int opt_map_channel(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
int n;
AVStream *st;
AudioChannelMap *m;
char *allow_unused;
char *mapchan;
mapchan = av_strdup(arg);
if (!mapchan)
return AVERROR(ENOMEM);
GROW_ARRAY(o->audio_channel_maps, o->nb_audio_channel_maps);
m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
/* muted channel syntax */
n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
if ((n == 1 || n == 3) && m->channel_idx == -1) {
m->file_idx = m->stream_idx = -1;
if (n == 1)
m->ofile_idx = m->ostream_idx = -1;
av_free(mapchan);
return 0;
}
/* normal syntax */
n = sscanf(arg, "%d.%d.%d:%d.%d",
&m->file_idx, &m->stream_idx, &m->channel_idx,
&m->ofile_idx, &m->ostream_idx);
if (n != 3 && n != 5) {
av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
"[file.stream.channel|-1][:syncfile:syncstream]\n");
exit_program(1);
}
if (n != 5) // only file.stream.channel specified
m->ofile_idx = m->ostream_idx = -1;
/* check input */
if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
m->file_idx);
exit_program(1);
}
if (m->stream_idx < 0 ||
m->stream_idx >= input_files[m->file_idx]->nb_streams) {
av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
m->file_idx, m->stream_idx);
exit_program(1);
}
st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
m->file_idx, m->stream_idx);
exit_program(1);
}
/* allow trailing ? to map_channel */
if (allow_unused = strchr(mapchan, '?'))
*allow_unused = 0;
if (m->channel_idx < 0 || m->channel_idx >= st->codecpar->channels ||
input_streams[input_files[m->file_idx]->ist_index + m->stream_idx]->user_set_discard == AVDISCARD_ALL) {
if (allow_unused) {
av_log(NULL, AV_LOG_VERBOSE, "mapchan: invalid audio channel #%d.%d.%d\n",
m->file_idx, m->stream_idx, m->channel_idx);
} else {
av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n"
"To ignore this, add a trailing '?' to the map_channel.\n",
m->file_idx, m->stream_idx, m->channel_idx);
exit_program(1);
}
}
av_free(mapchan);
return 0;
}
static int opt_sdp_file(void *optctx, const char *opt, const char *arg)
{
av_free(sdp_filename);
sdp_filename = av_strdup(arg);
return 0;
}
#if CONFIG_VAAPI
static int opt_vaapi_device(void *optctx, const char *opt, const char *arg)
{
HWDevice *dev;
const char *prefix = "vaapi:";
char *tmp;
int err;
tmp = av_asprintf("%s%s", prefix, arg);
if (!tmp)
return AVERROR(ENOMEM);
err = hw_device_init_from_string(tmp, &dev);
av_free(tmp);
if (err < 0)
return err;
hw_device_ctx = av_buffer_ref(dev->device_ref);
if (!hw_device_ctx)
return AVERROR(ENOMEM);
return 0;
}
#endif
// -init_hw_device选项的回调
static int opt_init_hw_device(void *optctx, const char *opt, const char *arg)
{
if (!strcmp(arg, "list")) {
enum AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
printf("Supported hardware device types:\n");
while ((type = av_hwdevice_iterate_types(type)) !=
AV_HWDEVICE_TYPE_NONE)
printf("%s\n", av_hwdevice_get_type_name(type));
printf("\n");
exit_program(0);
} else {
return hw_device_init_from_string(arg, NULL);
}
}
static int opt_filter_hw_device(void *optctx, const char *opt, const char *arg)
{
if (filter_hw_device) {
av_log(NULL, AV_LOG_ERROR, "Only one filter device can be used.\n");
return AVERROR(EINVAL);
}
filter_hw_device = hw_device_get_by_name(arg);
if (!filter_hw_device) {
av_log(NULL, AV_LOG_ERROR, "Invalid filter device %s.\n", arg);
return AVERROR(EINVAL);
}
return 0;
}
/**
* Parse a metadata specifier passed as 'arg' parameter.
* @param arg metadata string to parse
* @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
* @param index for type c/p, chapter/program index is written here
* @param stream_spec for type s, the stream specifier is written here
*/
static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
{
if (*arg) {
*type = *arg;
switch (*arg) {
case 'g':
break;
case 's':
if (*(++arg) && *arg != ':') {
av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
exit_program(1);
}
*stream_spec = *arg == ':' ? arg + 1 : "";
break;
case 'c':
case 'p':
if (*(++arg) == ':')
*index = strtol(++arg, NULL, 0);
break;
default:
av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
exit_program(1);
}
} else
*type = 'g';
}
static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
{
AVDictionary **meta_in = NULL;
AVDictionary **meta_out = NULL;
int i, ret = 0;
char type_in, type_out;
const char *istream_spec = NULL, *ostream_spec = NULL;
int idx_in = 0, idx_out = 0;
parse_meta_type(inspec, &type_in, &idx_in, &istream_spec);
parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
if (!ic) {
if (type_out == 'g' || !*outspec)
o->metadata_global_manual = 1;
if (type_out == 's' || !*outspec)
o->metadata_streams_manual = 1;
if (type_out == 'c' || !*outspec)
o->metadata_chapters_manual = 1;
return 0;
}
if (type_in == 'g' || type_out == 'g')
o->metadata_global_manual = 1;
if (type_in == 's' || type_out == 's')
o->metadata_streams_manual = 1;
if (type_in == 'c' || type_out == 'c')
o->metadata_chapters_manual = 1;
/* ic is NULL when just disabling automatic mappings */
if (!ic)
return 0;
#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
if ((index) < 0 || (index) >= (nb_elems)) {\
av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
(desc), (index));\
exit_program(1);\
}
#define SET_DICT(type, meta, context, index)\
switch (type) {\
case 'g':\
meta = &context->metadata;\
break;\
case 'c':\
METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
meta = &context->chapters[index]->metadata;\
break;\
case 'p':\
METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
meta = &context->programs[index]->metadata;\
break;\
case 's':\
break; /* handled separately below */ \
default: av_assert0(0);\
}\
SET_DICT(type_in, meta_in, ic, idx_in);
SET_DICT(type_out, meta_out, oc, idx_out);
/* for input streams choose first matching stream */
if (type_in == 's') {
for (i = 0; i < ic->nb_streams; i++) {
if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
meta_in = &ic->streams[i]->metadata;
break;
} else if (ret < 0)
exit_program(1);
}
if (!meta_in) {
av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match any streams.\n", istream_spec);
exit_program(1);
}
}
if (type_out == 's') {
for (i = 0; i < oc->nb_streams; i++) {
if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
meta_out = &oc->streams[i]->metadata;
av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
} else if (ret < 0)
exit_program(1);
}
} else
av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
return 0;
}
static int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
{
OptionsContext *o = optctx;
char buf[128];
int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
struct tm time = *gmtime((time_t*)&recording_timestamp);
if (!strftime(buf, sizeof(buf), "creation_time=%Y-%m-%dT%H:%M:%S%z", &time))
return -1;
parse_option(o, "metadata", buf, options);
av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
"tag instead.\n", opt);
return 0;
}
/**
* @brief
* @param name 要寻找的编解码器名字
* @param type 媒体类型
* @param encoder 要进行编码还是解码.0 解码, 1 编码
* @return 成功 返回找到的编解码器; 失败 程序退出
*/
static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
{
const AVCodecDescriptor *desc;
const char *codec_string = encoder ? "encoder" : "decoder";
AVCodec *codec;
// 1. 根据名字寻找编解码器
codec = encoder ?
avcodec_find_encoder_by_name(name) :
avcodec_find_decoder_by_name(name);
// 2. 如果根据名字找不到,则使用名字先找编解码器的描述符,再使用描述符寻找编解码器.
if (!codec && (desc = avcodec_descriptor_get_by_name(name))) {// 根据名字获取编解码器的描述符
codec = encoder ? avcodec_find_encoder(desc->id) :
avcodec_find_decoder(desc->id);
if (codec)
av_log(NULL, AV_LOG_VERBOSE, "Matched %s '%s' for codec '%s'.\n",
codec_string, codec->name, desc->name);
}
if (!codec) {
av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
exit_program(1);
}
// 3. 对比.根据用户传进的名字找到的编解码器的媒体类型,若与用户传进的不一致,退出程序.
// 例如用户传进:-codec:a libx264,那么MATCH_PER_TYPE_OPT匹配时,audio_codec_name="libx264"
// 虽然找到编解码器,但音频是没有libx264的,这个找到编解码器是视频的,所以退出.
// codec->type是通过用户输入的名字找到的编解码器名字的类型
if (codec->type != type) {
av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
exit_program(1);
}
return codec;
}
// 例如将choose_decoder的MATCH_PER_STREAM_OPT展开来,用于debug
/**
* @brief 这里看到,MATCH_PER_STREAM_OPT的作用是,遍历用户所有的编解码器名字所属的音视频类型是否都与该流st的st->codecpar->codec_type一样,
* 如果存在一个不一样,那么程序直接退出;否则当用户输入多个编解码器名字时,只会取最后一个编解码器名字作为返回.
* 例如用户传入:-vcodec libx265 -vcodec libx264,此时假设st是视频流,虽然h265,h264都是属于视频流类型的编解码器,但是只会返回用户最后一个
* 编解码器名字,即outvar="libx264"作为传出参数
*/
void MATCH_PER_STREAM_OPT_TYYCODE(OptionsContext *o,const char* name, const char *type,
char *outvar, AVFormatContext* fmtctx, AVStream *st){
int i, ret;
for (i = 0; i < o->nb_codec_names; i++) {
char *spec = o->codec_names[i].specifier;
if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)
outvar = o->codec_names[i].u.str;
else if (ret < 0)
exit_program(1);
}
}
/**
* @brief 选择解码器以及对应的解码器id.两种方案:
* 1.用户传进解码器,那么返回用户选择的解码器,并且st保存了用户选择的解码器的codec_id;
* 2.用户无传进解码器,则以流中的codec_id作为选择解码器返回, codec_id无需改变.
* 当用户传了 解码器选项时,若音视频类型与流的音视频类型不一致 或者 解码器不被ffmpeg支持,程序会退出.
*
* 实际上该函数不关心返回值的话,就是应用强制解码器id(apply forced codec ids)
*/
static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
{
char *codec_name = NULL;
MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);// 判断音视频类型是否与流一致.例如-vcodec libx264,这里是判断'v'是否与st的codec_type一致
if (codec_name) {
AVCodec *codec = find_codec_or_die(codec_name, st->codecpar->codec_type, 0);// 判断解码器是否被ffmpeg支持.例如-vcodec libx264,这里是判断 libx264是否被ffmpeg支持
st->codecpar->codec_id = codec->id;
return codec;
} else
return avcodec_find_decoder(st->codecpar->codec_id);
}
/* Add all the streams from the given input file to the global
* list of input streams. */
// 该函数实际上是对输入流中解码器相关参数的处理,然后封装到InputStream结构体中
static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
{
int i, ret;
for (i = 0; i < ic->nb_streams; i++) {
AVStream *st = ic->streams[i];
AVCodecParameters *par = st->codecpar;
InputStream *ist = av_mallocz(sizeof(*ist));
char *framerate = NULL, *hwaccel_device = NULL;
const char *hwaccel = NULL;
char *hwaccel_output_format = NULL;
char *codec_tag = NULL;
char *next;
char *discard_str = NULL;
const AVClass *cc = avcodec_get_class();// 获取AVCodecContext的AVClass
const AVOption *discard_opt = av_opt_find(&cc, "skip_frame", NULL, 0, 0);
if (!ist)
exit_program(1);
// 1. 往二维数组input_streams**增加一个input_streams*元素
GROW_ARRAY(input_streams, nb_input_streams);//注:这里只是开辟了InputStream *字节大小(64bit为8字节),而不是开辟InputStream字节大小(sizeof(InputStream))
input_streams[nb_input_streams - 1] = ist;
// 2. 利用o对InputStream内部进行赋值或者直接赋默认值
ist->st = st;
ist->file_index = nb_input_files;
ist->discard = 1;
st->discard = AVDISCARD_ALL;/*设置了AVDISCARD_ALL,表示用户丢弃该流*/
ist->nb_samples = 0;
ist->min_pts = INT64_MAX;
ist->max_pts = INT64_MIN;
ist->ts_scale = 1.0;
MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
ist->autorotate = 1;
MATCH_PER_STREAM_OPT(autorotate, i, ist->autorotate, ic, st);
MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
if (codec_tag) {
//strtlo see https://blog.csdn.net/weixin_37921201/article/details/119718403
uint32_t tag = strtol(codec_tag, &next, 0);// next指向非法字符串开始及后面的字符串.
if (*next)// codec_tag出现非法字符串的处理
tag = AV_RL32(codec_tag);
st->codecpar->codec_tag = tag;
}
// 3. 保存解码器
ist->dec = choose_decoder(o, ic, st);
// 4. 保存解码器选项。将o->g->codec_opts保存的解码器选项通过返回值设置到decoder_opts中。
/*这里看到,每个流都保存了一份o->g->codec_opts*/
ist->decoder_opts = filter_codec_opts(o->g->codec_opts, ist->st->codecpar->codec_id, ic, st, ist->dec);
ist->reinit_filters = -1;
MATCH_PER_STREAM_OPT(reinit_filters, i, ist->reinit_filters, ic, st);
MATCH_PER_STREAM_OPT(discard, str, discard_str, ic, st);
ist->user_set_discard = AVDISCARD_NONE;/*默认该流是不丢弃的*/
// 5. 判断是否丢弃该流.-vn,-an,-sn这些选项.
// 只要有视频或者音频或者字幕或者数据被禁用,那么user_set_discard标记为AVDISCARD_ALL
if ((o->video_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) ||
(o->audio_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) ||
(o->subtitle_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) ||
(o->data_disable && ist->st->codecpar->codec_type == AVMEDIA_TYPE_DATA))
ist->user_set_discard = AVDISCARD_ALL;/*设置了AVDISCARD_ALL,表示用户丢弃该流*/
/*检测ffmpeg设置后user_set_discard的值是否与用户的一致,不一致则程序退出*/
if (discard_str && av_opt_eval_int(&cc, discard_opt, discard_str, &ist->user_set_discard) < 0) {
av_log(NULL, AV_LOG_ERROR, "Error parsing discard %s.\n",
discard_str);
exit_program(1);
}
ist->filter_in_rescale_delta_last = AV_NOPTS_VALUE;
// 6. 为解码器上下文开辟内存
ist->dec_ctx = avcodec_alloc_context3(ist->dec);
if (!ist->dec_ctx) {
av_log(NULL, AV_LOG_ERROR, "Error allocating the decoder context.\n");
exit_program(1);
}
// 7. 从流中拷贝参数到解码器上下文
ret = avcodec_parameters_to_context(ist->dec_ctx, par);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error initializing the decoder context.\n");
exit_program(1);
}
if (o->bitexact)
ist->dec_ctx->flags |= AV_CODEC_FLAG_BITEXACT;
// 8. 给不同媒体类型的InputStream中的编解码器相关成员赋值.(忽略硬件相关内容)
switch (par->codec_type) {
case AVMEDIA_TYPE_VIDEO:
if(!ist->dec)// 一般在choose_decoder时已经找到,注open_input_files找到的解码器是ic中的,这里是ist
ist->dec = avcodec_find_decoder(par->codec_id);
#if FF_API_LOWRES
if (st->codec->lowres) {
ist->dec_ctx->lowres = st->codec->lowres;
ist->dec_ctx->width = st->codec->width;
ist->dec_ctx->height = st->codec->height;
ist->dec_ctx->coded_width = st->codec->coded_width;
ist->dec_ctx->coded_height = st->codec->coded_height;
}
#endif
// avformat_find_stream_info() doesn't set this for us anymore.
// avformat_find_stream_info()不再为我们设置这个。
ist->dec_ctx->framerate = st->avg_frame_rate;
MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
if (framerate && av_parse_video_rate(&ist->framerate,
framerate) < 0) {
av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
framerate);
exit_program(1);
}
ist->top_field_first = -1;
MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
// 硬件加速相关.
// 寻找硬件设备的id
MATCH_PER_STREAM_OPT(hwaccels, str, hwaccel, ic, st);
if (hwaccel) {
// The NVDEC hwaccels use a CUDA device, so remap the name here.
// NVDEC hwaccels使用CUDA设备,所以在这里重新映射名称。
// NVDEC是英伟达提供的一种视频解码器引擎,作用是用来解码,可认为是一个SDK库。see https://blog.csdn.net/qq_18998145/article/details/108535188
// cuda则是一种架构,使用CPU+GPU去处理各种复杂的运算。see https://baike.baidu.com/item/CUDA/1186262?fr=aladdin
// 所以这里再重新看这段代码:因为nvdec内部使用的是cuda架构,所以重新映射hwaccel字符串
if (!strcmp(hwaccel, "nvdec"))
hwaccel = "cuda";
if (!strcmp(hwaccel, "none"))
ist->hwaccel_id = HWACCEL_NONE;
else if (!strcmp(hwaccel, "auto"))
ist->hwaccel_id = HWACCEL_AUTO;
else {// 用户指定了具体的硬件解码器
enum AVHWDeviceType type;
int i;
for (i = 0; hwaccels[i].name; i++) {
if (!strcmp(hwaccels[i].name, hwaccel)) {
ist->hwaccel_id = hwaccels[i].id;
break;
}
}
// hwaccel_id=HWACCEL_NONE时
if (!ist->hwaccel_id) {
// 根据设备类型名称查找,该函数不区分大小写。找不到会返回AV_HWDEVICE_TYPE_NONE
type = av_hwdevice_find_type_by_name(hwaccel);
if (type != AV_HWDEVICE_TYPE_NONE) {
ist->hwaccel_id = HWACCEL_GENERIC;
ist->hwaccel_device_type = type;
}
}
// hwaccel_id还是为HWACCEL_NONE时,打印相关错误提示然后程序退出
if (!ist->hwaccel_id) {
av_log(NULL, AV_LOG_FATAL, "Unrecognized hwaccel: %s.\n",
hwaccel);
av_log(NULL, AV_LOG_FATAL, "Supported hwaccels: ");
type = AV_HWDEVICE_TYPE_NONE;
// av_hwdevice_iterate_types函数每次会返回在hw_table中,上一个id为prev的硬件解码器id
// hw_table是源码中的一个硬件映射表,保存了各个解码器的处理函数
while ((type = av_hwdevice_iterate_types(type)) !=
AV_HWDEVICE_TYPE_NONE)
av_log(NULL, AV_LOG_FATAL, "%s ",
av_hwdevice_get_type_name(type));
for (i = 0; hwaccels[i].name; i++)
av_log(NULL, AV_LOG_FATAL, "%s ", hwaccels[i].name);
av_log(NULL, AV_LOG_FATAL, "\n");
exit_program(1);
}
}
}//<== if (hwaccel) end ==>
// 从命令行的参数获取硬件设备名
MATCH_PER_STREAM_OPT(hwaccel_devices, str, hwaccel_device, ic, st);
if (hwaccel_device) {
ist->hwaccel_device = av_strdup(hwaccel_device);
if (!ist->hwaccel_device)
exit_program(1);
}
MATCH_PER_STREAM_OPT(hwaccel_output_formats, str,
hwaccel_output_format, ic, st);
if (hwaccel_output_format) {
ist->hwaccel_output_format = av_get_pix_fmt(hwaccel_output_format);
if (ist->hwaccel_output_format == AV_PIX_FMT_NONE) {
av_log(NULL, AV_LOG_FATAL, "Unrecognised hwaccel output "
"format: %s", hwaccel_output_format);
}
} else {
ist->hwaccel_output_format = AV_PIX_FMT_NONE;
}
ist->hwaccel_pix_fmt = AV_PIX_FMT_NONE;
break;
case AVMEDIA_TYPE_AUDIO:
ist->guess_layout_max = INT_MAX;
MATCH_PER_STREAM_OPT(guess_layout_max, i, ist->guess_layout_max, ic, st);
guess_input_channel_layout(ist);// 设置通道布局到ist中
break;
case AVMEDIA_TYPE_DATA:
case AVMEDIA_TYPE_SUBTITLE: {
char *canvas_size = NULL;
if(!ist->dec)// 一般在choose_decoder时已经找到
ist->dec = avcodec_find_decoder(par->codec_id);
MATCH_PER_STREAM_OPT(fix_sub_duration, i, ist->fix_sub_duration, ic, st);