avconv: don't include vsrc_buffer.h, which doesn't exist anymore
[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 "cmdutils.h"
77
78 #include "libavutil/avassert.h"
79
80 #define VSYNC_AUTO       -1
81 #define VSYNC_PASSTHROUGH 0
82 #define VSYNC_CFR         1
83 #define VSYNC_VFR         2
84
85 const char program_name[] = "avconv";
86 const int program_birth_year = 2000;
87
88 /* select an input stream for an output stream */
89 typedef struct StreamMap {
90     int disabled;           /** 1 is this mapping is disabled by a negative map */
91     int file_index;
92     int stream_index;
93     int sync_file_index;
94     int sync_stream_index;
95     char *linklabel;       /** name of an output link, for mapping lavfi outputs */
96 } StreamMap;
97
98 /**
99  * select an input file for an output file
100  */
101 typedef struct MetadataMap {
102     int  file;      ///< file index
103     char type;      ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
104     int  index;     ///< stream/chapter/program number
105 } MetadataMap;
106
107 static const OptionDef options[];
108
109 static int video_discard = 0;
110 static int same_quant = 0;
111 static int do_deinterlace = 0;
112 static int intra_dc_precision = 8;
113 static int qp_hist = 0;
114
115 static int file_overwrite = 0;
116 static int do_benchmark = 0;
117 static int do_hex_dump = 0;
118 static int do_pkt_dump = 0;
119 static int do_pass = 0;
120 static char *pass_logfilename_prefix = NULL;
121 static int video_sync_method = VSYNC_AUTO;
122 static int audio_sync_method = 0;
123 static float audio_drift_threshold = 0.1;
124 static int copy_ts = 0;
125 static int copy_tb = 1;
126 static int opt_shortest = 0;
127 static char *vstats_filename;
128 static FILE *vstats_file;
129
130 static int audio_volume = 256;
131
132 static int exit_on_error = 0;
133 static int using_stdin = 0;
134 static int64_t video_size = 0;
135 static int64_t audio_size = 0;
136 static int64_t extra_size = 0;
137 static int nb_frames_dup = 0;
138 static int nb_frames_drop = 0;
139 static int input_sync;
140
141 static float dts_delta_threshold = 10;
142
143 static int print_stats = 1;
144
145 #if HAVE_PTHREADS
146 /* signal to input threads that they should exit; set by the main thread */
147 static int transcoding_finished;
148 #endif
149
150 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
151
152 typedef struct InputFilter {
153     AVFilterContext    *filter;
154     struct InputStream *ist;
155     struct FilterGraph *graph;
156     uint8_t            *name;
157 } InputFilter;
158
159 typedef struct OutputFilter {
160     AVFilterContext     *filter;
161     struct OutputStream *ost;
162     struct FilterGraph  *graph;
163     uint8_t             *name;
164
165     /* temporary storage until stream maps are processed */
166     AVFilterInOut       *out_tmp;
167 } OutputFilter;
168
169 typedef struct FilterGraph {
170     int            index;
171     const char    *graph_desc;
172
173     AVFilterGraph *graph;
174
175     InputFilter   **inputs;
176     int          nb_inputs;
177     OutputFilter **outputs;
178     int         nb_outputs;
179 } FilterGraph;
180
181 typedef struct InputStream {
182     int file_index;
183     AVStream *st;
184     int discard;             /* true if stream data should be discarded */
185     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
186     AVCodec *dec;
187     AVFrame *decoded_frame;
188
189     int64_t       start;     /* time when read started */
190     /* predicted dts of the next packet read for this stream or (when there are
191      * several frames in a packet) of the next frame in current packet */
192     int64_t       next_dts;
193     /* dts of the last packet read for this stream */
194     int64_t       last_dts;
195     PtsCorrectionContext pts_ctx;
196     double ts_scale;
197     int is_start;            /* is 1 at the start and after a discontinuity */
198     int showed_multi_packet_warning;
199     AVDictionary *opts;
200     AVRational framerate;               /* framerate forced with -r */
201
202     int resample_height;
203     int resample_width;
204     int resample_pix_fmt;
205
206     int      resample_sample_fmt;
207     int      resample_sample_rate;
208     int      resample_channels;
209     uint64_t resample_channel_layout;
210
211     /* a pool of free buffers for decoded data */
212     FrameBuffer *buffer_pool;
213
214     /* decoded data from this stream goes into all those filters
215      * currently video and audio only */
216     InputFilter **filters;
217     int        nb_filters;
218 } InputStream;
219
220 typedef struct InputFile {
221     AVFormatContext *ctx;
222     int eof_reached;      /* true if eof reached */
223     int ist_index;        /* index of first stream in ist_table */
224     int buffer_size;      /* current total buffer size */
225     int64_t ts_offset;
226     int nb_streams;       /* number of stream that avconv is aware of; may be different
227                              from ctx.nb_streams if new streams appear during av_read_frame() */
228     int rate_emu;
229
230 #if HAVE_PTHREADS
231     pthread_t thread;           /* thread reading from this file */
232     int finished;               /* the thread has exited */
233     int joined;                 /* the thread has been joined */
234     pthread_mutex_t fifo_lock;  /* lock for access to fifo */
235     pthread_cond_t  fifo_cond;  /* the main thread will signal on this cond after reading from fifo */
236     AVFifoBuffer *fifo;         /* demuxed packets are stored here; freed by the main thread */
237 #endif
238 } InputFile;
239
240 typedef struct OutputStream {
241     int file_index;          /* file index */
242     int index;               /* stream index in the output file */
243     int source_index;        /* InputStream index */
244     AVStream *st;            /* stream in the output file */
245     int encoding_needed;     /* true if encoding needed for this stream */
246     int frame_number;
247     /* input pts and corresponding output pts
248        for A/V sync */
249     // double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
250     struct InputStream *sync_ist; /* input stream to sync against */
251     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
252     /* pts of the first frame encoded for this stream, used for limiting
253      * recording time */
254     int64_t first_pts;
255     AVBitStreamFilterContext *bitstream_filters;
256     AVCodec *enc;
257     int64_t max_frames;
258     AVFrame *filtered_frame;
259
260     /* video only */
261     AVRational frame_rate;
262     int force_fps;
263     int top_field_first;
264
265     float frame_aspect_ratio;
266     float last_quality;
267
268     /* forced key frames */
269     int64_t *forced_kf_pts;
270     int forced_kf_count;
271     int forced_kf_index;
272     char *forced_keyframes;
273
274     FILE *logfile;
275
276     OutputFilter *filter;
277     char *avfilter;
278
279     int64_t sws_flags;
280     AVDictionary *opts;
281     int is_past_recording_time;
282     int stream_copy;
283     const char *attachment_filename;
284     int copy_initial_nonkeyframes;
285
286     enum PixelFormat pix_fmts[2];
287 } OutputStream;
288
289
290 typedef struct OutputFile {
291     AVFormatContext *ctx;
292     AVDictionary *opts;
293     int ost_index;       /* index of the first stream in output_streams */
294     int64_t recording_time; /* desired length of the resulting file in microseconds */
295     int64_t start_time;     /* start time in microseconds */
296     uint64_t limit_filesize;
297 } OutputFile;
298
299 static InputStream **input_streams = NULL;
300 static int        nb_input_streams = 0;
301 static InputFile   **input_files   = NULL;
302 static int        nb_input_files   = 0;
303
304 static OutputStream **output_streams = NULL;
305 static int         nb_output_streams = 0;
306 static OutputFile   **output_files   = NULL;
307 static int         nb_output_files   = 0;
308
309 static FilterGraph **filtergraphs;
310 int               nb_filtergraphs;
311
312 typedef struct OptionsContext {
313     /* input/output options */
314     int64_t start_time;
315     const char *format;
316
317     SpecifierOpt *codec_names;
318     int        nb_codec_names;
319     SpecifierOpt *audio_channels;
320     int        nb_audio_channels;
321     SpecifierOpt *audio_sample_rate;
322     int        nb_audio_sample_rate;
323     SpecifierOpt *frame_rates;
324     int        nb_frame_rates;
325     SpecifierOpt *frame_sizes;
326     int        nb_frame_sizes;
327     SpecifierOpt *frame_pix_fmts;
328     int        nb_frame_pix_fmts;
329
330     /* input options */
331     int64_t input_ts_offset;
332     int rate_emu;
333
334     SpecifierOpt *ts_scale;
335     int        nb_ts_scale;
336     SpecifierOpt *dump_attachment;
337     int        nb_dump_attachment;
338
339     /* output options */
340     StreamMap *stream_maps;
341     int     nb_stream_maps;
342     /* first item specifies output metadata, second is input */
343     MetadataMap (*meta_data_maps)[2];
344     int nb_meta_data_maps;
345     int metadata_global_manual;
346     int metadata_streams_manual;
347     int metadata_chapters_manual;
348     const char **attachments;
349     int       nb_attachments;
350
351     int chapters_input_file;
352
353     int64_t recording_time;
354     uint64_t limit_filesize;
355     float mux_preload;
356     float mux_max_delay;
357
358     int video_disable;
359     int audio_disable;
360     int subtitle_disable;
361     int data_disable;
362
363     /* indexed by output file stream index */
364     int   *streamid_map;
365     int nb_streamid_map;
366
367     SpecifierOpt *metadata;
368     int        nb_metadata;
369     SpecifierOpt *max_frames;
370     int        nb_max_frames;
371     SpecifierOpt *bitstream_filters;
372     int        nb_bitstream_filters;
373     SpecifierOpt *codec_tags;
374     int        nb_codec_tags;
375     SpecifierOpt *sample_fmts;
376     int        nb_sample_fmts;
377     SpecifierOpt *qscale;
378     int        nb_qscale;
379     SpecifierOpt *forced_key_frames;
380     int        nb_forced_key_frames;
381     SpecifierOpt *force_fps;
382     int        nb_force_fps;
383     SpecifierOpt *frame_aspect_ratios;
384     int        nb_frame_aspect_ratios;
385     SpecifierOpt *rc_overrides;
386     int        nb_rc_overrides;
387     SpecifierOpt *intra_matrices;
388     int        nb_intra_matrices;
389     SpecifierOpt *inter_matrices;
390     int        nb_inter_matrices;
391     SpecifierOpt *top_field_first;
392     int        nb_top_field_first;
393     SpecifierOpt *metadata_map;
394     int        nb_metadata_map;
395     SpecifierOpt *presets;
396     int        nb_presets;
397     SpecifierOpt *copy_initial_nonkeyframes;
398     int        nb_copy_initial_nonkeyframes;
399     SpecifierOpt *filters;
400     int        nb_filters;
401 } OptionsContext;
402
403 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
404 {\
405     int i, ret;\
406     for (i = 0; i < o->nb_ ## name; i++) {\
407         char *spec = o->name[i].specifier;\
408         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
409             outvar = o->name[i].u.type;\
410         else if (ret < 0)\
411             exit_program(1);\
412     }\
413 }
414
415 static void reset_options(OptionsContext *o)
416 {
417     const OptionDef *po = options;
418     int i;
419
420     /* all OPT_SPEC and OPT_STRING can be freed in generic way */
421     while (po->name) {
422         void *dst = (uint8_t*)o + po->u.off;
423
424         if (po->flags & OPT_SPEC) {
425             SpecifierOpt **so = dst;
426             int i, *count = (int*)(so + 1);
427             for (i = 0; i < *count; i++) {
428                 av_freep(&(*so)[i].specifier);
429                 if (po->flags & OPT_STRING)
430                     av_freep(&(*so)[i].u.str);
431             }
432             av_freep(so);
433             *count = 0;
434         } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
435             av_freep(dst);
436         po++;
437     }
438
439     for (i = 0; i < o->nb_stream_maps; i++)
440         av_freep(&o->stream_maps[i].linklabel);
441     av_freep(&o->stream_maps);
442     av_freep(&o->meta_data_maps);
443     av_freep(&o->streamid_map);
444
445     memset(o, 0, sizeof(*o));
446
447     o->mux_max_delay  = 0.7;
448     o->recording_time = INT64_MAX;
449     o->limit_filesize = UINT64_MAX;
450     o->chapters_input_file = INT_MAX;
451
452     uninit_opts();
453     init_opts();
454 }
455
456 /**
457  * Define a function for building a string containing a list of
458  * allowed formats,
459  */
460 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name, separator) \
461 static char *choose_ ## var ## s(OutputStream *ost)                             \
462 {                                                                               \
463     if (ost->st->codec->var != none) {                                          \
464         get_name(ost->st->codec->var);                                          \
465         return av_strdup(name);                                                 \
466     } else if (ost->enc->supported_list) {                                      \
467         const type *p;                                                          \
468         AVIOContext *s = NULL;                                                  \
469         uint8_t *ret;                                                           \
470         int len;                                                                \
471                                                                                 \
472         if (avio_open_dyn_buf(&s) < 0)                                          \
473             exit_program(1);                                                    \
474                                                                                 \
475         for (p = ost->enc->supported_list; *p != none; p++) {                   \
476             get_name(*p);                                                       \
477             avio_printf(s, "%s" separator, name);                               \
478         }                                                                       \
479         len = avio_close_dyn_buf(s, &ret);                                      \
480         ret[len - 1] = 0;                                                       \
481         return ret;                                                             \
482     } else                                                                      \
483         return NULL;                                                            \
484 }
485
486 #define GET_PIX_FMT_NAME(pix_fmt)\
487     const char *name = av_get_pix_fmt_name(pix_fmt);
488
489 DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
490                   GET_PIX_FMT_NAME, ":")
491
492 #define GET_SAMPLE_FMT_NAME(sample_fmt)\
493     const char *name = av_get_sample_fmt_name(sample_fmt)
494
495 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
496                   AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME, ",")
497
498 #define GET_SAMPLE_RATE_NAME(rate)\
499     char name[16];\
500     snprintf(name, sizeof(name), "%d", rate);
501
502 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
503                   GET_SAMPLE_RATE_NAME, ",")
504
505 #define GET_CH_LAYOUT_NAME(ch_layout)\
506     char name[16];\
507     snprintf(name, sizeof(name), "0x%"PRIx64, ch_layout);
508
509 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
510                   GET_CH_LAYOUT_NAME, ",")
511
512 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
513 {
514     FilterGraph *fg = av_mallocz(sizeof(*fg));
515
516     if (!fg)
517         exit_program(1);
518     fg->index = nb_filtergraphs;
519
520     fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
521                              fg->nb_outputs + 1);
522     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
523         exit_program(1);
524     fg->outputs[0]->ost   = ost;
525     fg->outputs[0]->graph = fg;
526
527     ost->filter = fg->outputs[0];
528
529     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
530                             fg->nb_inputs + 1);
531     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
532         exit_program(1);
533     fg->inputs[0]->ist   = ist;
534     fg->inputs[0]->graph = fg;
535
536     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
537                               &ist->nb_filters, ist->nb_filters + 1);
538     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
539
540     filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
541                               &nb_filtergraphs, nb_filtergraphs + 1);
542     filtergraphs[nb_filtergraphs - 1] = fg;
543
544     return fg;
545 }
546
547 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
548 {
549     InputStream *ist;
550     enum AVMediaType type = avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx);
551     int i;
552
553     // TODO: support other filter types
554     if (type != AVMEDIA_TYPE_VIDEO && type != AVMEDIA_TYPE_AUDIO) {
555         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters supported "
556                "currently.\n");
557         exit_program(1);
558     }
559
560     if (in->name) {
561         AVFormatContext *s;
562         AVStream       *st = NULL;
563         char *p;
564         int file_idx = strtol(in->name, &p, 0);
565
566         if (file_idx < 0 || file_idx >= nb_input_files) {
567             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
568                    file_idx, fg->graph_desc);
569             exit_program(1);
570         }
571         s = input_files[file_idx]->ctx;
572
573         for (i = 0; i < s->nb_streams; i++) {
574             if (s->streams[i]->codec->codec_type != type)
575                 continue;
576             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
577                 st = s->streams[i];
578                 break;
579             }
580         }
581         if (!st) {
582             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
583                    "matches no streams.\n", p, fg->graph_desc);
584             exit_program(1);
585         }
586         ist = input_streams[input_files[file_idx]->ist_index + st->index];
587     } else {
588         /* find the first unused stream of corresponding type */
589         for (i = 0; i < nb_input_streams; i++) {
590             ist = input_streams[i];
591             if (ist->st->codec->codec_type == type && ist->discard)
592                 break;
593         }
594         if (i == nb_input_streams) {
595             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
596                    "unlabeled input pad %d on filter %s", in->pad_idx,
597                    in->filter_ctx->name);
598             exit_program(1);
599         }
600     }
601     ist->discard         = 0;
602     ist->decoding_needed = 1;
603     ist->st->discard = AVDISCARD_NONE;
604
605     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
606                             &fg->nb_inputs, fg->nb_inputs + 1);
607     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
608         exit_program(1);
609     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
610     fg->inputs[fg->nb_inputs - 1]->graph = fg;
611
612     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
613                               &ist->nb_filters, ist->nb_filters + 1);
614     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
615 }
616
617 static int configure_output_video_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
618 {
619     char *pix_fmts;
620     OutputStream *ost = ofilter->ost;
621     AVCodecContext *codec = ost->st->codec;
622     AVFilterContext *last_filter = out->filter_ctx;
623     int pad_idx = out->pad_idx;
624     int ret;
625     char name[255];
626
627     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
628     ret = avfilter_graph_create_filter(&ofilter->filter,
629                                        avfilter_get_by_name("buffersink"),
630                                        name, NULL, pix_fmts, fg->graph);
631     if (ret < 0)
632         return ret;
633
634     if (codec->width || codec->height) {
635         char args[255];
636         AVFilterContext *filter;
637
638         snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
639                  codec->width,
640                  codec->height,
641                  (unsigned)ost->sws_flags);
642         snprintf(name, sizeof(name), "scaler for output stream %d:%d",
643                  ost->file_index, ost->index);
644         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
645                                                 name, args, NULL, fg->graph)) < 0)
646             return ret;
647         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
648             return ret;
649
650         last_filter = filter;
651         pad_idx = 0;
652     }
653
654     if ((pix_fmts = choose_pix_fmts(ost))) {
655         AVFilterContext *filter;
656         snprintf(name, sizeof(name), "pixel format for output stream %d:%d",
657                  ost->file_index, ost->index);
658         if ((ret = avfilter_graph_create_filter(&filter,
659                                                 avfilter_get_by_name("format"),
660                                                 "format", pix_fmts, NULL,
661                                                 fg->graph)) < 0)
662             return ret;
663         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
664             return ret;
665
666         last_filter = filter;
667         pad_idx     = 0;
668         av_freep(&pix_fmts);
669     }
670
671     if (ost->frame_rate.num) {
672         AVFilterContext *fps;
673         char args[255];
674
675         snprintf(args, sizeof(args), "fps=%d/%d", ost->frame_rate.num,
676                  ost->frame_rate.den);
677         snprintf(name, sizeof(name), "fps for output stream %d:%d",
678                  ost->file_index, ost->index);
679         ret = avfilter_graph_create_filter(&fps, avfilter_get_by_name("fps"),
680                                            name, args, NULL, fg->graph);
681         if (ret < 0)
682             return ret;
683
684         ret = avfilter_link(last_filter, pad_idx, fps, 0);
685         if (ret < 0)
686             return ret;
687         last_filter = fps;
688         pad_idx = 0;
689     }
690
691     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
692         return ret;
693
694     return 0;
695 }
696
697 static int configure_output_audio_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
698 {
699     OutputStream *ost = ofilter->ost;
700     AVCodecContext *codec  = ost->st->codec;
701     AVFilterContext *last_filter = out->filter_ctx;
702     int pad_idx = out->pad_idx;
703     char *sample_fmts, *sample_rates, *channel_layouts;
704     char name[255];
705     int ret;
706
707
708     snprintf(name, sizeof(name), "output stream %d:%d", ost->file_index, ost->index);
709     ret = avfilter_graph_create_filter(&ofilter->filter,
710                                        avfilter_get_by_name("abuffersink"),
711                                        name, NULL, NULL, fg->graph);
712     if (ret < 0)
713         return ret;
714
715     if (codec->channels && !codec->channel_layout)
716         codec->channel_layout = av_get_default_channel_layout(codec->channels);
717
718     sample_fmts     = choose_sample_fmts(ost);
719     sample_rates    = choose_sample_rates(ost);
720     channel_layouts = choose_channel_layouts(ost);
721     if (sample_fmts || sample_rates || channel_layouts) {
722         AVFilterContext *format;
723         char args[256];
724         int len = 0;
725
726         if (sample_fmts)
727             len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
728                             sample_fmts);
729         if (sample_rates)
730             len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
731                             sample_rates);
732         if (channel_layouts)
733             len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
734                             channel_layouts);
735         args[len - 1] = 0;
736
737         av_freep(&sample_fmts);
738         av_freep(&sample_rates);
739         av_freep(&channel_layouts);
740
741         snprintf(name, sizeof(name), "audio format for output stream %d:%d",
742                  ost->file_index, ost->index);
743         ret = avfilter_graph_create_filter(&format,
744                                            avfilter_get_by_name("aformat"),
745                                            name, args, NULL, fg->graph);
746         if (ret < 0)
747             return ret;
748
749         ret = avfilter_link(last_filter, pad_idx, format, 0);
750         if (ret < 0)
751             return ret;
752
753         last_filter = format;
754         pad_idx = 0;
755     }
756
757     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
758         return ret;
759
760     return 0;
761 }
762
763 #define DESCRIBE_FILTER_LINK(f, inout, in)                         \
764 {                                                                  \
765     AVFilterContext *ctx = inout->filter_ctx;                      \
766     AVFilterPad *pads = in ? ctx->input_pads  : ctx->output_pads;  \
767     int       nb_pads = in ? ctx->input_count : ctx->output_count; \
768     AVIOContext *pb;                                               \
769                                                                    \
770     if (avio_open_dyn_buf(&pb) < 0)                                \
771         exit_program(1);                                           \
772                                                                    \
773     avio_printf(pb, "%s", ctx->filter->name);                      \
774     if (nb_pads > 1)                                               \
775         avio_printf(pb, ":%s", avfilter_pad_get_name(pads, inout->pad_idx));\
776     avio_w8(pb, 0);                                                \
777     avio_close_dyn_buf(pb, &f->name);                              \
778 }
779
780 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
781 {
782     av_freep(&ofilter->name);
783     DESCRIBE_FILTER_LINK(ofilter, out, 0);
784
785     switch (avfilter_pad_get_type(out->filter_ctx->output_pads, out->pad_idx)) {
786     case AVMEDIA_TYPE_VIDEO: return configure_output_video_filter(fg, ofilter, out);
787     case AVMEDIA_TYPE_AUDIO: return configure_output_audio_filter(fg, ofilter, out);
788     default: av_assert0(0);
789     }
790 }
791
792 static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,
793                                         AVFilterInOut *in)
794 {
795     AVFilterContext *first_filter = in->filter_ctx;
796     AVFilter *filter = avfilter_get_by_name("buffer");
797     InputStream *ist = ifilter->ist;
798     AVRational tb = ist->framerate.num ? (AVRational){ist->framerate.den,
799                                                       ist->framerate.num} :
800                                          ist->st->time_base;
801     AVRational sar;
802     char args[255], name[255];
803     int pad_idx = in->pad_idx;
804     int ret;
805
806     sar = ist->st->sample_aspect_ratio.num ?
807           ist->st->sample_aspect_ratio :
808           ist->st->codec->sample_aspect_ratio;
809     snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
810              ist->st->codec->height, ist->st->codec->pix_fmt,
811              tb.num, tb.den, sar.num, sar.den);
812     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
813              ist->file_index, ist->st->index);
814
815     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
816                                             args, NULL, fg->graph)) < 0)
817         return ret;
818
819     if (ist->framerate.num) {
820         AVFilterContext *setpts;
821
822         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
823                  ist->file_index, ist->st->index);
824         if ((ret = avfilter_graph_create_filter(&setpts,
825                                                 avfilter_get_by_name("setpts"),
826                                                 name, "N", NULL,
827                                                 fg->graph)) < 0)
828             return ret;
829
830         if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
831             return ret;
832
833         first_filter = setpts;
834         pad_idx = 0;
835     }
836
837     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
838         return ret;
839     return 0;
840 }
841
842 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
843                                         AVFilterInOut *in)
844 {
845     AVFilterContext *first_filter = in->filter_ctx;
846     AVFilter *filter = avfilter_get_by_name("abuffer");
847     InputStream *ist = ifilter->ist;
848     int pad_idx = in->pad_idx;
849     char args[255], name[255];
850     int ret;
851
852     snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"
853              ":channel_layout=0x%"PRIx64,
854              ist->st->time_base.num, ist->st->time_base.den,
855              ist->st->codec->sample_rate,
856              av_get_sample_fmt_name(ist->st->codec->sample_fmt),
857              ist->st->codec->channel_layout);
858     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
859              ist->file_index, ist->st->index);
860
861     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
862                                             name, args, NULL,
863                                             fg->graph)) < 0)
864         return ret;
865
866     if (audio_sync_method > 0) {
867         AVFilterContext *async;
868         char args[256];
869         int  len = 0;
870
871         av_log(NULL, AV_LOG_WARNING, "-async has been deprecated. Used the "
872                "asyncts audio filter instead.\n");
873
874         if (audio_sync_method > 1)
875             len += snprintf(args + len, sizeof(args) - len, "compensate=1:"
876                             "max_comp=%d:", audio_sync_method);
877         snprintf(args + len, sizeof(args) - len, "min_delta=%f",
878                  audio_drift_threshold);
879
880         snprintf(name, sizeof(name), "graph %d audio sync for input stream %d:%d",
881                  fg->index, ist->file_index, ist->st->index);
882         ret = avfilter_graph_create_filter(&async,
883                                            avfilter_get_by_name("asyncts"),
884                                            name, args, NULL, fg->graph);
885         if (ret < 0)
886             return ret;
887
888         ret = avfilter_link(async, 0, first_filter, pad_idx);
889         if (ret < 0)
890             return ret;
891
892         first_filter = async;
893         pad_idx = 0;
894     }
895     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
896         return ret;
897
898     return 0;
899 }
900
901 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
902                                   AVFilterInOut *in)
903 {
904     av_freep(&ifilter->name);
905     DESCRIBE_FILTER_LINK(ifilter, in, 1);
906
907     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
908     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
909     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
910     default: av_assert0(0);
911     }
912 }
913
914 static int configure_filtergraph(FilterGraph *fg)
915 {
916     AVFilterInOut *inputs, *outputs, *cur;
917     int ret, i, init = !fg->graph, simple = !fg->graph_desc;
918     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
919                                       fg->graph_desc;
920
921     avfilter_graph_free(&fg->graph);
922     if (!(fg->graph = avfilter_graph_alloc()))
923         return AVERROR(ENOMEM);
924
925     if (simple) {
926         OutputStream *ost = fg->outputs[0]->ost;
927         char args[255];
928         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
929         fg->graph->scale_sws_opts = av_strdup(args);
930     }
931
932     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
933         return ret;
934
935     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
936         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
937                "exactly one input and output.\n", graph_desc);
938         return AVERROR(EINVAL);
939     }
940
941     for (cur = inputs; !simple && init && cur; cur = cur->next)
942         init_input_filter(fg, cur);
943
944     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
945         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
946             return ret;
947     avfilter_inout_free(&inputs);
948
949     if (!init || simple) {
950         /* we already know the mappings between lavfi outputs and output streams,
951          * so we can finish the setup */
952         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
953             configure_output_filter(fg, fg->outputs[i], cur);
954         avfilter_inout_free(&outputs);
955
956         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
957             return ret;
958     } else {
959         /* wait until output mappings are processed */
960         for (cur = outputs; cur;) {
961             fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
962                                      &fg->nb_outputs, fg->nb_outputs + 1);
963             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
964                 exit_program(1);
965             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
966             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
967             cur = cur->next;
968             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
969         }
970     }
971
972     return 0;
973 }
974
975 static int configure_complex_filters(void)
976 {
977     int i, ret = 0;
978
979     for (i = 0; i < nb_filtergraphs; i++)
980         if (!filtergraphs[i]->graph &&
981             (ret = configure_filtergraph(filtergraphs[i])) < 0)
982             return ret;
983     return 0;
984 }
985
986 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
987 {
988     int i;
989     for (i = 0; i < fg->nb_inputs; i++)
990         if (fg->inputs[i]->ist == ist)
991             return 1;
992     return 0;
993 }
994
995 static void term_exit(void)
996 {
997     av_log(NULL, AV_LOG_QUIET, "");
998 }
999
1000 static volatile int received_sigterm = 0;
1001 static volatile int received_nb_signals = 0;
1002
1003 static void
1004 sigterm_handler(int sig)
1005 {
1006     received_sigterm = sig;
1007     received_nb_signals++;
1008     term_exit();
1009 }
1010
1011 static void term_init(void)
1012 {
1013     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
1014     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
1015 #ifdef SIGXCPU
1016     signal(SIGXCPU, sigterm_handler);
1017 #endif
1018 }
1019
1020 static int decode_interrupt_cb(void *ctx)
1021 {
1022     return received_nb_signals > 1;
1023 }
1024
1025 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1026
1027 void exit_program(int ret)
1028 {
1029     int i, j;
1030
1031     for (i = 0; i < nb_filtergraphs; i++) {
1032         avfilter_graph_free(&filtergraphs[i]->graph);
1033         for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
1034             av_freep(&filtergraphs[i]->inputs[j]->name);
1035             av_freep(&filtergraphs[i]->inputs[j]);
1036         }
1037         av_freep(&filtergraphs[i]->inputs);
1038         for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
1039             av_freep(&filtergraphs[i]->outputs[j]->name);
1040             av_freep(&filtergraphs[i]->outputs[j]);
1041         }
1042         av_freep(&filtergraphs[i]->outputs);
1043         av_freep(&filtergraphs[i]);
1044     }
1045     av_freep(&filtergraphs);
1046
1047     /* close files */
1048     for (i = 0; i < nb_output_files; i++) {
1049         AVFormatContext *s = output_files[i]->ctx;
1050         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1051             avio_close(s->pb);
1052         avformat_free_context(s);
1053         av_dict_free(&output_files[i]->opts);
1054         av_freep(&output_files[i]);
1055     }
1056     for (i = 0; i < nb_output_streams; i++) {
1057         AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1058         while (bsfc) {
1059             AVBitStreamFilterContext *next = bsfc->next;
1060             av_bitstream_filter_close(bsfc);
1061             bsfc = next;
1062         }
1063         output_streams[i]->bitstream_filters = NULL;
1064
1065         av_freep(&output_streams[i]->forced_keyframes);
1066         av_freep(&output_streams[i]->avfilter);
1067         av_freep(&output_streams[i]->filtered_frame);
1068         av_freep(&output_streams[i]);
1069     }
1070     for (i = 0; i < nb_input_files; i++) {
1071         avformat_close_input(&input_files[i]->ctx);
1072         av_freep(&input_files[i]);
1073     }
1074     for (i = 0; i < nb_input_streams; i++) {
1075         av_freep(&input_streams[i]->decoded_frame);
1076         av_dict_free(&input_streams[i]->opts);
1077         free_buffer_pool(&input_streams[i]->buffer_pool);
1078         av_freep(&input_streams[i]->filters);
1079         av_freep(&input_streams[i]);
1080     }
1081
1082     if (vstats_file)
1083         fclose(vstats_file);
1084     av_free(vstats_filename);
1085
1086     av_freep(&input_streams);
1087     av_freep(&input_files);
1088     av_freep(&output_streams);
1089     av_freep(&output_files);
1090
1091     uninit_opts();
1092
1093     avfilter_uninit();
1094     avformat_network_deinit();
1095
1096     if (received_sigterm) {
1097         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1098                (int) received_sigterm);
1099         exit (255);
1100     }
1101
1102     exit(ret);
1103 }
1104
1105 static void assert_avoptions(AVDictionary *m)
1106 {
1107     AVDictionaryEntry *t;
1108     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1109         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1110         exit_program(1);
1111     }
1112 }
1113
1114 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1115 {
1116     const char *codec_string = encoder ? "encoder" : "decoder";
1117     AVCodec *codec;
1118     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1119         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1120         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1121                 "results.\nAdd '-strict experimental' if you want to use it.\n",
1122                 codec_string, c->codec->name);
1123         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1124         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1125             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1126                    codec_string, codec->name);
1127         exit_program(1);
1128     }
1129 }
1130
1131 /**
1132  * Update the requested input sample format based on the output sample format.
1133  * This is currently only used to request float output from decoders which
1134  * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
1135  * Ideally this will be removed in the future when decoders do not do format
1136  * conversion and only output in their native format.
1137  */
1138 static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
1139                               AVCodecContext *enc)
1140 {
1141     /* if sample formats match or a decoder sample format has already been
1142        requested, just return */
1143     if (enc->sample_fmt == dec->sample_fmt ||
1144         dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
1145         return;
1146
1147     /* if decoder supports more than one output format */
1148     if (dec_codec && dec_codec->sample_fmts &&
1149         dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
1150         dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
1151         const enum AVSampleFormat *p;
1152         int min_dec = -1, min_inc = -1;
1153
1154         /* find a matching sample format in the encoder */
1155         for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
1156             if (*p == enc->sample_fmt) {
1157                 dec->request_sample_fmt = *p;
1158                 return;
1159             } else if (*p > enc->sample_fmt) {
1160                 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
1161             } else
1162                 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
1163         }
1164
1165         /* if none match, provide the one that matches quality closest */
1166         dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
1167                                   enc->sample_fmt - min_dec;
1168     }
1169 }
1170
1171 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1172 {
1173     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1174     AVCodecContext          *avctx = ost->st->codec;
1175     int ret;
1176
1177     /*
1178      * Audio encoders may split the packets --  #frames in != #packets out.
1179      * But there is no reordering, so we can limit the number of output packets
1180      * by simply dropping them here.
1181      * Counting encoded video frames needs to be done separately because of
1182      * reordering, see do_video_out()
1183      */
1184     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1185         if (ost->frame_number >= ost->max_frames) {
1186             av_free_packet(pkt);
1187             return;
1188         }
1189         ost->frame_number++;
1190     }
1191
1192     while (bsfc) {
1193         AVPacket new_pkt = *pkt;
1194         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1195                                            &new_pkt.data, &new_pkt.size,
1196                                            pkt->data, pkt->size,
1197                                            pkt->flags & AV_PKT_FLAG_KEY);
1198         if (a > 0) {
1199             av_free_packet(pkt);
1200             new_pkt.destruct = av_destruct_packet;
1201         } else if (a < 0) {
1202             av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
1203                    bsfc->filter->name, pkt->stream_index,
1204                    avctx->codec ? avctx->codec->name : "copy");
1205             print_error("", a);
1206             if (exit_on_error)
1207                 exit_program(1);
1208         }
1209         *pkt = new_pkt;
1210
1211         bsfc = bsfc->next;
1212     }
1213
1214     pkt->stream_index = ost->index;
1215     ret = av_interleaved_write_frame(s, pkt);
1216     if (ret < 0) {
1217         print_error("av_interleaved_write_frame()", ret);
1218         exit_program(1);
1219     }
1220 }
1221
1222 static int check_recording_time(OutputStream *ost)
1223 {
1224     OutputFile *of = output_files[ost->file_index];
1225
1226     if (of->recording_time != INT64_MAX &&
1227         av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
1228                       AV_TIME_BASE_Q) >= 0) {
1229         ost->is_past_recording_time = 1;
1230         return 0;
1231     }
1232     return 1;
1233 }
1234
1235 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1236                          AVFrame *frame)
1237 {
1238     AVCodecContext *enc = ost->st->codec;
1239     AVPacket pkt;
1240     int got_packet = 0;
1241
1242     av_init_packet(&pkt);
1243     pkt.data = NULL;
1244     pkt.size = 0;
1245
1246     if (!check_recording_time(ost))
1247         return;
1248
1249     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
1250         frame->pts = ost->sync_opts;
1251     ost->sync_opts = frame->pts + frame->nb_samples;
1252
1253     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1254         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1255         exit_program(1);
1256     }
1257
1258     if (got_packet) {
1259         if (pkt.pts != AV_NOPTS_VALUE)
1260             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
1261         if (pkt.dts != AV_NOPTS_VALUE)
1262             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
1263         if (pkt.duration > 0)
1264             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1265
1266         write_frame(s, &pkt, ost);
1267
1268         audio_size += pkt.size;
1269     }
1270 }
1271
1272 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1273 {
1274     AVCodecContext *dec;
1275     AVPicture *picture2;
1276     AVPicture picture_tmp;
1277     uint8_t *buf = 0;
1278
1279     dec = ist->st->codec;
1280
1281     /* deinterlace : must be done before any resize */
1282     if (do_deinterlace) {
1283         int size;
1284
1285         /* create temporary picture */
1286         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1287         buf  = av_malloc(size);
1288         if (!buf)
1289             return;
1290
1291         picture2 = &picture_tmp;
1292         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1293
1294         if (avpicture_deinterlace(picture2, picture,
1295                                  dec->pix_fmt, dec->width, dec->height) < 0) {
1296             /* if error, do not deinterlace */
1297             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1298             av_free(buf);
1299             buf = NULL;
1300             picture2 = picture;
1301         }
1302     } else {
1303         picture2 = picture;
1304     }
1305
1306     if (picture != picture2)
1307         *picture = *picture2;
1308     *bufp = buf;
1309 }
1310
1311 static void do_subtitle_out(AVFormatContext *s,
1312                             OutputStream *ost,
1313                             InputStream *ist,
1314                             AVSubtitle *sub,
1315                             int64_t pts)
1316 {
1317     static uint8_t *subtitle_out = NULL;
1318     int subtitle_out_max_size = 1024 * 1024;
1319     int subtitle_out_size, nb, i;
1320     AVCodecContext *enc;
1321     AVPacket pkt;
1322
1323     if (pts == AV_NOPTS_VALUE) {
1324         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1325         if (exit_on_error)
1326             exit_program(1);
1327         return;
1328     }
1329
1330     enc = ost->st->codec;
1331
1332     if (!subtitle_out) {
1333         subtitle_out = av_malloc(subtitle_out_max_size);
1334     }
1335
1336     /* Note: DVB subtitle need one packet to draw them and one other
1337        packet to clear them */
1338     /* XXX: signal it in the codec context ? */
1339     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1340         nb = 2;
1341     else
1342         nb = 1;
1343
1344     for (i = 0; i < nb; i++) {
1345         ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1346         if (!check_recording_time(ost))
1347             return;
1348
1349         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1350         // start_display_time is required to be 0
1351         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1352         sub->end_display_time  -= sub->start_display_time;
1353         sub->start_display_time = 0;
1354         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1355                                                     subtitle_out_max_size, sub);
1356         if (subtitle_out_size < 0) {
1357             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1358             exit_program(1);
1359         }
1360
1361         av_init_packet(&pkt);
1362         pkt.data = subtitle_out;
1363         pkt.size = subtitle_out_size;
1364         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1365         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1366             /* XXX: the pts correction is handled here. Maybe handling
1367                it in the codec would be better */
1368             if (i == 0)
1369                 pkt.pts += 90 * sub->start_display_time;
1370             else
1371                 pkt.pts += 90 * sub->end_display_time;
1372         }
1373         write_frame(s, &pkt, ost);
1374     }
1375 }
1376
1377 static void do_video_out(AVFormatContext *s,
1378                          OutputStream *ost,
1379                          AVFrame *in_picture,
1380                          int *frame_size, float quality)
1381 {
1382     int ret, format_video_sync;
1383     AVPacket pkt;
1384     AVCodecContext *enc = ost->st->codec;
1385
1386     *frame_size = 0;
1387
1388     format_video_sync = video_sync_method;
1389     if (format_video_sync == VSYNC_AUTO)
1390         format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
1391                             (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
1392     if (format_video_sync != VSYNC_PASSTHROUGH &&
1393         ost->frame_number &&
1394         in_picture->pts != AV_NOPTS_VALUE &&
1395         in_picture->pts < ost->sync_opts) {
1396         nb_frames_drop++;
1397         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1398         return;
1399     }
1400
1401     if (in_picture->pts == AV_NOPTS_VALUE)
1402         in_picture->pts = ost->sync_opts;
1403     ost->sync_opts = in_picture->pts;
1404
1405
1406     if (!ost->frame_number)
1407         ost->first_pts = in_picture->pts;
1408
1409     av_init_packet(&pkt);
1410     pkt.data = NULL;
1411     pkt.size = 0;
1412
1413     if (!check_recording_time(ost) ||
1414         ost->frame_number >= ost->max_frames)
1415         return;
1416
1417     if (s->oformat->flags & AVFMT_RAWPICTURE &&
1418         enc->codec->id == CODEC_ID_RAWVIDEO) {
1419         /* raw pictures are written as AVPicture structure to
1420            avoid any copies. We support temporarily the older
1421            method. */
1422         enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1423         enc->coded_frame->top_field_first  = in_picture->top_field_first;
1424         pkt.data   = (uint8_t *)in_picture;
1425         pkt.size   =  sizeof(AVPicture);
1426         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
1427         pkt.flags |= AV_PKT_FLAG_KEY;
1428
1429         write_frame(s, &pkt, ost);
1430     } else {
1431         int got_packet;
1432         AVFrame big_picture;
1433
1434         big_picture = *in_picture;
1435         /* better than nothing: use input picture interlaced
1436            settings */
1437         big_picture.interlaced_frame = in_picture->interlaced_frame;
1438         if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1439             if (ost->top_field_first == -1)
1440                 big_picture.top_field_first = in_picture->top_field_first;
1441             else
1442                 big_picture.top_field_first = !!ost->top_field_first;
1443         }
1444
1445         /* handles same_quant here. This is not correct because it may
1446            not be a global option */
1447         big_picture.quality = quality;
1448         if (!enc->me_threshold)
1449             big_picture.pict_type = 0;
1450         if (ost->forced_kf_index < ost->forced_kf_count &&
1451             big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1452             big_picture.pict_type = AV_PICTURE_TYPE_I;
1453             ost->forced_kf_index++;
1454         }
1455         ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
1456         if (ret < 0) {
1457             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1458             exit_program(1);
1459         }
1460
1461         if (got_packet) {
1462             if (pkt.pts != AV_NOPTS_VALUE)
1463                 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1464             if (pkt.dts != AV_NOPTS_VALUE)
1465                 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1466
1467             write_frame(s, &pkt, ost);
1468             *frame_size = pkt.size;
1469             video_size += pkt.size;
1470
1471             /* if two pass, output log */
1472             if (ost->logfile && enc->stats_out) {
1473                 fprintf(ost->logfile, "%s", enc->stats_out);
1474             }
1475         }
1476     }
1477     ost->sync_opts++;
1478     /*
1479      * For video, number of frames in == number of packets out.
1480      * But there may be reordering, so we can't throw away frames on encoder
1481      * flush, we need to limit them here, before they go into encoder.
1482      */
1483     ost->frame_number++;
1484 }
1485
1486 static double psnr(double d)
1487 {
1488     return -10.0 * log(d) / log(10.0);
1489 }
1490
1491 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1492                            int frame_size)
1493 {
1494     AVCodecContext *enc;
1495     int frame_number;
1496     double ti1, bitrate, avg_bitrate;
1497
1498     /* this is executed just the first time do_video_stats is called */
1499     if (!vstats_file) {
1500         vstats_file = fopen(vstats_filename, "w");
1501         if (!vstats_file) {
1502             perror("fopen");
1503             exit_program(1);
1504         }
1505     }
1506
1507     enc = ost->st->codec;
1508     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1509         frame_number = ost->frame_number;
1510         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1511         if (enc->flags&CODEC_FLAG_PSNR)
1512             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1513
1514         fprintf(vstats_file,"f_size= %6d ", frame_size);
1515         /* compute pts value */
1516         ti1 = ost->sync_opts * av_q2d(enc->time_base);
1517         if (ti1 < 0.01)
1518             ti1 = 0.01;
1519
1520         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1521         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1522         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1523                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1524         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1525     }
1526 }
1527
1528 /* check for new output on any of the filtergraphs */
1529 static int poll_filters(void)
1530 {
1531     AVFilterBufferRef *picref;
1532     AVFrame *filtered_frame = NULL;
1533     int i, frame_size;
1534
1535     for (i = 0; i < nb_output_streams; i++) {
1536         OutputStream *ost = output_streams[i];
1537         OutputFile    *of = output_files[ost->file_index];
1538         int ret = 0;
1539
1540         if (!ost->filter)
1541             continue;
1542
1543         if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1544             return AVERROR(ENOMEM);
1545         } else
1546             avcodec_get_frame_defaults(ost->filtered_frame);
1547         filtered_frame = ost->filtered_frame;
1548
1549         while (ret >= 0 && !ost->is_past_recording_time) {
1550             if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1551                 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1552                 ret = av_buffersink_read_samples(ost->filter->filter, &picref,
1553                                                  ost->st->codec->frame_size);
1554             else
1555                 ret = av_buffersink_read(ost->filter->filter, &picref);
1556
1557             if (ret < 0)
1558                 break;
1559
1560             avfilter_copy_buf_props(filtered_frame, picref);
1561             if (picref->pts != AV_NOPTS_VALUE)
1562                 filtered_frame->pts = av_rescale_q(picref->pts,
1563                                                    ost->filter->filter->inputs[0]->time_base,
1564                                                    ost->st->codec->time_base) -
1565                                       av_rescale_q(of->start_time,
1566                                                    AV_TIME_BASE_Q,
1567                                                    ost->st->codec->time_base);
1568
1569             if (of->start_time && filtered_frame->pts < of->start_time) {
1570                 avfilter_unref_buffer(picref);
1571                 continue;
1572             }
1573
1574             switch (ost->filter->filter->inputs[0]->type) {
1575             case AVMEDIA_TYPE_VIDEO:
1576                 if (!ost->frame_aspect_ratio)
1577                     ost->st->codec->sample_aspect_ratio = picref->video->pixel_aspect;
1578
1579                 do_video_out(of->ctx, ost, filtered_frame, &frame_size,
1580                              same_quant ? ost->last_quality :
1581                                           ost->st->codec->global_quality);
1582                 if (vstats_filename && frame_size)
1583                     do_video_stats(of->ctx, ost, frame_size);
1584                 break;
1585             case AVMEDIA_TYPE_AUDIO:
1586                 do_audio_out(of->ctx, ost, filtered_frame);
1587                 break;
1588             default:
1589                 // TODO support subtitle filters
1590                 av_assert0(0);
1591             }
1592
1593             avfilter_unref_buffer(picref);
1594         }
1595     }
1596     return 0;
1597 }
1598
1599 static void print_report(int is_last_report, int64_t timer_start)
1600 {
1601     char buf[1024];
1602     OutputStream *ost;
1603     AVFormatContext *oc;
1604     int64_t total_size;
1605     AVCodecContext *enc;
1606     int frame_number, vid, i;
1607     double bitrate, ti1, pts;
1608     static int64_t last_time = -1;
1609     static int qp_histogram[52];
1610
1611     if (!print_stats && !is_last_report)
1612         return;
1613
1614     if (!is_last_report) {
1615         int64_t cur_time;
1616         /* display the report every 0.5 seconds */
1617         cur_time = av_gettime();
1618         if (last_time == -1) {
1619             last_time = cur_time;
1620             return;
1621         }
1622         if ((cur_time - last_time) < 500000)
1623             return;
1624         last_time = cur_time;
1625     }
1626
1627
1628     oc = output_files[0]->ctx;
1629
1630     total_size = avio_size(oc->pb);
1631     if (total_size < 0) // FIXME improve avio_size() so it works with non seekable output too
1632         total_size = avio_tell(oc->pb);
1633
1634     buf[0] = '\0';
1635     ti1 = 1e10;
1636     vid = 0;
1637     for (i = 0; i < nb_output_streams; i++) {
1638         float q = -1;
1639         ost = output_streams[i];
1640         enc = ost->st->codec;
1641         if (!ost->stream_copy && enc->coded_frame)
1642             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1643         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1644             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1645         }
1646         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1647             float t = (av_gettime() - timer_start) / 1000000.0;
1648
1649             frame_number = ost->frame_number;
1650             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1651                      frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
1652             if (is_last_report)
1653                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1654             if (qp_hist) {
1655                 int j;
1656                 int qp = lrintf(q);
1657                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1658                     qp_histogram[qp]++;
1659                 for (j = 0; j < 32; j++)
1660                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1661             }
1662             if (enc->flags&CODEC_FLAG_PSNR) {
1663                 int j;
1664                 double error, error_sum = 0;
1665                 double scale, scale_sum = 0;
1666                 char type[3] = { 'Y','U','V' };
1667                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1668                 for (j = 0; j < 3; j++) {
1669                     if (is_last_report) {
1670                         error = enc->error[j];
1671                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1672                     } else {
1673                         error = enc->coded_frame->error[j];
1674                         scale = enc->width * enc->height * 255.0 * 255.0;
1675                     }
1676                     if (j)
1677                         scale /= 4;
1678                     error_sum += error;
1679                     scale_sum += scale;
1680                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1681                 }
1682                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1683             }
1684             vid = 1;
1685         }
1686         /* compute min output value */
1687         pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
1688         if ((pts < ti1) && (pts > 0))
1689             ti1 = pts;
1690     }
1691     if (ti1 < 0.01)
1692         ti1 = 0.01;
1693
1694     bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1695
1696     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1697             "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
1698             (double)total_size / 1024, ti1, bitrate);
1699
1700     if (nb_frames_dup || nb_frames_drop)
1701         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1702                 nb_frames_dup, nb_frames_drop);
1703
1704     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
1705
1706     fflush(stderr);
1707
1708     if (is_last_report) {
1709         int64_t raw= audio_size + video_size + extra_size;
1710         av_log(NULL, AV_LOG_INFO, "\n");
1711         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1712                video_size / 1024.0,
1713                audio_size / 1024.0,
1714                extra_size / 1024.0,
1715                100.0 * (total_size - raw) / raw
1716         );
1717     }
1718 }
1719
1720 static void flush_encoders(void)
1721 {
1722     int i, ret;
1723
1724     for (i = 0; i < nb_output_streams; i++) {
1725         OutputStream   *ost = output_streams[i];
1726         AVCodecContext *enc = ost->st->codec;
1727         AVFormatContext *os = output_files[ost->file_index]->ctx;
1728         int stop_encoding = 0;
1729
1730         if (!ost->encoding_needed)
1731             continue;
1732
1733         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1734             continue;
1735         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1736             continue;
1737
1738         for (;;) {
1739             int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1740             const char *desc;
1741             int64_t *size;
1742
1743             switch (ost->st->codec->codec_type) {
1744             case AVMEDIA_TYPE_AUDIO:
1745                 encode = avcodec_encode_audio2;
1746                 desc   = "Audio";
1747                 size   = &audio_size;
1748                 break;
1749             case AVMEDIA_TYPE_VIDEO:
1750                 encode = avcodec_encode_video2;
1751                 desc   = "Video";
1752                 size   = &video_size;
1753                 break;
1754             default:
1755                 stop_encoding = 1;
1756             }
1757
1758             if (encode) {
1759                 AVPacket pkt;
1760                 int got_packet;
1761                 av_init_packet(&pkt);
1762                 pkt.data = NULL;
1763                 pkt.size = 0;
1764
1765                 ret = encode(enc, &pkt, NULL, &got_packet);
1766                 if (ret < 0) {
1767                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1768                     exit_program(1);
1769                 }
1770                 *size += ret;
1771                 if (ost->logfile && enc->stats_out) {
1772                     fprintf(ost->logfile, "%s", enc->stats_out);
1773                 }
1774                 if (!got_packet) {
1775                     stop_encoding = 1;
1776                     break;
1777                 }
1778                 if (pkt.pts != AV_NOPTS_VALUE)
1779                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1780                 if (pkt.dts != AV_NOPTS_VALUE)
1781                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1782                 write_frame(os, &pkt, ost);
1783             }
1784
1785             if (stop_encoding)
1786                 break;
1787         }
1788     }
1789 }
1790
1791 /*
1792  * Check whether a packet from ist should be written into ost at this time
1793  */
1794 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1795 {
1796     OutputFile *of = output_files[ost->file_index];
1797     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
1798
1799     if (ost->source_index != ist_index)
1800         return 0;
1801
1802     if (of->start_time && ist->last_dts < of->start_time)
1803         return 0;
1804
1805     return 1;
1806 }
1807
1808 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1809 {
1810     OutputFile *of = output_files[ost->file_index];
1811     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1812     AVPacket opkt;
1813
1814     av_init_packet(&opkt);
1815
1816     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1817         !ost->copy_initial_nonkeyframes)
1818         return;
1819
1820     if (of->recording_time != INT64_MAX &&
1821         ist->last_dts >= of->recording_time + of->start_time) {
1822         ost->is_past_recording_time = 1;
1823         return;
1824     }
1825
1826     /* force the input stream PTS */
1827     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1828         audio_size += pkt->size;
1829     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1830         video_size += pkt->size;
1831         ost->sync_opts++;
1832     }
1833
1834     if (pkt->pts != AV_NOPTS_VALUE)
1835         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1836     else
1837         opkt.pts = AV_NOPTS_VALUE;
1838
1839     if (pkt->dts == AV_NOPTS_VALUE)
1840         opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
1841     else
1842         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1843     opkt.dts -= ost_tb_start_time;
1844
1845     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1846     opkt.flags    = pkt->flags;
1847
1848     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1849     if (  ost->st->codec->codec_id != CODEC_ID_H264
1850        && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1851        && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1852        && ost->st->codec->codec_id != CODEC_ID_VC1
1853        ) {
1854         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1855             opkt.destruct = av_destruct_packet;
1856     } else {
1857         opkt.data = pkt->data;
1858         opkt.size = pkt->size;
1859     }
1860
1861     write_frame(of->ctx, &opkt, ost);
1862     ost->st->codec->frame_number++;
1863     av_free_packet(&opkt);
1864 }
1865
1866 static void rate_emu_sleep(InputStream *ist)
1867 {
1868     if (input_files[ist->file_index]->rate_emu) {
1869         int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
1870         int64_t now = av_gettime() - ist->start;
1871         if (pts > now)
1872             av_usleep(pts - now);
1873     }
1874 }
1875
1876 static int guess_input_channel_layout(InputStream *ist)
1877 {
1878     AVCodecContext *dec = ist->st->codec;
1879
1880     if (!dec->channel_layout) {
1881         char layout_name[256];
1882
1883         dec->channel_layout = av_get_default_channel_layout(dec->channels);
1884         if (!dec->channel_layout)
1885             return 0;
1886         av_get_channel_layout_string(layout_name, sizeof(layout_name),
1887                                      dec->channels, dec->channel_layout);
1888         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
1889                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1890     }
1891     return 1;
1892 }
1893
1894 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1895 {
1896     AVFrame *decoded_frame;
1897     AVCodecContext *avctx = ist->st->codec;
1898     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1899     int i, ret, resample_changed;
1900
1901     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1902         return AVERROR(ENOMEM);
1903     else
1904         avcodec_get_frame_defaults(ist->decoded_frame);
1905     decoded_frame = ist->decoded_frame;
1906
1907     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1908     if (ret < 0) {
1909         return ret;
1910     }
1911
1912     if (!*got_output) {
1913         /* no audio frame */
1914         if (!pkt->size)
1915             for (i = 0; i < ist->nb_filters; i++)
1916                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
1917         return ret;
1918     }
1919
1920     /* if the decoder provides a pts, use it instead of the last packet pts.
1921        the decoder could be delaying output by a packet or more. */
1922     if (decoded_frame->pts != AV_NOPTS_VALUE)
1923         ist->next_dts = decoded_frame->pts;
1924     else if (pkt->pts != AV_NOPTS_VALUE) {
1925         decoded_frame->pts = pkt->pts;
1926         pkt->pts           = AV_NOPTS_VALUE;
1927     }
1928
1929     // preprocess audio (volume)
1930     if (audio_volume != 256) {
1931         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1932         void *samples = decoded_frame->data[0];
1933         switch (avctx->sample_fmt) {
1934         case AV_SAMPLE_FMT_U8:
1935         {
1936             uint8_t *volp = samples;
1937             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1938                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1939                 *volp++ = av_clip_uint8(v);
1940             }
1941             break;
1942         }
1943         case AV_SAMPLE_FMT_S16:
1944         {
1945             int16_t *volp = samples;
1946             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1947                 int v = ((*volp) * audio_volume + 128) >> 8;
1948                 *volp++ = av_clip_int16(v);
1949             }
1950             break;
1951         }
1952         case AV_SAMPLE_FMT_S32:
1953         {
1954             int32_t *volp = samples;
1955             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1956                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1957                 *volp++ = av_clipl_int32(v);
1958             }
1959             break;
1960         }
1961         case AV_SAMPLE_FMT_FLT:
1962         {
1963             float *volp = samples;
1964             float scale = audio_volume / 256.f;
1965             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1966                 *volp++ *= scale;
1967             }
1968             break;
1969         }
1970         case AV_SAMPLE_FMT_DBL:
1971         {
1972             double *volp = samples;
1973             double scale = audio_volume / 256.;
1974             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1975                 *volp++ *= scale;
1976             }
1977             break;
1978         }
1979         default:
1980             av_log(NULL, AV_LOG_FATAL,
1981                    "Audio volume adjustment on sample format %s is not supported.\n",
1982                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1983             exit_program(1);
1984         }
1985     }
1986
1987     rate_emu_sleep(ist);
1988
1989     resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
1990                        ist->resample_channels       != avctx->channels               ||
1991                        ist->resample_channel_layout != decoded_frame->channel_layout ||
1992                        ist->resample_sample_rate    != decoded_frame->sample_rate;
1993     if (resample_changed) {
1994         char layout1[64], layout2[64];
1995
1996         if (!guess_input_channel_layout(ist)) {
1997             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1998                    "layout for Input Stream #%d.%d\n", ist->file_index,
1999                    ist->st->index);
2000             exit_program(1);
2001         }
2002         decoded_frame->channel_layout = avctx->channel_layout;
2003
2004         av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
2005                                      ist->resample_channel_layout);
2006         av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
2007                                      decoded_frame->channel_layout);
2008
2009         av_log(NULL, AV_LOG_INFO,
2010                "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",
2011                ist->file_index, ist->st->index,
2012                ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
2013                ist->resample_channels, layout1,
2014                decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
2015                avctx->channels, layout2);
2016
2017         ist->resample_sample_fmt     = decoded_frame->format;
2018         ist->resample_sample_rate    = decoded_frame->sample_rate;
2019         ist->resample_channel_layout = decoded_frame->channel_layout;
2020         ist->resample_channels       = avctx->channels;
2021
2022         for (i = 0; i < nb_filtergraphs; i++)
2023             if (ist_in_filtergraph(filtergraphs[i], ist) &&
2024                 configure_filtergraph(filtergraphs[i]) < 0) {
2025                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2026                 exit_program(1);
2027             }
2028     }
2029
2030     for (i = 0; i < ist->nb_filters; i++)
2031         av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
2032
2033     return ret;
2034 }
2035
2036 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
2037 {
2038     AVFrame *decoded_frame;
2039     void *buffer_to_free = NULL;
2040     int i, ret = 0, resample_changed;
2041     float quality;
2042
2043     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2044         return AVERROR(ENOMEM);
2045     else
2046         avcodec_get_frame_defaults(ist->decoded_frame);
2047     decoded_frame = ist->decoded_frame;
2048
2049     ret = avcodec_decode_video2(ist->st->codec,
2050                                 decoded_frame, got_output, pkt);
2051     if (ret < 0)
2052         return ret;
2053
2054     quality = same_quant ? decoded_frame->quality : 0;
2055     if (!*got_output) {
2056         /* no picture yet */
2057         if (!pkt->size)
2058             for (i = 0; i < ist->nb_filters; i++)
2059                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
2060         return ret;
2061     }
2062     decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
2063                                            decoded_frame->pkt_dts);
2064     pkt->size = 0;
2065     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2066
2067     rate_emu_sleep(ist);
2068
2069     if (ist->st->sample_aspect_ratio.num)
2070         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2071
2072     resample_changed = ist->resample_width   != decoded_frame->width  ||
2073                        ist->resample_height  != decoded_frame->height ||
2074                        ist->resample_pix_fmt != decoded_frame->format;
2075     if (resample_changed) {
2076         av_log(NULL, AV_LOG_INFO,
2077                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2078                ist->file_index, ist->st->index,
2079                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
2080                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2081
2082         ist->resample_width   = decoded_frame->width;
2083         ist->resample_height  = decoded_frame->height;
2084         ist->resample_pix_fmt = decoded_frame->format;
2085
2086         for (i = 0; i < nb_filtergraphs; i++)
2087             if (ist_in_filtergraph(filtergraphs[i], ist) &&
2088                 configure_filtergraph(filtergraphs[i]) < 0) {
2089                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2090                 exit_program(1);
2091             }
2092     }
2093
2094     for (i = 0; i < ist->nb_filters; i++) {
2095         // XXX what an ugly hack
2096         if (ist->filters[i]->graph->nb_outputs == 1)
2097             ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2098
2099         if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
2100             FrameBuffer      *buf = decoded_frame->opaque;
2101             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2102                                         decoded_frame->data, decoded_frame->linesize,
2103                                         AV_PERM_READ | AV_PERM_PRESERVE,
2104                                         ist->st->codec->width, ist->st->codec->height,
2105                                         ist->st->codec->pix_fmt);
2106
2107             avfilter_copy_frame_props(fb, decoded_frame);
2108             fb->buf->priv           = buf;
2109             fb->buf->free           = filter_release_buffer;
2110
2111             buf->refcount++;
2112             av_buffersrc_buffer(ist->filters[i]->filter, fb);
2113         } else
2114             av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
2115     }
2116
2117     av_free(buffer_to_free);
2118     return ret;
2119 }
2120
2121 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2122 {
2123     AVSubtitle subtitle;
2124     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2125                                           &subtitle, got_output, pkt);
2126     if (ret < 0)
2127         return ret;
2128     if (!*got_output)
2129         return ret;
2130
2131     rate_emu_sleep(ist);
2132
2133     for (i = 0; i < nb_output_streams; i++) {
2134         OutputStream *ost = output_streams[i];
2135
2136         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2137             continue;
2138
2139         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2140     }
2141
2142     avsubtitle_free(&subtitle);
2143     return ret;
2144 }
2145
2146 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2147 static int output_packet(InputStream *ist, const AVPacket *pkt)
2148 {
2149     int i;
2150     int got_output;
2151     AVPacket avpkt;
2152
2153     if (ist->next_dts == AV_NOPTS_VALUE)
2154         ist->next_dts = ist->last_dts;
2155
2156     if (pkt == NULL) {
2157         /* EOF handling */
2158         av_init_packet(&avpkt);
2159         avpkt.data = NULL;
2160         avpkt.size = 0;
2161         goto handle_eof;
2162     } else {
2163         avpkt = *pkt;
2164     }
2165
2166     if (pkt->dts != AV_NOPTS_VALUE)
2167         ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2168
2169     // while we have more to decode or while the decoder did output something on EOF
2170     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2171         int ret = 0;
2172     handle_eof:
2173
2174         ist->last_dts = ist->next_dts;
2175
2176         if (avpkt.size && avpkt.size != pkt->size) {
2177             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2178                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2179             ist->showed_multi_packet_warning = 1;
2180         }
2181
2182         switch (ist->st->codec->codec_type) {
2183         case AVMEDIA_TYPE_AUDIO:
2184             ret = decode_audio    (ist, &avpkt, &got_output);
2185             break;
2186         case AVMEDIA_TYPE_VIDEO:
2187             ret = decode_video    (ist, &avpkt, &got_output);
2188             if (avpkt.duration)
2189                 ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2190             else if (ist->st->r_frame_rate.num)
2191                 ist->next_dts += av_rescale_q(1, (AVRational){ist->st->r_frame_rate.den,
2192                                                               ist->st->r_frame_rate.num},
2193                                               AV_TIME_BASE_Q);
2194             else if (ist->st->codec->time_base.num != 0) {
2195                 int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
2196                                                    ist->st->codec->ticks_per_frame;
2197                 ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
2198             }
2199             break;
2200         case AVMEDIA_TYPE_SUBTITLE:
2201             ret = transcode_subtitles(ist, &avpkt, &got_output);
2202             break;
2203         default:
2204             return -1;
2205         }
2206
2207         if (ret < 0)
2208             return ret;
2209         // touch data and size only if not EOF
2210         if (pkt) {
2211             avpkt.data += ret;
2212             avpkt.size -= ret;
2213         }
2214         if (!got_output) {
2215             continue;
2216         }
2217     }
2218
2219     /* handle stream copy */
2220     if (!ist->decoding_needed) {
2221         rate_emu_sleep(ist);
2222         ist->last_dts = ist->next_dts;
2223         switch (ist->st->codec->codec_type) {
2224         case AVMEDIA_TYPE_AUDIO:
2225             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2226                              ist->st->codec->sample_rate;
2227             break;
2228         case AVMEDIA_TYPE_VIDEO:
2229             if (ist->st->codec->time_base.num != 0) {
2230                 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2231                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2232                                   ist->st->codec->time_base.num * ticks) /
2233                                   ist->st->codec->time_base.den;
2234             }
2235             break;
2236         }
2237     }
2238     for (i = 0; pkt && i < nb_output_streams; i++) {
2239         OutputStream *ost = output_streams[i];
2240
2241         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2242             continue;
2243
2244         do_streamcopy(ist, ost, pkt);
2245     }
2246
2247     return 0;
2248 }
2249
2250 static void print_sdp(void)
2251 {
2252     char sdp[2048];
2253     int i;
2254     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2255
2256     if (!avc)
2257         exit_program(1);
2258     for (i = 0; i < nb_output_files; i++)
2259         avc[i] = output_files[i]->ctx;
2260
2261     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2262     printf("SDP:\n%s\n", sdp);
2263     fflush(stdout);
2264     av_freep(&avc);
2265 }
2266
2267 static int init_input_stream(int ist_index, char *error, int error_len)
2268 {
2269     int i;
2270     InputStream *ist = input_streams[ist_index];
2271     if (ist->decoding_needed) {
2272         AVCodec *codec = ist->dec;
2273         if (!codec) {
2274             snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2275                     ist->st->codec->codec_id, ist->file_index, ist->st->index);
2276             return AVERROR(EINVAL);
2277         }
2278
2279         /* update requested sample format for the decoder based on the
2280            corresponding encoder sample format */
2281         for (i = 0; i < nb_output_streams; i++) {
2282             OutputStream *ost = output_streams[i];
2283             if (ost->source_index == ist_index) {
2284                 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
2285                 break;
2286             }
2287         }
2288
2289         if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
2290             ist->st->codec->get_buffer     = codec_get_buffer;
2291             ist->st->codec->release_buffer = codec_release_buffer;
2292             ist->st->codec->opaque         = &ist->buffer_pool;
2293         }
2294
2295         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2296             av_dict_set(&ist->opts, "threads", "auto", 0);
2297         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2298             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2299                     ist->file_index, ist->st->index);
2300             return AVERROR(EINVAL);
2301         }
2302         assert_codec_experimental(ist->st->codec, 0);
2303         assert_avoptions(ist->opts);
2304     }
2305
2306     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;
2307     ist->next_dts = AV_NOPTS_VALUE;
2308     init_pts_correction(&ist->pts_ctx);
2309     ist->is_start = 1;
2310
2311     return 0;
2312 }
2313
2314 static InputStream *get_input_stream(OutputStream *ost)
2315 {
2316     if (ost->source_index >= 0)
2317         return input_streams[ost->source_index];
2318
2319     if (ost->filter) {
2320         FilterGraph *fg = ost->filter->graph;
2321         int i;
2322
2323         for (i = 0; i < fg->nb_inputs; i++)
2324             if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2325                 return fg->inputs[i]->ist;
2326     }
2327
2328     return NULL;
2329 }
2330
2331 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2332                                     AVCodecContext *avctx)
2333 {
2334     char *p;
2335     int n = 1, i;
2336     int64_t t;
2337
2338     for (p = kf; *p; p++)
2339         if (*p == ',')
2340             n++;
2341     ost->forced_kf_count = n;
2342     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
2343     if (!ost->forced_kf_pts) {
2344         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2345         exit_program(1);
2346     }
2347     for (i = 0; i < n; i++) {
2348         p = i ? strchr(p, ',') + 1 : kf;
2349         t = parse_time_or_die("force_key_frames", p, 1);
2350         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2351     }
2352 }
2353
2354 static int transcode_init(void)
2355 {
2356     int ret = 0, i, j, k;
2357     AVFormatContext *oc;
2358     AVCodecContext *codec, *icodec;
2359     OutputStream *ost;
2360     InputStream *ist;
2361     char error[1024];
2362     int want_sdp = 1;
2363
2364     /* init framerate emulation */
2365     for (i = 0; i < nb_input_files; i++) {
2366         InputFile *ifile = input_files[i];
2367         if (ifile->rate_emu)
2368             for (j = 0; j < ifile->nb_streams; j++)
2369                 input_streams[j + ifile->ist_index]->start = av_gettime();
2370     }
2371
2372     /* output stream init */
2373     for (i = 0; i < nb_output_files; i++) {
2374         oc = output_files[i]->ctx;
2375         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2376             av_dump_format(oc, i, oc->filename, 1);
2377             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2378             return AVERROR(EINVAL);
2379         }
2380     }
2381
2382     /* init complex filtergraphs */
2383     for (i = 0; i < nb_filtergraphs; i++)
2384         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2385             return ret;
2386
2387     /* for each output stream, we compute the right encoding parameters */
2388     for (i = 0; i < nb_output_streams; i++) {
2389         ost = output_streams[i];
2390         oc  = output_files[ost->file_index]->ctx;
2391         ist = get_input_stream(ost);
2392
2393         if (ost->attachment_filename)
2394             continue;
2395
2396         codec  = ost->st->codec;
2397
2398         if (ist) {
2399             icodec = ist->st->codec;
2400
2401             ost->st->disposition          = ist->st->disposition;
2402             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2403             codec->chroma_sample_location = icodec->chroma_sample_location;
2404         }
2405
2406         if (ost->stream_copy) {
2407             uint64_t extra_size;
2408
2409             av_assert0(ist && !ost->filter);
2410
2411             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2412
2413             if (extra_size > INT_MAX) {
2414                 return AVERROR(EINVAL);
2415             }
2416
2417             /* if stream_copy is selected, no need to decode or encode */
2418             codec->codec_id   = icodec->codec_id;
2419             codec->codec_type = icodec->codec_type;
2420
2421             if (!codec->codec_tag) {
2422                 if (!oc->oformat->codec_tag ||
2423                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2424                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2425                     codec->codec_tag = icodec->codec_tag;
2426             }
2427
2428             codec->bit_rate       = icodec->bit_rate;
2429             codec->rc_max_rate    = icodec->rc_max_rate;
2430             codec->rc_buffer_size = icodec->rc_buffer_size;
2431             codec->field_order    = icodec->field_order;
2432             codec->extradata      = av_mallocz(extra_size);
2433             if (!codec->extradata) {
2434                 return AVERROR(ENOMEM);
2435             }
2436             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2437             codec->extradata_size = icodec->extradata_size;
2438             if (!copy_tb) {
2439                 codec->time_base      = icodec->time_base;
2440                 codec->time_base.num *= icodec->ticks_per_frame;
2441                 av_reduce(&codec->time_base.num, &codec->time_base.den,
2442                           codec->time_base.num, codec->time_base.den, INT_MAX);
2443             } else
2444                 codec->time_base = ist->st->time_base;
2445
2446             switch (codec->codec_type) {
2447             case AVMEDIA_TYPE_AUDIO:
2448                 if (audio_volume != 256) {
2449                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2450                     exit_program(1);
2451                 }
2452                 codec->channel_layout     = icodec->channel_layout;
2453                 codec->sample_rate        = icodec->sample_rate;
2454                 codec->channels           = icodec->channels;
2455                 codec->frame_size         = icodec->frame_size;
2456                 codec->audio_service_type = icodec->audio_service_type;
2457                 codec->block_align        = icodec->block_align;
2458                 break;
2459             case AVMEDIA_TYPE_VIDEO:
2460                 codec->pix_fmt            = icodec->pix_fmt;
2461                 codec->width              = icodec->width;
2462                 codec->height             = icodec->height;
2463                 codec->has_b_frames       = icodec->has_b_frames;
2464                 if (!codec->sample_aspect_ratio.num) {
2465                     codec->sample_aspect_ratio   =
2466                     ost->st->sample_aspect_ratio =
2467                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2468                         ist->st->codec->sample_aspect_ratio.num ?
2469                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2470                 }
2471                 break;
2472             case AVMEDIA_TYPE_SUBTITLE:
2473                 codec->width  = icodec->width;
2474                 codec->height = icodec->height;
2475                 break;
2476             case AVMEDIA_TYPE_DATA:
2477             case AVMEDIA_TYPE_ATTACHMENT:
2478                 break;
2479             default:
2480                 abort();
2481             }
2482         } else {
2483             if (!ost->enc) {
2484                 /* should only happen when a default codec is not present. */
2485                 snprintf(error, sizeof(error), "Automatic encoder selection "
2486                          "failed for output stream #%d:%d. Default encoder for "
2487                          "format %s is probably disabled. Please choose an "
2488                          "encoder manually.\n", ost->file_index, ost->index,
2489                          oc->oformat->name);
2490                 ret = AVERROR(EINVAL);
2491                 goto dump_format;
2492             }
2493
2494             if (ist)
2495                 ist->decoding_needed = 1;
2496             ost->encoding_needed = 1;
2497
2498             /*
2499              * We want CFR output if and only if one of those is true:
2500              * 1) user specified output framerate with -r
2501              * 2) user specified -vsync cfr
2502              * 3) output format is CFR and the user didn't force vsync to
2503              *    something else than CFR
2504              *
2505              * in such a case, set ost->frame_rate
2506              */
2507             if (codec->codec_type == AVMEDIA_TYPE_VIDEO &&
2508                 !ost->frame_rate.num && ist &&
2509                 (video_sync_method ==  VSYNC_CFR ||
2510                  (video_sync_method ==  VSYNC_AUTO &&
2511                   !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
2512                 ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2513                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2514                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2515                     ost->frame_rate = ost->enc->supported_framerates[idx];
2516                 }
2517             }
2518
2519             if (!ost->filter &&
2520                 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2521                  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2522                     FilterGraph *fg;
2523                     fg = init_simple_filtergraph(ist, ost);
2524                     if (configure_filtergraph(fg)) {
2525                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2526                         exit(1);
2527                     }
2528             }
2529
2530             switch (codec->codec_type) {
2531             case AVMEDIA_TYPE_AUDIO:
2532                 codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
2533                 codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
2534                 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2535                 codec->channels       = av_get_channel_layout_nb_channels(codec->channel_layout);
2536                 codec->time_base      = (AVRational){ 1, codec->sample_rate };
2537                 break;
2538             case AVMEDIA_TYPE_VIDEO:
2539                 codec->time_base = ost->filter->filter->inputs[0]->time_base;
2540
2541                 codec->width  = ost->filter->filter->inputs[0]->w;
2542                 codec->height = ost->filter->filter->inputs[0]->h;
2543                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2544                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2545                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2546                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
2547                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2548
2549                 if (codec->width   != icodec->width  ||
2550                     codec->height  != icodec->height ||
2551                     codec->pix_fmt != icodec->pix_fmt) {
2552                     codec->bits_per_raw_sample = 0;
2553                 }
2554
2555                 if (ost->forced_keyframes)
2556                     parse_forced_key_frames(ost->forced_keyframes, ost,
2557                                             ost->st->codec);
2558                 break;
2559             case AVMEDIA_TYPE_SUBTITLE:
2560                 codec->time_base = (AVRational){1, 1000};
2561                 break;
2562             default:
2563                 abort();
2564                 break;
2565             }
2566             /* two pass mode */
2567             if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2568                 char logfilename[1024];
2569                 FILE *f;
2570
2571                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2572                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2573                          i);
2574                 if (!strcmp(ost->enc->name, "libx264")) {
2575                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2576                 } else {
2577                     if (codec->flags & CODEC_FLAG_PASS1) {
2578                         f = fopen(logfilename, "wb");
2579                         if (!f) {
2580                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2581                                    logfilename, strerror(errno));
2582                             exit_program(1);
2583                         }
2584                         ost->logfile = f;
2585                     } else {
2586                         char  *logbuffer;
2587                         size_t logbuffer_size;
2588                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2589                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2590                                    logfilename);
2591                             exit_program(1);
2592                         }
2593                         codec->stats_in = logbuffer;
2594                     }
2595                 }
2596             }
2597         }
2598     }
2599
2600     /* open each encoder */
2601     for (i = 0; i < nb_output_streams; i++) {
2602         ost = output_streams[i];
2603         if (ost->encoding_needed) {
2604             AVCodec      *codec = ost->enc;
2605             AVCodecContext *dec = NULL;
2606
2607             if ((ist = get_input_stream(ost)))
2608                 dec = ist->st->codec;
2609             if (dec && dec->subtitle_header) {
2610                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2611                 if (!ost->st->codec->subtitle_header) {
2612                     ret = AVERROR(ENOMEM);
2613                     goto dump_format;
2614                 }
2615                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2616                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2617             }
2618             if (!av_dict_get(ost->opts, "threads", NULL, 0))
2619                 av_dict_set(&ost->opts, "threads", "auto", 0);
2620             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2621                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2622                         ost->file_index, ost->index);
2623                 ret = AVERROR(EINVAL);
2624                 goto dump_format;
2625             }
2626             assert_codec_experimental(ost->st->codec, 1);
2627             assert_avoptions(ost->opts);
2628             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2629                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2630                                              "It takes bits/s as argument, not kbits/s\n");
2631             extra_size += ost->st->codec->extradata_size;
2632
2633             if (ost->st->codec->me_threshold)
2634                 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2635         }
2636     }
2637
2638     /* init input streams */
2639     for (i = 0; i < nb_input_streams; i++)
2640         if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
2641             goto dump_format;
2642
2643     /* discard unused programs */
2644     for (i = 0; i < nb_input_files; i++) {
2645         InputFile *ifile = input_files[i];
2646         for (j = 0; j < ifile->ctx->nb_programs; j++) {
2647             AVProgram *p = ifile->ctx->programs[j];
2648             int discard  = AVDISCARD_ALL;
2649
2650             for (k = 0; k < p->nb_stream_indexes; k++)
2651                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2652                     discard = AVDISCARD_DEFAULT;
2653                     break;
2654                 }
2655             p->discard = discard;
2656         }
2657     }
2658
2659     /* open files and write file headers */
2660     for (i = 0; i < nb_output_files; i++) {
2661         oc = output_files[i]->ctx;
2662         oc->interrupt_callback = int_cb;
2663         if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2664             char errbuf[128];
2665             const char *errbuf_ptr = errbuf;
2666             if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
2667                 errbuf_ptr = strerror(AVUNERROR(ret));
2668             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
2669             ret = AVERROR(EINVAL);
2670             goto dump_format;
2671         }
2672         assert_avoptions(output_files[i]->opts);
2673         if (strcmp(oc->oformat->name, "rtp")) {
2674             want_sdp = 0;
2675         }
2676     }
2677
2678  dump_format:
2679     /* dump the file output parameters - cannot be done before in case
2680        of stream copy */
2681     for (i = 0; i < nb_output_files; i++) {
2682         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2683     }
2684
2685     /* dump the stream mapping */
2686     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2687     for (i = 0; i < nb_input_streams; i++) {
2688         ist = input_streams[i];
2689
2690         for (j = 0; j < ist->nb_filters; j++) {
2691             if (ist->filters[j]->graph->graph_desc) {
2692                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
2693                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2694                        ist->filters[j]->name);
2695                 if (nb_filtergraphs > 1)
2696                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2697                 av_log(NULL, AV_LOG_INFO, "\n");
2698             }
2699         }
2700     }
2701
2702     for (i = 0; i < nb_output_streams; i++) {
2703         ost = output_streams[i];
2704
2705         if (ost->attachment_filename) {
2706             /* an attached file */
2707             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
2708                    ost->attachment_filename, ost->file_index, ost->index);
2709             continue;
2710         }
2711
2712         if (ost->filter && ost->filter->graph->graph_desc) {
2713             /* output from a complex graph */
2714             av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
2715             if (nb_filtergraphs > 1)
2716                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2717
2718             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2719                    ost->index, ost->enc ? ost->enc->name : "?");
2720             continue;
2721         }
2722
2723         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
2724                input_streams[ost->source_index]->file_index,
2725                input_streams[ost->source_index]->st->index,
2726                ost->file_index,
2727                ost->index);
2728         if (ost->sync_ist != input_streams[ost->source_index])
2729             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2730                    ost->sync_ist->file_index,
2731                    ost->sync_ist->st->index);
2732         if (ost->stream_copy)
2733             av_log(NULL, AV_LOG_INFO, " (copy)");
2734         else
2735             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2736                    input_streams[ost->source_index]->dec->name : "?",
2737                    ost->enc ? ost->enc->name : "?");
2738         av_log(NULL, AV_LOG_INFO, "\n");
2739     }
2740
2741     if (ret) {
2742         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2743         return ret;
2744     }
2745
2746     if (want_sdp) {
2747         print_sdp();
2748     }
2749
2750     return 0;
2751 }
2752
2753 /**
2754  * @return 1 if there are still streams where more output is wanted,
2755  *         0 otherwise
2756  */
2757 static int need_output(void)
2758 {
2759     int i;
2760
2761     for (i = 0; i < nb_output_streams; i++) {
2762         OutputStream *ost    = output_streams[i];
2763         OutputFile *of       = output_files[ost->file_index];
2764         AVFormatContext *os  = output_files[ost->file_index]->ctx;
2765
2766         if (ost->is_past_recording_time ||
2767             (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2768             continue;
2769         if (ost->frame_number >= ost->max_frames) {
2770             int j;
2771             for (j = 0; j < of->ctx->nb_streams; j++)
2772                 output_streams[of->ost_index + j]->is_past_recording_time = 1;
2773             continue;
2774         }
2775
2776         return 1;
2777     }
2778
2779     return 0;
2780 }
2781
2782 static int select_input_file(uint8_t *no_packet)
2783 {
2784     int64_t ipts_min = INT64_MAX;
2785     int i, file_index = -1;
2786
2787     for (i = 0; i < nb_input_streams; i++) {
2788         InputStream *ist = input_streams[i];
2789         int64_t ipts     = ist->last_dts;
2790
2791         if (ist->discard || no_packet[ist->file_index])
2792             continue;
2793         if (!input_files[ist->file_index]->eof_reached) {
2794             if (ipts < ipts_min) {
2795                 ipts_min = ipts;
2796                 file_index = ist->file_index;
2797             }
2798         }
2799     }
2800
2801     return file_index;
2802 }
2803
2804 #if HAVE_PTHREADS
2805 static void *input_thread(void *arg)
2806 {
2807     InputFile *f = arg;
2808     int ret = 0;
2809
2810     while (!transcoding_finished && ret >= 0) {
2811         AVPacket pkt;
2812         ret = av_read_frame(f->ctx, &pkt);
2813
2814         if (ret == AVERROR(EAGAIN)) {
2815             av_usleep(10000);
2816             ret = 0;
2817             continue;
2818         } else if (ret < 0)
2819             break;
2820
2821         pthread_mutex_lock(&f->fifo_lock);
2822         while (!av_fifo_space(f->fifo))
2823             pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2824
2825         av_dup_packet(&pkt);
2826         av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2827
2828         pthread_mutex_unlock(&f->fifo_lock);
2829     }
2830
2831     f->finished = 1;
2832     return NULL;
2833 }
2834
2835 static void free_input_threads(void)
2836 {
2837     int i;
2838
2839     if (nb_input_files == 1)
2840         return;
2841
2842     transcoding_finished = 1;
2843
2844     for (i = 0; i < nb_input_files; i++) {
2845         InputFile *f = input_files[i];
2846         AVPacket pkt;
2847
2848         if (!f->fifo || f->joined)
2849             continue;
2850
2851         pthread_mutex_lock(&f->fifo_lock);
2852         while (av_fifo_size(f->fifo)) {
2853             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2854             av_free_packet(&pkt);
2855         }
2856         pthread_cond_signal(&f->fifo_cond);
2857         pthread_mutex_unlock(&f->fifo_lock);
2858
2859         pthread_join(f->thread, NULL);
2860         f->joined = 1;
2861
2862         while (av_fifo_size(f->fifo)) {
2863             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2864             av_free_packet(&pkt);
2865         }
2866         av_fifo_free(f->fifo);
2867     }
2868 }
2869
2870 static int init_input_threads(void)
2871 {
2872     int i, ret;
2873
2874     if (nb_input_files == 1)
2875         return 0;
2876
2877     for (i = 0; i < nb_input_files; i++) {
2878         InputFile *f = input_files[i];
2879
2880         if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2881             return AVERROR(ENOMEM);
2882
2883         pthread_mutex_init(&f->fifo_lock, NULL);
2884         pthread_cond_init (&f->fifo_cond, NULL);
2885
2886         if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2887             return AVERROR(ret);
2888     }
2889     return 0;
2890 }
2891
2892 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2893 {
2894     int ret = 0;
2895
2896     pthread_mutex_lock(&f->fifo_lock);
2897
2898     if (av_fifo_size(f->fifo)) {
2899         av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2900         pthread_cond_signal(&f->fifo_cond);
2901     } else {
2902         if (f->finished)
2903             ret = AVERROR_EOF;
2904         else
2905             ret = AVERROR(EAGAIN);
2906     }
2907
2908     pthread_mutex_unlock(&f->fifo_lock);
2909
2910     return ret;
2911 }
2912 #endif
2913
2914 static int get_input_packet(InputFile *f, AVPacket *pkt)
2915 {
2916 #if HAVE_PTHREADS
2917     if (nb_input_files > 1)
2918         return get_input_packet_mt(f, pkt);
2919 #endif
2920     return av_read_frame(f->ctx, pkt);
2921 }
2922
2923 /*
2924  * The following code is the main loop of the file converter
2925  */
2926 static int transcode(void)
2927 {
2928     int ret, i;
2929     AVFormatContext *is, *os;
2930     OutputStream *ost;
2931     InputStream *ist;
2932     uint8_t *no_packet;
2933     int no_packet_count = 0;
2934     int64_t timer_start;
2935
2936     if (!(no_packet = av_mallocz(nb_input_files)))
2937         exit_program(1);
2938
2939     ret = transcode_init();
2940     if (ret < 0)
2941         goto fail;
2942
2943     av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2944     term_init();
2945
2946     timer_start = av_gettime();
2947
2948 #if HAVE_PTHREADS
2949     if ((ret = init_input_threads()) < 0)
2950         goto fail;
2951 #endif
2952
2953     for (; received_sigterm == 0;) {
2954         int file_index, ist_index;
2955         AVPacket pkt;
2956
2957         /* check if there's any stream where output is still needed */
2958         if (!need_output()) {
2959             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
2960             break;
2961         }
2962
2963         /* select the stream that we must read now */
2964         file_index = select_input_file(no_packet);
2965         /* if none, if is finished */
2966         if (file_index < 0) {
2967             if (no_packet_count) {
2968                 no_packet_count = 0;
2969                 memset(no_packet, 0, nb_input_files);
2970                 av_usleep(10000);
2971                 continue;
2972             }
2973             av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
2974             break;
2975         }
2976
2977         is  = input_files[file_index]->ctx;
2978         ret = get_input_packet(input_files[file_index], &pkt);
2979
2980         if (ret == AVERROR(EAGAIN)) {
2981             no_packet[file_index] = 1;
2982             no_packet_count++;
2983             continue;
2984         }
2985         if (ret < 0) {
2986             input_files[file_index]->eof_reached = 1;
2987
2988             for (i = 0; i < input_files[file_index]->nb_streams; i++) {
2989                 ist = input_streams[input_files[file_index]->ist_index + i];
2990                 if (ist->decoding_needed)
2991                     output_packet(ist, NULL);
2992             }
2993
2994             if (opt_shortest)
2995                 break;
2996             else
2997                 continue;
2998         }
2999
3000         no_packet_count = 0;
3001         memset(no_packet, 0, nb_input_files);
3002
3003         if (do_pkt_dump) {
3004             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3005                              is->streams[pkt.stream_index]);
3006         }
3007         /* the following test is needed in case new streams appear
3008            dynamically in stream : we ignore them */
3009         if (pkt.stream_index >= input_files[file_index]->nb_streams)
3010             goto discard_packet;
3011         ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3012         ist = input_streams[ist_index];
3013         if (ist->discard)
3014             goto discard_packet;
3015
3016         if (pkt.dts != AV_NOPTS_VALUE)
3017             pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3018         if (pkt.pts != AV_NOPTS_VALUE)
3019             pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3020
3021         if (pkt.pts != AV_NOPTS_VALUE)
3022             pkt.pts *= ist->ts_scale;
3023         if (pkt.dts != AV_NOPTS_VALUE)
3024             pkt.dts *= ist->ts_scale;
3025
3026         //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
3027         //        ist->next_dts,
3028         //        pkt.dts, input_files[ist->file_index].ts_offset,
3029         //        ist->st->codec->codec_type);
3030         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
3031             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
3032             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3033             int64_t delta   = pkt_dts - ist->next_dts;
3034             if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
3035                 input_files[ist->file_index]->ts_offset -= delta;
3036                 av_log(NULL, AV_LOG_DEBUG,
3037                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3038                        delta, input_files[ist->file_index]->ts_offset);
3039                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3040                 if (pkt.pts != AV_NOPTS_VALUE)
3041                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3042             }
3043         }
3044
3045         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3046         if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
3047             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3048                    ist->file_index, ist->st->index);
3049             if (exit_on_error)
3050                 exit_program(1);
3051             av_free_packet(&pkt);
3052             continue;
3053         }
3054
3055     discard_packet:
3056         av_free_packet(&pkt);
3057
3058         /* dump report by using the output first video and audio streams */
3059         print_report(0, timer_start);
3060     }
3061 #if HAVE_PTHREADS
3062     free_input_threads();
3063 #endif
3064
3065     /* at the end of stream, we must flush the decoder buffers */
3066     for (i = 0; i < nb_input_streams; i++) {
3067         ist = input_streams[i];
3068         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3069             output_packet(ist, NULL);
3070         }
3071     }
3072     poll_filters();
3073     flush_encoders();
3074
3075     term_exit();
3076
3077     /* write the trailer if needed and close file */
3078     for (i = 0; i < nb_output_files; i++) {
3079         os = output_files[i]->ctx;
3080         av_write_trailer(os);
3081     }
3082
3083     /* dump report by using the first video and audio streams */
3084     print_report(1, timer_start);
3085
3086     /* close each encoder */
3087     for (i = 0; i < nb_output_streams; i++) {
3088         ost = output_streams[i];
3089         if (ost->encoding_needed) {
3090             av_freep(&ost->st->codec->stats_in);
3091             avcodec_close(ost->st->codec);
3092         }
3093     }
3094
3095     /* close each decoder */
3096     for (i = 0; i < nb_input_streams; i++) {
3097         ist = input_streams[i];
3098         if (ist->decoding_needed) {
3099             avcodec_close(ist->st->codec);
3100         }
3101     }
3102
3103     /* finished ! */
3104     ret = 0;
3105
3106  fail:
3107     av_freep(&no_packet);
3108 #if HAVE_PTHREADS
3109     free_input_threads();
3110 #endif
3111
3112     if (output_streams) {
3113         for (i = 0; i < nb_output_streams; i++) {
3114             ost = output_streams[i];
3115             if (ost) {
3116                 if (ost->stream_copy)
3117                     av_freep(&ost->st->codec->extradata);
3118                 if (ost->logfile) {
3119                     fclose(ost->logfile);
3120                     ost->logfile = NULL;
3121                 }
3122                 av_freep(&ost->st->codec->subtitle_header);
3123                 av_free(ost->forced_kf_pts);
3124                 av_dict_free(&ost->opts);
3125             }
3126         }
3127     }
3128     return ret;
3129 }
3130
3131 static double parse_frame_aspect_ratio(const char *arg)
3132 {
3133     int x = 0, y = 0;
3134     double ar = 0;
3135     const char *p;
3136     char *end;
3137
3138     p = strchr(arg, ':');
3139     if (p) {
3140         x = strtol(arg, &end, 10);
3141         if (end == p)
3142             y = strtol(end + 1, &end, 10);
3143         if (x > 0 && y > 0)
3144             ar = (double)x / (double)y;
3145     } else
3146         ar = strtod(arg, NULL);
3147
3148     if (!ar) {
3149         av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
3150         exit_program(1);
3151     }
3152     return ar;
3153 }
3154
3155 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3156 {
3157     return parse_option(o, "codec:a", arg, options);
3158 }
3159
3160 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3161 {
3162     return parse_option(o, "codec:v", arg, options);
3163 }
3164
3165 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3166 {
3167     return parse_option(o, "codec:s", arg, options);
3168 }
3169
3170 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3171 {
3172     return parse_option(o, "codec:d", arg, options);
3173 }
3174
3175 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3176 {
3177     StreamMap *m = NULL;
3178     int i, negative = 0, file_idx;
3179     int sync_file_idx = -1, sync_stream_idx;
3180     char *p, *sync;
3181     char *map;
3182
3183     if (*arg == '-') {
3184         negative = 1;
3185         arg++;
3186     }
3187     map = av_strdup(arg);
3188
3189     /* parse sync stream first, just pick first matching stream */
3190     if (sync = strchr(map, ',')) {
3191         *sync = 0;
3192         sync_file_idx = strtol(sync + 1, &sync, 0);
3193         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3194             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3195             exit_program(1);
3196         }
3197         if (*sync)
3198             sync++;
3199         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3200             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3201                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3202                 sync_stream_idx = i;
3203                 break;
3204             }
3205         if (i == input_files[sync_file_idx]->nb_streams) {
3206             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3207                                        "match any streams.\n", arg);
3208             exit_program(1);
3209         }
3210     }
3211
3212
3213     if (map[0] == '[') {
3214         /* this mapping refers to lavfi output */
3215         const char *c = map + 1;
3216         o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3217                                     &o->nb_stream_maps, o->nb_stream_maps + 1);
3218         m = &o->stream_maps[o->nb_stream_maps - 1];
3219         m->linklabel = av_get_token(&c, "]");
3220         if (!m->linklabel) {
3221             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3222             exit_program(1);
3223         }
3224     } else {
3225         file_idx = strtol(map, &p, 0);
3226         if (file_idx >= nb_input_files || file_idx < 0) {
3227             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3228             exit_program(1);
3229         }
3230         if (negative)
3231             /* disable some already defined maps */
3232             for (i = 0; i < o->nb_stream_maps; i++) {
3233                 m = &o->stream_maps[i];
3234                 if (file_idx == m->file_index &&
3235                     check_stream_specifier(input_files[m->file_index]->ctx,
3236                                            input_files[m->file_index]->ctx->streams[m->stream_index],
3237                                            *p == ':' ? p + 1 : p) > 0)
3238                     m->disabled = 1;
3239             }
3240         else
3241             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3242                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3243                             *p == ':' ? p + 1 : p) <= 0)
3244                     continue;
3245                 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3246                                             &o->nb_stream_maps, o->nb_stream_maps + 1);
3247                 m = &o->stream_maps[o->nb_stream_maps - 1];
3248
3249                 m->file_index   = file_idx;
3250                 m->stream_index = i;
3251
3252                 if (sync_file_idx >= 0) {
3253                     m->sync_file_index   = sync_file_idx;
3254                     m->sync_stream_index = sync_stream_idx;
3255                 } else {
3256                     m->sync_file_index   = file_idx;
3257                     m->sync_stream_index = i;
3258                 }
3259             }
3260     }
3261
3262     if (!m) {
3263         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3264         exit_program(1);
3265     }
3266
3267     av_freep(&map);
3268     return 0;
3269 }
3270
3271 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3272 {
3273     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3274                                 &o->nb_attachments, o->nb_attachments + 1);
3275     o->attachments[o->nb_attachments - 1] = arg;
3276     return 0;
3277 }
3278
3279 /**
3280  * Parse a metadata specifier in arg.
3281  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3282  * @param index for type c/p, chapter/program index is written here
3283  * @param stream_spec for type s, the stream specifier is written here
3284  */
3285 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3286 {
3287     if (*arg) {
3288         *type = *arg;
3289         switch (*arg) {
3290         case 'g':
3291             break;
3292         case 's':
3293             if (*(++arg) && *arg != ':') {
3294                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3295                 exit_program(1);
3296             }
3297             *stream_spec = *arg == ':' ? arg + 1 : "";
3298             break;
3299         case 'c':
3300         case 'p':
3301             if (*(++arg) == ':')
3302                 *index = strtol(++arg, NULL, 0);
3303             break;
3304         default:
3305             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3306             exit_program(1);
3307         }
3308     } else
3309         *type = 'g';
3310 }
3311
3312 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3313 {
3314     AVDictionary **meta_in = NULL;
3315     AVDictionary **meta_out;
3316     int i, ret = 0;
3317     char type_in, type_out;
3318     const char *istream_spec = NULL, *ostream_spec = NULL;
3319     int idx_in = 0, idx_out = 0;
3320
3321     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
3322     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3323
3324     if (type_in == 'g' || type_out == 'g')
3325         o->metadata_global_manual = 1;
3326     if (type_in == 's' || type_out == 's')
3327         o->metadata_streams_manual = 1;
3328     if (type_in == 'c' || type_out == 'c')
3329         o->metadata_chapters_manual = 1;
3330
3331 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3332     if ((index) < 0 || (index) >= (nb_elems)) {\
3333         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3334                 (desc), (index));\
3335         exit_program(1);\
3336     }
3337
3338 #define SET_DICT(type, meta, context, index)\
3339         switch (type) {\
3340         case 'g':\
3341             meta = &context->metadata;\
3342             break;\
3343         case 'c':\
3344             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3345             meta = &context->chapters[index]->metadata;\
3346             break;\
3347         case 'p':\
3348             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3349             meta = &context->programs[index]->metadata;\
3350             break;\
3351         }\
3352
3353     SET_DICT(type_in, meta_in, ic, idx_in);
3354     SET_DICT(type_out, meta_out, oc, idx_out);
3355
3356     /* for input streams choose first matching stream */
3357     if (type_in == 's') {
3358         for (i = 0; i < ic->nb_streams; i++) {
3359             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3360                 meta_in = &ic->streams[i]->metadata;
3361                 break;
3362             } else if (ret < 0)
3363                 exit_program(1);
3364         }
3365         if (!meta_in) {
3366             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
3367             exit_program(1);
3368         }
3369     }
3370
3371     if (type_out == 's') {
3372         for (i = 0; i < oc->nb_streams; i++) {
3373             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3374                 meta_out = &oc->streams[i]->metadata;
3375                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3376             } else if (ret < 0)
3377                 exit_program(1);
3378         }
3379     } else
3380         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3381
3382     return 0;
3383 }
3384
3385 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3386 {
3387     const char *codec_string = encoder ? "encoder" : "decoder";
3388     AVCodec *codec;
3389
3390     codec = encoder ?
3391         avcodec_find_encoder_by_name(name) :
3392         avcodec_find_decoder_by_name(name);
3393     if (!codec) {
3394         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3395         exit_program(1);
3396     }
3397     if (codec->type != type) {
3398         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3399         exit_program(1);
3400     }
3401     return codec;
3402 }
3403
3404 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3405 {
3406     char *codec_name = NULL;
3407
3408     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3409     if (codec_name) {
3410         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3411         st->codec->codec_id = codec->id;
3412         return codec;
3413     } else
3414         return avcodec_find_decoder(st->codec->codec_id);
3415 }
3416
3417 /**
3418  * Add all the streams from the given input file to the global
3419  * list of input streams.
3420  */
3421 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3422 {
3423     int i;
3424
3425     for (i = 0; i < ic->nb_streams; i++) {
3426         AVStream *st = ic->streams[i];
3427         AVCodecContext *dec = st->codec;
3428         InputStream *ist = av_mallocz(sizeof(*ist));
3429         char *framerate = NULL;
3430
3431         if (!ist)
3432             exit_program(1);
3433
3434         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3435         input_streams[nb_input_streams - 1] = ist;
3436
3437         ist->st = st;
3438         ist->file_index = nb_input_files;
3439         ist->discard = 1;
3440         st->discard  = AVDISCARD_ALL;
3441         ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
3442
3443         ist->ts_scale = 1.0;
3444         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3445
3446         ist->dec = choose_decoder(o, ic, st);
3447
3448         switch (dec->codec_type) {
3449         case AVMEDIA_TYPE_VIDEO:
3450             ist->resample_height  = dec->height;
3451             ist->resample_width   = dec->width;
3452             ist->resample_pix_fmt = dec->pix_fmt;
3453
3454             MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
3455             if (framerate && av_parse_video_rate(&ist->framerate,
3456                                                  framerate) < 0) {
3457                 av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
3458                        framerate);
3459                 exit_program(1);
3460             }
3461
3462             break;
3463         case AVMEDIA_TYPE_AUDIO:
3464             guess_input_channel_layout(ist);
3465
3466             ist->resample_sample_fmt     = dec->sample_fmt;
3467             ist->resample_sample_rate    = dec->sample_rate;
3468             ist->resample_channels       = dec->channels;
3469             ist->resample_channel_layout = dec->channel_layout;
3470
3471             break;
3472         case AVMEDIA_TYPE_DATA:
3473         case AVMEDIA_TYPE_SUBTITLE:
3474         case AVMEDIA_TYPE_ATTACHMENT:
3475         case AVMEDIA_TYPE_UNKNOWN:
3476             break;
3477         default:
3478             abort();
3479         }
3480     }
3481 }
3482
3483 static void assert_file_overwrite(const char *filename)
3484 {
3485     if (!file_overwrite &&
3486         (strchr(filename, ':') == NULL || filename[1] == ':' ||
3487          av_strstart(filename, "file:", NULL))) {
3488         if (avio_check(filename, 0) == 0) {
3489             if (!using_stdin) {
3490                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3491                 fflush(stderr);
3492                 if (!read_yesno()) {
3493                     fprintf(stderr, "Not overwriting - exiting\n");
3494                     exit_program(1);
3495                 }
3496             }
3497             else {
3498                 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3499                 exit_program(1);
3500             }
3501         }
3502     }
3503 }
3504
3505 static void dump_attachment(AVStream *st, const char *filename)
3506 {
3507     int ret;
3508     AVIOContext *out = NULL;
3509     AVDictionaryEntry *e;
3510
3511     if (!st->codec->extradata_size) {
3512         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3513                nb_input_files - 1, st->index);
3514         return;
3515     }
3516     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3517         filename = e->value;
3518     if (!*filename) {
3519         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3520                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3521         exit_program(1);
3522     }
3523
3524     assert_file_overwrite(filename);
3525
3526     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3527         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3528                filename);
3529         exit_program(1);
3530     }
3531
3532     avio_write(out, st->codec->extradata, st->codec->extradata_size);
3533     avio_flush(out);
3534     avio_close(out);
3535 }
3536
3537 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3538 {
3539     AVFormatContext *ic;
3540     AVInputFormat *file_iformat = NULL;
3541     int err, i, ret;
3542     int64_t timestamp;
3543     uint8_t buf[128];
3544     AVDictionary **opts;
3545     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
3546
3547     if (o->format) {
3548         if (!(file_iformat = av_find_input_format(o->format))) {
3549             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3550             exit_program(1);
3551         }
3552     }
3553
3554     if (!strcmp(filename, "-"))
3555         filename = "pipe:";
3556
3557     using_stdin |= !strncmp(filename, "pipe:", 5) ||
3558                     !strcmp(filename, "/dev/stdin");
3559
3560     /* get default parameters from command line */
3561     ic = avformat_alloc_context();
3562     if (!ic) {
3563         print_error(filename, AVERROR(ENOMEM));
3564         exit_program(1);
3565     }
3566     if (o->nb_audio_sample_rate) {
3567         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3568         av_dict_set(&format_opts, "sample_rate", buf, 0);
3569     }
3570     if (o->nb_audio_channels) {
3571         /* because we set audio_channels based on both the "ac" and
3572          * "channel_layout" options, we need to check that the specified
3573          * demuxer actually has the "channels" option before setting it */
3574         if (file_iformat && file_iformat->priv_class &&
3575             av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
3576                         AV_OPT_SEARCH_FAKE_OBJ)) {
3577             snprintf(buf, sizeof(buf), "%d",
3578                      o->audio_channels[o->nb_audio_channels - 1].u.i);
3579             av_dict_set(&format_opts, "channels", buf, 0);
3580         }
3581     }
3582     if (o->nb_frame_rates) {
3583         /* set the format-level framerate option;
3584          * this is important for video grabbers, e.g. x11 */
3585         if (file_iformat && file_iformat->priv_class &&
3586             av_opt_find(&file_iformat->priv_class, "framerate", NULL, 0,
3587                         AV_OPT_SEARCH_FAKE_OBJ)) {
3588             av_dict_set(&format_opts, "framerate",
3589                         o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3590         }
3591     }
3592     if (o->nb_frame_sizes) {
3593         av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3594     }
3595     if (o->nb_frame_pix_fmts)
3596         av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3597
3598     ic->flags |= AVFMT_FLAG_NONBLOCK;
3599     ic->interrupt_callback = int_cb;
3600
3601     /* open the input file with generic libav function */
3602     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3603     if (err < 0) {
3604         print_error(filename, err);
3605         exit_program(1);
3606     }
3607     assert_avoptions(format_opts);
3608
3609     /* apply forced codec ids */
3610     for (i = 0; i < ic->nb_streams; i++)
3611         choose_decoder(o, ic, ic->streams[i]);
3612
3613     /* Set AVCodecContext options for avformat_find_stream_info */
3614     opts = setup_find_stream_info_opts(ic, codec_opts);
3615     orig_nb_streams = ic->nb_streams;
3616
3617     /* If not enough info to get the stream parameters, we decode the
3618        first frames to get it. (used in mpeg case for example) */
3619     ret = avformat_find_stream_info(ic, opts);
3620     if (ret < 0) {
3621         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3622         avformat_close_input(&ic);
3623         exit_program(1);
3624     }
3625
3626     timestamp = o->start_time;
3627     /* add the stream start time */
3628     if (ic->start_time != AV_NOPTS_VALUE)
3629         timestamp += ic->start_time;
3630
3631     /* if seeking requested, we execute it */
3632     if (o->start_time != 0) {
3633         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3634         if (ret < 0) {
3635             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3636                    filename, (double)timestamp / AV_TIME_BASE);
3637         }
3638     }
3639
3640     /* update the current parameters so that they match the one of the input stream */
3641     add_input_streams(o, ic);
3642
3643     /* dump the file content */
3644     av_dump_format(ic, nb_input_files, filename, 0);
3645
3646     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3647     if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
3648         exit_program(1);
3649
3650     input_files[nb_input_files - 1]->ctx        = ic;
3651     input_files[nb_input_files - 1]->ist_index  = nb_input_streams - ic->nb_streams;
3652     input_files[nb_input_files - 1]->ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3653     input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
3654     input_files[nb_input_files - 1]->rate_emu   = o->rate_emu;
3655
3656     for (i = 0; i < o->nb_dump_attachment; i++) {
3657         int j;
3658
3659         for (j = 0; j < ic->nb_streams; j++) {
3660             AVStream *st = ic->streams[j];
3661
3662             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3663                 dump_attachment(st, o->dump_attachment[i].u.str);
3664         }
3665     }
3666
3667     for (i = 0; i < orig_nb_streams; i++)
3668         av_dict_free(&opts[i]);
3669     av_freep(&opts);
3670
3671     reset_options(o);
3672     return 0;
3673 }
3674
3675 static uint8_t *get_line(AVIOContext *s)
3676 {
3677     AVIOContext *line;
3678     uint8_t *buf;
3679     char c;
3680
3681     if (avio_open_dyn_buf(&line) < 0) {
3682         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3683         exit_program(1);
3684     }
3685
3686     while ((c = avio_r8(s)) && c != '\n')
3687         avio_w8(line, c);
3688     avio_w8(line, 0);
3689     avio_close_dyn_buf(line, &buf);
3690
3691     return buf;
3692 }
3693
3694 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3695 {
3696     int i, ret = 1;
3697     char filename[1000];
3698     const char *base[3] = { getenv("AVCONV_DATADIR"),
3699                             getenv("HOME"),
3700                             AVCONV_DATADIR,
3701        &n