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