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