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