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