]> git.sesse.net Git - ffmpeg/blob - ffmpeg.c
Merge commit '36ef5369ee9b336febc2c270f8718cec4476cb85'
[ffmpeg] / 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 == AV_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 == AV_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 == AV_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 == AV_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 == AV_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 == AV_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 == AV_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 == AV_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 != AV_CODEC_ID_H264
2503        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
2504        && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
2505        && ost->st->codec->codec_id != AV_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 == AV_CODEC_ID_MP3)
3209                     codec->block_align= 0;
3210                 if(codec->codec_id == AV_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;
3618         }
3619         ost->unavailable = 1;
3620         nb_active_out--;
3621     }
3622     return -1;
3623 }
3624
3625 static int check_keyboard_interaction(int64_t cur_time)
3626 {
3627     int i, ret, key;
3628     static int64_t last_time;
3629     if (received_nb_signals)
3630         return AVERROR_EXIT;
3631     /* read_key() returns 0 on EOF */
3632     if(cur_time - last_time >= 100000 && !run_as_daemon){
3633         key =  read_key();
3634         last_time = cur_time;
3635     }else
3636         key = -1;
3637     if (key == 'q')
3638         return AVERROR_EXIT;
3639     if (key == '+') av_log_set_level(av_log_get_level()+10);
3640     if (key == '-') av_log_set_level(av_log_get_level()-10);
3641     if (key == 's') qp_hist     ^= 1;
3642     if (key == 'h'){
3643         if (do_hex_dump){
3644             do_hex_dump = do_pkt_dump = 0;
3645         } else if(do_pkt_dump){
3646             do_hex_dump = 1;
3647         } else
3648             do_pkt_dump = 1;
3649         av_log_set_level(AV_LOG_DEBUG);
3650     }
3651     if (key == 'c' || key == 'C'){
3652         char buf[4096], target[64], command[256], arg[256] = {0};
3653         double time;
3654         int k, n = 0;
3655         fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
3656         i = 0;
3657         while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
3658             if (k > 0)
3659                 buf[i++] = k;
3660         buf[i] = 0;
3661         if (k > 0 &&
3662             (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
3663             av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
3664                    target, time, command, arg);
3665             for (i = 0; i < nb_filtergraphs; i++) {
3666                 FilterGraph *fg = filtergraphs[i];
3667                 if (fg->graph) {
3668                     if (time < 0) {
3669                         ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
3670                                                           key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
3671                         fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
3672                     } else {
3673                         ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
3674                     }
3675                 }
3676             }
3677         } else {
3678             av_log(NULL, AV_LOG_ERROR,
3679                    "Parse error, at least 3 arguments were expected, "
3680                    "only %d given in string '%s'\n", n, buf);
3681         }
3682     }
3683     if (key == 'd' || key == 'D'){
3684         int debug=0;
3685         if(key == 'D') {
3686             debug = input_streams[0]->st->codec->debug<<1;
3687             if(!debug) debug = 1;
3688             while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
3689                 debug += debug;
3690         }else
3691             if(scanf("%d", &debug)!=1)
3692                 fprintf(stderr,"error parsing debug value\n");
3693         for(i=0;i<nb_input_streams;i++) {
3694             input_streams[i]->st->codec->debug = debug;
3695         }
3696         for(i=0;i<nb_output_streams;i++) {
3697             OutputStream *ost = output_streams[i];
3698             ost->st->codec->debug = debug;
3699         }
3700         if(debug) av_log_set_level(AV_LOG_DEBUG);
3701         fprintf(stderr,"debug=%d\n", debug);
3702     }
3703     if (key == '?'){
3704         fprintf(stderr, "key    function\n"
3705                         "?      show this help\n"
3706                         "+      increase verbosity\n"
3707                         "-      decrease verbosity\n"
3708                         "c      Send command to filtergraph\n"
3709                         "D      cycle through available debug modes\n"
3710                         "h      dump packets/hex press to cycle through the 3 states\n"
3711                         "q      quit\n"
3712                         "s      Show QP histogram\n"
3713         );
3714     }
3715     return 0;
3716 }
3717
3718 #if HAVE_PTHREADS
3719 static void *input_thread(void *arg)
3720 {
3721     InputFile *f = arg;
3722     int ret = 0;
3723
3724     while (!transcoding_finished && ret >= 0) {
3725         AVPacket pkt;
3726         ret = av_read_frame(f->ctx, &pkt);
3727
3728         if (ret == AVERROR(EAGAIN)) {
3729             av_usleep(10000);
3730             ret = 0;
3731             continue;
3732         } else if (ret < 0)
3733             break;
3734
3735         pthread_mutex_lock(&f->fifo_lock);
3736         while (!av_fifo_space(f->fifo))
3737             pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
3738
3739         av_dup_packet(&pkt);
3740         av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
3741
3742         pthread_mutex_unlock(&f->fifo_lock);
3743     }
3744
3745     f->finished = 1;
3746     return NULL;
3747 }
3748
3749 static void free_input_threads(void)
3750 {
3751     int i;
3752
3753     if (nb_input_files == 1)
3754         return;
3755
3756     transcoding_finished = 1;
3757
3758     for (i = 0; i < nb_input_files; i++) {
3759         InputFile *f = input_files[i];
3760         AVPacket pkt;
3761
3762         if (!f->fifo || f->joined)
3763             continue;
3764
3765         pthread_mutex_lock(&f->fifo_lock);
3766         while (av_fifo_size(f->fifo)) {
3767             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
3768             av_free_packet(&pkt);
3769         }
3770         pthread_cond_signal(&f->fifo_cond);
3771         pthread_mutex_unlock(&f->fifo_lock);
3772
3773         pthread_join(f->thread, NULL);
3774         f->joined = 1;
3775
3776         while (av_fifo_size(f->fifo)) {
3777             av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
3778             av_free_packet(&pkt);
3779         }
3780         av_fifo_free(f->fifo);
3781     }
3782 }
3783
3784 static int init_input_threads(void)
3785 {
3786     int i, ret;
3787
3788     if (nb_input_files == 1)
3789         return 0;
3790
3791     for (i = 0; i < nb_input_files; i++) {
3792         InputFile *f = input_files[i];
3793
3794         if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
3795             return AVERROR(ENOMEM);
3796
3797         pthread_mutex_init(&f->fifo_lock, NULL);
3798         pthread_cond_init (&f->fifo_cond, NULL);
3799
3800         if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
3801             return AVERROR(ret);
3802     }
3803     return 0;
3804 }
3805
3806 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
3807 {
3808     int ret = 0;
3809
3810     pthread_mutex_lock(&f->fifo_lock);
3811
3812     if (av_fifo_size(f->fifo)) {
3813         av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
3814         pthread_cond_signal(&f->fifo_cond);
3815     } else {
3816         if (f->finished)
3817             ret = AVERROR_EOF;
3818         else
3819             ret = AVERROR(EAGAIN);
3820     }
3821
3822     pthread_mutex_unlock(&f->fifo_lock);
3823
3824     return ret;
3825 }
3826 #endif
3827
3828 static int get_input_packet(InputFile *f, AVPacket *pkt)
3829 {
3830 #if HAVE_PTHREADS
3831     if (nb_input_files > 1)
3832         return get_input_packet_mt(f, pkt);
3833 #endif
3834     return av_read_frame(f->ctx, pkt);
3835 }
3836
3837 /*
3838  * The following code is the main loop of the file converter
3839  */
3840 static int transcode(void)
3841 {
3842     int ret, i;
3843     AVFormatContext *is, *os;
3844     OutputStream *ost;
3845     InputStream *ist;
3846     int no_packet_count = 0;
3847     int64_t timer_start;
3848
3849     ret = transcode_init();
3850     if (ret < 0)
3851         goto fail;
3852
3853     if (stdin_interaction) {
3854         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3855     }
3856
3857     timer_start = av_gettime();
3858
3859 #if HAVE_PTHREADS
3860     if ((ret = init_input_threads()) < 0)
3861         goto fail;
3862 #endif
3863
3864     for (; received_sigterm == 0;) {
3865         int file_index, ist_index;
3866         AVPacket pkt;
3867         int64_t cur_time= av_gettime();
3868
3869         /* if 'q' pressed, exits */
3870         if (stdin_interaction)
3871             if (check_keyboard_interaction(cur_time) < 0)
3872                 break;
3873
3874         /* check if there's any stream where output is still needed */
3875         if (!need_output()) {
3876             av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3877             break;
3878         }
3879
3880         /* select the stream that we must read now */
3881         file_index = select_input_file();
3882         /* if none, if is finished */
3883         if (file_index == -2) {
3884             poll_filters() ;
3885             continue;
3886         }
3887         if (file_index < 0) {
3888             if (no_packet_count) {
3889                 no_packet_count = 0;
3890                 for (i = 0; i < nb_input_files; i++)
3891                     input_files[i]->unavailable = 0;
3892                 av_usleep(10000);
3893                 continue;
3894             }
3895             av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3896             break;
3897         }
3898
3899         is  = input_files[file_index]->ctx;
3900         ret = get_input_packet(input_files[file_index], &pkt);
3901
3902         if (ret == AVERROR(EAGAIN)) {
3903             input_files[file_index]->unavailable = 1;
3904             no_packet_count++;
3905             continue;
3906         }
3907         if (ret < 0) {
3908             if (ret != AVERROR_EOF) {
3909                 print_error(is->filename, ret);
3910                 if (exit_on_error)
3911                     exit_program(1);
3912             }
3913             input_files[file_index]->eof_reached = 1;
3914
3915             for (i = 0; i < input_files[file_index]->nb_streams; i++) {
3916                 ist = input_streams[input_files[file_index]->ist_index + i];
3917                 if (ist->decoding_needed)
3918                     output_packet(ist, NULL);
3919                 poll_filters();
3920             }
3921
3922             if (opt_shortest)
3923                 break;
3924             else
3925                 continue;
3926         }
3927
3928         no_packet_count = 0;
3929         for (i = 0; i < nb_input_files; i++)
3930             input_files[i]->unavailable = 0;
3931
3932         if (do_pkt_dump) {
3933             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
3934                              is->streams[pkt.stream_index]);
3935         }
3936         /* the following test is needed in case new streams appear
3937            dynamically in stream : we ignore them */
3938         if (pkt.stream_index >= input_files[file_index]->nb_streams) {
3939             report_new_stream(file_index, &pkt);
3940             goto discard_packet;
3941         }
3942         ist_index = input_files[file_index]->ist_index + pkt.stream_index;
3943         ist = input_streams[ist_index];
3944         if (ist->discard)
3945             goto discard_packet;
3946
3947         if(!ist->wrap_correction_done && input_files[file_index]->ctx->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
3948             uint64_t stime = av_rescale_q(input_files[file_index]->ctx->start_time, AV_TIME_BASE_Q, ist->st->time_base);
3949             uint64_t stime2= stime + (1LL<<ist->st->pts_wrap_bits);
3950             ist->wrap_correction_done = 1;
3951             if(pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime && pkt.dts - stime > stime2 - pkt.dts) {
3952                 pkt.dts -= 1LL<<ist->st->pts_wrap_bits;
3953                 ist->wrap_correction_done = 0;
3954             }
3955             if(pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime && pkt.pts - stime > stime2 - pkt.pts) {
3956                 pkt.pts -= 1LL<<ist->st->pts_wrap_bits;
3957                 ist->wrap_correction_done = 0;
3958             }
3959         }
3960
3961         if (pkt.dts != AV_NOPTS_VALUE)
3962             pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3963         if (pkt.pts != AV_NOPTS_VALUE)
3964             pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3965
3966         if (pkt.pts != AV_NOPTS_VALUE)
3967             pkt.pts *= ist->ts_scale;
3968         if (pkt.dts != AV_NOPTS_VALUE)
3969             pkt.dts *= ist->ts_scale;
3970
3971         if (debug_ts) {
3972             av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3973                     "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s  pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",
3974                     ist_index, av_get_media_type_string(ist->st->codec->codec_type),
3975                     av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
3976                     av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
3977                     av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3978                     av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3979                     input_files[ist->file_index]->ts_offset);
3980         }
3981
3982         if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
3983             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3984             int64_t delta   = pkt_dts - ist->next_dts;
3985             if (is->iformat->flags & AVFMT_TS_DISCONT) {
3986             if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3987                 (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3988                  ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3989                 pkt_dts+1<ist->pts){
3990                 input_files[ist->file_index]->ts_offset -= delta;
3991                 av_log(NULL, AV_LOG_DEBUG,
3992                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3993                        delta, input_files[ist->file_index]->ts_offset);
3994                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3995                 if (pkt.pts != AV_NOPTS_VALUE)
3996                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3997             }
3998             } else {
3999                 if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
4000                     (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
4001                      pkt_dts+1<ist->pts){
4002                     av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
4003                     pkt.dts = AV_NOPTS_VALUE;
4004                 }
4005                 if (pkt.pts != AV_NOPTS_VALUE){
4006                     int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
4007                     delta   = pkt_pts - ist->next_dts;
4008                     if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
4009                         (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
4010                         pkt_pts+1<ist->pts) {
4011                         av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
4012                         pkt.pts = AV_NOPTS_VALUE;
4013                     }
4014                 }
4015             }
4016         }
4017
4018         sub2video_heartbeat(ist, pkt.pts);
4019
4020         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
4021         if ((ret = output_packet(ist, &pkt)) < 0 ||
4022             ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
4023             char buf[128];
4024             av_strerror(ret, buf, sizeof(buf));
4025             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
4026                    ist->file_index, ist->st->index, buf);
4027             if (exit_on_error)
4028                 exit_program(1);
4029             av_free_packet(&pkt);
4030             continue;
4031         }
4032
4033     discard_packet:
4034         av_free_packet(&pkt);
4035
4036         /* dump report by using the output first video and audio streams */
4037         print_report(0, timer_start, cur_time);
4038     }
4039 #if HAVE_PTHREADS
4040     free_input_threads();
4041 #endif
4042
4043     /* at the end of stream, we must flush the decoder buffers */
4044     for (i = 0; i < nb_input_streams; i++) {
4045         ist = input_streams[i];
4046         if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
4047             output_packet(ist, NULL);
4048         }
4049     }
4050     poll_filters();
4051     flush_encoders();
4052
4053     term_exit();
4054
4055     /* write the trailer if needed and close file */
4056     for (i = 0; i < nb_output_files; i++) {
4057         os = output_files[i]->ctx;
4058         av_write_trailer(os);
4059     }
4060
4061     /* dump report by using the first video and audio streams */
4062     print_report(1, timer_start, av_gettime());
4063
4064     /* close each encoder */
4065     for (i = 0; i < nb_output_streams; i++) {
4066         ost = output_streams[i];
4067         if (ost->encoding_needed) {
4068             av_freep(&ost->st->codec->stats_in);
4069             avcodec_close(ost->st->codec);
4070         }
4071     }
4072
4073     /* close each decoder */
4074     for (i = 0; i < nb_input_streams; i++) {
4075         ist = input_streams[i];
4076         if (ist->decoding_needed) {
4077             avcodec_close(ist->st->codec);
4078         }
4079     }
4080
4081     /* finished ! */
4082     ret = 0;
4083
4084  fail:
4085 #if HAVE_PTHREADS
4086     free_input_threads();
4087 #endif
4088
4089     if (output_streams) {
4090         for (i = 0; i < nb_output_streams; i++) {
4091             ost = output_streams[i];
4092             if (ost) {
4093                 if (ost->stream_copy)
4094                     av_freep(&ost->st->codec->extradata);
4095                 if (ost->logfile) {
4096                     fclose(ost->logfile);
4097                     ost->logfile = NULL;
4098                 }
4099                 av_freep(&ost->st->codec->subtitle_header);
4100                 av_free(ost->forced_kf_pts);
4101                 av_dict_free(&ost->opts);
4102             }
4103         }
4104     }
4105     return ret;
4106 }
4107
4108 static int opt_frame_crop(const char *opt, const char *arg)
4109 {
4110     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the crop filter instead\n", opt);
4111     return AVERROR(EINVAL);
4112 }
4113
4114 static int opt_pad(const char *opt, const char *arg)
4115 {
4116     av_log(NULL, AV_LOG_FATAL, "Option '%s' has been removed, use the pad filter instead\n", opt);
4117     return -1;
4118 }
4119
4120 static int opt_video_channel(const char *opt, const char *arg)
4121 {
4122     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -channel.\n");
4123     return opt_default("channel", arg);
4124 }
4125
4126 static int opt_video_standard(const char *opt, const char *arg)
4127 {
4128     av_log(NULL, AV_LOG_WARNING, "This option is deprecated, use -standard.\n");
4129     return opt_default("standard", arg);
4130 }
4131
4132 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
4133 {
4134     audio_codec_name = arg;
4135     return parse_option(o, "codec:a", arg, options);
4136 }
4137
4138 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
4139 {
4140     video_codec_name = arg;
4141     return parse_option(o, "codec:v", arg, options);
4142 }
4143
4144 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
4145 {
4146     subtitle_codec_name = arg;
4147     return parse_option(o, "codec:s", arg, options);
4148 }
4149
4150 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
4151 {
4152     return parse_option(o, "codec:d", arg, options);
4153 }
4154
4155 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
4156 {
4157     StreamMap *m = NULL;
4158     int i, negative = 0, file_idx;
4159     int sync_file_idx = -1, sync_stream_idx = 0;
4160     char *p, *sync;
4161     char *map;
4162
4163     if (*arg == '-') {
4164         negative = 1;
4165         arg++;
4166     }
4167     map = av_strdup(arg);
4168
4169     /* parse sync stream first, just pick first matching stream */
4170     if (sync = strchr(map, ',')) {
4171         *sync = 0;
4172         sync_file_idx = strtol(sync + 1, &sync, 0);
4173         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
4174             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
4175             exit_program(1);
4176         }
4177         if (*sync)
4178             sync++;
4179         for (i = 0; i < input_files[sync_file_idx]->nb_streams; i++)
4180             if (check_stream_specifier(input_files[sync_file_idx]->ctx,
4181                                        input_files[sync_file_idx]->ctx->streams[i], sync) == 1) {
4182                 sync_stream_idx = i;
4183                 break;
4184             }
4185         if (i == input_files[sync_file_idx]->nb_streams) {
4186             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
4187                                        "match any streams.\n", arg);
4188             exit_program(1);
4189         }
4190     }
4191
4192
4193     if (map[0] == '[') {
4194         /* this mapping refers to lavfi output */
4195         const char *c = map + 1;
4196         o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
4197                                     &o->nb_stream_maps, o->nb_stream_maps + 1);
4198         m = &o->stream_maps[o->nb_stream_maps - 1];
4199         m->linklabel = av_get_token(&c, "]");
4200         if (!m->linklabel) {
4201             av_log(NULL, AV_LOG_ERROR, "Invalid output link label: %s.\n", map);
4202             exit_program(1);
4203         }
4204     } else {
4205         file_idx = strtol(map, &p, 0);
4206         if (file_idx >= nb_input_files || file_idx < 0) {
4207             av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
4208             exit_program(1);
4209         }
4210         if (negative)
4211             /* disable some already defined maps */
4212             for (i = 0; i < o->nb_stream_maps; i++) {
4213                 m = &o->stream_maps[i];
4214                 if (file_idx == m->file_index &&
4215                     check_stream_specifier(input_files[m->file_index]->ctx,
4216                                            input_files[m->file_index]->ctx->streams[m->stream_index],
4217                                            *p == ':' ? p + 1 : p) > 0)
4218                     m->disabled = 1;
4219             }
4220         else
4221             for (i = 0; i < input_files[file_idx]->nb_streams; i++) {
4222                 if (check_stream_specifier(input_files[file_idx]->ctx, input_files[file_idx]->ctx->streams[i],
4223                             *p == ':' ? p + 1 : p) <= 0)
4224                     continue;
4225                 o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
4226                                             &o->nb_stream_maps, o->nb_stream_maps + 1);
4227                 m = &o->stream_maps[o->nb_stream_maps - 1];
4228
4229                 m->file_index   = file_idx;
4230                 m->stream_index = i;
4231
4232                 if (sync_file_idx >= 0) {
4233                     m->sync_file_index   = sync_file_idx;
4234                     m->sync_stream_index = sync_stream_idx;
4235                 } else {
4236                     m->sync_file_index   = file_idx;
4237                     m->sync_stream_index = i;
4238                 }
4239             }
4240     }
4241
4242     if (!m) {
4243         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
4244         exit_program(1);
4245     }
4246
4247     av_freep(&map);
4248     return 0;
4249 }
4250
4251 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
4252 {
4253     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
4254                                 &o->nb_attachments, o->nb_attachments + 1);
4255     o->attachments[o->nb_attachments - 1] = arg;
4256     return 0;
4257 }
4258
4259 static int opt_map_channel(OptionsContext *o, const char *opt, const char *arg)
4260 {
4261     int n;
4262     AVStream *st;
4263     AudioChannelMap *m;
4264
4265     o->audio_channel_maps =
4266         grow_array(o->audio_channel_maps, sizeof(*o->audio_channel_maps),
4267                    &o->nb_audio_channel_maps, o->nb_audio_channel_maps + 1);
4268     m = &o->audio_channel_maps[o->nb_audio_channel_maps - 1];
4269
4270     /* muted channel syntax */
4271     n = sscanf(arg, "%d:%d.%d", &m->channel_idx, &m->ofile_idx, &m->ostream_idx);
4272     if ((n == 1 || n == 3) && m->channel_idx == -1) {
4273         m->file_idx = m->stream_idx = -1;
4274         if (n == 1)
4275             m->ofile_idx = m->ostream_idx = -1;
4276         return 0;
4277     }
4278
4279     /* normal syntax */
4280     n = sscanf(arg, "%d.%d.%d:%d.%d",
4281                &m->file_idx,  &m->stream_idx, &m->channel_idx,
4282                &m->ofile_idx, &m->ostream_idx);
4283
4284     if (n != 3 && n != 5) {
4285         av_log(NULL, AV_LOG_FATAL, "Syntax error, mapchan usage: "
4286                "[file.stream.channel|-1][:syncfile:syncstream]\n");
4287         exit_program(1);
4288     }
4289
4290     if (n != 5) // only file.stream.channel specified
4291         m->ofile_idx = m->ostream_idx = -1;
4292
4293     /* check input */
4294     if (m->file_idx < 0 || m->file_idx >= nb_input_files) {
4295         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file index: %d\n",
4296                m->file_idx);
4297         exit_program(1);
4298     }
4299     if (m->stream_idx < 0 ||
4300         m->stream_idx >= input_files[m->file_idx]->nb_streams) {
4301         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid input file stream index #%d.%d\n",
4302                m->file_idx, m->stream_idx);
4303         exit_program(1);
4304     }
4305     st = input_files[m->file_idx]->ctx->streams[m->stream_idx];
4306     if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
4307         av_log(NULL, AV_LOG_FATAL, "mapchan: stream #%d.%d is not an audio stream.\n",
4308                m->file_idx, m->stream_idx);
4309         exit_program(1);
4310     }
4311     if (m->channel_idx < 0 || m->channel_idx >= st->codec->channels) {
4312         av_log(NULL, AV_LOG_FATAL, "mapchan: invalid audio channel #%d.%d.%d\n",
4313                m->file_idx, m->stream_idx, m->channel_idx);
4314         exit_program(1);
4315     }
4316     return 0;
4317 }
4318
4319 /**
4320  * Parse a metadata specifier in arg.
4321  * @param type metadata type is written here -- g(lobal)/s(tream)/c(hapter)/p(rogram)
4322  * @param index for type c/p, chapter/program index is written here
4323  * @param stream_spec for type s, the stream specifier is written here
4324  */
4325 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
4326 {
4327     if (*arg) {
4328         *type = *arg;
4329         switch (*arg) {
4330         case 'g':
4331             break;
4332         case 's':
4333             if (*(++arg) && *arg != ':') {
4334                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
4335                 exit_program(1);
4336             }
4337             *stream_spec = *arg == ':' ? arg + 1 : "";
4338             break;
4339         case 'c':
4340         case 'p':
4341             if (*(++arg) == ':')
4342                 *index = strtol(++arg, NULL, 0);
4343             break;
4344         default:
4345             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
4346             exit_program(1);
4347         }
4348     } else
4349         *type = 'g';
4350 }
4351
4352 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
4353 {
4354     AVDictionary **meta_in = NULL;
4355     AVDictionary **meta_out = NULL;
4356     int i, ret = 0;
4357     char type_in, type_out;
4358     const char *istream_spec = NULL, *ostream_spec = NULL;
4359     int idx_in = 0, idx_out = 0;
4360
4361     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
4362     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
4363
4364     if (!ic) {
4365         if (type_out == 'g' || !*outspec)
4366             o->metadata_global_manual = 1;
4367         if (type_out == 's' || !*outspec)
4368             o->metadata_streams_manual = 1;
4369         if (type_out == 'c' || !*outspec)
4370             o->metadata_chapters_manual = 1;
4371         return 0;
4372     }
4373
4374     if (type_in == 'g' || type_out == 'g')
4375         o->metadata_global_manual = 1;
4376     if (type_in == 's' || type_out == 's')
4377         o->metadata_streams_manual = 1;
4378     if (type_in == 'c' || type_out == 'c')
4379         o->metadata_chapters_manual = 1;
4380
4381 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
4382     if ((index) < 0 || (index) >= (nb_elems)) {\
4383         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
4384                 (desc), (index));\
4385         exit_program(1);\
4386     }
4387
4388 #define SET_DICT(type, meta, context, index)\
4389         switch (type) {\
4390         case 'g':\
4391             meta = &context->metadata;\
4392             break;\
4393         case 'c':\
4394             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
4395             meta = &context->chapters[index]->metadata;\
4396             break;\
4397         case 'p':\
4398             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
4399             meta = &context->programs[index]->metadata;\
4400             break;\
4401         default: av_assert0(0);\
4402         }\
4403
4404     SET_DICT(type_in, meta_in, ic, idx_in);
4405     SET_DICT(type_out, meta_out, oc, idx_out);
4406
4407     /* for input streams choose first matching stream */
4408     if (type_in == 's') {
4409         for (i = 0; i < ic->nb_streams; i++) {
4410             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
4411                 meta_in = &ic->streams[i]->metadata;
4412                 break;
4413             } else if (ret < 0)
4414                 exit_program(1);
4415         }
4416         if (!meta_in) {
4417             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
4418             exit_program(1);
4419         }
4420     }
4421
4422     if (type_out == 's') {
4423         for (i = 0; i < oc->nb_streams; i++) {
4424             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
4425                 meta_out = &oc->streams[i]->metadata;
4426                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4427             } else if (ret < 0)
4428                 exit_program(1);
4429         }
4430     } else
4431         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
4432
4433     return 0;
4434 }
4435
4436 static int opt_recording_timestamp(OptionsContext *o, const char *opt, const char *arg)
4437 {
4438     char buf[128];
4439     int64_t recording_timestamp = parse_time_or_die(opt, arg, 0) / 1E6;
4440     struct tm time = *gmtime((time_t*)&recording_timestamp);
4441     strftime(buf, sizeof(buf), "creation_time=%FT%T%z", &time);
4442     parse_option(o, "metadata", buf, options);
4443
4444     av_log(NULL, AV_LOG_WARNING, "%s is deprecated, set the 'creation_time' metadata "
4445                                  "tag instead.\n", opt);
4446     return 0;
4447 }
4448
4449 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
4450 {
4451     const char *codec_string = encoder ? "encoder" : "decoder";
4452     AVCodec *codec;
4453
4454     codec = encoder ?
4455         avcodec_find_encoder_by_name(name) :
4456         avcodec_find_decoder_by_name(name);
4457     if (!codec) {
4458         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
4459         exit_program(1);
4460     }
4461     if (codec->type != type) {
4462         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
4463         exit_program(1);
4464     }
4465     return codec;
4466 }
4467
4468 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
4469 {
4470     char *codec_name = NULL;
4471
4472     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
4473     if (codec_name) {
4474         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
4475         st->codec->codec_id = codec->id;
4476         return codec;
4477     } else
4478         return avcodec_find_decoder(st->codec->codec_id);
4479 }
4480
4481 /**
4482  * Add all the streams from the given input file to the global
4483  * list of input streams.
4484  */
4485 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
4486 {
4487     int i;
4488     char *next, *codec_tag = NULL;
4489
4490     for (i = 0; i < ic->nb_streams; i++) {
4491         AVStream *st = ic->streams[i];
4492         AVCodecContext *dec = st->codec;
4493         InputStream *ist = av_mallocz(sizeof(*ist));
4494         char *framerate = NULL;
4495
4496         if (!ist)
4497             exit_program(1);
4498
4499         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
4500         input_streams[nb_input_streams - 1] = ist;
4501
4502         ist->st = st;
4503         ist->file_index = nb_input_files;
4504         ist->discard = 1;
4505         st->discard  = AVDISCARD_ALL;
4506         ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st, choose_decoder(o, ic, st));
4507
4508         ist->ts_scale = 1.0;
4509         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
4510
4511         MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);
4512         if (codec_tag) {
4513             uint32_t tag = strtol(codec_tag, &next, 0);
4514             if (*next)
4515                 tag = AV_RL32(codec_tag);
4516             st->codec->codec_tag = tag;
4517         }
4518
4519         ist->dec = choose_decoder(o, ic, st);
4520
4521         switch (dec->codec_type) {
4522         case AVMEDIA_TYPE_VIDEO:
4523             if(!ist->dec)
4524                 ist->dec = avcodec_find_decoder(dec->codec_id);
4525             if (dec->lowres) {
4526                 dec->flags |= CODEC_FLAG_EMU_EDGE;
4527             }
4528
4529             ist->resample_height  = dec->height;
4530             ist->resample_width   = dec->width;
4531             ist->resample_pix_fmt = dec->pix_fmt;
4532
4533             MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);
4534             if (framerate && av_parse_video_rate(&ist->framerate,
4535                                                  framerate) < 0) {
4536                 av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",
4537                        framerate);
4538                 exit_program(1);
4539             }
4540
4541             ist->top_field_first = -1;
4542             MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);
4543
4544             break;
4545         case AVMEDIA_TYPE_AUDIO:
4546             guess_input_channel_layout(ist);
4547
4548             ist->resample_sample_fmt     = dec->sample_fmt;
4549             ist->resample_sample_rate    = dec->sample_rate;
4550             ist->resample_channels       = dec->channels;
4551             ist->resample_channel_layout = dec->channel_layout;
4552
4553             break;
4554         case AVMEDIA_TYPE_DATA:
4555         case AVMEDIA_TYPE_SUBTITLE:
4556             if(!ist->dec)
4557                 ist->dec = avcodec_find_decoder(dec->codec_id);
4558             break;
4559         case AVMEDIA_TYPE_ATTACHMENT:
4560         case AVMEDIA_TYPE_UNKNOWN:
4561             break;
4562         default:
4563             abort();
4564         }
4565     }
4566 }
4567
4568 static void assert_file_overwrite(const char *filename)
4569 {
4570     if ((!file_overwrite || no_file_overwrite) &&
4571         (strchr(filename, ':') == NULL || filename[1] == ':' ||
4572          av_strstart(filename, "file:", NULL))) {
4573         if (avio_check(filename, 0) == 0) {
4574             if (stdin_interaction && (!no_file_overwrite || file_overwrite)) {
4575                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
4576                 fflush(stderr);
4577                 term_exit();
4578                 signal(SIGINT, SIG_DFL);
4579                 if (!read_yesno()) {
4580                     av_log(NULL, AV_LOG_FATAL, "Not overwriting - exiting\n");
4581                     exit_program(1);
4582                 }
4583                 term_init();
4584             }
4585             else {
4586                 av_log(NULL, AV_LOG_FATAL, "File '%s' already exists. Exiting.\n", filename);
4587                 exit_program(1);
4588             }
4589         }
4590     }
4591 }
4592
4593 static void dump_attachment(AVStream *st, const char *filename)
4594 {
4595     int ret;
4596     AVIOContext *out = NULL;
4597     AVDictionaryEntry *e;
4598
4599     if (!st->codec->extradata_size) {
4600         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
4601                nb_input_files - 1, st->index);
4602         return;
4603     }
4604     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
4605         filename = e->value;
4606     if (!*filename) {
4607         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
4608                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
4609         exit_program(1);
4610     }
4611
4612     assert_file_overwrite(filename);
4613
4614     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
4615         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
4616                filename);
4617         exit_program(1);
4618     }
4619
4620     avio_write(out, st->codec->extradata, st->codec->extradata_size);
4621     avio_flush(out);
4622     avio_close(out);
4623 }
4624
4625 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
4626 {
4627     AVFormatContext *ic;
4628     AVInputFormat *file_iformat = NULL;
4629     int err, i, ret;
4630     int64_t timestamp;
4631     uint8_t buf[128];
4632     AVDictionary **opts;
4633     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
4634
4635     if (o->format) {
4636         if (!(file_iformat = av_find_input_format(o->format))) {
4637             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
4638             exit_program(1);
4639         }
4640     }
4641
4642     if (!strcmp(filename, "-"))
4643         filename = "pipe:";
4644
4645     stdin_interaction &= strncmp(filename, "pipe:", 5) &&
4646                          strcmp(filename, "/dev/stdin");
4647
4648     /* get default parameters from command line */
4649     ic = avformat_alloc_context();
4650     if (!ic) {
4651         print_error(filename, AVERROR(ENOMEM));
4652         exit_program(1);
4653     }
4654     if (o->nb_audio_sample_rate) {
4655         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
4656         av_dict_set(&format_opts, "sample_rate", buf, 0);
4657     }
4658     if (o->nb_audio_channels) {
4659         /* because we set audio_channels based on both the "ac" and
4660          * "channel_layout" options, we need to check that the specified
4661          * demuxer actually has the "channels" option before setting it */
4662         if (file_iformat && file_iformat->priv_class &&
4663             av_opt_find(&file_iformat->priv_class, "channels", NULL, 0,
4664                         AV_OPT_SEARCH_FAKE_OBJ)) {
4665             snprintf(buf, sizeof(buf), "%d",
4666                      o->audio_channels[o->nb_audio_channels - 1].u.i);
4667             av_dict_set(&format_opts, "channels", buf, 0);
4668         }
4669     }
4670     if (o->nb_frame_rates) {
4671         /* set the format-level framerate option;
4672          * this is important for video grabbers, e.g. x11 */
4673         if (file_iformat && file_iformat->priv_class &&
4674             av_opt_find(&file_iformat->priv_class, "framerate", NULL, 0,
4675                         AV_OPT_SEARCH_FAKE_OBJ)) {
4676             av_dict_set(&format_opts, "framerate",
4677                         o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
4678         }
4679     }
4680     if (o->nb_frame_sizes) {
4681         av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
4682     }
4683     if (o->nb_frame_pix_fmts)
4684         av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
4685
4686     ic->video_codec_id   = video_codec_name ?
4687         find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0)->id : AV_CODEC_ID_NONE;
4688     ic->audio_codec_id   = audio_codec_name ?
4689         find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0)->id : AV_CODEC_ID_NONE;
4690     ic->subtitle_codec_id= subtitle_codec_name ?
4691         find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0)->id : AV_CODEC_ID_NONE;
4692     ic->flags |= AVFMT_FLAG_NONBLOCK;
4693     ic->interrupt_callback = int_cb;
4694
4695     /* open the input file with generic avformat function */
4696     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
4697     if (err < 0) {
4698         print_error(filename, err);
4699         exit_program(1);
4700     }
4701     assert_avoptions(format_opts);
4702
4703     /* apply forced codec ids */
4704     for (i = 0; i < ic->nb_streams; i++)
4705         choose_decoder(o, ic, ic->streams[i]);
4706
4707     /* Set AVCodecContext options for avformat_find_stream_info */
4708     opts = setup_find_stream_info_opts(ic, codec_opts);
4709     orig_nb_streams = ic->nb_streams;
4710
4711     /* If not enough info to get the stream parameters, we decode the
4712        first frames to get it. (used in mpeg case for example) */
4713     ret = avformat_find_stream_info(ic, opts);
4714     if (ret < 0) {
4715         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
4716         avformat_close_input(&ic);
4717         exit_program(1);
4718     }
4719
4720     timestamp = o->start_time;
4721     /* add the stream start time */
4722     if (ic->start_time != AV_NOPTS_VALUE)
4723         timestamp += ic->start_time;
4724
4725     /* if seeking requested, we execute it */
4726     if (o->start_time != 0) {
4727         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
4728         if (ret < 0) {
4729             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
4730                    filename, (double)timestamp / AV_TIME_BASE);
4731         }
4732     }
4733
4734     /* update the current parameters so that they match the one of the input stream */
4735     add_input_streams(o, ic);
4736
4737     /* dump the file content */
4738     av_dump_format(ic, nb_input_files, filename, 0);
4739
4740     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
4741     if (!(input_files[nb_input_files - 1] = av_mallocz(sizeof(*input_files[0]))))
4742         exit_program(1);
4743
4744     input_files[nb_input_files - 1]->ctx        = ic;
4745     input_files[nb_input_files - 1]->ist_index  = nb_input_streams - ic->nb_streams;
4746     input_files[nb_input_files - 1]->ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
4747     input_files[nb_input_files - 1]->nb_streams = ic->nb_streams;
4748     input_files[nb_input_files - 1]->rate_emu   = o->rate_emu;
4749
4750     for (i = 0; i < o->nb_dump_attachment; i++) {
4751         int j;
4752
4753         for (j = 0; j < ic->nb_streams; j++) {
4754             AVStream *st = ic->streams[j];
4755
4756             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
4757                 dump_attachment(st, o->dump_attachment[i].u.str);
4758         }
4759     }
4760
4761     for (i = 0; i < orig_nb_streams; i++)
4762         av_dict_free(&opts[i]);
4763     av_freep(&opts);
4764
4765     reset_options(o, 1);
4766     return 0;
4767 }
4768
4769 static uint8_t *get_line(AVIOContext *s)
4770 {
4771     AVIOContext *line;
4772     uint8_t *buf;
4773     char c;
4774
4775     if (avio_open_dyn_buf(&line) < 0) {
4776         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
4777         exit_program(1);
4778     }
4779
4780     while ((c = avio_r8(s)) && c != '\n')
4781         avio_w8(line, c);
4782     avio_w8(line, 0);
4783     avio_close_dyn_buf(line, &buf);
4784
4785     return buf;
4786 }
4787
4788 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
4789 {
4790     int i, ret = 1;
4791     char filename[1000];
4792     const char *base[3] = { getenv("AVCONV_DATADIR"),
4793                             getenv("HOME"),
4794                             AVCONV_DATADIR,
4795                             };
4796
4797     for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
4798         if (!base[i])
4799             continue;
4800         if (codec_name) {
4801             snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
4802                      i != 1 ? "" : "/.avconv", codec_name, preset_name);
4803             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
4804         }
4805         if (ret) {
4806             snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
4807                      i != 1 ? "" : "/.avconv", preset_name);
4808             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
4809         }
4810     }
4811     return ret;
4812 }
4813
4814 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
4815 {
4816     char *codec_name = NULL;
4817
4818     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
4819     if (!codec_name) {
4820         ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
4821                                                   NULL, ost->st->codec->codec_type);
4822         ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
4823     } else if (!strcmp(codec_name, "copy"))
4824         ost->stream_copy = 1;
4825     else {
4826         ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
4827         ost->st->codec->codec_id = ost->enc->id;
4828     }
4829 }
4830
4831 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type, int source_index)
4832 {
4833     OutputStream *ost;
4834     AVStream *st = avformat_new_stream(oc, NULL);
4835     int idx      = oc->nb_streams - 1, ret = 0;
4836     char *bsf = NULL, *next, *codec_tag = NULL;
4837     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
4838     double qscale = -1;
4839     char *buf = NULL, *arg = NULL, *preset = NULL;
4840     AVIOContext *s = NULL;
4841
4842     if (!st) {
4843         av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
4844         exit_program(1);
4845     }
4846
4847     if (oc->nb_streams - 1 < o->nb_streamid_map)
4848         st->id = o->streamid_map[oc->nb_streams - 1];
4849
4850     output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
4851                                 nb_output_streams + 1);
4852     if (!(ost = av_mallocz(sizeof(*ost))))
4853         exit_program(1);
4854     output_streams[nb_output_streams - 1] = ost;
4855
4856     ost->file_index = nb_output_files;
4857     ost->index      = idx;
4858     ost->st         = st;
4859     st->codec->codec_type = type;
4860     choose_encoder(o, oc, ost);
4861     if (ost->enc) {
4862         ost->opts  = filter_codec_opts(codec_opts, ost->enc->id, oc, st, ost->enc);
4863     }
4864
4865     avcodec_get_context_defaults3(st->codec, ost->enc);
4866     st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
4867
4868     MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
4869     if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
4870         do  {
4871             buf = get_line(s);
4872             if (!buf[0] || buf[0] == '#') {
4873                 av_free(buf);
4874                 continue;
4875             }
4876             if (!(arg = strchr(buf, '='))) {
4877                 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
4878                 exit_program(1);
4879             }
4880             *arg++ = 0;
4881             av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
4882             av_free(buf);
4883         } while (!s->eof_reached);
4884         avio_close(s);
4885     }
4886     if (ret) {
4887         av_log(NULL, AV_LOG_FATAL,
4888                "Preset %s specified for stream %d:%d, but could not be opened.\n",
4889                preset, ost->file_index, ost->index);
4890         exit_program(1);
4891     }
4892
4893     ost->max_frames = INT64_MAX;
4894     MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
4895
4896     MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
4897     while (bsf) {
4898         if (next = strchr(bsf, ','))
4899             *next++ = 0;
4900         if (!(bsfc = av_bitstream_filter_init(bsf))) {
4901             av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
4902             exit_program(1);
4903         }
4904         if (bsfc_prev)
4905             bsfc_prev->next = bsfc;
4906         else
4907             ost->bitstream_filters = bsfc;
4908
4909         bsfc_prev = bsfc;
4910         bsf       = next;
4911     }
4912
4913     MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
4914     if (codec_tag) {
4915         uint32_t tag = strtol(codec_tag, &next, 0);
4916         if (*next)
4917             tag = AV_RL32(codec_tag);
4918         st->codec->codec_tag = tag;
4919     }
4920
4921     MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
4922     if (qscale >= 0 || same_quant) {
4923         st->codec->flags |= CODEC_FLAG_QSCALE;
4924         st->codec->global_quality = FF_QP2LAMBDA * qscale;
4925     }
4926
4927     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
4928         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
4929
4930     av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
4931     av_opt_get_int   (swr_opts, "dither_method", 0, &ost->swr_dither_method);
4932     av_opt_get_double(swr_opts, "dither_scale" , 0, &ost->swr_dither_scale);
4933
4934     ost->source_index = source_index;
4935     if (source_index >= 0) {
4936         ost->sync_ist = input_streams[source_index];
4937         input_streams[source_index]->discard = 0;
4938         input_streams[source_index]->st->discard = AVDISCARD_NONE;
4939     }
4940
4941     return ost;
4942 }
4943
4944 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
4945 {
4946     int i;
4947     const char *p = str;
4948     for (i = 0;; i++) {
4949         dest[i] = atoi(p);
4950         if (i == 63)
4951             break;
4952         p = strchr(p, ',');
4953         if (!p) {
4954             av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
4955             exit_program(1);
4956         }
4957         p++;
4958     }
4959 }
4960
4961 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
4962 {
4963     AVStream *st;
4964     OutputStream *ost;
4965     AVCodecContext *video_enc;
4966     char *frame_rate = NULL;
4967
4968     ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO, source_index);
4969     st  = ost->st;
4970     video_enc = st->codec;
4971
4972     MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
4973     if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
4974         av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
4975         exit_program(1);
4976     }
4977
4978     if (!ost->stream_copy) {
4979         const char *p = NULL;
4980         char *frame_size = NULL;
4981         char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
4982         char *intra_matrix = NULL, *inter_matrix = NULL;
4983         const char *filters = "null";
4984         int i;
4985
4986         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
4987         if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
4988             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
4989             exit_program(1);
4990         }
4991
4992         MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
4993         if (frame_aspect_ratio) {
4994             AVRational q;
4995             if (av_parse_ratio(&q, frame_aspect_ratio, 255, 0, NULL) < 0 ||
4996                 q.num <= 0 || q.den <= 0) {
4997                 av_log(NULL, AV_LOG_FATAL, "Invalid aspect ratio: %s\n", frame_aspect_ratio);
4998                 exit_program(1);
4999             }
5000             ost->frame_aspect_ratio = av_q2d(q);
5001         }
5002
5003         video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
5004         MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
5005         if (frame_pix_fmt && *frame_pix_fmt == '+') {
5006             ost->keep_pix_fmt = 1;
5007             if (!*++frame_pix_fmt)
5008                 frame_pix_fmt = NULL;
5009         }
5010         if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
5011             av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
5012             exit_program(1);
5013         }
5014         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
5015
5016         if (intra_only)
5017             video_enc->gop_size = 0;
5018         MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
5019         if (intra_matrix) {
5020             if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
5021                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
5022                 exit_program(1);
5023             }
5024             parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
5025         }
5026         MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
5027         if (inter_matrix) {
5028             if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
5029                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
5030                 exit_program(1);
5031             }
5032             parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
5033         }
5034
5035         MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
5036         for (i = 0; p; i++) {
5037             int start, end, q;
5038             int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
5039             if (e != 3) {
5040                 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
5041                 exit_program(1);
5042             }
5043             /* FIXME realloc failure */
5044             video_enc->rc_override =
5045                 av_realloc(video_enc->rc_override,
5046                            sizeof(RcOverride) * (i + 1));
5047             video_enc->rc_override[i].start_frame = start;
5048             video_enc->rc_override[i].end_frame   = end;
5049             if (q > 0) {
5050                 video_enc->rc_override[i].qscale         = q;
5051                 video_enc->rc_override[i].quality_factor = 1.0;
5052             }
5053             else {
5054                 video_enc->rc_override[i].qscale         = 0;
5055                 video_enc->rc_override[i].quality_factor = -q/100.0;
5056             }
5057             p = strchr(p, '/');
5058             if (p) p++;
5059         }
5060         video_enc->rc_override_count = i;
5061         if (!video_enc->rc_initial_buffer_occupancy)
5062             video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
5063         video_enc->intra_dc_precision = intra_dc_precision - 8;
5064
5065         if (do_psnr)
5066             video_enc->flags|= CODEC_FLAG_PSNR;
5067
5068         /* two pass mode */
5069         if (do_pass) {
5070             if (do_pass & 1) {
5071                 video_enc->flags |= CODEC_FLAG_PASS1;
5072             }
5073             if (do_pass & 2) {
5074                 video_enc->flags |= CODEC_FLAG_PASS2;
5075             }
5076         }
5077
5078         MATCH_PER_STREAM_OPT(forced_key_frames, str, ost->forced_keyframes, oc, st);
5079         if (ost->forced_keyframes)
5080             ost->forced_keyframes = av_strdup(ost->forced_keyframes);
5081
5082         MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
5083
5084         ost->top_field_first = -1;
5085         MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
5086
5087         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
5088         ost->avfilter = av_strdup(filters);
5089     } else {
5090         MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
5091     }
5092
5093     return ost;
5094 }
5095
5096 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
5097 {
5098     int n;
5099     AVStream *st;
5100     OutputStream *ost;
5101     AVCodecContext *audio_enc;
5102
5103     ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);
5104     st  = ost->st;
5105
5106     audio_enc = st->codec;
5107     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
5108
5109     if (!ost->stream_copy) {
5110         char *sample_fmt = NULL;
5111         const char *filters = "anull";
5112
5113         MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
5114
5115         MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
5116         if (sample_fmt &&
5117             (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
5118             av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
5119             exit_program(1);
5120         }
5121
5122         MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
5123
5124         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
5125
5126         av_assert1(filters);
5127         ost->avfilter = av_strdup(filters);
5128
5129         /* check for channel mapping for this audio stream */
5130         for (n = 0; n < o->nb_audio_channel_maps; n++) {
5131             AudioChannelMap *map = &o->audio_channel_maps[n];
5132             InputStream *ist = input_streams[ost->source_index];
5133             if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&
5134                 (map->ofile_idx   == -1 || ost->file_index == map->ofile_idx) &&
5135                 (map->ostream_idx == -1 || ost->st->index  == map->ostream_idx)) {
5136                 if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))
5137                     ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;
5138                 else
5139                     av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",
5140                            ost->file_index, ost->st->index);
5141             }
5142         }
5143     }
5144
5145     return ost;
5146 }
5147
5148 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
5149 {
5150     OutputStream *ost;
5151
5152     ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA, source_index);
5153     if (!ost->stream_copy) {
5154         av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
5155         exit_program(1);
5156     }
5157
5158     return ost;
5159 }
5160
5161 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
5162 {
5163     OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT, source_index);
5164     ost->stream_copy = 1;
5165     return ost;
5166 }
5167
5168 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc, int source_index)
5169 {
5170     AVStream *st;
5171     OutputStream *ost;
5172     AVCodecContext *subtitle_enc;
5173
5174     ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE, source_index);
5175     st  = ost->st;
5176     subtitle_enc = st->codec;
5177
5178     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
5179
5180     MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc, st);
5181
5182     return ost;
5183 }
5184
5185 /* arg format is "output-stream-index:streamid-value". */
5186 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
5187 {
5188     int idx;
5189     char *p;
5190     char idx_str[16];
5191
5192     av_strlcpy(idx_str, arg, sizeof(idx_str));
5193     p = strchr(idx_str, ':');
5194     if (!p) {
5195         av_log(NULL, AV_LOG_FATAL,
5196                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
5197                arg, opt);
5198         exit_program(1);
5199     }
5200     *p++ = '\0';
5201     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
5202     o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
5203     o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
5204     return 0;
5205 }
5206
5207 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
5208 {
5209     AVFormatContext *is = ifile->ctx;
5210     AVFormatContext *os = ofile->ctx;
5211     int i;
5212
5213     for (i = 0; i < is->nb_chapters; i++) {
5214         AVChapter *in_ch = is->chapters[i], *out_ch;
5215         int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
5216                                        AV_TIME_BASE_Q, in_ch->time_base);
5217         int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
5218                            av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
5219
5220
5221         if (in_ch->end < ts_off)
5222             continue;
5223         if (rt != INT64_MAX && in_ch->start > rt + ts_off)
5224             break;
5225
5226         out_ch = av_mallocz(sizeof(AVChapter));
5227         if (!out_ch)
5228             return AVERROR(ENOMEM);
5229
5230         out_ch->id        = in_ch->id;
5231         out_ch->time_base = in_ch->time_base;
5232         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
5233         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
5234
5235         if (copy_metadata)
5236             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
5237
5238         os->nb_chapters++;
5239         os->chapters = av_realloc_f(os->chapters, os->nb_chapters, sizeof(AVChapter));
5240         if (!os->chapters)
5241             return AVERROR(ENOMEM);
5242         os->chapters[os->nb_chapters - 1] = out_ch;
5243     }
5244     return 0;
5245 }
5246
5247 static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
5248 {
5249     int i, err;
5250     AVFormatContext *ic = avformat_alloc_context();
5251
5252     ic->interrupt_callback = int_cb;
5253     err = avformat_open_input(&ic, filename, NULL, NULL);
5254     if (err < 0)
5255         return err;
5256     /* copy stream format */
5257     for(i=0;i<ic->nb_streams;i++) {
5258         AVStream *st;
5259         OutputStream *ost;
5260         AVCodec *codec;
5261         AVCodecContext *avctx;
5262
5263         codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
5264         ost   = new_output_stream(o, s, codec->type, -1);
5265         st    = ost->st;
5266         avctx = st->codec;
5267         ost->enc = codec;
5268
5269         // FIXME: a more elegant solution is needed
5270         memcpy(st, ic->streams[i], sizeof(AVStream));
5271         st->cur_dts = 0;
5272         st->info = av_malloc(sizeof(*st->info));
5273         memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
5274         st->codec= avctx;
5275         avcodec_copy_context(st->codec, ic->streams[i]->codec);
5276
5277         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)
5278             choose_sample_fmt(st, codec);
5279         else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)
5280             choose_pixel_fmt(st, codec, st->codec->pix_fmt);
5281     }
5282
5283     avformat_close_input(&ic);
5284     return 0;
5285 }
5286
5287 static void init_output_filter(OutputFilter *ofilter, OptionsContext *o,
5288                                AVFormatContext *oc)
5289 {
5290     OutputStream *ost;
5291
5292     switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
5293                                   ofilter->out_tmp->pad_idx)) {
5294     case AVMEDIA_TYPE_VIDEO: ost = new_video_stream(o, oc, -1); break;
5295     case AVMEDIA_TYPE_AUDIO: ost = new_audio_stream(o, oc, -1); break;
5296     default:
5297         av_log(NULL, AV_LOG_FATAL, "Only video and audio filters are supported "
5298                "currently.\n");
5299         exit_program(1);
5300     }
5301
5302     ost->source_index = -1;
5303     ost->filter       = ofilter;
5304
5305     ofilter->ost      = ost;
5306
5307     if (ost->stream_copy) {
5308         av_log(NULL, AV_LOG_ERROR, "Streamcopy requested for output stream %d:%d, "
5309                "which is fed from a complex filtergraph. Filtering and streamcopy "
5310                "cannot be used together.\n", ost->file_index, ost->index);
5311         exit_program(1);
5312     }
5313     if (o->recording_time != INT64_MAX)
5314         av_log(NULL, AV_LOG_WARNING,
5315                "-t does not work with -filter_complex (yet).\n");
5316
5317     if (configure_output_filter(ofilter->graph, ofilter, ofilter->out_tmp) < 0) {
5318         av_log(NULL, AV_LOG_FATAL, "Error configuring filter.\n");
5319         exit_program(1);
5320     }
5321     avfilter_inout_free(&ofilter->out_tmp);
5322 }
5323
5324 static void opt_output_file(void *optctx, const char *filename)
5325 {
5326     OptionsContext *o = optctx;
5327     AVFormatContext *oc;
5328     int i, j, err;
5329     AVOutputFormat *file_oformat;
5330     OutputStream *ost;
5331     InputStream  *ist;
5332
5333     if (configure_complex_filters() < 0) {
5334         av_log(NULL, AV_LOG_FATAL, "Error configuring filters.\n");
5335         exit_program(1);
5336     }
5337
5338     if (!strcmp(filename, "-"))
5339         filename = "pipe:";
5340
5341     err = avformat_alloc_output_context2(&oc, NULL, o->format, filename);
5342     if (!oc) {
5343         print_error(filename, err);
5344         exit_program(1);
5345     }
5346     file_oformat= oc->oformat;
5347     oc->interrupt_callback = int_cb;
5348
5349     /* create streams for all unlabeled output pads */
5350     for (i = 0; i < nb_filtergraphs; i++) {
5351         FilterGraph *fg = filtergraphs[i];
5352         for (j = 0; j < fg->nb_outputs; j++) {
5353             OutputFilter *ofilter = fg->outputs[j];
5354
5355             if (!ofilter->out_tmp || ofilter->out_tmp->name)
5356                 continue;
5357
5358             switch (avfilter_pad_get_type(ofilter->out_tmp->filter_ctx->output_pads,
5359                                           ofilter->out_tmp->pad_idx)) {
5360             case AVMEDIA_TYPE_VIDEO:    o->video_disable    = 1; break;
5361             case AVMEDIA_TYPE_AUDIO:    o->audio_disable    = 1; break;
5362             case AVMEDIA_TYPE_SUBTITLE: o->subtitle_disable = 1; break;
5363             }
5364             init_output_filter(ofilter, o, oc);
5365         }
5366     }
5367
5368     if (!strcmp(file_oformat->name, "ffm") &&
5369         av_strstart(filename, "http:", NULL)) {
5370         int j;
5371         /* special case for files sent to ffserver: we get the stream
5372            parameters from ffserver */
5373         int err = read_ffserver_streams(o, oc, filename);
5374         if (err < 0) {
5375             print_error(filename, err);
5376             exit_program(1);
5377         }
5378         for(j = nb_output_streams - oc->nb_streams; j < nb_output_streams; j++) {
5379             ost = output_streams[j];
5380             for (i = 0; i < nb_input_streams; i++) {
5381                 ist = input_streams[i];
5382                 if(ist->st->codec->codec_type == ost->st->codec->codec_type){
5383                     ost->sync_ist= ist;
5384                     ost->source_index= i;
5385                     if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) ost->avfilter = av_strdup("anull");
5386                     if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) ost->avfilter = av_strdup("null");
5387                     ist->discard = 0;
5388                     ist->st->discard = AVDISCARD_NONE;
5389                     break;
5390                 }
5391             }
5392             if(!ost->sync_ist){
5393                 av_log(NULL, AV_LOG_FATAL, "Missing %s stream which is required by this ffm\n", av_get_media_type_string(ost->st->codec->codec_type));
5394                 exit_program(1);
5395             }
5396         }
5397     } else if (!o->nb_stream_maps) {
5398         /* pick the "best" stream of each type */
5399
5400         /* video: highest resolution */
5401         if (!o->video_disable && oc->oformat->video_codec != AV_CODEC_ID_NONE) {
5402             int area = 0, idx = -1;
5403             for (i = 0; i < nb_input_streams; i++) {
5404                 ist = input_streams[i];
5405                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
5406                     ist->st->codec->width * ist->st->codec->height > area) {
5407                     area = ist->st->codec->width * ist->st->codec->height;
5408                     idx = i;
5409                 }
5410             }
5411             if (idx >= 0)
5412                 new_video_stream(o, oc, idx);
5413         }
5414
5415         /* audio: most channels */
5416         if (!o->audio_disable && oc->oformat->audio_codec != AV_CODEC_ID_NONE) {
5417             int channels = 0, idx = -1;
5418             for (i = 0; i < nb_input_streams; i++) {
5419                 ist = input_streams[i];
5420                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
5421                     ist->st->codec->channels > channels) {
5422                     channels = ist->st->codec->channels;
5423                     idx = i;
5424                 }
5425             }
5426             if (idx >= 0)
5427                 new_audio_stream(o, oc, idx);
5428         }
5429
5430         /* subtitles: pick first */
5431         if (!o->subtitle_disable && (oc->oformat->subtitle_codec != AV_CODEC_ID_NONE || subtitle_codec_name)) {
5432             for (i = 0; i < nb_input_streams; i++)
5433                 if (input_streams[i]->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
5434                     new_subtitle_stream(o, oc, i);
5435                     break;
5436                 }
5437         }
5438         /* do something with data? */
5439     } else {
5440         for (i = 0; i < o->nb_stream_maps; i++) {
5441             StreamMap *map = &o->stream_maps[i];
5442             int src_idx = input_files[map->file_index]->ist_index + map->stream_index;
5443
5444             if (map->disabled)
5445                 continue;
5446
5447             if (map->linklabel) {
5448                 FilterGraph *fg;
5449                 OutputFilter *ofilter = NULL;
5450                 int j, k;
5451
5452                 for (j = 0; j < nb_filtergraphs; j++) {
5453                     fg = filtergraphs[j];
5454                     for (k = 0; k < fg->nb_outputs; k++) {
5455                         AVFilterInOut *out = fg->outputs[k]->out_tmp;
5456                         if (out && !strcmp(out->name, map->linklabel)) {
5457                             ofilter = fg->outputs[k];
5458                             goto loop_end;
5459                         }
5460                     }
5461                 }
5462 loop_end:
5463                 if (!ofilter) {
5464                     av_log(NULL, AV_LOG_FATAL, "Output with label '%s' does not exist "
5465                            "in any defined filter graph.\n", map->linklabel);
5466                     exit_program(1);
5467                 }
5468                 init_output_filter(ofilter, o, oc);
5469             } else {
5470                 ist = input_streams[input_files[map->file_index]->ist_index + map->stream_index];
5471                 if(o->subtitle_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE)
5472                     continue;
5473                 if(o->   audio_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
5474                     continue;
5475                 if(o->   video_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
5476                     continue;
5477                 if(o->    data_disable && ist->st->codec->codec_type == AVMEDIA_TYPE_DATA)
5478                     continue;
5479
5480                 switch (ist->st->codec->codec_type) {
5481                 case AVMEDIA_TYPE_VIDEO:      ost = new_video_stream     (o, oc, src_idx); break;
5482                 case AVMEDIA_TYPE_AUDIO:      ost = new_audio_stream     (o, oc, src_idx); break;
5483                 case AVMEDIA_TYPE_SUBTITLE:   ost = new_subtitle_stream  (o, oc, src_idx); break;
5484                 case AVMEDIA_TYPE_DATA:       ost = new_data_stream      (o, oc, src_idx); break;
5485                 case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc, src_idx); break;
5486                 default:
5487                     av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
5488                            map->file_index, map->stream_index);
5489                     exit_program(1);
5490                 }
5491             }
5492         }
5493     }
5494
5495
5496     for (i = nb_output_streams - oc->nb_streams; i < nb_output_streams; i++) { //for all streams of this output file
5497         AVDictionaryEntry *e;
5498         ost = output_streams[i];
5499
5500         if (   ost->stream_copy
5501             && (e = av_dict_get(codec_opts, "flags", NULL, AV_DICT_IGNORE_SUFFIX))
5502             && (!e->key[5] || check_stream_specifier(oc, ost->st, e->key+6)))
5503             if (av_opt_set(ost->st->codec, "flags", e->value, 0) < 0)
5504                 exit_program(1);
5505     }
5506
5507     /* handle attached files */
5508     for (i = 0; i < o->nb_attachments; i++) {
5509         AVIOContext *pb;
5510         uint8_t *attachment;
5511         const char *p;
5512         int64_t len;
5513
5514         if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
5515             av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
5516                    o->attachments[i]);
5517             exit_program(1);
5518         }
5519         if ((len = avio_size(pb)) <= 0) {
5520             av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
5521                    o->attachments[i]);
5522             exit_program(1);
5523         }
5524         if (!(attachment = av_malloc(len))) {
5525             av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
5526                    o->attachments[i]);
5527             exit_program(1);
5528         }
5529         avio_read(pb, attachment, len);
5530
5531         ost = new_attachment_stream(o, oc, -1);
5532         ost->stream_copy               = 0;
5533         ost->attachment_filename       = o->attachments[i];
5534         ost->st->codec->extradata      = attachment;
5535         ost->st->codec->extradata_size = len;
5536
5537         p = strrchr(o->attachments[i], '/');
5538         av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
5539         avio_close(pb);
5540     }
5541
5542     output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
5543     if (!(output_files[nb_output_files - 1] = av_mallocz(sizeof(*output_files[0]))))
5544         exit_program(1);
5545
5546     output_files[nb_output_files - 1]->ctx            = oc;
5547     output_files[nb_output_files - 1]->ost_index      = nb_output_streams - oc->nb_streams;
5548     output_files[nb_output_files - 1]->recording_time = o->recording_time;
5549     if (o->recording_time != INT64_MAX)
5550         oc->duration = o->recording_time;
5551     output_files[nb_output_files - 1]->start_time     = o->start_time;
5552     output_files[nb_output_files - 1]->limit_filesize = o->limit_filesize;
5553     av_dict_copy(&output_files[nb_output_files - 1]->opts, format_opts, 0);
5554
5555     /* check filename in case of an image number is expected */
5556     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
5557         if (!av_filename_number_test(oc->filename)) {
5558             print_error(oc->filename, AVERROR(EINVAL));
5559             exit_program(1);
5560         }
5561     }
5562
5563     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
5564         /* test if it already exists to avoid losing precious files */
5565         assert_file_overwrite(filename);
5566
5567         /* open the file */
5568         if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
5569                               &oc->interrupt_callback,
5570                               &output_files[nb_output_files - 1]->opts)) < 0) {
5571             print_error(filename, err);
5572             exit_program(1);
5573         }
5574     }
5575
5576     if (o->mux_preload) {
5577         uint8_t buf[64];
5578         snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
5579         av_dict_set(&output_files[nb_output_files - 1]->opts, "preload", buf, 0);
5580     }
5581     oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
5582
5583     /* copy metadata */
5584     for (i = 0; i < o->nb_metadata_map; i++) {
5585         char *p;
5586         int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
5587
5588         if (in_file_index >= nb_input_files) {
5589             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
5590             exit_program(1);
5591         }
5592         copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, in_file_index >= 0 ? input_files[in_file_index]->ctx : NULL, o);
5593     }
5594
5595     /* copy chapters */
5596     if (o->chapters_input_file >= nb_input_files) {
5597         if (o->chapters_input_file == INT_MAX) {
5598             /* copy chapters from the first input file that has them*/
5599             o->chapters_input_file = -1;
5600             for (i = 0; i < nb_input_files; i++)
5601                 if (input_files[i]->ctx->nb_chapters) {
5602                     o->chapters_input_file = i;
5603                     break;
5604                 }
5605         } else {
5606             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
5607                    o->chapters_input_file);
5608             exit_program(1);
5609         }
5610     }
5611     if (o->chapters_input_file >= 0)
5612         copy_chapters(input_files[o->chapters_input_file], output_files[nb_output_files - 1],
5613                       !o->metadata_chapters_manual);
5614
5615     /* copy global metadata by default */
5616     if (!o->metadata_global_manual && nb_input_files){
5617         av_dict_copy(&oc->metadata, input_files[0]->ctx->metadata,
5618                      AV_DICT_DONT_OVERWRITE);
5619         if(o->recording_time != INT64_MAX)
5620             av_dict_set(&oc->metadata, "duration", NULL, 0);
5621         av_dict_set(&oc->metadata, "creation_time", NULL, 0);
5622     }
5623     if (!o->metadata_streams_manual)
5624         for (i = output_files[nb_output_files - 1]->ost_index; i < nb_output_streams; i++) {
5625             InputStream *ist;
5626             if (output_streams[i]->source_index < 0)         /* this is true e.g. for attached files */
5627                 continue;
5628             ist = input_streams[output_streams[i]->source_index];
5629             av_dict_copy(&output_streams[i]->st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
5630         }
5631
5632     /* process manually set metadata */
5633     for (i = 0; i < o->nb_metadata; i++) {
5634         AVDictionary **m;
5635         char type, *val;
5636         const char *stream_spec;
5637         int index = 0, j, ret = 0;
5638
5639         val = strchr(o->metadata[i].u.str, '=');
5640         if (!val) {
5641             av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
5642                    o->metadata[i].u.str);
5643             exit_program(1);
5644         }
5645         *val++ = 0;
5646
5647         parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
5648         if (type == 's') {
5649             for (j = 0; j < oc->nb_streams; j++) {
5650                 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
5651                     av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
5652                 } else if (ret < 0)
5653                     exit_program(1);
5654             }
5655         }
5656         else {
5657             switch (type) {
5658             case 'g':
5659                 m = &oc->metadata;
5660                 break;
5661             case 'c':
5662                 if (index < 0 || index >= oc->nb_chapters) {
5663                     av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
5664                     exit_program(1);
5665                 }
5666                 m = &oc->chapters[index]->metadata;
5667                 break;
5668             default:
5669                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
5670                 exit_program(1);
5671             }
5672             av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
5673         }
5674     }
5675
5676     reset_options(o, 0);
5677 }
5678
5679 /* same option as mencoder */
5680 static int opt_pass(const char *opt, const char *arg)
5681 {
5682     do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 3);
5683     return 0;
5684 }
5685
5686 static int64_t getmaxrss(void)
5687 {
5688 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5689     struct rusage rusage;
5690     getrusage(RUSAGE_SELF, &rusage);
5691     return (int64_t)rusage.ru_maxrss * 1024;
5692 #elif HAVE_GETPROCESSMEMORYINFO
5693     HANDLE proc;
5694     PROCESS_MEMORY_COUNTERS memcounters;
5695     proc = GetCurrentProcess();
5696     memcounters.cb = sizeof(memcounters);
5697     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
5698     return memcounters.PeakPagefileUsage;
5699 #else
5700     return 0;
5701 #endif
5702 }
5703
5704 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
5705 {
5706     return parse_option(o, "q:a", arg, options);
5707 }
5708
5709 static void show_usage(void)
5710 {
5711     av_log(NULL, AV_LOG_INFO, "Hyper fast Audio and Video encoder\n");
5712     av_log(NULL, AV_LOG_INFO, "usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
5713     av_log(NULL, AV_LOG_INFO, "\n");
5714 }
5715
5716 static int opt_help(const char *opt, const char *arg)
5717 {
5718     int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
5719     av_log_set_callback(log_callback_help);
5720     show_usage();
5721     show_help_options(options, "Main options:\n",
5722                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
5723     show_help_options(options, "\nAdvanced options:\n",
5724                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
5725                       OPT_EXPERT);
5726     show_help_options(options, "\nVideo options:\n",
5727                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5728                       OPT_VIDEO);
5729     show_help_options(options, "\nAdvanced Video options:\n",
5730                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5731                       OPT_VIDEO | OPT_EXPERT);
5732     show_help_options(options, "\nAudio options:\n",
5733                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5734                       OPT_AUDIO);
5735     show_help_options(options, "\nAdvanced Audio options:\n",
5736                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
5737                       OPT_AUDIO | OPT_EXPERT);
5738     show_help_options(options, "\nSubtitle options:\n",
5739                       OPT_SUBTITLE | OPT_GRAB,
5740                       OPT_SUBTITLE);
5741     show_help_options(options, "\nAudio/Video grab options:\n",
5742                       OPT_GRAB,
5743                       OPT_GRAB);
5744     printf("\n");
5745     show_help_children(avcodec_get_class(), flags);
5746     show_help_children(avformat_get_class(), flags);
5747     show_help_children(sws_get_class(), flags);
5748     show_help_children(swr_get_class(), AV_OPT_FLAG_AUDIO_PARAM);
5749
5750     return 0;
5751 }
5752
5753 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
5754 {
5755     enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
5756     static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
5757
5758     if (!strncmp(arg, "pal-", 4)) {
5759         norm = PAL;
5760         arg += 4;
5761     } else if (!strncmp(arg, "ntsc-", 5)) {
5762         norm = NTSC;
5763         arg += 5;
5764     } else if (!strncmp(arg, "film-", 5)) {
5765         norm = FILM;
5766         arg += 5;
5767     } else {
5768         /* Try to determine PAL/NTSC by peeking in the input files */
5769         if (nb_input_files) {
5770             int i, j, fr;
5771             for (j = 0; j < nb_input_files; j++) {
5772                 for (i = 0; i < input_files[j]->nb_streams; i++) {
5773                     AVCodecContext *c = input_files[j]->ctx->streams[i]->codec;
5774                     if (c->codec_type != AVMEDIA_TYPE_VIDEO)
5775                         continue;
5776                     fr = c->time_base.den * 1000 / c->time_base.num;
5777                     if (fr == 25000) {
5778                         norm = PAL;
5779                         break;
5780                     } else if ((fr == 29970) || (fr == 23976)) {
5781                         norm = NTSC;
5782                         break;
5783                     }
5784                 }
5785                 if (norm != UNKNOWN)
5786                     break;
5787             }
5788         }
5789         if (norm != UNKNOWN)
5790             av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
5791     }
5792
5793     if (norm == UNKNOWN) {
5794         av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
5795         av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
5796         av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
5797         exit_program(1);
5798     }
5799
5800     if (!strcmp(arg, "vcd")) {
5801         opt_video_codec(o, "c:v", "mpeg1video");
5802         opt_audio_codec(o, "c:a", "mp2");
5803         parse_option(o, "f", "vcd", options);
5804
5805         parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
5806         parse_option(o, "r", frame_rates[norm], options);
5807         opt_default("g", norm == PAL ? "15" : "18");
5808
5809         opt_default("b:v", "1150000");
5810         opt_default("maxrate", "1150000");
5811         opt_default("minrate", "1150000");
5812         opt_default("bufsize", "327680"); // 40*1024*8;
5813
5814         opt_default("b:a", "224000");
5815         parse_option(o, "ar", "44100", options);
5816         parse_option(o, "ac", "2", options);
5817
5818         opt_default("packetsize", "2324");
5819         opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
5820
5821         /* We have to offset the PTS, so that it is consistent with the SCR.
5822            SCR starts at 36000, but the first two packs contain only padding
5823            and the first pack from the other stream, respectively, may also have
5824            been written before.
5825            So the real data starts at SCR 36000+3*1200. */
5826         o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
5827     } else if (!strcmp(arg, "svcd")) {
5828
5829         opt_video_codec(o, "c:v", "mpeg2video");
5830         opt_audio_codec(o, "c:a", "mp2");
5831         parse_option(o, "f", "svcd", options);
5832
5833         parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
5834         parse_option(o, "r", frame_rates[norm], options);
5835         parse_option(o, "pix_fmt", "yuv420p", options);
5836         opt_default("g", norm == PAL ? "15" : "18");
5837
5838         opt_default("b:v", "2040000");
5839         opt_default("maxrate", "2516000");
5840         opt_default("minrate", "0"); // 1145000;
5841         opt_default("bufsize", "1835008"); // 224*1024*8;
5842         opt_default("scan_offset", "1");
5843
5844
5845         opt_default("b:a", "224000");
5846         parse_option(o, "ar", "44100", options);
5847
5848         opt_default("packetsize", "2324");
5849
5850     } else if (!strcmp(arg, "dvd")) {
5851
5852         opt_video_codec(o, "c:v", "mpeg2video");
5853         opt_audio_codec(o, "c:a", "ac3");
5854         parse_option(o, "f", "dvd", options);
5855
5856         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
5857         parse_option(o, "r", frame_rates[norm], options);
5858         parse_option(o, "pix_fmt", "yuv420p", options);
5859         opt_default("g", norm == PAL ? "15" : "18");
5860
5861         opt_default("b:v", "6000000");
5862         opt_default("maxrate", "9000000");
5863         opt_default("minrate", "0"); // 1500000;
5864         opt_default("bufsize", "1835008"); // 224*1024*8;
5865
5866         opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
5867         opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
5868
5869         opt_default("b:a", "448000");
5870         parse_option(o, "ar", "48000", options);
5871
5872     } else if (!strncmp(arg, "dv", 2)) {
5873
5874         parse_option(o, "f", "dv", options);
5875
5876         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
5877         parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
5878                           norm == PAL ? "yuv420p" : "yuv411p", options);
5879         parse_option(o, "r", frame_rates[norm], options);
5880
5881         parse_option(o, "ar", "48000", options);
5882         parse_option(o, "ac", "2", options);
5883
5884     } else {
5885         av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
5886         return AVERROR(EINVAL);
5887     }
5888     return 0;
5889 }
5890
5891 static int opt_vstats_file(const char *opt, const char *arg)
5892 {
5893     av_free (vstats_filename);
5894     vstats_filename = av_strdup (arg);
5895     return 0;
5896 }
5897
5898 static int opt_vstats(const char *opt, const char *arg)
5899 {
5900     char filename[40];
5901     time_t today2 = time(NULL);
5902     struct tm *today = localtime(&today2);
5903
5904     snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
5905              today->tm_sec);
5906     return opt_vstats_file(opt, filename);
5907 }
5908
5909 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
5910 {
5911     return parse_option(o, "frames:v", arg, options);
5912 }
5913
5914 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
5915 {
5916     return parse_option(o, "frames:a", arg, options);
5917 }
5918
5919 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
5920 {
5921     return parse_option(o, "frames:d", arg, options);
5922 }
5923
5924 static int opt_preset(OptionsContext *o, const char *opt, const char *arg)
5925 {
5926     FILE *f=NULL;
5927     char filename[1000], line[1000], tmp_line[1000];
5928     const char *codec_name = *opt == 'v' ? video_codec_name :
5929                              *opt == 'a' ? audio_codec_name :
5930                                            subtitle_codec_name;
5931
5932     if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
5933         if(!strncmp(arg, "libx264-lossless", strlen("libx264-lossless"))){
5934             av_log(NULL, AV_LOG_FATAL, "Please use -preset <speed> -qp 0\n");
5935         }else
5936             av_log(NULL, AV_LOG_FATAL, "File for preset '%s' not found\n", arg);
5937         exit_program(1);
5938     }
5939
5940     while (fgets(line, sizeof(line), f)) {
5941         char *key = tmp_line, *value, *endptr;
5942
5943         if (strcspn(line, "#\n\r") == 0)
5944             continue;
5945         strcpy(tmp_line, line);
5946         if (!av_strtok(key,   "=",    &value) ||
5947             !av_strtok(value, "\r\n", &endptr)) {
5948             av_log(NULL, AV_LOG_FATAL, "%s: Invalid syntax: '%s'\n", filename, line);
5949             exit_program(1);
5950         }
5951         av_log(NULL, AV_LOG_DEBUG, "ffpreset[%s]: set '%s' = '%s'\n", filename, key, value);
5952
5953         if      (!strcmp(key, "acodec")) opt_audio_codec   (o, key, value);
5954         else if (!strcmp(key, "vcodec")) opt_video_codec   (o, key, value);
5955         else if (!strcmp(key, "scodec")) opt_subtitle_codec(o, key, value);
5956         else if (!strcmp(key, "dcodec")) opt_data_codec    (o, key, value);
5957         else if (opt_default(key, value) < 0) {
5958             av_log(NULL, AV_LOG_FATAL, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n",
5959                    filename, line, key, value);
5960             exit_program(1);
5961         }
5962     }
5963
5964     fclose(f);
5965
5966     return 0;
5967 }
5968
5969 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
5970 {
5971 }
5972
5973 static int opt_passlogfile(const char *opt, const char *arg)
5974 {
5975     pass_logfilename_prefix = arg;
5976 #if CONFIG_LIBX264_ENCODER
5977     return opt_default(opt, arg);
5978 #else
5979     return 0;
5980 #endif
5981 }
5982
5983 static int opt_old2new(OptionsContext *o, const char *opt, const char *arg)
5984 {
5985     char *s = av_asprintf("%s:%c", opt + 1, *opt);
5986     int ret = parse_option(o, s, arg, options);
5987     av_free(s);
5988     return ret;
5989 }
5990
5991 static int opt_bitrate(OptionsContext *o, const char *opt, const char *arg)
5992 {
5993     if(!strcmp(opt, "b")){
5994         av_log(NULL, AV_LOG_WARNING, "Please use -b:a or -b:v, -b is ambiguous\n");
5995         return parse_option(o, "b:v", arg, options);
5996     }
5997     return opt_default(opt, arg);
5998 }
5999
6000 static int opt_qscale(OptionsContext *o, const char *opt, const char *arg)
6001 {
6002     char *s;
6003     int ret;
6004     if(!strcmp(opt, "qscale")){
6005         av_log(NULL, AV_LOG_WARNING, "Please use -q:a or -q:v, -qscale is ambiguous\n");
6006         return parse_option(o, "q:v", arg, options);
6007     }
6008     s = av_asprintf("q%s", opt + 6);
6009     ret = parse_option(o, s, arg, options);
6010     av_free(s);
6011     return ret;
6012 }
6013
6014 static int opt_profile(OptionsContext *o, const char *opt, const char *arg)
6015 {
6016     if(!strcmp(opt, "profile")){
6017         av_log(NULL, AV_LOG_WARNING, "Please use -profile:a or -profile:v, -profile is ambiguous\n");
6018         return parse_option(o, "profile:v", arg, options);
6019     }
6020     return opt_default(opt, arg);
6021 }
6022
6023 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
6024 {
6025     return parse_option(o, "filter:v", arg, options);
6026 }
6027
6028 static int opt_audio_filters(OptionsContext *o, const char *opt, const char *arg)
6029 {
6030     return parse_option(o, "filter:a", arg, options);
6031 }
6032
6033 static int opt_vsync(const char *opt, const char *arg)
6034 {
6035     if      (!av_strcasecmp(arg, "cfr"))         video_sync_method = VSYNC_CFR;
6036     else if (!av_strcasecmp(arg, "vfr"))         video_sync_method = VSYNC_VFR;
6037     else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
6038     else if (!av_strcasecmp(arg, "drop"))        video_sync_method = VSYNC_DROP;
6039
6040     if (video_sync_method == VSYNC_AUTO)
6041         video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
6042     return 0;
6043 }
6044
6045 static int opt_deinterlace(const char *opt, const char *arg)
6046 {
6047     av_log(NULL, AV_LOG_WARNING, "-%s is deprecated, use -filter:v yadif instead\n", opt);
6048     do_deinterlace = 1;
6049     return 0;
6050 }
6051
6052 static int opt_timecode(OptionsContext *o, const char *opt, const char *arg)
6053 {
6054     char *tcr = av_asprintf("timecode=%s", arg);
6055     int ret = parse_option(o, "metadata:g", tcr, options);
6056     if (ret >= 0)
6057         ret = opt_default("gop_timecode", arg);
6058     av_free(tcr);
6059     return ret;
6060 }
6061
6062 static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
6063 {
6064     int idx = locate_option(argc, argv, options, "cpuflags");
6065     if (idx && argv[idx + 1])
6066         opt_cpuflags("cpuflags", argv[idx + 1]);
6067 }
6068
6069 static int opt_channel_layout(OptionsContext *o, const char *opt, const char *arg)
6070 {
6071     char layout_str[32];
6072     char *stream_str;
6073     char *ac_str;
6074     int ret, channels, ac_str_size;
6075     uint64_t layout;
6076
6077     layout = av_get_channel_layout(arg);
6078     if (!layout) {
6079         av_log(NULL, AV_LOG_ERROR, "Unknown channel layout: %s\n", arg);
6080         return AVERROR(EINVAL);
6081     }
6082     snprintf(layout_str, sizeof(layout_str), "%"PRIu64, layout);
6083     ret = opt_default(opt, layout_str);
6084     if (ret < 0)
6085         return ret;
6086
6087     /* set 'ac' option based on channel layout */
6088     channels = av_get_channel_layout_nb_channels(layout);
6089     snprintf(layout_str, sizeof(layout_str), "%d", channels);
6090     stream_str = strchr(opt, ':');
6091     ac_str_size = 3 + (stream_str ? strlen(stream_str) : 0);
6092     ac_str = av_mallocz(ac_str_size);
6093     if (!ac_str)
6094         return AVERROR(ENOMEM);
6095     av_strlcpy(ac_str, "ac", 3);
6096     if (stream_str)
6097         av_strlcat(ac_str, stream_str, ac_str_size);
6098     ret = parse_option(o, ac_str, layout_str, options);
6099     av_free(ac_str);
6100
6101     return ret;
6102 }
6103
6104 static int opt_filter_complex(const char *opt, const char *arg)
6105 {
6106     filtergraphs = grow_array(filtergraphs, sizeof(*filtergraphs),
6107                               &nb_filtergraphs, nb_filtergraphs + 1);
6108     if (!(filtergraphs[nb_filtergraphs - 1] = av_mallocz(sizeof(*filtergraphs[0]))))
6109         return AVERROR(ENOMEM);
6110     filtergraphs[nb_filtergraphs - 1]->index       = nb_filtergraphs - 1;
6111     filtergraphs[nb_filtergraphs - 1]->graph_desc = arg;
6112     return 0;
6113 }
6114
6115 static int opt_progress(const char *opt, const char *arg)
6116 {
6117     AVIOContext *avio = NULL;
6118     int ret;
6119
6120     if (!strcmp(arg, "-"))
6121         arg = "pipe:";
6122     ret = avio_open2(&avio, arg, AVIO_FLAG_WRITE, &int_cb, NULL);
6123     if (ret < 0) {
6124         av_log(0, AV_LOG_ERROR, "Failed to open progress URL \"%s\": %s\n",
6125                arg, av_err2str(ret));
6126         return ret;
6127     }
6128     progress_avio = avio;
6129     return 0;
6130 }
6131
6132 #define OFFSET(x) offsetof(OptionsContext, x)
6133 static const OptionDef real_options[] = {
6134     /* main options */
6135 #include "cmdutils_common_opts.h"
6136     { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
6137     { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
6138     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
6139     { "n", OPT_BOOL, {(void*)&no_file_overwrite}, "do not overwrite output files" },
6140     { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
6141     { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
6142     { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
6143     { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
6144     { "map_channel", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map_channel}, "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
6145     { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
6146       "outfile[,metadata]:infile[,metadata]" },
6147     { "map_chapters",  OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)},  "set chapters mapping", "input_file_index" },
6148     { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
6149     { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
6150     { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
6151     { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
6152     { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
6153     { "timestamp", HAS_ARG | OPT_FUNC2, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
6154     { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
6155     { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
6156     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
6157       "add timings for benchmarking" },
6158     { "benchmark_all", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark_all},
6159       "add timings for each task" },
6160     { "progress", HAS_ARG | OPT_EXPERT, {(void*)opt_progress},
6161       "write program-readable progress information", "url" },
6162     { "stdin", OPT_BOOL | OPT_EXPERT, {(void*)&stdin_interaction},
6163       "enable or disable interaction on standard input" },
6164     { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
6165     { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
6166       "dump each input packet" },
6167     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
6168       "when dumping packets, also dump the payload" },
6169     { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
6170     { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
6171     { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
6172     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
6173     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
6174     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
6175     { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying", "mode" },
6176     { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
6177     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
6178     { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_error_threshold}, "timestamp error delta threshold", "threshold" },
6179     { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
6180     { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
6181     { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
6182     { "tag",   OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
6183     { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
6184     { "qscale", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_qscale}, "use fixed quality scale (VBR)", "q" },
6185     { "profile", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_profile}, "set profile", "profile" },
6186     { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
6187     { "filter_complex", HAS_ARG | OPT_EXPERT, {(void*)opt_filter_complex}, "create a complex filtergraph", "graph_description" },
6188     { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
6189     { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
6190     { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
6191     { "debug_ts", OPT_BOOL | OPT_EXPERT, {&debug_ts}, "print timestamp debugging info" },
6192
6193     /* video options */
6194     { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
6195     { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
6196     { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
6197     { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
6198     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
6199     { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
6200     { "croptop",  HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
6201     { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
6202     { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
6203     { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
6204     { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
6205     { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
6206     { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
6207     { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
6208     { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
6209     { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "deprecated use -g 1"},
6210     { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
6211     { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
6212     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
6213     { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
6214     { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
6215     { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
6216       "use same quantizer as source (implies VBR)" },
6217     { "timecode", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_timecode}, "set initial TimeCode value.", "hh:mm:ss[:;.]ff" },
6218     { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
6219     { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
6220     { "deinterlace", OPT_EXPERT | OPT_VIDEO, {(void*)opt_deinterlace},
6221       "this option is deprecated, use the yadif filter instead" },
6222     { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
6223     { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
6224     { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
6225     { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
6226     { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
6227     { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
6228     { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
6229     { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
6230     { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
6231     { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
6232     { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
6233     { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
6234     { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
6235     { "b", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_bitrate}, "video bitrate (please use -b:v)", "bitrate" },
6236
6237     /* audio options */
6238     { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
6239     { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
6240     { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
6241     { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
6242     { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
6243     { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
6244     { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
6245     { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
6246     { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
6247     { "channel_layout", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_channel_layout}, "set channel layout", "layout" },
6248     { "af", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_filters}, "audio filters", "filter list" },
6249
6250     /* subtitle options */
6251     { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
6252     { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
6253     { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
6254
6255     /* grab options */
6256     { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
6257     { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "deprecated, use -standard", "standard" },
6258     { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
6259
6260     /* muxer options */
6261     { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT   | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
6262     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)},   "set the initial demux-decode delay", "seconds" },
6263
6264     { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
6265     { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "audio bitstream_filters" },
6266     { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_old2new}, "deprecated", "video bitstream_filters" },
6267
6268     { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
6269     { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
6270     { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
6271     { "fpre", HAS_ARG | OPT_EXPERT| OPT_FUNC2, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
6272     /* data codec support */
6273     { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
6274     { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(data_disable)}, "disable data" },
6275
6276     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
6277     { NULL, },
6278 };
6279
6280 int main(int argc, char **argv)
6281 {
6282     OptionsContext o = { 0 };
6283     int64_t ti;
6284
6285     options = real_options;
6286     reset_options(&o, 0);
6287
6288     av_log_set_flags(AV_LOG_SKIP_REPEATED);
6289     parse_loglevel(argc, argv, options);
6290
6291     if(argc>1 && !strcmp(argv[1], "-d")){
6292         run_as_daemon=1;
6293         av_log_set_callback(log_callback_null);
6294         argc--;
6295         argv++;
6296     }
6297
6298     avcodec_register_all();
6299 #if CONFIG_AVDEVICE
6300     avdevice_register_all();
6301 #endif
6302     avfilter_register_all();
6303     av_register_all();
6304     avformat_network_init();
6305
6306     show_banner(argc, argv, options);
6307
6308     term_init();
6309
6310     parse_cpuflags(argc, argv, options);
6311
6312     /* parse options */
6313     parse_options(&o, argc, argv, options, opt_output_file);
6314
6315     if (nb_output_files <= 0 && nb_input_files == 0) {
6316         show_usage();
6317         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
6318         exit_program(1);
6319     }
6320
6321     /* file converter / grab */
6322     if (nb_output_files <= 0) {
6323         av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
6324         exit_program(1);
6325     }
6326
6327     if (nb_input_files == 0) {
6328         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
6329         exit_program(1);
6330     }
6331
6332     current_time = ti = getutime();
6333     if (transcode() < 0)
6334         exit_program(1);
6335     ti = getutime() - ti;
6336     if (do_benchmark) {
6337         int maxrss = getmaxrss() / 1024;
6338         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
6339     }
6340
6341     exit_program(0);
6342     return 0;
6343 }