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