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