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