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