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