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