-
Notifications
You must be signed in to change notification settings - Fork 1
/
ffmpeg.c
6792 lines (5992 loc) · 287 KB
/
ffmpeg.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) 2000-2003 Fabrice Bellard
*
* 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
*/
/**
* @file
* multimedia converter based on the FFmpeg libraries
*/
#include "config.h"
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <stdatomic.h>
#include <stdint.h>
#if HAVE_IO_H
#include <io.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "libavformat/avformat.h"
#include "libavdevice/avdevice.h"
#include "libswresample/swresample.h"
#include "libavutil/opt.h"
#include "libavutil/channel_layout.h"
#include "libavutil/parseutils.h"
#include "libavutil/samplefmt.h"
#include "libavutil/fifo.h"
#include "libavutil/hwcontext.h"
#include "libavutil/internal.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/dict.h"
#include "libavutil/display.h"
#include "libavutil/mathematics.h"
#include "libavutil/pixdesc.h"
#include "libavutil/avstring.h"
#include "libavutil/libm.h"
#include "libavutil/imgutils.h"
#include "libavutil/timestamp.h"
#include "libavutil/bprint.h"
#include "libavutil/time.h"
#include "libavutil/thread.h"
#include "libavutil/threadmessage.h"
#include "libavcodec/mathops.h"
#include "libavformat/os_support.h"
# include "libavfilter/avfilter.h"
# include "libavfilter/buffersrc.h"
# include "libavfilter/buffersink.h"
#if HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
#elif HAVE_GETPROCESSTIMES
#include <windows.h>
#endif
#if HAVE_GETPROCESSMEMORYINFO
#include <windows.h>
#include <psapi.h>
#endif
#if HAVE_SETCONSOLECTRLHANDLER
#include <windows.h>
#endif
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#if HAVE_TERMIOS_H
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
#elif HAVE_KBHIT
#include <conio.h>
#endif
#include <time.h>
#include "ffmpeg.h"
#include "cmdutils.h"
#include "libavutil/avassert.h"
const char program_name[] = "ffmpeg";
const int program_birth_year = 2000;
static FILE *vstats_file;
const char *const forced_keyframes_const_names[] = {
"n",
"n_forced",
"prev_forced_n",
"prev_forced_t",
"t",
NULL
};
typedef struct BenchmarkTimeStamps {
int64_t real_usec; // transcode()调用前的实时时间,see av_gettime_relative().单位微秒
int64_t user_usec; // 进程在用户层消耗的时间.单位微秒
int64_t sys_usec; // 进程在内核层消耗的时间.单位微秒
} BenchmarkTimeStamps;
static void do_video_stats(OutputStream *ost, int frame_size);
static BenchmarkTimeStamps get_benchmark_time_stamps(void);
static int64_t getmaxrss(void);
static int ifilter_has_all_input_formats(FilterGraph *fg);
static int run_as_daemon = 0; // 0=前台运行;1=后台运行
static int nb_frames_dup = 0;
static unsigned dup_warning = 1000;
static int nb_frames_drop = 0;
static int64_t decode_error_stat[2];// 记录解码的状态.下标0记录的是成功解码的参数,下标1是失败的次数.
static int want_sdp = 1;
static BenchmarkTimeStamps current_time;
AVIOContext *progress_avio = NULL; // 指定-progress选项,会在回调为该全局对象初始化
static uint8_t *subtitle_out;
InputStream **input_streams = NULL;
int nb_input_streams = 0;
InputFile **input_files = NULL;
int nb_input_files = 0;
OutputStream **output_streams = NULL;
int nb_output_streams = 0;
OutputFile **output_files = NULL;
int nb_output_files = 0;
FilterGraph **filtergraphs;
int nb_filtergraphs;
#if HAVE_TERMIOS_H
/* init terminal so that we can grab keys */
static struct termios oldtty;
static int restore_tty;
#endif
#if HAVE_THREADS
static void free_input_threads(void);
#endif
/* sub2video hack:
Convert subtitles to video with alpha to insert them in filter graphs.
This is a temporary solution until libavfilter gets real subtitles support.
*/
static int sub2video_get_blank_frame(InputStream *ist)
{
int ret;
AVFrame *frame = ist->sub2video.frame;
av_frame_unref(frame);
ist->sub2video.frame->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
if ((ret = av_frame_get_buffer(frame, 32)) < 0)
return ret;
memset(frame->data[0], 0, frame->height * frame->linesize[0]);
return 0;
}
static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
AVSubtitleRect *r)
{
uint32_t *pal, *dst2;
uint8_t *src, *src2;
int x, y;
if (r->type != SUBTITLE_BITMAP) {
av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
return;
}
if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
r->x, r->y, r->w, r->h, w, h
);
return;
}
dst += r->y * dst_linesize + r->x * 4;
src = r->data[0];
pal = (uint32_t *)r->data[1];
for (y = 0; y < r->h; y++) {
dst2 = (uint32_t *)dst;
src2 = src;
for (x = 0; x < r->w; x++)
*(dst2++) = pal[*(src2++)];
dst += dst_linesize;
src += r->linesize[0];
}
}
static void sub2video_push_ref(InputStream *ist, int64_t pts)
{
AVFrame *frame = ist->sub2video.frame;
int i;
int ret;
av_assert1(frame->data[0]);
ist->sub2video.last_pts = frame->pts = pts;
for (i = 0; i < ist->nb_filters; i++) {
ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
AV_BUFFERSRC_FLAG_KEEP_REF |
AV_BUFFERSRC_FLAG_PUSH);
if (ret != AVERROR_EOF && ret < 0)
av_log(NULL, AV_LOG_WARNING, "Error while add the frame to buffer source(%s).\n",
av_err2str(ret));
}
}
void sub2video_update(InputStream *ist, AVSubtitle *sub)
{
AVFrame *frame = ist->sub2video.frame;
int8_t *dst;
int dst_linesize;
int num_rects, i;
int64_t pts, end_pts;
if (!frame)
return;
if (sub) {
pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
AV_TIME_BASE_Q, ist->st->time_base);
end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
AV_TIME_BASE_Q, ist->st->time_base);
num_rects = sub->num_rects;
} else {
pts = ist->sub2video.end_pts;
end_pts = INT64_MAX;
num_rects = 0;
}
if (sub2video_get_blank_frame(ist) < 0) {
av_log(ist->dec_ctx, AV_LOG_ERROR,
"Impossible to get a blank canvas.\n");
return;
}
dst = frame->data [0];
dst_linesize = frame->linesize[0];
for (i = 0; i < num_rects; i++)
sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
sub2video_push_ref(ist, pts);
ist->sub2video.end_pts = end_pts;
}
static void sub2video_heartbeat(InputStream *ist, int64_t pts)
{
InputFile *infile = input_files[ist->file_index];
int i, j, nb_reqs;
int64_t pts2;
/* When a frame is read from a file, examine all sub2video streams in
the same file and send the sub2video frame again. Otherwise, decoded
video frames could be accumulating in the filter graph while a filter
(possibly overlay) is desperately waiting for a subtitle frame. */
for (i = 0; i < infile->nb_streams; i++) {
InputStream *ist2 = input_streams[infile->ist_index + i];
if (!ist2->sub2video.frame)
continue;
/* subtitles seem to be usually muxed ahead of other streams;
if not, subtracting a larger time here is necessary */
pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
/* do not send the heartbeat frame if the subtitle is already ahead */
if (pts2 <= ist2->sub2video.last_pts)
continue;
if (pts2 >= ist2->sub2video.end_pts ||
(!ist2->sub2video.frame->data[0] && ist2->sub2video.end_pts < INT64_MAX))
sub2video_update(ist2, NULL);
for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
if (nb_reqs)
sub2video_push_ref(ist2, pts2);
}
}
static void sub2video_flush(InputStream *ist)
{
int i;
int ret;
if (ist->sub2video.end_pts < INT64_MAX)
sub2video_update(ist, NULL);
for (i = 0; i < ist->nb_filters; i++) {
ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
if (ret != AVERROR_EOF && ret < 0)
av_log(NULL, AV_LOG_WARNING, "Flush the frame error.\n");
}
}
/* end of sub2video hack */
static void term_exit_sigsafe(void)
{
#if HAVE_TERMIOS_H
if(restore_tty)
tcsetattr (0, TCSANOW, &oldtty);
#endif
}
void term_exit(void)
{
av_log(NULL, AV_LOG_QUIET, "%s", "");
term_exit_sigsafe();
}
static volatile int received_sigterm = 0;
static volatile int received_nb_signals = 0;
static atomic_int transcode_init_done = ATOMIC_VAR_INIT(0);
static volatile int ffmpeg_exited = 0;
static int main_return_code = 0;
static void
sigterm_handler(int sig)
{
int ret;
received_sigterm = sig;
received_nb_signals++;
term_exit_sigsafe();
if(received_nb_signals > 3) {
ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
strlen("Received > 3 system signals, hard exiting\n"));
if (ret < 0) { /* Do nothing */ };
exit(123);
}
}
#if HAVE_SETCONSOLECTRLHANDLER
static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
{
av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
switch (fdwCtrlType)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
sigterm_handler(SIGINT);
return TRUE;
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
sigterm_handler(SIGTERM);
/* Basically, with these 3 events, when we return from this method the
process is hard terminated, so stall as long as we need to
to try and let the main thread(s) clean up and gracefully terminate
(we have at most 5 seconds, but should be done far before that). */
while (!ffmpeg_exited) {
Sleep(0);
}
return TRUE;
default:
av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
return FALSE;
}
}
#endif
void term_init(void)
{
#if HAVE_TERMIOS_H
if (!run_as_daemon && stdin_interaction) {
struct termios tty;
if (tcgetattr (0, &tty) == 0) {
oldtty = tty;
restore_tty = 1;
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
|INLCR|IGNCR|ICRNL|IXON);
tty.c_oflag |= OPOST;
tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
tty.c_cflag &= ~(CSIZE|PARENB);
tty.c_cflag |= CS8;
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 0;
tcsetattr (0, TCSANOW, &tty);
}
signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
}
#endif
signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
#ifdef SIGXCPU
signal(SIGXCPU, sigterm_handler);
#endif
#ifdef SIGPIPE
signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
#endif
#if HAVE_SETCONSOLECTRLHANDLER
SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
#endif
}
/* read a key without blocking */
static int read_key(void)
{
unsigned char ch;
#if HAVE_TERMIOS_H
int n = 1;
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(0, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
n = select(1, &rfds, NULL, NULL, &tv);
if (n > 0) {
n = read(0, &ch, 1);
if (n == 1)
return ch;
return n;
}
#elif HAVE_KBHIT
# if HAVE_PEEKNAMEDPIPE
static int is_pipe;
static HANDLE input_handle;
DWORD dw, nchars;
// 1. 获取输入句柄,并且获取控制台模式(不过ffmpeg没有对控制台模式进一步处理).
if(!input_handle){
//获取输入设备的句柄.GetStdHandle see https://blog.csdn.net/dark_cy/article/details/89103875
input_handle = GetStdHandle(STD_INPUT_HANDLE);
/*GetConsoleMode() see https://docs.microsoft.com/en-us/windows/console/getconsolemode.
返回0表示错误;非0成功.*/
is_pipe = !GetConsoleMode(input_handle, &dw);//获取控制台模式 see https://blog.csdn.net/zanglengyu/article/details/125855938
}
// 2. 获取控制台模式失败的处理
if (is_pipe) {
/* When running under a GUI, you will end here.(当在GUI下运行时,您将在这里结束) */
/* PeekNamedPipe():从句柄的缓冲区读取数据,若不想读取,参2传NULL即可.管道不存在会报错返回0。
* msdn:https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-peeknamedpipe
* see http://www.manongjc.com/detail/19-xpsioohwzlyyvpp.html的例子*/
if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {//nchars是读到的字节数
// input pipe may have been closed by the program that ran ffmpeg
//(输入管道可能已被运行ffmpeg的程序关闭)
return -1;
}
//Read it
if(nchars != 0) {
read(0, &ch, 1);
return ch;
}else{
return -1;
}
}
# endif
if(kbhit())
return(getch());
#endif
return -1;
}
static int decode_interrupt_cb(void *ctx)
{
return received_nb_signals > atomic_load(&transcode_init_done);
}
const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
static void ffmpeg_cleanup(int ret)
{
int i, j;
if (do_benchmark) {
int maxrss = getmaxrss() / 1024;
av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
}
// 1. 释放fg数组相关内容
for (i = 0; i < nb_filtergraphs; i++) {
FilterGraph *fg = filtergraphs[i];
// 1.1 释放滤波图
avfilter_graph_free(&fg->graph);
// 1.2 释放InputFilter数组
for (j = 0; j < fg->nb_inputs; j++) {
while (av_fifo_size(fg->inputs[j]->frame_queue)) {// 释放帧队列剩余的帧
AVFrame *frame;
av_fifo_generic_read(fg->inputs[j]->frame_queue, &frame,
sizeof(frame), NULL);
av_frame_free(&frame);
}
av_fifo_freep(&fg->inputs[j]->frame_queue);
if (fg->inputs[j]->ist->sub2video.sub_queue) {
while (av_fifo_size(fg->inputs[j]->ist->sub2video.sub_queue)) {
AVSubtitle sub;
av_fifo_generic_read(fg->inputs[j]->ist->sub2video.sub_queue,
&sub, sizeof(sub), NULL);
avsubtitle_free(&sub);
}
av_fifo_freep(&fg->inputs[j]->ist->sub2video.sub_queue);
}
av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
av_freep(&fg->inputs[j]->name);
av_freep(&fg->inputs[j]);
}
av_freep(&fg->inputs);
// 1.3 释放OutputFilter数组
for (j = 0; j < fg->nb_outputs; j++) {
av_freep(&fg->outputs[j]->name);
av_freep(&fg->outputs[j]->formats);
av_freep(&fg->outputs[j]->channel_layouts);
av_freep(&fg->outputs[j]->sample_rates);
av_freep(&fg->outputs[j]);
}
av_freep(&fg->outputs);
av_freep(&fg->graph_desc);
// 1.4 释放fg元素
av_freep(&filtergraphs[i]);
}
// 1.5 释放fg数组本身
av_freep(&filtergraphs);
av_freep(&subtitle_out);
// 2. 关闭输出文件
/* close files */
for (i = 0; i < nb_output_files; i++) {
OutputFile *of = output_files[i];
AVFormatContext *s;
if (!of)
continue;
s = of->ctx;
if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
avio_closep(&s->pb);
avformat_free_context(s);
av_dict_free(&of->opts);
av_freep(&output_files[i]);
}
// 3. 关闭输出流
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
if (!ost)
continue;
for (j = 0; j < ost->nb_bitstream_filters; j++)
av_bsf_free(&ost->bsf_ctx[j]);
av_freep(&ost->bsf_ctx);
av_frame_free(&ost->filtered_frame);
av_frame_free(&ost->last_frame);
av_dict_free(&ost->encoder_opts);
av_freep(&ost->forced_keyframes);
av_expr_free(ost->forced_keyframes_pexpr);
av_freep(&ost->avfilter);
av_freep(&ost->logfile_prefix);
av_freep(&ost->audio_channels_map);
ost->audio_channels_mapped = 0;
av_dict_free(&ost->sws_dict);
av_dict_free(&ost->swr_opts);
avcodec_free_context(&ost->enc_ctx);// 释放编码器上下文
avcodec_parameters_free(&ost->ref_par);
if (ost->muxing_queue) {
while (av_fifo_size(ost->muxing_queue)) {
AVPacket pkt;
av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
av_packet_unref(&pkt);
}
av_fifo_freep(&ost->muxing_queue);
}
av_freep(&output_streams[i]);
}
// 4. 回收输入线程
#if HAVE_THREADS
free_input_threads();
#endif
// 5. 关闭输入文件
for (i = 0; i < nb_input_files; i++) {
avformat_close_input(&input_files[i]->ctx);
av_freep(&input_files[i]);
}
// 6. 关闭输入流
for (i = 0; i < nb_input_streams; i++) {
InputStream *ist = input_streams[i];
av_frame_free(&ist->decoded_frame);
av_frame_free(&ist->filter_frame);
av_dict_free(&ist->decoder_opts);
avsubtitle_free(&ist->prev_sub.subtitle);
av_frame_free(&ist->sub2video.frame);
av_freep(&ist->filters);
av_freep(&ist->hwaccel_device);
av_freep(&ist->dts_buffer);
avcodec_free_context(&ist->dec_ctx);// 关闭解码器上下文
av_freep(&input_streams[i]);
}
if (vstats_file) {
if (fclose(vstats_file))
av_log(NULL, AV_LOG_ERROR,
"Error closing vstats file, loss of information possible: %s\n",
av_err2str(AVERROR(errno)));
}
av_freep(&vstats_filename);
// 7. 关闭输入输出文件、流数组本身.
av_freep(&input_streams);
av_freep(&input_files);
av_freep(&output_streams);
av_freep(&output_files);
uninit_opts();
avformat_network_deinit();
if (received_sigterm) {
av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
(int) received_sigterm);
} else if (ret && atomic_load(&transcode_init_done)) {
av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
}
term_exit();
ffmpeg_exited = 1;
}
/**
* @brief 利用b中的key,将a中有同样key的value设置为NULL.获取时忽略后缀,设置时匹配大小写.
* @param a 字典1
* @param b 字典2
*/
void remove_avoptions(AVDictionary **a, AVDictionary *b)
{
AVDictionaryEntry *t = NULL;
while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
}
}
/**
* @brief 只有m中还有一个k-v键值对选项,那么程序就会退出.
*/
void assert_avoptions(AVDictionary *m)
{
AVDictionaryEntry *t;
if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
exit_program(1);
}
}
static void abort_codec_experimental(AVCodec *c, int encoder)
{
exit_program(1);
}
static void update_benchmark(const char *fmt, ...)
{
if (do_benchmark_all) {
BenchmarkTimeStamps t = get_benchmark_time_stamps();
va_list va;
char buf[1024];
if (fmt) {
va_start(va, fmt);
vsnprintf(buf, sizeof(buf), fmt, va);
va_end(va);
av_log(NULL, AV_LOG_INFO,
"bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
t.user_usec - current_time.user_usec,
t.sys_usec - current_time.sys_usec,
t.real_usec - current_time.real_usec, buf);
}
current_time = t;
}
}
/**
* @brief 给输出流退出时进行标记。
* @param ost 输出流
* @param this_stream ost的标记
* @param others ost以外的其它输出流的标记
* @note 并不是真正关闭输出流
*/
static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
{
int i;
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost2 = output_streams[i];
ost2->finished |= ost == ost2 ? this_stream : others;
}
}
/**
* @brief 将pkt写到输出文件(可以是文件或者实时流地址)
* @param of 输出文件
* @param pkt pkt
* @param ost 输出流
* @param unqueue 是否已经计算该pkt在ost->frame_number中,=1表示已经计算。see check_init_output_file()
*/
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
{
AVFormatContext *s = of->ctx;
AVStream *st = ost->st;
int ret;
/*
* Audio encoders may split the packets -- #frames in != #packets out.
* But there is no reordering, so we can limit the number of output packets
* by simply dropping them here.
* Counting encoded video frames needs to be done separately because of
* reordering, see do_video_out().
* Do not count the packet when unqueued because it has been counted when queued.
*/
/*
* 音频编码器可能会分割数据包 -- #输入帧!= #输出包。
* 但是没有重新排序,所以我们可以通过简单地将它们放在这里来限制输出数据包的数量。
* 由于重新排序,编码的视频帧需要单独计数,参见do_video_out()。
* 不要在未排队时计数数据包,因为它在排队时已被计数。
*/
/* 1. 统计已经写帧的数量. */
// "视频需要编码"以外的类型,且unqueue=0表示该pkt没有计算时,会进行计算.
if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
if (ost->frame_number >= ost->max_frames) {// 帧数大于允许的最大帧数,不作处理,并将该包释放
av_packet_unref(pkt);
return;
}
ost->frame_number++;// 视频流需要编码时,不会在这里计数,会在do_video_out()单独计数
#ifdef TYYCODE_TIMESTAMP_MUXER
mydebug(NULL, AV_LOG_INFO, "write_packet(), tpye: %s, ost->frame_number: %d\n",
av_get_media_type_string(st->codecpar->codec_type), ost->frame_number);
#endif
}
/* 2.没有写头或者写头失败,先将包缓存在复用队列,然后返回,不会调用到写帧函数 */
if (!of->header_written) {
AVPacket tmp_pkt = {0};
/* the muxer is not initialized yet, buffer the packet(muxer尚未初始化,请缓冲该数据包) */
// 2.1 fifo没有空间,则给其扩容
if (!av_fifo_space(ost->muxing_queue)) {// return f->end - f->buffer - av_fifo_size(f);
/* 新队列大小求法:若在最大队列大小内,那么以当前队列大小的两倍扩容.
* 例如用户不指定大小,默认是给复用队列先开辟8个空间大小,若此时没空间,说明av_fifo_size()返回的值为8*sizeof(pkt),
* 那么乘以2后,new_size值就是16个pkt的大小了. */
int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
ost->max_muxing_queue_size);
/* 若输出流的包缓存到达最大复用队列,那么ffmpeg会退出程序 */
if (new_size <= av_fifo_size(ost->muxing_queue)) {
av_log(NULL, AV_LOG_ERROR,
"Too many packets buffered for output stream %d:%d.\n",
ost->file_index, ost->st->index);
exit_program(1);
}
ret = av_fifo_realloc2(ost->muxing_queue, new_size);
if (ret < 0)
exit_program(1);
}
/*
* av_packet_make_refcounted(): 确保给定数据包所描述的数据被引用计数。
* @note 此函数不确保引用是可写的。 为此使用av_packet_make_writable。
* @see av_packet_ref.
* @see av_packet_make_writable.
* @param pkt 计算需要参考的PKT数据包.
* @return 成功为0,错误为负AVERROR。失败时,数据包不变。
* 源码也不难,工作是:
* 拷贝packet数据到pkt->buf->data中,再令pkt->data指向它.
*/
ret = av_packet_make_refcounted(pkt);
if (ret < 0)
exit_program(1);
av_packet_move_ref(&tmp_pkt, pkt);// 所有权转移,源码很简单
/*
* av_fifo_generic_write(): 将数据从用户提供的回调提供给AVFifoBuffer。
* @param f 要写入的AVFifoBuffer.
* @param src 数据来源;非const,因为它可以被定义在func中的函数用作可修改的上下文.
* @param size 要写入的字节数.
* @param func 一般写函数;第一个参数是src,第二个参数是dest_buf,第三个参数是dest_buf_size.
* Func必须返回写入dest_buf的字节数,或<= 0表示没有更多可写入的数据。如果func为NULL, src将被解释为源数据的简单字节数组。
* @return 写入FIFO的字节数.
* av_fifo_generic_write()的源码不算难.
*/
av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
return;
}
// 3. 将pkt.pts/pkt.dts置为无效值
if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
pkt->pts = pkt->dts = AV_NOPTS_VALUE;
// 4. 获取该pkt的编码质量,图片类型等信息.
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
int i;
// 关于下面获取q编码质量可参考https://blog.csdn.net/u012117034/article/details/123453863
/*
* av_packet_get_side_data():从packet获取side info.
* @param type 期待side information的类型
* @param size 用于存储side info大小的指针(可选)
* @return 如果存在数据,则指向数据的指针,否则为NULL.
* 源码很简单.
*/
// 获取编码质量状态的side data info
uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
NULL);
// 从sd中获取前32bit
/* AV_RL32(sd)的大概调用过程:
* 1)AV_RL(32, p)
* 2)而AV_RL的定义:
* # define AV_RL(s, p) AV_RN##s(p)
* 3)所以此时调用变成(##表示将参数与前后拼接):
* AV_RN32(p)
* 4)而AV_RN32的定义:
* # define AV_RN32(p) AV_RN(32, p)
* 5)而AV_RN的定义:
* # define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p)))
* 所以最终就是取sd前32bit的内容.(这部分是我使用vscode看源码得出的,qt貌似会跳转的共用体,不太准?)
*
* 至于为什么要获取32bit,看AV_PKT_DATA_QUALITY_STATS枚举注释,这个信息会由编码器填充,
* 被放在side info的前32bit,然后第5个字节存放帧类型,第6个字节存放错误次数,
* 第7、8两字节为保留位,
* 后面剩余的u64le[error count]是一个数组,每个元素是8字节.
*/
ost->quality = sd ? AV_RL32(sd) : -1;
ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
#ifdef TYYCODE_TIMESTAMP_MUXER
mydebug(NULL, AV_LOG_INFO, "write_packet(), video, ost->quality: %d, ost->pict_type: %c\n",
ost->quality, av_get_picture_type_char((enum AVPictureType)ost->pict_type));
#endif
for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {// ost->error[4]数组大小是4,i可能是0-4的值,即最多保存近4次的错误
if (sd && i < sd[5])// 若错误次数(error count) 大于0次以上,即表示有错误
ost->error[i] = AV_RL64(sd + 8 + 8*i);// sd+8是跳过quality+pict_type+保留位,8*i表示跳过前面已经获取的错误.
else
ost->error[i] = -1;// 没有错误
}
// 是否通过帧率对duration重写
if (ost->frame_rate.num && ost->is_cfr) {
// (通过帧速率覆盖数据包持续时间,这应该不会发生)
if (pkt->duration > 0)
av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
ost->mux_timebase);
}
}
// 5. 将pkt相关的时间戳转成输出容器的时基
/* 内部调用av_rescale_q,将pkt里面与时间戳相关的pts、dts、duration、convergence_duration转成以ost->st->time_base为单位 */
av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
#ifdef TYYCODE_TIMESTAMP_MUXER
mydebug(NULL, AV_LOG_WARNING, "write_packet(), ost->mux_timebase: %d/%d, "
"ost->st->time_base: %d/%d, "
"output stream %d:%d\n",
ost->mux_timebase.num, ost->mux_timebase.den,
ost->st->time_base.num, ost->st->time_base.den,
ost->file_index, ost->st->index);
#endif
/* 6. 输出流需要有时间戳的处理 */
/* AVFMT_NOTIMESTAMPS: 格式不需要/有任何时间戳.
* 所以当没有该宏时,就说明需要时间戳 */
if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
// 6.1 解码时间戳比显示时间戳大,重写它们的时间戳
if (pkt->dts != AV_NOPTS_VALUE &&
pkt->pts != AV_NOPTS_VALUE &&
pkt->dts > pkt->pts) {
av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
pkt->dts, pkt->pts,
ost->file_index, ost->st->index);
pkt->pts =
pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
- FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
- FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);// 减去最大最小值,最终得到的就是三者之中,处于中间的那个值
#ifdef TYYCODE_TIMESTAMP_MUXER
mydebug(NULL, AV_LOG_WARNING, "write_packet(), pkt->dts: %"PRId64", pkt->pts: %"PRId64", ost->last_mux_dts + 1: %"PRId64", "
"output stream %d:%d\n", pkt->dts, pkt->pts, ost->last_mux_dts + 1, ost->file_index, ost->st->index);
#endif
}
/* 6.2 判断当前pkt.dts与上一个pkt.dts比是否单调递增,以此修正pkt的pts/dts */
if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
pkt->dts != AV_NOPTS_VALUE &&
!(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) && /* VP9且不转码以外的条件 */
ost->last_mux_dts != AV_NOPTS_VALUE) {
/* AVFMT_TS_NONSTRICT:格式不需要严格增加时间戳,但它们仍然必须是单调的 */
// 包含该宏,max是last_mux_dts; 不包含,max是last_mux_dts+1.加1主要是确保单调递增.
int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
#ifdef TYYCODE_TIMESTAMP_MUXER
mydebug(NULL, AV_LOG_INFO, "write_packet(), --, "
"pkt->dts: %"PRId64", pkt->pts: %"PRId64", ost->last_mux_dts + 1: %"PRId64", ""max, "
"%"PRId64",output stream %d:%d\n",
pkt->dts, pkt->pts, ost->last_mux_dts + 1, max,
ost->file_index, ost->st->index);
#endif
if (pkt->dts < max) {
int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
av_log(s, loglevel, "Non-monotonous DTS in output stream "
"%d:%d; previous: %"PRId64", current: %"PRId64"; ",
ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);// dts没有单调递增
if (exit_on_error) {//-xerror选项,默认是0
av_log(NULL, AV_LOG_FATAL, "aborting.\n");
exit_program(1);
}
av_log(s, loglevel, "changing to %"PRId64". This may result "
"in incorrect timestamps in the output file.\n",
max);// (这可能会导致输出文件中的时间戳不正确)
#ifdef TYYCODE_TIMESTAMP_MUXER
mydebug(NULL, AV_LOG_INFO, "write_packet(), pkt->dts < max\n");
#endif
if (pkt->pts >= pkt->dts)
pkt->pts = FFMAX(pkt->pts, max);
pkt->dts = max;
}
}
}
ost->last_mux_dts = pkt->dts; // 保存最近一次有效的dts
ost->data_size += pkt->size; // 统计所有写入的包的字节大小
ost->packets_written++; // 统计所有写入的包的个数
pkt->stream_index = ost->index;
if (debug_ts) {// -debug_ts选项
av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
"pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
av_get_media_type_string(ost->enc_ctx->codec_type),
av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
pkt->size
);
}
// 7. 写帧
ret = av_interleaved_write_frame(s, pkt);
if (ret < 0) {
print_error("av_interleaved_write_frame()", ret);
main_return_code = 1;
close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
}
av_packet_unref(pkt);
}
/**
* @brief 给该输出流标记ENCODER_FINISHED.
* @param ost 输出流
*/
static void close_output_stream(OutputStream *ost)
{
OutputFile *of = output_files[ost->file_index];
ost->finished |= ENCODER_FINISHED;
if (of->shortest) {//重新设置录像时长.
int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
of->recording_time = FFMIN(of->recording_time, end);
}
}