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