• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • File List
  • Globals

ffmpeg.c

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

Generated on Sat Feb 16 2013 09:23:11 for ffmpeg by  doxygen 1.7.1