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