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

avconv.c

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