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