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