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