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