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