• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files

hvirtual/quicktime/ffmpeg/ffmpeg.c

Go to the documentation of this file.
00001 /*
00002  * FFmpeg main 
00003  * Copyright (c) 2000-2003 Fabrice Bellard
00004  *
00005  * This library is free software; you can redistribute it and/or
00006  * modify it under the terms of the GNU Lesser General Public
00007  * License as published by the Free Software Foundation; either
00008  * version 2 of the License, or (at your option) any later version.
00009  *
00010  * This library is distributed in the hope that it will be useful,
00011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013  * Lesser General Public License for more details.
00014  *
00015  * You should have received a copy of the GNU Lesser General Public
00016  * License along with this library; if not, write to the Free Software
00017  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00018  */
00019 #define HAVE_AV_CONFIG_H
00020 #include <limits.h>
00021 #include "avformat.h"
00022 #include "framehook.h"
00023 #include "dsputil.h"
00024 
00025 #ifndef CONFIG_WIN32
00026 #include <unistd.h>
00027 #include <fcntl.h>
00028 #include <sys/ioctl.h>
00029 #include <sys/time.h>
00030 #include <termios.h>
00031 #include <sys/resource.h>
00032 #include <signal.h>
00033 #endif
00034 #ifdef CONFIG_OS2
00035 #include <sys/types.h>
00036 #include <sys/select.h>
00037 #include <stdlib.h>
00038 #endif
00039 #undef time //needed because HAVE_AV_CONFIG_H is defined on top
00040 #include <time.h>
00041 
00042 #include "cmdutils.h"
00043 
00044 #undef NDEBUG
00045 #include <assert.h>
00046 
00047 #if !defined(INFINITY) && defined(HUGE_VAL)
00048 #define INFINITY HUGE_VAL
00049 #endif
00050 
00051 /* select an input stream for an output stream */
00052 typedef struct AVStreamMap {
00053     int file_index;
00054     int stream_index;
00055     int sync_file_index;
00056     int sync_stream_index;
00057 } AVStreamMap;
00058 
00060 typedef struct AVMetaDataMap {
00061     int out_file;
00062     int in_file;
00063 } AVMetaDataMap;
00064 
00065 extern const OptionDef options[];
00066 
00067 static void show_help(void);
00068 static void show_license(void);
00069 
00070 #define MAX_FILES 20
00071 
00072 static AVFormatContext *input_files[MAX_FILES];
00073 static int64_t input_files_ts_offset[MAX_FILES];
00074 static int nb_input_files = 0;
00075 
00076 static AVFormatContext *output_files[MAX_FILES];
00077 static int nb_output_files = 0;
00078 
00079 static AVStreamMap stream_maps[MAX_FILES];
00080 static int nb_stream_maps;
00081 
00082 static AVMetaDataMap meta_data_maps[MAX_FILES];
00083 static int nb_meta_data_maps;
00084 
00085 static AVInputFormat *file_iformat;
00086 static AVOutputFormat *file_oformat;
00087 static AVImageFormat *image_format;
00088 static int frame_width  = 0;
00089 static int frame_height = 0;
00090 static float frame_aspect_ratio = 0;
00091 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
00092 static int frame_padtop  = 0;
00093 static int frame_padbottom = 0;
00094 static int frame_padleft  = 0;
00095 static int frame_padright = 0;
00096 static int padcolor[3] = {16,128,128}; /* default to black */
00097 static int frame_topBand  = 0;
00098 static int frame_bottomBand = 0;
00099 static int frame_leftBand  = 0;
00100 static int frame_rightBand = 0;
00101 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
00102 static int frame_rate = 25;
00103 static int frame_rate_base = 1;
00104 static int video_bit_rate = 200*1000;
00105 static int video_bit_rate_tolerance = 4000*1000;
00106 static float video_qscale = 0;
00107 static int video_qmin = 2;
00108 static int video_qmax = 31;
00109 static int video_lmin = 2*FF_QP2LAMBDA;
00110 static int video_lmax = 31*FF_QP2LAMBDA;
00111 static int video_mb_lmin = 2*FF_QP2LAMBDA;
00112 static int video_mb_lmax = 31*FF_QP2LAMBDA;
00113 static int video_qdiff = 3;
00114 static int video_lelim = 0;
00115 static int video_celim = 0;
00116 static float video_qblur = 0.5;
00117 static float video_qsquish = 0.0;
00118 static float video_qcomp = 0.5;
00119 static uint16_t *intra_matrix = NULL;
00120 static uint16_t *inter_matrix = NULL;
00121 #if 0 //experimental, (can be removed)
00122 static float video_rc_qsquish=1.0;
00123 static float video_rc_qmod_amp=0;
00124 static int video_rc_qmod_freq=0;
00125 #endif
00126 static char *video_rc_override_string=NULL;
00127 static char *video_rc_eq="tex^qComp";
00128 static int video_rc_buffer_size=0;
00129 static float video_rc_buffer_aggressivity=1.0;
00130 static int video_rc_max_rate=0;
00131 static int video_rc_min_rate=0;
00132 static float video_rc_initial_cplx=0;
00133 static float video_b_qfactor = 1.25;
00134 static float video_b_qoffset = 1.25;
00135 static float video_i_qfactor = -0.8;
00136 static float video_i_qoffset = 0.0;
00137 static int video_intra_quant_bias= FF_DEFAULT_QUANT_BIAS;
00138 static int video_inter_quant_bias= FF_DEFAULT_QUANT_BIAS;
00139 static int me_method = ME_EPZS;
00140 static int video_disable = 0;
00141 static int video_discard = 0;
00142 static int video_codec_id = CODEC_ID_NONE;
00143 static int video_codec_tag = 0;
00144 static int same_quality = 0;
00145 static int b_frames = 0;
00146 static int b_strategy = 0;
00147 static int mb_decision = FF_MB_DECISION_SIMPLE;
00148 static int ildct_cmp = FF_CMP_VSAD;
00149 static int mb_cmp = FF_CMP_SAD;
00150 static int sub_cmp = FF_CMP_SAD;
00151 static int cmp = FF_CMP_SAD;
00152 static int pre_cmp = FF_CMP_SAD;
00153 static int pre_me = 0;
00154 static float lumi_mask = 0;
00155 static float dark_mask = 0;
00156 static float scplx_mask = 0;
00157 static float tcplx_mask = 0;
00158 static float p_mask = 0;
00159 static int use_4mv = 0;
00160 static int use_obmc = 0;
00161 static int use_loop = 0;
00162 static int use_aic = 0;
00163 static int use_aiv = 0;
00164 static int use_umv = 0;
00165 static int use_ss = 0;
00166 static int use_alt_scan = 0;
00167 static int use_trell = 0;
00168 static int use_scan_offset = 0;
00169 static int use_qpel = 0;
00170 static int use_qprd = 0;
00171 static int use_cbprd = 0;
00172 static int use_mv0 = 0;
00173 static int do_normalize_aqp = 0;
00174 static int qns = 0;
00175 static int closed_gop = 0;
00176 static int strict_gop = 0;
00177 static int no_output = 0;
00178 static int do_deinterlace = 0;
00179 static int do_interlace_dct = 0;
00180 static int do_interlace_me = 0;
00181 static int workaround_bugs = FF_BUG_AUTODETECT;
00182 static int error_resilience = FF_ER_CAREFUL;
00183 static int error_concealment = 3;
00184 static int dct_algo = 0;
00185 static int idct_algo = 0;
00186 static int use_part = 0;
00187 static int packet_size = 0;
00188 static int error_rate = 0;
00189 static int strict = 0;
00190 static int top_field_first = -1;
00191 static int noise_reduction = 0;
00192 static int sc_threshold = 0;
00193 static int debug = 0;
00194 static int debug_mv = 0;
00195 static int me_threshold = 0;
00196 static int mb_threshold = 0;
00197 static int intra_dc_precision = 8;
00198 static int coder = 0;
00199 static int context = 0;
00200 static int predictor = 0;
00201 static int video_profile = FF_PROFILE_UNKNOWN;
00202 static int video_level = FF_LEVEL_UNKNOWN;
00203 static int nsse_weight = 8;
00204 static int subpel_quality= 8;
00205 static int me_penalty_compensation= 256;
00206 static int lowres= 0;
00207 static int frame_skip_threshold= 0;
00208 static int frame_skip_factor= 0;
00209 static int frame_skip_exp= 0;
00210 static int frame_skip_cmp= FF_CMP_DCTMAX;
00211 extern int loop_input; /* currently a hack */
00212 static int loop_output = AVFMT_NOOUTPUTLOOP;
00213 static int gray_only = 0;
00214 
00215 static int gop_size = 12;
00216 static int intra_only = 0;
00217 static int audio_sample_rate = 44100;
00218 static int audio_bit_rate = 64000;
00219 static int audio_disable = 0;
00220 static int audio_channels = 1;
00221 static int audio_codec_id = CODEC_ID_NONE;
00222 static int audio_codec_tag = 0;
00223 static char *audio_language = NULL;
00224 
00225 static int subtitle_codec_id = CODEC_ID_NONE;
00226 static char *subtitle_language = NULL;
00227 
00228 static int mux_rate= 0;
00229 static int mux_packet_size= 0;
00230 static float mux_preload= 0.5;
00231 static float mux_max_delay= 0.7;
00232 
00233 static int64_t recording_time = 0;
00234 static int64_t start_time = 0;
00235 static int64_t rec_timestamp = 0;
00236 static int64_t input_ts_offset = 0;
00237 static int file_overwrite = 0;
00238 static char *str_title = NULL;
00239 static char *str_author = NULL;
00240 static char *str_copyright = NULL;
00241 static char *str_comment = NULL;
00242 static int do_benchmark = 0;
00243 static int do_hex_dump = 0;
00244 static int do_pkt_dump = 0;
00245 static int do_psnr = 0;
00246 static int do_vstats = 0;
00247 static int do_pass = 0;
00248 static int bitexact = 0;
00249 static char *pass_logfilename = NULL;
00250 static int audio_stream_copy = 0;
00251 static int video_stream_copy = 0;
00252 static int subtitle_stream_copy = 0;
00253 static int video_sync_method= 1;
00254 static int audio_sync_method= 0;
00255 static int copy_ts= 0;
00256 static int opt_shortest = 0; //
00257 static int video_global_header = 0;
00258 
00259 static int rate_emu = 0;
00260 
00261 #ifdef CONFIG_BKTR
00262 static char *video_grab_format = "bktr";
00263 #else
00264 static char *video_grab_format = "video4linux";
00265 #endif
00266 static char *video_device = NULL;
00267 static char *grab_device = NULL;
00268 static int  video_channel = 0;
00269 static char *video_standard = "ntsc";
00270 
00271 static char *audio_grab_format = "audio_device";
00272 static char *audio_device = NULL;
00273 static int audio_volume = 256;
00274 
00275 static int using_stdin = 0;
00276 static int using_vhook = 0;
00277 static int verbose = 1;
00278 static int thread_count= 1;
00279 static int q_pressed = 0;
00280 static int me_range = 0;
00281 static int64_t video_size = 0;
00282 static int64_t audio_size = 0;
00283 static int64_t extra_size = 0;
00284 static int nb_frames_dup = 0;
00285 static int nb_frames_drop = 0;
00286 static int input_sync;
00287 static int limit_filesize = 0; //
00288 
00289 static int pgmyuv_compatibility_hack=0;
00290 
00291 
00292 #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
00293 
00294 struct AVInputStream;
00295 
00296 typedef struct AVOutputStream {
00297     int file_index;          /* file index */
00298     int index;               /* stream index in the output file */
00299     int source_index;        /* AVInputStream index */
00300     AVStream *st;            /* stream in the output file */
00301     int encoding_needed;     /* true if encoding needed for this stream */
00302     int frame_number;
00303     /* input pts and corresponding output pts
00304        for A/V sync */
00305     //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
00306     struct AVInputStream *sync_ist; /* input stream to sync against */
00307     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
00308     /* video only */
00309     int video_resample;      /* video_resample and video_crop are mutually exclusive */
00310     AVFrame pict_tmp;      /* temporary image for resampling */
00311     ImgReSampleContext *img_resample_ctx; /* for image resampling */
00312 
00313     int video_crop;          /* video_resample and video_crop are mutually exclusive */
00314     int topBand;             /* cropping area sizes */
00315     int leftBand;
00316     
00317     int video_pad;           /* video_resample and video_pad are mutually exclusive */
00318     int padtop;              /* padding area sizes */
00319     int padbottom;
00320     int padleft;
00321     int padright;
00322     
00323     /* audio only */
00324     int audio_resample;
00325     ReSampleContext *resample; /* for audio resampling */
00326     FifoBuffer fifo;     /* for compression: one audio fifo per codec */
00327     FILE *logfile;
00328 } AVOutputStream;
00329 
00330 typedef struct AVInputStream {
00331     int file_index;
00332     int index;
00333     AVStream *st;
00334     int discard;             /* true if stream data should be discarded */
00335     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
00336     int64_t sample_index;      /* current sample */
00337 
00338     int64_t       start;     /* time when read started */
00339     unsigned long frame;     /* current frame */
00340     int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
00341                                 is not defined */
00342     int64_t       pts;       /* current pts */
00343     int is_start;            /* is 1 at the start and after a discontinuity */
00344 } AVInputStream;
00345 
00346 typedef struct AVInputFile {
00347     int eof_reached;      /* true if eof reached */
00348     int ist_index;        /* index of first stream in ist_table */
00349     int buffer_size;      /* current total buffer size */
00350     int buffer_size_max;  /* buffer size at which we consider we can stop
00351                              buffering */
00352     int nb_streams;       /* nb streams we are aware of */
00353 } AVInputFile;
00354 
00355 #ifndef CONFIG_WIN32
00356 
00357 /* init terminal so that we can grab keys */
00358 static struct termios oldtty;
00359 
00360 static void term_exit(void)
00361 {
00362     tcsetattr (0, TCSANOW, &oldtty);
00363 }
00364 
00365 static volatile sig_atomic_t received_sigterm = 0;
00366 
00367 static void
00368 sigterm_handler(int sig)
00369 {
00370     received_sigterm = sig;
00371     term_exit();
00372 }
00373 
00374 static void term_init(void)
00375 {
00376     struct termios tty;
00377 
00378     tcgetattr (0, &tty);
00379     oldtty = tty;
00380 
00381     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
00382                           |INLCR|IGNCR|ICRNL|IXON);
00383     tty.c_oflag |= OPOST;
00384     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
00385     tty.c_cflag &= ~(CSIZE|PARENB);
00386     tty.c_cflag |= CS8;
00387     tty.c_cc[VMIN] = 1;
00388     tty.c_cc[VTIME] = 0;
00389     
00390     tcsetattr (0, TCSANOW, &tty);
00391 
00392     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
00393     signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
00394     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
00395     /*
00396     register a function to be called at normal program termination
00397     */
00398     atexit(term_exit);
00399 #ifdef CONFIG_BEOS_NETSERVER
00400     fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
00401 #endif
00402 }
00403 
00404 /* read a key without blocking */
00405 static int read_key(void)
00406 {
00407     int n = 1;
00408     unsigned char ch;
00409 #ifndef CONFIG_BEOS_NETSERVER
00410     struct timeval tv;
00411     fd_set rfds;
00412 
00413     FD_ZERO(&rfds);
00414     FD_SET(0, &rfds);
00415     tv.tv_sec = 0;
00416     tv.tv_usec = 0;
00417     n = select(1, &rfds, NULL, NULL, &tv);
00418 #endif
00419     if (n > 0) {
00420         n = read(0, &ch, 1);
00421         if (n == 1)
00422             return ch;
00423 
00424         return n;
00425     }
00426     return -1;
00427 }
00428 
00429 static int decode_interrupt_cb(void)
00430 {
00431     return q_pressed || (q_pressed = read_key() == 'q');
00432 }
00433 
00434 #else
00435 
00436 static volatile int received_sigterm = 0;
00437 
00438 /* no interactive support */
00439 static void term_exit(void)
00440 {
00441 }
00442 
00443 static void term_init(void)
00444 {
00445 }
00446 
00447 static int read_key(void)
00448 {
00449     return 0;
00450 }
00451 
00452 #endif
00453 
00454 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
00455 {
00456     int i, err;
00457     AVFormatContext *ic;
00458 
00459     err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
00460     if (err < 0)
00461         return err;
00462     /* copy stream format */
00463     s->nb_streams = ic->nb_streams;
00464     for(i=0;i<ic->nb_streams;i++) {
00465         AVStream *st;
00466 
00467         st = av_mallocz(sizeof(AVStream));
00468         memcpy(st, ic->streams[i], sizeof(AVStream));
00469         s->streams[i] = st;
00470     }
00471 
00472     av_close_input_file(ic);
00473     return 0;
00474 }
00475 
00476 static double
00477 get_sync_ipts(const AVOutputStream *ost)
00478 {
00479     const AVInputStream *ist = ost->sync_ist;
00480     return (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/AV_TIME_BASE;
00481 }
00482 
00483 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
00484 
00485 static void do_audio_out(AVFormatContext *s, 
00486                          AVOutputStream *ost, 
00487                          AVInputStream *ist,
00488                          unsigned char *buf, int size)
00489 {
00490     uint8_t *buftmp;
00491     static uint8_t *audio_buf = NULL;
00492     static uint8_t *audio_out = NULL;
00493     const int audio_out_size= 4*MAX_AUDIO_PACKET_SIZE;
00494 
00495     int size_out, frame_bytes, ret;
00496     AVCodecContext *enc= ost->st->codec;
00497 
00498     /* SC: dynamic allocation of buffers */
00499     if (!audio_buf)
00500         audio_buf = av_malloc(2*MAX_AUDIO_PACKET_SIZE);
00501     if (!audio_out)
00502         audio_out = av_malloc(audio_out_size);
00503     if (!audio_buf || !audio_out)
00504         return;               /* Should signal an error ! */
00505 
00506     if(audio_sync_method){
00507         double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts 
00508                 - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2);
00509         double idelta= delta*ist->st->codec->sample_rate / enc->sample_rate;
00510         int byte_delta= ((int)idelta)*2*ist->st->codec->channels;
00511 
00512         //FIXME resample delay
00513         if(fabs(delta) > 50){
00514             if(ist->is_start){
00515                 if(byte_delta < 0){
00516                     byte_delta= FFMAX(byte_delta, -size);
00517                     size += byte_delta;
00518                     buf  -= byte_delta;
00519                     if(verbose > 2)
00520                         fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
00521                     if(!size)
00522                         return;
00523                     ist->is_start=0;
00524                 }else{
00525                     static uint8_t *input_tmp= NULL;
00526                     input_tmp= av_realloc(input_tmp, byte_delta + size);
00527 
00528                     if(byte_delta + size <= MAX_AUDIO_PACKET_SIZE)
00529                         ist->is_start=0;
00530                     else
00531                         byte_delta= MAX_AUDIO_PACKET_SIZE - size;
00532 
00533                     memset(input_tmp, 0, byte_delta);
00534                     memcpy(input_tmp + byte_delta, buf, size);
00535                     buf= input_tmp;
00536                     size += byte_delta;
00537                     if(verbose > 2)
00538                         fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
00539                 }
00540             }else if(audio_sync_method>1){
00541                 int comp= clip(delta, -audio_sync_method, audio_sync_method);
00542                 assert(ost->audio_resample);
00543                 if(verbose > 2)
00544                     fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
00545 //                fprintf(stderr, "drift:%f len:%d opts:%lld ipts:%lld fifo:%d\n", delta, -1, ost->sync_opts, (int64_t)(get_sync_ipts(ost) * enc->sample_rate), fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2));
00546                 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
00547             }
00548         } 
00549     }else
00550         ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
00551                         - fifo_size(&ost->fifo, ost->fifo.rptr)/(ost->st->codec->channels * 2); //FIXME wrong
00552 
00553     if (ost->audio_resample) {
00554         buftmp = audio_buf;
00555         size_out = audio_resample(ost->resample, 
00556                                   (short *)buftmp, (short *)buf,
00557                                   size / (ist->st->codec->channels * 2));
00558         size_out = size_out * enc->channels * 2;
00559     } else {
00560         buftmp = buf;
00561         size_out = size;
00562     }
00563 
00564     /* now encode as many frames as possible */
00565     if (enc->frame_size > 1) {
00566         /* output resampled raw samples */
00567         fifo_write(&ost->fifo, buftmp, size_out, 
00568                    &ost->fifo.wptr);
00569 
00570         frame_bytes = enc->frame_size * 2 * enc->channels;
00571         
00572         while (fifo_read(&ost->fifo, audio_buf, frame_bytes, 
00573                      &ost->fifo.rptr) == 0) {
00574             AVPacket pkt;
00575             av_init_packet(&pkt);
00576 
00577             ret = avcodec_encode_audio(enc, audio_out, audio_out_size, 
00578                                        (short *)audio_buf);
00579             audio_size += ret;
00580             pkt.stream_index= ost->index;
00581             pkt.data= audio_out;
00582             pkt.size= ret;
00583             if(enc->coded_frame)
00584                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
00585             pkt.flags |= PKT_FLAG_KEY;
00586             av_interleaved_write_frame(s, &pkt);
00587             
00588             ost->sync_opts += enc->frame_size;
00589         }
00590     } else {
00591         AVPacket pkt;
00592         av_init_packet(&pkt);
00593 
00594         ost->sync_opts += size_out / (2 * enc->channels);
00595 
00596         /* output a pcm frame */
00597         /* XXX: change encoding codec API to avoid this ? */
00598         switch(enc->codec->id) {
00599         case CODEC_ID_PCM_S16LE:
00600         case CODEC_ID_PCM_S16BE:
00601         case CODEC_ID_PCM_U16LE:
00602         case CODEC_ID_PCM_U16BE:
00603             break;
00604         default:
00605             size_out = size_out >> 1;
00606             break;
00607         }
00608         ret = avcodec_encode_audio(enc, audio_out, size_out, 
00609                                    (short *)buftmp);
00610         audio_size += ret;
00611         pkt.stream_index= ost->index;
00612         pkt.data= audio_out;
00613         pkt.size= ret;
00614         if(enc->coded_frame)
00615             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
00616         pkt.flags |= PKT_FLAG_KEY;
00617         av_interleaved_write_frame(s, &pkt);
00618     }
00619 }
00620 
00621 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
00622 {
00623     AVCodecContext *dec;
00624     AVPicture *picture2;
00625     AVPicture picture_tmp;
00626     uint8_t *buf = 0;
00627 
00628     dec = ist->st->codec;
00629 
00630     /* deinterlace : must be done before any resize */
00631     if (do_deinterlace || using_vhook) {
00632         int size;
00633 
00634         /* create temporary picture */
00635         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
00636         buf = av_malloc(size);
00637         if (!buf)
00638             return;
00639         
00640         picture2 = &picture_tmp;
00641         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
00642 
00643         if (do_deinterlace){
00644             if(avpicture_deinterlace(picture2, picture, 
00645                                      dec->pix_fmt, dec->width, dec->height) < 0) {
00646                 /* if error, do not deinterlace */
00647                 av_free(buf);
00648                 buf = NULL;
00649                 picture2 = picture;
00650             }
00651         } else {
00652             if (img_convert(picture2, dec->pix_fmt, picture, 
00653                             dec->pix_fmt, dec->width, dec->height) < 0) {
00654                 /* if error, do not copy */
00655                 av_free(buf);
00656                 buf = NULL;
00657                 picture2 = picture;
00658             }
00659         }
00660     } else {
00661         picture2 = picture;
00662     }
00663 
00664     frame_hook_process(picture2, dec->pix_fmt, dec->width, dec->height);
00665 
00666     if (picture != picture2)
00667         *picture = *picture2;
00668     *bufp = buf;
00669 }
00670 
00671 /* we begin to correct av delay at this threshold */
00672 #define AV_DELAY_MAX 0.100
00673 
00674 
00675 /* Expects img to be yuv420 */
00676 static void fill_pad_region(AVPicture* img, int height, int width,
00677         int padtop, int padbottom, int padleft, int padright, int *color) {
00678   
00679     int i, y, shift;
00680     uint8_t *optr;
00681     
00682     for (i = 0; i < 3; i++) {
00683         shift = (i == 0) ? 0 : 1;
00684         
00685         if (padtop || padleft) {
00686             memset(img->data[i], color[i], (((img->linesize[i] * padtop) + 
00687                             padleft) >> shift));
00688         }
00689 
00690         if (padleft || padright) {
00691             optr = img->data[i] + (img->linesize[i] * (padtop >> shift)) +
00692                 (img->linesize[i] - (padright >> shift));
00693 
00694             for (y = 0; y < ((height - (padtop + padbottom) - 1) >> shift); y++) {
00695                 memset(optr, color[i], (padleft + padright) >> shift);
00696                 optr += img->linesize[i];
00697             }
00698         }
00699       
00700         if (padbottom || padright) {
00701             optr = img->data[i] + (((img->linesize[i] * (height - padbottom)) - padright) >> shift);
00702             memset(optr, color[i], (((img->linesize[i] * padbottom) + padright) >> shift));
00703         }
00704     }
00705 }
00706 
00707 static void do_subtitle_out(AVFormatContext *s, 
00708                             AVOutputStream *ost, 
00709                             AVInputStream *ist,
00710                             AVSubtitle *sub,
00711                             int64_t pts)
00712 {
00713     static uint8_t *subtitle_out = NULL;
00714     int subtitle_out_max_size = 65536;
00715     int subtitle_out_size, nb, i;
00716     AVCodecContext *enc;
00717     AVPacket pkt;
00718 
00719     if (pts == AV_NOPTS_VALUE) {
00720         fprintf(stderr, "Subtitle packets must have a pts\n");
00721         return;
00722     }
00723 
00724     enc = ost->st->codec;
00725 
00726     if (!subtitle_out) {
00727         subtitle_out = av_malloc(subtitle_out_max_size);
00728     }
00729 
00730     /* Note: DVB subtitle need one packet to draw them and one other
00731        packet to clear them */
00732     /* XXX: signal it in the codec context ? */
00733     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
00734         nb = 2;
00735     else
00736         nb = 1;
00737 
00738     for(i = 0; i < nb; i++) {
00739         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out, 
00740                                                     subtitle_out_max_size, sub);
00741         
00742         av_init_packet(&pkt);
00743         pkt.stream_index = ost->index;
00744         pkt.data = subtitle_out;
00745         pkt.size = subtitle_out_size;
00746         pkt.pts = av_rescale_q(av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
00747         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
00748             /* XXX: the pts correction is handled here. Maybe handling
00749                it in the codec would be better */
00750             if (i == 0)
00751                 pkt.pts += 90 * sub->start_display_time;
00752             else
00753                 pkt.pts += 90 * sub->end_display_time;
00754         }
00755         av_interleaved_write_frame(s, &pkt);
00756     }
00757 }
00758 
00759 static int bit_buffer_size= 1024*256;
00760 static uint8_t *bit_buffer= NULL;
00761 
00762 static void do_video_out(AVFormatContext *s, 
00763                          AVOutputStream *ost, 
00764                          AVInputStream *ist,
00765                          AVFrame *in_picture,
00766                          int *frame_size)
00767 {
00768     int nb_frames, i, ret;
00769     AVFrame *final_picture, *formatted_picture;
00770     AVFrame picture_format_temp, picture_crop_temp;
00771     uint8_t *buf = NULL, *buf1 = NULL;
00772     AVCodecContext *enc, *dec;
00773     enum PixelFormat target_pixfmt;
00774     
00775     avcodec_get_frame_defaults(&picture_format_temp);
00776     avcodec_get_frame_defaults(&picture_crop_temp);
00777 
00778     enc = ost->st->codec;
00779     dec = ist->st->codec;
00780 
00781     /* by default, we output a single frame */
00782     nb_frames = 1;
00783 
00784     *frame_size = 0;
00785 
00786     if(video_sync_method){
00787         double vdelta;
00788         vdelta = get_sync_ipts(ost) / av_q2d(enc->time_base) - ost->sync_opts;
00789         //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
00790         if (vdelta < -1.1)
00791             nb_frames = 0;
00792         else if (vdelta > 1.1)
00793             nb_frames = lrintf(vdelta);
00794 //fprintf(stderr, "vdelta:%f, ost->sync_opts:%lld, ost->sync_ipts:%f nb_frames:%d\n", vdelta, ost->sync_opts, ost->sync_ipts, nb_frames);
00795         if (nb_frames == 0){
00796             ++nb_frames_drop;
00797             if (verbose>2)
00798                 fprintf(stderr, "*** drop!\n");
00799         }else if (nb_frames > 1) {
00800             nb_frames_dup += nb_frames;
00801             if (verbose>2)
00802                 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
00803         }
00804     }else
00805         ost->sync_opts= lrintf(get_sync_ipts(ost) / av_q2d(enc->time_base));
00806 
00807     nb_frames= FFMIN(nb_frames, max_frames[CODEC_TYPE_VIDEO] - ost->frame_number);
00808     if (nb_frames <= 0) 
00809         return;
00810 
00811     /* convert pixel format if needed */
00812     target_pixfmt = ost->video_resample || ost->video_pad
00813         ? PIX_FMT_YUV420P : enc->pix_fmt;
00814     if (dec->pix_fmt != target_pixfmt) {
00815         int size;
00816 
00817         /* create temporary picture */
00818         size = avpicture_get_size(target_pixfmt, dec->width, dec->height);
00819         buf = av_malloc(size);
00820         if (!buf)
00821             return;
00822         formatted_picture = &picture_format_temp;
00823         avpicture_fill((AVPicture*)formatted_picture, buf, target_pixfmt, dec->width, dec->height);
00824         
00825         if (img_convert((AVPicture*)formatted_picture, target_pixfmt, 
00826                         (AVPicture *)in_picture, dec->pix_fmt, 
00827                         dec->width, dec->height) < 0) {
00828 
00829             if (verbose >= 0)
00830                 fprintf(stderr, "pixel format conversion not handled\n");
00831 
00832             goto the_end;
00833         }
00834     } else {
00835         formatted_picture = in_picture;
00836     }
00837 
00838     /* XXX: resampling could be done before raw format conversion in
00839        some cases to go faster */
00840     /* XXX: only works for YUV420P */
00841     if (ost->video_resample) {
00842         final_picture = &ost->pict_tmp;
00843         img_resample(ost->img_resample_ctx, (AVPicture*)final_picture, (AVPicture*)formatted_picture);
00844        
00845         if (ost->padtop || ost->padbottom || ost->padleft || ost->padright) {
00846             fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
00847                     ost->padtop, ost->padbottom, ost->padleft, ost->padright,
00848                     padcolor);
00849         }
00850         
00851         if (enc->pix_fmt != PIX_FMT_YUV420P) {
00852             int size;
00853             
00854             av_free(buf);
00855             /* create temporary picture */
00856             size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
00857             buf = av_malloc(size);
00858             if (!buf)
00859                 return;
00860             final_picture = &picture_format_temp;
00861             avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
00862         
00863             if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
00864                             (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
00865                             enc->width, enc->height) < 0) {
00866 
00867                 if (verbose >= 0)
00868                     fprintf(stderr, "pixel format conversion not handled\n");
00869 
00870                 goto the_end;
00871             }
00872         }
00873     } else if (ost->video_crop) {
00874         picture_crop_temp.data[0] = formatted_picture->data[0] +
00875                 (ost->topBand * formatted_picture->linesize[0]) + ost->leftBand;
00876 
00877         picture_crop_temp.data[1] = formatted_picture->data[1] +
00878                 ((ost->topBand >> 1) * formatted_picture->linesize[1]) +
00879                 (ost->leftBand >> 1);
00880 
00881         picture_crop_temp.data[2] = formatted_picture->data[2] +
00882                 ((ost->topBand >> 1) * formatted_picture->linesize[2]) +
00883                 (ost->leftBand >> 1);
00884 
00885         picture_crop_temp.linesize[0] = formatted_picture->linesize[0];
00886         picture_crop_temp.linesize[1] = formatted_picture->linesize[1];
00887         picture_crop_temp.linesize[2] = formatted_picture->linesize[2];
00888         final_picture = &picture_crop_temp;
00889     } else if (ost->video_pad) {
00890         final_picture = &ost->pict_tmp;
00891 
00892         for (i = 0; i < 3; i++) {
00893             uint8_t *optr, *iptr;
00894             int shift = (i == 0) ? 0 : 1;
00895             int y, yheight;
00896             
00897             /* set offset to start writing image into */
00898             optr = final_picture->data[i] + (((final_picture->linesize[i] * 
00899                             ost->padtop) + ost->padleft) >> shift);
00900             iptr = formatted_picture->data[i];
00901 
00902             yheight = (enc->height - ost->padtop - ost->padbottom) >> shift;
00903             for (y = 0; y < yheight; y++) {
00904                 /* copy unpadded image row into padded image row */
00905                 memcpy(optr, iptr, formatted_picture->linesize[i]);
00906                 optr += final_picture->linesize[i];
00907                 iptr += formatted_picture->linesize[i];
00908             }
00909         }
00910 
00911         fill_pad_region((AVPicture*)final_picture, enc->height, enc->width,
00912                 ost->padtop, ost->padbottom, ost->padleft, ost->padright,
00913                 padcolor);
00914         
00915         if (enc->pix_fmt != PIX_FMT_YUV420P) {
00916             int size;
00917 
00918             av_free(buf);
00919             /* create temporary picture */
00920             size = avpicture_get_size(enc->pix_fmt, enc->width, enc->height);
00921             buf = av_malloc(size);
00922             if (!buf)
00923                 return;
00924             final_picture = &picture_format_temp;
00925             avpicture_fill((AVPicture*)final_picture, buf, enc->pix_fmt, enc->width, enc->height);
00926 
00927             if (img_convert((AVPicture*)final_picture, enc->pix_fmt, 
00928                         (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P, 
00929                         enc->width, enc->height) < 0) {
00930 
00931                 if (verbose >= 0)
00932                     fprintf(stderr, "pixel format conversion not handled\n");
00933 
00934                 goto the_end;
00935             }
00936         }
00937     } else {
00938         final_picture = formatted_picture;
00939     }
00940     /* duplicates frame if needed */
00941     for(i=0;i<nb_frames;i++) {
00942         AVPacket pkt;
00943         av_init_packet(&pkt);
00944         pkt.stream_index= ost->index;
00945 
00946         if (s->oformat->flags & AVFMT_RAWPICTURE) {
00947             /* raw pictures are written as AVPicture structure to
00948                avoid any copies. We support temorarily the older
00949                method. */
00950             AVFrame* old_frame = enc->coded_frame;
00951             enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
00952             pkt.data= (uint8_t *)final_picture;
00953             pkt.size=  sizeof(AVPicture);
00954             if(dec->coded_frame)
00955                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
00956             if(dec->coded_frame && dec->coded_frame->key_frame)
00957                 pkt.flags |= PKT_FLAG_KEY;
00958 
00959             av_interleaved_write_frame(s, &pkt);
00960             enc->coded_frame = old_frame;
00961         } else {
00962             AVFrame big_picture;
00963 
00964             big_picture= *final_picture;
00965             /* better than nothing: use input picture interlaced
00966                settings */
00967             big_picture.interlaced_frame = in_picture->interlaced_frame;
00968             if(do_interlace_me || do_interlace_dct){
00969                 if(top_field_first == -1)
00970                     big_picture.top_field_first = in_picture->top_field_first;
00971                 else
00972                     big_picture.top_field_first = top_field_first;
00973             }
00974 
00975             /* handles sameq here. This is not correct because it may
00976                not be a global option */
00977             if (same_quality) {
00978                 big_picture.quality = ist->st->quality;
00979             }else
00980                 big_picture.quality = ost->st->quality;
00981             if(!me_threshold)
00982                 big_picture.pict_type = 0;
00983 //            big_picture.pts = AV_NOPTS_VALUE;
00984             big_picture.pts= ost->sync_opts;
00985 //            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
00986 //av_log(NULL, AV_LOG_DEBUG, "%lld -> encoder\n", ost->sync_opts);
00987             ret = avcodec_encode_video(enc, 
00988                                        bit_buffer, bit_buffer_size,
00989                                        &big_picture);
00990             //enc->frame_number = enc->real_pict_num;
00991             if(ret>0){
00992                 pkt.data= bit_buffer;
00993                 pkt.size= ret;
00994                 if(enc->coded_frame)
00995                     pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
00996 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %lld/%lld\n", 
00997    pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
00998    pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
00999 
01000                 if(enc->coded_frame && enc->coded_frame->key_frame)
01001                     pkt.flags |= PKT_FLAG_KEY;
01002                 av_interleaved_write_frame(s, &pkt);
01003                 *frame_size = ret;
01004                 //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
01005                 //        enc->frame_number-1, enc->real_pict_num, ret,
01006                 //        enc->pict_type);
01007                 /* if two pass, output log */
01008                 if (ost->logfile && enc->stats_out) {
01009                     fprintf(ost->logfile, "%s", enc->stats_out);
01010                 }
01011             }
01012         }
01013         ost->sync_opts++;
01014         ost->frame_number++;
01015     }
01016  the_end:
01017     av_free(buf);
01018     av_free(buf1);
01019 }
01020 
01021 static double psnr(double d){
01022     if(d==0) return INFINITY;
01023     return -10.0*log(d)/log(10.0);
01024 }
01025 
01026 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost, 
01027                            int frame_size)
01028 {
01029     static FILE *fvstats=NULL;
01030     char filename[40];
01031     time_t today2;
01032     struct tm *today;
01033     AVCodecContext *enc;
01034     int frame_number;
01035     int64_t ti;
01036     double ti1, bitrate, avg_bitrate;
01037     
01038     if (!fvstats) {
01039         today2 = time(NULL);
01040         today = localtime(&today2);
01041         snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour,
01042                                                today->tm_min,
01043                                                today->tm_sec);
01044         fvstats = fopen(filename,"w");
01045         if (!fvstats) {
01046             perror("fopen");
01047             exit(1);
01048         }
01049     }
01050     
01051     ti = MAXINT64;
01052     enc = ost->st->codec;
01053     if (enc->codec_type == CODEC_TYPE_VIDEO) {
01054         frame_number = ost->frame_number;
01055         fprintf(fvstats, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
01056         if (enc->flags&CODEC_FLAG_PSNR)
01057             fprintf(fvstats, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
01058         
01059         fprintf(fvstats,"f_size= %6d ", frame_size);
01060         /* compute pts value */
01061         ti1 = ost->sync_opts * av_q2d(enc->time_base);
01062         if (ti1 < 0.01)
01063             ti1 = 0.01;
01064     
01065         bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
01066         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
01067         fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
01068             (double)video_size / 1024, ti1, bitrate, avg_bitrate);
01069         fprintf(fvstats,"type= %c\n", av_get_pict_type_char(enc->coded_frame->pict_type));        
01070     }
01071 }
01072 
01073 static void print_report(AVFormatContext **output_files,
01074                          AVOutputStream **ost_table, int nb_ostreams,
01075                          int is_last_report)
01076 {
01077     char buf[1024];
01078     AVOutputStream *ost;
01079     AVFormatContext *oc, *os;
01080     int64_t total_size;
01081     AVCodecContext *enc;
01082     int frame_number, vid, i;
01083     double bitrate, ti1, pts;
01084     static int64_t last_time = -1;
01085     
01086     if (!is_last_report) {
01087         int64_t cur_time;
01088         /* display the report every 0.5 seconds */
01089         cur_time = av_gettime();
01090         if (last_time == -1) {
01091             last_time = cur_time;
01092             return;
01093         } 
01094         if ((cur_time - last_time) < 500000)
01095             return;
01096         last_time = cur_time;
01097     }
01098 
01099 
01100     oc = output_files[0];
01101 
01102     total_size = url_ftell(&oc->pb);
01103     
01104     buf[0] = '\0';
01105     ti1 = 1e10;
01106     vid = 0;
01107     for(i=0;i<nb_ostreams;i++) {
01108         ost = ost_table[i];
01109         os = output_files[ost->file_index];
01110         enc = ost->st->codec;
01111         if (vid && enc->codec_type == CODEC_TYPE_VIDEO) {
01112             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ",
01113                     enc->coded_frame->quality/(float)FF_QP2LAMBDA);
01114         }
01115         if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
01116             frame_number = ost->frame_number;
01117             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d q=%2.1f ",
01118                     frame_number, enc->coded_frame ? enc->coded_frame->quality/(float)FF_QP2LAMBDA : 0);
01119             if(is_last_report)
01120                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
01121             if (enc->flags&CODEC_FLAG_PSNR){
01122                 int j;
01123                 double error, error_sum=0;
01124                 double scale, scale_sum=0;
01125                 char type[3]= {'Y','U','V'};
01126                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
01127                 for(j=0; j<3; j++){
01128                     if(is_last_report){
01129                         error= enc->error[j];
01130                         scale= enc->width*enc->height*255.0*255.0*frame_number;
01131                     }else{
01132                         error= enc->coded_frame->error[j];
01133                         scale= enc->width*enc->height*255.0*255.0;
01134                     }
01135                     if(j) scale/=4;
01136                     error_sum += error;
01137                     scale_sum += scale;
01138                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
01139                 }
01140                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
01141             }
01142             vid = 1;
01143         }
01144         /* compute min output value */
01145         pts = (double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den;
01146         if ((pts < ti1) && (pts > 0))
01147             ti1 = pts;
01148     }
01149     if (ti1 < 0.01)
01150         ti1 = 0.01;
01151     
01152     if (verbose || is_last_report) {
01153         bitrate = (double)(total_size * 8) / ti1 / 1000.0;
01154         
01155         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), 
01156             "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
01157             (double)total_size / 1024, ti1, bitrate);
01158 
01159         if (verbose > 1)
01160           snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
01161                   nb_frames_dup, nb_frames_drop);
01162         
01163         if (verbose >= 0)
01164             fprintf(stderr, "%s    \r", buf);
01165 
01166         fflush(stderr);
01167     }
01168         
01169     if (is_last_report && verbose >= 0){
01170         int64_t raw= audio_size + video_size + extra_size;
01171         fprintf(stderr, "\n");
01172         fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
01173                 video_size/1024.0,
01174                 audio_size/1024.0,
01175                 extra_size/1024.0,
01176                 100.0*(total_size - raw)/raw
01177         );
01178     }
01179 }
01180 
01181 /* pkt = NULL means EOF (needed to flush decoder buffers) */
01182 static int output_packet(AVInputStream *ist, int ist_index,
01183                          AVOutputStream **ost_table, int nb_ostreams,
01184                          const AVPacket *pkt)
01185 {
01186     AVFormatContext *os;
01187     AVOutputStream *ost;
01188     uint8_t *ptr;
01189     int len, ret, i;
01190     uint8_t *data_buf;
01191     int data_size, got_picture;
01192     AVFrame picture;
01193     void *buffer_to_free;
01194     static int samples_size= 0;
01195     static short *samples= NULL;
01196     AVSubtitle subtitle, *subtitle_to_free;
01197     int got_subtitle;
01198     
01199     if(!pkt){
01200         ist->pts= ist->next_pts; // needed for last packet if vsync=0
01201     } else if (pkt->dts != AV_NOPTS_VALUE) { //FIXME seems redundant, as libavformat does this too
01202         ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
01203     } else {
01204 //        assert(ist->pts == ist->next_pts);
01205     }
01206     
01207     if (pkt == NULL) {
01208         /* EOF handling */
01209         ptr = NULL;
01210         len = 0;
01211         goto handle_eof;
01212     }
01213 
01214     len = pkt->size;
01215     ptr = pkt->data;
01216     while (len > 0) {
01217     handle_eof:
01218         /* decode the packet if needed */
01219         data_buf = NULL; /* fail safe */
01220         data_size = 0;
01221         subtitle_to_free = NULL;
01222         if (ist->decoding_needed) {
01223             switch(ist->st->codec->codec_type) {
01224             case CODEC_TYPE_AUDIO:{
01225                 if(pkt) 
01226                     samples= av_fast_realloc(samples, &samples_size, FFMAX(pkt->size, AVCODEC_MAX_AUDIO_FRAME_SIZE));
01227                     /* XXX: could avoid copy if PCM 16 bits with same
01228                        endianness as CPU */
01229                 ret = avcodec_decode_audio(ist->st->codec, samples, &data_size,
01230                                            ptr, len);
01231                 if (ret < 0)
01232                     goto fail_decode;
01233                 ptr += ret;
01234                 len -= ret;
01235                 /* Some bug in mpeg audio decoder gives */
01236                 /* data_size < 0, it seems they are overflows */
01237                 if (data_size <= 0) {
01238                     /* no audio frame */
01239                     continue;
01240                 }
01241                 data_buf = (uint8_t *)samples;
01242                 ist->next_pts += ((int64_t)AV_TIME_BASE/2 * data_size) / 
01243                     (ist->st->codec->sample_rate * ist->st->codec->channels);
01244                 break;}
01245             case CODEC_TYPE_VIDEO:
01246                     data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
01247                     /* XXX: allocate picture correctly */
01248                     avcodec_get_frame_defaults(&picture);
01249 
01250                     ret = avcodec_decode_video(ist->st->codec, 
01251                                                &picture, &got_picture, ptr, len);
01252                     ist->st->quality= picture.quality;
01253                     if (ret < 0) 
01254                         goto fail_decode;
01255                     if (!got_picture) {
01256                         /* no picture yet */
01257                         goto discard_packet;
01258                     }
01259                     if (ist->st->codec->time_base.num != 0) {
01260                         ist->next_pts += ((int64_t)AV_TIME_BASE * 
01261                                           ist->st->codec->time_base.num) /
01262                             ist->st->codec->time_base.den;
01263                     }
01264                     len = 0;
01265                     break;
01266             case CODEC_TYPE_SUBTITLE:
01267                 ret = avcodec_decode_subtitle(ist->st->codec, 
01268                                               &subtitle, &got_subtitle, ptr, len);
01269                 if (ret < 0)
01270                     goto fail_decode;
01271                 if (!got_subtitle) {
01272                     goto discard_packet;
01273                 }
01274                 subtitle_to_free = &subtitle;
01275                 len = 0;
01276                 break;
01277             default:
01278                 goto fail_decode;
01279             }
01280         } else {
01281                 switch(ist->st->codec->codec_type) {
01282                 case CODEC_TYPE_AUDIO:
01283                     ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) / 
01284                         (ist->st->codec->sample_rate * ist->st->codec->channels);
01285                     break;
01286                 case CODEC_TYPE_VIDEO:
01287                     if (ist->st->codec->time_base.num != 0) {
01288                         ist->next_pts += ((int64_t)AV_TIME_BASE * 
01289                                           ist->st->codec->time_base.num) /
01290                             ist->st->codec->time_base.den;
01291                     }
01292                     break;
01293                 }
01294                 data_buf = ptr;
01295                 data_size = len;
01296                 ret = len;
01297                 len = 0;
01298             }
01299 
01300             buffer_to_free = NULL;
01301             if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO) {
01302                 pre_process_video_frame(ist, (AVPicture *)&picture, 
01303                                         &buffer_to_free);
01304             }
01305 
01306             // preprocess audio (volume)
01307             if (ist->st->codec->codec_type == CODEC_TYPE_AUDIO) {
01308                 if (audio_volume != 256) {
01309                     short *volp;
01310                     volp = samples;
01311                     for(i=0;i<(data_size / sizeof(short));i++) {
01312                         int v = ((*volp) * audio_volume + 128) >> 8;
01313                         if (v < -32768) v = -32768;
01314                         if (v >  32767) v = 32767;
01315                         *volp++ = v;
01316                     }
01317                 }
01318             }
01319 
01320             /* frame rate emulation */
01321             if (ist->st->codec->rate_emu) {
01322                 int64_t pts = av_rescale((int64_t) ist->frame * ist->st->codec->time_base.num, 1000000, ist->st->codec->time_base.den);
01323                 int64_t now = av_gettime() - ist->start;
01324                 if (pts > now)
01325                     usleep(pts - now);
01326 
01327                 ist->frame++;
01328             }
01329 
01330 #if 0
01331             /* mpeg PTS deordering : if it is a P or I frame, the PTS
01332                is the one of the next displayed one */
01333             /* XXX: add mpeg4 too ? */
01334             if (ist->st->codec->codec_id == CODEC_ID_MPEG1VIDEO) {
01335                 if (ist->st->codec->pict_type != B_TYPE) {
01336                     int64_t tmp;
01337                     tmp = ist->last_ip_pts;
01338                     ist->last_ip_pts  = ist->frac_pts.val;
01339                     ist->frac_pts.val = tmp;
01340                 }
01341             }
01342 #endif
01343             /* if output time reached then transcode raw format, 
01344                encode packets and output them */
01345             if (start_time == 0 || ist->pts >= start_time)
01346                 for(i=0;i<nb_ostreams;i++) {
01347                     int frame_size;
01348 
01349                     ost = ost_table[i];
01350                     if (ost->source_index == ist_index) {
01351                         os = output_files[ost->file_index];
01352 
01353 #if 0
01354                         printf("%d: got pts=%0.3f %0.3f\n", i, 
01355                                (double)pkt->pts / AV_TIME_BASE, 
01356                                ((double)ist->pts / AV_TIME_BASE) - 
01357                                ((double)ost->st->pts.val * ost->st->time_base.num / ost->st->time_base.den));
01358 #endif
01359                         /* set the input output pts pairs */
01360                         //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
01361 
01362                         if (ost->encoding_needed) {
01363                             switch(ost->st->codec->codec_type) {
01364                             case CODEC_TYPE_AUDIO:
01365                                 do_audio_out(os, ost, ist, data_buf, data_size);
01366                                 break;
01367                             case CODEC_TYPE_VIDEO:
01368                                     do_video_out(os, ost, ist, &picture, &frame_size);
01369                                     video_size += frame_size;
01370                                     if (do_vstats && frame_size)
01371                                         do_video_stats(os, ost, frame_size);
01372                                 break;
01373                             case CODEC_TYPE_SUBTITLE:
01374                                 do_subtitle_out(os, ost, ist, &subtitle,
01375                                                 pkt->pts);
01376                                 break;
01377                             default:
01378                                 av_abort();
01379                             }
01380                         } else {
01381                             AVFrame avframe; //FIXME/XXX remove this
01382                             AVPacket opkt;
01383                             av_init_packet(&opkt);
01384 
01385                             /* no reencoding needed : output the packet directly */
01386                             /* force the input stream PTS */
01387                         
01388                             avcodec_get_frame_defaults(&avframe);
01389                             ost->st->codec->coded_frame= &avframe;
01390                             avframe.key_frame = pkt->flags & PKT_FLAG_KEY; 
01391 
01392                             if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO)
01393                                 audio_size += data_size;
01394                             else if (ost->st->codec->codec_type == CODEC_TYPE_VIDEO) {
01395                                 video_size += data_size;
01396                                 ost->sync_opts++;
01397                             }
01398 
01399                             opkt.stream_index= ost->index;
01400                             if(pkt->pts != AV_NOPTS_VALUE)
01401                                 opkt.pts= av_rescale_q(av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q) + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
01402                             else
01403                                 opkt.pts= AV_NOPTS_VALUE;
01404 
01405                             {
01406                                 int64_t dts;
01407                                 if (pkt->dts == AV_NOPTS_VALUE)
01408                                     dts = ist->next_pts;
01409                                 else
01410                                     dts= av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
01411                                 opkt.dts= av_rescale_q(dts + input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q,  ost->st->time_base);
01412                             }
01413                             opkt.flags= pkt->flags;
01414                             if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & PKT_FLAG_KEY))
01415                                 opkt.destruct= av_destruct_packet;
01416                             av_interleaved_write_frame(os, &opkt);
01417                             ost->st->codec->frame_number++;
01418                             ost->frame_number++;
01419                             av_free_packet(&opkt);
01420                         }
01421                     }
01422                 }
01423             av_free(buffer_to_free);
01424             /* XXX: allocate the subtitles in the codec ? */
01425             if (subtitle_to_free) {
01426                 if (subtitle_to_free->rects != NULL) {
01427                     for (i = 0; i < subtitle_to_free->num_rects; i++) {
01428                         av_free(subtitle_to_free->rects[i].bitmap);
01429                         av_free(subtitle_to_free->rects[i].rgba_palette);
01430                     }
01431                     av_freep(&subtitle_to_free->rects);
01432                 }
01433                 subtitle_to_free->num_rects = 0;
01434                 subtitle_to_free = NULL;
01435             }
01436         }
01437  discard_packet:
01438     if (pkt == NULL) {
01439         /* EOF handling */
01440   
01441         for(i=0;i<nb_ostreams;i++) {
01442             ost = ost_table[i];
01443             if (ost->source_index == ist_index) {
01444                 AVCodecContext *enc= ost->st->codec;
01445                 os = output_files[ost->file_index];
01446                 
01447                 if(ost->st->codec->codec_type == CODEC_TYPE_AUDIO && enc->frame_size <=1)
01448                     continue;
01449                 if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
01450                     continue;
01451 
01452                 if (ost->encoding_needed) {
01453                     for(;;) {
01454                         AVPacket pkt;
01455                         av_init_packet(&pkt);
01456                         pkt.stream_index= ost->index;
01457  
01458                         switch(ost->st->codec->codec_type) {
01459                         case CODEC_TYPE_AUDIO:        
01460                             ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
01461                             audio_size += ret;
01462                             pkt.flags |= PKT_FLAG_KEY;
01463                             break;
01464                         case CODEC_TYPE_VIDEO:
01465                             ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
01466                             video_size += ret;
01467                             if(enc->coded_frame && enc->coded_frame->key_frame)
01468                                 pkt.flags |= PKT_FLAG_KEY;
01469                             if (ost->logfile && enc->stats_out) {
01470                                 fprintf(ost->logfile, "%s", enc->stats_out);
01471                             }
01472                             break;
01473                         default:
01474                             ret=-1;
01475                         }
01476                             
01477                         if(ret<=0)
01478                             break;
01479                         pkt.data= bit_buffer;
01480                         pkt.size= ret;
01481                         if(enc->coded_frame)
01482                             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01483                         av_interleaved_write_frame(os, &pkt);
01484                     }
01485                 }
01486             }
01487         }
01488     }
01489  
01490     return 0;
01491  fail_decode:
01492     return -1;
01493 }
01494 
01495 
01496 /*
01497  * The following code is the main loop of the file converter
01498  */
01499 static int av_encode(AVFormatContext **output_files,
01500                      int nb_output_files,
01501                      AVFormatContext **input_files,
01502                      int nb_input_files,
01503                      AVStreamMap *stream_maps, int nb_stream_maps)
01504 {
01505     int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0;
01506     AVFormatContext *is, *os;
01507     AVCodecContext *codec, *icodec;
01508     AVOutputStream *ost, **ost_table = NULL;
01509     AVInputStream *ist, **ist_table = NULL;
01510     AVInputFile *file_table;
01511     AVFormatContext *stream_no_data;
01512     int key;
01513 
01514     file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
01515     if (!file_table)
01516         goto fail;
01517         
01518     /* input stream init */
01519     j = 0;
01520     for(i=0;i<nb_input_files;i++) {
01521         is = input_files[i];
01522         file_table[i].ist_index = j;
01523         file_table[i].nb_streams = is->nb_streams;
01524         j += is->nb_streams;
01525     }
01526     nb_istreams = j;
01527 
01528     ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
01529     if (!ist_table)
01530         goto fail;
01531     
01532     for(i=0;i<nb_istreams;i++) {
01533         ist = av_mallocz(sizeof(AVInputStream));
01534         if (!ist)
01535             goto fail;
01536         ist_table[i] = ist;
01537     }
01538     j = 0;
01539     for(i=0;i<nb_input_files;i++) {
01540         is = input_files[i];
01541         for(k=0;k<is->nb_streams;k++) {
01542             ist = ist_table[j++];
01543             ist->st = is->streams[k];
01544             ist->file_index = i;
01545             ist->index = k;
01546             ist->discard = 1; /* the stream is discarded by default
01547                                  (changed later) */
01548 
01549             if (ist->st->codec->rate_emu) {
01550                 ist->start = av_gettime();
01551                 ist->frame = 0;
01552             }
01553         }
01554     }
01555 
01556     /* output stream init */
01557     nb_ostreams = 0;
01558     for(i=0;i<nb_output_files;i++) {
01559         os = output_files[i];
01560         nb_ostreams += os->nb_streams;
01561     }
01562     if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
01563         fprintf(stderr, "Number of stream maps must match number of output streams\n");
01564         exit(1);
01565     }
01566 
01567     /* Sanity check the mapping args -- do the input files & streams exist? */
01568     for(i=0;i<nb_stream_maps;i++) {
01569         int fi = stream_maps[i].file_index;
01570         int si = stream_maps[i].stream_index;
01571         
01572         if (fi < 0 || fi > nb_input_files - 1 ||
01573             si < 0 || si > file_table[fi].nb_streams - 1) {
01574             fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
01575             exit(1);
01576         }
01577         fi = stream_maps[i].sync_file_index;
01578         si = stream_maps[i].sync_stream_index;
01579         if (fi < 0 || fi > nb_input_files - 1 ||
01580             si < 0 || si > file_table[fi].nb_streams - 1) {
01581             fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
01582             exit(1);
01583         }
01584     }
01585     
01586     ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
01587     if (!ost_table)
01588         goto fail;
01589     for(i=0;i<nb_ostreams;i++) {
01590         ost = av_mallocz(sizeof(AVOutputStream));
01591         if (!ost)
01592             goto fail;
01593         ost_table[i] = ost;
01594     }
01595     
01596     n = 0;
01597     for(k=0;k<nb_output_files;k++) {
01598         os = output_files[k];
01599         for(i=0;i<os->nb_streams;i++) {
01600             int found;
01601             ost = ost_table[n++];
01602             ost->file_index = k;
01603             ost->index = i;
01604             ost->st = os->streams[i];
01605             if (nb_stream_maps > 0) {
01606                 ost->source_index = file_table[stream_maps[n-1].file_index].ist_index + 
01607                     stream_maps[n-1].stream_index;
01608                     
01609                 /* Sanity check that the stream types match */
01610                 if (ist_table[ost->source_index]->st->codec->codec_type != ost->st->codec->codec_type) {
01611                     fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
01612                         stream_maps[n-1].file_index, stream_maps[n-1].stream_index,
01613                         ost->file_index, ost->index);
01614                     exit(1);
01615                 }
01616                 
01617             } else {
01618                 /* get corresponding input stream index : we select the first one with the right type */
01619                 found = 0;
01620                 for(j=0;j<nb_istreams;j++) {
01621                     ist = ist_table[j];
01622                     if (ist->discard && 
01623                         ist->st->codec->codec_type == ost->st->codec->codec_type) {
01624                         ost->source_index = j;
01625                         found = 1;
01626                         break;
01627                     }
01628                 }
01629                 
01630                 if (!found) {
01631                     /* try again and reuse existing stream */
01632                     for(j=0;j<nb_istreams;j++) {
01633                         ist = ist_table[j];
01634                         if (ist->st->codec->codec_type == ost->st->codec->codec_type) {
01635                             ost->source_index = j;
01636                             found = 1;
01637                         }
01638                     }
01639                     if (!found) {
01640                         fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
01641                                 ost->file_index, ost->index);
01642                         exit(1);
01643                     }
01644                 }
01645             }
01646             ist = ist_table[ost->source_index];
01647             ist->discard = 0;
01648             ost->sync_ist = (nb_stream_maps > 0) ?
01649                 ist_table[file_table[stream_maps[n-1].sync_file_index].ist_index +
01650                          stream_maps[n-1].sync_stream_index] : ist;
01651         }
01652     }
01653 
01654     /* for each output stream, we compute the right encoding parameters */
01655     for(i=0;i<nb_ostreams;i++) {
01656         ost = ost_table[i];
01657         ist = ist_table[ost->source_index];
01658 
01659         codec = ost->st->codec;
01660         icodec = ist->st->codec;
01661 
01662         if (ost->st->stream_copy) {
01663             /* if stream_copy is selected, no need to decode or encode */
01664             codec->codec_id = icodec->codec_id;
01665             codec->codec_type = icodec->codec_type;
01666             if(!codec->codec_tag) codec->codec_tag = icodec->codec_tag;
01667             codec->bit_rate = icodec->bit_rate;
01668             codec->extradata= icodec->extradata;
01669             codec->extradata_size= icodec->extradata_size;
01670             switch(codec->codec_type) {
01671             case CODEC_TYPE_AUDIO:
01672                 codec->sample_rate = icodec->sample_rate;
01673                 codec->channels = icodec->channels;
01674                 codec->frame_size = icodec->frame_size;
01675                 codec->block_align= icodec->block_align;
01676                 break;
01677             case CODEC_TYPE_VIDEO:
01678                 codec->time_base = icodec->time_base;
01679                 codec->width = icodec->width;
01680                 codec->height = icodec->height;
01681                 codec->has_b_frames = icodec->has_b_frames;
01682                 break;
01683             case CODEC_TYPE_SUBTITLE:
01684                 break;
01685             default:
01686                 av_abort();
01687             }
01688         } else {
01689             switch(codec->codec_type) {
01690             case CODEC_TYPE_AUDIO:
01691                 if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
01692                     goto fail;
01693                 
01694                 if (codec->channels == icodec->channels &&
01695                     codec->sample_rate == icodec->sample_rate) {
01696                     ost->audio_resample = 0;
01697                 } else {
01698                     if (codec->channels != icodec->channels &&
01699                         (icodec->codec_id == CODEC_ID_AC3 ||
01700                          icodec->codec_id == CODEC_ID_DTS)) {
01701                         /* Special case for 5:1 AC3 and DTS input */
01702                         /* and mono or stereo output      */
01703                         /* Request specific number of channels */
01704                         icodec->channels = codec->channels;
01705                         if (codec->sample_rate == icodec->sample_rate)
01706                             ost->audio_resample = 0;
01707                         else {
01708                             ost->audio_resample = 1;
01709                         }
01710                     } else {
01711                         ost->audio_resample = 1; 
01712                     }
01713                 }
01714                 if(audio_sync_method>1)
01715                     ost->audio_resample = 1;
01716 
01717                 if(ost->audio_resample){
01718                     ost->resample = audio_resample_init(codec->channels, icodec->channels,
01719                                                     codec->sample_rate, icodec->sample_rate);
01720                     if(!ost->resample){
01721                         printf("Can't resample.  Aborting.\n");
01722                         av_abort();
01723                     }
01724                 }
01725                 ist->decoding_needed = 1;
01726                 ost->encoding_needed = 1;
01727                 break;
01728             case CODEC_TYPE_VIDEO:
01729                 if (codec->width == icodec->width &&
01730                     codec->height == icodec->height &&
01731                     frame_topBand == 0 &&
01732                     frame_bottomBand == 0 &&
01733                     frame_leftBand == 0 &&
01734                     frame_rightBand == 0 && 
01735                     frame_padtop == 0 &&
01736                     frame_padbottom == 0 &&
01737                     frame_padleft == 0 &&
01738                     frame_padright == 0)
01739                 {
01740                     ost->video_resample = 0;
01741                     ost->video_crop = 0;
01742                     ost->video_pad = 0;
01743                 } else if ((codec->width == icodec->width -
01744                                 (frame_leftBand + frame_rightBand)) &&
01745                         (codec->height == icodec->height -
01746                                 (frame_topBand  + frame_bottomBand)))
01747                 {
01748                     ost->video_resample = 0;
01749                     ost->video_crop = 1;
01750                     ost->topBand = frame_topBand;
01751                     ost->leftBand = frame_leftBand;
01752                 } else if ((codec->width == icodec->width + 
01753                                 (frame_padleft + frame_padright)) &&
01754                         (codec->height == icodec->height +
01755                                 (frame_padtop + frame_padbottom))) {
01756                     ost->video_resample = 0;
01757                     ost->video_crop = 0;
01758                     ost->video_pad = 1;
01759                     ost->padtop = frame_padtop;
01760                     ost->padleft = frame_padleft;
01761                     ost->padbottom = frame_padbottom;
01762                     ost->padright = frame_padright;
01763                     avcodec_get_frame_defaults(&ost->pict_tmp);
01764                     if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
01765                                 codec->width, codec->height ) )
01766                         goto fail;
01767                 } else {
01768                     ost->video_resample = 1;
01769                     ost->video_crop = 0; // cropping is handled as part of resample
01770                     avcodec_get_frame_defaults(&ost->pict_tmp);
01771                     if( avpicture_alloc( (AVPicture*)&ost->pict_tmp, PIX_FMT_YUV420P,
01772                                          codec->width, codec->height ) )
01773                         goto fail;
01774 
01775                     ost->img_resample_ctx = img_resample_full_init( 
01776                                       ost->st->codec->width, ost->st->codec->height,
01777                                       ist->st->codec->width, ist->st->codec->height,
01778                                       frame_topBand, frame_bottomBand,
01779                             frame_leftBand, frame_rightBand, 
01780                             frame_padtop, frame_padbottom, 
01781                             frame_padleft, frame_padright);
01782                     
01783                     ost->padtop = frame_padtop;
01784                     ost->padleft = frame_padleft;
01785                     ost->padbottom = frame_padbottom;
01786                     ost->padright = frame_padright;
01787                    
01788                 }
01789                 ost->encoding_needed = 1;
01790                 ist->decoding_needed = 1;
01791                 break;
01792             case CODEC_TYPE_SUBTITLE:
01793                 ost->encoding_needed = 1;
01794                 ist->decoding_needed = 1;
01795                 break;
01796             default:
01797                 av_abort();
01798                 break;
01799             }
01800             /* two pass mode */
01801             if (ost->encoding_needed && 
01802                 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
01803                 char logfilename[1024];
01804                 FILE *f;
01805                 int size;
01806                 char *logbuffer;
01807                 
01808                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log", 
01809                          pass_logfilename ? 
01810                          pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
01811                 if (codec->flags & CODEC_FLAG_PASS1) {
01812                     f = fopen(logfilename, "w");
01813                     if (!f) {
01814                         perror(logfilename);
01815                         exit(1);
01816                     }
01817                     ost->logfile = f;
01818                 } else {
01819                     /* read the log file */
01820                     f = fopen(logfilename, "r");
01821                     if (!f) {
01822                         perror(logfilename);
01823                         exit(1);
01824                     }
01825                     fseek(f, 0, SEEK_END);
01826                     size = ftell(f);
01827                     fseek(f, 0, SEEK_SET);
01828                     logbuffer = av_malloc(size + 1);
01829                     if (!logbuffer) {
01830                         fprintf(stderr, "Could not allocate log buffer\n");
01831                         exit(1);
01832                     }
01833                     size = fread(logbuffer, 1, size, f);
01834                     fclose(f);
01835                     logbuffer[size] = '\0';
01836                     codec->stats_in = logbuffer;
01837                 }
01838             }
01839         }
01840         if(codec->codec_type == CODEC_TYPE_VIDEO){
01841             int size= codec->width * codec->height;
01842             bit_buffer_size= FFMAX(bit_buffer_size, 4*size);
01843         }
01844     }
01845 
01846     if (!bit_buffer)
01847         bit_buffer = av_malloc(bit_buffer_size);
01848     if (!bit_buffer)
01849         goto fail;
01850 
01851     /* dump the file output parameters - cannot be done before in case
01852        of stream copy */
01853     for(i=0;i<nb_output_files;i++) {
01854         dump_format(output_files[i], i, output_files[i]->filename, 1);
01855     }
01856 
01857     /* dump the stream mapping */
01858     if (verbose >= 0) {
01859         fprintf(stderr, "Stream mapping:\n");
01860         for(i=0;i<nb_ostreams;i++) {
01861             ost = ost_table[i];
01862             fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
01863                     ist_table[ost->source_index]->file_index,
01864                     ist_table[ost->source_index]->index,
01865                     ost->file_index, 
01866                     ost->index);
01867             if (ost->sync_ist != ist_table[ost->source_index])
01868                 fprintf(stderr, " [sync #%d.%d]",
01869                         ost->sync_ist->file_index,
01870                         ost->sync_ist->index);
01871             fprintf(stderr, "\n");
01872         }
01873     }
01874 
01875     /* open each encoder */
01876     for(i=0;i<nb_ostreams;i++) {
01877         ost = ost_table[i];
01878         if (ost->encoding_needed) {
01879             AVCodec *codec;
01880             codec = avcodec_find_encoder(ost->st->codec->codec_id);
01881             if (!codec) {
01882                 fprintf(stderr, "Unsupported codec for output stream #%d.%d\n", 
01883                         ost->file_index, ost->index);
01884                 exit(1);
01885             }
01886             if (avcodec_open(ost->st->codec, codec) < 0) {
01887                 fprintf(stderr, "Error while opening codec for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n", 
01888                         ost->file_index, ost->index);
01889                 exit(1);
01890             }
01891             extra_size += ost->st->codec->extradata_size;
01892         }
01893     }
01894 
01895     /* open each decoder */
01896     for(i=0;i<nb_istreams;i++) {
01897         ist = ist_table[i];
01898         if (ist->decoding_needed) {
01899             AVCodec *codec;
01900             codec = avcodec_find_decoder(ist->st->codec->codec_id);
01901             if (!codec) {
01902                 fprintf(stderr, "Unsupported codec (id=%d) for input stream #%d.%d\n", 
01903                         ist->st->codec->codec_id, ist->file_index, ist->index);
01904                 exit(1);
01905             }
01906             if (avcodec_open(ist->st->codec, codec) < 0) {
01907                 fprintf(stderr, "Error while opening codec for input stream #%d.%d\n", 
01908                         ist->file_index, ist->index);
01909                 exit(1);
01910             }
01911             //if (ist->st->codec->codec_type == CODEC_TYPE_VIDEO)
01912             //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
01913         }
01914     }
01915 
01916     /* init pts */
01917     for(i=0;i<nb_istreams;i++) {
01918         ist = ist_table[i];
01919         is = input_files[ist->file_index];
01920         ist->pts = 0;
01921         ist->next_pts = av_rescale_q(ist->st->start_time, ist->st->time_base, AV_TIME_BASE_Q);
01922         if(ist->st->start_time == AV_NOPTS_VALUE) 
01923             ist->next_pts=0;
01924         if(input_files_ts_offset[ist->file_index])
01925             ist->next_pts= AV_NOPTS_VALUE;
01926         ist->is_start = 1;
01927     }
01928 
01929     /* compute buffer size max (should use a complete heuristic) */
01930     for(i=0;i<nb_input_files;i++) {
01931         file_table[i].buffer_size_max = 2048;
01932     }
01933 
01934     /* set meta data information from input file if required */
01935     for (i=0;i<nb_meta_data_maps;i++) {
01936         AVFormatContext *out_file;
01937         AVFormatContext *in_file;
01938 
01939         int out_file_index = meta_data_maps[i].out_file;
01940         int in_file_index = meta_data_maps[i].in_file;
01941         if ( out_file_index < 0 || out_file_index >= nb_output_files ) {
01942             fprintf(stderr, "Invalid output file index %d map_meta_data(%d,%d)\n", out_file_index, out_file_index, in_file_index);
01943             ret = -EINVAL;
01944             goto fail;
01945         }
01946         if ( in_file_index < 0 || in_file_index >= nb_input_files ) {
01947             fprintf(stderr, "Invalid input file index %d map_meta_data(%d,%d)\n", in_file_index, out_file_index, in_file_index);
01948             ret = -EINVAL;
01949             goto fail;
01950         }               
01951                  
01952         out_file = output_files[out_file_index];
01953         in_file = input_files[in_file_index];
01954 
01955         strcpy(out_file->title, in_file->title);
01956         strcpy(out_file->author, in_file->author);
01957         strcpy(out_file->copyright, in_file->copyright);
01958         strcpy(out_file->comment, in_file->comment);
01959         strcpy(out_file->album, in_file->album);
01960         out_file->year = in_file->year;
01961         out_file->track = in_file->track;
01962         strcpy(out_file->genre, in_file->genre);
01963     }
01964         
01965     /* open files and write file headers */
01966     for(i=0;i<nb_output_files;i++) {
01967         os = output_files[i];
01968         if (av_write_header(os) < 0) {
01969             fprintf(stderr, "Could not write header for output file #%d (incorrect codec parameters ?)\n", i);
01970             ret = -EINVAL;
01971             goto fail;
01972         }
01973     }
01974 
01975 #ifndef CONFIG_WIN32
01976     if ( !using_stdin && verbose >= 0) {
01977         fprintf(stderr, "Press [q] to stop encoding\n");
01978         url_set_interrupt_cb(decode_interrupt_cb);
01979     }
01980 #endif
01981     term_init();
01982 
01983     stream_no_data = 0;
01984     key = -1;
01985 
01986     for(; received_sigterm == 0;) {
01987         int file_index, ist_index;
01988         AVPacket pkt;
01989         double ipts_min;
01990         double opts_min;
01991 
01992     redo:
01993         ipts_min= 1e100;
01994         opts_min= 1e100;
01995         /* if 'q' pressed, exits */
01996         if (!using_stdin) {
01997             if (q_pressed)
01998                 break;
01999             /* read_key() returns 0 on EOF */
02000             key = read_key();
02001             if (key == 'q')
02002                 break;
02003         }
02004 
02005         /* select the stream that we must read now by looking at the
02006            smallest output pts */
02007         file_index = -1;
02008         for(i=0;i<nb_ostreams;i++) {
02009             double ipts, opts;
02010             ost = ost_table[i];
02011             os = output_files[ost->file_index];
02012             ist = ist_table[ost->source_index];
02013             if(ost->st->codec->codec_type == CODEC_TYPE_VIDEO)
02014                 opts = ost->sync_opts * av_q2d(ost->st->codec->time_base);
02015             else
02016                 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
02017             ipts = (double)ist->pts;
02018             if (!file_table[ist->file_index].eof_reached){
02019                 if(ipts < ipts_min) {
02020                     ipts_min = ipts;
02021                     if(input_sync ) file_index = ist->file_index;
02022                 }
02023                 if(opts < opts_min) {
02024                     opts_min = opts;
02025                     if(!input_sync) file_index = ist->file_index;
02026                 }
02027             }
02028             if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
02029                 file_index= -1;
02030                 break;
02031             }
02032         }
02033         /* if none, if is finished */
02034         if (file_index < 0) {
02035             break;
02036         }
02037 
02038         /* finish if recording time exhausted */
02039         if (recording_time > 0 && opts_min >= (recording_time / 1000000.0))
02040             break;
02041 
02042         /* finish if limit size exhausted */
02043         if (limit_filesize != 0 && (limit_filesize * 1024) < url_ftell(&output_files[0]->pb))
02044             break;
02045 
02046         /* read a frame from it and output it in the fifo */
02047         is = input_files[file_index];
02048         if (av_read_frame(is, &pkt) < 0) {
02049             file_table[file_index].eof_reached = 1;
02050             if (opt_shortest) break; else continue; //
02051         }
02052 
02053         if (!pkt.size) {
02054             stream_no_data = is;
02055         } else {
02056             stream_no_data = 0;
02057         }
02058         if (do_pkt_dump) {
02059             av_pkt_dump(stdout, &pkt, do_hex_dump);
02060         }
02061         /* the following test is needed in case new streams appear
02062            dynamically in stream : we ignore them */
02063         if (pkt.stream_index >= file_table[file_index].nb_streams)
02064             goto discard_packet;
02065         ist_index = file_table[file_index].ist_index + pkt.stream_index;
02066         ist = ist_table[ist_index];
02067         if (ist->discard)
02068             goto discard_packet;
02069 
02070 //        fprintf(stderr, "next:%lld dts:%lld off:%lld %d\n", ist->next_pts, pkt.dts, input_files_ts_offset[ist->file_index], ist->st->codec->codec_type);
02071         if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE) {
02072             int64_t delta= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q) - ist->next_pts;
02073             if(ABS(delta) > 10LL*AV_TIME_BASE && !copy_ts){
02074                 input_files_ts_offset[ist->file_index]-= delta;
02075                 if (verbose > 2)
02076                     fprintf(stderr, "timestamp discontinuity %lld, new offset= %lld\n", delta, input_files_ts_offset[ist->file_index]);
02077                 for(i=0; i<file_table[file_index].nb_streams; i++){
02078                     int index= file_table[file_index].ist_index + i;
02079                     ist_table[index]->next_pts += delta;
02080                     ist_table[index]->is_start=1;
02081                 }
02082             }
02083         }
02084 
02085         //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
02086         if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
02087 
02088             if (verbose >= 0)
02089                 fprintf(stderr, "Error while decoding stream #%d.%d\n",
02090                         ist->file_index, ist->index);
02091 
02092             av_free_packet(&pkt);
02093             goto redo;
02094         }
02095 
02096     discard_packet:
02097         av_free_packet(&pkt);
02098         
02099         /* dump report by using the output first video and audio streams */
02100         print_report(output_files, ost_table, nb_ostreams, 0);
02101     }
02102 
02103     /* at the end of stream, we must flush the decoder buffers */
02104     for(i=0;i<nb_istreams;i++) {
02105         ist = ist_table[i];
02106         if (ist->decoding_needed) {
02107             output_packet(ist, i, ost_table, nb_ostreams, NULL);
02108         }
02109     }
02110 
02111     term_exit();
02112 
02113     /* write the trailer if needed and close file */
02114     for(i=0;i<nb_output_files;i++) {
02115         os = output_files[i];
02116         av_write_trailer(os);
02117     }
02118 
02119     /* dump report by using the first video and audio streams */
02120     print_report(output_files, ost_table, nb_ostreams, 1);
02121 
02122     /* close each encoder */
02123     for(i=0;i<nb_ostreams;i++) {
02124         ost = ost_table[i];
02125         if (ost->encoding_needed) {
02126             av_freep(&ost->st->codec->stats_in);
02127             avcodec_close(ost->st->codec);
02128         }
02129     }
02130     
02131     /* close each decoder */
02132     for(i=0;i<nb_istreams;i++) {
02133         ist = ist_table[i];
02134         if (ist->decoding_needed) {
02135             avcodec_close(ist->st->codec);
02136         }
02137     }
02138 
02139     /* finished ! */
02140     
02141     ret = 0;
02142  fail1:
02143     av_freep(&bit_buffer);
02144     av_free(file_table);
02145 
02146     if (ist_table) {
02147         for(i=0;i<nb_istreams;i++) {
02148             ist = ist_table[i];
02149             av_free(ist);
02150         }
02151         av_free(ist_table);
02152     }
02153     if (ost_table) {
02154         for(i=0;i<nb_ostreams;i++) {
02155             ost = ost_table[i];
02156             if (ost) {
02157                 if (ost->logfile) {
02158                     fclose(ost->logfile);
02159                     ost->logfile = NULL;
02160                 }
02161                 fifo_free(&ost->fifo); /* works even if fifo is not
02162                                           initialized but set to zero */
02163                 av_free(ost->pict_tmp.data[0]);
02164                 if (ost->video_resample)
02165                     img_resample_close(ost->img_resample_ctx);
02166                 if (ost->audio_resample)
02167                     audio_resample_close(ost->resample);
02168                 av_free(ost);
02169             }
02170         }
02171         av_free(ost_table);
02172     }
02173     return ret;
02174  fail:
02175     ret = -ENOMEM;
02176     goto fail1;
02177 }
02178 
02179 #if 0
02180 int file_read(const char *filename)
02181 {
02182     URLContext *h;
02183     unsigned char buffer[1024];
02184     int len, i;
02185 
02186     if (url_open(&h, filename, O_RDONLY) < 0) {
02187         printf("could not open '%s'\n", filename);
02188         return -1;
02189     }
02190     for(;;) {
02191         len = url_read(h, buffer, sizeof(buffer));
02192         if (len <= 0)
02193             break;
02194         for(i=0;i<len;i++) putchar(buffer[i]);
02195     }
02196     url_close(h);
02197     return 0;
02198 }
02199 #endif
02200 
02201 static void opt_image_format(const char *arg)
02202 {
02203     AVImageFormat *f;
02204     
02205     for(f = first_image_format; f != NULL; f = f->next) {
02206         if (!strcmp(arg, f->name))
02207             break;
02208     }
02209     if (!f) {
02210         fprintf(stderr, "Unknown image format: '%s'\n", arg);
02211         exit(1);
02212     }
02213     image_format = f;
02214 }
02215 
02216 static void opt_format(const char *arg)
02217 {
02218     /* compatibility stuff for pgmyuv */
02219     if (!strcmp(arg, "pgmyuv")) {
02220         pgmyuv_compatibility_hack=1;
02221 //        opt_image_format(arg);
02222         arg = "image2";
02223     }
02224 
02225     file_iformat = av_find_input_format(arg);
02226     file_oformat = guess_format(arg, NULL, NULL);
02227     if (!file_iformat && !file_oformat) {
02228         fprintf(stderr, "Unknown input or output format: %s\n", arg);
02229         exit(1);
02230     }
02231 }
02232 
02233 static void opt_video_bitrate(const char *arg)
02234 {
02235     video_bit_rate = atoi(arg) * 1000;
02236 }
02237 
02238 static void opt_video_bitrate_tolerance(const char *arg)
02239 {
02240     video_bit_rate_tolerance = atoi(arg) * 1000;
02241 }
02242 
02243 static void opt_video_bitrate_max(const char *arg)
02244 {
02245     video_rc_max_rate = atoi(arg) * 1000;
02246 }
02247 
02248 static void opt_video_bitrate_min(const char *arg)
02249 {
02250     video_rc_min_rate = atoi(arg) * 1000;
02251 }
02252 
02253 static void opt_video_buffer_size(const char *arg)
02254 {
02255     video_rc_buffer_size = atoi(arg) * 8*1024;
02256 }
02257 
02258 static void opt_video_rc_eq(char *arg)
02259 {
02260     video_rc_eq = arg;
02261 }
02262 
02263 static void opt_video_rc_override_string(char *arg)
02264 {
02265     video_rc_override_string = arg;
02266 }
02267 
02268 
02269 static void opt_workaround_bugs(const char *arg)
02270 {
02271     workaround_bugs = atoi(arg);
02272 }
02273 
02274 static void opt_dct_algo(const char *arg)
02275 {
02276     dct_algo = atoi(arg);
02277 }
02278 
02279 static void opt_idct_algo(const char *arg)
02280 {
02281     idct_algo = atoi(arg);
02282 }
02283 
02284 static void opt_me_threshold(const char *arg)
02285 {
02286     me_threshold = atoi(arg);
02287 }
02288 
02289 static void opt_mb_threshold(const char *arg)
02290 {
02291     mb_threshold = atoi(arg);
02292 }
02293 
02294 static void opt_error_resilience(const char *arg)
02295 {
02296     error_resilience = atoi(arg);
02297 }
02298 
02299 static void opt_error_concealment(const char *arg)
02300 {
02301     error_concealment = atoi(arg);
02302 }
02303 
02304 static void opt_debug(const char *arg)
02305 {
02306     debug = atoi(arg);
02307     av_log_set_level(AV_LOG_DEBUG);
02308 }
02309 
02310 static void opt_vismv(const char *arg)
02311 {
02312     debug_mv = atoi(arg);
02313 }
02314     
02315 static void opt_verbose(const char *arg)
02316 {
02317     verbose = atoi(arg);
02318     av_log_set_level(atoi(arg));
02319 }
02320 
02321 static void opt_frame_rate(const char *arg)
02322 {
02323     if (parse_frame_rate(&frame_rate, &frame_rate_base, arg) < 0) {
02324         fprintf(stderr, "Incorrect frame rate\n");
02325         exit(1);
02326     }
02327 }
02328 
02329 static void opt_frame_crop_top(const char *arg)
02330 {
02331     frame_topBand = atoi(arg); 
02332     if (frame_topBand < 0) {
02333         fprintf(stderr, "Incorrect top crop size\n");
02334         exit(1);
02335     }
02336     if ((frame_topBand % 2) != 0) {
02337         fprintf(stderr, "Top crop size must be a multiple of 2\n");
02338         exit(1);
02339     }
02340     if ((frame_topBand) >= frame_height){
02341         fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
02342         exit(1);
02343     }
02344     frame_height -= frame_topBand;
02345 }
02346 
02347 static void opt_frame_crop_bottom(const char *arg)
02348 {
02349     frame_bottomBand = atoi(arg);
02350     if (frame_bottomBand < 0) {
02351         fprintf(stderr, "Incorrect bottom crop size\n");
02352         exit(1);
02353     }
02354     if ((frame_bottomBand % 2) != 0) {
02355         fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
02356         exit(1);        
02357     }
02358     if ((frame_bottomBand) >= frame_height){
02359         fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
02360         exit(1);
02361     }
02362     frame_height -= frame_bottomBand;
02363 }
02364 
02365 static void opt_frame_crop_left(const char *arg)
02366 {
02367     frame_leftBand = atoi(arg);
02368     if (frame_leftBand < 0) {
02369         fprintf(stderr, "Incorrect left crop size\n");
02370         exit(1);
02371     }
02372     if ((frame_leftBand % 2) != 0) {
02373         fprintf(stderr, "Left crop size must be a multiple of 2\n");
02374         exit(1);
02375     }
02376     if ((frame_leftBand) >= frame_width){
02377         fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
02378         exit(1);
02379     }
02380     frame_width -= frame_leftBand;
02381 }
02382 
02383 static void opt_frame_crop_right(const char *arg)
02384 {
02385     frame_rightBand = atoi(arg);
02386     if (frame_rightBand < 0) {
02387         fprintf(stderr, "Incorrect right crop size\n");
02388         exit(1);
02389     }
02390     if ((frame_rightBand % 2) != 0) {
02391         fprintf(stderr, "Right crop size must be a multiple of 2\n");
02392         exit(1);        
02393     }
02394     if ((frame_rightBand) >= frame_width){
02395         fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
02396         exit(1);
02397     }
02398     frame_width -= frame_rightBand;
02399 }
02400 
02401 static void opt_frame_size(const char *arg)
02402 {
02403     if (parse_image_size(&frame_width, &frame_height, arg) < 0) {
02404         fprintf(stderr, "Incorrect frame size\n");
02405         exit(1);
02406     }
02407     if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
02408         fprintf(stderr, "Frame size must be a multiple of 2\n");
02409         exit(1);
02410     }
02411 }
02412 
02413 
02414 #define SCALEBITS 10
02415 #define ONE_HALF  (1 << (SCALEBITS - 1))
02416 #define FIX(x)    ((int) ((x) * (1<<SCALEBITS) + 0.5))
02417 
02418 #define RGB_TO_Y(r, g, b) \
02419 ((FIX(0.29900) * (r) + FIX(0.58700) * (g) + \
02420   FIX(0.11400) * (b) + ONE_HALF) >> SCALEBITS)
02421 
02422 #define RGB_TO_U(r1, g1, b1, shift)\
02423 (((- FIX(0.16874) * r1 - FIX(0.33126) * g1 +         \
02424      FIX(0.50000) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
02425 
02426 #define RGB_TO_V(r1, g1, b1, shift)\
02427 (((FIX(0.50000) * r1 - FIX(0.41869) * g1 -           \
02428    FIX(0.08131) * b1 + (ONE_HALF << shift) - 1) >> (SCALEBITS + shift)) + 128)
02429 
02430 static void opt_pad_color(const char *arg) {
02431     /* Input is expected to be six hex digits similar to
02432        how colors are expressed in html tags (but without the #) */
02433     int rgb = strtol(arg, NULL, 16);
02434     int r,g,b;
02435     
02436     r = (rgb >> 16); 
02437     g = ((rgb >> 8) & 255);
02438     b = (rgb & 255);
02439 
02440     padcolor[0] = RGB_TO_Y(r,g,b);
02441     padcolor[1] = RGB_TO_U(r,g,b,0);
02442     padcolor[2] = RGB_TO_V(r,g,b,0);
02443 }
02444 
02445 static void opt_frame_pad_top(const char *arg)
02446 {
02447     frame_padtop = atoi(arg); 
02448     if (frame_padtop < 0) {
02449         fprintf(stderr, "Incorrect top pad size\n");
02450         exit(1);
02451     }
02452     if ((frame_padtop % 2) != 0) {
02453         fprintf(stderr, "Top pad size must be a multiple of 2\n");
02454         exit(1);
02455     }
02456 }
02457 
02458 static void opt_frame_pad_bottom(const char *arg)
02459 {
02460     frame_padbottom = atoi(arg); 
02461     if (frame_padbottom < 0) {
02462         fprintf(stderr, "Incorrect bottom pad size\n");
02463         exit(1);
02464     }
02465     if ((frame_padbottom % 2) != 0) {
02466         fprintf(stderr, "Bottom pad size must be a multiple of 2\n");
02467         exit(1);
02468     }
02469 }
02470 
02471 
02472 static void opt_frame_pad_left(const char *arg)
02473 {
02474     frame_padleft = atoi(arg); 
02475     if (frame_padleft < 0) {
02476         fprintf(stderr, "Incorrect left pad size\n");
02477         exit(1);
02478     }
02479     if ((frame_padleft % 2) != 0) {
02480         fprintf(stderr, "Left pad size must be a multiple of 2\n");
02481         exit(1);
02482     }
02483 }
02484 
02485 
02486 static void opt_frame_pad_right(const char *arg)
02487 {
02488     frame_padright = atoi(arg); 
02489     if (frame_padright < 0) {
02490         fprintf(stderr, "Incorrect right pad size\n");
02491         exit(1);
02492     }
02493     if ((frame_padright % 2) != 0) {
02494         fprintf(stderr, "Right pad size must be a multiple of 2\n");
02495         exit(1);
02496     }
02497 }
02498 
02499 
02500 static void opt_frame_pix_fmt(const char *arg)
02501 {
02502     frame_pix_fmt = avcodec_get_pix_fmt(arg);
02503 }
02504 
02505 static void opt_frame_aspect_ratio(const char *arg)
02506 {
02507     int x = 0, y = 0;
02508     double ar = 0;
02509     const char *p;
02510     
02511     p = strchr(arg, ':');
02512     if (p) {
02513         x = strtol(arg, (char **)&arg, 10);
02514         if (arg == p)
02515             y = strtol(arg+1, (char **)&arg, 10);
02516         if (x > 0 && y > 0)
02517             ar = (double)x / (double)y;
02518     } else
02519         ar = strtod(arg, (char **)&arg);
02520 
02521     if (!ar) {
02522         fprintf(stderr, "Incorrect aspect ratio specification.\n");
02523         exit(1);
02524     }
02525     frame_aspect_ratio = ar;
02526 }
02527 
02528 static void opt_gop_size(const char *arg)
02529 {
02530     gop_size = atoi(arg);
02531 }
02532 
02533 static void opt_b_frames(const char *arg)
02534 {
02535     b_frames = atoi(arg);
02536     if (b_frames > FF_MAX_B_FRAMES) {
02537         fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
02538         exit(1);
02539     } else if (b_frames < 1) {
02540         fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
02541         exit(1);
02542     }
02543 }
02544 
02545 static void opt_mb_decision(const char *arg)
02546 {
02547     mb_decision = atoi(arg);
02548 }
02549 
02550 static void opt_mb_cmp(const char *arg)
02551 {
02552     mb_cmp = atoi(arg);
02553 }
02554 
02555 static void opt_ildct_cmp(const char *arg)
02556 {
02557     ildct_cmp = atoi(arg);
02558 }
02559 
02560 static void opt_sub_cmp(const char *arg)
02561 {
02562     sub_cmp = atoi(arg);
02563 }
02564 
02565 static void opt_cmp(const char *arg)
02566 {
02567     cmp = atoi(arg);
02568 }
02569 
02570 static void opt_pre_cmp(const char *arg)
02571 {
02572     pre_cmp = atoi(arg);
02573 }
02574 
02575 static void opt_pre_me(const char *arg)
02576 {
02577     pre_me = atoi(arg);
02578 }
02579 
02580 static void opt_lumi_mask(const char *arg)
02581 {
02582     lumi_mask = atof(arg);
02583 }
02584 
02585 static void opt_dark_mask(const char *arg)
02586 {
02587     dark_mask = atof(arg);
02588 }
02589 
02590 static void opt_scplx_mask(const char *arg)
02591 {
02592     scplx_mask = atof(arg);
02593 }
02594 
02595 static void opt_tcplx_mask(const char *arg)
02596 {
02597     tcplx_mask = atof(arg);
02598 }
02599 
02600 static void opt_p_mask(const char *arg)
02601 {
02602     p_mask = atof(arg);
02603 }
02604 
02605 static void opt_qscale(const char *arg)
02606 {
02607     video_qscale = atof(arg);
02608     if (video_qscale < 0.01 ||
02609         video_qscale > 255) {
02610         fprintf(stderr, "qscale must be >= 0.01 and <= 255\n");
02611         exit(1);
02612     }
02613 }
02614 
02615 static void opt_qsquish(const char *arg)
02616 {
02617     video_qsquish = atof(arg);
02618     if (video_qsquish < 0.0 ||
02619         video_qsquish > 99.0) {
02620         fprintf(stderr, "qsquish must be >= 0.0 and <= 99.0\n");
02621         exit(1);
02622     }
02623 }
02624 
02625 static void opt_lelim(const char *arg)
02626 {
02627     video_lelim = atoi(arg);
02628     if (video_lelim < -99 ||
02629         video_lelim > 99) {
02630         fprintf(stderr, "lelim must be >= -99 and <= 99\n");
02631         exit(1);
02632     }
02633 }
02634 
02635 static void opt_celim(const char *arg)
02636 {
02637     video_celim = atoi(arg);
02638     if (video_celim < -99 ||
02639         video_celim > 99) {
02640         fprintf(stderr, "celim must be >= -99 and <= 99\n");
02641         exit(1);
02642     }
02643 }
02644 
02645 static void opt_lmax(const char *arg)
02646 {
02647     video_lmax = atof(arg)*FF_QP2LAMBDA;
02648 }
02649 
02650 static void opt_lmin(const char *arg)
02651 {
02652     video_lmin = atof(arg)*FF_QP2LAMBDA;
02653 }
02654 
02655 static void opt_qmin(const char *arg)
02656 {
02657     video_qmin = atoi(arg);
02658     if (video_qmin < 1 ||
02659         video_qmin > 31) {
02660         fprintf(stderr, "qmin must be >= 1 and <= 31\n");
02661         exit(1);
02662     }
02663 }
02664 
02665 static void opt_qmax(const char *arg)
02666 {
02667     video_qmax = atoi(arg);
02668     if (video_qmax < 1 ||
02669         video_qmax > 31) {
02670         fprintf(stderr, "qmax must be >= 1 and <= 31\n");
02671         exit(1);
02672     }
02673 }
02674 
02675 static void opt_mb_lmin(const char *arg)
02676 {
02677     video_mb_lmin = atof(arg)*FF_QP2LAMBDA;
02678     if (video_mb_lmin < 1 ||
02679         video_mb_lmin > FF_LAMBDA_MAX) {
02680         fprintf(stderr, "mblmin must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
02681         exit(1);
02682     }
02683 }
02684 
02685 static void opt_mb_lmax(const char *arg)
02686 {
02687     video_mb_lmax = atof(arg)*FF_QP2LAMBDA;
02688     if (video_mb_lmax < 1 ||
02689         video_mb_lmax > FF_LAMBDA_MAX) {
02690         fprintf(stderr, "mblmax must be >= 1 and <= %d\n", FF_LAMBDA_MAX / FF_QP2LAMBDA);
02691         exit(1);
02692     }
02693 }
02694 
02695 static void opt_qdiff(const char *arg)
02696 {
02697     video_qdiff = atoi(arg);
02698     if (video_qdiff < 0 ||
02699         video_qdiff > 31) {
02700         fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
02701         exit(1);
02702     }
02703 }
02704 
02705 static void opt_qblur(const char *arg)
02706 {
02707     video_qblur = atof(arg);
02708 }
02709 
02710 static void opt_qcomp(const char *arg)
02711 {
02712     video_qcomp = atof(arg);
02713 }
02714 
02715 static void opt_rc_initial_cplx(const char *arg)
02716 {
02717     video_rc_initial_cplx = atof(arg);
02718 }
02719 static void opt_b_qfactor(const char *arg)
02720 {
02721     video_b_qfactor = atof(arg);
02722 }
02723 static void opt_i_qfactor(const char *arg)
02724 {
02725     video_i_qfactor = atof(arg);
02726 }
02727 static void opt_b_qoffset(const char *arg)
02728 {
02729     video_b_qoffset = atof(arg);
02730 }
02731 static void opt_i_qoffset(const char *arg)
02732 {
02733     video_i_qoffset = atof(arg);
02734 }
02735 
02736 static void opt_ibias(const char *arg)
02737 {
02738     video_intra_quant_bias = atoi(arg);
02739 }
02740 static void opt_pbias(const char *arg)
02741 {
02742     video_inter_quant_bias = atoi(arg);
02743 }
02744 
02745 static void opt_packet_size(const char *arg)
02746 {
02747     packet_size= atoi(arg);
02748 }
02749 
02750 static void opt_error_rate(const char *arg)
02751 {
02752     error_rate= atoi(arg);
02753 }
02754 
02755 static void opt_strict(const char *arg)
02756 {
02757     strict= atoi(arg);
02758 }
02759 
02760 static void opt_top_field_first(const char *arg)
02761 {
02762     top_field_first= atoi(arg);
02763 }
02764 
02765 static void opt_noise_reduction(const char *arg)
02766 {
02767     noise_reduction= atoi(arg);
02768 }
02769 
02770 static void opt_qns(const char *arg)
02771 {
02772     qns= atoi(arg);
02773 }
02774 
02775 static void opt_sc_threshold(const char *arg)
02776 {
02777     sc_threshold= atoi(arg);
02778 }
02779 
02780 static void opt_me_range(const char *arg)
02781 {
02782     me_range = atoi(arg);
02783 }
02784 
02785 static void opt_thread_count(const char *arg)
02786 {
02787     thread_count= atoi(arg);
02788 #if !defined(HAVE_THREADS)
02789     if (verbose >= 0)
02790         fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
02791 #endif
02792 }
02793 
02794 static void opt_audio_bitrate(const char *arg)
02795 {
02796     audio_bit_rate = atoi(arg) * 1000;
02797 }
02798 
02799 static void opt_audio_rate(const char *arg)
02800 {
02801     audio_sample_rate = atoi(arg);
02802 }
02803 
02804 static void opt_audio_channels(const char *arg)
02805 {
02806     audio_channels = atoi(arg);
02807 }
02808 
02809 static void opt_video_device(const char *arg)
02810 {
02811     video_device = av_strdup(arg);
02812 }
02813 
02814 static void opt_grab_device(const char *arg)
02815 {
02816     grab_device = av_strdup(arg);
02817 }
02818 
02819 static void opt_video_channel(const char *arg)
02820 {
02821     video_channel = strtol(arg, NULL, 0);
02822 }
02823 
02824 static void opt_video_standard(const char *arg)
02825 {
02826     video_standard = av_strdup(arg);
02827 }
02828 
02829 static void opt_audio_device(const char *arg)
02830 {
02831     audio_device = av_strdup(arg);
02832 }
02833 
02834 static void opt_codec(int *pstream_copy, int *pcodec_id,
02835                       int codec_type, const char *arg)
02836 {
02837     AVCodec *p;
02838 
02839     if (!strcmp(arg, "copy")) {
02840         *pstream_copy = 1;
02841     } else {
02842         p = first_avcodec;
02843         while (p) {
02844             if (!strcmp(p->name, arg) && p->type == codec_type)
02845                 break;
02846             p = p->next;
02847         }
02848         if (p == NULL) {
02849             fprintf(stderr, "Unknown codec '%s'\n", arg);
02850             exit(1);
02851         } else {
02852             *pcodec_id = p->id;
02853         }
02854     }
02855 }
02856 
02857 static void opt_audio_codec(const char *arg)
02858 {
02859     opt_codec(&audio_stream_copy, &audio_codec_id, CODEC_TYPE_AUDIO, arg);
02860 }
02861 
02862 static void opt_audio_tag(const char *arg)
02863 {
02864     char *tail;
02865     audio_codec_tag= strtol(arg, &tail, 0);
02866 
02867     if(!tail || *tail)
02868         audio_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
02869 }
02870 
02871 static void opt_video_tag(const char *arg)
02872 {
02873     char *tail;
02874     video_codec_tag= strtol(arg, &tail, 0);
02875 
02876     if(!tail || *tail)
02877         video_codec_tag= arg[0] + (arg[1]<<8) + (arg[2]<<16) + (arg[3]<<24);
02878 }
02879 
02880 static void add_frame_hooker(const char *arg)
02881 {
02882     int argc = 0;
02883     char *argv[64];
02884     int i;
02885     char *args = av_strdup(arg);
02886 
02887     using_vhook = 1;
02888 
02889     argv[0] = strtok(args, " ");
02890     while (argc < 62 && (argv[++argc] = strtok(NULL, " "))) {
02891     }
02892 
02893     i = frame_hook_add(argc, argv);
02894 
02895     if (i != 0) {
02896         fprintf(stderr, "Failed to add video hook function: %s\n", arg);
02897         exit(1);
02898     }
02899 }
02900 
02901 const char *motion_str[] = {
02902     "zero",
02903     "full",
02904     "log",
02905     "phods",
02906     "epzs",
02907     "x1",
02908     NULL,
02909 };
02910 
02911 static void opt_motion_estimation(const char *arg)
02912 {
02913     const char **p;
02914     p = motion_str;
02915     for(;;) {
02916         if (!*p) {
02917             fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
02918             exit(1);
02919         }
02920         if (!strcmp(*p, arg))
02921             break;
02922         p++;
02923     }
02924     me_method = (p - motion_str) + 1;
02925 }
02926 
02927 static void opt_video_codec(const char *arg)
02928 {
02929     opt_codec(&video_stream_copy, &video_codec_id, CODEC_TYPE_VIDEO, arg);
02930 }
02931 
02932 static void opt_subtitle_codec(const char *arg)
02933 {
02934     opt_codec(&subtitle_stream_copy, &subtitle_codec_id, CODEC_TYPE_SUBTITLE, arg);
02935 }
02936 
02937 static void opt_map(const char *arg)
02938 {
02939     AVStreamMap *m;
02940     const char *p;
02941 
02942     p = arg;
02943     m = &stream_maps[nb_stream_maps++];
02944 
02945     m->file_index = strtol(arg, (char **)&p, 0);
02946     if (*p)
02947         p++;
02948 
02949     m->stream_index = strtol(p, (char **)&p, 0);
02950     if (*p) {
02951         p++;
02952         m->sync_file_index = strtol(p, (char **)&p, 0);
02953         if (*p)
02954             p++;
02955         m->sync_stream_index = strtol(p, (char **)&p, 0);
02956     } else {
02957         m->sync_file_index = m->file_index;
02958         m->sync_stream_index = m->stream_index;
02959     }
02960 }
02961 
02962 static void opt_map_meta_data(const char *arg)
02963 {
02964     AVMetaDataMap *m;
02965     const char *p;
02966         
02967     p = arg;
02968     m = &meta_data_maps[nb_meta_data_maps++];
02969 
02970     m->out_file = strtol(arg, (char **)&p, 0);
02971     if (*p)
02972         p++;
02973 
02974     m->in_file = strtol(p, (char **)&p, 0);
02975 }
02976 
02977 static void opt_recording_time(const char *arg)
02978 {
02979     recording_time = parse_date(arg, 1);
02980 }
02981 
02982 static void opt_start_time(const char *arg)
02983 {
02984     start_time = parse_date(arg, 1);
02985 }
02986 
02987 static void opt_rec_timestamp(const char *arg)
02988 {
02989     rec_timestamp = parse_date(arg, 0) / 1000000;
02990 }
02991 
02992 static void opt_input_ts_offset(const char *arg)
02993 {
02994     input_ts_offset = parse_date(arg, 1);
02995 }
02996 
02997 static void opt_input_file(const char *filename)
02998 {
02999     AVFormatContext *ic;
03000     AVFormatParameters params, *ap = &params;
03001     int err, i, ret, rfps, rfps_base;
03002     int64_t timestamp;
03003 
03004     if (!strcmp(filename, "-"))
03005         filename = "pipe:";
03006 
03007     using_stdin |= !strncmp(filename, "pipe:", 5) || 
03008                    !strcmp( filename, "/dev/stdin" );
03009 
03010     /* get default parameters from command line */
03011     memset(ap, 0, sizeof(*ap));
03012     ap->sample_rate = audio_sample_rate;
03013     ap->channels = audio_channels;
03014     ap->time_base.den = frame_rate;
03015     ap->time_base.num = frame_rate_base;
03016     ap->width = frame_width + frame_padleft + frame_padright;
03017     ap->height = frame_height + frame_padtop + frame_padbottom;
03018     ap->image_format = image_format;
03019     ap->pix_fmt = frame_pix_fmt;
03020     ap->device  = grab_device;
03021     ap->channel = video_channel;
03022     ap->standard = video_standard;
03023     ap->video_codec_id = video_codec_id;
03024     ap->audio_codec_id = audio_codec_id;
03025     if(pgmyuv_compatibility_hack)
03026         ap->video_codec_id= CODEC_ID_PGMYUV;
03027 
03028     /* open the input file with generic libav function */
03029     err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
03030     if (err < 0) {
03031         print_error(filename, err);
03032         exit(1);
03033     }
03034     
03035     /* If not enough info to get the stream parameters, we decode the
03036        first frames to get it. (used in mpeg case for example) */
03037     ret = av_find_stream_info(ic);
03038     if (ret < 0 && verbose >= 0) {
03039         fprintf(stderr, "%s: could not find codec parameters\n", filename);
03040         exit(1);
03041     }
03042 
03043     timestamp = start_time;
03044     /* add the stream start time */
03045     if (ic->start_time != AV_NOPTS_VALUE)
03046         timestamp += ic->start_time;
03047 
03048     /* if seeking requested, we execute it */
03049     if (start_time != 0) {
03050         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
03051         if (ret < 0) {
03052             fprintf(stderr, "%s: could not seek to position %0.3f\n", 
03053                     filename, (double)timestamp / AV_TIME_BASE);
03054         }
03055         /* reset seek info */
03056         start_time = 0;
03057     }
03058 
03059     /* update the current parameters so that they match the one of the input stream */
03060     for(i=0;i<ic->nb_streams;i++) {
03061         AVCodecContext *enc = ic->streams[i]->codec;
03062 #if defined(HAVE_THREADS)
03063         if(thread_count>1)
03064             avcodec_thread_init(enc, thread_count);
03065 #endif
03066         enc->thread_count= thread_count;
03067         switch(enc->codec_type) {
03068         case CODEC_TYPE_AUDIO:
03069             //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
03070             audio_channels = enc->channels;
03071             audio_sample_rate = enc->sample_rate;
03072             if(audio_disable)
03073                 ic->streams[i]->discard= AVDISCARD_ALL;
03074             break;
03075         case CODEC_TYPE_VIDEO:
03076             frame_height = enc->height;
03077             frame_width = enc->width;
03078             frame_aspect_ratio = av_q2d(enc->sample_aspect_ratio) * enc->width / enc->height;
03079             frame_pix_fmt = enc->pix_fmt;
03080             rfps      = ic->streams[i]->r_frame_rate.num;
03081             rfps_base = ic->streams[i]->r_frame_rate.den;
03082             enc->workaround_bugs = workaround_bugs;
03083             enc->error_resilience = error_resilience; 
03084             enc->error_concealment = error_concealment; 
03085             enc->idct_algo = idct_algo;
03086             enc->debug = debug;
03087             enc->debug_mv = debug_mv;            
03088             enc->lowres= lowres;
03089             if(lowres) enc->flags |= CODEC_FLAG_EMU_EDGE;
03090             if(bitexact)
03091                 enc->flags|= CODEC_FLAG_BITEXACT;
03092             if(me_threshold)
03093                 enc->debug |= FF_DEBUG_MV;
03094             if(gray_only)
03095                 enc->flags |= CODEC_FLAG_GRAY;
03096 
03097             if (enc->time_base.den != rfps || enc->time_base.num != rfps_base) { 
03098 
03099                 if (verbose >= 0)
03100                     fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
03101                             i, (float)enc->time_base.den / enc->time_base.num, enc->time_base.den, enc->time_base.num,
03102 
03103                     (float)rfps / rfps_base, rfps, rfps_base);
03104             }
03105             /* update the current frame rate to match the stream frame rate */
03106             frame_rate      = rfps;
03107             frame_rate_base = rfps_base;
03108 
03109             enc->rate_emu = rate_emu;
03110             if(video_disable)
03111                 ic->streams[i]->discard= AVDISCARD_ALL;
03112             else if(video_discard)
03113                 ic->streams[i]->discard= video_discard;
03114             break;
03115         case CODEC_TYPE_DATA:
03116             break;
03117         case CODEC_TYPE_SUBTITLE:
03118             break;
03119         default:
03120             av_abort();
03121         }
03122     }
03123     
03124     input_files[nb_input_files] = ic;
03125     input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
03126     /* dump the file content */
03127     if (verbose >= 0)
03128         dump_format(ic, nb_input_files, filename, 0);
03129 
03130     nb_input_files++;
03131     file_iformat = NULL;
03132     file_oformat = NULL;
03133     image_format = NULL;
03134 
03135     grab_device = NULL;
03136     video_channel = 0;
03137     
03138     rate_emu = 0;
03139 }
03140 
03141 static void opt_grab(const char *arg)
03142 {
03143     file_iformat = av_find_input_format(arg);
03144     opt_input_file("");
03145 }
03146 
03147 static void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
03148 {
03149     int has_video, has_audio, i, j;
03150     AVFormatContext *ic;
03151 
03152     has_video = 0;
03153     has_audio = 0;
03154     for(j=0;j<nb_input_files;j++) {
03155         ic = input_files[j];
03156         for(i=0;i<ic->nb_streams;i++) {
03157             AVCodecContext *enc = ic->streams[i]->codec;
03158             switch(enc->codec_type) {
03159             case CODEC_TYPE_AUDIO:
03160                 has_audio = 1;
03161                 break;
03162             case CODEC_TYPE_VIDEO:
03163                 has_video = 1;
03164                 break;
03165             case CODEC_TYPE_DATA:
03166             case CODEC_TYPE_SUBTITLE:
03167                 break;
03168             default:
03169                 av_abort();
03170             }
03171         }
03172     }
03173     *has_video_ptr = has_video;
03174     *has_audio_ptr = has_audio;
03175 }
03176 
03177 static void new_video_stream(AVFormatContext *oc)
03178 {
03179     AVStream *st;
03180     AVCodecContext *video_enc;
03181     int codec_id;
03182     
03183     st = av_new_stream(oc, oc->nb_streams);
03184     if (!st) {
03185         fprintf(stderr, "Could not alloc stream\n");
03186         exit(1);
03187     }
03188 #if defined(HAVE_THREADS)
03189     if(thread_count>1)
03190         avcodec_thread_init(st->codec, thread_count);
03191 #endif
03192     
03193     video_enc = st->codec;
03194     
03195     if(video_codec_tag)
03196         video_enc->codec_tag= video_codec_tag;
03197     
03198     if(   (video_global_header&1)
03199        || (video_global_header==0 && (oc->oformat->flags & AVFMT_GLOBALHEADER)))
03200         video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03201     if(video_global_header&2)
03202         video_enc->flags2 |= CODEC_FLAG2_LOCAL_HEADER;
03203 
03204     if (video_stream_copy) {
03205         st->stream_copy = 1;
03206         video_enc->codec_type = CODEC_TYPE_VIDEO;
03207     } else {
03208         char *p;
03209         int i;
03210         AVCodec *codec;
03211         
03212         codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_VIDEO);
03213         if (video_codec_id != CODEC_ID_NONE)
03214             codec_id = video_codec_id;
03215                 
03216         video_enc->codec_id = codec_id;
03217         codec = avcodec_find_encoder(codec_id);
03218                 
03219         video_enc->bit_rate = video_bit_rate;
03220         video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
03221         video_enc->time_base.den = frame_rate; 
03222         video_enc->time_base.num = frame_rate_base; 
03223         if(codec && codec->supported_framerates){
03224             const AVRational *p= codec->supported_framerates;
03225             AVRational req= (AVRational){frame_rate, frame_rate_base};
03226             const AVRational *best=NULL;
03227             AVRational best_error= (AVRational){INT_MAX, 1};
03228             for(; p->den!=0; p++){
03229                 AVRational error= av_sub_q(req, *p);
03230                 if(error.num <0) error.num *= -1;
03231                 if(av_cmp_q(error, best_error) < 0){
03232                     best_error= error;
03233                     best= p;
03234                 }
03235             }
03236             video_enc->time_base.den= best->num;
03237             video_enc->time_base.num= best->den;
03238         }
03239                 
03240         video_enc->width = frame_width + frame_padright + frame_padleft;
03241         video_enc->height = frame_height + frame_padtop + frame_padbottom;
03242         video_enc->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
03243         video_enc->pix_fmt = frame_pix_fmt;
03244 
03245         if(codec && codec->pix_fmts){
03246             const enum PixelFormat *p= codec->pix_fmts;
03247             for(; *p!=-1; p++){
03248                 if(*p == video_enc->pix_fmt)
03249                     break;
03250             }
03251             if(*p == -1)
03252                 video_enc->pix_fmt = codec->pix_fmts[0];
03253         }
03254 
03255         if (!intra_only)
03256             video_enc->gop_size = gop_size;
03257         else
03258             video_enc->gop_size = 0;
03259         if (video_qscale || same_quality) {
03260             video_enc->flags |= CODEC_FLAG_QSCALE;
03261             video_enc->global_quality= 
03262                 st->quality = FF_QP2LAMBDA * video_qscale;
03263         }
03264 
03265         if(intra_matrix)
03266             video_enc->intra_matrix = intra_matrix;
03267         if(inter_matrix)
03268             video_enc->inter_matrix = inter_matrix;
03269 
03270         if(bitexact)
03271             video_enc->flags |= CODEC_FLAG_BITEXACT;
03272 
03273         video_enc->mb_decision = mb_decision;
03274         video_enc->mb_cmp = mb_cmp;
03275         video_enc->ildct_cmp = ildct_cmp;
03276         video_enc->me_sub_cmp = sub_cmp;
03277         video_enc->me_cmp = cmp;
03278         video_enc->me_pre_cmp = pre_cmp;
03279         video_enc->pre_me = pre_me;
03280         video_enc->lumi_masking = lumi_mask;
03281         video_enc->dark_masking = dark_mask;
03282         video_enc->spatial_cplx_masking = scplx_mask;
03283         video_enc->temporal_cplx_masking = tcplx_mask;
03284         video_enc->p_masking = p_mask;
03285         video_enc->quantizer_noise_shaping= qns;
03286                 
03287         if (use_umv) {
03288             video_enc->flags |= CODEC_FLAG_H263P_UMV;
03289         }
03290         if (use_ss) {
03291             video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
03292         }
03293         if (use_aic) {
03294             video_enc->flags |= CODEC_FLAG_H263P_AIC;
03295         }
03296         if (use_aiv) {
03297             video_enc->flags |= CODEC_FLAG_H263P_AIV;
03298         }
03299         if (use_4mv) {
03300             video_enc->flags |= CODEC_FLAG_4MV;
03301         }
03302         if (use_obmc) {
03303             video_enc->flags |= CODEC_FLAG_OBMC;
03304         }
03305         if (use_loop) {
03306             video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
03307         }
03308             
03309         if(use_part) {
03310             video_enc->flags |= CODEC_FLAG_PART;
03311         }
03312         if (use_alt_scan) {
03313             video_enc->flags |= CODEC_FLAG_ALT_SCAN;
03314         }
03315         if (use_trell) {
03316             video_enc->flags |= CODEC_FLAG_TRELLIS_QUANT;
03317         }
03318         if (use_mv0) {
03319             video_enc->flags |= CODEC_FLAG_MV0;
03320         }
03321         if (do_normalize_aqp) {
03322             video_enc->flags |= CODEC_FLAG_NORMALIZE_AQP;
03323         }
03324         if (use_scan_offset) {
03325             video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
03326         }
03327         if (closed_gop) {
03328             video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
03329         }
03330         if (strict_gop) {
03331             video_enc->flags2 |= CODEC_FLAG2_STRICT_GOP;
03332         }
03333         if (use_qpel) {
03334             video_enc->flags |= CODEC_FLAG_QPEL;
03335         }
03336         if (use_qprd) {
03337             video_enc->flags |= CODEC_FLAG_QP_RD;
03338         }
03339         if (use_cbprd) {
03340             video_enc->flags |= CODEC_FLAG_CBP_RD;
03341         }
03342         if (b_frames) {
03343             video_enc->max_b_frames = b_frames;
03344             video_enc->b_frame_strategy = b_strategy;
03345             video_enc->b_quant_factor = 2.0;
03346         }
03347         if (do_interlace_dct) {
03348             video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
03349         }
03350         if (do_interlace_me) {
03351             video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
03352         }
03353         if (no_output) {
03354             video_enc->flags2 |= CODEC_FLAG2_NO_OUTPUT;
03355         }
03356         if (gray_only) {
03357             video_enc->flags |= CODEC_FLAG_GRAY;
03358         }
03359         video_enc->qmin = video_qmin;
03360         video_enc->qmax = video_qmax;
03361         video_enc->lmin = video_lmin;
03362         video_enc->lmax = video_lmax;
03363         video_enc->rc_qsquish = video_qsquish;
03364         video_enc->luma_elim_threshold = video_lelim;
03365         video_enc->chroma_elim_threshold = video_celim;
03366         video_enc->mb_lmin = video_mb_lmin;
03367         video_enc->mb_lmax = video_mb_lmax;
03368         video_enc->max_qdiff = video_qdiff;
03369         video_enc->qblur = video_qblur;
03370         video_enc->qcompress = video_qcomp;
03371         video_enc->rc_eq = video_rc_eq;
03372         video_enc->debug = debug;
03373         video_enc->debug_mv = debug_mv;
03374         video_enc->workaround_bugs = workaround_bugs;
03375         video_enc->thread_count = thread_count;
03376         p= video_rc_override_string;
03377         for(i=0; p; i++){
03378             int start, end, q;
03379             int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
03380             if(e!=3){
03381                 fprintf(stderr, "error parsing rc_override\n");
03382                 exit(1);
03383             }
03384             video_enc->rc_override= 
03385                 av_realloc(video_enc->rc_override, 
03386                            sizeof(RcOverride)*(i+1));
03387             video_enc->rc_override[i].start_frame= start;
03388             video_enc->rc_override[i].end_frame  = end;
03389             if(q>0){
03390                 video_enc->rc_override[i].qscale= q;
03391                 video_enc->rc_override[i].quality_factor= 1.0;
03392             }
03393             else{
03394                 video_enc->rc_override[i].qscale= 0;
03395                 video_enc->rc_override[i].quality_factor= -q/100.0;
03396             }
03397             p= strchr(p, '/');
03398             if(p) p++;
03399         }
03400         video_enc->rc_override_count=i;
03401 
03402         video_enc->rc_max_rate = video_rc_max_rate;
03403         video_enc->rc_min_rate = video_rc_min_rate;
03404         video_enc->rc_buffer_size = video_rc_buffer_size;
03405         video_enc->rc_initial_buffer_occupancy = video_rc_buffer_size*3/4;
03406         video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
03407         video_enc->rc_initial_cplx= video_rc_initial_cplx;
03408         video_enc->i_quant_factor = video_i_qfactor;
03409         video_enc->b_quant_factor = video_b_qfactor;
03410         video_enc->i_quant_offset = video_i_qoffset;
03411         video_enc->b_quant_offset = video_b_qoffset;
03412         video_enc->intra_quant_bias = video_intra_quant_bias;
03413         video_enc->inter_quant_bias = video_inter_quant_bias;
03414         video_enc->dct_algo = dct_algo;
03415         video_enc->idct_algo = idct_algo;
03416         video_enc->me_threshold= me_threshold;
03417         video_enc->mb_threshold= mb_threshold;
03418         video_enc->intra_dc_precision= intra_dc_precision - 8;
03419         video_enc->strict_std_compliance = strict;
03420         video_enc->error_rate = error_rate;
03421         video_enc->noise_reduction= noise_reduction;
03422         video_enc->scenechange_threshold= sc_threshold;
03423         video_enc->me_range = me_range;
03424         video_enc->coder_type= coder;
03425         video_enc->context_model= context;
03426         video_enc->prediction_method= predictor;
03427         video_enc->profile= video_profile;
03428         video_enc->level= video_level;
03429         video_enc->nsse_weight= nsse_weight;
03430         video_enc->me_subpel_quality= subpel_quality;
03431         video_enc->me_penalty_compensation= me_penalty_compensation;
03432         video_enc->frame_skip_threshold= frame_skip_threshold;
03433         video_enc->frame_skip_factor= frame_skip_factor;
03434         video_enc->frame_skip_exp= frame_skip_exp;
03435         video_enc->frame_skip_cmp= frame_skip_cmp;
03436 
03437         if(packet_size){
03438             video_enc->rtp_mode= 1;
03439             video_enc->rtp_payload_size= packet_size;
03440         }
03441             
03442         if (do_psnr)
03443             video_enc->flags|= CODEC_FLAG_PSNR;
03444             
03445         video_enc->me_method = me_method;
03446 
03447         /* two pass mode */
03448         if (do_pass) {
03449             if (do_pass == 1) {
03450                 video_enc->flags |= CODEC_FLAG_PASS1;
03451             } else {
03452                 video_enc->flags |= CODEC_FLAG_PASS2;
03453             }
03454         }
03455     }
03456 
03457     /* reset some key parameters */
03458     video_disable = 0;
03459     video_codec_id = CODEC_ID_NONE;
03460     video_stream_copy = 0;
03461 }
03462 
03463 static void new_audio_stream(AVFormatContext *oc)
03464 {
03465     AVStream *st;
03466     AVCodecContext *audio_enc;
03467     int codec_id;
03468             
03469     st = av_new_stream(oc, oc->nb_streams);
03470     if (!st) {
03471         fprintf(stderr, "Could not alloc stream\n");
03472         exit(1);
03473     }
03474 #if defined(HAVE_THREADS)
03475     if(thread_count>1)
03476         avcodec_thread_init(st->codec, thread_count);
03477 #endif
03478     
03479     audio_enc = st->codec;
03480     audio_enc->codec_type = CODEC_TYPE_AUDIO;
03481     
03482     if(audio_codec_tag)
03483         audio_enc->codec_tag= audio_codec_tag;
03484     
03485     if (oc->oformat->flags & AVFMT_GLOBALHEADER) 
03486         audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03487     if (audio_stream_copy) {
03488         st->stream_copy = 1;
03489         audio_enc->channels = audio_channels;
03490     } else {
03491         codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, CODEC_TYPE_AUDIO);
03492         if (audio_codec_id != CODEC_ID_NONE)
03493             codec_id = audio_codec_id;
03494         audio_enc->codec_id = codec_id;
03495         
03496         audio_enc->bit_rate = audio_bit_rate;
03497         audio_enc->strict_std_compliance = strict;
03498         audio_enc->thread_count = thread_count;
03499         /* For audio codecs other than AC3 or DTS we limit */
03500         /* the number of coded channels to stereo   */
03501         if (audio_channels > 2 && codec_id != CODEC_ID_AC3
03502             && codec_id != CODEC_ID_DTS) {
03503             audio_enc->channels = 2;
03504         } else
03505             audio_enc->channels = audio_channels;
03506     }
03507     audio_enc->sample_rate = audio_sample_rate;
03508     if (audio_language) {
03509         pstrcpy(st->language, sizeof(st->language), audio_language);
03510         av_free(audio_language);
03511         audio_language = NULL;
03512     }
03513 
03514     /* reset some key parameters */
03515     audio_disable = 0;
03516     audio_codec_id = CODEC_ID_NONE;
03517     audio_stream_copy = 0;
03518 }
03519 
03520 static void opt_new_subtitle_stream(void)
03521 {
03522     AVFormatContext *oc;
03523     AVStream *st;
03524     AVCodecContext *subtitle_enc;
03525             
03526     if (nb_output_files <= 0) {
03527         fprintf(stderr, "At least one output file must be specified\n");
03528         exit(1);
03529     }
03530     oc = output_files[nb_output_files - 1];
03531 
03532     st = av_new_stream(oc, oc->nb_streams);
03533     if (!st) {
03534         fprintf(stderr, "Could not alloc stream\n");
03535         exit(1);
03536     }
03537 
03538     subtitle_enc = st->codec;
03539     subtitle_enc->codec_type = CODEC_TYPE_SUBTITLE;
03540     if (subtitle_stream_copy) {
03541         st->stream_copy = 1;
03542     } else {
03543         subtitle_enc->codec_id = subtitle_codec_id;
03544     }
03545 
03546     if (subtitle_language) {
03547         pstrcpy(st->language, sizeof(st->language), subtitle_language);
03548         av_free(subtitle_language);
03549         subtitle_language = NULL;
03550     }
03551 
03552     subtitle_codec_id = CODEC_ID_NONE;
03553     subtitle_stream_copy = 0;
03554 }
03555 
03556 static void opt_new_audio_stream(void)
03557 {
03558     AVFormatContext *oc;
03559     if (nb_output_files <= 0) {
03560         fprintf(stderr, "At least one output file must be specified\n");
03561         exit(1);
03562     }
03563     oc = output_files[nb_output_files - 1];
03564     new_audio_stream(oc);
03565 }
03566 
03567 static void opt_new_video_stream(void)
03568 {
03569     AVFormatContext *oc;
03570     if (nb_output_files <= 0) {
03571         fprintf(stderr, "At least one output file must be specified\n");
03572         exit(1);
03573     }
03574     oc = output_files[nb_output_files - 1];
03575     new_video_stream(oc);
03576 }
03577 
03578 static void opt_output_file(const char *filename)
03579 {
03580     AVFormatContext *oc;
03581     int use_video, use_audio, input_has_video, input_has_audio;
03582     AVFormatParameters params, *ap = &params;
03583 
03584     if (!strcmp(filename, "-"))
03585         filename = "pipe:";
03586 
03587     oc = av_alloc_format_context();
03588 
03589     if (!file_oformat) {
03590         file_oformat = guess_format(NULL, filename, NULL);
03591         if (!file_oformat) {
03592             fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
03593                     filename);
03594             exit(1);
03595         }
03596     }
03597     
03598     oc->oformat = file_oformat;
03599     pstrcpy(oc->filename, sizeof(oc->filename), filename);
03600 
03601     if (!strcmp(file_oformat->name, "ffm") && 
03602         strstart(filename, "http:", NULL)) {
03603         /* special case for files sent to ffserver: we get the stream
03604            parameters from ffserver */
03605         if (read_ffserver_streams(oc, filename) < 0) {
03606             fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
03607             exit(1);
03608         }
03609     } else {
03610         use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_id != CODEC_ID_NONE;
03611         use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_id != CODEC_ID_NONE;
03612 
03613         /* disable if no corresponding type found and at least one
03614            input file */
03615         if (nb_input_files > 0) {
03616             check_audio_video_inputs(&input_has_video, &input_has_audio);
03617             if (!input_has_video)
03618                 use_video = 0;
03619             if (!input_has_audio)
03620                 use_audio = 0;
03621         }
03622 
03623         /* manual disable */
03624         if (audio_disable) {
03625             use_audio = 0;
03626         }
03627         if (video_disable) {
03628             use_video = 0;
03629         }
03630         
03631         if (use_video) {
03632             new_video_stream(oc);
03633         }
03634     
03635         if (use_audio) {
03636             new_audio_stream(oc);
03637         }
03638 
03639         if (!oc->nb_streams) {
03640             fprintf(stderr, "No audio or video streams available\n");
03641             exit(1);
03642         }
03643 
03644         oc->timestamp = rec_timestamp;
03645             
03646         if (str_title)
03647             pstrcpy(oc->title, sizeof(oc->title), str_title);
03648         if (str_author)
03649             pstrcpy(oc->author, sizeof(oc->author), str_author);
03650         if (str_copyright)
03651             pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
03652         if (str_comment)
03653             pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
03654     }
03655 
03656     output_files[nb_output_files++] = oc;
03657 
03658     /* check filename in case of an image number is expected */
03659     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
03660         if (filename_number_test(oc->filename) < 0) {
03661             print_error(oc->filename, AVERROR_NUMEXPECTED);
03662             exit(1);
03663         }
03664     }
03665 
03666     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
03667         /* test if it already exists to avoid loosing precious files */
03668         if (!file_overwrite && 
03669             (strchr(filename, ':') == NULL ||
03670              strstart(filename, "file:", NULL))) {
03671             if (url_exist(filename)) {
03672                 int c;
03673                 
03674                 if ( !using_stdin ) {
03675                     fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
03676                     fflush(stderr);
03677                     c = getchar();
03678                     if (toupper(c) != 'Y') {
03679                         fprintf(stderr, "Not overwriting - exiting\n");
03680                         exit(1);
03681                     }
03682                                 }
03683                                 else {
03684                     fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
03685                     exit(1);
03686                                 }
03687             }
03688         }
03689         
03690         /* open the file */
03691         if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
03692             fprintf(stderr, "Could not open '%s'\n", filename);
03693             exit(1);
03694         }
03695     }
03696 
03697     memset(ap, 0, sizeof(*ap));
03698     ap->image_format = image_format;
03699     if (av_set_parameters(oc, ap) < 0) {
03700         fprintf(stderr, "%s: Invalid encoding parameters\n",
03701                 oc->filename);
03702         exit(1);
03703     }
03704 
03705     oc->packet_size= mux_packet_size;
03706     oc->mux_rate= mux_rate;
03707     oc->preload= (int)(mux_preload*AV_TIME_BASE);
03708     oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
03709     oc->loop_output = loop_output;
03710 
03711     /* reset some options */
03712     file_oformat = NULL;
03713     file_iformat = NULL;
03714     image_format = NULL;
03715 }
03716 
03717 /* prepare dummy protocols for grab */
03718 static void prepare_grab(void)
03719 {
03720     int has_video, has_audio, i, j;
03721     AVFormatContext *oc;
03722     AVFormatContext *ic;
03723     AVFormatParameters vp1, *vp = &vp1;
03724     AVFormatParameters ap1, *ap = &ap1;
03725     
03726     /* see if audio/video inputs are needed */
03727     has_video = 0;
03728     has_audio = 0;
03729     memset(ap, 0, sizeof(*ap));
03730     memset(vp, 0, sizeof(*vp));
03731     vp->time_base.num= 1;
03732     for(j=0;j<nb_output_files;j++) {
03733         oc = output_files[j];
03734         for(i=0;i<oc->nb_streams;i++) {
03735             AVCodecContext *enc = oc->streams[i]->codec;
03736             switch(enc->codec_type) {
03737             case CODEC_TYPE_AUDIO:
03738                 if (enc->sample_rate > ap->sample_rate)
03739                     ap->sample_rate = enc->sample_rate;
03740                 if (enc->channels > ap->channels)
03741                     ap->channels = enc->channels;
03742                 has_audio = 1;
03743                 break;
03744             case CODEC_TYPE_VIDEO:
03745                 if