fa2c444664816ec5b0595f482606480c1fb1932b
[ffmpeg.git] / 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
2118     while (1) {
2119         /* Reap all buffers present in the buffer sinks */
2120         for (i = 0; i < nb_output_streams; i++) {
2121             OutputStream *ost = output_streams[i];
2122             OutputFile    *of = output_files[ost->file_index];
2123
2124             if (!ost->filter || ost->is_past_recording_time)
2125                 continue;
2126
2127             if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
2128                 return AVERROR(ENOMEM);
2129             } else
2130                 avcodec_get_frame_defaults(ost->filtered_frame);
2131             filtered_frame = ost->filtered_frame;
2132
2133             while (1) {
2134                 AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
2135                 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
2136                                                    AV_BUFFERSINK_FLAG_NO_REQUEST);
2137                 if (ret < 0) {
2138                     if (ret != AVERROR(EAGAIN)) {
2139                         char buf[256];
2140                         av_strerror(ret, buf, sizeof(buf));
2141                         av_log(NULL, AV_LOG_WARNING,
2142                                "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
2143                     }
2144                     break;
2145                 }
2146                 filtered_frame->pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2147                 //if (ost->source_index >= 0)
2148                 //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
2149
2150                 if (of->start_time && filtered_frame->pts < of->start_time)
2151                     return 0;
2152
2153                 switch (ost->filter->filter->inputs[0]->type) {
2154                 case AVMEDIA_TYPE_VIDEO:
2155                     avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2156                     if (!ost->frame_aspect_ratio)
2157                         ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2158
2159                     do_video_out(of->ctx, ost, filtered_frame,
2160                                  same_quant ? ost->last_quality :
2161                                               ost->st->codec->global_quality);
2162                     break;
2163                 default:
2164                     // TODO support audio/subtitle filters
2165                     av_assert0(0);
2166                 }
2167
2168                 avfilter_unref_buffer(picref);
2169             }
2170         }
2171         /* Request frames through all the graphs */
2172         ret_all = nb_success = nb_eof = 0;
2173         for (i = 0; i < nb_filtergraphs; i++) {
2174             ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
2175             if (!ret) {
2176                 nb_success++;
2177             } else if (ret == AVERROR_EOF) {
2178                 nb_eof++;
2179             } else if (ret != AVERROR(EAGAIN)) {
2180                 char buf[256];
2181                 av_strerror(ret, buf, sizeof(buf));
2182                 av_log(NULL, AV_LOG_WARNING,
2183                        "Error in request_frame(): %s\n", buf);
2184                 ret_all = ret;
2185             }
2186         }
2187         if (!nb_success)
2188             break;
2189         /* Try again if anything succeeded */
2190     }
2191     return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
2192 }
2193
2194 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
2195 {
2196     char buf[1024];
2197     OutputStream *ost;
2198     AVFormatContext *oc;
2199     int64_t total_size;
2200     AVCodecContext *enc;
2201     int frame_number, vid, i;
2202     double bitrate;
2203     int64_t pts = INT64_MAX;
2204     static int64_t last_time = -1;
2205     static int qp_histogram[52];
2206     int hours, mins, secs, us;
2207
2208     if (!print_stats && !is_last_report)
2209         return;
2210
2211     if (!is_last_report) {
2212         if (last_time == -1) {
2213             last_time = cur_time;
2214             return;
2215         }
2216         if ((cur_time - last_time) < 500000)
2217             return;
2218         last_time = cur_time;
2219     }
2220
2221
2222     oc = output_files[0]->ctx;
2223
2224     total_size = avio_size(oc->pb);
2225     if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
2226         total_size = avio_tell(oc->pb);
2227         if (total_size < 0)
2228             total_size = 0;
2229     }
2230
2231     buf[0] = '\0';
2232     vid = 0;
2233     for (i = 0; i < nb_output_streams; i++) {
2234         float q = -1;
2235         ost = output_streams[i];
2236         enc = ost->st->codec;
2237         if (!ost->stream_copy && enc->coded_frame)
2238             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
2239         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2240             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
2241         }
2242         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2243             float fps, t = (cur_time-timer_start) / 1000000.0;
2244
2245             frame_number = ost->frame_number;
2246             fps = t > 1 ? frame_number / t : 0;
2247             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
2248                      frame_number, fps < 9.95, fps, q);
2249             if (is_last_report)
2250                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
2251             if (qp_hist) {
2252                 int j;
2253                 int qp = lrintf(q);
2254                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
2255                     qp_histogram[qp]++;
2256                 for (j = 0; j < 32; j++)
2257                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
2258             }
2259             if (enc->flags&CODEC_FLAG_PSNR) {
2260                 int j;
2261                 double error, error_sum = 0;
2262                 double scale, scale_sum = 0;
2263                 char type[3] = { 'Y','U','V' };
2264                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
2265                 for (j = 0; j < 3; j++) {
2266                     if (is_last_report) {
2267                         error = enc->error[j];
2268                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
2269                     } else {
2270                         error = enc->coded_frame->error[j];
2271                         scale = enc->width * enc->height * 255.0 * 255.0;
2272                     }
2273                     if (j)
2274                         scale /= 4;
2275                     error_sum += error;
2276                     scale_sum += scale;
2277                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
2278                 }
2279                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
2280             }
2281             vid = 1;
2282         }
2283         /* compute min output value */
2284         pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
2285                                       ost->st->time_base, AV_TIME_BASE_Q));
2286     }
2287
2288     secs = pts / AV_TIME_BASE;
2289     us = pts % AV_TIME_BASE;
2290     mins = secs / 60;
2291     secs %= 60;
2292     hours = mins / 60;
2293     mins %= 60;
2294
2295     bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
2296
2297     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2298              "size=%8.0fkB time=", total_size / 1024.0);
2299     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2300              "%02d:%02d:%02d.%02d ", hours, mins, secs,
2301              (100 * us) / AV_TIME_BASE);
2302     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2303              "bitrate=%6.1fkbits/s", bitrate);
2304
2305     if (nb_frames_dup || nb_frames_drop)
2306         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
2307                 nb_frames_dup, nb_frames_drop);
2308
2309     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
2310
2311     fflush(stderr);
2312
2313     if (is_last_report) {
2314         int64_t raw= audio_size + video_size + extra_size;
2315         av_log(NULL, AV_LOG_INFO, "\n");
2316         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
2317                video_size / 1024.0,
2318                audio_size / 1024.0,
2319                extra_size / 1024.0,
2320                100.0 * (total_size - raw) / raw
2321         );
2322         if(video_size + audio_size + extra_size == 0){
2323             av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
2324         }
2325     }
2326 }
2327
2328 static void flush_encoders(void)
2329 {
2330     int i, ret;
2331
2332     for (i = 0; i < nb_output_streams; i++) {
2333         OutputStream   *ost = output_streams[i];
2334         AVCodecContext *enc = ost->st->codec;
2335         AVFormatContext *os = output_files[ost->file_index]->ctx;
2336         int stop_encoding = 0;
2337
2338         if (!ost->encoding_needed)
2339             continue;
2340
2341         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2342             continue;
2343         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
2344             continue;
2345
2346         for (;;) {
2347             AVPacket pkt;
2348             int fifo_bytes, got_packet;
2349             av_init_packet(&pkt);
2350             pkt.data = NULL;
2351             pkt.size = 0;
2352
2353             switch (ost->st->codec->codec_type) {
2354             case AVMEDIA_TYPE_AUDIO:
2355                 fifo_bytes = av_fifo_size(ost->fifo);
2356                 if (fifo_bytes > 0) {
2357                     /* encode any samples remaining in fifo */
2358                     int frame_bytes = fifo_bytes;
2359
2360                     av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
2361
2362                     encode_audio_frame(os, ost, audio_buf, frame_bytes);
2363                 } else {
2364                     /* flush encoder with NULL frames until it is done
2365                        returning packets */
2366                     if (encode_audio_frame(os, ost, NULL, 0) == 0) {
2367                         stop_encoding = 1;
2368                         break;
2369                     }
2370                 }
2371                 break;
2372             case AVMEDIA_TYPE_VIDEO:
2373                 update_benchmark(NULL);
2374                 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
2375                 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2376                 if (ret < 0) {
2377                     av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2378                     exit_program(1);
2379                 }
2380                 video_size += pkt.size;
2381                 if (ost->logfile && enc->stats_out) {
2382                     fprintf(ost->logfile, "%s", enc->stats_out);
2383                 }
2384                 if (!got_packet) {
2385                     stop_encoding = 1;
2386                     break;
2387                 }
2388                 if (pkt.pts != AV_NOPTS_VALUE)
2389                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2390                 if (pkt.dts != AV_NOPTS_VALUE)
2391                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2392                 write_frame(os, &pkt, ost);
2393                 break;
2394             default:
2395                 stop_encoding = 1;
2396             }
2397             if (stop_encoding)
2398                 break;
2399         }
2400     }
2401 }
2402
2403 /*
2404  * Check whether a packet from ist should be written into ost at this time
2405  */
2406 static int check_output_constraints(InputStream *ist, OutputStream *ost)
2407 {
2408     OutputFile *of = output_files[ost->file_index];
2409     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
2410
2411     if (ost->source_index != ist_index)
2412         return 0;
2413
2414     if (of->start_time && ist->pts < of->start_time)
2415         return 0;
2416
2417     if (of->recording_time != INT64_MAX &&
2418         av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
2419                       (AVRational){ 1, 1000000 }) >= 0) {
2420         ost->is_past_recording_time = 1;
2421         return 0;
2422     }
2423
2424     return 1;
2425 }
2426
2427 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2428 {
2429     OutputFile *of = output_files[ost->file_index];
2430     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2431     AVPicture pict;
2432     AVPacket opkt;
2433
2434     av_init_packet(&opkt);
2435
2436     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2437         !ost->copy_initial_nonkeyframes)
2438         return;
2439
2440     /* force the input stream PTS */
2441     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2442         audio_size += pkt->size;
2443     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2444         video_size += pkt->size;
2445         ost->sync_opts++;
2446     }
2447
2448     if (pkt->pts != AV_NOPTS_VALUE)
2449         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2450     else
2451         opkt.pts = AV_NOPTS_VALUE;
2452
2453     if (pkt->dts == AV_NOPTS_VALUE)
2454         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
2455     else
2456         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2457     opkt.dts -= ost_tb_start_time;
2458
2459     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2460     opkt.flags    = pkt->flags;
2461
2462     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2463     if (  ost->st->codec->codec_id != CODEC_ID_H264
2464        && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2465        && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
2466        && ost->st->codec->codec_id != CODEC_ID_VC1
2467        ) {
2468         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2469             opkt.destruct = av_destruct_packet;
2470     } else {
2471         opkt.data = pkt->data;
2472         opkt.size = pkt->size;
2473     }
2474     if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
2475         /* store AVPicture in AVPacket, as expected by the output format */
2476         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
2477         opkt.data = (uint8_t *)&pict;
2478         opkt.size = sizeof(AVPicture);
2479         opkt.flags |= AV_PKT_FLAG_KEY;
2480     }
2481
2482     write_frame(of->ctx, &opkt, ost);
2483     ost->st->codec->frame_number++;
2484     av_free_packet(&opkt);
2485 }
2486
2487 static void rate_emu_sleep(InputStream *ist)
2488 {
2489     if (input_files[ist->file_index]->rate_emu) {
2490         int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2491         int64_t now = av_gettime() - ist->start;
2492         if (pts > now)
2493             usleep(pts - now);
2494     }
2495 }
2496
2497 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2498 {
2499     AVFrame *decoded_frame;
2500     AVCodecContext *avctx = ist->st->codec;
2501     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
2502     int i, ret;
2503
2504     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2505         return AVERROR(ENOMEM);
2506     else
2507         avcodec_get_frame_defaults(ist->decoded_frame);
2508     decoded_frame = ist->decoded_frame;
2509
2510     update_benchmark(NULL);
2511     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2512     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2513     if (ret < 0) {
2514         return ret;
2515     }
2516     if (avctx->sample_rate <= 0) {
2517         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2518         return AVERROR_INVALIDDATA;
2519     }
2520
2521     if (!*got_output) {
2522         /* no audio frame */
2523         return ret;
2524     }
2525
2526     /* if the decoder provides a pts, use it instead of the last packet pts.
2527        the decoder could be delaying output by a packet or more. */
2528     if (decoded_frame->pts != AV_NOPTS_VALUE)
2529         ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2530
2531     /* increment next_dts to use for the case where the input stream does not
2532        have timestamps or there are multiple frames in the packet */
2533     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2534                      avctx->sample_rate;
2535     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2536                      avctx->sample_rate;
2537
2538
2539     // preprocess audio (volume)
2540     if (audio_volume != 256) {
2541         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2542         void *samples = decoded_frame->data[0];
2543         switch (avctx->sample_fmt) {
2544         case AV_SAMPLE_FMT_U8:
2545         {
2546             uint8_t *volp = samples;
2547             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2548                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2549                 *volp++ = av_clip_uint8(v);
2550             }
2551             break;
2552         }
2553         case AV_SAMPLE_FMT_S16:
2554         {
2555             int16_t *volp = samples;
2556             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2557                 int v = ((*volp) * audio_volume + 128) >> 8;
2558                 *volp++ = av_clip_int16(v);
2559             }
2560             break;
2561         }
2562         case AV_SAMPLE_FMT_S32:
2563         {
2564             int32_t *volp = samples;
2565             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2566                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2567                 *volp++ = av_clipl_int32(v);
2568             }
2569             break;
2570         }
2571         case AV_SAMPLE_FMT_FLT:
2572         {
2573             float *volp = samples;
2574             float scale = audio_volume / 256.f;
2575             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2576                 *volp++ *= scale;
2577             }
2578             break;
2579         }
2580         case AV_SAMPLE_FMT_DBL:
2581         {
2582             double *volp = samples;
2583             double scale = audio_volume / 256.;
2584             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2585                 *volp++ *= scale;
2586             }
2587             break;
2588         }
2589         default:
2590             av_log(NULL, AV_LOG_FATAL,
2591                    "Audio volume adjustment on sample format %s is not supported.\n",
2592                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2593             exit_program(1);
2594         }
2595     }
2596
2597     rate_emu_sleep(ist);
2598
2599     for (i = 0; i < nb_output_streams; i++) {
2600         OutputStream *ost = output_streams[i];
2601
2602         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2603             continue;
2604         do_audio_out(output_files[ost->file_index]->ctx, ost, ist, decoded_frame);
2605     }
2606
2607     return ret;
2608 }
2609
2610 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2611 {
2612     AVFrame *decoded_frame;
2613     void *buffer_to_free = NULL;
2614     int i, ret = 0, resample_changed;
2615     int64_t best_effort_timestamp;
2616     AVRational *frame_sample_aspect;
2617     float quality;
2618
2619     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2620         return AVERROR(ENOMEM);
2621     else
2622         avcodec_get_frame_defaults(ist->decoded_frame);
2623     decoded_frame = ist->decoded_frame;
2624     pkt->pts  = *pkt_pts;
2625     pkt->dts  = ist->dts;
2626     *pkt_pts  = AV_NOPTS_VALUE;
2627
2628     update_benchmark(NULL);
2629     ret = avcodec_decode_video2(ist->st->codec,
2630                                 decoded_frame, got_output, pkt);
2631     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2632     if (ret < 0)
2633         return ret;
2634
2635     quality = same_quant ? decoded_frame->quality : 0;
2636     if (!*got_output) {
2637         /* no picture yet */
2638         if (!pkt->size)
2639             for (i = 0; i < ist->nb_filters; i++)
2640                 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
2641         return ret;
2642     }
2643
2644     best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
2645     if(best_effort_timestamp != AV_NOPTS_VALUE)
2646         ist->next_pts = ist->pts = decoded_frame->pts = best_effort_timestamp;
2647
2648     pkt->size = 0;
2649
2650     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2651
2652     rate_emu_sleep(ist);
2653
2654     if (ist->st->sample_aspect_ratio.num)
2655         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2656
2657     resample_changed = ist->resample_width   != decoded_frame->width  ||
2658                        ist->resample_height  != decoded_frame->height ||
2659                        ist->resample_pix_fmt != decoded_frame->format;
2660     if (resample_changed) {
2661         av_log(NULL, AV_LOG_INFO,
2662                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2663                ist->file_index, ist->st->index,
2664                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
2665                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2666
2667         ist->resample_width   = decoded_frame->width;
2668         ist->resample_height  = decoded_frame->height;
2669         ist->resample_pix_fmt = decoded_frame->format;
2670
2671         for (i = 0; i < nb_filtergraphs; i++)
2672             if (ist_in_filtergraph(filtergraphs[i], ist) &&
2673                 configure_filtergraph(filtergraphs[i]) < 0) {
2674                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2675                 exit_program(1);
2676             }
2677     }
2678
2679     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2680     for (i = 0; i < ist->nb_filters; i++) {
2681         int changed =      ist->st->codec->width   != ist->filters[i]->filter->outputs[0]->w
2682                         || ist->st->codec->height  != ist->filters[i]->filter->outputs[0]->h
2683                         || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
2684         // XXX what an ugly hack
2685         if (ist->filters[i]->graph->nb_outputs == 1)
2686             ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2687
2688         if (!frame_sample_aspect->num)
2689             *frame_sample_aspect = ist->st->sample_aspect_ratio;
2690         if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2691             FrameBuffer      *buf = decoded_frame->opaque;
2692             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2693                                         decoded_frame->data, decoded_frame->linesize,
2694                                         AV_PERM_READ | AV_PERM_PRESERVE,
2695                                         ist->st->codec->width, ist->st->codec->height,
2696                                         ist->st->codec->pix_fmt);
2697
2698             avfilter_copy_frame_props(fb, decoded_frame);
2699             fb->buf->priv           = buf;
2700             fb->buf->free           = filter_release_buffer;
2701
2702             av_assert0(buf->refcount>0);
2703             buf->refcount++;
2704             av_buffersrc_add_ref(ist->filters[i]->filter, fb,
2705                                  AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
2706                                  AV_BUFFERSRC_FLAG_NO_COPY);
2707         } else
2708         if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
2709             av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2710             exit_program(1);
2711         }
2712
2713     }
2714
2715     av_free(buffer_to_free);
2716     return ret;
2717 }
2718
2719 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2720 {
2721     AVSubtitle subtitle;
2722     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2723                                           &subtitle, got_output, pkt);
2724     if (ret < 0)
2725         return ret;
2726     if (!*got_output)
2727         return ret;
2728
2729     rate_emu_sleep(ist);
2730
2731     for (i = 0; i < nb_output_streams; i++) {
2732         OutputStream *ost = output_streams[i];
2733
2734         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2735             continue;
2736
2737         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2738     }
2739
2740     avsubtitle_free(&subtitle);
2741     return ret;
2742 }
2743
2744 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2745 static int output_packet(InputStream *ist, const AVPacket *pkt)
2746 {
2747     int ret = 0, i;
2748     int got_output;
2749     int64_t pkt_pts = AV_NOPTS_VALUE;
2750
2751     AVPacket avpkt;
2752     if (!ist->saw_first_ts) {
2753         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;
2754         ist->pts = 0;
2755         if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2756             ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2757             ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2758         }
2759         ist->saw_first_ts = 1;
2760     }
2761
2762     if (ist->next_dts == AV_NOPTS_VALUE)
2763         ist->next_dts = ist->dts;
2764     if (ist->next_pts == AV_NOPTS_VALUE)
2765         ist->next_pts = ist->pts;
2766
2767     if (pkt == NULL) {
2768         /* EOF handling */
2769         av_init_packet(&avpkt);
2770         avpkt.data = NULL;
2771         avpkt.size = 0;
2772         goto handle_eof;
2773     } else {
2774         avpkt = *pkt;
2775     }
2776
2777     if (pkt->dts != AV_NOPTS_VALUE) {
2778         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2779         if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2780             ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2781     }
2782     if(pkt->pts != AV_NOPTS_VALUE)
2783         pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2784
2785     // while we have more to decode or while the decoder did output something on EOF
2786     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2787         int duration;
2788     handle_eof:
2789
2790         ist->pts = ist->next_pts;
2791         ist->dts = ist->next_dts;
2792
2793         if (avpkt.size && avpkt.size != pkt->size) {
2794             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2795                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2796             ist->showed_multi_packet_warning = 1;
2797         }
2798
2799         switch (ist->st->codec->codec_type) {
2800         case AVMEDIA_TYPE_AUDIO:
2801             ret = transcode_audio    (ist, &avpkt, &got_output);
2802             break;
2803         case AVMEDIA_TYPE_VIDEO:
2804             ret = transcode_video    (ist, &avpkt, &got_output, &pkt_pts);
2805             if (avpkt.duration) {
2806                 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2807             } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2808                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2809                 duration = ((int64_t)AV_TIME_BASE *
2810                                 ist->st->codec->time_base.num * ticks) /
2811                                 ist->st->codec->time_base.den;
2812             } else
2813                 duration = 0;
2814
2815             if(ist->dts != AV_NOPTS_VALUE && duration) {
2816                 ist->next_dts += duration;
2817             }else
2818                 ist->next_dts = AV_NOPTS_VALUE;
2819
2820             if (got_output)
2821                 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2822             break;
2823         case AVMEDIA_TYPE_SUBTITLE:
2824             ret = transcode_subtitles(ist, &avpkt, &got_output);
2825             break;
2826         default:
2827             return -1;
2828         }
2829
2830         if (ret < 0)
2831             return ret;
2832
2833         avpkt.dts=
2834         avpkt.pts= AV_NOPTS_VALUE;
2835
2836         // touch data and size only if not EOF
2837         if (pkt) {
2838             if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2839                 ret = avpkt.size;
2840             avpkt.data += ret;
2841             avpkt.size -= ret;
2842         }
2843         if (!got_output) {
2844             continue;
2845         }
2846     }
2847
2848     /* handle stream copy */
2849     if (!ist->decoding_needed) {
2850         rate_emu_sleep(ist);
2851         ist->dts = ist->next_dts;
2852         switch (ist->st->codec->codec_type) {
2853         case AVMEDIA_TYPE_AUDIO:
2854             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2855                              ist->st->codec->sample_rate;
2856             break;
2857         case AVMEDIA_TYPE_VIDEO:
2858             if (pkt->duration) {
2859                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2860             } else if(ist->st->codec->time_base.num != 0) {
2861                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2862                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2863                                   ist->st->codec->time_base.num * ticks) /
2864                                   ist->st->codec->time_base.den;
2865             }
2866             break;
2867         }
2868         ist->pts = ist->dts;
2869         ist->next_pts = ist->next_dts;
2870     }
2871     for (i = 0; pkt && i < nb_output_streams; i++) {
2872         OutputStream *ost = output_streams[i];
2873
2874         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2875             continue;
2876
2877         do_streamcopy(ist, ost, pkt);
2878     }
2879
2880     return 0;
2881 }
2882
2883 static void print_sdp(void)
2884 {
2885     char sdp[2048];
2886     int i;
2887     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2888
2889     if (!avc)
2890         exit_program(1);
2891     for (i = 0; i < nb_output_files; i++)
2892         avc[i] = output_files[i]->ctx;
2893
2894     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2895     printf("SDP:\n%s\n", sdp);
2896     fflush(stdout);
2897     av_freep(&avc);
2898 }
2899
2900 static int init_input_stream(int ist_index, char *error, int error_len)
2901 {
2902     int i;
2903     InputStream *ist = input_streams[ist_index];
2904
2905     if (ist->decoding_needed) {
2906         AVCodec *codec = ist->dec;
2907         if (!codec) {
2908             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2909                     avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2910             return AVERROR(EINVAL);
2911         }
2912
2913         ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
2914         if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2915             ist->st->codec->get_buffer     = codec_get_buffer;
2916             ist->st->codec->release_buffer = codec_release_buffer;
2917             ist->st->codec->opaque         = ist;
2918         }
2919
2920         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2921             av_dict_set(&ist->opts, "threads", "auto", 0);
2922         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2923             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2924                     ist->file_index, ist->st->index);
2925             return AVERROR(EINVAL);
2926         }
2927         assert_codec_experimental(ist->st->codec, 0);
2928         assert_avoptions(ist->opts);
2929
2930         if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2931             for (i = 0; i < nb_output_streams; i++) {
2932                 OutputStream *ost = output_streams[i];
2933                 if (ost->source_index == ist_index) {
2934                     if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2935                         get_default_channel_layouts(ost, ist);
2936                     break;
2937                 }
2938             }
2939         }
2940     }
2941
2942     ist->next_pts = AV_NOPTS_VALUE;
2943     ist->next_dts = AV_NOPTS_VALUE;
2944     ist->is_start = 1;
2945
2946     return 0;
2947 }
2948
2949 static InputStream *get_input_stream(OutputStream *ost)
2950 {
2951     if (ost->source_index >= 0)
2952         return input_streams[ost->source_index];
2953
2954     if (ost->filter) {
2955         FilterGraph *fg = ost->filter->graph;
2956         int i;
2957
2958         for (i = 0; i < fg->nb_inputs; i++)
2959             if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2960                 return fg->inputs[i]->ist;
2961     }
2962
2963     return NULL;
2964 }
2965
2966 static int transcode_init(void)
2967 {
2968     int ret = 0, i, j, k;
2969     AVFormatContext *oc;
2970     AVCodecContext *codec, *icodec;
2971     OutputStream *ost;
2972     InputStream *ist;
2973     char error[1024];
2974     int want_sdp = 1;
2975
2976     /* init framerate emulation */
2977     for (i = 0; i < nb_input_files; i++) {
2978         InputFile *ifile = input_files[i];
2979         if (ifile->rate_emu)
2980             for (j = 0; j < ifile->nb_streams; j++)
2981                 input_streams[j + ifile->ist_index]->start = av_gettime();
2982     }
2983
2984     /* output stream init */
2985     for (i = 0; i < nb_output_files; i++) {
2986         oc = output_files[i]->ctx;
2987         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2988             av_dump_format(oc, i, oc->filename, 1);
2989             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2990             return AVERROR(EINVAL);
2991         }
2992     }
2993
2994     /* init complex filtergraphs */
2995     for (i = 0; i < nb_filtergraphs; i++)
2996         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2997             return ret;
2998
2999     /* for each output stream, we compute the right encoding parameters */
3000     for (i = 0; i < nb_output_streams; i++) {
3001         ost = output_streams[i];
3002         oc  = output_files[ost->file_index]->ctx;
3003         ist = get_input_stream(ost);
3004
3005         if (ost->attachment_filename)
3006             continue;
3007
3008         codec  = ost->st->codec;
3009
3010         if (ist) {
3011             icodec = ist->st->codec;
3012
3013             ost->st->disposition          = ist->st->disposition;
3014             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
3015             codec->chroma_sample_location = icodec->chroma_sample_location;
3016         }
3017
3018         if (ost->stream_copy) {
3019             uint64_t extra_size;
3020
3021             av_assert0(ist && !ost->filter);
3022
3023             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
3024
3025             if (extra_size > INT_MAX) {
3026                 return AVERROR(EINVAL);
3027             }
3028
3029             /* if stream_copy is selected, no need to decode or encode */
3030             codec->codec_id   = icodec->codec_id;
3031             codec->codec_type = icodec->codec_type;
3032
3033             if (!codec->codec_tag) {
3034                 if (!oc->oformat->codec_tag ||
3035                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
3036                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
3037                     codec->codec_tag = icodec->codec_tag;
3038             }
3039
3040             codec->bit_rate       = icodec->bit_rate;
3041             codec->rc_max_rate    = icodec->rc_max_rate;
3042             codec->rc_buffer_size = icodec->rc_buffer_size;
3043             codec->field_order    = icodec->field_order;
3044             codec->extradata      = av_mallocz(extra_size);
3045             if (!codec->extradata) {
3046                 return AVERROR(ENOMEM);
3047             }
3048             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
3049             codec->extradata_size= icodec->extradata_size;
3050             codec->bits_per_coded_sample  = icodec->bits_per_coded_sample;
3051
3052             codec->time_base = ist->st->time_base;
3053             /*
3054              * Avi is a special case here because it supports variable fps but
3055              * having the fps and timebase differe significantly adds quite some
3056              * overhead
3057              */
3058             if(!strcmp(oc->oformat->name, "avi")) {
3059                 if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
3060                                  && av_q2d(ist->st->time_base) < 1.0/500
3061                     || copy_tb==0){
3062                     codec->time_base = icodec->time_base;
3063                     codec->time_base.num *= icodec->ticks_per_frame;
3064                     codec->time_base.den *= 2;
3065                     codec->ticks_per_frame = 2;
3066                 }
3067             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
3068                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
3069                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
3070             ) {
3071                 if(   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
3072                                 && av_q2d(ist->st->time_base) < 1.0/500
3073                    || copy_tb==0){
3074                     codec->time_base = icodec->time_base;
3075                     codec->time_base.num *= icodec->ticks_per_frame;
3076                 }
3077             }
3078             av_reduce(&codec->time_base.num, &codec->time_base.den,
3079                         codec->time_base.num, codec->time_base.den, INT_MAX);
3080
3081             switch (codec->codec_type) {
3082             case AVMEDIA_TYPE_AUDIO:
3083                 if (audio_volume != 256) {
3084                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3085                     exit_program(1);
3086                 }
3087                 codec->channel_layout     = icodec->channel_layout;
3088                 codec->sample_rate        = icodec->sample_rate;
3089                 codec->channels           = icodec->channels;
3090                 codec->frame_size         = icodec->frame_size;
3091                 codec->audio_service_type = icodec->audio_service_type;
3092                 codec->block_align        = icodec->block_align;
3093                 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
3094                     codec->block_align= 0;
3095                 if(codec->codec_id == CODEC_ID_AC3)
3096                     codec->block_align= 0;
3097                 break;
3098             case AVMEDIA_TYPE_VIDEO:
3099                 codec->pix_fmt            = icodec->pix_fmt;
3100                 codec->width              = icodec->width;
3101                 codec->height             = icodec->height;
3102                 codec->has_b_frames       = icodec->has_b_frames;
3103                 if (!codec->sample_aspect_ratio.num) {
3104                     codec->sample_aspect_ratio   =
3105                     ost->st->sample_aspect_ratio =
3106                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
3107                         ist->st->codec->sample_aspect_ratio.num ?
3108                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
3109                 }
3110                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3111                 break;
3112             case AVMEDIA_TYPE_SUBTITLE:
3113                 codec->width  = icodec->width;
3114                 codec->height = icodec->height;
3115                 break;
3116             case AVMEDIA_TYPE_DATA:
3117             case AVMEDIA_TYPE_ATTACHMENT:
3118                 break;
3119             default:
3120                 abort();
3121             }
3122         } else {
3123             if (!ost->enc)
3124                 ost->enc = avcodec_find_encoder(codec->codec_id);
3125             if (!ost->enc) {
3126                 /* should only happen when a default codec is not present. */
3127                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3128                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3129                 ret = AVERROR(EINVAL);
3130                 goto dump_format;
3131             }
3132
3133             if (ist)
3134                 ist->decoding_needed = 1;
3135             ost->encoding_needed = 1;
3136
3137             switch (codec->codec_type) {
3138             case AVMEDIA_TYPE_AUDIO:
3139                 ost->fifo = av_fifo_alloc(1024);
3140                 if (!ost->fifo) {
3141                     return AVERROR(ENOMEM);
3142                 }
3143
3144                 if (!codec->sample_rate)
3145                     codec->sample_rate = icodec->sample_rate;
3146                 choose_sample_rate(ost->st, ost->enc);
3147                 codec->time_base = (AVRational){ 1, codec->sample_rate };
3148
3149                 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
3150                     codec->sample_fmt = icodec->sample_fmt;
3151                 choose_sample_fmt(ost->st, ost->enc);
3152
3153                 if (ost->audio_channels_mapped) {
3154                     /* the requested output channel is set to the number of
3155                      * -map_channel only if no -ac are specified */
3156                     if (!codec->channels) {
3157                         codec->channels       = ost->audio_channels_mapped;
3158                         codec->channel_layout = av_get_default_channel_layout(codec->channels);
3159                         if (!codec->channel_layout) {
3160                             av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
3161                             exit_program(1);
3162                         }
3163                     }
3164                     /* fill unused channel mapping with -1 (which means a muted
3165                      * channel in case the number of output channels is bigger
3166                      * than the number of mapped channel) */
3167                     for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
3168                         ost->audio_channels_map[j] = -1;
3169                 } else if (!codec->channels) {
3170                     codec->channels = icodec->channels;
3171                     codec->channel_layout = icodec->channel_layout;
3172                 }
3173                 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
3174                     codec->channel_layout = 0;
3175
3176
3177 //                 ost->audio_resample       = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
3178 //                 ost->audio_resample      |=    codec->sample_fmt     != icodec->sample_fmt
3179 //                                             || codec->channel_layout != icodec->channel_layout;
3180                 icodec->request_channels  = codec-> channels;
3181                 ost->resample_sample_fmt  = icodec->sample_fmt;
3182                 ost->resample_sample_rate = icodec->sample_rate;
3183                 ost->resample_channels    = icodec->channels;
3184                 ost->resample_channel_layout = icodec->channel_layout;
3185                 break;
3186             case AVMEDIA_TYPE_VIDEO:
3187                 if (!ost->filter) {
3188                     FilterGraph *fg;
3189                     fg = init_simple_filtergraph(ist, ost);
3190                     if (configure_video_filters(fg)) {
3191                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3192                         exit(1);
3193                     }
3194                 }
3195
3196                 if (ist && !ost->frame_rate.num)
3197                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
3198                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3199                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3200                     ost->frame_rate = ost->enc->supported_framerates[idx];
3201                 }
3202                 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
3203                 if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3204                    && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3205                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3206                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3207                 }
3208                 for (j = 0; j < ost->forced_kf_count; j++)
3209                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3210                                                          AV_TIME_BASE_Q,
3211                                                          codec->time_base);
3212
3213                 codec->width  = ost->filter->filter->inputs[0]->w;
3214                 codec->height = ost->filter->filter->inputs[0]->h;
3215                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3216                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3217                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3218                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
3219                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3220
3221                 if (codec->width   != icodec->width  ||
3222                     codec->height  != icodec->height ||
3223                     codec->pix_fmt != icodec->pix_fmt) {
3224                     codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3225                 }
3226
3227                 break;
3228             case AVMEDIA_TYPE_SUBTITLE:
3229                 codec->time_base = (AVRational){1, 1000};
3230                 break;
3231             default:
3232                 abort();
3233                 break;
3234             }
3235             /* two pass mode */
3236             if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3237                 char logfilename[1024];
3238                 FILE *f;
3239
3240                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3241                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3242                          i);
3243                 if (!strcmp(ost->enc->name, "libx264")) {
3244                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3245                 } else {
3246                     if (codec->flags & CODEC_FLAG_PASS2) {
3247                         char  *logbuffer;
3248                         size_t logbuffer_size;
3249                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3250                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3251                                 logfilename);
3252                             exit_program(1);
3253                         }
3254                         codec->stats_in = logbuffer;
3255                     }
3256                     if (codec->flags & CODEC_FLAG_PASS1) {
3257                         f = fopen(logfilename, "wb");
3258                         if (!f) {
3259                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3260                                 logfilename, strerror(errno));
3261                             exit_program(1);
3262                         }
3263                         ost->logfile = f;
3264                     }
3265                 }
3266             }
3267         }
3268     }
3269
3270     /* open each encoder */
3271     for (i = 0; i < nb_output_streams; i++) {
3272         ost = output_streams[i];
3273         if (ost->encoding_needed) {
3274             AVCodec      *codec = ost->enc;
3275             AVCodecContext *dec = NULL;
3276
3277             if ((ist = get_input_stream(ost)))
3278                 dec = ist->st->codec;
3279             if (dec && dec->subtitle_header) {
3280                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
3281                 if (!ost->st->codec->subtitle_header) {
3282                     ret = AVERROR(ENOMEM);
3283                     goto dump_format;
3284                 }
3285                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3286                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
3287             }
3288             if (!av_dict_get(ost->opts, "threads", NULL, 0))
3289                 av_dict_set(&ost->opts, "threads", "auto", 0);
3290             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
3291                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
3292                         ost->file_index, ost->index);
3293                 ret = AVERROR(EINVAL);
3294                 goto dump_format;
3295             }
3296             assert_codec_experimental(ost->st->codec, 1);
3297             assert_avoptions(ost->opts);
3298             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
3299                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3300                                              " It takes bits/s as argument, not kbits/s\n");
3301             extra_size += ost->st->codec->extradata_size;
3302
3303             if (ost->st->codec->me_threshold)
3304                 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
3305         }
3306     }
3307
3308     /* init input streams */
3309     for (i = 0; i < nb_input_streams; i++)
3310         if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
3311             goto dump_format;
3312
3313     /* discard unused programs */
3314     for (i = 0; i < nb_input_files; i++) {
3315         InputFile *ifile = input_files[i];
3316         for (j = 0; j < ifile->ctx->nb_programs; j++) {
3317             AVProgram *p = ifile->ctx->programs[j];
3318             int discard  = AVDISCARD_ALL;
3319
3320             for (k = 0; k < p->nb_stream_indexes; k++)
3321                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3322                     discard = AVDISCARD_DEFAULT;
3323                     break;
3324                 }
3325             p->discard = discard;
3326         }
3327     }
3328
3329     /* open files and write file headers */
3330     for (i = 0; i < nb_output_files; i++) {
3331         oc = output_files[i]->ctx;
3332         oc->interrupt_callback = int_cb;
3333         if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
3334             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
3335             ret = AVERROR(EINVAL);
3336             goto dump_format;
3337         }
3338 //         assert_avoptions(output_files[i]->opts);
3339         if (strcmp(oc->oformat->name, "rtp")) {
3340             want_sdp = 0;
3341         }
3342     }
3343
3344  dump_format:
3345     /* dump the file output parameters - cannot be done before in case
3346        of stream copy */
3347     for (i = 0; i < nb_output_files; i++) {
3348         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3349     }
3350
3351     /* dump the stream mapping */
3352     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3353     for (i = 0; i < nb_input_streams; i++) {
3354         ist = input_streams[i];
3355
3356         for (j = 0; j < ist->nb_filters; j++) {
3357             AVFilterLink *link = ist->filters[j]->filter->outputs[0];
3358             if (ist->filters[j]->graph->graph_desc) {
3359                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
3360                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3361                        link->dst->filter->name);
3362                 if (link->dst->input_count > 1)
3363                     av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
3364                 if (nb_filtergraphs > 1)
3365                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3366                 av_log(NULL, AV_LOG_INFO, "\n");
3367             }
3368         }
3369     }
3370
3371     for (i = 0; i < nb_output_streams; i++) {
3372         ost = output_streams[i];
3373
3374         if (ost->attachment_filename) {
3375             /* an attached file */
3376             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
3377                    ost->attachment_filename, ost->file_index, ost->index);
3378             continue;
3379         }
3380
3381         if (ost->filter && ost->filter->graph->graph_desc) {
3382             /* output from a complex graph */
3383             AVFilterLink *link = ost->filter->filter->inputs[0];
3384             av_log(NULL, AV_LOG_INFO, "  %s", link->src->filter->name);
3385             if (link->src->output_count > 1)
3386                 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
3387             if (nb_filtergraphs > 1)
3388                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3389
3390             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3391                    ost->index, ost->enc ? ost->enc->name : "?");
3392             continue;
3393         }
3394
3395         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
3396                input_streams[ost->source_index]->file_index,
3397                input_streams[ost->source_index]->st->index,
3398                ost->file_index,
3399                ost->index);
3400         if (ost->audio_channels_mapped) {
3401             av_log(NULL, AV_LOG_INFO, " [ch:");
3402             for (j = 0; j < ost->audio_channels_mapped; j++)
3403                 if (ost->audio_channels_map[j] == -1)
3404                     av_log(NULL, AV_LOG_INFO, " M");
3405                 else
3406                     av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
3407             av_log(NULL, AV_LOG_INFO, "]");
3408         }
3409         if (ost->sync_ist != input_streams[ost->source_index])
3410             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3411                    ost->sync_ist->file_index,
3412                    ost->sync_ist->st->index);
3413         if (ost->stream_copy)
3414             av_log(NULL, AV_LOG_INFO, " (copy)");
3415         else
3416             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
3417                    input_streams[ost->source_index]->dec->name : "?",
3418                    ost->enc ? ost->enc->name : "?");
3419         av_log(NULL, AV_LOG_INFO, "\n");
3420     }
3421
3422     if (ret) {
3423         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3424         return ret;
3425     }
3426
3427     if (want_sdp) {
3428         print_sdp();
3429     }
3430
3431     return 0;
3432 }
3433
3434 /*
3435  * The following code is the main loop of the file converter
3436  */
3437 static int transcode(void)
3438 {
3439     int ret, i;
3440     AVFormatContext *is, *os;
3441     OutputStream *ost;
3442     InputStream *ist;
3443     uint8_t *no_packet;
3444     int no_packet_count = 0;
3445     int64_t timer_start;
3446     int key;
3447
3448     if (!(no_packet = av_mallocz(nb_input_files)))
3449         exit_program(1);
3450
3451     ret = transcode_init();
3452     if (ret < 0)
3453         goto fail;
3454
3455     if (!using_stdin) {
3456         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3457     }
3458
3459     timer_start = av_gettime();
3460
3461     for (; received_sigterm == 0;) {
3462         int file_index, ist_index, past_recording_time = 1;
3463         AVPacket pkt;
3464         int64_t ipts_min;
3465         int64_t cur_time= av_gettime();
3466
3467         ipts_min = INT64_MAX;
3468         /* if 'q' pressed, exits */
3469         if (!using_stdin) {
3470             static int64_t last_time;
3471             if (received_nb_signals)
3472                 break;
3473             /* read_key() returns 0 on EOF */
3474             if(cur_time - last_time >= 100000 && !run_as_daemon){
3475                 key =  read_key();
3476                 last_time = cur_time;
3477             }else
3478                 key = -1;
3479             if (key == 'q')
3480                 break;
3481             if (key == '+') av_log_set_level(av_log_get_level()+10);
3482             if (key == '-') av_log_set_level(av_log_get_level()-10);
3483             if (key == 's') qp_hist     ^= 1;
3484             if (key == 'h'){
3485                 if (do_hex_dump){
3486                     do_hex_dump = do_pkt_dump = 0;
3487                 } else if(do_pkt_dump){
3488                     do_hex_dump = 1;
3489                 } else
3490                     do_pkt_dump = 1;
3491                 av_log_set_level(AV_LOG_DEBUG);
3492             }
3493             if (key == 'c' || key == 'C'){
3494                 char buf[4096], target[64], command[256], arg[256] = {0};
3495                 double time;
3496                 int k, n = 0;
3497                 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3498                 i = 0;
3499                 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3500                     if (k > 0)
3501                         buf[i++] = k;
3502                 buf[i] = 0;
3503                 if (k > 0 &&
3504                     (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3505                     av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3506                            target, time, command, arg);
3507                     for (i = 0; i < nb_filtergraphs; i++) {
3508                         FilterGraph *fg = filtergraphs[i];
3509                         if (fg->graph) {
3510                             if (time < 0) {
3511                                 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3512                                                                   key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3513                                 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3514                             } else {
3515                                 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3516                             }
3517                         }
3518                     }
3519                 } else {
3520                     av_log(NULL, AV_LOG_ERROR,
3521                            "Parse error, at least 3 arguments were expected, "
3522                            "only %d given in string '%s'\n", n, buf);
3523                 }
3524             }
3525             if (key == 'd' || key == 'D'){
3526                 int debug=0;
3527                 if(key == 'D') {
3528                     debug = input_streams[0]->st->codec->debug<<1;
3529                     if(!debug) debug = 1;
3530                     while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3531                         debug += debug;
3532                 }else
3533                     if(scanf("%d", &debug)!=1)
3534                         fprintf(stderr,"error parsing debug value\n");
3535                 for(i=0;i<nb_input_streams;i++) {
3536                     input_streams[i]->st->codec->debug = debug;
3537                 }
3538                 for(i=0;i<nb_output_streams;i++) {
3539                     ost = output_streams[i];
3540                     ost->st->codec->debug = debug;
3541                 }
3542                 if(debug) av_log_set_level(AV_LOG_DEBUG);
3543                 fprintf(stderr,"debug=%d\n", debug);
3544             }
3545             if (key == '?'){
3546                 fprintf(stderr, "key    function\n"
3547                                 "?      show this help\n"
3548                                 "+      increase verbosity\n"
3549                                 "-      decrease verbosity\n"
3550                                 "c      Send command to filtergraph\n"
3551                                 "D      cycle through available debug modes\n"
3552                                 "h      dump packets/hex press to cycle through the 3 states\n"
3553                                 "q      quit\n"
3554                                 "s      Show QP histogram\n"
3555                 );
3556             }
3557         }
3558
3559         /* check if there's any stream where output is still needed */
3560         for (i = 0; i < nb_output_streams; i++) {
3561             OutputFile *of;
3562             ost = output_streams[i];
3563             of  = output_files[ost->file_index];
3564             os  = output_files[ost->file_index]->ctx;
3565             if (ost->is_past_recording_time ||
3566                 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3567                 continue;
3568             if (ost->frame_number >= ost->max_frames) {
3569                 int j;
3570                 for (j = 0; j < of->ctx->nb_streams; j++)
3571                     output_streams[of->ost_index + j]->is_past_recording_time = 1;
3572                 continue;
3573             }
3574             past_recording_time = 0;
3575         }
3576         if (past_recording_time)
3577             break;
3578
3579         /* select the stream that we must read now by looking at the
3580            smallest output pts */
3581         file_index = -1;
3582         for (i = 0; i < nb_input_streams; i++) {
3583             int64_t ipts;
3584             ist = input_streams[i];
3585             ipts = ist->pts;
3586             if (ist->discard || no_packet[ist->file_index])
3587                 continue;
3588             if (!input_files[ist->file_index]->eof_reached) {
3589                 if (ipts < ipts_min) {
3590                     ipts_min = ipts;
3591                     file_index = ist->file_index;
3592                 }
3593             }
3594         }
3595         /* if none, if is finished */
3596         if (file_index < 0) {
3597             if (no_packet_count) {
3598                 no_packet_count = 0;
3599                 memset(no_packet, 0, nb_input_files);
3600                 usleep(10000);
3601                 continue;
3602             }
3603             break;
3604         }
3605
3606         /* read a frame from it and output it in the fifo */
3607         is  = input_files[file_index]->ctx;
3608         ret = av_read_frame(is, &pkt);
3609         if (ret == AVERROR(EAGAIN)) {
3610             no_packet[file_index] = 1;
3611             no_packet_count++;
3612             continue;
3613         }
3614         if (ret < 0) {
3615             input_files[file_index]->eof_reached = 1;
3616
3617             for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3618                 ist = input_streams[input_files[file_index]->ist_index + i];
3619                 if (ist->decoding_needed)
3620                     output_packet(ist, NULL);
3621             }
3622
3623             if (opt_shortest)
3624                 break;
3625             else
3626                 continue;
3627         }
3628
3629         no_packet_count = 0;
3630         memset(no_packet, 0, nb_input_files);
3631
3632         if (do_pkt_dump) {
3633             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3634                              is->streams[pkt.stream_index]);
3635         }
3636         /* the following test is needed in case new streams appear
3637            dynamically in stream : we ignore them */
3638         if (pkt.stream_index >= input_files[file_index]->nb_streams)
3639             goto discard_packet;
3640         ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3641         ist = input_streams[ist_index];
3642         if (ist->discard)
3643             goto discard_packet;
3644
3645         if (pkt.dts != AV_NOPTS_VALUE)
3646             pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3647         if (pkt.pts != AV_NOPTS_VALUE)
3648             pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3649
3650         if (pkt.pts != AV_NOPTS_VALUE)
3651             pkt.pts *= ist->ts_scale;
3652         if (pkt.dts != AV_NOPTS_VALUE)
3653             pkt.dts *= ist->ts_scale;
3654
3655         if (debug_ts) {
3656             av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3657                     "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",
3658                     ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3659                     av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &ist->st->time_base),
3660                     av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3661                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3662                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3663                     input_files[ist->file_index]->ts_offset);
3664         }
3665
3666         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3667             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3668             int64_t delta   = pkt_dts - ist->next_dts;
3669             if (is->iformat->flags & AVFMT_TS_DISCONT) {
3670             if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3671                 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3672                  ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3673                 pkt_dts+1<ist->pts){
3674                 input_files[ist->file_index]->ts_offset -= delta;
3675                 av_log(NULL, AV_LOG_DEBUG,
3676                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3677                        delta, input_files[ist->file_index]->ts_offset);
3678                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3679                 if (pkt.pts != AV_NOPTS_VALUE)
3680                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3681             }
3682             } else {
3683                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3684                     (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3685                      pkt_dts+1<ist->pts){
3686                     av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3687                     pkt.dts = AV_NOPTS_VALUE;
3688                 }
3689                 if (pkt.pts != AV_NOPTS_VALUE){
3690                     int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3691                     delta   = pkt_pts - ist->next_dts;
3692                     if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3693                         (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3694                         pkt_pts+1<ist->pts) {
3695                         av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3696                         pkt.pts = AV_NOPTS_VALUE;
3697                     }
3698                 }
3699             }
3700         }
3701
3702         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3703         if (output_packet(ist, &pkt) < 0 ||
3704             ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
3705             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3706                    ist->file_index, ist->st->index);
3707             if (exit_on_error)
3708                 exit_program(1);
3709             av_free_packet(&pkt);
3710             continue;
3711         }
3712
3713     discard_packet:
3714         av_free_packet(&pkt);
3715
3716         /* dump report by using the output first video and audio streams */
3717         print_report(0, timer_start, cur_time);
3718     }
3719
3720     /* at the end of stream, we must flush the decoder buffers */
3721     for (i = 0; i < nb_input_streams; i++) {
3722         ist = input_streams[i];
3723         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3724             output_packet(ist, NULL);
3725         }
3726     }
3727     poll_filters();
3728     flush_encoders();
3729
3730     term_exit();
3731
3732     /* write the trailer if needed and close file */
3733     for (i = 0; i < nb_output_files; i++) {
3734         os = output_files[i]->ctx;
3735         av_write_trailer(os);
3736     }
3737
3738     /* dump report by using the first video and audio streams */
3739     print_report(1, timer_start, av_gettime());
3740
3741     /* close each encoder */
3742     for (i = 0; i < nb_output_streams; i++) {
3743         ost = output_streams[i];
3744         if (ost->encoding_needed) {
3745             av_freep(&ost->st->codec->stats_in);
3746             avcodec_close(ost->st->codec);
3747         }
3748     }
3749
3750     /* close each decoder */
3751     for (i = 0; i < nb_input_streams; i++) {
3752         ist = input_streams[i];
3753         if (ist->decoding_needed) {
3754             avcodec_close(ist->st->codec);
3755         }
3756     }
3757
3758     /* finished ! */
3759     ret = 0;
3760
3761  fail:
3762     av_freep(&no_packet);
3763
3764     if (output_streams) {
3765         for (i = 0; i < nb_output_streams; i++) {
3766             ost = output_streams[i];
3767             if (ost) {
3768                 if (ost->stream_copy)
3769                     av_freep(&ost->st->codec->extradata);
3770                 if (ost->logfile) {
3771                     fclose(ost->logfile);
3772                     ost->logfile = NULL;
3773                 }
3774                 av_fifo_free(ost->fifo); /* works even if fifo is not
3775                                              initialized but set to zero */
3776                 av_freep(&ost->st->codec->subtitle_header);
3777                 av_free(ost->forced_kf_pts);
3778                 swr_free(&ost->swr);
3779                 av_dict_free(&ost->opts);
3780             }
3781         }
3782     }
3783     return ret;
3784 }
3785
3786 static int opt_frame_crop(const char *opt, const char *arg)
3787 {
3788     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3789     return AVERROR(EINVAL);
3790 }
3791
3792 static int opt_pad(const char *opt, const char *arg)
3793 {
3794     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3795     return -1;
3796 }
3797
3798 static int opt_video_channel(const char *opt, const char *arg)
3799 {
3800     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3801     return opt_default("channel", arg);
3802 }
3803
3804 static int opt_video_standard(const char *opt, const char *arg)
3805 {
3806     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3807     return opt_default("standard", arg);
3808 }
3809
3810 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3811 {
3812     audio_codec_name = arg;
3813     return parse_option(o, "codec:a", arg, options);
3814 }
3815
3816 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3817 {
3818     video_codec_name = arg;
3819     return parse_option(o, "codec:v", arg, options);
3820 }
3821
3822 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3823 {
3824     subtitle_codec_name = arg;
3825     return parse_option(o, "codec:s", arg, options);
3826 }
3827
3828 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3829 {
3830     return parse_option(o, "codec:d", arg, options);
3831 }
3832
3833 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3834 {
3835     StreamMap *m = NULL;
3836     int i, negative = 0, file_idx;
3837     int sync_file_idx = -1, sync_stream_idx = 0;
3838     char *p, *sync;
3839     char *map;
3840
3841     if (*arg == '-') {
3842         negative = 1;
3843         arg++;
3844     }
3845     map = av_strdup(arg);
3846
3847     /* parse sync stream first, just pick first matching stream */
3848     if (sync = strchr(map, ',')) {
3849         *sync = 0;
3850         sync_file_idx = strtol(sync + 1, &sync, 0);
3851         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3852             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3853             exit_program(1);
3854         }
3855         if (*sync)
3856             sync++;
3857         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3858             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3859                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3860                 sync_stream_idx = i;
3861                 break;
3862             }
3863         if (i == input_files[sync_file_idx]->nb_streams) {
3864             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3865                                        "match any streams.\n", arg);
3866             exit_program(1);
3867         }
3868     }
3869
3870
3871     if (map[0] == '[') {
3872         /* this mapping refers to lavfi output */
3873         const char *c = map + 1;
3874         o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3875                                     &o->nb_stream_maps, o->nb_stream_maps + 1);
3876         m = &o->stream_maps[o->nb_stream_maps - 1];
3877         m->linklabel = av_get_token(&c, "]");
3878         if (!m->linklabel) {
3879             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3880             exit_program(1);
3881         }
3882     } else {
3883         file_idx = strtol(map, &p, 0);
3884         if (file_idx >= nb_input_files || file_idx < 0) {
3885             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3886             exit_program(1);
3887         }
3888         if (negative)
3889             /* disable some already defined maps */
3890             for (i = 0; i < o->nb_stream_maps; i++) {
3891                 m = &o->stream_maps[i];
3892                 if (file_idx == m->file_index &&
3893                     check_stream_specifier(input_files[m->file_index]->ctx,
3894                                            input_files[m->file_index]->ctx->streams[m->stream_index],
3895                                            *p == ':' ? p + 1 : p) > 0)
3896                     m->disabled = 1;
3897             }
3898         else
3899             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3900                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3901                             *p == ':' ? p + 1 : p) <= 0)
3902                     continue;
3903                 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3904                                             &o->nb_stream_maps, o->nb_stream_maps + 1);
3905                 m = &o->stream_maps[o->nb_stream_maps - 1];
3906
3907                 m->file_index   = file_idx;
3908                 m->stream_index = i;
3909
3910                 if (sync_file_idx >= 0) {
3911                     m->sync_file_index   = sync_file_idx;
3912                     m->sync_stream_index = sync_stream_idx;
3913                 } else {
3914                     m->sync_file_index   = file_idx;
3915                     m->sync_stream_index = i;
3916                 }
3917             }
3918     }
3919
3920     if (!m) {
3921         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3922         exit_program(1);
3923     }
3924
3925     av_freep(&map);
3926     return 0;
3927 }
3928
3929 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3930 {
3931     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3932                                 &o->nb_attachments, o->nb_attachments + 1);
3933     o->attachments[o->nb_attachments - 1] = arg;
3934     return 0;
3935 }
3936
3937 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3938 {
3939     int n;
3940     AVStream *st;
3941     AudioChannelMap *m;
3942
3943     o->audio_channel_maps =
3944         grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3945                    &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3946     m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3947
3948     /* muted channel syntax */
3949     n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3950     if ((n == 1 || n == 3) && m->channel_idx == -1) {
3951         m->file_idx = m->stream_idx = -1;
3952         if (n == 1)
3953             m->ofile_idx = m->ostream_idx = -1;
3954         return 0;
3955     }
3956
3957     /* normal syntax */
3958     n = sscanf(arg, "%d.%d.%d:%d.%d",
3959                &m->file_idx,  &m->stream_idx, &m->channel_idx,
3960                &m->ofile_idx, &m->ostream_idx);
3961
3962     if (n != 3 && n != 5) {
3963         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3964                "[file.stream.channel|-1][:syncfile:syncstream]\n");
3965         exit_program(1);
3966     }
3967
3968     if (n != 5) // only file.stream.channel specified
3969         m->ofile_idx = m->ostream_idx = -1;
3970
3971     /* check input */
3972     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
3973         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
3974                m->file_idx);
3975         exit_program(1);
3976     }
3977     if (m->stream_idx < 0 ||
3978         m->stream_idx >= input_files[m->file_idx]->nb_streams) {
3979         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
3980                m->file_idx, m->stream_idx);
3981         exit_program(1);
3982     }
3983     st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
3984     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
3985         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
3986                m->file_idx, m->stream_idx);
3987         exit_program(1);
3988     }
3989     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
3990         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
3991                m->file_idx, m->stream_idx, m->channel_idx);
3992         exit_program(1);
3993     }
3994     return 0;
3995 }
3996
3997 /**
3998  * Parse a metadata specifier in arg.
3999  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
4000  * @param index for type c/p, chapter/program index is written here
4001  * @param stream_spec for type s, the stream specifier is written here
4002  */
4003 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
4004 {
4005     if (*arg) {
4006         *type = *arg;
4007         switch (*arg) {
4008         case 'g':
4009             break;
4010         case 's':
4011             if (*(++arg) && *arg != ':') {
4012                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
4013                 exit_program(1);
4014             }
4015             *stream_spec = *arg == ':' ? arg + 1 : "";
4016             break;
4017         case 'c':
4018         case 'p':
4019             if (*(++arg) == ':')
4020                 *index = strtol(++arg, NULL, 0);
4021             break;
4022         default:
4023             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
4024             exit_program(1);
4025         }
4026     } else
4027         *type = 'g';
4028 }
4029
4030 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
4031 {
4032     AVDictionary **meta_in = NULL;
4033     AVDictionary **meta_out = NULL;
4034     int i, ret = 0;
4035     char type_in, type_out;
4036     const char *istream_spec = NULL, *ostream_spec = NULL;
4037     int idx_in = 0, idx_out = 0;
4038
4039     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
4040     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
4041
4042     if (!ic) {
4043         if (type_out == 'g' || !*outspec)
4044             o->metadata_global_manual = 1;
4045         if (type_out == 's' || !*outspec)
4046             o->metadata_streams_manual = 1;
4047         if (type_out == 'c' || !*outspec)
4048             o->metadata_chapters_manual = 1;
4049         return 0;
4050     }
4051
4052     if (type_in == 'g' || type_out == 'g')
4053         o->metadata_global_manual = 1;
4054     if (type_in == 's' || type_out == 's')
4055         o->metadata_streams_manual = 1;
4056     if (type_in == 'c' || type_out == 'c')
4057         o->metadata_chapters_manual = 1;
4058
4059 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
4060     if ((index) < 0 || (index) >= (nb_elems)) {\
4061         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
4062                 (desc), (index));\
4063         exit_program(1);\
4064     }
4065
4066 #define SET_DICT(type, meta, context, index)\
4067         switch (type) {\
4068         case 'g':\
4069             meta = &context->metadata;\
4070             break;\
4071         case 'c':\
4072             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
4073             meta = &context->chapters[index]->metadata;\
4074             break;\
4075         case 'p':\
4076             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
4077             meta = &context->programs[index]->metadata;\
4078             break;\
4079         }\
4080
4081     SET_DICT(type_in, meta_in, ic, idx_in);
4082     SET_DICT(type_out, meta_out, oc, idx_out);
4083
4084     /* for input streams choose first matching stream */
4085     if (type_in == 's') {
4086         for (i = 0; i < ic->nb_streams; i++) {
4087             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
4088                 meta_in = &ic->streams[i]->metadata;
4089                 break;
4090             } else if (ret < 0)
4091                 exit_program(1);
4092         }
4093         if (!meta_in) {
4094             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
4095             exit_program(1);
4096         }
4097     }
4098
4099     if (type_out == 's') {
4100         for (i = 0; i < oc->nb_streams; i++) {
4101             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
4102                 meta_out = &oc->streams[i]->metadata;
4103                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4104             } else if (ret < 0)
4105                 exit_program(1);
4106         }
4107     } else
4108         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4109
4110     return 0;
4111 }
4112
4113 static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
4114 {
4115     char buf[128];
4116     int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
4117     struct tm time = *gmtime((time_t*)&recording_timestamp);
4118     strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
4119     parse_option(o, "metadata", buf, options);
4120
4121     av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
4122                                  "tag instead.\n", opt);
4123     return 0;
4124 }
4125
4126 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
4127 {
4128     const char *codec_string = encoder ? "encoder" : "decoder";
4129     AVCodec *codec;
4130
4131     codec = encoder ?
4132         avcodec_find_encoder_by_name(name) :
4133         avcodec_find_decoder_by_name(name);
4134     if (!codec) {
4135         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
4136         exit_program(1);
4137     }
4138     if (codec->type != type) {
4139         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
4140         exit_program(1);
4141     }
4142     return codec;
4143 }
4144
4145 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
4146 {
4147     char *codec_name = NULL;
4148
4149     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
4150     if (codec_name) {
4151         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
4152         st->codec->codec_id = codec->id;
4153         return codec;
4154     } else
4155         return avcodec_find_decoder(st->codec->codec_id);
4156 }
4157
4158 /**
4159  * Add all the streams from the given input file to the global
4160  * list of input streams.
4161  */
4162 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
4163 {
4164     int i;
4165     char *next, *codec_tag = NULL;
4166
4167     for (i = 0; i < ic->nb_streams; i++) {
4168         AVStream *st = ic->streams[i];
4169         AVCodecContext *dec = st->codec;
4170         InputStream *ist = av_mallocz(sizeof(*ist));
4171
4172         if (!ist)
4173             exit_program(1);
4174
4175         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
4176         input_streams[nb_input_streams - 1] = ist;
4177
4178         ist->st = st;
4179         ist->file_index = nb_input_files;
4180         ist->discard = 1;
4181         st->discard  = AVDISCARD_ALL;
4182         ist->opts = filter_codec_opts(codec_opts, choose_decoder(o, ic, st), ic, st);
4183
4184         ist->ts_scale = 1.0;
4185         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
4186
4187         MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
4188         if (codec_tag) {
4189             uint32_t tag = strtol(codec_tag, &next, 0);
4190             if (*next)
4191                 tag = AV_RL32(codec_tag);
4192             st->codec->codec_tag = tag;
4193         }
4194
4195         ist->dec = choose_decoder(o, ic, st);
4196
4197         switch (dec->codec_type) {
4198         case AVMEDIA_TYPE_VIDEO:
4199             if(!ist->dec)
4200                 ist->dec = avcodec_find_decoder(dec->codec_id);
4201             if (dec->lowres) {
4202                 dec->flags |= CODEC_FLAG_EMU_EDGE;
4203             }
4204
4205             ist->resample_height  = dec->height;
4206             ist->resample_width   = dec->width;
4207             ist->resample_pix_fmt = dec->pix_fmt;
4208
4209             break;
4210         case AVMEDIA_TYPE_AUDIO:
4211         case AVMEDIA_TYPE_DATA:
4212         case AVMEDIA_TYPE_SUBTITLE:
4213             if(!ist->dec)
4214                 ist->dec = avcodec_find_decoder(dec->codec_id);
4215             break;
4216         case AVMEDIA_TYPE_ATTACHMENT:
4217         case AVMEDIA_TYPE_UNKNOWN:
4218             break;
4219         default:
4220             abort();
4221         }
4222     }
4223 }
4224
4225 static void assert_file_overwrite(const char *filename)
4226 {
4227     if ((!file_overwrite || no_file_overwrite) &&
4228         (strchr(filename, ':') == NULL || filename[1] == ':' ||
4229          av_strstart(filename, "file:", NULL))) {
4230         if (avio_check(filename, 0) == 0) {
4231             if (!using_stdin && (!no_file_overwrite || file_overwrite)) {
4232                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
4233                 fflush(stderr);
4234                 term_exit();
4235                 signal(SIGINT, SIG_DFL);
4236                 if (!read_yesno()) {
4237                     av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
4238                     exit_program(1);
4239                 }
4240                 term_init();
4241             }
4242             else {
4243                 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
4244                 exit_program(1);
4245             }
4246         }
4247     }
4248 }
4249
4250 static void dump_attachment(AVStream *st, const char *filename)
4251 {
4252     int ret;
4253     AVIOContext *out = NULL;
4254     AVDictionaryEntry *e;
4255
4256     if (!st->codec->extradata_size) {
4257         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
4258                nb_input_files - 1, st->index);
4259         return;
4260     }
4261     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
4262         filename = e->value;
4263     if (!*filename) {
4264         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
4265                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
4266         exit_program(1);
4267     }
4268
4269     assert_file_overwrite(filename);
4270
4271     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
4272         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
4273                filename);
4274         exit_program(1);
4275     }
4276
4277     avio_write(out, st->codec->extradata, st->codec->extradata_size);
4278     avio_flush(out);
4279     avio_close(out);
4280 }
4281
4282 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
4283 {
4284     AVFormatContext *ic;
4285     AVInputFormat *file_iformat = NULL;
4286     int err, i, ret;
4287     int64_t timestamp;
4288     uint8_t buf[128];
4289     AVDictionary **opts;
4290     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
4291
4292     if (o->format) {
4293         if (!(file_iformat = av_find_input_format(o->format))) {
4294             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
4295             exit_program(1);
4296         }
4297     }
4298
4299     if (!strcmp(filename, "-"))
4300         filename = "pipe:";
4301
4302     using_stdin |