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