• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • Examples
  • 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 #include "config.h"
00023 #include <ctype.h>
00024 #include <string.h>
00025 #include <math.h>
00026 #include <stdlib.h>
00027 #include <errno.h>
00028 #include <signal.h>
00029 #include <limits.h>
00030 #include <unistd.h>
00031 #include "libavformat/avformat.h"
00032 #include "libavdevice/avdevice.h"
00033 #include "libswscale/swscale.h"
00034 #include "libavcodec/opt.h"
00035 #include "libavcodec/audioconvert.h"
00036 #include "libavutil/audioconvert.h"
00037 #include "libavutil/parseutils.h"
00038 #include "libavutil/samplefmt.h"
00039 #include "libavutil/colorspace.h"
00040 #include "libavutil/fifo.h"
00041 #include "libavutil/intreadwrite.h"
00042 #include "libavutil/dict.h"
00043 #include "libavutil/pixdesc.h"
00044 #include "libavutil/avstring.h"
00045 #include "libavutil/libm.h"
00046 #include "libavformat/os_support.h"
00047 
00048 #include "libavformat/ffm.h" // not public API
00049 
00050 #if CONFIG_AVFILTER
00051 # include "libavfilter/avcodec.h"
00052 # include "libavfilter/avfilter.h"
00053 # include "libavfilter/avfiltergraph.h"
00054 # include "libavfilter/vsink_buffer.h"
00055 # include "libavfilter/vsrc_buffer.h"
00056 #endif
00057 
00058 #if HAVE_SYS_RESOURCE_H
00059 #include <sys/types.h>
00060 #include <sys/time.h>
00061 #include <sys/resource.h>
00062 #elif HAVE_GETPROCESSTIMES
00063 #include <windows.h>
00064 #endif
00065 #if HAVE_GETPROCESSMEMORYINFO
00066 #include <windows.h>
00067 #include <psapi.h>
00068 #endif
00069 
00070 #if HAVE_SYS_SELECT_H
00071 #include <sys/select.h>
00072 #endif
00073 
00074 #if HAVE_TERMIOS_H
00075 #include <fcntl.h>
00076 #include <sys/ioctl.h>
00077 #include <sys/time.h>
00078 #include <termios.h>
00079 #elif HAVE_KBHIT
00080 #include <conio.h>
00081 #endif
00082 #include <time.h>
00083 
00084 #include "cmdutils.h"
00085 
00086 #include "libavutil/avassert.h"
00087 
00088 const char program_name[] = "ffmpeg";
00089 const int program_birth_year = 2000;
00090 
00091 /* select an input stream for an output stream */
00092 typedef struct AVStreamMap {
00093     int file_index;
00094     int stream_index;
00095     int sync_file_index;
00096     int sync_stream_index;
00097 } AVStreamMap;
00098 
00102 typedef struct AVMetaDataMap {
00103     int  file;      //< file index
00104     char type;      //< type of metadata to copy -- (g)lobal, (s)tream, (c)hapter or (p)rogram
00105     int  index;     //< stream/chapter/program number
00106 } AVMetaDataMap;
00107 
00108 typedef struct AVChapterMap {
00109     int in_file;
00110     int out_file;
00111 } AVChapterMap;
00112 
00113 static const OptionDef options[];
00114 
00115 #define MAX_FILES 100
00116 #if !FF_API_MAX_STREAMS
00117 #define MAX_STREAMS 1024    /* arbitrary sanity check value */
00118 #endif
00119 
00120 static const char *last_asked_format = NULL;
00121 static int64_t input_files_ts_offset[MAX_FILES];
00122 static double *input_files_ts_scale[MAX_FILES] = {NULL};
00123 static AVCodec **input_codecs = NULL;
00124 static int nb_input_codecs = 0;
00125 static int nb_input_files_ts_scale[MAX_FILES] = {0};
00126 
00127 static AVFormatContext *output_files[MAX_FILES];
00128 static int nb_output_files = 0;
00129 
00130 static AVStreamMap *stream_maps = NULL;
00131 static int nb_stream_maps;
00132 
00133 /* first item specifies output metadata, second is input */
00134 static AVMetaDataMap (*meta_data_maps)[2] = NULL;
00135 static int nb_meta_data_maps;
00136 static int metadata_global_autocopy   = 1;
00137 static int metadata_streams_autocopy  = 1;
00138 static int metadata_chapters_autocopy = 1;
00139 
00140 static AVChapterMap *chapter_maps = NULL;
00141 static int nb_chapter_maps;
00142 
00143 /* indexed by output file stream index */
00144 static int *streamid_map = NULL;
00145 static int nb_streamid_map = 0;
00146 
00147 static int frame_width  = 0;
00148 static int frame_height = 0;
00149 static float frame_aspect_ratio = 0;
00150 static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
00151 static int frame_bits_per_raw_sample = 0;
00152 static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
00153 static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
00154 static AVRational frame_rate;
00155 static float video_qscale = 0;
00156 static uint16_t *intra_matrix = NULL;
00157 static uint16_t *inter_matrix = NULL;
00158 static const char *video_rc_override_string=NULL;
00159 static int video_disable = 0;
00160 static int video_discard = 0;
00161 static char *video_codec_name = NULL;
00162 static unsigned int video_codec_tag = 0;
00163 static char *video_language = NULL;
00164 static int same_quality = 0;
00165 static int do_deinterlace = 0;
00166 static int top_field_first = -1;
00167 static int me_threshold = 0;
00168 static int intra_dc_precision = 8;
00169 static int loop_input = 0;
00170 static int loop_output = AVFMT_NOOUTPUTLOOP;
00171 static int qp_hist = 0;
00172 #if CONFIG_AVFILTER
00173 static char *vfilters = NULL;
00174 #endif
00175 
00176 static int intra_only = 0;
00177 static int audio_sample_rate = 0;
00178 static int64_t channel_layout = 0;
00179 #define QSCALE_NONE -99999
00180 static float audio_qscale = QSCALE_NONE;
00181 static int audio_disable = 0;
00182 static int audio_channels = 0;
00183 static char  *audio_codec_name = NULL;
00184 static unsigned int audio_codec_tag = 0;
00185 static char *audio_language = NULL;
00186 
00187 static int subtitle_disable = 0;
00188 static char *subtitle_codec_name = NULL;
00189 static char *subtitle_language = NULL;
00190 static unsigned int subtitle_codec_tag = 0;
00191 
00192 static int data_disable = 0;
00193 static char *data_codec_name = NULL;
00194 static unsigned int data_codec_tag = 0;
00195 
00196 static float mux_preload= 0.5;
00197 static float mux_max_delay= 0.7;
00198 
00199 static int64_t recording_time = INT64_MAX;
00200 static int64_t start_time = 0;
00201 static int64_t recording_timestamp = 0;
00202 static int64_t input_ts_offset = 0;
00203 static int file_overwrite = 0;
00204 static AVDictionary *metadata;
00205 static int do_benchmark = 0;
00206 static int do_hex_dump = 0;
00207 static int do_pkt_dump = 0;
00208 static int do_psnr = 0;
00209 static int do_pass = 0;
00210 static const char *pass_logfilename_prefix;
00211 static int audio_stream_copy = 0;
00212 static int video_stream_copy = 0;
00213 static int subtitle_stream_copy = 0;
00214 static int data_stream_copy = 0;
00215 static int video_sync_method= -1;
00216 static int audio_sync_method= 0;
00217 static float audio_drift_threshold= 0.1;
00218 static int copy_ts= 0;
00219 static int copy_tb= 0;
00220 static int opt_shortest = 0;
00221 static char *vstats_filename;
00222 static FILE *vstats_file;
00223 static int opt_programid = 0;
00224 static int copy_initial_nonkeyframes = 0;
00225 
00226 static int rate_emu = 0;
00227 
00228 static int  video_channel = 0;
00229 static char *video_standard;
00230 
00231 static int audio_volume = 256;
00232 
00233 static int exit_on_error = 0;
00234 static int using_stdin = 0;
00235 static int verbose = 1;
00236 static int run_as_daemon  = 0;
00237 static int thread_count= 1;
00238 static int q_pressed = 0;
00239 static int64_t video_size = 0;
00240 static int64_t audio_size = 0;
00241 static int64_t extra_size = 0;
00242 static int nb_frames_dup = 0;
00243 static int nb_frames_drop = 0;
00244 static int input_sync;
00245 static uint64_t limit_filesize = 0;
00246 static int force_fps = 0;
00247 static char *forced_key_frames = NULL;
00248 
00249 static float dts_delta_threshold = 10;
00250 
00251 static int64_t timer_start;
00252 
00253 static uint8_t *audio_buf;
00254 static uint8_t *audio_out;
00255 static unsigned int allocated_audio_out_size, allocated_audio_buf_size;
00256 
00257 static short *samples;
00258 
00259 static AVBitStreamFilterContext *video_bitstream_filters=NULL;
00260 static AVBitStreamFilterContext *audio_bitstream_filters=NULL;
00261 static AVBitStreamFilterContext *subtitle_bitstream_filters=NULL;
00262 
00263 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
00264 
00265 struct AVInputStream;
00266 
00267 typedef struct AVOutputStream {
00268     int file_index;          /* file index */
00269     int index;               /* stream index in the output file */
00270     int source_index;        /* AVInputStream index */
00271     AVStream *st;            /* stream in the output file */
00272     int encoding_needed;     /* true if encoding needed for this stream */
00273     int frame_number;
00274     /* input pts and corresponding output pts
00275        for A/V sync */
00276     //double sync_ipts;        /* dts from the AVPacket of the demuxer in second units */
00277     struct AVInputStream *sync_ist; /* input stream to sync against */
00278     int64_t sync_opts;       /* output frame counter, could be changed to some true timestamp */ //FIXME look at frame_number
00279     AVBitStreamFilterContext *bitstream_filters;
00280     AVCodec *enc;
00281 
00282     /* video only */
00283     int video_resample;
00284     AVFrame resample_frame;              /* temporary frame for image resampling */
00285     struct SwsContext *img_resample_ctx; /* for image resampling */
00286     int resample_height;
00287     int resample_width;
00288     int resample_pix_fmt;
00289     AVRational frame_rate;
00290 
00291     float frame_aspect_ratio;
00292 
00293     /* forced key frames */
00294     int64_t *forced_kf_pts;
00295     int forced_kf_count;
00296     int forced_kf_index;
00297 
00298     /* audio only */
00299     int audio_resample;
00300     ReSampleContext *resample; /* for audio resampling */
00301     int resample_sample_fmt;
00302     int resample_channels;
00303     int resample_sample_rate;
00304     int reformat_pair;
00305     AVAudioConvert *reformat_ctx;
00306     AVFifoBuffer *fifo;     /* for compression: one audio fifo per codec */
00307     FILE *logfile;
00308 
00309 #if CONFIG_AVFILTER
00310     AVFilterContext *output_video_filter;
00311     AVFilterContext *input_video_filter;
00312     AVFilterBufferRef *picref;
00313     char *avfilter;
00314     AVFilterGraph *graph;
00315 #endif
00316 
00317    int sws_flags;
00318    char *forced_key_frames;
00319 } AVOutputStream;
00320 
00321 static AVOutputStream **output_streams_for_file[MAX_FILES] = { NULL };
00322 static int nb_output_streams_for_file[MAX_FILES] = { 0 };
00323 
00324 typedef struct AVInputStream {
00325     int file_index;
00326     AVStream *st;
00327     int discard;             /* true if stream data should be discarded */
00328     int decoding_needed;     /* true if the packets must be decoded in 'raw_fifo' */
00329     int64_t sample_index;      /* current sample */
00330 
00331     int64_t       start;     /* time when read started */
00332     int64_t       next_pts;  /* synthetic pts for cases where pkt.pts
00333                                 is not defined */
00334     int64_t       pts;       /* current pts */
00335     int is_start;            /* is 1 at the start and after a discontinuity */
00336     int showed_multi_packet_warning;
00337     int is_past_recording_time;
00338 #if CONFIG_AVFILTER
00339     AVFrame *filter_frame;
00340     int has_filter_frame;
00341 #endif
00342 } AVInputStream;
00343 
00344 typedef struct AVInputFile {
00345     AVFormatContext *ctx;
00346     int eof_reached;      /* true if eof reached */
00347     int ist_index;        /* index of first stream in ist_table */
00348     int buffer_size;      /* current total buffer size */
00349     int nb_streams;       /* nb streams we are aware of */
00350 } AVInputFile;
00351 
00352 #if HAVE_TERMIOS_H
00353 
00354 /* init terminal so that we can grab keys */
00355 static struct termios oldtty;
00356 #endif
00357 
00358 static AVInputStream *input_streams = NULL;
00359 static int         nb_input_streams = 0;
00360 static AVInputFile   *input_files   = NULL;
00361 static int         nb_input_files   = 0;
00362 
00363 #if CONFIG_AVFILTER
00364 
00365 static int configure_video_filters(AVInputStream *ist, AVOutputStream *ost)
00366 {
00367     AVFilterContext *last_filter, *filter;
00369     AVCodecContext *codec = ost->st->codec;
00370     AVCodecContext *icodec = ist->st->codec;
00371     enum PixelFormat pix_fmts[] = { codec->pix_fmt, PIX_FMT_NONE };
00372     AVRational sample_aspect_ratio;
00373     char args[255];
00374     int ret;
00375 
00376     ost->graph = avfilter_graph_alloc();
00377 
00378     if (ist->st->sample_aspect_ratio.num){
00379         sample_aspect_ratio = ist->st->sample_aspect_ratio;
00380     }else
00381         sample_aspect_ratio = ist->st->codec->sample_aspect_ratio;
00382 
00383     snprintf(args, 255, "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,
00384              ist->st->codec->height, ist->st->codec->pix_fmt, 1, AV_TIME_BASE,
00385              sample_aspect_ratio.num, sample_aspect_ratio.den);
00386 
00387     ret = avfilter_graph_create_filter(&ost->input_video_filter, avfilter_get_by_name("buffer"),
00388                                        "src", args, NULL, ost->graph);
00389     if (ret < 0)
00390         return ret;
00391     ret = avfilter_graph_create_filter(&ost->output_video_filter, avfilter_get_by_name("buffersink"),
00392                                        "out", NULL, pix_fmts, ost->graph);
00393     if (ret < 0)
00394         return ret;
00395     last_filter = ost->input_video_filter;
00396 
00397     if (codec->width  != icodec->width || codec->height != icodec->height) {
00398         snprintf(args, 255, "%d:%d:flags=0x%X",
00399                  codec->width,
00400                  codec->height,
00401                  ost->sws_flags);
00402         if ((ret = avfilter_graph_create_filter(&filter, avfilter_get_by_name("scale"),
00403                                                 NULL, args, NULL, ost->graph)) < 0)
00404             return ret;
00405         if ((ret = avfilter_link(last_filter, 0, filter, 0)) < 0)
00406             return ret;
00407         last_filter = filter;
00408     }
00409 
00410     snprintf(args, sizeof(args), "flags=0x%X", ost->sws_flags);
00411     ost->graph->scale_sws_opts = av_strdup(args);
00412 
00413     if (ost->avfilter) {
00414         AVFilterInOut *outputs = avfilter_inout_alloc();
00415         AVFilterInOut *inputs  = avfilter_inout_alloc();
00416 
00417         outputs->name    = av_strdup("in");
00418         outputs->filter_ctx = last_filter;
00419         outputs->pad_idx = 0;
00420         outputs->next    = NULL;
00421 
00422         inputs->name    = av_strdup("out");
00423         inputs->filter_ctx = ost->output_video_filter;
00424         inputs->pad_idx = 0;
00425         inputs->next    = NULL;
00426 
00427         if ((ret = avfilter_graph_parse(ost->graph, ost->avfilter, &inputs, &outputs, NULL)) < 0)
00428             return ret;
00429         av_freep(&ost->avfilter);
00430     } else {
00431         if ((ret = avfilter_link(last_filter, 0, ost->output_video_filter, 0)) < 0)
00432             return ret;
00433     }
00434 
00435     if ((ret = avfilter_graph_config(ost->graph, NULL)) < 0)
00436         return ret;
00437 
00438     codec->width  = ost->output_video_filter->inputs[0]->w;
00439     codec->height = ost->output_video_filter->inputs[0]->h;
00440     codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
00441         ost->frame_aspect_ratio ? // overriden by the -aspect cli option
00442         av_d2q(ost->frame_aspect_ratio*codec->height/codec->width, 255) :
00443         ost->output_video_filter->inputs[0]->sample_aspect_ratio;
00444 
00445     return 0;
00446 }
00447 #endif /* CONFIG_AVFILTER */
00448 
00449 static void term_exit(void)
00450 {
00451     av_log(NULL, AV_LOG_QUIET, "%s", "");
00452 #if HAVE_TERMIOS_H
00453     if(!run_as_daemon)
00454         tcsetattr (0, TCSANOW, &oldtty);
00455 #endif
00456 }
00457 
00458 static volatile int received_sigterm = 0;
00459 
00460 static void
00461 sigterm_handler(int sig)
00462 {
00463     received_sigterm = sig;
00464     q_pressed++;
00465     term_exit();
00466 }
00467 
00468 static void term_init(void)
00469 {
00470 #if HAVE_TERMIOS_H
00471     if(!run_as_daemon){
00472     struct termios tty;
00473 
00474     tcgetattr (0, &tty);
00475     oldtty = tty;
00476     atexit(term_exit);
00477 
00478     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
00479                           |INLCR|IGNCR|ICRNL|IXON);
00480     tty.c_oflag |= OPOST;
00481     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
00482     tty.c_cflag &= ~(CSIZE|PARENB);
00483     tty.c_cflag |= CS8;
00484     tty.c_cc[VMIN] = 1;
00485     tty.c_cc[VTIME] = 0;
00486 
00487     tcsetattr (0, TCSANOW, &tty);
00488     signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
00489     }
00490 #endif
00491 
00492     signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).  */
00493     signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
00494 #ifdef SIGXCPU
00495     signal(SIGXCPU, sigterm_handler);
00496 #endif
00497 }
00498 
00499 /* read a key without blocking */
00500 static int read_key(void)
00501 {
00502 #if HAVE_TERMIOS_H
00503     int n = 1;
00504     unsigned char ch;
00505     struct timeval tv;
00506     fd_set rfds;
00507 
00508     if(run_as_daemon)
00509         return -1;
00510 
00511     FD_ZERO(&rfds);
00512     FD_SET(0, &rfds);
00513     tv.tv_sec = 0;
00514     tv.tv_usec = 0;
00515     n = select(1, &rfds, NULL, NULL, &tv);
00516     if (n > 0) {
00517         n = read(0, &ch, 1);
00518         if (n == 1)
00519             return ch;
00520 
00521         return n;
00522     }
00523 #elif HAVE_KBHIT
00524     if(kbhit())
00525         return(getch());
00526 #endif
00527     return -1;
00528 }
00529 
00530 static int decode_interrupt_cb(void)
00531 {
00532     q_pressed += read_key() == 'q';
00533     return q_pressed > 1;
00534 }
00535 
00536 static int ffmpeg_exit(int ret)
00537 {
00538     int i;
00539 
00540     /* close files */
00541     for(i=0;i<nb_output_files;i++) {
00542         AVFormatContext *s = output_files[i];
00543         if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
00544             avio_close(s->pb);
00545         avformat_free_context(s);
00546         av_free(output_streams_for_file[i]);
00547     }
00548     for(i=0;i<nb_input_files;i++) {
00549         av_close_input_file(input_files[i].ctx);
00550         av_free(input_files_ts_scale[i]);
00551     }
00552 
00553     av_free(intra_matrix);
00554     av_free(inter_matrix);
00555 
00556     if (vstats_file)
00557         fclose(vstats_file);
00558     av_free(vstats_filename);
00559 
00560     av_free(streamid_map);
00561     av_free(input_codecs);
00562     av_free(stream_maps);
00563     av_free(meta_data_maps);
00564 
00565     av_freep(&input_streams);
00566     av_freep(&input_files);
00567 
00568     av_free(video_codec_name);
00569     av_free(audio_codec_name);
00570     av_free(subtitle_codec_name);
00571     av_free(data_codec_name);
00572 
00573     av_free(video_standard);
00574 
00575     uninit_opts();
00576     av_free(audio_buf);
00577     av_free(audio_out);
00578     allocated_audio_buf_size= allocated_audio_out_size= 0;
00579     av_free(samples);
00580 
00581 #if CONFIG_AVFILTER
00582     avfilter_uninit();
00583 #endif
00584 
00585     if (received_sigterm) {
00586         fprintf(stderr,
00587             "Received signal %d: terminating.\n",
00588             (int) received_sigterm);
00589         exit (255);
00590     }
00591 
00592     exit(ret); /* not all OS-es handle main() return value */
00593     return ret;
00594 }
00595 
00596 /* similar to ff_dynarray_add() and av_fast_realloc() */
00597 static void *grow_array(void *array, int elem_size, int *size, int new_size)
00598 {
00599     if (new_size >= INT_MAX / elem_size) {
00600         fprintf(stderr, "Array too big.\n");
00601         ffmpeg_exit(1);
00602     }
00603     if (*size < new_size) {
00604         uint8_t *tmp = av_realloc(array, new_size*elem_size);
00605         if (!tmp) {
00606             fprintf(stderr, "Could not alloc buffer.\n");
00607             ffmpeg_exit(1);
00608         }
00609         memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);
00610         *size = new_size;
00611         return tmp;
00612     }
00613     return array;
00614 }
00615 
00616 static void choose_sample_fmt(AVStream *st, AVCodec *codec)
00617 {
00618     if(codec && codec->sample_fmts){
00619         const enum AVSampleFormat *p= codec->sample_fmts;
00620         for(; *p!=-1; p++){
00621             if(*p == st->codec->sample_fmt)
00622                 break;
00623         }
00624         if (*p == -1) {
00625             if((codec->capabilities & CODEC_CAP_LOSSLESS) && av_get_sample_fmt_name(st->codec->sample_fmt) > av_get_sample_fmt_name(codec->sample_fmts[0]))
00626                 av_log(NULL, AV_LOG_ERROR, "Convertion will not be lossless'\n");
00627             av_log(NULL, AV_LOG_WARNING,
00628                    "Incompatible sample format '%s' for codec '%s', auto-selecting format '%s'\n",
00629                    av_get_sample_fmt_name(st->codec->sample_fmt),
00630                    codec->name,
00631                    av_get_sample_fmt_name(codec->sample_fmts[0]));
00632             st->codec->sample_fmt = codec->sample_fmts[0];
00633         }
00634     }
00635 }
00636 
00637 static void choose_sample_rate(AVStream *st, AVCodec *codec)
00638 {
00639     if(codec && codec->supported_samplerates){
00640         const int *p= codec->supported_samplerates;
00641         int best=0;
00642         int best_dist=INT_MAX;
00643         for(; *p; p++){
00644             int dist= abs(st->codec->sample_rate - *p);
00645             if(dist < best_dist){
00646                 best_dist= dist;
00647                 best= *p;
00648             }
00649         }
00650         if(best_dist){
00651             av_log(st->codec, AV_LOG_WARNING, "Requested sampling rate unsupported using closest supported (%d)\n", best);
00652         }
00653         st->codec->sample_rate= best;
00654     }
00655 }
00656 
00657 static void choose_pixel_fmt(AVStream *st, AVCodec *codec)
00658 {
00659     if(codec && codec->pix_fmts){
00660         const enum PixelFormat *p= codec->pix_fmts;
00661         if(st->codec->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL){
00662             if(st->codec->codec_id==CODEC_ID_MJPEG){
00663                 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_NONE};
00664             }else if(st->codec->codec_id==CODEC_ID_LJPEG){
00665                 p= (const enum PixelFormat[]){PIX_FMT_YUVJ420P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ444P, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_BGRA, PIX_FMT_NONE};
00666             }
00667         }
00668         for(; *p!=-1; p++){
00669             if(*p == st->codec->pix_fmt)
00670                 break;
00671         }
00672         if (*p == -1) {
00673             if(st->codec->pix_fmt != PIX_FMT_NONE)
00674                 av_log(NULL, AV_LOG_WARNING,
00675                         "Incompatible pixel format '%s' for codec '%s', auto-selecting format '%s'\n",
00676                         av_pix_fmt_descriptors[st->codec->pix_fmt].name,
00677                         codec->name,
00678                         av_pix_fmt_descriptors[codec->pix_fmts[0]].name);
00679             st->codec->pix_fmt = codec->pix_fmts[0];
00680         }
00681     }
00682 }
00683 
00684 static AVOutputStream *new_output_stream(AVFormatContext *oc, int file_idx)
00685 {
00686     int idx = oc->nb_streams - 1;
00687     AVOutputStream *ost;
00688 
00689     output_streams_for_file[file_idx] =
00690         grow_array(output_streams_for_file[file_idx],
00691                    sizeof(*output_streams_for_file[file_idx]),
00692                    &nb_output_streams_for_file[file_idx],
00693                    oc->nb_streams);
00694     ost = output_streams_for_file[file_idx][idx] =
00695         av_mallocz(sizeof(AVOutputStream));
00696     if (!ost) {
00697         fprintf(stderr, "Could not alloc output stream\n");
00698         ffmpeg_exit(1);
00699     }
00700     ost->file_index = file_idx;
00701     ost->index = idx;
00702 
00703     ost->sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
00704     return ost;
00705 }
00706 
00707 static int read_ffserver_streams(AVFormatContext *s, const char *filename)
00708 {
00709     int i, err;
00710     AVFormatContext *ic;
00711     int nopts = 0;
00712 
00713     err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
00714     if (err < 0)
00715         return err;
00716     /* copy stream format */
00717     s->nb_streams = 0;
00718     for(i=0;i<ic->nb_streams;i++) {
00719         AVStream *st;
00720         AVCodec *codec;
00721 
00722         s->nb_streams++;
00723 
00724         // FIXME: a more elegant solution is needed
00725         st = av_mallocz(sizeof(AVStream));
00726         memcpy(st, ic->streams[i], sizeof(AVStream));
00727         st->info = av_malloc(sizeof(*st->info));
00728         memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
00729         st->codec = avcodec_alloc_context();
00730         if (!st->codec) {
00731             print_error(filename, AVERROR(ENOMEM));
00732             ffmpeg_exit(1);
00733         }
00734         avcodec_copy_context(st->codec, ic->streams[i]->codec);
00735         s->streams[i] = st;
00736 
00737         codec = avcodec_find_encoder(st->codec->codec_id);
00738         if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
00739             if (audio_stream_copy) {
00740                 st->stream_copy = 1;
00741             } else
00742                 choose_sample_fmt(st, codec);
00743         } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
00744             if (video_stream_copy) {
00745                 st->stream_copy = 1;
00746             } else
00747                 choose_pixel_fmt(st, codec);
00748         }
00749 
00750         if(st->codec->flags & CODEC_FLAG_BITEXACT)
00751             nopts = 1;
00752 
00753         new_output_stream(s, nb_output_files);
00754     }
00755 
00756     if (!nopts)
00757         s->timestamp = av_gettime();
00758 
00759     av_close_input_file(ic);
00760     return 0;
00761 }
00762 
00763 static double
00764 get_sync_ipts(const AVOutputStream *ost)
00765 {
00766     const AVInputStream *ist = ost->sync_ist;
00767     return (double)(ist->pts - start_time)/AV_TIME_BASE;
00768 }
00769 
00770 static void write_frame(AVFormatContext *s, AVPacket *pkt, AVCodecContext *avctx, AVBitStreamFilterContext *bsfc){
00771     int ret;
00772 
00773     while(bsfc){
00774         AVPacket new_pkt= *pkt;
00775         int a= av_bitstream_filter_filter(bsfc, avctx, NULL,
00776                                           &new_pkt.data, &new_pkt.size,
00777                                           pkt->data, pkt->size,
00778                                           pkt->flags & AV_PKT_FLAG_KEY);
00779         if(a>0){
00780             av_free_packet(pkt);
00781             new_pkt.destruct= av_destruct_packet;
00782         } else if(a<0){
00783             fprintf(stderr, "%s failed for stream %d, codec %s",
00784                     bsfc->filter->name, pkt->stream_index,
00785                     avctx->codec ? avctx->codec->name : "copy");
00786             print_error("", a);
00787             if (exit_on_error)
00788                 ffmpeg_exit(1);
00789         }
00790         *pkt= new_pkt;
00791 
00792         bsfc= bsfc->next;
00793     }
00794 
00795     ret= av_interleaved_write_frame(s, pkt);
00796     if(ret < 0){
00797         print_error("av_interleaved_write_frame()", ret);
00798         ffmpeg_exit(1);
00799     }
00800 }
00801 
00802 #define MAX_AUDIO_PACKET_SIZE (128 * 1024)
00803 
00804 static void do_audio_out(AVFormatContext *s,
00805                          AVOutputStream *ost,
00806                          AVInputStream *ist,
00807                          unsigned char *buf, int size)
00808 {
00809     uint8_t *buftmp;
00810     int64_t audio_out_size, audio_buf_size;
00811     int64_t allocated_for_size= size;
00812 
00813     int size_out, frame_bytes, ret, resample_changed;
00814     AVCodecContext *enc= ost->st->codec;
00815     AVCodecContext *dec= ist->st->codec;
00816     int osize = av_get_bytes_per_sample(enc->sample_fmt);
00817     int isize = av_get_bytes_per_sample(dec->sample_fmt);
00818     const int coded_bps = av_get_bits_per_sample(enc->codec->id);
00819 
00820 need_realloc:
00821     audio_buf_size= (allocated_for_size + isize*dec->channels - 1) / (isize*dec->channels);
00822     audio_buf_size= (audio_buf_size*enc->sample_rate + dec->sample_rate) / dec->sample_rate;
00823     audio_buf_size= audio_buf_size*2 + 10000; //safety factors for the deprecated resampling API
00824     audio_buf_size= FFMAX(audio_buf_size, enc->frame_size);
00825     audio_buf_size*= osize*enc->channels;
00826 
00827     audio_out_size= FFMAX(audio_buf_size, enc->frame_size * osize * enc->channels);
00828     if(coded_bps > 8*osize)
00829         audio_out_size= audio_out_size * coded_bps / (8*osize);
00830     audio_out_size += FF_MIN_BUFFER_SIZE;
00831 
00832     if(audio_out_size > INT_MAX || audio_buf_size > INT_MAX){
00833         fprintf(stderr, "Buffer sizes too large\n");
00834         ffmpeg_exit(1);
00835     }
00836 
00837     av_fast_malloc(&audio_buf, &allocated_audio_buf_size, audio_buf_size);
00838     av_fast_malloc(&audio_out, &allocated_audio_out_size, audio_out_size);
00839     if (!audio_buf || !audio_out){
00840         fprintf(stderr, "Out of memory in do_audio_out\n");
00841         ffmpeg_exit(1);
00842     }
00843 
00844     if (enc->channels != dec->channels)
00845         ost->audio_resample = 1;
00846 
00847     resample_changed = ost->resample_sample_fmt  != dec->sample_fmt ||
00848                        ost->resample_channels    != dec->channels   ||
00849                        ost->resample_sample_rate != dec->sample_rate;
00850 
00851     if ((ost->audio_resample && !ost->resample) || resample_changed) {
00852         if (resample_changed) {
00853             av_log(NULL, AV_LOG_INFO, "Input stream #%d.%d frame changed from rate:%d fmt:%s ch:%d to rate:%d fmt:%s ch:%d\n",
00854                    ist->file_index, ist->st->index,
00855                    ost->resample_sample_rate, av_get_sample_fmt_name(ost->resample_sample_fmt), ost->resample_channels,
00856                    dec->sample_rate, av_get_sample_fmt_name(dec->sample_fmt), dec->channels);
00857             ost->resample_sample_fmt  = dec->sample_fmt;
00858             ost->resample_channels    = dec->channels;
00859             ost->resample_sample_rate = dec->sample_rate;
00860             if (ost->resample)
00861                 audio_resample_close(ost->resample);
00862         }
00863         /* if audio_sync_method is >1 the resampler is needed for audio drift compensation */
00864         if (audio_sync_method <= 1 &&
00865             ost->resample_sample_fmt  == enc->sample_fmt &&
00866             ost->resample_channels    == enc->channels   &&
00867             ost->resample_sample_rate == enc->sample_rate) {
00868             ost->resample = NULL;
00869             ost->audio_resample = 0;
00870         } else {
00871             if (dec->sample_fmt != AV_SAMPLE_FMT_S16)
00872                 fprintf(stderr, "Warning, using s16 intermediate sample format for resampling\n");
00873             ost->resample = av_audio_resample_init(enc->channels,    dec->channels,
00874                                                    enc->sample_rate, dec->sample_rate,
00875                                                    enc->sample_fmt,  dec->sample_fmt,
00876                                                    16, 10, 0, 0.8);
00877             if (!ost->resample) {
00878                 fprintf(stderr, "Can not resample %d channels @ %d Hz to %d channels @ %d Hz\n",
00879                         dec->channels, dec->sample_rate,
00880                         enc->channels, enc->sample_rate);
00881                 ffmpeg_exit(1);
00882             }
00883         }
00884     }
00885 
00886 #define MAKE_SFMT_PAIR(a,b) ((a)+AV_SAMPLE_FMT_NB*(b))
00887     if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt &&
00888         MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt)!=ost->reformat_pair) {
00889         if (ost->reformat_ctx)
00890             av_audio_convert_free(ost->reformat_ctx);
00891         ost->reformat_ctx = av_audio_convert_alloc(enc->sample_fmt, 1,
00892                                                    dec->sample_fmt, 1, NULL, 0);
00893         if (!ost->reformat_ctx) {
00894             fprintf(stderr, "Cannot convert %s sample format to %s sample format\n",
00895                 av_get_sample_fmt_name(dec->sample_fmt),
00896                 av_get_sample_fmt_name(enc->sample_fmt));
00897             ffmpeg_exit(1);
00898         }
00899         ost->reformat_pair=MAKE_SFMT_PAIR(enc->sample_fmt,dec->sample_fmt);
00900     }
00901 
00902     if(audio_sync_method){
00903         double delta = get_sync_ipts(ost) * enc->sample_rate - ost->sync_opts
00904                 - av_fifo_size(ost->fifo)/(enc->channels * 2);
00905         double idelta= delta*dec->sample_rate / enc->sample_rate;
00906         int byte_delta= ((int)idelta)*2*dec->channels;
00907 
00908         //FIXME resample delay
00909         if(fabs(delta) > 50){
00910             if(ist->is_start || fabs(delta) > audio_drift_threshold*enc->sample_rate){
00911                 if(byte_delta < 0){
00912                     byte_delta= FFMAX(byte_delta, -size);
00913                     size += byte_delta;
00914                     buf  -= byte_delta;
00915                     if(verbose > 2)
00916                         fprintf(stderr, "discarding %d audio samples\n", (int)-delta);
00917                     if(!size)
00918                         return;
00919                     ist->is_start=0;
00920                 }else{
00921                     static uint8_t *input_tmp= NULL;
00922                     input_tmp= av_realloc(input_tmp, byte_delta + size);
00923 
00924                     if(byte_delta > allocated_for_size - size){
00925                         allocated_for_size= byte_delta + (int64_t)size;
00926                         goto need_realloc;
00927                     }
00928                     ist->is_start=0;
00929 
00930                     memset(input_tmp, 0, byte_delta);
00931                     memcpy(input_tmp + byte_delta, buf, size);
00932                     buf= input_tmp;
00933                     size += byte_delta;
00934                     if(verbose > 2)
00935                         fprintf(stderr, "adding %d audio samples of silence\n", (int)delta);
00936                 }
00937             }else if(audio_sync_method>1){
00938                 int comp= av_clip(delta, -audio_sync_method, audio_sync_method);
00939                 av_assert0(ost->audio_resample);
00940                 if(verbose > 2)
00941                     fprintf(stderr, "compensating audio timestamp drift:%f compensation:%d in:%d\n", delta, comp, enc->sample_rate);
00942 //                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));
00943                 av_resample_compensate(*(struct AVResampleContext**)ost->resample, comp, enc->sample_rate);
00944             }
00945         }
00946     }else
00947         ost->sync_opts= lrintf(get_sync_ipts(ost) * enc->sample_rate)
00948                         - av_fifo_size(ost->fifo)/(enc->channels * 2); //FIXME wrong
00949 
00950     if (ost->audio_resample) {
00951         buftmp = audio_buf;
00952         size_out = audio_resample(ost->resample,
00953                                   (short *)buftmp, (short *)buf,
00954                                   size / (dec->channels * isize));
00955         size_out = size_out * enc->channels * osize;
00956     } else {
00957         buftmp = buf;
00958         size_out = size;
00959     }
00960 
00961     if (!ost->audio_resample && dec->sample_fmt!=enc->sample_fmt) {
00962         const void *ibuf[6]= {buftmp};
00963         void *obuf[6]= {audio_buf};
00964         int istride[6]= {isize};
00965         int ostride[6]= {osize};
00966         int len= size_out/istride[0];
00967         if (av_audio_convert(ost->reformat_ctx, obuf, ostride, ibuf, istride, len)<0) {
00968             printf("av_audio_convert() failed\n");
00969             if (exit_on_error)
00970                 ffmpeg_exit(1);
00971             return;
00972         }
00973         buftmp = audio_buf;
00974         size_out = len*osize;
00975     }
00976 
00977     /* now encode as many frames as possible */
00978     if (enc->frame_size > 1) {
00979         /* output resampled raw samples */
00980         if (av_fifo_realloc2(ost->fifo, av_fifo_size(ost->fifo) + size_out) < 0) {
00981             fprintf(stderr, "av_fifo_realloc2() failed\n");
00982             ffmpeg_exit(1);
00983         }
00984         av_fifo_generic_write(ost->fifo, buftmp, size_out, NULL);
00985 
00986         frame_bytes = enc->frame_size * osize * enc->channels;
00987 
00988         while (av_fifo_size(ost->fifo) >= frame_bytes) {
00989             AVPacket pkt;
00990             av_init_packet(&pkt);
00991 
00992             av_fifo_generic_read(ost->fifo, audio_buf, frame_bytes, NULL);
00993 
00994             //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
00995 
00996             ret = avcodec_encode_audio(enc, audio_out, audio_out_size,
00997                                        (short *)audio_buf);
00998             if (ret < 0) {
00999                 fprintf(stderr, "Audio encoding failed\n");
01000                 ffmpeg_exit(1);
01001             }
01002             audio_size += ret;
01003             pkt.stream_index= ost->index;
01004             pkt.data= audio_out;
01005             pkt.size= ret;
01006             if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01007                 pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01008             pkt.flags |= AV_PKT_FLAG_KEY;
01009             write_frame(s, &pkt, enc, ost->bitstream_filters);
01010 
01011             ost->sync_opts += enc->frame_size;
01012         }
01013     } else {
01014         AVPacket pkt;
01015         av_init_packet(&pkt);
01016 
01017         ost->sync_opts += size_out / (osize * enc->channels);
01018 
01019         /* output a pcm frame */
01020         /* determine the size of the coded buffer */
01021         size_out /= osize;
01022         if (coded_bps)
01023             size_out = size_out*coded_bps/8;
01024 
01025         if(size_out > audio_out_size){
01026             fprintf(stderr, "Internal error, buffer size too small\n");
01027             ffmpeg_exit(1);
01028         }
01029 
01030         //FIXME pass ost->sync_opts as AVFrame.pts in avcodec_encode_audio()
01031         ret = avcodec_encode_audio(enc, audio_out, size_out,
01032                                    (short *)buftmp);
01033         if (ret < 0) {
01034             fprintf(stderr, "Audio encoding failed\n");
01035             ffmpeg_exit(1);
01036         }
01037         audio_size += ret;
01038         pkt.stream_index= ost->index;
01039         pkt.data= audio_out;
01040         pkt.size= ret;
01041         if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01042             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01043         pkt.flags |= AV_PKT_FLAG_KEY;
01044         write_frame(s, &pkt, enc, ost->bitstream_filters);
01045     }
01046 }
01047 
01048 static void pre_process_video_frame(AVInputStream *ist, AVPicture *picture, void **bufp)
01049 {
01050     AVCodecContext *dec;
01051     AVPicture *picture2;
01052     AVPicture picture_tmp;
01053     uint8_t *buf = 0;
01054 
01055     dec = ist->st->codec;
01056 
01057     /* deinterlace : must be done before any resize */
01058     if (do_deinterlace) {
01059         int size;
01060 
01061         /* create temporary picture */
01062         size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
01063         buf = av_malloc(size);
01064         if (!buf)
01065             return;
01066 
01067         picture2 = &picture_tmp;
01068         avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
01069 
01070         if(avpicture_deinterlace(picture2, picture,
01071                                  dec->pix_fmt, dec->width, dec->height) < 0) {
01072             /* if error, do not deinterlace */
01073             fprintf(stderr, "Deinterlacing failed\n");
01074             av_free(buf);
01075             buf = NULL;
01076             picture2 = picture;
01077         }
01078     } else {
01079         picture2 = picture;
01080     }
01081 
01082     if (picture != picture2)
01083         *picture = *picture2;
01084     *bufp = buf;
01085 }
01086 
01087 /* we begin to correct av delay at this threshold */
01088 #define AV_DELAY_MAX 0.100
01089 
01090 static void do_subtitle_out(AVFormatContext *s,
01091                             AVOutputStream *ost,
01092                             AVInputStream *ist,
01093                             AVSubtitle *sub,
01094                             int64_t pts)
01095 {
01096     static uint8_t *subtitle_out = NULL;
01097     int subtitle_out_max_size = 1024 * 1024;
01098     int subtitle_out_size, nb, i;
01099     AVCodecContext *enc;
01100     AVPacket pkt;
01101 
01102     if (pts == AV_NOPTS_VALUE) {
01103         fprintf(stderr, "Subtitle packets must have a pts\n");
01104         if (exit_on_error)
01105             ffmpeg_exit(1);
01106         return;
01107     }
01108 
01109     enc = ost->st->codec;
01110 
01111     if (!subtitle_out) {
01112         subtitle_out = av_malloc(subtitle_out_max_size);
01113     }
01114 
01115     /* Note: DVB subtitle need one packet to draw them and one other
01116        packet to clear them */
01117     /* XXX: signal it in the codec context ? */
01118     if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)
01119         nb = 2;
01120     else
01121         nb = 1;
01122 
01123     for(i = 0; i < nb; i++) {
01124         sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
01125         // start_display_time is required to be 0
01126         sub->pts              += av_rescale_q(sub->start_display_time, (AVRational){1, 1000}, AV_TIME_BASE_Q);
01127         sub->end_display_time -= sub->start_display_time;
01128         sub->start_display_time = 0;
01129         subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
01130                                                     subtitle_out_max_size, sub);
01131         if (subtitle_out_size < 0) {
01132             fprintf(stderr, "Subtitle encoding failed\n");
01133             ffmpeg_exit(1);
01134         }
01135 
01136         av_init_packet(&pkt);
01137         pkt.stream_index = ost->index;
01138         pkt.data = subtitle_out;
01139         pkt.size = subtitle_out_size;
01140         pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
01141         if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {
01142             /* XXX: the pts correction is handled here. Maybe handling
01143                it in the codec would be better */
01144             if (i == 0)
01145                 pkt.pts += 90 * sub->start_display_time;
01146             else
01147                 pkt.pts += 90 * sub->end_display_time;
01148         }
01149         write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01150     }
01151 }
01152 
01153 static int bit_buffer_size= 1024*256;
01154 static uint8_t *bit_buffer= NULL;
01155 
01156 static void do_video_out(AVFormatContext *s,
01157                          AVOutputStream *ost,
01158                          AVInputStream *ist,
01159                          AVFrame *in_picture,
01160                          int *frame_size)
01161 {
01162     int nb_frames, i, ret, av_unused resample_changed;
01163     AVFrame *final_picture, *formatted_picture;
01164     AVCodecContext *enc, *dec;
01165     double sync_ipts;
01166 
01167     enc = ost->st->codec;
01168     dec = ist->st->codec;
01169 
01170     sync_ipts = get_sync_ipts(ost) / av_q2d(enc->time_base);
01171 
01172     /* by default, we output a single frame */
01173     nb_frames = 1;
01174 
01175     *frame_size = 0;
01176 
01177     if(video_sync_method){
01178         double vdelta = sync_ipts - ost->sync_opts;
01179         //FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
01180         if (vdelta < -1.1)
01181             nb_frames = 0;
01182         else if (video_sync_method == 2 || (video_sync_method<0 && (s->oformat->flags & AVFMT_VARIABLE_FPS))){
01183             if(vdelta<=-0.6){
01184                 nb_frames=0;
01185             }else if(vdelta>0.6)
01186                 ost->sync_opts= lrintf(sync_ipts);
01187         }else if (vdelta > 1.1)
01188             nb_frames = lrintf(vdelta);
01189 //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);
01190         if (nb_frames == 0){
01191             ++nb_frames_drop;
01192             if (verbose>2)
01193                 fprintf(stderr, "*** drop!\n");
01194         }else if (nb_frames > 1) {
01195             nb_frames_dup += nb_frames - 1;
01196             if (verbose>2)
01197                 fprintf(stderr, "*** %d dup!\n", nb_frames-1);
01198         }
01199     }else
01200         ost->sync_opts= lrintf(sync_ipts);
01201 
01202     nb_frames= FFMIN(nb_frames, max_frames[AVMEDIA_TYPE_VIDEO] - ost->frame_number);
01203     if (nb_frames <= 0)
01204         return;
01205 
01206     formatted_picture = in_picture;
01207     final_picture = formatted_picture;
01208 
01209 #if !CONFIG_AVFILTER
01210     resample_changed = ost->resample_width   != dec->width  ||
01211                        ost->resample_height  != dec->height ||
01212                        ost->resample_pix_fmt != dec->pix_fmt;
01213 
01214     if (resample_changed) {
01215         av_log(NULL, AV_LOG_INFO,
01216                "Input stream #%d.%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
01217                ist->file_index, ist->st->index,
01218                ost->resample_width, ost->resample_height, av_get_pix_fmt_name(ost->resample_pix_fmt),
01219                dec->width         , dec->height         , av_get_pix_fmt_name(dec->pix_fmt));
01220         ost->resample_width   = dec->width;
01221         ost->resample_height  = dec->height;
01222         ost->resample_pix_fmt = dec->pix_fmt;
01223     }
01224 
01225     ost->video_resample = dec->width   != enc->width  ||
01226                           dec->height  != enc->height ||
01227                           dec->pix_fmt != enc->pix_fmt;
01228 
01229     if (ost->video_resample) {
01230         final_picture = &ost->resample_frame;
01231         if (!ost->img_resample_ctx || resample_changed) {
01232             /* initialize the destination picture */
01233             if (!ost->resample_frame.data[0]) {
01234                 avcodec_get_frame_defaults(&ost->resample_frame);
01235                 if (avpicture_alloc((AVPicture *)&ost->resample_frame, enc->pix_fmt,
01236                                     enc->width, enc->height)) {
01237                     fprintf(stderr, "Cannot allocate temp picture, check pix fmt\n");
01238                     ffmpeg_exit(1);
01239                 }
01240             }
01241             /* initialize a new scaler context */
01242             sws_freeContext(ost->img_resample_ctx);
01243             ost->img_resample_ctx = sws_getContext(dec->width, dec->height, dec->pix_fmt,
01244                                                    enc->width, enc->height, enc->pix_fmt,
01245                                                    ost->sws_flags, NULL, NULL, NULL);
01246             if (ost->img_resample_ctx == NULL) {
01247                 fprintf(stderr, "Cannot get resampling context\n");
01248                 ffmpeg_exit(1);
01249             }
01250         }
01251         sws_scale(ost->img_resample_ctx, formatted_picture->data, formatted_picture->linesize,
01252               0, ost->resample_height, final_picture->data, final_picture->linesize);
01253     }
01254 #endif
01255 
01256     /* duplicates frame if needed */
01257     for(i=0;i<nb_frames;i++) {
01258         AVPacket pkt;
01259         av_init_packet(&pkt);
01260         pkt.stream_index= ost->index;
01261 
01262         if (s->oformat->flags & AVFMT_RAWPICTURE) {
01263             /* raw pictures are written as AVPicture structure to
01264                avoid any copies. We support temorarily the older
01265                method. */
01266             AVFrame* old_frame = enc->coded_frame;
01267             enc->coded_frame = dec->coded_frame; //FIXME/XXX remove this hack
01268             pkt.data= (uint8_t *)final_picture;
01269             pkt.size=  sizeof(AVPicture);
01270             pkt.pts= av_rescale_q(ost->sync_opts, enc->time_base, ost->st->time_base);
01271             pkt.flags |= AV_PKT_FLAG_KEY;
01272 
01273             write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01274             enc->coded_frame = old_frame;
01275         } else {
01276             AVFrame big_picture;
01277 
01278             big_picture= *final_picture;
01279             /* better than nothing: use input picture interlaced
01280                settings */
01281             big_picture.interlaced_frame = in_picture->interlaced_frame;
01282             if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
01283                 if(top_field_first == -1)
01284                     big_picture.top_field_first = in_picture->top_field_first;
01285                 else
01286                     big_picture.top_field_first = top_field_first;
01287             }
01288 
01289             /* handles sameq here. This is not correct because it may
01290                not be a global option */
01291             big_picture.quality = same_quality ? ist->st->quality : ost->st->quality;
01292             if(!me_threshold)
01293                 big_picture.pict_type = 0;
01294 //            big_picture.pts = AV_NOPTS_VALUE;
01295             big_picture.pts= ost->sync_opts;
01296 //            big_picture.pts= av_rescale(ost->sync_opts, AV_TIME_BASE*(int64_t)enc->time_base.num, enc->time_base.den);
01297 //av_log(NULL, AV_LOG_DEBUG, "%"PRId64" -> encoder\n", ost->sync_opts);
01298             if (ost->forced_kf_index < ost->forced_kf_count &&
01299                 big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
01300                 big_picture.pict_type = AV_PICTURE_TYPE_I;
01301                 ost->forced_kf_index++;
01302             }
01303             ret = avcodec_encode_video(enc,
01304                                        bit_buffer, bit_buffer_size,
01305                                        &big_picture);
01306             if (ret < 0) {
01307                 fprintf(stderr, "Video encoding failed\n");
01308                 ffmpeg_exit(1);
01309             }
01310 
01311             if(ret>0){
01312                 pkt.data= bit_buffer;
01313                 pkt.size= ret;
01314                 if(enc->coded_frame->pts != AV_NOPTS_VALUE)
01315                     pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01316 /*av_log(NULL, AV_LOG_DEBUG, "encoder -> %"PRId64"/%"PRId64"\n",
01317    pkt.pts != AV_NOPTS_VALUE ? av_rescale(pkt.pts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1,
01318    pkt.dts != AV_NOPTS_VALUE ? av_rescale(pkt.dts, enc->time_base.den, AV_TIME_BASE*(int64_t)enc->time_base.num) : -1);*/
01319 
01320                 if(enc->coded_frame->key_frame)
01321                     pkt.flags |= AV_PKT_FLAG_KEY;
01322                 write_frame(s, &pkt, ost->st->codec, ost->bitstream_filters);
01323                 *frame_size = ret;
01324                 video_size += ret;
01325                 //fprintf(stderr,"\nFrame: %3d size: %5d type: %d",
01326                 //        enc->frame_number-1, ret, enc->pict_type);
01327                 /* if two pass, output log */
01328                 if (ost->logfile && enc->stats_out) {
01329                     fprintf(ost->logfile, "%s", enc->stats_out);
01330                 }
01331             }
01332         }
01333         ost->sync_opts++;
01334         ost->frame_number++;
01335     }
01336 }
01337 
01338 static double psnr(double d){
01339     return -10.0*log(d)/log(10.0);
01340 }
01341 
01342 static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
01343                            int frame_size)
01344 {
01345     AVCodecContext *enc;
01346     int frame_number;
01347     double ti1, bitrate, avg_bitrate;
01348 
01349     /* this is executed just the first time do_video_stats is called */
01350     if (!vstats_file) {
01351         vstats_file = fopen(vstats_filename, "w");
01352         if (!vstats_file) {
01353             perror("fopen");
01354             ffmpeg_exit(1);
01355         }
01356     }
01357 
01358     enc = ost->st->codec;
01359     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01360         frame_number = ost->frame_number;
01361         fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality/(float)FF_QP2LAMBDA);
01362         if (enc->flags&CODEC_FLAG_PSNR)
01363             fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0]/(enc->width*enc->height*255.0*255.0)));
01364 
01365         fprintf(vstats_file,"f_size= %6d ", frame_size);
01366         /* compute pts value */
01367         ti1 = ost->sync_opts * av_q2d(enc->time_base);
01368         if (ti1 < 0.01)
01369             ti1 = 0.01;
01370 
01371         bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
01372         avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
01373         fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
01374             (double)video_size / 1024, ti1, bitrate, avg_bitrate);
01375         fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
01376     }
01377 }
01378 
01379 static void print_report(AVFormatContext **output_files,
01380                          AVOutputStream **ost_table, int nb_ostreams,
01381                          int is_last_report)
01382 {
01383     char buf[1024];
01384     AVOutputStream *ost;
01385     AVFormatContext *oc;
01386     int64_t total_size;
01387     AVCodecContext *enc;
01388     int frame_number, vid, i;
01389     double bitrate;
01390     int64_t pts = INT64_MAX;
01391     static int64_t last_time = -1;
01392     static int qp_histogram[52];
01393 
01394     if (!is_last_report) {
01395         int64_t cur_time;
01396         /* display the report every 0.5 seconds */
01397         cur_time = av_gettime();
01398         if (last_time == -1) {
01399             last_time = cur_time;
01400             return;
01401         }
01402         if ((cur_time - last_time) < 500000)
01403             return;
01404         last_time = cur_time;
01405     }
01406 
01407 
01408     oc = output_files[0];
01409 
01410     total_size = avio_size(oc->pb);
01411     if(total_size<0) // FIXME improve avio_size() so it works with non seekable output too
01412         total_size= avio_tell(oc->pb);
01413 
01414     buf[0] = '\0';
01415     vid = 0;
01416     for(i=0;i<nb_ostreams;i++) {
01417         float q = -1;
01418         ost = ost_table[i];
01419         enc = ost->st->codec;
01420         if (!ost->st->stream_copy && enc->coded_frame)
01421             q = enc->coded_frame->quality/(float)FF_QP2LAMBDA;
01422         if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01423             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
01424         }
01425         if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
01426             float t = (av_gettime()-timer_start) / 1000000.0;
01427 
01428             frame_number = ost->frame_number;
01429             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
01430                      frame_number, (t>1)?(int)(frame_number/t+0.5) : 0, q);
01431             if(is_last_report)
01432                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
01433             if(qp_hist){
01434                 int j;
01435                 int qp = lrintf(q);
01436                 if(qp>=0 && qp<FF_ARRAY_ELEMS(qp_histogram))
01437                     qp_histogram[qp]++;
01438                 for(j=0; j<32; j++)
01439                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j]+1)/log(2)));
01440             }
01441             if (enc->flags&CODEC_FLAG_PSNR){
01442                 int j;
01443                 double error, error_sum=0;
01444                 double scale, scale_sum=0;
01445                 char type[3]= {'Y','U','V'};
01446                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
01447                 for(j=0; j<3; j++){
01448                     if(is_last_report){
01449                         error= enc->error[j];
01450                         scale= enc->width*enc->height*255.0*255.0*frame_number;
01451                     }else{
01452                         error= enc->coded_frame->error[j];
01453                         scale= enc->width*enc->height*255.0*255.0;
01454                     }
01455                     if(j) scale/=4;
01456                     error_sum += error;
01457                     scale_sum += scale;
01458                     snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error/scale));
01459                 }
01460                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum/scale_sum));
01461             }
01462             vid = 1;
01463         }
01464         /* compute min output value */
01465         pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
01466                                       ost->st->time_base, AV_TIME_BASE_Q));
01467     }
01468 
01469     if (verbose > 0 || is_last_report) {
01470         int hours, mins, secs, us;
01471         secs = pts / AV_TIME_BASE;
01472         us = pts % AV_TIME_BASE;
01473         mins = secs / 60;
01474         secs %= 60;
01475         hours = mins / 60;
01476         mins %= 60;
01477 
01478         bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
01479 
01480         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01481                  "size=%8.0fkB time=", total_size / 1024.0);
01482         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01483                  "%02d:%02d:%02d.%02d ", hours, mins, secs,
01484                  (100 * us) / AV_TIME_BASE);
01485         snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
01486                  "bitrate=%6.1fkbits/s", bitrate);
01487 
01488         if (nb_frames_dup || nb_frames_drop)
01489           snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
01490                   nb_frames_dup, nb_frames_drop);
01491 
01492         if (verbose >= 0)
01493             fprintf(stderr, "%s    \r", buf);
01494 
01495         fflush(stderr);
01496     }
01497 
01498     if (is_last_report && verbose >= 0){
01499         int64_t raw= audio_size + video_size + extra_size;
01500         fprintf(stderr, "\n");
01501         fprintf(stderr, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
01502                 video_size/1024.0,
01503                 audio_size/1024.0,
01504                 extra_size/1024.0,
01505                 100.0*(total_size - raw)/raw
01506         );
01507     }
01508 }
01509 
01510 static void generate_silence(uint8_t* buf, enum AVSampleFormat sample_fmt, size_t size)
01511 {
01512     int fill_char = 0x00;
01513     if (sample_fmt == AV_SAMPLE_FMT_U8)
01514         fill_char = 0x80;
01515     memset(buf, fill_char, size);
01516 }
01517 
01518 /* pkt = NULL means EOF (needed to flush decoder buffers) */
01519 static int output_packet(AVInputStream *ist, int ist_index,
01520                          AVOutputStream **ost_table, int nb_ostreams,
01521                          const AVPacket *pkt)
01522 {
01523     AVFormatContext *os;
01524     AVOutputStream *ost;
01525     int ret, i;
01526     int got_output;
01527     AVFrame picture;
01528     void *buffer_to_free = NULL;
01529     static unsigned int samples_size= 0;
01530     AVSubtitle subtitle, *subtitle_to_free;
01531     int64_t pkt_pts = AV_NOPTS_VALUE;
01532 #if CONFIG_AVFILTER
01533     int frame_available;
01534 #endif
01535 
01536     AVPacket avpkt;
01537     int bps = av_get_bytes_per_sample(ist->st->codec->sample_fmt);
01538 
01539     if(ist->next_pts == AV_NOPTS_VALUE)
01540         ist->next_pts= ist->pts;
01541 
01542     if (pkt == NULL) {
01543         /* EOF handling */
01544         av_init_packet(&avpkt);
01545         avpkt.data = NULL;
01546         avpkt.size = 0;
01547         goto handle_eof;
01548     } else {
01549         avpkt = *pkt;
01550     }
01551 
01552     if(pkt->dts != AV_NOPTS_VALUE)
01553         ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
01554     if(pkt->pts != AV_NOPTS_VALUE)
01555         pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
01556 
01557     //while we have more to decode or while the decoder did output something on EOF
01558     while (avpkt.size > 0 || (!pkt && got_output)) {
01559         uint8_t *data_buf, *decoded_data_buf;
01560         int data_size, decoded_data_size;
01561     handle_eof:
01562         ist->pts= ist->next_pts;
01563 
01564         if(avpkt.size && avpkt.size != pkt->size &&
01565            ((!ist->showed_multi_packet_warning && verbose>0) || verbose>1)){
01566             fprintf(stderr, "Multiple frames in a packet from stream %d\n", pkt->stream_index);
01567             ist->showed_multi_packet_warning=1;
01568         }
01569 
01570         /* decode the packet if needed */
01571         decoded_data_buf = NULL; /* fail safe */
01572         decoded_data_size= 0;
01573         data_buf  = avpkt.data;
01574         data_size = avpkt.size;
01575         subtitle_to_free = NULL;
01576         if (ist->decoding_needed) {
01577             switch(ist->st->codec->codec_type) {
01578             case AVMEDIA_TYPE_AUDIO:{
01579                 if(pkt && samples_size < FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE)) {
01580                     samples_size = FFMAX(pkt->size*sizeof(*samples), AVCODEC_MAX_AUDIO_FRAME_SIZE);
01581                     av_free(samples);
01582                     samples= av_malloc(samples_size);
01583                 }
01584                 decoded_data_size= samples_size;
01585                     /* XXX: could avoid copy if PCM 16 bits with same
01586                        endianness as CPU */
01587                 ret = avcodec_decode_audio3(ist->st->codec, samples, &decoded_data_size,
01588                                             &avpkt);
01589                 if (ret < 0)
01590                     goto fail_decode;
01591                 avpkt.data += ret;
01592                 avpkt.size -= ret;
01593                 data_size   = ret;
01594                 got_output  = decoded_data_size > 0;
01595                 /* Some bug in mpeg audio decoder gives */
01596                 /* decoded_data_size < 0, it seems they are overflows */
01597                 if (!got_output) {
01598                     /* no audio frame */
01599                     continue;
01600                 }
01601                 decoded_data_buf = (uint8_t *)samples;
01602                 ist->next_pts += ((int64_t)AV_TIME_BASE/bps * decoded_data_size) /
01603                     (ist->st->codec->sample_rate * ist->st->codec->channels);
01604                 break;}
01605             case AVMEDIA_TYPE_VIDEO:
01606                     decoded_data_size = (ist->st->codec->width * ist->st->codec->height * 3) / 2;
01607                     /* XXX: allocate picture correctly */
01608                     avcodec_get_frame_defaults(&picture);
01609                     avpkt.pts = pkt_pts;
01610                     avpkt.dts = ist->pts;
01611                     pkt_pts = AV_NOPTS_VALUE;
01612 
01613                     ret = avcodec_decode_video2(ist->st->codec,
01614                                                 &picture, &got_output, &avpkt);
01615                     ist->st->quality= picture.quality;
01616                     if (ret < 0)
01617                         goto fail_decode;
01618                     if (!got_output) {
01619                         /* no picture yet */
01620                         goto discard_packet;
01621                     }
01622                     ist->next_pts = ist->pts = picture.best_effort_timestamp;
01623                     if (ist->st->codec->time_base.num != 0) {
01624                         int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
01625                         ist->next_pts += ((int64_t)AV_TIME_BASE *
01626                                           ist->st->codec->time_base.num * ticks) /
01627                             ist->st->codec->time_base.den;
01628                     }
01629                     avpkt.size = 0;
01630                     buffer_to_free = NULL;
01631                     pre_process_video_frame(ist, (AVPicture *)&picture, &buffer_to_free);
01632                     break;
01633             case AVMEDIA_TYPE_SUBTITLE:
01634                 ret = avcodec_decode_subtitle2(ist->st->codec,
01635                                                &subtitle, &got_output, &avpkt);
01636                 if (ret < 0)
01637                     goto fail_decode;
01638                 if (!got_output) {
01639                     goto discard_packet;
01640                 }
01641                 subtitle_to_free = &subtitle;
01642                 avpkt.size = 0;
01643                 break;
01644             default:
01645                 goto fail_decode;
01646             }
01647         } else {
01648             switch(ist->st->codec->codec_type) {
01649             case AVMEDIA_TYPE_AUDIO:
01650                 ist->next_pts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
01651                     ist->st->codec->sample_rate;
01652                 break;
01653             case AVMEDIA_TYPE_VIDEO:
01654                 if (ist->st->codec->time_base.num != 0) {
01655                     int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
01656                     ist->next_pts += ((int64_t)AV_TIME_BASE *
01657                                       ist->st->codec->time_base.num * ticks) /
01658                         ist->st->codec->time_base.den;
01659                 }
01660                 break;
01661             }
01662             ret = avpkt.size;
01663             avpkt.size = 0;
01664         }
01665 
01666 #if CONFIG_AVFILTER
01667         if(ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
01668         if (start_time == 0 || ist->pts >= start_time) {
01669             for(i=0;i<nb_ostreams;i++) {
01670                 ost = ost_table[i];
01671                 if (ost->input_video_filter && ost->source_index == ist_index) {
01672                     if (!picture.sample_aspect_ratio.num)
01673                         picture.sample_aspect_ratio = ist->st->sample_aspect_ratio;
01674                     picture.pts = ist->pts;
01675 
01676                     av_vsrc_buffer_add_frame(ost->input_video_filter, &picture, AV_VSRC_BUF_FLAG_OVERWRITE);
01677                 }
01678             }
01679         }
01680 #endif
01681 
01682         // preprocess audio (volume)
01683         if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
01684             if (audio_volume != 256) {
01685                 short *volp;
01686                 volp = samples;
01687                 for(i=0;i<(decoded_data_size / sizeof(short));i++) {
01688                     int v = ((*volp) * audio_volume + 128) >> 8;
01689                     if (v < -32768) v = -32768;
01690                     if (v >  32767) v = 32767;
01691                     *volp++ = v;
01692                 }
01693             }
01694         }
01695 
01696         /* frame rate emulation */
01697         if (rate_emu) {
01698             int64_t pts = av_rescale(ist->pts, 1000000, AV_TIME_BASE);
01699             int64_t now = av_gettime() - ist->start;
01700             if (pts > now)
01701                 usleep(pts - now);
01702         }
01703         /* if output time reached then transcode raw format,
01704            encode packets and output them */
01705         if (start_time == 0 || ist->pts >= start_time)
01706             for(i=0;i<nb_ostreams;i++) {
01707                 int frame_size;
01708 
01709                 ost = ost_table[i];
01710                 if (ost->source_index == ist_index) {
01711 #if CONFIG_AVFILTER
01712                 frame_available = ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO ||
01713                     !ost->output_video_filter || avfilter_poll_frame(ost->output_video_filter->inputs[0]);
01714                 while (frame_available) {
01715                     if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && ost->output_video_filter) {
01716                         AVRational ist_pts_tb = ost->output_video_filter->inputs[0]->time_base;
01717                         if (av_vsink_buffer_get_video_buffer_ref(ost->output_video_filter, &ost->picref, 0) < 0)
01718                             goto cont;
01719                         if (ost->picref) {
01720                             avfilter_fill_frame_from_video_buffer_ref(&picture, ost->picref);
01721                             ist->pts = av_rescale_q(ost->picref->pts, ist_pts_tb, AV_TIME_BASE_Q);
01722                         }
01723                     }
01724 #endif
01725                     os = output_files[ost->file_index];
01726 
01727                     /* set the input output pts pairs */
01728                     //ost->sync_ipts = (double)(ist->pts + input_files_ts_offset[ist->file_index] - start_time)/ AV_TIME_BASE;
01729 
01730                     if (ost->encoding_needed) {
01731                         av_assert0(ist->decoding_needed);
01732                         switch(ost->st->codec->codec_type) {
01733                         case AVMEDIA_TYPE_AUDIO:
01734                             do_audio_out(os, ost, ist, decoded_data_buf, decoded_data_size);
01735                             break;
01736                         case AVMEDIA_TYPE_VIDEO:
01737 #if CONFIG_AVFILTER
01738                             if (ost->picref->video && !ost->frame_aspect_ratio)
01739                                 ost->st->codec->sample_aspect_ratio = ost->picref->video->sample_aspect_ratio;
01740 #endif
01741                             do_video_out(os, ost, ist, &picture, &frame_size);
01742                             if (vstats_filename && frame_size)
01743                                 do_video_stats(os, ost, frame_size);
01744                             break;
01745                         case AVMEDIA_TYPE_SUBTITLE:
01746                             do_subtitle_out(os, ost, ist, &subtitle,
01747                                             pkt->pts);
01748                             break;
01749                         default:
01750                             abort();
01751                         }
01752                     } else {
01753                         AVFrame avframe; //FIXME/XXX remove this
01754                         AVPicture pict;
01755                         AVPacket opkt;
01756                         int64_t ost_tb_start_time= av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
01757 
01758                         av_init_packet(&opkt);
01759 
01760                         if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) && !copy_initial_nonkeyframes)
01761 #if !CONFIG_AVFILTER
01762                             continue;
01763 #else
01764                             goto cont;
01765 #endif
01766 
01767                         /* no reencoding needed : output the packet directly */
01768                         /* force the input stream PTS */
01769 
01770                         avcodec_get_frame_defaults(&avframe);
01771                         ost->st->codec->coded_frame= &avframe;
01772                         avframe.key_frame = pkt->flags & AV_PKT_FLAG_KEY;
01773 
01774                         if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
01775                             audio_size += data_size;
01776                         else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
01777                             video_size += data_size;
01778                             ost->sync_opts++;
01779                         }
01780 
01781                         opkt.stream_index= ost->index;
01782                         if(pkt->pts != AV_NOPTS_VALUE)
01783                             opkt.pts= av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
01784                         else
01785                             opkt.pts= AV_NOPTS_VALUE;
01786 
01787                         if (pkt->dts == AV_NOPTS_VALUE)
01788                             opkt.dts = av_rescale_q(ist->pts, AV_TIME_BASE_Q, ost->st->time_base);
01789                         else
01790                             opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
01791                         opkt.dts -= ost_tb_start_time;
01792 
01793                         opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
01794                         opkt.flags= pkt->flags;
01795 
01796                         //FIXME remove the following 2 lines they shall be replaced by the bitstream filters
01797                         if(   ost->st->codec->codec_id != CODEC_ID_H264
01798                            && ost->st->codec->codec_id != CODEC_ID_MPEG1VIDEO
01799                            && ost->st->codec->codec_id != CODEC_ID_MPEG2VIDEO
01800                            ) {
01801                             if(av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, data_buf, data_size, pkt->flags & AV_PKT_FLAG_KEY))
01802                                 opkt.destruct= av_destruct_packet;
01803                         } else {
01804                             opkt.data = data_buf;
01805                             opkt.size = data_size;
01806                         }
01807 
01808                         if (os->oformat->flags & AVFMT_RAWPICTURE) {
01809                             /* store AVPicture in AVPacket, as expected by the output format */
01810                             avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
01811                             opkt.data = (uint8_t *)&pict;
01812                             opkt.size = sizeof(AVPicture);
01813                             opkt.flags |= AV_PKT_FLAG_KEY;
01814                         }
01815                         write_frame(os, &opkt, ost->st->codec, ost->bitstream_filters);
01816                         ost->st->codec->frame_number++;
01817                         ost->frame_number++;
01818                         av_free_packet(&opkt);
01819                     }
01820 #if CONFIG_AVFILTER
01821                     cont:
01822                     frame_available = (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&
01823                                        ost->output_video_filter && avfilter_poll_frame(ost->output_video_filter->inputs[0]);
01824                     avfilter_unref_buffer(ost->picref);
01825                 }
01826 #endif
01827                 }
01828             }
01829 
01830         av_free(buffer_to_free);
01831         /* XXX: allocate the subtitles in the codec ? */
01832         if (subtitle_to_free) {
01833             avsubtitle_free(subtitle_to_free);
01834             subtitle_to_free = NULL;
01835         }
01836     }
01837  discard_packet:
01838     if (pkt == NULL) {
01839         /* EOF handling */
01840 
01841         for(i=0;i<nb_ostreams;i++) {
01842             ost = ost_table[i];
01843             if (ost->source_index == ist_index) {
01844                 AVCodecContext *enc= ost->st->codec;
01845                 os = output_files[ost->file_index];
01846 
01847                 if(ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <=1)
01848                     continue;
01849                 if(ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE))
01850                     continue;
01851 
01852                 if (ost->encoding_needed) {
01853                     for(;;) {
01854                         AVPacket pkt;
01855                         int fifo_bytes;
01856                         av_init_packet(&pkt);
01857                         pkt.stream_index= ost->index;
01858 
01859                         switch(ost->st->codec->codec_type) {
01860                         case AVMEDIA_TYPE_AUDIO:
01861                             fifo_bytes = av_fifo_size(ost->fifo);
01862                             ret = 0;
01863                             /* encode any samples remaining in fifo */
01864                             if (fifo_bytes > 0) {
01865                                 int osize = av_get_bytes_per_sample(enc->sample_fmt);
01866                                 int fs_tmp = enc->frame_size;
01867 
01868                                 av_fifo_generic_read(ost->fifo, audio_buf, fifo_bytes, NULL);
01869                                 if (enc->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {
01870                                     enc->frame_size = fifo_bytes / (osize * enc->channels);
01871                                 } else { /* pad */
01872                                     int frame_bytes = enc->frame_size*osize*enc->channels;
01873                                     if (allocated_audio_buf_size < frame_bytes)
01874                                         ffmpeg_exit(1);
01875                                     generate_silence(audio_buf+fifo_bytes, enc->sample_fmt, frame_bytes - fifo_bytes);
01876                                 }
01877 
01878                                 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, (short *)audio_buf);
01879                                 pkt.duration = av_rescale((int64_t)enc->frame_size*ost->st->time_base.den,
01880                                                           ost->st->time_base.num, enc->sample_rate);
01881                                 enc->frame_size = fs_tmp;
01882                             }
01883                             if(ret <= 0) {
01884                                 ret = avcodec_encode_audio(enc, bit_buffer, bit_buffer_size, NULL);
01885                             }
01886                             if (ret < 0) {
01887                                 fprintf(stderr, "Audio encoding failed\n");
01888                                 ffmpeg_exit(1);
01889                             }
01890                             audio_size += ret;
01891                             pkt.flags |= AV_PKT_FLAG_KEY;
01892                             break;
01893                         case AVMEDIA_TYPE_VIDEO:
01894                             ret = avcodec_encode_video(enc, bit_buffer, bit_buffer_size, NULL);
01895                             if (ret < 0) {
01896                                 fprintf(stderr, "Video encoding failed\n");
01897                                 ffmpeg_exit(1);
01898                             }
01899                             video_size += ret;
01900                             if(enc->coded_frame && enc->coded_frame->key_frame)
01901                                 pkt.flags |= AV_PKT_FLAG_KEY;
01902                             if (ost->logfile && enc->stats_out) {
01903                                 fprintf(ost->logfile, "%s", enc->stats_out);
01904                             }
01905                             break;
01906                         default:
01907                             ret=-1;
01908                         }
01909 
01910                         if(ret<=0)
01911                             break;
01912                         pkt.data= bit_buffer;
01913                         pkt.size= ret;
01914                         if(enc->coded_frame && enc->coded_frame->pts != AV_NOPTS_VALUE)
01915                             pkt.pts= av_rescale_q(enc->coded_frame->pts, enc->time_base, ost->st->time_base);
01916                         write_frame(os, &pkt, ost->st->codec, ost->bitstream_filters);
01917                     }
01918                 }
01919             }
01920         }
01921     }
01922 
01923     return 0;
01924  fail_decode:
01925     return -1;
01926 }
01927 
01928 static void print_sdp(AVFormatContext **avc, int n)
01929 {
01930     char sdp[2048];
01931 
01932     av_sdp_create(avc, n, sdp, sizeof(sdp));
01933     printf("SDP:\n%s\n", sdp);
01934     fflush(stdout);
01935 }
01936 
01937 static int copy_chapters(int infile, int outfile)
01938 {
01939     AVFormatContext *is = input_files[infile].ctx;
01940     AVFormatContext *os = output_files[outfile];
01941     int i;
01942 
01943     for (i = 0; i < is->nb_chapters; i++) {
01944         AVChapter *in_ch = is->chapters[i], *out_ch;
01945         int64_t ts_off   = av_rescale_q(start_time - input_files_ts_offset[infile],
01946                                       AV_TIME_BASE_Q, in_ch->time_base);
01947         int64_t rt       = (recording_time == INT64_MAX) ? INT64_MAX :
01948                            av_rescale_q(recording_time, AV_TIME_BASE_Q, in_ch->time_base);
01949 
01950 
01951         if (in_ch->end < ts_off)
01952             continue;
01953         if (rt != INT64_MAX && in_ch->start > rt + ts_off)
01954             break;
01955 
01956         out_ch = av_mallocz(sizeof(AVChapter));
01957         if (!out_ch)
01958             return AVERROR(ENOMEM);
01959 
01960         out_ch->id        = in_ch->id;
01961         out_ch->time_base = in_ch->time_base;
01962         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
01963         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
01964 
01965         if (metadata_chapters_autocopy)
01966             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
01967 
01968         os->nb_chapters++;
01969         os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
01970         if (!os->chapters)
01971             return AVERROR(ENOMEM);
01972         os->chapters[os->nb_chapters - 1] = out_ch;
01973     }
01974     return 0;
01975 }
01976 
01977 static void parse_forced_key_frames(char *kf, AVOutputStream *ost,
01978                                     AVCodecContext *avctx)
01979 {
01980     char *p;
01981     int n = 1, i;
01982     int64_t t;
01983 
01984     for (p = kf; *p; p++)
01985         if (*p == ',')
01986             n++;
01987     ost->forced_kf_count = n;
01988     ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
01989     if (!ost->forced_kf_pts) {
01990         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
01991         ffmpeg_exit(1);
01992     }
01993     for (i = 0; i < n; i++) {
01994         p = i ? strchr(p, ',') + 1 : kf;
01995         t = parse_time_or_die("force_key_frames", p, 1);
01996         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
01997     }
01998 }
01999 
02000 /*
02001  * The following code is the main loop of the file converter
02002  */
02003 static int transcode(AVFormatContext **output_files,
02004                      int nb_output_files,
02005                      AVInputFile *input_files,
02006                      int nb_input_files,
02007                      AVStreamMap *stream_maps, int nb_stream_maps)
02008 {
02009     int ret = 0, i, j, k, n, nb_ostreams = 0, step;
02010 
02011     AVFormatContext *is, *os;
02012     AVCodecContext *codec, *icodec;
02013     AVOutputStream *ost, **ost_table = NULL;
02014     AVInputStream *ist;
02015     char error[1024];
02016     int key;
02017     int want_sdp = 1;
02018     uint8_t no_packet[MAX_FILES]={0};
02019     int no_packet_count=0;
02020     int nb_frame_threshold[AVMEDIA_TYPE_NB]={0};
02021     int nb_streams[AVMEDIA_TYPE_NB]={0};
02022 
02023     if (rate_emu)
02024         for (i = 0; i < nb_input_streams; i++)
02025             input_streams[i].start = av_gettime();
02026 
02027     /* output stream init */
02028     nb_ostreams = 0;
02029     for(i=0;i<nb_output_files;i++) {
02030         os = output_files[i];
02031         if (!os->nb_streams && !(os->oformat->flags & AVFMT_NOSTREAMS)) {
02032             av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02033             fprintf(stderr, "Output file #%d does not contain any stream\n", i);
02034             ret = AVERROR(EINVAL);
02035             goto fail;
02036         }
02037         nb_ostreams += os->nb_streams;
02038     }
02039     if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
02040         fprintf(stderr, "Number of stream maps must match number of output streams\n");
02041         ret = AVERROR(EINVAL);
02042         goto fail;
02043     }
02044 
02045     /* Sanity check the mapping args -- do the input files & streams exist? */
02046     for(i=0;i<nb_stream_maps;i++) {
02047         int fi = stream_maps[i].file_index;
02048         int si = stream_maps[i].stream_index;
02049 
02050         if (fi < 0 || fi > nb_input_files - 1 ||
02051             si < 0 || si > input_files[fi].nb_streams - 1) {
02052             fprintf(stderr,"Could not find input stream #%d.%d\n", fi, si);
02053             ret = AVERROR(EINVAL);
02054             goto fail;
02055         }
02056         fi = stream_maps[i].sync_file_index;
02057         si = stream_maps[i].sync_stream_index;
02058         if (fi < 0 || fi > nb_input_files - 1 ||
02059             si < 0 || si > input_files[fi].nb_streams - 1) {
02060             fprintf(stderr,"Could not find sync stream #%d.%d\n", fi, si);
02061             ret = AVERROR(EINVAL);
02062             goto fail;
02063         }
02064     }
02065 
02066     ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
02067     if (!ost_table)
02068         goto fail;
02069 
02070     for(k=0;k<nb_output_files;k++) {
02071         os = output_files[k];
02072         for(i=0;i<os->nb_streams;i++,n++) {
02073             nb_streams[os->streams[i]->codec->codec_type]++;
02074         }
02075     }
02076     for(step=1<<30; step; step>>=1){
02077         int found_streams[AVMEDIA_TYPE_NB]={0};
02078         for(j=0; j<AVMEDIA_TYPE_NB; j++)
02079             nb_frame_threshold[j] += step;
02080 
02081         for(j=0; j<nb_input_streams; j++) {
02082             int skip=0;
02083             ist = &input_streams[j];
02084             if(opt_programid){
02085                 int pi,si;
02086                 AVFormatContext *f= input_files[ ist->file_index ].ctx;
02087                 skip=1;
02088                 for(pi=0; pi<f->nb_programs; pi++){
02089                     AVProgram *p= f->programs[pi];
02090                     if(p->id == opt_programid)
02091                         for(si=0; si<p->nb_stream_indexes; si++){
02092                             if(f->streams[ p->stream_index[si] ] == ist->st)
02093                                 skip=0;
02094                         }
02095                 }
02096             }
02097             if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip
02098                 && nb_frame_threshold[ist->st->codec->codec_type] <= ist->st->codec_info_nb_frames){
02099                 found_streams[ist->st->codec->codec_type]++;
02100             }
02101         }
02102         for(j=0; j<AVMEDIA_TYPE_NB; j++)
02103             if(found_streams[j] < nb_streams[j])
02104                 nb_frame_threshold[j] -= step;
02105     }
02106     n = 0;
02107     for(k=0;k<nb_output_files;k++) {
02108         os = output_files[k];
02109         for(i=0;i<os->nb_streams;i++,n++) {
02110             int found;
02111             ost = ost_table[n] = output_streams_for_file[k][i];
02112             ost->st = os->streams[i];
02113             if (nb_stream_maps > 0) {
02114                 ost->source_index = input_files[stream_maps[n].file_index].ist_index +
02115                     stream_maps[n].stream_index;
02116 
02117                 /* Sanity check that the stream types match */
02118                 if (input_streams[ost->source_index].st->codec->codec_type != ost->st->codec->codec_type) {
02119                     int i= ost->file_index;
02120                     av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02121                     fprintf(stderr, "Codec type mismatch for mapping #%d.%d -> #%d.%d\n",
02122                         stream_maps[n].file_index, stream_maps[n].stream_index,
02123                         ost->file_index, ost->index);
02124                     ffmpeg_exit(1);
02125                 }
02126 
02127             } else {
02128                 /* get corresponding input stream index : we select the first one with the right type */
02129                 found = 0;
02130                 for (j = 0; j < nb_input_streams; j++) {
02131                     int skip=0;
02132                     ist = &input_streams[j];
02133                     if(opt_programid){
02134                         int pi,si;
02135                         AVFormatContext *f = input_files[ist->file_index].ctx;
02136                         skip=1;
02137                         for(pi=0; pi<f->nb_programs; pi++){
02138                             AVProgram *p= f->programs[pi];
02139                             if(p->id == opt_programid)
02140                                 for(si=0; si<p->nb_stream_indexes; si++){
02141                                     if(f->streams[ p->stream_index[si] ] == ist->st)
02142                                         skip=0;
02143                                 }
02144                         }
02145                     }
02146                     if (ist->discard && ist->st->discard != AVDISCARD_ALL && !skip &&
02147                         ist->st->codec->codec_type == ost->st->codec->codec_type &&
02148                         nb_frame_threshold[ist->st->codec->codec_type] <= ist->st->codec_info_nb_frames) {
02149                             ost->source_index = j;
02150                             found = 1;
02151                             break;
02152                     }
02153                 }
02154 
02155                 if (!found) {
02156                     if(! opt_programid) {
02157                         /* try again and reuse existing stream */
02158                         for (j = 0; j < nb_input_streams; j++) {
02159                             ist = &input_streams[j];
02160                             if (   ist->st->codec->codec_type == ost->st->codec->codec_type
02161                                 && ist->st->discard != AVDISCARD_ALL) {
02162                                 ost->source_index = j;
02163                                 found = 1;
02164                             }
02165                         }
02166                     }
02167                     if (!found) {
02168                         int i= ost->file_index;
02169                         av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02170                         fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
02171                                 ost->file_index, ost->index);
02172                         ffmpeg_exit(1);
02173                     }
02174                 }
02175             }
02176             ist = &input_streams[ost->source_index];
02177             ist->discard = 0;
02178             ost->sync_ist = (nb_stream_maps > 0) ?
02179                 &input_streams[input_files[stream_maps[n].sync_file_index].ist_index +
02180                          stream_maps[n].sync_stream_index] : ist;
02181         }
02182     }
02183 
02184     /* for each output stream, we compute the right encoding parameters */
02185     for(i=0;i<nb_ostreams;i++) {
02186         ost = ost_table[i];
02187         os = output_files[ost->file_index];
02188         ist = &input_streams[ost->source_index];
02189 
02190         codec = ost->st->codec;
02191         icodec = ist->st->codec;
02192 
02193         if (metadata_streams_autocopy)
02194             av_dict_copy(&ost->st->metadata, ist->st->metadata,
02195                          AV_DICT_DONT_OVERWRITE);
02196 
02197         ost->st->disposition = ist->st->disposition;
02198         codec->bits_per_raw_sample= icodec->bits_per_raw_sample;
02199         codec->chroma_sample_location = icodec->chroma_sample_location;
02200 
02201         if (ost->st->stream_copy) {
02202             uint64_t extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
02203 
02204             if (extra_size > INT_MAX)
02205                 goto fail;
02206 
02207             /* if stream_copy is selected, no need to decode or encode */
02208             codec->codec_id = icodec->codec_id;
02209             codec->codec_type = icodec->codec_type;
02210 
02211             if(!codec->codec_tag){
02212                 if(   !os->oformat->codec_tag
02213                    || av_codec_get_id (os->oformat->codec_tag, icodec->codec_tag) == codec->codec_id
02214                    || av_codec_get_tag(os->oformat->codec_tag, icodec->codec_id) <= 0)
02215                     codec->codec_tag = icodec->codec_tag;
02216             }
02217 
02218             codec->bit_rate = icodec->bit_rate;
02219             codec->rc_max_rate    = icodec->rc_max_rate;
02220             codec->rc_buffer_size = icodec->rc_buffer_size;
02221             codec->extradata= av_mallocz(extra_size);
02222             if (!codec->extradata)
02223                 goto fail;
02224             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
02225             codec->extradata_size= icodec->extradata_size;
02226             if(!copy_tb && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base) && av_q2d(ist->st->time_base) < 1.0/500){
02227                 codec->time_base = icodec->time_base;
02228                 codec->time_base.num *= icodec->ticks_per_frame;
02229                 av_reduce(&codec->time_base.num, &codec->time_base.den,
02230                           codec->time_base.num, codec->time_base.den, INT_MAX);
02231             }else
02232                 codec->time_base = ist->st->time_base;
02233             switch(codec->codec_type) {
02234             case AVMEDIA_TYPE_AUDIO:
02235                 if(audio_volume != 256) {
02236                     fprintf(stderr,"-acodec copy and -vol are incompatible (frames are not decoded)\n");
02237                     ffmpeg_exit(1);
02238                 }
02239                 codec->channel_layout = icodec->channel_layout;
02240                 codec->sample_rate = icodec->sample_rate;
02241                 codec->channels = icodec->channels;
02242                 codec->frame_size = icodec->frame_size;
02243                 codec->audio_service_type = icodec->audio_service_type;
02244                 codec->block_align= icodec->block_align;
02245                 if(codec->block_align == 1 && codec->codec_id == CODEC_ID_MP3)
02246                     codec->block_align= 0;
02247                 if(codec->codec_id == CODEC_ID_AC3)
02248                     codec->block_align= 0;
02249                 break;
02250             case AVMEDIA_TYPE_VIDEO:
02251                 codec->pix_fmt = icodec->pix_fmt;
02252                 codec->width = icodec->width;
02253                 codec->height = icodec->height;
02254                 codec->has_b_frames = icodec->has_b_frames;
02255                 if (!codec->sample_aspect_ratio.num) {
02256                     codec->sample_aspect_ratio =
02257                     ost->st->sample_aspect_ratio =
02258                         ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
02259                         ist->st->codec->sample_aspect_ratio.num ?
02260                         ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
02261                 }
02262                 break;
02263             case AVMEDIA_TYPE_SUBTITLE:
02264                 codec->width = icodec->width;
02265                 codec->height = icodec->height;
02266                 break;
02267             case AVMEDIA_TYPE_DATA:
02268                 break;
02269             default:
02270                 abort();
02271             }
02272         } else {
02273             if (!ost->enc)
02274                 ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
02275             switch(codec->codec_type) {
02276             case AVMEDIA_TYPE_AUDIO:
02277                 ost->fifo= av_fifo_alloc(1024);
02278                 if(!ost->fifo)
02279                     goto fail;
02280                 ost->reformat_pair = MAKE_SFMT_PAIR(AV_SAMPLE_FMT_NONE,AV_SAMPLE_FMT_NONE);
02281                 if (!codec->sample_rate) {
02282                     codec->sample_rate = icodec->sample_rate;
02283                     if (icodec->lowres)
02284                         codec->sample_rate >>= icodec->lowres;
02285                 }
02286                 choose_sample_rate(ost->st, ost->enc);
02287                 codec->time_base = (AVRational){1, codec->sample_rate};
02288                 if (!codec->channels)
02289                     codec->channels = icodec->channels;
02290                 if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
02291                     codec->channel_layout = 0;
02292                 ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
02293                 icodec->request_channels = codec->channels;
02294                 ist->decoding_needed = 1;
02295                 ost->encoding_needed = 1;
02296                 ost->resample_sample_fmt  = icodec->sample_fmt;
02297                 ost->resample_sample_rate = icodec->sample_rate;
02298                 ost->resample_channels    = icodec->channels;
02299                 break;
02300             case AVMEDIA_TYPE_VIDEO:
02301                 if (codec->pix_fmt == PIX_FMT_NONE)
02302                     codec->pix_fmt = icodec->pix_fmt;
02303                 choose_pixel_fmt(ost->st, ost->enc);
02304 
02305                 if (ost->st->codec->pix_fmt == PIX_FMT_NONE) {
02306                     fprintf(stderr, "Video pixel format is unknown, stream cannot be encoded\n");
02307                     ffmpeg_exit(1);
02308                 }
02309 
02310                 if (!codec->width || !codec->height) {
02311                     codec->width  = icodec->width;
02312                     codec->height = icodec->height;
02313                 }
02314 
02315                 ost->video_resample = codec->width   != icodec->width  ||
02316                                       codec->height  != icodec->height ||
02317                                       codec->pix_fmt != icodec->pix_fmt;
02318                 if (ost->video_resample) {
02319                     codec->bits_per_raw_sample= frame_bits_per_raw_sample;
02320                 }
02321 
02322                 ost->resample_height = icodec->height;
02323                 ost->resample_width  = icodec->width;
02324                 ost->resample_pix_fmt= icodec->pix_fmt;
02325                 ost->encoding_needed = 1;
02326                 ist->decoding_needed = 1;
02327 
02328                 if (!ost->frame_rate.num)
02329                     ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
02330                 if (ost->enc && ost->enc->supported_framerates && !force_fps) {
02331                     int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
02332                     ost->frame_rate = ost->enc->supported_framerates[idx];
02333                 }
02334                 codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};
02335                 if(   av_q2d(codec->time_base) < 0.001 && video_sync_method
02336                    && (video_sync_method==1 || (video_sync_method<0 && !(os->oformat->flags & AVFMT_VARIABLE_FPS)))){
02337                     av_log(os, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
02338                                                "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
02339                 }
02340 
02341                 if (ost->forced_key_frames)
02342                     parse_forced_key_frames(ost->forced_key_frames, ost, codec);
02343 
02344 #if CONFIG_AVFILTER
02345                 if (configure_video_filters(ist, ost)) {
02346                     fprintf(stderr, "Error opening filters!\n");
02347                     exit(1);
02348                 }
02349 #endif
02350                 break;
02351             case AVMEDIA_TYPE_SUBTITLE:
02352                 ost->encoding_needed = 1;
02353                 ist->decoding_needed = 1;
02354                 break;
02355             default:
02356                 abort();
02357                 break;
02358             }
02359             /* two pass mode */
02360             if (ost->encoding_needed && codec->codec_id != CODEC_ID_H264 &&
02361                 (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
02362                 char logfilename[1024];
02363                 FILE *f;
02364 
02365                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
02366                          pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
02367                          i);
02368                 if (codec->flags & CODEC_FLAG_PASS1) {
02369                     f = fopen(logfilename, "wb");
02370                     if (!f) {
02371                         fprintf(stderr, "Cannot write log file '%s' for pass-1 encoding: %s\n", logfilename, strerror(errno));
02372                         ffmpeg_exit(1);
02373                     }
02374                     ost->logfile = f;
02375                 } else {
02376                     char  *logbuffer;
02377                     size_t logbuffer_size;
02378                     if (read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
02379                         fprintf(stderr, "Error reading log file '%s' for pass-2 encoding\n", logfilename);
02380                         ffmpeg_exit(1);
02381                     }
02382                     codec->stats_in = logbuffer;
02383                 }
02384             }
02385         }
02386         if(codec->codec_type == AVMEDIA_TYPE_VIDEO){
02387             /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)*/
02388             int size= codec->width * codec->height;
02389             bit_buffer_size= FFMAX(bit_buffer_size, 7*size + 10000);
02390         }
02391     }
02392 
02393     if (!bit_buffer)
02394         bit_buffer = av_malloc(bit_buffer_size);
02395     if (!bit_buffer) {
02396         fprintf(stderr, "Cannot allocate %d bytes output buffer\n",
02397                 bit_buffer_size);
02398         ret = AVERROR(ENOMEM);
02399         goto fail;
02400     }
02401 
02402     /* open each encoder */
02403     for(i=0;i<nb_ostreams;i++) {
02404         ost = ost_table[i];
02405         if (ost->encoding_needed) {
02406             AVCodec *codec = ost->enc;
02407             AVCodecContext *dec = input_streams[ost->source_index].st->codec;
02408             if (!codec) {
02409                 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d.%d",
02410                          ost->st->codec->codec_id, ost->file_index, ost->index);
02411                 ret = AVERROR(EINVAL);
02412                 goto dump_format;
02413             }
02414             if (dec->subtitle_header) {
02415                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
02416                 if (!ost->st->codec->subtitle_header) {
02417                     ret = AVERROR(ENOMEM);
02418                     goto dump_format;
02419                 }
02420                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
02421                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
02422             }
02423             if (avcodec_open(ost->st->codec, codec) < 0) {
02424                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height",
02425                         ost->file_index, ost->index);
02426                 ret = AVERROR(EINVAL);
02427                 goto dump_format;
02428             }
02429             extra_size += ost->st->codec->extradata_size;
02430         }
02431     }
02432 
02433     /* open each decoder */
02434     for (i = 0; i < nb_input_streams; i++) {
02435         ist = &input_streams[i];
02436         if (ist->decoding_needed) {
02437             AVCodec *codec = i < nb_input_codecs ? input_codecs[i] : NULL;
02438             if (!codec)
02439                 codec = avcodec_find_decoder(ist->st->codec->codec_id);
02440             if (!codec) {
02441                 snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
02442                         ist->st->codec->codec_id, ist->file_index, ist->st->index);
02443                 ret = AVERROR(EINVAL);
02444                 goto dump_format;
02445             }
02446             if (avcodec_open(ist->st->codec, codec) < 0) {
02447                 snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
02448                         ist->file_index, ist->st->index);
02449                 ret = AVERROR(EINVAL);
02450                 goto dump_format;
02451             }
02452             //if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
02453             //    ist->st->codec->flags |= CODEC_FLAG_REPEAT_FIELD;
02454         }
02455     }
02456 
02457     /* init pts */
02458     for (i = 0; i < nb_input_streams; i++) {
02459         AVStream *st;
02460         ist = &input_streams[i];
02461         st= ist->st;
02462         ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
02463         ist->next_pts = AV_NOPTS_VALUE;
02464         ist->is_start = 1;
02465     }
02466 
02467     /* set meta data information from input file if required */
02468     for (i=0;i<nb_meta_data_maps;i++) {
02469         AVFormatContext *files[2];
02470         AVDictionary    **meta[2];
02471         int j;
02472 
02473 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
02474         if ((index) < 0 || (index) >= (nb_elems)) {\
02475             snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
02476                      (desc), (index));\
02477             ret = AVERROR(EINVAL);\
02478             goto dump_format;\
02479         }
02480 
02481         int out_file_index = meta_data_maps[i][0].file;
02482         int in_file_index = meta_data_maps[i][1].file;
02483         if (in_file_index < 0 || out_file_index < 0)
02484             continue;
02485         METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
02486         METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
02487 
02488         files[0] = output_files[out_file_index];
02489         files[1] = input_files[in_file_index].ctx;
02490 
02491         for (j = 0; j < 2; j++) {
02492             AVMetaDataMap *map = &meta_data_maps[i][j];
02493 
02494             switch (map->type) {
02495             case 'g':
02496                 meta[j] = &files[j]->metadata;
02497                 break;
02498             case 's':
02499                 METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
02500                 meta[j] = &files[j]->streams[map->index]->metadata;
02501                 break;
02502             case 'c':
02503                 METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
02504                 meta[j] = &files[j]->chapters[map->index]->metadata;
02505                 break;
02506             case 'p':
02507                 METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
02508                 meta[j] = &files[j]->programs[map->index]->metadata;
02509                 break;
02510             }
02511         }
02512 
02513         av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
02514     }
02515 
02516     /* copy global metadata by default */
02517     if (metadata_global_autocopy) {
02518 
02519         for (i = 0; i < nb_output_files; i++)
02520             av_dict_copy(&output_files[i]->metadata, input_files[0].ctx->metadata,
02521                          AV_DICT_DONT_OVERWRITE);
02522     }
02523 
02524     /* copy chapters according to chapter maps */
02525     for (i = 0; i < nb_chapter_maps; i++) {
02526         int infile  = chapter_maps[i].in_file;
02527         int outfile = chapter_maps[i].out_file;
02528 
02529         if (infile < 0 || outfile < 0)
02530             continue;
02531         if (infile >= nb_input_files) {
02532             snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
02533             ret = AVERROR(EINVAL);
02534             goto dump_format;
02535         }
02536         if (outfile >= nb_output_files) {
02537             snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
02538             ret = AVERROR(EINVAL);
02539             goto dump_format;
02540         }
02541         copy_chapters(infile, outfile);
02542     }
02543 
02544     /* copy chapters from the first input file that has them*/
02545     if (!nb_chapter_maps)
02546         for (i = 0; i < nb_input_files; i++) {
02547             if (!input_files[i].ctx->nb_chapters)
02548                 continue;
02549 
02550             for (j = 0; j < nb_output_files; j++)
02551                 if ((ret = copy_chapters(i, j)) < 0)
02552                     goto dump_format;
02553             break;
02554         }
02555 
02556     /* open files and write file headers */
02557     for(i=0;i<nb_output_files;i++) {
02558         os = output_files[i];
02559         if (av_write_header(os) < 0) {
02560             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
02561             ret = AVERROR(EINVAL);
02562             goto dump_format;
02563         }
02564         if (strcmp(output_files[i]->oformat->name, "rtp")) {
02565             want_sdp = 0;
02566         }
02567     }
02568 
02569  dump_format:
02570     /* dump the file output parameters - cannot be done before in case
02571        of stream copy */
02572     for(i=0;i<nb_output_files;i++) {
02573         av_dump_format(output_files[i], i, output_files[i]->filename, 1);
02574     }
02575 
02576     /* dump the stream mapping */
02577     if (verbose >= 0) {
02578         fprintf(stderr, "Stream mapping:\n");
02579         for(i=0;i<nb_ostreams;i++) {
02580             ost = ost_table[i];
02581             fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
02582                     input_streams[ost->source_index].file_index,
02583                     input_streams[ost->source_index].st->index,
02584                     ost->file_index,
02585                     ost->index);
02586             if (ost->sync_ist != &input_streams[ost->source_index])
02587                 fprintf(stderr, " [sync #%d.%d]",
02588                         ost->sync_ist->file_index,
02589                         ost->sync_ist->st->index);
02590             fprintf(stderr, "\n");
02591         }
02592     }
02593 
02594     if (ret) {
02595         fprintf(stderr, "%s\n", error);
02596         goto fail;
02597     }
02598 
02599     if (want_sdp) {
02600         print_sdp(output_files, nb_output_files);
02601     }
02602 
02603     if (!using_stdin) {
02604         if(verbose >= 0)
02605             fprintf(stderr, "Press [q] to stop, [?] for help\n");
02606         avio_set_interrupt_cb(decode_interrupt_cb);
02607     }
02608     term_init();
02609 
02610     timer_start = av_gettime();
02611 
02612     for(; received_sigterm == 0;) {
02613         int file_index, ist_index;
02614         AVPacket pkt;
02615         double ipts_min;
02616         double opts_min;
02617 
02618     redo:
02619         ipts_min= 1e100;
02620         opts_min= 1e100;
02621         /* if 'q' pressed, exits */
02622         if (!using_stdin) {
02623             if (q_pressed)
02624                 break;
02625             /* read_key() returns 0 on EOF */
02626             key = read_key();
02627             if (key == 'q')
02628                 break;
02629             if (key == '+') verbose++;
02630             if (key == '-') verbose--;
02631             if (key == 's') qp_hist     ^= 1;
02632             if (key == 'h'){
02633                 if (do_hex_dump){
02634                     do_hex_dump = do_pkt_dump = 0;
02635                 } else if(do_pkt_dump){
02636                     do_hex_dump = 1;
02637                 } else
02638                     do_pkt_dump = 1;
02639                 av_log_set_level(AV_LOG_DEBUG);
02640             }
02641             if (key == 'd' || key == 'D'){
02642                 int debug=0;
02643                 if(key == 'D') {
02644                     debug = input_streams[0].st->codec->debug<<1;
02645                     if(!debug) debug = 1;
02646                     while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
02647                         debug += debug;
02648                 }else
02649                     scanf("%d", &debug);
02650                 for(i=0;i<nb_input_streams;i++) {
02651                     input_streams[i].st->codec->debug = debug;
02652                 }
02653                 for(i=0;i<nb_ostreams;i++) {
02654                     ost = ost_table[i];
02655                     ost->st->codec->debug = debug;
02656                 }
02657                 if(debug) av_log_set_level(AV_LOG_DEBUG);
02658                 fprintf(stderr,"debug=%d\n", debug);
02659             }
02660             if (key == '?'){
02661                 fprintf(stderr, "key    function\n"
02662                                 "?      show this help\n"
02663                                 "+      increase verbosity\n"
02664                                 "-      decrease verbosity\n"
02665                                 "D      cycle through available debug modes\n"
02666                                 "h      dump packets/hex press to cycle through the 3 states\n"
02667                                 "q      quit\n"
02668                                 "s      Show QP histogram\n"
02669                 );
02670             }
02671         }
02672 
02673         /* select the stream that we must read now by looking at the
02674            smallest output pts */
02675         file_index = -1;
02676         for(i=0;i<nb_ostreams;i++) {
02677             double ipts, opts;
02678             ost = ost_table[i];
02679             os = output_files[ost->file_index];
02680             ist = &input_streams[ost->source_index];
02681             if(ist->is_past_recording_time || no_packet[ist->file_index])
02682                 continue;
02683                 opts = ost->st->pts.val * av_q2d(ost->st->time_base);
02684             ipts = (double)ist->pts;
02685             if (!input_files[ist->file_index].eof_reached){
02686                 if(ipts < ipts_min) {
02687                     ipts_min = ipts;
02688                     if(input_sync ) file_index = ist->file_index;
02689                 }
02690                 if(opts < opts_min) {
02691                     opts_min = opts;
02692                     if(!input_sync) file_index = ist->file_index;
02693                 }
02694             }
02695             if(ost->frame_number >= max_frames[ost->st->codec->codec_type]){
02696                 file_index= -1;
02697                 break;
02698             }
02699         }
02700         /* if none, if is finished */
02701         if (file_index < 0) {
02702             if(no_packet_count){
02703                 no_packet_count=0;
02704                 memset(no_packet, 0, sizeof(no_packet));
02705                 usleep(10000);
02706                 continue;
02707             }
02708             break;
02709         }
02710 
02711         /* finish if limit size exhausted */
02712         if (limit_filesize != 0 && limit_filesize <= avio_tell(output_files[0]->pb))
02713             break;
02714 
02715         /* read a frame from it and output it in the fifo */
02716         is = input_files[file_index].ctx;
02717         ret= av_read_frame(is, &pkt);
02718         if(ret == AVERROR(EAGAIN)){
02719             no_packet[file_index]=1;
02720             no_packet_count++;
02721             continue;
02722         }
02723         if (ret < 0) {
02724             input_files[file_index].eof_reached = 1;
02725             if (opt_shortest)
02726                 break;
02727             else
02728                 continue;
02729         }
02730 
02731         no_packet_count=0;
02732         memset(no_packet, 0, sizeof(no_packet));
02733 
02734         if (do_pkt_dump) {
02735             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
02736                              is->streams[pkt.stream_index]);
02737         }
02738         /* the following test is needed in case new streams appear
02739            dynamically in stream : we ignore them */
02740         if (pkt.stream_index >= input_files[file_index].nb_streams)
02741             goto discard_packet;
02742         ist_index = input_files[file_index].ist_index + pkt.stream_index;
02743         ist = &input_streams[ist_index];
02744         if (ist->discard)
02745             goto discard_packet;
02746 
02747         if (pkt.dts != AV_NOPTS_VALUE)
02748             pkt.dts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
02749         if (pkt.pts != AV_NOPTS_VALUE)
02750             pkt.pts += av_rescale_q(input_files_ts_offset[ist->file_index], AV_TIME_BASE_Q, ist->st->time_base);
02751 
02752         if (pkt.stream_index < nb_input_files_ts_scale[file_index]
02753             && input_files_ts_scale[file_index][pkt.stream_index]){
02754             if(pkt.pts != AV_NOPTS_VALUE)
02755                 pkt.pts *= input_files_ts_scale[file_index][pkt.stream_index];
02756             if(pkt.dts != AV_NOPTS_VALUE)
02757                 pkt.dts *= input_files_ts_scale[file_index][pkt.stream_index];
02758         }
02759 
02760 //        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);
02761         if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
02762             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
02763             int64_t pkt_dts= av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
02764             int64_t delta= pkt_dts - ist->next_pts;
02765             if((FFABS(delta) > 1LL*dts_delta_threshold*AV_TIME_BASE || pkt_dts+1<ist->pts)&& !copy_ts){
02766                 input_files_ts_offset[ist->file_index]-= delta;
02767                 if (verbose > 2)
02768                     fprintf(stderr, "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n", delta, input_files_ts_offset[ist->file_index]);
02769                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02770                 if(pkt.pts != AV_NOPTS_VALUE)
02771                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02772             }
02773         }
02774 
02775         /* finish if recording time exhausted */
02776         if (recording_time != INT64_MAX &&
02777             (pkt.pts != AV_NOPTS_VALUE ?
02778                 av_compare_ts(pkt.pts, ist->st->time_base, recording_time + start_time, (AVRational){1, 1000000})
02779                     :
02780                 av_compare_ts(ist->pts, AV_TIME_BASE_Q, recording_time + start_time, (AVRational){1, 1000000})
02781             )>= 0) {
02782             ist->is_past_recording_time = 1;
02783             goto discard_packet;
02784         }
02785 
02786         //fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
02787         if (output_packet(ist, ist_index, ost_table, nb_ostreams, &pkt) < 0) {
02788 
02789             if (verbose >= 0)
02790                 fprintf(stderr, "Error while decoding stream #%d.%d\n",
02791                         ist->file_index, ist->st->index);
02792             if (exit_on_error)
02793                 ffmpeg_exit(1);
02794             av_free_packet(&pkt);
02795             goto redo;
02796         }
02797 
02798     discard_packet:
02799         av_free_packet(&pkt);
02800 
02801         /* dump report by using the output first video and audio streams */
02802         print_report(output_files, ost_table, nb_ostreams, 0);
02803     }
02804 
02805     /* at the end of stream, we must flush the decoder buffers */
02806     for (i = 0; i < nb_input_streams; i++) {
02807         ist = &input_streams[i];
02808         if (ist->decoding_needed) {
02809             output_packet(ist, i, ost_table, nb_ostreams, NULL);
02810         }
02811     }
02812 
02813     term_exit();
02814 
02815     /* write the trailer if needed and close file */
02816     for(i=0;i<nb_output_files;i++) {
02817         os = output_files[i];
02818         av_write_trailer(os);
02819     }
02820 
02821     /* dump report by using the first video and audio streams */
02822     print_report(output_files, ost_table, nb_ostreams, 1);
02823 
02824     /* close each encoder */
02825     for(i=0;i<nb_ostreams;i++) {
02826         ost = ost_table[i];
02827         if (ost->encoding_needed) {
02828             av_freep(&ost->st->codec->stats_in);
02829             avcodec_close(ost->st->codec);
02830         }
02831 #if CONFIG_AVFILTER
02832         avfilter_graph_free(&ost->graph);
02833 #endif
02834     }
02835 
02836     /* close each decoder */
02837     for (i = 0; i < nb_input_streams; i++) {
02838         ist = &input_streams[i];
02839         if (ist->decoding_needed) {
02840             avcodec_close(ist->st->codec);
02841         }
02842     }
02843 
02844     /* finished ! */
02845     ret = 0;
02846 
02847  fail:
02848     av_freep(&bit_buffer);
02849 
02850     if (ost_table) {
02851         for(i=0;i<nb_ostreams;i++) {
02852             ost = ost_table[i];
02853             if (ost) {
02854                 if (ost->st->stream_copy)
02855                     av_freep(&ost->st->codec->extradata);
02856                 if (ost->logfile) {
02857                     fclose(ost->logfile);
02858                     ost->logfile = NULL;
02859                 }
02860                 av_fifo_free(ost->fifo); /* works even if fifo is not
02861                                              initialized but set to zero */
02862                 av_freep(&ost->st->codec->subtitle_header);
02863                 av_free(ost->resample_frame.data[0]);
02864                 av_free(ost->forced_kf_pts);
02865                 av_free(ost->forced_key_frames);
02866                 if (ost->video_resample)
02867                     sws_freeContext(ost->img_resample_ctx);
02868                 if (ost->resample)
02869                     audio_resample_close(ost->resample);
02870                 if (ost->reformat_ctx)
02871                     av_audio_convert_free(ost->reformat_ctx);
02872                 av_free(ost);
02873             }
02874         }
02875         av_free(ost_table);
02876     }
02877     return ret;
02878 }
02879 
02880 static int opt_format(const char *opt, const char *arg)
02881 {
02882     last_asked_format = arg;
02883     return 0;
02884 }
02885 
02886 static int opt_video_rc_override_string(const char *opt, const char *arg)
02887 {
02888     video_rc_override_string = arg;
02889     return 0;
02890 }
02891 
02892 static int opt_me_threshold(const char *opt, const char *arg)
02893 {
02894     me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
02895     return 0;
02896 }
02897 
02898 static int opt_verbose(const char *opt, const char *arg)
02899 {
02900     verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
02901     return 0;
02902 }
02903 
02904 static int opt_frame_rate(const char *opt, const char *arg)
02905 {
02906     if (av_parse_video_rate(&frame_rate, arg) < 0) {
02907         fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
02908         ffmpeg_exit(1);
02909     }
02910     return 0;
02911 }
02912 
02913 static int opt_bitrate(const char *opt, const char *arg)
02914 {
02915     int codec_type = opt[0]=='a' ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
02916 
02917     opt_default(opt, arg);
02918 
02919     if (av_get_int(avcodec_opts[codec_type], "b", NULL) < 1000)
02920         fprintf(stderr, "WARNING: The bitrate parameter is set too low. It takes bits/s as argument, not kbits/s\n");
02921 
02922     return 0;
02923 }
02924 
02925 static int opt_frame_crop(const char *opt, const char *arg)
02926 {
02927     fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
02928     return AVERROR(EINVAL);
02929 }
02930 
02931 static int opt_frame_size(const char *opt, const char *arg)
02932 {
02933     if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
02934         fprintf(stderr, "Incorrect frame size\n");
02935         return AVERROR(EINVAL);
02936     }
02937     return 0;
02938 }
02939 
02940 static int opt_pad(const char *opt, const char *arg) {
02941     fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
02942     return -1;
02943 }
02944 
02945 static int opt_frame_pix_fmt(const char *opt, const char *arg)
02946 {
02947     if (strcmp(arg, "list")) {
02948         frame_pix_fmt = av_get_pix_fmt(arg);
02949         if (frame_pix_fmt == PIX_FMT_NONE) {
02950             fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
02951             return AVERROR(EINVAL);
02952         }
02953     } else {
02954         opt_pix_fmts(NULL, NULL);
02955         ffmpeg_exit(0);
02956     }
02957     return 0;
02958 }
02959 
02960 static int opt_frame_aspect_ratio(const char *opt, const char *arg)
02961 {
02962     int x = 0, y = 0;
02963     double ar = 0;
02964     const char *p;
02965     char *end;
02966 
02967     p = strchr(arg, ':');
02968     if (p) {
02969         x = strtol(arg, &end, 10);
02970         if (end == p)
02971             y = strtol(end+1, &end, 10);
02972         if (x > 0 && y > 0)
02973             ar = (double)x / (double)y;
02974     } else
02975         ar = strtod(arg, NULL);
02976 
02977     if (!ar) {
02978         fprintf(stderr, "Incorrect aspect ratio specification.\n");
02979         return AVERROR(EINVAL);
02980     }
02981     frame_aspect_ratio = ar;
02982     return 0;
02983 }
02984 
02985 static int opt_metadata(const char *opt, const char *arg)
02986 {
02987     char *mid= strchr(arg, '=');
02988 
02989     if(!mid){
02990         fprintf(stderr, "Missing =\n");
02991         ffmpeg_exit(1);
02992     }
02993     *mid++= 0;
02994 
02995     av_dict_set(&metadata, arg, mid, 0);
02996 
02997     return 0;
02998 }
02999 
03000 static int opt_qscale(const char *opt, const char *arg)
03001 {
03002     video_qscale = parse_number_or_die(opt, arg, OPT_FLOAT, 0, 255);
03003     if (video_qscale <= 0 || video_qscale > 255) {
03004         fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
03005         return AVERROR(EINVAL);
03006     }
03007     return 0;
03008 }
03009 
03010 static int opt_top_field_first(const char *opt, const char *arg)
03011 {
03012     top_field_first = parse_number_or_die(opt, arg, OPT_INT, 0, 1);
03013     opt_default(opt, arg);
03014     return 0;
03015 }
03016 
03017 static int opt_thread_count(const char *opt, const char *arg)
03018 {
03019     thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03020 #if !HAVE_THREADS
03021     if (verbose >= 0)
03022         fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
03023 #endif
03024     return 0;
03025 }
03026 
03027 static int opt_audio_sample_fmt(const char *opt, const char *arg)
03028 {
03029     if (strcmp(arg, "list")) {
03030         audio_sample_fmt = av_get_sample_fmt(arg);
03031         if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
03032             av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
03033             return AVERROR(EINVAL);
03034         }
03035     } else {
03036         int i;
03037         char fmt_str[128];
03038         for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
03039             printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
03040         ffmpeg_exit(0);
03041     }
03042     return 0;
03043 }
03044 
03045 static int opt_audio_rate(const char *opt, const char *arg)
03046 {
03047     audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03048     return 0;
03049 }
03050 
03051 static int opt_audio_channels(const char *opt, const char *arg)
03052 {
03053     audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03054     return 0;
03055 }
03056 
03057 static int opt_video_channel(const char *opt, const char *arg)
03058 {
03059     video_channel = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
03060     return 0;
03061 }
03062 
03063 static int opt_video_standard(const char *opt, const char *arg)
03064 {
03065     video_standard = av_strdup(arg);
03066     return 0;
03067 }
03068 
03069 static int opt_codec(const char *opt, const char *arg)
03070 {
03071     int *pstream_copy; char **pcodec_name; enum AVMediaType codec_type;
03072 
03073     if      (!strcmp(opt, "acodec")) { pstream_copy = &audio_stream_copy;    pcodec_name = &audio_codec_name;    codec_type = AVMEDIA_TYPE_AUDIO;    }
03074     else if (!strcmp(opt, "vcodec")) { pstream_copy = &video_stream_copy;    pcodec_name = &video_codec_name;    codec_type = AVMEDIA_TYPE_VIDEO;    }
03075     else if (!strcmp(opt, "scodec")) { pstream_copy = &subtitle_stream_copy; pcodec_name = &subtitle_codec_name; codec_type = AVMEDIA_TYPE_SUBTITLE; }
03076     else if (!strcmp(opt, "dcodec")) { pstream_copy = &data_stream_copy;     pcodec_name = &data_codec_name;     codec_type = AVMEDIA_TYPE_DATA;     }
03077 
03078     av_freep(pcodec_name);
03079     if (!strcmp(arg, "copy")) {
03080         *pstream_copy = 1;
03081     } else {
03082         *pcodec_name = av_strdup(arg);
03083     }
03084     return 0;
03085 }
03086 
03087 static int opt_codec_tag(const char *opt, const char *arg)
03088 {
03089     char *tail;
03090     uint32_t *codec_tag;
03091 
03092     codec_tag = !strcmp(opt, "atag") ? &audio_codec_tag :
03093                 !strcmp(opt, "vtag") ? &video_codec_tag :
03094                 !strcmp(opt, "stag") ? &subtitle_codec_tag : NULL;
03095     if (!codec_tag)
03096         return -1;
03097 
03098     *codec_tag = strtol(arg, &tail, 0);
03099     if (!tail || *tail)
03100         *codec_tag = AV_RL32(arg);
03101 
03102     return 0;
03103 }
03104 
03105 static int opt_map(const char *opt, const char *arg)
03106 {
03107     AVStreamMap *m;
03108     char *p;
03109 
03110     stream_maps = grow_array(stream_maps, sizeof(*stream_maps), &nb_stream_maps, nb_stream_maps + 1);
03111     m = &stream_maps[nb_stream_maps-1];
03112 
03113     m->file_index = strtol(arg, &p, 0);
03114     if (*p)
03115         p++;
03116 
03117     m->stream_index = strtol(p, &p, 0);
03118     if (*p) {
03119         p++;
03120         m->sync_file_index = strtol(p, &p, 0);
03121         if (*p)
03122             p++;
03123         m->sync_stream_index = strtol(p, &p, 0);
03124     } else {
03125         m->sync_file_index = m->file_index;
03126         m->sync_stream_index = m->stream_index;
03127     }
03128     return 0;
03129 }
03130 
03131 static void parse_meta_type(char *arg, char *type, int *index, char **endptr)
03132 {
03133     *endptr = arg;
03134     if (*arg == ',') {
03135         *type = *(++arg);
03136         switch (*arg) {
03137         case 'g':
03138             break;
03139         case 's':
03140         case 'c':
03141         case 'p':
03142             *index = strtol(++arg, endptr, 0);
03143             break;
03144         default:
03145             fprintf(stderr, "Invalid metadata type %c.\n", *arg);
03146             ffmpeg_exit(1);
03147         }
03148     } else
03149         *type = 'g';
03150 }
03151 
03152 static int opt_map_metadata(const char *opt, const char *arg)
03153 {
03154     AVMetaDataMap *m, *m1;
03155     char *p;
03156 
03157     meta_data_maps = grow_array(meta_data_maps, sizeof(*meta_data_maps),
03158                                 &nb_meta_data_maps, nb_meta_data_maps + 1);
03159 
03160     m = &meta_data_maps[nb_meta_data_maps - 1][0];
03161     m->file = strtol(arg, &p, 0);
03162     parse_meta_type(p, &m->type, &m->index, &p);
03163     if (*p)
03164         p++;
03165 
03166     m1 = &meta_data_maps[nb_meta_data_maps - 1][1];
03167     m1->file = strtol(p, &p, 0);
03168     parse_meta_type(p, &m1->type, &m1->index, &p);
03169 
03170     if (m->type == 'g' || m1->type == 'g')
03171         metadata_global_autocopy = 0;
03172     if (m->type == 's' || m1->type == 's')
03173         metadata_streams_autocopy = 0;
03174     if (m->type == 'c' || m1->type == 'c')
03175         metadata_chapters_autocopy = 0;
03176 
03177     return 0;
03178 }
03179 
03180 static int opt_map_meta_data(const char *opt, const char *arg)
03181 {
03182     fprintf(stderr, "-map_meta_data is deprecated and will be removed soon. "
03183                     "Use -map_metadata instead.\n");
03184     return opt_map_metadata(opt, arg);
03185 }
03186 
03187 static int opt_map_chapters(const char *opt, const char *arg)
03188 {
03189     AVChapterMap *c;
03190     char *p;
03191 
03192     chapter_maps = grow_array(chapter_maps, sizeof(*chapter_maps), &nb_chapter_maps,
03193                               nb_chapter_maps + 1);
03194     c = &chapter_maps[nb_chapter_maps - 1];
03195     c->out_file = strtol(arg, &p, 0);
03196     if (*p)
03197         p++;
03198 
03199     c->in_file = strtol(p, &p, 0);
03200     return 0;
03201 }
03202 
03203 static int opt_input_ts_scale(const char *opt, const char *arg)
03204 {
03205     unsigned int stream;
03206     double scale;
03207     char *p;
03208 
03209     stream = strtol(arg, &p, 0);
03210     if (*p)
03211         p++;
03212     scale= strtod(p, &p);
03213 
03214     if(stream >= MAX_STREAMS)
03215         ffmpeg_exit(1);
03216 
03217     input_files_ts_scale[nb_input_files] = grow_array(input_files_ts_scale[nb_input_files], sizeof(*input_files_ts_scale[nb_input_files]), &nb_input_files_ts_scale[nb_input_files], stream + 1);
03218     input_files_ts_scale[nb_input_files][stream]= scale;
03219     return 0;
03220 }
03221 
03222 static int opt_recording_time(const char *opt, const char *arg)
03223 {
03224     recording_time = parse_time_or_die(opt, arg, 1);
03225     return 0;
03226 }
03227 
03228 static int opt_start_time(const char *opt, const char *arg)
03229 {
03230     start_time = parse_time_or_die(opt, arg, 1);
03231     return 0;
03232 }
03233 
03234 static int opt_recording_timestamp(const char *opt, const char *arg)
03235 {
03236     recording_timestamp = parse_time_or_die(opt, arg, 0) / 1000000;
03237     return 0;
03238 }
03239 
03240 static int opt_input_ts_offset(const char *opt, const char *arg)
03241 {
03242     input_ts_offset = parse_time_or_die(opt, arg, 1);
03243     return 0;
03244 }
03245 
03246 static enum CodecID find_codec_or_die(const char *name, int type, int encoder, int strict)
03247 {
03248     const char *codec_string = encoder ? "encoder" : "decoder";
03249     AVCodec *codec;
03250 
03251     if(!name)
03252         return CODEC_ID_NONE;
03253     codec = encoder ?
03254         avcodec_find_encoder_by_name(name) :
03255         avcodec_find_decoder_by_name(name);
03256     if(!codec) {
03257         fprintf(stderr, "Unknown %s '%s'\n", codec_string, name);
03258         ffmpeg_exit(1);
03259     }
03260     if(codec->type != type) {
03261         fprintf(stderr, "Invalid %s type '%s'\n", codec_string, name);
03262         ffmpeg_exit(1);
03263     }
03264     if(codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
03265        strict > FF_COMPLIANCE_EXPERIMENTAL) {
03266         fprintf(stderr, "%s '%s' is experimental and might produce bad "
03267                 "results.\nAdd '-strict experimental' if you want to use it.\n",
03268                 codec_string, codec->name);
03269         codec = encoder ?
03270             avcodec_find_encoder(codec->id) :
03271             avcodec_find_decoder(codec->id);
03272         if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
03273             fprintf(stderr, "Or use the non experimental %s '%s'.\n",
03274                     codec_string, codec->name);
03275         ffmpeg_exit(1);
03276     }
03277     return codec->id;
03278 }
03279 
03280 static int opt_input_file(const char *opt, const char *filename)
03281 {
03282     AVFormatContext *ic;
03283     AVFormatParameters params, *ap = &params;
03284     AVInputFormat *file_iformat = NULL;
03285     int err, i, ret, rfps, rfps_base;
03286     int64_t timestamp;
03287 
03288     if (last_asked_format) {
03289         if (!(file_iformat = av_find_input_format(last_asked_format))) {
03290             fprintf(stderr, "Unknown input format: '%s'\n", last_asked_format);
03291             ffmpeg_exit(1);
03292         }
03293         last_asked_format = NULL;
03294     }
03295 
03296     if (!strcmp(filename, "-"))
03297         filename = "pipe:";
03298 
03299     using_stdin |= !strncmp(filename, "pipe:", 5) ||
03300                     !strcmp(filename, "/dev/stdin");
03301 
03302     /* get default parameters from command line */
03303     ic = avformat_alloc_context();
03304     if (!ic) {
03305         print_error(filename, AVERROR(ENOMEM));
03306         ffmpeg_exit(1);
03307     }
03308 
03309     memset(ap, 0, sizeof(*ap));
03310     ap->prealloced_context = 1;
03311     ap->sample_rate = audio_sample_rate;
03312     ap->channels = audio_channels;
03313     ap->time_base.den = frame_rate.num;
03314     ap->time_base.num = frame_rate.den;
03315     ap->width = frame_width;
03316     ap->height = frame_height;
03317     ap->pix_fmt = frame_pix_fmt;
03318    // ap->sample_fmt = audio_sample_fmt; //FIXME:not implemented in libavformat
03319     ap->channel = video_channel;
03320     ap->standard = video_standard;
03321 
03322     set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
03323 
03324     ic->video_codec_id   =
03325         find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0,
03326                           avcodec_opts[AVMEDIA_TYPE_VIDEO   ]->strict_std_compliance);
03327     ic->audio_codec_id   =
03328         find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0,
03329                           avcodec_opts[AVMEDIA_TYPE_AUDIO   ]->strict_std_compliance);
03330     ic->subtitle_codec_id=
03331         find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0,
03332                           avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
03333     ic->flags |= AVFMT_FLAG_NONBLOCK | AVFMT_FLAG_PRIV_OPT;
03334 
03335     /* open the input file with generic libav function */
03336     err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
03337     if(err >= 0){
03338         set_context_opts(ic, avformat_opts, AV_OPT_FLAG_DECODING_PARAM, NULL);
03339         err = av_demuxer_open(ic, ap);
03340         if(err < 0)
03341             avformat_free_context(ic);
03342     }
03343     if (err < 0) {
03344         print_error(filename, err);
03345         ffmpeg_exit(1);
03346     }
03347     if(opt_programid) {
03348         int i, j;
03349         int found=0;
03350         for(i=0; i<ic->nb_streams; i++){
03351             ic->streams[i]->discard= AVDISCARD_ALL;
03352         }
03353         for(i=0; i<ic->nb_programs; i++){
03354             AVProgram *p= ic->programs[i];
03355             if(p->id != opt_programid){
03356                 p->discard = AVDISCARD_ALL;
03357             }else{
03358                 found=1;
03359                 for(j=0; j<p->nb_stream_indexes; j++){
03360                     ic->streams[p->stream_index[j]]->discard= AVDISCARD_DEFAULT;
03361                 }
03362             }
03363         }
03364         if(!found){
03365             fprintf(stderr, "Specified program id not found\n");
03366             ffmpeg_exit(1);
03367         }
03368         opt_programid=0;
03369     }
03370 
03371     ic->loop_input = loop_input;
03372 
03373     /* If not enough info to get the stream parameters, we decode the
03374        first frames to get it. (used in mpeg case for example) */
03375     ret = av_find_stream_info(ic);
03376     if (ret < 0 && verbose >= 0) {
03377         fprintf(stderr, "%s: could not find codec parameters\n", filename);
03378         av_close_input_file(ic);
03379         ffmpeg_exit(1);
03380     }
03381 
03382     timestamp = start_time;
03383     /* add the stream start time */
03384     if (ic->start_time != AV_NOPTS_VALUE)
03385         timestamp += ic->start_time;
03386 
03387     /* if seeking requested, we execute it */
03388     if (start_time != 0) {
03389         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
03390         if (ret < 0) {
03391             fprintf(stderr, "%s: could not seek to position %0.3f\n",
03392                     filename, (double)timestamp / AV_TIME_BASE);
03393         }
03394         /* reset seek info */
03395         start_time = 0;
03396     }
03397 
03398     /* update the current parameters so that they match the one of the input stream */
03399     for(i=0;i<ic->nb_streams;i++) {
03400         AVStream *st = ic->streams[i];
03401         AVCodecContext *dec = st->codec;
03402         AVInputStream *ist;
03403 
03404         dec->thread_count = thread_count;
03405         input_codecs = grow_array(input_codecs, sizeof(*input_codecs), &nb_input_codecs, nb_input_codecs + 1);
03406 
03407         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
03408         ist = &input_streams[nb_input_streams - 1];
03409         ist->st = st;
03410         ist->file_index = nb_input_files;
03411         ist->discard = 1;
03412 
03413         switch (dec->codec_type) {
03414         case AVMEDIA_TYPE_AUDIO:
03415             input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(audio_codec_name);
03416             if(!input_codecs[nb_input_codecs-1])
03417                 input_codecs[nb_input_codecs-1] = avcodec_find_decoder(dec->codec_id);
03418             set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
03419             channel_layout    = dec->channel_layout;
03420             audio_sample_fmt  = dec->sample_fmt;
03421             if(audio_disable)
03422                 st->discard= AVDISCARD_ALL;
03423             break;
03424         case AVMEDIA_TYPE_VIDEO:
03425             input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(video_codec_name);
03426             if(!input_codecs[nb_input_codecs-1])
03427                 input_codecs[nb_input_codecs-1] = avcodec_find_decoder(dec->codec_id);
03428             set_context_opts(dec, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, input_codecs[nb_input_codecs-1]);
03429             rfps      = ic->streams[i]->r_frame_rate.num;
03430             rfps_base = ic->streams[i]->r_frame_rate.den;
03431             if (dec->lowres) {
03432                 dec->flags |= CODEC_FLAG_EMU_EDGE;
03433                 dec->height >>= dec->lowres;
03434                 dec->width  >>= dec->lowres;
03435             }
03436             if(me_threshold)
03437                 dec->debug |= FF_DEBUG_MV;
03438 
03439             if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
03440 
03441                 if (verbose >= 0)
03442                     fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
03443                             i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
03444 
03445                     (float)rfps / rfps_base, rfps, rfps_base);
03446             }
03447 
03448             if(video_disable)
03449                 st->discard= AVDISCARD_ALL;
03450             else if(video_discard)
03451                 st->discard= video_discard;
03452             break;
03453         case AVMEDIA_TYPE_DATA:
03454             break;
03455         case AVMEDIA_TYPE_SUBTITLE:
03456             input_codecs[nb_input_codecs-1] = avcodec_find_decoder_by_name(subtitle_codec_name);
03457             if(!input_codecs[nb_input_codecs-1])
03458                 input_codecs[nb_input_codecs-1] = avcodec_find_decoder(dec->codec_id);
03459             if(subtitle_disable)
03460                 st->discard = AVDISCARD_ALL;
03461             break;
03462         case AVMEDIA_TYPE_ATTACHMENT:
03463         case AVMEDIA_TYPE_UNKNOWN:
03464             break;
03465         default:
03466             abort();
03467         }
03468     }
03469 
03470     input_files_ts_offset[nb_input_files] = input_ts_offset - (copy_ts ? 0 : timestamp);
03471     /* dump the file content */
03472     if (verbose >= 0)
03473         av_dump_format(ic, nb_input_files, filename, 0);
03474 
03475     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
03476     input_files[nb_input_files - 1].ctx        = ic;
03477     input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;
03478     input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
03479 
03480     top_field_first = -1;
03481     video_channel = 0;
03482     frame_rate    = (AVRational){0, 0};
03483     frame_pix_fmt = PIX_FMT_NONE;
03484     frame_height = 0;
03485     frame_width  = 0;
03486     audio_sample_rate = 0;
03487     audio_channels    = 0;
03488 
03489     av_freep(&video_codec_name);
03490     av_freep(&audio_codec_name);
03491     av_freep(&subtitle_codec_name);
03492     uninit_opts();
03493     init_opts();
03494     return 0;
03495 }
03496 
03497 static void check_inputs(int *has_video_ptr,
03498                          int *has_audio_ptr,
03499                          int *has_subtitle_ptr,
03500                          int *has_data_ptr)
03501 {
03502     int has_video, has_audio, has_subtitle, has_data, i, j;
03503     AVFormatContext *ic;
03504 
03505     has_video = 0;
03506     has_audio = 0;
03507     has_subtitle = 0;
03508     has_data = 0;
03509 
03510     for(j=0;j<nb_input_files;j++) {
03511         ic = input_files[j].ctx;
03512         for(i=0;i<ic->nb_streams;i++) {
03513             AVCodecContext *enc = ic->streams[i]->codec;
03514             switch(enc->codec_type) {
03515             case AVMEDIA_TYPE_AUDIO:
03516                 has_audio = 1;
03517                 break;
03518             case AVMEDIA_TYPE_VIDEO:
03519                 has_video = 1;
03520                 break;
03521             case AVMEDIA_TYPE_SUBTITLE:
03522                 has_subtitle = 1;
03523                 break;
03524             case AVMEDIA_TYPE_DATA:
03525             case AVMEDIA_TYPE_ATTACHMENT:
03526             case AVMEDIA_TYPE_UNKNOWN:
03527                 has_data = 1;
03528                 break;
03529             default:
03530                 abort();
03531             }
03532         }
03533     }
03534     *has_video_ptr = has_video;
03535     *has_audio_ptr = has_audio;
03536     *has_subtitle_ptr = has_subtitle;
03537     *has_data_ptr = has_data;
03538 }
03539 
03540 static void new_video_stream(AVFormatContext *oc, int file_idx)
03541 {
03542     AVStream *st;
03543     AVOutputStream *ost;
03544     AVCodecContext *video_enc;
03545     enum CodecID codec_id = CODEC_ID_NONE;
03546     AVCodec *codec= NULL;
03547 
03548     st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03549     if (!st) {
03550         fprintf(stderr, "Could not alloc stream\n");
03551         ffmpeg_exit(1);
03552     }
03553     ost = new_output_stream(oc, file_idx);
03554 
03555     if(!video_stream_copy){
03556         if (video_codec_name) {
03557             codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1,
03558                                          avcodec_opts[AVMEDIA_TYPE_VIDEO]->strict_std_compliance);
03559             codec = avcodec_find_encoder_by_name(video_codec_name);
03560             ost->enc = codec;
03561         } else {
03562             codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
03563             codec = avcodec_find_encoder(codec_id);
03564         }
03565         ost->frame_aspect_ratio = frame_aspect_ratio;
03566         frame_aspect_ratio = 0;
03567 #if CONFIG_AVFILTER
03568         ost->avfilter = vfilters;
03569         vfilters = NULL;
03570 #endif
03571     }
03572 
03573     avcodec_get_context_defaults3(st->codec, codec);
03574     ost->bitstream_filters = video_bitstream_filters;
03575     video_bitstream_filters= NULL;
03576 
03577     st->codec->thread_count= thread_count;
03578 
03579     video_enc = st->codec;
03580 
03581     if(video_codec_tag)
03582         video_enc->codec_tag= video_codec_tag;
03583 
03584     if(oc->oformat->flags & AVFMT_GLOBALHEADER) {
03585         video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03586         avcodec_opts[AVMEDIA_TYPE_VIDEO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
03587     }
03588 
03589     if (video_stream_copy) {
03590         st->stream_copy = 1;
03591         video_enc->codec_type = AVMEDIA_TYPE_VIDEO;
03592         video_enc->sample_aspect_ratio =
03593         st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
03594     } else {
03595         const char *p;
03596         int i;
03597 
03598         if (frame_rate.num)
03599             ost->frame_rate = frame_rate;
03600         video_enc->codec_id = codec_id;
03601         set_context_opts(video_enc, avcodec_opts[AVMEDIA_TYPE_VIDEO], AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
03602 
03603         video_enc->width = frame_width;
03604         video_enc->height = frame_height;
03605         video_enc->pix_fmt = frame_pix_fmt;
03606         video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
03607         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
03608 
03609         if (intra_only)
03610             video_enc->gop_size = 0;
03611         if (video_qscale || same_quality) {
03612             video_enc->flags |= CODEC_FLAG_QSCALE;
03613             video_enc->global_quality=
03614                 st->quality = FF_QP2LAMBDA * video_qscale;
03615         }
03616 
03617         if(intra_matrix)
03618             video_enc->intra_matrix = intra_matrix;
03619         if(inter_matrix)
03620             video_enc->inter_matrix = inter_matrix;
03621 
03622         p= video_rc_override_string;
03623         for(i=0; p; i++){
03624             int start, end, q;
03625             int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
03626             if(e!=3){
03627                 fprintf(stderr, "error parsing rc_override\n");
03628                 ffmpeg_exit(1);
03629             }
03630             video_enc->rc_override=
03631                 av_realloc(video_enc->rc_override,
03632                            sizeof(RcOverride)*(i+1));
03633             video_enc->rc_override[i].start_frame= start;
03634             video_enc->rc_override[i].end_frame  = end;
03635             if(q>0){
03636                 video_enc->rc_override[i].qscale= q;
03637                 video_enc->rc_override[i].quality_factor= 1.0;
03638             }
03639             else{
03640                 video_enc->rc_override[i].qscale= 0;
03641                 video_enc->rc_override[i].quality_factor= -q/100.0;
03642             }
03643             p= strchr(p, '/');
03644             if(p) p++;
03645         }
03646         video_enc->rc_override_count=i;
03647         if (!video_enc->rc_initial_buffer_occupancy)
03648             video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
03649         video_enc->me_threshold= me_threshold;
03650         video_enc->intra_dc_precision= intra_dc_precision - 8;
03651 
03652         if (do_psnr)
03653             video_enc->flags|= CODEC_FLAG_PSNR;
03654 
03655         /* two pass mode */
03656         if (do_pass) {
03657             if (do_pass == 1) {
03658                 video_enc->flags |= CODEC_FLAG_PASS1;
03659             } else {
03660                 video_enc->flags |= CODEC_FLAG_PASS2;
03661             }
03662         }
03663 
03664         if (forced_key_frames) {
03665             ost->forced_key_frames = forced_key_frames;
03666             forced_key_frames = NULL;
03667         }
03668     }
03669     if (video_language) {
03670         av_dict_set(&st->metadata, "language", video_language, 0);
03671         av_freep(&video_language);
03672     }
03673 
03674     /* reset some key parameters */
03675     video_disable = 0;
03676     av_freep(&video_codec_name);
03677     video_stream_copy = 0;
03678     frame_pix_fmt = PIX_FMT_NONE;
03679 }
03680 
03681 static void new_audio_stream(AVFormatContext *oc, int file_idx)
03682 {
03683     AVStream *st;
03684     AVOutputStream *ost;
03685     AVCodec *codec= NULL;
03686     AVCodecContext *audio_enc;
03687     enum CodecID codec_id = CODEC_ID_NONE;
03688 
03689     st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03690     if (!st) {
03691         fprintf(stderr, "Could not alloc stream\n");
03692         ffmpeg_exit(1);
03693     }
03694     ost = new_output_stream(oc, file_idx);
03695 
03696     if(!audio_stream_copy){
03697         if (audio_codec_name) {
03698             codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1,
03699                                          avcodec_opts[AVMEDIA_TYPE_AUDIO]->strict_std_compliance);
03700             codec = avcodec_find_encoder_by_name(audio_codec_name);
03701             ost->enc = codec;
03702         } else {
03703             codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
03704             codec = avcodec_find_encoder(codec_id);
03705         }
03706     }
03707 
03708     avcodec_get_context_defaults3(st->codec, codec);
03709 
03710     ost->bitstream_filters = audio_bitstream_filters;
03711     audio_bitstream_filters= NULL;
03712 
03713     st->codec->thread_count= thread_count;
03714 
03715     audio_enc = st->codec;
03716     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
03717 
03718     if(audio_codec_tag)
03719         audio_enc->codec_tag= audio_codec_tag;
03720 
03721     if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
03722         audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03723         avcodec_opts[AVMEDIA_TYPE_AUDIO]->flags|= CODEC_FLAG_GLOBAL_HEADER;
03724     }
03725     if (audio_stream_copy) {
03726         st->stream_copy = 1;
03727     } else {
03728         audio_enc->codec_id = codec_id;
03729         set_context_opts(audio_enc, avcodec_opts[AVMEDIA_TYPE_AUDIO], AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
03730 
03731         if (audio_qscale > QSCALE_NONE) {
03732             audio_enc->flags |= CODEC_FLAG_QSCALE;
03733             audio_enc->global_quality = st->quality = FF_QP2LAMBDA * audio_qscale;
03734         }
03735         if (audio_channels)
03736             audio_enc->channels = audio_channels;
03737         audio_enc->sample_fmt = audio_sample_fmt;
03738         if (audio_sample_rate)
03739             audio_enc->sample_rate = audio_sample_rate;
03740         audio_enc->channel_layout = channel_layout;
03741         choose_sample_fmt(st, codec);
03742     }
03743     if (audio_language) {
03744         av_dict_set(&st->metadata, "language", audio_language, 0);
03745         av_freep(&audio_language);
03746     }
03747 
03748     /* reset some key parameters */
03749     audio_disable = 0;
03750     av_freep(&audio_codec_name);
03751     audio_stream_copy = 0;
03752 }
03753 
03754 static void new_data_stream(AVFormatContext *oc, int file_idx)
03755 {
03756     AVStream *st;
03757     AVCodec *codec=NULL;
03758     AVCodecContext *data_enc;
03759 
03760     st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03761     if (!st) {
03762         fprintf(stderr, "Could not alloc stream\n");
03763         ffmpeg_exit(1);
03764     }
03765     new_output_stream(oc, file_idx);
03766     data_enc = st->codec;
03767     if (!data_stream_copy) {
03768         fprintf(stderr, "Data stream encoding not supported yet (only streamcopy)\n");
03769         ffmpeg_exit(1);
03770     }
03771     avcodec_get_context_defaults3(st->codec, codec);
03772 
03773     data_enc->codec_type = AVMEDIA_TYPE_DATA;
03774 
03775     if (data_codec_tag)
03776         data_enc->codec_tag= data_codec_tag;
03777 
03778     if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
03779         data_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03780         avcodec_opts[AVMEDIA_TYPE_DATA]->flags |= CODEC_FLAG_GLOBAL_HEADER;
03781     }
03782     if (data_stream_copy) {
03783         st->stream_copy = 1;
03784     }
03785 
03786     data_disable = 0;
03787     av_freep(&data_codec_name);
03788     data_stream_copy = 0;
03789 }
03790 
03791 static void new_subtitle_stream(AVFormatContext *oc, int file_idx)
03792 {
03793     AVStream *st;
03794     AVOutputStream *ost;
03795     AVCodec *codec=NULL;
03796     AVCodecContext *subtitle_enc;
03797     enum CodecID codec_id = CODEC_ID_NONE;
03798 
03799     st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
03800     if (!st) {
03801         fprintf(stderr, "Could not alloc stream\n");
03802         ffmpeg_exit(1);
03803     }
03804     ost = new_output_stream(oc, file_idx);
03805     subtitle_enc = st->codec;
03806     if(!subtitle_stream_copy){
03807         if (subtitle_codec_name) {
03808             codec_id = find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 1,
03809                                          avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->strict_std_compliance);
03810             codec = avcodec_find_encoder_by_name(subtitle_codec_name);
03811             ost->enc = codec;
03812         } else {
03813             codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_SUBTITLE);
03814             codec = avcodec_find_encoder(codec_id);
03815         }
03816     }
03817     avcodec_get_context_defaults3(st->codec, codec);
03818 
03819     ost->bitstream_filters = subtitle_bitstream_filters;
03820     subtitle_bitstream_filters= NULL;
03821 
03822     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
03823 
03824     if(subtitle_codec_tag)
03825         subtitle_enc->codec_tag= subtitle_codec_tag;
03826 
03827     if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
03828         subtitle_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
03829         avcodec_opts[AVMEDIA_TYPE_SUBTITLE]->flags |= CODEC_FLAG_GLOBAL_HEADER;
03830     }
03831     if (subtitle_stream_copy) {
03832         st->stream_copy = 1;
03833     } else {
03834         subtitle_enc->codec_id = codec_id;
03835         set_context_opts(avcodec_opts[AVMEDIA_TYPE_SUBTITLE], subtitle_enc, AV_OPT_FLAG_SUBTITLE_PARAM | AV_OPT_FLAG_ENCODING_PARAM, codec);
03836     }
03837 
03838     if (subtitle_language) {
03839         av_dict_set(&st->metadata, "language", subtitle_language, 0);
03840         av_freep(&subtitle_language);
03841     }
03842 
03843     subtitle_disable = 0;
03844     av_freep(&subtitle_codec_name);
03845     subtitle_stream_copy = 0;
03846 }
03847 
03848 static int opt_new_stream(const char *opt, const char *arg)
03849 {
03850     AVFormatContext *oc;
03851     int file_idx = nb_output_files - 1;
03852     if (nb_output_files <= 0) {
03853         fprintf(stderr, "At least one output file must be specified\n");
03854         ffmpeg_exit(1);
03855     }
03856     oc = output_files[file_idx];
03857 
03858     if      (!strcmp(opt, "newvideo"   )) new_video_stream   (oc, file_idx);
03859     else if (!strcmp(opt, "newaudio"   )) new_audio_stream   (oc, file_idx);
03860     else if (!strcmp(opt, "newsubtitle")) new_subtitle_stream(oc, file_idx);
03861     else if (!strcmp(opt, "newdata"    )) new_data_stream    (oc, file_idx);
03862     else av_assert0(0);
03863     return 0;
03864 }
03865 
03866 /* arg format is "output-stream-index:streamid-value". */
03867 static int opt_streamid(const char *opt, const char *arg)
03868 {
03869     int idx;
03870     char *p;
03871     char idx_str[16];
03872 
03873     av_strlcpy(idx_str, arg, sizeof(idx_str));
03874     p = strchr(idx_str, ':');
03875     if (!p) {
03876         fprintf(stderr,
03877                 "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
03878                 arg, opt);
03879         ffmpeg_exit(1);
03880     }
03881     *p++ = '\0';
03882     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
03883     streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
03884     streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
03885     return 0;
03886 }
03887 
03888 static int opt_output_file(const char *opt, const char *filename)
03889 {
03890     AVFormatContext *oc;
03891     int err, use_video, use_audio, use_subtitle, use_data;
03892     int input_has_video, input_has_audio, input_has_subtitle, input_has_data;
03893     AVFormatParameters params, *ap = &params;
03894     AVOutputFormat *file_oformat;
03895 
03896     if(nb_output_files >= FF_ARRAY_ELEMS(output_files)){
03897         fprintf(stderr, "Too many output files\n");
03898         ffmpeg_exit(1);
03899     }
03900 
03901     if (!strcmp(filename, "-"))
03902         filename = "pipe:";
03903 
03904     err = avformat_alloc_output_context2(&oc, NULL, last_asked_format, filename);
03905     last_asked_format = NULL;
03906     if (!oc) {
03907         print_error(filename, err);
03908         ffmpeg_exit(1);
03909     }
03910     file_oformat= oc->oformat;
03911 
03912     if (!strcmp(file_oformat->name, "ffm") &&
03913         av_strstart(filename, "http:", NULL)) {
03914         /* special case for files sent to ffserver: we get the stream
03915            parameters from ffserver */
03916         int err = read_ffserver_streams(oc, filename);
03917         if (err < 0) {
03918             print_error(filename, err);
03919             ffmpeg_exit(1);
03920         }
03921     } else {
03922         use_video = file_oformat->video_codec != CODEC_ID_NONE || video_stream_copy || video_codec_name;
03923         use_audio = file_oformat->audio_codec != CODEC_ID_NONE || audio_stream_copy || audio_codec_name;
03924         use_subtitle = file_oformat->subtitle_codec != CODEC_ID_NONE || subtitle_stream_copy || subtitle_codec_name;
03925         use_data = data_stream_copy ||  data_codec_name; /* XXX once generic data codec will be available add a ->data_codec reference and use it here */
03926 
03927         /* disable if no corresponding type found and at least one
03928            input file */
03929         if (nb_input_files > 0) {
03930             check_inputs(&input_has_video,
03931                          &input_has_audio,
03932                          &input_has_subtitle,
03933                          &input_has_data);
03934 
03935             if (!input_has_video)
03936                 use_video = 0;
03937             if (!input_has_audio)
03938                 use_audio = 0;
03939             if (!input_has_subtitle)
03940                 use_subtitle = 0;
03941             if (!input_has_data)
03942                 use_data = 0;
03943         }
03944 
03945         /* manual disable */
03946         if (audio_disable)    use_audio    = 0;
03947         if (video_disable)    use_video    = 0;
03948         if (subtitle_disable) use_subtitle = 0;
03949         if (data_disable)     use_data     = 0;
03950 
03951         if (use_video)    new_video_stream(oc, nb_output_files);
03952         if (use_audio)    new_audio_stream(oc, nb_output_files);
03953         if (use_subtitle) new_subtitle_stream(oc, nb_output_files);
03954         if (use_data)     new_data_stream(oc, nb_output_files);
03955 
03956         oc->timestamp = recording_timestamp;
03957 
03958         av_dict_copy(&oc->metadata, metadata, 0);
03959         av_dict_free(&metadata);
03960     }
03961 
03962     output_files[nb_output_files++] = oc;
03963 
03964     /* check filename in case of an image number is expected */
03965     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
03966         if (!av_filename_number_test(oc->filename)) {
03967             print_error(oc->filename, AVERROR_NUMEXPECTED);
03968             ffmpeg_exit(1);
03969         }
03970     }
03971 
03972     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
03973         /* test if it already exists to avoid loosing precious files */
03974         if (!file_overwrite &&
03975             (strchr(filename, ':') == NULL ||
03976              filename[1] == ':' ||
03977              av_strstart(filename, "file:", NULL))) {
03978             if (url_exist(filename)) {
03979                 if (!using_stdin) {
03980                     fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
03981                     fflush(stderr);
03982                     if (!read_yesno()) {
03983                         fprintf(stderr, "Not overwriting - exiting\n");
03984                         ffmpeg_exit(1);
03985                     }
03986                 }
03987                 else {
03988                     fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
03989                     ffmpeg_exit(1);
03990                 }
03991             }
03992         }
03993 
03994         /* open the file */
03995         if ((err = avio_open(&oc->pb, filename, AVIO_WRONLY)) < 0) {
03996             print_error(filename, err);
03997             ffmpeg_exit(1);
03998         }
03999     }
04000 
04001     memset(ap, 0, sizeof(*ap));
04002     if (av_set_parameters(oc, ap) < 0) {
04003         fprintf(stderr, "%s: Invalid encoding parameters\n",
04004                 oc->filename);
04005         ffmpeg_exit(1);
04006     }
04007 
04008     oc->preload= (int)(mux_preload*AV_TIME_BASE);
04009     oc->max_delay= (int)(mux_max_delay*AV_TIME_BASE);
04010     oc->loop_output = loop_output;
04011 
04012     set_context_opts(oc, avformat_opts, AV_OPT_FLAG_ENCODING_PARAM, NULL);
04013 
04014     frame_rate    = (AVRational){0, 0};
04015     frame_width   = 0;
04016     frame_height  = 0;
04017     audio_sample_rate = 0;
04018     audio_channels    = 0;
04019 
04020     av_freep(&forced_key_frames);
04021     uninit_opts();
04022     init_opts();
04023     return 0;
04024 }
04025 
04026 /* same option as mencoder */
04027 static int opt_pass(const char *opt, const char *arg)
04028 {
04029     do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
04030     return 0;
04031 }
04032 
04033 static int64_t getutime(void)
04034 {
04035 #if HAVE_GETRUSAGE
04036     struct rusage rusage;
04037 
04038     getrusage(RUSAGE_SELF, &rusage);
04039     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
04040 #elif HAVE_GETPROCESSTIMES
04041     HANDLE proc;
04042     FILETIME c, e, k, u;
04043     proc = GetCurrentProcess();
04044     GetProcessTimes(proc, &c, &e, &k, &u);
04045     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
04046 #else
04047     return av_gettime();
04048 #endif
04049 }
04050 
04051 static int64_t getmaxrss(void)
04052 {
04053 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
04054     struct rusage rusage;
04055     getrusage(RUSAGE_SELF, &rusage);
04056     return (int64_t)rusage.ru_maxrss * 1024;
04057 #elif HAVE_GETPROCESSMEMORYINFO
04058     HANDLE proc;
04059     PROCESS_MEMORY_COUNTERS memcounters;
04060     proc = GetCurrentProcess();
04061     memcounters.cb = sizeof(memcounters);
04062     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
04063     return memcounters.PeakPagefileUsage;
04064 #else
04065     return 0;
04066 #endif
04067 }
04068 
04069 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
04070 {
04071     int i;
04072     const char *p = str;
04073     for(i = 0;; i++) {
04074         dest[i] = atoi(p);
04075         if(i == 63)
04076             break;
04077         p = strchr(p, ',');
04078         if(!p) {
04079             fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
04080             ffmpeg_exit(1);
04081         }
04082         p++;
04083     }
04084 }
04085 
04086 static int opt_inter_matrix(const char *opt, const char *arg)
04087 {
04088     inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
04089     parse_matrix_coeffs(inter_matrix, arg);
04090     return 0;
04091 }
04092 
04093 static int opt_intra_matrix(const char *opt, const char *arg)
04094 {
04095     intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
04096     parse_matrix_coeffs(intra_matrix, arg);
04097     return 0;
04098 }
04099 
04100 static void show_usage(void)
04101 {
04102     printf("Hyper fast Audio and Video encoder\n");
04103     printf("usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...\n");
04104     printf("\n");
04105 }
04106 
04107 static int opt_help(const char *opt, const char *arg)
04108 {
04109     AVCodec *c;
04110     AVOutputFormat *oformat = NULL;
04111 
04112     av_log_set_callback(log_callback_help);
04113     show_usage();
04114     show_help_options(options, "Main options:\n",
04115                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
04116     show_help_options(options, "\nAdvanced options:\n",
04117                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
04118                       OPT_EXPERT);
04119     show_help_options(options, "\nVideo options:\n",
04120                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04121                       OPT_VIDEO);
04122     show_help_options(options, "\nAdvanced Video options:\n",
04123                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04124                       OPT_VIDEO | OPT_EXPERT);
04125     show_help_options(options, "\nAudio options:\n",
04126                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04127                       OPT_AUDIO);
04128     show_help_options(options, "\nAdvanced Audio options:\n",
04129                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04130                       OPT_AUDIO | OPT_EXPERT);
04131     show_help_options(options, "\nSubtitle options:\n",
04132                       OPT_SUBTITLE | OPT_GRAB,
04133                       OPT_SUBTITLE);
04134     show_help_options(options, "\nAudio/Video grab options:\n",
04135                       OPT_GRAB,
04136                       OPT_GRAB);
04137     printf("\n");
04138     av_opt_show2(avcodec_opts[0], NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04139     printf("\n");
04140 
04141     /* individual codec options */
04142     c = NULL;
04143     while ((c = av_codec_next(c))) {
04144         if (c->priv_class) {
04145             av_opt_show2(&c->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04146             printf("\n");
04147         }
04148     }
04149 
04150     av_opt_show2(avformat_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04151     printf("\n");
04152 
04153     /* individual muxer options */
04154     while ((oformat = av_oformat_next(oformat))) {
04155         if (oformat->priv_class) {
04156             av_opt_show2(&oformat->priv_class, NULL, AV_OPT_FLAG_ENCODING_PARAM, 0);
04157             printf("\n");
04158         }
04159     }
04160 
04161     av_opt_show2(sws_opts, NULL, AV_OPT_FLAG_ENCODING_PARAM|AV_OPT_FLAG_DECODING_PARAM, 0);
04162     return 0;
04163 }
04164 
04165 static int opt_target(const char *opt, const char *arg)
04166 {
04167     enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
04168     static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};
04169 
04170     if(!strncmp(arg, "pal-", 4)) {
04171         norm = PAL;
04172         arg += 4;
04173     } else if(!strncmp(arg, "ntsc-", 5)) {
04174         norm = NTSC;
04175         arg += 5;
04176     } else if(!strncmp(arg, "film-", 5)) {
04177         norm = FILM;
04178         arg += 5;
04179     } else {
04180         int fr;
04181         /* Calculate FR via float to avoid int overflow */
04182         fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
04183         if(fr == 25000) {
04184             norm = PAL;
04185         } else if((fr == 29970) || (fr == 23976)) {
04186             norm = NTSC;
04187         } else {
04188             /* Try to determine PAL/NTSC by peeking in the input files */
04189             if(nb_input_files) {
04190                 int i, j;
04191                 for (j = 0; j < nb_input_files; j++) {
04192                     for (i = 0; i < input_files[j].ctx->nb_streams; i++) {
04193                         AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
04194                         if(c->codec_type != AVMEDIA_TYPE_VIDEO)
04195                             continue;
04196                         fr = c->time_base.den * 1000 / c->time_base.num;
04197                         if(fr == 25000) {
04198                             norm = PAL;
04199                             break;
04200                         } else if((fr == 29970) || (fr == 23976)) {
04201                             norm = NTSC;
04202                             break;
04203                         }
04204                     }
04205                     if(norm != UNKNOWN)
04206                         break;
04207                 }
04208             }
04209         }
04210         if(verbose > 0 && norm != UNKNOWN)
04211             fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
04212     }
04213 
04214     if(norm == UNKNOWN) {
04215         fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
04216         fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
04217         fprintf(stderr, "or set a framerate with \"-r xxx\".\n");
04218         ffmpeg_exit(1);
04219     }
04220 
04221     if(!strcmp(arg, "vcd")) {
04222         opt_codec("vcodec", "mpeg1video");
04223         opt_codec("acodec", "mp2");
04224         opt_format("f", "vcd");
04225 
04226         opt_frame_size("s", norm == PAL ? "352x288" : "352x240");
04227         opt_frame_rate("r", frame_rates[norm]);
04228         opt_default("g", norm == PAL ? "15" : "18");
04229 
04230         opt_default("b", "1150000");
04231         opt_default("maxrate", "1150000");
04232         opt_default("minrate", "1150000");
04233         opt_default("bufsize", "327680"); // 40*1024*8;
04234 
04235         opt_default("ab", "224000");
04236         audio_sample_rate = 44100;
04237         audio_channels = 2;
04238 
04239         opt_default("packetsize", "2324");
04240         opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
04241 
04242         /* We have to offset the PTS, so that it is consistent with the SCR.
04243            SCR starts at 36000, but the first two packs contain only padding
04244            and the first pack from the other stream, respectively, may also have
04245            been written before.
04246            So the real data starts at SCR 36000+3*1200. */
04247         mux_preload= (36000+3*1200) / 90000.0; //0.44
04248     } else if(!strcmp(arg, "svcd")) {
04249 
04250         opt_codec("vcodec", "mpeg2video");
04251         opt_codec("acodec", "mp2");
04252         opt_format("f", "svcd");
04253 
04254         opt_frame_size("s", norm == PAL ? "480x576" : "480x480");
04255         opt_frame_rate("r", frame_rates[norm]);
04256         opt_frame_pix_fmt("pix_fmt", "yuv420p");
04257         opt_default("g", norm == PAL ? "15" : "18");
04258 
04259         opt_default("b", "2040000");
04260         opt_default("maxrate", "2516000");
04261         opt_default("minrate", "0"); //1145000;
04262         opt_default("bufsize", "1835008"); //224*1024*8;
04263         opt_default("flags", "+scan_offset");
04264 
04265 
04266         opt_default("ab", "224000");
04267         audio_sample_rate = 44100;
04268 
04269         opt_default("packetsize", "2324");
04270 
04271     } else if(!strcmp(arg, "dvd")) {
04272 
04273         opt_codec("vcodec", "mpeg2video");
04274         opt_codec("acodec", "ac3");
04275         opt_format("f", "dvd");
04276 
04277         opt_frame_size("vcodec", norm == PAL ? "720x576" : "720x480");
04278         opt_frame_rate("r", frame_rates[norm]);
04279         opt_frame_pix_fmt("pix_fmt", "yuv420p");
04280         opt_default("g", norm == PAL ? "15" : "18");
04281 
04282         opt_default("b", "6000000");
04283         opt_default("maxrate", "9000000");
04284         opt_default("minrate", "0"); //1500000;
04285         opt_default("bufsize", "1835008"); //224*1024*8;
04286 
04287         opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
04288         opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
04289 
04290         opt_default("ab", "448000");
04291         audio_sample_rate = 48000;
04292 
04293     } else if(!strncmp(arg, "dv", 2)) {
04294 
04295         opt_format("f", "dv");
04296 
04297         opt_frame_size("s", norm == PAL ? "720x576" : "720x480");
04298         opt_frame_pix_fmt("pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
04299                           norm == PAL ? "yuv420p" : "yuv411p");
04300         opt_frame_rate("r", frame_rates[norm]);
04301 
04302         audio_sample_rate = 48000;
04303         audio_channels = 2;
04304 
04305     } else {
04306         fprintf(stderr, "Unknown target: %s\n", arg);
04307         return AVERROR(EINVAL);
04308     }
04309     return 0;
04310 }
04311 
04312 static int opt_vstats_file(const char *opt, const char *arg)
04313 {
04314     av_free (vstats_filename);
04315     vstats_filename=av_strdup (arg);
04316     return 0;
04317 }
04318 
04319 static int opt_vstats(const char *opt, const char *arg)
04320 {
04321     char filename[40];
04322     time_t today2 = time(NULL);
04323     struct tm *today = localtime(&today2);
04324 
04325     snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
04326              today->tm_sec);
04327     return opt_vstats_file(opt, filename);
04328 }
04329 
04330 static int opt_bsf(const char *opt, const char *arg)
04331 {
04332     AVBitStreamFilterContext *bsfc= av_bitstream_filter_init(arg); //FIXME split name and args for filter at '='
04333     AVBitStreamFilterContext **bsfp;
04334 
04335     if(!bsfc){
04336         fprintf(stderr, "Unknown bitstream filter %s\n", arg);
04337         ffmpeg_exit(1);
04338     }
04339 
04340     bsfp= *opt == 'v' ? &video_bitstream_filters :
04341           *opt == 'a' ? &audio_bitstream_filters :
04342                         &subtitle_bitstream_filters;
04343     while(*bsfp)
04344         bsfp= &(*bsfp)->next;
04345 
04346     *bsfp= bsfc;
04347 
04348     return 0;
04349 }
04350 
04351 static int opt_preset(const char *opt, const char *arg)
04352 {
04353     FILE *f=NULL;
04354     char filename[1000], tmp[1000], tmp2[1000], line[1000];
04355     char *codec_name = *opt == 'v' ? video_codec_name :
04356                        *opt == 'a' ? audio_codec_name :
04357                                      subtitle_codec_name;
04358 
04359     if (!(f = get_preset_file(filename, sizeof(filename), arg, *opt == 'f', codec_name))) {
04360         fprintf(stderr, "File for preset '%s' not found\n", arg);
04361         ffmpeg_exit(1);
04362     }
04363 
04364     while(!feof(f)){
04365         int e= fscanf(f, "%999[^\n]\n", line) - 1;
04366         if(line[0] == '#' && !e)
04367             continue;
04368         e|= sscanf(line, "%999[^=]=%999[^\n]\n", tmp, tmp2) - 2;
04369         if(e){
04370             fprintf(stderr, "%s: Invalid syntax: '%s'\n", filename, line);
04371             ffmpeg_exit(1);
04372         }
04373         if (!strcmp(tmp, "acodec") ||
04374             !strcmp(tmp, "vcodec") ||
04375             !strcmp(tmp, "scodec") ||
04376             !strcmp(tmp, "dcodec")) {
04377             opt_codec(tmp, tmp2);
04378         }else if(opt_default(tmp, tmp2) < 0){
04379             fprintf(stderr, "%s: Invalid option or argument: '%s', parsed as '%s' = '%s'\n", filename, line, tmp, tmp2);
04380             ffmpeg_exit(1);
04381         }
04382     }
04383 
04384     fclose(f);
04385 
04386     return 0;
04387 }
04388 
04389 static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
04390 {
04391 }
04392 
04393 static int opt_passlogfile(const char *opt, const char *arg)
04394 {
04395     pass_logfilename_prefix = arg;
04396 #if CONFIG_LIBX264_ENCODER
04397     return opt_default("passlogfile", arg);
04398 #else
04399     return 0;
04400 #endif
04401 }
04402 
04403 static const OptionDef options[] = {
04404     /* main options */
04405 #include "cmdutils_common_opts.h"
04406     { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
04407     { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
04408     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
04409     { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file.stream[:syncfile.syncstream]" },
04410     { "map_meta_data", HAS_ARG | OPT_EXPERT, {(void*)opt_map_meta_data}, "DEPRECATED set meta data information of outfile from infile",
04411       "outfile[,metadata]:infile[,metadata]" },
04412     { "map_metadata", HAS_ARG | OPT_EXPERT, {(void*)opt_map_metadata}, "set metadata information of outfile from infile",
04413       "outfile[,metadata]:infile[,metadata]" },
04414     { "map_chapters",  HAS_ARG | OPT_EXPERT, {(void*)opt_map_chapters},  "set chapters mapping", "outfile:infile" },
04415     { "t", HAS_ARG, {(void*)opt_recording_time}, "record or transcode \"duration\" seconds of audio/video", "duration" },
04416     { "fs", HAS_ARG | OPT_INT64, {(void*)&limit_filesize}, "set the limit file size in bytes", "limit_size" }, //
04417     { "ss", HAS_ARG, {(void*)opt_start_time}, "set the start time offset", "time_off" },
04418     { "itsoffset", HAS_ARG, {(void*)opt_input_ts_offset}, "set the input ts offset", "time_off" },
04419     { "itsscale", HAS_ARG, {(void*)opt_input_ts_scale}, "set the input ts scale", "stream:scale" },
04420     { "timestamp", HAS_ARG, {(void*)opt_recording_timestamp}, "set the recording timestamp ('now' to set the current time)", "time" },
04421     { "metadata", HAS_ARG, {(void*)opt_metadata}, "add metadata", "string=string" },
04422     { "dframes", OPT_INT | HAS_ARG, {(void*)&max_frames[AVMEDIA_TYPE_DATA]}, "set the number of data frames to record", "number" },
04423     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
04424       "add timings for benchmarking" },
04425     { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
04426     { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
04427       "dump each input packet" },
04428     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
04429       "when dumping packets, also dump the payload" },
04430     { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
04431     { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "loop (current only works with images)" },
04432     { "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)", "" },
04433     { "v", HAS_ARG, {(void*)opt_verbose}, "set ffmpeg verbosity level", "number" },
04434     { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
04435     { "threads",  HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
04436     { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
04437     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
04438     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
04439     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
04440     { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
04441     { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
04442     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
04443     { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
04444     { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
04445     { "copyinkf", OPT_BOOL | OPT_EXPERT, {(void*)&copy_initial_nonkeyframes}, "copy initial non-keyframes" },
04446 
04447     /* video options */
04448     { "b", HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
04449     { "vb", HAS_ARG | OPT_VIDEO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
04450     { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[AVMEDIA_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
04451     { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
04452     { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
04453     { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
04454     { "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" },
04455     { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
04456     { "croptop",  HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04457     { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04458     { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04459     { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
04460     { "padtop", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04461     { "padbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04462     { "padleft", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04463     { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
04464     { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
04465     { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
04466     { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
04467     { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
04468     { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
04469     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
04470     { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_codec}, "force video codec ('copy' to copy stream)", "codec" },
04471     { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
04472     { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
04473       "use same quantizer as source (implies VBR)" },
04474     { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
04475     { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
04476     { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
04477       "deinterlace pictures" },
04478     { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
04479     { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
04480     { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
04481 #if CONFIG_AVFILTER
04482     { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
04483 #endif
04484     { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
04485     { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
04486     { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
04487     { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
04488     { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_codec_tag}, "force video tag/fourcc", "fourcc/tag" },
04489     { "newvideo", OPT_VIDEO, {(void*)opt_new_stream}, "add a new video stream to the current output stream" },
04490     { "vlang", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void *)&video_language}, "set the ISO 639 language code (3 letters) of the current video stream" , "code" },
04491     { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
04492     { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&force_fps}, "force the selected framerate, disable the best supported framerate selection" },
04493     { "streamid", HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
04494     { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void *)&forced_key_frames}, "force key frames at specified timestamps", "timestamps" },
04495 
04496     /* audio options */
04497     { "ab", HAS_ARG | OPT_AUDIO, {(void*)opt_bitrate}, "set bitrate (in bits/s)", "bitrate" },
04498     { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[AVMEDIA_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
04499     { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
04500     { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
04501     { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
04502     { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
04503     { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_codec}, "force audio codec ('copy' to copy stream)", "codec" },
04504     { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
04505     { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
04506     { "newaudio", OPT_AUDIO, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
04507     { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
04508     { "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" },
04509 
04510     /* subtitle options */
04511     { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
04512     { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
04513     { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
04514     { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
04515     { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
04516 
04517     /* grab options */
04518     { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "set video grab channel (DV1394 only)", "channel" },
04519     { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_standard}, "set television standard (NTSC, PAL (SECAM))", "standard" },
04520     { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
04521 
04522     /* muxer options */
04523     { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_max_delay}, "set the maximum demux-decode delay", "seconds" },
04524     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT, {(void*)&mux_preload}, "set the initial demux-decode delay", "seconds" },
04525 
04526     { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
04527     { "vbsf", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
04528     { "sbsf", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_bsf}, "", "bitstream_filter" },
04529 
04530     { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT, {(void*)opt_preset}, "set the audio options to the indicated preset", "preset" },
04531     { "vpre", HAS_ARG | OPT_VIDEO | OPT_EXPERT, {(void*)opt_preset}, "set the video options to the indicated preset", "preset" },
04532     { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT, {(void*)opt_preset}, "set the subtitle options to the indicated preset", "preset" },
04533     { "fpre", HAS_ARG | OPT_EXPERT, {(void*)opt_preset}, "set options from indicated preset file", "filename" },
04534     /* data codec support */
04535     { "dcodec", HAS_ARG | OPT_DATA, {(void*)opt_codec}, "force data codec ('copy' to copy stream)", "codec" },
04536 
04537     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
04538     { NULL, },
04539 };
04540 
04541 int main(int argc, char **argv)
04542 {
04543     int64_t ti;
04544 
04545     av_log_set_flags(AV_LOG_SKIP_REPEATED);
04546 
04547     if(argc>1 && !strcmp(argv[1], "-d")){
04548         run_as_daemon=1;
04549         verbose=-1;
04550         av_log_set_callback(log_callback_null);
04551         argc--;
04552         argv++;
04553     }
04554 
04555     avcodec_register_all();
04556 #if CONFIG_AVDEVICE
04557     avdevice_register_all();
04558 #endif
04559 #if CONFIG_AVFILTER
04560     avfilter_register_all();
04561 #endif
04562     av_register_all();
04563 
04564 #if HAVE_ISATTY
04565     if(isatty(STDIN_FILENO))
04566         avio_set_interrupt_cb(decode_interrupt_cb);
04567 #endif
04568 
04569     init_opts();
04570 
04571     if(verbose>=0)
04572         show_banner();
04573 
04574     /* parse options */
04575     parse_options(argc, argv, options, opt_output_file);
04576 
04577     if(nb_output_files <= 0 && nb_input_files == 0) {
04578         show_usage();
04579         fprintf(stderr, "Use -h to get full help or, even better, run 'man ffmpeg'\n");
04580         ffmpeg_exit(1);
04581     }
04582 
04583     /* file converter / grab */
04584     if (nb_output_files <= 0) {
04585         fprintf(stderr, "At least one output file must be specified\n");
04586         ffmpeg_exit(1);
04587     }
04588 
04589     if (nb_input_files == 0) {
04590         fprintf(stderr, "At least one input file must be specified\n");
04591         ffmpeg_exit(1);
04592     }
04593 
04594     ti = getutime();
04595     if (transcode(output_files, nb_output_files, input_files, nb_input_files,
04596                   stream_maps, nb_stream_maps) < 0)
04597         ffmpeg_exit(1);
04598     ti = getutime() - ti;
04599     if (do_benchmark) {
04600         int maxrss = getmaxrss() / 1024;
04601         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
04602     }
04603 
04604     return ffmpeg_exit(0);
04605 }

Generated on Fri Feb 22 2013 07:24:24 for FFmpeg by  doxygen 1.7.1