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