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