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