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