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