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