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