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