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