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