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