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