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