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