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