]> git.sesse.net Git - ffmpeg/blob - ffmpeg.c
Remove the GOP "g" OptionDef option from ffmpeg.c .
[ffmpeg] / ffmpeg.c
1 /*
2  * FFmpeg main
3  * Copyright (c) 2000-2003 Fabrice Bellard
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 #define HAVE_AV_CONFIG_H
20 #include <limits.h>
21 #include "avformat.h"
22 #include "swscale.h"
23 #include "framehook.h"
24 #include "dsputil.h"
25 #include "opt.h"
26
27 #ifndef __MINGW32__
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <sys/ioctl.h>
31 #include <sys/time.h>
32 #include <termios.h>
33 #include <sys/resource.h>
34 #include <signal.h>
35 #endif
36 #ifdef CONFIG_OS2
37 #include <sys/types.h>
38 #include <sys/select.h>
39 #include <stdlib.h>
40 #endif
41 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
42 #include <time.h>
43
44 #include "version.h"
45 #include "cmdutils.h"
46
47 #undef NDEBUG
48 #include <assert.h>
49
50 #if !defined(INFINITY) && defined(HUGE_VAL)
51 #define INFINITY HUGE_VAL
52 #endif
53
54 /* select an input stream for an output stream */
55 typedef struct AVStreamMap {
56     int file_index;
57     int stream_index;
58     int sync_file_index;
59     int sync_stream_index;
60 } AVStreamMap;
61
62 /** select an input file for an output file */
63 typedef struct AVMetaDataMap {
64     int out_file;
65     int in_file;
66 } AVMetaDataMap;
67
68 extern const OptionDef options[];
69
70 static void show_help(void);
71 static void show_license(void);
72 static int opt_default(const char *opt, const char *arg);
73
74 #define MAX_FILES 20
75
76 static AVFormatContext *input_files[MAX_FILES];
77 static int64_t input_files_ts_offset[MAX_FILES];
78 static int nb_input_files = 0;
79
80 static AVFormatContext *output_files[MAX_FILES];
81 static int nb_output_files = 0;
82
83 static AVStreamMap stream_maps[MAX_FILES];
84 static int nb_stream_maps;
85
86 static AVMetaDataMap meta_data_maps[MAX_FILES];
87 static int nb_meta_data_maps;
88
89 static AVInputFormat *file_iformat;
90 static AVOutputFormat *file_oformat;
91 static AVImageFormat *image_format;
92 static int frame_width  = 0;
93 static int frame_height = 0;
94 static float frame_aspect_ratio = 0;
95 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
96 static int frame_padtop  = 0;
97 static int frame_padbottom = 0;
98 static int frame_padleft  = 0;
99 static int frame_padright = 0;
100 static int padcolor[3] = {16,128,128}; /* default to black */
101 static int frame_topBand  = 0;
102 static int frame_bottomBand = 0;
103 static int frame_leftBand  = 0;
104 static int frame_rightBand = 0;
105 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
106 static int frame_rate = 25;
107 static int frame_rate_base = 1;
108 static int video_bit_rate_tolerance = 4000*1000;
109 static float video_qscale = 0;
110 static int video_qmin = 2;
111 static int video_qmax = 31;
112 static int video_lmin = 2*FF_QP2LAMBDA;
113 static int video_lmax = 31*FF_QP2LAMBDA;
114 static int video_mb_lmin = 2*FF_QP2LAMBDA;
115 static int video_mb_lmax = 31*FF_QP2LAMBDA;
116 static int video_qdiff = 3;
117 static float video_qblur = 0.5;
118 static float video_qsquish = 0.0;
119 static float video_qcomp = 0.5;
120 static uint16_t *intra_matrix = NULL;
121 static uint16_t *inter_matrix = NULL;
122 #if 0 //experimental, (can be removed)
123 static float video_rc_qsquish=1.0;
124 static float video_rc_qmod_amp=0;
125 static int video_rc_qmod_freq=0;
126 #endif
127 static char *video_rc_override_string=NULL;
128 static char *video_rc_eq="tex^qComp";
129 static int video_rc_buffer_size=0;
130 static float video_rc_buffer_aggressivity=1.0;
131 static float video_rc_initial_cplx=0;
132 static float video_b_qfactor = 1.25;
133 static float video_b_qoffset = 1.25;
134 static float video_i_qfactor = -0.8;
135 static float video_i_qoffset = 0.0;
136 static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
137 static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
138 static int me_method = ME_EPZS;
139 static int video_disable = 0;
140 static int video_discard = 0;
141 static int video_codec_id = CODEC_ID_NONE;
142 static int video_codec_tag = 0;
143 static int same_quality = 0;
144 static int b_frames = 0;
145 static int pre_me = 0;
146 static int do_deinterlace = 0;
147 static int workaround_bugs = FF_BUG_AUTODETECT;
148 static int packet_size = 0;
149 static int error_rate = 0;
150 static int strict = 0;
151 static int top_field_first = -1;
152 static int sc_threshold = 0;
153 static int me_threshold = 0;
154 static int mb_threshold = 0;
155 static int intra_dc_precision = 8;
156 static int me_penalty_compensation= 256;
157 static int frame_skip_threshold= 0;
158 static int frame_skip_factor= 0;
159 static int frame_skip_exp= 0;
160 static int loop_input = 0;
161 static int loop_output = AVFMT_NOOUTPUTLOOP;
162 static int qp_hist = 0;
163
164 static int intra_only = 0;
165 static int audio_sample_rate = 44100;
166 static int audio_bit_rate = 64000;
167 #define QSCALE_NONE -99999
168 static float audio_qscale = QSCALE_NONE;
169 static int audio_disable = 0;
170 static int audio_channels = 1;
171 static int audio_codec_id = CODEC_ID_NONE;
172 static int audio_codec_tag = 0;
173 static char *audio_language = NULL;
174
175 static int subtitle_codec_id = CODEC_ID_NONE;
176 static char *subtitle_language = NULL;
177
178 static int mux_rate= 0;
179 static int mux_packet_size= 0;
180 static float mux_preload= 0.5;
181 static float mux_max_delay= 0.7;
182
183 static int64_t recording_time = 0;
184 static int64_t start_time = 0;
185 static int64_t rec_timestamp = 0;
186 static int64_t input_ts_offset = 0;
187 static int file_overwrite = 0;
188 static char *str_title = NULL;
189 static char *str_author = NULL;
190 static char *str_copyright = NULL;
191 static char *str_comment = NULL;
192 static char *str_album = NULL;
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_vstats = 0;
198 static int do_pass = 0;
199 static char *pass_logfilename = NULL;
200 static int audio_stream_copy = 0;
201 static int video_stream_copy = 0;
202 static int subtitle_stream_copy = 0;
203 static int video_sync_method= 1;
204 static int audio_sync_method= 0;
205 static int copy_ts= 0;
206 static int opt_shortest = 0; //
207 static int video_global_header = 0;
208
209 static int rate_emu = 0;
210
211 #ifdef CONFIG_BKTR
212 static const char *video_grab_format = "bktr";
213 #else
214 #ifdef CONFIG_VIDEO4LINUX2
215 static const char *video_grab_format = "video4linux2";
216 #else
217 static const char *video_grab_format = "video4linux";
218 #endif
219 #endif
220 static char *video_device = NULL;
221 static char *grab_device = NULL;
222 static int  video_channel = 0;
223 static char *video_standard = "ntsc";
224
225 static const char *audio_grab_format = "audio_device";
226 static char *audio_device = NULL;
227 static int audio_volume = 256;
228
229 static int using_stdin = 0;
230 static int using_vhook = 0;
231 static int verbose = 1;
232 static int thread_count= 1;
233 static int q_pressed = 0;
234 static int me_range = 0;
235 static int64_t video_size = 0;
236 static int64_t audio_size = 0;
237 static int64_t extra_size = 0;
238 static int nb_frames_dup = 0;
239 static int nb_frames_drop = 0;
240 static int input_sync;
241 static int limit_filesize = 0; //
242
243 static int pgmyuv_compatibility_hack=0;
244 static int dts_delta_threshold = 10;
245
246 static int sws_flags = SWS_BICUBIC;
247
248 const char **opt_names=NULL;
249 int opt_name_count=0;
250 AVCodecContext *avctx_opts;
251 AVFormatContext *avformat_opts;
252
253 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
254 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
255 static AVBitStreamFilterContext *bitstream_filters[MAX_FILES][MAX_STREAMS];
256
257 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
258
259 struct AVInputStream;
260
261 typedef struct AVOutputStream {
262     int file_index;          /* file index */
263     int index;               /* stream index in the output file */
264     int source_index;        /* AVInputStream index */
265     AVStream *st;            /* stream in the output file */
266     int encoding_needed;     /* true if encoding needed for this stream */
267     int frame_number;
268     /* input pts and corresponding output pts
269        for A/V sync */
270     //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
271     struct AVInputStream *sync_ist; /* input stream to sync against */
272     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
273     /* video only */
274     int video_resample;
275     AVFrame pict_tmp;      /* temporary image for resampling */
276     struct SwsContext *img_resample_ctx; /* for image resampling */
277     int resample_height;
278
279     int video_crop;
280     int topBand;             /* cropping area sizes */
281     int leftBand;
282
283     int video_pad;
284     int padtop;              /* padding area sizes */
285     int padbottom;
286     int padleft;
287     int padright;
288
289     /* audio only */
290     int audio_resample;
291     ReSampleContext *resample; /* for audio resampling */
292     FifoBuffer fifo;     /* for compression: one audio fifo per codec */
293     FILE *logfile;
294 } AVOutputStream;
295
296 typedef struct AVInputStream {
297     int file_index;
298     int index;
299     AVStream *st;
300     int discard;             /* true if stream data should be discarded */
301     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
302     int64_t sample_index;      /* current sample */
303
304     int64_t       start;     /* time when read started */
305     unsigned long frame;     /* current frame */
306     int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
307                                 is not defined */
308     int64_t       pts;       /* current pts */
309     int is_start;            /* is 1 at the start and after a discontinuity */
310 } AVInputStream;
311
312 typedef struct AVInputFile {
313     int eof_reached;      /* true if eof reached */
314     int ist_index;        /* index of first stream in ist_table */
315     int buffer_size;      /* current total buffer size */
316     int buffer_size_max;  /* buffer size at which we consider we can stop
317                              buffering */
318     int nb_streams;       /* nb streams we are aware of */
319 } AVInputFile;
320
321 #ifndef __MINGW32__
322
323 /* init terminal so that we can grab keys */
324 static struct termios oldtty;
325
326 static void term_exit(void)
327 {
328     tcsetattr (0, TCSANOW, &oldtty);
329 }
330
331 static volatile sig_atomic_t received_sigterm = 0;
332
333 static void
334 sigterm_handler(int sig)
335 {
336     received_sigterm = sig;
337     term_exit();
338 }
339
340 static void term_init(void)
341 {
342     struct termios tty;
343
344     tcgetattr (0, &tty);
345     oldtty = tty;
346
347     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
348                           |INLCR|IGNCR|ICRNL|IXON);
349     tty.c_oflag |= OPOST;
350     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
351     tty.c_cflag &= ~(CSIZE|PARENB);
352     tty.c_cflag |= CS8;
353     tty.c_cc[VMIN] = 1;
354     tty.c_cc[VTIME] = 0;
355
356     tcsetattr (0, TCSANOW, &tty);
357
358     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
359     signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
360     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
361     /*
362     register a function to be called at normal program termination
363     */
364     atexit(term_exit);
365 #ifdef CONFIG_BEOS_NETSERVER
366     fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
367 #endif
368 }
369
370 /* read a key without blocking */
371 static int read_key(void)
372 {
373     int n = 1;
374     unsigned char ch;
375 #ifndef CONFIG_BEOS_NETSERVER
376     struct timeval tv;
377     fd_set rfds;
378
379     FD_ZERO(&rfds);
380     FD_SET(0, &rfds);
381     tv.tv_sec = 0;
382     tv.tv_usec = 0;
383     n = select(1, &rfds, NULL, NULL, &tv);
384 #endif
385     if (n > 0) {
386         n = read(0, &ch, 1);
387         if (n == 1)
388             return ch;
389
390         return n;
391     }
392     return -1;
393 }
394
395 static int decode_interrupt_cb(void)
396 {
397     return q_pressed || (q_pressed = read_key() == 'q');
398 }
399
400 #else
401
402 static volatile int received_sigterm = 0;
403
404 /* no interactive support */
405 static void term_exit(void)
406 {
407 }
408
409 static void term_init(void)
410 {
411 }
412
413 static int read_key(void)
414 {
415     return 0;
416 }
417
418 #endif
419
420 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
421 {
422     int i, err;
423     AVFormatContext *ic;
424
425     err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
426     if (err < 0)
427         return err;
428     /* copy stream format */
429     s->nb_streams = ic->nb_streams;
430     for(i=0;i<ic->nb_streams;i++) {
431         AVStream *st;
432
433         // FIXME: a more elegant solution is needed
434         st = av_mallocz(sizeof(AVStream));
435         memcpy(st, ic->streams[i], sizeof(AVStream));
436         st->codec = avcodec_alloc_context();
437         memcpy(st->codec, ic->streams[i]->codec, sizeof(AVCodecContext));
438         s->streams[i] = st;
439     }
440
441     av_close_input_file(ic);
442     return 0;
443 }
444
445 static double
446 get_sync_ipts(const AVOutputStream *ost)
447 {
448     const AVInputStream *ist = ost->sync_ist;
449     return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
450 }
451
452 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
453     while(bsfc){
454         AVPacket new_pkt= *pkt;
455         int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
456                                           &new_pkt.data, &new_pkt.size,
457                                           pkt->data, pkt->size,
458                                           pkt->flags & PKT_FLAG_KEY);
459         if(a){
460             av_free_packet(pkt);
461             new_pkt.destruct= av_destruct_packet;
462         }
463         *pkt= new_pkt;
464
465         bsfc= bsfc->next;
466     }
467
468     av_interleaved_write_frame(s, pkt);
469 }
470
471 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
472
473 static void do_audio_out(AVFormatContext *s,
474                          AVOutputStream *ost,
475                          AVInputStream *ist,
476                          unsigned char *buf, int size)
477 {
478     uint8_t *buftmp;
479     static uint8_t *audio_buf = NULL;
480     static uint8_t *audio_out = NULL;
481     const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
482
483     int size_out, frame_bytes, ret;
484     AVCodecContext *enc= ost->st->codec;
485
486     /* SC: dynamic allocation of buffers */
487     if (!audio_buf)
488         audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
489     if (!audio_out)
490         audio_out = av_malloc(audio_out_size);
491     if (!audio_buf || !audio_out)
492         return;               /* Should signal an error ! */
493
494     if(audio_sync_method){
495         double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
496                 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
497         double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
498         int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
499
500         //FIXME resample delay
501         if(fabs(delta) > 50){
502             if(ist->is_start){
503                 if(byte_delta < 0){
504                     byte_delta= FFMAX(byte_delta, -size);
505                     size += byte_delta;
506                     buf  -= byte_delta;
507                     if(verbose > 2)
508                         fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
509                     if(!size)
510                         return;
511                     ist->is_start=0;
512                 }else{
513                     static uint8_t *input_tmp= NULL;
514                     input_tmp= av_realloc(input_tmp, byte_delta + size);
515
516                     if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
517                         ist->is_start=0;
518                     else
519                         byte_delta= MAX_AUDIO_PACKET_SIZE - size;
520
521                     memset(input_tmp, 0, byte_delta);
522                     memcpy(input_tmp + byte_delta, buf, size);
523                     buf= input_tmp;
524                     size += byte_delta;
525                     if(verbose > 2)
526                         fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
527                 }
528             }else if(audio_sync_method>1){
529                 int comp= clip(delta, -audio_sync_method, audio_sync_method);
530                 assert(ost->audio_resample);
531                 if(verbose > 2)
532                     fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
533 //                fprintf(stderr, "drift:%f len:%d opts:%lld ipts:%lld fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2));
534                 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
535             }
536         }
537     }else
538         ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
539                         - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
540
541     if (ost->audio_resample) {
542         buftmp = audio_buf;
543         size_out = audio_resample(ost->resample,
544                                   (short *)buftmp, (short *)buf,
545                                   size / (ist->st->codec->channels * 2));
546         size_out = size_out * enc->channels * 2;
547     } else {
548         buftmp = buf;
549         size_out = size;
550     }
551
552     /* now encode as many frames as possible */
553     if (enc->frame_size > 1) {
554         /* output resampled raw samples */
555         fifo_write(&ost->fifo, buftmp, size_out,
556                    &ost->fifo.wptr);
557
558         frame_bytes = enc->frame_size * 2 * enc->channels;
559
560         while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
561                      &ost->fifo.rptr) == 0) {
562             AVPacket pkt;
563             av_init_packet(&pkt);
564
565             ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
566                                        (short *)audio_buf);
567             audio_size += ret;
568             pkt.stream_index= ost->index;
569             pkt.data= audio_out;
570             pkt.size= ret;
571             if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
572                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
573             pkt.flags |= PKT_FLAG_KEY;
574             write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
575
576             ost->sync_opts += enc->frame_size;
577         }
578     } else {
579         AVPacket pkt;
580         av_init_packet(&pkt);
581
582         ost->sync_opts += size_out / (2 * enc->channels);
583
584         /* output a pcm frame */
585         /* XXX: change encoding codec API to avoid this ? */
586         switch(enc->codec->id) {
587         case CODEC_ID_PCM_S32LE:
588         case CODEC_ID_PCM_S32BE:
589         case CODEC_ID_PCM_U32LE:
590         case CODEC_ID_PCM_U32BE:
591             size_out = size_out << 1;
592             break;
593         case CODEC_ID_PCM_S24LE:
594         case CODEC_ID_PCM_S24BE:
595         case CODEC_ID_PCM_U24LE:
596         case CODEC_ID_PCM_U24BE:
597         case CODEC_ID_PCM_S24DAUD:
598             size_out = size_out / 2 * 3;
599             break;
600         case CODEC_ID_PCM_S16LE:
601         case CODEC_ID_PCM_S16BE:
602         case CODEC_ID_PCM_U16LE:
603         case CODEC_ID_PCM_U16BE:
604             break;
605         default:
606             size_out = size_out >> 1;
607             break;
608         }
609         ret = avcodec_encode_audio(enc, audio_out, size_out,
610                                    (short *)buftmp);
611         audio_size += ret;
612         pkt.stream_index= ost->index;
613         pkt.data= audio_out;
614         pkt.size= ret;
615         if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
616             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
617         pkt.flags |= PKT_FLAG_KEY;
618         write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
619     }
620 }
621
622 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
623 {
624     AVCodecContext *dec;
625     AVPicture *picture2;
626     AVPicture picture_tmp;
627     uint8_t *buf = 0;
628
629     dec = ist->st->codec;
630
631     /* deinterlace : must be done before any resize */
632     if (do_deinterlace || using_vhook) {
633         int size;
634
635         /* create temporary picture */
636         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
637         buf = av_malloc(size);
638         if (!buf)
639             return;
640
641         picture2 = &picture_tmp;
642         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
643
644         if (do_deinterlace){
645             if(avpicture_deinterlace(picture2, picture,
646                                      dec->pix_fmt, dec->width, dec->height) < 0) {
647                 /* if error, do not deinterlace */
648                 av_free(buf);
649                 buf = NULL;
650                 picture2 = picture;
651             }
652         } else {
653             img_copy(picture2, picture, dec->pix_fmt, dec->width, dec->height);
654         }
655     } else {
656         picture2 = picture;
657     }
658
659     frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
660
661     if (picture != picture2)
662         *picture = *picture2;
663     *bufp = buf;
664 }
665
666 /* we begin to correct av delay at this threshold */
667 #define AV_DELAY_MAX 0.100
668
669 static void do_subtitle_out(AVFormatContext *s,
670                             AVOutputStream *ost,
671                             AVInputStream *ist,
672                             AVSubtitle *sub,
673                             int64_t pts)
674 {
675     static uint8_t *subtitle_out = NULL;
676     int subtitle_out_max_size = 65536;
677     int subtitle_out_size, nb, i;
678     AVCodecContext *enc;
679     AVPacket pkt;
680
681     if (pts == AV_NOPTS_VALUE) {
682         fprintf(stderr, "Subtitle packets must have a pts\n");
683         return;
684     }
685
686     enc = ost->st->codec;
687
688     if (!subtitle_out) {
689         subtitle_out = av_malloc(subtitle_out_max_size);
690     }
691
692     /* Note: DVB subtitle need one packet to draw them and one other
693        packet to clear them */
694     /* XXX: signal it in the codec context ? */
695     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
696         nb = 2;
697     else
698         nb = 1;
699
700     for(i = 0; i < nb; i++) {
701         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
702                                                     subtitle_out_max_size, sub);
703
704         av_init_packet(&pkt);
705         pkt.stream_index = ost->index;
706         pkt.data = subtitle_out;
707         pkt.size = subtitle_out_size;
708         pkt.pts = av_rescale_q(av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
709         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
710             /* XXX: the pts correction is handled here. Maybe handling
711                it in the codec would be better */
712             if (i == 0)
713                 pkt.pts += 90 * sub->start_display_time;
714             else
715                 pkt.pts += 90 * sub->end_display_time;
716         }
717         write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
718     }
719 }
720
721 static int bit_buffer_size= 1024*256;
722 static uint8_t *bit_buffer= NULL;
723
724 static void do_video_out(AVFormatContext *s,
725                          AVOutputStream *ost,
726                          AVInputStream *ist,
727                          AVFrame *in_picture,
728                          int *frame_size)
729 {
730     int nb_frames, i, ret;
731     AVFrame *final_picture, *formatted_picture, *resampling_dst, *padding_src;
732     AVFrame picture_crop_temp, picture_pad_temp;
733     uint8_t *buf = NULL, *buf1 = NULL;
734     AVCodecContext *enc, *dec;
735
736     avcodec_get_frame_defaults(&picture_crop_temp);
737     avcodec_get_frame_defaults(&picture_pad_temp);
738
739     enc = ost->st->codec;
740     dec = ist->st->codec;
741
742     /* by default, we output a single frame */
743     nb_frames = 1;
744
745     *frame_size = 0;
746
747     if(video_sync_method){
748         double vdelta;
749         vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
750         //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
751         if (vdelta < -1.1)
752             nb_frames = 0;
753         else if (vdelta > 1.1)
754             nb_frames = lrintf(vdelta);
755 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
756         if (nb_frames == 0){
757             ++nb_frames_drop;
758             if (verbose>2)
759                 fprintf(stderr, "*** drop!\n");
760         }else if (nb_frames > 1) {
761             nb_frames_dup += nb_frames;
762             if (verbose>2)
763                 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
764         }
765     }else
766         ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
767
768     nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
769     if (nb_frames <= 0)
770         return;
771
772     if (ost->video_crop) {
773         if (img_crop((AVPicture *)&picture_crop_temp, (AVPicture *)in_picture, dec->pix_fmt, ost->topBand, ost->leftBand) < 0) {
774             av_log(NULL, AV_LOG_ERROR, "error cropping picture\n");
775             goto the_end;
776         }
777         formatted_picture = &picture_crop_temp;
778     } else {
779         formatted_picture = in_picture;
780     }
781
782     final_picture = formatted_picture;
783     padding_src = formatted_picture;
784     resampling_dst = &ost->pict_tmp;
785     if (ost->video_pad) {
786         final_picture = &ost->pict_tmp;
787         if (ost->video_resample) {
788             if (img_crop((AVPicture *)&picture_pad_temp, (AVPicture *)final_picture, enc->pix_fmt, ost->padtop, ost->padleft) < 0) {
789                 av_log(NULL, AV_LOG_ERROR, "error padding picture\n");
790                 goto the_end;
791             }
792             resampling_dst = &picture_pad_temp;
793         }
794     }
795
796     if (ost->video_resample) {
797         padding_src = NULL;
798         final_picture = &ost->pict_tmp;
799         sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
800               0, ost->resample_height, resampling_dst->data, resampling_dst->linesize);
801     }
802
803     if (ost->video_pad) {
804         img_pad((AVPicture*)final_picture, (AVPicture *)padding_src,
805                 enc->height, enc->width, enc->pix_fmt,
806                 ost->padtop, ost->padbottom, ost->padleft, ost->padright, padcolor);
807     }
808
809     /* duplicates frame if needed */
810     for(i=0;i<nb_frames;i++) {
811         AVPacket pkt;
812         av_init_packet(&pkt);
813         pkt.stream_index= ost->index;
814
815         if (s->oformat->flags & AVFMT_RAWPICTURE) {
816             /* raw pictures are written as AVPicture structure to
817                avoid any copies. We support temorarily the older
818                method. */
819             AVFrame* old_frame = enc->coded_frame;
820             enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
821             pkt.data= (uint8_t *)final_picture;
822             pkt.size=  sizeof(AVPicture);
823             if(dec->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
824                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
825             if(dec->coded_frame && dec->coded_frame->key_frame)
826                 pkt.flags |= PKT_FLAG_KEY;
827
828             write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
829             enc->coded_frame = old_frame;
830         } else {
831             AVFrame big_picture;
832
833             big_picture= *final_picture;
834             /* better than nothing: use input picture interlaced
835                settings */
836             big_picture.interlaced_frame = in_picture->interlaced_frame;
837             if(avctx_opts->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)){
838                 if(top_field_first == -1)
839                     big_picture.top_field_first = in_picture->top_field_first;
840                 else
841                     big_picture.top_field_first = top_field_first;
842             }
843
844             /* handles sameq here. This is not correct because it may
845                not be a global option */
846             if (same_quality) {
847                 big_picture.quality = ist->st->quality;
848             }else
849                 big_picture.quality = ost->st->quality;
850             if(!me_threshold)
851                 big_picture.pict_type = 0;
852 //            big_picture.pts = AV_NOPTS_VALUE;
853             big_picture.pts= ost->sync_opts;
854 //            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
855 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
856             ret = avcodec_encode_video(enc,
857                                        bit_buffer, bit_buffer_size,
858                                        &big_picture);
859             //enc->frame_number = enc->real_pict_num;
860             if(ret>0){
861                 pkt.data= bit_buffer;
862                 pkt.size= ret;
863                 if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
864                     pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
865 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n",
866    pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
867    pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
868
869                 if(enc->coded_frame && enc->coded_frame->key_frame)
870                     pkt.flags |= PKT_FLAG_KEY;
871                 write_frame(s, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
872                 *frame_size = ret;
873                 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
874                 //        enc->frame_number-1, enc->real_pict_num, ret,
875                 //        enc->pict_type);
876                 /* if two pass, output log */
877                 if (ost->logfile && enc->stats_out) {
878                     fprintf(ost->logfile, "%s", enc->stats_out);
879                 }
880             }
881         }
882         ost->sync_opts++;
883         ost->frame_number++;
884     }
885  the_end:
886     av_free(buf);
887     av_free(buf1);
888 }
889
890 static double psnr(double d){
891     if(d==0) return INFINITY;
892     return -10.0*log(d)/log(10.0);
893 }
894
895 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
896                            int frame_size)
897 {
898     static FILE *fvstats=NULL;
899     char filename[40];
900     time_t today2;
901     struct tm *today;
902     AVCodecContext *enc;
903     int frame_number;
904     int64_t ti;
905     double ti1, bitrate, avg_bitrate;
906
907     if (!fvstats) {
908         today2 = time(NULL);
909         today = localtime(&today2);
910         snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
911                                                today->tm_min,
912                                                today->tm_sec);
913         fvstats = fopen(filename,"w");
914         if (!fvstats) {
915             perror("fopen");
916             exit(1);
917         }
918     }
919
920     ti = MAXINT64;
921     enc = ost->st->codec;
922     if (enc->codec_type == CODEC_TYPE_VIDEO) {
923         frame_number = ost->frame_number;
924         fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
925         if (enc->flags&CODEC_FLAG_PSNR)
926             fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
927
928         fprintf(fvstats,"f_size= %6d ", frame_size);
929         /* compute pts value */
930         ti1 = ost->sync_opts * av_q2d(enc->time_base);
931         if (ti1 < 0.01)
932             ti1 = 0.01;
933
934         bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
935         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
936         fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
937             (double)video_size / 1024, ti1, bitrate, avg_bitrate);
938         fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));
939     }
940 }
941
942 static void print_report(AVFormatContext **output_files,
943                          AVOutputStream **ost_table, int nb_ostreams,
944                          int is_last_report)
945 {
946     char buf[1024];
947     AVOutputStream *ost;
948     AVFormatContext *oc, *os;
949     int64_t total_size;
950     AVCodecContext *enc;
951     int frame_number, vid, i;
952     double bitrate, ti1, pts;
953     static int64_t last_time = -1;
954     static int qp_histogram[52];
955
956     if (!is_last_report) {
957         int64_t cur_time;
958         /* display the report every 0.5 seconds */
959         cur_time = av_gettime();
960         if (last_time == -1) {
961             last_time = cur_time;
962             return;
963         }
964         if ((cur_time - last_time) < 500000)
965             return;
966         last_time = cur_time;
967     }
968
969
970     oc = output_files[0];
971
972     total_size = url_ftell(&oc->pb);
973
974     buf[0] = '\0';
975     ti1 = 1e10;
976     vid = 0;
977     for(i=0;i<nb_ostreams;i++) {
978         ost = ost_table[i];
979         os = output_files[ost->file_index];
980         enc = ost->st->codec;
981         if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
982             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
983                     enc->coded_frame->quality/(float)FF_QP2LAMBDA);
984         }
985         if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
986             frame_number = ost->frame_number;
987             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%3.1f ",
988                     frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : -1);
989             if(is_last_report)
990                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
991             if(qp_hist && enc->coded_frame){
992                 int j;
993                 int qp= lrintf(enc->coded_frame->quality/(float)FF_QP2LAMBDA);
994                 if(qp>=0 && qp<sizeof(qp_histogram)/sizeof(int))
995                     qp_histogram[qp]++;
996                 for(j=0; j<32; j++)
997                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
998             }
999             if (enc->flags&CODEC_FLAG_PSNR){
1000                 int j;
1001                 double error, error_sum=0;
1002                 double scale, scale_sum=0;
1003                 char type[3]= {'Y','U','V'};
1004                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1005                 for(j=0; j<3; j++){
1006                     if(is_last_report){
1007                         error= enc->error[j];
1008                         scale= enc->width*enc->height*255.0*255.0*frame_number;
1009                     }else{
1010                         error= enc->coded_frame->error[j];
1011                         scale= enc->width*enc->height*255.0*255.0;
1012                     }
1013                     if(j) scale/=4;
1014                     error_sum += error;
1015                     scale_sum += scale;
1016                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
1017                 }
1018                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
1019             }
1020             vid = 1;
1021         }
1022         /* compute min output value */
1023         pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
1024         if ((pts < ti1) && (pts > 0))
1025             ti1 = pts;
1026     }
1027     if (ti1 < 0.01)
1028         ti1 = 0.01;
1029
1030     if (verbose || is_last_report) {
1031         bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1032
1033         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1034             "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1035             (double)total_size / 1024, ti1, bitrate);
1036
1037         if (verbose > 1)
1038           snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1039                   nb_frames_dup, nb_frames_drop);
1040
1041         if (verbose >= 0)
1042             fprintf(stderr, "%s    \r", buf);
1043
1044         fflush(stderr);
1045     }
1046
1047     if (is_last_report && verbose >= 0){
1048         int64_t raw= audio_size + video_size + extra_size;
1049         fprintf(stderr, "\n");
1050         fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
1051                 video_size/1024.0,
1052                 audio_size/1024.0,
1053                 extra_size/1024.0,
1054                 100.0*(total_size - raw)/raw
1055         );
1056     }
1057 }
1058
1059 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1060 static int output_packet(AVInputStream *ist, int ist_index,
1061                          AVOutputStream **ost_table, int nb_ostreams,
1062                          const AVPacket *pkt)
1063 {
1064     AVFormatContext *os;
1065     AVOutputStream *ost;
1066     uint8_t *ptr;
1067     int len, ret, i;
1068     uint8_t *data_buf;
1069     int data_size, got_picture;
1070     AVFrame picture;
1071     void *buffer_to_free;
1072     static unsigned int samples_size= 0;
1073     static short *samples= NULL;
1074     AVSubtitle subtitle, *subtitle_to_free;
1075     int got_subtitle;
1076
1077     if(!pkt){
1078         ist->pts= ist->next_pts; // needed for last packet if vsync=0
1079     } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
1080         ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1081     } else {
1082 //        assert(ist->pts == ist->next_pts);
1083     }
1084
1085     if (pkt == NULL) {
1086         /* EOF handling */
1087         ptr = NULL;
1088         len = 0;
1089         goto handle_eof;
1090     }
1091
1092     len = pkt->size;
1093     ptr = pkt->data;
1094     while (len > 0) {
1095     handle_eof:
1096         /* decode the packet if needed */
1097         data_buf = NULL; /* fail safe */
1098         data_size = 0;
1099         subtitle_to_free = NULL;
1100         if (ist->decoding_needed) {
1101             switch(ist->st->codec->codec_type) {
1102             case CODEC_TYPE_AUDIO:{
1103                 if(pkt)
1104                     samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
1105                     /* XXX: could avoid copy if PCM 16 bits with same
1106                        endianness as CPU */
1107                 ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
1108                                            ptr, len);
1109                 if (ret < 0)
1110                     goto fail_decode;
1111                 ptr += ret;
1112                 len -= ret;
1113                 /* Some bug in mpeg audio decoder gives */
1114                 /* data_size < 0, it seems they are overflows */
1115                 if (data_size <= 0) {
1116                     /* no audio frame */
1117                     continue;
1118                 }
1119                 data_buf = (uint8_t *)samples;
1120                 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) /
1121                     (ist->st->codec->sample_rate * ist->st->codec->channels);
1122                 break;}
1123             case CODEC_TYPE_VIDEO:
1124                     data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
1125                     /* XXX: allocate picture correctly */
1126                     avcodec_get_frame_defaults(&picture);
1127
1128                     ret = avcodec_decode_video(ist->st->codec,
1129                                                &picture, &got_picture, ptr, len);
1130                     ist->st->quality= picture.quality;
1131                     if (ret < 0)
1132                         goto fail_decode;
1133                     if (!got_picture) {
1134                         /* no picture yet */
1135                         goto discard_packet;
1136                     }
1137                     if (ist->st->codec->time_base.num != 0) {
1138                         ist->next_pts += ((int64_t)AV_TIME_BASE *
1139                                           ist->st->codec->time_base.num) /
1140                             ist->st->codec->time_base.den;
1141                     }
1142                     len = 0;
1143                     break;
1144             case CODEC_TYPE_SUBTITLE:
1145                 ret = avcodec_decode_subtitle(ist->st->codec,
1146                                               &subtitle, &got_subtitle, ptr, len);
1147                 if (ret < 0)
1148                     goto fail_decode;
1149                 if (!got_subtitle) {
1150                     goto discard_packet;
1151                 }
1152                 subtitle_to_free = &subtitle;
1153                 len = 0;
1154                 break;
1155             default:
1156                 goto fail_decode;
1157             }
1158         } else {
1159                 switch(ist->st->codec->codec_type) {
1160                 case CODEC_TYPE_AUDIO:
1161                     ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1162                         (ist->st->codec->sample_rate * ist->st->codec->channels);
1163                     break;
1164                 case CODEC_TYPE_VIDEO:
1165                     if (ist->st->codec->time_base.num != 0) {
1166                         ist->next_pts += ((int64_t)AV_TIME_BASE *
1167                                           ist->st->codec->time_base.num) /
1168                             ist->st->codec->time_base.den;
1169                     }
1170                     break;
1171                 }
1172                 data_buf = ptr;
1173                 data_size = len;
1174                 ret = len;
1175                 len = 0;
1176             }
1177
1178             buffer_to_free = NULL;
1179             if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1180                 pre_process_video_frame(ist, (AVPicture *)&picture,
1181                                         &buffer_to_free);
1182             }
1183
1184             // preprocess audio (volume)
1185             if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
1186                 if (audio_volume != 256) {
1187                     short *volp;
1188                     volp = samples;
1189                     for(i=0;i<(data_size / sizeof(short));i++) {
1190                         int v = ((*volp) * audio_volume + 128) >> 8;
1191                         if (v < -32768) v = -32768;
1192                         if (v >  32767) v = 32767;
1193                         *volp++ = v;
1194                     }
1195                 }
1196             }
1197
1198             /* frame rate emulation */
1199             if (ist->st->codec->rate_emu) {
1200                 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
1201                 int64_t now = av_gettime() - ist->start;
1202                 if (pts > now)
1203                     usleep(pts - now);
1204
1205                 ist->frame++;
1206             }
1207
1208 #if 0
1209             /* mpeg PTS deordering : if it is a P or I frame, the PTS
1210                is the one of the next displayed one */
1211             /* XXX: add mpeg4 too ? */
1212             if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
1213                 if (ist->st->codec->pict_type != B_TYPE) {
1214                     int64_t tmp;
1215                     tmp = ist->last_ip_pts;
1216                     ist->last_ip_pts  = ist->frac_pts.val;
1217                     ist->frac_pts.val = tmp;
1218                 }
1219             }
1220 #endif
1221             /* if output time reached then transcode raw format,
1222                encode packets and output them */
1223             if (start_time == 0 || ist->pts >= start_time)
1224                 for(i=0;i<nb_ostreams;i++) {
1225                     int frame_size;
1226
1227                     ost = ost_table[i];
1228                     if (ost->source_index == ist_index) {
1229                         os = output_files[ost->file_index];
1230
1231 #if 0
1232                         printf("%d: got pts=%0.3f %0.3f\n", i,
1233                                (double)pkt->pts / AV_TIME_BASE,
1234                                ((double)ist->pts / AV_TIME_BASE) -
1235                                ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
1236 #endif
1237                         /* set the input output pts pairs */
1238                         //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
1239
1240                         if (ost->encoding_needed) {
1241                             switch(ost->st->codec->codec_type) {
1242                             case CODEC_TYPE_AUDIO:
1243                                 do_audio_out(os, ost, ist, data_buf, data_size);
1244                                 break;
1245                             case CODEC_TYPE_VIDEO:
1246                                     do_video_out(os, ost, ist, &picture, &frame_size);
1247                                     video_size += frame_size;
1248                                     if (do_vstats && frame_size)
1249                                         do_video_stats(os, ost, frame_size);
1250                                 break;
1251                             case CODEC_TYPE_SUBTITLE:
1252                                 do_subtitle_out(os, ost, ist, &subtitle,
1253                                                 pkt->pts);
1254                                 break;
1255                             default:
1256                                 av_abort();
1257                             }
1258                         } else {
1259                             AVFrame avframe; //FIXME/XXX remove this
1260                             AVPacket opkt;
1261                             av_init_packet(&opkt);
1262
1263                             /* no reencoding needed : output the packet directly */
1264                             /* force the input stream PTS */
1265
1266                             avcodec_get_frame_defaults(&avframe);
1267                             ost->st->codec->coded_frame= &avframe;
1268                             avframe.key_frame = pkt->flags & PKT_FLAG_KEY;
1269
1270                             if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
1271                                 audio_size += data_size;
1272                             else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
1273                                 video_size += data_size;
1274                                 ost->sync_opts++;
1275                             }
1276
1277                             opkt.stream_index= ost->index;
1278                             if(pkt->pts != AV_NOPTS_VALUE)
1279                                 opkt.pts= av_rescale_q(av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
1280                             else
1281                                 opkt.pts= AV_NOPTS_VALUE;
1282
1283                             {
1284                                 int64_t dts;
1285                                 if (pkt->dts == AV_NOPTS_VALUE)
1286                                     dts = ist->next_pts;
1287                                 else
1288                                     dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1289                                 opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
1290                             }
1291                             opkt.flags= pkt->flags;
1292
1293                             //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1294                             if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
1295                                 opkt.destruct= av_destruct_packet;
1296
1297                             write_frame(os, &opkt, ost->st->codec, bitstream_filters[ost->file_index][pkt->stream_index]);
1298                             ost->st->codec->frame_number++;
1299                             ost->frame_number++;
1300                             av_free_packet(&opkt);
1301                         }
1302                     }
1303                 }
1304             av_free(buffer_to_free);
1305             /* XXX: allocate the subtitles in the codec ? */
1306             if (subtitle_to_free) {
1307                 if (subtitle_to_free->rects != NULL) {
1308                     for (i = 0; i < subtitle_to_free->num_rects; i++) {
1309                         av_free(subtitle_to_free->rects[i].bitmap);
1310                         av_free(subtitle_to_free->rects[i].rgba_palette);
1311                     }
1312                     av_freep(&subtitle_to_free->rects);
1313                 }
1314                 subtitle_to_free->num_rects = 0;
1315                 subtitle_to_free = NULL;
1316             }
1317         }
1318  discard_packet:
1319     if (pkt == NULL) {
1320         /* EOF handling */
1321
1322         for(i=0;i<nb_ostreams;i++) {
1323             ost = ost_table[i];
1324             if (ost->source_index == ist_index) {
1325                 AVCodecContext *enc= ost->st->codec;
1326                 os = output_files[ost->file_index];
1327
1328                 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
1329                     continue;
1330                 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
1331                     continue;
1332
1333                 if (ost->encoding_needed) {
1334                     for(;;) {
1335                         AVPacket pkt;
1336                         int fifo_bytes;
1337                         av_init_packet(&pkt);
1338                         pkt.stream_index= ost->index;
1339
1340                         switch(ost->st->codec->codec_type) {
1341                         case CODEC_TYPE_AUDIO:
1342                             fifo_bytes = fifo_size(&ost->fifo, NULL);
1343                             ret = 0;
1344                             /* encode any samples remaining in fifo */
1345                             if(fifo_bytes > 0 && enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
1346                                 int fs_tmp = enc->frame_size;
1347                                 enc->frame_size = fifo_bytes / (2 * enc->channels);
1348                                 if(fifo_read(&ost->fifo, (uint8_t *)samples, fifo_bytes,
1349                                         &ost->fifo.rptr) == 0) {
1350                                     ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, samples);
1351                                 }
1352                                 enc->frame_size = fs_tmp;
1353                             }
1354                             if(ret <= 0) {
1355                                 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
1356                             }
1357                             audio_size += ret;
1358                             pkt.flags |= PKT_FLAG_KEY;
1359                             break;
1360                         case CODEC_TYPE_VIDEO:
1361                             ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
1362                             video_size += ret;
1363                             if(enc->coded_frame && enc->coded_frame->key_frame)
1364                                 pkt.flags |= PKT_FLAG_KEY;
1365                             if (ost->logfile && enc->stats_out) {
1366                                 fprintf(ost->logfile, "%s", enc->stats_out);
1367                             }
1368                             break;
1369                         default:
1370                             ret=-1;
1371                         }
1372
1373                         if(ret<=0)
1374                             break;
1375                         pkt.data= bit_buffer;
1376                         pkt.size= ret;
1377                         if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
1378                             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
1379                         write_frame(os, &pkt, ost->st->codec, bitstream_filters[ost->file_index][pkt.stream_index]);
1380                     }
1381                 }
1382             }
1383         }
1384     }
1385
1386     return 0;
1387  fail_decode:
1388     return -1;
1389 }
1390
1391
1392 /*
1393  * The following code is the main loop of the file converter
1394  */
1395 static int av_encode(AVFormatContext **output_files,
1396                      int nb_output_files,
1397                      AVFormatContext **input_files,
1398                      int nb_input_files,
1399                      AVStreamMap *stream_maps, int nb_stream_maps)
1400 {
1401     int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
1402     AVFormatContext *is, *os;
1403     AVCodecContext *codec, *icodec;
1404     AVOutputStream *ost, **ost_table = NULL;
1405     AVInputStream *ist, **ist_table = NULL;
1406     AVInputFile *file_table;
1407     AVFormatContext *stream_no_data;
1408     int key;
1409
1410     file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
1411     if (!file_table)
1412         goto fail;
1413
1414     /* input stream init */
1415     j = 0;
1416     for(i=0;i<nb_input_files;i++) {
1417         is = input_files[i];
1418         file_table[i].ist_index = j;
1419         file_table[i].nb_streams = is->nb_streams;
1420         j += is->nb_streams;
1421     }
1422     nb_istreams = j;
1423
1424     ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
1425     if (!ist_table)
1426         goto fail;
1427
1428     for(i=0;i<nb_istreams;i++) {
1429         ist = av_mallocz(sizeof(AVInputStream));
1430         if (!ist)
1431             goto fail;
1432         ist_table[i] = ist;
1433     }
1434     j = 0;
1435     for(i=0;i<nb_input_files;i++) {
1436         is = input_files[i];
1437         for(k=0;k<is->nb_streams;k++) {
1438             ist = ist_table[j++];
1439             ist->st = is->streams[k];
1440             ist->file_index = i;
1441             ist->index = k;
1442             ist->discard = 1; /* the stream is discarded by default
1443                                  (changed later) */
1444
1445             if (ist->st->codec->rate_emu) {
1446                 ist->start = av_gettime();
1447                 ist->frame = 0;
1448             }
1449         }
1450     }
1451
1452     /* output stream init */
1453     nb_ostreams = 0;
1454     for(i=0;i<nb_output_files;i++) {
1455         os = output_files[i];
1456         nb_ostreams += os->nb_streams;
1457     }
1458     if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
1459         fprintf(stderr, "Number of stream maps must match number of output streams\n");
1460         exit(1);
1461     }
1462
1463     /* Sanity check the mapping args -- do the input files & streams exist? */
1464     for(i=0;i<nb_stream_maps;i++) {
1465         int fi = stream_maps[i].file_index;
1466         int si = stream_maps[i].stream_index;
1467
1468         if (fi < 0 || fi > nb_input_files - 1 ||
1469             si < 0 || si > file_table[fi].nb_streams - 1) {
1470             fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
1471             exit(1);
1472         }
1473         fi = stream_maps[i].sync_file_index;
1474         si = stream_maps[i].sync_stream_index;
1475         if (fi < 0 || fi > nb_input_files - 1 ||
1476             si < 0 || si > file_table[fi].nb_streams - 1) {
1477             fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
1478             exit(1);
1479         }
1480     }
1481
1482     ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
1483     if (!ost_table)
1484         goto fail;
1485     for(i=0;i<nb_ostreams;i++) {
1486         ost = av_mallocz(sizeof(AVOutputStream));
1487         if (!ost)
1488             goto fail;
1489         ost_table[i] = ost;
1490     }
1491
1492     n = 0;
1493     for(k=0;k<nb_output_files;k++) {
1494         os = output_files[k];
1495         for(i=0;i<os->nb_streams;i++) {
1496             int found;
1497             ost = ost_table[n++];
1498             ost->file_index = k;
1499             ost->index = i;
1500             ost->st = os->streams[i];
1501             if (nb_stream_maps > 0) {
1502                 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
1503                     stream_maps[n-1].stream_index;
1504
1505                 /* Sanity check that the stream types match */
1506                 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
1507                     fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
1508                         stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
1509                         ost->file_index, ost->index);
1510                     exit(1);
1511                 }
1512
1513             } else {
1514                 /* get corresponding input stream index : we select the first one with the right type */
1515                 found = 0;
1516                 for(j=0;j<nb_istreams;j++) {
1517                     ist = ist_table[j];
1518                     if (ist->discard &&
1519                         ist->st->codec->codec_type == ost->st->codec->codec_type) {
1520                         ost->source_index = j;
1521                         found = 1;
1522                         break;
1523                     }
1524                 }
1525
1526                 if (!found) {
1527                     /* try again and reuse existing stream */
1528                     for(j=0;j<nb_istreams;j++) {
1529                         ist = ist_table[j];
1530                         if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
1531                             ost->source_index = j;
1532                             found = 1;
1533                         }
1534                     }
1535                     if (!found) {
1536                         fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
1537                                 ost->file_index, ost->index);
1538                         exit(1);
1539                     }
1540                 }
1541             }
1542             ist = ist_table[ost->source_index];
1543             ist->discard = 0;
1544             ost->sync_ist = (nb_stream_maps > 0) ?
1545                 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
1546                          stream_maps[n-1].sync_stream_index] : ist;
1547         }
1548     }
1549
1550     /* for each output stream, we compute the right encoding parameters */
1551     for(i=0;i<nb_ostreams;i++) {
1552         ost = ost_table[i];
1553         ist = ist_table[ost->source_index];
1554
1555         codec = ost->st->codec;
1556         icodec = ist->st->codec;
1557
1558         if (ost->st->stream_copy) {
1559             /* if stream_copy is selected, no need to decode or encode */
1560             codec->codec_id = icodec->codec_id;
1561             codec->codec_type = icodec->codec_type;
1562             if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
1563             codec->bit_rate = icodec->bit_rate;
1564             codec->extradata= icodec->extradata;
1565             codec->extradata_size= icodec->extradata_size;
1566             codec->time_base = icodec->time_base;
1567             switch(codec->codec_type) {
1568             case CODEC_TYPE_AUDIO:
1569                 codec->sample_rate = icodec->sample_rate;
1570                 codec->channels = icodec->channels;
1571                 codec->frame_size = icodec->frame_size;
1572                 codec->block_align= icodec->block_align;
1573                 break;
1574             case CODEC_TYPE_VIDEO:
1575                 codec->pix_fmt = icodec->pix_fmt;
1576                 codec->width = icodec->width;
1577                 codec->height = icodec->height;
1578                 codec->has_b_frames = icodec->has_b_frames;
1579                 break;
1580             case CODEC_TYPE_SUBTITLE:
1581                 break;
1582             default:
1583                 av_abort();
1584             }
1585         } else {
1586             switch(codec->codec_type) {
1587             case CODEC_TYPE_AUDIO:
1588                 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
1589                     goto fail;
1590
1591                 if (codec->channels == icodec->channels &&
1592                     codec->sample_rate == icodec->sample_rate) {
1593                     ost->audio_resample = 0;
1594                 } else {
1595                     if (codec->channels != icodec->channels &&
1596                         (icodec->codec_id == CODEC_ID_AC3 ||
1597                          icodec->codec_id == CODEC_ID_DTS)) {
1598                         /* Special case for 5:1 AC3 and DTS input */
1599                         /* and mono or stereo output      */
1600                         /* Request specific number of channels */
1601                         icodec->channels = codec->channels;
1602                         if (codec->sample_rate == icodec->sample_rate)
1603                             ost->audio_resample = 0;
1604                         else {
1605                             ost->audio_resample = 1;
1606                         }
1607                     } else {
1608                         ost->audio_resample = 1;
1609                     }
1610                 }
1611                 if(audio_sync_method>1)
1612                     ost->audio_resample = 1;
1613
1614                 if(ost->audio_resample){
1615                     ost->resample = audio_resample_init(codec->channels, icodec->channels,
1616                                                     codec->sample_rate, icodec->sample_rate);
1617                     if(!ost->resample){
1618                         printf("Can't resample.  Aborting.\n");
1619                         av_abort();
1620                     }
1621                 }
1622                 ist->decoding_needed = 1;
1623                 ost->encoding_needed = 1;
1624                 break;
1625             case CODEC_TYPE_VIDEO:
1626                 ost->video_crop = ((frame_leftBand + frame_rightBand + frame_topBand + frame_bottomBand) != 0);
1627                 ost->video_pad = ((frame_padleft + frame_padright + frame_padtop + frame_padbottom) != 0);
1628                 ost->video_resample = ((codec->width != icodec->width -
1629                                 (frame_leftBand + frame_rightBand) +
1630                                 (frame_padleft + frame_padright)) ||
1631                         (codec->height != icodec->height -
1632                                 (frame_topBand  + frame_bottomBand) +
1633                                 (frame_padtop + frame_padbottom)) ||
1634                         (codec->pix_fmt != icodec->pix_fmt));
1635                 if (ost->video_crop) {
1636                     ost->topBand = frame_topBand;
1637                     ost->leftBand = frame_leftBand;
1638                 }
1639                 if (ost->video_pad) {
1640                     ost->padtop = frame_padtop;
1641                     ost->padleft = frame_padleft;
1642                     ost->padbottom = frame_padbottom;
1643                     ost->padright = frame_padright;
1644                     if (!ost->video_resample) {
1645                         avcodec_get_frame_defaults(&ost->pict_tmp);
1646                         if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1647                                          codec->width, codec->height ) )
1648                             goto fail;
1649                     }
1650                 }
1651                 if (ost->video_resample) {
1652                     avcodec_get_frame_defaults(&ost->pict_tmp);
1653                     if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, codec->pix_fmt,
1654                                          codec->width, codec->height ) )
1655                         goto fail;
1656
1657                     ost->img_resample_ctx = sws_getContext(
1658                             icodec->width - (frame_leftBand + frame_rightBand),
1659                             icodec->height - (frame_topBand + frame_bottomBand),
1660                             icodec->pix_fmt,
1661                             codec->width - (frame_padleft + frame_padright),
1662                             codec->height - (frame_padtop + frame_padbottom),
1663                             codec->pix_fmt,
1664                             sws_flags, NULL, NULL, NULL);
1665                     if (ost->img_resample_ctx == NULL) {
1666                         fprintf(stderr, "Cannot get resampling context\n");
1667                         exit(1);
1668                     }
1669                     ost->resample_height = icodec->height - (frame_topBand + frame_bottomBand);
1670                 }
1671                 ost->encoding_needed = 1;
1672                 ist->decoding_needed = 1;
1673                 break;
1674             case CODEC_TYPE_SUBTITLE:
1675                 ost->encoding_needed = 1;
1676                 ist->decoding_needed = 1;
1677                 break;
1678             default:
1679                 av_abort();
1680                 break;
1681             }
1682             /* two pass mode */
1683             if (ost->encoding_needed &&
1684                 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
1685                 char logfilename[1024];
1686                 FILE *f;
1687                 int size;
1688                 char *logbuffer;
1689
1690                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
1691                          pass_logfilename ?
1692                          pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
1693                 if (codec->flags & CODEC_FLAG_PASS1) {
1694                     f = fopen(logfilename, "w");
1695                     if (!f) {
1696                         perror(logfilename);
1697                         exit(1);
1698                     }
1699                     ost->logfile = f;
1700                 } else {
1701                     /* read the log file */
1702                     f = fopen(logfilename, "r");
1703                     if (!f) {
1704                         perror(logfilename);
1705                         exit(1);
1706                     }
1707                     fseek(f, 0, SEEK_END);
1708                     size = ftell(f);
1709                     fseek(f, 0, SEEK_SET);
1710                     logbuffer = av_malloc(size + 1);
1711                     if (!logbuffer) {
1712                         fprintf(stderr, "Could not allocate log buffer\n");
1713                         exit(1);
1714                     }
1715                     size = fread(logbuffer, 1, size, f);
1716                     fclose(f);
1717                     logbuffer[size] = '\0';
1718                     codec->stats_in = logbuffer;
1719                 }
1720             }
1721         }
1722         if(codec->codec_type == CODEC_TYPE_VIDEO){
1723             int size= codec->width * codec->height;
1724             bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
1725         }
1726     }
1727
1728     if (!bit_buffer)
1729         bit_buffer = av_malloc(bit_buffer_size);
1730     if (!bit_buffer)
1731         goto fail;
1732
1733     /* dump the file output parameters - cannot be done before in case
1734        of stream copy */
1735     for(i=0;i<nb_output_files;i++) {
1736         dump_format(output_files[i], i, output_files[i]->filename, 1);
1737     }
1738
1739     /* dump the stream mapping */
1740     if (verbose >= 0) {
1741         fprintf(stderr, "Stream mapping:\n");
1742         for(i=0;i<nb_ostreams;i++) {
1743             ost = ost_table[i];
1744             fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
1745                     ist_table[ost->source_index]->file_index,
1746                     ist_table[ost->source_index]->index,
1747                     ost->file_index,
1748                     ost->index);
1749             if (ost->sync_ist != ist_table[ost->source_index])
1750                 fprintf(stderr, " [sync #%d.%d]",
1751                         ost->sync_ist->file_index,
1752                         ost->sync_ist->index);
1753             fprintf(stderr, "\n");
1754         }
1755     }
1756
1757     /* open each encoder */
1758     for(i=0;i<nb_ostreams;i++) {
1759         ost = ost_table[i];
1760         if (ost->encoding_needed) {
1761             AVCodec *codec;
1762             codec = avcodec_find_encoder(ost->st->codec->codec_id);
1763             if (!codec) {
1764                 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
1765                         ost->file_index, ost->index);
1766                 exit(1);
1767             }
1768             if (avcodec_open(ost->st->codec, codec) < 0) {
1769                 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
1770                         ost->file_index, ost->index);
1771                 exit(1);
1772             }
1773             extra_size += ost->st->codec->extradata_size;
1774         }
1775     }
1776
1777     /* open each decoder */
1778     for(i=0;i<nb_istreams;i++) {
1779         ist = ist_table[i];
1780         if (ist->decoding_needed) {
1781             AVCodec *codec;
1782             codec = avcodec_find_decoder(ist->st->codec->codec_id);
1783             if (!codec) {
1784                 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n",
1785                         ist->st->codec->codec_id, ist->file_index, ist->index);
1786                 exit(1);
1787             }
1788             if (avcodec_open(ist->st->codec, codec) < 0) {
1789                 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
1790                         ist->file_index, ist->index);
1791                 exit(1);
1792             }
1793             //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
1794             //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
1795         }
1796     }
1797
1798     /* init pts */
1799     for(i=0;i<nb_istreams;i++) {
1800         ist = ist_table[i];
1801         is = input_files[ist->file_index];
1802         ist->pts = 0;
1803         ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
1804         if(ist->st->start_time == AV_NOPTS_VALUE)
1805             ist->next_pts=0;
1806         if(input_files_ts_offset[ist->file_index])
1807             ist->next_pts= AV_NOPTS_VALUE;
1808         ist->is_start = 1;
1809     }
1810
1811     /* compute buffer size max (should use a complete heuristic) */
1812     for(i=0;i<nb_input_files;i++) {
1813         file_table[i].buffer_size_max = 2048;
1814     }
1815
1816     /* set meta data information from input file if required */
1817     for (i=0;i<nb_meta_data_maps;i++) {
1818         AVFormatContext *out_file;
1819         AVFormatContext *in_file;
1820
1821         int out_file_index = meta_data_maps[i].out_file;
1822         int in_file_index = meta_data_maps[i].in_file;
1823         if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
1824             fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
1825             ret = -EINVAL;
1826             goto fail;
1827         }
1828         if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
1829             fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
1830             ret = -EINVAL;
1831             goto fail;
1832         }
1833
1834         out_file = output_files[out_file_index];
1835         in_file = input_files[in_file_index];
1836
1837         strcpy(out_file->title, in_file->title);
1838         strcpy(out_file->author, in_file->author);
1839         strcpy(out_file->copyright, in_file->copyright);
1840         strcpy(out_file->comment, in_file->comment);
1841         strcpy(out_file->album, in_file->album);
1842         out_file->year = in_file->year;
1843         out_file->track = in_file->track;
1844         strcpy(out_file->genre, in_file->genre);
1845     }
1846
1847     /* open files and write file headers */
1848     for(i=0;i<nb_output_files;i++) {
1849         os = output_files[i];
1850         if (av_write_header(os) < 0) {
1851             fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
1852             ret = -EINVAL;
1853             goto fail;
1854         }
1855     }
1856
1857 #ifndef __MINGW32__
1858     if ( !using_stdin && verbose >= 0) {
1859         fprintf(stderr, "Press [q] to stop encoding\n");
1860         url_set_interrupt_cb(decode_interrupt_cb);
1861     }
1862 #endif
1863     term_init();
1864
1865     stream_no_data = 0;
1866     key = -1;
1867
1868     for(; received_sigterm == 0;) {
1869         int file_index, ist_index;
1870         AVPacket pkt;
1871         double ipts_min;
1872         double opts_min;
1873
1874     redo:
1875         ipts_min= 1e100;
1876         opts_min= 1e100;
1877         /* if 'q' pressed, exits */
1878         if (!using_stdin) {
1879             if (q_pressed)
1880                 break;
1881             /* read_key() returns 0 on EOF */
1882             key = read_key();
1883             if (key == 'q')
1884                 break;
1885         }
1886
1887         /* select the stream that we must read now by looking at the
1888            smallest output pts */
1889         file_index = -1;
1890         for(i=0;i<nb_ostreams;i++) {
1891             double ipts, opts;
1892             ost = ost_table[i];
1893             os = output_files[ost->file_index];
1894             ist = ist_table[ost->source_index];
1895             if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
1896                 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
1897             else
1898                 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
1899             ipts = (double)ist->pts;
1900             if (!file_table[ist->file_index].eof_reached){
1901                 if(ipts < ipts_min) {
1902                     ipts_min = ipts;
1903                     if(input_sync ) file_index = ist->file_index;
1904                 }
1905                 if(opts < opts_min) {
1906                     opts_min = opts;
1907                     if(!input_sync) file_index = ist->file_index;
1908                 }
1909             }
1910             if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
1911                 file_index= -1;
1912                 break;
1913             }
1914         }
1915         /* if none, if is finished */
1916         if (file_index < 0) {
1917             break;
1918         }
1919
1920         /* finish if recording time exhausted */
1921         if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
1922             break;
1923
1924         /* finish if limit size exhausted */
1925         if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
1926             break;
1927
1928         /* read a frame from it and output it in the fifo */
1929         is = input_files[file_index];
1930         if (av_read_frame(is, &pkt) < 0) {
1931             file_table[file_index].eof_reached = 1;
1932             if (opt_shortest) break; else continue; //
1933         }
1934
1935         if (!pkt.size) {
1936             stream_no_data = is;
1937         } else {
1938             stream_no_data = 0;
1939         }
1940         if (do_pkt_dump) {
1941             av_pkt_dump(stdout, &pkt, do_hex_dump);
1942         }
1943         /* the following test is needed in case new streams appear
1944            dynamically in stream : we ignore them */
1945         if (pkt.stream_index >= file_table[file_index].nb_streams)
1946             goto discard_packet;
1947         ist_index = file_table[file_index].ist_index + pkt.stream_index;
1948         ist = ist_table[ist_index];
1949         if (ist->discard)
1950             goto discard_packet;
1951
1952 //        fprintf(stderr, "next:%lld dts:%lld off:%lld %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);
1953         if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
1954             int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
1955             if(ABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE && !copy_ts){
1956                 input_files_ts_offset[ist->file_index]-= delta;
1957                 if (verbose > 2)
1958                     fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
1959                 for(i=0; i<file_table[file_index].nb_streams; i++){
1960                     int index= file_table[file_index].ist_index + i;
1961                     ist_table[index]->next_pts += delta;
1962                     ist_table[index]->is_start=1;
1963                 }
1964             }
1965         }
1966
1967         //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
1968         if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
1969
1970             if (verbose >= 0)
1971                 fprintf(stderr, "Error while decoding stream #%d.%d\n",
1972                         ist->file_index, ist->index);
1973
1974             av_free_packet(&pkt);
1975             goto redo;
1976         }
1977
1978     discard_packet:
1979         av_free_packet(&pkt);
1980
1981         /* dump report by using the output first video and audio streams */
1982         print_report(output_files, ost_table, nb_ostreams, 0);
1983     }
1984
1985     /* at the end of stream, we must flush the decoder buffers */
1986     for(i=0;i<nb_istreams;i++) {
1987         ist = ist_table[i];
1988         if (ist->decoding_needed) {
1989             output_packet(ist, i, ost_table, nb_ostreams, NULL);
1990         }
1991     }
1992
1993     term_exit();
1994
1995     /* write the trailer if needed and close file */
1996     for(i=0;i<nb_output_files;i++) {
1997         os = output_files[i];
1998         av_write_trailer(os);
1999     }
2000
2001     /* dump report by using the first video and audio streams */
2002     print_report(output_files, ost_table, nb_ostreams, 1);
2003
2004     /* close each encoder */
2005     for(i=0;i<nb_ostreams;i++) {
2006         ost = ost_table[i];
2007         if (ost->encoding_needed) {
2008             av_freep(&ost->st->codec->stats_in);
2009             avcodec_close(ost->st->codec);
2010         }
2011     }
2012
2013     /* close each decoder */
2014     for(i=0;i<nb_istreams;i++) {
2015         ist = ist_table[i];
2016         if (ist->decoding_needed) {
2017             avcodec_close(ist->st->codec);
2018         }
2019     }
2020
2021     /* finished ! */
2022
2023     ret = 0;
2024  fail1:
2025     av_freep(&bit_buffer);
2026     av_free(file_table);
2027
2028     if (ist_table) {
2029         for(i=0;i<nb_istreams;i++) {
2030             ist = ist_table[i];
2031             av_free(ist);
2032         }
2033         av_free(ist_table);
2034     }
2035     if (ost_table) {
2036         for(i=0;i<nb_ostreams;i++) {
2037             ost = ost_table[i];
2038             if (ost) {
2039                 if (ost->logfile) {
2040                     fclose(ost->logfile);
2041                     ost->logfile = NULL;
2042                 }
2043                 fifo_free(&ost->fifo); /* works even if fifo is not
2044                                           initialized but set to zero */
2045                 av_free(ost->pict_tmp.data[0]);
2046                 if (ost->video_resample)
2047                     sws_freeContext(ost->img_resample_ctx);
2048                 if (ost->audio_resample)
2049                     audio_resample_close(ost->resample);
2050                 av_free(ost);
2051             }
2052         }
2053         av_free(ost_table);
2054     }
2055     return ret;
2056  fail:
2057     ret = -ENOMEM;
2058     goto fail1;
2059 }
2060
2061 #if 0
2062 int file_read(const char *filename)
2063 {
2064     URLContext *h;
2065     unsigned char buffer[1024];
2066     int len, i;
2067
2068     if (url_open(&h, filename, O_RDONLY) < 0) {
2069         printf("could not open '%s'\n", filename);
2070         return -1;
2071     }
2072     for(;;) {
2073         len = url_read(h, buffer, sizeof(buffer));
2074         if (len <= 0)
2075             break;
2076         for(i=0;i<len;i++) putchar(buffer[i]);
2077     }
2078     url_close(h);
2079     return 0;
2080 }
2081 #endif
2082
2083 static void opt_image_format(const char *arg)
2084 {
2085     AVImageFormat *f;
2086
2087     for(f = first_image_format; f != NULL; f = f->next) {
2088         if (!strcmp(arg, f->name))
2089             break;
2090     }
2091     if (!f) {
2092         fprintf(stderr, "Unknown image format: '%s'\n", arg);
2093         exit(1);
2094     }
2095     image_format = f;
2096 }
2097
2098 static void opt_format(const char *arg)
2099 {
2100     /* compatibility stuff for pgmyuv */
2101     if (!strcmp(arg, "pgmyuv")) {
2102         pgmyuv_compatibility_hack=1;
2103 //        opt_image_format(arg);
2104         arg = "image2";
2105     }
2106
2107     file_iformat = av_find_input_format(arg);
2108     file_oformat = guess_format(arg, NULL, NULL);
2109     if (!file_iformat && !file_oformat) {
2110         fprintf(stderr, "Unknown input or output format: %s\n", arg);
2111         exit(1);
2112     }
2113 }
2114
2115 static void opt_video_bitrate_tolerance(const char *arg)
2116 {
2117     video_bit_rate_tolerance = atoi(arg) * 1000;
2118 }
2119
2120 static void opt_video_buffer_size(const char *arg)
2121 {
2122     video_rc_buffer_size = atoi(arg) * 8*1024;
2123 }
2124
2125 static void opt_video_rc_eq(char *arg)
2126 {
2127     video_rc_eq = arg;
2128 }
2129
2130 static void opt_video_rc_override_string(char *arg)
2131 {
2132     video_rc_override_string = arg;
2133 }
2134
2135
2136 static void opt_workaround_bugs(const char *arg)
2137 {
2138     workaround_bugs = atoi(arg);
2139 }
2140
2141 static void opt_me_threshold(const char *arg)
2142 {
2143     me_threshold = atoi(arg);
2144 }
2145
2146 static void opt_mb_threshold(const char *arg)
2147 {
2148     mb_threshold = atoi(arg);
2149 }
2150
2151 static void opt_verbose(const char *arg)
2152 {
2153     verbose = atoi(arg);
2154     av_log_set_level(atoi(arg));
2155 }
2156
2157 static void opt_frame_rate(const char *arg)
2158 {
2159     if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
2160         fprintf(stderr, "Incorrect frame rate\n");
2161         exit(1);
2162     }
2163 }
2164
2165 static void opt_frame_crop_top(const char *arg)
2166 {
2167     frame_topBand = atoi(arg);
2168     if (frame_topBand < 0) {
2169         fprintf(stderr, "Incorrect top crop size\n");
2170         exit(1);
2171     }
2172     if ((frame_topBand % 2) != 0) {
2173         fprintf(stderr, "Top crop size must be a multiple of 2\n");
2174         exit(1);
2175     }
2176     if ((frame_topBand) >= frame_height){
2177         fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2178         exit(1);
2179     }
2180     frame_height -= frame_topBand;
2181 }
2182
2183 static void opt_frame_crop_bottom(const char *arg)
2184 {
2185     frame_bottomBand = atoi(arg);
2186     if (frame_bottomBand < 0) {
2187         fprintf(stderr, "Incorrect bottom crop size\n");
2188         exit(1);
2189     }
2190     if ((frame_bottomBand % 2) != 0) {
2191         fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
2192         exit(1);
2193     }
2194     if ((frame_bottomBand) >= frame_height){
2195         fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2196         exit(1);
2197     }
2198     frame_height -= frame_bottomBand;
2199 }
2200
2201 static void opt_frame_crop_left(const char *arg)
2202 {
2203     frame_leftBand = atoi(arg);
2204     if (frame_leftBand < 0) {
2205         fprintf(stderr, "Incorrect left crop size\n");
2206         exit(1);
2207     }
2208     if ((frame_leftBand % 2) != 0) {
2209         fprintf(stderr, "Left crop size must be a multiple of 2\n");
2210         exit(1);
2211     }
2212     if ((frame_leftBand) >= frame_width){
2213         fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2214         exit(1);
2215     }
2216     frame_width -= frame_leftBand;
2217 }
2218
2219 static void opt_frame_crop_right(const char *arg)
2220 {
2221     frame_rightBand = atoi(arg);
2222     if (frame_rightBand < 0) {
2223         fprintf(stderr, "Incorrect right crop size\n");
2224         exit(1);
2225     }
2226     if ((frame_rightBand % 2) != 0) {
2227         fprintf(stderr, "Right crop size must be a multiple of 2\n");
2228         exit(1);
2229     }
2230     if ((frame_rightBand) >= frame_width){
2231         fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
2232         exit(1);
2233     }
2234     frame_width -= frame_rightBand;
2235 }
2236
2237 static void opt_frame_size(const char *arg)
2238 {
2239     if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
2240         fprintf(stderr, "Incorrect frame size\n");
2241         exit(1);
2242     }
2243     if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
2244         fprintf(stderr, "Frame size must be a multiple of 2\n");
2245         exit(1);
2246     }
2247 }
2248
2249
2250 #define SCALEBITS 10
2251 #define ONE_HALF  (1 << (SCALEBITS - 1))
2252 #define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
2253
2254 #define RGB_TO_Y(r, g, b) \
2255 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
2256   FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
2257
2258 #define RGB_TO_U(r1, g1, b1, shift)\
2259 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
2260      FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2261
2262 #define RGB_TO_V(r1, g1, b1, shift)\
2263 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
2264    FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
2265
2266 static void opt_pad_color(const char *arg) {
2267     /* Input is expected to be six hex digits similar to
2268        how colors are expressed in html tags (but without the #) */
2269     int rgb = strtol(arg, NULL, 16);
2270     int r,g,b;
2271
2272     r = (rgb >> 16);
2273     g = ((rgb >> 8) & 255);
2274     b = (rgb & 255);
2275
2276     padcolor[0] = RGB_TO_Y(r,g,b);
2277     padcolor[1] = RGB_TO_U(r,g,b,0);
2278     padcolor[2] = RGB_TO_V(r,g,b,0);
2279 }
2280
2281 static void opt_frame_pad_top(const char *arg)
2282 {
2283     frame_padtop = atoi(arg);
2284     if (frame_padtop < 0) {
2285         fprintf(stderr, "Incorrect top pad size\n");
2286         exit(1);
2287     }
2288     if ((frame_padtop % 2) != 0) {
2289         fprintf(stderr, "Top pad size must be a multiple of 2\n");
2290         exit(1);
2291     }
2292 }
2293
2294 static void opt_frame_pad_bottom(const char *arg)
2295 {
2296     frame_padbottom = atoi(arg);
2297     if (frame_padbottom < 0) {
2298         fprintf(stderr, "Incorrect bottom pad size\n");
2299         exit(1);
2300     }
2301     if ((frame_padbottom % 2) != 0) {
2302         fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
2303         exit(1);
2304     }
2305 }
2306
2307
2308 static void opt_frame_pad_left(const char *arg)
2309 {
2310     frame_padleft = atoi(arg);
2311     if (frame_padleft < 0) {
2312         fprintf(stderr, "Incorrect left pad size\n");
2313         exit(1);
2314     }
2315     if ((frame_padleft % 2) != 0) {
2316         fprintf(stderr, "Left pad size must be a multiple of 2\n");
2317         exit(1);
2318     }
2319 }
2320
2321
2322 static void opt_frame_pad_right(const char *arg)
2323 {
2324     frame_padright = atoi(arg);
2325     if (frame_padright < 0) {
2326         fprintf(stderr, "Incorrect right pad size\n");
2327         exit(1);
2328     }
2329     if ((frame_padright % 2) != 0) {
2330         fprintf(stderr, "Right pad size must be a multiple of 2\n");
2331         exit(1);
2332     }
2333 }
2334
2335
2336 static void opt_frame_pix_fmt(const char *arg)
2337 {
2338     frame_pix_fmt = avcodec_get_pix_fmt(arg);
2339 }
2340
2341 static void opt_frame_aspect_ratio(const char *arg)
2342 {
2343     int x = 0, y = 0;
2344     double ar = 0;
2345     const char *p;
2346
2347     p = strchr(arg, ':');
2348     if (p) {
2349         x = strtol(arg, (char **)&arg, 10);
2350         if (arg == p)
2351             y = strtol(arg+1, (char **)&arg, 10);
2352         if (x > 0 && y > 0)
2353             ar = (double)x / (double)y;
2354     } else
2355         ar = strtod(arg, (char **)&arg);
2356
2357     if (!ar) {
2358         fprintf(stderr, "Incorrect aspect ratio specification.\n");
2359         exit(1);
2360     }
2361     frame_aspect_ratio = ar;
2362 }
2363
2364 static void opt_b_frames(const char *arg)
2365 {
2366     b_frames = atoi(arg);
2367     if (b_frames > FF_MAX_B_FRAMES) {
2368         fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
2369         exit(1);
2370     } else if (b_frames < 1) {
2371         fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
2372         exit(1);
2373     }
2374 }
2375
2376 static void opt_pre_me(const char *arg)
2377 {
2378     pre_me = atoi(arg);
2379 }
2380
2381 static void opt_qscale(const char *arg)
2382 {
2383     video_qscale = atof(arg);
2384     if (video_qscale <= 0 ||
2385         video_qscale > 255) {
2386         fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
2387         exit(1);
2388     }
2389 }
2390
2391 static void opt_qsquish(const char *arg)
2392 {
2393     video_qsquish = atof(arg);
2394     if (video_qsquish < 0.0 ||
2395         video_qsquish > 99.0) {
2396         fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
2397         exit(1);
2398     }
2399 }
2400
2401 static void opt_lmax(const char *arg)
2402 {
2403     video_lmax = atof(arg)*FF_QP2LAMBDA;
2404 }
2405
2406 static void opt_lmin(const char *arg)
2407 {
2408     video_lmin = atof(arg)*FF_QP2LAMBDA;
2409 }
2410
2411 static void opt_qmin(const char *arg)
2412 {
2413     video_qmin = atoi(arg);
2414     if (video_qmin < 1 ||
2415         video_qmin > 51) {
2416         fprintf(stderr, "qmin must be >= 1 and <= 51\n");
2417         exit(1);
2418     }
2419 }
2420
2421 static void opt_qmax(const char *arg)
2422 {
2423     video_qmax = atoi(arg);
2424     if (video_qmax < 1 ||
2425         video_qmax > 51) {
2426         fprintf(stderr, "qmax must be >= 1 and <= 51\n");
2427         exit(1);
2428     }
2429 }
2430
2431 static void opt_mb_lmin(const char *arg)
2432 {
2433     video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
2434     if (video_mb_lmin < 1 ||
2435         video_mb_lmin > FF_LAMBDA_MAX) {
2436         fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2437         exit(1);
2438     }
2439 }
2440
2441 static void opt_mb_lmax(const char *arg)
2442 {
2443     video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
2444     if (video_mb_lmax < 1 ||
2445         video_mb_lmax > FF_LAMBDA_MAX) {
2446         fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
2447         exit(1);
2448     }
2449 }
2450
2451 static void opt_qdiff(const char *arg)
2452 {
2453     video_qdiff = atoi(arg);
2454     if (video_qdiff < 0 ||
2455         video_qdiff > 31) {
2456         fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
2457         exit(1);
2458     }
2459 }
2460
2461 static void opt_qblur(const char *arg)
2462 {
2463     video_qblur = atof(arg);
2464 }
2465
2466 static void opt_qcomp(const char *arg)
2467 {
2468     video_qcomp = atof(arg);
2469 }
2470
2471 static void opt_rc_initial_cplx(const char *arg)
2472 {
2473     video_rc_initial_cplx = atof(arg);
2474 }
2475 static void opt_b_qfactor(const char *arg)
2476 {
2477     video_b_qfactor = atof(arg);
2478 }
2479 static void opt_i_qfactor(const char *arg)
2480 {
2481     video_i_qfactor = atof(arg);
2482 }
2483 static void opt_b_qoffset(const char *arg)
2484 {
2485     video_b_qoffset = atof(arg);
2486 }
2487 static void opt_i_qoffset(const char *arg)
2488 {
2489     video_i_qoffset = atof(arg);
2490 }
2491
2492 static void opt_ibias(const char *arg)
2493 {
2494     video_intra_quant_bias = atoi(arg);
2495 }
2496 static void opt_pbias(const char *arg)
2497 {
2498     video_inter_quant_bias = atoi(arg);
2499 }
2500
2501 static void opt_packet_size(const char *arg)
2502 {
2503     packet_size= atoi(arg);
2504 }
2505
2506 static void opt_error_rate(const char *arg)
2507 {
2508     error_rate= atoi(arg);
2509 }
2510
2511 static void opt_strict(const char *arg)
2512 {
2513     strict= atoi(arg);
2514 }
2515
2516 static void opt_top_field_first(const char *arg)
2517 {
2518     top_field_first= atoi(arg);
2519 }
2520
2521 static void opt_sc_threshold(const char *arg)
2522 {
2523     sc_threshold= atoi(arg);
2524 }
2525
2526 static void opt_me_range(const char *arg)
2527 {
2528     me_range = atoi(arg);
2529 }
2530
2531 static void opt_thread_count(const char *arg)
2532 {
2533     thread_count= atoi(arg);
2534 #if !defined(HAVE_THREADS)
2535     if (verbose >= 0)
2536         fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
2537 #endif
2538 }
2539
2540 static void opt_audio_bitrate(const char *arg)
2541 {
2542     audio_bit_rate = atoi(arg) * 1000;
2543 }
2544
2545 static void opt_audio_rate(const char *arg)
2546 {
2547     audio_sample_rate = atoi(arg);
2548 }
2549
2550 static void opt_audio_channels(const char *arg)
2551 {
2552     audio_channels = atoi(arg);
2553 }
2554
2555 static void opt_video_device(const char *arg)
2556 {
2557     video_device = av_strdup(arg);
2558 }
2559
2560 static void opt_grab_device(const char *arg)
2561 {
2562     grab_device = av_strdup(arg);
2563 }
2564
2565 static void opt_video_channel(const char *arg)
2566 {
2567     video_channel = strtol(arg, NULL, 0);
2568 }
2569
2570 static void opt_video_standard(const char *arg)
2571 {
2572     video_standard = av_strdup(arg);
2573 }
2574
2575 static void opt_audio_device(const char *arg)
2576 {
2577     audio_device = av_strdup(arg);
2578 }
2579
2580 static void opt_codec(int *pstream_copy, int *pcodec_id,
2581                       int codec_type, const char *arg)
2582 {
2583     AVCodec *p;
2584
2585     if (!strcmp(arg, "copy")) {
2586         *pstream_copy = 1;
2587     } else {
2588         p = first_avcodec;
2589         while (p) {
2590             if (!strcmp(p->name, arg) && p->type == codec_type)
2591                 break;
2592             p = p->next;
2593         }
2594         if (p == NULL) {
2595             fprintf(stderr, "Unknown codec '%s'\n", arg);
2596             exit(1);
2597         } else {
2598             *pcodec_id = p->id;
2599         }
2600     }
2601 }
2602
2603 static void opt_audio_codec(const char *arg)
2604 {
2605     opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
2606 }
2607
2608 static void opt_audio_tag(const char *arg)
2609 {
2610     char *tail;
2611     audio_codec_tag= strtol(arg, &tail, 0);
2612
2613     if(!tail || *tail)
2614         audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2615 }
2616
2617 static void opt_video_tag(const char *arg)
2618 {
2619     char *tail;
2620     video_codec_tag= strtol(arg, &tail, 0);
2621
2622     if(!tail || *tail)
2623         video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
2624 }
2625
2626 static void add_frame_hooker(const char *arg)
2627 {
2628     int argc = 0;
2629     char *argv[64];
2630     int i;
2631     char *args = av_strdup(arg);
2632
2633     using_vhook = 1;
2634
2635     argv[0] = strtok(args, " ");
2636     while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
2637     }
2638
2639     i = frame_hook_add(argc, argv);
2640
2641     if (i != 0) {
2642         fprintf(stderr, "Failed to add video hook function: %s\n", arg);
2643         exit(1);
2644     }
2645 }
2646
2647 const char *motion_str[] = {
2648     "zero",
2649     "full",
2650     "log",
2651     "phods",
2652     "epzs",
2653     "x1",
2654     "hex",
2655     "umh",
2656     "iter",
2657     NULL,
2658 };
2659
2660 static void opt_motion_estimation(const char *arg)
2661 {
2662     const char **p;
2663     p = motion_str;
2664     for(;;) {
2665         if (!*p) {
2666             fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
2667             exit(1);
2668         }
2669         if (!strcmp(*p, arg))
2670             break;
2671         p++;
2672     }
2673     me_method = (p - motion_str) + 1;
2674 }
2675
2676 static void opt_video_codec(const char *arg)
2677 {
2678     opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
2679 }
2680
2681 static void opt_subtitle_codec(const char *arg)
2682 {
2683     opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
2684 }
2685
2686 static void opt_map(const char *arg)
2687 {
2688     AVStreamMap *m;
2689     const char *p;
2690
2691     p = arg;
2692     m = &stream_maps[nb_stream_maps++];
2693
2694     m->file_index = strtol(arg, (char **)&p, 0);
2695     if (*p)
2696         p++;
2697
2698     m->stream_index = strtol(p, (char **)&p, 0);
2699     if (*p) {
2700         p++;
2701         m->sync_file_index = strtol(p, (char **)&p, 0);
2702         if (*p)
2703             p++;
2704         m->sync_stream_index = strtol(p, (char **)&p, 0);
2705     } else {
2706         m->sync_file_index = m->file_index;
2707         m->sync_stream_index = m->stream_index;
2708     }
2709 }
2710
2711 static void opt_map_meta_data(const char *arg)
2712 {
2713     AVMetaDataMap *m;
2714     const char *p;
2715
2716     p = arg;
2717     m = &meta_data_maps[nb_meta_data_maps++];
2718
2719     m->out_file = strtol(arg, (char **)&p, 0);
2720     if (*p)
2721         p++;
2722
2723     m->in_file = strtol(p, (char **)&p, 0);
2724 }
2725
2726 static void opt_recording_time(const char *arg)
2727 {
2728     recording_time = parse_date(arg, 1);
2729 }
2730
2731 static void opt_start_time(const char *arg)
2732 {
2733     start_time = parse_date(arg, 1);
2734 }
2735
2736 static void opt_rec_timestamp(const char *arg)
2737 {
2738     rec_timestamp = parse_date(arg, 0) / 1000000;
2739 }
2740
2741 static void opt_input_ts_offset(const char *arg)
2742 {
2743     input_ts_offset = parse_date(arg, 1);
2744 }
2745
2746 static void opt_input_file(const char *filename)
2747 {
2748     AVFormatContext *ic;
2749     AVFormatParameters params, *ap = &params;
2750     int err, i, ret, rfps, rfps_base;
2751     int64_t timestamp;
2752
2753     if (!strcmp(filename, "-"))
2754         filename = "pipe:";
2755
2756     using_stdin |= !strncmp(filename, "pipe:", 5) ||
2757                    !strcmp( filename, "/dev/stdin" );
2758
2759     /* get default parameters from command line */
2760     ic = av_alloc_format_context();
2761
2762     memset(ap, 0, sizeof(*ap));
2763     ap->prealloced_context = 1;
2764     ap->sample_rate = audio_sample_rate;
2765     ap->channels = audio_channels;
2766     ap->time_base.den = frame_rate;
2767     ap->time_base.num = frame_rate_base;
2768     ap->width = frame_width + frame_padleft + frame_padright;
2769     ap->height = frame_height + frame_padtop + frame_padbottom;
2770     ap->image_format = image_format;
2771     ap->pix_fmt = frame_pix_fmt;
2772     ap->device  = grab_device;
2773     ap->channel = video_channel;
2774     ap->standard = video_standard;
2775     ap->video_codec_id = video_codec_id;
2776     ap->audio_codec_id = audio_codec_id;
2777     if(pgmyuv_compatibility_hack)
2778         ap->video_codec_id= CODEC_ID_PGMYUV;
2779
2780     for(i=0; i<opt_name_count; i++){
2781         AVOption *opt;
2782         double d= av_get_double(avformat_opts, opt_names[i], &opt);
2783         if(d==d && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2784             av_set_double(ic, opt_names[i], d);
2785     }
2786     /* open the input file with generic libav function */
2787     err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
2788     if (err < 0) {
2789         print_error(filename, err);
2790         exit(1);
2791     }
2792
2793     ic->loop_input = loop_input;
2794
2795     /* If not enough info to get the stream parameters, we decode the
2796        first frames to get it. (used in mpeg case for example) */
2797     ret = av_find_stream_info(ic);
2798     if (ret < 0 && verbose >= 0) {
2799         fprintf(stderr, "%s: could not find codec parameters\n", filename);
2800         exit(1);
2801     }
2802
2803     timestamp = start_time;
2804     /* add the stream start time */
2805     if (ic->start_time != AV_NOPTS_VALUE)
2806         timestamp += ic->start_time;
2807
2808     /* if seeking requested, we execute it */
2809     if (start_time != 0) {
2810         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
2811         if (ret < 0) {
2812             fprintf(stderr, "%s: could not seek to position %0.3f\n",
2813                     filename, (double)timestamp / AV_TIME_BASE);
2814         }
2815         /* reset seek info */
2816         start_time = 0;
2817     }
2818
2819     /* update the current parameters so that they match the one of the input stream */
2820     for(i=0;i<ic->nb_streams;i++) {
2821         int j;
2822         AVCodecContext *enc = ic->streams[i]->codec;
2823 #if defined(HAVE_THREADS)
2824         if(thread_count>1)
2825             avcodec_thread_init(enc, thread_count);
2826 #endif
2827         enc->thread_count= thread_count;
2828         switch(enc->codec_type) {
2829         case CODEC_TYPE_AUDIO:
2830             for(j=0; j<opt_name_count; j++){
2831                 AVOption *opt;
2832                 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2833                 if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2834                     av_set_double(enc, opt_names[j], d);
2835             }
2836             //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
2837             audio_channels = enc->channels;
2838             audio_sample_rate = enc->sample_rate;
2839             if(audio_disable)
2840                 ic->streams[i]->discard= AVDISCARD_ALL;
2841             break;
2842         case CODEC_TYPE_VIDEO:
2843             for(j=0; j<opt_name_count; j++){
2844                 AVOption *opt;
2845                 double d= av_get_double(avctx_opts, opt_names[j], &opt);
2846                 if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_DECODING_PARAM))
2847                     av_set_double(enc, opt_names[j], d);
2848             }
2849             frame_height = enc->height;
2850             frame_width = enc->width;
2851             frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
2852             frame_pix_fmt = enc->pix_fmt;
2853             rfps      = ic->streams[i]->r_frame_rate.num;
2854             rfps_base = ic->streams[i]->r_frame_rate.den;
2855             enc->workaround_bugs = workaround_bugs;
2856             if(enc->lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
2857             if(me_threshold)
2858                 enc->debug |= FF_DEBUG_MV;
2859
2860             if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) {
2861
2862                 if (verbose >= 0)
2863                     fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
2864                             i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
2865
2866                     (float)rfps / rfps_base, rfps, rfps_base);
2867             }
2868             /* update the current frame rate to match the stream frame rate */
2869             frame_rate      = rfps;
2870             frame_rate_base = rfps_base;
2871
2872             enc->rate_emu = rate_emu;
2873             if(video_disable)
2874                 ic->streams[i]->discard= AVDISCARD_ALL;
2875             else if(video_discard)
2876                 ic->streams[i]->discard= video_discard;
2877             break;
2878         case CODEC_TYPE_DATA:
2879             break;
2880         case CODEC_TYPE_SUBTITLE:
2881             break;
2882         case CODEC_TYPE_UNKNOWN:
2883             break;
2884         default:
2885             av_abort();
2886         }
2887     }
2888
2889     input_files[nb_input_files] = ic;
2890     input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
2891     /* dump the file content */
2892     if (verbose >= 0)
2893         dump_format(ic, nb_input_files, filename, 0);
2894
2895     nb_input_files++;
2896     file_iformat = NULL;
2897     file_oformat = NULL;
2898     image_format = NULL;
2899
2900     grab_device = NULL;
2901     video_channel = 0;
2902
2903     rate_emu = 0;
2904 }
2905
2906 static void opt_grab(const char *arg)
2907 {
2908     file_iformat = av_find_input_format(arg);
2909     opt_input_file("");
2910 }
2911
2912 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
2913 {
2914     int has_video, has_audio, i, j;
2915     AVFormatContext *ic;
2916
2917     has_video = 0;
2918     has_audio = 0;
2919     for(j=0;j<nb_input_files;j++) {
2920         ic = input_files[j];
2921         for(i=0;i<ic->nb_streams;i++) {
2922             AVCodecContext *enc = ic->streams[i]->codec;
2923             switch(enc->codec_type) {
2924             case CODEC_TYPE_AUDIO:
2925                 has_audio = 1;
2926                 break;
2927             case CODEC_TYPE_VIDEO:
2928                 has_video = 1;
2929                 break;
2930             case CODEC_TYPE_DATA:
2931             case CODEC_TYPE_UNKNOWN:
2932             case CODEC_TYPE_SUBTITLE:
2933                 break;
2934             default:
2935                 av_abort();
2936             }
2937         }
2938     }
2939     *has_video_ptr = has_video;
2940     *has_audio_ptr = has_audio;
2941 }
2942
2943 static void new_video_stream(AVFormatContext *oc)
2944 {
2945     AVStream *st;
2946     AVCodecContext *video_enc;
2947     int codec_id;
2948
2949     st = av_new_stream(oc, oc->nb_streams);
2950     if (!st) {
2951         fprintf(stderr, "Could not alloc stream\n");
2952         exit(1);
2953     }
2954     bitstream_filters[nb_output_files][oc->nb_streams - 1]= video_bitstream_filters;
2955     video_bitstream_filters= NULL;
2956
2957 #if defined(HAVE_THREADS)
2958     if(thread_count>1)
2959         avcodec_thread_init(st->codec, thread_count);
2960 #endif
2961
2962     video_enc = st->codec;
2963
2964     if(video_codec_tag)
2965         video_enc->codec_tag= video_codec_tag;
2966
2967     if(   (video_global_header&1)
2968        || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER))){
2969         video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
2970         avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
2971     }
2972     if(video_global_header&2){
2973         video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
2974         avctx_opts->flags2|= CODEC_FLAG2_LOCAL_HEADER;
2975     }
2976
2977     if (video_stream_copy) {
2978         st->stream_copy = 1;
2979         video_enc->codec_type = CODEC_TYPE_VIDEO;
2980     } else {
2981         char *p;
2982         int i;
2983         AVCodec *codec;
2984
2985         codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
2986         if (video_codec_id != CODEC_ID_NONE)
2987             codec_id = video_codec_id;
2988
2989         video_enc->codec_id = codec_id;
2990         codec = avcodec_find_encoder(codec_id);
2991
2992         for(i=0; i<opt_name_count; i++){
2993              AVOption *opt;
2994              double d= av_get_double(avctx_opts, opt_names[i], &opt);
2995              if(d==d && (opt->flags&AV_OPT_FLAG_VIDEO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
2996                  av_set_double(video_enc, opt_names[i], d);
2997         }
2998
2999         video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
3000         video_enc->time_base.den = frame_rate;
3001         video_enc->time_base.num = frame_rate_base;
3002         if(codec && codec->supported_framerates){
3003             const AVRational *p= codec->supported_framerates;
3004             AVRational req= (AVRational){frame_rate, frame_rate_base};
3005             const AVRational *best=NULL;
3006             AVRational best_error= (AVRational){INT_MAX, 1};
3007             for(; p->den!=0; p++){
3008                 AVRational error= av_sub_q(req, *p);
3009                 if(error.num <0) error.num *= -1;
3010                 if(av_cmp_q(error, best_error) < 0){
3011                     best_error= error;
3012                     best= p;
3013                 }
3014             }
3015             video_enc->time_base.den= best->num;
3016             video_enc->time_base.num= best->den;
3017         }
3018
3019         video_enc->width = frame_width + frame_padright + frame_padleft;
3020         video_enc->height = frame_height + frame_padtop + frame_padbottom;
3021         video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*video_enc->height/video_enc->width, 255);
3022         video_enc->pix_fmt = frame_pix_fmt;
3023
3024         if(codec && codec->pix_fmts){
3025             const enum PixelFormat *p= codec->pix_fmts;
3026             for(; *p!=-1; p++){
3027                 if(*p == video_enc->pix_fmt)
3028                     break;
3029             }
3030             if(*p == -1)
3031                 video_enc->pix_fmt = codec->pix_fmts[0];
3032         }
3033
3034         if (intra_only)
3035             video_enc->gop_size = 0;
3036         if (video_qscale || same_quality) {
3037             video_enc->flags |= CODEC_FLAG_QSCALE;
3038             video_enc->global_quality=
3039                 st->quality = FF_QP2LAMBDA * video_qscale;
3040         }
3041
3042         if(intra_matrix)
3043             video_enc->intra_matrix = intra_matrix;
3044         if(inter_matrix)
3045             video_enc->inter_matrix = inter_matrix;
3046
3047         video_enc->pre_me = pre_me;
3048
3049         if (b_frames) {
3050             video_enc->max_b_frames = b_frames;
3051             video_enc->b_quant_factor = 2.0;
3052         }
3053         video_enc->qmin = video_qmin;
3054         video_enc->qmax = video_qmax;
3055         video_enc->lmin = video_lmin;
3056         video_enc->lmax = video_lmax;
3057         video_enc->rc_qsquish = video_qsquish;
3058         video_enc->mb_lmin = video_mb_lmin;
3059         video_enc->mb_lmax = video_mb_lmax;
3060         video_enc->max_qdiff = video_qdiff;
3061         video_enc->qblur = video_qblur;
3062         video_enc->qcompress = video_qcomp;
3063         video_enc->rc_eq = video_rc_eq;
3064         video_enc->workaround_bugs = workaround_bugs;
3065         video_enc->thread_count = thread_count;
3066         p= video_rc_override_string;
3067         for(i=0; p; i++){
3068             int start, end, q;
3069             int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
3070             if(e!=3){
3071                 fprintf(stderr, "error parsing rc_override\n");
3072                 exit(1);
3073             }
3074             video_enc->rc_override=
3075                 av_realloc(video_enc->rc_override,
3076                            sizeof(RcOverride)*(i+1));
3077             video_enc->rc_override[i].start_frame= start;
3078             video_enc->rc_override[i].end_frame  = end;
3079             if(q>0){
3080                 video_enc->rc_override[i].qscale= q;
3081                 video_enc->rc_override[i].quality_factor= 1.0;
3082             }
3083             else{
3084                 video_enc->rc_override[i].qscale= 0;
3085                 video_enc->rc_override[i].quality_factor= -q/100.0;
3086             }
3087             p= strchr(p, '/');
3088             if(p) p++;
3089         }
3090         video_enc->rc_override_count=i;
3091
3092         video_enc->rc_buffer_size = video_rc_buffer_size;
3093         video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
3094         video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
3095         video_enc->rc_initial_cplx= video_rc_initial_cplx;
3096         video_enc->i_quant_factor = video_i_qfactor;
3097         video_enc->b_quant_factor = video_b_qfactor;
3098         video_enc->i_quant_offset = video_i_qoffset;
3099         video_enc->b_quant_offset = video_b_qoffset;
3100         video_enc->intra_quant_bias = video_intra_quant_bias;
3101         video_enc->inter_quant_bias = video_inter_quant_bias;
3102         video_enc->me_threshold= me_threshold;
3103         video_enc->mb_threshold= mb_threshold;
3104         video_enc->intra_dc_precision= intra_dc_precision - 8;
3105         video_enc->strict_std_compliance = strict;
3106         video_enc->error_rate = error_rate;
3107         video_enc->scenechange_threshold= sc_threshold;
3108         video_enc->me_range = me_range;
3109         video_enc->me_penalty_compensation= me_penalty_compensation;
3110         video_enc->frame_skip_threshold= frame_skip_threshold;
3111         video_enc->frame_skip_factor= frame_skip_factor;
3112         video_enc->frame_skip_exp= frame_skip_exp;
3113
3114         if(packet_size){
3115             video_enc->rtp_mode= 1;
3116             video_enc->rtp_payload_size= packet_size;
3117         }
3118
3119         if (do_psnr)
3120             video_enc->flags|= CODEC_FLAG_PSNR;
3121
3122         video_enc->me_method = me_method;
3123
3124         /* two pass mode */
3125         if (do_pass) {
3126             if (do_pass == 1) {
3127                 video_enc->flags |= CODEC_FLAG_PASS1;
3128             } else {
3129                 video_enc->flags |= CODEC_FLAG_PASS2;
3130             }
3131         }
3132     }
3133
3134     /* reset some key parameters */
3135     video_disable = 0;
3136     video_codec_id = CODEC_ID_NONE;
3137     video_stream_copy = 0;
3138 }
3139
3140 static void new_audio_stream(AVFormatContext *oc)
3141 {
3142     AVStream *st;
3143     AVCodecContext *audio_enc;
3144     int codec_id, i;
3145
3146     st = av_new_stream(oc, oc->nb_streams);
3147     if (!st) {
3148         fprintf(stderr, "Could not alloc stream\n");
3149         exit(1);
3150     }
3151
3152     bitstream_filters[nb_output_files][oc->nb_streams - 1]= audio_bitstream_filters;
3153     audio_bitstream_filters= NULL;
3154
3155 #if defined(HAVE_THREADS)
3156     if(thread_count>1)
3157         avcodec_thread_init(st->codec, thread_count);
3158 #endif
3159
3160     audio_enc = st->codec;
3161     audio_enc->codec_type = CODEC_TYPE_AUDIO;
3162
3163     if(audio_codec_tag)
3164         audio_enc->codec_tag= audio_codec_tag;
3165
3166     if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
3167         audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
3168         avctx_opts->flags|= CODEC_FLAG_GLOBAL_HEADER;
3169     }
3170     if (audio_stream_copy) {
3171         st->stream_copy = 1;
3172         audio_enc->channels = audio_channels;
3173     } else {
3174         codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
3175
3176         for(i=0; i<opt_name_count; i++){
3177             AVOption *opt;
3178             double d= av_get_double(avctx_opts, opt_names[i], &opt);
3179             if(d==d && (opt->flags&AV_OPT_FLAG_AUDIO_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3180                 av_set_double(audio_enc, opt_names[i], d);
3181         }
3182
3183         if (audio_codec_id != CODEC_ID_NONE)
3184             codec_id = audio_codec_id;
3185         audio_enc->codec_id = codec_id;
3186
3187         audio_enc->bit_rate = audio_bit_rate;
3188         if (audio_qscale > QSCALE_NONE) {
3189             audio_enc->flags |= CODEC_FLAG_QSCALE;
3190             audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
3191         }
3192         audio_enc->strict_std_compliance = strict;
3193         audio_enc->thread_count = thread_count;
3194         /* For audio codecs other than AC3 or DTS we limit */
3195         /* the number of coded channels to stereo   */
3196         if (audio_channels > 2 && codec_id != CODEC_ID_AC3
3197             && codec_id != CODEC_ID_DTS) {
3198             audio_enc->channels = 2;
3199         } else
3200             audio_enc->channels = audio_channels;
3201     }
3202     audio_enc->sample_rate = audio_sample_rate;
3203     audio_enc->time_base= (AVRational){1, audio_sample_rate};
3204     if (audio_language) {
3205         pstrcpy(st->language, sizeof(st->language), audio_language);
3206         av_free(audio_language);
3207         audio_language = NULL;
3208     }
3209
3210     /* reset some key parameters */
3211     audio_disable = 0;
3212     audio_codec_id = CODEC_ID_NONE;
3213     audio_stream_copy = 0;
3214 }
3215
3216 static void opt_new_subtitle_stream(void)
3217 {
3218     AVFormatContext *oc;
3219     AVStream *st;
3220     AVCodecContext *subtitle_enc;
3221     int i;
3222
3223     if (nb_output_files <= 0) {
3224         fprintf(stderr, "At least one output file must be specified\n");
3225         exit(1);
3226     }
3227     oc = output_files[nb_output_files - 1];
3228
3229     st = av_new_stream(oc, oc->nb_streams);
3230     if (!st) {
3231         fprintf(stderr, "Could not alloc stream\n");
3232         exit(1);
3233     }
3234
3235     subtitle_enc = st->codec;
3236     subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
3237     if (subtitle_stream_copy) {
3238         st->stream_copy = 1;
3239     } else {
3240         for(i=0; i<opt_name_count; i++){
3241              AVOption *opt;
3242              double d= av_get_double(avctx_opts, opt_names[i], &opt);
3243              if(d==d && (opt->flags&AV_OPT_FLAG_SUBTITLE_PARAM) && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3244                  av_set_double(subtitle_enc, opt_names[i], d);
3245         }
3246         subtitle_enc->codec_id = subtitle_codec_id;
3247     }
3248
3249     if (subtitle_language) {
3250         pstrcpy(st->language, sizeof(st->language), subtitle_language);
3251         av_free(subtitle_language);
3252         subtitle_language = NULL;
3253     }
3254
3255     subtitle_codec_id = CODEC_ID_NONE;
3256     subtitle_stream_copy = 0;
3257 }
3258
3259 static void opt_new_audio_stream(void)
3260 {
3261     AVFormatContext *oc;
3262     if (nb_output_files <= 0) {
3263         fprintf(stderr, "At least one output file must be specified\n");
3264         exit(1);
3265     }
3266     oc = output_files[nb_output_files - 1];
3267     new_audio_stream(oc);
3268 }
3269
3270 static void opt_new_video_stream(void)
3271 {
3272     AVFormatContext *oc;
3273     if (nb_output_files <= 0) {
3274         fprintf(stderr, "At least one output file must be specified\n");
3275         exit(1);
3276     }
3277     oc = output_files[nb_output_files - 1];
3278     new_video_stream(oc);
3279 }
3280
3281 static void opt_output_file(const char *filename)
3282 {
3283     AVFormatContext *oc;
3284     int use_video, use_audio, input_has_video, input_has_audio, i;
3285     AVFormatParameters params, *ap = &params;
3286
3287     if (!strcmp(filename, "-"))
3288         filename = "pipe:";
3289
3290     oc = av_alloc_format_context();
3291
3292     if (!file_oformat) {
3293         file_oformat = guess_format(NULL, filename, NULL);
3294         if (!file_oformat) {
3295             fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
3296                     filename);
3297             exit(1);
3298         }
3299     }
3300
3301     oc->oformat = file_oformat;
3302     pstrcpy(oc->filename, sizeof(oc->filename), filename);
3303
3304     if (!strcmp(file_oformat->name, "ffm") &&
3305         strstart(filename, "http:", NULL)) {
3306         /* special case for files sent to ffserver: we get the stream
3307            parameters from ffserver */
3308         if (read_ffserver_streams(oc, filename) < 0) {
3309             fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
3310             exit(1);
3311         }
3312     } else {
3313         use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
3314         use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
3315
3316         /* disable if no corresponding type found and at least one
3317            input file */
3318         if (nb_input_files > 0) {
3319             check_audio_video_inputs(&input_has_video, &input_has_audio);
3320             if (!input_has_video)
3321                 use_video = 0;
3322             if (!input_has_audio)
3323                 use_audio = 0;
3324         }
3325
3326         /* manual disable */
3327         if (audio_disable) {
3328             use_audio = 0;
3329         }
3330         if (video_disable) {
3331             use_video = 0;
3332         }
3333
3334         if (use_video) {
3335             new_video_stream(oc);
3336         }
3337
3338         if (use_audio) {
3339             new_audio_stream(oc);
3340         }
3341
3342         if (!oc->nb_streams) {
3343             fprintf(stderr, "No audio or video streams available\n");
3344             exit(1);
3345         }
3346
3347         oc->timestamp = rec_timestamp;
3348
3349         if (str_title)
3350             pstrcpy(oc->title, sizeof(oc->title), str_title);
3351         if (str_author)
3352             pstrcpy(oc->author, sizeof(oc->author), str_author);
3353         if (str_copyright)
3354             pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
3355         if (str_comment)
3356             pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
3357         if (str_album)
3358             pstrcpy(oc->album, sizeof(oc->album), str_album);
3359     }
3360
3361     output_files[nb_output_files++] = oc;
3362
3363     /* check filename in case of an image number is expected */
3364     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
3365         if (!av_filename_number_test(oc->filename)) {
3366             print_error(oc->filename, AVERROR_NUMEXPECTED);
3367             exit(1);
3368         }
3369     }
3370
3371     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
3372         /* test if it already exists to avoid loosing precious files */
3373         if (!file_overwrite &&
3374             (strchr(filename, ':') == NULL ||
3375              strstart(filename, "file:", NULL))) {
3376             if (url_exist(filename)) {
3377                 int c;
3378
3379                 if ( !using_stdin ) {
3380                     fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
3381                     fflush(stderr);
3382                     c = getchar();
3383                     if (toupper(c) != 'Y') {
3384                         fprintf(stderr, "Not overwriting - exiting\n");
3385                         exit(1);
3386                     }
3387                                 }
3388                                 else {
3389                     fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
3390                     exit(1);
3391                                 }
3392             }
3393         }
3394
3395         /* open the file */
3396         if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
3397             fprintf(stderr, "Could not open '%s'\n", filename);
3398             exit(1);
3399         }
3400     }
3401
3402     memset(ap, 0, sizeof(*ap));
3403     ap->image_format = image_format;
3404     if (av_set_parameters(oc, ap) < 0) {
3405         fprintf(stderr, "%s: Invalid encoding parameters\n",
3406                 oc->filename);
3407         exit(1);
3408     }
3409
3410     oc->packet_size= mux_packet_size;
3411     oc->mux_rate= mux_rate;
3412     oc->preload= (int)(mux_preload*AV_TIME_BASE);
3413     oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
3414     oc->loop_output = loop_output;
3415
3416     for(i=0; i<opt_name_count; i++){
3417         AVOption *opt;
3418         double d = av_get_double(avformat_opts, opt_names[i], &opt);
3419         if(d==d && (opt->flags&AV_OPT_FLAG_ENCODING_PARAM))
3420             av_set_double(oc, opt_names[i], d);
3421     }
3422
3423     /* reset some options */
3424     file_oformat = NULL;
3425     file_iformat = NULL;
3426     image_format = NULL;
3427 }
3428
3429 /* prepare dummy protocols for grab */
3430 static void prepare_grab(void)
3431 {
3432     int has_video, has_audio, i, j;
3433     AVFormatContext *oc;
3434     AVFormatContext *ic;
3435     AVFormatParameters vp1, *vp = &vp1;
3436     AVFormatParameters ap1, *ap = &ap1;
3437
3438     /* see if audio/video inputs are needed */
3439     has_video = 0;
3440     has_audio = 0;
3441     memset(ap, 0, sizeof(*ap));
3442     memset(vp, 0, sizeof(*vp));
3443     vp->time_base.num= 1;
3444     for(j=0;j<nb_output_files;j++) {
3445         oc = output_files[j];
3446         for(i=0;i<oc->nb_streams;i++) {
3447             AVCodecContext *enc = oc->streams[i]->codec;
3448             switch(enc->codec_type) {
3449             case CODEC_TYPE_AUDIO:
3450                 if (enc->sample_rate > ap->sample_rate)
3451                     ap->sample_rate = enc->sample_rate;
3452                 if (enc->channels > ap->channels)
3453                     ap->channels = enc->channels;
3454                 has_audio = 1;
3455                 break;
3456             case CODEC_TYPE_VIDEO:
3457                 if (enc->width > vp->width)
3458                     vp->width = enc->width;
3459                 if (enc->height > vp->height)
3460                     vp->height = enc->height;
3461
3462                 if (vp->time_base.num*(int64_t)enc->time_base.den > enc->time_base.num*(int64_t)vp->time_base.den){
3463                     vp->time_base = enc->time_base;
3464                     vp->width += frame_leftBand + frame_rightBand;
3465                     vp->width -= (frame_padleft + frame_padright);
3466                     vp->height += frame_topBand + frame_bottomBand;
3467                     vp->height -= (frame_padtop + frame_padbottom);
3468                 }
3469                 has_video = 1;
3470                 break;
3471             default:
3472                 av_abort();
3473             }
3474         }
3475     }
3476
3477     if (has_video == 0 && has_audio == 0) {
3478         fprintf(stderr, "Output file must have at least one audio or video stream\n");
3479         exit(1);
3480     }
3481
3482     if (has_video) {
3483         AVInputFormat *fmt1;
3484         fmt1 = av_find_input_format(video_grab_format);
3485         vp->device  = video_device;
3486         vp->channel = video_channel;
3487         vp->standard = video_standard;
3488         vp->pix_fmt = frame_pix_fmt;
3489         if (av_open_input_file(&ic, "", fmt1, 0, vp) < 0) {
3490             fprintf(stderr, "Could not find video grab device\n");
3491             exit(1);
3492         }
3493         /* If not enough info to get the stream parameters, we decode the
3494            first frames to get it. */
3495         if ((ic->ctx_flags & AVFMTCTX_NOHEADER) && av_find_stream_info(ic) < 0) {
3496             fprintf(stderr, "Could not find video grab parameters\n");
3497             exit(1);
3498         }
3499         /* by now video grab has one stream */
3500         ic->streams[0]->r_frame_rate.num = vp->time_base.den;
3501         ic->streams[0]->r_frame_rate.den = vp->time_base.num;
3502         input_files[nb_input_files] = ic;
3503
3504         if (verbose >= 0)
3505             dump_format(ic, nb_input_files, "", 0);
3506
3507         nb_input_files++;
3508     }
3509     if (has_audio && audio_grab_format) {
3510         AVInputFormat *fmt1;
3511         fmt1 = av_find_input_format(audio_grab_format);
3512         ap->device = audio_device;
3513         if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
3514             fprintf(stderr, "Could not find audio grab device\n");
3515             exit(1);
3516         }
3517         input_files[nb_input_files] = ic;
3518
3519         if (verbose >= 0)
3520             dump_format(ic, nb_input_files, "", 0);
3521
3522         nb_input_files++;
3523     }
3524 }
3525
3526 /* same option as mencoder */
3527 static void opt_pass(const char *pass_str)
3528 {
3529     int pass;
3530     pass = atoi(pass_str);
3531     if (pass != 1 && pass != 2) {
3532         fprintf(stderr, "pass number can be only 1 or 2\n");
3533         exit(1);
3534     }
3535     do_pass = pass;
3536 }
3537
3538 #if defined(__MINGW32__) || defined(CONFIG_OS2)
3539 static int64_t getutime(void)
3540 {
3541   return av_gettime();
3542 }
3543 #else
3544 static int64_t getutime(void)
3545 {
3546     struct rusage rusage;
3547
3548     getrusage(RUSAGE_SELF, &rusage);
3549     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3550 }
3551 #endif
3552
3553 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3554 extern int ffm_nopts;
3555 #endif
3556
3557 static void show_formats(void)
3558 {
3559     AVInputFormat *ifmt;
3560     AVOutputFormat *ofmt;
3561     AVImageFormat *image_fmt;
3562     URLProtocol *up;
3563     AVCodec *p, *p2;
3564     const char **pp, *last_name;
3565
3566     printf("File formats:\n");
3567     last_name= "000";
3568     for(;;){
3569         int decode=0;
3570         int encode=0;
3571         const char *name=NULL;
3572         const char *long_name=NULL;
3573
3574         for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
3575             if((name == NULL || strcmp(ofmt->name, name)<0) &&
3576                 strcmp(ofmt->name, last_name)>0){
3577                 name= ofmt->name;
3578                 long_name= ofmt->long_name;
3579                 encode=1;
3580             }
3581         }
3582         for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
3583             if((name == NULL || strcmp(ifmt->name, name)<0) &&
3584                 strcmp(ifmt->name, last_name)>0){
3585                 name= ifmt->name;
3586                 long_name= ifmt->long_name;
3587                 encode=0;
3588             }
3589             if(name && strcmp(ifmt->name, name)==0)
3590                 decode=1;
3591         }
3592         if(name==NULL)
3593             break;
3594         last_name= name;
3595
3596         printf(
3597             " %s%s %-15s %s\n",
3598             decode ? "D":" ",
3599             encode ? "E":" ",
3600             name,
3601             long_name ? long_name:" ");
3602     }
3603     printf("\n");
3604
3605     printf("Image formats (filename extensions, if any, follow):\n");
3606     for(image_fmt = first_image_format; image_fmt != NULL;
3607         image_fmt = image_fmt->next) {
3608         printf(
3609             " %s%s %-6s %s\n",
3610             image_fmt->img_read  ? "D":" ",
3611             image_fmt->img_write ? "E":" ",
3612             image_fmt->name,
3613             image_fmt->extensions ? image_fmt->extensions:" ");
3614     }
3615     printf("\n");
3616
3617     printf("Codecs:\n");
3618     last_name= "000";
3619     for(;;){
3620         int decode=0;
3621         int encode=0;
3622         int cap=0;
3623         const char *type_str;
3624
3625         p2=NULL;
3626         for(p = first_avcodec; p != NULL; p = p->next) {
3627             if((p2==NULL || strcmp(p->name, p2->name)<0) &&
3628                 strcmp(p->name, last_name)>0){
3629                 p2= p;
3630                 decode= encode= cap=0;
3631             }
3632             if(p2 && strcmp(p->name, p2->name)==0){
3633                 if(p->decode) decode=1;
3634                 if(p->encode) encode=1;
3635                 cap |= p->capabilities;
3636             }
3637         }
3638         if(p2==NULL)
3639             break;
3640         last_name= p2->name;
3641
3642         switch(p2->type) {
3643         case CODEC_TYPE_VIDEO:
3644             type_str = "V";
3645             break;
3646         case CODEC_TYPE_AUDIO:
3647             type_str = "A";
3648             break;
3649         case CODEC_TYPE_SUBTITLE:
3650             type_str = "S";
3651             break;
3652         default:
3653             type_str = "?";
3654             break;
3655         }
3656         printf(
3657             " %s%s%s%s%s%s %s",
3658             decode ? "D": (/*p2->decoder ? "d":*/" "),
3659             encode ? "E":" ",
3660             type_str,
3661             cap & CODEC_CAP_DRAW_HORIZ_BAND ? "S":" ",
3662             cap & CODEC_CAP_DR1 ? "D":" ",
3663             cap & CODEC_CAP_TRUNCATED ? "T":" ",
3664             p2->name);
3665        /* if(p2->decoder && decode==0)
3666             printf(" use %s for decoding", p2->decoder->name);*/
3667         printf("\n");
3668     }
3669     printf("\n");
3670
3671     printf("Supported file protocols:\n");
3672     for(up = first_protocol; up != NULL; up = up->next)
3673         printf(" %s:", up->name);
3674     printf("\n");
3675
3676     printf("Frame size, frame rate abbreviations:\n ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cif\n");
3677     printf("Motion estimation methods:\n");
3678     pp = motion_str;
3679     while (*pp) {
3680         printf(" %s", *pp);
3681         if ((pp - motion_str + 1) == ME_ZERO)
3682             printf("(fastest)");
3683         else if ((pp - motion_str + 1) == ME_FULL)
3684             printf("(slowest)");
3685         else if ((pp - motion_str + 1) == ME_EPZS)
3686             printf("(default)");
3687         pp++;
3688     }
3689     printf("\n\n");
3690     printf(
3691 "Note, the names of encoders and decoders dont always match, so there are\n"
3692 "several cases where the above table shows encoder only or decoder only entries\n"
3693 "even though both encoding and decoding are supported for example, the h263\n"
3694 "decoder corresponds to the h263 and h263p encoders, for file formats its even\n"
3695 "worse\n");
3696     exit(1);
3697 }
3698
3699 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
3700 {
3701     int i;
3702     const char *p = str;
3703     for(i = 0;; i++) {
3704         dest[i] = atoi(p);
3705         if(i == 63)
3706             break;
3707         p = strchr(p, ',');
3708         if(!p) {
3709             fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
3710             exit(1);
3711         }
3712         p++;
3713     }
3714 }
3715
3716 static void opt_inter_matrix(const char *arg)
3717 {
3718     inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
3719     parse_matrix_coeffs(inter_matrix, arg);
3720 }
3721
3722 static void opt_intra_matrix(const char *arg)
3723 {
3724     intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
3725     parse_matrix_coeffs(intra_matrix, arg);
3726 }
3727
3728 static void opt_target(const char *arg)
3729 {
3730     int norm = -1;
3731     static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
3732
3733     if(!strncmp(arg, "pal-", 4)) {
3734         norm = 0;
3735         arg += 4;
3736     } else if(!strncmp(arg, "ntsc-", 5)) {
3737         norm = 1;
3738         arg += 5;
3739     } else if(!strncmp(arg, "film-", 5)) {
3740         norm = 2;
3741         arg += 5;
3742     } else {
3743         int fr;
3744         /* Calculate FR via float to avoid int overflow */
3745         fr = (int)(frame_rate * 1000.0 / frame_rate_base);
3746         if(fr == 25000) {
3747             norm = 0;
3748         } else if((fr == 29970) || (fr == 23976)) {
3749             norm = 1;
3750         } else {
3751             /* Try to determine PAL/NTSC by peeking in the input files */
3752             if(nb_input_files) {
3753                 int i, j;
3754                 for(j = 0; j < nb_input_files; j++) {
3755                     for(i = 0; i < input_files[j]->nb_streams; i++) {
3756                         AVCodecContext *c = input_files[j]->streams[i]->codec;
3757                         if(c->codec_type != CODEC_TYPE_VIDEO)
3758                             continue;
3759                         fr = c->time_base.den * 1000 / c->time_base.num;
3760                         if(fr == 25000) {
3761                             norm = 0;
3762                             break;
3763                         } else if((fr == 29970) || (fr == 23976)) {
3764                             norm = 1;
3765                             break;
3766                         }
3767                     }
3768                     if(norm >= 0)
3769                         break;
3770                 }
3771             }
3772         }
3773         if(verbose && norm >= 0)
3774             fprintf(stderr, "Assuming %s for target.\n", norm ? "NTSC" : "PAL");
3775     }
3776
3777     if(norm < 0) {
3778         fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
3779         fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
3780         fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
3781         exit(1);
3782     }
3783
3784     if(!strcmp(arg, "vcd")) {
3785
3786         opt_video_codec("mpeg1video");
3787         opt_audio_codec("mp2");
3788         opt_format("vcd");
3789
3790         opt_frame_size(norm ? "352x240" : "352x288");
3791         opt_frame_rate(frame_rates[norm]);
3792         opt_default("gop", norm ? "18" : "15");
3793
3794         opt_default("b", "1150000");
3795         opt_default("maxrate", "1150000");
3796         opt_default("minrate", "1150000");
3797         video_rc_buffer_size = 40*1024*8;
3798
3799         audio_bit_rate = 224000;
3800         audio_sample_rate = 44100;
3801
3802         mux_packet_size= 2324;
3803         mux_rate= 2352 * 75 * 8;
3804
3805         /* We have to offset the PTS, so that it is consistent with the SCR.
3806            SCR starts at 36000, but the first two packs contain only padding
3807            and the first pack from the other stream, respectively, may also have
3808            been written before.
3809            So the real data starts at SCR 36000+3*1200. */
3810         mux_preload= (36000+3*1200) / 90000.0; //0.44
3811     } else if(!strcmp(arg, "svcd")) {
3812
3813         opt_video_codec("mpeg2video");
3814         opt_audio_codec("mp2");
3815         opt_format("svcd");
3816
3817         opt_frame_size(norm ? "480x480" : "480x576");
3818         opt_frame_rate(frame_rates[norm]);
3819         opt_default("gop", norm ? "18" : "15");
3820
3821         opt_default("b", "2040000");
3822         opt_default("maxrate", "2516000");
3823         opt_default("minrate", "0"); //1145000;
3824         video_rc_buffer_size = 224*1024*8;
3825         opt_default("flags", "+SCAN_OFFSET");
3826
3827
3828         audio_bit_rate = 224000;
3829         audio_sample_rate = 44100;
3830
3831         mux_packet_size= 2324;
3832
3833     } else if(!strcmp(arg, "dvd")) {
3834
3835         opt_video_codec("mpeg2video");
3836         opt_audio_codec("ac3");
3837         opt_format("dvd");
3838
3839         opt_frame_size(norm ? "720x480" : "720x576");
3840         opt_frame_rate(frame_rates[norm]);
3841         opt_default("gop", norm ? "18" : "15");
3842
3843         opt_default("b", "6000000");
3844         opt_default("maxrate", "9000000");
3845         opt_default("minrate", "0"); //1500000;
3846         video_rc_buffer_size = 224*1024*8;
3847
3848         mux_packet_size= 2048;  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
3849         mux_rate = 10080000;    // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
3850
3851         audio_bit_rate = 448000;
3852         audio_sample_rate = 48000;
3853
3854     } else if(!strncmp(arg, "dv", 2)) {
3855
3856         opt_format("dv");
3857
3858         opt_frame_size(norm ? "720x480" : "720x576");
3859         opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :
3860                                              (norm ? "yuv411p" : "yuv420p"));
3861         opt_frame_rate(frame_rates[norm]);
3862
3863         audio_sample_rate = 48000;
3864         audio_channels = 2;
3865
3866     } else {
3867         fprintf(stderr, "Unknown target: %s\n", arg);
3868         exit(1);
3869     }
3870 }
3871
3872 static void opt_video_bsf(const char *arg)
3873 {
3874     AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3875     AVBitStreamFilterContext **bsfp;
3876
3877     if(!bsfc){
3878         fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3879         exit(1);
3880     }
3881
3882     bsfp= &video_bitstream_filters;
3883     while(*bsfp)
3884         bsfp= &(*bsfp)->next;
3885
3886     *bsfp= bsfc;
3887 }
3888
3889 //FIXME avoid audio - video code duplication
3890 static void opt_audio_bsf(const char *arg)
3891 {
3892     AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
3893     AVBitStreamFilterContext **bsfp;
3894
3895     if(!bsfc){
3896         fprintf(stderr, "Unkown bitstream filter %s\n", arg);
3897         exit(1);
3898     }
3899
3900     bsfp= &audio_bitstream_filters;
3901     while(*bsfp)
3902         bsfp= &(*bsfp)->next;
3903
3904     *bsfp= bsfc;
3905 }
3906
3907 static void show_version(void)
3908 {
3909     /* TODO: add function interface to avutil and avformat */
3910     fprintf(stderr, "ffmpeg      " FFMPEG_VERSION "\n"
3911            "libavutil   %d\n"
3912            "libavcodec  %d\n"
3913            "libavformat %d\n",
3914            LIBAVUTIL_BUILD, avcodec_build(), LIBAVFORMAT_BUILD);
3915     exit(1);
3916 }
3917
3918 static int opt_default(const char *opt, const char *arg){
3919     AVOption *o= av_set_string(avctx_opts, opt, arg);
3920     if(!o)
3921         o = av_set_string(avformat_opts, opt, arg);
3922     if(!o)
3923         return -1;
3924
3925 //    av_log(NULL, AV_LOG_ERROR, "%s:%s: %f 0x%0X\n", opt, arg, av_get_double(avctx_opts, opt, NULL), (int)av_get_int(avctx_opts, opt, NULL));
3926
3927     //FIXME we should always use avctx_opts, ... for storing options so there wont be any need to keep track of whats set over this
3928     opt_names= av_realloc(opt_names, sizeof(void*)*(opt_name_count+1));
3929     opt_names[opt_name_count++]= o->name;
3930
3931 #if defined(CONFIG_FFM_DEMUXER) || defined(CONFIG_FFM_MUXER)
3932     /* disable generate of real time pts in ffm (need to be supressed anyway) */
3933     if(avctx_opts->flags & CODEC_FLAG_BITEXACT)
3934         ffm_nopts = 1;
3935 #endif
3936
3937     if(avctx_opts->debug)
3938         av_log_set_level(AV_LOG_DEBUG);
3939     return 0;
3940 }
3941
3942 const OptionDef options[] = {
3943     /* main options */
3944     { "L", 0, {(void*)show_license}, "show license" },
3945     { "h", 0, {(void*)show_help}, "show help" },
3946     { "version", 0, {(void*)show_version}, "show version" },
3947     { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
3948     { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
3949     { "img", HAS_ARG, {(void*)opt_image_format}, "force image format", "img_fmt" },
3950     { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
3951     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
3952     { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream[:syncfile:syncstream]" },
3953     { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "set meta data information of outfile from infile", "outfile:infile" },
3954     { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
3955     { "fs", HAS_ARG | OPT_INT, {(void*)&limit_filesize}, "set the limit file size", "limit_size" }, //
3956     { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
3957     { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
3958     { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
3959     { "timestamp", HAS_ARG, {(void*)&opt_rec_timestamp}, "set the timestamp", "time" },
3960     { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
3961     { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
3962     { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
3963     { "album", HAS_ARG | OPT_STRING, {(void*)&str_album}, "set the album", "string" },
3964     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
3965       "add timings for benchmarking" },
3966     { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
3967       "dump each input packet" },
3968     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
3969       "when dumping packets, also dump the payload" },
3970     { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
3971     { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
3972     { "loop_output", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&loop_output}, "number of times to loop output in formats that support looping (0 loops forever)", "" },
3973     { "v", HAS_ARG, {(void*)opt_verbose}, "control amount of logging", "verbose" },
3974     { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
3975     { "threads", HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
3976     { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
3977     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
3978     { "vglobal", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_global_header}, "video global header storage type", "" },
3979     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
3980     { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
3981     { "dts_delta_threshold", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "" },
3982
3983     /* video options */
3984     { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[CODEC_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
3985     { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[CODEC_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
3986     { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[CODEC_TYPE_DATA]}, "set the number of data frames to record", "number" },
3987     { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
3988     { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
3989     { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
3990     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format", "format" },
3991     { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
3992     { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
3993     { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
3994     { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
3995     { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_top}, "set top pad band size (in pixels)", "size" },
3996     { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_bottom}, "set bottom pad band size (in pixels)", "size" },
3997     { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_left}, "set left pad band size (in pixels)", "size" },
3998     { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_pad_right}, "set right pad band size (in pixels)", "size" },
3999     { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad_color}, "set color of pad bands (Hex 000000 thru FFFFFF)", "color" },
4000     { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
4001     { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
4002     { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
4003     { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
4004     { "qmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
4005     { "qmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
4006     { "lmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmin}, "min video lagrange factor (VBR)", "lambda" },
4007     { "lmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_lmax}, "max video lagrange factor (VBR)", "lambda" },
4008     { "mblmin", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmin}, "min macroblock quantiser scale (VBR)", "q" },
4009     { "mblmax", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_lmax}, "max macroblock quantiser scale (VBR)", "q" },
4010     { "qdiff", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
4011     { "qblur", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
4012     { "qsquish", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qsquish}, "how to keep quantiser between qmin and qmax (0 = clip, 1 = use differentiable function)", "squish" },
4013     { "qcomp", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
4014     { "rc_init_cplx", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
4015     { "b_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
4016     { "i_qfactor", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
4017     { "b_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
4018     { "i_qoffset", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
4019     { "ibias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_ibias}, "intra quant bias", "bias" },
4020     { "pbias", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pbias}, "inter quant bias", "bias" },
4021     { "rc_eq", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_eq}, "set rate control equation", "equation" },
4022     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
4023     { "bt", HAS_ARG | OPT_VIDEO, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
4024     { "bufsize", HAS_ARG | OPT_VIDEO, {(void*)opt_video_buffer_size}, "set ratecontrol buffer size (in kByte)", "size" },
4025     { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
4026     { "me", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_motion_estimation}, "set motion estimation method",
4027       "method" },
4028     { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "" },
4029     { "mb_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_mb_threshold}, "macroblock threshold",  "" },
4030     { "bf", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_b_frames}, "use 'frames' B frames", "frames" },
4031     { "preme", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_pre_me}, "pre motion estimation", "" },
4032     { "bug", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
4033     { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "set packet size in bits", "size" },
4034     { "error", HAS_ARG | OPT_EXPERT, {(void*)opt_error_rate}, "error rate", "rate" },
4035     { "strict", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_strict}, "how strictly to follow the standards", "strictness" },
4036     { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
4037       "use same video quality as source (implies VBR)" },
4038     { "pass", HAS_ARG | OPT_VIDEO, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
4039     { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
4040     { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
4041       "deinterlace pictures" },
4042     { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
4043     { "vstats", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_vstats}, "dump video coding statistics to file" },
4044     { "vhook", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)add_frame_hooker}, "insert video processing module", "module" },
4045     { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
4046     { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
4047     { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
4048     { "sc_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_sc_threshold}, "scene change threshold", "threshold" },
4049     { "me_range", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_range}, "limit motion vectors range (1023 for DivX player)", "range" },
4050     { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
4051     { "mepc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&me_penalty_compensation}, "motion estimation bitrate penalty compensation", "factor (1.0 = 256)" },
4052     { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
4053     { "skip_threshold", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_threshold}, "frame skip threshold", "threshold" },
4054     { "skip_factor", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_factor}, "frame skip factor", "factor" },
4055     { "skip_exp", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&frame_skip_exp}, "frame skip exponent", "exponent" },
4056     { "newvideo", OPT_VIDEO, {(void*)opt_new_video_stream}, "add a new video stream to the current output stream" },
4057     { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
4058
4059     /* audio options */
4060     { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
4061     { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
4062     { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
4063     { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
4064     { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
4065     { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
4066     { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
4067     { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
4068     { "newaudio", OPT_AUDIO, {(void*)opt_new_audio_stream}, "add a new audio stream to the current output stream" },
4069     { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
4070
4071     /* subtitle options */
4072     { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
4073     { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_subtitle_stream}, "add a new subtitle stream to the current output stream" },
4074     { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
4075
4076     /* grab options */
4077     { "vd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_device}, "set video grab device", "device" },
4078     { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
4079     { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
4080     { "ad", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_GRAB, {(void*)opt_audio_device}, "set audio device", "device" },
4081
4082     /* G.2 grab options */
4083     { "grab", HAS_ARG | OPT_EXPERT | OPT_GRAB, {(void*)opt_grab}, "request grabbing using", "format" },
4084     { "gd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_grab_device}, "set grab device", "device" },
4085
4086     /* muxer options */
4087     { "muxrate", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_rate}, "set mux rate", "rate" },
4088     { "packetsize", OPT_INT | HAS_ARG | OPT_EXPERT, {(void*)&mux_packet_size}, "set packet size", "size" },
4089     { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
4090     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
4091
4092     { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_audio_bsf}, "", "bitstream filter" },
4093     { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_video_bsf}, "", "bitstream filter" },
4094
4095     { "default", OPT_FUNC2 | HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
4096     { NULL, },
4097 };
4098
4099 static void show_banner(void)
4100 {
4101     fprintf(stderr, "FFmpeg version " FFMPEG_VERSION ", Copyright (c) 2000-2004 Fabrice Bellard\n");
4102     fprintf(stderr, "  configuration: " FFMPEG_CONFIGURATION "\n");
4103     fprintf(stderr, "  libavutil version: " AV_STRINGIFY(LIBAVUTIL_VERSION) "\n");
4104     fprintf(stderr, "  libavcodec version: " AV_STRINGIFY(LIBAVCODEC_VERSION) "\n");
4105     fprintf(stderr, "  libavformat version: " AV_STRINGIFY(LIBAVFORMAT_VERSION) "\n");
4106     fprintf(stderr, "  built on " __DATE__ " " __TIME__);
4107 #ifdef __GNUC__
4108     fprintf(stderr, ", gcc: " __VERSION__ "\n");
4109 #else
4110     fprintf(stderr, ", using a non-gcc compiler\n");
4111 #endif
4112 }
4113
4114 static void show_license(void)
4115 {
4116     show_banner();
4117 #ifdef CONFIG_GPL
4118     printf(
4119     "This program is free software; you can redistribute it and/or modify\n"
4120     "it under the terms of the GNU General Public License as published by\n"
4121     "the Free Software Foundation; either version 2 of the License, or\n"
4122     "(at your option) any later version.\n"
4123     "\n"
4124     "This program is distributed in the hope that it will be useful,\n"
4125     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4126     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
4127     "GNU General Public License for more details.\n"
4128     "\n"
4129     "You should have received a copy of the GNU General Public License\n"
4130     "along with this program; if not, write to the Free Software\n"
4131     "Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n"
4132     );
4133 #else
4134     printf(
4135     "This library is free software; you can redistribute it and/or\n"
4136     "modify it under the terms of the GNU Lesser General Public\n"
4137     "License as published by the Free Software Foundation; either\n"
4138     "version 2 of the License, or (at your option) any later version.\n"
4139     "\n"
4140     "This library is distributed in the hope that it will be useful,\n"
4141     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
4142     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
4143     "Lesser General Public License for more details.\n"
4144     "\n"
4145     "You should have received a copy of the GNU Lesser General Public\n"
4146     "License along with this library; if not, write to the Free Software\n"
4147     "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n"
4148     );
4149 #endif
4150     exit(1);
4151 }
4152
4153 static void show_help(void)
4154 {
4155     show_banner();
4156     printf("usage: ffmpeg [[infile options] -i infile]... {[outfile options] outfile}...\n"
4157            "Hyper fast Audio and Video encoder\n");
4158     printf("\n");
4159     show_help_options(options, "Main options:\n",
4160                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO, 0);
4161     show_help_options(options, "\nVideo options:\n",
4162                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4163                       OPT_VIDEO);
4164     show_help_options(options, "\nAdvanced Video options:\n",
4165                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4166                       OPT_VIDEO | OPT_EXPERT);
4167     show_help_options(options, "\nAudio options:\n",
4168                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4169                       OPT_AUDIO);
4170     show_help_options(options, "\nAdvanced Audio options:\n",
4171                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4172                       OPT_AUDIO | OPT_EXPERT);
4173     show_help_options(options, "\nSubtitle options:\n",
4174                       OPT_SUBTITLE | OPT_GRAB,
4175                       OPT_SUBTITLE);
4176     show_help_options(options, "\nAudio/Video grab options:\n",
4177                       OPT_GRAB,
4178                       OPT_GRAB);
4179     show_help_options(options, "\nAdvanced options:\n",
4180                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
4181                       OPT_EXPERT);
4182     av_opt_show(avctx_opts, NULL);
4183     av_opt_show(avformat_opts, NULL);
4184
4185     exit(1);
4186 }
4187
4188 void parse_arg_file(const char *filename)
4189 {
4190     opt_output_file(filename);
4191 }
4192
4193 int main(int argc, char **argv)
4194 {
4195     int i;
4196     int64_t ti;
4197
4198     av_register_all();
4199
4200     avctx_opts= avcodec_alloc_context();
4201     avformat_opts = av_alloc_format_context();
4202
4203     if (argc <= 1)
4204         show_help();
4205     else
4206         show_banner();
4207
4208     /* parse options */
4209     parse_options(argc, argv, options);
4210
4211     /* file converter / grab */
4212     if (nb_output_files <= 0) {
4213         fprintf(stderr, "Must supply at least one output file\n");
4214         exit(1);
4215     }
4216
4217     if (nb_input_files == 0) {
4218         input_sync = 1;
4219         prepare_grab();
4220     }
4221
4222     ti = getutime();
4223     av_encode(output_files, nb_output_files, input_files, nb_input_files,
4224               stream_maps, nb_stream_maps);
4225     ti = getutime() - ti;
4226     if (do_benchmark) {
4227         printf("bench: utime=%0.3fs\n", ti / 1000000.0);
4228     }
4229
4230     /* close files */
4231     for(i=0;i<nb_output_files;i++) {
4232         /* maybe av_close_output_file ??? */
4233         AVFormatContext *s = output_files[i];
4234         int j;
4235         if (!(s->oformat->flags & AVFMT_NOFILE))
4236             url_fclose(&s->pb);
4237         for(j=0;j<s->nb_streams;j++)
4238             av_free(s->streams[j]);
4239         av_free(s);
4240     }
4241     for(i=0;i<nb_input_files;i++)
4242         av_close_input_file(input_files[i]);
4243
4244     av_free_static();
4245
4246     if(intra_matrix)
4247         av_free(intra_matrix);
4248     if(inter_matrix)
4249         av_free(inter_matrix);
4250
4251 #ifdef POWERPC_PERFORMANCE_REPORT
4252     extern void powerpc_display_perf_report(void);
4253     powerpc_display_perf_report();
4254 #endif /* POWERPC_PERFORMANCE_REPORT */
4255
4256 #ifndef __MINGW32__
4257     if (received_sigterm) {
4258         fprintf(stderr,
4259             "Received signal %d: terminating.\n",
4260             (int) received_sigterm);
4261         exit (255);
4262     }
4263 #endif
4264     exit(0); /* not all OS-es handle main() return value */
4265     return 0;
4266 }