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