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