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