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