]> git.sesse.net Git - ffmpeg/blob - ffmpeg.c
fixing qmin==qmax && qsquish==1
[ffmpeg] / ffmpeg.c
1 /*
2  * FFmpeg main 
3  * Copyright (c) 2000, 2001, 2002 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 "tick.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 #endif
31 #ifdef __BEOS__
32 /* for snooze() */
33 #include <OS.h>
34 #endif
35 #include <time.h>
36 #include <ctype.h>
37
38
39 #define MAXINT64 INT64_C(0x7fffffffffffffff)
40
41 typedef struct {
42     const char *name;
43     int flags;
44 #define HAS_ARG    0x0001
45 #define OPT_BOOL   0x0002
46 #define OPT_EXPERT 0x0004
47 #define OPT_STRING 0x0008
48     union {
49         void (*func_arg)();
50         int *int_arg;
51         char **str_arg;
52     } u;
53     const char *help;
54     const char *argname;
55 } OptionDef;
56
57 /* select an input stream for an output stream */
58 typedef struct AVStreamMap {
59     int file_index;
60     int stream_index;
61 } AVStreamMap;
62
63 extern const OptionDef options[];
64
65 void show_help(void);
66
67 #define MAX_FILES 20
68
69 static AVFormatContext *input_files[MAX_FILES];
70 static int nb_input_files = 0;
71
72 static AVFormatContext *output_files[MAX_FILES];
73 static int nb_output_files = 0;
74
75 static AVStreamMap stream_maps[MAX_FILES];
76 static int nb_stream_maps;
77
78 static AVInputFormat *file_iformat;
79 static AVOutputFormat *file_oformat;
80 static int frame_width  = 160;
81 static int frame_height = 128;
82 static int frame_rate = 25 * FRAME_RATE_BASE;
83 static int video_bit_rate = 200*1000;
84 static int video_bit_rate_tolerance = 4000*1000;
85 static int video_qscale = 0;
86 static int video_qmin = 2;
87 static int video_qmax = 31;
88 static int video_qdiff = 3;
89 static float video_qblur = 0.5;
90 static float video_qcomp = 0.5;
91 static float video_rc_qsquish=1.0;
92 static float video_rc_qmod_amp=0;
93 static int video_rc_qmod_freq=0;
94 static char *video_rc_override_string=NULL;
95 static char *video_rc_eq="tex^qComp";
96 static int video_rc_buffer_size=0;
97 static float video_rc_buffer_aggressivity=1.0;
98 static int video_rc_max_rate=0;
99 static int video_rc_min_rate=0;
100 static float video_rc_initial_cplx=0;
101 static float video_b_qfactor = 1.25;
102 static float video_b_qoffset = 1.25;
103 static float video_i_qfactor = 0.8;
104 static float video_i_qoffset = 0.0;
105 static int me_method = 0;
106 static int video_disable = 0;
107 static int video_codec_id = CODEC_ID_NONE;
108 static int same_quality = 0;
109 static int b_frames = 0;
110 static int use_hq = 0;
111 static int use_4mv = 0;
112 static int do_deinterlace = 0;
113 static int workaround_bugs = 0;
114
115 static int gop_size = 12;
116 static int intra_only = 0;
117 static int audio_sample_rate = 44100;
118 static int audio_bit_rate = 64000;
119 static int audio_disable = 0;
120 static int audio_channels = 1;
121 static int audio_codec_id = CODEC_ID_NONE;
122
123 static INT64 recording_time = 0;
124 static int file_overwrite = 0;
125 static char *str_title = NULL;
126 static char *str_author = NULL;
127 static char *str_copyright = NULL;
128 static char *str_comment = NULL;
129 static int do_benchmark = 0;
130 static int do_hex_dump = 0;
131 static int do_play = 0;
132 static int do_psnr = 0;
133 static int do_vstats = 0;
134 static int mpeg_vcd = 0;
135
136 #ifndef CONFIG_AUDIO_OSS
137 const char *audio_device = "none";
138 #endif
139 #ifndef CONFIG_VIDEO4LINUX
140 const char *v4l_device = "none";
141 #endif
142
143 typedef struct AVOutputStream {
144     int file_index;          /* file index */
145     int index;               /* stream index in the output file */
146     int source_index;        /* AVInputStream index */
147     AVStream *st;            /* stream in the output file */
148     int encoding_needed;   /* true if encoding needed for this stream */
149
150     /* video only */
151     AVPicture pict_tmp;         /* temporary image for resizing */
152     int video_resample;
153     ImgReSampleContext *img_resample_ctx; /* for image resampling */
154     
155     /* audio only */
156     int audio_resample;
157     ReSampleContext *resample; /* for audio resampling */
158     FifoBuffer fifo;     /* for compression: one audio fifo per codec */
159 } AVOutputStream;
160
161 typedef struct AVInputStream {
162     int file_index;
163     int index;
164     AVStream *st;
165     int discard;             /* true if stream data should be discarded */
166     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
167     Ticker pts_ticker;       /* Ticker for PTS calculation */
168     int ticker_inited;       /* to signal if the ticker was initialized */
169     INT64 pts;               /* current pts */
170     int   pts_increment;     /* expected pts increment for next packet */
171     int frame_number;        /* current frame */
172     INT64 sample_index;      /* current sample */
173 } AVInputStream;
174
175 typedef struct AVInputFile {
176     int eof_reached;      /* true if eof reached */
177     int ist_index;        /* index of first stream in ist_table */
178     int buffer_size;      /* current total buffer size */
179     int buffer_size_max;  /* buffer size at which we consider we can stop
180                              buffering */
181     int nb_streams;       /* nb streams we are aware of */
182 } AVInputFile;
183
184 #ifndef CONFIG_WIN32
185
186 /* init terminal so that we can grab keys */
187 static struct termios oldtty;
188
189 static void term_exit(void)
190 {
191     tcsetattr (0, TCSANOW, &oldtty);
192 }
193
194 static void term_init(void)
195 {
196     struct termios tty;
197
198     tcgetattr (0, &tty);
199     oldtty = tty;
200
201     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
202                           |INLCR|IGNCR|ICRNL|IXON);
203     tty.c_oflag |= OPOST;
204     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
205     tty.c_cflag &= ~(CSIZE|PARENB);
206     tty.c_cflag |= CS8;
207     tty.c_cc[VMIN] = 1;
208     tty.c_cc[VTIME] = 0;
209     
210     tcsetattr (0, TCSANOW, &tty);
211
212     atexit(term_exit);
213 }
214
215 /* read a key without blocking */
216 static int read_key(void)
217 {
218     struct timeval tv;
219     int n;
220     unsigned char ch;
221     fd_set rfds;
222
223     FD_ZERO(&rfds);
224     FD_SET(0, &rfds);
225     tv.tv_sec = 0;
226     tv.tv_usec = 0;
227     n = select(1, &rfds, NULL, NULL, &tv);
228     if (n > 0) {
229         n = read(0, &ch, 1);
230         if (n == 1)
231             return ch;
232
233         return n;
234     }
235     return -1;
236 }
237
238 #else
239
240 /* no interactive support */
241 static void term_exit(void)
242 {
243 }
244
245 static void term_init(void)
246 {
247 }
248
249 static int read_key(void)
250 {
251     return 0;
252 }
253
254 #endif
255
256 int read_ffserver_streams(AVFormatContext *s, const char *filename)
257 {
258     int i, err;
259     AVFormatContext *ic;
260
261     err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
262     if (err < 0)
263         return err;
264     /* copy stream format */
265     s->nb_streams = ic->nb_streams;
266     for(i=0;i<ic->nb_streams;i++) {
267         AVStream *st;
268         st = av_mallocz(sizeof(AVFormatContext));
269         memcpy(st, ic->streams[i], sizeof(AVStream));
270         s->streams[i] = st;
271     }
272
273     av_close_input_file(ic);
274     return 0;
275 }
276
277 #define MAX_AUDIO_PACKET_SIZE 16384
278
279 static void do_audio_out(AVFormatContext *s, 
280                          AVOutputStream *ost, 
281                          AVInputStream *ist,
282                          unsigned char *buf, int size)
283 {
284     UINT8 *buftmp;
285     UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
286     UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
287     int size_out, frame_bytes, ret;
288     AVCodecContext *enc;
289
290     enc = &ost->st->codec;
291
292     if (ost->audio_resample) {
293         buftmp = audio_buf;
294         size_out = audio_resample(ost->resample, 
295                                   (short *)buftmp, (short *)buf,
296                                   size / (ist->st->codec.channels * 2));
297         size_out = size_out * enc->channels * 2;
298     } else {
299         buftmp = buf;
300         size_out = size;
301     }
302
303     /* now encode as many frames as possible */
304     if (enc->frame_size > 1) {
305         /* output resampled raw samples */
306         fifo_write(&ost->fifo, buftmp, size_out, 
307                    &ost->fifo.wptr);
308
309         frame_bytes = enc->frame_size * 2 * enc->channels;
310         
311         while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
312                      &ost->fifo.rptr) == 0) {
313             ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out), 
314                                        (short *)audio_buf);
315             s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
316         }
317     } else {
318         /* output a pcm frame */
319         /* XXX: change encoding codec API to avoid this ? */
320         switch(enc->codec->id) {
321         case CODEC_ID_PCM_S16LE:
322         case CODEC_ID_PCM_S16BE:
323         case CODEC_ID_PCM_U16LE:
324         case CODEC_ID_PCM_U16BE:
325             break;
326         default:
327             size_out = size_out >> 1;
328             break;
329         }
330         ret = avcodec_encode_audio(enc, audio_out, size_out, 
331                                    (short *)buftmp);
332         s->oformat->write_packet(s, ost->index, audio_out, ret, 0);
333     }
334 }
335
336 /* write a picture to a raw mux */
337 static void write_picture(AVFormatContext *s, int index, AVPicture *picture, 
338                           int pix_fmt, int w, int h)
339 {
340     UINT8 *buf, *src, *dest;
341     int size, j, i;
342
343     /* XXX: not efficient, should add test if we can take
344        directly the AVPicture */
345     switch(pix_fmt) {
346     case PIX_FMT_YUV420P:
347         size = avpicture_get_size(pix_fmt, w, h);
348         buf = av_malloc(size);
349         if (!buf)
350             return;
351         dest = buf;
352         for(i=0;i<3;i++) {
353             if (i == 1) {
354                 w >>= 1;
355                 h >>= 1;
356             }
357             src = picture->data[i];
358             for(j=0;j<h;j++) {
359                 memcpy(dest, src, w);
360                 dest += w;
361                 src += picture->linesize[i];
362             }
363         }
364         break;
365     case PIX_FMT_YUV422P:
366         size = (w * h) * 2; 
367         buf = av_malloc(size);
368         if (!buf)
369             return;
370         dest = buf;
371         for(i=0;i<3;i++) {
372             if (i == 1) {
373                 w >>= 1;
374             }
375             src = picture->data[i];
376             for(j=0;j<h;j++) {
377                 memcpy(dest, src, w);
378                 dest += w;
379                 src += picture->linesize[i];
380             }
381         }
382         break;
383     case PIX_FMT_YUV444P:
384         size = (w * h) * 3; 
385         buf = av_malloc(size);
386         if (!buf)
387             return;
388         dest = buf;
389         for(i=0;i<3;i++) {
390             src = picture->data[i];
391             for(j=0;j<h;j++) {
392                 memcpy(dest, src, w);
393                 dest += w;
394                 src += picture->linesize[i];
395             }
396         }
397         break;
398     case PIX_FMT_YUV422:
399         size = (w * h) * 2; 
400         buf = av_malloc(size);
401         if (!buf)
402             return;
403         dest = buf;
404         src = picture->data[0];
405         for(j=0;j<h;j++) {
406             memcpy(dest, src, w * 2);
407             dest += w * 2;
408             src += picture->linesize[0];
409         }
410         break;
411     case PIX_FMT_RGB24:
412     case PIX_FMT_BGR24:
413         size = (w * h) * 3; 
414         buf = av_malloc(size);
415         if (!buf)
416             return;
417         dest = buf;
418         src = picture->data[0];
419         for(j=0;j<h;j++) {
420             memcpy(dest, src, w * 3);
421             dest += w * 3;
422             src += picture->linesize[0];
423         }
424         break;
425     default:
426         return;
427     }
428     s->oformat->write_packet(s, index, buf, size, 0);
429     av_free(buf);
430 }
431
432
433 static void do_video_out(AVFormatContext *s, 
434                          AVOutputStream *ost, 
435                          AVInputStream *ist,
436                          AVPicture *picture1,
437                          int *frame_size)
438 {
439     int n1, n2, nb, i, ret, frame_number, dec_frame_rate;
440     AVPicture *picture, *picture2, *pict;
441     AVPicture picture_tmp1, picture_tmp2;
442     static UINT8 *video_buffer;
443     UINT8 *buf = NULL, *buf1 = NULL;
444     AVCodecContext *enc, *dec;
445
446 #define VIDEO_BUFFER_SIZE (1024*1024)
447
448     enc = &ost->st->codec;
449     dec = &ist->st->codec;
450
451     frame_number = ist->frame_number;
452     dec_frame_rate = ist->st->r_frame_rate;
453     //    fprintf(stderr, "\n%d", dec_frame_rate);
454     /* first drop frame if needed */
455     n1 = ((INT64)frame_number * enc->frame_rate) / dec_frame_rate;
456     n2 = (((INT64)frame_number + 1) * enc->frame_rate) / dec_frame_rate;
457     nb = n2 - n1;
458     if (nb <= 0) 
459         return;
460
461     if (!video_buffer)
462         video_buffer= av_malloc(VIDEO_BUFFER_SIZE);
463     if(!video_buffer) return;
464
465     /* deinterlace : must be done before any resize */
466     if (do_deinterlace) {
467         int size;
468
469         /* create temporary picture */
470         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
471         buf1 = av_malloc(size);
472         if (!buf1)
473             return;
474         
475         picture2 = &picture_tmp2;
476         avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
477
478         if (avpicture_deinterlace(picture2, picture1, 
479                                   dec->pix_fmt, dec->width, dec->height) < 0) {
480             /* if error, do not deinterlace */
481             av_free(buf1);
482             buf1 = NULL;
483             picture2 = picture1;
484         }
485     } else {
486         picture2 = picture1;
487     }
488
489     /* convert pixel format if needed */
490     if (enc->pix_fmt != dec->pix_fmt) {
491         int size;
492
493         /* create temporary picture */
494         size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
495         buf = av_malloc(size);
496         if (!buf)
497             return;
498         pict = &picture_tmp1;
499         avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
500         
501         if (img_convert(pict, enc->pix_fmt, 
502                         picture2, dec->pix_fmt, 
503                         dec->width, dec->height) < 0) {
504             fprintf(stderr, "pixel format conversion not handled\n");
505             goto the_end;
506         }
507     } else {
508         pict = picture2;
509     }
510
511     /* XXX: resampling could be done before raw format convertion in
512        some cases to go faster */
513     /* XXX: only works for YUV420P */
514     if (ost->video_resample) {
515         picture = &ost->pict_tmp;
516         img_resample(ost->img_resample_ctx, picture, pict);
517     } else {
518         picture = pict;
519     }
520     nb=1;
521     /* duplicates frame if needed */
522     /* XXX: pb because no interleaving */
523     for(i=0;i<nb;i++) {
524         if (enc->codec_id != CODEC_ID_RAWVIDEO) {
525             /* handles sameq here. This is not correct because it may
526                not be a global option */
527             if (same_quality) {
528                 enc->quality = dec->quality;
529             }
530             
531             ret = avcodec_encode_video(enc, 
532                                        video_buffer, VIDEO_BUFFER_SIZE,
533                                        picture);
534             //enc->frame_number = enc->real_pict_num;
535             s->oformat->write_packet(s, ost->index, video_buffer, ret, 0);
536             *frame_size = ret;
537             //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
538             //        enc->frame_number-1, enc->real_pict_num, ret,
539             //        enc->pict_type);
540         } else {
541             write_picture(s, ost->index, picture, enc->pix_fmt, enc->width, enc->height);
542         }
543     }
544     the_end:
545     av_free(buf);
546     av_free(buf1);
547 }
548
549 static void do_video_stats(AVOutputStream *ost, 
550                          AVInputStream *ist,
551                          int frame_size)
552 {
553     static FILE *fvstats=NULL;
554     static INT64 total_size = 0;
555     char filename[40];
556     time_t today2;
557     struct tm *today;
558     AVCodecContext *enc;
559     int frame_number;
560     INT64 ti;
561     double ti1, bitrate, avg_bitrate;
562     
563     if (!fvstats) {
564         today2 = time(NULL);
565         today = localtime(&today2);
566         sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
567                                                today->tm_min,
568                                                today->tm_sec);
569         fvstats = fopen(filename,"w");
570         if (!fvstats) {
571             perror("fopen");
572             exit(1);
573         }
574     }
575     
576     ti = MAXINT64;
577     enc = &ost->st->codec;
578     total_size += frame_size;
579     if (enc->codec_type == CODEC_TYPE_VIDEO) {
580         frame_number = ist->frame_number;
581         fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
582         if (do_psnr)
583             fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
584         
585         fprintf(fvstats,"f_size= %6d ", frame_size);
586         /* compute min pts value */
587         if (!ist->discard && ist->pts < ti) {
588             ti = ist->pts;
589         }
590         ti1 = (double)ti / 1000000.0;
591         if (ti1 < 0.01)
592             ti1 = 0.01;
593     
594         bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
595         avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
596         fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
597             (double)total_size / 1024, ti1, bitrate, avg_bitrate);
598         fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");        
599     }
600
601     
602     
603 }
604
605 /*
606  * The following code is the main loop of the file converter
607  */
608 static int av_encode(AVFormatContext **output_files,
609                      int nb_output_files,
610                      AVFormatContext **input_files,
611                      int nb_input_files,
612                      AVStreamMap *stream_maps, int nb_stream_maps)
613 {
614     int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
615     AVFormatContext *is, *os;
616     AVCodecContext *codec, *icodec;
617     AVOutputStream *ost, **ost_table = NULL;
618     AVInputStream *ist, **ist_table = NULL;
619     INT64 min_pts, start_time;
620     AVInputFile *file_table;
621     AVFormatContext *stream_no_data;
622     int key;
623
624     file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
625     if (!file_table)
626         goto fail;
627
628     /* input stream init */
629     j = 0;
630     for(i=0;i<nb_input_files;i++) {
631         is = input_files[i];
632         file_table[i].ist_index = j;
633         file_table[i].nb_streams = is->nb_streams;
634         j += is->nb_streams;
635     }
636     nb_istreams = j;
637
638     ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
639     if (!ist_table)
640         goto fail;
641     
642     for(i=0;i<nb_istreams;i++) {
643         ist = av_mallocz(sizeof(AVInputStream));
644         if (!ist)
645             goto fail;
646         ist_table[i] = ist;
647     }
648     j = 0;
649     for(i=0;i<nb_input_files;i++) {
650         is = input_files[i];
651         for(k=0;k<is->nb_streams;k++) {
652             ist = ist_table[j++];
653             ist->st = is->streams[k];
654             ist->file_index = i;
655             ist->index = k;
656             ist->discard = 1; /* the stream is discarded by default
657                                  (changed later) */
658         }
659     }
660
661     /* output stream init */
662     nb_ostreams = 0;
663     for(i=0;i<nb_output_files;i++) {
664         os = output_files[i];
665         nb_ostreams += os->nb_streams;
666         if (mpeg_vcd)
667             os->flags |= AVF_FLAG_VCD;
668     }
669     if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
670         fprintf(stderr, "Number of stream maps must match number of output streams\n");
671         exit(1);
672     }
673
674     ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
675     if (!ost_table)
676         goto fail;
677     for(i=0;i<nb_ostreams;i++) {
678         ost = av_mallocz(sizeof(AVOutputStream));
679         if (!ost)
680             goto fail;
681         ost_table[i] = ost;
682     }
683     
684     n = 0;
685     for(k=0;k<nb_output_files;k++) {
686         os = output_files[k];
687         for(i=0;i<os->nb_streams;i++) {
688             int found;
689             ost = ost_table[n++];
690             ost->file_index = k;
691             ost->index = i;
692             ost->st = os->streams[i];
693             if (nb_stream_maps > 0) {
694                 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
695                     stream_maps[n-1].stream_index;
696             } else {
697                 /* get corresponding input stream index : we select the first one with the right type */
698                 found = 0;
699                 for(j=0;j<nb_istreams;j++) {
700                     ist = ist_table[j];
701                     if (ist->discard && 
702                         ist->st->codec.codec_type == ost->st->codec.codec_type) {
703                         ost->source_index = j;
704                         found = 1;
705                     }
706                 }
707                 
708                 if (!found) {
709                     /* try again and reuse existing stream */
710                     for(j=0;j<nb_istreams;j++) {
711                         ist = ist_table[j];
712                         if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
713                             ost->source_index = j;
714                             found = 1;
715                         }
716                     }
717                     if (!found) {
718                         fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
719                                 ost->file_index, ost->index);
720                         exit(1);
721                     }
722                 }
723             }
724             ist = ist_table[ost->source_index];
725             ist->discard = 0;
726         }
727     }
728
729     /* dump the stream mapping */
730     fprintf(stderr, "Stream mapping:\n");
731     for(i=0;i<nb_ostreams;i++) {
732         ost = ost_table[i];
733         fprintf(stderr, "  Stream #%d.%d -> #%d.%d\n",
734                 ist_table[ost->source_index]->file_index,
735                 ist_table[ost->source_index]->index,
736                 ost->file_index, 
737                 ost->index);
738     }
739
740     /* for each output stream, we compute the right encoding parameters */
741     for(i=0;i<nb_ostreams;i++) {
742         ost = ost_table[i];
743         ist = ist_table[ost->source_index];
744
745         codec = &ost->st->codec;
746         icodec = &ist->st->codec;
747
748         switch(codec->codec_type) {
749         case CODEC_TYPE_AUDIO:
750             /* check if same codec with same parameters. If so, no
751                reencoding is needed */
752             if (codec->codec_id == icodec->codec_id &&
753                 codec->bit_rate == icodec->bit_rate &&
754                 codec->sample_rate == icodec->sample_rate &&
755                 codec->channels == icodec->channels) {
756                 /* no reencoding */
757                 /* use the same frame size */
758                 codec->frame_size = icodec->frame_size;
759                 //codec->frame_size = 8*icodec->sample_rate*icodec->frame_size/
760                 //                    icodec->bit_rate;
761                 //fprintf(stderr,"\nFrame size: %d", codec->frame_size);
762             } else {
763                 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
764                     goto fail;
765
766                 if (codec->channels == icodec->channels &&
767                     codec->sample_rate == icodec->sample_rate) {
768                     ost->audio_resample = 0;
769                 } else {
770                     if (codec->channels != icodec->channels &&
771                         icodec->codec_id == CODEC_ID_AC3) {
772                         /* Special case for 5:1 AC3 input */
773                         /* and mono or stereo output      */
774                         /* Request specific number of channels */
775                         icodec->channels = codec->channels;
776                         if (codec->sample_rate == icodec->sample_rate)
777                             ost->audio_resample = 0;
778                         else {
779                             ost->audio_resample = 1;
780                             ost->resample = audio_resample_init(codec->channels, icodec->channels,
781                                                         codec->sample_rate, 
782                                                         icodec->sample_rate);
783                         }
784                         /* Request specific number of channels */
785                         icodec->channels = codec->channels;
786                     } else {
787                         ost->audio_resample = 1; 
788                         ost->resample = audio_resample_init(codec->channels, icodec->channels,
789                                                         codec->sample_rate, 
790                                                         icodec->sample_rate);
791                     }
792                 }
793                 ist->decoding_needed = 1;
794                 ost->encoding_needed = 1;
795             }
796             break;
797         case CODEC_TYPE_VIDEO:
798             /* check if same codec with same parameters. If so, no
799                reencoding is needed */
800             if (codec->codec_id == icodec->codec_id &&
801                 codec->bit_rate == icodec->bit_rate &&
802                 codec->frame_rate == icodec->frame_rate &&
803                 codec->width == icodec->width &&
804                 codec->height == icodec->height) {
805                 /* no reencoding */
806             } else {
807                 if (codec->width == icodec->width &&
808                     codec->height == icodec->height) {
809                     ost->video_resample = 0;
810                 } else {
811                     UINT8 *buf;
812                     ost->video_resample = 1;
813                     buf = av_malloc((codec->width * codec->height * 3) / 2);
814                     if (!buf)
815                         goto fail;
816                     ost->pict_tmp.data[0] = buf;
817                     ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
818                     ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
819                     ost->pict_tmp.linesize[0] = codec->width;
820                     ost->pict_tmp.linesize[1] = codec->width / 2;
821                     ost->pict_tmp.linesize[2] = codec->width / 2;
822
823                     ost->img_resample_ctx = img_resample_init( 
824                                       ost->st->codec.width, ost->st->codec.height,
825                                       ist->st->codec.width, ist->st->codec.height);
826                 }
827                 ost->encoding_needed = 1;
828                 ist->decoding_needed = 1;
829             }
830             break;
831         default:
832             av_abort();
833         }
834     }
835
836     /* open each encoder */
837     for(i=0;i<nb_ostreams;i++) {
838         ost = ost_table[i];
839         if (ost->encoding_needed) {
840             AVCodec *codec;
841             codec = avcodec_find_encoder(ost->st->codec.codec_id);
842             if (!codec) {
843                 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
844                         ost->file_index, ost->index);
845                 exit(1);
846             }
847             if (avcodec_open(&ost->st->codec, codec) < 0) {
848                 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
849                         ost->file_index, ost->index);
850                 exit(1);
851             }
852         }
853     }
854
855     /* open each decoder */
856     for(i=0;i<nb_istreams;i++) {
857         ist = ist_table[i];
858         if (ist->decoding_needed) {
859             AVCodec *codec;
860             codec = avcodec_find_decoder(ist->st->codec.codec_id);
861             if (!codec) {
862                 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
863                         ist->file_index, ist->index);
864                 exit(1);
865             }
866             if (avcodec_open(&ist->st->codec, codec) < 0) {
867                 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
868                         ist->file_index, ist->index);
869                 exit(1);
870             }
871             //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
872             //    ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
873         }
874     }
875
876     /* init pts */
877     for(i=0;i<nb_istreams;i++) {
878         ist = ist_table[i];
879         ist->pts = 0;
880         ist->frame_number = 0;
881     }
882     
883     /* compute buffer size max (should use a complete heuristic) */
884     for(i=0;i<nb_input_files;i++) {
885         file_table[i].buffer_size_max = 2048;
886     }
887
888     /* open files and write file headers */
889     for(i=0;i<nb_output_files;i++) {
890         os = output_files[i];
891         if (av_write_header(os) < 0) {
892             fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
893             ret = -EINVAL;
894             goto fail;
895         }
896     }
897
898 #ifndef CONFIG_WIN32
899     if (!do_play) {
900         fprintf(stderr, "Press [q] to stop encoding\n");
901     } else {
902         fprintf(stderr, "Press [q] to stop playing\n");
903     }
904 #endif
905     term_init();
906
907     start_time = av_gettime();
908     min_pts = 0;
909     stream_no_data = 0;
910     key = -1;
911
912     for(;;) {
913         int file_index, ist_index;
914         AVPacket pkt;
915         UINT8 *ptr;
916         int len;
917         UINT8 *data_buf;
918         int data_size, got_picture;
919         AVPicture picture;
920         short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
921
922     redo:
923         /* if 'q' pressed, exits */
924         if (key) {
925             /* read_key() returns 0 on EOF */
926             key = read_key();
927             if (key == 'q')
928                 break;
929         }
930
931         /* select the input file with the smallest pts */
932         file_index = -1;
933         min_pts = MAXINT64;
934         for(i=0;i<nb_istreams;i++) {
935             ist = ist_table[i];
936             /* For some reason, the pts_increment code breaks q estimation?!? */
937             if (!ist->discard && !file_table[ist->file_index].eof_reached && 
938                 ist->pts /* + ist->pts_increment */ < min_pts && input_files[ist->file_index] != stream_no_data) {
939                 min_pts = ist->pts /* + ist->pts_increment */;
940                 file_index = ist->file_index;
941             }
942         }
943         /* if none, if is finished */
944         if (file_index < 0) {
945             if (stream_no_data) {
946 #ifndef CONFIG_WIN32
947 #ifndef __BEOS__
948                 struct timespec ts;
949
950                 ts.tv_sec = 0;
951                 ts.tv_nsec = 1000 * 1000 * 10;
952                 nanosleep(&ts, 0);
953 #else
954                snooze(10 * 1000); /* mmu_man */ /* in microsec */
955 #endif
956 #endif
957                 stream_no_data = 0;
958                 continue;
959             }
960             break;
961         }    
962         /* finish if recording time exhausted */
963         if (recording_time > 0 && min_pts >= recording_time)
964             break;
965         /* read a packet from it and output it in the fifo */
966         is = input_files[file_index];
967         if (av_read_packet(is, &pkt) < 0) {
968             file_table[file_index].eof_reached = 1;
969             continue;
970         }
971         if (!pkt.size) {
972             stream_no_data = is;
973         } else {
974             stream_no_data = 0;
975         }
976         /* the following test is needed in case new streams appear
977            dynamically in stream : we ignore them */
978         if (pkt.stream_index >= file_table[file_index].nb_streams)
979             goto discard_packet;
980         ist_index = file_table[file_index].ist_index + pkt.stream_index;
981         ist = ist_table[ist_index];
982         if (ist->discard)
983             goto discard_packet;
984
985         if (pkt.flags & PKT_FLAG_DROPPED_FRAME)
986             ist->frame_number++;
987
988         if (do_hex_dump) {
989             printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
990             av_hex_dump(pkt.data, pkt.size);
991         }
992
993         //        printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
994
995         len = pkt.size;
996         ptr = pkt.data;
997         while (len > 0) {
998
999             /* decode the packet if needed */
1000             data_buf = NULL; /* fail safe */
1001             data_size = 0;
1002             if (ist->decoding_needed) {
1003                 switch(ist->st->codec.codec_type) {
1004                 case CODEC_TYPE_AUDIO:
1005                     /* XXX: could avoid copy if PCM 16 bits with same
1006                        endianness as CPU */
1007                     ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
1008                                                ptr, len);
1009                     if (ret < 0)
1010                         goto fail_decode;
1011                     /* Some bug in mpeg audio decoder gives */
1012                     /* data_size < 0, it seems they are overflows */
1013                     if (data_size <= 0) {
1014                         /* no audio frame */
1015                         ptr += ret;
1016                         len -= ret;
1017                         continue;
1018                     }
1019                     data_buf = (UINT8 *)samples;
1020                     break;
1021                 case CODEC_TYPE_VIDEO:
1022                     if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
1023                         int size;
1024                         size = (ist->st->codec.width * ist->st->codec.height);
1025                         avpicture_fill(&picture, ptr, 
1026                                      ist->st->codec.pix_fmt,
1027                                      ist->st->codec.width,
1028                                      ist->st->codec.height);
1029                         ret = len;
1030                     } else {
1031                         data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
1032                         ret = avcodec_decode_video(&ist->st->codec, 
1033                                                    &picture, &got_picture, ptr, len);
1034                         if (ret < 0) {
1035                         fail_decode:
1036                             fprintf(stderr, "Error while decoding stream #%d.%d\n",
1037                                     ist->file_index, ist->index);
1038                             av_free_packet(&pkt);
1039                             goto redo;
1040                         }
1041                         if (!got_picture) {
1042                             /* no picture yet */
1043                             ptr += ret;
1044                             len -= ret;
1045                             continue;
1046                         }
1047                                   
1048                     }
1049                     break;
1050                 default:
1051                     goto fail_decode;
1052                 }
1053             } else {
1054                 data_buf = ptr;
1055                 data_size = len;
1056                 ret = len;
1057             }
1058             /* init tickers */
1059             if (!ist->ticker_inited) {
1060                 switch (ist->st->codec.codec_type) {
1061                 case CODEC_TYPE_AUDIO:
1062                     ticker_init(&ist->pts_ticker,
1063                             (INT64)ist->st->codec.sample_rate,
1064                             (INT64)(1000000));
1065                     ist->ticker_inited = 1;
1066                     break;
1067                 case CODEC_TYPE_VIDEO:
1068                     ticker_init(&ist->pts_ticker,
1069                             (INT64)ist->st->r_frame_rate,
1070                             ((INT64)1000000 * FRAME_RATE_BASE));
1071                     ist->ticker_inited = 1;
1072                     break;
1073                 default:
1074                     av_abort();
1075                 }
1076             }
1077             /* update pts */
1078             switch(ist->st->codec.codec_type) {
1079             case CODEC_TYPE_AUDIO:
1080                 //ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
1081                 ist->pts = ticker_abs(&ist->pts_ticker, ist->sample_index);
1082                 ist->sample_index += data_size / (2 * ist->st->codec.channels);
1083                 ist->pts_increment = (INT64) (data_size / (2 * ist->st->codec.channels)) * 1000000 / ist->st->codec.sample_rate;
1084                 break;
1085             case CODEC_TYPE_VIDEO:
1086                 ist->frame_number++;
1087                 //ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) / 
1088                 //    ist->st->codec.frame_rate;
1089                 ist->pts = ticker_abs(&ist->pts_ticker, ist->frame_number);
1090                 ist->pts_increment = ((INT64) 1000000 * FRAME_RATE_BASE) / 
1091                     ist->st->codec.frame_rate;
1092                 break;
1093             default:
1094                 av_abort();
1095             }
1096             ptr += ret;
1097             len -= ret;
1098
1099             /* transcode raw format, encode packets and output them */
1100             
1101             for(i=0;i<nb_ostreams;i++) {
1102                 int frame_size;
1103                 ost = ost_table[i];
1104                 if (ost->source_index == ist_index) {
1105                     os = output_files[ost->file_index];
1106
1107                     if (ost->encoding_needed) {
1108                         switch(ost->st->codec.codec_type) {
1109                         case CODEC_TYPE_AUDIO:
1110                             do_audio_out(os, ost, ist, data_buf, data_size);
1111                             break;
1112                         case CODEC_TYPE_VIDEO:
1113                             do_video_out(os, ost, ist, &picture, &frame_size);
1114                             if (do_vstats)
1115                                 do_video_stats(ost, ist, frame_size);
1116                             break;
1117                         default:
1118                             av_abort();
1119                         }
1120                     } else {
1121                         /* no reencoding needed : output the packet directly */
1122                         /* force the input stream PTS */
1123                         os->oformat->write_packet(os, ost->index, data_buf, data_size, pkt.pts);
1124                     }
1125                 }
1126             }
1127         }
1128     discard_packet:
1129         av_free_packet(&pkt);
1130         
1131         /* dump report by using the first video and audio streams */
1132         {
1133             char buf[1024];
1134             AVFormatContext *oc;
1135             INT64 total_size, ti;
1136             AVCodecContext *enc;
1137             int frame_number, vid;
1138             double bitrate, ti1;
1139             static INT64 last_time;
1140
1141             if ((min_pts - last_time) >= 500000) {
1142                 last_time = min_pts;
1143                 
1144                 oc = output_files[0];
1145                 
1146                 total_size = url_ftell(&oc->pb);
1147                 
1148                 buf[0] = '\0';
1149                 ti = MAXINT64;
1150                 vid = 0;
1151                 for(i=0;i<nb_ostreams;i++) {
1152                     ost = ost_table[i];
1153                     enc = &ost->st->codec;
1154                     ist = ist_table[ost->source_index];
1155                     if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1156                         frame_number = ist->frame_number;
1157                         sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1158                                 frame_number, enc->quality);
1159                         if (do_psnr)
1160                             sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1161                         vid = 1;
1162                     }
1163                     /* compute min pts value */
1164                     if (!ist->discard && ist->pts < ti) {
1165                         ti = ist->pts;
1166                     }
1167                 }
1168
1169                 ti1 = (double)ti / 1000000.0;
1170                 if (ti1 < 0.01)
1171                     ti1 = 0.01;
1172                 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1173
1174                 sprintf(buf + strlen(buf), 
1175                         "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1176                         (double)total_size / 1024, ti1, bitrate);
1177                 
1178                 fprintf(stderr, "%s   \r", buf);
1179                 fflush(stderr);
1180             }
1181         }
1182     }
1183     term_exit();
1184
1185     /* dump report by using the first video and audio streams */
1186     {
1187         char buf[1024];
1188         AVFormatContext *oc;
1189         INT64 total_size, ti;
1190         AVCodecContext *enc;
1191         int frame_number, vid;
1192         double bitrate, ti1;
1193
1194         oc = output_files[0];
1195         
1196         total_size = url_ftell(&oc->pb);
1197         
1198         buf[0] = '\0';
1199         ti = MAXINT64;
1200         vid = 0;
1201         for(i=0;i<nb_ostreams;i++) {
1202             ost = ost_table[i];
1203             enc = &ost->st->codec;
1204             ist = ist_table[ost->source_index];
1205             if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1206                 frame_number = ist->frame_number;
1207                 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1208                         frame_number, enc->quality);
1209                 if (do_psnr)
1210                     sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1211                 vid = 1;
1212             }
1213             /* compute min pts value */
1214             if (!ist->discard && ist->pts < ti) {
1215                 ti = ist->pts;
1216             }
1217         }
1218         
1219         ti1 = ti / 1000000.0;
1220         if (ti1 < 0.01)
1221             ti1 = 0.01;
1222         bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1223         
1224         sprintf(buf + strlen(buf), 
1225                 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1226                 (double)total_size / 1024, ti1, bitrate);
1227         
1228         fprintf(stderr, "%s   \n", buf);
1229     }
1230     /* close each encoder */
1231     for(i=0;i<nb_ostreams;i++) {
1232         ost = ost_table[i];
1233         if (ost->encoding_needed) {
1234             avcodec_close(&ost->st->codec);
1235         }
1236     }
1237     
1238     /* close each decoder */
1239     for(i=0;i<nb_istreams;i++) {
1240         ist = ist_table[i];
1241         if (ist->decoding_needed) {
1242             avcodec_close(&ist->st->codec);
1243         }
1244     }
1245     
1246
1247     /* write the trailer if needed and close file */
1248     for(i=0;i<nb_output_files;i++) {
1249         os = output_files[i];
1250         av_write_trailer(os);
1251     }
1252     /* finished ! */
1253     
1254     ret = 0;
1255  fail1:
1256     av_free(file_table);
1257
1258     if (ist_table) {
1259         for(i=0;i<nb_istreams;i++) {
1260             ist = ist_table[i];
1261             av_free(ist);
1262         }
1263         av_free(ist_table);
1264     }
1265     if (ost_table) {
1266         for(i=0;i<nb_ostreams;i++) {
1267             ost = ost_table[i];
1268             if (ost) {
1269                 fifo_free(&ost->fifo); /* works even if fifo is not
1270                                           initialized but set to zero */
1271                 av_free(ost->pict_tmp.data[0]);
1272                 if (ost->video_resample)
1273                     img_resample_close(ost->img_resample_ctx);
1274                 if (ost->audio_resample)
1275                     audio_resample_close(ost->resample);
1276                 av_free(ost);
1277             }
1278         }
1279         av_free(ost_table);
1280     }
1281     return ret;
1282  fail:
1283     ret = -ENOMEM;
1284     goto fail1;
1285 }
1286
1287 #if 0
1288 int file_read(const char *filename)
1289 {
1290     URLContext *h;
1291     unsigned char buffer[1024];
1292     int len, i;
1293
1294     if (url_open(&h, filename, O_RDONLY) < 0) {
1295         printf("could not open '%s'\n", filename);
1296         return -1;
1297     }
1298     for(;;) {
1299         len = url_read(h, buffer, sizeof(buffer));
1300         if (len <= 0)
1301             break;
1302         for(i=0;i<len;i++) putchar(buffer[i]);
1303     }
1304     url_close(h);
1305     return 0;
1306 }
1307 #endif
1308
1309 void show_licence(void)
1310 {
1311     printf(
1312     "ffmpeg version " FFMPEG_VERSION "\n"
1313     "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
1314     "This library is free software; you can redistribute it and/or\n"
1315     "modify it under the terms of the GNU Lesser General Public\n"
1316     "License as published by the Free Software Foundation; either\n"
1317     "version 2 of the License, or (at your option) any later version.\n"
1318     "\n"
1319     "This library is distributed in the hope that it will be useful,\n"
1320     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1321     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
1322     "Lesser General Public License for more details.\n"
1323     "\n"
1324     "You should have received a copy of the GNU Lesser General Public\n"
1325     "License along with this library; if not, write to the Free Software\n"
1326     "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
1327     );
1328     exit(1);
1329 }
1330
1331 void opt_format(const char *arg)
1332 {
1333     file_iformat = av_find_input_format(arg);
1334     file_oformat = guess_format(arg, NULL, NULL);
1335     if (!file_iformat && !file_oformat) {
1336         fprintf(stderr, "Unknown input or output format: %s\n", arg);
1337         exit(1);
1338     }
1339 }
1340
1341 void opt_video_bitrate(const char *arg)
1342 {
1343     video_bit_rate = atoi(arg) * 1000;
1344 }
1345
1346 void opt_video_bitrate_tolerance(const char *arg)
1347 {
1348     video_bit_rate_tolerance = atoi(arg) * 1000;
1349 }
1350
1351 void opt_video_bitrate_max(const char *arg)
1352 {
1353     video_rc_max_rate = atoi(arg) * 1000;
1354 }
1355
1356 void opt_video_bitrate_min(const char *arg)
1357 {
1358     video_rc_min_rate = atoi(arg) * 1000;
1359 }
1360
1361 void opt_video_rc_eq(char *arg)
1362 {
1363     video_rc_eq = arg;
1364 }
1365
1366
1367 void opt_workaround_bugs(const char *arg)
1368 {
1369     workaround_bugs = atoi(arg);
1370 }
1371
1372 void opt_frame_rate(const char *arg)
1373 {
1374     frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1375 }
1376
1377 void opt_frame_size(const char *arg)
1378 {
1379     parse_image_size(&frame_width, &frame_height, arg);
1380     if (frame_width <= 0 || frame_height <= 0) {
1381         fprintf(stderr, "Incorrect frame size\n");
1382         exit(1);
1383     }
1384     if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1385         fprintf(stderr, "Frame size must be a multiple of 2\n");
1386         exit(1);
1387     }
1388 }
1389
1390 void opt_gop_size(const char *arg)
1391 {
1392     gop_size = atoi(arg);
1393 }
1394
1395 void opt_b_frames(const char *arg)
1396 {
1397     b_frames = atoi(arg);
1398     if (b_frames > FF_MAX_B_FRAMES) {
1399         fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
1400         exit(1);
1401     } else if (b_frames < 1) {
1402         fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
1403         exit(1);
1404     }
1405 }
1406
1407 void opt_qscale(const char *arg)
1408 {
1409     video_qscale = atoi(arg);
1410     if (video_qscale < 0 ||
1411         video_qscale > 31) {
1412         fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1413         exit(1);
1414     }
1415 }
1416
1417 void opt_qmin(const char *arg)
1418 {
1419     video_qmin = atoi(arg);
1420     if (video_qmin < 0 ||
1421         video_qmin > 31) {
1422         fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1423         exit(1);
1424     }
1425 }
1426
1427 void opt_qmax(const char *arg)
1428 {
1429     video_qmax = atoi(arg);
1430     if (video_qmax < 0 ||
1431         video_qmax > 31) {
1432         fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1433         exit(1);
1434     }
1435 }
1436
1437 void opt_qdiff(const char *arg)
1438 {
1439     video_qdiff = atoi(arg);
1440     if (video_qdiff < 0 ||
1441         video_qdiff > 31) {
1442         fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1443         exit(1);
1444     }
1445 }
1446
1447 void opt_qblur(const char *arg)
1448 {
1449     video_qblur = atof(arg);
1450 }
1451
1452 void opt_qcomp(const char *arg)
1453 {
1454     video_qcomp = atof(arg);
1455 }
1456
1457 void opt_audio_bitrate(const char *arg)
1458 {
1459     audio_bit_rate = atoi(arg) * 1000;
1460 }
1461
1462 void opt_audio_rate(const char *arg)
1463 {
1464     audio_sample_rate = atoi(arg);
1465 }
1466
1467 void opt_audio_channels(const char *arg)
1468 {
1469     audio_channels = atoi(arg);
1470 }
1471
1472 void opt_video_device(const char *arg)
1473 {
1474     v4l_device = strdup(arg);
1475 }
1476
1477 void opt_audio_device(const char *arg)
1478 {
1479     audio_device = strdup(arg);
1480 }
1481
1482 void opt_audio_codec(const char *arg)
1483 {
1484     AVCodec *p;
1485
1486     p = first_avcodec;
1487     while (p) {
1488         if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1489             break;
1490         p = p->next;
1491     }
1492     if (p == NULL) {
1493         fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1494         exit(1);
1495     } else {
1496         audio_codec_id = p->id;
1497     }
1498 }
1499
1500 const char *motion_str[] = {
1501     "zero",
1502     "full",
1503     "log",
1504     "phods",
1505     "epzs",
1506     "x1",
1507     NULL,
1508 };
1509
1510 void opt_motion_estimation(const char *arg)
1511 {
1512     const char **p;
1513     p = motion_str;
1514     for(;;) {
1515         if (!*p) {
1516             fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1517             exit(1);
1518         }
1519         if (!strcmp(*p, arg))
1520             break;
1521         p++;
1522     }
1523     me_method = (p - motion_str) + 1;
1524 }
1525
1526 void opt_video_codec(const char *arg)
1527 {
1528     AVCodec *p;
1529
1530     p = first_avcodec;
1531     while (p) {
1532         if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1533             break;
1534         p = p->next;
1535     }
1536     if (p == NULL) {
1537         fprintf(stderr, "Unknown video codec '%s'\n", arg);
1538         exit(1);
1539     } else {
1540         video_codec_id = p->id;
1541     }
1542 }
1543
1544 void opt_map(const char *arg)
1545 {
1546     AVStreamMap *m;
1547     const char *p;
1548
1549     p = arg;
1550     m = &stream_maps[nb_stream_maps++];
1551
1552     m->file_index = strtol(arg, (char **)&p, 0);
1553     if (*p)
1554         p++;
1555
1556     m->stream_index = strtol(p, (char **)&p, 0);
1557 }
1558
1559 void opt_recording_time(const char *arg)
1560 {
1561     recording_time = parse_date(arg, 1);
1562 }
1563
1564 void print_error(const char *filename, int err)
1565 {
1566     switch(err) {
1567     case AVERROR_NUMEXPECTED:
1568         fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1569                 "Use '%%d' to specify the image number:\n"
1570                 "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1571                 "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1572                 filename);
1573         break;
1574     case AVERROR_INVALIDDATA:
1575         fprintf(stderr, "%s: Error while parsing header\n", filename);
1576         break;
1577     case AVERROR_NOFMT:
1578         fprintf(stderr, "%s: Unknown format\n", filename);
1579         break;
1580     default:
1581         fprintf(stderr, "%s: Error while opening file\n", filename);
1582         break;
1583     }
1584 }
1585
1586 void opt_input_file(const char *filename)
1587 {
1588     AVFormatContext *ic;
1589     AVFormatParameters params, *ap = &params;
1590     int err, i, ret, rfps;
1591
1592     /* get default parameters from command line */
1593     memset(ap, 0, sizeof(*ap));
1594     ap->sample_rate = audio_sample_rate;
1595     ap->channels = audio_channels;
1596     ap->frame_rate = frame_rate;
1597     ap->width = frame_width;
1598     ap->height = frame_height;
1599
1600     /* open the input file with generic libav function */
1601     err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
1602     if (err < 0) {
1603         print_error(filename, err);
1604         exit(1);
1605     }
1606     
1607     /* If not enough info to get the stream parameters, we decode the
1608        first frames to get it. (used in mpeg case for example) */
1609     ret = av_find_stream_info(ic);
1610     if (ret < 0) {
1611         fprintf(stderr, "%s: could not find codec parameters\n", filename);
1612         exit(1);
1613     }
1614
1615     /* update the current parameters so that they match the one of the input stream */
1616     for(i=0;i<ic->nb_streams;i++) {
1617         AVCodecContext *enc = &ic->streams[i]->codec;
1618         switch(enc->codec_type) {
1619         case CODEC_TYPE_AUDIO:
1620             //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
1621             audio_channels = enc->channels;
1622             audio_sample_rate = enc->sample_rate;
1623             break;
1624         case CODEC_TYPE_VIDEO:
1625             frame_height = enc->height;
1626             frame_width = enc->width;
1627             rfps = ic->streams[i]->r_frame_rate;
1628             enc->workaround_bugs = workaround_bugs;
1629             if (enc->frame_rate != rfps) {
1630                 fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
1631                     i, (float)enc->frame_rate / FRAME_RATE_BASE,
1632                     (float)rfps / FRAME_RATE_BASE);
1633             }
1634             /* update the current frame rate to match the stream frame rate */
1635             frame_rate = rfps;
1636             break;
1637         default:
1638             av_abort();
1639         }
1640     }
1641     
1642     input_files[nb_input_files] = ic;
1643     /* dump the file content */
1644     dump_format(ic, nb_input_files, filename, 0);
1645     nb_input_files++;
1646     file_iformat = NULL;
1647     file_oformat = NULL;
1648 }
1649
1650 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1651 {
1652     int has_video, has_audio, i, j;
1653     AVFormatContext *ic;
1654
1655     has_video = 0;
1656     has_audio = 0;
1657     for(j=0;j<nb_input_files;j++) {
1658         ic = input_files[j];
1659         for(i=0;i<ic->nb_streams;i++) {
1660             AVCodecContext *enc = &ic->streams[i]->codec;
1661             switch(enc->codec_type) {
1662             case CODEC_TYPE_AUDIO:
1663                 has_audio = 1;
1664                 break;
1665             case CODEC_TYPE_VIDEO:
1666                 has_video = 1;
1667                 break;
1668             default:
1669                 av_abort();
1670             }
1671         }
1672     }
1673     *has_video_ptr = has_video;
1674     *has_audio_ptr = has_audio;
1675 }
1676
1677 void opt_output_file(const char *filename)
1678 {
1679     AVStream *st;
1680     AVFormatContext *oc;
1681     int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1682     int codec_id;
1683
1684     if (!strcmp(filename, "-"))
1685         filename = "pipe:";
1686
1687     oc = av_mallocz(sizeof(AVFormatContext));
1688
1689     if (!file_oformat) {
1690         file_oformat = guess_format(NULL, filename, NULL);
1691         if (!file_oformat) {
1692             fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
1693                     filename);
1694             exit(1);
1695         }
1696     }
1697     
1698     oc->oformat = file_oformat;
1699
1700     if (!strcmp(file_oformat->name, "ffm") && 
1701         strstart(filename, "http:", NULL)) {
1702         /* special case for files sent to ffserver: we get the stream
1703            parameters from ffserver */
1704         if (read_ffserver_streams(oc, filename) < 0) {
1705             fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1706             exit(1);
1707         }
1708     } else {
1709         use_video = file_oformat->video_codec != CODEC_ID_NONE;
1710         use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
1711
1712         /* disable if no corresponding type found and at least one
1713            input file */
1714         if (nb_input_files > 0) {
1715             check_audio_video_inputs(&input_has_video, &input_has_audio);
1716             if (!input_has_video)
1717                 use_video = 0;
1718             if (!input_has_audio)
1719                 use_audio = 0;
1720         }
1721
1722         /* manual disable */
1723         if (audio_disable) {
1724             use_audio = 0;
1725         }
1726         if (video_disable) {
1727             use_video = 0;
1728         }
1729         
1730         nb_streams = 0;
1731         if (use_video) {
1732             AVCodecContext *video_enc;
1733             
1734             st = av_mallocz(sizeof(AVStream));
1735             if (!st) {
1736                 fprintf(stderr, "Could not alloc stream\n");
1737                 exit(1);
1738             }
1739             video_enc = &st->codec;
1740
1741             codec_id = file_oformat->video_codec;
1742             if (video_codec_id != CODEC_ID_NONE)
1743                 codec_id = video_codec_id;
1744
1745             video_enc->codec_id = codec_id;
1746             video_enc->codec_type = CODEC_TYPE_VIDEO;
1747             
1748             video_enc->bit_rate = video_bit_rate;
1749             video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1750             video_enc->frame_rate = frame_rate; 
1751             
1752             video_enc->width = frame_width;
1753             video_enc->height = frame_height;
1754             if (!intra_only)
1755                 video_enc->gop_size = gop_size;
1756             else
1757                 video_enc->gop_size = 0;
1758             if (video_qscale || same_quality) {
1759                 video_enc->flags |= CODEC_FLAG_QSCALE;
1760                 video_enc->quality = video_qscale;
1761             }
1762             
1763             if (use_hq) {
1764                 video_enc->flags |= CODEC_FLAG_HQ;
1765             }
1766             
1767             if (use_4mv) {
1768                 video_enc->flags |= CODEC_FLAG_HQ;
1769                 video_enc->flags |= CODEC_FLAG_4MV;
1770             }
1771             
1772             if (b_frames) {
1773                 if (codec_id != CODEC_ID_MPEG4) {
1774                     fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
1775                     exit(1);
1776                 }
1777                 video_enc->max_b_frames = b_frames;
1778                 video_enc->b_frame_strategy = 0;
1779                 video_enc->b_quant_factor = 2.0;
1780             }
1781             
1782             video_enc->qmin = video_qmin;
1783             video_enc->qmax = video_qmax;
1784             video_enc->max_qdiff = video_qdiff;
1785             video_enc->qblur = video_qblur;
1786             video_enc->qcompress = video_qcomp;
1787             video_enc->rc_eq = video_rc_eq;
1788             video_enc->rc_max_rate = video_rc_max_rate;
1789             video_enc->rc_min_rate = video_rc_min_rate;
1790             video_enc->rc_buffer_size = video_rc_buffer_size;
1791             video_enc->i_quant_factor = video_i_qfactor;
1792             video_enc->b_quant_factor = video_b_qfactor;
1793             video_enc->i_quant_offset = video_i_qoffset;
1794             video_enc->b_quant_offset = video_b_qoffset;
1795             
1796             if (do_psnr)
1797                 video_enc->get_psnr = 1;
1798             else
1799                 video_enc->get_psnr = 0;
1800             
1801             video_enc->me_method = me_method;
1802             
1803             /* XXX: need to find a way to set codec parameters */
1804             if (oc->oformat->flags & AVFMT_RGB24) {
1805                 video_enc->pix_fmt = PIX_FMT_RGB24;
1806             }
1807
1808             oc->streams[nb_streams] = st;
1809             nb_streams++;
1810         }
1811     
1812         if (use_audio) {
1813             AVCodecContext *audio_enc;
1814
1815             st = av_mallocz(sizeof(AVStream));
1816             if (!st) {
1817                 fprintf(stderr, "Could not alloc stream\n");
1818                 exit(1);
1819             }
1820             audio_enc = &st->codec;
1821             codec_id = file_oformat->audio_codec;
1822             if (audio_codec_id != CODEC_ID_NONE)
1823                 codec_id = audio_codec_id;
1824             audio_enc->codec_id = codec_id;
1825             audio_enc->codec_type = CODEC_TYPE_AUDIO;
1826             
1827             audio_enc->bit_rate = audio_bit_rate;
1828             audio_enc->sample_rate = audio_sample_rate;
1829             /* For audio codecs other than AC3 we limit */
1830             /* the number of coded channels to stereo   */
1831             if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
1832                 audio_enc->channels = 2;
1833             } else
1834                 audio_enc->channels = audio_channels;
1835             oc->streams[nb_streams] = st;
1836             nb_streams++;
1837         }
1838
1839         oc->nb_streams = nb_streams;
1840
1841         if (!nb_streams) {
1842             fprintf(stderr, "No audio or video streams available\n");
1843             exit(1);
1844         }
1845
1846         if (str_title)
1847             pstrcpy(oc->title, sizeof(oc->title), str_title);
1848         if (str_author)
1849             pstrcpy(oc->author, sizeof(oc->author), str_author);
1850         if (str_copyright)
1851             pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
1852         if (str_comment)
1853             pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
1854     }
1855
1856     output_files[nb_output_files] = oc;
1857     /* dump the file content */
1858     dump_format(oc, nb_output_files, filename, 1);
1859     nb_output_files++;
1860
1861     strcpy(oc->filename, filename);
1862
1863     /* check filename in case of an image number is expected */
1864     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
1865         if (filename_number_test(oc->filename) < 0) {
1866             print_error(oc->filename, AVERROR_NUMEXPECTED);
1867             exit(1);
1868         }
1869     }
1870
1871     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
1872         /* test if it already exists to avoid loosing precious files */
1873         if (!file_overwrite && 
1874             (strchr(filename, ':') == NULL ||
1875              strstart(filename, "file:", NULL))) {
1876             if (url_exist(filename)) {
1877                 int c;
1878                 
1879                 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
1880                 fflush(stdout);
1881                 c = getchar();
1882                 if (toupper(c) != 'Y') {
1883                     fprintf(stderr, "Not overwriting - exiting\n");
1884                     exit(1);
1885                 }
1886             }
1887         }
1888         
1889         /* open the file */
1890         if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
1891             fprintf(stderr, "Could not open '%s'\n", filename);
1892             exit(1);
1893         }
1894     }
1895
1896     /* reset some options */
1897     file_oformat = NULL;
1898     file_iformat = NULL;
1899     audio_disable = 0;
1900     video_disable = 0;
1901     audio_codec_id = CODEC_ID_NONE;
1902     video_codec_id = CODEC_ID_NONE;
1903 }
1904
1905 /* prepare dummy protocols for grab */
1906 void prepare_grab(void)
1907 {
1908     int has_video, has_audio, i, j;
1909     AVFormatContext *oc;
1910     AVFormatContext *ic;
1911     AVFormatParameters ap1, *ap = &ap1;
1912
1913     /* see if audio/video inputs are needed */
1914     has_video = 0;
1915     has_audio = 0;
1916     memset(ap, 0, sizeof(*ap));
1917     for(j=0;j<nb_output_files;j++) {
1918         oc = output_files[j];
1919         for(i=0;i<oc->nb_streams;i++) {
1920             AVCodecContext *enc = &oc->streams[i]->codec;
1921             switch(enc->codec_type) {
1922             case CODEC_TYPE_AUDIO:
1923                 if (enc->sample_rate > ap->sample_rate)
1924                     ap->sample_rate = enc->sample_rate;
1925                 if (enc->channels > ap->channels)
1926                     ap->channels = enc->channels;
1927                 has_audio = 1;
1928                 break;
1929             case CODEC_TYPE_VIDEO:
1930                 if (enc->width > ap->width)
1931                     ap->width = enc->width;
1932                 if (enc->height > ap->height)
1933                     ap->height = enc->height;
1934                 if (enc->frame_rate > ap->frame_rate)
1935                     ap->frame_rate = enc->frame_rate;
1936                 has_video = 1;
1937                 break;
1938             default:
1939                 av_abort();
1940             }
1941         }
1942     }
1943     
1944     if (has_video == 0 && has_audio == 0) {
1945         fprintf(stderr, "Output file must have at least one audio or video stream\n");
1946         exit(1);
1947     }
1948     
1949     if (has_video) {
1950         AVInputFormat *fmt1;
1951         fmt1 = av_find_input_format("video_grab_device");
1952         if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
1953             fprintf(stderr, "Could not find video grab device\n");
1954             exit(1);
1955         }
1956         /* by now video grab has one stream */
1957         ic->streams[0]->r_frame_rate = ap->frame_rate;
1958         input_files[nb_input_files] = ic;
1959         dump_format(ic, nb_input_files, v4l_device, 0);
1960         nb_input_files++;
1961     }
1962     if (has_audio) {
1963         AVInputFormat *fmt1;
1964         fmt1 = av_find_input_format("audio_device");
1965         if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
1966             fprintf(stderr, "Could not find audio grab device\n");
1967             exit(1);
1968         }
1969         input_files[nb_input_files] = ic;
1970         dump_format(ic, nb_input_files, audio_device, 0);
1971         nb_input_files++;
1972     }
1973 }
1974
1975 /* open the necessary output devices for playing */
1976 void prepare_play(void)
1977 {
1978     file_iformat = NULL;
1979     file_oformat = guess_format("audio_device", NULL, NULL);
1980     if (!file_oformat) {
1981         fprintf(stderr, "Could not find audio device\n");
1982         exit(1);
1983     }
1984     
1985     opt_output_file(audio_device);
1986 }
1987
1988
1989 #ifndef CONFIG_WIN32
1990 INT64 getutime(void)
1991 {
1992     struct rusage rusage;
1993
1994     getrusage(RUSAGE_SELF, &rusage);
1995     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
1996 }
1997 #else
1998 INT64 getutime(void)
1999 {
2000   return av_gettime();
2001 }
2002 #endif
2003
2004 extern int ffm_nopts;
2005
2006 void opt_bitexact(void)
2007 {
2008     avcodec_set_bit_exact();
2009     /* disable generate of real time pts in ffm (need to be supressed anyway) */
2010     ffm_nopts = 1;
2011 }
2012
2013 void show_formats(void)
2014 {
2015     AVInputFormat *ifmt;
2016     AVOutputFormat *ofmt;
2017     URLProtocol *up;
2018     AVCodec *p;
2019     const char **pp;
2020
2021     printf("File formats:\n");
2022     printf("  Encoding:");
2023     for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
2024         printf(" %s", ofmt->name);
2025     }
2026     printf("\n");
2027     printf("  Decoding:");
2028     for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
2029         printf(" %s", ifmt->name);
2030     }
2031     printf("\n");
2032
2033     printf("Codecs:\n");
2034     printf("  Encoders:");
2035     for(p = first_avcodec; p != NULL; p = p->next) {
2036         if (p->encode)
2037             printf(" %s", p->name);
2038     }
2039     printf("\n");
2040
2041     printf("  Decoders:");
2042     for(p = first_avcodec; p != NULL; p = p->next) {
2043         if (p->decode)
2044             printf(" %s", p->name);
2045     }
2046     printf("\n");
2047
2048     printf("Supported file protocols:");
2049     for(up = first_protocol; up != NULL; up = up->next)
2050         printf(" %s:", up->name);
2051     printf("\n");
2052     
2053     printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2054     printf("Motion estimation methods:");
2055     pp = motion_str;
2056     while (*pp) {
2057         printf(" %s", *pp);
2058         if ((pp - motion_str + 1) == ME_ZERO) 
2059             printf("(fastest)");
2060         else if ((pp - motion_str + 1) == ME_FULL) 
2061             printf("(slowest)");
2062         else if ((pp - motion_str + 1) == ME_EPZS) 
2063             printf("(default)");
2064         pp++;
2065     }
2066     printf("\n");
2067     exit(1);
2068 }
2069
2070 void show_help(void)
2071 {
2072     const char *prog;
2073     const OptionDef *po;
2074     int i, expert;
2075     
2076     prog = do_play ? "ffplay" : "ffmpeg";
2077
2078     printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
2079            prog);
2080     
2081     if (!do_play) {
2082         printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2083                "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2084     } else {
2085         printf("usage: ffplay [options] input_file...\n"
2086                "Simple audio player\n");
2087     }
2088            
2089     printf("\n"
2090            "Main options are:\n");
2091     for(i=0;i<2;i++) {
2092         if (i == 1)
2093             printf("\nAdvanced options are:\n");
2094         for(po = options; po->name != NULL; po++) {
2095             char buf[64];
2096             expert = (po->flags & OPT_EXPERT) != 0;
2097             if (expert == i) {
2098                 strcpy(buf, po->name);
2099                 if (po->flags & HAS_ARG) {
2100                     strcat(buf, " ");
2101                     strcat(buf, po->argname);
2102                 }
2103                 printf("-%-17s  %s\n", buf, po->help);
2104             }
2105         }
2106     }
2107
2108     exit(1);
2109 }
2110
2111 const OptionDef options[] = {
2112     { "L", 0, {(void*)show_licence}, "show license" },
2113     { "h", 0, {(void*)show_help}, "show help" },
2114     { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2115     { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2116     { "vcd", OPT_BOOL, {(void*)&mpeg_vcd}, "output Video CD MPEG-PS compliant file" },
2117     { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2118     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2119     { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2120     { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2121     { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2122     { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2123     { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2124     { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2125     /* video options */
2126     { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2127     { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2128     { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2129     { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2130     { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2131     { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2132     { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2133     { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2134     { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2135     { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2136     { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2137     { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2138     { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
2139     { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2140     { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
2141     { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
2142     { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
2143     { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2144     { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2145       "method" },
2146     { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
2147     { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
2148     { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
2149     { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
2150     { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2151       "use same video quality as source (implies VBR)" },
2152     /* audio options */
2153     { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2154     { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2155     { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2156     { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2157     { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2158     { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2159     { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2160       "deinterlace pictures" },
2161     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2162       "add timings for benchmarking" },
2163     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2164       "dump each input packet" },
2165     { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2166     { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2167     { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" }, 
2168     { NULL, },
2169 };
2170
2171 int main(int argc, char **argv)
2172 {
2173     int optindex, i;
2174     const char *opt, *arg;
2175     const OptionDef *po;
2176     INT64 ti;
2177     
2178     av_register_all();
2179
2180     /* detect if invoked as player */
2181     i = strlen(argv[0]);
2182     if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2183         do_play = 1;
2184
2185     if (argc <= 1)
2186         show_help();
2187     
2188     /* parse options */
2189     optindex = 1;
2190     while (optindex < argc) {
2191         opt = argv[optindex++];
2192         
2193         if (opt[0] == '-' && opt[1] != '\0') {
2194             po = options;
2195             while (po->name != NULL) {
2196                 if (!strcmp(opt + 1, po->name))
2197                     break;
2198                 po++;
2199             }
2200             if (!po->name) {
2201                 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2202                 exit(1);
2203             }
2204             arg = NULL;
2205             if (po->flags & HAS_ARG)
2206                 arg = argv[optindex++];
2207             if (po->flags & OPT_STRING) {
2208                 char *str;
2209                 str = strdup(arg);
2210                 *po->u.str_arg = str;
2211             } else if (po->flags & OPT_BOOL) {
2212                 *po->u.int_arg = 1;
2213             } else {
2214                 po->u.func_arg(arg);
2215             }
2216         } else {
2217             if (!do_play) {
2218                 opt_output_file(opt);
2219             } else {
2220                 opt_input_file(opt);
2221             }
2222         }
2223     }
2224
2225
2226     if (!do_play) {
2227         /* file converter / grab */
2228         if (nb_output_files <= 0) {
2229             fprintf(stderr, "Must supply at least one output file\n");
2230             exit(1);
2231         }
2232         
2233         if (nb_input_files == 0) {
2234             prepare_grab();
2235         }
2236     } else {
2237         /* player */
2238         if (nb_input_files <= 0) {
2239             fprintf(stderr, "Must supply at least one input file\n");
2240             exit(1);
2241         }
2242         prepare_play();
2243     }
2244
2245     ti = getutime();
2246     av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2247               stream_maps, nb_stream_maps);
2248     ti = getutime() - ti;
2249     if (do_benchmark) {
2250         printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2251     }
2252
2253     /* close files */
2254     for(i=0;i<nb_output_files;i++) {
2255         if (!(output_files[i]->oformat->flags & AVFMT_NOFILE)) 
2256             url_fclose(&output_files[i]->pb);
2257     }
2258     for(i=0;i<nb_input_files;i++)
2259         av_close_input_file(input_files[i]);
2260
2261     return 0;
2262 }