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