movdec: Fix bad computed size for atoms with size 0 in MOV files
[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 = 1;
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 #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
159
160 typedef struct InputStream {
161     int file_index;
162     AVStream *st;
163     int discard;             /* true if stream data should be discarded */
164     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
165     AVCodec *dec;
166     AVFrame *decoded_frame;
167     AVFrame *filtered_frame;
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_freep(&input_streams[i].decoded_frame);
617         av_freep(&input_streams[i].filtered_frame);
618         av_dict_free(&input_streams[i].opts);
619     }
620
621     if (vstats_file)
622         fclose(vstats_file);
623     av_free(vstats_filename);
624
625     av_freep(&input_streams);
626     av_freep(&input_files);
627     av_freep(&output_streams);
628     av_freep(&output_files);
629
630     uninit_opts();
631     av_free(audio_buf);
632     av_free(audio_out);
633     allocated_audio_buf_size= allocated_audio_out_size= 0;
634
635 #if CONFIG_AVFILTER
636     avfilter_uninit();
637 #endif
638     avformat_network_deinit();
639
640     if (received_sigterm) {
641         av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
642                (int) received_sigterm);
643         exit (255);
644     }
645
646     exit(ret); /* not all OS-es handle main() return value */
647 }
648
649 static void assert_avoptions(AVDictionary *m)
650 {
651     AVDictionaryEntry *t;
652     if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
653         av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
654         exit_program(1);
655     }
656 }
657
658 static void assert_codec_experimental(AVCodecContext *c, int encoder)
659 {
660     const char *codec_string = encoder ? "encoder" : "decoder";
661     AVCodec *codec;
662     if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
663         c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
664         av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
665                 "results.\nAdd '-strict experimental' if you want to use it.\n",
666                 codec_string, c->codec->name);
667         codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
668         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
669             av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
670                    codec_string, codec->name);
671         exit_program(1);
672     }
673 }
674
675 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
676 {
677     if(codec && codec->sample_fmts){
678         const enum AVSampleFormat *p= codec->sample_fmts;
679         for(; *p!=-1; p++){
680             if(*p == st->codec->sample_fmt)
681                 break;
682         }
683         if (*p == -1) {
684             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
685                 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
686             if(av_get_sample_fmt_name(st->codec->sample_fmt))
687             av_log(NULL, AV_LOG_WARNING,
688                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
689                    av_get_sample_fmt_name(st->codec->sample_fmt),
690                    codec->name,
691                    av_get_sample_fmt_name(codec->sample_fmts[0]));
692             st->codec->sample_fmt = codec->sample_fmts[0];
693         }
694     }
695 }
696
697 static void choose_sample_rate(AVStream *st, AVCodec *codec)
698 {
699     if(codec && codec->supported_samplerates){
700         const int *p= codec->supported_samplerates;
701         int best=0;
702         int best_dist=INT_MAX;
703         for(; *p; p++){
704             int dist= abs(st->codec->sample_rate - *p);
705             if(dist < best_dist){
706                 best_dist= dist;
707                 best= *p;
708             }
709         }
710         if(best_dist){
711             av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
712         }
713         st->codec->sample_rate= best;
714     }
715 }
716
717 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
718 {
719     if(codec && codec->pix_fmts){
720         const enum PixelFormat *p= codec->pix_fmts;
721         if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
722             if(st->codec->codec_id==CODEC_ID_MJPEG){
723                 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
724             }else if(st->codec->codec_id==CODEC_ID_LJPEG){
725                 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};
726             }
727         }
728         for (; *p != PIX_FMT_NONE; p++) {
729             if(*p == st->codec->pix_fmt)
730                 break;
731         }
732         if (*p == PIX_FMT_NONE) {
733             if(st->codec->pix_fmt != PIX_FMT_NONE)
734                 av_log(NULL, AV_LOG_WARNING,
735                         "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
736                         av_pix_fmt_descriptors[st->codec->pix_fmt].name,
737                         codec->name,
738                         av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
739             st->codec->pix_fmt = codec->pix_fmts[0];
740         }
741     }
742 }
743
744 static double
745 get_sync_ipts(const OutputStream *ost)
746 {
747     const InputStream *ist = ost->sync_ist;
748     OutputFile *of = &output_files[ost->file_index];
749     return (double)(ist->pts - of->start_time)/AV_TIME_BASE;
750 }
751
752 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
753     int ret;
754
755     while(bsfc){
756         AVPacket new_pkt= *pkt;
757         int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
758                                           &new_pkt.data, &new_pkt.size,
759                                           pkt->data, pkt->size,
760                                           pkt->flags & AV_PKT_FLAG_KEY);
761         if(a>0){
762             av_free_packet(pkt);
763             new_pkt.destruct= av_destruct_packet;
764         } else if(a<0){
765             av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
766                    bsfc->filter->name, pkt->stream_index,
767                    avctx->codec ? avctx->codec->name : "copy");
768             print_error("", a);
769             if (exit_on_error)
770                 exit_program(1);
771         }
772         *pkt= new_pkt;
773
774         bsfc= bsfc->next;
775     }
776
777     ret= av_interleaved_write_frame(s, pkt);
778     if(ret < 0){
779         print_error("av_interleaved_write_frame()", ret);
780         exit_program(1);
781     }
782 }
783
784 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
785 {
786     int fill_char = 0x00;
787     if (sample_fmt == AV_SAMPLE_FMT_U8)
788         fill_char = 0x80;
789     memset(buf, fill_char, size);
790 }
791
792 static void do_audio_out(AVFormatContext *s, OutputStream *ost,
793                          InputStream *ist, AVFrame *decoded_frame)
794 {
795     uint8_t *buftmp;
796     int64_t audio_out_size, audio_buf_size;
797
798     int size_out, frame_bytes, ret, resample_changed;
799     AVCodecContext *enc= ost->st->codec;
800     AVCodecContext *dec= ist->st->codec;
801     int osize = av_get_bytes_per_sample(enc->sample_fmt);
802     int isize = av_get_bytes_per_sample(dec->sample_fmt);
803     const int coded_bps = av_get_bits_per_sample(enc->codec->id);
804     uint8_t *buf = decoded_frame->data[0];
805     int size     = decoded_frame->nb_samples * dec->channels * isize;
806     int64_t allocated_for_size = size;
807
808 need_realloc:
809     audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
810     audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
811     audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
812     audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
813     audio_buf_size*= osize*enc->channels;
814
815     audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
816     if(coded_bps > 8*osize)
817         audio_out_size= audio_out_size * coded_bps / (8*osize);
818     audio_out_size += FF_MIN_BUFFER_SIZE;
819
820     if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
821         av_log(NULL, AV_LOG_FATAL, "Buffer sizes too large\n");
822         exit_program(1);
823     }
824
825     av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
826     av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
827     if (!audio_buf || !audio_out){
828         av_log(NULL, AV_LOG_FATAL, "Out of memory in do_audio_out\n");
829         exit_program(1);
830     }
831
832     if (enc->channels != dec->channels)
833         ost->audio_resample = 1;
834
835     resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
836                        ost->resample_channels    != dec->channels   ||
837                        ost->resample_sample_rate != dec->sample_rate;
838
839     if ((ost->audio_resample && !ost->resample) || resample_changed) {
840         if (resample_changed) {
841             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",
842                    ist->file_index, ist->st->index,
843                    ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
844                    dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
845             ost->resample_sample_fmt  = dec->sample_fmt;
846             ost->resample_channels    = dec->channels;
847             ost->resample_sample_rate = dec->sample_rate;
848             if (ost->resample)
849                 audio_resample_close(ost->resample);
850         }
851         /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
852         if (audio_sync_method <= 1 &&
853             ost->resample_sample_fmt  == enc->sample_fmt &&
854             ost->resample_channels    == enc->channels   &&
855             ost->resample_sample_rate == enc->sample_rate) {
856             ost->resample = NULL;
857             ost->audio_resample = 0;
858         } else {
859             if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
860                 av_log(NULL, AV_LOG_WARNING, "Using s16 intermediate sample format for resampling\n");
861             ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
862                                                    enc->sample_rate, dec->sample_rate,
863                                                    enc->sample_fmt,  dec->sample_fmt,
864                                                    16, 10, 0, 0.8);
865             if (!ost->resample) {
866                 av_log(NULL, AV_LOG_FATAL, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
867                        dec->channels, dec->sample_rate,
868                        enc->channels, enc->sample_rate);
869                 exit_program(1);
870             }
871         }
872     }
873
874 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
875     if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
876         MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
877         if (ost->reformat_ctx)
878             av_audio_convert_free(ost->reformat_ctx);
879         ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
880                                                    dec->sample_fmt, 1, NULL, 0);
881         if (!ost->reformat_ctx) {
882             av_log(NULL, AV_LOG_FATAL, "Cannot convert %s sample format to %s sample format\n",
883                    av_get_sample_fmt_name(dec->sample_fmt),
884                    av_get_sample_fmt_name(enc->sample_fmt));
885             exit_program(1);
886         }
887         ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
888     }
889
890     if(audio_sync_method){
891         double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
892                 - av_fifo_size(ost->fifo)/(enc->channels * osize);
893         int idelta = delta * dec->sample_rate / enc->sample_rate;
894         int byte_delta = idelta * isize * dec->channels;
895
896         //FIXME resample delay
897         if(fabs(delta) > 50){
898             if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
899                 if(byte_delta < 0){
900                     byte_delta= FFMAX(byte_delta, -size);
901                     size += byte_delta;
902                     buf  -= byte_delta;
903                     av_log(NULL, AV_LOG_VERBOSE, "discarding %d audio samples\n",
904                            -byte_delta / (isize * dec->channels));
905                     if(!size)
906                         return;
907                     ist->is_start=0;
908                 }else{
909                     static uint8_t *input_tmp= NULL;
910                     input_tmp= av_realloc(input_tmp, byte_delta + size);
911
912                     if(byte_delta > allocated_for_size - size){
913                         allocated_for_size= byte_delta + (int64_t)size;
914                         goto need_realloc;
915                     }
916                     ist->is_start=0;
917
918                     generate_silence(input_tmp, dec->sample_fmt, byte_delta);
919                     memcpy(input_tmp + byte_delta, buf, size);
920                     buf= input_tmp;
921                     size += byte_delta;
922                     av_log(NULL, AV_LOG_VERBOSE, "adding %d audio samples of silence\n", idelta);
923                 }
924             }else if(audio_sync_method>1){
925                 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
926                 av_assert0(ost->audio_resample);
927                 av_log(NULL, AV_LOG_VERBOSE, "compensating audio timestamp drift:%f compensation:%d in:%d\n",
928                        delta, comp, enc->sample_rate);
929 //                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));
930                 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
931             }
932         }
933     }else
934         ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
935                         - av_fifo_size(ost->fifo)/(enc->channels * osize); //FIXME wrong
936
937     if (ost->audio_resample) {
938         buftmp = audio_buf;
939         size_out = audio_resample(ost->resample,
940                                   (short *)buftmp, (short *)buf,
941                                   size / (dec->channels * isize));
942         size_out = size_out * enc->channels * osize;
943     } else {
944         buftmp = buf;
945         size_out = size;
946     }
947
948     if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
949         const void *ibuf[6]= {buftmp};
950         void *obuf[6]= {audio_buf};
951         int istride[6]= {isize};
952         int ostride[6]= {osize};
953         int len= size_out/istride[0];
954         if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
955             printf("av_audio_convert() failed\n");
956             if (exit_on_error)
957                 exit_program(1);
958             return;
959         }
960         buftmp = audio_buf;
961         size_out = len*osize;
962     }
963
964     /* now encode as many frames as possible */
965     if (enc->frame_size > 1) {
966         /* output resampled raw samples */
967         if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
968             av_log(NULL, AV_LOG_FATAL, "av_fifo_realloc2() failed\n");
969             exit_program(1);
970         }
971         av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
972
973         frame_bytes = enc->frame_size * osize * enc->channels;
974
975         while (av_fifo_size(ost->fifo) >= frame_bytes) {
976             AVPacket pkt;
977             av_init_packet(&pkt);
978
979             av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
980
981             //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
982
983             ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
984                                        (short *)audio_buf);
985             if (ret < 0) {
986                 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
987                 exit_program(1);
988             }
989             audio_size += ret;
990             pkt.stream_index= ost->index;
991             pkt.data= audio_out;
992             pkt.size= ret;
993             if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
994                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
995             pkt.flags |= AV_PKT_FLAG_KEY;
996             write_frame(s, &pkt, enc, ost->bitstream_filters);
997
998             ost->sync_opts += enc->frame_size;
999         }
1000     } else {
1001         AVPacket pkt;
1002         av_init_packet(&pkt);
1003
1004         ost->sync_opts += size_out / (osize * enc->channels);
1005
1006         /* output a pcm frame */
1007         /* determine the size of the coded buffer */
1008         size_out /= osize;
1009         if (coded_bps)
1010             size_out = size_out*coded_bps/8;
1011
1012         if(size_out > audio_out_size){
1013             av_log(NULL, AV_LOG_FATAL, "Internal error, buffer size too small\n");
1014             exit_program(1);
1015         }
1016
1017         //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
1018         ret = avcodec_encode_audio(enc, audio_out, size_out,
1019                                    (short *)buftmp);
1020         if (ret < 0) {
1021             av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1022             exit_program(1);
1023         }
1024         audio_size += ret;
1025         pkt.stream_index= ost->index;
1026         pkt.data= audio_out;
1027         pkt.size= ret;
1028         if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1029             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1030         pkt.flags |= AV_PKT_FLAG_KEY;
1031         write_frame(s, &pkt, enc, ost->bitstream_filters);
1032     }
1033 }
1034
1035 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
1036 {
1037     AVCodecContext *dec;
1038     AVPicture *picture2;
1039     AVPicture picture_tmp;
1040     uint8_t *buf = 0;
1041
1042     dec = ist->st->codec;
1043
1044     /* deinterlace : must be done before any resize */
1045     if (do_deinterlace) {
1046         int size;
1047
1048         /* create temporary picture */
1049         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
1050         buf = av_malloc(size);
1051         if (!buf)
1052             return;
1053
1054         picture2 = &picture_tmp;
1055         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
1056
1057         if(avpicture_deinterlace(picture2, picture,
1058                                  dec->pix_fmt, dec->width, dec->height) < 0) {
1059             /* if error, do not deinterlace */
1060             av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
1061             av_free(buf);
1062             buf = NULL;
1063             picture2 = picture;
1064         }
1065     } else {
1066         picture2 = picture;
1067     }
1068
1069     if (picture != picture2)
1070         *picture = *picture2;
1071     *bufp = buf;
1072 }
1073
1074 static void do_subtitle_out(AVFormatContext *s,
1075                             OutputStream *ost,
1076                             InputStream *ist,
1077                             AVSubtitle *sub,
1078                             int64_t pts)
1079 {
1080     static uint8_t *subtitle_out = NULL;
1081     int subtitle_out_max_size = 1024 * 1024;
1082     int subtitle_out_size, nb, i;
1083     AVCodecContext *enc;
1084     AVPacket pkt;
1085
1086     if (pts == AV_NOPTS_VALUE) {
1087         av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1088         if (exit_on_error)
1089             exit_program(1);
1090         return;
1091     }
1092
1093     enc = ost->st->codec;
1094
1095     if (!subtitle_out) {
1096         subtitle_out = av_malloc(subtitle_out_max_size);
1097     }
1098
1099     /* Note: DVB subtitle need one packet to draw them and one other
1100        packet to clear them */
1101     /* XXX: signal it in the codec context ? */
1102     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
1103         nb = 2;
1104     else
1105         nb = 1;
1106
1107     for(i = 0; i < nb; i++) {
1108         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
1109         // start_display_time is required to be 0
1110         sub->pts              += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
1111         sub->end_display_time -= sub->start_display_time;
1112         sub->start_display_time = 0;
1113         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1114                                                     subtitle_out_max_size, sub);
1115         if (subtitle_out_size < 0) {
1116             av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1117             exit_program(1);
1118         }
1119
1120         av_init_packet(&pkt);
1121         pkt.stream_index = ost->index;
1122         pkt.data = subtitle_out;
1123         pkt.size = subtitle_out_size;
1124         pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
1125         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
1126             /* XXX: the pts correction is handled here. Maybe handling
1127                it in the codec would be better */
1128             if (i == 0)
1129                 pkt.pts += 90 * sub->start_display_time;
1130             else
1131                 pkt.pts += 90 * sub->end_display_time;
1132         }
1133         write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1134     }
1135 }
1136
1137 static int bit_buffer_size= 1024*256;
1138 static uint8_t *bit_buffer= NULL;
1139
1140 static void do_video_resample(OutputStream *ost,
1141                               InputStream *ist,
1142                               AVFrame *in_picture,
1143                               AVFrame **out_picture)
1144 {
1145     int resample_changed = 0;
1146     AVCodecContext *dec = ist->st->codec;
1147     AVCodecContext *enc = ost->st->codec;
1148     *out_picture = in_picture;
1149
1150     resample_changed = ost->resample_width   != dec->width  ||
1151                        ost->resample_height  != dec->height ||
1152                        ost->resample_pix_fmt != dec->pix_fmt;
1153
1154 #if !CONFIG_AVFILTER
1155     if (resample_changed) {
1156         av_log(NULL, AV_LOG_INFO,
1157                "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1158                ist->file_index, ist->st->index,
1159                ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
1160                dec->width         , dec->height         , av_get_pix_fmt_name(dec->pix_fmt));
1161         ost->resample_width   = dec->width;
1162         ost->resample_height  = dec->height;
1163         ost->resample_pix_fmt = dec->pix_fmt;
1164     }
1165
1166     ost->video_resample = dec->width   != enc->width  ||
1167                           dec->height  != enc->height ||
1168                           dec->pix_fmt != enc->pix_fmt;
1169
1170     if (ost->video_resample) {
1171         *out_picture = &ost->resample_frame;
1172         if (!ost->img_resample_ctx || resample_changed) {
1173             /* initialize the destination picture */
1174             if (!ost->resample_frame.data[0]) {
1175                 avcodec_get_frame_defaults(&ost->resample_frame);
1176                 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
1177                                     enc->width, enc->height)) {
1178                     fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
1179                     exit_program(1);
1180                 }
1181             }
1182             /* initialize a new scaler context */
1183             sws_freeContext(ost->img_resample_ctx);
1184             ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
1185                                                    enc->width, enc->height, enc->pix_fmt,
1186                                                    ost->sws_flags, NULL, NULL, NULL);
1187             if (ost->img_resample_ctx == NULL) {
1188                 av_log(NULL, AV_LOG_FATAL, "Cannot get resampling context\n");
1189                 exit_program(1);
1190             }
1191         }
1192         sws_scale(ost->img_resample_ctx, in_picture->data, in_picture->linesize,
1193               0, ost->resample_height, (*out_picture)->data, (*out_picture)->linesize);
1194     }
1195 #else
1196     if (resample_changed) {
1197         avfilter_graph_free(&ost->graph);
1198         if (configure_video_filters(ist, ost)) {
1199             av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1200             exit_program(1);
1201         }
1202     }
1203 #endif
1204     if (resample_changed) {
1205         ost->resample_width   = dec->width;
1206         ost->resample_height  = dec->height;
1207         ost->resample_pix_fmt = dec->pix_fmt;
1208     }
1209 }
1210
1211
1212 static void do_video_out(AVFormatContext *s,
1213                          OutputStream *ost,
1214                          InputStream *ist,
1215                          AVFrame *in_picture,
1216                          int *frame_size, float quality)
1217 {
1218     int nb_frames, i, ret, format_video_sync;
1219     AVFrame *final_picture;
1220     AVCodecContext *enc;
1221     double sync_ipts;
1222
1223     enc = ost->st->codec;
1224
1225     sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
1226
1227     /* by default, we output a single frame */
1228     nb_frames = 1;
1229
1230     *frame_size = 0;
1231
1232     format_video_sync = video_sync_method;
1233     if (format_video_sync < 0)
1234         format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? 0 :
1235                             (s->oformat->flags & AVFMT_VARIABLE_FPS) ? 2 : 1;
1236
1237     if (format_video_sync) {
1238         double vdelta = sync_ipts - ost->sync_opts;
1239         //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1240         if (vdelta < -1.1)
1241             nb_frames = 0;
1242         else if (format_video_sync == 2) {
1243             if(vdelta<=-0.6){
1244                 nb_frames=0;
1245             }else if(vdelta>0.6)
1246                 ost->sync_opts= lrintf(sync_ipts);
1247         }else if (vdelta > 1.1)
1248             nb_frames = lrintf(vdelta);
1249 //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);
1250         if (nb_frames == 0){
1251             ++nb_frames_drop;
1252             av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
1253         }else if (nb_frames > 1) {
1254             nb_frames_dup += nb_frames - 1;
1255             av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames-1);
1256         }
1257     }else
1258         ost->sync_opts= lrintf(sync_ipts);
1259
1260     nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1261     if (nb_frames <= 0)
1262         return;
1263
1264     do_video_resample(ost, ist, in_picture, &final_picture);
1265
1266     /* duplicates frame if needed */
1267     for(i=0;i<nb_frames;i++) {
1268         AVPacket pkt;
1269         av_init_packet(&pkt);
1270         pkt.stream_index= ost->index;
1271
1272         if (s->oformat->flags & AVFMT_RAWPICTURE &&
1273             enc->codec->id == CODEC_ID_RAWVIDEO) {
1274             /* raw pictures are written as AVPicture structure to
1275                avoid any copies. We support temporarily the older
1276                method. */
1277             enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
1278             enc->coded_frame->top_field_first  = in_picture->top_field_first;
1279             pkt.data= (uint8_t *)final_picture;
1280             pkt.size=  sizeof(AVPicture);
1281             pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
1282             pkt.flags |= AV_PKT_FLAG_KEY;
1283
1284             write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1285         } else {
1286             AVFrame big_picture;
1287
1288             big_picture= *final_picture;
1289             /* better than nothing: use input picture interlaced
1290                settings */
1291             big_picture.interlaced_frame = in_picture->interlaced_frame;
1292             if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
1293                 if (ost->top_field_first == -1)
1294                     big_picture.top_field_first = in_picture->top_field_first;
1295                 else
1296                     big_picture.top_field_first = !!ost->top_field_first;
1297             }
1298
1299             /* handles same_quant here. This is not correct because it may
1300                not be a global option */
1301             big_picture.quality = quality;
1302             if (!enc->me_threshold)
1303                 big_picture.pict_type = 0;
1304 //            big_picture.pts = AV_NOPTS_VALUE;
1305             big_picture.pts= ost->sync_opts;
1306 //            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
1307 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
1308             if (ost->forced_kf_index < ost->forced_kf_count &&
1309                 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1310                 big_picture.pict_type = AV_PICTURE_TYPE_I;
1311                 ost->forced_kf_index++;
1312             }
1313             ret = avcodec_encode_video(enc,
1314                                        bit_buffer, bit_buffer_size,
1315                                        &big_picture);
1316             if (ret < 0) {
1317                 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1318                 exit_program(1);
1319             }
1320
1321             if(ret>0){
1322                 pkt.data= bit_buffer;
1323                 pkt.size= ret;
1324                 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
1325                     pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1326 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
1327    pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
1328    pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
1329
1330                 if(enc->coded_frame->key_frame)
1331                     pkt.flags |= AV_PKT_FLAG_KEY;
1332                 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
1333                 *frame_size = ret;
1334                 video_size += ret;
1335                 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
1336                 //        enc->frame_number-1, ret, enc->pict_type);
1337                 /* if two pass, output log */
1338                 if (ost->logfile && enc->stats_out) {
1339                     fprintf(ost->logfile, "%s", enc->stats_out);
1340                 }
1341             }
1342         }
1343         ost->sync_opts++;
1344         ost->frame_number++;
1345     }
1346 }
1347
1348 static double psnr(double d){
1349     return -10.0*log(d)/log(10.0);
1350 }
1351
1352 static void do_video_stats(AVFormatContext *os, OutputStream *ost,
1353                            int frame_size)
1354 {
1355     AVCodecContext *enc;
1356     int frame_number;
1357     double ti1, bitrate, avg_bitrate;
1358
1359     /* this is executed just the first time do_video_stats is called */
1360     if (!vstats_file) {
1361         vstats_file = fopen(vstats_filename, "w");
1362         if (!vstats_file) {
1363             perror("fopen");
1364             exit_program(1);
1365         }
1366     }
1367
1368     enc = ost->st->codec;
1369     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1370         frame_number = ost->frame_number;
1371         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
1372         if (enc->flags&CODEC_FLAG_PSNR)
1373             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
1374
1375         fprintf(vstats_file,"f_size= %6d ", frame_size);
1376         /* compute pts value */
1377         ti1 = ost->sync_opts * av_q2d(enc->time_base);
1378         if (ti1 < 0.01)
1379             ti1 = 0.01;
1380
1381         bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1382         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1383         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1384             (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1385         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1386     }
1387 }
1388
1389 static void print_report(OutputFile *output_files,
1390                          OutputStream *ost_table, int nb_ostreams,
1391                          int is_last_report, int64_t timer_start)
1392 {
1393     char buf[1024];
1394     OutputStream *ost;
1395     AVFormatContext *oc;
1396     int64_t total_size;
1397     AVCodecContext *enc;
1398     int frame_number, vid, i;
1399     double bitrate;
1400     int64_t pts = INT64_MAX;
1401     static int64_t last_time = -1;
1402     static int qp_histogram[52];
1403     int hours, mins, secs, us;
1404
1405     if (!print_stats && !is_last_report)
1406         return;
1407
1408     if (!is_last_report) {
1409         int64_t cur_time;
1410         /* display the report every 0.5 seconds */
1411         cur_time = av_gettime();
1412         if (last_time == -1) {
1413             last_time = cur_time;
1414             return;
1415         }
1416         if ((cur_time - last_time) < 500000)
1417             return;
1418         last_time = cur_time;
1419     }
1420
1421
1422     oc = output_files[0].ctx;
1423
1424     total_size = avio_size(oc->pb);
1425     if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
1426         total_size= avio_tell(oc->pb);
1427
1428     buf[0] = '\0';
1429     vid = 0;
1430     for(i=0;i<nb_ostreams;i++) {
1431         float q = -1;
1432         ost = &ost_table[i];
1433         enc = ost->st->codec;
1434         if (!ost->stream_copy && enc->coded_frame)
1435             q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
1436         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1437             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1438         }
1439         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1440             float t = (av_gettime()-timer_start) / 1000000.0;
1441
1442             frame_number = ost->frame_number;
1443             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
1444                      frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);
1445             if(is_last_report)
1446                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1447             if(qp_hist){
1448                 int j;
1449                 int qp = lrintf(q);
1450                 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
1451                     qp_histogram[qp]++;
1452                 for(j=0; j<32; j++)
1453                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
1454             }
1455             if (enc->flags&CODEC_FLAG_PSNR){
1456                 int j;
1457                 double error, error_sum=0;
1458                 double scale, scale_sum=0;
1459                 char type[3]= {'Y','U','V'};
1460                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1461                 for(j=0; j<3; j++){
1462                     if(is_last_report){
1463                         error= enc->error[j];
1464                         scale= enc->width*enc->height*255.0*255.0*frame_number;
1465                     }else{
1466                         error= enc->coded_frame->error[j];
1467                         scale= enc->width*enc->height*255.0*255.0;
1468                     }
1469                     if(j) scale/=4;
1470                     error_sum += error;
1471                     scale_sum += scale;
1472                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1473                 }
1474                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1475             }
1476             vid = 1;
1477         }
1478         /* compute min output value */
1479         pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
1480                                       ost->st->time_base, AV_TIME_BASE_Q));
1481     }
1482
1483     secs = pts / AV_TIME_BASE;
1484     us = pts % AV_TIME_BASE;
1485     mins = secs / 60;
1486     secs %= 60;
1487     hours = mins / 60;
1488     mins %= 60;
1489
1490     bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
1491
1492     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1493              "size=%8.0fkB time=", total_size / 1024.0);
1494     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1495              "%02d:%02d:%02d.%02d ", hours, mins, secs,
1496              (100 * us) / AV_TIME_BASE);
1497     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1498              "bitrate=%6.1fkbits/s", bitrate);
1499
1500     if (nb_frames_dup || nb_frames_drop)
1501         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1502                 nb_frames_dup, nb_frames_drop);
1503
1504     av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
1505
1506     fflush(stderr);
1507
1508     if (is_last_report) {
1509         int64_t raw= audio_size + video_size + extra_size;
1510         av_log(NULL, AV_LOG_INFO, "\n");
1511         av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1512                video_size/1024.0,
1513                audio_size/1024.0,
1514                extra_size/1024.0,
1515                100.0*(total_size - raw)/raw
1516         );
1517     }
1518 }
1519
1520 static void flush_encoders(OutputStream *ost_table, int nb_ostreams)
1521 {
1522     int i, ret;
1523
1524     for (i = 0; i < nb_ostreams; i++) {
1525         OutputStream   *ost = &ost_table[i];
1526         AVCodecContext *enc = ost->st->codec;
1527         AVFormatContext *os = output_files[ost->file_index].ctx;
1528
1529         if (!ost->encoding_needed)
1530             continue;
1531
1532         if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
1533             continue;
1534         if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == CODEC_ID_RAWVIDEO)
1535             continue;
1536
1537         for(;;) {
1538             AVPacket pkt;
1539             int fifo_bytes;
1540             av_init_packet(&pkt);
1541             pkt.stream_index= ost->index;
1542
1543             switch (ost->st->codec->codec_type) {
1544             case AVMEDIA_TYPE_AUDIO:
1545                 fifo_bytes = av_fifo_size(ost->fifo);
1546                 ret = 0;
1547                 /* encode any samples remaining in fifo */
1548                 if (fifo_bytes > 0) {
1549                     int osize = av_get_bytes_per_sample(enc->sample_fmt);
1550                     int fs_tmp = enc->frame_size;
1551
1552                     av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
1553                     if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1554                         enc->frame_size = fifo_bytes / (osize * enc->channels);
1555                     } else { /* pad */
1556                         int frame_bytes = enc->frame_size*osize*enc->channels;
1557                         if (allocated_audio_buf_size < frame_bytes)
1558                             exit_program(1);
1559                         generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
1560                     }
1561
1562                     ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
1563                     pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
1564                                               ost->st->time_base.num, enc->sample_rate);
1565                     enc->frame_size = fs_tmp;
1566                 }
1567                 if (ret <= 0) {
1568                     ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1569                 }
1570                 if (ret < 0) {
1571                     av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1572                     exit_program(1);
1573                 }
1574                 audio_size += ret;
1575                 pkt.flags |= AV_PKT_FLAG_KEY;
1576                 break;
1577             case AVMEDIA_TYPE_VIDEO:
1578                 ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1579                 if (ret < 0) {
1580                     av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1581                     exit_program(1);
1582                 }
1583                 video_size += ret;
1584                 if(enc->coded_frame && enc->coded_frame->key_frame)
1585                     pkt.flags |= AV_PKT_FLAG_KEY;
1586                 if (ost->logfile && enc->stats_out) {
1587                     fprintf(ost->logfile, "%s", enc->stats_out);
1588                 }
1589                 break;
1590             default:
1591                 ret=-1;
1592             }
1593
1594             if (ret <= 0)
1595                 break;
1596             pkt.data = bit_buffer;
1597             pkt.size = ret;
1598             if (enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1599                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1600             write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
1601         }
1602     }
1603 }
1604
1605 /*
1606  * Check whether a packet from ist should be written into ost at this time
1607  */
1608 static int check_output_constraints(InputStream *ist, OutputStream *ost)
1609 {
1610     OutputFile *of = &output_files[ost->file_index];
1611     int ist_index  = ist - input_streams;
1612
1613     if (ost->source_index != ist_index)
1614         return 0;
1615
1616     if (of->start_time && ist->pts < of->start_time)
1617         return 0;
1618
1619     if (of->recording_time != INT64_MAX &&
1620         av_compare_ts(ist->pts, AV_TIME_BASE_Q, of->recording_time + of->start_time,
1621                       (AVRational){1, 1000000}) >= 0) {
1622         ost->is_past_recording_time = 1;
1623         return 0;
1624     }
1625
1626     return 1;
1627 }
1628
1629 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1630 {
1631     OutputFile *of = &output_files[ost->file_index];
1632     int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1633     AVPicture pict;
1634     AVPacket opkt;
1635
1636     av_init_packet(&opkt);
1637
1638     if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1639         !ost->copy_initial_nonkeyframes)
1640         return;
1641
1642     /* force the input stream PTS */
1643     if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1644         audio_size += pkt->size;
1645     else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1646         video_size += pkt->size;
1647         ost->sync_opts++;
1648     }
1649
1650     opkt.stream_index = ost->index;
1651     if (pkt->pts != AV_NOPTS_VALUE)
1652         opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1653     else
1654         opkt.pts = AV_NOPTS_VALUE;
1655
1656     if (pkt->dts == AV_NOPTS_VALUE)
1657         opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
1658     else
1659         opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1660     opkt.dts -= ost_tb_start_time;
1661
1662     opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1663     opkt.flags    = pkt->flags;
1664
1665     //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1666     if(   ost->st->codec->codec_id != CODEC_ID_H264
1667        && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
1668        && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
1669        ) {
1670         if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1671             opkt.destruct = av_destruct_packet;
1672     } else {
1673         opkt.data = pkt->data;
1674         opkt.size = pkt->size;
1675     }
1676     if (of->ctx->oformat->flags & AVFMT_RAWPICTURE) {
1677         /* store AVPicture in AVPacket, as expected by the output format */
1678         avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1679         opkt.data = (uint8_t *)&pict;
1680         opkt.size = sizeof(AVPicture);
1681         opkt.flags |= AV_PKT_FLAG_KEY;
1682     }
1683
1684     write_frame(of->ctx, &opkt, ost->st->codec, ost->bitstream_filters);
1685     ost->st->codec->frame_number++;
1686     ost->frame_number++;
1687     av_free_packet(&opkt);
1688 }
1689
1690 static void rate_emu_sleep(InputStream *ist)
1691 {
1692     if (input_files[ist->file_index].rate_emu) {
1693         int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
1694         int64_t now = av_gettime() - ist->start;
1695         if (pts > now)
1696             usleep(pts - now);
1697     }
1698 }
1699
1700 static int transcode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1701 {
1702     AVFrame *decoded_frame;
1703     AVCodecContext *avctx = ist->st->codec;
1704     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
1705     int i, ret;
1706
1707     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1708         return AVERROR(ENOMEM);
1709     else
1710         avcodec_get_frame_defaults(ist->decoded_frame);
1711     decoded_frame = ist->decoded_frame;
1712
1713     ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1714     if (ret < 0) {
1715         return ret;
1716     }
1717
1718     if (!*got_output) {
1719         /* no audio frame */
1720         return ret;
1721     }
1722
1723     /* if the decoder provides a pts, use it instead of the last packet pts.
1724        the decoder could be delaying output by a packet or more. */
1725     if (decoded_frame->pts != AV_NOPTS_VALUE)
1726         ist->next_pts = decoded_frame->pts;
1727
1728     /* increment next_pts to use for the case where the input stream does not
1729        have timestamps or there are multiple frames in the packet */
1730     ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1731                      avctx->sample_rate;
1732
1733     // preprocess audio (volume)
1734     if (audio_volume != 256) {
1735         int decoded_data_size = decoded_frame->nb_samples * avctx->channels * bps;
1736         void *samples = decoded_frame->data[0];
1737         switch (avctx->sample_fmt) {
1738         case AV_SAMPLE_FMT_U8:
1739         {
1740             uint8_t *volp = samples;
1741             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1742                 int v = (((*volp - 128) * audio_volume + 128) >> 8) + 128;
1743                 *volp++ = av_clip_uint8(v);
1744             }
1745             break;
1746         }
1747         case AV_SAMPLE_FMT_S16:
1748         {
1749             int16_t *volp = samples;
1750             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1751                 int v = ((*volp) * audio_volume + 128) >> 8;
1752                 *volp++ = av_clip_int16(v);
1753             }
1754             break;
1755         }
1756         case AV_SAMPLE_FMT_S32:
1757         {
1758             int32_t *volp = samples;
1759             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1760                 int64_t v = (((int64_t)*volp * audio_volume + 128) >> 8);
1761                 *volp++ = av_clipl_int32(v);
1762             }
1763             break;
1764         }
1765         case AV_SAMPLE_FMT_FLT:
1766         {
1767             float *volp = samples;
1768             float scale = audio_volume / 256.f;
1769             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1770                 *volp++ *= scale;
1771             }
1772             break;
1773         }
1774         case AV_SAMPLE_FMT_DBL:
1775         {
1776             double *volp = samples;
1777             double scale = audio_volume / 256.;
1778             for (i = 0; i < (decoded_data_size / sizeof(*volp)); i++) {
1779                 *volp++ *= scale;
1780             }
1781             break;
1782         }
1783         default:
1784             av_log(NULL, AV_LOG_FATAL,
1785                    "Audio volume adjustment on sample format %s is not supported.\n",
1786                    av_get_sample_fmt_name(ist->st->codec->sample_fmt));
1787             exit_program(1);
1788         }
1789     }
1790
1791     rate_emu_sleep(ist);
1792
1793     for (i = 0; i < nb_output_streams; i++) {
1794         OutputStream *ost = &output_streams[i];
1795
1796         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1797             continue;
1798         do_audio_out(output_files[ost->file_index].ctx, ost, ist, decoded_frame);
1799     }
1800
1801     return ret;
1802 }
1803
1804 static int transcode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *pkt_pts)
1805 {
1806     AVFrame *decoded_frame, *filtered_frame = NULL;
1807     void *buffer_to_free = NULL;
1808     int i, ret = 0;
1809     float quality;
1810 #if CONFIG_AVFILTER
1811     int frame_available = 1;
1812 #endif
1813
1814     if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1815         return AVERROR(ENOMEM);
1816     else
1817         avcodec_get_frame_defaults(ist->decoded_frame);
1818     decoded_frame = ist->decoded_frame;
1819     pkt->pts  = *pkt_pts;
1820     pkt->dts  = ist->pts;
1821     *pkt_pts  = AV_NOPTS_VALUE;
1822
1823     ret = avcodec_decode_video2(ist->st->codec,
1824                                 decoded_frame, got_output, pkt);
1825     if (ret < 0)
1826         return ret;
1827
1828     quality = same_quant ? decoded_frame->quality : 0;
1829     if (!*got_output) {
1830         /* no picture yet */
1831         return ret;
1832     }
1833     ist->next_pts = ist->pts = decoded_frame->best_effort_timestamp;
1834     if (pkt->duration)
1835         ist->next_pts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1836     else if (ist->st->codec->time_base.num != 0) {
1837         int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
1838                                            ist->st->codec->ticks_per_frame;
1839         ist->next_pts += ((int64_t)AV_TIME_BASE *
1840                           ist->st->codec->time_base.num * ticks) /
1841                           ist->st->codec->time_base.den;
1842     }
1843     pkt->size = 0;
1844     pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1845
1846     rate_emu_sleep(ist);
1847
1848     for (i = 0; i < nb_output_streams; i++) {
1849         OutputStream *ost = &output_streams[i];
1850         int frame_size;
1851
1852         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1853             continue;
1854
1855 #if CONFIG_AVFILTER
1856         if (ost->input_video_filter) {
1857             if (!decoded_frame->sample_aspect_ratio.num)
1858                 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1859             decoded_frame->pts = ist->pts;
1860
1861             av_vsrc_buffer_add_frame(ost->input_video_filter, decoded_frame, AV_VSRC_BUF_FLAG_OVERWRITE);
1862             if (!ist->filtered_frame && !(ist->filtered_frame = avcodec_alloc_frame())) {
1863                 av_free(buffer_to_free);
1864                 return AVERROR(ENOMEM);
1865             } else
1866                 avcodec_get_frame_defaults(ist->filtered_frame);
1867             filtered_frame = ist->filtered_frame;
1868             frame_available = avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1869         }
1870         while (frame_available) {
1871             if (ost->output_video_filter) {
1872                 AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
1873                 if (av_buffersink_get_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
1874                     goto cont;
1875                 if (ost->picref) {
1876                     avfilter_fill_frame_from_video_buffer_ref(filtered_frame, ost->picref);
1877                     ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
1878                 }
1879             }
1880             if (ost->picref->video && !ost->frame_aspect_ratio)
1881                 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
1882 #else
1883             filtered_frame = decoded_frame;
1884 #endif
1885
1886             do_video_out(output_files[ost->file_index].ctx, ost, ist, filtered_frame, &frame_size,
1887                          same_quant ? quality : ost->st->codec->global_quality);
1888             if (vstats_filename && frame_size)
1889                 do_video_stats(output_files[ost->file_index].ctx, ost, frame_size);
1890 #if CONFIG_AVFILTER
1891             cont:
1892             frame_available = ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
1893             if (ost->picref)
1894                 avfilter_unref_buffer(ost->picref);
1895         }
1896 #endif
1897     }
1898
1899     av_free(buffer_to_free);
1900     return ret;
1901 }
1902
1903 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1904 {
1905     AVSubtitle subtitle;
1906     int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1907                                           &subtitle, got_output, pkt);
1908     if (ret < 0)
1909         return ret;
1910     if (!*got_output)
1911         return ret;
1912
1913     rate_emu_sleep(ist);
1914
1915     for (i = 0; i < nb_output_streams; i++) {
1916         OutputStream *ost = &output_streams[i];
1917
1918         if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1919             continue;
1920
1921         do_subtitle_out(output_files[ost->file_index].ctx, ost, ist, &subtitle, pkt->pts);
1922     }
1923
1924     avsubtitle_free(&subtitle);
1925     return ret;
1926 }
1927
1928 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1929 static int output_packet(InputStream *ist,
1930                          OutputStream *ost_table, int nb_ostreams,
1931                          const AVPacket *pkt)
1932 {
1933     int i;
1934     int got_output;
1935     int64_t pkt_pts = AV_NOPTS_VALUE;
1936     AVPacket avpkt;
1937
1938     if (ist->next_pts == AV_NOPTS_VALUE)
1939         ist->next_pts = ist->pts;
1940
1941     if (pkt == NULL) {
1942         /* EOF handling */
1943         av_init_packet(&avpkt);
1944         avpkt.data = NULL;
1945         avpkt.size = 0;
1946         goto handle_eof;
1947     } else {
1948         avpkt = *pkt;
1949     }
1950
1951     if(pkt->dts != AV_NOPTS_VALUE)
1952         ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1953     if(pkt->pts != AV_NOPTS_VALUE)
1954         pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1955
1956     //while we have more to decode or while the decoder did output something on EOF
1957     while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1958         int ret = 0;
1959     handle_eof:
1960
1961         ist->pts = ist->next_pts;
1962
1963         if (avpkt.size && avpkt.size != pkt->size) {
1964             av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1965                    "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1966             ist->showed_multi_packet_warning = 1;
1967         }
1968
1969         switch(ist->st->codec->codec_type) {
1970         case AVMEDIA_TYPE_AUDIO:
1971             ret = transcode_audio    (ist, &avpkt, &got_output);
1972             break;
1973         case AVMEDIA_TYPE_VIDEO:
1974             ret = transcode_video    (ist, &avpkt, &got_output, &pkt_pts);
1975             break;
1976         case AVMEDIA_TYPE_SUBTITLE:
1977             ret = transcode_subtitles(ist, &avpkt, &got_output);
1978             break;
1979         default:
1980             return -1;
1981         }
1982
1983         if (ret < 0)
1984             return ret;
1985         // touch data and size only if not EOF
1986         if (pkt) {
1987             avpkt.data += ret;
1988             avpkt.size -= ret;
1989         }
1990         if (!got_output) {
1991             continue;
1992         }
1993     }
1994
1995     /* handle stream copy */
1996     if (!ist->decoding_needed) {
1997         rate_emu_sleep(ist);
1998         ist->pts = ist->next_pts;
1999         switch (ist->st->codec->codec_type) {
2000         case AVMEDIA_TYPE_AUDIO:
2001             ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
2002                              ist->st->codec->sample_rate;
2003             break;
2004         case AVMEDIA_TYPE_VIDEO:
2005             if (ist->st->codec->time_base.num != 0) {
2006                 int ticks = ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
2007                 ist->next_pts += ((int64_t)AV_TIME_BASE *
2008                                   ist->st->codec->time_base.num * ticks) /
2009                                   ist->st->codec->time_base.den;
2010             }
2011             break;
2012         }
2013     }
2014     for (i = 0; pkt && i < nb_ostreams; i++) {
2015         OutputStream *ost = &ost_table[i];
2016
2017         if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2018             continue;
2019
2020         do_streamcopy(ist, ost, pkt);
2021     }
2022
2023     return 0;
2024 }
2025
2026 static void print_sdp(OutputFile *output_files, int n)
2027 {
2028     char sdp[2048];
2029     int i;
2030     AVFormatContext **avc = av_malloc(sizeof(*avc)*n);
2031
2032     if (!avc)
2033         exit_program(1);
2034     for (i = 0; i < n; i++)
2035         avc[i] = output_files[i].ctx;
2036
2037     av_sdp_create(avc, n, sdp, sizeof(sdp));
2038     printf("SDP:\n%s\n", sdp);
2039     fflush(stdout);
2040     av_freep(&avc);
2041 }
2042
2043 static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
2044                              char *error, int error_len)
2045 {
2046     int i;
2047     InputStream *ist = &input_streams[ist_index];
2048     if (ist->decoding_needed) {
2049         AVCodec *codec = ist->dec;
2050         if (!codec) {
2051             snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
2052                     ist->st->codec->codec_id, ist->file_index, ist->st->index);
2053             return AVERROR(EINVAL);
2054         }
2055
2056         if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
2057             snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
2058                     ist->file_index, ist->st->index);
2059             return AVERROR(EINVAL);
2060         }
2061         assert_codec_experimental(ist->st->codec, 0);
2062         assert_avoptions(ist->opts);
2063     }
2064
2065     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;
2066     ist->next_pts = AV_NOPTS_VALUE;
2067     ist->is_start = 1;
2068
2069     return 0;
2070 }
2071
2072 static int transcode_init(OutputFile *output_files,
2073                           int nb_output_files,
2074                           InputFile *input_files,
2075                           int nb_input_files)
2076 {
2077     int ret = 0, i, j, k;
2078     AVFormatContext *oc;
2079     AVCodecContext *codec, *icodec;
2080     OutputStream *ost;
2081     InputStream *ist;
2082     char error[1024];
2083     int want_sdp = 1;
2084
2085     /* init framerate emulation */
2086     for (i = 0; i < nb_input_files; i++) {
2087         InputFile *ifile = &input_files[i];
2088         if (ifile->rate_emu)
2089             for (j = 0; j < ifile->nb_streams; j++)
2090                 input_streams[j + ifile->ist_index].start = av_gettime();
2091     }
2092
2093     /* output stream init */
2094     for (i = 0; i < nb_output_files; i++) {
2095         oc = output_files[i].ctx;
2096         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2097             av_dump_format(oc, i, oc->filename, 1);
2098             av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2099             return AVERROR(EINVAL);
2100         }
2101     }
2102
2103     /* for each output stream, we compute the right encoding parameters */
2104     for (i = 0; i < nb_output_streams; i++) {
2105         ost = &output_streams[i];
2106         oc  = output_files[ost->file_index].ctx;
2107         ist = &input_streams[ost->source_index];
2108
2109         if (ost->attachment_filename)
2110             continue;
2111
2112         codec  = ost->st->codec;
2113         icodec = ist->st->codec;
2114
2115         ost->st->disposition          = ist->st->disposition;
2116         codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2117         codec->chroma_sample_location = icodec->chroma_sample_location;
2118
2119         if (ost->stream_copy) {
2120             uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2121
2122             if (extra_size > INT_MAX) {
2123                 return AVERROR(EINVAL);
2124             }
2125
2126             /* if stream_copy is selected, no need to decode or encode */
2127             codec->codec_id   = icodec->codec_id;
2128             codec->codec_type = icodec->codec_type;
2129
2130             if (!codec->codec_tag) {
2131                 if (!oc->oformat->codec_tag ||
2132                      av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2133                      av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
2134                     codec->codec_tag = icodec->codec_tag;
2135             }
2136
2137             codec->bit_rate       = icodec->bit_rate;
2138             codec->rc_max_rate    = icodec->rc_max_rate;
2139             codec->rc_buffer_size = icodec->rc_buffer_size;
2140             codec->extradata      = av_mallocz(extra_size);
2141             if (!codec->extradata) {
2142                 return AVERROR(ENOMEM);
2143             }
2144             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2145
2146             codec->extradata_size = icodec->extradata_size;
2147             if (!copy_tb) {
2148                 codec->time_base      = icodec->time_base;
2149                 codec->time_base.num *= icodec->ticks_per_frame;
2150                 av_reduce(&codec->time_base.num, &codec->time_base.den,
2151                           codec->time_base.num, codec->time_base.den, INT_MAX);
2152             } else
2153                 codec->time_base = ist->st->time_base;
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);
3427
3428         MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
3429         if (frame_pix_fmt&nbs