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