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