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