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