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