]> git.sesse.net Git - ffmpeg/blob - ffmpeg.c
- Fix memory leak and others bugs for ppmpipe. Thanks to Rudolf Opalla.
[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);
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);
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);
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);
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             } else {
732                 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
733                     goto fail;
734
735                 if (codec->channels == icodec->channels &&
736                     codec->sample_rate == icodec->sample_rate) {
737                     ost->audio_resample = 0;
738                 } else {
739                     ost->audio_resample = 1;
740                     ost->resample = audio_resample_init(codec->channels, icodec->channels,
741                                                         codec->sample_rate, 
742                                                         icodec->sample_rate);
743                 }
744                 ist->decoding_needed = 1;
745                 ost->encoding_needed = 1;
746             }
747             break;
748         case CODEC_TYPE_VIDEO:
749             /* check if same codec with same parameters. If so, no
750                reencoding is needed */
751             if (codec->codec_id == icodec->codec_id &&
752                 codec->bit_rate == icodec->bit_rate &&
753                 codec->frame_rate == icodec->frame_rate &&
754                 codec->width == icodec->width &&
755                 codec->height == icodec->height) {
756                 /* no reencoding */
757             } else {
758                 if (codec->width == icodec->width &&
759                     codec->height == icodec->height) {
760                     ost->video_resample = 0;
761                 } else {
762                     UINT8 *buf;
763                     ost->video_resample = 1;
764                     buf = malloc((codec->width * codec->height * 3) / 2);
765                     if (!buf)
766                         goto fail;
767                     ost->pict_tmp.data[0] = buf;
768                     ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
769                     ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
770                     ost->pict_tmp.linesize[0] = codec->width;
771                     ost->pict_tmp.linesize[1] = codec->width / 2;
772                     ost->pict_tmp.linesize[2] = codec->width / 2;
773
774                     ost->img_resample_ctx = img_resample_init( 
775                                       ost->st->codec.width, ost->st->codec.height,
776                                       ist->st->codec.width, ist->st->codec.height);
777                 }
778                 ost->encoding_needed = 1;
779                 ist->decoding_needed = 1;
780             }
781             break;
782         }
783     }
784
785     /* open each encoder */
786     for(i=0;i<nb_ostreams;i++) {
787         ost = ost_table[i];
788         if (ost->encoding_needed) {
789             AVCodec *codec;
790             codec = avcodec_find_encoder(ost->st->codec.codec_id);
791             if (!codec) {
792                 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
793                         ost->file_index, ost->index);
794                 exit(1);
795             }
796             if (avcodec_open(&ost->st->codec, codec) < 0) {
797                 fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
798                         ost->file_index, ost->index);
799                 exit(1);
800             }
801         }
802     }
803
804     /* open each decoder */
805     for(i=0;i<nb_istreams;i++) {
806         ist = ist_table[i];
807         if (ist->decoding_needed) {
808             AVCodec *codec;
809             codec = avcodec_find_decoder(ist->st->codec.codec_id);
810             if (!codec) {
811                 fprintf(stderr, "Unsupported codec for input stream #%d.%d\n", 
812                         ist->file_index, ist->index);
813                 exit(1);
814             }
815             if (avcodec_open(&ist->st->codec, codec) < 0) {
816                 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
817                         ist->file_index, ist->index);
818                 exit(1);
819             }
820         }
821     }
822
823     /* init pts */
824     for(i=0;i<nb_istreams;i++) {
825         ist = ist_table[i];
826         ist->pts = 0;
827         ist->frame_number = 0;
828     }
829     
830     /* compute buffer size max (should use a complete heuristic) */
831     for(i=0;i<nb_input_files;i++) {
832         file_table[i].buffer_size_max = 2048;
833     }
834
835     /* open files and write file headers */
836     for(i=0;i<nb_output_files;i++) {
837         os = output_files[i];
838         if (os->format->write_header(os) < 0) {
839             fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
840             ret = -EINVAL;
841             goto fail;
842         }
843     }
844
845 #ifndef CONFIG_WIN32
846     if (!do_play) {
847         fprintf(stderr, "Press [q] to stop encoding\n");
848     } else {
849         fprintf(stderr, "Press [q] to stop playing\n");
850     }
851 #endif
852     term_init();
853
854     start_time = gettime();
855     min_pts = 0;
856     for(;;) {
857         int file_index, ist_index;
858         AVPacket pkt;
859         UINT8 *ptr;
860         int len;
861         UINT8 *data_buf;
862         int data_size, got_picture;
863         AVPicture picture;
864         short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
865
866     redo:
867         /* if 'q' pressed, exits */
868         if (read_key() == 'q')
869             break;
870
871         /* select the input file with the smallest pts */
872         file_index = -1;
873         min_pts = MAXINT64;
874         for(i=0;i<nb_istreams;i++) {
875             ist = ist_table[i];
876             if (!ist->discard && !file_table[ist->file_index].eof_reached && ist->pts < min_pts) {
877                 min_pts = ist->pts;
878                 file_index = ist->file_index;
879             }
880         }
881         /* if none, if is finished */
882         if (file_index < 0)
883             break;
884         /* finish if recording time exhausted */
885         if (recording_time > 0 && min_pts >= recording_time)
886             break;
887         /* read a packet from it and output it in the fifo */
888         is = input_files[file_index];
889         if (av_read_packet(is, &pkt) < 0) {
890             file_table[file_index].eof_reached = 1;
891             continue;
892         }
893         ist_index = file_table[file_index].ist_index + pkt.stream_index;
894         ist = ist_table[ist_index];
895         if (ist->discard) {
896             continue;
897         }
898
899         if (do_hex_dump) {
900             printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
901             hex_dump(pkt.data, pkt.size);
902         }
903
904         //        printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
905
906         len = pkt.size;
907         ptr = pkt.data;
908         while (len > 0) {
909
910             /* decode the packet if needed */
911             data_buf = NULL; /* fail safe */
912             data_size = 0;
913             if (ist->decoding_needed) {
914                 switch(ist->st->codec.codec_type) {
915                 case CODEC_TYPE_AUDIO:
916                     /* XXX: could avoid copy if PCM 16 bits with same
917                        endianness as CPU */
918                     ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
919                                                ptr, len);
920                     if (ret < 0)
921                         goto fail_decode;
922                     if (data_size == 0) {
923                         /* no audio frame */
924                         ptr += ret;
925                         len -= ret;
926                         continue;
927                     }
928                     data_buf = (UINT8 *)samples;
929                     break;
930                 case CODEC_TYPE_VIDEO:
931                     if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
932                         int size;
933                         size = (ist->st->codec.width * ist->st->codec.height);
934                         avpicture_fill(&picture, ptr, 
935                                      ist->st->codec.pix_fmt,
936                                      ist->st->codec.width,
937                                      ist->st->codec.height);
938                         ret = len;
939                     } else {
940                         data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
941                         ret = avcodec_decode_video(&ist->st->codec, 
942                                                    &picture, &got_picture, ptr, len);
943                         if (ret < 0) {
944                         fail_decode:
945                             fprintf(stderr, "Error while decoding stream #%d.%d\n",
946                                     ist->file_index, ist->index);
947                             av_free_packet(&pkt);
948                             goto redo;
949                         }
950                         if (!got_picture) {
951                             /* no picture yet */
952                             ptr += ret;
953                             len -= ret;
954                             continue;
955                         }
956                     }
957                     break;
958                 default:
959                     goto fail_decode;
960                 }
961             } else {
962                 data_buf = ptr;
963                 data_size = len;
964                 ret = len;
965             }
966             /* update pts */
967             switch(ist->st->codec.codec_type) {
968             case CODEC_TYPE_AUDIO:
969                 ist->pts = (INT64)1000000 * ist->sample_index / ist->st->codec.sample_rate;
970                 ist->sample_index += data_size / (2 * ist->st->codec.channels);
971                 break;
972             case CODEC_TYPE_VIDEO:
973                 ist->frame_number++;
974                 ist->pts = ((INT64)ist->frame_number * 1000000 * FRAME_RATE_BASE) / 
975                     ist->st->codec.frame_rate;
976                 break;
977             }
978             ptr += ret;
979             len -= ret;
980
981             /* transcode raw format, encode packets and output them */
982             
983             for(i=0;i<nb_ostreams;i++) {
984                 int frame_size;
985                 ost = ost_table[i];
986                 if (ost->source_index == ist_index) {
987                     os = output_files[ost->file_index];
988
989                     if (ost->encoding_needed) {
990                         switch(ost->st->codec.codec_type) {
991                         case CODEC_TYPE_AUDIO:
992                             do_audio_out(os, ost, ist, data_buf, data_size);
993                             break;
994                         case CODEC_TYPE_VIDEO:
995                             do_video_out(os, ost, ist, &picture, &frame_size);
996                             if (do_vstats)
997                                 do_video_stats(ost, ist, frame_size);
998                             break;
999                         }
1000                     } else {
1001                         /* no reencoding needed : output the packet directly */
1002                         os->format->write_packet(os, ost->index, data_buf, data_size);
1003                     }
1004                 }
1005             }
1006         }
1007         av_free_packet(&pkt);
1008         
1009         /* dump report by using the first video and audio streams */
1010         {
1011             char buf[1024];
1012             AVFormatContext *oc;
1013             INT64 total_size, ti;
1014             AVCodecContext *enc;
1015             int frame_number, vid;
1016             double bitrate, ti1;
1017             static INT64 last_time;
1018
1019             if ((min_pts - last_time) >= 500000) {
1020                 last_time = min_pts;
1021                 
1022                 oc = output_files[0];
1023                 
1024                 total_size = url_ftell(&oc->pb);
1025                 
1026                 buf[0] = '\0';
1027                 ti = MAXINT64;
1028                 vid = 0;
1029                 for(i=0;i<nb_ostreams;i++) {
1030                     ost = ost_table[i];
1031                     enc = &ost->st->codec;
1032                     ist = ist_table[ost->source_index];
1033                     if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1034                         frame_number = ist->frame_number;
1035                         sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1036                                 frame_number, enc->quality);
1037                         if (do_psnr)
1038                             sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1039                         vid = 1;
1040                     }
1041                     /* compute min pts value */
1042                     if (!ist->discard && ist->pts < ti) {
1043                         ti = ist->pts;
1044                     }
1045                 }
1046
1047                 ti1 = (double)ti / 1000000.0;
1048                 if (ti1 < 0.01)
1049                     ti1 = 0.01;
1050                 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1051
1052                 sprintf(buf + strlen(buf), 
1053                         "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1054                         (double)total_size / 1024, ti1, bitrate);
1055                 
1056                 fprintf(stderr, "%s   \r", buf);
1057                 fflush(stderr);
1058             }
1059         }
1060     }
1061     term_exit();
1062
1063     /* dump report by using the first video and audio streams */
1064     {
1065         char buf[1024];
1066         AVFormatContext *oc;
1067         INT64 total_size, ti;
1068         AVCodecContext *enc;
1069         int frame_number, vid;
1070         double bitrate, ti1;
1071
1072         oc = output_files[0];
1073         
1074         total_size = url_ftell(&oc->pb);
1075         
1076         buf[0] = '\0';
1077         ti = MAXINT64;
1078         vid = 0;
1079         for(i=0;i<nb_ostreams;i++) {
1080             ost = ost_table[i];
1081             enc = &ost->st->codec;
1082             ist = ist_table[ost->source_index];
1083             if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
1084                 frame_number = ist->frame_number;
1085                 sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
1086                         frame_number, enc->quality);
1087                 if (do_psnr)
1088                     sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
1089                 vid = 1;
1090             }
1091             /* compute min pts value */
1092             if (!ist->discard && ist->pts < ti) {
1093                 ti = ist->pts;
1094             }
1095         }
1096         
1097         ti1 = ti / 1000000.0;
1098         if (ti1 < 0.01)
1099             ti1 = 0.01;
1100         bitrate = (double)(total_size * 8) / ti1 / 1000.0;
1101         
1102         sprintf(buf + strlen(buf), 
1103                 "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
1104                 (double)total_size / 1024, ti1, bitrate);
1105         
1106         fprintf(stderr, "%s   \n", buf);
1107     }
1108     /* close each encoder */
1109     for(i=0;i<nb_ostreams;i++) {
1110         ost = ost_table[i];
1111         if (ost->encoding_needed) {
1112             avcodec_close(&ost->st->codec);
1113         }
1114     }
1115     
1116     /* close each decoder */
1117     for(i=0;i<nb_istreams;i++) {
1118         ist = ist_table[i];
1119         if (ist->decoding_needed) {
1120             avcodec_close(&ist->st->codec);
1121         }
1122     }
1123     
1124
1125     /* write the trailer if needed and close file */
1126     for(i=0;i<nb_output_files;i++) {
1127         os = output_files[i];
1128         os->format->write_trailer(os);
1129     }
1130     /* finished ! */
1131     
1132     ret = 0;
1133  fail1:
1134     free(file_table);
1135
1136     if (ist_table) {
1137         for(i=0;i<nb_istreams;i++) {
1138             ist = ist_table[i];
1139             if (ist) {
1140                 free(ist);
1141             }
1142         }
1143         free(ist_table);
1144     }
1145     if (ost_table) {
1146         for(i=0;i<nb_ostreams;i++) {
1147             ost = ost_table[i];
1148             if (ost) {
1149                 if (ost->pict_tmp.data[0])
1150                     free(ost->pict_tmp.data[0]);
1151                 if (ost->video_resample)
1152                     img_resample_close(ost->img_resample_ctx);
1153                 if (ost->audio_resample)
1154                     audio_resample_close(ost->resample);
1155                 free(ost);
1156             }
1157         }
1158         free(ost_table);
1159     }
1160     return ret;
1161  fail:
1162     ret = -ENOMEM;
1163     goto fail1;
1164 }
1165
1166 #if 0
1167 int file_read(const char *filename)
1168 {
1169     URLContext *h;
1170     unsigned char buffer[1024];
1171     int len, i;
1172
1173     if (url_open(&h, filename, O_RDONLY) < 0) {
1174         printf("could not open '%s'\n", filename);
1175         return -1;
1176     }
1177     for(;;) {
1178         len = url_read(h, buffer, sizeof(buffer));
1179         if (len <= 0)
1180             break;
1181         for(i=0;i<len;i++) putchar(buffer[i]);
1182     }
1183     url_close(h);
1184     return 0;
1185 }
1186 #endif
1187
1188 void show_licence(void)
1189 {
1190     printf(
1191     "ffmpeg version " FFMPEG_VERSION "\n"
1192     "Copyright (c) 2000,2001 Gerard Lantau\n"
1193     "This program is free software; you can redistribute it and/or modify\n"
1194     "it under the terms of the GNU General Public License as published by\n"
1195     "the Free Software Foundation; either version 2 of the License, or\n"
1196     "(at your option) any later version.\n"
1197     "\n"
1198     "This program is distributed in the hope that it will be useful,\n"
1199     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
1200     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
1201     "GNU General Public License for more details.\n"
1202     "\n"
1203     "You should have received a copy of the GNU General Public License\n"
1204     "along with this program; if not, write to the Free Software\n"
1205     "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n"
1206     );
1207     exit(1);
1208 }
1209
1210 void opt_format(const char *arg)
1211 {
1212     AVFormat *f;
1213     f = first_format;
1214     while (f != NULL && strcmp(f->name, arg) != 0) f = f->next;
1215     if (f == NULL) {
1216         fprintf(stderr, "Invalid format: %s\n", arg);
1217         exit(1);
1218     }
1219     file_format = f;
1220 }
1221
1222 void opt_video_bitrate(const char *arg)
1223 {
1224     video_bit_rate = atoi(arg) * 1000;
1225 }
1226
1227 void opt_video_bitrate_tolerance(const char *arg)
1228 {
1229     video_bit_rate_tolerance = atoi(arg) * 1000;
1230 }
1231
1232 void opt_frame_rate(const char *arg)
1233 {
1234     frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
1235 }
1236
1237 void opt_frame_size(const char *arg)
1238 {
1239     parse_image_size(&frame_width, &frame_height, arg);
1240     if (frame_width <= 0 || frame_height <= 0) {
1241         fprintf(stderr, "Incorrect frame size\n");
1242         exit(1);
1243     }
1244     if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
1245         fprintf(stderr, "Frame size must be a multiple of 2\n");
1246         exit(1);
1247     }
1248 }
1249
1250 void opt_gop_size(const char *arg)
1251 {
1252     gop_size = atoi(arg);
1253 }
1254
1255 void opt_qscale(const char *arg)
1256 {
1257     video_qscale = atoi(arg);
1258     if (video_qscale < 0 ||
1259         video_qscale > 31) {
1260         fprintf(stderr, "qscale must be >= 1 and <= 31\n");
1261         exit(1);
1262     }
1263 }
1264
1265 void opt_qmin(const char *arg)
1266 {
1267     video_qmin = atoi(arg);
1268     if (video_qmin < 0 ||
1269         video_qmin > 31) {
1270         fprintf(stderr, "qmin must be >= 1 and <= 31\n");
1271         exit(1);
1272     }
1273 }
1274
1275 void opt_qmax(const char *arg)
1276 {
1277     video_qmax = atoi(arg);
1278     if (video_qmax < 0 ||
1279         video_qmax > 31) {
1280         fprintf(stderr, "qmax must be >= 1 and <= 31\n");
1281         exit(1);
1282     }
1283 }
1284
1285 void opt_qdiff(const char *arg)
1286 {
1287     video_qdiff = atoi(arg);
1288     if (video_qdiff < 0 ||
1289         video_qdiff > 31) {
1290         fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
1291         exit(1);
1292     }
1293 }
1294
1295 void opt_qblur(const char *arg)
1296 {
1297     video_qblur = atof(arg);
1298 }
1299
1300 void opt_qcomp(const char *arg)
1301 {
1302     video_qcomp = atof(arg);
1303 }
1304
1305 void opt_audio_bitrate(const char *arg)
1306 {
1307     audio_bit_rate = atoi(arg) * 1000;
1308 }
1309
1310 void opt_audio_rate(const char *arg)
1311 {
1312     audio_sample_rate = atoi(arg);
1313 }
1314
1315 void opt_audio_channels(const char *arg)
1316 {
1317     audio_channels = atoi(arg);
1318 }
1319
1320 #ifdef CONFIG_GRAB
1321 void opt_video_device(const char *arg)
1322 {
1323     v4l_device = strdup(arg);
1324 }
1325
1326 void opt_audio_device(const char *arg)
1327 {
1328     audio_device = strdup(arg);
1329 }
1330 #endif
1331
1332 void opt_audio_codec(const char *arg)
1333 {
1334     AVCodec *p;
1335
1336     p = first_avcodec;
1337     while (p) {
1338         if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
1339             break;
1340         p = p->next;
1341     }
1342     if (p == NULL) {
1343         fprintf(stderr, "Unknown audio codec '%s'\n", arg);
1344         exit(1);
1345     } else {
1346         audio_codec_id = p->id;
1347     }
1348 }
1349
1350 const char *motion_str[] = {
1351     "zero",
1352     "full",
1353     "log",
1354     "phods",
1355     "epzs",
1356     "x1",
1357     NULL,
1358 };
1359
1360 void opt_motion_estimation(const char *arg)
1361 {
1362     const char **p;
1363     p = motion_str;
1364     for(;;) {
1365         if (!*p) {
1366             fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
1367             exit(1);
1368         }
1369         if (!strcmp(*p, arg))
1370             break;
1371         p++;
1372     }
1373     motion_estimation_method = p - motion_str;
1374 }
1375
1376 void opt_video_codec(const char *arg)
1377 {
1378     AVCodec *p;
1379
1380     p = first_avcodec;
1381     while (p) {
1382         if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
1383             break;
1384         p = p->next;
1385     }
1386     if (p == NULL) {
1387         fprintf(stderr, "Unknown video codec '%s'\n", arg);
1388         exit(1);
1389     } else {
1390         video_codec_id = p->id;
1391     }
1392 }
1393
1394 void opt_map(const char *arg)
1395 {
1396     AVStreamMap *m;
1397     const char *p;
1398
1399     p = arg;
1400     m = &stream_maps[nb_stream_maps++];
1401
1402     m->file_index = strtol(arg, (char **)&p, 0);
1403     if (*p)
1404         p++;
1405     m->stream_index = strtol(arg, (char **)&p, 0);
1406 }
1407
1408 void opt_recording_time(const char *arg)
1409 {
1410     recording_time = parse_date(arg, 1);
1411 }
1412
1413 /* return the number of packet read to find the codec parameters */
1414 int find_codec_parameters(AVFormatContext *ic)
1415 {
1416     int val, i, count, ret, got_picture, size;
1417     AVCodec *codec;
1418     AVCodecContext *enc;
1419     AVStream *st;
1420     AVPacket *pkt;
1421     AVPicture picture;
1422     AVPacketList *pktl, **ppktl;
1423     short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
1424     UINT8 *ptr;
1425
1426     count = 0;
1427     ppktl = &ic->packet_buffer;
1428     for(;;) {
1429         for(i=0;i<ic->nb_streams;i++) {
1430             enc = &ic->streams[i]->codec;
1431             
1432             switch(enc->codec_type) {
1433             case CODEC_TYPE_AUDIO:
1434                 val = enc->sample_rate;
1435                 break;
1436             case CODEC_TYPE_VIDEO:
1437                 val = enc->width;
1438                 break;
1439             default:
1440                 val = 1;
1441                 break;
1442             }
1443             /* if no parameters supplied, then we should read it from
1444                the stream */
1445             if (val == 0)
1446                 break;
1447         }
1448         if (i == ic->nb_streams) {
1449             ret = count;
1450             break;
1451         }
1452
1453         if (count == 0) {
1454             /* open each codec */
1455             for(i=0;i<ic->nb_streams;i++) {
1456                 st = ic->streams[i];
1457                 codec = avcodec_find_decoder(st->codec.codec_id);
1458                 if (codec == NULL) {
1459                     ret = -1;
1460                     goto the_end;
1461                 }
1462                 avcodec_open(&st->codec, codec);
1463             }
1464         }
1465         pktl = av_mallocz(sizeof(AVPacketList));
1466         if (!pktl) {
1467             ret = -1;
1468             break;
1469         }
1470
1471         /* add the packet in the buffered packet list */
1472         *ppktl = pktl;
1473         ppktl = &pktl->next;
1474
1475         pkt = &pktl->pkt;
1476         if (ic->format->read_packet(ic, pkt) < 0) {
1477             ret = -1;
1478             break;
1479         }
1480         st = ic->streams[pkt->stream_index];
1481
1482         /* decode the data and update codec parameters */
1483         ptr = pkt->data;
1484         size = pkt->size;
1485         while (size > 0) {
1486             switch(st->codec.codec_type) {
1487             case CODEC_TYPE_VIDEO:
1488                 ret = avcodec_decode_video(&st->codec, &picture, &got_picture, ptr, size);
1489                 break;
1490             case CODEC_TYPE_AUDIO:
1491                 ret = avcodec_decode_audio(&st->codec, samples, &got_picture, ptr, size);
1492                 break;
1493             default:
1494                 ret = -1;
1495                 break;
1496             }
1497             if (ret < 0) {
1498                 ret = -1;
1499                 goto the_end;
1500             }
1501             if (got_picture)
1502                 break;
1503             ptr += ret;
1504             size -= ret;
1505         }
1506
1507         count++;
1508     }
1509  the_end:
1510     if (count > 0) {
1511         /* close each codec */
1512         for(i=0;i<ic->nb_streams;i++) {
1513             st = ic->streams[i];
1514             avcodec_close(&st->codec);
1515         }
1516     }
1517     return ret;
1518 }
1519
1520 int filename_number_test(const char *filename)
1521 {
1522     char buf[1024];
1523
1524     if (get_frame_filename(buf, sizeof(buf), filename, 1) < 0) {
1525         fprintf(stderr, "%s: Incorrect image filename syntax.\n"
1526                 "Use '%%d' to specify the image number:\n"
1527                 "  for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
1528                 "  for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n", 
1529                 filename);
1530         return -1;
1531     } else {
1532         return 0;
1533     }
1534 }
1535
1536 void opt_input_file(const char *filename)
1537 {
1538     AVFormatContext *ic;
1539     AVFormatParameters params, *ap = &params;
1540     URLFormat url_format;
1541     AVFormat *fmt;
1542     int err, i, ret;
1543
1544     ic = av_mallocz(sizeof(AVFormatContext));
1545     strcpy(ic->filename, filename);
1546     /* first format guess to know if we must open file */
1547     fmt = file_format;
1548     if (!fmt) 
1549         fmt = guess_format(NULL, filename, NULL);
1550     
1551     if (fmt == NULL || !(fmt->flags & AVFMT_NOFILE)) {
1552         /* open file */
1553         if (url_fopen(&ic->pb, filename, URL_RDONLY) < 0) {
1554             fprintf(stderr, "Could not open '%s'\n", filename);
1555             exit(1);
1556         }
1557     
1558         /* find format and set default parameters */
1559         fmt = file_format;
1560         err = url_getformat(url_fileno(&ic->pb), &url_format);
1561         if (err >= 0) {
1562             if (!fmt)
1563                 fmt = guess_format(url_format.format_name, NULL, NULL);
1564             ap->sample_rate = url_format.sample_rate;
1565             ap->frame_rate = url_format.frame_rate;
1566             ap->channels = url_format.channels;
1567             ap->width = url_format.width;
1568             ap->height = url_format.height;
1569             ap->pix_fmt = url_format.pix_fmt;
1570         } else {
1571             if (!fmt)
1572                 fmt = guess_format(NULL, filename, NULL);
1573             memset(ap, 0, sizeof(*ap));
1574         }
1575     } else {
1576         memset(ap, 0, sizeof(*ap));
1577     }
1578
1579     if (!fmt || !fmt->read_header) {
1580         fprintf(stderr, "%s: Unknown file format\n", filename);
1581         exit(1);
1582     }
1583     ic->format = fmt;
1584
1585     /* get default parameters from command line */
1586     if (!ap->sample_rate)
1587         ap->sample_rate = audio_sample_rate;
1588     if (!ap->channels)
1589         ap->channels = audio_channels;
1590
1591     if (!ap->frame_rate)
1592         ap->frame_rate = frame_rate;
1593     if (!ap->width)
1594         ap->width = frame_width;
1595     if (!ap->height)
1596         ap->height = frame_height;
1597
1598     /* check filename in case of an image number is expected */
1599     if (ic->format->flags & AVFMT_NEEDNUMBER) {
1600         if (filename_number_test(ic->filename) < 0)
1601             exit(1);
1602     }
1603     
1604     err = ic->format->read_header(ic, ap);
1605     if (err < 0) {
1606         fprintf(stderr, "%s: Error while parsing header\n", filename);
1607         exit(1);
1608     }
1609     
1610     /* If not enough info for the codecs, we decode the first frames
1611        to get it. (used in mpeg case for example) */
1612     ret = find_codec_parameters(ic);
1613     if (ret < 0) {
1614         fprintf(stderr, "%s: could not find codec parameters\n", filename);
1615         exit(1);
1616     }
1617
1618     /* update the current parameters so that they match the one of the input stream */
1619     for(i=0;i<ic->nb_streams;i++) {
1620         AVCodecContext *enc = &ic->streams[i]->codec;
1621         switch(enc->codec_type) {
1622         case CODEC_TYPE_AUDIO:
1623             audio_channels = enc->channels;
1624             audio_sample_rate = enc->sample_rate;
1625             break;
1626         case CODEC_TYPE_VIDEO:
1627             frame_height = enc->height;
1628             frame_width = enc->width;
1629             frame_rate = enc->frame_rate;
1630             break;
1631         }
1632     }
1633     
1634     input_files[nb_input_files] = ic;
1635     /* dump the file content */
1636     dump_format(ic, nb_input_files, filename, 0);
1637     nb_input_files++;
1638     file_format = NULL;
1639 }
1640
1641 void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
1642 {
1643     int has_video, has_audio, i, j;
1644     AVFormatContext *ic;
1645
1646     has_video = 0;
1647     has_audio = 0;
1648     for(j=0;j<nb_input_files;j++) {
1649         ic = input_files[j];
1650         for(i=0;i<ic->nb_streams;i++) {
1651             AVCodecContext *enc = &ic->streams[i]->codec;
1652             switch(enc->codec_type) {
1653             case CODEC_TYPE_AUDIO:
1654                 has_audio = 1;
1655                 break;
1656             case CODEC_TYPE_VIDEO:
1657                 has_video = 1;
1658                 break;
1659             }
1660         }
1661     }
1662     *has_video_ptr = has_video;
1663     *has_audio_ptr = has_audio;
1664 }
1665
1666 void opt_output_file(const char *filename)
1667 {
1668     AVStream *st;
1669     AVFormatContext *oc;
1670     int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
1671     int codec_id;
1672
1673     if (!strcmp(filename, "-"))
1674         filename = "pipe:";
1675
1676     oc = av_mallocz(sizeof(AVFormatContext));
1677
1678     if (!file_format) {
1679         file_format = guess_format(NULL, filename, NULL);
1680         if (!file_format)
1681             file_format = &mpeg_mux_format;
1682     }
1683     
1684     oc->format = file_format;
1685
1686     if (!strcmp(file_format->name, "ffm") && 
1687         strstart(filename, "http:", NULL)) {
1688         /* special case for files sent to ffserver: we get the stream
1689            parameters from ffserver */
1690         if (read_ffserver_streams(oc, filename) < 0) {
1691             fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
1692             exit(1);
1693         }
1694     } else {
1695         use_video = file_format->video_codec != CODEC_ID_NONE;
1696         use_audio = file_format->audio_codec != CODEC_ID_NONE;
1697
1698         /* disable if no corresponding type found and at least one
1699            input file */
1700         if (nb_input_files > 0) {
1701             check_audio_video_inputs(&input_has_video, &input_has_audio);
1702             if (!input_has_video)
1703                 use_video = 0;
1704             if (!input_has_audio)
1705                 use_audio = 0;
1706         }
1707
1708         /* manual disable */
1709         if (audio_disable) {
1710             use_audio = 0;
1711         }
1712         if (video_disable) {
1713             use_video = 0;
1714         }
1715         
1716         nb_streams = 0;
1717         if (use_video) {
1718             AVCodecContext *video_enc;
1719             
1720             st = av_mallocz(sizeof(AVStream));
1721             if (!st) {
1722                 fprintf(stderr, "Could not alloc stream\n");
1723                 exit(1);
1724             }
1725             video_enc = &st->codec;
1726
1727             codec_id = file_format->video_codec;
1728             if (video_codec_id != CODEC_ID_NONE)
1729                 codec_id = video_codec_id;
1730
1731             video_enc->codec_id = codec_id;
1732             video_enc->codec_type = CODEC_TYPE_VIDEO;
1733             
1734             video_enc->bit_rate = video_bit_rate;
1735             video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
1736             video_enc->frame_rate = frame_rate; 
1737             
1738             video_enc->width = frame_width;
1739             video_enc->height = frame_height;
1740             if (!intra_only)
1741                 video_enc->gop_size = gop_size;
1742             else
1743                 video_enc->gop_size = 0;
1744             if (video_qscale || same_quality) {
1745                 video_enc->flags |= CODEC_FLAG_QSCALE;
1746                 video_enc->quality = video_qscale;
1747             }
1748             
1749             video_enc->qmin= video_qmin;
1750             video_enc->qmax= video_qmax;
1751             video_enc->max_qdiff= video_qdiff;
1752             video_enc->qblur= video_qblur;
1753             video_enc->qcompress= video_qcomp;
1754             
1755             if (do_psnr)
1756                 video_enc->get_psnr = 1;
1757             else
1758                 video_enc->get_psnr = 0;
1759             /* XXX: need to find a way to set codec parameters */
1760             if (oc->format == &ppm_format ||
1761                 oc->format == &ppmpipe_format) {
1762                 video_enc->pix_fmt = PIX_FMT_RGB24;
1763             }
1764
1765             oc->streams[nb_streams] = st;
1766             nb_streams++;
1767         }
1768     
1769         if (use_audio) {
1770             AVCodecContext *audio_enc;
1771
1772             st = av_mallocz(sizeof(AVStream));
1773             if (!st) {
1774                 fprintf(stderr, "Could not alloc stream\n");
1775                 exit(1);
1776             }
1777             audio_enc = &st->codec;
1778             codec_id = file_format->audio_codec;
1779             if (audio_codec_id != CODEC_ID_NONE)
1780                 codec_id = audio_codec_id;
1781             audio_enc->codec_id = codec_id;
1782             audio_enc->codec_type = CODEC_TYPE_AUDIO;
1783             
1784             audio_enc->bit_rate = audio_bit_rate;
1785             audio_enc->sample_rate = audio_sample_rate;
1786             audio_enc->channels = audio_channels;
1787             oc->streams[nb_streams] = st;
1788             nb_streams++;
1789         }
1790
1791         oc->nb_streams = nb_streams;
1792
1793         if (!nb_streams) {
1794             fprintf(stderr, "No audio or video streams available\n");
1795             exit(1);
1796         }
1797
1798         if (str_title)
1799             nstrcpy(oc->title, sizeof(oc->title), str_title);
1800         if (str_author)
1801             nstrcpy(oc->author, sizeof(oc->author), str_author);
1802         if (str_copyright)
1803             nstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
1804         if (str_comment)
1805             nstrcpy(oc->comment, sizeof(oc->comment), str_comment);
1806     }
1807
1808     output_files[nb_output_files] = oc;
1809     /* dump the file content */
1810     dump_format(oc, nb_output_files, filename, 1);
1811     nb_output_files++;
1812
1813     strcpy(oc->filename, filename);
1814
1815     /* check filename in case of an image number is expected */
1816     if (oc->format->flags & AVFMT_NEEDNUMBER) {
1817         if (filename_number_test(oc->filename) < 0)
1818             exit(1);
1819     }
1820
1821     if (!(oc->format->flags & AVFMT_NOFILE)) {
1822         /* test if it already exists to avoid loosing precious files */
1823         if (!file_overwrite && 
1824             (strchr(filename, ':') == NULL ||
1825              strstart(filename, "file:", NULL))) {
1826             if (url_exist(filename)) {
1827                 int c;
1828                 
1829                 printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
1830                 fflush(stdout);
1831                 c = getchar();
1832                 if (toupper(c) != 'Y') {
1833                     fprintf(stderr, "Not overwriting - exiting\n");
1834                     exit(1);
1835                 }
1836             }
1837         }
1838         
1839         /* open the file */
1840         if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
1841             fprintf(stderr, "Could not open '%s'\n", filename);
1842             exit(1);
1843         }
1844     }
1845
1846     /* reset some options */
1847     file_format = NULL;
1848     audio_disable = 0;
1849     video_disable = 0;
1850     audio_codec_id = CODEC_ID_NONE;
1851     video_codec_id = CODEC_ID_NONE;
1852 }
1853
1854 #ifdef CONFIG_GRAB
1855
1856 /* prepare dummy protocols for grab */
1857 void prepare_grab(void)
1858 {
1859     int has_video, has_audio, i, j;
1860     AVFormatContext *oc;
1861     AVFormatContext *ic;
1862     AVFormatParameters ap1, *ap = &ap1;
1863
1864     /* see if audio/video inputs are needed */
1865     has_video = 0;
1866     has_audio = 0;
1867     memset(ap, 0, sizeof(*ap));
1868     for(j=0;j<nb_output_files;j++) {
1869         oc = output_files[j];
1870         for(i=0;i<oc->nb_streams;i++) {
1871             AVCodecContext *enc = &oc->streams[i]->codec;
1872             switch(enc->codec_type) {
1873             case CODEC_TYPE_AUDIO:
1874                 if (enc->sample_rate > ap->sample_rate)
1875                     ap->sample_rate = enc->sample_rate;
1876                 if (enc->channels > ap->channels)
1877                     ap->channels = enc->channels;
1878                 has_audio = 1;
1879                 break;
1880             case CODEC_TYPE_VIDEO:
1881                 if (enc->width > ap->width)
1882                     ap->width = enc->width;
1883                 if (enc->height > ap->height)
1884                     ap->height = enc->height;
1885                 if (enc->frame_rate > ap->frame_rate)
1886                     ap->frame_rate = enc->frame_rate;
1887                 has_video = 1;
1888                 break;
1889             }
1890         }
1891     }
1892     
1893     if (has_video == 0 && has_audio == 0) {
1894         fprintf(stderr, "Output file must have at least one audio or video stream\n");
1895         exit(1);
1896     }
1897     
1898     if (has_video) {
1899         ic = av_open_input_file("", "video_grab_device", 0, ap);
1900         if (!ic) {
1901             fprintf(stderr, "Could not open video grab device\n");
1902             exit(1);
1903         }
1904         input_files[nb_input_files] = ic;
1905         dump_format(ic, nb_input_files, v4l_device, 0);
1906         nb_input_files++;
1907     }
1908     if (has_audio) {
1909         ic = av_open_input_file("", "audio_device", 0, ap);
1910         if (!ic) {
1911             fprintf(stderr, "Could not open audio grab device\n");
1912             exit(1);
1913         }
1914         input_files[nb_input_files] = ic;
1915         dump_format(ic, nb_input_files, audio_device, 0);
1916         nb_input_files++;
1917     }
1918 }
1919
1920 #else
1921
1922 void prepare_grab(void)
1923 {
1924     fprintf(stderr, "Must supply at least one input file\n");
1925     exit(1);
1926 }
1927
1928 #endif
1929
1930 /* open the necessary output devices for playing */
1931 void prepare_play(void)
1932 {
1933 #ifndef __BEOS__
1934     file_format = guess_format("audio_device", NULL, NULL);
1935     if (!file_format) {
1936         fprintf(stderr, "Could not find audio device\n");
1937         exit(1);
1938     }
1939     
1940     opt_output_file(audio_device);
1941 #endif
1942 }
1943
1944
1945 #ifndef CONFIG_WIN32
1946 INT64 getutime(void)
1947 {
1948     struct rusage rusage;
1949
1950     getrusage(RUSAGE_SELF, &rusage);
1951     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
1952 }
1953 #else
1954 INT64 getutime(void)
1955 {
1956   return gettime();
1957 }
1958 #endif
1959
1960 void show_formats(void)
1961 {
1962     AVFormat *f;
1963     URLProtocol *up;
1964     AVCodec *p;
1965     const char **pp;
1966
1967     printf("File formats:\n");
1968     printf("  Encoding:");
1969     for(f = first_format; f != NULL; f = f->next) {
1970         if (f->write_header)
1971             printf(" %s", f->name);
1972     }
1973     printf("\n");
1974     printf("  Decoding:");
1975     for(f = first_format; f != NULL; f = f->next) {
1976         if (f->read_header)
1977             printf(" %s", f->name);
1978     }
1979     printf("\n");
1980
1981     printf("Codecs:\n");
1982     printf("  Encoders:");
1983     for(p = first_avcodec; p != NULL; p = p->next) {
1984         if (p->encode)
1985             printf(" %s", p->name);
1986     }
1987     printf("\n");
1988
1989     printf("  Decoders:");
1990     for(p = first_avcodec; p != NULL; p = p->next) {
1991         if (p->decode)
1992             printf(" %s", p->name);
1993     }
1994     printf("\n");
1995
1996     printf("Supported file protocols:");
1997     for(up = first_protocol; up != NULL; up = up->next)
1998         printf(" %s:", up->name);
1999     printf("\n");
2000     
2001     printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
2002     printf("Motion estimation methods:");
2003     pp = motion_str;
2004     while (*pp) {
2005         printf(" %s", *pp);
2006         if ((pp - motion_str) == ME_ZERO) 
2007             printf("(fastest)");
2008         else if ((pp - motion_str) == ME_FULL) 
2009             printf("(slowest)");
2010         else if ((pp - motion_str) == ME_LOG) 
2011             printf("(default)");
2012         pp++;
2013     }
2014     printf("\n");
2015     exit(1);
2016 }
2017
2018 void show_help(void)
2019 {
2020     const char *prog;
2021     const OptionDef *po;
2022     int i, expert;
2023     
2024     prog = do_play ? "ffplay" : "ffmpeg";
2025
2026     printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001 Gerard Lantau\n", 
2027            prog);
2028     
2029     if (!do_play) {
2030         printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
2031                "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
2032     } else {
2033         printf("usage: ffplay [options] input_file...\n"
2034                "Simple audio player\n");
2035     }
2036            
2037     printf("\n"
2038            "Main options are:\n");
2039     for(i=0;i<2;i++) {
2040         if (i == 1)
2041             printf("\nAdvanced options are:\n");
2042         for(po = options; po->name != NULL; po++) {
2043             char buf[64];
2044             expert = (po->flags & OPT_EXPERT) != 0;
2045             if (expert == i) {
2046                 strcpy(buf, po->name);
2047                 if (po->flags & HAS_ARG) {
2048                     strcat(buf, " ");
2049                     strcat(buf, po->argname);
2050                 }
2051                 printf("-%-17s  %s\n", buf, po->help);
2052             }
2053         }
2054     }
2055
2056     exit(1);
2057 }
2058
2059 const OptionDef options[] = {
2060     { "L", 0, {(void*)show_licence}, "show license" },
2061     { "h", 0, {(void*)show_help}, "show help" },
2062     { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
2063     { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
2064     { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
2065     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
2066     { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
2067     { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
2068     { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
2069     { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
2070     { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
2071     { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
2072     /* video options */
2073     { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
2074     { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
2075     { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
2076     { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
2077     { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
2078     { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
2079     { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
2080     { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
2081     { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
2082     { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
2083     { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
2084     { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
2085     { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
2086 #ifdef CONFIG_GRAB
2087     { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video device", "device" },
2088 #endif
2089     { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec", "codec" },
2090     { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method", 
2091       "method" },
2092     { "sameq", OPT_BOOL, {(void*)&same_quality}, 
2093       "use same video quality as source (implies VBR)" },
2094     /* audio options */
2095     { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
2096     { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
2097     { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
2098     { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
2099 #ifdef CONFIG_GRAB
2100     { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
2101 #endif
2102     { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec", "codec" },
2103     { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace}, 
2104       "deinterlace pictures" },
2105     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark}, 
2106       "add timings for benchmarking" },
2107     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump}, 
2108       "dump each input packet" },
2109     { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
2110     { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" }, 
2111
2112     { NULL, },
2113 };
2114
2115 int main(int argc, char **argv)
2116 {
2117     int optindex, i;
2118     const char *opt, *arg;
2119     const OptionDef *po;
2120     INT64 ti;
2121     
2122     register_all();
2123
2124     /* detect if invoked as player */
2125     i = strlen(argv[0]);
2126     if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
2127         do_play = 1;
2128
2129     if (argc <= 1)
2130         show_help();
2131     
2132     /* parse options */
2133     optindex = 1;
2134     while (optindex < argc) {
2135         opt = argv[optindex++];
2136         
2137         if (opt[0] == '-' && opt[1] != '\0') {
2138             po = options;
2139             while (po->name != NULL) {
2140                 if (!strcmp(opt + 1, po->name))
2141                     break;
2142                 po++;
2143             }
2144             if (!po->name) {
2145                 fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
2146                 exit(1);
2147             }
2148             arg = NULL;
2149             if (po->flags & HAS_ARG)
2150                 arg = argv[optindex++];
2151             if (po->flags & OPT_STRING) {
2152                 char *str;
2153                 str = strdup(arg);
2154                 *po->u.str_arg = str;
2155             } else if (po->flags & OPT_BOOL) {
2156                 *po->u.int_arg = 1;
2157             } else {
2158                 po->u.func_arg(arg);
2159             }
2160         } else {
2161             if (!do_play) {
2162                 opt_output_file(opt);
2163             } else {
2164                 opt_input_file(opt);
2165             }
2166         }
2167     }
2168
2169
2170     if (!do_play) {
2171         /* file converter / grab */
2172         if (nb_output_files <= 0) {
2173             fprintf(stderr, "Must supply at least one output file\n");
2174             exit(1);
2175         }
2176         
2177         if (nb_input_files == 0) {
2178             prepare_grab();
2179         }
2180     } else {
2181         /* player */
2182         if (nb_input_files <= 0) {
2183             fprintf(stderr, "Must supply at least one input file\n");
2184             exit(1);
2185         }
2186         prepare_play();
2187     }
2188
2189     ti = getutime();
2190     av_encode(output_files, nb_output_files, input_files, nb_input_files, 
2191               stream_maps, nb_stream_maps);
2192     ti = getutime() - ti;
2193     if (do_benchmark) {
2194         printf("bench: utime=%0.3fs\n", ti / 1000000.0);
2195     }
2196
2197     /* close files */
2198     for(i=0;i<nb_output_files;i++) {
2199         if (!(output_files[i]->format->flags & AVFMT_NOFILE)) 
2200             url_fclose(&output_files[i]->pb);
2201     }
2202     for(i=0;i<nb_input_files;i++) {
2203         if (!(input_files[i]->format->flags & AVFMT_NOFILE)) 
2204             url_fclose(&input_files[i]->pb);
2205     }
2206
2207     return 0;
2208 }