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