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