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