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