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