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