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