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