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