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