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