proresenc_kostya: do not attempt to free random things
[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 ? av_inv_q(ist->framerate) :
1176                                          ist->st->time_base;
1177     AVRational fr = ist->framerate.num ? ist->framerate :
1178                                          ist->st->r_frame_rate;
1179     AVRational sar;
1180     AVBPrint args;
1181     char name[255];
1182     int pad_idx = in->pad_idx;
1183     int ret;
1184
1185     if (ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1186         ret = sub2video_prepare(ist);
1187         if (ret < 0)
1188             return ret;
1189     }
1190
1191     sar = ist->st->sample_aspect_ratio.num ?
1192           ist->st->sample_aspect_ratio :
1193           ist->st->codec->sample_aspect_ratio;
1194     if(!sar.den)
1195         sar = (AVRational){0,1};
1196     av_bprint_init(&args, 0, 1);
1197     av_bprintf(&args,
1198              "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:"
1199              "pixel_aspect=%d/%d:sws_param=flags=%d", ist->st->codec->width,
1200              ist->st->codec->height, ist->st->codec->pix_fmt,
1201              tb.num, tb.den, sar.num, sar.den,
1202              SWS_BILINEAR + ((ist->st->codec->flags&CODEC_FLAG_BITEXACT) ? SWS_BITEXACT:0));
1203     if (fr.num && fr.den)
1204         av_bprintf(&args, ":frame_rate=%d/%d", fr.num, fr.den);
1205     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
1206              ist->file_index, ist->st->index);
1207
1208     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter, name,
1209                                             args.str, NULL, fg->graph)) < 0)
1210         return ret;
1211
1212     if (ist->framerate.num) {
1213         AVFilterContext *setpts;
1214
1215         snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",
1216                  ist->file_index, ist->st->index);
1217         if ((ret = avfilter_graph_create_filter(&setpts,
1218                                                 avfilter_get_by_name("setpts"),
1219                                                 name, "N", NULL,
1220                                                 fg->graph)) < 0)
1221             return ret;
1222
1223         if ((ret = avfilter_link(setpts, 0, first_filter, pad_idx)) < 0)
1224             return ret;
1225
1226         first_filter = setpts;
1227         pad_idx = 0;
1228     }
1229
1230     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
1231         return ret;
1232     return 0;
1233 }
1234
1235 static int configure_input_audio_filter(FilterGraph *fg, InputFilter *ifilter,
1236                                         AVFilterInOut *in)
1237 {
1238     AVFilterContext *first_filter = in->filter_ctx;
1239     AVFilter *filter = avfilter_get_by_name("abuffer");
1240     InputStream *ist = ifilter->ist;
1241     int pad_idx = in->pad_idx;
1242     char args[255], name[255];
1243     int ret;
1244
1245     snprintf(args, sizeof(args), "time_base=%d/%d:sample_rate=%d:sample_fmt=%s"
1246              ":channel_layout=0x%"PRIx64,
1247              1, ist->st->codec->sample_rate,
1248              ist->st->codec->sample_rate,
1249              av_get_sample_fmt_name(ist->st->codec->sample_fmt),
1250              ist->st->codec->channel_layout);
1251     snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,
1252              ist->file_index, ist->st->index);
1253
1254     if ((ret = avfilter_graph_create_filter(&ifilter->filter, filter,
1255                                             name, args, NULL,
1256                                             fg->graph)) < 0)
1257         return ret;
1258
1259 #define AUTO_INSERT_FILTER_INPUT(opt_name, filter_name, arg) do {                 \
1260     AVFilterContext *filt_ctx;                                              \
1261                                                                             \
1262     av_log(NULL, AV_LOG_INFO, opt_name " is forwarded to lavfi "            \
1263            "similarly to -af " filter_name "=%s.\n", arg);                  \
1264                                                                             \
1265     snprintf(name, sizeof(name), "graph %d %s for input stream %d:%d",      \
1266                 fg->index, filter_name, ist->file_index, ist->st->index);   \
1267     ret = avfilter_graph_create_filter(&filt_ctx,                           \
1268                                        avfilter_get_by_name(filter_name),   \
1269                                        name, arg, NULL, fg->graph);         \
1270     if (ret < 0)                                                            \
1271         return ret;                                                         \
1272                                                                             \
1273     ret = avfilter_link(filt_ctx, 0, first_filter, pad_idx);                \
1274     if (ret < 0)                                                            \
1275         return ret;                                                         \
1276                                                                             \
1277     first_filter = filt_ctx;                                                  \
1278 } while (0)
1279
1280     if (audio_sync_method > 0) {
1281         char args[256] = {0};
1282
1283         av_strlcatf(args, sizeof(args), "min_comp=0.001:min_hard_comp=%f", audio_drift_threshold);
1284         if (audio_sync_method > 1)
1285             av_strlcatf(args, sizeof(args), ":max_soft_comp=%f", audio_sync_method/(double)ist->st->codec->sample_rate);
1286         AUTO_INSERT_FILTER_INPUT("-async", "aresample", args);
1287     }
1288
1289 //     if (ost->audio_channels_mapped) {
1290 //         int i;
1291 //         AVBPrint pan_buf;
1292 //         av_bprint_init(&pan_buf, 256, 8192);
1293 //         av_bprintf(&pan_buf, "0x%"PRIx64,
1294 //                    av_get_default_channel_layout(ost->audio_channels_mapped));
1295 //         for (i = 0; i < ost->audio_channels_mapped; i++)
1296 //             if (ost->audio_channels_map[i] != -1)
1297 //                 av_bprintf(&pan_buf, ":c%d=c%d", i, ost->audio_channels_map[i]);
1298 //         AUTO_INSERT_FILTER_INPUT("-map_channel", "pan", pan_buf.str);
1299 //         av_bprint_finalize(&pan_buf, NULL);
1300 //     }
1301
1302     if (audio_volume != 256) {
1303         char args[256];
1304
1305         snprintf(args, sizeof(args), "%f", audio_volume / 256.);
1306         AUTO_INSERT_FILTER_INPUT("-vol", "volume", args);
1307     }
1308     if ((ret = avfilter_link(ifilter->filter, 0, first_filter, pad_idx)) < 0)
1309         return ret;
1310
1311     return 0;
1312 }
1313
1314 static int configure_input_filter(FilterGraph *fg, InputFilter *ifilter,
1315                                   AVFilterInOut *in)
1316 {
1317     av_freep(&ifilter->name);
1318     DESCRIBE_FILTER_LINK(ifilter, in, 1);
1319
1320     switch (avfilter_pad_get_type(in->filter_ctx->input_pads, in->pad_idx)) {
1321     case AVMEDIA_TYPE_VIDEO: return configure_input_video_filter(fg, ifilter, in);
1322     case AVMEDIA_TYPE_AUDIO: return configure_input_audio_filter(fg, ifilter, in);
1323     default: av_assert0(0);
1324     }
1325 }
1326
1327 static int configure_filtergraph(FilterGraph *fg)
1328 {
1329     AVFilterInOut *inputs, *outputs, *cur;
1330     int ret, i, init = !fg->graph, simple = !fg->graph_desc;
1331     const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :
1332                                       fg->graph_desc;
1333
1334     avfilter_graph_free(&fg->graph);
1335     if (!(fg->graph = avfilter_graph_alloc()))
1336         return AVERROR(ENOMEM);
1337
1338     if (simple) {
1339         OutputStream *ost = fg->outputs[0]->ost;
1340         char args[255];
1341         snprintf(args, sizeof(args), "flags=0x%X", (unsigned)ost->sws_flags);
1342         fg->graph->scale_sws_opts = av_strdup(args);
1343     }
1344
1345     if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)
1346         return ret;
1347
1348     if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {
1349         av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' does not have "
1350                "exactly one input and output.\n", graph_desc);
1351         return AVERROR(EINVAL);
1352     }
1353
1354     for (cur = inputs; !simple && init && cur; cur = cur->next)
1355         init_input_filter(fg, cur);
1356
1357     for (cur = inputs, i = 0; cur; cur = cur->next, i++)
1358         if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0)
1359             return ret;
1360     avfilter_inout_free(&inputs);
1361
1362     if (!init || simple) {
1363         /* we already know the mappings between lavfi outputs and output streams,
1364          * so we can finish the setup */
1365         for (cur = outputs, i = 0; cur; cur = cur->next, i++)
1366             configure_output_filter(fg, fg->outputs[i], cur);
1367         avfilter_inout_free(&outputs);
1368
1369         if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)
1370             return ret;
1371     } else {
1372         /* wait until output mappings are processed */
1373         for (cur = outputs; cur;) {
1374             fg->outputs = grow_array(fg->outputs, sizeof(*fg->outputs),
1375                                      &fg->nb_outputs, fg->nb_outputs + 1);
1376             if (!(fg->outputs[fg->nb_outputs - 1] = av_mallocz(sizeof(*fg->outputs[0]))))
1377                 exit_program(1);
1378             fg->outputs[fg->nb_outputs - 1]->graph   = fg;
1379             fg->outputs[fg->nb_outputs - 1]->out_tmp = cur;
1380             cur = cur->next;
1381             fg->outputs[fg->nb_outputs - 1]->out_tmp->next = NULL;
1382         }
1383     }
1384
1385     return 0;
1386 }
1387
1388 static int configure_complex_filters(void)
1389 {
1390     int i, ret = 0;
1391
1392     for (i = 0; i < nb_filtergraphs; i++)
1393         if (!filtergraphs[i]->graph &&
1394             (ret = configure_filtergraph(filtergraphs[i])) < 0)
1395             return ret;
1396     return 0;
1397 }
1398
1399 static int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
1400 {
1401     int i;
1402     for (i = 0; i < fg->nb_inputs; i++)
1403         if (fg->inputs[i]->ist == ist)
1404             return 1;
1405     return 0;
1406 }
1407
1408 static void term_exit(void)
1409 {
1410     av_log(NULL, AV_LOG_QUIET, "%s", "");
1411 #if HAVE_TERMIOS_H
1412     if(restore_tty)
1413         tcsetattr (0, TCSANOW, &oldtty);
1414 #endif
1415 }
1416
1417 static volatile int received_sigterm = 0;
1418
1419 static void sigterm_handler(int sig)
1420 {
1421     received_sigterm = sig;
1422     received_nb_signals++;
1423     term_exit();
1424     if(received_nb_signals > 3)
1425         exit(123);
1426 }
1427
1428 static void term_init(void)
1429 {
1430 #if HAVE_TERMIOS_H
1431     if(!run_as_daemon){
1432         struct termios tty;
1433         int istty = 1;
1434 #if HAVE_ISATTY
1435         istty = isatty(0) && isatty(2);
1436 #endif
1437         if (istty && tcgetattr (0, &tty) == 0) {
1438             oldtty = tty;
1439             restore_tty = 1;
1440             atexit(term_exit);
1441
1442             tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1443                              |INLCR|IGNCR|ICRNL|IXON);
1444             tty.c_oflag |= OPOST;
1445             tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1446             tty.c_cflag &= ~(CSIZE|PARENB);
1447             tty.c_cflag |= CS8;
1448             tty.c_cc[VMIN] = 1;
1449             tty.c_cc[VTIME] = 0;
1450
1451             tcsetattr (0, TCSANOW, &tty);
1452         }
1453         signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
1454     }
1455 #endif
1456     avformat_network_deinit();
1457
1458     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
1459     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
1460 #ifdef SIGXCPU
1461     signal(SIGXCPU, sigterm_handler);
1462 #endif
1463 }
1464
1465 /* read a key without blocking */
1466 static int read_key(void)
1467 {
1468     unsigned char ch;
1469 #if HAVE_TERMIOS_H
1470     int n = 1;
1471     struct timeval tv;
1472     fd_set rfds;
1473
1474     FD_ZERO(&rfds);
1475     FD_SET(0, &rfds);
1476     tv.tv_sec = 0;
1477     tv.tv_usec = 0;
1478     n = select(1, &rfds, NULL, NULL, &tv);
1479     if (n > 0) {
1480         n = read(0, &ch, 1);
1481         if (n == 1)
1482             return ch;
1483
1484         return n;
1485     }
1486 #elif HAVE_KBHIT
1487 #    if HAVE_PEEKNAMEDPIPE
1488     static int is_pipe;
1489     static HANDLE input_handle;
1490     DWORD dw, nchars;
1491     if(!input_handle){
1492         input_handle = GetStdHandle(STD_INPUT_HANDLE);
1493         is_pipe = !GetConsoleMode(input_handle, &dw);
1494     }
1495
1496     if (stdin->_cnt > 0) {
1497         read(0, &ch, 1);
1498         return ch;
1499     }
1500     if (is_pipe) {
1501         /* When running under a GUI, you will end here. */
1502         if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
1503             return -1;
1504         //Read it
1505         if(nchars != 0) {
1506             read(0, &ch, 1);
1507             return ch;
1508         }else{
1509             return -1;
1510         }
1511     }
1512 #    endif
1513     if(kbhit())
1514         return(getch());
1515 #endif
1516     return -1;
1517 }
1518
1519 static int decode_interrupt_cb(void *ctx)
1520 {
1521     return received_nb_signals > 1;
1522 }
1523
1524 static const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
1525
1526 void av_noreturn exit_program(int ret)
1527 {
1528     int i, j;
1529
1530     for (i = 0; i < nb_filtergraphs; i++) {
1531         avfilter_graph_free(&filtergraphs[i]->graph);
1532         for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
1533             av_freep(&filtergraphs[i]->inputs[j]->name);
1534             av_freep(&filtergraphs[i]->inputs[j]);
1535         }
1536         av_freep(&filtergraphs[i]->inputs);
1537         for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
1538             av_freep(&filtergraphs[i]->outputs[j]->name);
1539             av_freep(&filtergraphs[i]->outputs[j]);
1540         }
1541         av_freep(&filtergraphs[i]->outputs);
1542         av_freep(&filtergraphs[i]);
1543     }
1544     av_freep(&filtergraphs);
1545
1546     av_freep(&subtitle_out);
1547
1548     /* close files */
1549     for (i = 0; i < nb_output_files; i++) {
1550         AVFormatContext *s = output_files[i]->ctx;
1551         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
1552             avio_close(s->pb);
1553         avformat_free_context(s);
1554         av_dict_free(&output_files[i]->opts);
1555         av_freep(&output_files[i]);
1556     }
1557     for (i = 0; i < nb_output_streams; i++) {
1558         AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
1559         while (bsfc) {
1560             AVBitStreamFilterContext *next = bsfc->next;
1561             av_bitstream_filter_close(bsfc);
1562             bsfc = next;
1563         }
1564         output_streams[i]->bitstream_filters = NULL;
1565
1566         av_freep(&output_streams[i]->forced_keyframes);
1567         av_freep(&output_streams[i]->filtered_frame);
1568         av_freep(&output_streams[i]->avfilter);
1569         av_freep(&output_streams[i]);
1570     }
1571     for (i = 0; i < nb_input_files; i++) {
1572         avformat_close_input(&input_files[i]->ctx);
1573         av_freep(&input_files[i]);
1574     }
1575     for (i = 0; i < nb_input_streams; i++) {
1576         av_freep(&input_streams[i]->decoded_frame);
1577         av_dict_free(&input_streams[i]->opts);
1578         free_buffer_pool(&input_streams[i]->buffer_pool);
1579         avfilter_unref_bufferp(&input_streams[i]->sub2video.ref);
1580         av_freep(&input_streams[i]->filters);
1581         av_freep(&input_streams[i]);
1582     }
1583
1584     if (vstats_file)
1585         fclose(vstats_file);
1586     av_free(vstats_filename);
1587
1588     av_freep(&input_streams);
1589     av_freep(&input_files);
1590     av_freep(&output_streams);
1591     av_freep(&output_files);
1592
1593     uninit_opts();
1594
1595     avfilter_uninit();
1596     avformat_network_deinit();
1597
1598     if (received_sigterm) {
1599         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
1600                (int) received_sigterm);
1601         exit (255);
1602     }
1603
1604     exit(ret);
1605 }
1606
1607 static void assert_avoptions(AVDictionary *m)
1608 {
1609     AVDictionaryEntry *t;
1610     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
1611         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
1612         exit_program(1);
1613     }
1614 }
1615
1616 static void assert_codec_experimental(AVCodecContext *c, int encoder)
1617 {
1618     const char *codec_string = encoder ? "encoder" : "decoder";
1619     AVCodec *codec;
1620     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
1621         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
1622         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
1623                 "results.\nAdd '-strict experimental' if you want to use it.\n",
1624                 codec_string, c->codec->name);
1625         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
1626         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
1627             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
1628                    codec_string, codec->name);
1629         exit_program(1);
1630     }
1631 }
1632
1633 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
1634 {
1635     if (codec && codec->sample_fmts) {
1636         const enum AVSampleFormat *p = codec->sample_fmts;
1637         for (; *p != -1; p++) {
1638             if (*p == st->codec->sample_fmt)
1639                 break;
1640         }
1641         if (*p == -1) {
1642             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
1643                 av_log(NULL, AV_LOG_ERROR, "Conversion will not be lossless.\n");
1644             if(av_get_sample_fmt_name(st->codec->sample_fmt))
1645             av_log(NULL, AV_LOG_WARNING,
1646                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
1647                    av_get_sample_fmt_name(st->codec->sample_fmt),
1648                    codec->name,
1649                    av_get_sample_fmt_name(codec->sample_fmts[0]));
1650             st->codec->sample_fmt = codec->sample_fmts[0];
1651         }
1652     }
1653 }
1654
1655 static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
1656 {
1657     AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
1658     AVCodecContext          *avctx = ost->st->codec;
1659     int ret;
1660
1661     if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
1662         (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
1663         pkt->pts = pkt->dts = AV_NOPTS_VALUE;
1664
1665     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1666         int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
1667         if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE &&  max > pkt->dts) {
1668             av_log(s, max - pkt->dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt->dts, max);
1669             pkt->pts = pkt->dts = max;
1670         }
1671     }
1672
1673     /*
1674      * Audio encoders may split the packets --  #frames in != #packets out.
1675      * But there is no reordering, so we can limit the number of output packets
1676      * by simply dropping them here.
1677      * Counting encoded video frames needs to be done separately because of
1678      * reordering, see do_video_out()
1679      */
1680     if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
1681         if (ost->frame_number >= ost->max_frames) {
1682             av_free_packet(pkt);
1683             return;
1684         }
1685         ost->frame_number++;
1686     }
1687
1688     while (bsfc) {
1689         AVPacket new_pkt = *pkt;
1690         int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
1691                                            &new_pkt.data, &new_pkt.size,
1692                                            pkt->data, pkt->size,
1693                                            pkt->flags & AV_PKT_FLAG_KEY);
1694         if (a > 0) {
1695             av_free_packet(pkt);
1696             new_pkt.destruct = av_destruct_packet;
1697         } else if (a < 0) {
1698             av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
1699                    bsfc->filter->name, pkt->stream_index,
1700                    avctx->codec ? avctx->codec->name : "copy");
1701             print_error("", a);
1702             if (exit_on_error)
1703                 exit_program(1);
1704         }
1705         *pkt = new_pkt;
1706
1707         bsfc = bsfc->next;
1708     }
1709
1710     pkt->stream_index = ost->index;
1711     ret = av_interleaved_write_frame(s, pkt);
1712     if (ret < 0) {
1713         print_error("av_interleaved_write_frame()", ret);
1714         exit_program(1);
1715     }
1716 }
1717
1718 static int check_recording_time(OutputStream *ost)
1719 {
1720     OutputFile *of = output_files[ost->file_index];
1721
1722     if (of->recording_time != INT64_MAX &&
1723         av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
1724                       AV_TIME_BASE_Q) >= 0) {
1725         ost->is_past_recording_time = 1;
1726         return 0;
1727     }
1728     return 1;
1729 }
1730
1731 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
1732                          AVFrame *frame)
1733 {
1734     AVCodecContext *enc = ost->st->codec;
1735     AVPacket pkt;
1736     int got_packet = 0;
1737
1738     av_init_packet(&pkt);
1739     pkt.data = NULL;
1740     pkt.size = 0;
1741
1742     if (!check_recording_time(ost))
1743         return;
1744
1745     if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
1746         frame->pts = ost->sync_opts;
1747     ost->sync_opts = frame->pts + frame->nb_samples;
1748
1749     av_assert0(pkt.size || !pkt.data);
1750     update_benchmark(NULL);
1751     if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
1752         av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
1753         exit_program(1);
1754     }
1755     update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1756
1757     if (got_packet) {
1758         if (pkt.pts != AV_NOPTS_VALUE)
1759             pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
1760         if (pkt.dts != AV_NOPTS_VALUE)
1761             pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
1762         if (pkt.duration > 0)
1763             pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1764
1765         if (debug_ts) {
1766             av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1767                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1768                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
1769                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
1770         }
1771
1772         write_frame(s, &pkt, ost);
1773
1774         audio_size += pkt.size;
1775         av_free_packet(&pkt);
1776     }
1777 }
1778
1779 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1780 {
1781     AVCodecContext *dec;
1782     AVPicture *picture2;
1783     AVPicture picture_tmp;
1784     uint8_t *buf = 0;
1785
1786     dec = ist->st->codec;
1787
1788     /* deinterlace : must be done before any resize */
1789     if (do_deinterlace) {
1790         int size;
1791
1792         /* create temporary picture */
1793         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1794         buf  = av_malloc(size);
1795         if (!buf)
1796             return;
1797
1798         picture2 = &picture_tmp;
1799         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1800
1801         if (avpicture_deinterlace(picture2, picture,
1802                                  dec->pix_fmt, dec->width, dec->height) < 0) {
1803             /* if error, do not deinterlace */
1804             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1805             av_free(buf);
1806             buf = NULL;
1807             picture2 = picture;
1808         }
1809     } else {
1810         picture2 = picture;
1811     }
1812
1813     if (picture != picture2)
1814         *picture = *picture2;
1815     *bufp = buf;
1816 }
1817
1818 static void do_subtitle_out(AVFormatContext *s,
1819                             OutputStream *ost,
1820                             InputStream *ist,
1821                             AVSubtitle *sub,
1822                             int64_t pts)
1823 {
1824     int subtitle_out_max_size = 1024 * 1024;
1825     int subtitle_out_size, nb, i;
1826     AVCodecContext *enc;
1827     AVPacket pkt;
1828
1829     if (pts == AV_NOPTS_VALUE) {
1830         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1831         if (exit_on_error)
1832             exit_program(1);
1833         return;
1834     }
1835
1836     enc = ost->st->codec;
1837
1838     if (!subtitle_out) {
1839         subtitle_out = av_malloc(subtitle_out_max_size);
1840     }
1841
1842     /* Note: DVB subtitle need one packet to draw them and one other
1843        packet to clear them */
1844     /* XXX: signal it in the codec context ? */
1845     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1846         nb = 2;
1847     else
1848         nb = 1;
1849
1850     /* shift timestamp to honor -ss and make check_recording_time() work with -t */
1851     pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q)
1852         - output_files[ost->file_index]->start_time;
1853     for (i = 0; i < nb; i++) {
1854         ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
1855         if (!check_recording_time(ost))
1856             return;
1857
1858         sub->pts = pts;
1859         // start_display_time is required to be 0
1860         sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1861         sub->end_display_time  -= sub->start_display_time;
1862         sub->start_display_time = 0;
1863         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1864                                                     subtitle_out_max_size, sub);
1865         if (subtitle_out_size < 0) {
1866             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1867             exit_program(1);
1868         }
1869
1870         av_init_packet(&pkt);
1871         pkt.data = subtitle_out;
1872         pkt.size = subtitle_out_size;
1873         pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1874         pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
1875         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1876             /* XXX: the pts correction is handled here. Maybe handling
1877                it in the codec would be better */
1878             if (i == 0)
1879                 pkt.pts += 90 * sub->start_display_time;
1880             else
1881                 pkt.pts += 90 * sub->end_display_time;
1882         }
1883         write_frame(s, &pkt, ost);
1884         subtitle_size += pkt.size;
1885     }
1886 }
1887
1888 static void do_video_out(AVFormatContext *s,
1889                          OutputStream *ost,
1890                          AVFrame *in_picture,
1891                          float quality)
1892 {
1893     int ret, format_video_sync;
1894     AVPacket pkt;
1895     AVCodecContext *enc = ost->st->codec;
1896     int nb_frames, i;
1897     double sync_ipts, delta;
1898     double duration = 0;
1899     int frame_size = 0;
1900     InputStream *ist = NULL;
1901
1902     if (ost->source_index >= 0)
1903         ist = input_streams[ost->source_index];
1904
1905     if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
1906         duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
1907
1908     sync_ipts = in_picture->pts;
1909     delta = sync_ipts - ost->sync_opts + duration;
1910
1911     /* by default, we output a single frame */
1912     nb_frames = 1;
1913
1914     format_video_sync = video_sync_method;
1915     if (format_video_sync == VSYNC_AUTO)
1916         format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
1917
1918     switch (format_video_sync) {
1919     case VSYNC_CFR:
1920         // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1921         if (delta < -1.1)
1922             nb_frames = 0;
1923         else if (delta > 1.1)
1924             nb_frames = lrintf(delta);
1925         break;
1926     case VSYNC_VFR:
1927         if (delta <= -0.6)
1928             nb_frames = 0;
1929         else if (delta > 0.6)
1930             ost->sync_opts = lrint(sync_ipts);
1931         break;
1932     case VSYNC_DROP:
1933     case VSYNC_PASSTHROUGH:
1934         ost->sync_opts = lrint(sync_ipts);
1935         break;
1936     default:
1937         av_assert0(0);
1938     }
1939
1940     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1941     if (nb_frames == 0) {
1942         nb_frames_drop++;
1943         av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1944         return;
1945     } else if (nb_frames > 1) {
1946         if (nb_frames > dts_error_threshold * 30) {
1947             av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skiping\n", nb_frames - 1);
1948             nb_frames_drop++;
1949             return;
1950         }
1951         nb_frames_dup += nb_frames - 1;
1952         av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1953     }
1954
1955   /* duplicates frame if needed */
1956   for (i = 0; i < nb_frames; i++) {
1957     av_init_packet(&pkt);
1958     pkt.data = NULL;
1959     pkt.size = 0;
1960
1961     in_picture->pts = ost->sync_opts;
1962
1963     if (!check_recording_time(ost))
1964         return;
1965
1966     if (s->oformat->flags & AVFMT_RAWPICTURE &&
1967         enc->codec->id == CODEC_ID_RAWVIDEO) {
1968         /* raw pictures are written as AVPicture structure to
1969            avoid any copies. We support temporarily the older
1970            method. */
1971         enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1972         enc->coded_frame->top_field_first  = in_picture->top_field_first;
1973         pkt.data   = (uint8_t *)in_picture;
1974         pkt.size   =  sizeof(AVPicture);
1975         pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
1976         pkt.flags |= AV_PKT_FLAG_KEY;
1977
1978         write_frame(s, &pkt, ost);
1979         video_size += pkt.size;
1980     } else {
1981         int got_packet;
1982         AVFrame big_picture;
1983
1984         big_picture = *in_picture;
1985         /* better than nothing: use input picture interlaced
1986            settings */
1987         big_picture.interlaced_frame = in_picture->interlaced_frame;
1988         if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1989             if (ost->top_field_first == -1)
1990                 big_picture.top_field_first = in_picture->top_field_first;
1991             else
1992                 big_picture.top_field_first = !!ost->top_field_first;
1993         }
1994
1995         /* handles same_quant here. This is not correct because it may
1996            not be a global option */
1997         big_picture.quality = quality;
1998         if (!enc->me_threshold)
1999             big_picture.pict_type = 0;
2000         if (ost->forced_kf_index < ost->forced_kf_count &&
2001             big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
2002             big_picture.pict_type = AV_PICTURE_TYPE_I;
2003             ost->forced_kf_index++;
2004         }
2005         update_benchmark(NULL);
2006         ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
2007         update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
2008         if (ret < 0) {
2009             av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
2010             exit_program(1);
2011         }
2012
2013         if (got_packet) {
2014             if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
2015                 pkt.pts = ost->sync_opts;
2016
2017             if (pkt.pts != AV_NOPTS_VALUE)
2018                 pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2019             if (pkt.dts != AV_NOPTS_VALUE)
2020                 pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2021
2022             if (debug_ts) {
2023                 av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
2024                     "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
2025                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
2026                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
2027             }
2028
2029             write_frame(s, &pkt, ost);
2030             frame_size = pkt.size;
2031             video_size += pkt.size;
2032             av_free_packet(&pkt);
2033
2034             /* if two pass, output log */
2035             if (ost->logfile && enc->stats_out) {
2036                 fprintf(ost->logfile, "%s", enc->stats_out);
2037             }
2038         }
2039     }
2040     ost->sync_opts++;
2041     /*
2042      * For video, number of frames in == number of packets out.
2043      * But there may be reordering, so we can't throw away frames on encoder
2044      * flush, we need to limit them here, before they go into encoder.
2045      */
2046     ost->frame_number++;
2047   }
2048
2049     if (vstats_filename && frame_size)
2050         do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
2051 }
2052
2053 static double psnr(double d)
2054 {
2055     return -10.0 * log(d) / log(10.0);
2056 }
2057
2058 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
2059                            int frame_size)
2060 {
2061     AVCodecContext *enc;
2062     int frame_number;
2063     double ti1, bitrate, avg_bitrate;
2064
2065     /* this is executed just the first time do_video_stats is called */
2066     if (!vstats_file) {
2067         vstats_file = fopen(vstats_filename, "w");
2068         if (!vstats_file) {
2069             perror("fopen");
2070             exit_program(1);
2071         }
2072     }
2073
2074     enc = ost->st->codec;
2075     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2076         frame_number = ost->frame_number;
2077         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
2078         if (enc->flags&CODEC_FLAG_PSNR)
2079             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
2080
2081         fprintf(vstats_file,"f_size= %6d ", frame_size);
2082         /* compute pts value */
2083         ti1 = ost->sync_opts * av_q2d(enc->time_base);
2084         if (ti1 < 0.01)
2085             ti1 = 0.01;
2086
2087         bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
2088         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
2089         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
2090                (double)video_size / 1024, ti1, bitrate, avg_bitrate);
2091         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
2092     }
2093 }
2094
2095 /* check for new output on any of the filtergraphs */
2096 static int poll_filters(void)
2097 {
2098     AVFilterBufferRef *picref;
2099     AVFrame *filtered_frame = NULL;
2100     int i, ret, ret_all;
2101     unsigned nb_success = 1, av_uninit(nb_eof);
2102     int64_t frame_pts;
2103
2104     while (1) {
2105         /* Reap all buffers present in the buffer sinks */
2106         for (i = 0; i < nb_output_streams; i++) {
2107             OutputStream *ost = output_streams[i];
2108             OutputFile    *of = output_files[ost->file_index];
2109             int ret = 0;
2110
2111             if (!ost->filter)
2112                 continue;
2113
2114             if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
2115                 return AVERROR(ENOMEM);
2116             } else
2117                 avcodec_get_frame_defaults(ost->filtered_frame);
2118             filtered_frame = ost->filtered_frame;
2119
2120             while (1) {
2121                 ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
2122                                                    AV_BUFFERSINK_FLAG_NO_REQUEST);
2123                 if (ret < 0) {
2124                     if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
2125                         char buf[256];
2126                         av_strerror(ret, buf, sizeof(buf));
2127                         av_log(NULL, AV_LOG_WARNING,
2128                                "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
2129                     }
2130                     break;
2131                 }
2132                 frame_pts = AV_NOPTS_VALUE;
2133                 if (picref->pts != AV_NOPTS_VALUE) {
2134                     filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
2135                                                     ost->filter->filter->inputs[0]->time_base,
2136                                                     ost->st->codec->time_base) -
2137                                         av_rescale_q(of->start_time,
2138                                                     AV_TIME_BASE_Q,
2139                                                     ost->st->codec->time_base);
2140
2141                     if (of->start_time && filtered_frame->pts < 0) {
2142                         avfilter_unref_buffer(picref);
2143                         continue;
2144                     }
2145                 }
2146                 //if (ost->source_index >= 0)
2147                 //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
2148
2149
2150                 switch (ost->filter->filter->inputs[0]->type) {
2151                 case AVMEDIA_TYPE_VIDEO:
2152                     avfilter_copy_buf_props(filtered_frame, picref);
2153                     filtered_frame->pts = frame_pts;
2154                     if (!ost->frame_aspect_ratio)
2155                         ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
2156
2157                     do_video_out(of->ctx, ost, filtered_frame,
2158                                  same_quant ? ost->last_quality :
2159                                               ost->st->codec->global_quality);
2160                     break;
2161                 case AVMEDIA_TYPE_AUDIO:
2162                     avfilter_copy_buf_props(filtered_frame, picref);
2163                     filtered_frame->pts = frame_pts;
2164                     do_audio_out(of->ctx, ost, filtered_frame);
2165                     break;
2166                 default:
2167                     // TODO support subtitle filters
2168                     av_assert0(0);
2169                 }
2170
2171                 avfilter_unref_buffer(picref);
2172             }
2173         }
2174         if (!nb_success) /* from last round */
2175             break;
2176         /* Request frames through all the graphs */
2177         ret_all = nb_success = nb_eof = 0;
2178         for (i = 0; i < nb_filtergraphs; i++) {
2179             ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
2180             if (!ret) {
2181                 nb_success++;
2182             } else if (ret == AVERROR_EOF) {
2183                 nb_eof++;
2184             } else if (ret != AVERROR(EAGAIN)) {
2185                 char buf[256];
2186                 av_strerror(ret, buf, sizeof(buf));
2187                 av_log(NULL, AV_LOG_WARNING,
2188                        "Error in request_frame(): %s\n", buf);
2189                 ret_all = ret;
2190             }
2191         }
2192         /* Try again if anything succeeded */
2193     }
2194     return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
2195 }
2196
2197 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
2198 {
2199     char buf[1024];
2200     AVBPrint buf_script;
2201     OutputStream *ost;
2202     AVFormatContext *oc;
2203     int64_t total_size;
2204     AVCodecContext *enc;
2205     int frame_number, vid, i;
2206     double bitrate;
2207     int64_t pts = INT64_MAX;
2208     static int64_t last_time = -1;
2209     static int qp_histogram[52];
2210     int hours, mins, secs, us;
2211
2212     if (!print_stats && !is_last_report && !progress_avio)
2213         return;
2214
2215     if (!is_last_report) {
2216         if (last_time == -1) {
2217             last_time = cur_time;
2218             return;
2219         }
2220         if ((cur_time - last_time) < 500000)
2221             return;
2222         last_time = cur_time;
2223     }
2224
2225
2226     oc = output_files[0]->ctx;
2227
2228     total_size = avio_size(oc->pb);
2229     if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
2230         total_size = avio_tell(oc->pb);
2231         if (total_size < 0)
2232             total_size = 0;
2233     }
2234
2235     buf[0] = '\0';
2236     vid = 0;
2237     av_bprint_init(&buf_script, 0, 1);
2238     for (i = 0; i < nb_output_streams; i++) {
2239         float q = -1;
2240         ost = output_streams[i];
2241         enc = ost->st->codec;
2242         if (!ost->stream_copy && enc->coded_frame)
2243             q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
2244         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2245             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
2246             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
2247                        ost->file_index, ost->index, q);
2248         }
2249         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
2250             float fps, t = (cur_time-timer_start) / 1000000.0;
2251
2252             frame_number = ost->frame_number;
2253             fps = t > 1 ? frame_number / t : 0;
2254             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
2255                      frame_number, fps < 9.95, fps, q);
2256             av_bprintf(&buf_script, "frame=%d\n", frame_number);
2257             av_bprintf(&buf_script, "fps=%.1f\n", fps);
2258             av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
2259                        ost->file_index, ost->index, q);
2260             if (is_last_report)
2261                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
2262             if (qp_hist) {
2263                 int j;
2264                 int qp = lrintf(q);
2265                 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
2266                     qp_histogram[qp]++;
2267                 for (j = 0; j < 32; j++)
2268                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
2269             }
2270             if (enc->flags&CODEC_FLAG_PSNR) {
2271                 int j;
2272                 double error, error_sum = 0;
2273                 double scale, scale_sum = 0;
2274                 double p;
2275                 char type[3] = { 'Y','U','V' };
2276                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
2277                 for (j = 0; j < 3; j++) {
2278                     if (is_last_report) {
2279                         error = enc->error[j];
2280                         scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
2281                     } else {
2282                         error = enc->coded_frame->error[j];
2283                         scale = enc->width * enc->height * 255.0 * 255.0;
2284                     }
2285                     if (j)
2286                         scale /= 4;
2287                     error_sum += error;
2288                     scale_sum += scale;
2289                     p = psnr(error / scale);
2290                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
2291                     av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
2292                                ost->file_index, ost->index, type[i] | 32, p);
2293                 }
2294                 p = psnr(error_sum / scale_sum);
2295                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
2296                 av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
2297                            ost->file_index, ost->index, p);
2298             }
2299             vid = 1;
2300         }
2301         /* compute min output value */
2302         pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
2303                                       ost->st->time_base, AV_TIME_BASE_Q));
2304     }
2305
2306     secs = pts / AV_TIME_BASE;
2307     us = pts % AV_TIME_BASE;
2308     mins = secs / 60;
2309     secs %= 60;
2310     hours = mins / 60;
2311     mins %= 60;
2312
2313     bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
2314
2315     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2316              "size=%8.0fkB time=", total_size / 1024.0);
2317     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2318              "%02d:%02d:%02d.%02d ", hours, mins, secs,
2319              (100 * us) / AV_TIME_BASE);
2320     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2321              "bitrate=%6.1fkbits/s", bitrate);
2322     av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
2323     av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
2324     av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
2325                hours, mins, secs, us);
2326
2327     if (nb_frames_dup || nb_frames_drop)
2328         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
2329                 nb_frames_dup, nb_frames_drop);
2330     av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
2331     av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
2332
2333     if (print_stats || is_last_report) {
2334     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
2335
2336     fflush(stderr);
2337     }
2338
2339     if (progress_avio) {
2340         av_bprintf(&buf_script, "progress=%s\n",
2341                    is_last_report ? "end" : "continue");
2342         avio_write(progress_avio, buf_script.str,
2343                    FFMIN(buf_script.len, buf_script.size - 1));
2344         avio_flush(progress_avio);
2345         av_bprint_finalize(&buf_script, NULL);
2346         if (is_last_report) {
2347             avio_close(progress_avio);
2348             progress_avio = NULL;
2349         }
2350     }
2351
2352     if (is_last_report) {
2353         int64_t raw= audio_size + video_size + subtitle_size + extra_size;
2354         av_log(NULL, AV_LOG_INFO, "\n");
2355         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
2356                video_size / 1024.0,
2357                audio_size / 1024.0,
2358                subtitle_size / 1024.0,
2359                extra_size / 1024.0,
2360                100.0 * (total_size - raw) / raw
2361         );
2362         if(video_size + audio_size + subtitle_size + extra_size == 0){
2363             av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
2364         }
2365     }
2366 }
2367
2368 static void flush_encoders(void)
2369 {
2370     int i, ret;
2371
2372     for (i = 0; i < nb_output_streams; i++) {
2373         OutputStream   *ost = output_streams[i];
2374         AVCodecContext *enc = ost->st->codec;
2375         AVFormatContext *os = output_files[ost->file_index]->ctx;
2376         int stop_encoding = 0;
2377
2378         if (!ost->encoding_needed)
2379             continue;
2380
2381         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2382             continue;
2383         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
2384             continue;
2385
2386         for (;;) {
2387             int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
2388             const char *desc;
2389             int64_t *size;
2390
2391             switch (ost->st->codec->codec_type) {
2392             case AVMEDIA_TYPE_AUDIO:
2393                 encode = avcodec_encode_audio2;
2394                 desc   = "Audio";
2395                 size   = &audio_size;
2396                 break;
2397             case AVMEDIA_TYPE_VIDEO:
2398                 encode = avcodec_encode_video2;
2399                 desc   = "Video";
2400                 size   = &video_size;
2401                 break;
2402             default:
2403                 stop_encoding = 1;
2404             }
2405
2406             if (encode) {
2407                 AVPacket pkt;
2408                 int got_packet;
2409                 av_init_packet(&pkt);
2410                 pkt.data = NULL;
2411                 pkt.size = 0;
2412
2413                 update_benchmark(NULL);
2414                 ret = encode(enc, &pkt, NULL, &got_packet);
2415                 update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
2416                 if (ret < 0) {
2417                     av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
2418                     exit_program(1);
2419                 }
2420                 *size += pkt.size;
2421                 if (ost->logfile && enc->stats_out) {
2422                     fprintf(ost->logfile, "%s", enc->stats_out);
2423                 }
2424                 if (!got_packet) {
2425                     stop_encoding = 1;
2426                     break;
2427                 }
2428                 if (pkt.pts != AV_NOPTS_VALUE)
2429                     pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
2430                 if (pkt.dts != AV_NOPTS_VALUE)
2431                     pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
2432                 write_frame(os, &pkt, ost);
2433             }
2434
2435             if (stop_encoding)
2436                 break;
2437         }
2438     }
2439 }
2440
2441 /*
2442  * Check whether a packet from ist should be written into ost at this time
2443  */
2444 static int check_output_constraints(InputStream *ist, OutputStream *ost)
2445 {
2446     OutputFile *of = output_files[ost->file_index];
2447     int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
2448
2449     if (ost->source_index != ist_index)
2450         return 0;
2451
2452     if (of->start_time && ist->pts < of->start_time)
2453         return 0;
2454
2455     return 1;
2456 }
2457
2458 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2459 {
2460     OutputFile *of = output_files[ost->file_index];
2461     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
2462     AVPicture pict;
2463     AVPacket opkt;
2464
2465     av_init_packet(&opkt);
2466
2467     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2468         !ost->copy_initial_nonkeyframes)
2469         return;
2470
2471     if (of->recording_time != INT64_MAX &&
2472         ist->pts >= of->recording_time + of->start_time) {
2473         ost->is_past_recording_time = 1;
2474         return;
2475     }
2476
2477     /* force the input stream PTS */
2478     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
2479         audio_size += pkt->size;
2480     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2481         video_size += pkt->size;
2482         ost->sync_opts++;
2483     } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
2484         subtitle_size += pkt->size;
2485     }
2486
2487     if (pkt->pts != AV_NOPTS_VALUE)
2488         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
2489     else
2490         opkt.pts = AV_NOPTS_VALUE;
2491
2492     if (pkt->dts == AV_NOPTS_VALUE)
2493         opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
2494     else
2495         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
2496     opkt.dts -= ost_tb_start_time;
2497
2498     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
2499     opkt.flags    = pkt->flags;
2500
2501     // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
2502     if (  ost->st->codec->codec_id != CODEC_ID_H264
2503        && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
2504        && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
2505        && ost->st->codec->codec_id != CODEC_ID_VC1
2506        ) {
2507         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
2508             opkt.destruct = av_destruct_packet;
2509     } else {
2510         opkt.data = pkt->data;
2511         opkt.size = pkt->size;
2512     }
2513
2514     if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
2515         /* store AVPicture in AVPacket, as expected by the output format */
2516         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
2517         opkt.data = (uint8_t *)&pict;
2518         opkt.size = sizeof(AVPicture);
2519         opkt.flags |= AV_PKT_FLAG_KEY;
2520     }
2521
2522     write_frame(of->ctx, &opkt, ost);
2523     ost->st->codec->frame_number++;
2524     av_free_packet(&opkt);
2525 }
2526
2527 static void rate_emu_sleep(InputStream *ist)
2528 {
2529     if (input_files[ist->file_index]->rate_emu) {
2530         int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2531         int64_t now = av_gettime() - ist->start;
2532         if (pts > now)
2533             av_usleep(pts - now);
2534     }
2535 }
2536
2537 static int guess_input_channel_layout(InputStream *ist)
2538 {
2539     AVCodecContext *dec = ist->st->codec;
2540
2541     if (!dec->channel_layout) {
2542         char layout_name[256];
2543
2544         dec->channel_layout = av_get_default_channel_layout(dec->channels);
2545         if (!dec->channel_layout)
2546             return 0;
2547         av_get_channel_layout_string(layout_name, sizeof(layout_name),
2548                                      dec->channels, dec->channel_layout);
2549         av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
2550                "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
2551     }
2552     return 1;
2553 }
2554
2555 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
2556 {
2557     AVFrame *decoded_frame;
2558     AVCodecContext *avctx = ist->st->codec;
2559     int i, ret, resample_changed;
2560     AVRational decoded_frame_tb;
2561
2562     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2563         return AVERROR(ENOMEM);
2564     else
2565         avcodec_get_frame_defaults(ist->decoded_frame);
2566     decoded_frame = ist->decoded_frame;
2567
2568     update_benchmark(NULL);
2569     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
2570     update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2571     if (ret < 0) {
2572         return ret;
2573     }
2574     if (avctx->sample_rate <= 0) {
2575         av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2576         return AVERROR_INVALIDDATA;
2577     }
2578
2579     if (!*got_output) {
2580         /* no audio frame */
2581         if (!pkt->size)
2582             for (i = 0; i < ist->nb_filters; i++)
2583                 av_buffersrc_add_ref(ist->filters[i]->filter, NULL,
2584                                      AV_BUFFERSRC_FLAG_NO_COPY);
2585         return ret;
2586     }
2587
2588 #if 1
2589     /* increment next_dts to use for the case where the input stream does not
2590        have timestamps or there are multiple frames in the packet */
2591     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2592                      avctx->sample_rate;
2593     ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2594                      avctx->sample_rate;
2595 #endif
2596
2597     rate_emu_sleep(ist);
2598
2599     resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
2600                        ist->resample_channels       != avctx->channels               ||
2601                        ist->resample_channel_layout != decoded_frame->channel_layout ||
2602                        ist->resample_sample_rate    != decoded_frame->sample_rate;
2603     if (resample_changed) {
2604         char layout1[64], layout2[64];
2605
2606         if (!guess_input_channel_layout(ist)) {
2607             av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
2608                    "layout for Input Stream #%d.%d\n", ist->file_index,
2609                    ist->st->index);
2610             exit_program(1);
2611         }
2612         decoded_frame->channel_layout = avctx->channel_layout;
2613
2614         av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
2615                                      ist->resample_channel_layout);
2616         av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
2617                                      decoded_frame->channel_layout);
2618
2619         av_log(NULL, AV_LOG_INFO,
2620                "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",
2621                ist->file_index, ist->st->index,
2622                ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
2623                ist->resample_channels, layout1,
2624                decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
2625                avctx->channels, layout2);
2626
2627         ist->resample_sample_fmt     = decoded_frame->format;
2628         ist->resample_sample_rate    = decoded_frame->sample_rate;
2629         ist->resample_channel_layout = decoded_frame->channel_layout;
2630         ist->resample_channels       = avctx->channels;
2631
2632         for (i = 0; i < nb_filtergraphs; i++)
2633             if (ist_in_filtergraph(filtergraphs[i], ist)) {
2634                 FilterGraph *fg = filtergraphs[i];
2635                 int j;
2636                 if (configure_filtergraph(fg) < 0) {
2637                     av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2638                     exit_program(1);
2639                 }
2640                 for (j = 0; j < fg->nb_outputs; j++) {
2641                     OutputStream *ost = fg->outputs[j]->ost;
2642                     if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2643                         !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
2644                         av_buffersink_set_frame_size(ost->filter->filter,
2645                                                      ost->st->codec->frame_size);
2646                 }
2647             }
2648     }
2649
2650     /* if the decoder provides a pts, use it instead of the last packet pts.
2651        the decoder could be delaying output by a packet or more. */
2652     if (decoded_frame->pts != AV_NOPTS_VALUE) {
2653         ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
2654         decoded_frame_tb   = avctx->time_base;
2655     } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
2656         decoded_frame->pts = decoded_frame->pkt_pts;
2657         pkt->pts           = AV_NOPTS_VALUE;
2658         decoded_frame_tb   = ist->st->time_base;
2659     } else if (pkt->pts != AV_NOPTS_VALUE) {
2660         decoded_frame->pts = pkt->pts;
2661         pkt->pts           = AV_NOPTS_VALUE;
2662         decoded_frame_tb   = ist->st->time_base;
2663     }else {
2664         decoded_frame->pts = ist->dts;
2665         decoded_frame_tb   = AV_TIME_BASE_Q;
2666     }
2667     if (decoded_frame->pts != AV_NOPTS_VALUE)
2668         decoded_frame->pts = av_rescale_q(decoded_frame->pts,
2669                                           decoded_frame_tb,
2670                                           (AVRational){1, ist->st->codec->sample_rate});
2671     for (i = 0; i < ist->nb_filters; i++)
2672         av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0);
2673
2674     decoded_frame->pts = AV_NOPTS_VALUE;
2675
2676     return ret;
2677 }
2678
2679 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
2680 {
2681     AVFrame *decoded_frame;
2682     void *buffer_to_free = NULL;
2683     int i, ret = 0, resample_changed;
2684     int64_t best_effort_timestamp;
2685     AVRational *frame_sample_aspect;
2686     float quality;
2687
2688     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
2689         return AVERROR(ENOMEM);
2690     else
2691         avcodec_get_frame_defaults(ist->decoded_frame);
2692     decoded_frame = ist->decoded_frame;
2693     pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
2694
2695     update_benchmark(NULL);
2696     ret = avcodec_decode_video2(ist->st->codec,
2697                                 decoded_frame, got_output, pkt);
2698     update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2699     if (ret < 0)
2700         return ret;
2701
2702     quality = same_quant ? decoded_frame->quality : 0;
2703     if (!*got_output) {
2704         /* no picture yet */
2705         if (!pkt->size)
2706             for (i = 0; i < ist->nb_filters; i++)
2707                 av_buffersrc_add_ref(ist->filters[i]->filter, NULL, AV_BUFFERSRC_FLAG_NO_COPY);
2708         return ret;
2709     }
2710
2711     if(ist->top_field_first>=0)
2712         decoded_frame->top_field_first = ist->top_field_first;
2713
2714     best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
2715     if(best_effort_timestamp != AV_NOPTS_VALUE)
2716         ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
2717
2718     if (debug_ts) {
2719         av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
2720                 "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
2721                 ist->st->index, av_ts2str(decoded_frame->pts),
2722                 av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
2723                 best_effort_timestamp,
2724                 av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
2725                 decoded_frame->key_frame, decoded_frame->pict_type);
2726     }
2727
2728     pkt->size = 0;
2729     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
2730
2731     rate_emu_sleep(ist);
2732
2733     if (ist->st->sample_aspect_ratio.num)
2734         decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2735
2736     resample_changed = ist->resample_width   != decoded_frame->width  ||
2737                        ist->resample_height  != decoded_frame->height ||
2738                        ist->resample_pix_fmt != decoded_frame->format;
2739     if (resample_changed) {
2740         av_log(NULL, AV_LOG_INFO,
2741                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
2742                ist->file_index, ist->st->index,
2743                ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
2744                decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
2745
2746         ist->resample_width   = decoded_frame->width;
2747         ist->resample_height  = decoded_frame->height;
2748         ist->resample_pix_fmt = decoded_frame->format;
2749
2750         for (i = 0; i < nb_filtergraphs; i++)
2751             if (ist_in_filtergraph(filtergraphs[i], ist) &&
2752                 configure_filtergraph(filtergraphs[i]) < 0) {
2753                 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
2754                 exit_program(1);
2755             }
2756     }
2757
2758     frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
2759     for (i = 0; i < ist->nb_filters; i++) {
2760         int changed =      ist->st->codec->width   != ist->filters[i]->filter->outputs[0]->w
2761                         || ist->st->codec->height  != ist->filters[i]->filter->outputs[0]->h
2762                         || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
2763         // XXX what an ugly hack
2764         if (ist->filters[i]->graph->nb_outputs == 1)
2765             ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
2766
2767         if (!frame_sample_aspect->num)
2768             *frame_sample_aspect = ist->st->sample_aspect_ratio;
2769         if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
2770             FrameBuffer      *buf = decoded_frame->opaque;
2771             AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
2772                                         decoded_frame->data, decoded_frame->linesize,
2773                                         AV_PERM_READ | AV_PERM_PRESERVE,
2774                                         ist->st->codec->width, ist->st->codec->height,
2775                                         ist->st->codec->pix_fmt);
2776
2777             avfilter_copy_frame_props(fb, decoded_frame);
2778             fb->buf->priv           = buf;
2779             fb->buf->free           = filter_release_buffer;
2780
2781             av_assert0(buf->refcount>0);
2782             buf->refcount++;
2783             av_buffersrc_add_ref(ist->filters[i]->filter, fb,
2784                                  AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
2785                                  AV_BUFFERSRC_FLAG_NO_COPY);
2786         } else
2787         if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
2788             av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
2789             exit_program(1);
2790         }
2791
2792     }
2793
2794     av_free(buffer_to_free);
2795     return ret;
2796 }
2797
2798 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
2799 {
2800     AVSubtitle subtitle;
2801     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
2802                                           &subtitle, got_output, pkt);
2803     if (ret < 0 || !*got_output) {
2804         if (!pkt->size)
2805             sub2video_flush(ist);
2806         return ret;
2807     }
2808
2809     rate_emu_sleep(ist);
2810
2811     sub2video_update(ist, &subtitle, pkt->pts);
2812
2813     for (i = 0; i < nb_output_streams; i++) {
2814         OutputStream *ost = output_streams[i];
2815
2816         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
2817             continue;
2818
2819         do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
2820     }
2821
2822     avsubtitle_free(&subtitle);
2823     return ret;
2824 }
2825
2826 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2827 static int output_packet(InputStream *ist, const AVPacket *pkt)
2828 {
2829     int ret = 0, i;
2830     int got_output;
2831
2832     AVPacket avpkt;
2833     if (!ist->saw_first_ts) {
2834         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;
2835         ist->pts = 0;
2836         if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2837             ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2838             ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2839         }
2840         ist->saw_first_ts = 1;
2841     }
2842
2843     if (ist->next_dts == AV_NOPTS_VALUE)
2844         ist->next_dts = ist->dts;
2845     if (ist->next_pts == AV_NOPTS_VALUE)
2846         ist->next_pts = ist->pts;
2847
2848     if (pkt == NULL) {
2849         /* EOF handling */
2850         av_init_packet(&avpkt);
2851         avpkt.data = NULL;
2852         avpkt.size = 0;
2853         goto handle_eof;
2854     } else {
2855         avpkt = *pkt;
2856     }
2857
2858     if (pkt->dts != AV_NOPTS_VALUE) {
2859         ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2860         if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2861             ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2862     }
2863
2864     // while we have more to decode or while the decoder did output something on EOF
2865     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
2866         int duration;
2867     handle_eof:
2868
2869         ist->pts = ist->next_pts;
2870         ist->dts = ist->next_dts;
2871
2872         if (avpkt.size && avpkt.size != pkt->size) {
2873             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
2874                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
2875             ist->showed_multi_packet_warning = 1;
2876         }
2877
2878         switch (ist->st->codec->codec_type) {
2879         case AVMEDIA_TYPE_AUDIO:
2880             ret = decode_audio    (ist, &avpkt, &got_output);
2881             break;
2882         case AVMEDIA_TYPE_VIDEO:
2883             ret = decode_video    (ist, &avpkt, &got_output);
2884             if (avpkt.duration) {
2885                 duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
2886             } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
2887                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2888                 duration = ((int64_t)AV_TIME_BASE *
2889                                 ist->st->codec->time_base.num * ticks) /
2890                                 ist->st->codec->time_base.den;
2891             } else
2892                 duration = 0;
2893
2894             if(ist->dts != AV_NOPTS_VALUE && duration) {
2895                 ist->next_dts += duration;
2896             }else
2897                 ist->next_dts = AV_NOPTS_VALUE;
2898
2899             if (got_output)
2900                 ist->next_pts += duration; //FIXME the duration is not correct in some cases
2901             break;
2902         case AVMEDIA_TYPE_SUBTITLE:
2903             ret = transcode_subtitles(ist, &avpkt, &got_output);
2904             break;
2905         default:
2906             return -1;
2907         }
2908
2909         if (ret < 0)
2910             return ret;
2911
2912         avpkt.dts=
2913         avpkt.pts= AV_NOPTS_VALUE;
2914
2915         // touch data and size only if not EOF
2916         if (pkt) {
2917             if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
2918                 ret = avpkt.size;
2919             avpkt.data += ret;
2920             avpkt.size -= ret;
2921         }
2922         if (!got_output) {
2923             continue;
2924         }
2925     }
2926
2927     /* handle stream copy */
2928     if (!ist->decoding_needed) {
2929         rate_emu_sleep(ist);
2930         ist->dts = ist->next_dts;
2931         switch (ist->st->codec->codec_type) {
2932         case AVMEDIA_TYPE_AUDIO:
2933             ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2934                              ist->st->codec->sample_rate;
2935             break;
2936         case AVMEDIA_TYPE_VIDEO:
2937             if (pkt->duration) {
2938                 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2939             } else if(ist->st->codec->time_base.num != 0) {
2940                 int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
2941                 ist->next_dts += ((int64_t)AV_TIME_BASE *
2942                                   ist->st->codec->time_base.num * ticks) /
2943                                   ist->st->codec->time_base.den;
2944             }
2945             break;
2946         }
2947         ist->pts = ist->dts;
2948         ist->next_pts = ist->next_dts;
2949     }
2950     for (i = 0; pkt && i < nb_output_streams; i++) {
2951         OutputStream *ost = output_streams[i];
2952
2953         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2954             continue;
2955
2956         do_streamcopy(ist, ost, pkt);
2957     }
2958
2959     return 0;
2960 }
2961
2962 static void print_sdp(void)
2963 {
2964     char sdp[2048];
2965     int i;
2966     AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
2967
2968     if (!avc)
2969         exit_program(1);
2970     for (i = 0; i < nb_output_files; i++)
2971         avc[i] = output_files[i]->ctx;
2972
2973     av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
2974     printf("SDP:\n%s\n", sdp);
2975     fflush(stdout);
2976     av_freep(&avc);
2977 }
2978
2979 static int init_input_stream(int ist_index, char *error, int error_len)
2980 {
2981     InputStream *ist = input_streams[ist_index];
2982
2983     if (ist->decoding_needed) {
2984         AVCodec *codec = ist->dec;
2985         if (!codec) {
2986             snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2987                     avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
2988             return AVERROR(EINVAL);
2989         }
2990
2991         ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
2992         if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
2993             ist->st->codec->get_buffer     = codec_get_buffer;
2994             ist->st->codec->release_buffer = codec_release_buffer;
2995             ist->st->codec->opaque         = &ist->buffer_pool;
2996         }
2997
2998         if (!av_dict_get(ist->opts, "threads", NULL, 0))
2999             av_dict_set(&ist->opts, "threads", "auto", 0);
3000         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
3001             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
3002                     ist->file_index, ist->st->index);
3003             return AVERROR(EINVAL);
3004         }
3005         assert_codec_experimental(ist->st->codec, 0);
3006         assert_avoptions(ist->opts);
3007     }
3008
3009     ist->next_pts = AV_NOPTS_VALUE;
3010     ist->next_dts = AV_NOPTS_VALUE;
3011     ist->is_start = 1;
3012
3013     return 0;
3014 }
3015
3016 static InputStream *get_input_stream(OutputStream *ost)
3017 {
3018     if (ost->source_index >= 0)
3019         return input_streams[ost->source_index];
3020     return NULL;
3021 }
3022
3023 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3024                                     AVCodecContext *avctx)
3025 {
3026     char *p;
3027     int n = 1, i;
3028     int64_t t;
3029
3030     for (p = kf; *p; p++)
3031         if (*p == ',')
3032             n++;
3033     ost->forced_kf_count = n;
3034     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
3035     if (!ost->forced_kf_pts) {
3036         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3037         exit_program(1);
3038     }
3039
3040     p = kf;
3041     for (i = 0; i < n; i++) {
3042         char *next = strchr(p, ',');
3043
3044         if (next)
3045             *next++ = 0;
3046
3047         t = parse_time_or_die("force_key_frames", p, 1);
3048         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3049
3050         p = next;
3051     }
3052 }
3053
3054 static void report_new_stream(int input_index, AVPacket *pkt)
3055 {
3056     InputFile *file = input_files[input_index];
3057     AVStream *st = file->ctx->streams[pkt->stream_index];
3058
3059     if (pkt->stream_index < file->nb_streams_warn)
3060         return;
3061     av_log(file->ctx, AV_LOG_WARNING,
3062            "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
3063            av_get_media_type_string(st->codec->codec_type),
3064            input_index, pkt->stream_index,
3065            pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
3066     file->nb_streams_warn = pkt->stream_index + 1;
3067 }
3068
3069 static int transcode_init(void)
3070 {
3071     int ret = 0, i, j, k;
3072     AVFormatContext *oc;
3073     AVCodecContext *codec, *icodec = NULL;
3074     OutputStream *ost;
3075     InputStream *ist;
3076     char error[1024];
3077     int want_sdp = 1;
3078
3079     /* init framerate emulation */
3080     for (i = 0; i < nb_input_files; i++) {
3081         InputFile *ifile = input_files[i];
3082         if (ifile->rate_emu)
3083             for (j = 0; j < ifile->nb_streams; j++)
3084                 input_streams[j + ifile->ist_index]->start = av_gettime();
3085     }
3086
3087     /* output stream init */
3088     for (i = 0; i < nb_output_files; i++) {
3089         oc = output_files[i]->ctx;
3090         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
3091             av_dump_format(oc, i, oc->filename, 1);
3092             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
3093             return AVERROR(EINVAL);
3094         }
3095     }
3096
3097     /* init complex filtergraphs */
3098     for (i = 0; i < nb_filtergraphs; i++)
3099         if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
3100             return ret;
3101
3102     /* for each output stream, we compute the right encoding parameters */
3103     for (i = 0; i < nb_output_streams; i++) {
3104         ost = output_streams[i];
3105         oc  = output_files[ost->file_index]->ctx;
3106         ist = get_input_stream(ost);
3107
3108         if (ost->attachment_filename)
3109             continue;
3110
3111         codec  = ost->st->codec;
3112
3113         if (ist) {
3114             icodec = ist->st->codec;
3115
3116             ost->st->disposition          = ist->st->disposition;
3117             codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
3118             codec->chroma_sample_location = icodec->chroma_sample_location;
3119         }
3120
3121         if (ost->stream_copy) {
3122             uint64_t extra_size;
3123
3124             av_assert0(ist && !ost->filter);
3125
3126             extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
3127
3128             if (extra_size > INT_MAX) {
3129                 return AVERROR(EINVAL);
3130             }
3131
3132             /* if stream_copy is selected, no need to decode or encode */
3133             codec->codec_id   = icodec->codec_id;
3134             codec->codec_type = icodec->codec_type;
3135
3136             if (!codec->codec_tag) {
3137                 if (!oc->oformat->codec_tag ||
3138                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
3139                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
3140                     codec->codec_tag = icodec->codec_tag;
3141             }
3142
3143             codec->bit_rate       = icodec->bit_rate;
3144             codec->rc_max_rate    = icodec->rc_max_rate;
3145             codec->rc_buffer_size = icodec->rc_buffer_size;
3146             codec->field_order    = icodec->field_order;
3147             codec->extradata      = av_mallocz(extra_size);
3148             if (!codec->extradata) {
3149                 return AVERROR(ENOMEM);
3150             }
3151             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
3152             codec->extradata_size= icodec->extradata_size;
3153             codec->bits_per_coded_sample  = icodec->bits_per_coded_sample;
3154
3155             codec->time_base = ist->st->time_base;
3156             /*
3157              * Avi is a special case here because it supports variable fps but
3158              * having the fps and timebase differe significantly adds quite some
3159              * overhead
3160              */
3161             if(!strcmp(oc->oformat->name, "avi")) {
3162                 if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
3163                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
3164                                && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
3165                                && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
3166                      || copy_tb==2){
3167                     codec->time_base.num = ist->st->r_frame_rate.den;
3168                     codec->time_base.den = 2*ist->st->r_frame_rate.num;
3169                     codec->ticks_per_frame = 2;
3170                 } else if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
3171                                  && av_q2d(ist->st->time_base) < 1.0/500
3172                     || copy_tb==0){
3173                     codec->time_base = icodec->time_base;
3174                     codec->time_base.num *= icodec->ticks_per_frame;
3175                     codec->time_base.den *= 2;
3176                     codec->ticks_per_frame = 2;
3177                 }
3178             } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
3179                       && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
3180                       && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
3181             ) {
3182                 if(   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
3183                                 && av_q2d(ist->st->time_base) < 1.0/500
3184                    || copy_tb==0){
3185                     codec->time_base = icodec->time_base;
3186                     codec->time_base.num *= icodec->ticks_per_frame;
3187                 }
3188             }
3189
3190             if(ost->frame_rate.num)
3191                 codec->time_base = av_inv_q(ost->frame_rate);
3192
3193             av_reduce(&codec->time_base.num, &codec->time_base.den,
3194                         codec->time_base.num, codec->time_base.den, INT_MAX);
3195
3196             switch (codec->codec_type) {
3197             case AVMEDIA_TYPE_AUDIO:
3198                 if (audio_volume != 256) {
3199                     av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3200                     exit_program(1);
3201                 }
3202                 codec->channel_layout     = icodec->channel_layout;
3203                 codec->sample_rate        = icodec->sample_rate;
3204                 codec->channels           = icodec->channels;
3205                 codec->frame_size         = icodec->frame_size;
3206                 codec->audio_service_type = icodec->audio_service_type;
3207                 codec->block_align        = icodec->block_align;
3208                 if((codec->block_align == 1 || codec->block_align == 1152) && codec->codec_id == CODEC_ID_MP3)
3209                     codec->block_align= 0;
3210                 if(codec->codec_id == CODEC_ID_AC3)
3211                     codec->block_align= 0;
3212                 break;
3213             case AVMEDIA_TYPE_VIDEO:
3214                 codec->pix_fmt            = icodec->pix_fmt;
3215                 codec->width              = icodec->width;
3216                 codec->height             = icodec->height;
3217                 codec->has_b_frames       = icodec->has_b_frames;
3218                 if (!codec->sample_aspect_ratio.num) {
3219                     codec->sample_aspect_ratio   =
3220                     ost->st->sample_aspect_ratio =
3221                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
3222                         ist->st->codec->sample_aspect_ratio.num ?
3223                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
3224                 }
3225                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3226                 break;
3227             case AVMEDIA_TYPE_SUBTITLE:
3228                 codec->width  = icodec->width;
3229                 codec->height = icodec->height;
3230                 break;
3231             case AVMEDIA_TYPE_DATA:
3232             case AVMEDIA_TYPE_ATTACHMENT:
3233                 break;
3234             default:
3235                 abort();
3236             }
3237         } else {
3238             if (!ost->enc)
3239                 ost->enc = avcodec_find_encoder(codec->codec_id);
3240             if (!ost->enc) {
3241                 /* should only happen when a default codec is not present. */
3242                 snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
3243                          avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
3244                 ret = AVERROR(EINVAL);
3245                 goto dump_format;
3246             }
3247
3248             if (ist)
3249                 ist->decoding_needed = 1;
3250             ost->encoding_needed = 1;
3251
3252             if (!ost->filter &&
3253                 (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
3254                  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
3255                     FilterGraph *fg;
3256                     fg = init_simple_filtergraph(ist, ost);
3257                     if (configure_filtergraph(fg)) {
3258                         av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
3259                         exit(1);
3260                     }
3261             }
3262
3263             if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
3264                 if (ost->filter && !ost->frame_rate.num)
3265                     ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
3266                 if (ist && !ost->frame_rate.num)
3267                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
3268 //                    ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
3269                 if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
3270                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3271                     ost->frame_rate = ost->enc->supported_framerates[idx];
3272                 }
3273             }
3274
3275             switch (codec->codec_type) {
3276             case AVMEDIA_TYPE_AUDIO:
3277                 codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
3278                 codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
3279                 codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
3280                 codec->channels       = av_get_channel_layout_nb_channels(codec->channel_layout);
3281                 codec->time_base      = (AVRational){ 1, codec->sample_rate };
3282                 break;
3283             case AVMEDIA_TYPE_VIDEO:
3284                 codec->time_base = av_inv_q(ost->frame_rate);
3285                 if (ost->filter && !(codec->time_base.num && codec->time_base.den))
3286                     codec->time_base = ost->filter->filter->inputs[0]->time_base;
3287                 if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3288                    && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3289                     av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3290                                                "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3291                 }
3292                 for (j = 0; j < ost->forced_kf_count; j++)
3293                     ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3294                                                          AV_TIME_BASE_Q,
3295                                                          codec->time_base);
3296
3297                 codec->width  = ost->filter->filter->inputs[0]->w;
3298                 codec->height = ost->filter->filter->inputs[0]->h;
3299                 codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3300                     ost->frame_aspect_ratio ? // overridden by the -aspect cli option
3301                     av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
3302                     ost->filter->filter->inputs[0]->sample_aspect_ratio;
3303                 codec->pix_fmt = ost->filter->filter->inputs[0]->format;
3304
3305                 if (!icodec ||
3306                     codec->width   != icodec->width  ||
3307                     codec->height  != icodec->height ||
3308                     codec->pix_fmt != icodec->pix_fmt) {
3309                     codec->bits_per_raw_sample = frame_bits_per_raw_sample;
3310                 }
3311
3312                 if (ost->forced_keyframes)
3313                     parse_forced_key_frames(ost->forced_keyframes, ost,
3314                                             ost->st->codec);
3315                 break;
3316             case AVMEDIA_TYPE_SUBTITLE:
3317                 codec->time_base = (AVRational){1, 1000};
3318                 break;
3319             default:
3320                 abort();
3321                 break;
3322             }
3323             /* two pass mode */
3324             if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
3325                 char logfilename[1024];
3326                 FILE *f;
3327
3328                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
3329                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
3330                          i);
3331                 if (!strcmp(ost->enc->name, "libx264")) {
3332                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
3333                 } else {
3334                     if (codec->flags & CODEC_FLAG_PASS2) {
3335                         char  *logbuffer;
3336                         size_t logbuffer_size;
3337                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
3338                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
3339                                    logfilename);
3340                             exit_program(1);
3341                         }
3342                         codec->stats_in = logbuffer;
3343                     }
3344                     if (codec->flags & CODEC_FLAG_PASS1) {
3345                         f = fopen(logfilename, "wb");
3346                         if (!f) {
3347                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
3348                                 logfilename, strerror(errno));
3349                             exit_program(1);
3350                         }
3351                         ost->logfile = f;
3352                     }
3353                 }
3354             }
3355         }
3356     }
3357
3358     /* open each encoder */
3359     for (i = 0; i < nb_output_streams; i++) {
3360         ost = output_streams[i];
3361         if (ost->encoding_needed) {
3362             AVCodec      *codec = ost->enc;
3363             AVCodecContext *dec = NULL;
3364
3365             if ((ist = get_input_stream(ost)))
3366                 dec = ist->st->codec;
3367             if (dec && dec->subtitle_header) {
3368                 /* ASS code assumes this buffer is null terminated so add extra byte. */
3369                 ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
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;