avconv: split option parsing into a separate file.
[ffmpeg.git] / avconv.c
1 /*
2  * avconv main
3  * Copyright (c) 2000-2011 The libav developers.
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #include <ctype.h>
24 #include <string.h>
25 #include <math.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <signal.h>
29 #include <limits.h>
30 #include "libavformat/avformat.h"
31 #include "libavdevice/avdevice.h"
32 #include "libswscale/swscale.h"
33 #include "libavresample/avresample.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/audioconvert.h"
36 #include "libavutil/parseutils.h"
37 #include "libavutil/samplefmt.h"
38 #include "libavutil/colorspace.h"
39 #include "libavutil/fifo.h"
40 #include "libavutil/intreadwrite.h"
41 #include "libavutil/dict.h"
42 #include "libavutil/mathematics.h"
43 #include "libavutil/pixdesc.h"
44 #include "libavutil/avstring.h"
45 #include "libavutil/libm.h"
46 #include "libavutil/imgutils.h"
47 #include "libavutil/time.h"
48 #include "libavformat/os_support.h"
49
50 # include "libavfilter/avfilter.h"
51 # include "libavfilter/avfiltergraph.h"
52 # include "libavfilter/buffersrc.h"
53 # include "libavfilter/buffersink.h"
54
55 #if HAVE_SYS_RESOURCE_H
56 #include <sys/types.h>
57 #include <sys/resource.h>
58 #elif HAVE_GETPROCESSTIMES
59 #include <windows.h>
60 #endif
61 #if HAVE_GETPROCESSMEMORYINFO
62 #include <windows.h>
63 #include <psapi.h>
64 #endif
65
66 #if HAVE_SYS_SELECT_H
67 #include <sys/select.h>
68 #endif
69
70 #if HAVE_PTHREADS
71 #include <pthread.h>
72 #endif
73
74 #include <time.h>
75
76 #include "avconv.h"
77 #include "cmdutils.h"
78
79 #include "libavutil/avassert.h"
80
81 const char program_name[] = "avconv";
82 const int program_birth_year = 2000;
83
84 static FILE *vstats_file;
85
86 static int64_t video_size = 0;
87 static int64_t audio_size = 0;
88 static int64_t extra_size = 0;
89 static int nb_frames_dup = 0;
90 static int nb_frames_drop = 0;
91
92
93
94 #if HAVE_PTHREADS
95 /* signal to input threads that they should exit; set by the main thread */
96 static int transcoding_finished;
97 #endif
98
99 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
100
101 InputStream **input_streams = NULL;
102 int        nb_input_streams = 0;
103 InputFile   **input_files   = NULL;
104 int        nb_input_files   = 0;
105
106 OutputStream **output_streams = NULL;
107 int         nb_output_streams = 0;
108 OutputFile   **output_files   = NULL;
109 int         nb_output_files   = 0;
110
111 FilterGraph **filtergraphs;
112 int        nb_filtergraphs;
113
114 /**
115  * Define a function for building a string containing a list of
116  * allowed formats,
117  */
118 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name, separator) \
119 static char *choose_ ## var ## s(OutputStream *ost)                             \
120 {                                                                               \
121     if (ost->st->codec->var != none) {                                          \
122         get_name(ost->st->codec->var);                                          \
123         return av_strdup(name);                                                 \
124     } else if (ost->enc->supported_list) {                                      \
125         const type *p;                                                          \
126         AVIOContext *s = NULL;                                                  \
127         uint8_t *ret;                                                           \
128         int len;                                                                \
129                                                                                 \
130         if (avio_open_dyn_buf(&s) < 0)                                          \
131             exit_program(1);                                                    \
132                                                                                 \
133         for (p = ost->enc->supported_list; *p != none; p++) {                   \
134             get_name(*p);                                                       \
135             avio_printf(s, "%s" separator, name);                               \
136         }                                                                       \
137         len = avio_close_dyn_buf(s, &ret);                                      \
138         ret[len - 1] = 0;                                                       \
139         return ret;                                                             \
140     } else                                                                      \
141         return NULL;                                                            \
142 }
143
144 #define GET_PIX_FMT_NAME(pix_fmt)\
145     const char *name = av_get_pix_fmt_name(pix_fmt);
146
147 DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
148                   GET_PIX_FMT_NAME, ":")
149
150 #define GET_SAMPLE_FMT_NAME(sample_fmt)\
151     const char *name = av_get_sample_fmt_name(sample_fmt)
152
153 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
154                   AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME, ",")
155
156 #define GET_SAMPLE_RATE_NAME(rate)\
157     char name[16];\
158     snprintf(name, sizeof(name), "%d", rate);
159
160 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
161                   GET_SAMPLE_RATE_NAME, ",")
162
163 #define GET_CH_LAYOUT_NAME(ch_layout)\
164     char name[16];\
165     snprintf(name, sizeof(name), "0x%"PRIx64, ch_layout);
166
167 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
168                   GET_CH_LAYOUT_NAME, ",")
169
170 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
171 {
172     FilterGraph *fg = av_mallocz(sizeof(*fg));
173
174     if (!fg)
175         exit_program(1);
176     fg->index = nb_filtergraphs;
177
178     fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
179                              fg->nb_outputs + 1);
180     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
181         exit_program(1);
182     fg->outputs[0]->ost   = ost;
183     fg->outputs[0]->graph = fg;
184
185     ost->filter = fg->outputs[0];
186
187     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
188                             fg->nb_inputs + 1);
189     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
190         exit_program(1);
191     fg->inputs[0]->ist   = ist;
192     fg->inputs[0]->graph = fg;
193
194     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
195                               &ist->nb_filters, ist->nb_filters + 1);
196     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
197
198     filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
199                               &nb_filtergraphs, nb_filtergraphs + 1);
200     filtergraphs[nb_filtergraphs - 1] = fg;
201
202     return fg;
203 }
204
205 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
206 {
207     InputStream *ist = NULL;
208     enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
209     int i;
210
211     // TODO: support other filter types
212     if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
213         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
214                "currently.\n");
215         exit_program(1);
216     }
217
218     if (in->name) {
219         AVFormatContext *s;
220         AVStream       *st = NULL;
221         char *p;
222         int file_idx = strtol(in->name, &p, 0);
223
224         if (file_idx < 0 || file_idx >= nb_input_files) {
225             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
226                    file_idx, fg->graph_desc);
227             exit_program(1);
228         }
229         s = input_files[file_idx]->ctx;
230
231         for (i = 0; i < s->nb_streams; i++) {
232             if (s->streams[i]->codec->codec_type != type)
233                 continue;
234             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
235                 st = s->streams[i];
236                 break;
237             }
238         }
239         if (!st) {
240             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
241                    "matches no streams.\n", p, fg->graph_desc);
242             exit_program(1);
243         }
244         ist = input_streams[input_files[file_idx]->ist_index + st->index];
245     } else {
246         /* find the first unused stream of corresponding type */
247         for (i = 0; i < nb_input_streams; i++) {
248             ist = input_streams[i];
249             if (ist->st->codec->codec_type == type && ist->discard)
250                 break;
251         }
252         if (i == nb_input_streams) {
253             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
254                    "unlabeled input pad %d on filter %s", in->pad_idx,
255                    in->filter_ctx->name);
256             exit_program(1);
257         }
258     }
259     av_assert0(ist);
260
261     ist->discard         = 0;
262     ist->decoding_needed = 1;
263     ist->st->discard = AVDISCARD_NONE;
264
265     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
266                             &fg->nb_inputs, fg->nb_inputs + 1);
267     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
268         exit_program(1);
269     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
270     fg->inputs[fg->nb_inputs - 1]->graph = fg;
271
272     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
273                               &ist->nb_filters, ist->nb_filters + 1);
274     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
275 }
276
277 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
278 {
279     char *pix_fmts;
280     OutputStream *ost = ofilter->ost;
281     AVCodecContext *codec = ost->st->codec;
282     AVFilterContext *last_filter = out->filter_ctx;
283     int pad_idx = out->pad_idx;
284     int ret;
285     char name[255];
286
287     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
288     ret = avfilter_graph_create_filter(&ofilter->filter,
289                                        avfilter_get_by_name("buffersink"),
290                                        name, NULL, pix_fmts, fg->graph);
291     if (ret < 0)
292         return ret;
293
294     if (codec->width || codec->height) {
295         char args[255];
296         AVFilterContext *filter;
297
298         snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
299                  codec->width,
300                  codec->height,
301                  (unsigned)ost->sws_flags);
302         snprintf(name, sizeof(name), "scaler for output stream %d:%d",
303                  ost->file_index, ost->index);
304         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
305                                                 name, args, NULL, fg->graph)) < 0)
306             return ret;
307         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
308             return ret;
309
310         last_filter = filter;
311         pad_idx = 0;
312     }
313
314     if ((pix_fmts = choose_pix_fmts(ost))) {
315         AVFilterContext *filter;
316         snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
317                  ost->file_index, ost->index);
318         if ((ret = avfilter_graph_create_filter(&filter,
319                                                 avfilter_get_by_name("format"),
320                                                 "format", pix_fmts, NULL,
321                                                 fg->graph)) < 0)
322             return ret;
323         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
324             return ret;
325
326         last_filter = filter;
327         pad_idx     = 0;
328         av_freep(&pix_fmts);
329     }
330
331     if (ost->frame_rate.num) {
332         AVFilterContext *fps;
333         char args[255];
334
335         snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
336                  ost->frame_rate.den);
337         snprintf(name, sizeof(name), "fps for output stream %d:%d",
338                  ost->file_index, ost->index);
339         ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
340                                            name, args, NULL, fg->graph);
341         if (ret < 0)
342             return ret;
343
344         ret = avfilter_link(last_filter, pad_idx, fps, 0);
345         if (ret < 0)
346             return ret;
347         last_filter = fps;
348         pad_idx = 0;
349     }
350
351     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
352         return ret;
353
354     return 0;
355 }
356
357 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
358 {
359     OutputStream *ost = ofilter->ost;
360     AVCodecContext *codec  = ost->st->codec;
361     AVFilterContext *last_filter = out->filter_ctx;
362     int pad_idx = out->pad_idx;
363     char *sample_fmts, *sample_rates, *channel_layouts;
364     char name[255];
365     int ret;
366
367
368     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
369     ret = avfilter_graph_create_filter(&ofilter->filter,
370                                        avfilter_get_by_name("abuffersink"),
371                                        name, NULL, NULL, fg->graph);
372     if (ret < 0)
373         return ret;
374
375     if (codec->channels && !codec->channel_layout)
376         codec->channel_layout = av_get_default_channel_layout(codec->channels);
377
378     sample_fmts     = choose_sample_fmts(ost);
379     sample_rates    = choose_sample_rates(ost);
380     channel_layouts = choose_channel_layouts(ost);
381     if (sample_fmts || sample_rates || channel_layouts) {
382         AVFilterContext *format;
383         char args[256];
384         int len = 0;
385
386         if (sample_fmts)
387             len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
388                             sample_fmts);
389         if (sample_rates)
390             len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
391                             sample_rates);
392         if (channel_layouts)
393             len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
394                             channel_layouts);
395         args[len - 1] = 0;
396
397         av_freep(&sample_fmts);
398         av_freep(&sample_rates);
399         av_freep(&channel_layouts);
400
401         snprintf(name, sizeof(name), "audio format for output stream %d:%d",
402                  ost->file_index, ost->index);
403         ret = avfilter_graph_create_filter(&format,
404                                            avfilter_get_by_name("aformat"),
405                                            name, args, NULL, fg->graph);
406         if (ret < 0)
407             return ret;
408
409         ret = avfilter_link(last_filter, pad_idx, format, 0);
410         if (ret < 0)
411             return ret;
412
413         last_filter = format;
414         pad_idx = 0;
415     }
416
417     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
418         return ret;
419
420     return 0;
421 }
422
423 #define DESCRIBE_FILTER_LINK(f, inout, in)                         \
424 {                                                                  \
425     AVFilterContext *ctx = inout->filter_ctx;                      \
426     AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
427     int       nb_pads = in ? ctx->input_count : ctx->output_count; \
428     AVIOContext *pb;                                               \
429                                                                    \
430     if (avio_open_dyn_buf(&pb) < 0)                                \
431         exit_program(1);                                           \
432                                                                    \
433     avio_printf(pb, "%s", ctx->filter->name);                      \
434     if (nb_pads > 1)                                               \
435         avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
436     avio_w8(pb, 0);                                                \
437     avio_close_dyn_buf(pb, &f->name);                              \
438 }
439
440 int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
441 {
442     av_freep(&ofilter->name);
443     DESCRIBE_FILTER_LINK(ofilter, out, 0);
444
445     switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
446     case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
447     case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
448     default: av_assert0(0);
449     }
450 }
451
452 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
453                                         AVFilterInOut *in)
454 {
455     AVFilterContext *first_filter = in->filter_ctx;
456     AVFilter *filter = avfilter_get_by_name("buffer");
457     InputStream *ist = ifilter->ist;
458     AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :
459                                          ist->st->time_base;
460     AVRational sar;
461     char args[255], name[255];
462     int pad_idx = in->pad_idx;
463     int ret;
464
465     sar = ist->st->sample_aspect_ratio.num ?
466           ist->st->sample_aspect_ratio :
467           ist->st->codec->sample_aspect_ratio;
468     snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
469              ist->st->codec->height, ist->st->codec->pix_fmt,
470              tb.num, tb.den, sar.num, sar.den);
471     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
472              ist->file_index, ist->st->index);
473
474     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
475                                             args, NULL, fg->graph)) < 0)
476         return ret;
477
478     if (ist->framerate.num) {
479         AVFilterContext *setpts;
480
481         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
482                  ist->file_index, ist->st->index);
483         if ((ret = avfilter_graph_create_filter(&setpts,
484                                                 avfilter_get_by_name("setpts"),
485                                                 name, "N", NULL,
486                                                 fg->graph)) < 0)
487             return ret;
488
489         if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
490             return ret;
491
492         first_filter = setpts;
493         pad_idx = 0;
494     }
495
496     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
497         return ret;
498     return 0;
499 }
500
501 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
502                                         AVFilterInOut *in)
503 {
504     AVFilterContext *first_filter = in->filter_ctx;
505     AVFilter *filter = avfilter_get_by_name("abuffer");
506     InputStream *ist = ifilter->ist;
507     int pad_idx = in->pad_idx;
508     char args[255], name[255];
509     int ret;
510
511     snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"
512              ":channel_layout=0x%"PRIx64,
513              1, ist->st->codec->sample_rate,
514              ist->st->codec->sample_rate,
515              av_get_sample_fmt_name(ist->st->codec->sample_fmt),
516              ist->st->codec->channel_layout);
517     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
518              ist->file_index, ist->st->index);
519
520     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
521                                             name, args, NULL,
522                                             fg->graph)) < 0)
523         return ret;
524
525     if (audio_sync_method > 0) {
526         AVFilterContext *async;
527         char args[256];
528         int  len = 0;
529
530         av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
531                "asyncts audio filter instead.\n");
532
533         if (audio_sync_method > 1)
534             len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
535                             "max_comp=%d:", audio_sync_method);
536         snprintf(args + len, sizeof(args) - len, "min_delta=%f",
537                  audio_drift_threshold);
538
539         snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",
540                  fg->index, ist->file_index, ist->st->index);
541         ret = avfilter_graph_create_filter(&async,
542                                            avfilter_get_by_name("asyncts"),
543                                            name, args, NULL, fg->graph);
544         if (ret < 0)
545             return ret;
546
547         ret = avfilter_link(async, 0, first_filter, pad_idx);
548         if (ret < 0)
549             return ret;
550
551         first_filter = async;
552         pad_idx = 0;
553     }
554     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
555         return ret;
556
557     return 0;
558 }
559
560 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
561                                   AVFilterInOut *in)
562 {
563     av_freep(&ifilter->name);
564     DESCRIBE_FILTER_LINK(ifilter, in, 1);
565
566     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
567     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
568     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
569     default: av_assert0(0);
570     }
571 }
572
573 int configure_filtergraph(FilterGraph *fg)
574 {
575     AVFilterInOut *inputs, *outputs, *cur;
576     int ret, i, init = !fg->graph, simple = !fg->graph_desc;
577     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
578                                       fg->graph_desc;
579
580     avfilter_graph_free(&fg->graph);
581     if (!(fg->graph = avfilter_graph_alloc()))
582         return AVERROR(ENOMEM);
583
584     if (simple) {
585         OutputStream *ost = fg->outputs[0]->ost;
586         char args[255];
587         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
588         fg->graph->scale_sws_opts = av_strdup(args);
589     }
590
591     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
592         return ret;
593
594     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
595         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
596                "exactly one input and output.\n", graph_desc);
597         return AVERROR(EINVAL);
598     }
599
600     for (cur = inputs; !simple && init && cur; cur = cur->next)
601         init_input_filter(fg, cur);
602
603     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
604         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
605             return ret;
606     avfilter_inout_free(&inputs);
607
608     if (!init || simple) {
609         /* we already know the mappings between lavfi outputs and output streams,
610          * so we can finish the setup */
611         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
612             configure_output_filter(fg, fg->outputs[i], cur);
613         avfilter_inout_free(&outputs);
614
615         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
616             return ret;
617     } else {
618         /* wait until output mappings are processed */
619         for (cur = outputs; cur;) {
620             fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
621                                      &fg->nb_outputs, fg->nb_outputs + 1);
622             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
623                 exit_program(1);
624             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
625             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
626             cur = cur->next;
627             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
628         }
629     }
630
631     return 0;
632 }
633
634 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
635 {
636     int i;
637     for (i = 0; i < fg->nb_inputs; i++)
638         if (fg->inputs[i]->ist == ist)
639             return 1;
640     return 0;
641 }
642
643 static void term_exit(void)
644 {
645     av_log(NULL, AV_LOG_QUIET, "");
646 }
647
648 static volatile int received_sigterm = 0;
649 static volatile int received_nb_signals = 0;
650
651 static void
652 sigterm_handler(int sig)
653 {
654     received_sigterm = sig;
655     received_nb_signals++;
656     term_exit();
657 }
658
659 static void term_init(void)
660 {
661     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
662     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
663 #ifdef SIGXCPU
664     signal(SIGXCPU, sigterm_handler);
665 #endif
666 }
667
668 static int decode_interrupt_cb(void *ctx)
669 {
670     return received_nb_signals > 1;
671 }
672
673 const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
674
675 void exit_program(int ret)
676 {
677     int i, j;
678
679     for (i = 0; i < nb_filtergraphs; i++) {
680         avfilter_graph_free(&filtergraphs[i]->graph);
681         for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
682             av_freep(&filtergraphs[i]->inputs[j]->name);
683             av_freep(&filtergraphs[i]->inputs[j]);
684         }
685         av_freep(&filtergraphs[i]->inputs);
686         for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
687             av_freep(&filtergraphs[i]->outputs[j]->name);
688             av_freep(&filtergraphs[i]->outputs[j]);
689         }
690         av_freep(&filtergraphs[i]->outputs);
691         av_freep(&filtergraphs[i]);
692     }
693     av_freep(&filtergraphs);
694
695     /* close files */
696     for (i = 0; i < nb_output_files; i++) {
697         AVFormatContext *s = output_files[i]->ctx;
698         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
699             avio_close(s->pb);
700         avformat_free_context(s);
701         av_dict_free(&output_files[i]->opts);
702         av_freep(&output_files[i]);
703     }
704     for (i = 0; i < nb_output_streams; i++) {
705         AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
706         while (bsfc) {
707             AVBitStreamFilterContext *next = bsfc->next;
708             av_bitstream_filter_close(bsfc);
709             bsfc = next;
710         }
711         output_streams[i]->bitstream_filters = NULL;
712
713         av_freep(&output_streams[i]->forced_keyframes);
714         av_freep(&output_streams[i]->avfilter);
715         av_freep(&output_streams[i]->filtered_frame);
716         av_freep(&output_streams[i]);
717     }
718     for (i = 0; i < nb_input_files; i++) {
719         avformat_close_input(&input_files[i]->ctx);
720         av_freep(&input_files[i]);
721     }
722     for (i = 0; i < nb_input_streams; i++) {
723         av_freep(&input_streams[i]->decoded_frame);
724         av_dict_free(&input_streams[i]->opts);
725         free_buffer_pool(&input_streams[i]->buffer_pool);
726         av_freep(&input_streams[i]->filters);
727         av_freep(&input_streams[i]);
728     }
729
730     if (vstats_file)
731         fclose(vstats_file);
732     av_free(vstats_filename);
733
734     av_freep(&input_streams);
735     av_freep(&input_files);
736     av_freep(&output_streams);
737     av_freep(&output_files);
738
739     uninit_opts();
740
741     avfilter_uninit();
742     avformat_network_deinit();
743
744     if (received_sigterm) {
745         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
746                (int) received_sigterm);
747         exit (255);
748     }
749
750     exit(ret);
751 }
752
753 void assert_avoptions(AVDictionary *m)
754 {
755     AVDictionaryEntry *t;
756     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
757         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
758         exit_program(1);
759     }
760 }
761
762 static void assert_codec_experimental(AVCodecContext *c, int encoder)
763 {
764     const char *codec_string = encoder ? "encoder" : "decoder";
765     AVCodec *codec;
766     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
767         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
768         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
769                 "results.\nAdd '-strict experimental' if you want to use it.\n",
770                 codec_string, c->codec->name);
771         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
772         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
773             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
774                    codec_string, codec->name);
775         exit_program(1);
776     }
777 }
778
779 /**
780  * Update the requested input sample format based on the output sample format.
781  * This is currently only used to request float output from decoders which
782  * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
783  * Ideally this will be removed in the future when decoders do not do format
784  * conversion and only output in their native format.
785  */
786 static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
787                               AVCodecContext *enc)
788 {
789     /* if sample formats match or a decoder sample format has already been
790        requested, just return */
791     if (enc->sample_fmt == dec->sample_fmt ||
792         dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
793         return;
794
795     /* if decoder supports more than one output format */
796     if (dec_codec && dec_codec->sample_fmts &&
797         dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
798         dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
799         const enum AVSampleFormat *p;
800         int min_dec = -1, min_inc = -1;
801
802         /* find a matching sample format in the encoder */
803         for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
804             if (*p == enc->sample_fmt) {
805                 dec->request_sample_fmt = *p;
806                 return;
807             } else if (*p > enc->sample_fmt) {
808                 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
809             } else
810                 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
811         }
812
813         /* if none match, provide the one that matches quality closest */
814         dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
815                                   enc->sample_fmt - min_dec;
816     }
817 }
818
819 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
820 {
821     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
822     AVCodecContext          *avctx = ost->st->codec;
823     int ret;
824
825     /*
826      * Audio encoders may split the packets --  #frames in != #packets out.
827      * But there is no reordering, so we can limit the number of output packets
828      * by simply dropping them here.
829      * Counting encoded video frames needs to be done separately because of
830      * reordering, see do_video_out()
831      */
832     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
833         if (ost->frame_number >= ost->max_frames) {
834             av_free_packet(pkt);
835             return;
836         }
837         ost->frame_number++;
838     }
839
840     while (bsfc) {
841         AVPacket new_pkt = *pkt;
842         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
843                                            &new_pkt.data, &new_pkt.size,
844                                            pkt->data, pkt->size,
845                                            pkt->flags & AV_PKT_FLAG_KEY);
846         if (a > 0) {
847             av_free_packet(pkt);
848             new_pkt.destruct = av_destruct_packet;
849         } else if (a < 0) {
850             av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
851                    bsfc->filter->name, pkt->stream_index,
852                    avctx->codec ? avctx->codec->name : "copy");
853             print_error("", a);
854             if (exit_on_error)
855                 exit_program(1);
856         }
857         *pkt = new_pkt;
858
859         bsfc = bsfc->next;
860     }
861
862     pkt->stream_index = ost->index;
863     ret = av_interleaved_write_frame(s, pkt);
864     if (ret < 0) {
865         print_error("av_interleaved_write_frame()", ret);
866         exit_program(1);
867     }
868 }
869
870 static int check_recording_time(OutputStream *ost)
871 {
872     OutputFile *of = output_files[ost->file_index];
873
874     if (of->recording_time != INT64_MAX &&
875         av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
876                       AV_TIME_BASE_Q) >= 0) {
877         ost->is_past_recording_time = 1;
878         return 0;
879     }
880     return 1;
881 }
882
883 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
884                          AVFrame *frame)
885 {
886     AVCodecContext *enc = ost->st->codec;
887     AVPacket pkt;
888     int got_packet = 0;
889
890     av_init_packet(&pkt);
891     pkt.data = NULL;
892     pkt.size = 0;
893
894     if (!check_recording_time(ost))
895         return;
896
897     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
898         frame->pts = ost->sync_opts;
899     ost->sync_opts = frame->pts + frame->nb_samples;
900
901     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
902         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
903         exit_program(1);
904     }
905
906     if (got_packet) {
907         if (pkt.pts != AV_NOPTS_VALUE)
908             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
909         if (pkt.dts != AV_NOPTS_VALUE)
910             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
911         if (pkt.duration > 0)
912             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
913
914         write_frame(s, &pkt, ost);
915
916         audio_size += pkt.size;
917     }
918 }
919
920 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
921 {
922     AVCodecContext *dec;
923     AVPicture *picture2;
924     AVPicture picture_tmp;
925     uint8_t *buf = 0;
926
927     dec = ist->st->codec;
928
929     /* deinterlace : must be done before any resize */
930     if (do_deinterlace) {
931         int size;
932
933         /* create temporary picture */
934         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
935         buf  = av_malloc(size);
936         if (!buf)
937             return;
938
939         picture2 = &picture_tmp;
940         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
941
942         if (avpicture_deinterlace(picture2, picture,
943                                  dec->pix_fmt, dec->width, dec->height) < 0) {
944             /* if error, do not deinterlace */
945             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
946             av_free(buf);
947             buf = NULL;
948             picture2 = picture;
949         }
950     } else {
951         picture2 = picture;
952     }
953
954     if (picture != picture2)
955         *picture = *picture2;
956     *bufp = buf;
957 }
958
959 static void do_subtitle_out(AVFormatContext *s,
960                             OutputStream *ost,
961                             InputStream *ist,
962                             AVSubtitle *sub,
963                             int64_t pts)
964 {
965     static uint8_t *subtitle_out = NULL;
966     int subtitle_out_max_size = 1024 * 1024;
967     int subtitle_out_size, nb, i;
968     AVCodecContext *enc;
969     AVPacket pkt;
970
971     if (pts == AV_NOPTS_VALUE) {
972         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
973         if (exit_on_error)
974             exit_program(1);
975         return;
976     }
977
978     enc = ost->st->codec;
979
980     if (!subtitle_out) {
981         subtitle_out = av_malloc(subtitle_out_max_size);
982     }
983
984     /* Note: DVB subtitle need one packet to draw them and one other
985        packet to clear them */
986     /* XXX: signal it in the codec context ? */
987     if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
988         nb = 2;
989     else
990         nb = 1;
991
992     for (i = 0; i < nb; i++) {
993         ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
994         if (!check_recording_time(ost))
995             return;
996
997         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
998         // start_display_time is required to be 0
999         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1000         sub->end_display_time  -= sub->start_display_time;
1001         sub->start_display_time = 0;
1002         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1003                                                     subtitle_out_max_size, sub);
1004         if (subtitle_out_size < 0) {
1005             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1006             exit_program(1);
1007         }
1008
1009         av_init_packet(&pkt);
1010         pkt.data = subtitle_out;
1011         pkt.size = subtitle_out_size;
1012         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1013         if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1014             /* XXX: the pts correction is handled here. Maybe handling
1015                it in the codec would be better */
1016             if (i == 0)
1017                 pkt.pts += 90 * sub->start_display_time;
1018             else
1019                 pkt.pts += 90 * sub->end_display_time;
1020         }
1021         write_frame(s, &pkt, ost);
1022     }
1023 }
1024
1025 static void do_video_out(AVFormatContext *s,
1026                          OutputStream *ost,
1027                          AVFrame *in_picture,
1028                          int *frame_size, float quality)
1029 {
1030     int ret, format_video_sync;
1031     AVPacket pkt;
1032     AVCodecContext *enc = ost->st->codec;
1033
1034     *frame_size = 0;
1035
1036     format_video_sync = video_sync_method;
1037     if (format_video_sync == VSYNC_AUTO)
1038         format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
1039                             (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
1040     if (format_video_sync != VSYNC_PASSTHROUGH &&
1041         ost->frame_number &&
1042         in_picture->pts != AV_NOPTS_VALUE &&
1043         in_picture->pts < ost->sync_opts) {
1044         nb_frames_drop++;
1045         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1046         return;
1047     }
1048
1049     if (in_picture->pts == AV_NOPTS_VALUE)
1050         in_picture->pts = ost->sync_opts;
1051     ost->sync_opts = in_picture->pts;
1052
1053
1054     if (!ost->frame_number)
1055         ost->first_pts = in_picture->pts;
1056
1057     av_init_packet(&pkt);
1058     pkt.data = NULL;
1059     pkt.size = 0;
1060
1061     if (!check_recording_time(ost) ||
1062         ost->frame_number >= ost->max_frames)
1063         return;
1064
1065     if (s->oformat->flags & AVFMT_RAWPICTURE &&
1066         enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
1067         /* raw pictures are written as AVPicture structure to
1068            avoid any copies. We support temporarily the older
1069            method. */
1070         enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1071         enc->coded_frame->top_field_first  = in_picture->top_field_first;
1072         pkt.data   = (uint8_t *)in_picture;
1073         pkt.size   =  sizeof(AVPicture);
1074         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
1075         pkt.flags |= AV_PKT_FLAG_KEY;
1076
1077         write_frame(s, &pkt, ost);
1078     } else {
1079         int got_packet;
1080         AVFrame big_picture;
1081
1082         big_picture = *in_picture;
1083         /* better than nothing: use input picture interlaced
1084            settings */
1085         big_picture.interlaced_frame = in_picture->interlaced_frame;
1086         if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1087             if (ost->top_field_first == -1)
1088                 big_picture.top_field_first = in_picture->top_field_first;
1089             else
1090                 big_picture.top_field_first = !!ost->top_field_first;
1091         }
1092
1093         /* handles same_quant here. This is not correct because it may
1094            not be a global option */
1095         big_picture.quality = quality;
1096         if (!enc->me_threshold)
1097             big_picture.pict_type = 0;
1098         if (ost->forced_kf_index < ost->forced_kf_count &&
1099             big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1100             big_picture.pict_type = AV_PICTURE_TYPE_I;
1101             ost->forced_kf_index++;
1102         }
1103         ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
1104         if (ret < 0) {
1105             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1106             exit_program(1);
1107         }
1108
1109         if (got_packet) {
1110             if (pkt.pts != AV_NOPTS_VALUE)
1111                 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1112             if (pkt.dts != AV_NOPTS_VALUE)
1113                 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1114
1115             write_frame(s, &pkt, ost);
1116             *frame_size = pkt.size;
1117             video_size += pkt.size;
1118
1119             /* if two pass, output log */
1120             if (ost->logfile && enc->stats_out) {
1121                 fprintf(ost->logfile, "%s", enc->stats_out);
1122             }
1123         }
1124     }
1125     ost->sync_opts++;
1126     /*
1127      * For video, number of frames in == number of packets out.
1128      * But there may be reordering, so we can't throw away frames on encoder
1129      * flush, we need to limit them here, before they go into encoder.
1130      */
1131     ost->frame_number++;
1132 }
1133
1134 static double psnr(double d)
1135 {
1136     return -10.0 * log(d) / log(10.0);
1137 }
1138
1139 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1140                            int frame_size)
1141 {
1142     AVCodecContext *enc;
1143     int frame_number;
1144     double ti1, bitrate, avg_bitrate;
1145
1146     /* this is executed just the first time do_video_stats is called */
1147     if (!vstats_file) {
1148         vstats_file = fopen(vstats_filename, "w");
1149         if (!vstats_file) {
1150             perror("fopen");
1151             exit_program(1);
1152         }
1153     }
1154
1155     enc = ost->st->codec;
1156     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1157         frame_number = ost->frame_number;
1158         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1159         if (enc->flags&CODEC_FLAG_PSNR)
1160             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1161
1162         fprintf(vstats_file,"f_size= %6d ", frame_size);
1163         /* compute pts value */
1164         ti1 = ost->sync_opts * av_q2d(enc->time_base);
1165         if (ti1 < 0.01)
1166             ti1 = 0.01;
1167
1168         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1169         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1170         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1171                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1172         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1173     }
1174 }
1175
1176 /* check for new output on any of the filtergraphs */
1177 static int poll_filters(void)
1178 {
1179     AVFilterBufferRef *picref;
1180     AVFrame *filtered_frame = NULL;
1181     int i, frame_size;
1182
1183     for (i = 0; i < nb_output_streams; i++) {
1184         OutputStream *ost = output_streams[i];
1185         OutputFile    *of = output_files[ost->file_index];
1186         int ret = 0;
1187
1188         if (!ost->filter)
1189             continue;
1190
1191         if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1192             return AVERROR(ENOMEM);
1193         } else
1194             avcodec_get_frame_defaults(ost->filtered_frame);
1195         filtered_frame = ost->filtered_frame;
1196
1197         while (ret >= 0 && !ost->is_past_recording_time) {
1198             if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1199                 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1200                 ret = av_buffersink_read_samples(ost->filter->filter, &picref,
1201                                                  ost->st->codec->frame_size);
1202             else
1203                 ret = av_buffersink_read(ost->filter->filter, &picref);
1204
1205             if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
1206                 break;
1207             else if (ret < 0)
1208                 return ret;
1209
1210             avfilter_copy_buf_props(filtered_frame, picref);
1211             if (picref->pts != AV_NOPTS_VALUE) {
1212                 filtered_frame->pts = av_rescale_q(picref->pts,
1213                                                    ost->filter->filter->inputs[0]->time_base,
1214                                                    ost->st->codec->time_base) -
1215                                       av_rescale_q(of->start_time,
1216                                                    AV_TIME_BASE_Q,
1217                                                    ost->st->codec->time_base);
1218
1219                 if (of->start_time && filtered_frame->pts < 0) {
1220                     avfilter_unref_buffer(picref);
1221                     continue;
1222                 }
1223             }
1224
1225             switch (ost->filter->filter->inputs[0]->type) {
1226             case AVMEDIA_TYPE_VIDEO:
1227                 if (!ost->frame_aspect_ratio)
1228                     ost->st->codec->sample_aspect_ratio = picref->video->pixel_aspect;
1229
1230                 do_video_out(of->ctx, ost, filtered_frame, &frame_size,
1231                              same_quant ? ost->last_quality :
1232                                           ost->st->codec->global_quality);
1233                 if (vstats_filename && frame_size)
1234                     do_video_stats(of->ctx, ost, frame_size);
1235                 break;
1236             case AVMEDIA_TYPE_AUDIO:
1237                 do_audio_out(of->ctx, ost, filtered_frame);
1238                 break;
1239             default:
1240                 // TODO support subtitle filters
1241                 av_assert0(0);
1242             }
1243
1244             avfilter_unref_buffer(picref);
1245         }
1246     }
1247     return 0;
1248 }
1249
1250 static void print_report(int is_last_report, int64_t timer_start)
1251 {
1252     char buf[1024];
1253     OutputStream *ost;
1254     AVFormatContext *oc;
1255     int64_t total_size;
1256     AVCodecContext *enc;
1257     int frame_number, vid, i;
1258     double bitrate, ti1, pts;
1259     static int64_t last_time = -1;
1260     static int qp_histogram[52];
1261
1262     if (!print_stats && !is_last_report)
1263         return;
1264
1265     if (!is_last_report) {
1266         int64_t cur_time;
1267         /* display the report every 0.5 seconds */
1268         cur_time = av_gettime();
1269         if (last_time == -1) {
1270             last_time = cur_time;
1271             return;
1272         }
1273         if ((cur_time - last_time) < 500000)
1274             return;
1275         last_time = cur_time;
1276     }
1277
1278
1279     oc = output_files[0]->ctx;
1280
1281     total_size = avio_size(oc->pb);
1282     if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
1283         total_size = avio_tell(oc->pb);
1284
1285     buf[0] = '\0';
1286     ti1 = 1e10;
1287     vid = 0;
1288     for (i = 0; i < nb_output_streams; i++) {
1289         float q = -1;
1290         ost = output_streams[i];
1291         enc = ost->st->codec;
1292         if (!ost->stream_copy && enc->coded_frame)
1293             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1294         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1295             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1296         }
1297         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1298             float t = (av_gettime() - timer_start) / 1000000.0;
1299
1300             frame_number = ost->frame_number;
1301             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1302                      frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
1303             if (is_last_report)
1304                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1305             if (qp_hist) {
1306                 int j;
1307                 int qp = lrintf(q);
1308                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1309                     qp_histogram[qp]++;
1310                 for (j = 0; j < 32; j++)
1311                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1312             }
1313             if (enc->flags&CODEC_FLAG_PSNR) {
1314                 int j;
1315                 double error, error_sum = 0;
1316                 double scale, scale_sum = 0;
1317                 char type[3] = { 'Y','U','V' };
1318                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1319                 for (j = 0; j < 3; j++) {
1320                     if (is_last_report) {
1321                         error = enc->error[j];
1322                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1323                     } else {
1324                         error = enc->coded_frame->error[j];
1325                         scale = enc->width * enc->height * 255.0 * 255.0;
1326                     }
1327                     if (j)
1328                         scale /= 4;
1329                     error_sum += error;
1330                     scale_sum += scale;
1331                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1332                 }
1333                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1334             }
1335             vid = 1;
1336         }
1337         /* compute min output value */
1338         pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1339         if ((pts < ti1) && (pts > 0))
1340             ti1 = pts;
1341     }
1342     if (ti1 < 0.01)
1343         ti1 = 0.01;
1344
1345     bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1346
1347     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1348             "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1349             (double)total_size / 1024, ti1, bitrate);
1350
1351     if (nb_frames_dup || nb_frames_drop)
1352         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1353                 nb_frames_dup, nb_frames_drop);
1354
1355     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
1356
1357     fflush(stderr);
1358
1359     if (is_last_report) {
1360         int64_t raw= audio_size + video_size + extra_size;
1361         av_log(NULL, AV_LOG_INFO, "\n");
1362         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1363                video_size / 1024.0,
1364                audio_size / 1024.0,
1365                extra_size / 1024.0,
1366                100.0 * (total_size - raw) / raw
1367         );
1368     }
1369 }
1370
1371 static void flush_encoders(void)
1372 {
1373     int i, ret;
1374
1375     for (i = 0; i < nb_output_streams; i++) {
1376         OutputStream   *ost = output_streams[i];
1377         AVCodecContext *enc = ost->st->codec;
1378         AVFormatContext *os = output_files[ost->file_index]->ctx;
1379         int stop_encoding = 0;
1380
1381         if (!ost->encoding_needed)
1382             continue;
1383
1384         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1385             continue;
1386         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
1387             continue;
1388
1389         for (;;) {
1390             int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1391             const char *desc;
1392             int64_t *size;
1393
1394             switch (ost->st->codec->codec_type) {
1395             case AVMEDIA_TYPE_AUDIO:
1396                 encode = avcodec_encode_audio2;
1397                 desc   = "Audio";
1398                 size   = &audio_size;
1399                 break;
1400             case AVMEDIA_TYPE_VIDEO:
1401                 encode = avcodec_encode_video2;
1402                 desc   = "Video";
1403                 size   = &video_size;
1404                 break;
1405             default:
1406                 stop_encoding = 1;
1407             }
1408
1409             if (encode) {
1410                 AVPacket pkt;
1411                 int got_packet;
1412                 av_init_packet(&pkt);
1413                 pkt.data = NULL;
1414                 pkt.size = 0;
1415
1416                 ret = encode(enc, &pkt, NULL, &got_packet);
1417                 if (ret < 0) {
1418                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1419                     exit_program(1);
1420                 }
1421                 *size += ret;
1422                 if (ost->logfile && enc->stats_out) {
1423                     fprintf(ost->logfile, "%s", enc->stats_out);
1424                 }
1425                 if (!got_packet) {
1426                     stop_encoding = 1;
1427                     break;
1428                 }
1429                 if (pkt.pts != AV_NOPTS_VALUE)
1430                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1431                 if (pkt.dts != AV_NOPTS_VALUE)
1432                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1433                 write_frame(os, &pkt, ost);
1434             }
1435
1436             if (stop_encoding)
1437                 break;
1438         }
1439     }
1440 }
1441
1442 /*
1443  * Check whether a packet from ist should be written into ost at this time
1444  */
1445 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1446 {
1447     OutputFile *of = output_files[ost->file_index];
1448     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
1449
1450     if (ost->source_index != ist_index)
1451         return 0;
1452
1453     if (of->start_time && ist->last_dts < of->start_time)
1454         return 0;
1455
1456     return 1;
1457 }
1458
1459 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1460 {
1461     OutputFile *of = output_files[ost->file_index];
1462     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1463     AVPacket opkt;
1464
1465     av_init_packet(&opkt);
1466
1467     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1468         !ost->copy_initial_nonkeyframes)
1469         return;
1470
1471     if (of->recording_time != INT64_MAX &&
1472         ist->last_dts >= of->recording_time + of->start_time) {
1473         ost->is_past_recording_time = 1;
1474         return;
1475     }
1476
1477     /* force the input stream PTS */
1478     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1479         audio_size += pkt->size;
1480     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1481         video_size += pkt->size;
1482         ost->sync_opts++;
1483     }
1484
1485     if (pkt->pts != AV_NOPTS_VALUE)
1486         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1487     else
1488         opkt.pts = AV_NOPTS_VALUE;
1489
1490     if (pkt->dts == AV_NOPTS_VALUE)
1491         opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
1492     else
1493         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1494     opkt.dts -= ost_tb_start_time;
1495
1496     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1497     opkt.flags    = pkt->flags;
1498
1499     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1500     if (  ost->st->codec->codec_id != AV_CODEC_ID_H264
1501        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
1502        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
1503        && ost->st->codec->codec_id != AV_CODEC_ID_VC1
1504        ) {
1505         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1506             opkt.destruct = av_destruct_packet;
1507     } else {
1508         opkt.data = pkt->data;
1509         opkt.size = pkt->size;
1510     }
1511
1512     write_frame(of->ctx, &opkt, ost);
1513     ost->st->codec->frame_number++;
1514     av_free_packet(&opkt);
1515 }
1516
1517 static void rate_emu_sleep(InputStream *ist)
1518 {
1519     if (input_files[ist->file_index]->rate_emu) {
1520         int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
1521         int64_t now = av_gettime() - ist->start;
1522         if (pts > now)
1523             av_usleep(pts - now);
1524     }
1525 }
1526
1527 int guess_input_channel_layout(InputStream *ist)
1528 {
1529     AVCodecContext *dec = ist->st->codec;
1530
1531     if (!dec->channel_layout) {
1532         char layout_name[256];
1533
1534         dec->channel_layout = av_get_default_channel_layout(dec->channels);
1535         if (!dec->channel_layout)
1536             return 0;
1537         av_get_channel_layout_string(layout_name, sizeof(layout_name),
1538                                      dec->channels, dec->channel_layout);
1539         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
1540                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1541     }
1542     return 1;
1543 }
1544
1545 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1546 {
1547     AVFrame *decoded_frame;
1548     AVCodecContext *avctx = ist->st->codec;
1549     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1550     int i, ret, resample_changed;
1551
1552     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1553         return AVERROR(ENOMEM);
1554     else
1555         avcodec_get_frame_defaults(ist->decoded_frame);
1556     decoded_frame = ist->decoded_frame;
1557
1558     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1559     if (ret < 0) {
1560         return ret;
1561     }
1562
1563     if (!*got_output) {
1564         /* no audio frame */
1565         if (!pkt->size)
1566             for (i = 0; i < ist->nb_filters; i++)
1567                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
1568         return ret;
1569     }
1570
1571     /* if the decoder provides a pts, use it instead of the last packet pts.
1572        the decoder could be delaying output by a packet or more. */
1573     if (decoded_frame->pts != AV_NOPTS_VALUE)
1574         ist->next_dts = decoded_frame->pts;
1575     else if (pkt->pts != AV_NOPTS_VALUE) {
1576         decoded_frame->pts = pkt->pts;
1577         pkt->pts           = AV_NOPTS_VALUE;
1578     }
1579
1580     // preprocess audio (volume)
1581     if (audio_volume != 256) {
1582         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1583         void *samples = decoded_frame->data[0];
1584         switch (avctx->sample_fmt) {
1585         case AV_SAMPLE_FMT_U8:
1586         {
1587             uint8_t *volp = samples;
1588             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1589                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1590                 *volp++ = av_clip_uint8(v);
1591             }
1592             break;
1593         }
1594         case AV_SAMPLE_FMT_S16:
1595         {
1596             int16_t *volp = samples;
1597             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1598                 int v = ((*volp) * audio_volume + 128) >> 8;
1599                 *volp++ = av_clip_int16(v);
1600             }
1601             break;
1602         }
1603         case AV_SAMPLE_FMT_S32:
1604         {
1605             int32_t *volp = samples;
1606             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1607                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1608                 *volp++ = av_clipl_int32(v);
1609             }
1610             break;
1611         }
1612         case AV_SAMPLE_FMT_FLT:
1613         {
1614             float *volp = samples;
1615             float scale = audio_volume / 256.f;
1616             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1617                 *volp++ *= scale;
1618             }
1619             break;
1620         }
1621         case AV_SAMPLE_FMT_DBL:
1622         {
1623             double *volp = samples;
1624             double scale = audio_volume / 256.;
1625             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1626                 *volp++ *= scale;
1627             }
1628             break;
1629         }
1630         default:
1631             av_log(NULL, AV_LOG_FATAL,
1632                    "Audio volume adjustment on sample format %s is not supported.\n",
1633                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1634             exit_program(1);
1635         }
1636     }
1637
1638     rate_emu_sleep(ist);
1639
1640     resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
1641                        ist->resample_channels       != avctx->channels               ||
1642                        ist->resample_channel_layout != decoded_frame->channel_layout ||
1643                        ist->resample_sample_rate    != decoded_frame->sample_rate;
1644     if (resample_changed) {
1645         char layout1[64], layout2[64];
1646
1647         if (!guess_input_channel_layout(ist)) {
1648             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1649                    "layout for Input Stream #%d.%d\n", ist->file_index,
1650                    ist->st->index);
1651             exit_program(1);
1652         }
1653         decoded_frame->channel_layout = avctx->channel_layout;
1654
1655         av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1656                                      ist->resample_channel_layout);
1657         av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1658                                      decoded_frame->channel_layout);
1659
1660         av_log(NULL, AV_LOG_INFO,
1661                "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
1662                ist->file_index, ist->st->index,
1663                ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
1664                ist->resample_channels, layout1,
1665                decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1666                avctx->channels, layout2);
1667
1668         ist->resample_sample_fmt     = decoded_frame->format;
1669         ist->resample_sample_rate    = decoded_frame->sample_rate;
1670         ist->resample_channel_layout = decoded_frame->channel_layout;
1671         ist->resample_channels       = avctx->channels;
1672
1673         for (i = 0; i < nb_filtergraphs; i++)
1674             if (ist_in_filtergraph(filtergraphs[i], ist) &&
1675                 configure_filtergraph(filtergraphs[i]) < 0) {
1676                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1677                 exit_program(1);
1678             }
1679     }
1680
1681     if (decoded_frame->pts != AV_NOPTS_VALUE)
1682         decoded_frame->pts = av_rescale_q(decoded_frame->pts,
1683                                           ist->st->time_base,
1684                                           (AVRational){1, ist->st->codec->sample_rate});
1685     for (i = 0; i < ist->nb_filters; i++)
1686         av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
1687
1688     return ret;
1689 }
1690
1691 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1692 {
1693     AVFrame *decoded_frame;
1694     void *buffer_to_free = NULL;
1695     int i, ret = 0, resample_changed;
1696     float quality;
1697
1698     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1699         return AVERROR(ENOMEM);
1700     else
1701         avcodec_get_frame_defaults(ist->decoded_frame);
1702     decoded_frame = ist->decoded_frame;
1703
1704     ret = avcodec_decode_video2(ist->st->codec,
1705                                 decoded_frame, got_output, pkt);
1706     if (ret < 0)
1707         return ret;
1708
1709     quality = same_quant ? decoded_frame->quality : 0;
1710     if (!*got_output) {
1711         /* no picture yet */
1712         if (!pkt->size)
1713             for (i = 0; i < ist->nb_filters; i++)
1714                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
1715         return ret;
1716     }
1717     decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
1718                                            decoded_frame->pkt_dts);
1719     pkt->size = 0;
1720     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1721
1722     rate_emu_sleep(ist);
1723
1724     if (ist->st->sample_aspect_ratio.num)
1725         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1726
1727     resample_changed = ist->resample_width   != decoded_frame->width  ||
1728                        ist->resample_height  != decoded_frame->height ||
1729                        ist->resample_pix_fmt != decoded_frame->format;
1730     if (resample_changed) {
1731         av_log(NULL, AV_LOG_INFO,
1732                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1733                ist->file_index, ist->st->index,
1734                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
1735                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1736
1737         ist->resample_width   = decoded_frame->width;
1738         ist->resample_height  = decoded_frame->height;
1739         ist->resample_pix_fmt = decoded_frame->format;
1740
1741         for (i = 0; i < nb_filtergraphs; i++)
1742             if (ist_in_filtergraph(filtergraphs[i], ist) &&
1743                 configure_filtergraph(filtergraphs[i]) < 0) {
1744                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1745                 exit_program(1);
1746             }
1747     }
1748
1749     for (i = 0; i < ist->nb_filters; i++) {
1750         // XXX what an ugly hack
1751         if (ist->filters[i]->graph->nb_outputs == 1)
1752             ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
1753
1754         if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
1755             FrameBuffer      *buf = decoded_frame->opaque;
1756             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
1757                                         decoded_frame->data, decoded_frame->linesize,
1758                                         AV_PERM_READ | AV_PERM_PRESERVE,
1759                                         ist->st->codec->width, ist->st->codec->height,
1760                                         ist->st->codec->pix_fmt);
1761
1762             avfilter_copy_frame_props(fb, decoded_frame);
1763             fb->buf->priv           = buf;
1764             fb->buf->free           = filter_release_buffer;
1765
1766             buf->refcount++;
1767             av_buffersrc_buffer(ist->filters[i]->filter, fb);
1768         } else
1769             av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
1770     }
1771
1772     av_free(buffer_to_free);
1773     return ret;
1774 }
1775
1776 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1777 {
1778     AVSubtitle subtitle;
1779     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1780                                           &subtitle, got_output, pkt);
1781     if (ret < 0)
1782         return ret;
1783     if (!*got_output)
1784         return ret;
1785
1786     rate_emu_sleep(ist);
1787
1788     for (i = 0; i < nb_output_streams; i++) {
1789         OutputStream *ost = output_streams[i];
1790
1791         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1792             continue;
1793
1794         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
1795     }
1796
1797     avsubtitle_free(&subtitle);
1798     return ret;
1799 }
1800
1801 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1802 static int output_packet(InputStream *ist, const AVPacket *pkt)
1803 {
1804     int i;
1805     int got_output;
1806     AVPacket avpkt;
1807
1808     if (ist->next_dts == AV_NOPTS_VALUE)
1809         ist->next_dts = ist->last_dts;
1810
1811     if (pkt == NULL) {
1812         /* EOF handling */
1813         av_init_packet(&avpkt);
1814         avpkt.data = NULL;
1815         avpkt.size = 0;
1816         goto handle_eof;
1817     } else {
1818         avpkt = *pkt;
1819     }
1820
1821     if (pkt->dts != AV_NOPTS_VALUE)
1822         ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1823
1824     // while we have more to decode or while the decoder did output something on EOF
1825     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1826         int ret = 0;
1827     handle_eof:
1828
1829         ist->last_dts = ist->next_dts;
1830
1831         if (avpkt.size && avpkt.size != pkt->size) {
1832             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1833                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1834             ist->showed_multi_packet_warning = 1;
1835         }
1836
1837         switch (ist->st->codec->codec_type) {
1838         case AVMEDIA_TYPE_AUDIO:
1839             ret = decode_audio    (ist, &avpkt, &got_output);
1840             break;
1841         case AVMEDIA_TYPE_VIDEO:
1842             ret = decode_video    (ist, &avpkt, &got_output);
1843             if (avpkt.duration)
1844                 ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1845             else if (ist->st->avg_frame_rate.num)
1846                 ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
1847                                               AV_TIME_BASE_Q);
1848             else if (ist->st->codec->time_base.num != 0) {
1849                 int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1850                                                    ist->st->codec->ticks_per_frame;
1851                 ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
1852             }
1853             break;
1854         case AVMEDIA_TYPE_SUBTITLE:
1855             ret = transcode_subtitles(ist, &avpkt, &got_output);
1856             break;
1857         default:
1858             return -1;
1859         }
1860
1861         if (ret < 0)
1862             return ret;
1863         // touch data and size only if not EOF
1864         if (pkt) {
1865             avpkt.data += ret;
1866             avpkt.size -= ret;
1867         }
1868         if (!got_output) {
1869             continue;
1870         }
1871     }
1872
1873     /* handle stream copy */
1874     if (!ist->decoding_needed) {
1875         rate_emu_sleep(ist);
1876         ist->last_dts = ist->next_dts;
1877         switch (ist->st->codec->codec_type) {
1878         case AVMEDIA_TYPE_AUDIO:
1879             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1880                              ist->st->codec->sample_rate;
1881             break;
1882         case AVMEDIA_TYPE_VIDEO:
1883             if (ist->st->codec->time_base.num != 0) {
1884                 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
1885                 ist->next_dts += ((int64_t)AV_TIME_BASE *
1886                                   ist->st->codec->time_base.num * ticks) /
1887                                   ist->st->codec->time_base.den;
1888             }
1889             break;
1890         }
1891     }
1892     for (i = 0; pkt && i < nb_output_streams; i++) {
1893         OutputStream *ost = output_streams[i];
1894
1895         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1896             continue;
1897
1898         do_streamcopy(ist, ost, pkt);
1899     }
1900
1901     return 0;
1902 }
1903
1904 static void print_sdp(void)
1905 {
1906     char sdp[2048];
1907     int i;
1908     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1909
1910     if (!avc)
1911         exit_program(1);
1912     for (i = 0; i < nb_output_files; i++)
1913         avc[i] = output_files[i]->ctx;
1914
1915     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1916     printf("SDP:\n%s\n", sdp);
1917     fflush(stdout);
1918     av_freep(&avc);
1919 }
1920
1921 static int init_input_stream(int ist_index, char *error, int error_len)
1922 {
1923     int i;
1924     InputStream *ist = input_streams[ist_index];
1925     if (ist->decoding_needed) {
1926         AVCodec *codec = ist->dec;
1927         if (!codec) {
1928             snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
1929                     ist->st->codec->codec_id, ist->file_index, ist->st->index);
1930             return AVERROR(EINVAL);
1931         }
1932
1933         /* update requested sample format for the decoder based on the
1934            corresponding encoder sample format */
1935         for (i = 0; i < nb_output_streams; i++) {
1936             OutputStream *ost = output_streams[i];
1937             if (ost->source_index == ist_index) {
1938                 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
1939                 break;
1940             }
1941         }
1942
1943         if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
1944             ist->st->codec->get_buffer     = codec_get_buffer;
1945             ist->st->codec->release_buffer = codec_release_buffer;
1946             ist->st->codec->opaque         = &ist->buffer_pool;
1947         }
1948
1949         if (!av_dict_get(ist->opts, "threads", NULL, 0))
1950             av_dict_set(&ist->opts, "threads", "auto", 0);
1951         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
1952             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
1953                     ist->file_index, ist->st->index);
1954             return AVERROR(EINVAL);
1955         }
1956         assert_codec_experimental(ist->st->codec, 0);
1957         assert_avoptions(ist->opts);
1958     }
1959
1960     ist->last_dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1961     ist->next_dts = AV_NOPTS_VALUE;
1962     init_pts_correction(&ist->pts_ctx);
1963     ist->is_start = 1;
1964
1965     return 0;
1966 }
1967
1968 static InputStream *get_input_stream(OutputStream *ost)
1969 {
1970     if (ost->source_index >= 0)
1971         return input_streams[ost->source_index];
1972
1973     if (ost->filter) {
1974         FilterGraph *fg = ost->filter->graph;
1975         int i;
1976
1977         for (i = 0; i < fg->nb_inputs; i++)
1978             if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
1979                 return fg->inputs[i]->ist;
1980     }
1981
1982     return NULL;
1983 }
1984
1985 static void parse_forced_key_frames(char *kf, OutputStream *ost,
1986                                     AVCodecContext *avctx)
1987 {
1988     char *p;
1989     int n = 1, i;
1990     int64_t t;
1991
1992     for (p = kf; *p; p++)
1993         if (*p == ',')
1994             n++;
1995     ost->forced_kf_count = n;
1996     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1997     if (!ost->forced_kf_pts) {
1998         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
1999         exit_program(1);
2000     }
2001
2002     p = kf;
2003     for (i = 0; i < n; i++) {
2004         char *next = strchr(p, ',');
2005
2006         if (next)
2007             *next++ = 0;
2008
2009         t = parse_time_or_die("force_key_frames", p, 1);
2010         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2011
2012         p = next;
2013     }
2014 }
2015
2016 static int transcode_init(void)
2017 {
2018     int ret = 0, i, j, k;
2019     AVFormatContext *oc;
2020     AVCodecContext *codec, *icodec;
2021     OutputStream *ost;
2022     InputStream *ist;
2023     char error[1024];
2024     int want_sdp = 1;
2025
2026     /* init framerate emulation */
2027     for (i = 0; i < nb_input_files; i++) {
2028         InputFile *ifile = input_files[i];
2029         if (ifile->rate_emu)
2030             for (j = 0; j < ifile->nb_streams; j++)
2031                 input_streams[j + ifile->ist_index]->start = av_gettime();
2032     }
2033
2034     /* output stream init */
2035     for (i = 0; i < nb_output_files; i++) {
2036         oc = output_files[i]->ctx;
2037         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2038             av_dump_format(oc, i, oc->filename, 1);
2039             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2040             return AVERROR(EINVAL);
2041         }
2042     }
2043
2044     /* init complex filtergraphs */
2045     for (i = 0; i < nb_filtergraphs; i++)
2046         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2047             return ret;
2048
2049     /* for each output stream, we compute the right encoding parameters */
2050     for (i = 0; i < nb_output_streams; i++) {
2051         ost = output_streams[i];
2052         oc  = output_files[ost->file_index]->ctx;
2053         ist = get_input_stream(ost);
2054
2055         if (ost->attachment_filename)
2056             continue;
2057
2058         codec  = ost->st->codec;
2059
2060         if (ist) {
2061             icodec = ist->st->codec;
2062
2063             ost->st->disposition          = ist->st->disposition;
2064             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2065             codec->chroma_sample_location = icodec->chroma_sample_location;
2066         }
2067
2068         if (ost->stream_copy) {
2069             uint64_t extra_size;
2070
2071             av_assert0(ist && !ost->filter);
2072
2073             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2074
2075             if (extra_size > INT_MAX) {
2076                 return AVERROR(EINVAL);
2077             }
2078
2079             /* if stream_copy is selected, no need to decode or encode */
2080             codec->codec_id   = icodec->codec_id;
2081             codec->codec_type = icodec->codec_type;
2082
2083             if (!codec->codec_tag) {
2084                 if (!oc->oformat->codec_tag ||
2085                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2086                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2087                     codec->codec_tag = icodec->codec_tag;
2088             }
2089
2090             codec->bit_rate       = icodec->bit_rate;
2091             codec->rc_max_rate    = icodec->rc_max_rate;
2092             codec->rc_buffer_size = icodec->rc_buffer_size;
2093             codec->field_order    = icodec->field_order;
2094             codec->extradata      = av_mallocz(extra_size);
2095             if (!codec->extradata) {
2096                 return AVERROR(ENOMEM);
2097             }
2098             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2099             codec->extradata_size = icodec->extradata_size;
2100             if (!copy_tb) {
2101                 codec->time_base      = icodec->time_base;
2102                 codec->time_base.num *= icodec->ticks_per_frame;
2103                 av_reduce(&codec->time_base.num, &codec->time_base.den,
2104                           codec->time_base.num, codec->time_base.den, INT_MAX);
2105             } else
2106                 codec->time_base = ist->st->time_base;
2107
2108             switch (codec->codec_type) {
2109             case AVMEDIA_TYPE_AUDIO:
2110                 if (audio_volume != 256) {
2111                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2112                     exit_program(1);
2113                 }
2114                 codec->channel_layout     = icodec->channel_layout;
2115                 codec->sample_rate        = icodec->sample_rate;
2116                 codec->channels           = icodec->channels;
2117                 codec->frame_size         = icodec->frame_size;
2118                 codec->audio_service_type = icodec->audio_service_type;
2119                 codec->block_align        = icodec->block_align;
2120                 break;
2121             case AVMEDIA_TYPE_VIDEO:
2122                 codec->pix_fmt            = icodec->pix_fmt;
2123                 codec->width              = icodec->width;
2124                 codec->height             = icodec->height;
2125                 codec->has_b_frames       = icodec->has_b_frames;
2126                 if (!codec->sample_aspect_ratio.num) {
2127                     codec->sample_aspect_ratio   =
2128                     ost->st->sample_aspect_ratio =
2129                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2130                         ist->st->codec->sample_aspect_ratio.num ?
2131                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2132                 }
2133                 break;
2134             case AVMEDIA_TYPE_SUBTITLE:
2135                 codec->width  = icodec->width;
2136                 codec->height = icodec->height;
2137                 break;
2138             case AVMEDIA_TYPE_DATA:
2139             case AVMEDIA_TYPE_ATTACHMENT:
2140                 break;
2141             default:
2142                 abort();
2143             }
2144         } else {
2145             if (!ost->enc) {
2146                 /* should only happen when a default codec is not present. */
2147                 snprintf(error, sizeof(error), "Automatic encoder selection "
2148                          "failed for output stream #%d:%d. Default encoder for "
2149                          "format %s is probably disabled. Please choose an "
2150                          "encoder manually.\n", ost->file_index, ost->index,
2151                          oc->oformat->name);
2152                 ret = AVERROR(EINVAL);
2153                 goto dump_format;
2154             }
2155
2156             if (ist)
2157                 ist->decoding_needed = 1;
2158             ost->encoding_needed = 1;
2159
2160             /*
2161              * We want CFR output if and only if one of those is true:
2162              * 1) user specified output framerate with -r
2163              * 2) user specified -vsync cfr
2164              * 3) output format is CFR and the user didn't force vsync to
2165              *    something else than CFR
2166              *
2167              * in such a case, set ost->frame_rate
2168              */
2169             if (codec->codec_type == AVMEDIA_TYPE_VIDEO &&
2170                 !ost->frame_rate.num && ist &&
2171                 (video_sync_method ==  VSYNC_CFR ||
2172                  (video_sync_method ==  VSYNC_AUTO &&
2173                   !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
2174                 ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
2175                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2176                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2177                     ost->frame_rate = ost->enc->supported_framerates[idx];
2178                 }
2179             }
2180
2181             if (!ost->filter &&
2182                 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2183                  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2184                     FilterGraph *fg;
2185                     fg = init_simple_filtergraph(ist, ost);
2186                     if (configure_filtergraph(fg)) {
2187                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2188                         exit(1);
2189                     }
2190             }
2191
2192             switch (codec->codec_type) {
2193             case AVMEDIA_TYPE_AUDIO:
2194                 codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
2195                 codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
2196                 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2197                 codec->channels       = av_get_channel_layout_nb_channels(codec->channel_layout);
2198                 codec->time_base      = (AVRational){ 1, codec->sample_rate };
2199                 break;
2200             case AVMEDIA_TYPE_VIDEO:
2201                 codec->time_base = ost->filter->filter->inputs[0]->time_base;
2202
2203                 codec->width  = ost->filter->filter->inputs[0]->w;
2204                 codec->height = ost->filter->filter->inputs[0]->h;
2205                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2206                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2207                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2208                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
2209                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2210
2211                 if (codec->width   != icodec->width  ||
2212                     codec->height  != icodec->height ||
2213                     codec->pix_fmt != icodec->pix_fmt) {
2214                     codec->bits_per_raw_sample = 0;
2215                 }
2216
2217                 if (ost->forced_keyframes)
2218                     parse_forced_key_frames(ost->forced_keyframes, ost,
2219                                             ost->st->codec);
2220                 break;
2221             case AVMEDIA_TYPE_SUBTITLE:
2222                 codec->time_base = (AVRational){1, 1000};
2223                 break;
2224             default:
2225                 abort();
2226                 break;
2227             }
2228             /* two pass mode */
2229             if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2230                 char logfilename[1024];
2231                 FILE *f;
2232
2233                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2234                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2235                          i);
2236                 if (!strcmp(ost->enc->name, "libx264")) {
2237                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2238                 } else {
2239                     if (codec->flags & CODEC_FLAG_PASS1) {
2240                         f = fopen(logfilename, "wb");
2241                         if (!f) {
2242                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2243                                    logfilename, strerror(errno));
2244                             exit_program(1);
2245                         }
2246                         ost->logfile = f;
2247                     } else {
2248                         char  *logbuffer;
2249                         size_t logbuffer_size;
2250                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2251                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2252                                    logfilename);
2253                             exit_program(1);
2254                         }
2255                         codec->stats_in = logbuffer;
2256                     }
2257                 }
2258             }
2259         }
2260     }
2261
2262     /* open each encoder */
2263     for (i = 0; i < nb_output_streams; i++) {
2264         ost = output_streams[i];
2265         if (ost->encoding_needed) {
2266             AVCodec      *codec = ost->enc;
2267             AVCodecContext *dec = NULL;
2268
2269             if ((ist = get_input_stream(ost)))
2270                 dec = ist->st->codec;
2271             if (dec && dec->subtitle_header) {
2272                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2273                 if (!ost->st->codec->subtitle_header) {
2274                     ret = AVERROR(ENOMEM);
2275                     goto dump_format;
2276                 }
2277                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2278                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2279             }
2280             if (!av_dict_get(ost->opts, "threads", NULL, 0))
2281                 av_dict_set(&ost->opts, "threads", "auto", 0);
2282             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2283                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2284                         ost->file_index, ost->index);
2285                 ret = AVERROR(EINVAL);
2286                 goto dump_format;
2287             }
2288             assert_codec_experimental(ost->st->codec, 1);
2289             assert_avoptions(ost->opts);
2290             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2291                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2292                                              "It takes bits/s as argument, not kbits/s\n");
2293             extra_size += ost->st->codec->extradata_size;
2294
2295             if (ost->st->codec->me_threshold)
2296                 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2297         }
2298     }
2299
2300     /* init input streams */
2301     for (i = 0; i < nb_input_streams; i++)
2302         if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
2303             goto dump_format;
2304
2305     /* discard unused programs */
2306     for (i = 0; i < nb_input_files; i++) {
2307         InputFile *ifile = input_files[i];
2308         for (j = 0; j < ifile->ctx->nb_programs; j++) {
2309             AVProgram *p = ifile->ctx->programs[j];
2310             int discard  = AVDISCARD_ALL;
2311
2312             for (k = 0; k < p->nb_stream_indexes; k++)
2313                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2314                     discard = AVDISCARD_DEFAULT;
2315                     break;
2316                 }
2317             p->discard = discard;
2318         }
2319     }
2320
2321     /* open files and write file headers */
2322     for (i = 0; i < nb_output_files; i++) {
2323         oc = output_files[i]->ctx;
2324         oc->interrupt_callback = int_cb;
2325         if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2326             char errbuf[128];
2327             const char *errbuf_ptr = errbuf;
2328             if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
2329                 errbuf_ptr = strerror(AVUNERROR(ret));
2330             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
2331             ret = AVERROR(EINVAL);
2332             goto dump_format;
2333         }
2334         assert_avoptions(output_files[i]->opts);
2335         if (strcmp(oc->oformat->name, "rtp")) {
2336             want_sdp = 0;
2337         }
2338     }
2339
2340  dump_format:
2341     /* dump the file output parameters - cannot be done before in case
2342        of stream copy */
2343     for (i = 0; i < nb_output_files; i++) {
2344         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2345     }
2346
2347     /* dump the stream mapping */
2348     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2349     for (i = 0; i < nb_input_streams; i++) {
2350         ist = input_streams[i];
2351
2352         for (j = 0; j < ist->nb_filters; j++) {
2353             if (ist->filters[j]->graph->graph_desc) {
2354                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
2355                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2356                        ist->filters[j]->name);
2357                 if (nb_filtergraphs > 1)
2358                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2359                 av_log(NULL, AV_LOG_INFO, "\n");
2360             }
2361         }
2362     }
2363
2364     for (i = 0; i < nb_output_streams; i++) {
2365         ost = output_streams[i];
2366
2367         if (ost->attachment_filename) {
2368             /* an attached file */
2369             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
2370                    ost->attachment_filename, ost->file_index, ost->index);
2371             continue;
2372         }
2373
2374         if (ost->filter && ost->filter->graph->graph_desc) {
2375             /* output from a complex graph */
2376             av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
2377             if (nb_filtergraphs > 1)
2378                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2379
2380             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2381                    ost->index, ost->enc ? ost->enc->name : "?");
2382             continue;
2383         }
2384
2385         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
2386                input_streams[ost->source_index]->file_index,
2387                input_streams[ost->source_index]->st->index,
2388                ost->file_index,
2389                ost->index);
2390         if (ost->sync_ist != input_streams[ost->source_index])
2391             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2392                    ost->sync_ist->file_index,
2393                    ost->sync_ist->st->index);
2394         if (ost->stream_copy)
2395             av_log(NULL, AV_LOG_INFO, " (copy)");
2396         else
2397             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2398                    input_streams[ost->source_index]->dec->name : "?",
2399                    ost->enc ? ost->enc->name : "?");
2400         av_log(NULL, AV_LOG_INFO, "\n");
2401     }
2402
2403     if (ret) {
2404         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2405         return ret;
2406     }
2407
2408     if (want_sdp) {
2409         print_sdp();
2410     }
2411
2412     return 0;
2413 }
2414
2415 /**
2416  * @return 1 if there are still streams where more output is wanted,
2417  *         0 otherwise
2418  */
2419 static int need_output(void)
2420 {
2421     int i;
2422
2423     for (i = 0; i < nb_output_streams; i++) {
2424         OutputStream *ost    = output_streams[i];
2425         OutputFile *of       = output_files[ost->file_index];
2426         AVFormatContext *os  = output_files[ost->file_index]->ctx;
2427
2428         if (ost->is_past_recording_time ||
2429             (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2430             continue;
2431         if (ost->frame_number >= ost->max_frames) {
2432             int j;
2433             for (j = 0; j < of->ctx->nb_streams; j++)
2434                 output_streams[of->ost_index + j]->is_past_recording_time = 1;
2435             continue;
2436         }
2437
2438         return 1;
2439     }
2440
2441     return 0;
2442 }
2443
2444 static int select_input_file(uint8_t *no_packet)
2445 {
2446     int64_t ipts_min = INT64_MAX;
2447     int i, file_index = -1;
2448
2449     for (i = 0; i < nb_input_streams; i++) {
2450         InputStream *ist = input_streams[i];
2451         int64_t ipts     = ist->last_dts;
2452
2453         if (ist->discard || no_packet[ist->file_index])
2454             continue;
2455         if (!input_files[ist->file_index]->eof_reached) {
2456             if (ipts < ipts_min) {
2457                 ipts_min = ipts;
2458                 file_index = ist->file_index;
2459             }
2460         }
2461     }
2462
2463     return file_index;
2464 }
2465
2466 #if HAVE_PTHREADS
2467 static void *input_thread(void *arg)
2468 {
2469     InputFile *f = arg;
2470     int ret = 0;
2471
2472     while (!transcoding_finished && ret >= 0) {
2473         AVPacket pkt;
2474         ret = av_read_frame(f->ctx, &pkt);
2475
2476         if (ret == AVERROR(EAGAIN)) {
2477             av_usleep(10000);
2478             ret = 0;
2479             continue;
2480         } else if (ret < 0)
2481             break;
2482
2483         pthread_mutex_lock(&f->fifo_lock);
2484         while (!av_fifo_space(f->fifo))
2485             pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2486
2487         av_dup_packet(&pkt);
2488         av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2489
2490         pthread_mutex_unlock(&f->fifo_lock);
2491     }
2492
2493     f->finished = 1;
2494     return NULL;
2495 }
2496
2497 static void free_input_threads(void)
2498 {
2499     int i;
2500
2501     if (nb_input_files == 1)
2502         return;
2503
2504     transcoding_finished = 1;
2505
2506     for (i = 0; i < nb_input_files; i++) {
2507         InputFile *f = input_files[i];
2508         AVPacket pkt;
2509
2510         if (!f->fifo || f->joined)
2511             continue;
2512
2513         pthread_mutex_lock(&f->fifo_lock);
2514         while (av_fifo_size(f->fifo)) {
2515             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2516             av_free_packet(&pkt);
2517         }
2518         pthread_cond_signal(&f->fifo_cond);
2519         pthread_mutex_unlock(&f->fifo_lock);
2520
2521         pthread_join(f->thread, NULL);
2522         f->joined = 1;
2523
2524         while (av_fifo_size(f->fifo)) {
2525             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2526             av_free_packet(&pkt);
2527         }
2528         av_fifo_free(f->fifo);
2529     }
2530 }
2531
2532 static int init_input_threads(void)
2533 {
2534     int i, ret;
2535
2536     if (nb_input_files == 1)
2537         return 0;
2538
2539     for (i = 0; i < nb_input_files; i++) {
2540         InputFile *f = input_files[i];
2541
2542         if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2543             return AVERROR(ENOMEM);
2544
2545         pthread_mutex_init(&f->fifo_lock, NULL);
2546         pthread_cond_init (&f->fifo_cond, NULL);
2547
2548         if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2549             return AVERROR(ret);
2550     }
2551     return 0;
2552 }
2553
2554 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2555 {
2556     int ret = 0;
2557
2558     pthread_mutex_lock(&f->fifo_lock);
2559
2560     if (av_fifo_size(f->fifo)) {
2561         av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2562         pthread_cond_signal(&f->fifo_cond);
2563     } else {
2564         if (f->finished)
2565             ret = AVERROR_EOF;
2566         else
2567             ret = AVERROR(EAGAIN);
2568     }
2569
2570     pthread_mutex_unlock(&f->fifo_lock);
2571
2572     return ret;
2573 }
2574 #endif
2575
2576 static int get_input_packet(InputFile *f, AVPacket *pkt)
2577 {
2578 #if HAVE_PTHREADS
2579     if (nb_input_files > 1)
2580         return get_input_packet_mt(f, pkt);
2581 #endif
2582     return av_read_frame(f->ctx, pkt);
2583 }
2584
2585 /*
2586  * The following code is the main loop of the file converter
2587  */
2588 static int transcode(void)
2589 {
2590     int ret, i;
2591     AVFormatContext *is, *os;
2592     OutputStream *ost;
2593     InputStream *ist;
2594     uint8_t *no_packet;
2595     int no_packet_count = 0;
2596     int64_t timer_start;
2597
2598     if (!(no_packet = av_mallocz(nb_input_files)))
2599         exit_program(1);
2600
2601     ret = transcode_init();
2602     if (ret < 0)
2603         goto fail;
2604
2605     av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2606     term_init();
2607
2608     timer_start = av_gettime();
2609
2610 #if HAVE_PTHREADS
2611     if ((ret = init_input_threads()) < 0)
2612         goto fail;
2613 #endif
2614
2615     for (; received_sigterm == 0;) {
2616         int file_index, ist_index;
2617         AVPacket pkt;
2618
2619         /* check if there's any stream where output is still needed */
2620         if (!need_output()) {
2621             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
2622             break;
2623         }
2624
2625         /* select the stream that we must read now */
2626         file_index = select_input_file(no_packet);
2627         /* if none, if is finished */
2628         if (file_index < 0) {
2629             if (no_packet_count) {
2630                 no_packet_count = 0;
2631                 memset(no_packet, 0, nb_input_files);
2632                 av_usleep(10000);
2633                 continue;
2634             }
2635             av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
2636             break;
2637         }
2638
2639         is  = input_files[file_index]->ctx;
2640         ret = get_input_packet(input_files[file_index], &pkt);
2641
2642         if (ret == AVERROR(EAGAIN)) {
2643             no_packet[file_index] = 1;
2644             no_packet_count++;
2645             continue;
2646         }
2647         if (ret < 0) {
2648             if (ret != AVERROR_EOF) {
2649                 print_error(is->filename, ret);
2650                 if (exit_on_error)
2651                     exit_program(1);
2652             }
2653             input_files[file_index]->eof_reached = 1;
2654
2655             for (i = 0; i < input_files[file_index]->nb_streams; i++) {
2656                 ist = input_streams[input_files[file_index]->ist_index + i];
2657                 if (ist->decoding_needed)
2658                     output_packet(ist, NULL);
2659             }
2660
2661             if (opt_shortest)
2662                 break;
2663             else
2664                 continue;
2665         }
2666
2667         no_packet_count = 0;
2668         memset(no_packet, 0, nb_input_files);
2669
2670         if (do_pkt_dump) {
2671             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2672                              is->streams[pkt.stream_index]);
2673         }
2674         /* the following test is needed in case new streams appear
2675            dynamically in stream : we ignore them */
2676         if (pkt.stream_index >= input_files[file_index]->nb_streams)
2677             goto discard_packet;
2678         ist_index = input_files[file_index]->ist_index + pkt.stream_index;
2679         ist = input_streams[ist_index];
2680         if (ist->discard)
2681             goto discard_packet;
2682
2683         if (pkt.dts != AV_NOPTS_VALUE)
2684             pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2685         if (pkt.pts != AV_NOPTS_VALUE)
2686             pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2687
2688         if (pkt.pts != AV_NOPTS_VALUE)
2689             pkt.pts *= ist->ts_scale;
2690         if (pkt.dts != AV_NOPTS_VALUE)
2691             pkt.dts *= ist->ts_scale;
2692
2693         //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
2694         //        ist->next_dts,
2695         //        pkt.dts, input_files[ist->file_index].ts_offset,
2696         //        ist->st->codec->codec_type);
2697         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
2698             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2699             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2700             int64_t delta   = pkt_dts - ist->next_dts;
2701             if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2702                 input_files[ist->file_index]->ts_offset -= delta;
2703                 av_log(NULL, AV_LOG_DEBUG,
2704                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2705                        delta, input_files[ist->file_index]->ts_offset);
2706                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2707                 if (pkt.pts != AV_NOPTS_VALUE)
2708                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2709             }
2710         }
2711
2712         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2713         if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
2714             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2715                    ist->file_index, ist->st->index);
2716             if (exit_on_error)
2717                 exit_program(1);
2718             av_free_packet(&pkt);
2719             continue;
2720         }
2721
2722     discard_packet:
2723         av_free_packet(&pkt);
2724
2725         /* dump report by using the output first video and audio streams */
2726         print_report(0, timer_start);
2727     }
2728 #if HAVE_PTHREADS
2729     free_input_threads();
2730 #endif
2731
2732     /* at the end of stream, we must flush the decoder buffers */
2733     for (i = 0; i < nb_input_streams; i++) {
2734         ist = input_streams[i];
2735         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
2736             output_packet(ist, NULL);
2737         }
2738     }
2739     poll_filters();
2740     flush_encoders();
2741
2742     term_exit();
2743
2744     /* write the trailer if needed and close file */
2745     for (i = 0; i < nb_output_files; i++) {
2746         os = output_files[i]->ctx;
2747         av_write_trailer(os);
2748     }
2749
2750     /* dump report by using the first video and audio streams */
2751     print_report(1, timer_start);
2752
2753     /* close each encoder */
2754     for (i = 0; i < nb_output_streams; i++) {
2755         ost = output_streams[i];
2756         if (ost->encoding_needed) {
2757             av_freep(&ost->st->codec->stats_in);
2758             avcodec_close(ost->st->codec);
2759         }
2760     }
2761
2762     /* close each decoder */
2763     for (i = 0; i < nb_input_streams; i++) {
2764         ist = input_streams[i];
2765         if (ist->decoding_needed) {
2766             avcodec_close(ist->st->codec);
2767         }
2768     }
2769
2770     /* finished ! */
2771     ret = 0;
2772
2773  fail:
2774     av_freep(&no_packet);
2775 #if HAVE_PTHREADS
2776     free_input_threads();
2777 #endif
2778
2779     if (output_streams) {
2780         for (i = 0; i < nb_output_streams; i++) {
2781             ost = output_streams[i];
2782             if (ost) {
2783                 if (ost->stream_copy)
2784                     av_freep(&ost->st->codec->extradata);
2785                 if (ost->logfile) {
2786                     fclose(ost->logfile);
2787                     ost->logfile = NULL;
2788                 }
2789                 av_freep(&ost->st->codec->subtitle_header);
2790                 av_free(ost->forced_kf_pts);
2791                 av_dict_free(&ost->opts);
2792             }
2793         }
2794     }
2795     return ret;
2796 }
2797
2798 static int64_t getutime(void)
2799 {
2800 #if HAVE_GETRUSAGE
2801     struct rusage rusage;
2802
2803     getrusage(RUSAGE_SELF, &rusage);
2804     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2805 #elif HAVE_GETPROCESSTIMES
2806     HANDLE proc;
2807     FILETIME c, e, k, u;
2808     proc = GetCurrentProcess();
2809     GetProcessTimes(proc, &c, &e, &k, &u);
2810     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
2811 #else
2812     return av_gettime();
2813 #endif
2814 }
2815
2816 static int64_t getmaxrss(void)
2817 {
2818 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
2819     struct rusage rusage;
2820     getrusage(RUSAGE_SELF, &rusage);
2821     return (int64_t)rusage.ru_maxrss * 1024;
2822 #elif HAVE_GETPROCESSMEMORYINFO
2823     HANDLE proc;
2824     PROCESS_MEMORY_COUNTERS memcounters;
2825     proc = GetCurrentProcess();
2826     memcounters.cb = sizeof(memcounters);
2827     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
2828     return memcounters.PeakPagefileUsage;
2829 #else
2830     return 0;
2831 #endif
2832 }
2833
2834 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
2835 {
2836     int idx = locate_option(argc, argv, options, "cpuflags");
2837     if (idx && argv[idx + 1])
2838         opt_cpuflags("cpuflags", argv[idx + 1]);
2839 }
2840
2841 int main(int argc, char **argv)
2842 {
2843     OptionsContext o = { 0 };
2844     int64_t ti;
2845
2846     reset_options(&o);
2847
2848     av_log_set_flags(AV_LOG_SKIP_REPEATED);
2849     parse_loglevel(argc, argv, options);
2850
2851     avcodec_register_all();
2852 #if CONFIG_AVDEVICE
2853     avdevice_register_all();
2854 #endif
2855     avfilter_register_all();
2856     av_register_all();
2857     avformat_network_init();
2858
2859     show_banner();
2860
2861     parse_cpuflags(argc, argv, options);
2862
2863     /* parse options */
2864     parse_options(&o, argc, argv, options, opt_output_file);
2865
2866     if (nb_output_files <= 0 && nb_input_files == 0) {
2867         show_usage();
2868         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
2869         exit_program(1);
2870     }
2871
2872     /* file converter / grab */
2873     if (nb_output_files <= 0) {
2874         fprintf(stderr, "At least one output file must be specified\n");
2875         exit_program(1);
2876     }
2877
2878     if (nb_input_files == 0) {
2879         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
2880         exit_program(1);
2881     }
2882
2883     ti = getutime();
2884     if (transcode() < 0)
2885         exit_program(1);
2886     ti = getutime() - ti;
2887     if (do_benchmark) {
2888         int maxrss = getmaxrss() / 1024;
2889         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
2890     }
2891
2892     exit_program(0);
2893     return 0;
2894 }