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