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