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