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