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