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