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