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