]> git.sesse.net Git - ffmpeg/blob - ffmpeg.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / ffmpeg.c
1 /*
2  * Copyright (c) 2000-2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * multimedia converter based on the FFmpeg libraries
24  */
25
26 #include "config.h"
27 #include <ctype.h>
28 #include <string.h>
29 #include <math.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <signal.h>
33 #include <limits.h>
34 #include <unistd.h>
35 #include "libavformat/avformat.h"
36 #include "libavdevice/avdevice.h"
37 #include "libswscale/swscale.h"
38 #include "libavutil/opt.h"
39 #include "libavcodec/audioconvert.h"
40 #include "libavutil/audioconvert.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/samplefmt.h"
43 #include "libavutil/colorspace.h"
44 #include "libavutil/fifo.h"
45 #include "libavutil/intreadwrite.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/avstring.h"
50 #include "libavutil/libm.h"
51 #include "libavutil/imgutils.h"
52 #include "libavutil/timestamp.h"
53 #include "libavformat/os_support.h"
54 #include "libswresample/swresample.h"
55
56 #include "libavformat/ffm.h" // not public API
57
58 # include "libavfilter/avcodec.h"
59 # include "libavfilter/avfilter.h"
60 # include "libavfilter/avfiltergraph.h"
61 # include "libavfilter/buffersink.h"
62 # include "libavfilter/buffersrc.h"
63 # include "libavfilter/vsrc_buffer.h"
64
65 #if HAVE_SYS_RESOURCE_H
66 #include <sys/types.h>
67 #include <sys/time.h>
68 #include <sys/resource.h>
69 #elif HAVE_GETPROCESSTIMES
70 #include <windows.h>
71 #endif
72 #if HAVE_GETPROCESSMEMORYINFO
73 #include <windows.h>
74 #include <psapi.h>
75 #endif
76
77 #if HAVE_SYS_SELECT_H
78 #include <sys/select.h>
79 #endif
80
81 #if HAVE_TERMIOS_H
82 #include <fcntl.h>
83 #include <sys/ioctl.h>
84 #include <sys/time.h>
85 #include <termios.h>
86 #elif HAVE_KBHIT
87 #include <conio.h>
88 #endif
89 #include <time.h>
90
91 #include "cmdutils.h"
92
93 #include "libavutil/avassert.h"
94
95 #define VSYNC_AUTO       -1
96 #define VSYNC_PASSTHROUGH 0
97 #define VSYNC_CFR         1
98 #define VSYNC_VFR         2
99 #define VSYNC_DROP        0xff
100
101 const char program_name[] = "ffmpeg";
102 const int program_birth_year = 2000;
103
104 /* select an input stream for an output stream */
105 typedef struct StreamMap {
106     int disabled;           /** 1 is this mapping is disabled by a negative map */
107     int file_index;
108     int stream_index;
109     int sync_file_index;
110     int sync_stream_index;
111 } StreamMap;
112
113 typedef struct {
114     int  file_idx,  stream_idx,  channel_idx; // input
115     int ofile_idx, ostream_idx;               // output
116 } AudioChannelMap;
117
118 static const OptionDef options[];
119
120 #define MAX_STREAMS 1024    /* arbitrary sanity check value */
121
122 static int frame_bits_per_raw_sample = 0;
123 static int video_discard = 0;
124 static int same_quant = 0;
125 static int do_deinterlace = 0;
126 static int intra_dc_precision = 8;
127 static int qp_hist = 0;
128 static int intra_only = 0;
129 static const char *video_codec_name    = NULL;
130 static const char *audio_codec_name    = NULL;
131 static const char *subtitle_codec_name = NULL;
132
133 static int file_overwrite = 0;
134 static int no_file_overwrite = 0;
135 static int do_benchmark = 0;
136 static int do_benchmark_all = 0;
137 static int do_hex_dump = 0;
138 static int do_pkt_dump = 0;
139 static int do_psnr = 0;
140 static int do_pass = 0;
141 static const char *pass_logfilename_prefix;
142 static int video_sync_method = VSYNC_AUTO;
143 static int audio_sync_method = 0;
144 static float audio_drift_threshold = 0.1;
145 static int copy_ts = 0;
146 static int copy_tb = -1;
147 static int opt_shortest = 0;
148 static char *vstats_filename;
149 static FILE *vstats_file;
150
151 static int audio_volume = 256;
152
153 static int exit_on_error = 0;
154 static int using_stdin = 0;
155 static int run_as_daemon  = 0;
156 static volatile int received_nb_signals = 0;
157 static int64_t video_size = 0;
158 static int64_t audio_size = 0;
159 static int64_t extra_size = 0;
160 static int nb_frames_dup = 0;
161 static int nb_frames_drop = 0;
162 static int input_sync;
163
164 static float dts_delta_threshold = 10;
165 static float dts_error_threshold = 3600*30;
166
167 static int print_stats = 1;
168 static int debug_ts = 0;
169 static int current_time;
170
171 static uint8_t *audio_buf;
172 static unsigned int allocated_audio_buf_size;
173 static uint8_t *async_buf;
174 static unsigned int allocated_async_buf_size;
175
176 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
177
178 typedef struct FrameBuffer {
179     uint8_t *base[4];
180     uint8_t *data[4];
181     int  linesize[4];
182
183     int h, w;
184     enum PixelFormat pix_fmt;
185
186     int refcount;
187     struct InputStream *ist;
188     struct FrameBuffer *next;
189 } FrameBuffer;
190
191 typedef struct InputStream {
192     int file_index;
193     AVStream *st;
194     int discard;             /* true if stream data should be discarded */
195     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
196     AVCodec *dec;
197     AVFrame *decoded_frame;
198     AVFrame *filtered_frame;
199
200     int64_t       start;     /* time when read started */
201     /* predicted dts of the next packet read for this stream or (when there are
202      * several frames in a packet) of the next frame in current packet */
203     int64_t       next_dts;
204     /* dts of the last packet read for this stream */
205     int64_t       dts;
206
207     int64_t       next_pts;  ///< synthetic pts for the next decode frame
208     int64_t       pts;       ///< current pts of the decoded frame
209     double ts_scale;
210     int is_start;            /* is 1 at the start and after a discontinuity */
211     int showed_multi_packet_warning;
212     AVDictionary *opts;
213
214     /* a pool of free buffers for decoded data */
215     FrameBuffer *buffer_pool;
216     int dr1;
217 } InputStream;
218
219 typedef struct InputFile {
220     AVFormatContext *ctx;
221     int eof_reached;      /* true if eof reached */
222     int ist_index;        /* index of first stream in input_streams */
223     int buffer_size;      /* current total buffer size */
224     int64_t ts_offset;
225     int nb_streams;       /* number of stream that ffmpeg is aware of; may be different
226                              from ctx.nb_streams if new streams appear during av_read_frame() */
227     int rate_emu;
228 } InputFile;
229
230 typedef struct OutputStream {
231     int file_index;          /* file index */
232     int index;               /* stream index in the output file */
233     int source_index;        /* InputStream index */
234     AVStream *st;            /* stream in the output file */
235     int encoding_needed;     /* true if encoding needed for this stream */
236     int frame_number;
237     /* input pts and corresponding output pts
238        for A/V sync */
239     struct InputStream *sync_ist; /* input stream to sync against */
240     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
241     AVBitStreamFilterContext *bitstream_filters;
242     AVCodec *enc;
243     int64_t max_frames;
244     AVFrame *output_frame;
245
246     /* video only */
247     int video_resample;
248     int resample_height;
249     int resample_width;
250     int resample_pix_fmt;
251     AVRational frame_rate;
252     int force_fps;
253     int top_field_first;
254
255     float frame_aspect_ratio;
256
257     /* forced key frames */
258     int64_t *forced_kf_pts;
259     int forced_kf_count;
260     int forced_kf_index;
261
262     /* audio only */
263     int audio_resample;
264     int audio_channels_map[SWR_CH_MAX];  ///< list of the channels id to pick from the source stream
265     int audio_channels_mapped;           ///< number of channels in audio_channels_map
266     int resample_sample_fmt;
267     int resample_channels;
268     int resample_sample_rate;
269     float rematrix_volume;
270     AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
271     FILE *logfile;
272
273     SwrContext *swr;
274
275     AVFilterContext *output_video_filter;
276     AVFilterContext *input_video_filter;
277     char *avfilter;
278     AVFilterGraph *graph;
279
280     int64_t sws_flags;
281     int64_t swr_dither_method;
282     double swr_dither_scale;
283     AVDictionary *opts;
284     int is_past_recording_time;
285     int stream_copy;
286     const char *attachment_filename;
287     int copy_initial_nonkeyframes;
288 } OutputStream;
289
290
291 #if HAVE_TERMIOS_H
292
293 /* init terminal so that we can grab keys */
294 static struct termios oldtty;
295 static int restore_tty;
296 #endif
297
298 typedef struct OutputFile {
299     AVFormatContext *ctx;
300     AVDictionary *opts;
301     int ost_index;       /* index of the first stream in output_streams */
302     int64_t recording_time; /* desired length of the resulting file in microseconds */
303     int64_t start_time;     /* start time in microseconds */
304     uint64_t limit_filesize; /* filesize limit expressed in bytes */
305 } OutputFile;
306
307 static InputStream *input_streams   = NULL;
308 static int         nb_input_streams = 0;
309 static InputFile   *input_files     = NULL;
310 static int         nb_input_files   = 0;
311
312 static OutputStream *output_streams = NULL;
313 static int        nb_output_streams = 0;
314 static OutputFile   *output_files   = NULL;
315 static int        nb_output_files   = 0;
316
317 typedef struct OptionsContext {
318     /* input/output options */
319     int64_t start_time;
320     const char *format;
321
322     SpecifierOpt *codec_names;
323     int        nb_codec_names;
324     SpecifierOpt *audio_channels;
325     int        nb_audio_channels;
326     SpecifierOpt *audio_sample_rate;
327     int        nb_audio_sample_rate;
328     SpecifierOpt *rematrix_volume;
329     int        nb_rematrix_volume;
330     SpecifierOpt *frame_rates;
331     int        nb_frame_rates;
332     SpecifierOpt *frame_sizes;
333     int        nb_frame_sizes;
334     SpecifierOpt *frame_pix_fmts;
335     int        nb_frame_pix_fmts;
336
337     /* input options */
338     int64_t input_ts_offset;
339     int rate_emu;
340
341     SpecifierOpt *ts_scale;
342     int        nb_ts_scale;
343     SpecifierOpt *dump_attachment;
344     int        nb_dump_attachment;
345
346     /* output options */
347     StreamMap *stream_maps;
348     int     nb_stream_maps;
349     AudioChannelMap *audio_channel_maps; ///< one info entry per -map_channel
350     int           nb_audio_channel_maps; ///< number of (valid) -map_channel settings
351     int metadata_global_manual;
352     int metadata_streams_manual;
353     int metadata_chapters_manual;
354     const char **attachments;
355     int       nb_attachments;
356
357     int chapters_input_file;
358
359     int64_t recording_time;
360     uint64_t limit_filesize;
361     float mux_preload;
362     float mux_max_delay;
363
364     int video_disable;
365     int audio_disable;
366     int subtitle_disable;
367     int data_disable;
368
369     /* indexed by output file stream index */
370     int   *streamid_map;
371     int nb_streamid_map;
372
373     SpecifierOpt *metadata;
374     int        nb_metadata;
375     SpecifierOpt *max_frames;
376     int        nb_max_frames;
377     SpecifierOpt *bitstream_filters;
378     int        nb_bitstream_filters;
379     SpecifierOpt *codec_tags;
380     int        nb_codec_tags;
381     SpecifierOpt *sample_fmts;
382     int        nb_sample_fmts;
383     SpecifierOpt *qscale;
384     int        nb_qscale;
385     SpecifierOpt *forced_key_frames;
386     int        nb_forced_key_frames;
387     SpecifierOpt *force_fps;
388     int        nb_force_fps;
389     SpecifierOpt *frame_aspect_ratios;
390     int        nb_frame_aspect_ratios;
391     SpecifierOpt *rc_overrides;
392     int        nb_rc_overrides;
393     SpecifierOpt *intra_matrices;
394     int        nb_intra_matrices;
395     SpecifierOpt *inter_matrices;
396     int        nb_inter_matrices;
397     SpecifierOpt *top_field_first;
398     int        nb_top_field_first;
399     SpecifierOpt *metadata_map;
400     int        nb_metadata_map;
401     SpecifierOpt *presets;
402     int        nb_presets;
403     SpecifierOpt *copy_initial_nonkeyframes;
404     int        nb_copy_initial_nonkeyframes;
405     SpecifierOpt *filters;
406     int        nb_filters;
407 } OptionsContext;
408
409 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
410 {\
411     int i, ret;\
412     for (i = 0; i < o->nb_ ## name; i++) {\
413         char *spec = o->name[i].specifier;\
414         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
415             outvar = o->name[i].u.type;\
416         else if (ret < 0)\
417             exit_program(1);\
418     }\
419 }
420
421 static int64_t getutime(void)
422 {
423 #if HAVE_GETRUSAGE
424     struct rusage rusage;
425
426     getrusage(RUSAGE_SELF, &rusage);
427     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
428 #elif HAVE_GETPROCESSTIMES
429     HANDLE proc;
430     FILETIME c, e, k, u;
431     proc = GetCurrentProcess();
432     GetProcessTimes(proc, &c, &e, &k, &u);
433     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
434 #else
435     return av_gettime();
436 #endif
437 }
438
439 static void update_benchmark(const char *fmt, ...)
440 {
441     if (do_benchmark_all) {
442         int64_t t = getutime();
443         va_list va;
444         char buf[1024];
445
446         if (fmt) {
447             va_start(va, fmt);
448             vsnprintf(buf, sizeof(buf), fmt, va);
449             va_end(va);
450             printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
451         }
452         current_time = t;
453     }
454 }
455
456 static void reset_options(OptionsContext *o, int is_input)
457 {
458     const OptionDef *po = options;
459     OptionsContext bak= *o;
460
461     /* all OPT_SPEC and OPT_STRING can be freed in generic way */
462     while (po->name) {
463         void *dst = (uint8_t*)o + po->u.off;
464
465         if (po->flags & OPT_SPEC) {
466             SpecifierOpt **so = dst;
467             int i, *count = (int*)(so + 1);
468             for (i = 0; i < *count; i++) {
469                 av_freep(&(*so)[i].specifier);
470                 if (po->flags & OPT_STRING)
471                     av_freep(&(*so)[i].u.str);
472             }
473             av_freep(so);
474             *count = 0;
475         } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
476             av_freep(dst);
477         po++;
478     }
479
480     av_freep(&o->stream_maps);
481     av_freep(&o->audio_channel_maps);
482     av_freep(&o->streamid_map);
483
484     memset(o, 0, sizeof(*o));
485
486     if(is_input) o->recording_time = bak.recording_time;
487     else         o->recording_time = INT64_MAX;
488     o->mux_max_delay  = 0.7;
489     o->limit_filesize = UINT64_MAX;
490     o->chapters_input_file = INT_MAX;
491
492     uninit_opts();
493     init_opts();
494 }
495
496 static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
497 {
498     FrameBuffer  *buf = av_mallocz(sizeof(*buf));
499     int i, ret;
500     const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
501     int h_chroma_shift, v_chroma_shift;
502     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
503     int w = s->width, h = s->height;
504
505     if (!buf)
506         return AVERROR(ENOMEM);
507
508     if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
509         w += 2*edge;
510         h += 2*edge;
511     }
512
513     avcodec_align_dimensions(s, &w, &h);
514     if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
515                               s->pix_fmt, 32)) < 0) {
516         av_freep(&buf);
517         return ret;
518     }
519     /* XXX this shouldn't be needed, but some tests break without this line
520      * those decoders are buggy and need to be fixed.
521      * the following tests fail:
522      * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
523      */
524     memset(buf->base[0], 128, ret);
525
526     avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
527     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
528         const int h_shift = i==0 ? 0 : h_chroma_shift;
529         const int v_shift = i==0 ? 0 : v_chroma_shift;
530         if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[1])
531             buf->data[i] = buf->base[i];
532         else
533             buf->data[i] = buf->base[i] +
534                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
535                                    (pixel_size*edge >> h_shift), 32);
536     }
537     buf->w       = s->width;
538     buf->h       = s->height;
539     buf->pix_fmt = s->pix_fmt;
540     buf->ist     = ist;
541
542     *pbuf = buf;
543     return 0;
544 }
545
546 static void free_buffer_pool(InputStream *ist)
547 {
548     FrameBuffer *buf = ist->buffer_pool;
549     while (buf) {
550         ist->buffer_pool = buf->next;
551         av_freep(&buf->base[0]);
552         av_free(buf);
553         buf = ist->buffer_pool;
554     }
555 }
556
557 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
558 {
559     av_assert0(buf->refcount);
560     buf->refcount--;
561     if (!buf->refcount) {
562         buf->next = ist->buffer_pool;
563         ist->buffer_pool = buf;
564     }
565 }
566
567 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
568 {
569     InputStream *ist = s->opaque;
570     FrameBuffer *buf;
571     int ret, i;
572
573     if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0)
574         return -1;
575
576     if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
577         return ret;
578
579     buf              = ist->buffer_pool;
580     ist->buffer_pool = buf->next;
581     buf->next        = NULL;
582     if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
583         av_freep(&buf->base[0]);
584         av_free(buf);
585         if ((ret = alloc_buffer(ist, s, &buf)) < 0)
586             return ret;
587     }
588     buf->refcount++;
589
590     frame->opaque        = buf;
591     frame->type          = FF_BUFFER_TYPE_USER;
592     frame->extended_data = frame->data;
593     frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
594     frame->width         = buf->w;
595     frame->height        = buf->h;
596     frame->format        = buf->pix_fmt;
597     frame->sample_aspect_ratio = s->sample_aspect_ratio;
598
599     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
600         frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
601         frame->data[i]     = buf->data[i];
602         frame->linesize[i] = buf->linesize[i];
603     }
604
605     return 0;
606 }
607
608 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
609 {
610     InputStream *ist = s->opaque;
611     FrameBuffer *buf = frame->opaque;
612     int i;
613
614     if(frame->type!=FF_BUFFER_TYPE_USER)
615         return avcodec_default_release_buffer(s, frame);
616
617     for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
618         frame->data[i] = NULL;
619
620     unref_buffer(ist, buf);
621 }
622
623 static void filter_release_buffer(AVFilterBuffer *fb)
624 {
625     FrameBuffer *buf = fb->priv;
626     av_free(fb);
627     unref_buffer(buf->ist, buf);
628 }
629
630 static int configure_video_filters(InputStream *ist, OutputStream *ost)
631 {
632     AVFilterContext *last_filter, *filter;
633     /** filter graph containing all filters including input & output */
634     AVCodecContext *codec = ost->st->codec;
635     AVCodecContext *icodec = ist->st->codec;
636     enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
637     AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
638     AVRational sample_aspect_ratio;
639     char args[255];
640     int ret;
641
642     ost->graph = avfilter_graph_alloc();
643     if (!ost->graph)
644         return AVERROR(ENOMEM);
645
646     if (ist->st->sample_aspect_ratio.num) {
647         sample_aspect_ratio = ist->st->sample_aspect_ratio;
648     } else
649         sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
650
651     snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
652              ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
653              sample_aspect_ratio.num, sample_aspect_ratio.den, SWS_BILINEAR + ((icodec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
654
655     ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
656                                        "src", args, NULL, ost->graph);
657     if (ret < 0)
658         return ret;
659
660 #if FF_API_OLD_VSINK_API
661     ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
662                                        "out", NULL, pix_fmts, ost->graph);
663 #else
664     buffersink_params->pixel_fmts = pix_fmts;
665     ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
666                                        "out", NULL, buffersink_params, ost->graph);
667 #endif
668     av_freep(&buffersink_params);
669
670     if (ret < 0)
671         return ret;
672     last_filter = ost->input_video_filter;
673
674     if (codec->width != icodec->width || codec->height != icodec->height) {
675         snprintf(args, 255, "%d:%d:flags=0x%X",
676                  codec->width,
677                  codec->height,
678                  (unsigned)ost->sws_flags);
679         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
680                                                 NULL, args, NULL, ost->graph)) < 0)
681             return ret;
682         if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
683             return ret;
684         last_filter = filter;
685     }
686
687     snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
688     ost->graph->scale_sws_opts = av_strdup(args);
689
690     if (ost->avfilter) {
691         AVFilterInOut *outputs = avfilter_inout_alloc();
692         AVFilterInOut *inputs  = avfilter_inout_alloc();
693
694         outputs->name    = av_strdup("in");
695         outputs->filter_ctx = last_filter;
696         outputs->pad_idx = 0;
697         outputs->next    = NULL;
698
699         inputs->name    = av_strdup("out");
700         inputs->filter_ctx = ost->output_video_filter;
701         inputs->pad_idx = 0;
702         inputs->next    = NULL;
703
704         if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
705             return ret;
706         av_freep(&ost->avfilter);
707     } else {
708         if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
709             return ret;
710     }
711
712     if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
713         return ret;
714
715     codec->width  = ost->output_video_filter->inputs[0]->w;
716     codec->height = ost->output_video_filter->inputs[0]->h;
717     codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
718         ost->frame_aspect_ratio ? // overridden by the -aspect cli option
719         av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
720         ost->output_video_filter->inputs[0]->sample_aspect_ratio;
721
722     return 0;
723 }
724
725 static void term_exit(void)
726 {
727     av_log(NULL, AV_LOG_QUIET, "%s", "");
728 #if HAVE_TERMIOS_H
729     if(restore_tty)
730         tcsetattr (0, TCSANOW, &oldtty);
731 #endif
732 }
733
734 static volatile int received_sigterm = 0;
735
736 static void sigterm_handler(int sig)
737 {
738     received_sigterm = sig;
739     received_nb_signals++;
740     term_exit();
741     if(received_nb_signals > 3)
742         exit(123);
743 }
744
745 static void term_init(void)
746 {
747 #if HAVE_TERMIOS_H
748     if(!run_as_daemon){
749     struct termios tty;
750
751     if (tcgetattr (0, &tty) == 0) {
752     oldtty = tty;
753     restore_tty = 1;
754     atexit(term_exit);
755
756     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
757                           |INLCR|IGNCR|ICRNL|IXON);
758     tty.c_oflag |= OPOST;
759     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
760     tty.c_cflag &= ~(CSIZE|PARENB);
761     tty.c_cflag |= CS8;
762     tty.c_cc[VMIN] = 1;
763     tty.c_cc[VTIME] = 0;
764
765     tcsetattr (0, TCSANOW, &tty);
766     }
767     signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
768     }
769 #endif
770     avformat_network_deinit();
771
772     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
773     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
774 #ifdef SIGXCPU
775     signal(SIGXCPU, sigterm_handler);
776 #endif
777 }
778
779 /* read a key without blocking */
780 static int read_key(void)
781 {
782     unsigned char ch;
783 #if HAVE_TERMIOS_H
784     int n = 1;
785     struct timeval tv;
786     fd_set rfds;
787
788     FD_ZERO(&rfds);
789     FD_SET(0, &rfds);
790     tv.tv_sec = 0;
791     tv.tv_usec = 0;
792     n = select(1, &rfds, NULL, NULL, &tv);
793     if (n > 0) {
794         n = read(0, &ch, 1);
795         if (n == 1)
796             return ch;
797
798         return n;
799     }
800 #elif HAVE_KBHIT
801 #    if HAVE_PEEKNAMEDPIPE
802     static int is_pipe;
803     static HANDLE input_handle;
804     DWORD dw, nchars;
805     if(!input_handle){
806         input_handle = GetStdHandle(STD_INPUT_HANDLE);
807         is_pipe = !GetConsoleMode(input_handle, &dw);
808     }
809
810     if (stdin->_cnt > 0) {
811         read(0, &ch, 1);
812         return ch;
813     }
814     if (is_pipe) {
815         /* When running under a GUI, you will end here. */
816         if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
817             return -1;
818         //Read it
819         if(nchars != 0) {
820             read(0, &ch, 1);
821             return ch;
822         }else{
823             return -1;
824         }
825     }
826 #    endif
827     if(kbhit())
828         return(getch());
829 #endif
830     return -1;
831 }
832
833 static int decode_interrupt_cb(void *ctx)
834 {
835     return received_nb_signals > 1;
836 }
837
838 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
839
840 void av_noreturn exit_program(int ret)
841 {
842     int i;
843
844     /* close files */
845     for (i = 0; i < nb_output_files; i++) {
846         AVFormatContext *s = output_files[i].ctx;
847         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
848             avio_close(s->pb);
849         avformat_free_context(s);
850         av_dict_free(&output_files[i].opts);
851     }
852     for (i = 0; i < nb_output_streams; i++) {
853         AVBitStreamFilterContext *bsfc = output_streams[i].bitstream_filters;
854         while (bsfc) {
855             AVBitStreamFilterContext *next = bsfc->next;
856             av_bitstream_filter_close(bsfc);
857             bsfc = next;
858         }
859         output_streams[i].bitstream_filters = NULL;
860
861         if (output_streams[i].output_frame) {
862             AVFrame *frame = output_streams[i].output_frame;
863             if (frame->extended_data != frame->data)
864                 av_freep(&frame->extended_data);
865             av_freep(&frame);
866         }
867     }
868     for (i = 0; i < nb_input_files; i++) {
869         avformat_close_input(&input_files[i].ctx);
870     }
871     for (i = 0; i < nb_input_streams; i++) {
872         av_freep(&input_streams[i].decoded_frame);
873         av_freep(&input_streams[i].filtered_frame);
874         av_dict_free(&input_streams[i].opts);
875         free_buffer_pool(&input_streams[i]);
876     }
877
878     if (vstats_file)
879         fclose(vstats_file);
880     av_free(vstats_filename);
881
882     av_freep(&input_streams);
883     av_freep(&input_files);
884     av_freep(&output_streams);
885     av_freep(&output_files);
886
887     uninit_opts();
888     av_freep(&audio_buf);
889     allocated_audio_buf_size = 0;
890     av_freep(&async_buf);
891     allocated_async_buf_size = 0;
892
893     avfilter_uninit();
894     avformat_network_deinit();
895
896     if (received_sigterm) {
897         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
898                (int) received_sigterm);
899         exit (255);
900     }
901
902     exit(ret); /* not all OS-es handle main() return value */
903 }
904
905 static void assert_avoptions(AVDictionary *m)
906 {
907     AVDictionaryEntry *t;
908     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
909         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
910         exit_program(1);
911     }
912 }
913
914 static void assert_codec_experimental(AVCodecContext *c, int encoder)
915 {
916     const char *codec_string = encoder ? "encoder" : "decoder";
917     AVCodec *codec;
918     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
919         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
920         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
921                 "results.\nAdd '-strict experimental' if you want to use it.\n",
922                 codec_string, c->codec->name);
923         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
924         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
925             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
926                    codec_string, codec->name);
927         exit_program(1);
928     }
929 }
930
931 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
932 {
933     if (codec && codec->sample_fmts) {
934         const enum AVSampleFormat *p = codec->sample_fmts;
935         for (; *p != -1; p++) {
936             if (*p == st->codec->sample_fmt)
937                 break;
938         }
939         if (*p == -1) {
940             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
941                 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
942             if(av_get_sample_fmt_name(st->codec->sample_fmt))
943             av_log(NULL, AV_LOG_WARNING,
944                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
945                    av_get_sample_fmt_name(st->codec->sample_fmt),
946                    codec->name,
947                    av_get_sample_fmt_name(codec->sample_fmts[0]));
948             st->codec->sample_fmt = codec->sample_fmts[0];
949         }
950     }
951 }
952
953 static void choose_sample_rate(AVStream *st, AVCodec *codec)
954 {
955     if (codec && codec->supported_samplerates) {
956         const int *p  = codec->supported_samplerates;
957         int best      = 0;
958         int best_dist = INT_MAX;
959         for (; *p; p++) {
960             int dist = abs(st->codec->sample_rate - *p);
961             if (dist < best_dist) {
962                 best_dist = dist;
963                 best      = *p;
964             }
965         }
966         if (best_dist) {
967             int i;
968             const int *sample_rates = codec->supported_samplerates;
969             av_log(st->codec, AV_LOG_WARNING,
970                    "Requested sampling rate (%dHz) unsupported, using %dHz instead\n"
971                    "Available sampling rates for %s:",
972                    st->codec->sample_rate, best, codec->name);
973             for (i = 0; sample_rates[i]; i++) {
974                 if (!sample_rates[i + 1]) av_log(st->codec, AV_LOG_WARNING, " and");
975                 else if (i)               av_log(st->codec, AV_LOG_WARNING, ",");
976                 av_log(st->codec, AV_LOG_WARNING, " %d", sample_rates[i]);
977             }
978             av_log(st->codec, AV_LOG_WARNING, ".\n");
979         }
980         st->codec->sample_rate = best;
981     }
982 }
983
984 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
985 {
986     if (codec && codec->pix_fmts) {
987         const enum PixelFormat *p = codec->pix_fmts;
988         int has_alpha= av_pix_fmt_descriptors[st->codec->pix_fmt].nb_components % 2 == 0;
989         enum PixelFormat best= PIX_FMT_NONE;
990         if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
991             if (st->codec->codec_id == CODEC_ID_MJPEG) {
992                 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
993             } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
994                 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
995                                                  PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
996             }
997         }
998         for (; *p != PIX_FMT_NONE; p++) {
999             best= avcodec_find_best_pix_fmt2(best, *p, st->codec->pix_fmt, has_alpha, NULL);
1000             if (*p == st->codec->pix_fmt)
1001                 break;
1002         }
1003         if (*p == PIX_FMT_NONE) {
1004             if (st->codec->pix_fmt != PIX_FMT_NONE)
1005                 av_log(NULL, AV_LOG_WARNING,
1006                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
1007                        av_pix_fmt_descriptors[st->codec->pix_fmt].name,
1008                        codec->name,
1009                        av_pix_fmt_descriptors[best].name);
1010             st->codec->pix_fmt = best;
1011         }
1012     }
1013 }
1014
1015 static double
1016 get_sync_ipts(const OutputStream *ost, int64_t pts)
1017 {
1018     OutputFile *of = &output_files[ost->file_index];
1019     return (double)(pts - of->start_time) / AV_TIME_BASE;
1020 }
1021
1022 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1023 {
1024     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1025     AVCodecContext          *avctx = ost->st->codec;
1026     int ret;
1027
1028     if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
1029         (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
1030         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1031
1032     /*
1033      * Audio encoders may split the packets --  #frames in != #packets out.
1034      * But there is no reordering, so we can limit the number of output packets
1035      * by simply dropping them here.
1036      * Counting encoded video frames needs to be done separately because of
1037      * reordering, see do_video_out()
1038      */
1039     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1040         if (ost->frame_number >= ost->max_frames) {
1041             av_free_packet(pkt);
1042             return;
1043         }
1044         ost->frame_number++;
1045     }
1046
1047     while (bsfc) {
1048         AVPacket new_pkt = *pkt;
1049         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1050                                            &new_pkt.data, &new_pkt.size,
1051                                            pkt->data, pkt->size,
1052                                            pkt->flags & AV_PKT_FLAG_KEY);
1053         if (a > 0) {
1054             av_free_packet(pkt);
1055             new_pkt.destruct = av_destruct_packet;
1056         } else if (a < 0) {
1057             av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
1058                    bsfc->filter->name, pkt->stream_index,
1059                    avctx->codec ? avctx->codec->name : "copy");
1060             print_error("", a);
1061             if (exit_on_error)
1062                 exit_program(1);
1063         }
1064         *pkt = new_pkt;
1065
1066         bsfc = bsfc->next;
1067     }
1068
1069     pkt->stream_index = ost->index;
1070     ret = av_interleaved_write_frame(s, pkt);
1071     if (ret < 0) {
1072         print_error("av_interleaved_write_frame()", ret);
1073         exit_program(1);
1074     }
1075 }
1076
1077 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1078 {
1079     int fill_char = 0x00;
1080     if (sample_fmt == AV_SAMPLE_FMT_U8)
1081         fill_char = 0x80;
1082     memset(buf, fill_char, size);
1083 }
1084
1085 static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
1086                               const uint8_t *buf, int buf_size)
1087 {
1088     AVCodecContext *enc = ost->st->codec;
1089     AVFrame *frame = NULL;
1090     AVPacket pkt;
1091     int ret, got_packet;
1092
1093     av_init_packet(&pkt);
1094     pkt.data = NULL;
1095     pkt.size = 0;
1096
1097     if (buf && buf_size) {
1098         if (!ost->output_frame) {
1099             ost->output_frame = avcodec_alloc_frame();
1100             if (!ost->output_frame) {
1101                 av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
1102                 exit_program(1);
1103             }
1104         }
1105         frame = ost->output_frame;
1106         if (frame->extended_data != frame->data)
1107             av_freep(&frame->extended_data);
1108         avcodec_get_frame_defaults(frame);
1109
1110         frame->nb_samples  = buf_size /
1111                              (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
1112         if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
1113                                             buf, buf_size, 1)) < 0) {
1114             av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_fill_audio_frame)\n");
1115             exit_program(1);
1116         }
1117
1118         frame->pts = ost->sync_opts;
1119         ost->sync_opts += frame->nb_samples;
1120     }
1121
1122     got_packet = 0;
1123     update_benchmark(NULL);
1124     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1125         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
1126         exit_program(1);
1127     }
1128     update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1129
1130     ret = pkt.size;
1131
1132     if (got_packet) {
1133         if (pkt.pts != AV_NOPTS_VALUE)
1134             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
1135         if (pkt.dts != AV_NOPTS_VALUE) {
1136             int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
1137             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
1138             if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE &&  max > pkt.dts) {
1139                 av_log(s, max - pkt.dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt.dts, max);
1140                 pkt.pts = pkt.dts = max;
1141             }
1142         }
1143         if (pkt.duration > 0)
1144             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1145
1146         write_frame(s, &pkt, ost);
1147
1148         audio_size += pkt.size;
1149
1150         av_free_packet(&pkt);
1151     }
1152
1153     if (debug_ts) {
1154         av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1155                "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1156                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1157                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1158     }
1159
1160     return ret;
1161 }
1162
1163 static int alloc_audio_output_buf(AVCodecContext *dec, AVCodecContext *enc,
1164                                   int nb_samples)
1165 {
1166     int64_t audio_buf_samples;
1167     int audio_buf_size;
1168
1169     /* calculate required number of samples to allocate */
1170     audio_buf_samples = ((int64_t)nb_samples * enc->sample_rate + dec->sample_rate) /
1171                         dec->sample_rate;
1172     audio_buf_samples = 4 * audio_buf_samples + 10000; // safety factors for resampling
1173     audio_buf_samples = FFMAX(audio_buf_samples, enc->frame_size);
1174     if (audio_buf_samples > INT_MAX)
1175         return AVERROR(EINVAL);
1176
1177     audio_buf_size = av_samples_get_buffer_size(NULL, enc->channels,
1178                                                 audio_buf_samples,
1179                                                 enc->sample_fmt, 0);
1180     if (audio_buf_size < 0)
1181         return audio_buf_size;
1182
1183     av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
1184     if (!audio_buf)
1185         return AVERROR(ENOMEM);
1186
1187     return 0;
1188 }
1189
1190 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1191                          InputStream *ist, AVFrame *decoded_frame)
1192 {
1193     uint8_t *buftmp;
1194     int64_t size_out;
1195
1196     int frame_bytes, resample_changed;
1197     AVCodecContext *enc = ost->st->codec;
1198     AVCodecContext *dec = ist->st->codec;
1199     int osize = av_get_bytes_per_sample(enc->sample_fmt);
1200     int isize = av_get_bytes_per_sample(dec->sample_fmt);
1201     uint8_t *buf[AV_NUM_DATA_POINTERS];
1202     int size     = decoded_frame->nb_samples * dec->channels * isize;
1203     int planes   = av_sample_fmt_is_planar(dec->sample_fmt) ? dec->channels : 1;
1204     int i;
1205
1206     av_assert0(planes <= AV_NUM_DATA_POINTERS);
1207
1208     for(i=0; i<planes; i++)
1209         buf[i]= decoded_frame->data[i];
1210
1211     if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples) < 0) {
1212         av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1213         exit_program(1);
1214     }
1215
1216     if (enc->channels != dec->channels
1217      || enc->sample_fmt != dec->sample_fmt
1218      || enc->sample_rate!= dec->sample_rate
1219     )
1220         ost->audio_resample = 1;
1221
1222     resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
1223                        ost->resample_channels    != dec->channels   ||
1224                        ost->resample_sample_rate != dec->sample_rate;
1225
1226     if ((ost->audio_resample && !ost->swr) || resample_changed || ost->audio_channels_mapped) {
1227         if (resample_changed) {
1228             av_log(NULL, AV_LOG_INFO, "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
1229                    ist->file_index, ist->st->index,
1230                    ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
1231                    dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
1232             ost->resample_sample_fmt  = dec->sample_fmt;
1233             ost->resample_channels    = dec->channels;
1234             ost->resample_sample_rate = dec->sample_rate;
1235             swr_free(&ost->swr);
1236         }
1237         /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1238         if (audio_sync_method <= 1 && !ost->audio_channels_mapped &&
1239             ost->resample_sample_fmt  == enc->sample_fmt &&
1240             ost->resample_channels    == enc->channels   &&
1241             ost->resample_sample_rate == enc->sample_rate) {
1242             //ost->swr = NULL;
1243             ost->audio_resample = 0;
1244         } else {
1245             ost->swr = swr_alloc_set_opts(ost->swr,
1246                                           enc->channel_layout, enc->sample_fmt, enc->sample_rate,
1247                                           dec->channel_layout, dec->sample_fmt, dec->sample_rate,
1248                                           0, NULL);
1249             av_opt_set_int(ost->swr, "dither_method", ost->swr_dither_method,0);
1250             av_opt_set_int(ost->swr, "dither_scale", ost->swr_dither_scale,0);
1251             if (ost->audio_channels_mapped)
1252                 swr_set_channel_mapping(ost->swr, ost->audio_channels_map);
1253             av_opt_set_double(ost->swr, "rmvol", ost->rematrix_volume, 0);
1254             if (ost->audio_channels_mapped) {
1255                 av_opt_set_int(ost->swr, "icl", av_get_default_channel_layout(ost->audio_channels_mapped), 0);
1256                 av_opt_set_int(ost->swr, "uch", ost->audio_channels_mapped, 0);
1257             }
1258             if (av_opt_set_int(ost->swr, "ich", dec->channels, 0) < 0) {
1259                 av_log(NULL, AV_LOG_FATAL, "Unsupported number of input channels\n");
1260                 exit_program(1);
1261             }
1262             if (av_opt_set_int(ost->swr, "och", enc->channels, 0) < 0) {
1263                 av_log(NULL, AV_LOG_FATAL, "Unsupported number of output channels\n");
1264                 exit_program(1);
1265             }
1266             if(audio_sync_method>1) av_opt_set_int(ost->swr, "flags", SWR_FLAG_RESAMPLE, 0);
1267             if(ost->swr && swr_init(ost->swr) < 0){
1268                 av_log(NULL, AV_LOG_FATAL, "swr_init() failed\n");
1269                 swr_free(&ost->swr);
1270             }
1271
1272             if (!ost->swr) {
1273                 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1274                         dec->channels, dec->sample_rate,
1275                         enc->channels, enc->sample_rate);
1276                 exit_program(1);
1277             }
1278         }
1279     }
1280
1281     av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1282
1283     if (audio_sync_method > 0) {
1284         double delta = get_sync_ipts(ost, ist->pts) * enc->sample_rate - ost->sync_opts -
1285                        av_fifo_size(ost->fifo) / (enc->channels * osize);
1286         int idelta = delta * dec->sample_rate / enc->sample_rate;
1287         int byte_delta = idelta * isize * dec->channels;
1288
1289         // FIXME resample delay
1290         if (fabs(delta) > 50) {
1291             if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1292                 if (byte_delta < 0) {
1293                     byte_delta = FFMAX(byte_delta, -size);
1294                     size += byte_delta;
1295                     for (i=0; i<planes; i++)
1296                         buf[i]  -= byte_delta/planes;
1297                     av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1298                            -byte_delta / (isize * dec->channels));
1299                     if (!size)
1300                         return;
1301                     ist->is_start = 0;
1302                 } else {
1303                     av_fast_malloc(&async_buf, &allocated_async_buf_size,
1304                                    byte_delta + size);
1305                     if (!async_buf) {
1306                         av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
1307                         exit_program(1);
1308                     }
1309
1310                     if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples + idelta) < 0) {
1311                         av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1312                         exit_program(1);
1313                     }
1314                     ist->is_start = 0;
1315
1316                     for (i=0; i<planes; i++) {
1317                         uint8_t *t = async_buf + i*((byte_delta + size)/planes);
1318                         generate_silence(t, dec->sample_fmt, byte_delta/planes);
1319                         memcpy(t + byte_delta/planes, buf[i], size/planes);
1320                         buf[i] = t;
1321                     }
1322                     size += byte_delta;
1323                     av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1324                 }
1325             } else if (audio_sync_method > 1) {
1326                 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1327                 av_assert0(ost->audio_resample);
1328                 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1329                        delta, comp, enc->sample_rate);
1330 //                fprintf(stderr, "drift:%f len:%d opts:%"PRId64" ipts:%"PRId64" fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), av_fifo_size(ost->fifo)/(ost->st->codec->channels * 2));
1331                 swr_set_compensation(ost->swr, comp, enc->sample_rate);
1332             }
1333         }
1334     } else if (audio_sync_method == 0)
1335         ost->sync_opts = lrintf(get_sync_ipts(ost, ist->pts) * enc->sample_rate) -
1336                                 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1337
1338     if (ost->audio_resample || ost->audio_channels_mapped) {
1339         buftmp = audio_buf;
1340         size_out = swr_convert(ost->swr, (      uint8_t*[]){buftmp}, allocated_audio_buf_size / (enc->channels * osize),
1341                                          buf, size / (dec->channels * isize));
1342         if (size_out < 0) {
1343             av_log(NULL, AV_LOG_FATAL, "swr_convert failed\n");
1344             exit_program(1);
1345         }
1346         size_out = size_out * enc->channels * osize;
1347     } else {
1348         buftmp = buf[0];
1349         size_out = size;
1350     }
1351
1352     av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1353
1354     /* now encode as many frames as possible */
1355     if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1356         /* output resampled raw samples */
1357         if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1358             av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1359             exit_program(1);
1360         }
1361         av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1362
1363         frame_bytes = enc->frame_size * osize * enc->channels;
1364
1365         while (av_fifo_size(ost->fifo) >= frame_bytes) {
1366             av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1367             encode_audio_frame(s, ost, audio_buf, frame_bytes);
1368         }
1369     } else {
1370         encode_audio_frame(s, ost, buftmp, size_out);
1371     }
1372 }
1373
1374 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1375 {
1376     AVCodecContext *dec;
1377     AVPicture *picture2;
1378     AVPicture picture_tmp;
1379     uint8_t *buf = 0;
1380
1381     dec = ist->st->codec;
1382
1383     /* deinterlace : must be done before any resize */
1384     if (do_deinterlace) {
1385         int size;
1386
1387         /* create temporary picture */
1388         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1389         buf  = av_malloc(size);
1390         if (!buf)
1391             return;
1392
1393         picture2 = &picture_tmp;
1394         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1395
1396         if (avpicture_deinterlace(picture2, picture,
1397                                  dec->pix_fmt, dec->width, dec->height) < 0) {
1398             /* if error, do not deinterlace */
1399             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1400             av_free(buf);
1401             buf = NULL;
1402             picture2 = picture;
1403         }
1404     } else {
1405         picture2 = picture;
1406     }
1407
1408     if (picture != picture2)
1409         *picture = *picture2;
1410     *bufp = buf;
1411 }
1412
1413 static void do_subtitle_out(AVFormatContext *s,
1414                             OutputStream *ost,
1415                             InputStream *ist,
1416                             AVSubtitle *sub,
1417                             int64_t pts)
1418 {
1419     static uint8_t *subtitle_out = NULL;
1420     int subtitle_out_max_size = 1024 * 1024;
1421     int subtitle_out_size, nb, i;
1422     AVCodecContext *enc;
1423     AVPacket pkt;
1424
1425     if (pts == AV_NOPTS_VALUE) {
1426         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1427         if (exit_on_error)
1428             exit_program(1);
1429         return;
1430     }
1431
1432     enc = ost->st->codec;
1433
1434     if (!subtitle_out) {
1435         subtitle_out = av_malloc(subtitle_out_max_size);
1436     }
1437
1438     /* Note: DVB subtitle need one packet to draw them and one other
1439        packet to clear them */
1440     /* XXX: signal it in the codec context ? */
1441     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1442         nb = 2;
1443     else
1444         nb = 1;
1445
1446     for (i = 0; i < nb; i++) {
1447         ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1448
1449         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1450         // start_display_time is required to be 0
1451         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1452         sub->end_display_time  -= sub->start_display_time;
1453         sub->start_display_time = 0;
1454         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1455                                                     subtitle_out_max_size, sub);
1456         if (subtitle_out_size < 0) {
1457             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1458             exit_program(1);
1459         }
1460
1461         av_init_packet(&pkt);
1462         pkt.data = subtitle_out;
1463         pkt.size = subtitle_out_size;
1464         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1465         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1466             /* XXX: the pts correction is handled here. Maybe handling
1467                it in the codec would be better */
1468             if (i == 0)
1469                 pkt.pts += 90 * sub->start_display_time;
1470             else
1471                 pkt.pts += 90 * sub->end_display_time;
1472         }
1473         write_frame(s, &pkt, ost);
1474     }
1475 }
1476
1477 static double psnr(double d)
1478 {
1479     return -10.0 * log(d) / log(10.0);
1480 }
1481
1482 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1483                            int frame_size)
1484 {
1485     AVCodecContext *enc;
1486     int frame_number;
1487     double ti1, bitrate, avg_bitrate;
1488
1489     /* this is executed just the first time do_video_stats is called */
1490     if (!vstats_file) {
1491         vstats_file = fopen(vstats_filename, "w");
1492         if (!vstats_file) {
1493             perror("fopen");
1494             exit_program(1);
1495         }
1496     }
1497
1498     enc = ost->st->codec;
1499     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1500         frame_number = ost->frame_number;
1501         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1502         if (enc->flags&CODEC_FLAG_PSNR)
1503             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1504
1505         fprintf(vstats_file,"f_size= %6d ", frame_size);
1506         /* compute pts value */
1507         ti1 = ost->sync_opts * av_q2d(enc->time_base);
1508         if (ti1 < 0.01)
1509             ti1 = 0.01;
1510
1511         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1512         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1513         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1514                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1515         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1516     }
1517 }
1518
1519
1520 static void do_video_out(AVFormatContext *s, OutputStream *ost,
1521                          InputStream *ist, AVFrame *in_picture)
1522 {
1523     int nb_frames, i, ret, format_video_sync;
1524     AVCodecContext *enc;
1525     double sync_ipts, delta;
1526     double duration = 0;
1527     int frame_size = 0;
1528     float quality = same_quant ? in_picture->quality
1529                                : ost->st->codec->global_quality;
1530
1531     enc = ost->st->codec;
1532
1533     if (ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE) {
1534         duration = FFMAX(av_q2d(ist->st->time_base), av_q2d(ist->st->codec->time_base));
1535         if(ist->st->r_frame_rate.num)
1536             duration= FFMAX(duration, 1/av_q2d(ist->st->r_frame_rate));
1537         if(ist->st->avg_frame_rate.num && 0)
1538             duration= FFMAX(duration, 1/av_q2d(ist->st->avg_frame_rate));
1539
1540         duration /= av_q2d(enc->time_base);
1541     }
1542
1543     sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
1544     delta = sync_ipts - ost->sync_opts + duration;
1545
1546     /* by default, we output a single frame */
1547     nb_frames = 1;
1548
1549     format_video_sync = video_sync_method;
1550     if (format_video_sync == VSYNC_AUTO)
1551         format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
1552
1553     switch (format_video_sync) {
1554     case VSYNC_CFR:
1555         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1556         if (delta < -1.1)
1557             nb_frames = 0;
1558         else if (delta > 1.1)
1559             nb_frames = lrintf(delta);
1560         break;
1561     case VSYNC_VFR:
1562         if (delta <= -0.6)
1563             nb_frames = 0;
1564         else if (delta > 0.6)
1565             ost->sync_opts = lrintf(sync_ipts);
1566         break;
1567     case VSYNC_DROP:
1568     case VSYNC_PASSTHROUGH:
1569         ost->sync_opts = lrintf(sync_ipts);
1570         break;
1571     default:
1572         av_assert0(0);
1573     }
1574
1575     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1576     if (nb_frames == 0) {
1577         nb_frames_drop++;
1578         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1579         return;
1580     } else if (nb_frames > 1) {
1581         nb_frames_dup += nb_frames - 1;
1582         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1583     }
1584
1585     /* duplicates frame if needed */
1586     for (i = 0; i < nb_frames; i++) {
1587         AVPacket pkt;
1588         av_init_packet(&pkt);
1589         pkt.data = NULL;
1590         pkt.size = 0;
1591
1592         if (s->oformat->flags & AVFMT_RAWPICTURE &&
1593             enc->codec->id == CODEC_ID_RAWVIDEO) {
1594             /* raw pictures are written as AVPicture structure to
1595                avoid any copies. We support temporarily the older
1596                method. */
1597             enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1598             enc->coded_frame->top_field_first  = in_picture->top_field_first;
1599             pkt.data   = (uint8_t *)in_picture;
1600             pkt.size   =  sizeof(AVPicture);
1601             pkt.pts    = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1602             pkt.flags |= AV_PKT_FLAG_KEY;
1603
1604             write_frame(s, &pkt, ost);
1605         } else {
1606             int got_packet;
1607             AVFrame big_picture;
1608
1609             big_picture = *in_picture;
1610             /* better than nothing: use input picture interlaced
1611                settings */
1612             big_picture.interlaced_frame = in_picture->interlaced_frame;
1613             if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1614                 if (ost->top_field_first == -1)
1615                     big_picture.top_field_first = in_picture->top_field_first;
1616                 else
1617                     big_picture.top_field_first = !!ost->top_field_first;
1618             }
1619
1620             /* handles same_quant here. This is not correct because it may
1621                not be a global option */
1622             big_picture.quality = quality;
1623             if (!enc->me_threshold)
1624                 big_picture.pict_type = 0;
1625             big_picture.pts = ost->sync_opts;
1626             if (ost->forced_kf_index < ost->forced_kf_count &&
1627                 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1628                 big_picture.pict_type = AV_PICTURE_TYPE_I;
1629                 ost->forced_kf_index++;
1630             }
1631             update_benchmark(NULL);
1632             ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
1633             update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1634             if (ret < 0) {
1635                 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1636                 exit_program(1);
1637             }
1638
1639             if (got_packet) {
1640                 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
1641                     pkt.pts = ost->sync_opts;
1642
1643                 if (pkt.pts != AV_NOPTS_VALUE)
1644                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1645                 if (pkt.dts != AV_NOPTS_VALUE)
1646                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1647
1648                 if (debug_ts) {
1649                     av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1650                            "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1651                            av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1652                            av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1653                 }
1654
1655                 write_frame(s, &pkt, ost);
1656                 frame_size = pkt.size;
1657                 video_size += pkt.size;
1658                 av_free_packet(&pkt);
1659
1660                 /* if two pass, output log */
1661                 if (ost->logfile && enc->stats_out) {
1662                     fprintf(ost->logfile, "%s", enc->stats_out);
1663                 }
1664             }
1665         }
1666         ost->sync_opts++;
1667         /*
1668          * For video, number of frames in == number of packets out.
1669          * But there may be reordering, so we can't throw away frames on encoder
1670          * flush, we need to limit them here, before they go into encoder.
1671          */
1672         ost->frame_number++;
1673     }
1674     if (vstats_filename && frame_size)
1675         do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
1676 }
1677
1678 static void print_report(OutputFile *output_files,
1679                          OutputStream *ost_table, int nb_ostreams,
1680                          int is_last_report, int64_t timer_start, int64_t cur_time)
1681 {
1682     char buf[1024];
1683     OutputStream *ost;
1684     AVFormatContext *oc;
1685     int64_t total_size;
1686     AVCodecContext *enc;
1687     int frame_number, vid, i;
1688     double bitrate;
1689     int64_t pts = INT64_MAX;
1690     static int64_t last_time = -1;
1691     static int qp_histogram[52];
1692     int hours, mins, secs, us;
1693
1694     if (!print_stats && !is_last_report)
1695         return;
1696
1697     if (!is_last_report) {
1698         if (last_time == -1) {
1699             last_time = cur_time;
1700             return;
1701         }
1702         if ((cur_time - last_time) < 500000)
1703             return;
1704         last_time = cur_time;
1705     }
1706
1707
1708     oc = output_files[0].ctx;
1709
1710     total_size = avio_size(oc->pb);
1711     if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
1712         total_size = avio_tell(oc->pb);
1713         if (total_size < 0)
1714             total_size = 0;
1715     }
1716
1717     buf[0] = '\0';
1718     vid = 0;
1719     for (i = 0; i < nb_ostreams; i++) {
1720         float q = -1;
1721         ost = &ost_table[i];
1722         enc = ost->st->codec;
1723         if (!ost->stream_copy && enc->coded_frame)
1724             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1725         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1726             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1727         }
1728         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1729             float fps, t = (cur_time-timer_start) / 1000000.0;
1730
1731             frame_number = ost->frame_number;
1732             fps = t > 1 ? frame_number / t : 0;
1733             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1734                      frame_number, fps < 9.95, fps, q);
1735             if (is_last_report)
1736                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1737             if (qp_hist) {
1738                 int j;
1739                 int qp = lrintf(q);
1740                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1741                     qp_histogram[qp]++;
1742                 for (j = 0; j < 32; j++)
1743                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
1744             }
1745             if (enc->flags&CODEC_FLAG_PSNR) {
1746                 int j;
1747                 double error, error_sum = 0;
1748                 double scale, scale_sum = 0;
1749                 char type[3] = { 'Y','U','V' };
1750                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1751                 for (j = 0; j < 3; j++) {
1752                     if (is_last_report) {
1753                         error = enc->error[j];
1754                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1755                     } else {
1756                         error = enc->coded_frame->error[j];
1757                         scale = enc->width * enc->height * 255.0 * 255.0;
1758                     }
1759                     if (j)
1760                         scale /= 4;
1761                     error_sum += error;
1762                     scale_sum += scale;
1763                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
1764                 }
1765                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1766             }
1767             vid = 1;
1768         }
1769         /* compute min output value */
1770         pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1771                                       ost->st->time_base, AV_TIME_BASE_Q));
1772     }
1773
1774     secs = pts / AV_TIME_BASE;
1775     us = pts % AV_TIME_BASE;
1776     mins = secs / 60;
1777     secs %= 60;
1778     hours = mins / 60;
1779     mins %= 60;
1780
1781     bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1782
1783     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1784              "size=%8.0fkB time=", total_size / 1024.0);
1785     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1786              "%02d:%02d:%02d.%02d ", hours, mins, secs,
1787              (100 * us) / AV_TIME_BASE);
1788     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1789              "bitrate=%6.1fkbits/s", bitrate);
1790
1791     if (nb_frames_dup || nb_frames_drop)
1792         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1793                 nb_frames_dup, nb_frames_drop);
1794
1795     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
1796
1797     fflush(stderr);
1798
1799     if (is_last_report) {
1800         int64_t raw= audio_size + video_size + extra_size;
1801         av_log(NULL, AV_LOG_INFO, "\n");
1802         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1803                video_size / 1024.0,
1804                audio_size / 1024.0,
1805                extra_size / 1024.0,
1806                100.0 * (total_size - raw) / raw
1807         );
1808         if(video_size + audio_size + extra_size == 0){
1809             av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
1810         }
1811     }
1812 }
1813
1814 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1815 {
1816     int i, ret;
1817
1818     for (i = 0; i < nb_ostreams; i++) {
1819         OutputStream   *ost = &ost_table[i];
1820         AVCodecContext *enc = ost->st->codec;
1821         AVFormatContext *os = output_files[ost->file_index].ctx;
1822         int stop_encoding = 0;
1823
1824         if (!ost->encoding_needed)
1825             continue;
1826
1827         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1828             continue;
1829         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1830             continue;
1831
1832         for (;;) {
1833             AVPacket pkt;
1834             int fifo_bytes, got_packet;
1835             av_init_packet(&pkt);
1836             pkt.data = NULL;
1837             pkt.size = 0;
1838
1839             switch (ost->st->codec->codec_type) {
1840             case AVMEDIA_TYPE_AUDIO:
1841                 fifo_bytes = av_fifo_size(ost->fifo);
1842                 if (fifo_bytes > 0) {
1843                     /* encode any samples remaining in fifo */
1844                     int frame_bytes = fifo_bytes;
1845
1846                     av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1847
1848                     /* pad last frame with silence if needed */
1849                     if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
1850                         frame_bytes = enc->frame_size * enc->channels *
1851                                       av_get_bytes_per_sample(enc->sample_fmt);
1852                         if (allocated_audio_buf_size < frame_bytes)
1853                             exit_program(1);
1854                         generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1855                     }
1856                     encode_audio_frame(os, ost, audio_buf, frame_bytes);
1857                 } else {
1858                     /* flush encoder with NULL frames until it is done
1859                        returning packets */
1860                     if (encode_audio_frame(os, ost, NULL, 0) == 0) {
1861                         stop_encoding = 1;
1862                         break;
1863                     }
1864                 }
1865                 break;
1866             case AVMEDIA_TYPE_VIDEO:
1867                 update_benchmark(NULL);
1868                 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
1869                 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1870                 if (ret < 0) {
1871                     av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1872                     exit_program(1);
1873                 }
1874                 video_size += pkt.size;
1875                 if (ost->logfile && enc->stats_out) {
1876                     fprintf(ost->logfile, "%s", enc->stats_out);
1877                 }
1878                 if (!got_packet) {
1879                     stop_encoding = 1;
1880                     break;
1881                 }
1882                 if (pkt.pts != AV_NOPTS_VALUE)
1883                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1884                 if (pkt.dts != AV_NOPTS_VALUE)
1885                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1886                 write_frame(os, &pkt, ost);
1887                 break;
1888             default:
1889                 stop_encoding = 1;
1890             }
1891             if (stop_encoding)
1892                 break;
1893         }
1894     }
1895 }
1896
1897 /*
1898  * Check whether a packet from ist should be written into ost at this time
1899  */
1900 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1901 {
1902     OutputFile *of = &output_files[ost->file_index];
1903     int ist_index  = ist - input_streams;
1904
1905     if (ost->source_index != ist_index)
1906         return 0;
1907
1908     if (of->start_time && ist->pts < of->start_time)
1909         return 0;
1910
1911     if (of->recording_time != INT64_MAX &&
1912         av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1913                       (AVRational){ 1, 1000000 }) >= 0) {
1914         ost->is_past_recording_time = 1;
1915         return 0;
1916     }
1917
1918     return 1;
1919 }
1920
1921 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1922 {
1923     OutputFile *of = &output_files[ost->file_index];
1924     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1925     AVPicture pict;
1926     AVPacket opkt;
1927
1928     av_init_packet(&opkt);
1929
1930     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1931         !ost->copy_initial_nonkeyframes)
1932         return;
1933
1934     /* force the input stream PTS */
1935     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1936         audio_size += pkt->size;
1937     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1938         video_size += pkt->size;
1939         ost->sync_opts++;
1940     }
1941
1942     if (pkt->pts != AV_NOPTS_VALUE)
1943         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1944     else
1945         opkt.pts = AV_NOPTS_VALUE;
1946
1947     if (pkt->dts == AV_NOPTS_VALUE)
1948         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1949     else
1950         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1951     opkt.dts -= ost_tb_start_time;
1952
1953     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1954     opkt.flags    = pkt->flags;
1955
1956     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1957     if (  ost->st->codec->codec_id != CODEC_ID_H264
1958        && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1959        && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1960        && ost->st->codec->codec_id != CODEC_ID_VC1
1961        ) {
1962         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1963             opkt.destruct = av_destruct_packet;
1964     } else {
1965         opkt.data = pkt->data;
1966         opkt.size = pkt->size;
1967     }
1968     if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1969         /* store AVPicture in AVPacket, as expected by the output format */
1970         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1971         opkt.data = (uint8_t *)&pict;
1972         opkt.size = sizeof(AVPicture);
1973         opkt.flags |= AV_PKT_FLAG_KEY;
1974     }
1975
1976     write_frame(of->ctx, &opkt, ost);
1977     ost->st->codec->frame_number++;
1978     av_free_packet(&opkt);
1979 }
1980
1981 static void rate_emu_sleep(InputStream *ist)
1982 {
1983     if (input_files[ist->file_index].rate_emu) {
1984         int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
1985         int64_t now = av_gettime() - ist->start;
1986         if (pts > now)
1987             usleep(pts - now);
1988     }
1989 }
1990
1991 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1992 {
1993     AVFrame *decoded_frame;
1994     AVCodecContext *avctx = ist->st->codec;
1995     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1996     int i, ret;
1997
1998     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1999         return AVERROR(ENOMEM);
2000     else
2001         avcodec_get_frame_defaults(ist->decoded_frame);
2002     decoded_frame = ist->decoded_frame;
2003
2004     update_benchmark(NULL);
2005     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2006     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2007     if (ret < 0) {
2008         return ret;
2009     }
2010     if (avctx->sample_rate <= 0) {
2011         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2012         return AVERROR_INVALIDDATA;
2013     }
2014
2015     if (!*got_output) {
2016         /* no audio frame */
2017         return ret;
2018     }
2019
2020     /* if the decoder provides a pts, use it instead of the last packet pts.
2021        the decoder could be delaying output by a packet or more. */
2022     if (decoded_frame->pts != AV_NOPTS_VALUE)
2023         ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2024
2025     /* increment next_dts to use for the case where the input stream does not
2026        have timestamps or there are multiple frames in the packet */
2027     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2028                      avctx->sample_rate;
2029     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2030                      avctx->sample_rate;
2031
2032
2033     // preprocess audio (volume)
2034     if (audio_volume != 256) {
2035         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2036         void *samples = decoded_frame->data[0];
2037         switch (avctx->sample_fmt) {
2038         case AV_SAMPLE_FMT_U8:
2039         {
2040             uint8_t *volp = samples;
2041             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2042                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2043                 *volp++ = av_clip_uint8(v);
2044             }
2045             break;
2046         }
2047         case AV_SAMPLE_FMT_S16:
2048         {
2049             int16_t *volp = samples;
2050             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2051                 int v = ((*volp) * audio_volume + 128) >> 8;
2052                 *volp++ = av_clip_int16(v);
2053             }
2054             break;
2055         }
2056         case AV_SAMPLE_FMT_S32:
2057         {
2058             int32_t *volp = samples;
2059             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2060                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2061                 *volp++ = av_clipl_int32(v);
2062             }
2063             break;
2064         }
2065         case AV_SAMPLE_FMT_FLT:
2066         {
2067             float *volp = samples;
2068             float scale = audio_volume / 256.f;
2069             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2070                 *volp++ *= scale;
2071             }
2072             break;
2073         }
2074         case AV_SAMPLE_FMT_DBL:
2075         {
2076             double *volp = samples;
2077             double scale = audio_volume / 256.;
2078             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2079                 *volp++ *= scale;
2080             }
2081             break;
2082         }
2083         default:
2084             av_log(NULL, AV_LOG_FATAL,
2085                    "Audio volume adjustment on sample format %s is not supported.\n",
2086                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2087             exit_program(1);
2088         }
2089     }
2090
2091     rate_emu_sleep(ist);
2092
2093     for (i = 0; i < nb_output_streams; i++) {
2094         OutputStream *ost = &output_streams[i];
2095
2096         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2097             continue;
2098         do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
2099     }
2100
2101     return ret;
2102 }
2103
2104 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2105 {
2106     AVFrame *decoded_frame;
2107     void *buffer_to_free = NULL;
2108     int i, ret = 0;
2109     int64_t *best_effort_timestamp;
2110     AVRational *frame_sample_aspect;
2111
2112     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2113         return AVERROR(ENOMEM);
2114     else
2115         avcodec_get_frame_defaults(ist->decoded_frame);
2116     decoded_frame = ist->decoded_frame;
2117     pkt->pts  = *pkt_pts;
2118     pkt->dts  = ist->dts;
2119     *pkt_pts  = AV_NOPTS_VALUE;
2120
2121     update_benchmark(NULL);
2122     ret = avcodec_decode_video2(ist->st->codec,
2123                                 decoded_frame, got_output, pkt);
2124     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2125     if (ret < 0)
2126         return ret;
2127
2128     if (!*got_output) {
2129         /* no picture yet */
2130         return ret;
2131     }
2132
2133     best_effort_timestamp= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "best_effort_timestamp");
2134     if(*best_effort_timestamp != AV_NOPTS_VALUE)
2135         ist->next_pts = ist->pts = decoded_frame->pts = *best_effort_timestamp;
2136
2137     pkt->size = 0;
2138
2139     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2140
2141     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2142     for(i=0;i<nb_output_streams;i++) {
2143         OutputStream *ost = ost = &output_streams[i];
2144         if(check_output_constraints(ist, ost) && ost->encoding_needed){
2145             int changed =    ist->st->codec->width   != ost->input_video_filter->outputs[0]->w
2146                           || ist->st->codec->height  != ost->input_video_filter->outputs[0]->h
2147                           || ist->st->codec->pix_fmt != ost->input_video_filter->outputs[0]->format;
2148             if (!frame_sample_aspect->num)
2149                 *frame_sample_aspect = ist->st->sample_aspect_ratio;
2150             decoded_frame->pts = ist->pts;
2151             if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2152                 FrameBuffer      *buf = decoded_frame->opaque;
2153                 AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2154                                             decoded_frame->data, decoded_frame->linesize,
2155                                             AV_PERM_READ | AV_PERM_PRESERVE,
2156                                             ist->st->codec->width, ist->st->codec->height,
2157                                             ist->st->codec->pix_fmt);
2158
2159                 avfilter_copy_frame_props(fb, decoded_frame);
2160                 fb->buf->priv           = buf;
2161                 fb->buf->free           = filter_release_buffer;
2162
2163                 buf->refcount++;
2164                 av_buffersrc_buffer(ost->input_video_filter, fb);
2165             } else
2166             if((av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE)) < 0){
2167                 av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2168                 exit_program(1);
2169             }
2170         }
2171     }
2172
2173     rate_emu_sleep(ist);
2174
2175     if (ist->st->sample_aspect_ratio.num)
2176         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2177
2178     for (i = 0; i < nb_output_streams; i++) {
2179         OutputStream *ost = &output_streams[i];
2180
2181         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2182             continue;
2183
2184         while (av_buffersink_poll_frame(ost->output_video_filter)) {
2185             AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
2186             AVFrame *filtered_frame;
2187             AVFilterBufferRef *picref;
2188
2189             if (av_buffersink_get_buffer_ref(ost->output_video_filter, &picref, 0) < 0){
2190                 av_log(NULL, AV_LOG_WARNING, "AV Filter told us it has a frame available but failed to output one\n");
2191                 goto cont;
2192             }
2193             if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
2194                 ret = AVERROR(ENOMEM);
2195                 goto fail;
2196             }
2197             filtered_frame = ist->filtered_frame;
2198             *filtered_frame= *decoded_frame; //for me_threshold
2199             avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2200             filtered_frame->pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2201             if (!ost->frame_aspect_ratio)
2202                 ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2203             do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame);
2204             cont:
2205             avfilter_unref_buffer(picref);
2206         }
2207     }
2208
2209 fail:
2210     av_free(buffer_to_free);
2211     return ret;
2212 }
2213
2214 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2215 {
2216     AVSubtitle subtitle;
2217     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2218                                           &subtitle, got_output, pkt);
2219     if (ret < 0)
2220         return ret;
2221     if (!*got_output)
2222         return ret;
2223
2224     rate_emu_sleep(ist);
2225
2226     for (i = 0; i < nb_output_streams; i++) {
2227         OutputStream *ost = &output_streams[i];
2228
2229         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2230             continue;
2231
2232         do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
2233     }
2234
2235     avsubtitle_free(&subtitle);
2236     return ret;
2237 }
2238
2239 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2240 static int output_packet(InputStream *ist,
2241                          OutputStream *ost_table, int nb_ostreams,
2242                          const AVPacket *pkt)
2243 {
2244     int ret = 0, i;
2245     int got_output;
2246     int64_t pkt_pts = AV_NOPTS_VALUE;
2247
2248     AVPacket avpkt;
2249
2250     if (ist->next_dts == AV_NOPTS_VALUE)
2251         ist->next_dts = ist->dts;
2252     if (ist->next_pts == AV_NOPTS_VALUE)
2253         ist->next_pts = ist->pts;
2254
2255     if (pkt == NULL) {
2256         /* EOF handling */
2257         av_init_packet(&avpkt);
2258         avpkt.data = NULL;
2259         avpkt.size = 0;
2260         goto handle_eof;
2261     } else {
2262         avpkt = *pkt;
2263     }
2264
2265     if (pkt->dts != AV_NOPTS_VALUE) {
2266         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2267         if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2268             ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2269     }
2270     if(pkt->pts != AV_NOPTS_VALUE)
2271         pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2272
2273     // while we have more to decode or while the decoder did output something on EOF
2274     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2275         int duration;
2276     handle_eof:
2277
2278         ist->pts = ist->next_pts;
2279         ist->dts = ist->next_dts;
2280
2281         if (avpkt.size && avpkt.size != pkt->size) {
2282             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2283                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2284             ist->showed_multi_packet_warning = 1;
2285         }
2286
2287         switch (ist->st->codec->codec_type) {
2288         case AVMEDIA_TYPE_AUDIO:
2289             ret = transcode_audio    (ist, &avpkt, &got_output);
2290             break;
2291         case AVMEDIA_TYPE_VIDEO:
2292             ret = transcode_video    (ist, &avpkt, &got_output, &pkt_pts);
2293             if (avpkt.duration) {
2294                 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2295             } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2296                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2297                 duration = ((int64_t)AV_TIME_BASE *
2298                                 ist->st->codec->time_base.num * ticks) /
2299                                 ist->st->codec->time_base.den;
2300             } else
2301                 duration = 0;
2302
2303             if(ist->dts != AV_NOPTS_VALUE && duration) {
2304                 ist->next_dts += duration;
2305             }else
2306                 ist->next_dts = AV_NOPTS_VALUE;
2307
2308             if (got_output)
2309                 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2310             break;
2311         case AVMEDIA_TYPE_SUBTITLE:
2312             ret = transcode_subtitles(ist, &avpkt, &got_output);
2313             break;
2314         default:
2315             return -1;
2316         }
2317
2318         if (ret < 0)
2319             return ret;
2320
2321         avpkt.dts=
2322         avpkt.pts= AV_NOPTS_VALUE;
2323
2324         // touch data and size only if not EOF
2325         if (pkt) {
2326             if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2327                 ret = avpkt.size;
2328             avpkt.data += ret;
2329             avpkt.size -= ret;
2330         }
2331         if (!got_output) {
2332             continue;
2333         }
2334     }
2335
2336     /* handle stream copy */
2337     if (!ist->decoding_needed) {
2338         rate_emu_sleep(ist);
2339         ist->dts = ist->next_dts;
2340         switch (ist->st->codec->codec_type) {
2341         case AVMEDIA_TYPE_AUDIO:
2342             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2343                              ist->st->codec->sample_rate;
2344             break;
2345         case AVMEDIA_TYPE_VIDEO:
2346             if (pkt->duration) {
2347                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2348             } else if(ist->st->codec->time_base.num != 0) {
2349                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2350                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2351                                   ist->st->codec->time_base.num * ticks) /
2352                                   ist->st->codec->time_base.den;
2353             }
2354             break;
2355         }
2356         ist->pts = ist->dts;
2357         ist->next_pts = ist->next_dts;
2358     }
2359     for (i = 0; pkt && i < nb_ostreams; i++) {
2360         OutputStream *ost = &ost_table[i];
2361
2362         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2363             continue;
2364
2365         do_streamcopy(ist, ost, pkt);
2366     }
2367
2368     return 0;
2369 }
2370
2371 static void print_sdp(OutputFile *output_files, int n)
2372 {
2373     char sdp[2048];
2374     int i;
2375     AVFormatContext **avc = av_malloc(sizeof(*avc) * n);
2376
2377     if (!avc)
2378         exit_program(1);
2379     for (i = 0; i < n; i++)
2380         avc[i] = output_files[i].ctx;
2381
2382     av_sdp_create(avc, n, sdp, sizeof(sdp));
2383     printf("SDP:\n%s\n", sdp);
2384     fflush(stdout);
2385     av_freep(&avc);
2386 }
2387
2388 static void get_default_channel_layouts(OutputStream *ost, InputStream *ist)
2389 {
2390     char layout_name[256];
2391     AVCodecContext *enc = ost->st->codec;
2392     AVCodecContext *dec = ist->st->codec;
2393
2394     if (!dec->channel_layout) {
2395         if (enc->channel_layout && dec->channels == enc->channels) {
2396             dec->channel_layout = enc->channel_layout;
2397         } else {
2398             dec->channel_layout = av_get_default_channel_layout(dec->channels);
2399
2400             if (!dec->channel_layout) {
2401                 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
2402                        "layout for Input Stream #%d.%d\n", ist->file_index,
2403                        ist->st->index);
2404                 exit_program(1);
2405             }
2406         }
2407         av_get_channel_layout_string(layout_name, sizeof(layout_name),
2408                                      dec->channels, dec->channel_layout);
2409         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
2410                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
2411     }
2412     if (!enc->channel_layout) {
2413         if (dec->channels == enc->channels) {
2414             enc->channel_layout = dec->channel_layout;
2415             return;
2416         } else {
2417             enc->channel_layout = av_get_default_channel_layout(enc->channels);
2418         }
2419         if (!enc->channel_layout) {
2420             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel layout "
2421                    "for Output Stream #%d.%d\n", ost->file_index,
2422                    ost->st->index);
2423             exit_program(1);
2424         }
2425         av_get_channel_layout_string(layout_name, sizeof(layout_name),
2426                                      enc->channels, enc->channel_layout);
2427         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Output Stream "
2428                "#%d.%d : %s\n", ost->file_index, ost->st->index, layout_name);
2429     }
2430 }
2431
2432
2433 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2434                              char *error, int error_len)
2435 {
2436     InputStream *ist = &input_streams[ist_index];
2437     int i;
2438
2439     if (ist->decoding_needed) {
2440         AVCodec *codec = ist->dec;
2441         if (!codec) {
2442             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2443                     avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2444             return AVERROR(EINVAL);
2445         }
2446
2447         ist->dr1 = codec->capabilities & CODEC_CAP_DR1;
2448         if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2449             ist->st->codec->get_buffer     = codec_get_buffer;
2450             ist->st->codec->release_buffer = codec_release_buffer;
2451             ist->st->codec->opaque         = ist;
2452         }
2453
2454         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2455             av_dict_set(&ist->opts, "threads", "auto", 0);
2456         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2457             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2458                     ist->file_index, ist->st->index);
2459             return AVERROR(EINVAL);
2460         }
2461         assert_codec_experimental(ist->st->codec, 0);
2462         assert_avoptions(ist->opts);
2463
2464         if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2465             for (i = 0; i < nb_output_streams; i++) {
2466                 OutputStream *ost = &output_streams[i];
2467                 if (ost->source_index == ist_index) {
2468                     if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2469                         get_default_channel_layouts(ost, ist);
2470                     break;
2471                 }
2472             }
2473         }
2474     }
2475
2476     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;
2477     ist->next_pts = AV_NOPTS_VALUE;
2478     ist->next_dts = AV_NOPTS_VALUE;
2479     ist->is_start = 1;
2480
2481     return 0;
2482 }
2483
2484 static int transcode_init(OutputFile *output_files, int nb_output_files,
2485                           InputFile  *input_files,  int nb_input_files)
2486 {
2487     int ret = 0, i, j, k;
2488     AVFormatContext *oc;
2489     AVCodecContext *codec, *icodec;
2490     OutputStream *ost;
2491     InputStream *ist;
2492     char error[1024];
2493     int want_sdp = 1;
2494
2495     /* init framerate emulation */
2496     for (i = 0; i < nb_input_files; i++) {
2497         InputFile *ifile = &input_files[i];
2498         if (ifile->rate_emu)
2499             for (j = 0; j < ifile->nb_streams; j++)
2500                 input_streams[j + ifile->ist_index].start = av_gettime();
2501     }
2502
2503     /* output stream init */
2504     for (i = 0; i < nb_output_files; i++) {
2505         oc = output_files[i].ctx;
2506         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2507             av_dump_format(oc, i, oc->filename, 1);
2508             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2509             return AVERROR(EINVAL);
2510         }
2511     }
2512
2513     /* for each output stream, we compute the right encoding parameters */
2514     for (i = 0; i < nb_output_streams; i++) {
2515         ost = &output_streams[i];
2516         oc  = output_files[ost->file_index].ctx;
2517         ist = &input_streams[ost->source_index];
2518
2519         if (ost->attachment_filename)
2520             continue;
2521
2522         codec  = ost->st->codec;
2523         icodec = ist->st->codec;
2524
2525         ost->st->disposition          = ist->st->disposition;
2526         codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2527         codec->chroma_sample_location = icodec->chroma_sample_location;
2528
2529         if (ost->stream_copy) {
2530             uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2531
2532             if (extra_size > INT_MAX) {
2533                 return AVERROR(EINVAL);
2534             }
2535
2536             /* if stream_copy is selected, no need to decode or encode */
2537             codec->codec_id   = icodec->codec_id;
2538             codec->codec_type = icodec->codec_type;
2539
2540             if (!codec->codec_tag) {
2541                 if (!oc->oformat->codec_tag ||
2542                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2543                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2544                     codec->codec_tag = icodec->codec_tag;
2545             }
2546
2547             codec->bit_rate       = icodec->bit_rate;
2548             codec->rc_max_rate    = icodec->rc_max_rate;
2549             codec->rc_buffer_size = icodec->rc_buffer_size;
2550             codec->field_order    = icodec->field_order;
2551             codec->extradata      = av_mallocz(extra_size);
2552             if (!codec->extradata) {
2553                 return AVERROR(ENOMEM);
2554             }
2555             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2556             codec->extradata_size= icodec->extradata_size;
2557
2558             codec->time_base = ist->st->time_base;
2559             /*
2560              * Avi is a special case here because it supports variable fps but
2561              * having the fps and timebase differe significantly adds quite some
2562              * overhead
2563              */
2564             if(!strcmp(oc->oformat->name, "avi")) {
2565                 if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2566                                  && av_q2d(ist->st->time_base) < 1.0/500
2567                     || copy_tb==0){
2568                     codec->time_base = icodec->time_base;
2569                     codec->time_base.num *= icodec->ticks_per_frame;
2570                     codec->time_base.den *= 2;
2571                     codec->ticks_per_frame = 2;
2572                 }
2573             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2574                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2575                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2576             ) {
2577                 if(   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2578                                 && av_q2d(ist->st->time_base) < 1.0/500
2579                    || copy_tb==0){
2580                     codec->time_base = icodec->time_base;
2581                     codec->time_base.num *= icodec->ticks_per_frame;
2582                 }
2583             }
2584             av_reduce(&codec->time_base.num, &codec->time_base.den,
2585                         codec->time_base.num, codec->time_base.den, INT_MAX);
2586
2587             switch (codec->codec_type) {
2588             case AVMEDIA_TYPE_AUDIO:
2589                 if (audio_volume != 256) {
2590                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2591                     exit_program(1);
2592                 }
2593                 codec->channel_layout     = icodec->channel_layout;
2594                 codec->sample_rate        = icodec->sample_rate;
2595                 codec->channels           = icodec->channels;
2596                 codec->frame_size         = icodec->frame_size;
2597                 codec->audio_service_type = icodec->audio_service_type;
2598                 codec->block_align        = icodec->block_align;
2599                 break;
2600             case AVMEDIA_TYPE_VIDEO:
2601                 codec->pix_fmt            = icodec->pix_fmt;
2602                 codec->width              = icodec->width;
2603                 codec->height             = icodec->height;
2604                 codec->has_b_frames       = icodec->has_b_frames;
2605                 if (!codec->sample_aspect_ratio.num) {
2606                     codec->sample_aspect_ratio   =
2607                     ost->st->sample_aspect_ratio =
2608                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2609                         ist->st->codec->sample_aspect_ratio.num ?
2610                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2611                 }
2612                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2613                 break;
2614             case AVMEDIA_TYPE_SUBTITLE:
2615                 codec->width  = icodec->width;
2616                 codec->height = icodec->height;
2617                 break;
2618             case AVMEDIA_TYPE_DATA:
2619             case AVMEDIA_TYPE_ATTACHMENT:
2620                 break;
2621             default:
2622                 abort();
2623             }
2624         } else {
2625             if (!ost->enc)
2626                 ost->enc = avcodec_find_encoder(codec->codec_id);
2627
2628             ist->decoding_needed = 1;
2629             ost->encoding_needed = 1;
2630
2631             switch (codec->codec_type) {
2632             case AVMEDIA_TYPE_AUDIO:
2633                 ost->fifo = av_fifo_alloc(1024);
2634                 if (!ost->fifo) {
2635                     return AVERROR(ENOMEM);
2636                 }
2637                 if (!codec->sample_rate)
2638                     codec->sample_rate = icodec->sample_rate;
2639                 choose_sample_rate(ost->st, ost->enc);
2640                 codec->time_base = (AVRational){ 1, codec->sample_rate };
2641
2642                 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
2643                     codec->sample_fmt = icodec->sample_fmt;
2644                 choose_sample_fmt(ost->st, ost->enc);
2645
2646                 if (ost->audio_channels_mapped) {
2647                     /* the requested output channel is set to the number of
2648                      * -map_channel only if no -ac are specified */
2649                     if (!codec->channels) {
2650                         codec->channels       = ost->audio_channels_mapped;
2651                         codec->channel_layout = av_get_default_channel_layout(codec->channels);
2652                         if (!codec->channel_layout) {
2653                             av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
2654                             exit_program(1);
2655                         }
2656                     }
2657                     /* fill unused channel mapping with -1 (which means a muted
2658                      * channel in case the number of output channels is bigger
2659                      * than the number of mapped channel) */
2660                     for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
2661                         ost->audio_channels_map[j] = -1;
2662                 } else if (!codec->channels) {
2663                     codec->channels = icodec->channels;
2664                     codec->channel_layout = icodec->channel_layout;
2665                 }
2666                 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
2667                     codec->channel_layout = 0;
2668
2669                 ost->audio_resample       = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
2670                 ost->audio_resample      |=    codec->sample_fmt     != icodec->sample_fmt
2671                                             || codec->channel_layout != icodec->channel_layout;
2672                 icodec->request_channels  = codec->channels;
2673                 ost->resample_sample_fmt  = icodec->sample_fmt;
2674                 ost->resample_sample_rate = icodec->sample_rate;
2675                 ost->resample_channels    = icodec->channels;
2676                 break;
2677             case AVMEDIA_TYPE_VIDEO:
2678                 if (codec->pix_fmt == PIX_FMT_NONE)
2679                     codec->pix_fmt = icodec->pix_fmt;
2680                 choose_pixel_fmt(ost->st, ost->enc);
2681
2682                 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
2683                     av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
2684                     exit_program(1);
2685                 }
2686
2687                 if (!codec->width || !codec->height) {
2688                     codec->width  = icodec->width;
2689                     codec->height = icodec->height;
2690                 }
2691
2692                 ost->video_resample = codec->width   != icodec->width  ||
2693                                       codec->height  != icodec->height ||
2694                                       codec->pix_fmt != icodec->pix_fmt;
2695                 if (ost->video_resample) {
2696                     codec->bits_per_raw_sample = frame_bits_per_raw_sample;
2697                 }
2698
2699                 ost->resample_height  = icodec->height;
2700                 ost->resample_width   = icodec->width;
2701                 ost->resample_pix_fmt = icodec->pix_fmt;
2702
2703                 if (!ost->frame_rate.num)
2704                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
2705                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2706                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2707                     ost->frame_rate = ost->enc->supported_framerates[idx];
2708                 }
2709                 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
2710                 if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2711                    && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2712                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2713                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2714                 }
2715                 for (j = 0; j < ost->forced_kf_count; j++)
2716                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2717                                                          AV_TIME_BASE_Q,
2718                                                          codec->time_base);
2719
2720                 if (configure_video_filters(ist, ost)) {
2721                     av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2722                     exit_program(1);
2723                 }
2724                 break;
2725             case AVMEDIA_TYPE_SUBTITLE:
2726                 codec->time_base = (AVRational){1, 1000};
2727                 break;
2728             default:
2729                 abort();
2730                 break;
2731             }
2732             /* two pass mode */
2733             if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2734                 char logfilename[1024];
2735                 FILE *f;
2736
2737                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2738                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
2739                          i);
2740                 if (!strcmp(ost->enc->name, "libx264")) {
2741                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2742                 } else {
2743                     if (codec->flags & CODEC_FLAG_PASS2) {
2744                         char  *logbuffer;
2745                         size_t logbuffer_size;
2746                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2747                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2748                                 logfilename);
2749                             exit_program(1);
2750                         }
2751                         codec->stats_in = logbuffer;
2752                     }
2753                     if (codec->flags & CODEC_FLAG_PASS1) {
2754                         f = fopen(logfilename, "wb");
2755                         if (!f) {
2756                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2757                                 logfilename, strerror(errno));
2758                             exit_program(1);
2759                         }
2760                         ost->logfile = f;
2761                     }
2762                 }
2763             }
2764         }
2765     }
2766
2767     /* open each encoder */
2768     for (i = 0; i < nb_output_streams; i++) {
2769         ost = &output_streams[i];
2770         if (ost->encoding_needed) {
2771             AVCodec      *codec = ost->enc;
2772             AVCodecContext *dec = input_streams[ost->source_index].st->codec;
2773             if (!codec) {
2774                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2775                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2776                 ret = AVERROR(EINVAL);
2777                 goto dump_format;
2778             }
2779             if (dec->subtitle_header) {
2780                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
2781                 if (!ost->st->codec->subtitle_header) {
2782                     ret = AVERROR(ENOMEM);
2783                     goto dump_format;
2784                 }
2785                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2786                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2787             }
2788             if (!av_dict_get(ost->opts, "threads", NULL, 0))
2789                 av_dict_set(&ost->opts, "threads", "auto", 0);
2790             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
2791                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2792                         ost->file_index, ost->index);
2793                 ret = AVERROR(EINVAL);
2794                 goto dump_format;
2795             }
2796             assert_codec_experimental(ost->st->codec, 1);
2797             assert_avoptions(ost->opts);
2798             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2799                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2800                                              " It takes bits/s as argument, not kbits/s\n");
2801             extra_size += ost->st->codec->extradata_size;
2802
2803             if (ost->st->codec->me_threshold)
2804                 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
2805         }
2806     }
2807
2808     /* init input streams */
2809     for (i = 0; i < nb_input_streams; i++)
2810         if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
2811             goto dump_format;
2812
2813     /* discard unused programs */
2814     for (i = 0; i < nb_input_files; i++) {
2815         InputFile *ifile = &input_files[i];
2816         for (j = 0; j < ifile->ctx->nb_programs; j++) {
2817             AVProgram *p = ifile->ctx->programs[j];
2818             int discard  = AVDISCARD_ALL;
2819
2820             for (k = 0; k < p->nb_stream_indexes; k++)
2821                 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
2822                     discard = AVDISCARD_DEFAULT;
2823                     break;
2824                 }
2825             p->discard = discard;
2826         }
2827     }
2828
2829     /* open files and write file headers */
2830     for (i = 0; i < nb_output_files; i++) {
2831         oc = output_files[i].ctx;
2832         oc->interrupt_callback = int_cb;
2833         if (avformat_write_header(oc, &output_files[i].opts) < 0) {
2834             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
2835             ret = AVERROR(EINVAL);
2836             goto dump_format;
2837         }
2838 //        assert_avoptions(output_files[i].opts);
2839         if (strcmp(oc->oformat->name, "rtp")) {
2840             want_sdp = 0;
2841         }
2842     }
2843
2844  dump_format:
2845     /* dump the file output parameters - cannot be done before in case
2846        of stream copy */
2847     for (i = 0; i < nb_output_files; i++) {
2848         av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
2849     }
2850
2851     /* dump the stream mapping */
2852     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2853     for (i = 0; i < nb_output_streams; i++) {
2854         ost = &output_streams[i];
2855
2856         if (ost->attachment_filename) {
2857             /* an attached file */
2858             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
2859                    ost->attachment_filename, ost->file_index, ost->index);
2860             continue;
2861         }
2862         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
2863                input_streams[ost->source_index].file_index,
2864                input_streams[ost->source_index].st->index,
2865                ost->file_index,
2866                ost->index);
2867         if (ost->audio_channels_mapped) {
2868             av_log(NULL, AV_LOG_INFO, " [ch:");
2869             for (j = 0; j < ost->audio_channels_mapped; j++)
2870                 if (ost->audio_channels_map[j] == -1)
2871                     av_log(NULL, AV_LOG_INFO, " M");
2872                 else
2873                     av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
2874             av_log(NULL, AV_LOG_INFO, "]");
2875         }
2876         if (ost->sync_ist != &input_streams[ost->source_index])
2877             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2878                    ost->sync_ist->file_index,
2879                    ost->sync_ist->st->index);
2880         if (ost->stream_copy)
2881             av_log(NULL, AV_LOG_INFO, " (copy)");
2882         else
2883             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
2884                    input_streams[ost->source_index].dec->name : "?",
2885                    ost->enc ? ost->enc->name : "?");
2886         av_log(NULL, AV_LOG_INFO, "\n");
2887     }
2888
2889     if (ret) {
2890         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2891         return ret;
2892     }
2893
2894     if (want_sdp) {
2895         print_sdp(output_files, nb_output_files);
2896     }
2897
2898     return 0;
2899 }
2900
2901 /*
2902  * The following code is the main loop of the file converter
2903  */
2904 static int transcode(OutputFile *output_files, int nb_output_files,
2905                      InputFile  *input_files,  int nb_input_files)
2906 {
2907     int ret, i;
2908     AVFormatContext *is, *os;
2909     OutputStream *ost;
2910     InputStream *ist;
2911     uint8_t *no_packet;
2912     int no_packet_count = 0;
2913     int64_t timer_start;
2914     int key;
2915
2916     if (!(no_packet = av_mallocz(nb_input_files)))
2917         exit_program(1);
2918
2919     ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
2920     if (ret < 0)
2921         goto fail;
2922
2923     if (!using_stdin) {
2924         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
2925     }
2926
2927     timer_start = av_gettime();
2928
2929     for (; received_sigterm == 0;) {
2930         int file_index, ist_index;
2931         AVPacket pkt;
2932         int64_t ipts_min;
2933         double opts_min;
2934         int64_t cur_time= av_gettime();
2935
2936         ipts_min = INT64_MAX;
2937         opts_min = 1e100;
2938         /* if 'q' pressed, exits */
2939         if (!using_stdin) {
2940             static int64_t last_time;
2941             if (received_nb_signals)
2942                 break;
2943             /* read_key() returns 0 on EOF */
2944             if(cur_time - last_time >= 100000 && !run_as_daemon){
2945                 key =  read_key();
2946                 last_time = cur_time;
2947             }else
2948                 key = -1;
2949             if (key == 'q')
2950                 break;
2951             if (key == '+') av_log_set_level(av_log_get_level()+10);
2952             if (key == '-') av_log_set_level(av_log_get_level()-10);
2953             if (key == 's') qp_hist     ^= 1;
2954             if (key == 'h'){
2955                 if (do_hex_dump){
2956                     do_hex_dump = do_pkt_dump = 0;
2957                 } else if(do_pkt_dump){
2958                     do_hex_dump = 1;
2959                 } else
2960                     do_pkt_dump = 1;
2961                 av_log_set_level(AV_LOG_DEBUG);
2962             }
2963             if (key == 'c' || key == 'C'){
2964                 char buf[4096], target[64], command[256], arg[256] = {0};
2965                 double time;
2966                 int k, n = 0;
2967                 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
2968                 i = 0;
2969                 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2970                     if (k > 0)
2971                         buf[i++] = k;
2972                 buf[i] = 0;
2973                 if (k > 0 &&
2974                     (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2975                     av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2976                            target, time, command, arg);
2977                     for (i = 0; i < nb_output_streams; i++) {
2978                         ost = &output_streams[i];
2979                         if (ost->graph) {
2980                             if (time < 0) {
2981                                 ret = avfilter_graph_send_command(ost->graph, target, command, arg, buf, sizeof(buf),
2982                                                                   key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2983                                 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
2984                             } else {
2985                                 ret = avfilter_graph_queue_command(ost->graph, target, command, arg, 0, time);
2986                             }
2987                         }
2988                     }
2989                 } else {
2990                     av_log(NULL, AV_LOG_ERROR,
2991                            "Parse error, at least 3 arguments were expected, "
2992                            "only %d given in string '%s'\n", n, buf);
2993                 }
2994             }
2995             if (key == 'd' || key == 'D'){
2996                 int debug=0;
2997                 if(key == 'D') {
2998                     debug = input_streams[0].st->codec->debug<<1;
2999                     if(!debug) debug = 1;
3000                     while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3001                         debug += debug;
3002                 }else
3003                     if(scanf("%d", &debug)!=1)
3004                         fprintf(stderr,"error parsing debug value\n");
3005                 for(i=0;i<nb_input_streams;i++) {
3006                     input_streams[i].st->codec->debug = debug;
3007                 }
3008                 for(i=0;i<nb_output_streams;i++) {
3009                     ost = &output_streams[i];
3010                     ost->st->codec->debug = debug;
3011                 }
3012                 if(debug) av_log_set_level(AV_LOG_DEBUG);
3013                 fprintf(stderr,"debug=%d\n", debug);
3014             }
3015             if (key == '?'){
3016                 fprintf(stderr, "key    function\n"
3017                                 "?      show this help\n"
3018                                 "+      increase verbosity\n"
3019                                 "-      decrease verbosity\n"
3020                                 "c      Send command to filtergraph\n"
3021                                 "D      cycle through available debug modes\n"
3022                                 "h      dump packets/hex press to cycle through the 3 states\n"
3023                                 "q      quit\n"
3024                                 "s      Show QP histogram\n"
3025                 );
3026             }
3027         }
3028
3029         /* select the stream that we must read now by looking at the
3030            smallest output pts */
3031         file_index = -1;
3032         for (i = 0; i < nb_output_streams; i++) {
3033             OutputFile *of;
3034             int64_t ipts;
3035             double  opts;
3036             ost = &output_streams[i];
3037             of = &output_files[ost->file_index];
3038             os = output_files[ost->file_index].ctx;
3039             ist = &input_streams[ost->source_index];
3040             if (ost->is_past_recording_time || no_packet[ist->file_index] ||
3041                 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3042                 continue;
3043             opts = ost->st->pts.val * av_q2d(ost->st->time_base);
3044             ipts = ist->pts;
3045             if (!input_files[ist->file_index].eof_reached) {
3046                 if (ipts < ipts_min) {
3047                     ipts_min = ipts;
3048                     if (input_sync)
3049                         file_index = ist->file_index;
3050                 }
3051                 if (opts < opts_min) {
3052                     opts_min = opts;
3053                     if (!input_sync) file_index = ist->file_index;
3054                 }
3055             }
3056             if (ost->frame_number >= ost->max_frames) {
3057                 int j;
3058                 for (j = 0; j < of->ctx->nb_streams; j++)
3059                     output_streams[of->ost_index + j].is_past_recording_time = 1;
3060                 continue;
3061             }
3062         }
3063         /* if none, if is finished */
3064         if (file_index < 0) {
3065             if (no_packet_count) {
3066                 no_packet_count = 0;
3067                 memset(no_packet, 0, nb_input_files);
3068                 usleep(10000);
3069                 continue;
3070             }
3071             break;
3072         }
3073
3074         /* read a frame from it and output it in the fifo */
3075         is  = input_files[file_index].ctx;
3076         ret = av_read_frame(is, &pkt);
3077         if (ret == AVERROR(EAGAIN)) {
3078             no_packet[file_index] = 1;
3079             no_packet_count++;
3080             continue;
3081         }
3082         if (ret < 0) {
3083             input_files[file_index].eof_reached = 1;
3084             if (opt_shortest)
3085                 break;
3086             else
3087                 continue;
3088         }
3089
3090         no_packet_count = 0;
3091         memset(no_packet, 0, nb_input_files);
3092
3093         if (do_pkt_dump) {
3094             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3095                              is->streams[pkt.stream_index]);
3096         }
3097         /* the following test is needed in case new streams appear
3098            dynamically in stream : we ignore them */
3099         if (pkt.stream_index >= input_files[file_index].nb_streams)
3100             goto discard_packet;
3101         ist_index = input_files[file_index].ist_index + pkt.stream_index;
3102         ist = &input_streams[ist_index];
3103         if (ist->discard)
3104             goto discard_packet;
3105
3106         if (pkt.dts != AV_NOPTS_VALUE)
3107             pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3108         if (pkt.pts != AV_NOPTS_VALUE)
3109             pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3110
3111         if (pkt.pts != AV_NOPTS_VALUE)
3112             pkt.pts *= ist->ts_scale;
3113         if (pkt.dts != AV_NOPTS_VALUE)
3114             pkt.dts *= ist->ts_scale;
3115
3116         if (debug_ts) {
3117             av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3118                     "next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3119                     ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3120                     av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3121                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3122                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3123                     input_files[ist->file_index].ts_offset);
3124         }
3125
3126         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3127             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3128             int64_t delta   = pkt_dts - ist->next_dts;
3129             if (is->iformat->flags & AVFMT_TS_DISCONT) {
3130             if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3131                 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3132                  ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3133                 pkt_dts+1<ist->pts){
3134                 input_files[ist->file_index].ts_offset -= delta;
3135                 av_log(NULL, AV_LOG_DEBUG,
3136                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3137                        delta, input_files[ist->file_index].ts_offset);
3138                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3139                 if (pkt.pts != AV_NOPTS_VALUE)
3140                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3141             }
3142             } else {
3143                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3144                     (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3145                      pkt_dts+1<ist->pts){
3146                     av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3147                     pkt.dts = AV_NOPTS_VALUE;
3148                 }
3149                 if (pkt.pts != AV_NOPTS_VALUE){
3150                     int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3151                     delta   = pkt_pts - ist->next_dts;
3152                     if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3153                         (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3154                         pkt_pts+1<ist->pts) {
3155                         av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3156                         pkt.pts = AV_NOPTS_VALUE;
3157                     }
3158                 }
3159             }
3160         }
3161
3162         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3163         if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
3164
3165             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3166                    ist->file_index, ist->st->index);
3167             if (exit_on_error)
3168                 exit_program(1);
3169             av_free_packet(&pkt);
3170             continue;
3171         }
3172
3173     discard_packet:
3174         av_free_packet(&pkt);
3175
3176         /* dump report by using the output first video and audio streams */
3177         print_report(output_files, output_streams, nb_output_streams, 0, timer_start, cur_time);
3178     }
3179
3180     /* at the end of stream, we must flush the decoder buffers */
3181     for (i = 0; i < nb_input_streams; i++) {
3182         ist = &input_streams[i];
3183         if (ist->decoding_needed) {
3184             output_packet(ist, output_streams, nb_output_streams, NULL);
3185         }
3186     }
3187     flush_encoders(output_streams, nb_output_streams);
3188
3189     term_exit();
3190
3191     /* write the trailer if needed and close file */
3192     for (i = 0; i < nb_output_files; i++) {
3193         os = output_files[i].ctx;
3194         av_write_trailer(os);
3195     }
3196
3197     /* dump report by using the first video and audio streams */
3198     print_report(output_files, output_streams, nb_output_streams, 1, timer_start, av_gettime());
3199
3200     /* close each encoder */
3201     for (i = 0; i < nb_output_streams; i++) {
3202         ost = &output_streams[i];
3203         if (ost->encoding_needed) {
3204             av_freep(&ost->st->codec->stats_in);
3205             avcodec_close(ost->st->codec);
3206         }
3207         avfilter_graph_free(&ost->graph);
3208     }
3209
3210     /* close each decoder */
3211     for (i = 0; i < nb_input_streams; i++) {
3212         ist = &input_streams[i];
3213         if (ist->decoding_needed) {
3214             avcodec_close(ist->st->codec);
3215         }
3216     }
3217
3218     /* finished ! */
3219     ret = 0;
3220
3221  fail:
3222     av_freep(&no_packet);
3223
3224     if (output_streams) {
3225         for (i = 0; i < nb_output_streams; i++) {
3226             ost = &output_streams[i];
3227             if (ost) {
3228                 if (ost->stream_copy)
3229                     av_freep(&ost->st->codec->extradata);
3230                 if (ost->logfile) {
3231                     fclose(ost->logfile);
3232                     ost->logfile = NULL;
3233                 }
3234                 av_fifo_free(ost->fifo); /* works even if fifo is not
3235                                              initialized but set to zero */
3236                 av_freep(&ost->st->codec->subtitle_header);
3237                 av_free(ost->forced_kf_pts);
3238                 swr_free(&ost->swr);
3239                 av_dict_free(&ost->opts);
3240             }
3241         }
3242     }
3243     return ret;
3244 }
3245
3246 static int opt_frame_crop(const char *opt, const char *arg)
3247 {
3248     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3249     return AVERROR(EINVAL);
3250 }
3251
3252 static int opt_pad(const char *opt, const char *arg)
3253 {
3254     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3255     return -1;
3256 }
3257
3258 static int opt_video_channel(const char *opt, const char *arg)
3259 {
3260     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3261     return opt_default("channel", arg);
3262 }
3263
3264 static int opt_video_standard(const char *opt, const char *arg)
3265 {
3266     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3267     return opt_default("standard", arg);
3268 }
3269
3270 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3271 {
3272     audio_codec_name = arg;
3273     return parse_option(o, "codec:a", arg, options);
3274 }
3275
3276 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3277 {
3278     video_codec_name = arg;
3279     return parse_option(o, "codec:v", arg, options);
3280 }
3281
3282 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3283 {
3284     subtitle_codec_name = arg;
3285     return parse_option(o, "codec:s", arg, options);
3286 }
3287
3288 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3289 {
3290     return parse_option(o, "codec:d", arg, options);
3291 }
3292
3293 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3294 {
3295     StreamMap *m = NULL;
3296     int i, negative = 0, file_idx;
3297     int sync_file_idx = -1, sync_stream_idx = 0;
3298     char *p, *sync;
3299     char *map;
3300
3301     if (*arg == '-') {
3302         negative = 1;
3303         arg++;
3304     }
3305     map = av_strdup(arg);
3306
3307     /* parse sync stream first, just pick first matching stream */
3308     if (sync = strchr(map, ',')) {
3309         *sync = 0;
3310         sync_file_idx = strtol(sync + 1, &sync, 0);
3311         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3312             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3313             exit_program(1);
3314         }
3315         if (*sync)
3316             sync++;
3317         for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
3318             if (check_stream_specifier(input_files[sync_file_idx].ctx,
3319                                        input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
3320                 sync_stream_idx = i;
3321                 break;
3322             }
3323         if (i == input_files[sync_file_idx].nb_streams) {
3324             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3325                                        "match any streams.\n", arg);
3326             exit_program(1);
3327         }
3328     }
3329
3330
3331     file_idx = strtol(map, &p, 0);
3332     if (file_idx >= nb_input_files || file_idx < 0) {
3333         av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3334         exit_program(1);
3335     }
3336     if (negative)
3337         /* disable some already defined maps */
3338         for (i = 0; i < o->nb_stream_maps; i++) {
3339             m = &o->stream_maps[i];
3340             if (file_idx == m->file_index &&
3341                 check_stream_specifier(input_files[m->file_index].ctx,
3342                                        input_files[m->file_index].ctx->streams[m->stream_index],
3343                                        *p == ':' ? p + 1 : p) > 0)
3344                 m->disabled = 1;
3345         }
3346     else
3347         for (i = 0; i < input_files[file_idx].nb_streams; i++) {
3348             if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
3349                         *p == ':' ? p + 1 : p) <= 0)
3350                 continue;
3351             o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3352                                         &o->nb_stream_maps, o->nb_stream_maps + 1);
3353             m = &o->stream_maps[o->nb_stream_maps - 1];
3354
3355             m->file_index   = file_idx;
3356             m->stream_index = i;
3357
3358             if (sync_file_idx >= 0) {
3359                 m->sync_file_index   = sync_file_idx;
3360                 m->sync_stream_index = sync_stream_idx;
3361             } else {
3362                 m->sync_file_index   = file_idx;
3363                 m->sync_stream_index = i;
3364             }
3365         }
3366
3367     if (!m) {
3368         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3369         exit_program(1);
3370     }
3371
3372     av_freep(&map);
3373     return 0;
3374 }
3375
3376 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3377 {
3378     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3379                                 &o->nb_attachments, o->nb_attachments + 1);
3380     o->attachments[o->nb_attachments - 1] = arg;
3381     return 0;
3382 }
3383
3384 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3385 {
3386     int n;
3387     AVStream *st;
3388     AudioChannelMap *m;
3389
3390     o->audio_channel_maps =
3391         grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3392                    &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3393     m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3394
3395     /* muted channel syntax */
3396     n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3397     if ((n == 1 || n == 3) && m->channel_idx == -1) {
3398         m->file_idx = m->stream_idx = -1;
3399         if (n == 1)
3400             m->ofile_idx = m->ostream_idx = -1;
3401         return 0;
3402     }
3403
3404     /* normal syntax */
3405     n = sscanf(arg, "%d.%d.%d:%d.%d",
3406                &m->file_idx,  &m->stream_idx, &m->channel_idx,
3407                &m->ofile_idx, &m->ostream_idx);
3408
3409     if (n != 3 && n != 5) {
3410         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3411                "[file.stream.channel|-1][:syncfile:syncstream]\n");
3412         exit_program(1);
3413     }
3414
3415     if (n != 5) // only file.stream.channel specified
3416         m->ofile_idx = m->ostream_idx = -1;
3417
3418     /* check input */
3419     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
3420         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
3421                m->file_idx);
3422         exit_program(1);
3423     }
3424     if (m->stream_idx < 0 ||
3425         m->stream_idx >= input_files[m->file_idx].nb_streams) {
3426         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
3427                m->file_idx, m->stream_idx);
3428         exit_program(1);
3429     }
3430     st = input_files[m->file_idx].ctx->streams[m->stream_idx];
3431     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
3432         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
3433                m->file_idx, m->stream_idx);
3434         exit_program(1);
3435     }
3436     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
3437         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
3438                m->file_idx, m->stream_idx, m->channel_idx);
3439         exit_program(1);
3440     }
3441     return 0;
3442 }
3443
3444 /**
3445  * Parse a metadata specifier in arg.
3446  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3447  * @param index for type c/p, chapter/program index is written here
3448  * @param stream_spec for type s, the stream specifier is written here
3449  */
3450 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3451 {
3452     if (*arg) {
3453         *type = *arg;
3454         switch (*arg) {
3455         case 'g':
3456             break;
3457         case 's':
3458             if (*(++arg) && *arg != ':') {
3459                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3460                 exit_program(1);
3461             }
3462             *stream_spec = *arg == ':' ? arg + 1 : "";
3463             break;
3464         case 'c':
3465         case 'p':
3466             if (*(++arg) == ':')
3467                 *index = strtol(++arg, NULL, 0);
3468             break;
3469         default:
3470             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3471             exit_program(1);
3472         }
3473     } else
3474         *type = 'g';
3475 }
3476
3477 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3478 {
3479     AVDictionary **meta_in = NULL;
3480     AVDictionary **meta_out = NULL;
3481     int i, ret = 0;
3482     char type_in, type_out;
3483     const char *istream_spec = NULL, *ostream_spec = NULL;
3484     int idx_in = 0, idx_out = 0;
3485
3486     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
3487     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3488
3489     if (!ic) {
3490         if (type_out == 'g' || !*outspec)
3491             o->metadata_global_manual = 1;
3492         if (type_out == 's' || !*outspec)
3493             o->metadata_streams_manual = 1;
3494         if (type_out == 'c' || !*outspec)
3495             o->metadata_chapters_manual = 1;
3496         return 0;
3497     }
3498
3499     if (type_in == 'g' || type_out == 'g')
3500         o->metadata_global_manual = 1;
3501     if (type_in == 's' || type_out == 's')
3502         o->metadata_streams_manual = 1;
3503     if (type_in == 'c' || type_out == 'c')
3504         o->metadata_chapters_manual = 1;
3505
3506 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3507     if ((index) < 0 || (index) >= (nb_elems)) {\
3508         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3509                 (desc), (index));\
3510         exit_program(1);\
3511     }
3512
3513 #define SET_DICT(type, meta, context, index)\
3514         switch (type) {\
3515         case 'g':\
3516             meta = &context->metadata;\
3517             break;\
3518         case 'c':\
3519             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
3520             meta = &context->chapters[index]->metadata;\
3521             break;\
3522         case 'p':\
3523             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
3524             meta = &context->programs[index]->metadata;\
3525             break;\
3526         }\
3527
3528     SET_DICT(type_in, meta_in, ic, idx_in);
3529     SET_DICT(type_out, meta_out, oc, idx_out);
3530
3531     /* for input streams choose first matching stream */
3532     if (type_in == 's') {
3533         for (i = 0; i < ic->nb_streams; i++) {
3534             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
3535                 meta_in = &ic->streams[i]->metadata;
3536                 break;
3537             } else if (ret < 0)
3538                 exit_program(1);
3539         }
3540         if (!meta_in) {
3541             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
3542             exit_program(1);
3543         }
3544     }
3545
3546     if (type_out == 's') {
3547         for (i = 0; i < oc->nb_streams; i++) {
3548             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
3549                 meta_out = &oc->streams[i]->metadata;
3550                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3551             } else if (ret < 0)
3552                 exit_program(1);
3553         }
3554     } else
3555         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
3556
3557     return 0;
3558 }
3559
3560 static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
3561 {
3562     char buf[128];
3563     int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
3564     struct tm time = *gmtime((time_t*)&recording_timestamp);
3565     strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
3566     parse_option(o, "metadata", buf, options);
3567
3568     av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
3569                                  "tag instead.\n", opt);
3570     return 0;
3571 }
3572
3573 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
3574 {
3575     const char *codec_string = encoder ? "encoder" : "decoder";
3576     AVCodec *codec;
3577
3578     codec = encoder ?
3579         avcodec_find_encoder_by_name(name) :
3580         avcodec_find_decoder_by_name(name);
3581     if (!codec) {
3582         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
3583         exit_program(1);
3584     }
3585     if (codec->type != type) {
3586         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
3587         exit_program(1);
3588     }
3589     return codec;
3590 }
3591
3592 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
3593 {
3594     char *codec_name = NULL;
3595
3596     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
3597     if (codec_name) {
3598         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
3599         st->codec->codec_id = codec->id;
3600         return codec;
3601     } else
3602         return avcodec_find_decoder(st->codec->codec_id);
3603 }
3604
3605 /**
3606  * Add all the streams from the given input file to the global
3607  * list of input streams.
3608  */
3609 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
3610 {
3611     int i;
3612     char *next, *codec_tag = NULL;
3613
3614     for (i = 0; i < ic->nb_streams; i++) {
3615         AVStream *st = ic->streams[i];
3616         AVCodecContext *dec = st->codec;
3617         InputStream *ist;
3618
3619         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
3620         ist = &input_streams[nb_input_streams - 1];
3621         ist->st = st;
3622         ist->file_index = nb_input_files;
3623         ist->discard = 1;
3624         st->discard  = AVDISCARD_ALL;
3625         ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
3626
3627         ist->ts_scale = 1.0;
3628         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
3629
3630         MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
3631         if (codec_tag) {
3632             uint32_t tag = strtol(codec_tag, &next, 0);
3633             if (*next)
3634                 tag = AV_RL32(codec_tag);
3635             st->codec->codec_tag = tag;
3636         }
3637
3638         ist->dec = choose_decoder(o, ic, st);
3639
3640         switch (dec->codec_type) {
3641         case AVMEDIA_TYPE_VIDEO:
3642             if(!ist->dec)
3643                 ist->dec = avcodec_find_decoder(dec->codec_id);
3644             if (dec->lowres) {
3645                 dec->flags |= CODEC_FLAG_EMU_EDGE;
3646             }
3647
3648             break;
3649         case AVMEDIA_TYPE_AUDIO:
3650         case AVMEDIA_TYPE_DATA:
3651         case AVMEDIA_TYPE_SUBTITLE:
3652             if(!ist->dec)
3653                 ist->dec = avcodec_find_decoder(dec->codec_id);
3654             break;
3655         case AVMEDIA_TYPE_ATTACHMENT:
3656         case AVMEDIA_TYPE_UNKNOWN:
3657             break;
3658         default:
3659             abort();
3660         }
3661     }
3662 }
3663
3664 static void assert_file_overwrite(const char *filename)
3665 {
3666     if ((!file_overwrite || no_file_overwrite) &&
3667         (strchr(filename, ':') == NULL || filename[1] == ':' ||
3668          av_strstart(filename, "file:", NULL))) {
3669         if (avio_check(filename, 0) == 0) {
3670             if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
3671                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3672                 fflush(stderr);
3673                 term_exit();
3674                 signal(SIGINT, SIG_DFL);
3675                 if (!read_yesno()) {
3676                     av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
3677                     exit_program(1);
3678                 }
3679                 term_init();
3680             }
3681             else {
3682                 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
3683                 exit_program(1);
3684             }
3685         }
3686     }
3687 }
3688
3689 static void dump_attachment(AVStream *st, const char *filename)
3690 {
3691     int ret;
3692     AVIOContext *out = NULL;
3693     AVDictionaryEntry *e;
3694
3695     if (!st->codec->extradata_size) {
3696         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
3697                nb_input_files - 1, st->index);
3698         return;
3699     }
3700     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
3701         filename = e->value;
3702     if (!*filename) {
3703         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
3704                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
3705         exit_program(1);
3706     }
3707
3708     assert_file_overwrite(filename);
3709
3710     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
3711         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
3712                filename);
3713         exit_program(1);
3714     }
3715
3716     avio_write(out, st->codec->extradata, st->codec->extradata_size);
3717     avio_flush(out);
3718     avio_close(out);
3719 }
3720
3721 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
3722 {
3723     AVFormatContext *ic;
3724     AVInputFormat *file_iformat = NULL;
3725     int err, i, ret;
3726     int64_t timestamp;
3727     uint8_t buf[128];
3728     AVDictionary **opts;
3729     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
3730
3731     if (o->format) {
3732         if (!(file_iformat = av_find_input_format(o->format))) {
3733             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
3734             exit_program(1);
3735         }
3736     }
3737
3738     if (!strcmp(filename, "-"))
3739         filename = "pipe:";
3740
3741     using_stdin |= !strncmp(filename, "pipe:", 5) ||
3742                     !strcmp(filename, "/dev/stdin");
3743
3744     /* get default parameters from command line */
3745     ic = avformat_alloc_context();
3746     if (!ic) {
3747         print_error(filename, AVERROR(ENOMEM));
3748         exit_program(1);
3749     }
3750     if (o->nb_audio_sample_rate) {
3751         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
3752         av_dict_set(&format_opts, "sample_rate", buf, 0);
3753     }
3754     if (o->nb_audio_channels) {
3755         snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
3756         av_dict_set(&format_opts, "channels", buf, 0);
3757     }
3758     if (o->nb_frame_rates) {
3759         av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
3760     }
3761     if (o->nb_frame_sizes) {
3762         av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
3763     }
3764     if (o->nb_frame_pix_fmts)
3765         av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
3766
3767     ic->video_codec_id   = video_codec_name ?
3768         find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0)->id : CODEC_ID_NONE;
3769     ic->audio_codec_id   = audio_codec_name ?
3770         find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0)->id : CODEC_ID_NONE;
3771     ic->subtitle_codec_id= subtitle_codec_name ?
3772         find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : CODEC_ID_NONE;
3773     ic->flags |= AVFMT_FLAG_NONBLOCK;
3774     ic->interrupt_callback = int_cb;
3775
3776     /* open the input file with generic avformat function */
3777     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
3778     if (err < 0) {
3779         print_error(filename, err);
3780         exit_program(1);
3781     }
3782     assert_avoptions(format_opts);
3783
3784     /* apply forced codec ids */
3785     for (i = 0; i < ic->nb_streams; i++)
3786         choose_decoder(o, ic, ic->streams[i]);
3787
3788     /* Set AVCodecContext options for avformat_find_stream_info */
3789     opts = setup_find_stream_info_opts(ic, codec_opts);
3790     orig_nb_streams = ic->nb_streams;
3791
3792     /* If not enough info to get the stream parameters, we decode the
3793        first frames to get it. (used in mpeg case for example) */
3794     ret = avformat_find_stream_info(ic, opts);
3795     if (ret < 0) {
3796         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
3797         avformat_close_input(&ic);
3798         exit_program(1);
3799     }
3800
3801     timestamp = o->start_time;
3802     /* add the stream start time */
3803     if (ic->start_time != AV_NOPTS_VALUE)
3804         timestamp += ic->start_time;
3805
3806     /* if seeking requested, we execute it */
3807     if (o->start_time != 0) {
3808         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
3809         if (ret < 0) {
3810             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
3811                    filename, (double)timestamp / AV_TIME_BASE);
3812         }
3813     }
3814
3815     /* update the current parameters so that they match the one of the input stream */
3816     add_input_streams(o, ic);
3817
3818     /* dump the file content */
3819     av_dump_format(ic, nb_input_files, filename, 0);
3820
3821     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
3822     input_files[nb_input_files - 1].ctx        = ic;
3823     input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;
3824     input_files[nb_input_files - 1].ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
3825     input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
3826     input_files[nb_input_files - 1].rate_emu   = o->rate_emu;
3827
3828     for (i = 0; i < o->nb_dump_attachment; i++) {
3829         int j;
3830
3831         for (j = 0; j < ic->nb_streams; j++) {
3832             AVStream *st = ic->streams[j];
3833
3834             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
3835                 dump_attachment(st, o->dump_attachment[i].u.str);
3836         }
3837     }
3838
3839     for (i = 0; i < orig_nb_streams; i++)
3840         av_dict_free(&opts[i]);
3841     av_freep(&opts);
3842
3843     reset_options(o, 1);
3844     return 0;
3845 }
3846
3847 static void parse_forced_key_frames(char *kf, OutputStream *ost)
3848 {
3849     char *p;
3850     int n = 1, i;
3851
3852     for (p = kf; *p; p++)
3853         if (*p == ',')
3854             n++;
3855     ost->forced_kf_count = n;
3856     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3857     if (!ost->forced_kf_pts) {
3858         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3859         exit_program(1);
3860     }
3861     for (i = 0; i < n; i++) {
3862         p = i ? strchr(p, ',') + 1 : kf;
3863         ost->forced_kf_pts[i] = parse_time_or_die("force_key_frames", p, 1);
3864     }
3865 }
3866
3867 static uint8_t *get_line(AVIOContext *s)
3868 {
3869     AVIOContext *line;
3870     uint8_t *buf;
3871     char c;
3872
3873     if (avio_open_dyn_buf(&line) < 0) {
3874         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
3875         exit_program(1);
3876     }
3877
3878     while ((c = avio_r8(s)) && c != '\n')
3879         avio_w8(line, c);
3880     avio_w8(line, 0);
3881     avio_close_dyn_buf(line, &buf);
3882
3883     return buf;
3884 }
3885
3886 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
3887 {
3888     int i, ret = 1;
3889     char filename[1000];
3890     const char *base[3] = { getenv("AVCONV_DATADIR"),
3891                             getenv("HOME"),
3892                             AVCONV_DATADIR,
3893                             };
3894
3895     for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
3896         if (!base[i])
3897             continue;
3898         if (codec_name) {
3899             snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
3900                      i != 1 ? "" : "/.avconv", codec_name, preset_name);
3901             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3902         }
3903         if (ret) {
3904             snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
3905                      i != 1 ? "" : "/.avconv", preset_name);
3906             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
3907         }
3908     }
3909     return ret;
3910 }
3911
3912 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
3913 {
3914     char *codec_name = NULL;
3915
3916     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
3917     if (!codec_name) {
3918         ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
3919                                                   NULL, ost->st->codec->codec_type);
3920         ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
3921     } else if (!strcmp(codec_name, "copy"))
3922         ost->stream_copy = 1;
3923     else {
3924         ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
3925         ost->st->codec->codec_id = ost->enc->id;
3926     }
3927 }
3928
3929 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
3930 {
3931     OutputStream *ost;
3932     AVStream *st = avformat_new_stream(oc, NULL);
3933     int idx      = oc->nb_streams - 1, ret = 0;
3934     char *bsf = NULL, *next, *codec_tag = NULL;
3935     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
3936     double qscale = -1;
3937     char *buf = NULL, *arg = NULL, *preset = NULL;
3938     AVIOContext *s = NULL;
3939
3940     if (!st) {
3941         av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
3942         exit_program(1);
3943     }
3944
3945     if (oc->nb_streams - 1 < o->nb_streamid_map)
3946         st->id = o->streamid_map[oc->nb_streams - 1];
3947
3948     output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
3949                                 nb_output_streams + 1);
3950     ost = &output_streams[nb_output_streams - 1];
3951     ost->file_index = nb_output_files;
3952     ost->index      = idx;
3953     ost->st         = st;
3954     st->codec->codec_type = type;
3955     choose_encoder(o, oc, ost);
3956     if (ost->enc) {
3957         ost->opts  = filter_codec_opts(codec_opts, ost->enc, oc, st);
3958     }
3959
3960     avcodec_get_context_defaults3(st->codec, ost->enc);
3961     st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
3962
3963     MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
3964     if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
3965         do  {
3966             buf = get_line(s);
3967             if (!buf[0] || buf[0] == '#') {
3968                 av_free(buf);
3969                 continue;
3970             }
3971             if (!(arg = strchr(buf, '='))) {
3972                 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
3973                 exit_program(1);
3974             }
3975             *arg++ = 0;
3976             av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
3977             av_free(buf);
3978         } while (!s->eof_reached);
3979         avio_close(s);
3980     }
3981     if (ret) {
3982         av_log(NULL, AV_LOG_FATAL,
3983                "Preset %s specified for stream %d:%d, but could not be opened.\n",
3984                preset, ost->file_index, ost->index);
3985         exit_program(1);
3986     }
3987
3988     ost->max_frames = INT64_MAX;
3989     MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
3990
3991     MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
3992     while (bsf) {
3993         if (next = strchr(bsf, ','))
3994             *next++ = 0;
3995         if (!(bsfc = av_bitstream_filter_init(bsf))) {
3996             av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
3997             exit_program(1);
3998         }
3999         if (bsfc_prev)
4000             bsfc_prev->next = bsfc;
4001         else
4002             ost->bitstream_filters = bsfc;
4003
4004         bsfc_prev = bsfc;
4005         bsf       = next;
4006     }
4007
4008     MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
4009     if (codec_tag) {
4010         uint32_t tag = strtol(codec_tag, &next, 0);
4011         if (*next)
4012             tag = AV_RL32(codec_tag);
4013         st->codec->codec_tag = tag;
4014     }
4015
4016     MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
4017     if (qscale >= 0 || same_quant) {
4018         st->codec->flags |= CODEC_FLAG_QSCALE;
4019         st->codec->global_quality = FF_QP2LAMBDA * qscale;
4020     }
4021
4022     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
4023         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
4024
4025     av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
4026     av_opt_get_int   (swr_opts, "dither_method", 0, &ost->swr_dither_method);
4027     av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
4028
4029     ost->source_index = source_index;
4030     if (source_index >= 0) {
4031         ost->sync_ist = &input_streams[source_index];
4032         input_streams[source_index].discard = 0;
4033         input_streams[source_index].st->discard = AVDISCARD_NONE;
4034     }
4035
4036     return ost;
4037 }
4038
4039 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
4040 {
4041     int i;
4042     const char *p = str;
4043     for (i = 0;; i++) {
4044         dest[i] = atoi(p);
4045         if (i == 63)
4046             break;
4047         p = strchr(p, ',');
4048         if (!p) {
4049             av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
4050             exit_program(1);
4051         }
4052         p++;
4053     }
4054 }
4055
4056 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4057 {
4058     AVStream *st;
4059     OutputStream *ost;
4060     AVCodecContext *video_enc;
4061
4062     ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
4063     st  = ost->st;
4064     video_enc = st->codec;
4065
4066     if (!ost->stream_copy) {
4067         const char *p = NULL;
4068         char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
4069         char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
4070         char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
4071         int i;
4072
4073         MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
4074         if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
4075             av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
4076             exit_program(1);
4077         }
4078
4079         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
4080         if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
4081             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
4082             exit_program(1);
4083         }
4084
4085         MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
4086         if (frame_aspect_ratio) {
4087             AVRational q;
4088             if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
4089                 q.num <= 0 || q.den <= 0) {
4090                 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
4091                 exit_program(1);
4092             }
4093             ost->frame_aspect_ratio = av_q2d(q);
4094         }
4095
4096         video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
4097         MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
4098         if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
4099             av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
4100             exit_program(1);
4101         }
4102         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
4103
4104         if (intra_only)
4105             video_enc->gop_size = 0;
4106         MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
4107         if (intra_matrix) {
4108             if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
4109                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
4110                 exit_program(1);
4111             }
4112             parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
4113         }
4114         MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
4115         if (inter_matrix) {
4116             if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
4117                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
4118                 exit_program(1);
4119             }
4120             parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
4121         }
4122
4123         MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
4124         for (i = 0; p; i++) {
4125             int start, end, q;
4126             int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
4127             if (e != 3) {
4128                 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
4129                 exit_program(1);
4130             }
4131             /* FIXME realloc failure */
4132             video_enc->rc_override =
4133                 av_realloc(video_enc->rc_override,
4134                            sizeof(RcOverride) * (i + 1));
4135             video_enc->rc_override[i].start_frame = start;
4136             video_enc->rc_override[i].end_frame   = end;
4137             if (q > 0) {
4138                 video_enc->rc_override[i].qscale         = q;
4139                 video_enc->rc_override[i].quality_factor = 1.0;
4140             }
4141             else {
4142                 video_enc->rc_override[i].qscale         = 0;
4143                 video_enc->rc_override[i].quality_factor = -q/100.0;
4144             }
4145             p = strchr(p, '/');
4146             if (p) p++;
4147         }
4148         video_enc->rc_override_count = i;
4149         if (!video_enc->rc_initial_buffer_occupancy)
4150             video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
4151         video_enc->intra_dc_precision = intra_dc_precision - 8;
4152
4153         if (do_psnr)
4154             video_enc->flags|= CODEC_FLAG_PSNR;
4155
4156         /* two pass mode */
4157         if (do_pass) {
4158             if (do_pass & 1) {
4159                 video_enc->flags |= CODEC_FLAG_PASS1;
4160             }
4161             if (do_pass & 2) {
4162                 video_enc->flags |= CODEC_FLAG_PASS2;
4163             }
4164         }
4165
4166         MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
4167         if (forced_key_frames)
4168             parse_forced_key_frames(forced_key_frames, ost);
4169
4170         MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
4171
4172         ost->top_field_first = -1;
4173         MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
4174
4175         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
4176         if (filters)
4177             ost->avfilter = av_strdup(filters);
4178     } else {
4179         MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
4180     }
4181
4182     return ost;
4183 }
4184
4185 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4186 {
4187     int n;
4188     AVStream *st;
4189     OutputStream *ost;
4190     AVCodecContext *audio_enc;
4191
4192     ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
4193     st  = ost->st;
4194
4195     audio_enc = st->codec;
4196     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
4197
4198     if (!ost->stream_copy) {
4199         char *sample_fmt = NULL;
4200
4201         MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
4202
4203         MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
4204         if (sample_fmt &&
4205             (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
4206             av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
4207             exit_program(1);
4208         }
4209
4210         MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
4211
4212         ost->rematrix_volume=1.0;
4213         MATCH_PER_STREAM_OPT(rematrix_volume, f, ost->rematrix_volume, oc, st);
4214     }
4215
4216     /* check for channel mapping for this audio stream */
4217     for (n = 0; n < o->nb_audio_channel_maps; n++) {
4218         AudioChannelMap *map = &o->audio_channel_maps[n];
4219         InputStream *ist = &input_streams[ost->source_index];
4220         if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
4221             (map->ofile_idx   == -1 || ost->file_index == map->ofile_idx) &&
4222             (map->ostream_idx == -1 || ost->st->index  == map->ostream_idx)) {
4223             if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
4224                 ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
4225             else
4226                 av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
4227                        ost->file_index, ost->st->index);
4228         }
4229     }
4230
4231     return ost;
4232 }
4233
4234 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4235 {
4236     OutputStream *ost;
4237
4238     ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
4239     if (!ost->stream_copy) {
4240         av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
4241         exit_program(1);
4242     }
4243
4244     return ost;
4245 }
4246
4247 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4248 {
4249     OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
4250     ost->stream_copy = 1;
4251     return ost;
4252 }
4253
4254 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4255 {
4256     AVStream *st;
4257     OutputStream *ost;
4258     AVCodecContext *subtitle_enc;
4259
4260     ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
4261     st  = ost->st;
4262     subtitle_enc = st->codec;
4263
4264     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
4265
4266     return ost;
4267 }
4268
4269 /* arg format is "output-stream-index:streamid-value". */
4270 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
4271 {
4272     int idx;
4273     char *p;
4274     char idx_str[16];
4275
4276     av_strlcpy(idx_str, arg, sizeof(idx_str));
4277     p = strchr(idx_str, ':');
4278     if (!p) {
4279         av_log(NULL, AV_LOG_FATAL,
4280                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
4281                arg, opt);
4282         exit_program(1);
4283     }
4284     *p++ = '\0';
4285     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
4286     o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
4287     o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
4288     return 0;
4289 }
4290
4291 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
4292 {
4293     AVFormatContext *is = ifile->ctx;
4294     AVFormatContext *os = ofile->ctx;
4295     int i;
4296
4297     for (i = 0; i < is->nb_chapters; i++) {
4298         AVChapter *in_ch = is->chapters[i], *out_ch;
4299         int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
4300                                        AV_TIME_BASE_Q, in_ch->time_base);
4301         int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
4302                            av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
4303
4304
4305         if (in_ch->end < ts_off)
4306             continue;
4307         if (rt != INT64_MAX && in_ch->start > rt + ts_off)
4308             break;
4309
4310         out_ch = av_mallocz(sizeof(AVChapter));
4311         if (!out_ch)
4312             return AVERROR(ENOMEM);
4313
4314         out_ch->id        = in_ch->id;
4315         out_ch->time_base = in_ch->time_base;
4316         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
4317         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
4318
4319         if (copy_metadata)
4320             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
4321
4322         os->nb_chapters++;
4323         os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
4324         if (!os->chapters)
4325             return AVERROR(ENOMEM);
4326         os->chapters[os->nb_chapters - 1] = out_ch;
4327     }
4328     return 0;
4329 }
4330
4331 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
4332 {
4333     int i, err;
4334     AVFormatContext *ic = avformat_alloc_context();
4335
4336     ic->interrupt_callback = int_cb;
4337     err = avformat_open_input(&ic, filename, NULL, NULL);
4338     if (err < 0)
4339         return err;
4340     /* copy stream format */
4341     for(i=0;i<ic->nb_streams;i++) {
4342         AVStream *st;
4343         OutputStream *ost;
4344         AVCodec *codec;
4345         AVCodecContext *avctx;
4346
4347         codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
4348         ost   = new_output_stream(o, s, codec->type, -1);
4349         st    = ost->st;
4350         avctx = st->codec;
4351         ost->enc = codec;
4352
4353         // FIXME: a more elegant solution is needed
4354         memcpy(st, ic->streams[i], sizeof(AVStream));
4355         st->cur_dts = 0;
4356         st->info = av_malloc(sizeof(*st->info));
4357         memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
4358         st->codec= avctx;
4359         avcodec_copy_context(st->codec, ic->streams[i]->codec);
4360
4361         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
4362             choose_sample_fmt(st, codec);
4363         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
4364             choose_pixel_fmt(st, codec);
4365     }
4366
4367     avformat_close_input(&ic);
4368     return 0;
4369 }
4370
4371 static void opt_output_file(void *optctx, const char *filename)
4372 {
4373     OptionsContext *o = optctx;
4374     AVFormatContext *oc;
4375     int i, err;
4376     AVOutputFormat *file_oformat;
4377     OutputStream *ost;
4378     InputStream  *ist;
4379
4380     if (!strcmp(filename, "-"))
4381         filename = "pipe:";
4382
4383     err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
4384     if (!oc) {
4385         print_error(filename, err);
4386         exit_program(1);
4387     }
4388     file_oformat= oc->oformat;
4389     oc->interrupt_callback = int_cb;
4390
4391     if (!strcmp(file_oformat->name, "ffm") &&
4392         av_strstart(filename, "http:", NULL)) {
4393         int j;
4394         /* special case for files sent to ffserver: we get the stream
4395            parameters from ffserver */
4396         int err = read_ffserver_streams(o, oc, filename);
4397         if (err < 0) {
4398             print_error(filename, err);
4399             exit_program(1);
4400         }
4401         for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
4402             ost = &output_streams[j];
4403             for (i = 0; i < nb_input_streams; i++) {
4404                 ist = &input_streams[i];
4405                 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
4406                     ost->sync_ist= ist;
4407                     ost->source_index= i;
4408                     ist->discard = 0;
4409                     ist->st->discard = AVDISCARD_NONE;
4410                     break;
4411                 }
4412             }
4413             if(!ost->sync_ist){
4414                 av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
4415                 exit_program(1);
4416             }
4417         }
4418     } else if (!o->nb_stream_maps) {
4419         /* pick the "best" stream of each type */
4420
4421         /* video: highest resolution */
4422         if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
4423             int area = 0, idx = -1;
4424             for (i = 0; i < nb_input_streams; i++) {
4425                 ist = &input_streams[i];
4426                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
4427                     ist->st->codec->width * ist->st->codec->height > area) {
4428                     area = ist->st->codec->width * ist->st->codec->height;
4429                     idx = i;
4430                 }
4431             }
4432             if (idx >= 0)
4433                 new_video_stream(o, oc, idx);
4434         }
4435
4436         /* audio: most channels */
4437         if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
4438             int channels = 0, idx = -1;
4439             for (i = 0; i < nb_input_streams; i++) {
4440                 ist = &input_streams[i];
4441                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
4442                     ist->st->codec->channels > channels) {
4443                     channels = ist->st->codec->channels;
4444                     idx = i;
4445                 }
4446             }
4447             if (idx >= 0)
4448                 new_audio_stream(o, oc, idx);
4449         }
4450
4451         /* subtitles: pick first */
4452         if (!o->subtitle_disable && (oc->oformat->subtitle_codec != CODEC_ID_NONE || subtitle_codec_name)) {
4453             for (i = 0; i < nb_input_streams; i++)
4454                 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
4455                     new_subtitle_stream(o, oc, i);
4456                     break;
4457                 }
4458         }
4459         /* do something with data? */
4460     } else {
4461         for (i = 0; i < o->nb_stream_maps; i++) {
4462             StreamMap *map = &o->stream_maps[i];
4463             int src_idx = input_files[map->file_index].ist_index + map->stream_index;
4464
4465             if (map->disabled)
4466                 continue;
4467
4468             ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
4469             if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
4470                 continue;
4471             if(o->   audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
4472                 continue;
4473             if(o->   video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
4474                 continue;
4475             if(o->    data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
4476                 continue;
4477
4478             switch (ist->st->codec->codec_type) {
4479             case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(o, oc, src_idx);    break;
4480             case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(o, oc, src_idx);    break;
4481             case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc, src_idx); break;
4482             case AVMEDIA_TYPE_DATA:     ost = new_data_stream(o, oc, src_idx);     break;
4483             case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
4484             default:
4485                 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
4486                        map->file_index, map->stream_index);
4487                 exit_program(1);
4488             }
4489         }
4490     }
4491
4492
4493     for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
4494         AVDictionaryEntry *e;
4495         ost = &output_streams[i];
4496
4497         if (   ost->stream_copy
4498             && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
4499             && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
4500             if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
4501                 exit_program(1);
4502     }
4503
4504     /* handle attached files */
4505     for (i = 0; i < o->nb_attachments; i++) {
4506         AVIOContext *pb;
4507         uint8_t *attachment;
4508         const char *p;
4509         int64_t len;
4510
4511         if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
4512             av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
4513                    o->attachments[i]);
4514             exit_program(1);
4515         }
4516         if ((len = avio_size(pb)) <= 0) {
4517             av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
4518                    o->attachments[i]);
4519             exit_program(1);
4520         }
4521         if (!(attachment = av_malloc(len))) {
4522             av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
4523                    o->attachments[i]);
4524             exit_program(1);
4525         }
4526         avio_read(pb, attachment, len);
4527
4528         ost = new_attachment_stream(o, oc, -1);
4529         ost->stream_copy               = 0;
4530         ost->attachment_filename       = o->attachments[i];
4531         ost->st->codec->extradata      = attachment;
4532         ost->st->codec->extradata_size = len;
4533
4534         p = strrchr(o->attachments[i], '/');
4535         av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
4536         avio_close(pb);
4537     }
4538
4539     output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
4540     output_files[nb_output_files - 1].ctx       = oc;
4541     output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
4542     output_files[nb_output_files - 1].recording_time = o->recording_time;
4543     if (o->recording_time != INT64_MAX)
4544         oc->duration = o->recording_time;
4545     output_files[nb_output_files - 1].start_time     = o->start_time;
4546     output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
4547     av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
4548
4549     /* check filename in case of an image number is expected */
4550     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
4551         if (!av_filename_number_test(oc->filename)) {
4552             print_error(oc->filename, AVERROR(EINVAL));
4553             exit_program(1);
4554         }
4555     }
4556
4557     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
4558         /* test if it already exists to avoid losing precious files */
4559         assert_file_overwrite(filename);
4560
4561         /* open the file */
4562         if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
4563                               &oc->interrupt_callback,
4564                               &output_files[nb_output_files - 1].opts)) < 0) {
4565             print_error(filename, err);
4566             exit_program(1);
4567         }
4568     }
4569
4570     if (o->mux_preload) {
4571         uint8_t buf[64];
4572         snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
4573         av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
4574     }
4575     oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
4576
4577     /* copy metadata */
4578     for (i = 0; i < o->nb_metadata_map; i++) {
4579         char *p;
4580         int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
4581
4582         if (in_file_index >= nb_input_files) {
4583             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
4584             exit_program(1);
4585         }
4586         copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index].ctx : NULL, o);
4587     }
4588
4589     /* copy chapters */
4590     if (o->chapters_input_file >= nb_input_files) {
4591         if (o->chapters_input_file == INT_MAX) {
4592             /* copy chapters from the first input file that has them*/
4593             o->chapters_input_file = -1;
4594             for (i = 0; i < nb_input_files; i++)
4595                 if (input_files[i].ctx->nb_chapters) {
4596                     o->chapters_input_file = i;
4597                     break;
4598                 }
4599         } else {
4600             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
4601                    o->chapters_input_file);
4602             exit_program(1);
4603         }
4604     }
4605     if (o->chapters_input_file >= 0)
4606         copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
4607                       !o->metadata_chapters_manual);
4608
4609     /* copy global metadata by default */
4610     if (!o->metadata_global_manual && nb_input_files){
4611         av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
4612                      AV_DICT_DONT_OVERWRITE);
4613         if(o->recording_time != INT64_MAX)
4614             av_dict_set(&oc->metadata, "duration", NULL, 0);
4615     }
4616     if (!o->metadata_streams_manual)
4617         for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
4618             InputStream *ist;
4619             if (output_streams[i].source_index < 0)         /* this is true e.g. for attached files */
4620                 continue;
4621             ist = &input_streams[output_streams[i].source_index];
4622             av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
4623         }
4624
4625     /* process manually set metadata */
4626     for (i = 0; i < o->nb_metadata; i++) {
4627         AVDictionary **m;
4628         char type, *val;
4629         const char *stream_spec;
4630         int index = 0, j, ret = 0;
4631
4632         val = strchr(o->metadata[i].u.str, '=');
4633         if (!val) {
4634             av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
4635                    o->metadata[i].u.str);
4636             exit_program(1);
4637         }
4638         *val++ = 0;
4639
4640         parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
4641         if (type == 's') {
4642             for (j = 0; j < oc->nb_streams; j++) {
4643                 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
4644                     av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
4645                 } else if (ret < 0)
4646                     exit_program(1);
4647             }
4648             printf("ret %d, stream_spec %s\n", ret, stream_spec);
4649         }
4650         else {
4651             switch (type) {
4652             case 'g':
4653                 m = &oc->metadata;
4654                 break;
4655             case 'c':
4656                 if (index < 0 || index >= oc->nb_chapters) {
4657                     av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
4658                     exit_program(1);
4659                 }
4660                 m = &oc->chapters[index]->metadata;
4661                 break;
4662             default:
4663                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
4664                 exit_program(1);
4665             }
4666             av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
4667         }
4668     }
4669
4670     reset_options(o, 0);
4671 }
4672
4673 /* same option as mencoder */
4674 static int opt_pass(const char *opt, const char *arg)
4675 {
4676     do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
4677     return 0;
4678 }
4679
4680 static int64_t getmaxrss(void)
4681 {
4682 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4683     struct rusage rusage;
4684     getrusage(RUSAGE_SELF, &rusage);
4685     return (int64_t)rusage.ru_maxrss * 1024;
4686 #elif HAVE_GETPROCESSMEMORYINFO
4687     HANDLE proc;
4688     PROCESS_MEMORY_COUNTERS memcounters;
4689     proc = GetCurrentProcess();
4690     memcounters.cb = sizeof(memcounters);
4691     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4692     return memcounters.PeakPagefileUsage;
4693 #else
4694     return 0;
4695 #endif
4696 }
4697
4698 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
4699 {
4700     return parse_option(o, "q:a", arg, options);
4701 }
4702
4703 static void show_usage(void)
4704 {
4705     av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
4706     av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
4707     av_log(NULL, AV_LOG_INFO, "\n");
4708 }
4709
4710 static int opt_help(const char *opt, const char *arg)
4711 {
4712     int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
4713     av_log_set_callback(log_callback_help);
4714     show_usage();
4715     show_help_options(options, "Main options:\n",
4716                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
4717     show_help_options(options, "\nAdvanced options:\n",
4718                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
4719                       OPT_EXPERT);
4720     show_help_options(options, "\nVideo options:\n",
4721                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4722                       OPT_VIDEO);
4723     show_help_options(options, "\nAdvanced Video options:\n",
4724                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4725                       OPT_VIDEO | OPT_EXPERT);
4726     show_help_options(options, "\nAudio options:\n",
4727                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4728                       OPT_AUDIO);
4729     show_help_options(options, "\nAdvanced Audio options:\n",
4730                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4731                       OPT_AUDIO | OPT_EXPERT);
4732     show_help_options(options, "\nSubtitle options:\n",
4733                       OPT_SUBTITLE | OPT_GRAB,
4734                       OPT_SUBTITLE);
4735     show_help_options(options, "\nAudio/Video grab options:\n",
4736                       OPT_GRAB,
4737                       OPT_GRAB);
4738     printf("\n");
4739     show_help_children(avcodec_get_class(), flags);
4740     show_help_children(avformat_get_class(), flags);
4741     show_help_children(sws_get_class(), flags);
4742
4743     return 0;
4744 }
4745
4746 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
4747 {
4748     enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
4749     static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
4750
4751     if (!strncmp(arg, "pal-", 4)) {
4752         norm = PAL;
4753         arg += 4;
4754     } else if (!strncmp(arg, "ntsc-", 5)) {
4755         norm = NTSC;
4756         arg += 5;
4757     } else if (!strncmp(arg, "film-", 5)) {
4758         norm = FILM;
4759         arg += 5;
4760     } else {
4761         /* Try to determine PAL/NTSC by peeking in the input files */
4762         if (nb_input_files) {
4763             int i, j, fr;
4764             for (j = 0; j < nb_input_files; j++) {
4765                 for (i = 0; i < input_files[j].nb_streams; i++) {
4766                     AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
4767                     if (c->codec_type != AVMEDIA_TYPE_VIDEO)
4768                         continue;
4769                     fr = c->time_base.den * 1000 / c->time_base.num;
4770                     if (fr == 25000) {
4771                         norm = PAL;
4772                         break;
4773                     } else if ((fr == 29970) || (fr == 23976)) {
4774                         norm = NTSC;
4775                         break;
4776                     }
4777                 }
4778                 if (norm != UNKNOWN)
4779                     break;
4780             }
4781         }
4782         if (norm != UNKNOWN)
4783             av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
4784     }
4785
4786     if (norm == UNKNOWN) {
4787         av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
4788         av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
4789         av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
4790         exit_program(1);
4791     }
4792
4793     if (!strcmp(arg, "vcd")) {
4794         opt_video_codec(o, "c:v", "mpeg1video");
4795         opt_audio_codec(o, "c:a", "mp2");
4796         parse_option(o, "f", "vcd", options);
4797
4798         parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
4799         parse_option(o, "r", frame_rates[norm], options);
4800         opt_default("g", norm == PAL ? "15" : "18");
4801
4802         opt_default("b:v", "1150000");
4803         opt_default("maxrate", "1150000");
4804         opt_default("minrate", "1150000");
4805         opt_default("bufsize", "327680"); // 40*1024*8;
4806
4807         opt_default("b:a", "224000");
4808         parse_option(o, "ar", "44100", options);
4809         parse_option(o, "ac", "2", options);
4810
4811         opt_default("packetsize", "2324");
4812         opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
4813
4814         /* We have to offset the PTS, so that it is consistent with the SCR.
4815            SCR starts at 36000, but the first two packs contain only padding
4816            and the first pack from the other stream, respectively, may also have
4817            been written before.
4818            So the real data starts at SCR 36000+3*1200. */
4819         o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
4820     } else if (!strcmp(arg, "svcd")) {
4821
4822         opt_video_codec(o, "c:v", "mpeg2video");
4823         opt_audio_codec(o, "c:a", "mp2");
4824         parse_option(o, "f", "svcd", options);
4825
4826         parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
4827         parse_option(o, "r", frame_rates[norm], options);
4828         parse_option(o, "pix_fmt", "yuv420p", options);
4829         opt_default("g", norm == PAL ? "15" : "18");
4830
4831         opt_default("b:v", "2040000");
4832         opt_default("maxrate", "2516000");
4833         opt_default("minrate", "0"); // 1145000;
4834         opt_default("bufsize", "1835008"); // 224*1024*8;
4835         opt_default("scan_offset", "1");
4836
4837
4838         opt_default("b:a", "224000");
4839         parse_option(o, "ar", "44100", options);
4840
4841         opt_default("packetsize", "2324");
4842
4843     } else if (!strcmp(arg, "dvd")) {
4844
4845         opt_video_codec(o, "c:v", "mpeg2video");
4846         opt_audio_codec(o, "c:a", "ac3");
4847         parse_option(o, "f", "dvd", options);
4848
4849         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4850         parse_option(o, "r", frame_rates[norm], options);
4851         parse_option(o, "pix_fmt", "yuv420p", options);
4852         opt_default("g", norm == PAL ? "15" : "18");
4853
4854         opt_default("b:v", "6000000");
4855         opt_default("maxrate", "9000000");
4856         opt_default("minrate", "0"); // 1500000;
4857         opt_default("bufsize", "1835008"); // 224*1024*8;
4858
4859         opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
4860         opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
4861
4862         opt_default("b:a", "448000");
4863         parse_option(o, "ar", "48000", options);
4864
4865     } else if (!strncmp(arg, "dv", 2)) {
4866
4867         parse_option(o, "f", "dv", options);
4868
4869         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
4870         parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
4871                           norm == PAL ? "yuv420p" : "yuv411p", options);
4872         parse_option(o, "r", frame_rates[norm], options);
4873
4874         parse_option(o, "ar", "48000", options);
4875         parse_option(o, "ac", "2", options);
4876
4877     } else {
4878         av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
4879         return AVERROR(EINVAL);
4880     }
4881     return 0;
4882 }
4883
4884 static int opt_vstats_file(const char *opt, const char *arg)
4885 {
4886     av_free (vstats_filename);
4887     vstats_filename = av_strdup (arg);
4888     return 0;
4889 }
4890
4891 static int opt_vstats(const char *opt, const char *arg)
4892 {
4893     char filename[40];
4894     time_t today2 = time(NULL);
4895     struct tm *today = localtime(&today2);
4896
4897     snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
4898              today->tm_sec);
4899     return opt_vstats_file(opt, filename);
4900 }
4901
4902 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
4903 {
4904     return parse_option(o, "frames:v", arg, options);
4905 }
4906
4907 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
4908 {
4909     return parse_option(o, "frames:a", arg, options);
4910 }
4911
4912 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
4913 {
4914     return parse_option(o, "frames:d", arg, options);
4915 }
4916
4917 static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
4918 {
4919     FILE *f=NULL;
4920     char filename[1000], tmp[1000], tmp2[1000], line[1000];
4921     const char *codec_name = *opt == 'v' ? video_codec_name :
4922                              *opt == 'a' ? audio_codec_name :
4923                                            subtitle_codec_name;
4924
4925     if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
4926         if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
4927             av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
4928         }else
4929             av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
4930         exit_program(1);
4931     }
4932
4933     while(!feof(f)){
4934         int e= fscanf(f, "%999[^\n]\n", line) - 1;
4935         if(line[0] == '#' && !e)
4936             continue;
4937         e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
4938         if(e){
4939             av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
4940             exit_program(1);
4941         }
4942         if(!strcmp(tmp, "acodec")){
4943             opt_audio_codec(o, tmp, tmp2);
4944         }else if(!strcmp(tmp, "vcodec")){
4945             opt_video_codec(o, tmp, tmp2);
4946         }else if(!strcmp(tmp, "scodec")){
4947             opt_subtitle_codec(o, tmp, tmp2);
4948         }else if(!strcmp(tmp, "dcodec")){
4949             opt_data_codec(o, tmp, tmp2);
4950         }else if(opt_default(tmp, tmp2) < 0){
4951             av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
4952             exit_program(1);
4953         }
4954     }
4955
4956     fclose(f);
4957
4958     return 0;
4959 }
4960
4961 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
4962 {
4963 }
4964
4965 static int opt_passlogfile(const char *opt, const char *arg)
4966 {
4967     pass_logfilename_prefix = arg;
4968 #if CONFIG_LIBX264_ENCODER
4969     return opt_default(opt, arg);
4970 #else
4971     return 0;
4972 #endif
4973 }
4974
4975 static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
4976 {
4977     char *s = av_asprintf("%s:%c", opt + 1, *opt);
4978     int ret = parse_option(o, s, arg, options);
4979     av_free(s);
4980     return ret;
4981 }
4982
4983 static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
4984 {
4985     if(!strcmp(opt, "b")){
4986         av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
4987         return parse_option(o, "b:v", arg, options);
4988     }
4989     return opt_default(opt, arg);
4990 }
4991
4992 static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
4993 {
4994     char *s;
4995     int ret;
4996     if(!strcmp(opt, "qscale")){
4997         av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
4998         return parse_option(o, "q:v", arg, options);
4999     }
5000     s = av_asprintf("q%s", opt + 6);
5001     ret = parse_option(o, s, arg, options);
5002     av_free(s);
5003     return ret;
5004 }
5005
5006 static int opt_profile(OptionsContext *o, const char *opt, const char *arg)
5007 {
5008     if(!strcmp(opt, "profile")){
5009         av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
5010         return parse_option(o, "profile:v", arg, options);
5011     }
5012     return opt_default(opt, arg);
5013 }
5014
5015 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
5016 {
5017     return parse_option(o, "filter:v", arg, options);
5018 }
5019
5020 static int opt_vsync(const char *opt, const char *arg)
5021 {
5022     if      (!av_strcasecmp(arg, "cfr"))         video_sync_method = VSYNC_CFR;
5023     else if (!av_strcasecmp(arg, "vfr"))         video_sync_method = VSYNC_VFR;
5024     else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
5025     else if (!av_strcasecmp(arg, "drop"))        video_sync_method = VSYNC_DROP;
5026
5027     if (video_sync_method == VSYNC_AUTO)
5028         video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
5029     return 0;
5030 }
5031
5032 static int opt_deinterlace(const char *opt, const char *arg)
5033 {
5034     av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
5035     do_deinterlace = 1;
5036     return 0;
5037 }
5038
5039 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
5040 {
5041     int idx = locate_option(argc, argv, options, "cpuflags");
5042     if (idx && argv[idx + 1])
5043         opt_cpuflags("cpuflags", argv[idx + 1]);
5044 }
5045
5046 static int opt_channel_layout(OptionsContext *o, const char *opt, const char *arg)
5047 {
5048     char layout_str[32];
5049     char *stream_str;
5050     char *ac_str;
5051     int ret, channels, ac_str_size;
5052     uint64_t layout;
5053
5054     layout = av_get_channel_layout(arg);
5055     if (!layout) {
5056         av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
5057         return AVERROR(EINVAL);
5058     }
5059     snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
5060     ret = opt_default(opt, layout_str);
5061     if (ret < 0)
5062         return ret;
5063
5064     /* set 'ac' option based on channel layout */
5065     channels = av_get_channel_layout_nb_channels(layout);
5066     snprintf(layout_str, sizeof(layout_str), "%d", channels);
5067     stream_str = strchr(opt, ':');
5068     ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
5069     ac_str = av_mallocz(ac_str_size);
5070     if (!ac_str)
5071         return AVERROR(ENOMEM);
5072     av_strlcpy(ac_str, "ac", 3);
5073     if (stream_str)
5074         av_strlcat(ac_str, stream_str, ac_str_size);
5075     ret = parse_option(o, ac_str, layout_str, options);
5076     av_free(ac_str);
5077
5078     return ret;
5079 }
5080
5081 #define OFFSET(x) offsetof(OptionsContext, x)
5082 static const OptionDef options[] = {
5083     /* main options */
5084 #include "cmdutils_common_opts.h"
5085     { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
5086     { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
5087     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
5088     { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
5089     { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5090     { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
5091     { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
5092     { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5093     { "map_channel", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_channel}, "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
5094     { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
5095       "outfile[,metadata]:infile[,metadata]" },
5096     { "map_chapters",  OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)},  "set chapters mapping", "input_file_index" },
5097     { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
5098     { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
5099     { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
5100     { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
5101     { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
5102     { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
5103     { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
5104     { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
5105     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
5106       "add timings for benchmarking" },
5107     { "benchmark_all", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark_all},
5108       "add timings for each task" },
5109     { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
5110     { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
5111       "dump each input packet" },
5112     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
5113       "when dumping packets, also dump the payload" },
5114     { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
5115     { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
5116     { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
5117     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
5118     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
5119     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
5120     { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying", "mode" },
5121     { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
5122     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
5123     { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_error_threshold}, "timestamp error delta threshold", "threshold" },
5124     { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
5125     { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
5126     { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
5127     { "tag",   OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
5128     { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
5129     { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
5130     { "profile", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_profile}, "set profile", "profile" },
5131     { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
5132     { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
5133     { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
5134     { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
5135     { "debug_ts", OPT_BOOL | OPT_EXPERT, {&debug_ts}, "print timestamp debugging info" },
5136
5137     /* video options */
5138     { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
5139     { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
5140     { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
5141     { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
5142     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
5143     { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
5144     { "croptop",  HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5145     { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5146     { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5147     { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
5148     { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5149     { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5150     { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5151     { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
5152     { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
5153     { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "deprecated use -g 1"},
5154     { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
5155     { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
5156     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
5157     { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
5158     { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
5159     { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
5160       "use same quantizer as source (implies VBR)" },
5161     { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
5162     { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
5163     { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
5164       "this option is deprecated, use the yadif filter instead" },
5165     { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
5166     { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
5167     { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
5168     { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
5169     { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
5170     { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
5171     { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
5172     { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
5173     { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
5174     { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
5175     { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
5176     { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
5177     { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
5178     { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
5179
5180     /* audio options */
5181     { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
5182     { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
5183     { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
5184     { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
5185     { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
5186     { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
5187     { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
5188     { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
5189     { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
5190     { "rmvol", HAS_ARG | OPT_AUDIO | OPT_FLOAT | OPT_SPEC, {.off = OFFSET(rematrix_volume)}, "rematrix volume (as factor)", "volume" },
5191     { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
5192
5193     /* subtitle options */
5194     { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
5195     { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
5196     { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
5197
5198     /* grab options */
5199     { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
5200     { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
5201     { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
5202
5203     /* muxer options */
5204     { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT   | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
5205     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)},   "set the initial demux-decode delay", "seconds" },
5206
5207     { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
5208     { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
5209     { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
5210
5211     { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
5212     { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
5213     { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
5214     { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
5215     /* data codec support */
5216     { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
5217     { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
5218
5219     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
5220     { NULL, },
5221 };
5222
5223 int main(int argc, char **argv)
5224 {
5225     OptionsContext o = { 0 };
5226     int64_t ti;
5227
5228     reset_options(&o, 0);
5229
5230     av_log_set_flags(AV_LOG_SKIP_REPEATED);
5231     parse_loglevel(argc, argv, options);
5232
5233     if(argc>1 && !strcmp(argv[1], "-d")){
5234         run_as_daemon=1;
5235         av_log_set_callback(log_callback_null);
5236         argc--;
5237         argv++;
5238     }
5239
5240     avcodec_register_all();
5241 #if CONFIG_AVDEVICE
5242     avdevice_register_all();
5243 #endif
5244     avfilter_register_all();
5245     av_register_all();
5246     avformat_network_init();
5247
5248     show_banner(argc, argv, options);
5249
5250     term_init();
5251
5252     parse_cpuflags(argc, argv, options);
5253
5254     /* parse options */
5255     parse_options(&o, argc, argv, options, opt_output_file);
5256
5257     if (nb_output_files <= 0 && nb_input_files == 0) {
5258         show_usage();
5259         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
5260         exit_program(1);
5261     }
5262
5263     /* file converter / grab */
5264     if (nb_output_files <= 0) {
5265         av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
5266         exit_program(1);
5267     }
5268
5269     if (nb_input_files == 0) {
5270         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
5271         exit_program(1);
5272     }
5273
5274     current_time = ti = getutime();
5275     if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
5276         exit_program(1);
5277     ti = getutime() - ti;
5278     if (do_benchmark) {
5279         int maxrss = getmaxrss() / 1024;
5280         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
5281     }
5282
5283     exit_program(0);
5284     return 0;
5285 }