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