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