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