ffmpeg: do not deprecate -vol and -map_channel.
[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     int i;
2814     InputStream *ist = input_streams[ist_index];
2815
2816     if (ist->decoding_needed) {
2817         AVCodec *codec = ist->dec;
2818         if (!codec) {
2819             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2820                     avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2821             return AVERROR(EINVAL);
2822         }
2823
2824         ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
2825         if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2826             ist->st->codec->get_buffer     = codec_get_buffer;
2827             ist->st->codec->release_buffer = codec_release_buffer;
2828             ist->st->codec->opaque         = ist;
2829         }
2830
2831         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2832             av_dict_set(&ist->opts, "threads", "auto", 0);
2833         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2834             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2835                     ist->file_index, ist->st->index);
2836             return AVERROR(EINVAL);
2837         }
2838         assert_codec_experimental(ist->st->codec, 0);
2839         assert_avoptions(ist->opts);
2840     }
2841
2842     ist->next_pts = AV_NOPTS_VALUE;
2843     ist->next_dts = AV_NOPTS_VALUE;
2844     ist->is_start = 1;
2845
2846     return 0;
2847 }
2848
2849 static InputStream *get_input_stream(OutputStream *ost)
2850 {
2851     if (ost->source_index >= 0)
2852         return input_streams[ost->source_index];
2853
2854     if (ost->filter) {
2855         FilterGraph *fg = ost->filter->graph;
2856         int i;
2857
2858         for (i = 0; i < fg->nb_inputs; i++)
2859             if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
2860                 return fg->inputs[i]->ist;
2861     }
2862
2863     return NULL;
2864 }
2865
2866 static int transcode_init(void)
2867 {
2868     int ret = 0, i, j, k;
2869     AVFormatContext *oc;
2870     AVCodecContext *codec, *icodec;
2871     OutputStream *ost;
2872     InputStream *ist;
2873     char error[1024];
2874     int want_sdp = 1;
2875
2876     /* init framerate emulation */
2877     for (i = 0; i < nb_input_files; i++) {
2878         InputFile *ifile = input_files[i];
2879         if (ifile->rate_emu)
2880             for (j = 0; j < ifile->nb_streams; j++)
2881                 input_streams[j + ifile->ist_index]->start = av_gettime();
2882     }
2883
2884     /* output stream init */
2885     for (i = 0; i < nb_output_files; i++) {
2886         oc = output_files[i]->ctx;
2887         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2888             av_dump_format(oc, i, oc->filename, 1);
2889             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2890             return AVERROR(EINVAL);
2891         }
2892     }
2893
2894     /* init complex filtergraphs */
2895     for (i = 0; i < nb_filtergraphs; i++)
2896         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2897             return ret;
2898
2899     /* for each output stream, we compute the right encoding parameters */
2900     for (i = 0; i < nb_output_streams; i++) {
2901         ost = output_streams[i];
2902         oc  = output_files[ost->file_index]->ctx;
2903         ist = get_input_stream(ost);
2904
2905         if (ost->attachment_filename)
2906             continue;
2907
2908         codec  = ost->st->codec;
2909
2910         if (ist) {
2911             icodec = ist->st->codec;
2912
2913             ost->st->disposition          = ist->st->disposition;
2914             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2915             codec->chroma_sample_location = icodec->chroma_sample_location;
2916         }
2917
2918         if (ost->stream_copy) {
2919             uint64_t extra_size;
2920
2921             av_assert0(ist && !ost->filter);
2922
2923             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2924
2925             if (extra_size > INT_MAX) {
2926                 return AVERROR(EINVAL);
2927             }
2928
2929             /* if stream_copy is selected, no need to decode or encode */
2930             codec->codec_id   = icodec->codec_id;
2931             codec->codec_type = icodec->codec_type;
2932
2933             if (!codec->codec_tag) {
2934                 if (!oc->oformat->codec_tag ||
2935                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2936                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2937                     codec->codec_tag = icodec->codec_tag;
2938             }
2939
2940             codec->bit_rate       = icodec->bit_rate;
2941             codec->rc_max_rate    = icodec->rc_max_rate;
2942             codec->rc_buffer_size = icodec->rc_buffer_size;
2943             codec->field_order    = icodec->field_order;
2944             codec->extradata      = av_mallocz(extra_size);
2945             if (!codec->extradata) {
2946                 return AVERROR(ENOMEM);
2947             }
2948             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2949             codec->extradata_size= icodec->extradata_size;
2950             codec->bits_per_coded_sample  = icodec->bits_per_coded_sample;
2951
2952             codec->time_base = ist->st->time_base;
2953             /*
2954              * Avi is a special case here because it supports variable fps but
2955              * having the fps and timebase differe significantly adds quite some
2956              * overhead
2957              */
2958             if(!strcmp(oc->oformat->name, "avi")) {
2959                 if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2960                                  && av_q2d(ist->st->time_base) < 1.0/500
2961                     || copy_tb==0){
2962                     codec->time_base = icodec->time_base;
2963                     codec->time_base.num *= icodec->ticks_per_frame;
2964                     codec->time_base.den *= 2;
2965                     codec->ticks_per_frame = 2;
2966                 }
2967             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2968                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2969                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2970             ) {
2971                 if(   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2972                                 && av_q2d(ist->st->time_base) < 1.0/500
2973                    || copy_tb==0){
2974                     codec->time_base = icodec->time_base;
2975                     codec->time_base.num *= icodec->ticks_per_frame;
2976                 }
2977             }
2978             av_reduce(&codec->time_base.num, &codec->time_base.den,
2979                         codec->time_base.num, codec->time_base.den, INT_MAX);
2980
2981             switch (codec->codec_type) {
2982             case AVMEDIA_TYPE_AUDIO:
2983                 if (audio_volume != 256) {
2984                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2985                     exit_program(1);
2986                 }
2987                 codec->channel_layout     = icodec->channel_layout;
2988                 codec->sample_rate        = icodec->sample_rate;
2989                 codec->channels           = icodec->channels;
2990                 codec->frame_size         = icodec->frame_size;
2991                 codec->audio_service_type = icodec->audio_service_type;
2992                 codec->block_align        = icodec->block_align;
2993                 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
2994                     codec->block_align= 0;
2995                 if(codec->codec_id == CODEC_ID_AC3)
2996                     codec->block_align= 0;
2997                 break;
2998             case AVMEDIA_TYPE_VIDEO:
2999                 codec->pix_fmt            = icodec->pix_fmt;
3000                 codec->width              = icodec->width;
3001                 codec->height             = icodec->height;
3002                 codec->has_b_frames       = icodec->has_b_frames;
3003                 if (!codec->sample_aspect_ratio.num) {
3004                     codec->sample_aspect_ratio   =
3005                     ost->st->sample_aspect_ratio =
3006                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
3007                         ist->st->codec->sample_aspect_ratio.num ?
3008                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
3009                 }
3010                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3011                 break;
3012             case AVMEDIA_TYPE_SUBTITLE:
3013                 codec->width  = icodec->width;
3014                 codec->height = icodec->height;
3015                 break;
3016             case AVMEDIA_TYPE_DATA:
3017             case AVMEDIA_TYPE_ATTACHMENT:
3018                 break;
3019             default:
3020                 abort();
3021             }
3022         } else {
3023             if (!ost->enc)
3024                 ost->enc = avcodec_find_encoder(codec->codec_id);
3025             if (!ost->enc) {
3026                 /* should only happen when a default codec is not present. */
3027                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3028                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3029                 ret = AVERROR(EINVAL);
3030                 goto dump_format;
3031             }
3032
3033             if (ist)
3034                 ist->decoding_needed = 1;
3035             ost->encoding_needed = 1;
3036
3037             if (!ost->filter &&
3038                 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3039                  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
3040                     FilterGraph *fg;
3041                     fg = init_simple_filtergraph(ist, ost);
3042                     if (configure_simple_filtergraph(fg)) {
3043                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3044                         exit(1);
3045                     }
3046             }
3047
3048             switch (codec->codec_type) {
3049             case AVMEDIA_TYPE_AUDIO:
3050                 codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
3051                 codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
3052                 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
3053                 codec->channels       = av_get_channel_layout_nb_channels(codec->channel_layout);
3054                 codec->time_base      = (AVRational){ 1, codec->sample_rate };
3055                 break;
3056             case AVMEDIA_TYPE_VIDEO:
3057                 if (ist && !ost->frame_rate.num)
3058                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
3059                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3060                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3061                     ost->frame_rate = ost->enc->supported_framerates[idx];
3062                 }
3063                 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
3064                 if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3065                    && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3066                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3067                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3068                 }
3069                 for (j = 0; j < ost->forced_kf_count; j++)
3070                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3071                                                          AV_TIME_BASE_Q,
3072                                                          codec->time_base);
3073
3074                 codec->width  = ost->filter->filter->inputs[0]->w;
3075                 codec->height = ost->filter->filter->inputs[0]->h;
3076                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3077                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3078                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3079                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
3080                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3081
3082                 if (codec->width   != icodec->width  ||
3083                     codec->height  != icodec->height ||
3084                     codec->pix_fmt != icodec->pix_fmt) {
3085                     codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3086                 }
3087
3088                 break;
3089             case AVMEDIA_TYPE_SUBTITLE:
3090                 codec->time_base = (AVRational){1, 1000};
3091                 break;
3092             default:
3093                 abort();
3094                 break;
3095             }
3096             /* two pass mode */
3097             if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3098                 char logfilename[1024];
3099                 FILE *f;
3100
3101                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3102                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3103                          i);
3104                 if (!strcmp(ost->enc->name, "libx264")) {
3105                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3106                 } else {
3107                     if (codec->flags & CODEC_FLAG_PASS2) {
3108                         char  *logbuffer;
3109                         size_t logbuffer_size;
3110                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3111                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3112                                 logfilename);
3113                             exit_program(1);
3114                         }
3115                         codec->stats_in = logbuffer;
3116                     }
3117                     if (codec->flags & CODEC_FLAG_PASS1) {
3118                         f = fopen(logfilename, "wb");
3119                         if (!f) {
3120                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3121                                 logfilename, strerror(errno));
3122                             exit_program(1);
3123                         }
3124                         ost->logfile = f;
3125                     }
3126                 }
3127             }
3128         }
3129     }
3130
3131     /* open each encoder */
3132     for (i = 0; i < nb_output_streams; i++) {
3133         ost = output_streams[i];
3134         if (ost->encoding_needed) {
3135             AVCodec      *codec = ost->enc;
3136             AVCodecContext *dec = NULL;
3137
3138             if ((ist = get_input_stream(ost)))
3139                 dec = ist->st->codec;
3140             if (dec && dec->subtitle_header) {
3141                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
3142                 if (!ost->st->codec->subtitle_header) {
3143                     ret = AVERROR(ENOMEM);
3144                     goto dump_format;
3145                 }
3146                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3147                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
3148             }
3149             if (!av_dict_get(ost->opts, "threads", NULL, 0))
3150                 av_dict_set(&ost->opts, "threads", "auto", 0);
3151             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
3152                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
3153                         ost->file_index, ost->index);
3154                 ret = AVERROR(EINVAL);
3155                 goto dump_format;
3156             }
3157             assert_codec_experimental(ost->st->codec, 1);
3158             assert_avoptions(ost->opts);
3159             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
3160                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3161                                              " It takes bits/s as argument, not kbits/s\n");
3162             extra_size += ost->st->codec->extradata_size;
3163
3164             if (ost->st->codec->me_threshold)
3165                 input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
3166         }
3167     }
3168
3169     /* init input streams */
3170     for (i = 0; i < nb_input_streams; i++)
3171         if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
3172             goto dump_format;
3173
3174     /* discard unused programs */
3175     for (i = 0; i < nb_input_files; i++) {
3176         InputFile *ifile = input_files[i];
3177         for (j = 0; j < ifile->ctx->nb_programs; j++) {
3178             AVProgram *p = ifile->ctx->programs[j];
3179             int discard  = AVDISCARD_ALL;
3180
3181             for (k = 0; k < p->nb_stream_indexes; k++)
3182                 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3183                     discard = AVDISCARD_DEFAULT;
3184                     break;
3185                 }
3186             p->discard = discard;
3187         }
3188     }
3189
3190     /* open files and write file headers */
3191     for (i = 0; i < nb_output_files; i++) {
3192         oc = output_files[i]->ctx;
3193         oc->interrupt_callback = int_cb;
3194         if (avformat_write_header(oc, &output_files[i]->opts) < 0) {
3195             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
3196             ret = AVERROR(EINVAL);
3197             goto dump_format;
3198         }
3199 //         assert_avoptions(output_files[i]->opts);
3200         if (strcmp(oc->oformat->name, "rtp")) {
3201             want_sdp = 0;
3202         }
3203     }
3204
3205  dump_format:
3206     /* dump the file output parameters - cannot be done before in case
3207        of stream copy */
3208     for (i = 0; i < nb_output_files; i++) {
3209         av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
3210     }
3211
3212     /* dump the stream mapping */
3213     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3214     for (i = 0; i < nb_input_streams; i++) {
3215         ist = input_streams[i];
3216
3217         for (j = 0; j < ist->nb_filters; j++) {
3218             AVFilterLink *link = ist->filters[j]->filter->outputs[0];
3219             if (ist->filters[j]->graph->graph_desc) {
3220                 av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
3221                        ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3222                        link->dst->filter->name);
3223                 if (link->dst->input_count > 1)
3224                     av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);
3225                 if (nb_filtergraphs > 1)
3226                     av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3227                 av_log(NULL, AV_LOG_INFO, "\n");
3228             }
3229         }
3230     }
3231
3232     for (i = 0; i < nb_output_streams; i++) {
3233         ost = output_streams[i];
3234
3235         if (ost->attachment_filename) {
3236             /* an attached file */
3237             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
3238                    ost->attachment_filename, ost->file_index, ost->index);
3239             continue;
3240         }
3241
3242         if (ost->filter && ost->filter->graph->graph_desc) {
3243             /* output from a complex graph */
3244             AVFilterLink *link = ost->filter->filter->inputs[0];
3245             av_log(NULL, AV_LOG_INFO, "  %s", link->src->filter->name);
3246             if (link->src->output_count > 1)
3247                 av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);
3248             if (nb_filtergraphs > 1)
3249                 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3250
3251             av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3252                    ost->index, ost->enc ? ost->enc->name : "?");
3253             continue;
3254         }
3255
3256         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
3257                input_streams[ost->source_index]->file_index,
3258                input_streams[ost->source_index]->st->index,
3259                ost->file_index,
3260                ost->index);
3261         if (ost->sync_ist != input_streams[ost->source_index])
3262             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3263                    ost->sync_ist->file_index,
3264                    ost->sync_ist->st->index);
3265         if (ost->stream_copy)
3266             av_log(NULL, AV_LOG_INFO, " (copy)");
3267         else
3268             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
3269                    input_streams[ost->source_index]->dec->name : "?",
3270                    ost->enc ? ost->enc->name : "?");
3271         av_log(NULL, AV_LOG_INFO, "\n");
3272     }
3273
3274     if (ret) {
3275         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3276         return ret;
3277     }
3278
3279     if (want_sdp) {
3280         print_sdp();
3281     }
3282
3283     return 0;
3284 }
3285
3286 /*
3287  * The following code is the main loop of the file converter
3288  */
3289 static int transcode(void)
3290 {
3291     int ret, i;
3292     AVFormatContext *is, *os;
3293     OutputStream *ost;
3294     InputStream *ist;
3295     uint8_t *no_packet;
3296     int no_packet_count = 0;
3297     int64_t timer_start;
3298     int key;
3299
3300     if (!(no_packet = av_mallocz(nb_input_files)))
3301         exit_program(1);
3302
3303     ret = transcode_init();
3304     if (ret < 0)
3305         goto fail;
3306
3307     if (!using_stdin) {
3308         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3309     }
3310
3311     timer_start = av_gettime();
3312
3313     for (; received_sigterm == 0;) {
3314         int file_index, ist_index, past_recording_time = 1;
3315         AVPacket pkt;
3316         int64_t ipts_min;
3317         int64_t cur_time= av_gettime();
3318
3319         ipts_min = INT64_MAX;
3320         /* if 'q' pressed, exits */
3321         if (!using_stdin) {
3322             static int64_t last_time;
3323             if (received_nb_signals)
3324                 break;
3325             /* read_key() returns 0 on EOF */
3326             if(cur_time - last_time >= 100000 && !run_as_daemon){
3327                 key =  read_key();
3328                 last_time = cur_time;
3329             }else
3330                 key = -1;
3331             if (key == 'q')
3332                 break;
3333             if (key == '+') av_log_set_level(av_log_get_level()+10);
3334             if (key == '-') av_log_set_level(av_log_get_level()-10);
3335             if (key == 's') qp_hist     ^= 1;
3336             if (key == 'h'){
3337                 if (do_hex_dump){
3338                     do_hex_dump = do_pkt_dump = 0;
3339                 } else if(do_pkt_dump){
3340                     do_hex_dump = 1;
3341                 } else
3342                     do_pkt_dump = 1;
3343                 av_log_set_level(AV_LOG_DEBUG);
3344             }
3345             if (key == 'c' || key == 'C'){
3346                 char buf[4096], target[64], command[256], arg[256] = {0};
3347                 double time;
3348                 int k, n = 0;
3349                 fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3350                 i = 0;
3351                 while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3352                     if (k > 0)
3353                         buf[i++] = k;
3354                 buf[i] = 0;
3355                 if (k > 0 &&
3356                     (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3357                     av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3358                            target, time, command, arg);
3359                     for (i = 0; i < nb_filtergraphs; i++) {
3360                         FilterGraph *fg = filtergraphs[i];
3361                         if (fg->graph) {
3362                             if (time < 0) {
3363                                 ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3364                                                                   key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3365                                 fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3366                             } else {
3367                                 ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3368                             }
3369                         }
3370                     }
3371                 } else {
3372                     av_log(NULL, AV_LOG_ERROR,
3373                            "Parse error, at least 3 arguments were expected, "
3374                            "only %d given in string '%s'\n", n, buf);
3375                 }
3376             }
3377             if (key == 'd' || key == 'D'){
3378                 int debug=0;
3379                 if(key == 'D') {
3380                     debug = input_streams[0]->st->codec->debug<<1;
3381                     if(!debug) debug = 1;
3382                     while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3383                         debug += debug;
3384                 }else
3385                     if(scanf("%d", &debug)!=1)
3386                         fprintf(stderr,"error parsing debug value\n");
3387                 for(i=0;i<nb_input_streams;i++) {
3388                     input_streams[i]->st->codec->debug = debug;
3389                 }
3390                 for(i=0;i<nb_output_streams;i++) {
3391                     ost = output_streams[i];
3392                     ost->st->codec->debug = debug;
3393                 }
3394                 if(debug) av_log_set_level(AV_LOG_DEBUG);
3395                 fprintf(stderr,"debug=%d\n", debug);
3396             }
3397             if (key == '?'){
3398                 fprintf(stderr, "key    function\n"
3399                                 "?      show this help\n"
3400                                 "+      increase verbosity\n"
3401                                 "-      decrease verbosity\n"
3402                                 "c      Send command to filtergraph\n"
3403                                 "D      cycle through available debug modes\n"
3404                                 "h      dump packets/hex press to cycle through the 3 states\n"
3405                                 "q      quit\n"
3406                                 "s      Show QP histogram\n"
3407                 );
3408             }
3409         }
3410
3411         /* check if there's any stream where output is still needed */
3412         for (i = 0; i < nb_output_streams; i++) {
3413             OutputFile *of;
3414             ost = output_streams[i];
3415             of  = output_files[ost->file_index];
3416             os  = output_files[ost->file_index]->ctx;
3417             if (ost->is_past_recording_time ||
3418                 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3419                 continue;
3420             if (ost->frame_number >= ost->max_frames) {
3421                 int j;
3422                 for (j = 0; j < of->ctx->nb_streams; j++)
3423                     output_streams[of->ost_index + j]->is_past_recording_time = 1;
3424                 continue;
3425             }
3426             past_recording_time = 0;
3427         }
3428         if (past_recording_time)
3429             break;
3430
3431         /* select the stream that we must read now by looking at the
3432            smallest output pts */
3433         file_index = -1;
3434         for (i = 0; i < nb_input_streams; i++) {
3435             int64_t ipts;
3436             ist = input_streams[i];
3437             ipts = ist->pts;
3438             if (ist->discard || no_packet[ist->file_index])
3439                 continue;
3440             if (!input_files[ist->file_index]->eof_reached) {
3441                 if (ipts < ipts_min) {
3442                     ipts_min = ipts;
3443                     file_index = ist->file_index;
3444                 }
3445             }
3446         }
3447         /* if none, if is finished */
3448         if (file_index < 0) {
3449             if (no_packet_count) {
3450                 no_packet_count = 0;
3451                 memset(no_packet, 0, nb_input_files);
3452                 usleep(10000);
3453                 continue;
3454             }
3455             break;
3456         }
3457
3458         /* read a frame from it and output it in the fifo */
3459         is  = input_files[file_index]->ctx;
3460         ret = av_read_frame(is, &pkt);
3461         if (ret == AVERROR(EAGAIN)) {
3462             no_packet[file_index] = 1;
3463             no_packet_count++;
3464             continue;
3465         }
3466         if (ret < 0) {
3467             input_files[file_index]->eof_reached = 1;
3468
3469             for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3470                 ist = input_streams[input_files[file_index]->ist_index + i];
3471                 if (ist->decoding_needed)
3472                     output_packet(ist, NULL);
3473             }
3474
3475             if (opt_shortest)
3476                 break;
3477             else
3478                 continue;
3479         }
3480
3481         no_packet_count = 0;
3482         memset(no_packet, 0, nb_input_files);
3483
3484         if (do_pkt_dump) {
3485             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3486                              is->streams[pkt.stream_index]);
3487         }
3488         /* the following test is needed in case new streams appear
3489            dynamically in stream : we ignore them */
3490         if (pkt.stream_index >= input_files[file_index]->nb_streams)
3491             goto discard_packet;
3492         ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3493         ist = input_streams[ist_index];
3494         if (ist->discard)
3495             goto discard_packet;
3496
3497         if (pkt.dts != AV_NOPTS_VALUE)
3498             pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3499         if (pkt.pts != AV_NOPTS_VALUE)
3500             pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3501
3502         if (pkt.pts != AV_NOPTS_VALUE)
3503             pkt.pts *= ist->ts_scale;
3504         if (pkt.dts != AV_NOPTS_VALUE)
3505             pkt.dts *= ist->ts_scale;
3506
3507         if (debug_ts) {
3508             av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3509                     "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",
3510                     ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3511                     av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &ist->st->time_base),
3512                     av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &ist->st->time_base),
3513                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3514                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3515                     input_files[ist->file_index]->ts_offset);
3516         }
3517
3518         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3519             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3520             int64_t delta   = pkt_dts - ist->next_dts;
3521             if (is->iformat->flags & AVFMT_TS_DISCONT) {
3522             if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3523                 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3524                  ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3525                 pkt_dts+1<ist->pts){
3526                 input_files[ist->file_index]->ts_offset -= delta;
3527                 av_log(NULL, AV_LOG_DEBUG,
3528                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3529                        delta, input_files[ist->file_index]->ts_offset);
3530                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3531                 if (pkt.pts != AV_NOPTS_VALUE)
3532                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3533             }
3534             } else {
3535                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3536                     (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3537                      pkt_dts+1<ist->pts){
3538                     av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3539                     pkt.dts = AV_NOPTS_VALUE;
3540                 }
3541                 if (pkt.pts != AV_NOPTS_VALUE){
3542                     int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3543                     delta   = pkt_pts - ist->next_dts;
3544                     if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3545                         (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3546                         pkt_pts+1<ist->pts) {
3547                         av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3548                         pkt.pts = AV_NOPTS_VALUE;
3549                     }
3550                 }
3551             }
3552         }
3553
3554         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
3555         if (output_packet(ist, &pkt) < 0 ||
3556             ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
3557             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
3558                    ist->file_index, ist->st->index);
3559             if (exit_on_error)
3560                 exit_program(1);
3561             av_free_packet(&pkt);
3562             continue;
3563         }
3564
3565     discard_packet:
3566         av_free_packet(&pkt);
3567
3568         /* dump report by using the output first video and audio streams */
3569         print_report(0, timer_start, cur_time);
3570     }
3571
3572     /* at the end of stream, we must flush the decoder buffers */
3573     for (i = 0; i < nb_input_streams; i++) {
3574         ist = input_streams[i];
3575         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3576             output_packet(ist, NULL);
3577         }
3578     }
3579     poll_filters();
3580     flush_encoders();
3581
3582     term_exit();
3583
3584     /* write the trailer if needed and close file */
3585     for (i = 0; i < nb_output_files; i++) {
3586         os = output_files[i]->ctx;
3587         av_write_trailer(os);
3588     }
3589
3590     /* dump report by using the first video and audio streams */
3591     print_report(1, timer_start, av_gettime());
3592
3593     /* close each encoder */
3594     for (i = 0; i < nb_output_streams; i++) {
3595         ost = output_streams[i];
3596         if (ost->encoding_needed) {
3597             av_freep(&ost->st->codec->stats_in);
3598             avcodec_close(ost->st->codec);
3599         }
3600     }
3601
3602     /* close each decoder */
3603     for (i = 0; i < nb_input_streams; i++) {
3604         ist = input_streams[i];
3605         if (ist->decoding_needed) {
3606             avcodec_close(ist->st->codec);
3607         }
3608     }
3609
3610     /* finished ! */
3611     ret = 0;
3612
3613  fail:
3614     av_freep(&no_packet);
3615
3616     if (output_streams) {
3617         for (i = 0; i < nb_output_streams; i++) {
3618             ost = output_streams[i];
3619             if (ost) {
3620                 if (ost->stream_copy)
3621                     av_freep(&ost->st->codec->extradata);
3622                 if (ost->logfile) {
3623                     fclose(ost->logfile);
3624                     ost->logfile = NULL;
3625                 }
3626                 av_freep(&ost->st->codec->subtitle_header);
3627                 av_free(ost->forced_kf_pts);
3628                 av_dict_free(&ost->opts);
3629             }
3630         }
3631     }
3632     return ret;
3633 }
3634
3635 static int opt_frame_crop(const char *opt, const char *arg)
3636 {
3637     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
3638     return AVERROR(EINVAL);
3639 }
3640
3641 static int opt_pad(const char *opt, const char *arg)
3642 {
3643     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
3644     return -1;
3645 }
3646
3647 static int opt_video_channel(const char *opt, const char *arg)
3648 {
3649     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
3650     return opt_default("channel", arg);
3651 }
3652
3653 static int opt_video_standard(const char *opt, const char *arg)
3654 {
3655     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
3656     return opt_default("standard", arg);
3657 }
3658
3659 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
3660 {
3661     audio_codec_name = arg;
3662     return parse_option(o, "codec:a", arg, options);
3663 }
3664
3665 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
3666 {
3667     video_codec_name = arg;
3668     return parse_option(o, "codec:v", arg, options);
3669 }
3670
3671 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
3672 {
3673     subtitle_codec_name = arg;
3674     return parse_option(o, "codec:s", arg, options);
3675 }
3676
3677 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
3678 {
3679     return parse_option(o, "codec:d", arg, options);
3680 }
3681
3682 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
3683 {
3684     StreamMap *m = NULL;
3685     int i, negative = 0, file_idx;
3686     int sync_file_idx = -1, sync_stream_idx = 0;
3687     char *p, *sync;
3688     char *map;
3689
3690     if (*arg == '-') {
3691         negative = 1;
3692         arg++;
3693     }
3694     map = av_strdup(arg);
3695
3696     /* parse sync stream first, just pick first matching stream */
3697     if (sync = strchr(map, ',')) {
3698         *sync = 0;
3699         sync_file_idx = strtol(sync + 1, &sync, 0);
3700         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
3701             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
3702             exit_program(1);
3703         }
3704         if (*sync)
3705             sync++;
3706         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
3707             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
3708                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
3709                 sync_stream_idx = i;
3710                 break;
3711             }
3712         if (i == input_files[sync_file_idx]->nb_streams) {
3713             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
3714                                        "match any streams.\n", arg);
3715             exit_program(1);
3716         }
3717     }
3718
3719
3720     if (map[0] == '[') {
3721         /* this mapping refers to lavfi output */
3722         const char *c = map + 1;
3723         o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3724                                     &o->nb_stream_maps, o->nb_stream_maps + 1);
3725         m = &o->stream_maps[o->nb_stream_maps - 1];
3726         m->linklabel = av_get_token(&c, "]");
3727         if (!m->linklabel) {
3728             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
3729             exit_program(1);
3730         }
3731     } else {
3732         file_idx = strtol(map, &p, 0);
3733         if (file_idx >= nb_input_files || file_idx < 0) {
3734             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
3735             exit_program(1);
3736         }
3737         if (negative)
3738             /* disable some already defined maps */
3739             for (i = 0; i < o->nb_stream_maps; i++) {
3740                 m = &o->stream_maps[i];
3741                 if (file_idx == m->file_index &&
3742                     check_stream_specifier(input_files[m->file_index]->ctx,
3743                                            input_files[m->file_index]->ctx->streams[m->stream_index],
3744                                            *p == ':' ? p + 1 : p) > 0)
3745                     m->disabled = 1;
3746             }
3747         else
3748             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
3749                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
3750                             *p == ':' ? p + 1 : p) <= 0)
3751                     continue;
3752                 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
3753                                             &o->nb_stream_maps, o->nb_stream_maps + 1);
3754                 m = &o->stream_maps[o->nb_stream_maps - 1];
3755
3756                 m->file_index   = file_idx;
3757                 m->stream_index = i;
3758
3759                 if (sync_file_idx >= 0) {
3760                     m->sync_file_index   = sync_file_idx;
3761                     m->sync_stream_index = sync_stream_idx;
3762                 } else {
3763                     m->sync_file_index   = file_idx;
3764                     m->sync_stream_index = i;
3765                 }
3766             }
3767     }
3768
3769     if (!m) {
3770         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
3771         exit_program(1);
3772     }
3773
3774     av_freep(&map);
3775     return 0;
3776 }
3777
3778 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
3779 {
3780     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
3781                                 &o->nb_attachments, o->nb_attachments + 1);
3782     o->attachments[o->nb_attachments - 1] = arg;
3783     return 0;
3784 }
3785
3786 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
3787 {
3788     int n;
3789     AVStream *st;
3790     AudioChannelMap *m;
3791
3792     o->audio_channel_maps =
3793         grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
3794                    &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
3795     m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
3796
3797     /* muted channel syntax */
3798     n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
3799     if ((n == 1 || n == 3) && m->channel_idx == -1) {
3800         m->file_idx = m->stream_idx = -1;
3801         if (n == 1)
3802             m->ofile_idx = m->ostream_idx = -1;
3803         return 0;
3804     }
3805
3806     /* normal syntax */
3807     n = sscanf(arg, "%d.%d.%d:%d.%d",
3808                &m->file_idx,  &m->stream_idx, &m->channel_idx,
3809                &m->ofile_idx, &m->ostream_idx);
3810
3811     if (n != 3 && n != 5) {
3812         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
3813                "[file.stream.channel|-1][:syncfile:syncstream]\n");
3814         exit_program(1);
3815     }
3816
3817     if (n != 5) // only file.stream.channel specified
3818         m->ofile_idx = m->ostream_idx = -1;
3819
3820     /* check input */
3821     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
3822         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
3823                m->file_idx);
3824         exit_program(1);
3825     }
3826     if (m->stream_idx < 0 ||
3827         m->stream_idx >= input_files[m->file_idx]->nb_streams) {
3828         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
3829                m->file_idx, m->stream_idx);
3830         exit_program(1);
3831     }
3832     st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
3833     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
3834         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
3835                m->file_idx, m->stream_idx);
3836         exit_program(1);
3837     }
3838     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
3839         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
3840                m->file_idx, m->stream_idx, m->channel_idx);
3841         exit_program(1);
3842     }
3843     return 0;
3844 }
3845
3846 /**
3847  * Parse a metadata specifier in arg.
3848  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
3849  * @param index for type c/p, chapter/program index is written here
3850  * @param stream_spec for type s, the stream specifier is written here
3851  */
3852 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
3853 {
3854     if (*arg) {
3855         *type = *arg;
3856         switch (*arg) {
3857         case 'g':
3858             break;
3859         case 's':
3860             if (*(++arg) && *arg != ':') {
3861                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
3862                 exit_program(1);
3863             }
3864             *stream_spec = *arg == ':' ? arg + 1 : "";
3865             break;
3866         case 'c':
3867         case 'p':
3868             if (*(++arg) == ':')
3869                 *index = strtol(++arg, NULL, 0);
3870             break;
3871         default:
3872             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
3873             exit_program(1);
3874         }
3875     } else
3876         *type = 'g';
3877 }
3878
3879 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
3880 {
3881     AVDictionary **meta_in = NULL;
3882     AVDictionary **meta_out = NULL;
3883     int i, ret = 0;
3884     char type_in, type_out;
3885     const char *istream_spec = NULL, *ostream_spec = NULL;
3886     int idx_in = 0, idx_out = 0;
3887
3888     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
3889     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
3890
3891     if (!ic) {
3892         if (type_out == 'g' || !*outspec)
3893             o->metadata_global_manual = 1;
3894         if (type_out == 's' || !*outspec)
3895             o->metadata_streams_manual = 1;
3896         if (type_out == 'c' || !*outspec)
3897             o->metadata_chapters_manual = 1;
3898         return 0;
3899     }
3900
3901     if (type_in == 'g' || type_out == 'g')
3902         o->metadata_global_manual = 1;
3903     if (type_in == 's' || type_out == 's')
3904         o->metadata_streams_manual = 1;
3905     if (type_in == 'c' || type_out == 'c')
3906         o->metadata_chapters_manual = 1;
3907
3908 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
3909     if ((index) < 0 || (index) >= (nb_elems)) {\
3910         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
3911                 (desc), (index));\
3912         exit_program(1);\
3913     }
3914
3915 #define SET_DICT(type, meta, context, index)\
3916         switch (type) {\
3917         case 'g':\