25958ea5592f1e321d3b3aa0c380fb7de6e0bb97
[ffmpeg.git] / avconv.c
1 /*
2  * avconv main
3  * Copyright (c) 2000-2011 The libav developers.
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23 #include <ctype.h>
24 #include <string.h>
25 #include <math.h>
26 #include <stdlib.h>
27 #include <errno.h>
28 #include <signal.h>
29 #include <limits.h>
30 #include <unistd.h>
31 #include "libavformat/avformat.h"
32 #include "libavdevice/avdevice.h"
33 #include "libswscale/swscale.h"
34 #include "libavresample/avresample.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/audioconvert.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/samplefmt.h"
39 #include "libavutil/colorspace.h"
40 #include "libavutil/fifo.h"
41 #include "libavutil/intreadwrite.h"
42 #include "libavutil/dict.h"
43 #include "libavutil/mathematics.h"
44 #include "libavutil/pixdesc.h"
45 #include "libavutil/avstring.h"
46 #include "libavutil/libm.h"
47 #include "libavutil/imgutils.h"
48 #include "libavformat/os_support.h"
49
50 # include "libavfilter/avfilter.h"
51 # include "libavfilter/avfiltergraph.h"
52 # include "libavfilter/buffersrc.h"
53 # include "libavfilter/buffersink.h"
54 # include "libavfilter/vsrc_buffer.h"
55
56 #if HAVE_SYS_RESOURCE_H
57 #include <sys/types.h>
58 #include <sys/time.h>
59 #include <sys/resource.h>
60 #elif HAVE_GETPROCESSTIMES
61 #include <windows.h>
62 #endif
63 #if HAVE_GETPROCESSMEMORYINFO
64 #include <windows.h>
65 #include <psapi.h>
66 #endif
67
68 #if HAVE_SYS_SELECT_H
69 #include <sys/select.h>
70 #endif
71
72 #include <time.h>
73
74 #include "cmdutils.h"
75
76 #include "libavutil/avassert.h"
77
78 #define VSYNC_AUTO       -1
79 #define VSYNC_PASSTHROUGH 0
80 #define VSYNC_CFR         1
81 #define VSYNC_VFR         2
82
83 const char program_name[] = "avconv";
84 const int program_birth_year = 2000;
85
86 /* select an input stream for an output stream */
87 typedef struct StreamMap {
88     int disabled;           /** 1 is this mapping is disabled by a negative map */
89     int file_index;
90     int stream_index;
91     int sync_file_index;
92     int sync_stream_index;
93     char *linklabel;       /** name of an output link, for mapping lavfi outputs */
94 } StreamMap;
95
96 /**
97  * select an input file for an output file
98  */
99 typedef struct MetadataMap {
100     int  file;      ///< file index
101     char type;      ///< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
102     int  index;     ///< stream/chapter/program number
103 } MetadataMap;
104
105 static const OptionDef options[];
106
107 static int video_discard = 0;
108 static int same_quant = 0;
109 static int do_deinterlace = 0;
110 static int intra_dc_precision = 8;
111 static int qp_hist = 0;
112
113 static int file_overwrite = 0;
114 static int do_benchmark = 0;
115 static int do_hex_dump = 0;
116 static int do_pkt_dump = 0;
117 static int do_pass = 0;
118 static char *pass_logfilename_prefix = NULL;
119 static int video_sync_method = VSYNC_AUTO;
120 static int audio_sync_method = 0;
121 static float audio_drift_threshold = 0.1;
122 static int copy_ts = 0;
123 static int copy_tb = 1;
124 static int opt_shortest = 0;
125 static char *vstats_filename;
126 static FILE *vstats_file;
127
128 static int audio_volume = 256;
129
130 static int exit_on_error = 0;
131 static int using_stdin = 0;
132 static int64_t video_size = 0;
133 static int64_t audio_size = 0;
134 static int64_t extra_size = 0;
135 static int nb_frames_dup = 0;
136 static int nb_frames_drop = 0;
137 static int input_sync;
138
139 static float dts_delta_threshold = 10;
140
141 static int print_stats = 1;
142
143 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
144
145 typedef struct InputFilter {
146     AVFilterContext    *filter;
147     struct InputStream *ist;
148     struct FilterGraph *graph;
149 } InputFilter;
150
151 typedef struct OutputFilter {
152     AVFilterContext     *filter;
153     struct OutputStream *ost;
154     struct FilterGraph  *graph;
155
156     /* temporary storage until stream maps are processed */
157     AVFilterInOut       *out_tmp;
158 } OutputFilter;
159
160 typedef struct FilterGraph {
161     int            index;
162     const char    *graph_desc;
163
164     AVFilterGraph *graph;
165
166     InputFilter   **inputs;
167     int          nb_inputs;
168     OutputFilter **outputs;
169     int         nb_outputs;
170 } FilterGraph;
171
172 typedef struct FrameBuffer {
173     uint8_t *base[4];
174     uint8_t *data[4];
175     int  linesize[4];
176
177     int h, w;
178     enum PixelFormat pix_fmt;
179
180     int refcount;
181     struct InputStream *ist;
182     struct FrameBuffer *next;
183 } FrameBuffer;
184
185 typedef struct InputStream {
186     int file_index;
187     AVStream *st;
188     int discard;             /* true if stream data should be discarded */
189     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
190     AVCodec *dec;
191     AVFrame *decoded_frame;
192
193     int64_t       start;     /* time when read started */
194     /* predicted dts of the next packet read for this stream or (when there are
195      * several frames in a packet) of the next frame in current packet */
196     int64_t       next_dts;
197     /* dts of the last packet read for this stream */
198     int64_t       last_dts;
199     PtsCorrectionContext pts_ctx;
200     double ts_scale;
201     int is_start;            /* is 1 at the start and after a discontinuity */
202     int showed_multi_packet_warning;
203     AVDictionary *opts;
204
205     int resample_height;
206     int resample_width;
207     int resample_pix_fmt;
208
209     int      resample_sample_fmt;
210     int      resample_sample_rate;
211     int      resample_channels;
212     uint64_t resample_channel_layout;
213
214     /* a pool of free buffers for decoded data */
215     FrameBuffer *buffer_pool;
216
217     /* decoded data from this stream goes into all those filters
218      * currently video only */
219     InputFilter **filters;
220     int        nb_filters;
221 } InputStream;
222
223 typedef struct InputFile {
224     AVFormatContext *ctx;
225     int eof_reached;      /* true if eof reached */
226     int ist_index;        /* index of first stream in ist_table */
227     int buffer_size;      /* current total buffer size */
228     int64_t ts_offset;
229     int nb_streams;       /* number of stream that avconv is aware of; may be different
230                              from ctx.nb_streams if new streams appear during av_read_frame() */
231     int rate_emu;
232 } InputFile;
233
234 typedef struct OutputStream {
235     int file_index;          /* file index */
236     int index;               /* stream index in the output file */
237     int source_index;        /* InputStream index */
238     AVStream *st;            /* stream in the output file */
239     int encoding_needed;     /* true if encoding needed for this stream */
240     int frame_number;
241     /* input pts and corresponding output pts
242        for A/V sync */
243     // double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
244     struct InputStream *sync_ist; /* input stream to sync against */
245     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
246     /* pts of the first frame encoded for this stream, used for limiting
247      * recording time */
248     int64_t first_pts;
249     AVBitStreamFilterContext *bitstream_filters;
250     AVCodec *enc;
251     int64_t max_frames;
252     AVFrame *filtered_frame;
253
254     /* video only */
255     AVRational frame_rate;
256     int force_fps;
257     int top_field_first;
258
259     float frame_aspect_ratio;
260     float last_quality;
261
262     /* forced key frames */
263     int64_t *forced_kf_pts;
264     int forced_kf_count;
265     int forced_kf_index;
266
267     FILE *logfile;
268
269     OutputFilter *filter;
270     char *avfilter;
271
272     int64_t sws_flags;
273     AVDictionary *opts;
274     int is_past_recording_time;
275     int stream_copy;
276     const char *attachment_filename;
277     int copy_initial_nonkeyframes;
278
279     enum PixelFormat pix_fmts[2];
280 } OutputStream;
281
282
283 typedef struct OutputFile {
284     AVFormatContext *ctx;
285     AVDictionary *opts;
286     int ost_index;       /* index of the first stream in output_streams */
287     int64_t recording_time; /* desired length of the resulting file in microseconds */
288     int64_t start_time;     /* start time in microseconds */
289     uint64_t limit_filesize;
290 } OutputFile;
291
292 static InputStream **input_streams = NULL;
293 static int        nb_input_streams = 0;
294 static InputFile   **input_files   = NULL;
295 static int        nb_input_files   = 0;
296
297 static OutputStream **output_streams = NULL;
298 static int         nb_output_streams = 0;
299 static OutputFile   **output_files   = NULL;
300 static int         nb_output_files   = 0;
301
302 static FilterGraph **filtergraphs;
303 int               nb_filtergraphs;
304
305 typedef struct OptionsContext {
306     /* input/output options */
307     int64_t start_time;
308     const char *format;
309
310     SpecifierOpt *codec_names;
311     int        nb_codec_names;
312     SpecifierOpt *audio_channels;
313     int        nb_audio_channels;
314     SpecifierOpt *audio_sample_rate;
315     int        nb_audio_sample_rate;
316     SpecifierOpt *frame_rates;
317     int        nb_frame_rates;
318     SpecifierOpt *frame_sizes;
319     int        nb_frame_sizes;
320     SpecifierOpt *frame_pix_fmts;
321     int        nb_frame_pix_fmts;
322
323     /* input options */
324     int64_t input_ts_offset;
325     int rate_emu;
326
327     SpecifierOpt *ts_scale;
328     int        nb_ts_scale;
329     SpecifierOpt *dump_attachment;
330     int        nb_dump_attachment;
331
332     /* output options */
333     StreamMap *stream_maps;
334     int     nb_stream_maps;
335     /* first item specifies output metadata, second is input */
336     MetadataMap (*meta_data_maps)[2];
337     int nb_meta_data_maps;
338     int metadata_global_manual;
339     int metadata_streams_manual;
340     int metadata_chapters_manual;
341     const char **attachments;
342     int       nb_attachments;
343
344     int chapters_input_file;
345
346     int64_t recording_time;
347     uint64_t limit_filesize;
348     float mux_preload;
349     float mux_max_delay;
350
351     int video_disable;
352     int audio_disable;
353     int subtitle_disable;
354     int data_disable;
355
356     /* indexed by output file stream index */
357     int   *streamid_map;
358     int nb_streamid_map;
359
360     SpecifierOpt *metadata;
361     int        nb_metadata;
362     SpecifierOpt *max_frames;
363     int        nb_max_frames;
364     SpecifierOpt *bitstream_filters;
365     int        nb_bitstream_filters;
366     SpecifierOpt *codec_tags;
367     int        nb_codec_tags;
368     SpecifierOpt *sample_fmts;
369     int        nb_sample_fmts;
370     SpecifierOpt *qscale;
371     int        nb_qscale;
372     SpecifierOpt *forced_key_frames;
373     int        nb_forced_key_frames;
374     SpecifierOpt *force_fps;
375     int        nb_force_fps;
376     SpecifierOpt *frame_aspect_ratios;
377     int        nb_frame_aspect_ratios;
378     SpecifierOpt *rc_overrides;
379     int        nb_rc_overrides;
380     SpecifierOpt *intra_matrices;
381     int        nb_intra_matrices;
382     SpecifierOpt *inter_matrices;
383     int        nb_inter_matrices;
384     SpecifierOpt *top_field_first;
385     int        nb_top_field_first;
386     SpecifierOpt *metadata_map;
387     int        nb_metadata_map;
388     SpecifierOpt *presets;
389     int        nb_presets;
390     SpecifierOpt *copy_initial_nonkeyframes;
391     int        nb_copy_initial_nonkeyframes;
392     SpecifierOpt *filters;
393     int        nb_filters;
394 } OptionsContext;
395
396 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
397 {\
398     int i, ret;\
399     for (i = 0; i < o->nb_ ## name; i++) {\
400         char *spec = o->name[i].specifier;\
401         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
402             outvar = o->name[i].u.type;\
403         else if (ret < 0)\
404             exit_program(1);\
405     }\
406 }
407
408 static void reset_options(OptionsContext *o)
409 {
410     const OptionDef *po = options;
411     int i;
412
413     /* all OPT_SPEC and OPT_STRING can be freed in generic way */
414     while (po->name) {
415         void *dst = (uint8_t*)o + po->u.off;
416
417         if (po->flags & OPT_SPEC) {
418             SpecifierOpt **so = dst;
419             int i, *count = (int*)(so + 1);
420             for (i = 0; i < *count; i++) {
421                 av_freep(&(*so)[i].specifier);
422                 if (po->flags & OPT_STRING)
423                     av_freep(&(*so)[i].u.str);
424             }
425             av_freep(so);
426             *count = 0;
427         } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
428             av_freep(dst);
429         po++;
430     }
431
432     for (i = 0; i < o->nb_stream_maps; i++)
433         av_freep(&o->stream_maps[i].linklabel);
434     av_freep(&o->stream_maps);
435     av_freep(&o->meta_data_maps);
436     av_freep(&o->streamid_map);
437
438     memset(o, 0, sizeof(*o));
439
440     o->mux_max_delay  = 0.7;
441     o->recording_time = INT64_MAX;
442     o->limit_filesize = UINT64_MAX;
443     o->chapters_input_file = INT_MAX;
444
445     uninit_opts();
446     init_opts();
447 }
448
449 static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
450 {
451     FrameBuffer  *buf = av_mallocz(sizeof(*buf));
452     int i, ret;
453     const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
454     int h_chroma_shift, v_chroma_shift;
455     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
456     int w = s->width, h = s->height;
457
458     if (!buf)
459         return AVERROR(ENOMEM);
460
461     if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
462         w += 2*edge;
463         h += 2*edge;
464     }
465
466     avcodec_align_dimensions(s, &w, &h);
467     if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
468                               s->pix_fmt, 32)) < 0) {
469         av_freep(&buf);
470         return ret;
471     }
472     /* XXX this shouldn't be needed, but some tests break without this line
473      * those decoders are buggy and need to be fixed.
474      * the following tests fail:
475      * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
476      */
477     memset(buf->base[0], 128, ret);
478
479     avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
480     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
481         const int h_shift = i==0 ? 0 : h_chroma_shift;
482         const int v_shift = i==0 ? 0 : v_chroma_shift;
483         if (s->flags & CODEC_FLAG_EMU_EDGE)
484             buf->data[i] = buf->base[i];
485         else
486             buf->data[i] = buf->base[i] +
487                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
488                                    (pixel_size*edge >> h_shift), 32);
489     }
490     buf->w       = s->width;
491     buf->h       = s->height;
492     buf->pix_fmt = s->pix_fmt;
493     buf->ist     = ist;
494
495     *pbuf = buf;
496     return 0;
497 }
498
499 static void free_buffer_pool(InputStream *ist)
500 {
501     FrameBuffer *buf = ist->buffer_pool;
502     while (buf) {
503         ist->buffer_pool = buf->next;
504         av_freep(&buf->base[0]);
505         av_free(buf);
506         buf = ist->buffer_pool;
507     }
508 }
509
510 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
511 {
512     av_assert0(buf->refcount);
513     buf->refcount--;
514     if (!buf->refcount) {
515         buf->next = ist->buffer_pool;
516         ist->buffer_pool = buf;
517     }
518 }
519
520 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
521 {
522     InputStream *ist = s->opaque;
523     FrameBuffer *buf;
524     int ret, i;
525
526     if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
527         return ret;
528
529     buf              = ist->buffer_pool;
530     ist->buffer_pool = buf->next;
531     buf->next        = NULL;
532     if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
533         av_freep(&buf->base[0]);
534         av_free(buf);
535         if ((ret = alloc_buffer(ist, s, &buf)) < 0)
536             return ret;
537     }
538     buf->refcount++;
539
540     frame->opaque        = buf;
541     frame->type          = FF_BUFFER_TYPE_USER;
542     frame->extended_data = frame->data;
543     frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
544     frame->width         = buf->w;
545     frame->height        = buf->h;
546     frame->format        = buf->pix_fmt;
547     frame->sample_aspect_ratio = s->sample_aspect_ratio;
548
549     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
550         frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
551         frame->data[i]     = buf->data[i];
552         frame->linesize[i] = buf->linesize[i];
553     }
554
555     return 0;
556 }
557
558 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
559 {
560     InputStream *ist = s->opaque;
561     FrameBuffer *buf = frame->opaque;
562     int i;
563
564     for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
565         frame->data[i] = NULL;
566
567     unref_buffer(ist, buf);
568 }
569
570 static void filter_release_buffer(AVFilterBuffer *fb)
571 {
572     FrameBuffer *buf = fb->priv;
573     av_free(fb);
574     unref_buffer(buf->ist, buf);
575 }
576
577 /**
578  * Define a function for building a string containing a list of
579  * allowed formats,
580  */
581 #define DEF_CHOOSE_FORMAT(type, var, supported_list, none, get_name, separator) \
582 static char *choose_ ## var ## s(OutputStream *ost)                             \
583 {                                                                               \
584     if (ost->st->codec->var != none) {                                          \
585         get_name(ost->st->codec->var);                                          \
586         return av_strdup(name);                                                 \
587     } else if (ost->enc->supported_list) {                                      \
588         const type *p;                                                          \
589         AVIOContext *s = NULL;                                                  \
590         uint8_t *ret;                                                           \
591         int len;                                                                \
592                                                                                 \
593         if (avio_open_dyn_buf(&s) < 0)                                          \
594             exit_program(1);                                                    \
595                                                                                 \
596         for (p = ost->enc->supported_list; *p != none; p++) {                   \
597             get_name(*p);                                                       \
598             avio_printf(s, "%s" separator, name);                               \
599         }                                                                       \
600         len = avio_close_dyn_buf(s, &ret);                                      \
601         ret[len - 1] = 0;                                                       \
602         return ret;                                                             \
603     } else                                                                      \
604         return NULL;                                                            \
605 }
606
607 #define GET_PIX_FMT_NAME(pix_fmt)\
608     const char *name = av_get_pix_fmt_name(pix_fmt);
609
610 DEF_CHOOSE_FORMAT(enum PixelFormat, pix_fmt, pix_fmts, PIX_FMT_NONE,
611                   GET_PIX_FMT_NAME, ":")
612
613 #define GET_SAMPLE_FMT_NAME(sample_fmt)\
614     const char *name = av_get_sample_fmt_name(sample_fmt)
615
616 DEF_CHOOSE_FORMAT(enum AVSampleFormat, sample_fmt, sample_fmts,
617                   AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME, ",")
618
619 #define GET_SAMPLE_RATE_NAME(rate)\
620     char name[16];\
621     snprintf(name, sizeof(name), "%d", rate);
622
623 DEF_CHOOSE_FORMAT(int, sample_rate, supported_samplerates, 0,
624                   GET_SAMPLE_RATE_NAME, ",")
625
626 #define GET_CH_LAYOUT_NAME(ch_layout)\
627     char name[16];\
628     snprintf(name, sizeof(name), "0x%"PRIx64, ch_layout);
629
630 DEF_CHOOSE_FORMAT(uint64_t, channel_layout, channel_layouts, 0,
631                   GET_CH_LAYOUT_NAME, ",")
632
633 static int configure_audio_filters(FilterGraph *fg, AVFilterContext **in_filter,
634                                    AVFilterContext **out_filter)
635 {
636     InputStream  *ist = fg->inputs[0]->ist;
637     OutputStream *ost = fg->outputs[0]->ost;
638     AVCodecContext *codec  = ost->st->codec;
639     AVCodecContext *icodec = ist->st->codec;
640     char *sample_fmts, *sample_rates, *channel_layouts;
641     char args[256];
642     int ret;
643
644     avfilter_graph_free(&fg->graph);
645     if (!(fg->graph = avfilter_graph_alloc()))
646         return AVERROR(ENOMEM);
647
648     snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:"
649              "channel_layout=0x%"PRIx64, ist->st->time_base.num,
650              ist->st->time_base.den, icodec->sample_rate,
651              av_get_sample_fmt_name(icodec->sample_fmt), icodec->channel_layout);
652     ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
653                                        avfilter_get_by_name("abuffer"),
654                                        "src", args, NULL, fg->graph);
655     if (ret < 0)
656         return ret;
657
658     ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
659                                        avfilter_get_by_name("abuffersink"),
660                                        "out", NULL, NULL, fg->graph);
661     if (ret < 0)
662         return ret;
663
664     *in_filter  = fg->inputs[0]->filter;
665     *out_filter = fg->outputs[0]->filter;
666
667     if (codec->channels && !codec->channel_layout)
668         codec->channel_layout = av_get_default_channel_layout(codec->channels);
669
670     sample_fmts     = choose_sample_fmts(ost);
671     sample_rates    = choose_sample_rates(ost);
672     channel_layouts = choose_channel_layouts(ost);
673     if (sample_fmts || sample_rates || channel_layouts) {
674         AVFilterContext *format;
675         char args[256];
676         int len = 0;
677
678         if (sample_fmts)
679             len += snprintf(args + len, sizeof(args) - len, "sample_fmts=%s:",
680                             sample_fmts);
681         if (sample_rates)
682             len += snprintf(args + len, sizeof(args) - len, "sample_rates=%s:",
683                             sample_rates);
684         if (channel_layouts)
685             len += snprintf(args + len, sizeof(args) - len, "channel_layouts=%s:",
686                             channel_layouts);
687         args[len - 1] = 0;
688
689         av_freep(&sample_fmts);
690         av_freep(&sample_rates);
691         av_freep(&channel_layouts);
692
693         ret = avfilter_graph_create_filter(&format,
694                                            avfilter_get_by_name("aformat"),
695                                            "aformat", args, NULL, fg->graph);
696         if (ret < 0)
697             return ret;
698
699         ret = avfilter_link(format, 0, fg->outputs[0]->filter, 0);
700         if (ret < 0)
701             return ret;
702
703         *out_filter = format;
704     }
705
706     return 0;
707 }
708
709 static int configure_video_filters(FilterGraph *fg, AVFilterContext **in_filter,
710                                    AVFilterContext **out_filter)
711 {
712     InputStream  *ist = fg->inputs[0]->ist;
713     OutputStream *ost = fg->outputs[0]->ost;
714     AVFilterContext *filter;
715     AVCodecContext *codec = ost->st->codec;
716     char *pix_fmts;
717     AVRational sample_aspect_ratio;
718     char args[255];
719     int ret;
720
721     if (ist->st->sample_aspect_ratio.num) {
722         sample_aspect_ratio = ist->st->sample_aspect_ratio;
723     } else
724         sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
725
726     snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
727              ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
728              sample_aspect_ratio.num, sample_aspect_ratio.den);
729
730     ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
731                                        avfilter_get_by_name("buffer"),
732                                        "src", args, NULL, fg->graph);
733     if (ret < 0)
734         return ret;
735     ret = avfilter_graph_create_filter(&fg->outputs[0]->filter,
736                                        avfilter_get_by_name("buffersink"),
737                                        "out", NULL, NULL, fg->graph);
738     if (ret < 0)
739         return ret;
740     *in_filter  = fg->inputs[0]->filter;
741     *out_filter = fg->outputs[0]->filter;
742
743     if (codec->width || codec->height) {
744         snprintf(args, 255, "%d:%d:flags=0x%X",
745                  codec->width,
746                  codec->height,
747                  (unsigned)ost->sws_flags);
748         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
749                                                 NULL, args, NULL, fg->graph)) < 0)
750             return ret;
751         if ((ret = avfilter_link(*in_filter, 0, filter, 0)) < 0)
752             return ret;
753         *in_filter = filter;
754     }
755
756     if ((pix_fmts = choose_pix_fmts(ost))) {
757         if ((ret = avfilter_graph_create_filter(&filter,
758                                                 avfilter_get_by_name("format"),
759                                                 "format", pix_fmts, NULL,
760                                                 fg->graph)) < 0)
761             return ret;
762         if ((ret = avfilter_link(filter, 0, *out_filter, 0)) < 0)
763             return ret;
764
765         *out_filter = filter;
766         av_freep(&pix_fmts);
767     }
768
769     snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
770     fg->graph->scale_sws_opts = av_strdup(args);
771
772     return 0;
773 }
774
775 static int configure_simple_filtergraph(FilterGraph *fg)
776 {
777     OutputStream *ost = fg->outputs[0]->ost;
778     AVFilterContext *in_filter, *out_filter;
779     int ret;
780
781     avfilter_graph_free(&fg->graph);
782     fg->graph = avfilter_graph_alloc();
783
784     switch (ost->st->codec->codec_type) {
785     case AVMEDIA_TYPE_VIDEO:
786         ret = configure_video_filters(fg, &in_filter, &out_filter);
787         break;
788     case AVMEDIA_TYPE_AUDIO:
789         ret = configure_audio_filters(fg, &in_filter, &out_filter);
790         break;
791     default: av_assert0(0);
792     }
793     if (ret < 0)
794         return ret;
795
796     if (ost->avfilter) {
797         AVFilterInOut *outputs = avfilter_inout_alloc();
798         AVFilterInOut *inputs  = avfilter_inout_alloc();
799
800         outputs->name    = av_strdup("in");
801         outputs->filter_ctx = in_filter;
802         outputs->pad_idx = 0;
803         outputs->next    = NULL;
804
805         inputs->name    = av_strdup("out");
806         inputs->filter_ctx = out_filter;
807         inputs->pad_idx = 0;
808         inputs->next    = NULL;
809
810         if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, inputs, outputs, NULL)) < 0)
811             return ret;
812     } else {
813         if ((ret = avfilter_link(in_filter, 0, out_filter, 0)) < 0)
814             return ret;
815     }
816
817     if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
818         return ret;
819
820     ost->filter = fg->outputs[0];
821
822     return 0;
823 }
824
825 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
826 {
827     FilterGraph *fg = av_mallocz(sizeof(*fg));
828
829     if (!fg)
830         exit_program(1);
831     fg->index = nb_filtergraphs;
832
833     fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
834                              fg->nb_outputs + 1);
835     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
836         exit_program(1);
837     fg->outputs[0]->ost   = ost;
838     fg->outputs[0]->graph = fg;
839
840     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
841                             fg->nb_inputs + 1);
842     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
843         exit_program(1);
844     fg->inputs[0]->ist   = ist;
845     fg->inputs[0]->graph = fg;
846
847     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
848                               &ist->nb_filters, ist->nb_filters + 1);
849     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
850
851     filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
852                               &nb_filtergraphs, nb_filtergraphs + 1);
853     filtergraphs[nb_filtergraphs - 1] = fg;
854
855     return fg;
856 }
857
858 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
859 {
860     InputStream *ist;
861     enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
862     int i;
863
864     // TODO: support other filter types
865     if (type != AVMEDIA_TYPE_VIDEO) {
866         av_log(NULL, AV_LOG_FATAL, "Only video filters supported currently.\n");
867         exit_program(1);
868     }
869
870     if (in->name) {
871         AVFormatContext *s;
872         AVStream       *st = NULL;
873         char *p;
874         int file_idx = strtol(in->name, &p, 0);
875
876         if (file_idx < 0 || file_idx >= nb_input_files) {
877             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
878                    file_idx, fg->graph_desc);
879             exit_program(1);
880         }
881         s = input_files[file_idx]->ctx;
882
883         for (i = 0; i < s->nb_streams; i++) {
884             if (s->streams[i]->codec->codec_type != type)
885                 continue;
886             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
887                 st = s->streams[i];
888                 break;
889             }
890         }
891         if (!st) {
892             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
893                    "matches no streams.\n", p, fg->graph_desc);
894             exit_program(1);
895         }
896         ist = input_streams[input_files[file_idx]->ist_index + st->index];
897     } else {
898         /* find the first unused stream of corresponding type */
899         for (i = 0; i < nb_input_streams; i++) {
900             ist = input_streams[i];
901             if (ist->st->codec->codec_type == type && ist->discard)
902                 break;
903         }
904         if (i == nb_input_streams) {
905             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
906                    "unlabeled input pad %d on filter %s", in->pad_idx,
907                    in->filter_ctx->name);
908             exit_program(1);
909         }
910     }
911     ist->discard         = 0;
912     ist->decoding_needed = 1;
913     ist->st->discard = AVDISCARD_NONE;
914
915     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
916                             &fg->nb_inputs, fg->nb_inputs + 1);
917     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
918         exit_program(1);
919     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
920     fg->inputs[fg->nb_inputs - 1]->graph = fg;
921
922     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
923                               &ist->nb_filters, ist->nb_filters + 1);
924     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
925 }
926
927 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
928 {
929     char *pix_fmts;
930     AVCodecContext *codec = ofilter->ost->st->codec;
931     AVFilterContext *last_filter = out->filter_ctx;
932     int pad_idx = out->pad_idx;
933     int ret;
934
935
936     ret = avfilter_graph_create_filter(&ofilter->filter,
937                                        avfilter_get_by_name("buffersink"),
938                                        "out", NULL, pix_fmts, fg->graph);
939     if (ret < 0)
940         return ret;
941
942     if (codec->width || codec->height) {
943         char args[255];
944         AVFilterContext *filter;
945
946         snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
947                  codec->width,
948                  codec->height,
949                  (unsigned)ofilter->ost->sws_flags);
950         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
951                                                 NULL, args, NULL, fg->graph)) < 0)
952             return ret;
953         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
954             return ret;
955
956         last_filter = filter;
957         pad_idx = 0;
958     }
959
960     if ((pix_fmts = choose_pix_fmts(ofilter->ost))) {
961         AVFilterContext *filter;
962         if ((ret = avfilter_graph_create_filter(&filter,
963                                                 avfilter_get_by_name("format"),
964                                                 "format", pix_fmts, NULL,
965                                                 fg->graph)) < 0)
966             return ret;
967         if ((ret = avfilter_link(last_filter, pad_idx, filter, 0)) < 0)
968             return ret;
969
970         last_filter = filter;
971         pad_idx     = 0;
972         av_freep(&pix_fmts);
973     }
974
975     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
976         return ret;
977
978     return 0;
979 }
980
981 static int configure_complex_filter(FilterGraph *fg)
982 {
983     AVFilterInOut *inputs, *outputs, *cur;
984     int ret, i, init = !fg->graph;
985
986     avfilter_graph_free(&fg->graph);
987     if (!(fg->graph = avfilter_graph_alloc()))
988         return AVERROR(ENOMEM);
989
990     if ((ret = avfilter_graph_parse2(fg->graph, fg->graph_desc, &inputs, &outputs)) < 0)
991         return ret;
992
993     for (cur = inputs; init && cur; cur = cur->next)
994         init_input_filter(fg, cur);
995
996     for (cur = inputs, i = 0; cur; cur = cur->next, i++) {
997         InputFilter *ifilter = fg->inputs[i];
998         InputStream     *ist = ifilter->ist;
999         AVRational       sar;
1000         char            args[255];
1001
1002         sar = ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
1003                                                  ist->st->codec->sample_aspect_ratio;
1004         snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
1005                  ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
1006                  sar.num, sar.den);
1007
1008         if ((ret = avfilter_graph_create_filter(&ifilter->filter,
1009                                                 avfilter_get_by_name("buffer"), cur->name,
1010                                                 args, NULL, fg->graph)) < 0)
1011             return ret;
1012         if ((ret = avfilter_link(ifilter->filter, 0,
1013                                  cur->filter_ctx, cur->pad_idx)) < 0)
1014             return ret;
1015     }
1016     avfilter_inout_free(&inputs);
1017
1018     if (!init) {
1019         /* we already know the mappings between lavfi outputs and output streams,
1020          * so we can finish the setup */
1021         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
1022             configure_output_filter(fg, fg->outputs[i], cur);
1023         avfilter_inout_free(&outputs);
1024
1025         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1026             return ret;
1027     } else {
1028         /* wait until output mappings are processed */
1029         for (cur = outputs; cur;) {
1030             fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
1031                                      &fg->nb_outputs, fg->nb_outputs + 1);
1032             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
1033                 exit_program(1);
1034             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
1035             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
1036             cur = cur->next;
1037             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
1038         }
1039     }
1040
1041     return 0;
1042 }
1043
1044 static int configure_complex_filters(void)
1045 {
1046     int i, ret = 0;
1047
1048     for (i = 0; i < nb_filtergraphs; i++)
1049         if (!filtergraphs[i]->graph &&
1050             (ret = configure_complex_filter(filtergraphs[i])) < 0)
1051             return ret;
1052     return 0;
1053 }
1054
1055 static int configure_filtergraph(FilterGraph *fg)
1056 {
1057     return fg->graph_desc ? configure_complex_filter(fg) :
1058                             configure_simple_filtergraph(fg);
1059 }
1060
1061 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1062 {
1063     int i;
1064     for (i = 0; i < fg->nb_inputs; i++)
1065         if (fg->inputs[i]->ist == ist)
1066             return 1;
1067     return 0;
1068 }
1069
1070 static void term_exit(void)
1071 {
1072     av_log(NULL, AV_LOG_QUIET, "");
1073 }
1074
1075 static volatile int received_sigterm = 0;
1076 static volatile int received_nb_signals = 0;
1077
1078 static void
1079 sigterm_handler(int sig)
1080 {
1081     received_sigterm = sig;
1082     received_nb_signals++;
1083     term_exit();
1084 }
1085
1086 static void term_init(void)
1087 {
1088     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
1089     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
1090 #ifdef SIGXCPU
1091     signal(SIGXCPU, sigterm_handler);
1092 #endif
1093 }
1094
1095 static int decode_interrupt_cb(void *ctx)
1096 {
1097     return received_nb_signals > 1;
1098 }
1099
1100 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1101
1102 void exit_program(int ret)
1103 {
1104     int i, j;
1105
1106     for (i = 0; i < nb_filtergraphs; i++) {
1107         avfilter_graph_free(&filtergraphs[i]->graph);
1108         for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
1109             av_freep(&filtergraphs[i]->inputs[j]);
1110         av_freep(&filtergraphs[i]->inputs);
1111         for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
1112             av_freep(&filtergraphs[i]->outputs[j]);
1113         av_freep(&filtergraphs[i]->outputs);
1114         av_freep(&filtergraphs[i]);
1115     }
1116     av_freep(&filtergraphs);
1117
1118     /* close files */
1119     for (i = 0; i < nb_output_files; i++) {
1120         AVFormatContext *s = output_files[i]->ctx;
1121         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1122             avio_close(s->pb);
1123         avformat_free_context(s);
1124         av_dict_free(&output_files[i]->opts);
1125         av_freep(&output_files[i]);
1126     }
1127     for (i = 0; i < nb_output_streams; i++) {
1128         AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1129         while (bsfc) {
1130             AVBitStreamFilterContext *next = bsfc->next;
1131             av_bitstream_filter_close(bsfc);
1132             bsfc = next;
1133         }
1134         output_streams[i]->bitstream_filters = NULL;
1135
1136         av_freep(&output_streams[i]->avfilter);
1137         av_freep(&output_streams[i]->filtered_frame);
1138         av_freep(&output_streams[i]);
1139     }
1140     for (i = 0; i < nb_input_files; i++) {
1141         avformat_close_input(&input_files[i]->ctx);
1142         av_freep(&input_files[i]);
1143     }
1144     for (i = 0; i < nb_input_streams; i++) {
1145         av_freep(&input_streams[i]->decoded_frame);
1146         av_dict_free(&input_streams[i]->opts);
1147         free_buffer_pool(input_streams[i]);
1148         av_freep(&input_streams[i]->filters);
1149         av_freep(&input_streams[i]);
1150     }
1151
1152     if (vstats_file)
1153         fclose(vstats_file);
1154     av_free(vstats_filename);
1155
1156     av_freep(&input_streams);
1157     av_freep(&input_files);
1158     av_freep(&output_streams);
1159     av_freep(&output_files);
1160
1161     uninit_opts();
1162
1163     avfilter_uninit();
1164     avformat_network_deinit();
1165
1166     if (received_sigterm) {
1167         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1168                (int) received_sigterm);
1169         exit (255);
1170     }
1171
1172     exit(ret);
1173 }
1174
1175 static void assert_avoptions(AVDictionary *m)
1176 {
1177     AVDictionaryEntry *t;
1178     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1179         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1180         exit_program(1);
1181     }
1182 }
1183
1184 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1185 {
1186     const char *codec_string = encoder ? "encoder" : "decoder";
1187     AVCodec *codec;
1188     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1189         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1190         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1191                 "results.\nAdd '-strict experimental' if you want to use it.\n",
1192                 codec_string, c->codec->name);
1193         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1194         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1195             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1196                    codec_string, codec->name);
1197         exit_program(1);
1198     }
1199 }
1200
1201 /**
1202  * Update the requested input sample format based on the output sample format.
1203  * This is currently only used to request float output from decoders which
1204  * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
1205  * Ideally this will be removed in the future when decoders do not do format
1206  * conversion and only output in their native format.
1207  */
1208 static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
1209                               AVCodecContext *enc)
1210 {
1211     /* if sample formats match or a decoder sample format has already been
1212        requested, just return */
1213     if (enc->sample_fmt == dec->sample_fmt ||
1214         dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
1215         return;
1216
1217     /* if decoder supports more than one output format */
1218     if (dec_codec && dec_codec->sample_fmts &&
1219         dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
1220         dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
1221         const enum AVSampleFormat *p;
1222         int min_dec = -1, min_inc = -1;
1223
1224         /* find a matching sample format in the encoder */
1225         for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
1226             if (*p == enc->sample_fmt) {
1227                 dec->request_sample_fmt = *p;
1228                 return;
1229             } else if (*p > enc->sample_fmt) {
1230                 min_inc = FFMIN(min_inc, *p - enc->sample_fmt);
1231             } else
1232                 min_dec = FFMIN(min_dec, enc->sample_fmt - *p);
1233         }
1234
1235         /* if none match, provide the one that matches quality closest */
1236         dec->request_sample_fmt = min_inc > 0 ? enc->sample_fmt + min_inc :
1237                                   enc->sample_fmt - min_dec;
1238     }
1239 }
1240
1241 static double
1242 get_sync_ipts(const OutputStream *ost, int64_t pts)
1243 {
1244     OutputFile *of = output_files[ost->file_index];
1245     return (double)(pts - of->start_time) / AV_TIME_BASE;
1246 }
1247
1248 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1249 {
1250     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1251     AVCodecContext          *avctx = ost->st->codec;
1252     int ret;
1253
1254     /*
1255      * Audio encoders may split the packets --  #frames in != #packets out.
1256      * But there is no reordering, so we can limit the number of output packets
1257      * by simply dropping them here.
1258      * Counting encoded video frames needs to be done separately because of
1259      * reordering, see do_video_out()
1260      */
1261     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1262         if (ost->frame_number >= ost->max_frames) {
1263             av_free_packet(pkt);
1264             return;
1265         }
1266         ost->frame_number++;
1267     }
1268
1269     while (bsfc) {
1270         AVPacket new_pkt = *pkt;
1271         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1272                                            &new_pkt.data, &new_pkt.size,
1273                                            pkt->data, pkt->size,
1274                                            pkt->flags & AV_PKT_FLAG_KEY);
1275         if (a > 0) {
1276             av_free_packet(pkt);
1277             new_pkt.destruct = av_destruct_packet;
1278         } else if (a < 0) {
1279             av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
1280                    bsfc->filter->name, pkt->stream_index,
1281                    avctx->codec ? avctx->codec->name : "copy");
1282             print_error("", a);
1283             if (exit_on_error)
1284                 exit_program(1);
1285         }
1286         *pkt = new_pkt;
1287
1288         bsfc = bsfc->next;
1289     }
1290
1291     pkt->stream_index = ost->index;
1292     ret = av_interleaved_write_frame(s, pkt);
1293     if (ret < 0) {
1294         print_error("av_interleaved_write_frame()", ret);
1295         exit_program(1);
1296     }
1297 }
1298
1299 static int check_recording_time(OutputStream *ost)
1300 {
1301     OutputFile *of = output_files[ost->file_index];
1302
1303     if (of->recording_time != INT64_MAX &&
1304         av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
1305                       AV_TIME_BASE_Q) >= 0) {
1306         ost->is_past_recording_time = 1;
1307         return 0;
1308     }
1309     return 1;
1310 }
1311
1312 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1313                          AVFrame *frame)
1314 {
1315     AVCodecContext *enc = ost->st->codec;
1316     AVPacket pkt;
1317     int got_packet = 0;
1318
1319     av_init_packet(&pkt);
1320     pkt.data = NULL;
1321     pkt.size = 0;
1322
1323     if (!check_recording_time(ost))
1324         return;
1325
1326     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
1327         frame->pts = ost->sync_opts;
1328     ost->sync_opts = frame->pts + frame->nb_samples;
1329
1330     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1331         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1332         exit_program(1);
1333     }
1334
1335     if (got_packet) {
1336         if (pkt.pts != AV_NOPTS_VALUE)
1337             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
1338         if (pkt.dts != AV_NOPTS_VALUE)
1339             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
1340         if (pkt.duration > 0)
1341             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1342
1343         write_frame(s, &pkt, ost);
1344
1345         audio_size += pkt.size;
1346     }
1347 }
1348
1349 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1350 {
1351     AVCodecContext *dec;
1352     AVPicture *picture2;
1353     AVPicture picture_tmp;
1354     uint8_t *buf = 0;
1355
1356     dec = ist->st->codec;
1357
1358     /* deinterlace : must be done before any resize */
1359     if (do_deinterlace) {
1360         int size;
1361
1362         /* create temporary picture */
1363         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1364         buf  = av_malloc(size);
1365         if (!buf)
1366             return;
1367
1368         picture2 = &picture_tmp;
1369         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1370
1371         if (avpicture_deinterlace(picture2, picture,
1372                                  dec->pix_fmt, dec->width, dec->height) < 0) {
1373             /* if error, do not deinterlace */
1374             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1375             av_free(buf);
1376             buf = NULL;
1377             picture2 = picture;
1378         }
1379     } else {
1380         picture2 = picture;
1381     }
1382
1383     if (picture != picture2)
1384         *picture = *picture2;
1385     *bufp = buf;
1386 }
1387
1388 static void do_subtitle_out(AVFormatContext *s,
1389                             OutputStream *ost,
1390                             InputStream *ist,
1391                             AVSubtitle *sub,
1392                             int64_t pts)
1393 {
1394     static uint8_t *subtitle_out = NULL;
1395     int subtitle_out_max_size = 1024 * 1024;
1396     int subtitle_out_size, nb, i;
1397     AVCodecContext *enc;
1398     AVPacket pkt;
1399
1400     if (pts == AV_NOPTS_VALUE) {
1401         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1402         if (exit_on_error)
1403             exit_program(1);
1404         return;
1405     }
1406
1407     enc = ost->st->codec;
1408
1409     if (!subtitle_out) {
1410         subtitle_out = av_malloc(subtitle_out_max_size);
1411     }
1412
1413     /* Note: DVB subtitle need one packet to draw them and one other
1414        packet to clear them */
1415     /* XXX: signal it in the codec context ? */
1416     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1417         nb = 2;
1418     else
1419         nb = 1;
1420
1421     for (i = 0; i < nb; i++) {
1422         ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1423         if (!check_recording_time(ost))
1424             return;
1425
1426         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1427         // start_display_time is required to be 0
1428         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1429         sub->end_display_time  -= sub->start_display_time;
1430         sub->start_display_time = 0;
1431         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1432                                                     subtitle_out_max_size, sub);
1433         if (subtitle_out_size < 0) {
1434             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1435             exit_program(1);
1436         }
1437
1438         av_init_packet(&pkt);
1439         pkt.data = subtitle_out;
1440         pkt.size = subtitle_out_size;
1441         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1442         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1443             /* XXX: the pts correction is handled here. Maybe handling
1444                it in the codec would be better */
1445             if (i == 0)
1446                 pkt.pts += 90 * sub->start_display_time;
1447             else
1448                 pkt.pts += 90 * sub->end_display_time;
1449         }
1450         write_frame(s, &pkt, ost);
1451     }
1452 }
1453
1454 static void do_video_out(AVFormatContext *s,
1455                          OutputStream *ost,
1456                          AVFrame *in_picture,
1457                          int *frame_size, float quality)
1458 {
1459     int nb_frames, i, ret, format_video_sync;
1460     AVCodecContext *enc;
1461     double sync_ipts, delta;
1462
1463     enc = ost->st->codec;
1464
1465     sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
1466     delta = sync_ipts - ost->sync_opts;
1467
1468     /* by default, we output a single frame */
1469     nb_frames = 1;
1470
1471     *frame_size = 0;
1472
1473     format_video_sync = video_sync_method;
1474     if (format_video_sync == VSYNC_AUTO)
1475         format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
1476                             (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
1477
1478     switch (format_video_sync) {
1479     case VSYNC_CFR:
1480         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1481         if (delta < -1.1)
1482             nb_frames = 0;
1483         else if (delta > 1.1)
1484             nb_frames = lrintf(delta);
1485         break;
1486     case VSYNC_VFR:
1487         if (delta <= -0.6)
1488             nb_frames = 0;
1489         else if (delta > 0.6)
1490             ost->sync_opts = lrint(sync_ipts);
1491         break;
1492     case VSYNC_PASSTHROUGH:
1493         ost->sync_opts = lrint(sync_ipts);
1494         break;
1495     default:
1496         av_assert0(0);
1497     }
1498
1499     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1500     if (nb_frames == 0) {
1501         nb_frames_drop++;
1502         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1503         return;
1504     } else if (nb_frames > 1) {
1505         nb_frames_dup += nb_frames - 1;
1506         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1507     }
1508
1509     if (!ost->frame_number)
1510         ost->first_pts = ost->sync_opts;
1511
1512     /* duplicates frame if needed */
1513     for (i = 0; i < nb_frames; i++) {
1514         AVPacket pkt;
1515         av_init_packet(&pkt);
1516         pkt.data = NULL;
1517         pkt.size = 0;
1518
1519         if (!check_recording_time(ost))
1520             return;
1521
1522         if (s->oformat->flags & AVFMT_RAWPICTURE &&
1523             enc->codec->id == CODEC_ID_RAWVIDEO) {
1524             /* raw pictures are written as AVPicture structure to
1525                avoid any copies. We support temporarily the older
1526                method. */
1527             enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1528             enc->coded_frame->top_field_first  = in_picture->top_field_first;
1529             pkt.data   = (uint8_t *)in_picture;
1530             pkt.size   =  sizeof(AVPicture);
1531             pkt.pts    = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1532             pkt.flags |= AV_PKT_FLAG_KEY;
1533
1534             write_frame(s, &pkt, ost);
1535         } else {
1536             int got_packet;
1537             AVFrame big_picture;
1538
1539             big_picture = *in_picture;
1540             /* better than nothing: use input picture interlaced
1541                settings */
1542             big_picture.interlaced_frame = in_picture->interlaced_frame;
1543             if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1544                 if (ost->top_field_first == -1)
1545                     big_picture.top_field_first = in_picture->top_field_first;
1546                 else
1547                     big_picture.top_field_first = !!ost->top_field_first;
1548             }
1549
1550             /* handles same_quant here. This is not correct because it may
1551                not be a global option */
1552             big_picture.quality = quality;
1553             if (!enc->me_threshold)
1554                 big_picture.pict_type = 0;
1555             big_picture.pts = ost->sync_opts;
1556             if (ost->forced_kf_index < ost->forced_kf_count &&
1557                 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1558                 big_picture.pict_type = AV_PICTURE_TYPE_I;
1559                 ost->forced_kf_index++;
1560             }
1561             ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
1562             if (ret < 0) {
1563                 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1564                 exit_program(1);
1565             }
1566
1567             if (got_packet) {
1568                 if (pkt.pts != AV_NOPTS_VALUE)
1569                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1570                 if (pkt.dts != AV_NOPTS_VALUE)
1571                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1572
1573                 write_frame(s, &pkt, ost);
1574                 *frame_size = pkt.size;
1575                 video_size += pkt.size;
1576
1577                 /* if two pass, output log */
1578                 if (ost->logfile && enc->stats_out) {
1579                     fprintf(ost->logfile, "%s", enc->stats_out);
1580                 }
1581             }
1582         }
1583         ost->sync_opts++;
1584         /*
1585          * For video, number of frames in == number of packets out.
1586          * But there may be reordering, so we can't throw away frames on encoder
1587          * flush, we need to limit them here, before they go into encoder.
1588          */
1589         ost->frame_number++;
1590     }
1591 }
1592
1593 static double psnr(double d)
1594 {
1595     return -10.0 * log(d) / log(10.0);
1596 }
1597
1598 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1599                            int frame_size)
1600 {
1601     AVCodecContext *enc;
1602     int frame_number;
1603     double ti1, bitrate, avg_bitrate;
1604
1605     /* this is executed just the first time do_video_stats is called */
1606     if (!vstats_file) {
1607         vstats_file = fopen(vstats_filename, "w");
1608         if (!vstats_file) {
1609             perror("fopen");
1610             exit_program(1);
1611         }
1612     }
1613
1614     enc = ost->st->codec;
1615     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1616         frame_number = ost->frame_number;
1617         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1618         if (enc->flags&CODEC_FLAG_PSNR)
1619             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1620
1621         fprintf(vstats_file,"f_size= %6d ", frame_size);
1622         /* compute pts value */
1623         ti1 = ost->sync_opts * av_q2d(enc->time_base);
1624         if (ti1 < 0.01)
1625             ti1 = 0.01;
1626
1627         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1628         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1629         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1630                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1631         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1632     }
1633 }
1634
1635 /* check for new output on any of the filtergraphs */
1636 static int poll_filters(void)
1637 {
1638     AVFilterBufferRef *picref;
1639     AVFrame *filtered_frame = NULL;
1640     int i, frame_size;
1641
1642     for (i = 0; i < nb_output_streams; i++) {
1643         OutputStream *ost = output_streams[i];
1644         OutputFile    *of = output_files[ost->file_index];
1645         int ret = 0;
1646
1647         if (!ost->filter || ost->is_past_recording_time)
1648             continue;
1649
1650         if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1651             return AVERROR(ENOMEM);
1652         } else
1653             avcodec_get_frame_defaults(ost->filtered_frame);
1654         filtered_frame = ost->filtered_frame;
1655
1656         while (ret >= 0) {
1657             if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1658                 !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1659                 ret = av_buffersink_read_samples(ost->filter->filter, &picref,
1660                                                  ost->st->codec->frame_size);
1661             else
1662                 ret = av_buffersink_read(ost->filter->filter, &picref);
1663
1664             if (ret < 0)
1665                 break;
1666
1667             avfilter_copy_buf_props(filtered_frame, picref);
1668             if (ost->enc->type == AVMEDIA_TYPE_VIDEO)
1669                 filtered_frame->pts = av_rescale_q(picref->pts,
1670                                                    ost->filter->filter->inputs[0]->time_base,
1671                                                    AV_TIME_BASE_Q);
1672             else if (picref->pts != AV_NOPTS_VALUE)
1673                 filtered_frame->pts = av_rescale_q(picref->pts,
1674                                                    ost->filter->filter->inputs[0]->time_base,
1675                                                    ost->st->codec->time_base) -
1676                                       av_rescale_q(of->start_time,
1677                                                    AV_TIME_BASE_Q,
1678                                                    ost->st->codec->time_base);
1679
1680             if (of->start_time && filtered_frame->pts < of->start_time)
1681                 return 0;
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 transcode_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 transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
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     pkt->pts  = *pkt_pts;
2158     pkt->dts  = ist->last_dts;
2159     *pkt_pts  = AV_NOPTS_VALUE;
2160
2161     ret = avcodec_decode_video2(ist->st->codec,
2162                                 decoded_frame, got_output, pkt);
2163     if (ret < 0)
2164         return ret;
2165
2166     quality = same_quant ? decoded_frame->quality : 0;
2167     if (!*got_output) {
2168         /* no picture yet */
2169         if (!pkt->size)
2170             for (i = 0; i < ist->nb_filters; i++)
2171                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
2172         return ret;
2173     }
2174     decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
2175                                            decoded_frame->pkt_dts);
2176     pkt->size = 0;
2177     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2178
2179     rate_emu_sleep(ist);
2180
2181     if (ist->st->sample_aspect_ratio.num)
2182         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2183
2184     resample_changed = ist->resample_width   != decoded_frame->width  ||
2185                        ist->resample_height  != decoded_frame->height ||
2186                        ist->resample_pix_fmt != decoded_frame->format;
2187     if (resample_changed) {
2188         av_log(NULL, AV_LOG_INFO,
2189                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2190                ist->file_index, ist->st->index,
2191                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
2192                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2193
2194         ist->resample_width   = decoded_frame->width;
2195         ist->resample_height  = decoded_frame->height;
2196         ist->resample_pix_fmt = decoded_frame->format;
2197
2198         for (i = 0; i < nb_filtergraphs; i++)
2199             if (ist_in_filtergraph(filtergraphs[i], ist) &&
2200                 configure_filtergraph(filtergraphs[i]) < 0) {
2201                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2202                 exit_program(1);
2203             }
2204     }
2205
2206     for (i = 0; i < ist->nb_filters; i++) {
2207         // XXX what an ugly hack
2208         if (ist->filters[i]->graph->nb_outputs == 1)
2209             ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2210
2211         if (ist->st->codec->codec->capabilities & CODEC_CAP_DR1) {
2212             FrameBuffer      *buf = decoded_frame->opaque;
2213             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2214                                         decoded_frame->data, decoded_frame->linesize,
2215                                         AV_PERM_READ | AV_PERM_PRESERVE,
2216                                         ist->st->codec->width, ist->st->codec->height,
2217                                         ist->st->codec->pix_fmt);
2218
2219             avfilter_copy_frame_props(fb, decoded_frame);
2220             fb->buf->priv           = buf;
2221             fb->buf->free           = filter_release_buffer;
2222
2223             buf->refcount++;
2224             av_buffersrc_buffer(ist->filters[i]->filter, fb);
2225         } else
2226             av_buffersrc_write_frame(ist->filters[i]->filter, decoded_frame);
2227     }
2228
2229     av_free(buffer_to_free);
2230     return ret;
2231 }
2232
2233 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2234 {
2235     AVSubtitle subtitle;
2236     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2237                                           &subtitle, got_output, pkt);
2238     if (ret < 0)
2239         return ret;
2240     if (!*got_output)
2241         return ret;
2242
2243     rate_emu_sleep(ist);
2244
2245     for (i = 0; i < nb_output_streams; i++) {
2246         OutputStream *ost = output_streams[i];
2247
2248         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2249             continue;
2250
2251         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2252     }
2253
2254     avsubtitle_free(&subtitle);
2255     return ret;
2256 }
2257
2258 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2259 static int output_packet(InputStream *ist, const AVPacket *pkt)
2260 {
2261     int i;
2262     int got_output;
2263     int64_t pkt_pts = AV_NOPTS_VALUE;
2264     AVPacket avpkt;
2265
2266     if (ist->next_dts == AV_NOPTS_VALUE)
2267         ist->next_dts = ist->last_dts;
2268
2269     if (pkt == NULL) {
2270         /* EOF handling */
2271         av_init_packet(&avpkt);
2272         avpkt.data = NULL;
2273         avpkt.size = 0;
2274         goto handle_eof;
2275     } else {
2276         avpkt = *pkt;
2277     }
2278
2279     if (pkt->dts != AV_NOPTS_VALUE)
2280         ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2281     if (pkt->pts != AV_NOPTS_VALUE)
2282         pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2283
2284     // while we have more to decode or while the decoder did output something on EOF
2285     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2286         int ret = 0;
2287     handle_eof:
2288
2289         ist->last_dts = ist->next_dts;
2290
2291         if (avpkt.size && avpkt.size != pkt->size) {
2292             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2293                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2294             ist->showed_multi_packet_warning = 1;
2295         }
2296
2297         switch (ist->st->codec->codec_type) {
2298         case AVMEDIA_TYPE_AUDIO:
2299             ret = transcode_audio    (ist, &avpkt, &got_output);
2300             break;
2301         case AVMEDIA_TYPE_VIDEO:
2302             ret = transcode_video    (ist, &avpkt, &got_output, &pkt_pts);
2303             if (avpkt.duration)
2304                 ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2305             else if (ist->st->r_frame_rate.num)
2306                 ist->next_dts += av_rescale_q(1, (AVRational){ist->st->r_frame_rate.den,
2307                                                               ist->st->r_frame_rate.num},
2308                                               AV_TIME_BASE_Q);
2309             else if (ist->st->codec->time_base.num != 0) {
2310                 int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
2311                                                    ist->st->codec->ticks_per_frame;
2312                 ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
2313             }
2314             break;
2315         case AVMEDIA_TYPE_SUBTITLE:
2316             ret = transcode_subtitles(ist, &avpkt, &got_output);
2317             break;
2318         default:
2319             return -1;
2320         }
2321
2322         if (ret < 0)
2323             return ret;
2324         // touch data and size only if not EOF
2325         if (pkt) {
2326             avpkt.data += ret;
2327             avpkt.size -= ret;
2328         }
2329         if (!got_output) {
2330             continue;
2331         }
2332     }
2333
2334     /* handle stream copy */
2335     if (!ist->decoding_needed) {
2336         rate_emu_sleep(ist);
2337         ist->last_dts = ist->next_dts;
2338         switch (ist->st->codec->codec_type) {
2339         case AVMEDIA_TYPE_AUDIO:
2340             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2341                              ist->st->codec->sample_rate;
2342             break;
2343         case AVMEDIA_TYPE_VIDEO:
2344             if (ist->st->codec->time_base.num != 0) {
2345                 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2346                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2347                                   ist->st->codec->time_base.num * ticks) /
2348                                   ist->st->codec->time_base.den;
2349             }
2350             break;
2351         }
2352     }
2353     for (i = 0; pkt && i < nb_output_streams; i++) {
2354         OutputStream *ost = output_streams[i];
2355
2356         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2357             continue;
2358
2359         do_streamcopy(ist, ost, pkt);
2360     }
2361
2362     return 0;
2363 }
2364
2365 static void print_sdp(void)
2366 {
2367     char sdp[2048];
2368     int i;
2369     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2370
2371     if (!avc)
2372         exit_program(1);
2373     for (i = 0; i < nb_output_files; i++)
2374         avc[i] = output_files[i]->ctx;
2375
2376     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2377     printf("SDP:\n%s\n", sdp);
2378     fflush(stdout);
2379     av_freep(&avc);
2380 }
2381
2382 static int init_input_stream(int ist_index, char *error, int error_len)
2383 {
2384     int i;
2385     InputStream *ist = input_streams[ist_index];
2386     if (ist->decoding_needed) {
2387         AVCodec *codec = ist->dec;
2388         if (!codec) {
2389             snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2390                     ist->st->codec->codec_id, ist->file_index, ist->st->index);
2391             return AVERROR(EINVAL);
2392         }
2393
2394         /* update requested sample format for the decoder based on the
2395            corresponding encoder sample format */
2396         for (i = 0; i < nb_output_streams; i++) {
2397             OutputStream *ost = output_streams[i];
2398             if (ost->source_index == ist_index) {
2399                 update_sample_fmt(ist->st->codec, codec, ost->st->codec);
2400                 break;
2401             }
2402         }
2403
2404         if (codec->type == AVMEDIA_TYPE_VIDEO && codec->capabilities & CODEC_CAP_DR1) {
2405             ist->st->codec->get_buffer     = codec_get_buffer;
2406             ist->st->codec->release_buffer = codec_release_buffer;
2407             ist->st->codec->opaque         = ist;
2408         }
2409
2410         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2411             av_dict_set(&ist->opts, "threads", "auto", 0);
2412         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2413             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2414                     ist->file_index, ist->st->index);
2415             return AVERROR(EINVAL);
2416         }
2417         assert_codec_experimental(ist->st->codec, 0);
2418         assert_avoptions(ist->opts);
2419     }
2420
2421     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;
2422     ist->next_dts = AV_NOPTS_VALUE;
2423     init_pts_correction(&ist->pts_ctx);
2424     ist->is_start = 1;
2425
2426     return 0;
2427 }
2428
2429 static InputStream *get_input_stream(OutputStream *ost)
2430 {
2431     if (ost->source_index >= 0)
2432         return input_streams[ost->source_index];
2433
2434     if (ost->filter) {
2435         FilterGraph *fg = ost->filter->graph;
2436         int i;
2437
2438         for (i = 0; i < fg->nb_inputs; i++)
2439             if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2440                 return fg->inputs[i]->ist;
2441     }
2442
2443     return NULL;
2444 }
2445
2446 static int transcode_init(void)
2447 {
2448     int ret = 0, i, j, k;
2449     AVFormatContext *oc;
2450     AVCodecContext *codec, *icodec;
2451     OutputStream *ost;
2452     InputStream *ist;
2453     char error[1024];
2454     int want_sdp = 1;
2455
2456     /* init framerate emulation */
2457     for (i = 0; i < nb_input_files; i++) {
2458         InputFile *ifile = input_files[i];
2459         if (ifile->rate_emu)
2460             for (j = 0; j < ifile->nb_streams; j++)
2461                 input_streams[j + ifile->ist_index]->start = av_gettime();
2462     }
2463
2464     /* output stream init */
2465     for (i = 0; i < nb_output_files; i++) {
2466         oc = output_files[i]->ctx;
2467         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2468             av_dump_format(oc, i, oc->filename, 1);
2469             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2470             return AVERROR(EINVAL);
2471         }
2472     }
2473
2474     /* init complex filtergraphs */
2475     for (i = 0; i < nb_filtergraphs; i++)
2476         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2477             return ret;
2478
2479     /* for each output stream, we compute the right encoding parameters */
2480     for (i = 0; i < nb_output_streams; i++) {
2481         ost = output_streams[i];
2482         oc  = output_files[ost->file_index]->ctx;
2483         ist = get_input_stream(ost);
2484
2485         if (ost->attachment_filename)
2486             continue;
2487
2488         codec  = ost->st->codec;
2489
2490         if (ist) {
2491             icodec = ist->st->codec;
2492
2493             ost->st->disposition          = ist->st->disposition;
2494             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2495             codec->chroma_sample_location = icodec->chroma_sample_location;
2496         }
2497
2498         if (ost->stream_copy) {
2499             uint64_t extra_size;
2500
2501             av_assert0(ist && !ost->filter);
2502
2503             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2504
2505             if (extra_size > INT_MAX) {
2506                 return AVERROR(EINVAL);
2507             }
2508
2509             /* if stream_copy is selected, no need to decode or encode */
2510             codec->codec_id   = icodec->codec_id;
2511             codec->codec_type = icodec->codec_type;
2512
2513             if (!codec->codec_tag) {
2514                 if (!oc->oformat->codec_tag ||
2515                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2516                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2517                     codec->codec_tag = icodec->codec_tag;
2518             }
2519
2520             codec->bit_rate       = icodec->bit_rate;
2521             codec->rc_max_rate    = icodec->rc_max_rate;
2522             codec->rc_buffer_size = icodec->rc_buffer_size;
2523             codec->field_order    = icodec->field_order;
2524             codec->extradata      = av_mallocz(extra_size);
2525             if (!codec->extradata) {
2526                 return AVERROR(ENOMEM);
2527             }
2528             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2529             codec->extradata_size = icodec->extradata_size;
2530             if (!copy_tb) {
2531                 codec->time_base      = icodec->time_base;
2532                 codec->time_base.num *= icodec->ticks_per_frame;
2533                 av_reduce(&codec->time_base.num, &codec->time_base.den,
2534                           codec->time_base.num, codec->time_base.den, INT_MAX);
2535             } else
2536                 codec->time_base = ist->st->time_base;
2537
2538             switch (codec->codec_type) {
2539             case AVMEDIA_TYPE_AUDIO:
2540                 if (audio_volume != 256) {
2541                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2542                     exit_program(1);
2543                 }
2544                 codec->channel_layout     = icodec->channel_layout;
2545                 codec->sample_rate        = icodec->sample_rate;
2546                 codec->channels           = icodec->channels;
2547                 codec->frame_size         = icodec->frame_size;
2548                 codec->audio_service_type = icodec->audio_service_type;
2549                 codec->block_align        = icodec->block_align;
2550                 break;
2551             case AVMEDIA_TYPE_VIDEO:
2552                 codec->pix_fmt            = icodec->pix_fmt;
2553                 codec->width              = icodec->width;
2554                 codec->height             = icodec->height;
2555                 codec->has_b_frames       = icodec->has_b_frames;
2556                 if (!codec->sample_aspect_ratio.num) {
2557                     codec->sample_aspect_ratio   =
2558                     ost->st->sample_aspect_ratio =
2559                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2560                         ist->st->codec->sample_aspect_ratio.num ?
2561                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2562                 }
2563                 break;
2564             case AVMEDIA_TYPE_SUBTITLE:
2565                 codec->width  = icodec->width;
2566                 codec->height = icodec->height;
2567                 break;
2568             case AVMEDIA_TYPE_DATA:
2569             case AVMEDIA_TYPE_ATTACHMENT:
2570                 break;
2571             default:
2572                 abort();
2573             }
2574         } else {
2575             if (!ost->enc) {
2576                 /* should only happen when a default codec is not present. */
2577                 snprintf(error, sizeof(error), "Automatic encoder selection "
2578                          "failed for output stream #%d:%d. Default encoder for "
2579                          "format %s is probably disabled. Please choose an "
2580                          "encoder manually.\n", ost->file_index, ost->index,
2581                          oc->oformat->name);
2582                 ret = AVERROR(EINVAL);
2583                 goto dump_format;
2584             }
2585
2586             if (ist)
2587                 ist->decoding_needed = 1;
2588             ost->encoding_needed = 1;
2589
2590             if (!ost->filter &&
2591                 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2592                  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2593                     FilterGraph *fg;
2594                     fg = init_simple_filtergraph(ist, ost);
2595                     if (configure_simple_filtergraph(fg)) {
2596                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2597                         exit(1);
2598                     }
2599             }
2600
2601             switch (codec->codec_type) {
2602             case AVMEDIA_TYPE_AUDIO:
2603                 codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
2604                 codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
2605                 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2606                 codec->channels       = av_get_channel_layout_nb_channels(codec->channel_layout);
2607                 codec->time_base      = (AVRational){ 1, codec->sample_rate };
2608                 break;
2609             case AVMEDIA_TYPE_VIDEO:
2610                 /*
2611                  * We want CFR output if and only if one of those is true:
2612                  * 1) user specified output framerate with -r
2613                  * 2) user specified -vsync cfr
2614                  * 3) output format is CFR and the user didn't force vsync to
2615                  *    something else than CFR
2616                  *
2617                  * in such a case, set ost->frame_rate
2618                  */
2619                 if (!ost->frame_rate.num && ist &&
2620                     (video_sync_method ==  VSYNC_CFR ||
2621                      (video_sync_method ==  VSYNC_AUTO &&
2622                       !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
2623                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2624                     if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2625                         int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2626                         ost->frame_rate = ost->enc->supported_framerates[idx];
2627                     }
2628                 }
2629                 if (ost->frame_rate.num) {
2630                     codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2631                     video_sync_method = VSYNC_CFR;
2632                 } else if (ist)
2633                     codec->time_base = ist->st->time_base;
2634                 else
2635                     codec->time_base = ost->filter->filter->inputs[0]->time_base;
2636
2637                 codec->width  = ost->filter->filter->inputs[0]->w;
2638                 codec->height = ost->filter->filter->inputs[0]->h;
2639                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2640                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2641                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2642                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
2643                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2644
2645                 if (codec->width   != icodec->width  ||
2646                     codec->height  != icodec->height ||
2647                     codec->pix_fmt != icodec->pix_fmt) {
2648                     codec->bits_per_raw_sample = 0;
2649                 }
2650
2651                 break;
2652             case AVMEDIA_TYPE_SUBTITLE:
2653                 codec->time_base = (AVRational){1, 1000};
2654                 break;
2655             default:
2656                 abort();
2657                 break;
2658             }
2659             /* two pass mode */
2660             if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
2661                 char logfilename[1024];
2662                 FILE *f;
2663
2664                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2665                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2666                          i);
2667                 if (!strcmp(ost->enc->name, "libx264")) {
2668                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2669                 } else {
2670                     if (codec->flags & CODEC_FLAG_PASS1) {
2671                         f = fopen(logfilename, "wb");
2672                         if (!f) {
2673                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2674                                    logfilename, strerror(errno));
2675                             exit_program(1);
2676                         }
2677                         ost->logfile = f;
2678                     } else {
2679                         char  *logbuffer;
2680                         size_t logbuffer_size;
2681                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2682                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2683                                    logfilename);
2684                             exit_program(1);
2685                         }
2686                         codec->stats_in = logbuffer;
2687                     }
2688                 }
2689             }
2690         }
2691     }
2692
2693     /* open each encoder */
2694     for (i = 0; i < nb_output_streams; i++) {
2695         ost = output_streams[i];
2696         if (ost->encoding_needed) {
2697             AVCodec      *codec = ost->enc;
2698             AVCodecContext *dec = NULL;
2699
2700             if ((ist = get_input_stream(ost)))
2701                 dec = ist->st->codec;
2702             if (dec && dec->subtitle_header) {
2703                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2704                 if (!ost->st->codec->subtitle_header) {
2705                     ret = AVERROR(ENOMEM);
2706                     goto dump_format;
2707                 }
2708                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2709                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2710             }
2711             if (!av_dict_get(ost->opts, "threads", NULL, 0))
2712                 av_dict_set(&ost->opts, "threads", "auto", 0);
2713             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2714                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2715                         ost->file_index, ost->index);
2716                 ret = AVERROR(EINVAL);
2717                 goto dump_format;
2718             }
2719             assert_codec_experimental(ost->st->codec, 1);
2720             assert_avoptions(ost->opts);
2721             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2722                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2723                                              "It takes bits/s as argument, not kbits/s\n");
2724             extra_size += ost->st->codec->extradata_size;
2725
2726             if (ost->st->codec->me_threshold)
2727                 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2728         }
2729     }
2730
2731     /* init input streams */
2732     for (i = 0; i < nb_input_streams; i++)
2733         if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
2734             goto dump_format;
2735
2736     /* discard unused programs */
2737     for (i = 0; i < nb_input_files; i++) {
2738         InputFile *ifile = input_files[i];
2739         for (j = 0; j < ifile->ctx->nb_programs; j++) {
2740             AVProgram *p = ifile->ctx->programs[j];
2741             int discard  = AVDISCARD_ALL;
2742
2743             for (k = 0; k < p->nb_stream_indexes; k++)
2744                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2745                     discard = AVDISCARD_DEFAULT;
2746                     break;
2747                 }
2748             p->discard = discard;
2749         }
2750     }
2751
2752     /* open files and write file headers */
2753     for (i = 0; i < nb_output_files; i++) {
2754         oc = output_files[i]->ctx;
2755         oc->interrupt_callback = int_cb;
2756         if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
2757             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2758             ret = AVERROR(EINVAL);
2759             goto dump_format;
2760         }
2761         assert_avoptions(output_files[i]->opts);
2762         if (strcmp(oc->oformat->name, "rtp")) {
2763             want_sdp = 0;
2764         }
2765     }
2766
2767  dump_format:
2768     /* dump the file output parameters - cannot be done before in case
2769        of stream copy */
2770     for (i = 0; i < nb_output_files; i++) {
2771         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2772     }
2773
2774     /* dump the stream mapping */
2775     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2776     for (i = 0; i < nb_input_streams; i++) {
2777         ist = input_streams[i];
2778
2779         for (j = 0; j < ist->nb_filters; j++) {
2780             AVFilterLink *link = ist->filters[j]->filter->outputs[0];
2781             if (ist->filters[j]->graph->graph_desc) {
2782                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
2783                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2784                        link->dst->filter->name);
2785                 if (link->dst->input_count > 1)
2786                     av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
2787                 if (nb_filtergraphs > 1)
2788                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2789                 av_log(NULL, AV_LOG_INFO, "\n");
2790             }
2791         }
2792     }
2793
2794     for (i = 0; i < nb_output_streams; i++) {
2795         ost = output_streams[i];
2796
2797         if (ost->attachment_filename) {
2798             /* an attached file */
2799             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
2800                    ost->attachment_filename, ost->file_index, ost->index);
2801             continue;
2802         }
2803
2804         if (ost->filter && ost->filter->graph->graph_desc) {
2805             /* output from a complex graph */
2806             AVFilterLink *link = ost->filter->filter->inputs[0];
2807             av_log(NULL, AV_LOG_INFO, "  %s", link->src->filter->name);
2808             if (link->src->output_count > 1)
2809                 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
2810             if (nb_filtergraphs > 1)
2811                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2812
2813             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2814                    ost->index, ost->enc ? ost->enc->name : "?");
2815             continue;
2816         }
2817
2818         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
2819                input_streams[ost->source_index]->file_index,
2820                input_streams[ost->source_index]->st->index,
2821                ost->file_index,
2822                ost->index);
2823         if (ost->sync_ist != input_streams[ost->source_index])
2824             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2825                    ost->sync_ist->file_index,
2826                    ost->sync_ist->st->index);
2827         if (ost->stream_copy)
2828             av_log(NULL, AV_LOG_INFO, " (copy)");
2829         else
2830             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2831                    input_streams[ost->source_index]->dec->name : "?",
2832                    ost->enc ? ost->enc->name : "?");
2833         av_log(NULL, AV_LOG_INFO, "\n");
2834     }
2835
2836     if (ret) {
2837         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2838         return ret;
2839     }
2840
2841     if (want_sdp) {
2842         print_sdp();
2843     }
2844
2845     return 0;
2846 }
2847
2848 /*
2849  * The following code is the main loop of the file converter
2850  */
2851 static int transcode(void)
2852 {
2853     int ret, i;
2854     AVFormatContext *is, *os;
2855     OutputStream *ost;
2856     InputStream *ist;
2857     uint8_t *no_packet;
2858     int no_packet_count = 0;
2859     int64_t timer_start;
2860
2861     if (!(no_packet = av_mallocz(nb_input_files)))
2862         exit_program(1);
2863
2864     ret = transcode_init();
2865     if (ret < 0)
2866         goto fail;
2867
2868     av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
2869     term_init();
2870
2871     timer_start = av_gettime();
2872
2873     for (; received_sigterm == 0;) {
2874         int file_index, ist_index, past_recording_time = 1;
2875         AVPacket pkt;
2876         int64_t ipts_min;
2877
2878         ipts_min = INT64_MAX;
2879
2880         /* check if there's any stream where output is still needed */
2881         for (i = 0; i < nb_output_streams; i++) {
2882             OutputFile *of;
2883             ost = output_streams[i];
2884             of  = output_files[ost->file_index];
2885             os  = output_files[ost->file_index]->ctx;
2886             if (ost->is_past_recording_time ||
2887                 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2888                 continue;
2889             if (ost->frame_number > ost->max_frames) {
2890                 int j;
2891                 for (j = 0; j < of->ctx->nb_streams; j++)
2892                     output_streams[of->ost_index + j]->is_past_recording_time = 1;
2893                 continue;
2894             }
2895             past_recording_time = 0;
2896         }
2897         if (past_recording_time)
2898             break;
2899
2900         /* select the stream that we must read now by looking at the
2901            smallest output pts */
2902         file_index = -1;
2903         for (i = 0; i < nb_input_streams; i++) {
2904             int64_t ipts;
2905             ist = input_streams[i];
2906             ipts = ist->last_dts;
2907             if (ist->discard || no_packet[ist->file_index])
2908                 continue;
2909             if (!input_files[ist->file_index]->eof_reached) {
2910                 if (ipts < ipts_min) {
2911                     ipts_min = ipts;
2912                     file_index = ist->file_index;
2913                 }
2914             }
2915         }
2916         /* if none, if is finished */
2917         if (file_index < 0) {
2918             if (no_packet_count) {
2919                 no_packet_count = 0;
2920                 memset(no_packet, 0, nb_input_files);
2921                 usleep(10000);
2922                 continue;
2923             }
2924             break;
2925         }
2926
2927         /* read a frame from it and output it in the fifo */
2928         is  = input_files[file_index]->ctx;
2929         ret = av_read_frame(is, &pkt);
2930         if (ret == AVERROR(EAGAIN)) {
2931             no_packet[file_index] = 1;
2932             no_packet_count++;
2933             continue;
2934         }
2935         if (ret < 0) {
2936             input_files[file_index]->eof_reached = 1;
2937
2938             for (i = 0; i < input_files[file_index]->nb_streams; i++) {
2939                 ist = input_streams[input_files[file_index]->ist_index + i];
2940                 if (ist->decoding_needed)
2941                     output_packet(ist, NULL);
2942             }
2943
2944             if (opt_shortest)
2945                 break;
2946             else
2947                 continue;
2948         }
2949
2950         no_packet_count = 0;
2951         memset(no_packet, 0, nb_input_files);
2952
2953         if (do_pkt_dump) {
2954             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2955                              is->streams[pkt.stream_index]);
2956         }
2957         /* the following test is needed in case new streams appear
2958            dynamically in stream : we ignore them */
2959         if (pkt.stream_index >= input_files[file_index]->nb_streams)
2960             goto discard_packet;
2961         ist_index = input_files[file_index]->ist_index + pkt.stream_index;
2962         ist = input_streams[ist_index];
2963         if (ist->discard)
2964             goto discard_packet;
2965
2966         if (pkt.dts != AV_NOPTS_VALUE)
2967             pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2968         if (pkt.pts != AV_NOPTS_VALUE)
2969             pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2970
2971         if (pkt.pts != AV_NOPTS_VALUE)
2972             pkt.pts *= ist->ts_scale;
2973         if (pkt.dts != AV_NOPTS_VALUE)
2974             pkt.dts *= ist->ts_scale;
2975
2976         //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
2977         //        ist->next_dts,
2978         //        pkt.dts, input_files[ist->file_index].ts_offset,
2979         //        ist->st->codec->codec_type);
2980         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE
2981             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2982             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2983             int64_t delta   = pkt_dts - ist->next_dts;
2984             if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2985                 input_files[ist->file_index]->ts_offset -= delta;
2986                 av_log(NULL, AV_LOG_DEBUG,
2987                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2988                        delta, input_files[ist->file_index]->ts_offset);
2989                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2990                 if (pkt.pts != AV_NOPTS_VALUE)
2991                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2992             }
2993         }
2994
2995         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
2996         if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
2997             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
2998                    ist->file_index, ist->st->index);
2999             if (exit_on_error)
3000                 exit_program(1);
3001             av_free_packet(&pkt);
3002             continue;
3003         }
3004
3005     discard_packet:
3006         av_free_packet(&pkt);
3007
3008         /* dump report by using the output first video and audio streams */
3009         print_report(0, timer_start);
3010     }
3011
3012     /* at the end of stream, we must flush the decoder buffers */
3013     for (i = 0; i < nb_input_streams; i++) {
3014         ist = input_streams[i];
3015         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3016             output_packet(ist, NULL);
3017         }
3018     }
3019     poll_filters();
3020     flush_encoders();
3021
3022     term_exit();
3023
3024     /* write the trailer if needed and close file */
3025     for (i = 0; i < nb_output_files; i++) {
3026         os = output_files[i]->ctx;
3027         av_write_trailer(os);
3028     }
3029
3030     /* dump report by using the first video and audio streams */
3031     print_report(1, timer_start);
3032
3033     /* close each encoder */
3034     for (i = 0; i < nb_output_streams; i++) {
3035         ost = output_streams[i];
3036         if (ost->encoding_needed) {
3037             av_freep(&ost->st->codec->stats_in);
3038             avcodec_close(ost->st->codec);
3039         }
3040     }
3041
3042     /* close each decoder */
3043     for (i = 0; i < nb_input_streams; i++) {
3044         ist = input_streams[i];
3045         if (ist->decoding_needed) {
3046             avcodec_close(ist->st->codec);
3047         }
3048     }
3049
3050     /* finished ! */
3051     ret = 0;
3052
3053  fail:
3054     av_freep(&no_packet);
3055
3056     if (output_streams) {
3057         for (i = 0; i < nb_output_streams; i++) {
3058             ost = output_streams[i];
3059             if (ost) {
3060                 if (ost->stream_copy)
3061                     av_freep(&ost->st->codec->extradata);
3062                 if (ost->logfile) {
3063                     fclose(ost->logfile);
3064                     ost->logfile = NULL;
3065                 }
3066                 av_freep(&ost->st->codec->subtitle_header);
3067                 av_free(ost->forced_kf_pts);
3068                 av_dict_free(&ost->opts);
3069             }
3070         }
3071     }
3072     return ret;
3073 }
3074
3075 static double parse_frame_aspect_ratio(const char *arg)
3076 {
3077     int x = 0, y = 0;
3078     double ar = 0;
3079     const char *p;
3080     char *end;
3081
3082     p = strchr(arg, ':');
3083     if (p) {
3084         x = strtol(arg, &end, 10);
3085         if (end == p)
3086             y = strtol(end + 1, &end, 10);
3087         if (x > 0 && y > 0)
3088             ar = (double)x / (double)y;
3089     } else
3090         ar = strtod(arg, NULL);
3091
3092     if (!ar) {
3093         av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
3094         exit_program(1);
3095     }
3096     return ar;
3097 }
3098
3099 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3100 {
3101     return parse_option(o, "codec:a", arg, options);
3102 }
3103
3104 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3105 {
3106     return parse_option(o, "codec:v", arg, options);
3107 }
3108
3109 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3110 {
3111     return parse_option(o, "codec:s", arg, options);
3112 }
3113
3114 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3115 {
3116     return parse_option(o, "codec:d", arg, options);
3117 }
3118
3119 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3120 {
3121     StreamMap *m = NULL;
3122     int i, negative = 0, file_idx;
3123     int sync_file_idx = -1, sync_stream_idx;
3124     char *p, *sync;
3125     char *map;
3126
3127     if (*arg == '-') {
3128         negative = 1;
3129         arg++;
3130     }
3131     map = av_strdup(arg);
3132
3133     /* parse sync stream first, just pick first matching stream */
3134     if (sync = strchr(map, ',')) {
3135         *sync = 0;
3136         sync_file_idx = strtol(sync + 1, &sync, 0);
3137         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3138             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3139             exit_program(1);
3140         }
3141         if (*sync)
3142             sync++;
3143         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3144             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3145                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3146                 sync_stream_idx = i;
3147                 break;
3148             }
3149         if (i == input_files[sync_file_idx]->nb_streams) {
3150             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3151                                        "match any streams.\n", arg);
3152             exit_program(1);
3153         }
3154     }
3155
3156
3157     if (map[0] == '[') {
3158         /* this mapping refers to lavfi output */
3159         const char *c = map + 1;
3160         o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3161                                     &o->nb_stream_maps, o->nb_stream_maps + 1);
3162         m = &o->stream_maps[o->nb_stream_maps - 1];
3163         m->linklabel = av_get_token(&c, "]");
3164         if (!m->linklabel) {
3165             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3166             exit_program(1);
3167         }
3168     } else {
3169         file_idx = strtol(map, &p, 0);
3170         if (file_idx >= nb_input_files || file_idx < 0) {
3171             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3172             exit_program(1);
3173         }
3174         if (negative)
3175             /* disable some already defined maps */
3176             for (i = 0; i < o->nb_stream_maps; i++) {
3177                 m = &o->stream_maps[i];
3178                 if (file_idx == m->file_index &&
3179                     check_stream_specifier(input_files[m->file_index]->ctx,
3180                                            input_files[m->file_index]->ctx->streams[m->stream_index],
3181                                            *p == ':' ? p + 1 : p) > 0)
3182                     m->disabled = 1;
3183             }
3184         else
3185             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3186                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3187                             *p == ':' ? p + 1 : p) <= 0)
3188                     continue;
3189                 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3190                                             &o->nb_stream_maps, o->nb_stream_maps + 1);
3191                 m = &o->stream_maps[o->nb_stream_maps - 1];
3192
3193                 m->file_index   = file_idx;
3194                 m->stream_index = i;
3195
3196                 if (sync_file_idx >= 0) {
3197                     m->sync_file_index   = sync_file_idx;
3198                     m->sync_stream_index = sync_stream_idx;
3199                 } else {
3200                     m->sync_file_index   = file_idx;
3201                     m->sync_stream_index = i;
3202                 }
3203             }
3204     }
3205
3206     if (!m) {
3207         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3208         exit_program(1);
3209     }
3210
3211     av_freep(&map);
3212     return 0;
3213 }
3214
3215 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3216 {
3217     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3218                                 &o->nb_attachments, o->nb_attachments + 1);
3219     o->attachments[o->nb_attachments - 1] = arg;
3220     return 0;
3221 }
3222
3223 /**
3224  * Parse a metadata specifier in arg.
3225  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3226  * @param index for type c/p, chapter/program index is written here
3227  * @param stream_spec for type s, the stream specifier is written here
3228  */
3229 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3230 {
3231     if (*arg) {
3232         *type = *arg;
3233         switch (*arg) {
3234         case 'g':
3235             break;
3236         case 's':
3237             if (*(++arg) && *arg != ':') {
3238                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3239                 exit_program(1);
3240             }
3241             *stream_spec = *arg == ':' ? arg + 1 : "";
3242             break;
3243         case 'c':
3244         case 'p':
3245             if (*(++arg) == ':')
3246                 *index = strtol(++arg, NULL, 0);
3247             break;
3248         default:
3249             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3250             exit_program(1);
3251         }
3252     } else
3253         *type = 'g';
3254 }
3255
3256 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3257 {
3258     AVDictionary **meta_in = NULL;
3259     AVDictionary **meta_out;
3260     int i, ret = 0;
3261     char type_in, type_out;
3262     const char *istream_spec = NULL, *ostream_spec = NULL;
3263     int idx_in = 0, idx_out = 0;
3264
3265     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
3266     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3267
3268     if (type_in == 'g' || type_out == 'g')
3269         o->metadata_global_manual = 1;
3270     if (type_in == 's' || type_out == 's')
3271         o->metadata_streams_manual = 1;
3272     if (type_in == 'c' || type_out == 'c')
3273         o->metadata_chapters_manual = 1;
3274
3275 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3276     if ((index) < 0 || (index) >= (nb_elems)) {\
3277         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3278                 (desc), (index));\
3279         exit_program(1);\
3280     }
3281
3282 #define SET_DICT(type, meta, context, index)\
3283         switch (type) {\
3284         case 'g':\
3285             meta = &context->metadata;\
3286             break;\
3287         case 'c':\
3288             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3289             meta = &context->chapters[index]->metadata;\
3290             break;\
3291         case 'p':\
3292             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3293             meta = &context->programs[index]->metadata;\
3294             break;\
3295         }\
3296
3297     SET_DICT(type_in, meta_in, ic, idx_in);
3298     SET_DICT(type_out, meta_out, oc, idx_out);
3299
3300     /* for input streams choose first matching stream */
3301     if (type_in == 's') {
3302         for (i = 0; i < ic->nb_streams; i++) {
3303             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3304                 meta_in = &ic->streams[i]->metadata;
3305                 break;
3306             } else if (ret < 0)
3307                 exit_program(1);
3308         }
3309         if (!meta_in) {
3310             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
3311             exit_program(1);
3312         }
3313     }
3314
3315     if (type_out == 's') {
3316         for (i = 0; i < oc->nb_streams; i++) {
3317             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3318                 meta_out = &oc->streams[i]->metadata;
3319                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3320             } else if (ret < 0)
3321                 exit_program(1);
3322         }
3323     } else
3324         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3325
3326     return 0;
3327 }
3328
3329 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3330 {
3331     const char *codec_string = encoder ? "encoder" : "decoder";
3332     AVCodec *codec;
3333
3334     codec = encoder ?
3335         avcodec_find_encoder_by_name(name) :
3336         avcodec_find_decoder_by_name(name);
3337     if (!codec) {
3338         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3339         exit_program(1);
3340     }
3341     if (codec->type != type) {
3342         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3343         exit_program(1);
3344     }
3345     return codec;
3346 }
3347
3348 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3349 {
3350     char *codec_name = NULL;
3351
3352     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3353     if (codec_name) {
3354         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3355         st->codec->codec_id = codec->id;
3356         return codec;
3357     } else
3358         return avcodec_find_decoder(st->codec->codec_id);
3359 }
3360
3361 /**
3362  * Add all the streams from the given input file to the global
3363  * list of input streams.
3364  */
3365 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3366 {
3367     int i;
3368
3369     for (i = 0; i < ic->nb_streams; i++) {
3370         AVStream *st = ic->streams[i];
3371         AVCodecContext *dec = st->codec;
3372         InputStream *ist = av_mallocz(sizeof(*ist));
3373
3374         if (!ist)
3375             exit_program(1);
3376
3377         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3378         input_streams[nb_input_streams - 1] = ist;
3379
3380         ist->st = st;
3381         ist->file_index = nb_input_files;
3382         ist->discard = 1;
3383         st->discard  = AVDISCARD_ALL;
3384         ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
3385
3386         ist->ts_scale = 1.0;
3387         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3388
3389         ist->dec = choose_decoder(o, ic, st);
3390
3391         switch (dec->codec_type) {
3392         case AVMEDIA_TYPE_VIDEO:
3393             ist->resample_height  = dec->height;
3394             ist->resample_width   = dec->width;
3395             ist->resample_pix_fmt = dec->pix_fmt;
3396
3397             break;
3398         case AVMEDIA_TYPE_AUDIO:
3399             guess_input_channel_layout(ist);
3400
3401             ist->resample_sample_fmt     = dec->sample_fmt;
3402             ist->resample_sample_rate    = dec->sample_rate;
3403             ist->resample_channels       = dec->channels;
3404             ist->resample_channel_layout = dec->channel_layout;
3405
3406             break;
3407         case AVMEDIA_TYPE_DATA:
3408         case AVMEDIA_TYPE_SUBTITLE:
3409         case AVMEDIA_TYPE_ATTACHMENT:
3410         case AVMEDIA_TYPE_UNKNOWN:
3411             break;
3412         default:
3413             abort();
3414         }
3415     }
3416 }
3417
3418 static void assert_file_overwrite(const char *filename)
3419 {
3420     if (!file_overwrite &&
3421         (strchr(filename, ':') == NULL || filename[1] == ':' ||
3422          av_strstart(filename, "file:", NULL))) {
3423         if (avio_check(filename, 0) == 0) {
3424             if (!using_stdin) {
3425                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3426                 fflush(stderr);
3427                 if (!read_yesno()) {
3428                     fprintf(stderr, "Not overwriting - exiting\n");
3429                     exit_program(1);
3430                 }
3431             }
3432             else {
3433                 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3434                 exit_program(1);
3435             }
3436         }
3437     }
3438 }
3439
3440 static void dump_attachment(AVStream *st, const char *filename)
3441 {
3442     int ret;
3443     AVIOContext *out = NULL;
3444     AVDictionaryEntry *e;
3445
3446     if (!st->codec->extradata_size) {
3447         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3448                nb_input_files - 1, st->index);
3449         return;
3450     }
3451     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3452         filename = e->value;
3453     if (!*filename) {
3454         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3455                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3456         exit_program(1);
3457     }
3458
3459     assert_file_overwrite(filename);
3460
3461     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3462         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3463                filename);
3464         exit_program(1);
3465     }
3466
3467     avio_write(out, st->codec->extradata, st->codec->extradata_size);
3468     avio_flush(out);
3469     avio_close(out);
3470 }
3471
3472 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3473 {
3474     AVFormatContext *ic;
3475     AVInputFormat *file_iformat = NULL;
3476     int err, i, ret;
3477     int64_t timestamp;
3478     uint8_t buf[128];
3479     AVDictionary **opts;
3480     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
3481
3482     if (o->format) {
3483         if (!(file_iformat = av_find_input_format(o->format))) {
3484             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3485             exit_program(1);
3486         }
3487     }
3488
3489     if (!strcmp(filename, "-"))
3490         filename = "pipe:";
3491
3492     using_stdin |= !strncmp(filename, "pipe:", 5) ||
3493                     !strcmp(filename, "/dev/stdin");
3494
3495     /* get default parameters from command line */
3496     ic = avformat_alloc_context();
3497     if (!ic) {
3498         print_error(filename, AVERROR(ENOMEM));
3499         exit_program(1);
3500     }
3501     if (o->nb_audio_sample_rate) {
3502         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3503         av_dict_set(&format_opts, "sample_rate", buf, 0);
3504     }
3505     if (o->nb_audio_channels) {
3506         /* because we set audio_channels based on both the "ac" and
3507          * "channel_layout" options, we need to check that the specified
3508          * demuxer actually has the "channels" option before setting it */
3509         if (file_iformat && file_iformat->priv_class &&
3510             av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
3511                         AV_OPT_SEARCH_FAKE_OBJ)) {
3512             snprintf(buf, sizeof(buf), "%d",
3513                      o->audio_channels[o->nb_audio_channels - 1].u.i);
3514             av_dict_set(&format_opts, "channels", buf, 0);
3515         }
3516     }
3517     if (o->nb_frame_rates) {
3518         av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3519     }
3520     if (o->nb_frame_sizes) {
3521         av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3522     }
3523     if (o->nb_frame_pix_fmts)
3524         av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3525
3526     ic->flags |= AVFMT_FLAG_NONBLOCK;
3527     ic->interrupt_callback = int_cb;
3528
3529     /* open the input file with generic libav function */
3530     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3531     if (err < 0) {
3532         print_error(filename, err);
3533         exit_program(1);
3534     }
3535     assert_avoptions(format_opts);
3536
3537     /* apply forced codec ids */
3538     for (i = 0; i < ic->nb_streams; i++)
3539         choose_decoder(o, ic, ic->streams[i]);
3540
3541     /* Set AVCodecContext options for avformat_find_stream_info */
3542     opts = setup_find_stream_info_opts(ic, codec_opts);
3543     orig_nb_streams = ic->nb_streams;
3544
3545     /* If not enough info to get the stream parameters, we decode the
3546        first frames to get it. (used in mpeg case for example) */
3547     ret = avformat_find_stream_info(ic, opts);
3548     if (ret < 0) {
3549         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3550         avformat_close_input(&ic);
3551         exit_program(1);
3552     }
3553
3554     timestamp = o->start_time;
3555     /* add the stream start time */
3556     if (ic->start_time != AV_NOPTS_VALUE)
3557         timestamp += ic->start_time;
3558
3559     /* if seeking requested, we execute it */
3560     if (o->start_time != 0) {
3561         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3562         if (ret < 0) {
3563             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3564                    filename, (double)timestamp / AV_TIME_BASE);
3565         }
3566     }
3567
3568     /* update the current parameters so that they match the one of the input stream */
3569     add_input_streams(o, ic);
3570
3571     /* dump the file content */
3572     av_dump_format(ic, nb_input_files, filename, 0);
3573
3574     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3575     if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
3576         exit_program(1);
3577
3578     input_files[nb_input_files - 1]->ctx        = ic;
3579     input_files[nb_input_files - 1]->ist_index  = nb_input_streams - ic->nb_streams;
3580     input_files[nb_input_files - 1]->ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3581     input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
3582     input_files[nb_input_files - 1]->rate_emu   = o->rate_emu;
3583
3584     for (i = 0; i < o->nb_dump_attachment; i++) {
3585         int j;
3586
3587         for (j = 0; j < ic->nb_streams; j++) {
3588             AVStream *st = ic->streams[j];
3589
3590             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3591                 dump_attachment(st, o->dump_attachment[i].u.str);
3592         }
3593     }
3594
3595     for (i = 0; i < orig_nb_streams; i++)
3596         av_dict_free(&opts[i]);
3597     av_freep(&opts);
3598
3599     reset_options(o);
3600     return 0;
3601 }
3602
3603 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3604                                     AVCodecContext *avctx)
3605 {
3606     char *p;
3607     int n = 1, i;
3608     int64_t t;
3609
3610     for (p = kf; *p; p++)
3611         if (*p == ',')
3612             n++;
3613     ost->forced_kf_count = n;
3614     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3615     if (!ost->forced_kf_pts) {
3616         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3617         exit_program(1);
3618     }
3619     for (i = 0; i < n; i++) {
3620         p = i ? strchr(p, ',') + 1 : kf;
3621         t = parse_time_or_die("force_key_frames", p, 1);
3622         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3623     }
3624 }
3625
3626 static uint8_t *get_line(AVIOContext *s)
3627 {
3628     AVIOContext *line;
3629     uint8_t *buf;
3630     char c;
3631
3632     if (avio_open_dyn_buf(&line) < 0) {
3633         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3634         exit_program(1);
3635     }
3636
3637     while ((c = avio_r8(s)) && c != '\n')
3638         avio_w8(line, c);
3639     avio_w8(line, 0);
3640     avio_close_dyn_buf(line, &buf);
3641
3642     return buf;
3643 }
3644
3645 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3646 {
3647     int i, ret = 1;
3648     char filename[1000];
3649     const char *base[3] = { getenv("AVCONV_DATADIR"),
3650                             getenv("HOME"),
3651                             AVCONV_DATADIR,
3652                             };
3653
3654     for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3655         if (!base[i])
3656             continue;
3657         if (codec_name) {
3658             snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3659                      i != 1 ? "" : "/.avconv", codec_name, preset_name);
3660             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3661         }
3662         if (ret) {
3663             snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3664                      i != 1 ? "" : "/.avconv", preset_name);
3665             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3666         }
3667     }
3668     return ret;
3669 }
3670
3671 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3672 {
3673     char *codec_name = NULL;
3674
3675     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3676     if (!codec_name) {
3677         ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3678                                                   NULL, ost->st->codec->codec_type);
3679         ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3680     } else if (!strcmp(codec_name, "copy"))
3681         ost->stream_copy = 1;
3682     else {
3683         ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3684         ost->st->codec->codec_id = ost->enc->id;
3685     }
3686 }
3687
3688 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
3689 {
3690     OutputStream *ost;
3691     AVStream *st = avformat_new_stream(oc, NULL);
3692     int idx      = oc->nb_streams - 1, ret = 0;
3693     char *bsf = NULL, *next, *codec_tag = NULL;
3694     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3695     double qscale = -1;
3696     char *buf = NULL, *arg = NULL, *preset = NULL;
3697     AVIOContext *s = NULL;
3698
3699    &n