Merge remote-tracking branch 'qatar/master'
[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 "libavcodec/audioconvert.h"
40 #include "libavutil/audioconvert.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/samplefmt.h"
43 #include "libavutil/colorspace.h"
44 #include "libavutil/fifo.h"
45 #include "libavutil/intreadwrite.h"
46 #include "libavutil/dict.h"
47 #include "libavutil/mathematics.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/avstring.h"
50 #include "libavutil/libm.h"
51 #include "libavutil/imgutils.h"
52 #include "libavutil/timestamp.h"
53 #include "libavformat/os_support.h"
54 #include "libswresample/swresample.h"
55
56 #include "libavformat/ffm.h" // not public API
57
58 # include "libavfilter/avcodec.h"
59 # include "libavfilter/avfilter.h"
60 # include "libavfilter/avfiltergraph.h"
61 # include "libavfilter/buffersink.h"
62 # include "libavfilter/buffersrc.h"
63 # include "libavfilter/vsrc_buffer.h"
64
65 #if HAVE_SYS_RESOURCE_H
66 #include <sys/types.h>
67 #include <sys/time.h>
68 #include <sys/resource.h>
69 #elif HAVE_GETPROCESSTIMES
70 #include <windows.h>
71 #endif
72 #if HAVE_GETPROCESSMEMORYINFO
73 #include <windows.h>
74 #include <psapi.h>
75 #endif
76
77 #if HAVE_SYS_SELECT_H
78 #include <sys/select.h>
79 #endif
80
81 #if HAVE_TERMIOS_H
82 #include <fcntl.h>
83 #include <sys/ioctl.h>
84 #include <sys/time.h>
85 #include <termios.h>
86 #elif HAVE_KBHIT
87 #include <conio.h>
88 #endif
89 #include <time.h>
90
91 #include "cmdutils.h"
92
93 #include "libavutil/avassert.h"
94
95 #define VSYNC_AUTO       -1
96 #define VSYNC_PASSTHROUGH 0
97 #define VSYNC_CFR         1
98 #define VSYNC_VFR         2
99 #define VSYNC_DROP        0xff
100
101 const char program_name[] = "ffmpeg";
102 const int program_birth_year = 2000;
103
104 /* select an input stream for an output stream */
105 typedef struct StreamMap {
106     int disabled;           /** 1 is this mapping is disabled by a negative map */
107     int file_index;
108     int stream_index;
109     int sync_file_index;
110     int sync_stream_index;
111     char *linklabel;       /** name of an output link, for mapping lavfi outputs */
112 } StreamMap;
113
114 typedef struct {
115     int  file_idx,  stream_idx,  channel_idx; // input
116     int ofile_idx, ostream_idx;               // output
117 } AudioChannelMap;
118
119 static const OptionDef options[];
120
121 #define MAX_STREAMS 1024    /* arbitrary sanity check value */
122
123 static int frame_bits_per_raw_sample = 0;
124 static int video_discard = 0;
125 static int same_quant = 0;
126 static int do_deinterlace = 0;
127 static int intra_dc_precision = 8;
128 static int qp_hist = 0;
129 static int intra_only = 0;
130 static const char *video_codec_name    = NULL;
131 static const char *audio_codec_name    = NULL;
132 static const char *subtitle_codec_name = NULL;
133
134 static int file_overwrite = 0;
135 static int no_file_overwrite = 0;
136 static int do_benchmark = 0;
137 static int do_benchmark_all = 0;
138 static int do_hex_dump = 0;
139 static int do_pkt_dump = 0;
140 static int do_psnr = 0;
141 static int do_pass = 0;
142 static const char *pass_logfilename_prefix;
143 static int video_sync_method = VSYNC_AUTO;
144 static int audio_sync_method = 0;
145 static float audio_drift_threshold = 0.1;
146 static int copy_ts = 0;
147 static int copy_tb = -1;
148 static int opt_shortest = 0;
149 static char *vstats_filename;
150 static FILE *vstats_file;
151
152 static int audio_volume = 256;
153
154 static int exit_on_error = 0;
155 static int using_stdin = 0;
156 static int run_as_daemon  = 0;
157 static volatile int received_nb_signals = 0;
158 static int64_t video_size = 0;
159 static int64_t audio_size = 0;
160 static int64_t extra_size = 0;
161 static int nb_frames_dup = 0;
162 static int nb_frames_drop = 0;
163 static int input_sync;
164
165 static float dts_delta_threshold = 10;
166 static float dts_error_threshold = 3600*30;
167
168 static int print_stats = 1;
169 static int debug_ts = 0;
170 static int current_time;
171
172 static uint8_t *audio_buf;
173 static unsigned int allocated_audio_buf_size;
174 static uint8_t *async_buf;
175 static unsigned int allocated_async_buf_size;
176
177 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
178
179 typedef struct InputFilter {
180     AVFilterContext    *filter;
181     struct InputStream *ist;
182     struct FilterGraph *graph;
183 } InputFilter;
184
185 typedef struct OutputFilter {
186     AVFilterContext     *filter;
187     struct OutputStream *ost;
188     struct FilterGraph  *graph;
189
190     /* temporary storage until stream maps are processed */
191     AVFilterInOut       *out_tmp;
192 } OutputFilter;
193
194 typedef struct FilterGraph {
195     int            index;
196     const char    *graph_desc;
197
198     AVFilterGraph *graph;
199
200     InputFilter   **inputs;
201     int          nb_inputs;
202     OutputFilter **outputs;
203     int         nb_outputs;
204 } FilterGraph;
205
206 typedef struct FrameBuffer {
207     uint8_t *base[4];
208     uint8_t *data[4];
209     int  linesize[4];
210
211     int h, w;
212     enum PixelFormat pix_fmt;
213
214     int refcount;
215     struct InputStream *ist;
216     struct FrameBuffer *next;
217 } FrameBuffer;
218
219 typedef struct InputStream {
220     int file_index;
221     AVStream *st;
222     int discard;             /* true if stream data should be discarded */
223     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
224     AVCodec *dec;
225     AVFrame *decoded_frame;
226
227     int64_t       start;     /* time when read started */
228     /* predicted dts of the next packet read for this stream or (when there are
229      * several frames in a packet) of the next frame in current packet */
230     int64_t       next_dts;
231     /* dts of the last packet read for this stream */
232     int64_t       dts;
233
234     int64_t       next_pts;  ///< synthetic pts for the next decode frame
235     int64_t       pts;       ///< current pts of the decoded frame
236     double ts_scale;
237     int is_start;            /* is 1 at the start and after a discontinuity */
238     int showed_multi_packet_warning;
239     AVDictionary *opts;
240
241     int resample_height;
242     int resample_width;
243     int resample_pix_fmt;
244
245     /* a pool of free buffers for decoded data */
246     FrameBuffer *buffer_pool;
247     int dr1;
248
249     /* decoded data from this stream goes into all those filters
250      * currently video only */
251     InputFilter **filters;
252     int        nb_filters;
253 } InputStream;
254
255 typedef struct InputFile {
256     AVFormatContext *ctx;
257     int eof_reached;      /* true if eof reached */
258     int ist_index;        /* index of first stream in input_streams */
259     int buffer_size;      /* current total buffer size */
260     int64_t ts_offset;
261     int nb_streams;       /* number of stream that ffmpeg is aware of; may be different
262                              from ctx.nb_streams if new streams appear during av_read_frame() */
263     int rate_emu;
264 } InputFile;
265
266 typedef struct OutputStream {
267     int file_index;          /* file index */
268     int index;               /* stream index in the output file */
269     int source_index;        /* InputStream index */
270     AVStream *st;            /* stream in the output file */
271     int encoding_needed;     /* true if encoding needed for this stream */
272     int frame_number;
273     /* input pts and corresponding output pts
274        for A/V sync */
275     struct InputStream *sync_ist; /* input stream to sync against */
276     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ // FIXME look at frame_number
277     AVBitStreamFilterContext *bitstream_filters;
278     AVCodec *enc;
279     int64_t max_frames;
280     AVFrame *output_frame;
281     AVFrame *filtered_frame;
282
283     /* video only */
284     AVRational frame_rate;
285     int force_fps;
286     int top_field_first;
287
288     float frame_aspect_ratio;
289     float last_quality;
290
291     /* forced key frames */
292     int64_t *forced_kf_pts;
293     int forced_kf_count;
294     int forced_kf_index;
295
296     /* audio only */
297     int audio_resample;
298     int audio_channels_map[SWR_CH_MAX];  ///< list of the channels id to pick from the source stream
299     int audio_channels_mapped;           ///< number of channels in audio_channels_map
300     int resample_sample_fmt;
301     int resample_channels;
302     int resample_sample_rate;
303     float rematrix_volume;
304     AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
305     FILE *logfile;
306
307     SwrContext *swr;
308
309     OutputFilter *filter;
310     char *avfilter;
311
312     int64_t sws_flags;
313     int64_t swr_dither_method;
314     double swr_dither_scale;
315     AVDictionary *opts;
316     int is_past_recording_time;
317     int stream_copy;
318     const char *attachment_filename;
319     int copy_initial_nonkeyframes;
320
321     enum PixelFormat pix_fmts[2];
322 } OutputStream;
323
324
325 #if HAVE_TERMIOS_H
326
327 /* init terminal so that we can grab keys */
328 static struct termios oldtty;
329 static int restore_tty;
330 #endif
331
332 typedef struct OutputFile {
333     AVFormatContext *ctx;
334     AVDictionary *opts;
335     int ost_index;       /* index of the first stream in output_streams */
336     int64_t recording_time; /* desired length of the resulting file in microseconds */
337     int64_t start_time;     /* start time in microseconds */
338     uint64_t limit_filesize; /* filesize limit expressed in bytes */
339 } OutputFile;
340
341 static InputStream **input_streams = NULL;
342 static int        nb_input_streams = 0;
343 static InputFile   **input_files   = NULL;
344 static int        nb_input_files   = 0;
345
346 static OutputStream **output_streams = NULL;
347 static int         nb_output_streams = 0;
348 static OutputFile   **output_files   = NULL;
349 static int         nb_output_files   = 0;
350
351 static FilterGraph **filtergraphs;
352 int               nb_filtergraphs;
353
354 typedef struct OptionsContext {
355     /* input/output options */
356     int64_t start_time;
357     const char *format;
358
359     SpecifierOpt *codec_names;
360     int        nb_codec_names;
361     SpecifierOpt *audio_channels;
362     int        nb_audio_channels;
363     SpecifierOpt *audio_sample_rate;
364     int        nb_audio_sample_rate;
365     SpecifierOpt *rematrix_volume;
366     int        nb_rematrix_volume;
367     SpecifierOpt *frame_rates;
368     int        nb_frame_rates;
369     SpecifierOpt *frame_sizes;
370     int        nb_frame_sizes;
371     SpecifierOpt *frame_pix_fmts;
372     int        nb_frame_pix_fmts;
373
374     /* input options */
375     int64_t input_ts_offset;
376     int rate_emu;
377
378     SpecifierOpt *ts_scale;
379     int        nb_ts_scale;
380     SpecifierOpt *dump_attachment;
381     int        nb_dump_attachment;
382
383     /* output options */
384     StreamMap *stream_maps;
385     int     nb_stream_maps;
386     AudioChannelMap *audio_channel_maps; ///< one info entry per -map_channel
387     int           nb_audio_channel_maps; ///< number of (valid) -map_channel settings
388     int metadata_global_manual;
389     int metadata_streams_manual;
390     int metadata_chapters_manual;
391     const char **attachments;
392     int       nb_attachments;
393
394     int chapters_input_file;
395
396     int64_t recording_time;
397     uint64_t limit_filesize;
398     float mux_preload;
399     float mux_max_delay;
400
401     int video_disable;
402     int audio_disable;
403     int subtitle_disable;
404     int data_disable;
405
406     /* indexed by output file stream index */
407     int   *streamid_map;
408     int nb_streamid_map;
409
410     SpecifierOpt *metadata;
411     int        nb_metadata;
412     SpecifierOpt *max_frames;
413     int        nb_max_frames;
414     SpecifierOpt *bitstream_filters;
415     int        nb_bitstream_filters;
416     SpecifierOpt *codec_tags;
417     int        nb_codec_tags;
418     SpecifierOpt *sample_fmts;
419     int        nb_sample_fmts;
420     SpecifierOpt *qscale;
421     int        nb_qscale;
422     SpecifierOpt *forced_key_frames;
423     int        nb_forced_key_frames;
424     SpecifierOpt *force_fps;
425     int        nb_force_fps;
426     SpecifierOpt *frame_aspect_ratios;
427     int        nb_frame_aspect_ratios;
428     SpecifierOpt *rc_overrides;
429     int        nb_rc_overrides;
430     SpecifierOpt *intra_matrices;
431     int        nb_intra_matrices;
432     SpecifierOpt *inter_matrices;
433     int        nb_inter_matrices;
434     SpecifierOpt *top_field_first;
435     int        nb_top_field_first;
436     SpecifierOpt *metadata_map;
437     int        nb_metadata_map;
438     SpecifierOpt *presets;
439     int        nb_presets;
440     SpecifierOpt *copy_initial_nonkeyframes;
441     int        nb_copy_initial_nonkeyframes;
442     SpecifierOpt *filters;
443     int        nb_filters;
444 } OptionsContext;
445
446 #define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
447 {\
448     int i, ret;\
449     for (i = 0; i < o->nb_ ## name; i++) {\
450         char *spec = o->name[i].specifier;\
451         if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
452             outvar = o->name[i].u.type;\
453         else if (ret < 0)\
454             exit_program(1);\
455     }\
456 }
457
458 static int64_t getutime(void)
459 {
460 #if HAVE_GETRUSAGE
461     struct rusage rusage;
462
463     getrusage(RUSAGE_SELF, &rusage);
464     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
465 #elif HAVE_GETPROCESSTIMES
466     HANDLE proc;
467     FILETIME c, e, k, u;
468     proc = GetCurrentProcess();
469     GetProcessTimes(proc, &c, &e, &k, &u);
470     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
471 #else
472     return av_gettime();
473 #endif
474 }
475
476 static void update_benchmark(const char *fmt, ...)
477 {
478     if (do_benchmark_all) {
479         int64_t t = getutime();
480         va_list va;
481         char buf[1024];
482
483         if (fmt) {
484             va_start(va, fmt);
485             vsnprintf(buf, sizeof(buf), fmt, va);
486             va_end(va);
487             printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
488         }
489         current_time = t;
490     }
491 }
492
493 static void reset_options(OptionsContext *o, int is_input)
494 {
495     const OptionDef *po = options;
496     OptionsContext bak= *o;
497     int i;
498
499     /* all OPT_SPEC and OPT_STRING can be freed in generic way */
500     while (po->name) {
501         void *dst = (uint8_t*)o + po->u.off;
502
503         if (po->flags & OPT_SPEC) {
504             SpecifierOpt **so = dst;
505             int i, *count = (int*)(so + 1);
506             for (i = 0; i < *count; i++) {
507                 av_freep(&(*so)[i].specifier);
508                 if (po->flags & OPT_STRING)
509                     av_freep(&(*so)[i].u.str);
510             }
511             av_freep(so);
512             *count = 0;
513         } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
514             av_freep(dst);
515         po++;
516     }
517
518     for (i = 0; i < o->nb_stream_maps; i++)
519         av_freep(&o->stream_maps[i].linklabel);
520     av_freep(&o->stream_maps);
521     av_freep(&o->audio_channel_maps);
522     av_freep(&o->streamid_map);
523
524     memset(o, 0, sizeof(*o));
525
526     if(is_input) o->recording_time = bak.recording_time;
527     else         o->recording_time = INT64_MAX;
528     o->mux_max_delay  = 0.7;
529     o->limit_filesize = UINT64_MAX;
530     o->chapters_input_file = INT_MAX;
531
532     uninit_opts();
533     init_opts();
534 }
535
536 static int alloc_buffer(InputStream *ist, AVCodecContext *s, FrameBuffer **pbuf)
537 {
538     FrameBuffer  *buf = av_mallocz(sizeof(*buf));
539     int i, ret;
540     const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;
541     int h_chroma_shift, v_chroma_shift;
542     int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1
543     int w = s->width, h = s->height;
544
545     if (!buf)
546         return AVERROR(ENOMEM);
547
548     if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {
549         w += 2*edge;
550         h += 2*edge;
551     }
552
553     avcodec_align_dimensions(s, &w, &h);
554     if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,
555                               s->pix_fmt, 32)) < 0) {
556         av_freep(&buf);
557         return ret;
558     }
559     /* XXX this shouldn't be needed, but some tests break without this line
560      * those decoders are buggy and need to be fixed.
561      * the following tests fail:
562      * cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit
563      */
564     memset(buf->base[0], 128, ret);
565
566     avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);
567     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
568         const int h_shift = i==0 ? 0 : h_chroma_shift;
569         const int v_shift = i==0 ? 0 : v_chroma_shift;
570         if ((s->flags & CODEC_FLAG_EMU_EDGE) || !buf->linesize[1])
571             buf->data[i] = buf->base[i];
572         else
573             buf->data[i] = buf->base[i] +
574                            FFALIGN((buf->linesize[i]*edge >> v_shift) +
575                                    (pixel_size*edge >> h_shift), 32);
576     }
577     buf->w       = s->width;
578     buf->h       = s->height;
579     buf->pix_fmt = s->pix_fmt;
580     buf->ist     = ist;
581
582     *pbuf = buf;
583     return 0;
584 }
585
586 static void free_buffer_pool(InputStream *ist)
587 {
588     FrameBuffer *buf = ist->buffer_pool;
589     while (buf) {
590         ist->buffer_pool = buf->next;
591         av_freep(&buf->base[0]);
592         av_free(buf);
593         buf = ist->buffer_pool;
594     }
595 }
596
597 static void unref_buffer(InputStream *ist, FrameBuffer *buf)
598 {
599     av_assert0(buf->refcount);
600     buf->refcount--;
601     if (!buf->refcount) {
602         buf->next = ist->buffer_pool;
603         ist->buffer_pool = buf;
604     }
605 }
606
607 static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)
608 {
609     InputStream *ist = s->opaque;
610     FrameBuffer *buf;
611     int ret, i;
612
613     if(av_image_check_size(s->width, s->height, 0, s) || s->pix_fmt<0)
614         return -1;
615
616     if (!ist->buffer_pool && (ret = alloc_buffer(ist, s, &ist->buffer_pool)) < 0)
617         return ret;
618
619     buf              = ist->buffer_pool;
620     ist->buffer_pool = buf->next;
621     buf->next        = NULL;
622     if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {
623         av_freep(&buf->base[0]);
624         av_free(buf);
625         if ((ret = alloc_buffer(ist, s, &buf)) < 0)
626             return ret;
627     }
628     buf->refcount++;
629
630     frame->opaque        = buf;
631     frame->type          = FF_BUFFER_TYPE_USER;
632     frame->extended_data = frame->data;
633     frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;
634     frame->width         = buf->w;
635     frame->height        = buf->h;
636     frame->format        = buf->pix_fmt;
637     frame->sample_aspect_ratio = s->sample_aspect_ratio;
638
639     for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {
640         frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't
641         frame->data[i]     = buf->data[i];
642         frame->linesize[i] = buf->linesize[i];
643     }
644
645     return 0;
646 }
647
648 static void codec_release_buffer(AVCodecContext *s, AVFrame *frame)
649 {
650     InputStream *ist = s->opaque;
651     FrameBuffer *buf = frame->opaque;
652     int i;
653
654     if(frame->type!=FF_BUFFER_TYPE_USER)
655         return avcodec_default_release_buffer(s, frame);
656
657     for (i = 0; i < FF_ARRAY_ELEMS(frame->data); i++)
658         frame->data[i] = NULL;
659
660     unref_buffer(ist, buf);
661 }
662
663 static void filter_release_buffer(AVFilterBuffer *fb)
664 {
665     FrameBuffer *buf = fb->priv;
666     av_free(fb);
667     unref_buffer(buf->ist, buf);
668 }
669
670 static enum PixelFormat choose_pixel_fmt(AVStream *st, AVCodec *codec, enum PixelFormat target)
671 {
672     if (codec && codec->pix_fmts) {
673         const enum PixelFormat *p = codec->pix_fmts;
674         int has_alpha= av_pix_fmt_descriptors[target].nb_components % 2 == 0;
675         enum PixelFormat best= PIX_FMT_NONE;
676         if (st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
677             if (st->codec->codec_id == CODEC_ID_MJPEG) {
678                 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
679             } else if (st->codec->codec_id == CODEC_ID_LJPEG) {
680                 p = (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
681                                                  PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
682             }
683         }
684         for (; *p != PIX_FMT_NONE; p++) {
685             best= avcodec_find_best_pix_fmt2(best, *p, target, has_alpha, NULL);
686             if (*p == target)
687                 break;
688         }
689         if (*p == PIX_FMT_NONE) {
690             if (target != PIX_FMT_NONE)
691                 av_log(NULL, AV_LOG_WARNING,
692                        "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
693                        av_pix_fmt_descriptors[target].name,
694                        codec->name,
695                        av_pix_fmt_descriptors[best].name);
696             return best;
697         }
698     }
699     return target;
700 }
701
702 static const enum PixelFormat *choose_pixel_fmts(OutputStream *ost)
703 {
704     if (ost->st->codec->pix_fmt != PIX_FMT_NONE) {
705         ost->pix_fmts[0] = choose_pixel_fmt(ost->st, ost->enc, ost->st->codec->pix_fmt);
706         return ost->pix_fmts;
707     } else if (ost->enc->pix_fmts) {
708         if (ost->st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
709             if (ost->st->codec->codec_id == CODEC_ID_MJPEG) {
710                 return (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE };
711             } else if (ost->st->codec->codec_id == CODEC_ID_LJPEG) {
712                 return (const enum PixelFormat[]) { PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P,
713                                                     PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE };
714             }
715         }
716         return ost->enc->pix_fmts;
717     } else
718         return NULL;
719 }
720
721 static int configure_video_filters(FilterGraph *fg)
722 {
723     InputStream  *ist = fg->inputs[0]->ist;
724     OutputStream *ost = fg->outputs[0]->ost;
725     AVFilterContext *last_filter, *filter;
726     /** filter graph containing all filters including input & output */
727     AVCodecContext *codec = ost->st->codec;
728     enum PixelFormat *pix_fmts = choose_pixel_fmts(ost);
729     AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
730     AVRational sample_aspect_ratio;
731     char args[255];
732     int ret;
733
734     avfilter_graph_free(&fg->graph);
735     fg->graph = avfilter_graph_alloc();
736     if (!fg->graph)
737         return AVERROR(ENOMEM);
738
739     if (ist->st->sample_aspect_ratio.num) {
740         sample_aspect_ratio = ist->st->sample_aspect_ratio;
741     } else
742         sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
743
744     snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d:flags=%d", ist->st->codec->width,
745              ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
746              sample_aspect_ratio.num, sample_aspect_ratio.den, SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
747
748     ret = avfilter_graph_create_filter(&fg->inputs[0]->filter,
749                                        avfilter_get_by_name("buffer"),
750                                        "src", args, NULL, fg->graph);
751     if (ret < 0)
752         return ret;
753
754 #if FF_API_OLD_VSINK_API
755     ret = avfilter_graph_create_filter(&fg->outputs[0]->filter, avfilter_get_by_name("buffersink"),
756                                        "out", NULL, pix_fmts, fg->graph);
757 #else
758     buffersink_params->pixel_fmts = pix_fmts;
759     ret = avfilter_graph_create_filter(&fg->outputs[0]->filter, avfilter_get_by_name("buffersink"),
760                                        "out", NULL, buffersink_params, fg->graph);
761 #endif
762     av_freep(&buffersink_params);
763
764     if (ret < 0)
765         return ret;
766     last_filter = fg->inputs[0]->filter;
767
768     if (codec->width || codec->height) {
769         snprintf(args, 255, "%d:%d:flags=0x%X",
770                  codec->width,
771                  codec->height,
772                  (unsigned)ost->sws_flags);
773         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
774                                                 NULL, args, NULL, fg->graph)) < 0)
775             return ret;
776         if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
777             return ret;
778         last_filter = filter;
779     }
780
781     snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
782     fg->graph->scale_sws_opts = av_strdup(args);
783
784     if (ost->avfilter) {
785         AVFilterInOut *outputs = avfilter_inout_alloc();
786         AVFilterInOut *inputs  = avfilter_inout_alloc();
787
788         outputs->name    = av_strdup("in");
789         outputs->filter_ctx = last_filter;
790         outputs->pad_idx = 0;
791         outputs->next    = NULL;
792
793         inputs->name    = av_strdup("out");
794         inputs->filter_ctx = fg->outputs[0]->filter;
795         inputs->pad_idx = 0;
796         inputs->next    = NULL;
797
798         if ((ret = avfilter_graph_parse(fg->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
799             return ret;
800         av_freep(&ost->avfilter);
801     } else {
802         if ((ret = avfilter_link(last_filter, 0, fg->outputs[0]->filter, 0)) < 0)
803             return ret;
804     }
805
806     if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
807         return ret;
808
809     ost->filter = fg->outputs[0];
810
811     return 0;
812 }
813
814 static FilterGraph *init_simple_filtergraph(InputStream *ist, OutputStream *ost)
815 {
816     FilterGraph *fg = av_mallocz(sizeof(*fg));
817
818     if (!fg)
819         exit_program(1);
820     fg->index = nb_filtergraphs;
821
822     fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs), &fg->nb_outputs,
823                              fg->nb_outputs + 1);
824     if (!(fg->outputs[0] = av_mallocz(sizeof(*fg->outputs[0]))))
825         exit_program(1);
826     fg->outputs[0]->ost   = ost;
827     fg->outputs[0]->graph = fg;
828
829     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs), &fg->nb_inputs,
830                             fg->nb_inputs + 1);
831     if (!(fg->inputs[0] = av_mallocz(sizeof(*fg->inputs[0]))))
832         exit_program(1);
833     fg->inputs[0]->ist   = ist;
834     fg->inputs[0]->graph = fg;
835
836     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
837                               &ist->nb_filters, ist->nb_filters + 1);
838     ist->filters[ist->nb_filters - 1] = fg->inputs[0];
839
840     filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
841                               &nb_filtergraphs, nb_filtergraphs + 1);
842     filtergraphs[nb_filtergraphs - 1] = fg;
843
844     return fg;
845 }
846
847 static void init_input_filter(FilterGraph *fg, AVFilterInOut *in)
848 {
849     InputStream *ist;
850     enum AVMediaType type = in->filter_ctx->input_pads[in->pad_idx].type;
851     int i;
852
853     // TODO: support other filter types
854     if (type != AVMEDIA_TYPE_VIDEO) {
855         av_log(NULL, AV_LOG_FATAL, "Only video filters supported currently.\n");
856         exit_program(1);
857     }
858
859     if (in->name) {
860         AVFormatContext *s;
861         AVStream       *st = NULL;
862         char *p;
863         int file_idx = strtol(in->name, &p, 0);
864
865         if (file_idx < 0 || file_idx > nb_input_files) {
866             av_log(NULL, AV_LOG_FATAL, "Invalid file index %d in filtegraph description %s.\n",
867                    file_idx, fg->graph_desc);
868             exit_program(1);
869         }
870         s = input_files[file_idx]->ctx;
871
872         for (i = 0; i < s->nb_streams; i++) {
873             if (s->streams[i]->codec->codec_type != type)
874                 continue;
875             if (check_stream_specifier(s, s->streams[i], *p == ':' ? p + 1 : p) == 1) {
876                 st = s->streams[i];
877                 break;
878             }
879         }
880         if (!st) {
881             av_log(NULL, AV_LOG_FATAL, "Stream specifier '%s' in filtergraph description %s "
882                    "matches no streams.\n", p, fg->graph_desc);
883             exit_program(1);
884         }
885         ist = input_streams[input_files[file_idx]->ist_index + st->index];
886     } else {
887         /* find the first unused stream of corresponding type */
888         for (i = 0; i < nb_input_streams; i++) {
889             ist = input_streams[i];
890             if (ist->st->codec->codec_type == type && ist->discard)
891                 break;
892         }
893         if (i == nb_input_streams) {
894             av_log(NULL, AV_LOG_FATAL, "Cannot find a matching stream for "
895                    "unlabeled input pad %d on filter %s", in->pad_idx,
896                    in->filter_ctx->name);
897             exit_program(1);
898         }
899     }
900     ist->discard         = 0;
901     ist->decoding_needed = 1;
902     ist->st->discard = AVDISCARD_NONE;
903
904     fg->inputs = grow_array(fg->inputs, sizeof(*fg->inputs),
905                             &fg->nb_inputs, fg->nb_inputs + 1);
906     if (!(fg->inputs[fg->nb_inputs - 1] = av_mallocz(sizeof(*fg->inputs[0]))))
907         exit_program(1);
908     fg->inputs[fg->nb_inputs - 1]->ist   = ist;
909     fg->inputs[fg->nb_inputs - 1]->graph = fg;
910
911     ist->filters = grow_array(ist->filters, sizeof(*ist->filters),
912                               &ist->nb_filters, ist->nb_filters + 1);
913     ist->filters[ist->nb_filters - 1] = fg->inputs[fg->nb_inputs - 1];
914 }
915
916 static int configure_output_filter(FilterGraph *fg, OutputFilter *ofilter, AVFilterInOut *out)
917 {
918     AVCodecContext *codec = ofilter->ost->st->codec;
919     AVFilterContext *last_filter = out->filter_ctx;
920     int pad_idx = out->pad_idx;
921     int ret;
922     enum PixelFormat *pix_fmts = choose_pixel_fmts(ofilter->ost);
923     AVBufferSinkParams *buffersink_params = av_buffersink_params_alloc();
924
925 #if FF_API_OLD_VSINK_API
926     ret = avfilter_graph_create_filter(&ofilter->filter, avfilter_get_by_name("buffersink"),
927                                        "out", NULL, pix_fmts, fg->graph);
928 #else
929     buffersink_params->pixel_fmts = pix_fmts;
930     ret = avfilter_graph_create_filter(&ofilter->filter, avfilter_get_by_name("buffersink"),
931                                        "out", NULL, buffersink_params, fg->graph);
932 #endif
933     av_freep(&buffersink_params);
934
935     if (ret < 0)
936         return ret;
937
938     if (codec->width || codec->height) {
939         char args[255];
940         snprintf(args, sizeof(args), "%d:%d:flags=0x%X",
941                  codec->width,
942                  codec->height,
943                  (unsigned)ofilter->ost->sws_flags);
944         if ((ret = avfilter_graph_create_filter(&last_filter, avfilter_get_by_name("scale"),
945                                                 NULL, args, NULL, fg->graph)) < 0)
946             return ret;
947         if ((ret = avfilter_link(out->filter_ctx, out->pad_idx, last_filter, 0)) < 0)
948             return ret;
949         pad_idx = 0;
950     }
951
952     if ((ret = avfilter_link(last_filter, pad_idx, ofilter->filter, 0)) < 0)
953         return ret;
954
955     return 0;
956 }
957
958 static int configure_complex_filter(FilterGraph *fg)
959 {
960     AVFilterInOut *inputs, *outputs, *cur;
961     int ret, i, init = !fg->graph;
962
963     avfilter_graph_free(&fg->graph);
964     if (!(fg->graph = avfilter_graph_alloc()))
965         return AVERROR(ENOMEM);
966
967     if ((ret = avfilter_graph_parse2(fg->graph, fg->graph_desc, &inputs, &outputs)) < 0)
968         return ret;
969
970     for (cur = inputs; init && cur; cur = cur->next)
971         init_input_filter(fg, cur);
972
973     for (cur = inputs, i = 0; cur; cur = cur->next, i++) {
974         InputFilter *ifilter = fg->inputs[i];
975         InputStream     *ist = ifilter->ist;
976         AVRational       sar;
977         char            args[255];
978
979         sar = ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
980                                                  ist->st->codec->sample_aspect_ratio;
981         snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
982                  ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
983                  sar.num, sar.den);
984
985         if ((ret = avfilter_graph_create_filter(&ifilter->filter,
986                                                 avfilter_get_by_name("buffer"), cur->name,
987                                                 args, NULL, fg->graph)) < 0)
988             return ret;
989         if ((ret = avfilter_link(ifilter->filter, 0,
990                                  cur->filter_ctx, cur->pad_idx)) < 0)
991             return ret;
992     }
993     avfilter_inout_free(&inputs);
994
995     if (!init) {
996         /* we already know the mappings between lavfi outputs and output streams,
997          * so we can finish the setup */
998         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
999             configure_output_filter(fg, fg->outputs[i], cur);
1000         avfilter_inout_free(&outputs);
1001
1002         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1003             return ret;
1004     } else {
1005         /* wait until output mappings are processed */
1006         for (cur = outputs; cur;) {
1007             fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
1008                                      &fg->nb_outputs, fg->nb_outputs + 1);
1009             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
1010                 exit_program(1);
1011             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
1012             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
1013             cur = cur->next;
1014             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
1015         }
1016     }
1017
1018     return 0;
1019 }
1020
1021 static int configure_complex_filters(void)
1022 {
1023     int i, ret = 0;
1024
1025     for (i = 0; i < nb_filtergraphs; i++)
1026         if (!filtergraphs[i]->graph &&
1027             (ret = configure_complex_filter(filtergraphs[i])) < 0)
1028             return ret;
1029     return 0;
1030 }
1031
1032 static int configure_filtergraph(FilterGraph *fg)
1033 {
1034     return fg->graph_desc ? configure_complex_filter(fg) : configure_video_filters(fg);
1035 }
1036
1037 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1038 {
1039     int i;
1040     for (i = 0; i < fg->nb_inputs; i++)
1041         if (fg->inputs[i]->ist == ist)
1042             return 1;
1043     return 0;
1044 }
1045
1046 static void term_exit(void)
1047 {
1048     av_log(NULL, AV_LOG_QUIET, "%s", "");
1049 #if HAVE_TERMIOS_H
1050     if(restore_tty)
1051         tcsetattr (0, TCSANOW, &oldtty);
1052 #endif
1053 }
1054
1055 static volatile int received_sigterm = 0;
1056
1057 static void sigterm_handler(int sig)
1058 {
1059     received_sigterm = sig;
1060     received_nb_signals++;
1061     term_exit();
1062     if(received_nb_signals > 3)
1063         exit(123);
1064 }
1065
1066 static void term_init(void)
1067 {
1068 #if HAVE_TERMIOS_H
1069     if(!run_as_daemon){
1070     struct termios tty;
1071
1072     if (tcgetattr (0, &tty) == 0) {
1073     oldtty = tty;
1074     restore_tty = 1;
1075     atexit(term_exit);
1076
1077     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1078                           |INLCR|IGNCR|ICRNL|IXON);
1079     tty.c_oflag |= OPOST;
1080     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1081     tty.c_cflag &= ~(CSIZE|PARENB);
1082     tty.c_cflag |= CS8;
1083     tty.c_cc[VMIN] = 1;
1084     tty.c_cc[VTIME] = 0;
1085
1086     tcsetattr (0, TCSANOW, &tty);
1087     }
1088     signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
1089     }
1090 #endif
1091     avformat_network_deinit();
1092
1093     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
1094     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
1095 #ifdef SIGXCPU
1096     signal(SIGXCPU, sigterm_handler);
1097 #endif
1098 }
1099
1100 /* read a key without blocking */
1101 static int read_key(void)
1102 {
1103     unsigned char ch;
1104 #if HAVE_TERMIOS_H
1105     int n = 1;
1106     struct timeval tv;
1107     fd_set rfds;
1108
1109     FD_ZERO(&rfds);
1110     FD_SET(0, &rfds);
1111     tv.tv_sec = 0;
1112     tv.tv_usec = 0;
1113     n = select(1, &rfds, NULL, NULL, &tv);
1114     if (n > 0) {
1115         n = read(0, &ch, 1);
1116         if (n == 1)
1117             return ch;
1118
1119         return n;
1120     }
1121 #elif HAVE_KBHIT
1122 #    if HAVE_PEEKNAMEDPIPE
1123     static int is_pipe;
1124     static HANDLE input_handle;
1125     DWORD dw, nchars;
1126     if(!input_handle){
1127         input_handle = GetStdHandle(STD_INPUT_HANDLE);
1128         is_pipe = !GetConsoleMode(input_handle, &dw);
1129     }
1130
1131     if (stdin->_cnt > 0) {
1132         read(0, &ch, 1);
1133         return ch;
1134     }
1135     if (is_pipe) {
1136         /* When running under a GUI, you will end here. */
1137         if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
1138             return -1;
1139         //Read it
1140         if(nchars != 0) {
1141             read(0, &ch, 1);
1142             return ch;
1143         }else{
1144             return -1;
1145         }
1146     }
1147 #    endif
1148     if(kbhit())
1149         return(getch());
1150 #endif
1151     return -1;
1152 }
1153
1154 static int decode_interrupt_cb(void *ctx)
1155 {
1156     return received_nb_signals > 1;
1157 }
1158
1159 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1160
1161 void av_noreturn exit_program(int ret)
1162 {
1163     int i, j;
1164
1165     for (i = 0; i < nb_filtergraphs; i++) {
1166         avfilter_graph_free(&filtergraphs[i]->graph);
1167         for (j = 0; j < filtergraphs[i]->nb_inputs; j++)
1168             av_freep(&filtergraphs[i]->inputs[j]);
1169         av_freep(&filtergraphs[i]->inputs);
1170         for (j = 0; j < filtergraphs[i]->nb_outputs; j++)
1171             av_freep(&filtergraphs[i]->outputs[j]);
1172         av_freep(&filtergraphs[i]->outputs);
1173         av_freep(&filtergraphs[i]);
1174     }
1175     av_freep(&filtergraphs);
1176
1177     /* close files */
1178     for (i = 0; i < nb_output_files; i++) {
1179         AVFormatContext *s = output_files[i]->ctx;
1180         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1181             avio_close(s->pb);
1182         avformat_free_context(s);
1183         av_dict_free(&output_files[i]->opts);
1184         av_freep(&output_files[i]);
1185     }
1186     for (i = 0; i < nb_output_streams; i++) {
1187         AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1188         while (bsfc) {
1189             AVBitStreamFilterContext *next = bsfc->next;
1190             av_bitstream_filter_close(bsfc);
1191             bsfc = next;
1192         }
1193         output_streams[i]->bitstream_filters = NULL;
1194
1195         if (output_streams[i]->output_frame) {
1196             AVFrame *frame = output_streams[i]->output_frame;
1197             if (frame->extended_data != frame->data)
1198                 av_freep(&frame->extended_data);
1199             av_freep(&frame);
1200         }
1201         av_freep(&output_streams[i]->filtered_frame);
1202         av_freep(&output_streams[i]);
1203     }
1204     for (i = 0; i < nb_input_files; i++) {
1205         avformat_close_input(&input_files[i]->ctx);
1206         av_freep(&input_files[i]);
1207     }
1208     for (i = 0; i < nb_input_streams; i++) {
1209         av_freep(&input_streams[i]->decoded_frame);
1210         av_dict_free(&input_streams[i]->opts);
1211         free_buffer_pool(input_streams[i]);
1212         av_freep(&input_streams[i]->filters);
1213         av_freep(&input_streams[i]);
1214     }
1215
1216     if (vstats_file)
1217         fclose(vstats_file);
1218     av_free(vstats_filename);
1219
1220     av_freep(&input_streams);
1221     av_freep(&input_files);
1222     av_freep(&output_streams);
1223     av_freep(&output_files);
1224
1225     uninit_opts();
1226     av_freep(&audio_buf);
1227     allocated_audio_buf_size = 0;
1228     av_freep(&async_buf);
1229     allocated_async_buf_size = 0;
1230
1231     avfilter_uninit();
1232     avformat_network_deinit();
1233
1234     if (received_sigterm) {
1235         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1236                (int) received_sigterm);
1237         exit (255);
1238     }
1239
1240     exit(ret); /* not all OS-es handle main() return value */
1241 }
1242
1243 static void assert_avoptions(AVDictionary *m)
1244 {
1245     AVDictionaryEntry *t;
1246     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1247         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1248         exit_program(1);
1249     }
1250 }
1251
1252 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1253 {
1254     const char *codec_string = encoder ? "encoder" : "decoder";
1255     AVCodec *codec;
1256     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1257         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1258         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1259                 "results.\nAdd '-strict experimental' if you want to use it.\n",
1260                 codec_string, c->codec->name);
1261         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1262         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1263             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1264                    codec_string, codec->name);
1265         exit_program(1);
1266     }
1267 }
1268
1269 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
1270 {
1271     if (codec && codec->sample_fmts) {
1272         const enum AVSampleFormat *p = codec->sample_fmts;
1273         for (; *p != -1; p++) {
1274             if (*p == st->codec->sample_fmt)
1275                 break;
1276         }
1277         if (*p == -1) {
1278             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
1279                 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
1280             if(av_get_sample_fmt_name(st->codec->sample_fmt))
1281             av_log(NULL, AV_LOG_WARNING,
1282                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
1283                    av_get_sample_fmt_name(st->codec->sample_fmt),
1284                    codec->name,
1285                    av_get_sample_fmt_name(codec->sample_fmts[0]));
1286             st->codec->sample_fmt = codec->sample_fmts[0];
1287         }
1288     }
1289 }
1290
1291 static void choose_sample_rate(AVStream *st, AVCodec *codec)
1292 {
1293     if (codec && codec->supported_samplerates) {
1294         const int *p  = codec->supported_samplerates;
1295         int best      = 0;
1296         int best_dist = INT_MAX;
1297         for (; *p; p++) {
1298             int dist = abs(st->codec->sample_rate - *p);
1299             if (dist < best_dist) {
1300                 best_dist = dist;
1301                 best      = *p;
1302             }
1303         }
1304         if (best_dist) {
1305             int i;
1306             const int *sample_rates = codec->supported_samplerates;
1307             av_log(st->codec, AV_LOG_WARNING,
1308                    "Requested sampling rate (%dHz) unsupported, using %dHz instead\n"
1309                    "Available sampling rates for %s:",
1310                    st->codec->sample_rate, best, codec->name);
1311             for (i = 0; sample_rates[i]; i++) {
1312                 if (!sample_rates[i + 1]) av_log(st->codec, AV_LOG_WARNING, " and");
1313                 else if (i)               av_log(st->codec, AV_LOG_WARNING, ",");
1314                 av_log(st->codec, AV_LOG_WARNING, " %d", sample_rates[i]);
1315             }
1316             av_log(st->codec, AV_LOG_WARNING, ".\n");
1317         }
1318         st->codec->sample_rate = best;
1319     }
1320 }
1321
1322 static double
1323 get_sync_ipts(const OutputStream *ost, int64_t pts)
1324 {
1325     OutputFile *of = output_files[ost->file_index];
1326     return (double)(pts - of->start_time) / AV_TIME_BASE;
1327 }
1328
1329 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1330 {
1331     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1332     AVCodecContext          *avctx = ost->st->codec;
1333     int ret;
1334
1335     if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
1336         (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
1337         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1338
1339     /*
1340      * Audio encoders may split the packets --  #frames in != #packets out.
1341      * But there is no reordering, so we can limit the number of output packets
1342      * by simply dropping them here.
1343      * Counting encoded video frames needs to be done separately because of
1344      * reordering, see do_video_out()
1345      */
1346     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1347         if (ost->frame_number >= ost->max_frames) {
1348             av_free_packet(pkt);
1349             return;
1350         }
1351         ost->frame_number++;
1352     }
1353
1354     while (bsfc) {
1355         AVPacket new_pkt = *pkt;
1356         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1357                                            &new_pkt.data, &new_pkt.size,
1358                                            pkt->data, pkt->size,
1359                                            pkt->flags & AV_PKT_FLAG_KEY);
1360         if (a > 0) {
1361             av_free_packet(pkt);
1362             new_pkt.destruct = av_destruct_packet;
1363         } else if (a < 0) {
1364             av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
1365                    bsfc->filter->name, pkt->stream_index,
1366                    avctx->codec ? avctx->codec->name : "copy");
1367             print_error("", a);
1368             if (exit_on_error)
1369                 exit_program(1);
1370         }
1371         *pkt = new_pkt;
1372
1373         bsfc = bsfc->next;
1374     }
1375
1376     pkt->stream_index = ost->index;
1377     ret = av_interleaved_write_frame(s, pkt);
1378     if (ret < 0) {
1379         print_error("av_interleaved_write_frame()", ret);
1380         exit_program(1);
1381     }
1382 }
1383
1384 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
1385 {
1386     int fill_char = 0x00;
1387     if (sample_fmt == AV_SAMPLE_FMT_U8)
1388         fill_char = 0x80;
1389     memset(buf, fill_char, size);
1390 }
1391
1392 static int encode_audio_frame(AVFormatContext *s, OutputStream *ost,
1393                               const uint8_t *buf, int buf_size)
1394 {
1395     AVCodecContext *enc = ost->st->codec;
1396     AVFrame *frame = NULL;
1397     AVPacket pkt;
1398     int ret, got_packet;
1399
1400     av_init_packet(&pkt);
1401     pkt.data = NULL;
1402     pkt.size = 0;
1403
1404     if (buf && buf_size) {
1405         if (!ost->output_frame) {
1406             ost->output_frame = avcodec_alloc_frame();
1407             if (!ost->output_frame) {
1408                 av_log(NULL, AV_LOG_FATAL, "out-of-memory in encode_audio_frame()\n");
1409                 exit_program(1);
1410             }
1411         }
1412         frame = ost->output_frame;
1413         if (frame->extended_data != frame->data)
1414             av_freep(&frame->extended_data);
1415         avcodec_get_frame_defaults(frame);
1416
1417         frame->nb_samples  = buf_size /
1418                              (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));
1419         if ((ret = avcodec_fill_audio_frame(frame, enc->channels, enc->sample_fmt,
1420                                             buf, buf_size, 1)) < 0) {
1421             av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_fill_audio_frame)\n");
1422             exit_program(1);
1423         }
1424
1425         frame->pts = ost->sync_opts;
1426         ost->sync_opts += frame->nb_samples;
1427     }
1428
1429     got_packet = 0;
1430     update_benchmark(NULL);
1431     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1432         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
1433         exit_program(1);
1434     }
1435     update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1436
1437     ret = pkt.size;
1438
1439     if (got_packet) {
1440         if (pkt.pts != AV_NOPTS_VALUE)
1441             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
1442         if (pkt.dts != AV_NOPTS_VALUE) {
1443             int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
1444             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
1445             if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE &&  max > pkt.dts) {
1446                 av_log(s, max - pkt.dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt.dts, max);
1447                 pkt.pts = pkt.dts = max;
1448             }
1449         }
1450         if (pkt.duration > 0)
1451             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1452
1453         write_frame(s, &pkt, ost);
1454
1455         audio_size += pkt.size;
1456
1457         av_free_packet(&pkt);
1458     }
1459
1460     if (debug_ts) {
1461         av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1462                "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1463                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1464                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1465     }
1466
1467     return ret;
1468 }
1469
1470 static int alloc_audio_output_buf(AVCodecContext *dec, AVCodecContext *enc,
1471                                   int nb_samples)
1472 {
1473     int64_t audio_buf_samples;
1474     int audio_buf_size;
1475
1476     /* calculate required number of samples to allocate */
1477     audio_buf_samples = ((int64_t)nb_samples * enc->sample_rate + dec->sample_rate) /
1478                         dec->sample_rate;
1479     audio_buf_samples = 4 * audio_buf_samples + 10000; // safety factors for resampling
1480     audio_buf_samples = FFMAX(audio_buf_samples, enc->frame_size);
1481     if (audio_buf_samples > INT_MAX)
1482         return AVERROR(EINVAL);
1483
1484     audio_buf_size = av_samples_get_buffer_size(NULL, enc->channels,
1485                                                 audio_buf_samples,
1486                                                 enc->sample_fmt, 0);
1487     if (audio_buf_size < 0)
1488         return audio_buf_size;
1489
1490     av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
1491     if (!audio_buf)
1492         return AVERROR(ENOMEM);
1493
1494     return 0;
1495 }
1496
1497 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1498                          InputStream *ist, AVFrame *decoded_frame)
1499 {
1500     uint8_t *buftmp;
1501     int64_t size_out;
1502
1503     int frame_bytes, resample_changed;
1504     AVCodecContext *enc = ost->st->codec;
1505     AVCodecContext *dec = ist->st->codec;
1506     int osize = av_get_bytes_per_sample(enc->sample_fmt);
1507     int isize = av_get_bytes_per_sample(dec->sample_fmt);
1508     uint8_t *buf[AV_NUM_DATA_POINTERS];
1509     int size     = decoded_frame->nb_samples * dec->channels * isize;
1510     int planes   = av_sample_fmt_is_planar(dec->sample_fmt) ? dec->channels : 1;
1511     int i;
1512
1513     av_assert0(planes <= AV_NUM_DATA_POINTERS);
1514
1515     for(i=0; i<planes; i++)
1516         buf[i]= decoded_frame->data[i];
1517
1518     if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples) < 0) {
1519         av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1520         exit_program(1);
1521     }
1522
1523     if (enc->channels != dec->channels
1524      || enc->sample_fmt != dec->sample_fmt
1525      || enc->sample_rate!= dec->sample_rate
1526     )
1527         ost->audio_resample = 1;
1528
1529     resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
1530                        ost->resample_channels    != dec->channels   ||
1531                        ost->resample_sample_rate != dec->sample_rate;
1532
1533     if ((ost->audio_resample && !ost->swr) || resample_changed || ost->audio_channels_mapped) {
1534         if (resample_changed) {
1535             av_log(NULL, AV_LOG_INFO, "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
1536                    ist->file_index, ist->st->index,
1537                    ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
1538                    dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
1539             ost->resample_sample_fmt  = dec->sample_fmt;
1540             ost->resample_channels    = dec->channels;
1541             ost->resample_sample_rate = dec->sample_rate;
1542             swr_free(&ost->swr);
1543         }
1544         /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
1545         if (audio_sync_method <= 1 && !ost->audio_channels_mapped &&
1546             ost->resample_sample_fmt  == enc->sample_fmt &&
1547             ost->resample_channels    == enc->channels   &&
1548             ost->resample_sample_rate == enc->sample_rate) {
1549             //ost->swr = NULL;
1550             ost->audio_resample = 0;
1551         } else {
1552             ost->swr = swr_alloc_set_opts(ost->swr,
1553                                           enc->channel_layout, enc->sample_fmt, enc->sample_rate,
1554                                           dec->channel_layout, dec->sample_fmt, dec->sample_rate,
1555                                           0, NULL);
1556             av_opt_set_int(ost->swr, "dither_method", ost->swr_dither_method,0);
1557             av_opt_set_int(ost->swr, "dither_scale", ost->swr_dither_scale,0);
1558             if (ost->audio_channels_mapped)
1559                 swr_set_channel_mapping(ost->swr, ost->audio_channels_map);
1560             av_opt_set_double(ost->swr, "rmvol", ost->rematrix_volume, 0);
1561             if (ost->audio_channels_mapped) {
1562                 av_opt_set_int(ost->swr, "icl", av_get_default_channel_layout(ost->audio_channels_mapped), 0);
1563                 av_opt_set_int(ost->swr, "uch", ost->audio_channels_mapped, 0);
1564             }
1565             if (av_opt_set_int(ost->swr, "ich", dec->channels, 0) < 0) {
1566                 av_log(NULL, AV_LOG_FATAL, "Unsupported number of input channels\n");
1567                 exit_program(1);
1568             }
1569             if (av_opt_set_int(ost->swr, "och", enc->channels, 0) < 0) {
1570                 av_log(NULL, AV_LOG_FATAL, "Unsupported number of output channels\n");
1571                 exit_program(1);
1572             }
1573             if(audio_sync_method>1) av_opt_set_int(ost->swr, "flags", SWR_FLAG_RESAMPLE, 0);
1574             if(ost->swr && swr_init(ost->swr) < 0){
1575                 av_log(NULL, AV_LOG_FATAL, "swr_init() failed\n");
1576                 swr_free(&ost->swr);
1577             }
1578
1579             if (!ost->swr) {
1580                 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
1581                         dec->channels, dec->sample_rate,
1582                         enc->channels, enc->sample_rate);
1583                 exit_program(1);
1584             }
1585         }
1586     }
1587
1588     av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1589
1590     if (audio_sync_method > 0) {
1591         double delta = get_sync_ipts(ost, ist->pts) * enc->sample_rate - ost->sync_opts -
1592                        av_fifo_size(ost->fifo) / (enc->channels * osize);
1593         int idelta = delta * dec->sample_rate / enc->sample_rate;
1594         int byte_delta = idelta * isize * dec->channels;
1595
1596         // FIXME resample delay
1597         if (fabs(delta) > 50) {
1598             if (ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate) {
1599                 if (byte_delta < 0) {
1600                     byte_delta = FFMAX(byte_delta, -size);
1601                     size += byte_delta;
1602                     for (i=0; i<planes; i++)
1603                         buf[i]  -= byte_delta/planes;
1604                     av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
1605                            -byte_delta / (isize * dec->channels));
1606                     if (!size)
1607                         return;
1608                     ist->is_start = 0;
1609                 } else {
1610                     av_fast_malloc(&async_buf, &allocated_async_buf_size,
1611                                    byte_delta + size);
1612                     if (!async_buf) {
1613                         av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
1614                         exit_program(1);
1615                     }
1616
1617                     if (alloc_audio_output_buf(dec, enc, decoded_frame->nb_samples + idelta) < 0) {
1618                         av_log(NULL, AV_LOG_FATAL, "Error allocating audio buffer\n");
1619                         exit_program(1);
1620                     }
1621                     ist->is_start = 0;
1622
1623                     for (i=0; i<planes; i++) {
1624                         uint8_t *t = async_buf + i*((byte_delta + size)/planes);
1625                         generate_silence(t, dec->sample_fmt, byte_delta/planes);
1626                         memcpy(t + byte_delta/planes, buf[i], size/planes);
1627                         buf[i] = t;
1628                     }
1629                     size += byte_delta;
1630                     av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
1631                 }
1632             } else if (audio_sync_method > 1) {
1633                 int comp = av_clip(delta, -audio_sync_method, audio_sync_method);
1634                 av_assert0(ost->audio_resample);
1635                 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
1636                        delta, comp, enc->sample_rate);
1637 //                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));
1638                 swr_set_compensation(ost->swr, comp, enc->sample_rate);
1639             }
1640         }
1641     } else if (audio_sync_method == 0)
1642         ost->sync_opts = lrintf(get_sync_ipts(ost, ist->pts) * enc->sample_rate) -
1643                                 av_fifo_size(ost->fifo) / (enc->channels * osize); // FIXME wrong
1644
1645     if (ost->audio_resample || ost->audio_channels_mapped) {
1646         buftmp = audio_buf;
1647         size_out = swr_convert(ost->swr, (      uint8_t*[]){buftmp}, allocated_audio_buf_size / (enc->channels * osize),
1648                                          buf, size / (dec->channels * isize));
1649         if (size_out < 0) {
1650             av_log(NULL, AV_LOG_FATAL, "swr_convert failed\n");
1651             exit_program(1);
1652         }
1653         size_out = size_out * enc->channels * osize;
1654     } else {
1655         buftmp = buf[0];
1656         size_out = size;
1657     }
1658
1659     av_assert0(ost->audio_resample || dec->sample_fmt==enc->sample_fmt);
1660
1661     /* now encode as many frames as possible */
1662     if (!(enc->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {
1663         /* output resampled raw samples */
1664         if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
1665             av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
1666             exit_program(1);
1667         }
1668         av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
1669
1670         frame_bytes = enc->frame_size * osize * enc->channels;
1671
1672         while (av_fifo_size(ost->fifo) >= frame_bytes) {
1673             av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
1674             encode_audio_frame(s, ost, audio_buf, frame_bytes);
1675         }
1676     } else {
1677         encode_audio_frame(s, ost, buftmp, size_out);
1678     }
1679 }
1680
1681 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1682 {
1683     AVCodecContext *dec;
1684     AVPicture *picture2;
1685     AVPicture picture_tmp;
1686     uint8_t *buf = 0;
1687
1688     dec = ist->st->codec;
1689
1690     /* deinterlace : must be done before any resize */
1691     if (do_deinterlace) {
1692         int size;
1693
1694         /* create temporary picture */
1695         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1696         buf  = av_malloc(size);
1697         if (!buf)
1698             return;
1699
1700         picture2 = &picture_tmp;
1701         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1702
1703         if (avpicture_deinterlace(picture2, picture,
1704                                  dec->pix_fmt, dec->width, dec->height) < 0) {
1705             /* if error, do not deinterlace */
1706             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1707             av_free(buf);
1708             buf = NULL;
1709             picture2 = picture;
1710         }
1711     } else {
1712         picture2 = picture;
1713     }
1714
1715     if (picture != picture2)
1716         *picture = *picture2;
1717     *bufp = buf;
1718 }
1719
1720 static void do_subtitle_out(AVFormatContext *s,
1721                             OutputStream *ost,
1722                             InputStream *ist,
1723                             AVSubtitle *sub,
1724                             int64_t pts)
1725 {
1726     static uint8_t *subtitle_out = NULL;
1727     int subtitle_out_max_size = 1024 * 1024;
1728     int subtitle_out_size, nb, i;
1729     AVCodecContext *enc;
1730     AVPacket pkt;
1731
1732     if (pts == AV_NOPTS_VALUE) {
1733         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1734         if (exit_on_error)
1735             exit_program(1);
1736         return;
1737     }
1738
1739     enc = ost->st->codec;
1740
1741     if (!subtitle_out) {
1742         subtitle_out = av_malloc(subtitle_out_max_size);
1743     }
1744
1745     /* Note: DVB subtitle need one packet to draw them and one other
1746        packet to clear them */
1747     /* XXX: signal it in the codec context ? */
1748     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1749         nb = 2;
1750     else
1751         nb = 1;
1752
1753     for (i = 0; i < nb; i++) {
1754         ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
1755
1756         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1757         // start_display_time is required to be 0
1758         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1759         sub->end_display_time  -= sub->start_display_time;
1760         sub->start_display_time = 0;
1761         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1762                                                     subtitle_out_max_size, sub);
1763         if (subtitle_out_size < 0) {
1764             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1765             exit_program(1);
1766         }
1767
1768         av_init_packet(&pkt);
1769         pkt.data = subtitle_out;
1770         pkt.size = subtitle_out_size;
1771         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1772         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1773             /* XXX: the pts correction is handled here. Maybe handling
1774                it in the codec would be better */
1775             if (i == 0)
1776                 pkt.pts += 90 * sub->start_display_time;
1777             else
1778                 pkt.pts += 90 * sub->end_display_time;
1779         }
1780         write_frame(s, &pkt, ost);
1781     }
1782 }
1783
1784 static double psnr(double d)
1785 {
1786     return -10.0 * log(d) / log(10.0);
1787 }
1788
1789 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1790                            int frame_size)
1791 {
1792     AVCodecContext *enc;
1793     int frame_number;
1794     double ti1, bitrate, avg_bitrate;
1795
1796     /* this is executed just the first time do_video_stats is called */
1797     if (!vstats_file) {
1798         vstats_file = fopen(vstats_filename, "w");
1799         if (!vstats_file) {
1800             perror("fopen");
1801             exit_program(1);
1802         }
1803     }
1804
1805     enc = ost->st->codec;
1806     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1807         frame_number = ost->frame_number;
1808         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1809         if (enc->flags&CODEC_FLAG_PSNR)
1810             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1811
1812         fprintf(vstats_file,"f_size= %6d ", frame_size);
1813         /* compute pts value */
1814         ti1 = ost->sync_opts * av_q2d(enc->time_base);
1815         if (ti1 < 0.01)
1816             ti1 = 0.01;
1817
1818         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1819         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1820         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1821                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1822         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1823     }
1824 }
1825
1826
1827 static void do_video_out(AVFormatContext *s, OutputStream *ost,
1828                          AVFrame *in_picture, float quality)
1829 {
1830     int nb_frames, i, ret, format_video_sync;
1831     AVCodecContext *enc;
1832     double sync_ipts, delta;
1833     double duration = 0;
1834     int frame_size = 0;
1835     InputStream *ist = NULL;
1836
1837     if (ost->source_index >= 0)
1838         ist = input_streams[ost->source_index];
1839
1840     enc = ost->st->codec;
1841
1842     if (ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE) {
1843         duration = FFMAX(av_q2d(ist->st->time_base), av_q2d(ist->st->codec->time_base));
1844         if(ist->st->r_frame_rate.num)
1845             duration= FFMAX(duration, 1/av_q2d(ist->st->r_frame_rate));
1846         if(ist->st->avg_frame_rate.num && 0)
1847             duration= FFMAX(duration, 1/av_q2d(ist->st->avg_frame_rate));
1848
1849         duration /= av_q2d(enc->time_base);
1850     }
1851
1852     sync_ipts = get_sync_ipts(ost, in_picture->pts) / av_q2d(enc->time_base);
1853     delta = sync_ipts - ost->sync_opts + duration;
1854
1855     /* by default, we output a single frame */
1856     nb_frames = 1;
1857
1858     format_video_sync = video_sync_method;
1859     if (format_video_sync == VSYNC_AUTO)
1860         format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
1861
1862     switch (format_video_sync) {
1863     case VSYNC_CFR:
1864         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1865         if (delta < -1.1)
1866             nb_frames = 0;
1867         else if (delta > 1.1)
1868             nb_frames = lrintf(delta);
1869         break;
1870     case VSYNC_VFR:
1871         if (delta <= -0.6)
1872             nb_frames = 0;
1873         else if (delta > 0.6)
1874             ost->sync_opts = lrintf(sync_ipts);
1875         break;
1876     case VSYNC_DROP:
1877     case VSYNC_PASSTHROUGH:
1878         ost->sync_opts = lrintf(sync_ipts);
1879         break;
1880     default:
1881         av_assert0(0);
1882     }
1883
1884     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1885     if (nb_frames == 0) {
1886         nb_frames_drop++;
1887         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1888         return;
1889     } else if (nb_frames > 1) {
1890         nb_frames_dup += nb_frames - 1;
1891         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1892     }
1893
1894     /* duplicates frame if needed */
1895     for (i = 0; i < nb_frames; i++) {
1896         AVPacket pkt;
1897         av_init_packet(&pkt);
1898         pkt.data = NULL;
1899         pkt.size = 0;
1900
1901         if (s->oformat->flags & AVFMT_RAWPICTURE &&
1902             enc->codec->id == CODEC_ID_RAWVIDEO) {
1903             /* raw pictures are written as AVPicture structure to
1904                avoid any copies. We support temporarily the older
1905                method. */
1906             enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1907             enc->coded_frame->top_field_first  = in_picture->top_field_first;
1908             pkt.data   = (uint8_t *)in_picture;
1909             pkt.size   =  sizeof(AVPicture);
1910             pkt.pts    = av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1911             pkt.flags |= AV_PKT_FLAG_KEY;
1912
1913             write_frame(s, &pkt, ost);
1914         } else {
1915             int got_packet;
1916             AVFrame big_picture;
1917
1918             big_picture = *in_picture;
1919             /* better than nothing: use input picture interlaced
1920                settings */
1921             big_picture.interlaced_frame = in_picture->interlaced_frame;
1922             if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1923                 if (ost->top_field_first == -1)
1924                     big_picture.top_field_first = in_picture->top_field_first;
1925                 else
1926                     big_picture.top_field_first = !!ost->top_field_first;
1927             }
1928
1929             /* handles same_quant here. This is not correct because it may
1930                not be a global option */
1931             big_picture.quality = quality;
1932             if (!enc->me_threshold)
1933                 big_picture.pict_type = 0;
1934             big_picture.pts = ost->sync_opts;
1935             if (ost->forced_kf_index < ost->forced_kf_count &&
1936                 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1937                 big_picture.pict_type = AV_PICTURE_TYPE_I;
1938                 ost->forced_kf_index++;
1939             }
1940             update_benchmark(NULL);
1941             ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
1942             update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1943             if (ret < 0) {
1944                 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1945                 exit_program(1);
1946             }
1947
1948             if (got_packet) {
1949                 if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
1950                     pkt.pts = ost->sync_opts;
1951
1952                 if (pkt.pts != AV_NOPTS_VALUE)
1953                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1954                 if (pkt.dts != AV_NOPTS_VALUE)
1955                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1956
1957                 if (debug_ts) {
1958                     av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1959                            "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1960                            av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1961                            av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1962                 }
1963
1964                 write_frame(s, &pkt, ost);
1965                 frame_size = pkt.size;
1966                 video_size += pkt.size;
1967                 av_free_packet(&pkt);
1968
1969                 /* if two pass, output log */
1970                 if (ost->logfile && enc->stats_out) {
1971                     fprintf(ost->logfile, "%s", enc->stats_out);
1972                 }
1973             }
1974         }
1975         ost->sync_opts++;
1976         /*
1977          * For video, number of frames in == number of packets out.
1978          * But there may be reordering, so we can't throw away frames on encoder
1979          * flush, we need to limit them here, before they go into encoder.
1980          */
1981         ost->frame_number++;
1982     }
1983     if (vstats_filename && frame_size)
1984         do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
1985 }
1986
1987 /* check for new output on any of the filtergraphs */
1988 static int poll_filters(void)
1989 {
1990     AVFilterBufferRef *picref;
1991     AVFrame *filtered_frame = NULL;
1992     int i, ret;
1993
1994     for (i = 0; i < nb_output_streams; i++) {
1995         OutputStream *ost = output_streams[i];
1996         OutputFile    *of = output_files[ost->file_index];
1997
1998         if (!ost->filter || ost->is_past_recording_time)
1999             continue;
2000
2001         if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
2002             return AVERROR(ENOMEM);
2003         } else
2004             avcodec_get_frame_defaults(ost->filtered_frame);
2005         filtered_frame = ost->filtered_frame;
2006
2007         while (avfilter_poll_frame(ost->filter->filter->inputs[0])) {
2008             AVRational ist_pts_tb = ost->filter->filter->inputs[0]->time_base;
2009             if ((ret = av_buffersink_get_buffer_ref(ost->filter->filter,
2010                                                             &picref,
2011                                                             0)) < 0) {
2012                 av_log(NULL, AV_LOG_WARNING, "AV Filter told us it has a frame available but failed to output one\n");
2013                 return ret;
2014             }
2015             filtered_frame->pts = av_rescale_q(picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
2016 //             if (ost->source_index >= 0)
2017 //                 *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
2018
2019             if (of->start_time && filtered_frame->pts < of->start_time)
2020                 return 0;
2021
2022             switch (ost->filter->filter->inputs[0]->type) {
2023             case AVMEDIA_TYPE_VIDEO:
2024                 avfilter_fill_frame_from_video_buffer_ref(filtered_frame, picref);
2025                 if (!ost->frame_aspect_ratio)
2026                     ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2027
2028                 do_video_out(of->ctx, ost, filtered_frame,
2029                              same_quant ? ost->last_quality :
2030                                           ost->st->codec->global_quality);
2031                 break;
2032             default:
2033                 // TODO support audio/subtitle filters
2034                 av_assert0(0);
2035             }
2036
2037             avfilter_unref_buffer(picref);
2038         }
2039     }
2040     return 0;
2041 }
2042
2043 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
2044 {
2045     char buf[1024];
2046     OutputStream *ost;
2047     AVFormatContext *oc;
2048     int64_t total_size;
2049     AVCodecContext *enc;
2050     int frame_number, vid, i;
2051     double bitrate;
2052     int64_t pts = INT64_MAX;
2053     static int64_t last_time = -1;
2054     static int qp_histogram[52];
2055     int hours, mins, secs, us;
2056
2057     if (!print_stats && !is_last_report)
2058         return;
2059
2060     if (!is_last_report) {
2061         if (last_time == -1) {
2062             last_time = cur_time;
2063             return;
2064         }
2065         if ((cur_time - last_time) < 500000)
2066             return;
2067         last_time = cur_time;
2068     }
2069
2070
2071     oc = output_files[0]->ctx;
2072
2073     total_size = avio_size(oc->pb);
2074     if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
2075         total_size = avio_tell(oc->pb);
2076         if (total_size < 0)
2077             total_size = 0;
2078     }
2079
2080     buf[0] = '\0';
2081     vid = 0;
2082     for (i = 0; i < nb_output_streams; i++) {
2083         float q = -1;
2084         ost = output_streams[i];
2085         enc = ost->st->codec;
2086         if (!ost->stream_copy && enc->coded_frame)
2087             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
2088         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2089             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
2090         }
2091         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2092             float fps, t = (cur_time-timer_start) / 1000000.0;
2093
2094             frame_number = ost->frame_number;
2095             fps = t > 1 ? frame_number / t : 0;
2096             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
2097                      frame_number, fps < 9.95, fps, q);
2098             if (is_last_report)
2099                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
2100             if (qp_hist) {
2101                 int j;
2102                 int qp = lrintf(q);
2103                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
2104                     qp_histogram[qp]++;
2105                 for (j = 0; j < 32; j++)
2106                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
2107             }
2108             if (enc->flags&CODEC_FLAG_PSNR) {
2109                 int j;
2110                 double error, error_sum = 0;
2111                 double scale, scale_sum = 0;
2112                 char type[3] = { 'Y','U','V' };
2113                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
2114                 for (j = 0; j < 3; j++) {
2115                     if (is_last_report) {
2116                         error = enc->error[j];
2117                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
2118                     } else {
2119                         error = enc->coded_frame->error[j];
2120                         scale = enc->width * enc->height * 255.0 * 255.0;
2121                     }
2122                     if (j)
2123                         scale /= 4;
2124                     error_sum += error;
2125                     scale_sum += scale;
2126                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
2127                 }
2128                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
2129             }
2130             vid = 1;
2131         }
2132         /* compute min output value */
2133         pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
2134                                       ost->st->time_base, AV_TIME_BASE_Q));
2135     }
2136
2137     secs = pts / AV_TIME_BASE;
2138     us = pts % AV_TIME_BASE;
2139     mins = secs / 60;
2140     secs %= 60;
2141     hours = mins / 60;
2142     mins %= 60;
2143
2144     bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
2145
2146     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2147              "size=%8.0fkB time=", total_size / 1024.0);
2148     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2149              "%02d:%02d:%02d.%02d ", hours, mins, secs,
2150              (100 * us) / AV_TIME_BASE);
2151     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2152              "bitrate=%6.1fkbits/s", bitrate);
2153
2154     if (nb_frames_dup || nb_frames_drop)
2155         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
2156                 nb_frames_dup, nb_frames_drop);
2157
2158     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
2159
2160     fflush(stderr);
2161
2162     if (is_last_report) {
2163         int64_t raw= audio_size + video_size + extra_size;
2164         av_log(NULL, AV_LOG_INFO, "\n");
2165         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
2166                video_size / 1024.0,
2167                audio_size / 1024.0,
2168                extra_size / 1024.0,
2169                100.0 * (total_size - raw) / raw
2170         );
2171         if(video_size + audio_size + extra_size == 0){
2172             av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
2173         }
2174     }
2175 }
2176
2177 static void flush_encoders(void)
2178 {
2179     int i, ret;
2180
2181     for (i = 0; i < nb_output_streams; i++) {
2182         OutputStream   *ost = output_streams[i];
2183         AVCodecContext *enc = ost->st->codec;
2184         AVFormatContext *os = output_files[ost->file_index]->ctx;
2185         int stop_encoding = 0;
2186
2187         if (!ost->encoding_needed)
2188             continue;
2189
2190         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2191             continue;
2192         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
2193             continue;
2194
2195         for (;;) {
2196             AVPacket pkt;
2197             int fifo_bytes, got_packet;
2198             av_init_packet(&pkt);
2199             pkt.data = NULL;
2200             pkt.size = 0;
2201
2202             switch (ost->st->codec->codec_type) {
2203             case AVMEDIA_TYPE_AUDIO:
2204                 fifo_bytes = av_fifo_size(ost->fifo);
2205                 if (fifo_bytes > 0) {
2206                     /* encode any samples remaining in fifo */
2207                     int frame_bytes = fifo_bytes;
2208
2209                     av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
2210
2211                     /* pad last frame with silence if needed */
2212                     if (!(enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME)) {
2213                         frame_bytes = enc->frame_size * enc->channels *
2214                                       av_get_bytes_per_sample(enc->sample_fmt);
2215                         if (allocated_audio_buf_size < frame_bytes)
2216                             exit_program(1);
2217                         generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
2218                     }
2219                     encode_audio_frame(os, ost, audio_buf, frame_bytes);
2220                 } else {
2221                     /* flush encoder with NULL frames until it is done
2222                        returning packets */
2223                     if (encode_audio_frame(os, ost, NULL, 0) == 0) {
2224                         stop_encoding = 1;
2225                         break;
2226                     }
2227                 }
2228                 break;
2229             case AVMEDIA_TYPE_VIDEO:
2230                 update_benchmark(NULL);
2231                 ret = avcodec_encode_video2(enc, &pkt, NULL, &got_packet);
2232                 update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2233                 if (ret < 0) {
2234                     av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2235                     exit_program(1);
2236                 }
2237                 video_size += pkt.size;
2238                 if (ost->logfile && enc->stats_out) {
2239                     fprintf(ost->logfile, "%s", enc->stats_out);
2240                 }
2241                 if (!got_packet) {
2242                     stop_encoding = 1;
2243                     break;
2244                 }
2245                 if (pkt.pts != AV_NOPTS_VALUE)
2246                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2247                 if (pkt.dts != AV_NOPTS_VALUE)
2248                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2249                 write_frame(os, &pkt, ost);
2250                 break;
2251             default:
2252                 stop_encoding = 1;
2253             }
2254             if (stop_encoding)
2255                 break;
2256         }
2257     }
2258 }
2259
2260 /*
2261  * Check whether a packet from ist should be written into ost at this time
2262  */
2263 static int check_output_constraints(InputStream *ist, OutputStream *ost)
2264 {
2265     OutputFile *of = output_files[ost->file_index];
2266     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
2267
2268     if (ost->source_index != ist_index)
2269         return 0;
2270
2271     if (of->start_time && ist->pts < of->start_time)
2272         return 0;
2273
2274     if (of->recording_time != INT64_MAX &&
2275         av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
2276                       (AVRational){ 1, 1000000 }) >= 0) {
2277         ost->is_past_recording_time = 1;
2278         return 0;
2279     }
2280
2281     return 1;
2282 }
2283
2284 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2285 {
2286     OutputFile *of = output_files[ost->file_index];
2287     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2288     AVPicture pict;
2289     AVPacket opkt;
2290
2291     av_init_packet(&opkt);
2292
2293     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2294         !ost->copy_initial_nonkeyframes)
2295         return;
2296
2297     /* force the input stream PTS */
2298     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2299         audio_size += pkt->size;
2300     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2301         video_size += pkt->size;
2302         ost->sync_opts++;
2303     }
2304
2305     if (pkt->pts != AV_NOPTS_VALUE)
2306         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2307     else
2308         opkt.pts = AV_NOPTS_VALUE;
2309
2310     if (pkt->dts == AV_NOPTS_VALUE)
2311         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
2312     else
2313         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2314     opkt.dts -= ost_tb_start_time;
2315
2316     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2317     opkt.flags    = pkt->flags;
2318
2319     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2320     if (  ost->st->codec->codec_id != CODEC_ID_H264
2321        && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2322        && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
2323        && ost->st->codec->codec_id != CODEC_ID_VC1
2324        ) {
2325         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2326             opkt.destruct = av_destruct_packet;
2327     } else {
2328         opkt.data = pkt->data;
2329         opkt.size = pkt->size;
2330     }
2331     if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
2332         /* store AVPicture in AVPacket, as expected by the output format */
2333         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
2334         opkt.data = (uint8_t *)&pict;
2335         opkt.size = sizeof(AVPicture);
2336         opkt.flags |= AV_PKT_FLAG_KEY;
2337     }
2338
2339     write_frame(of->ctx, &opkt, ost);
2340     ost->st->codec->frame_number++;
2341     av_free_packet(&opkt);
2342 }
2343
2344 static void rate_emu_sleep(InputStream *ist)
2345 {
2346     if (input_files[ist->file_index]->rate_emu) {
2347         int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2348         int64_t now = av_gettime() - ist->start;
2349         if (pts > now)
2350             usleep(pts - now);
2351     }
2352 }
2353
2354 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2355 {
2356     AVFrame *decoded_frame;
2357     AVCodecContext *avctx = ist->st->codec;
2358     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
2359     int i, ret;
2360
2361     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2362         return AVERROR(ENOMEM);
2363     else
2364         avcodec_get_frame_defaults(ist->decoded_frame);
2365     decoded_frame = ist->decoded_frame;
2366
2367     update_benchmark(NULL);
2368     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2369     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2370     if (ret < 0) {
2371         return ret;
2372     }
2373     if (avctx->sample_rate <= 0) {
2374         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2375         return AVERROR_INVALIDDATA;
2376     }
2377
2378     if (!*got_output) {
2379         /* no audio frame */
2380         return ret;
2381     }
2382
2383     /* if the decoder provides a pts, use it instead of the last packet pts.
2384        the decoder could be delaying output by a packet or more. */
2385     if (decoded_frame->pts != AV_NOPTS_VALUE)
2386         ist->dts = ist->next_dts = ist->pts = ist->next_pts = decoded_frame->pts;
2387
2388     /* increment next_dts to use for the case where the input stream does not
2389        have timestamps or there are multiple frames in the packet */
2390     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2391                      avctx->sample_rate;
2392     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2393                      avctx->sample_rate;
2394
2395
2396     // preprocess audio (volume)
2397     if (audio_volume != 256) {
2398         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
2399         void *samples = decoded_frame->data[0];
2400         switch (avctx->sample_fmt) {
2401         case AV_SAMPLE_FMT_U8:
2402         {
2403             uint8_t *volp = samples;
2404             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2405                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
2406                 *volp++ = av_clip_uint8(v);
2407             }
2408             break;
2409         }
2410         case AV_SAMPLE_FMT_S16:
2411         {
2412             int16_t *volp = samples;
2413             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2414                 int v = ((*volp) * audio_volume + 128) >> 8;
2415                 *volp++ = av_clip_int16(v);
2416             }
2417             break;
2418         }
2419         case AV_SAMPLE_FMT_S32:
2420         {
2421             int32_t *volp = samples;
2422             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2423                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
2424                 *volp++ = av_clipl_int32(v);
2425             }
2426             break;
2427         }
2428         case AV_SAMPLE_FMT_FLT:
2429         {
2430             float *volp = samples;
2431             float scale = audio_volume / 256.f;
2432             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2433                 *volp++ *= scale;
2434             }
2435             break;
2436         }
2437         case AV_SAMPLE_FMT_DBL:
2438         {
2439             double *volp = samples;
2440             double scale = audio_volume / 256.;
2441             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
2442                 *volp++ *= scale;
2443             }
2444             break;
2445         }
2446         default:
2447             av_log(NULL, AV_LOG_FATAL,
2448                    "Audio volume adjustment on sample format %s is not supported.\n",
2449                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
2450             exit_program(1);
2451         }
2452     }
2453
2454     rate_emu_sleep(ist);
2455
2456     for (i = 0; i < nb_output_streams; i++) {
2457         OutputStream *ost = output_streams[i];
2458
2459         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2460             continue;
2461         do_audio_out(output_files[ost->file_index]->ctx, ost, ist, decoded_frame);
2462     }
2463
2464     return ret;
2465 }
2466
2467 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
2468 {
2469     AVFrame *decoded_frame;
2470     void *buffer_to_free = NULL;
2471     int i, ret = 0, resample_changed;
2472     int64_t *best_effort_timestamp;
2473     AVRational *frame_sample_aspect;
2474     float quality;
2475
2476     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2477         return AVERROR(ENOMEM);
2478     else
2479         avcodec_get_frame_defaults(ist->decoded_frame);
2480     decoded_frame = ist->decoded_frame;
2481     pkt->pts  = *pkt_pts;
2482     pkt->dts  = ist->dts;
2483     *pkt_pts  = AV_NOPTS_VALUE;
2484
2485     update_benchmark(NULL);
2486     ret = avcodec_decode_video2(ist->st->codec,
2487                                 decoded_frame, got_output, pkt);
2488     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2489     if (ret < 0)
2490         return ret;
2491
2492     quality = same_quant ? decoded_frame->quality : 0;
2493     if (!*got_output) {
2494         /* no picture yet */
2495         if (!pkt->size)
2496             for (i = 0; i < ist->nb_filters; i++)
2497                 av_buffersrc_buffer(ist->filters[i]->filter, NULL);
2498         return ret;
2499     }
2500
2501     best_effort_timestamp= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "best_effort_timestamp");
2502     if(*best_effort_timestamp != AV_NOPTS_VALUE)
2503         ist->next_pts = ist->pts = decoded_frame->pts = *best_effort_timestamp;
2504
2505     pkt->size = 0;
2506
2507     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2508
2509     rate_emu_sleep(ist);
2510
2511     if (ist->st->sample_aspect_ratio.num)
2512         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2513
2514     resample_changed = ist->resample_width   != decoded_frame->width  ||
2515                        ist->resample_height  != decoded_frame->height ||
2516                        ist->resample_pix_fmt != decoded_frame->format;
2517     if (resample_changed) {
2518         av_log(NULL, AV_LOG_INFO,
2519                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2520                ist->file_index, ist->st->index,
2521                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
2522                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2523
2524         ist->resample_width   = decoded_frame->width;
2525         ist->resample_height  = decoded_frame->height;
2526         ist->resample_pix_fmt = decoded_frame->format;
2527
2528         for (i = 0; i < nb_filtergraphs; i++)
2529             if (ist_in_filtergraph(filtergraphs[i], ist) &&
2530                 configure_filtergraph(filtergraphs[i]) < 0) {
2531                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2532                 exit_program(1);
2533             }
2534     }
2535
2536     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2537     for (i = 0; i < ist->nb_filters; i++) {
2538         int changed =      ist->st->codec->width   != ist->filters[i]->filter->outputs[0]->w
2539                         || ist->st->codec->height  != ist->filters[i]->filter->outputs[0]->h
2540                         || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
2541         // XXX what an ugly hack
2542         if (ist->filters[i]->graph->nb_outputs == 1)
2543             ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2544
2545         if (!frame_sample_aspect->num)
2546             *frame_sample_aspect = ist->st->sample_aspect_ratio;
2547         if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2548             FrameBuffer      *buf = decoded_frame->opaque;
2549             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2550                                         decoded_frame->data, decoded_frame->linesize,
2551                                         AV_PERM_READ | AV_PERM_PRESERVE,
2552                                         ist->st->codec->width, ist->st->codec->height,
2553                                         ist->st->codec->pix_fmt);
2554
2555             avfilter_copy_frame_props(fb, decoded_frame);
2556             fb->buf->priv           = buf;
2557             fb->buf->free           = filter_release_buffer;
2558
2559             buf->refcount++;
2560             av_buffersrc_buffer(ist->filters[i]->filter, fb);
2561         } else
2562         if(av_vsrc_buffer_add_frame(ist->filters[i]->filter, decoded_frame,AV_VSRC_BUF_FLAG_OVERWRITE)<0) {
2563             av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2564             exit_program(1);
2565         }
2566
2567     }
2568
2569     av_free(buffer_to_free);
2570     return ret;
2571 }
2572
2573 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2574 {
2575     AVSubtitle subtitle;
2576     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2577                                           &subtitle, got_output, pkt);
2578     if (ret < 0)
2579         return ret;
2580     if (!*got_output)
2581         return ret;
2582
2583     rate_emu_sleep(ist);
2584
2585     for (i = 0; i < nb_output_streams; i++) {
2586         OutputStream *ost = output_streams[i];
2587
2588         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2589             continue;
2590
2591         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2592     }
2593
2594     avsubtitle_free(&subtitle);
2595     return ret;
2596 }
2597
2598 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2599 static int output_packet(InputStream *ist, const AVPacket *pkt)
2600 {
2601     int ret = 0, i;
2602     int got_output;
2603     int64_t pkt_pts = AV_NOPTS_VALUE;
2604
2605     AVPacket avpkt;
2606
2607     if (ist->next_dts == AV_NOPTS_VALUE)
2608         ist->next_dts = ist->dts;
2609     if (ist->next_pts == AV_NOPTS_VALUE)
2610         ist->next_pts = ist->pts;
2611
2612     if (pkt == NULL) {
2613         /* EOF handling */
2614         av_init_packet(&avpkt);
2615         avpkt.data = NULL;
2616         avpkt.size = 0;
2617         goto handle_eof;
2618     } else {
2619         avpkt = *pkt;
2620     }
2621
2622     if (pkt->dts != AV_NOPTS_VALUE) {
2623         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2624         if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2625             ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2626     }
2627     if(pkt->pts != AV_NOPTS_VALUE)
2628         pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2629
2630     // while we have more to decode or while the decoder did output something on EOF
2631     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2632         int duration;
2633     handle_eof:
2634
2635         ist->pts = ist->next_pts;
2636         ist->dts = ist->next_dts;
2637
2638         if (avpkt.size && avpkt.size != pkt->size) {
2639             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2640                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2641             ist->showed_multi_packet_warning = 1;
2642         }
2643
2644         switch (ist->st->codec->codec_type) {
2645         case AVMEDIA_TYPE_AUDIO:
2646             ret = transcode_audio    (ist, &avpkt, &got_output);
2647             break;
2648         case AVMEDIA_TYPE_VIDEO:
2649             ret = transcode_video    (ist, &avpkt, &got_output, &pkt_pts);
2650             if (avpkt.duration) {
2651                 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2652             } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2653                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2654                 duration = ((int64_t)AV_TIME_BASE *
2655                                 ist->st->codec->time_base.num * ticks) /
2656                                 ist->st->codec->time_base.den;
2657             } else
2658                 duration = 0;
2659
2660             if(ist->dts != AV_NOPTS_VALUE && duration) {
2661                 ist->next_dts += duration;
2662             }else
2663                 ist->next_dts = AV_NOPTS_VALUE;
2664
2665             if (got_output)
2666                 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2667             break;
2668         case AVMEDIA_TYPE_SUBTITLE:
2669             ret = transcode_subtitles(ist, &avpkt, &got_output);
2670             break;
2671         default:
2672             return -1;
2673         }
2674
2675         if (ret < 0)
2676             return ret;
2677
2678         avpkt.dts=
2679         avpkt.pts= AV_NOPTS_VALUE;
2680
2681         // touch data and size only if not EOF
2682         if (pkt) {
2683             if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2684                 ret = avpkt.size;
2685             avpkt.data += ret;
2686             avpkt.size -= ret;
2687         }
2688         if (!got_output) {
2689             continue;
2690         }
2691     }
2692
2693     /* handle stream copy */
2694     if (!ist->decoding_needed) {
2695         rate_emu_sleep(ist);
2696         ist->dts = ist->next_dts;
2697         switch (ist->st->codec->codec_type) {
2698         case AVMEDIA_TYPE_AUDIO:
2699             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2700                              ist->st->codec->sample_rate;
2701             break;
2702         case AVMEDIA_TYPE_VIDEO:
2703             if (pkt->duration) {
2704                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2705             } else if(ist->st->codec->time_base.num != 0) {
2706                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2707                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2708                                   ist->st->codec->time_base.num * ticks) /
2709                                   ist->st->codec->time_base.den;
2710             }
2711             break;
2712         }
2713         ist->pts = ist->dts;
2714         ist->next_pts = ist->next_dts;
2715     }
2716     for (i = 0; pkt && i < nb_output_streams; i++) {
2717         OutputStream *ost = output_streams[i];
2718
2719         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2720             continue;
2721
2722         do_streamcopy(ist, ost, pkt);
2723     }
2724
2725     return 0;
2726 }
2727
2728 static void print_sdp(void)
2729 {
2730     char sdp[2048];
2731     int i;
2732     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2733
2734     if (!avc)
2735         exit_program(1);
2736     for (i = 0; i < nb_output_files; i++)
2737         avc[i] = output_files[i]->ctx;
2738
2739     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2740     printf("SDP:\n%s\n", sdp);
2741     fflush(stdout);
2742     av_freep(&avc);
2743 }
2744
2745 static void get_default_channel_layouts(OutputStream *ost, InputStream *ist)
2746 {
2747     char layout_name[256];
2748     AVCodecContext *enc = ost->st->codec;
2749     AVCodecContext *dec = ist->st->codec;
2750
2751     if (!dec->channel_layout) {
2752         if (enc->channel_layout && dec->channels == enc->channels) {
2753             dec->channel_layout = enc->channel_layout;
2754         } else {
2755             dec->channel_layout = av_get_default_channel_layout(dec->channels);
2756
2757             if (!dec->channel_layout) {
2758                 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
2759                        "layout for Input Stream #%d.%d\n", ist->file_index,
2760                        ist->st->index);
2761                 exit_program(1);
2762             }
2763         }
2764         av_get_channel_layout_string(layout_name, sizeof(layout_name),
2765                                      dec->channels, dec->channel_layout);
2766         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
2767                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
2768     }
2769     if (!enc->channel_layout) {
2770         if (dec->channels == enc->channels) {
2771             enc->channel_layout = dec->channel_layout;
2772             return;
2773         } else {
2774             enc->channel_layout = av_get_default_channel_layout(enc->channels);
2775         }
2776         if (!enc->channel_layout) {
2777             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel layout "
2778                    "for Output Stream #%d.%d\n", ost->file_index,
2779                    ost->st->index);
2780             exit_program(1);
2781         }
2782         av_get_channel_layout_string(layout_name, sizeof(layout_name),
2783                                      enc->channels, enc->channel_layout);
2784         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Output Stream "
2785                "#%d.%d : %s\n", ost->file_index, ost->st->index, layout_name);
2786     }
2787 }
2788
2789
2790 static int init_input_stream(int ist_index, char *error, int error_len)
2791 {
2792     int i;
2793     InputStream *ist = input_streams[ist_index];
2794
2795     if (ist->decoding_needed) {
2796         AVCodec *codec = ist->dec;
2797         if (!codec) {
2798             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2799                     avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2800             return AVERROR(EINVAL);
2801         }
2802
2803         ist->dr1 = codec->capabilities & CODEC_CAP_DR1;
2804         if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2805             ist->st->codec->get_buffer     = codec_get_buffer;
2806             ist->st->codec->release_buffer = codec_release_buffer;
2807             ist->st->codec->opaque         = ist;
2808         }
2809
2810         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2811             av_dict_set(&ist->opts, "threads", "auto", 0);
2812         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2813             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2814                     ist->file_index, ist->st->index);
2815             return AVERROR(EINVAL);
2816         }
2817         assert_codec_experimental(ist->st->codec, 0);
2818         assert_avoptions(ist->opts);
2819
2820         if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
2821             for (i = 0; i < nb_output_streams; i++) {
2822                 OutputStream *ost = output_streams[i];
2823                 if (ost->source_index == ist_index) {
2824                     if (!ist->st->codec->channel_layout || !ost->st->codec->channel_layout)
2825                         get_default_channel_layouts(ost, ist);
2826                     break;
2827                 }
2828             }
2829         }
2830     }
2831
2832     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;
2833     ist->next_pts = AV_NOPTS_VALUE;
2834     ist->next_dts = AV_NOPTS_VALUE;
2835     ist->is_start = 1;
2836
2837     return 0;
2838 }
2839
2840 static InputStream *get_input_stream(OutputStream *ost)
2841 {
2842     if (ost->source_index >= 0)
2843         return input_streams[ost->source_index];
2844
2845     if (ost->filter) {
2846         FilterGraph *fg = ost->filter->graph;
2847         int i;
2848
2849         for (i = 0; i < fg->nb_inputs; i++)
2850             if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2851                 return fg->inputs[i]->ist;
2852     }
2853
2854     return NULL;
2855 }
2856
2857 static int transcode_init(void)
2858 {
2859     int ret = 0, i, j, k;
2860     AVFormatContext *oc;
2861     AVCodecContext *codec, *icodec;
2862     OutputStream *ost;
2863     InputStream *ist;
2864     char error[1024];
2865     int want_sdp = 1;
2866
2867     /* init framerate emulation */
2868     for (i = 0; i < nb_input_files; i++) {
2869         InputFile *ifile = input_files[i];
2870         if (ifile->rate_emu)
2871             for (j = 0; j < ifile->nb_streams; j++)
2872                 input_streams[j + ifile->ist_index]->start = av_gettime();
2873     }
2874
2875     /* output stream init */
2876     for (i = 0; i < nb_output_files; i++) {
2877         oc = output_files[i]->ctx;
2878         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2879             av_dump_format(oc, i, oc->filename, 1);
2880             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2881             return AVERROR(EINVAL);
2882         }
2883     }
2884
2885     /* init complex filtergraphs */
2886     for (i = 0; i < nb_filtergraphs; i++)
2887         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2888             return ret;
2889
2890     /* for each output stream, we compute the right encoding parameters */
2891     for (i = 0; i < nb_output_streams; i++) {
2892         ost = output_streams[i];
2893         oc  = output_files[ost->file_index]->ctx;
2894         ist = get_input_stream(ost);
2895
2896         if (ost->attachment_filename)
2897             continue;
2898
2899         codec  = ost->st->codec;
2900
2901         if (ist) {
2902             icodec = ist->st->codec;
2903
2904             ost->st->disposition          = ist->st->disposition;
2905             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2906             codec->chroma_sample_location = icodec->chroma_sample_location;
2907         }
2908
2909         if (ost->stream_copy) {
2910             uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2911
2912             if (extra_size > INT_MAX) {
2913                 return AVERROR(EINVAL);
2914             }
2915
2916             /* if stream_copy is selected, no need to decode or encode */
2917             codec->codec_id   = icodec->codec_id;
2918             codec->codec_type = icodec->codec_type;
2919
2920             if (!codec->codec_tag) {
2921                 if (!oc->oformat->codec_tag ||
2922                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2923                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2924                     codec->codec_tag = icodec->codec_tag;
2925             }
2926
2927             codec->bit_rate       = icodec->bit_rate;
2928             codec->rc_max_rate    = icodec->rc_max_rate;
2929             codec->rc_buffer_size = icodec->rc_buffer_size;
2930             codec->field_order    = icodec->field_order;
2931             codec->extradata      = av_mallocz(extra_size);
2932             if (!codec->extradata) {
2933                 return AVERROR(ENOMEM);
2934             }
2935             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2936             codec->extradata_size= icodec->extradata_size;
2937
2938             codec->time_base = ist->st->time_base;
2939             /*
2940              * Avi is a special case here because it supports variable fps but
2941              * having the fps and timebase differe significantly adds quite some
2942              * overhead
2943              */
2944             if(!strcmp(oc->oformat->name, "avi")) {
2945                 if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2946                                  && av_q2d(ist->st->time_base) < 1.0/500
2947                     || copy_tb==0){
2948                     codec->time_base = icodec->time_base;
2949                     codec->time_base.num *= icodec->ticks_per_frame;
2950                     codec->time_base.den *= 2;
2951                     codec->ticks_per_frame = 2;
2952                 }
2953             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2954                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2955                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2956             ) {
2957                 if(   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2958                                 && av_q2d(ist->st->time_base) < 1.0/500
2959                    || copy_tb==0){
2960                     codec->time_base = icodec->time_base;
2961                     codec->time_base.num *= icodec->ticks_per_frame;
2962                 }
2963             }
2964             av_reduce(&codec->time_base.num, &codec->time_base.den,
2965                         codec->time_base.num, codec->time_base.den, INT_MAX);
2966
2967             switch (codec->codec_type) {
2968             case AVMEDIA_TYPE_AUDIO:
2969                 if (audio_volume != 256) {
2970                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2971                     exit_program(1);
2972                 }
2973                 codec->channel_layout     = icodec->channel_layout;
2974                 codec->sample_rate        = icodec->sample_rate;
2975                 codec->channels           = icodec->channels;
2976                 codec->frame_size         = icodec->frame_size;
2977                 codec->audio_service_type = icodec->audio_service_type;
2978                 codec->block_align        = icodec->block_align;
2979                 break;
2980             case AVMEDIA_TYPE_VIDEO:
2981                 codec->pix_fmt            = icodec->pix_fmt;
2982                 codec->width              = icodec->width;
2983                 codec->height             = icodec->height;
2984                 codec->has_b_frames       = icodec->has_b_frames;
2985                 if (!codec->sample_aspect_ratio.num) {
2986                     codec->sample_aspect_ratio   =
2987                     ost->st->sample_aspect_ratio =
2988                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
2989                         ist->st->codec->sample_aspect_ratio.num ?
2990                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2991                 }
2992                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2993                 break;
2994             case AVMEDIA_TYPE_SUBTITLE:
2995                 codec->width  = icodec->width;
2996                 codec->height = icodec->height;
2997                 break;
2998             case AVMEDIA_TYPE_DATA:
2999             case AVMEDIA_TYPE_ATTACHMENT:
3000                 break;
3001             default:
3002                 abort();
3003             }
3004         } else {
3005             if (!ost->enc)
3006                 ost->enc = avcodec_find_encoder(codec->codec_id);
3007
3008             if (ist)
3009                 ist->decoding_needed = 1;
3010             ost->encoding_needed = 1;
3011
3012             switch (codec->codec_type) {
3013             case AVMEDIA_TYPE_AUDIO:
3014                 ost->fifo = av_fifo_alloc(1024);
3015                 if (!ost->fifo) {
3016                     return AVERROR(ENOMEM);
3017                 }
3018                 if (!codec->sample_rate)
3019                     codec->sample_rate = icodec->sample_rate;
3020                 choose_sample_rate(ost->st, ost->enc);
3021                 codec->time_base = (AVRational){ 1, codec->sample_rate };
3022
3023                 if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
3024                     codec->sample_fmt = icodec->sample_fmt;
3025                 choose_sample_fmt(ost->st, ost->enc);
3026
3027                 if (ost->audio_channels_mapped) {
3028                     /* the requested output channel is set to the number of
3029                      * -map_channel only if no -ac are specified */
3030                     if (!codec->channels) {
3031                         codec->channels       = ost->audio_channels_mapped;
3032                         codec->channel_layout = av_get_default_channel_layout(codec->channels);
3033                         if (!codec->channel_layout) {
3034                             av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n");
3035                             exit_program(1);
3036                         }
3037                     }
3038                     /* fill unused channel mapping with -1 (which means a muted
3039                      * channel in case the number of output channels is bigger
3040                      * than the number of mapped channel) */
3041                     for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
3042                         ost->audio_channels_map[j] = -1;
3043                 } else if (!codec->channels) {
3044                     codec->channels = icodec->channels;
3045                     codec->channel_layout = icodec->channel_layout;
3046                 }
3047                 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
3048                     codec->channel_layout = 0;
3049
3050                 ost->audio_resample       = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
3051                 ost->audio_resample      |=    codec->sample_fmt     != icodec->sample_fmt
3052                                             || codec->channel_layout != icodec->channel_layout;
3053                 icodec->request_channels  = codec->channels;
3054                 ost->resample_sample_fmt  = icodec->sample_fmt;
3055                 ost->resample_sample_rate = icodec->sample_rate;
3056                 ost->resample_channels    = icodec->channels;
3057                 break;
3058             case AVMEDIA_TYPE_VIDEO:
3059                 if (!ost->filter) {
3060                     FilterGraph *fg;
3061                     fg = init_simple_filtergraph(ist, ost);
3062                     if (configure_video_filters(fg)) {
3063                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3064                         exit(1);
3065                     }
3066                 }
3067
3068                 if (ist && !ost->frame_rate.num)
3069                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational) { 25, 1 };
3070                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3071                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3072                     ost->frame_rate = ost->enc->supported_framerates[idx];
3073                 }
3074                 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
3075                 if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3076                    && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3077                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3078                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3079                 }
3080                 for (j = 0; j < ost->forced_kf_count; j++)
3081                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3082                                                          AV_TIME_BASE_Q,
3083                                                          codec->time_base);
3084
3085                 codec->width  = ost->filter->filter->inputs[0]->w;
3086                 codec->height = ost->filter->filter->inputs[0]->h;
3087                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3088                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3089                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3090                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
3091                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3092
3093                 if (codec->width   != icodec->width  ||
3094                     codec->height  != icodec->height ||
3095                     codec->pix_fmt != icodec->pix_fmt) {
3096                     codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3097                 }
3098
3099                 break;
3100             case AVMEDIA_TYPE_SUBTITLE:
3101                 codec->time_base = (AVRational){1, 1000};
3102                 break;
3103             default:
3104                 abort();
3105                 break;
3106             }
3107             /* two pass mode */
3108             if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3109                 char logfilename[1024];
3110                 FILE *f;
3111
3112                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3113                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3114                          i);
3115                 if (!strcmp(ost->enc->name, "libx264")) {
3116                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3117                 } else {
3118                     if (codec->flags & CODEC_FLAG_PASS2) {
3119                         char  *logbuffer;
3120                         size_t logbuffer_size;
3121                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3122                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3123                                 logfilename);
3124                             exit_program(1);
3125                         }
3126                         codec->stats_in = logbuffer;
3127                     }
3128                     if (codec->flags & CODEC_FLAG_PASS1) {
3129                         f = fopen(logfilename, "wb");
3130                         if (!f) {
3131                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3132                                 logfilename, strerror(errno));
3133                             exit_program(1);
3134                         }
3135                         ost->logfile = f;
3136                     }
3137                 }
3138             }
3139         }
3140     }
3141
3142     /* open each encoder */
3143     for (i = 0; i < nb_output_streams; i++) {
3144         ost = output_streams[i];
3145         if (ost->encoding_needed) {
3146             AVCodec      *codec = ost->enc;
3147             AVCodecContext *dec = NULL;
3148             if (!codec) {
3149                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3150                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3151                 ret = AVERROR(EINVAL);
3152                 goto dump_format;
3153             }
3154
3155             if ((ist = get_input_stream(ost)))
3156                 dec = ist->st->codec;
3157             if (dec && dec->subtitle_header) {
3158                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
3159                 if (!ost->st->codec->subtitle_header) {
3160                     ret = AVERROR(ENOMEM);
3161                     goto dump_format;
3162                 }
3163                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3164                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
3165             }
3166             if (!av_dict_get(ost->opts, "threads", NULL, 0))
3167                 av_dict_set(&ost->opts, "threads", "auto", 0);
3168             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
3169                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
3170                         ost->file_index, ost->index);
3171                 ret = AVERROR(EINVAL);
3172                 goto dump_format;
3173             }
3174             assert_codec_experimental(ost->st->codec, 1);
3175             assert_avoptions(ost->opts);
3176             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
3177                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3178                                              " It takes bits/s as argument, not kbits/s\n");
3179             extra_size += ost->st->codec->extradata_size;
3180
3181             if (ost->st->codec->me_threshold)
3182                 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
3183         }
3184     }
3185
3186     /* init input streams */
3187     for (i = 0; i < nb_input_streams; i++)
3188         if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
3189             goto dump_format;
3190
3191     /* discard unused programs */
3192     for (i = 0; i < nb_input_files; i++) {
3193         InputFile *ifile = input_files[i];
3194         for (j = 0; j < ifile->ctx->nb_programs; j++) {
3195             AVProgram *p = ifile->ctx->programs[j];
3196             int discard  = AVDISCARD_ALL;
3197
3198             for (k = 0; k < p->nb_stream_indexes; k++)
3199                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3200                     discard = AVDISCARD_DEFAULT;
3201                     break;
3202                 }
3203             p->discard = discard;
3204         }
3205     }
3206
3207     /* open files and write file headers */
3208     for (i = 0; i < nb_output_files; i++) {
3209         oc = output_files[i]->ctx;
3210         oc->interrupt_callback = int_cb;
3211         if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
3212             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
3213             ret = AVERROR(EINVAL);
3214             goto dump_format;
3215         }
3216 //         assert_avoptions(output_files[i]->opts);
3217         if (strcmp(oc->oformat->name, "rtp")) {
3218             want_sdp = 0;
3219         }
3220     }
3221
3222  dump_format:
3223     /* dump the file output parameters - cannot be done before in case
3224        of stream copy */
3225     for (i = 0; i < nb_output_files; i++) {
3226         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3227     }
3228
3229     /* dump the stream mapping */
3230     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3231     for (i = 0; i < nb_input_streams; i++) {
3232         ist = input_streams[i];
3233
3234         for (j = 0; j < ist->nb_filters; j++) {
3235             AVFilterLink *link = ist->filters[j]->filter->outputs[0];
3236             if (ist->filters[j]->graph->graph_desc) {
3237                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
3238                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3239                        link->dst->filter->name);
3240                 if (link->dst->input_count > 1)
3241                     av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
3242                 if (nb_filtergraphs > 1)
3243                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3244                 av_log(NULL, AV_LOG_INFO, "\n");
3245             }
3246         }
3247     }
3248
3249     for (i = 0; i < nb_output_streams; i++) {
3250         ost = output_streams[i];
3251
3252         if (ost->attachment_filename) {
3253             /* an attached file */
3254             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
3255                    ost->attachment_filename, ost->file_index, ost->index);
3256             continue;
3257         }
3258
3259         if (ost->filter && ost->filter->graph->graph_desc) {
3260             /* output from a complex graph */
3261             AVFilterLink *link = ost->filter->filter->inputs[0];
3262             av_log(NULL, AV_LOG_INFO, "  %s", link->src->filter->name);
3263             if (link->src->output_count > 1)
3264                 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
3265             if (nb_filtergraphs > 1)
3266                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3267
3268             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3269                    ost->index, ost->enc ? ost->enc->name : "?");
3270             continue;
3271         }
3272
3273         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
3274                input_streams[ost->source_index]->file_index,
3275                input_streams[ost->source_index]->st->index,
3276                ost->file_index,
3277                ost->index);
3278         if (ost->audio_channels_mapped) {
3279             av_log(NULL, AV_LOG_INFO, " [ch:");
3280             for (j = 0; j < ost->audio_channels_mapped; j++)
3281                 if (ost->audio_channels_map[j] == -1)
3282                     av_log(NULL, AV_LOG_INFO, " M");
3283                 else
3284                     av_log(NULL, AV_LOG_INFO, " %d", ost->audio_channels_map[j]);
3285             av_log(NULL, AV_LOG_INFO, "]");
3286         }
3287         if (ost->sync_ist != input_streams[ost->source_index])
3288             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3289                    ost->sync_ist->file_index,
3290                    ost->sync_ist->st->index);
3291         if (ost->stream_copy)
3292             av_log(NULL, AV_LOG_INFO, " (copy)");
3293         else
3294             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
3295                    input_streams[ost->source_index]->dec->name : "?",
3296                    ost->enc ? ost->enc->name : "?");
3297         av_log(NULL, AV_LOG_INFO, "\n");
3298     }
3299
3300     if (ret) {
3301         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3302         return ret;
3303     }
3304
3305     if (want_sdp) {
3306         print_sdp();
3307     }
3308
3309     return 0;
3310 }
3311
3312 /*
3313  * The following code is the main loop of the file converter
3314  */
3315 static int transcode(void)
3316 {
3317     int ret, i;
3318     AVFormatContext *is, *os;
3319     OutputStream *ost;
3320     InputStream *ist;
3321     uint8_t *no_packet;
3322     int no_packet_count = 0;
3323     int64_t timer_start;
3324     int key;
3325
3326     if (!(no_packet = av_mallocz(nb_input_files)))
3327         exit_program(1);
3328
3329     ret = transcode_init();
3330     if (ret < 0)
3331         goto fail;
3332
3333     if (!using_stdin) {
3334         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3335     }
3336
3337     timer_start = av_gettime();
3338
3339     for (; received_sigterm == 0;) {
3340         int file_index, ist_index, past_recording_time = 1;
3341         AVPacket pkt;
3342         int64_t ipts_min;
3343         int64_t cur_time= av_gettime();
3344
3345         ipts_min = INT64_MAX;
3346         /* if 'q' pressed, exits */
3347         if (!using_stdin) {
3348             static int64_t last_time;
3349             if (received_nb_signals)
3350                 break;
3351             /* read_key() returns 0 on EOF */
3352             if(cur_time - last_time >= 100000 && !run_as_daemon){
3353                 key =  read_key();
3354                 last_time = cur_time;
3355             }else
3356                 key = -1;
3357             if (key == 'q')
3358                 break;
3359             if (key == '+') av_log_set_level(av_log_get_level()+10);
3360             if (key == '-') av_log_set_level(av_log_get_level()-10);
3361             if (key == 's') qp_hist     ^= 1;
3362             if (key == 'h'){
3363                 if (do_hex_dump){
3364                     do_hex_dump = do_pkt_dump = 0;
3365                 } else if(do_pkt_dump){
3366                     do_hex_dump = 1;
3367                 } else
3368                     do_pkt_dump = 1;
3369                 av_log_set_level(AV_LOG_DEBUG);
3370             }
3371             if (key == 'c' || key == 'C'){
3372                 char buf[4096], target[64], command[256], arg[256] = {0};
3373                 double time;
3374                 int k, n = 0;
3375                 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3376                 i = 0;
3377                 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3378                     if (k > 0)
3379                         buf[i++] = k;
3380                 buf[i] = 0;
3381                 if (k > 0 &&
3382                     (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3383                     av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3384                            target, time, command, arg);
3385                     for (i = 0; i < nb_filtergraphs; i++) {
3386                         FilterGraph *fg = filtergraphs[i];
3387                         if (fg->graph) {
3388                             if (time < 0) {
3389                                 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3390                                                                   key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3391                                 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3392                             } else {
3393                                 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3394                             }
3395                         }
3396                     }
3397                 } else {
3398                     av_log(NULL, AV_LOG_ERROR,
3399                            "Parse error, at least 3 arguments were expected, "
3400                            "only %d given in string '%s'\n", n, buf);
3401                 }
3402             }
3403             if (key == 'd' || key == 'D'){
3404                 int debug=0;
3405                 if(key == 'D') {
3406                     debug = input_streams[0]->st->codec->debug<<1;
3407                     if(!debug) debug = 1;
3408                     while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3409                         debug += debug;
3410                 }else
3411                     if(scanf("%d", &debug)!=1)
3412                         fprintf(stderr,"error parsing debug value\n");
3413                 for(i=0;i<nb_input_streams;i++) {
3414                     input_streams[i]->st->codec->debug = debug;
3415                 }
3416                 for(i=0;i<nb_output_streams;i++) {
3417                     ost = output_streams[i];
3418                     ost->st->codec->debug = debug;
3419                 }
3420                 if(debug) av_log_set_level(AV_LOG_DEBUG);
3421                 fprintf(stderr,"debug=%d\n", debug);
3422             }
3423             if (key == '?'){
3424                 fprintf(stderr, "key    function\n"
3425                                 "?      show this help\n"
3426                                 "+      increase verbosity\n"
3427                                 "-      decrease verbosity\n"
3428                                 "c      Send command to filtergraph\n"
3429                                 "D      cycle through available debug modes\n"
3430                                 "h      dump packets/hex press to cycle through the 3 states\n"
3431                                 "q      quit\n"
3432                                 "s      Show QP histogram\n"
3433                 );
3434             }
3435         }
3436
3437         /* check if there's any stream where output is still needed */
3438         for (i = 0; i < nb_output_streams; i++) {
3439             OutputFile *of;
3440             ost = output_streams[i];
3441             of  = output_files[ost->file_index];
3442             os  = output_files[ost->file_index]->ctx;
3443             if (ost->is_past_recording_time ||
3444                 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3445                 continue;
3446             if (ost->frame_number >= ost->max_frames) {
3447                 int j;
3448                 for (j = 0; j < of->ctx->nb_streams; j++)
3449                     output_streams[of->ost_index + j]->is_past_recording_time = 1;
3450                 continue;
3451             }
3452             past_recording_time = 0;
3453         }
3454         if (past_recording_time)
3455             break;
3456
3457         /* select the stream that we must read now by looking at the
3458            smallest output pts */
3459         file_index = -1;
3460         for (i = 0; i < nb_input_streams; i++) {
3461             int64_t ipts;
3462             ist = input_streams[i];
3463             ipts = ist->pts;
3464             if (ist->discard || no_packet[ist->file_index])
3465                 continue;
3466             if (!input_files[ist->file_index]->eof_reached) {
3467                 if (ipts < ipts_min) {
3468                     ipts_min = ipts;
3469                     file_index = ist->file_index;
3470                 }
3471             }
3472         }
3473         /* if none, if is finished */
3474         if (file_index < 0) {
3475             if (no_packet_count) {
3476                 no_packet_count = 0;
3477                 memset(no_packet, 0, nb_input_files);
3478                 usleep(10000);
3479                 continue;
3480             }
3481             break;
3482         }
3483
3484         /* read a frame from it and output it in the fifo */
3485         is  = input_files[file_index]->ctx;
3486         ret = av_read_frame(is, &pkt);
3487         if (ret == AVERROR(EAGAIN)) {
3488             no_packet[file_index] = 1;
3489             no_packet_count++;
3490             continue;
3491         }
3492         if (ret < 0) {
3493             input_files[file_index]->eof_reached = 1;
3494
3495             for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3496                 ist = input_streams[input_files[file_index]->ist_index + i];
3497                 if (ist->decoding_needed)
3498                     output_packet(ist, NULL);
3499             }
3500
3501             if (opt_shortest)
3502                 break;
3503             else
3504                 continue;
3505         }
3506
3507         no_packet_count = 0;
3508         memset(no_packet, 0, nb_input_files);
3509
3510         if (do_pkt_dump) {
3511             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3512                              is->streams[pkt.stream_index]);
3513         }
3514         /* the following test is needed in case new streams appear
3515            dynamically in stream : we ignore them */
3516         if (pkt.stream_index >= input_files[file_index]->nb_streams)
3517             goto discard_packet;
3518         ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3519         ist = input_streams[ist_index];
3520         if (ist->discard)
3521             goto discard_packet;
3522
3523         if (pkt.dts != AV_NOPTS_VALUE)
3524             pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3525         if (pkt.pts != AV_NOPTS_VALUE)
3526             pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3527
3528         if (pkt.pts != AV_NOPTS_VALUE)
3529             pkt.pts *= ist->ts_scale;
3530         if (pkt.dts != AV_NOPTS_VALUE)
3531             pkt.dts *= ist->ts_scale;
3532
3533         if (debug_ts) {
3534             av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3535                     "next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3536                     ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3537                     av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3538                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3539                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3540                     input_files[ist->file_index]->ts_offset);
3541         }
3542
3543         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3544             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3545             int64_t delta   = pkt_dts - ist->next_dts;
3546             if (is->iformat->flags & AVFMT_TS_DISCONT) {
3547             if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3548                 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3549                  ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3550                 pkt_dts+1<ist->pts){
3551                 input_files[ist->file_index]->ts_offset -= delta;
3552                 av_log(NULL, AV_LOG_DEBUG,
3553                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3554                        delta, input_files[ist->file_index]->ts_offset);
3555                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3556                 if (pkt.pts != AV_NOPTS_VALUE)
3557                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3558             }
3559             } else {
3560                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3561                     (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3562                      pkt_dts+1<ist->pts){
3563                     av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3564                     pkt.dts = AV_NOPTS_VALUE;
3565                 }
3566                 if (pkt.pts != AV_NOPTS_VALUE){
3567                     int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3568                     delta   = pkt_pts - ist->next_dts;
3569                     if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3570                         (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3571                         pkt_pts+1<ist->pts) {
3572                         av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3573                         pkt.pts = AV_NOPTS_VALUE;
3574                     }
3575                 }
3576             }
3577         }
3578
3579         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3580         if (output_packet(ist, &pkt) < 0 || poll_filters() < 0) {
3581             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3582                    ist->file_index, ist->st->index);
3583             if (exit_on_error)
3584                 exit_program(1);
3585             av_free_packet(&pkt);
3586             continue;
3587         }
3588
3589     discard_packet:
3590         av_free_packet(&pkt);
3591
3592         /* dump report by using the output first video and audio streams */
3593         print_report(0, timer_start, cur_time);
3594     }
3595
3596     /* at the end of stream, we must flush the decoder buffers */
3597     for (i = 0; i < nb_input_streams; i++) {
3598         ist = input_streams[i];
3599         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3600             output_packet(ist, NULL);
3601         }
3602     }
3603     poll_filters();
3604     flush_encoders();
3605
3606     term_exit();
3607
3608     /* write the trailer if needed and close file */
3609     for (i = 0; i < nb_output_files; i++) {
3610         os = output_files[i]->ctx;
3611         av_write_trailer(os);
3612     }
3613
3614     /* dump report by using the first video and audio streams */
3615     print_report(1, timer_start, av_gettime());
3616
3617     /* close each encoder */
3618     for (i = 0; i < nb_output_streams; i++) {
3619         ost = output_streams[i];
3620         if (ost->encoding_needed) {
3621             av_freep(&ost->st->codec->stats_in);
3622             avcodec_close(ost->st->codec);
3623         }
3624     }
3625
3626     /* close each decoder */
3627     for (i = 0; i < nb_input_streams; i++) {
3628         ist = input_streams[i];
3629         if (ist->decoding_needed) {
3630             avcodec_close(ist->st->codec);
3631         }
3632     }
3633
3634     /* finished ! */
3635     ret = 0;
3636
3637  fail:
3638     av_freep(&no_packet);
3639
3640     if (output_streams) {
3641         for (i = 0; i < nb_output_streams; i++) {
3642             ost = output_streams[i];
3643             if (ost) {
3644                 if (ost->stream_copy)
3645                     av_freep(&ost->st->codec->extradata);
3646                 if (ost->logfile) {
3647                     fclose(ost->logfile);
3648                     ost->logfile = NULL;
3649                 }
3650                 av_fifo_free(ost->fifo); /* works even if fifo is not
3651                                              initialized but set to zero */
3652                 av_freep(&ost->st->codec->subtitle_header);
3653                 av_free(ost->forced_kf_pts);
3654                 swr_free(&ost->swr);
3655                 av_dict_free(&ost->opts);
3656             }
3657         }
3658     }
3659     return ret;
3660 }
3661
3662 static int opt_frame_crop(const char *opt, const char *arg)
3663 {
3664     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3665     return AVERROR(EINVAL);
3666 }
3667
3668 static int opt_pad(const char *opt, const char *arg)
3669 {
3670     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3671     return -1;
3672 }
3673
3674 static int opt_video_channel(const char *opt, const char *arg)
3675 {
3676     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3677     return opt_default("channel", arg);
3678 }
3679
3680 static int opt_video_standard(const char *opt, const char *arg)
3681 {
3682     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3683     return opt_default("standard", arg);
3684 }
3685
3686 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3687 {
3688     audio_codec_name = arg;
3689     return parse_option(o, "codec:a", arg, options);
3690 }
3691
3692 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3693 {
3694     video_codec_name = arg;
3695     return parse_option(o, "codec:v", arg, options);
3696 }
3697
3698 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3699 {
3700     subtitle_codec_name = arg;
3701     return parse_option(o, "codec:s", arg, options);
3702 }
3703
3704 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3705 {
3706     return parse_option(o, "codec:d", arg, options);
3707 }
3708
3709 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3710 {
3711     StreamMap *m = NULL;
3712     int i, negative = 0, file_idx;
3713     int sync_file_idx = -1, sync_stream_idx = 0;
3714     char *p, *sync;
3715     char *map;
3716
3717     if (*arg == '-') {
3718         negative = 1;
3719         arg++;
3720     }
3721     map = av_strdup(arg);
3722
3723     /* parse sync stream first, just pick first matching stream */
3724     if (sync = strchr(map, ',')) {
3725         *sync = 0;
3726         sync_file_idx = strtol(sync + 1, &sync, 0);
3727         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3728             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3729             exit_program(1);
3730         }
3731         if (*sync)
3732             sync++;
3733         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3734             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3735                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3736                 sync_stream_idx = i;
3737                 break;
3738             }
3739         if (i == input_files[sync_file_idx]->nb_streams) {
3740             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3741                                        "match any streams.\n", arg);
3742             exit_program(1);
3743         }
3744     }
3745
3746
3747     if (map[0] == '[') {
3748         /* this mapping refers to lavfi output */
3749         const char *c = map + 1;
3750         o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3751                                     &o->nb_stream_maps, o->nb_stream_maps + 1);
3752         m = &o->stream_maps[o->nb_stream_maps - 1];
3753         m->linklabel = av_get_token(&c, "]");
3754         if (!m->linklabel) {
3755             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3756             exit_program(1);
3757         }
3758     } else {
3759         file_idx = strtol(map, &p, 0);
3760         if (file_idx >= nb_input_files || file_idx < 0) {
3761             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3762             exit_program(1);
3763         }
3764         if (negative)
3765             /* disable some already defined maps */
3766             for (i = 0; i < o->nb_stream_maps; i++) {
3767                 m = &o->stream_maps[i];
3768                 if (file_idx == m->file_index &&
3769                     check_stream_specifier(input_files[m->file_index]->ctx,
3770                                            input_files[m->file_index]->ctx->streams[m->stream_index],
3771                                            *p == ':' ? p + 1 : p) > 0)
3772                     m->disabled = 1;
3773             }
3774         else
3775             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3776                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3777                             *p == ':' ? p + 1 : p) <= 0)
3778                     continue;
3779                 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3780                                             &o->nb_stream_maps, o->nb_stream_maps + 1);
3781                 m = &o->stream_maps[o->nb_stream_maps - 1];
3782
3783                 m->file_index   = file_idx;
3784                 m->stream_index = i;
3785
3786                 if (sync_file_idx >= 0) {
3787                     m->sync_file_index   = sync_file_idx;
3788                     m->sync_stream_index = sync_stream_idx;
3789                 } else {
3790                     m->sync_file_index   = file_idx;
3791                     m->sync_stream_index = i;
3792                 }
3793             }
3794     }
3795
3796     if (!m) {
3797         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3798         exit_program(1);
3799     }
3800
3801     av_freep(&map);
3802     return 0;
3803 }
3804
3805 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3806 {
3807     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3808                                 &o->nb_attachments, o->nb_attachments + 1);
3809     o->attachments[o->nb_attachments - 1] = arg;
3810     return 0;
3811 }
3812
3813 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3814 {
3815     int n;
3816     AVStream *st;
3817     AudioChannelMap *m;
3818
3819     o->audio_channel_maps =
3820         grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3821                    &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3822     m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3823
3824     /* muted channel syntax */
3825     n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3826     if ((n == 1 || n == 3) && m->channel_idx == -1) {
3827         m->file_idx = m->stream_idx = -1;
3828         if (n == 1)
3829             m->ofile_idx = m->ostream_idx = -1;
3830         return 0;
3831     }
3832
3833     /* normal syntax */
3834     n = sscanf(arg, "%d.%d.%d:%d.%d",
3835                &m->file_idx,  &m->stream_idx, &m->channel_idx,
3836                &m->ofile_idx, &m->ostream_idx);
3837
3838     if (n != 3 && n != 5) {
3839         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3840                "[file.stream.channel|-1][:syncfile:syncstream]\n");
3841         exit_program(1);
3842     }
3843
3844     if (n != 5) // only file.stream.channel specified
3845         m->ofile_idx = m->ostream_idx = -1;
3846
3847     /* check input */
3848     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
3849         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
3850                m->file_idx);
3851         exit_program(1);
3852     }
3853     if (m->stream_idx < 0 ||
3854         m->stream_idx >= input_files[m->file_idx]->nb_streams) {
3855         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
3856                m->file_idx, m->stream_idx);
3857         exit_program(1);
3858     }
3859     st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
3860     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
3861         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
3862                m->file_idx, m->stream_idx);
3863         exit_program(1);
3864     }
3865     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
3866         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
3867                m->file_idx, m->stream_idx, m->channel_idx);
3868         exit_program(1);
3869     }
3870     return 0;
3871 }
3872
3873 /**
3874  * Parse a metadata specifier in arg.
3875  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3876  * @param index for type c/p, chapter/program index is written here
3877  * @param stream_spec for type s, the stream specifier is written here
3878  */
3879 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3880 {
3881     if (*arg) {
3882         *type = *arg;
3883         switch (*arg) {
3884         case 'g':
3885             break;
3886         case 's':
3887             if (*(++arg) && *arg != ':') {
3888                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3889                 exit_program(1);
3890             }
3891             *stream_spec = *arg == ':' ? arg + 1 : "";
3892             break;
3893         case 'c':
3894         case 'p':
3895             if (*(++arg) == ':')
3896                 *index = strtol(++arg, NULL, 0);
3897             break;
3898         default:
3899             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3900             exit_program(1);
3901         }
3902     } else
3903         *type = 'g';
3904 }
3905
3906 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3907 {
3908     AVDictionary **meta_in = NULL;
3909     AVDictionary **meta_out = NULL;
3910     int i, ret = 0;
3911     char type_in, type_out;
3912     const char *istream_spec = NULL, *ostream_spec = NULL;
3913     int idx_in = 0, idx_out = 0;
3914
3915     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
3916     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3917
3918     if (!ic) {
3919         if (type_out == 'g' || !*outspec)
3920             o->metadata_global_manual = 1;
3921         if (type_out == 's' || !*outspec)
3922             o->metadata_streams_manual = 1;
3923         if (type_out == 'c' || !*outspec)
3924             o->metadata_chapters_manual = 1;
3925         return 0;
3926     }
3927