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

Generated on Wed Apr 11 2012 07:31:32 for FFmpeg by  doxygen 1.7.1