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