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