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