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