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