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