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