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