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