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