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 (!strcmp(ost->enc->name, "libx264")) {
02463                     av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
02464                 } else {
02465                     if (codec->flags & CODEC_FLAG_PASS1) {
02466                         f = fopen(logfilename, "wb");
02467                         if (!f) {
02468                             av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
02469                                    logfilename, strerror(errno));
02470                             exit_program(1);
02471                         }
02472                         ost->logfile = f;
02473                     } else {
02474                         char  *logbuffer;
02475                         size_t logbuffer_size;
02476                         if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
02477                             av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
02478                                    logfilename);
02479                             exit_program(1);
02480                         }
02481                         codec->stats_in = logbuffer;
02482                     }
02483                 }
02484             }
02485         }
02486         if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
02487             int        size = codec->width * codec->height;
02488             bit_buffer_size = FFMAX(bit_buffer_size, 6 * size + 200);
02489         }
02490     }
02491 
02492     if (!bit_buffer)
02493         bit_buffer = av_malloc(bit_buffer_size);
02494     if (!bit_buffer) {
02495         av_log(NULL, AV_LOG_ERROR, "Cannot allocate %d bytes output buffer\n",
02496                bit_buffer_size);
02497         return AVERROR(ENOMEM);
02498     }
02499 
02500     /* open each encoder */
02501     for (i = 0; i < nb_output_streams; i++) {
02502         ost = &output_streams[i];
02503         if (ost->encoding_needed) {
02504             AVCodec      *codec = ost->enc;
02505             AVCodecContext *dec = input_streams[ost->source_index].st->codec;
02506             if (!codec) {
02507                 snprintf(error, sizeof(error), "Encoder (codec id %d) not found for output stream #%d:%d",
02508                          ost->st->codec->codec_id, ost->file_index, ost->index);
02509                 ret = AVERROR(EINVAL);
02510                 goto dump_format;
02511             }
02512             if (dec->subtitle_header) {
02513                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
02514                 if (!ost->st->codec->subtitle_header) {
02515                     ret = AVERROR(ENOMEM);
02516                     goto dump_format;
02517                 }
02518                 memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
02519                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
02520             }
02521             if (!av_dict_get(ost->opts, "threads", NULL, 0))
02522                 av_dict_set(&ost->opts, "threads", "auto", 0);
02523             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
02524                 snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
02525                         ost->file_index, ost->index);
02526                 ret = AVERROR(EINVAL);
02527                 goto dump_format;
02528             }
02529             assert_codec_experimental(ost->st->codec, 1);
02530             assert_avoptions(ost->opts);
02531             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
02532                 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
02533                                              "It takes bits/s as argument, not kbits/s\n");
02534             extra_size += ost->st->codec->extradata_size;
02535 
02536             if (ost->st->codec->me_threshold)
02537                 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
02538         }
02539     }
02540 
02541     /* init input streams */
02542     for (i = 0; i < nb_input_streams; i++)
02543         if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
02544             goto dump_format;
02545 
02546     /* discard unused programs */
02547     for (i = 0; i < nb_input_files; i++) {
02548         InputFile *ifile = &input_files[i];
02549         for (j = 0; j < ifile->ctx->nb_programs; j++) {
02550             AVProgram *p = ifile->ctx->programs[j];
02551             int discard  = AVDISCARD_ALL;
02552 
02553             for (k = 0; k < p->nb_stream_indexes; k++)
02554                 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
02555                     discard = AVDISCARD_DEFAULT;
02556                     break;
02557                 }
02558             p->discard = discard;
02559         }
02560     }
02561 
02562     /* open files and write file headers */
02563     for (i = 0; i < nb_output_files; i++) {
02564         oc = output_files[i].ctx;
02565         oc->interrupt_callback = int_cb;
02566         if (avformat_write_header(oc, &output_files[i].opts) < 0) {
02567             snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
02568             ret = AVERROR(EINVAL);
02569             goto dump_format;
02570         }
02571         assert_avoptions(output_files[i].opts);
02572         if (strcmp(oc->oformat->name, "rtp")) {
02573             want_sdp = 0;
02574         }
02575     }
02576 
02577  dump_format:
02578     /* dump the file output parameters - cannot be done before in case
02579        of stream copy */
02580     for (i = 0; i < nb_output_files; i++) {
02581         av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
02582     }
02583 
02584     /* dump the stream mapping */
02585     av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
02586     for (i = 0; i < nb_output_streams; i++) {
02587         ost = &output_streams[i];
02588 
02589         if (ost->attachment_filename) {
02590             /* an attached file */
02591             av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
02592                    ost->attachment_filename, ost->file_index, ost->index);
02593             continue;
02594         }
02595         av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
02596                input_streams[ost->source_index].file_index,
02597                input_streams[ost->source_index].st->index,
02598                ost->file_index,
02599                ost->index);
02600         if (ost->sync_ist != &input_streams[ost->source_index])
02601             av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
02602                    ost->sync_ist->file_index,
02603                    ost->sync_ist->st->index);
02604         if (ost->stream_copy)
02605             av_log(NULL, AV_LOG_INFO, " (copy)");
02606         else
02607             av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index].dec ?
02608                    input_streams[ost->source_index].dec->name : "?",
02609                    ost->enc ? ost->enc->name : "?");
02610         av_log(NULL, AV_LOG_INFO, "\n");
02611     }
02612 
02613     if (ret) {
02614         av_log(NULL, AV_LOG_ERROR, "%s\n", error);
02615         return ret;
02616     }
02617 
02618     if (want_sdp) {
02619         print_sdp(output_files, nb_output_files);
02620     }
02621 
02622     return 0;
02623 }
02624 
02625 /*
02626  * The following code is the main loop of the file converter
02627  */
02628 static int transcode(OutputFile *output_files,
02629                      int nb_output_files,
02630                      InputFile *input_files,
02631                      int nb_input_files)
02632 {
02633     int ret, i;
02634     AVFormatContext *is, *os;
02635     OutputStream *ost;
02636     InputStream *ist;
02637     uint8_t *no_packet;
02638     int no_packet_count = 0;
02639     int64_t timer_start;
02640 
02641     if (!(no_packet = av_mallocz(nb_input_files)))
02642         exit_program(1);
02643 
02644     ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
02645     if (ret < 0)
02646         goto fail;
02647 
02648     av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
02649     term_init();
02650 
02651     timer_start = av_gettime();
02652 
02653     for (; received_sigterm == 0;) {
02654         int file_index, ist_index;
02655         AVPacket pkt;
02656         int64_t ipts_min;
02657         double opts_min;
02658 
02659         ipts_min = INT64_MAX;
02660         opts_min = 1e100;
02661 
02662         /* select the stream that we must read now by looking at the
02663            smallest output pts */
02664         file_index = -1;
02665         for (i = 0; i < nb_output_streams; i++) {
02666             OutputFile *of;
02667             int64_t ipts;
02668             double  opts;
02669             ost = &output_streams[i];
02670             of = &output_files[ost->file_index];
02671             os = output_files[ost->file_index].ctx;
02672             ist = &input_streams[ost->source_index];
02673             if (ost->is_past_recording_time || no_packet[ist->file_index] ||
02674                 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
02675                 continue;
02676             opts = ost->st->pts.val * av_q2d(ost->st->time_base);
02677             ipts = ist->pts;
02678             if (!input_files[ist->file_index].eof_reached) {
02679                 if (ipts < ipts_min) {
02680                     ipts_min = ipts;
02681                     if (input_sync)
02682                         file_index = ist->file_index;
02683                 }
02684                 if (opts < opts_min) {
02685                     opts_min = opts;
02686                     if (!input_sync) file_index = ist->file_index;
02687                 }
02688             }
02689             if (ost->frame_number >= ost->max_frames) {
02690                 int j;
02691                 for (j = 0; j < of->ctx->nb_streams; j++)
02692                     output_streams[of->ost_index + j].is_past_recording_time = 1;
02693                 continue;
02694             }
02695         }
02696         /* if none, if is finished */
02697         if (file_index < 0) {
02698             if (no_packet_count) {
02699                 no_packet_count = 0;
02700                 memset(no_packet, 0, nb_input_files);
02701                 usleep(10000);
02702                 continue;
02703             }
02704             break;
02705         }
02706 
02707         /* read a frame from it and output it in the fifo */
02708         is  = input_files[file_index].ctx;
02709         ret = av_read_frame(is, &pkt);
02710         if (ret == AVERROR(EAGAIN)) {
02711             no_packet[file_index] = 1;
02712             no_packet_count++;
02713             continue;
02714         }
02715         if (ret < 0) {
02716             input_files[file_index].eof_reached = 1;
02717             if (opt_shortest)
02718                 break;
02719             else
02720                 continue;
02721         }
02722 
02723         no_packet_count = 0;
02724         memset(no_packet, 0, nb_input_files);
02725 
02726         if (do_pkt_dump) {
02727             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
02728                              is->streams[pkt.stream_index]);
02729         }
02730         /* the following test is needed in case new streams appear
02731            dynamically in stream : we ignore them */
02732         if (pkt.stream_index >= input_files[file_index].nb_streams)
02733             goto discard_packet;
02734         ist_index = input_files[file_index].ist_index + pkt.stream_index;
02735         ist = &input_streams[ist_index];
02736         if (ist->discard)
02737             goto discard_packet;
02738 
02739         if (pkt.dts != AV_NOPTS_VALUE)
02740             pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
02741         if (pkt.pts != AV_NOPTS_VALUE)
02742             pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
02743 
02744         if (pkt.pts != AV_NOPTS_VALUE)
02745             pkt.pts *= ist->ts_scale;
02746         if (pkt.dts != AV_NOPTS_VALUE)
02747             pkt.dts *= ist->ts_scale;
02748 
02749         //fprintf(stderr, "next:%"PRId64" dts:%"PRId64" off:%"PRId64" %d\n",
02750         //        ist->next_pts,
02751         //        pkt.dts, input_files[ist->file_index].ts_offset,
02752         //        ist->st->codec->codec_type);
02753         if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
02754             && (is->iformat->flags & AVFMT_TS_DISCONT)) {
02755             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
02756             int64_t delta   = pkt_dts - ist->next_pts;
02757             if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->pts) && !copy_ts) {
02758                 input_files[ist->file_index].ts_offset -= delta;
02759                 av_log(NULL, AV_LOG_DEBUG,
02760                        "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
02761                        delta, input_files[ist->file_index].ts_offset);
02762                 pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02763                 if (pkt.pts != AV_NOPTS_VALUE)
02764                     pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
02765             }
02766         }
02767 
02768         // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
02769         if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0) {
02770 
02771             av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
02772                    ist->file_index, ist->st->index);
02773             if (exit_on_error)
02774                 exit_program(1);
02775             av_free_packet(&pkt);
02776             continue;
02777         }
02778 
02779     discard_packet:
02780         av_free_packet(&pkt);
02781 
02782         /* dump report by using the output first video and audio streams */
02783         print_report(output_files, output_streams, nb_output_streams, 0, timer_start);
02784     }
02785 
02786     /* at the end of stream, we must flush the decoder buffers */
02787     for (i = 0; i < nb_input_streams; i++) {
02788         ist = &input_streams[i];
02789         if (ist->decoding_needed) {
02790             output_packet(ist, output_streams, nb_output_streams, NULL);
02791         }
02792     }
02793     flush_encoders(output_streams, nb_output_streams);
02794 
02795     term_exit();
02796 
02797     /* write the trailer if needed and close file */
02798     for (i = 0; i < nb_output_files; i++) {
02799         os = output_files[i].ctx;
02800         av_write_trailer(os);
02801     }
02802 
02803     /* dump report by using the first video and audio streams */
02804     print_report(output_files, output_streams, nb_output_streams, 1, timer_start);
02805 
02806     /* close each encoder */
02807     for (i = 0; i < nb_output_streams; i++) {
02808         ost = &output_streams[i];
02809         if (ost->encoding_needed) {
02810             av_freep(&ost->st->codec->stats_in);
02811             avcodec_close(ost->st->codec);
02812         }
02813 #if CONFIG_AVFILTER
02814         avfilter_graph_free(&ost->graph);
02815 #endif
02816     }
02817 
02818     /* close each decoder */
02819     for (i = 0; i < nb_input_streams; i++) {
02820         ist = &input_streams[i];
02821         if (ist->decoding_needed) {
02822             avcodec_close(ist->st->codec);
02823         }
02824     }
02825 
02826     /* finished ! */
02827     ret = 0;
02828 
02829  fail:
02830     av_freep(&bit_buffer);
02831     av_freep(&no_packet);
02832 
02833     if (output_streams) {
02834         for (i = 0; i < nb_output_streams; i++) {
02835             ost = &output_streams[i];
02836             if (ost) {
02837                 if (ost->stream_copy)
02838                     av_freep(&ost->st->codec->extradata);
02839                 if (ost->logfile) {
02840                     fclose(ost->logfile);
02841                     ost->logfile = NULL;
02842                 }
02843                 av_fifo_free(ost->fifo); /* works even if fifo is not
02844                                              initialized but set to zero */
02845                 av_freep(&ost->st->codec->subtitle_header);
02846                 av_free(ost->pict_tmp.data[0]);
02847                 av_free(ost->forced_kf_pts);
02848                 if (ost->video_resample)
02849                     sws_freeContext(ost->img_resample_ctx);
02850                 if (ost->resample)
02851                     audio_resample_close(ost->resample);
02852                 if (ost->reformat_ctx)
02853                     av_audio_convert_free(ost->reformat_ctx);
02854                 av_dict_free(&ost->opts);
02855             }
02856         }
02857     }
02858     return ret;
02859 }
02860 
02861 static double parse_frame_aspect_ratio(const char *arg)
02862 {
02863     int x = 0, y = 0;
02864     double ar = 0;
02865     const char *p;
02866     char *end;
02867 
02868     p = strchr(arg, ':');
02869     if (p) {
02870         x = strtol(arg, &end, 10);
02871         if (end == p)
02872             y = strtol(end + 1, &end, 10);
02873         if (x > 0 && y > 0)
02874             ar = (double)x / (double)y;
02875     } else
02876         ar = strtod(arg, NULL);
02877 
02878     if (!ar) {
02879         av_log(NULL, AV_LOG_FATAL, "Incorrect aspect ratio specification.\n");
02880         exit_program(1);
02881     }
02882     return ar;
02883 }
02884 
02885 static int opt_audio_codec(OptionsContext *o, const char *opt, const char *arg)
02886 {
02887     return parse_option(o, "codec:a", arg, options);
02888 }
02889 
02890 static int opt_video_codec(OptionsContext *o, const char *opt, const char *arg)
02891 {
02892     return parse_option(o, "codec:v", arg, options);
02893 }
02894 
02895 static int opt_subtitle_codec(OptionsContext *o, const char *opt, const char *arg)
02896 {
02897     return parse_option(o, "codec:s", arg, options);
02898 }
02899 
02900 static int opt_data_codec(OptionsContext *o, const char *opt, const char *arg)
02901 {
02902     return parse_option(o, "codec:d", arg, options);
02903 }
02904 
02905 static int opt_map(OptionsContext *o, const char *opt, const char *arg)
02906 {
02907     StreamMap *m = NULL;
02908     int i, negative = 0, file_idx;
02909     int sync_file_idx = -1, sync_stream_idx;
02910     char *p, *sync;
02911     char *map;
02912 
02913     if (*arg == '-') {
02914         negative = 1;
02915         arg++;
02916     }
02917     map = av_strdup(arg);
02918 
02919     /* parse sync stream first, just pick first matching stream */
02920     if (sync = strchr(map, ',')) {
02921         *sync = 0;
02922         sync_file_idx = strtol(sync + 1, &sync, 0);
02923         if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {
02924             av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);
02925             exit_program(1);
02926         }
02927         if (*sync)
02928             sync++;
02929         for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)
02930             if (check_stream_specifier(input_files[sync_file_idx].ctx,
02931                                        input_files[sync_file_idx].ctx->streams[i], sync) == 1) {
02932                 sync_stream_idx = i;
02933                 break;
02934             }
02935         if (i == input_files[sync_file_idx].nb_streams) {
02936             av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "
02937                                        "match any streams.\n", arg);
02938             exit_program(1);
02939         }
02940     }
02941 
02942 
02943     file_idx = strtol(map, &p, 0);
02944     if (file_idx >= nb_input_files || file_idx < 0) {
02945         av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);
02946         exit_program(1);
02947     }
02948     if (negative)
02949         /* disable some already defined maps */
02950         for (i = 0; i < o->nb_stream_maps; i++) {
02951             m = &o->stream_maps[i];
02952             if (file_idx == m->file_index &&
02953                 check_stream_specifier(input_files[m->file_index].ctx,
02954                                        input_files[m->file_index].ctx->streams[m->stream_index],
02955                                        *p == ':' ? p + 1 : p) > 0)
02956                 m->disabled = 1;
02957         }
02958     else
02959         for (i = 0; i < input_files[file_idx].nb_streams; i++) {
02960             if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],
02961                         *p == ':' ? p + 1 : p) <= 0)
02962                 continue;
02963             o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),
02964                                         &o->nb_stream_maps, o->nb_stream_maps + 1);
02965             m = &o->stream_maps[o->nb_stream_maps - 1];
02966 
02967             m->file_index   = file_idx;
02968             m->stream_index = i;
02969 
02970             if (sync_file_idx >= 0) {
02971                 m->sync_file_index   = sync_file_idx;
02972                 m->sync_stream_index = sync_stream_idx;
02973             } else {
02974                 m->sync_file_index   = file_idx;
02975                 m->sync_stream_index = i;
02976             }
02977         }
02978 
02979     if (!m) {
02980         av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);
02981         exit_program(1);
02982     }
02983 
02984     av_freep(&map);
02985     return 0;
02986 }
02987 
02988 static int opt_attach(OptionsContext *o, const char *opt, const char *arg)
02989 {
02990     o->attachments = grow_array(o->attachments, sizeof(*o->attachments),
02991                                 &o->nb_attachments, o->nb_attachments + 1);
02992     o->attachments[o->nb_attachments - 1] = arg;
02993     return 0;
02994 }
02995 
03002 static void parse_meta_type(char *arg, char *type, int *index, const char **stream_spec)
03003 {
03004     if (*arg) {
03005         *type = *arg;
03006         switch (*arg) {
03007         case 'g':
03008             break;
03009         case 's':
03010             if (*(++arg) && *arg != ':') {
03011                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", arg);
03012                 exit_program(1);
03013             }
03014             *stream_spec = *arg == ':' ? arg + 1 : "";
03015             break;
03016         case 'c':
03017         case 'p':
03018             if (*(++arg) == ':')
03019                 *index = strtol(++arg, NULL, 0);
03020             break;
03021         default:
03022             av_log(NULL, AV_LOG_FATAL, "Invalid metadata type %c.\n", *arg);
03023             exit_program(1);
03024         }
03025     } else
03026         *type = 'g';
03027 }
03028 
03029 static int copy_metadata(char *outspec, char *inspec, AVFormatContext *oc, AVFormatContext *ic, OptionsContext *o)
03030 {
03031     AVDictionary **meta_in = NULL;
03032     AVDictionary **meta_out;
03033     int i, ret = 0;
03034     char type_in, type_out;
03035     const char *istream_spec = NULL, *ostream_spec = NULL;
03036     int idx_in = 0, idx_out = 0;
03037 
03038     parse_meta_type(inspec,  &type_in,  &idx_in,  &istream_spec);
03039     parse_meta_type(outspec, &type_out, &idx_out, &ostream_spec);
03040 
03041     if (type_in == 'g' || type_out == 'g')
03042         o->metadata_global_manual = 1;
03043     if (type_in == 's' || type_out == 's')
03044         o->metadata_streams_manual = 1;
03045     if (type_in == 'c' || type_out == 'c')
03046         o->metadata_chapters_manual = 1;
03047 
03048 #define METADATA_CHECK_INDEX(index, nb_elems, desc)\
03049     if ((index) < 0 || (index) >= (nb_elems)) {\
03050         av_log(NULL, AV_LOG_FATAL, "Invalid %s index %d while processing metadata maps.\n",\
03051                 (desc), (index));\
03052         exit_program(1);\
03053     }
03054 
03055 #define SET_DICT(type, meta, context, index)\
03056         switch (type) {\
03057         case 'g':\
03058             meta = &context->metadata;\
03059             break;\
03060         case 'c':\
03061             METADATA_CHECK_INDEX(index, context->nb_chapters, "chapter")\
03062             meta = &context->chapters[index]->metadata;\
03063             break;\
03064         case 'p':\
03065             METADATA_CHECK_INDEX(index, context->nb_programs, "program")\
03066             meta = &context->programs[index]->metadata;\
03067             break;\
03068         }\
03069 
03070     SET_DICT(type_in, meta_in, ic, idx_in);
03071     SET_DICT(type_out, meta_out, oc, idx_out);
03072 
03073     /* for input streams choose first matching stream */
03074     if (type_in == 's') {
03075         for (i = 0; i < ic->nb_streams; i++) {
03076             if ((ret = check_stream_specifier(ic, ic->streams[i], istream_spec)) > 0) {
03077                 meta_in = &ic->streams[i]->metadata;
03078                 break;
03079             } else if (ret < 0)
03080                 exit_program(1);
03081         }
03082         if (!meta_in) {
03083             av_log(NULL, AV_LOG_FATAL, "Stream specifier %s does not match  any streams.\n", istream_spec);
03084             exit_program(1);
03085         }
03086     }
03087 
03088     if (type_out == 's') {
03089         for (i = 0; i < oc->nb_streams; i++) {
03090             if ((ret = check_stream_specifier(oc, oc->streams[i], ostream_spec)) > 0) {
03091                 meta_out = &oc->streams[i]->metadata;
03092                 av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
03093             } else if (ret < 0)
03094                 exit_program(1);
03095         }
03096     } else
03097         av_dict_copy(meta_out, *meta_in, AV_DICT_DONT_OVERWRITE);
03098 
03099     return 0;
03100 }
03101 
03102 static AVCodec *find_codec_or_die(const char *name, enum AVMediaType type, int encoder)
03103 {
03104     const char *codec_string = encoder ? "encoder" : "decoder";
03105     AVCodec *codec;
03106 
03107     codec = encoder ?
03108         avcodec_find_encoder_by_name(name) :
03109         avcodec_find_decoder_by_name(name);
03110     if (!codec) {
03111         av_log(NULL, AV_LOG_FATAL, "Unknown %s '%s'\n", codec_string, name);
03112         exit_program(1);
03113     }
03114     if (codec->type != type) {
03115         av_log(NULL, AV_LOG_FATAL, "Invalid %s type '%s'\n", codec_string, name);
03116         exit_program(1);
03117     }
03118     return codec;
03119 }
03120 
03121 static AVCodec *choose_decoder(OptionsContext *o, AVFormatContext *s, AVStream *st)
03122 {
03123     char *codec_name = NULL;
03124 
03125     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
03126     if (codec_name) {
03127         AVCodec *codec = find_codec_or_die(codec_name, st->codec->codec_type, 0);
03128         st->codec->codec_id = codec->id;
03129         return codec;
03130     } else
03131         return avcodec_find_decoder(st->codec->codec_id);
03132 }
03133 
03138 static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
03139 {
03140     int i;
03141 
03142     for (i = 0; i < ic->nb_streams; i++) {
03143         AVStream *st = ic->streams[i];
03144         AVCodecContext *dec = st->codec;
03145         InputStream *ist;
03146 
03147         input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
03148         ist = &input_streams[nb_input_streams - 1];
03149         ist->st = st;
03150         ist->file_index = nb_input_files;
03151         ist->discard = 1;
03152         ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
03153 
03154         ist->ts_scale = 1.0;
03155         MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);
03156 
03157         ist->dec = choose_decoder(o, ic, st);
03158 
03159         switch (dec->codec_type) {
03160         case AVMEDIA_TYPE_AUDIO:
03161             if (o->audio_disable)
03162                 st->discard = AVDISCARD_ALL;
03163             break;
03164         case AVMEDIA_TYPE_VIDEO:
03165             if (dec->lowres) {
03166                 dec->flags |= CODEC_FLAG_EMU_EDGE;
03167                 dec->height >>= dec->lowres;
03168                 dec->width  >>= dec->lowres;
03169             }
03170 
03171             if (o->video_disable)
03172                 st->discard = AVDISCARD_ALL;
03173             else if (video_discard)
03174                 st->discard = video_discard;
03175             break;
03176         case AVMEDIA_TYPE_DATA:
03177             break;
03178         case AVMEDIA_TYPE_SUBTITLE:
03179             if (o->subtitle_disable)
03180                 st->discard = AVDISCARD_ALL;
03181             break;
03182         case AVMEDIA_TYPE_ATTACHMENT:
03183         case AVMEDIA_TYPE_UNKNOWN:
03184             break;
03185         default:
03186             abort();
03187         }
03188     }
03189 }
03190 
03191 static void assert_file_overwrite(const char *filename)
03192 {
03193     if (!file_overwrite &&
03194         (strchr(filename, ':') == NULL || filename[1] == ':' ||
03195          av_strstart(filename, "file:", NULL))) {
03196         if (avio_check(filename, 0) == 0) {
03197             if (!using_stdin) {
03198                 fprintf(stderr,"File '%s' already exists. Overwrite ? [y/N] ", filename);
03199                 fflush(stderr);
03200                 if (!read_yesno()) {
03201                     fprintf(stderr, "Not overwriting - exiting\n");
03202                     exit_program(1);
03203                 }
03204             }
03205             else {
03206                 fprintf(stderr,"File '%s' already exists. Exiting.\n", filename);
03207                 exit_program(1);
03208             }
03209         }
03210     }
03211 }
03212 
03213 static void dump_attachment(AVStream *st, const char *filename)
03214 {
03215     int ret;
03216     AVIOContext *out = NULL;
03217     AVDictionaryEntry *e;
03218 
03219     if (!st->codec->extradata_size) {
03220         av_log(NULL, AV_LOG_WARNING, "No extradata to dump in stream #%d:%d.\n",
03221                nb_input_files - 1, st->index);
03222         return;
03223     }
03224     if (!*filename && (e = av_dict_get(st->metadata, "filename", NULL, 0)))
03225         filename = e->value;
03226     if (!*filename) {
03227         av_log(NULL, AV_LOG_FATAL, "No filename specified and no 'filename' tag"
03228                "in stream #%d:%d.\n", nb_input_files - 1, st->index);
03229         exit_program(1);
03230     }
03231 
03232     assert_file_overwrite(filename);
03233 
03234     if ((ret = avio_open2(&out, filename, AVIO_FLAG_WRITE, &int_cb, NULL)) < 0) {
03235         av_log(NULL, AV_LOG_FATAL, "Could not open file %s for writing.\n",
03236                filename);
03237         exit_program(1);
03238     }
03239 
03240     avio_write(out, st->codec->extradata, st->codec->extradata_size);
03241     avio_flush(out);
03242     avio_close(out);
03243 }
03244 
03245 static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
03246 {
03247     AVFormatContext *ic;
03248     AVInputFormat *file_iformat = NULL;
03249     int err, i, ret;
03250     int64_t timestamp;
03251     uint8_t buf[128];
03252     AVDictionary **opts;
03253     int orig_nb_streams;                     // number of streams before avformat_find_stream_info
03254 
03255     if (o->format) {
03256         if (!(file_iformat = av_find_input_format(o->format))) {
03257             av_log(NULL, AV_LOG_FATAL, "Unknown input format: '%s'\n", o->format);
03258             exit_program(1);
03259         }
03260     }
03261 
03262     if (!strcmp(filename, "-"))
03263         filename = "pipe:";
03264 
03265     using_stdin |= !strncmp(filename, "pipe:", 5) ||
03266                     !strcmp(filename, "/dev/stdin");
03267 
03268     /* get default parameters from command line */
03269     ic = avformat_alloc_context();
03270     if (!ic) {
03271         print_error(filename, AVERROR(ENOMEM));
03272         exit_program(1);
03273     }
03274     if (o->nb_audio_sample_rate) {
03275         snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
03276         av_dict_set(&format_opts, "sample_rate", buf, 0);
03277     }
03278     if (o->nb_audio_channels) {
03279         snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
03280         av_dict_set(&format_opts, "channels", buf, 0);
03281     }
03282     if (o->nb_frame_rates) {
03283         av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
03284     }
03285     if (o->nb_frame_sizes) {
03286         av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
03287     }
03288     if (o->nb_frame_pix_fmts)
03289         av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
03290 
03291     ic->flags |= AVFMT_FLAG_NONBLOCK;
03292     ic->interrupt_callback = int_cb;
03293 
03294     /* open the input file with generic libav function */
03295     err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
03296     if (err < 0) {
03297         print_error(filename, err);
03298         exit_program(1);
03299     }
03300     assert_avoptions(format_opts);
03301 
03302     /* apply forced codec ids */
03303     for (i = 0; i < ic->nb_streams; i++)
03304         choose_decoder(o, ic, ic->streams[i]);
03305 
03306     /* Set AVCodecContext options for avformat_find_stream_info */
03307     opts = setup_find_stream_info_opts(ic, codec_opts);
03308     orig_nb_streams = ic->nb_streams;
03309 
03310     /* If not enough info to get the stream parameters, we decode the
03311        first frames to get it. (used in mpeg case for example) */
03312     ret = avformat_find_stream_info(ic, opts);
03313     if (ret < 0) {
03314         av_log(NULL, AV_LOG_FATAL, "%s: could not find codec parameters\n", filename);
03315         avformat_close_input(&ic);
03316         exit_program(1);
03317     }
03318 
03319     timestamp = o->start_time;
03320     /* add the stream start time */
03321     if (ic->start_time != AV_NOPTS_VALUE)
03322         timestamp += ic->start_time;
03323 
03324     /* if seeking requested, we execute it */
03325     if (o->start_time != 0) {
03326         ret = av_seek_frame(ic, -1, timestamp, AVSEEK_FLAG_BACKWARD);
03327         if (ret < 0) {
03328             av_log(NULL, AV_LOG_WARNING, "%s: could not seek to position %0.3f\n",
03329                    filename, (double)timestamp / AV_TIME_BASE);
03330         }
03331     }
03332 
03333     /* update the current parameters so that they match the one of the input stream */
03334     add_input_streams(o, ic);
03335 
03336     /* dump the file content */
03337     av_dump_format(ic, nb_input_files, filename, 0);
03338 
03339     input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
03340     input_files[nb_input_files - 1].ctx        = ic;
03341     input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;
03342     input_files[nb_input_files - 1].ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
03343     input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
03344     input_files[nb_input_files - 1].rate_emu   = o->rate_emu;
03345 
03346     for (i = 0; i < o->nb_dump_attachment; i++) {
03347         int j;
03348 
03349         for (j = 0; j < ic->nb_streams; j++) {
03350             AVStream *st = ic->streams[j];
03351 
03352             if (check_stream_specifier(ic, st, o->dump_attachment[i].specifier) == 1)
03353                 dump_attachment(st, o->dump_attachment[i].u.str);
03354         }
03355     }
03356 
03357     for (i = 0; i < orig_nb_streams; i++)
03358         av_dict_free(&opts[i]);
03359     av_freep(&opts);
03360 
03361     reset_options(o);
03362     return 0;
03363 }
03364 
03365 static void parse_forced_key_frames(char *kf, OutputStream *ost,
03366                                     AVCodecContext *avctx)
03367 {
03368     char *p;
03369     int n = 1, i;
03370     int64_t t;
03371 
03372     for (p = kf; *p; p++)
03373         if (*p == ',')
03374             n++;
03375     ost->forced_kf_count = n;
03376     ost->forced_kf_pts   = av_malloc(sizeof(*ost->forced_kf_pts) * n);
03377     if (!ost->forced_kf_pts) {
03378         av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
03379         exit_program(1);
03380     }
03381     for (i = 0; i < n; i++) {
03382         p = i ? strchr(p, ',') + 1 : kf;
03383         t = parse_time_or_die("force_key_frames", p, 1);
03384         ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
03385     }
03386 }
03387 
03388 static uint8_t *get_line(AVIOContext *s)
03389 {
03390     AVIOContext *line;
03391     uint8_t *buf;
03392     char c;
03393 
03394     if (avio_open_dyn_buf(&line) < 0) {
03395         av_log(NULL, AV_LOG_FATAL, "Could not alloc buffer for reading preset.\n");
03396         exit_program(1);
03397     }
03398 
03399     while ((c = avio_r8(s)) && c != '\n')
03400         avio_w8(line, c);
03401     avio_w8(line, 0);
03402     avio_close_dyn_buf(line, &buf);
03403 
03404     return buf;
03405 }
03406 
03407 static int get_preset_file_2(const char *preset_name, const char *codec_name, AVIOContext **s)
03408 {
03409     int i, ret = 1;
03410     char filename[1000];
03411     const char *base[3] = { getenv("AVCONV_DATADIR"),
03412                             getenv("HOME"),
03413                             AVCONV_DATADIR,
03414                             };
03415 
03416     for (i = 0; i < FF_ARRAY_ELEMS(base) && ret; i++) {
03417         if (!base[i])
03418             continue;
03419         if (codec_name) {
03420             snprintf(filename, sizeof(filename), "%s%s/%s-%s.avpreset", base[i],
03421                      i != 1 ? "" : "/.avconv", codec_name, preset_name);
03422             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
03423         }
03424         if (ret) {
03425             snprintf(filename, sizeof(filename), "%s%s/%s.avpreset", base[i],
03426                      i != 1 ? "" : "/.avconv", preset_name);
03427             ret = avio_open2(s, filename, AVIO_FLAG_READ, &int_cb, NULL);
03428         }
03429     }
03430     return ret;
03431 }
03432 
03433 static void choose_encoder(OptionsContext *o, AVFormatContext *s, OutputStream *ost)
03434 {
03435     char *codec_name = NULL;
03436 
03437     MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, ost->st);
03438     if (!codec_name) {
03439         ost->st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename,
03440                                                   NULL, ost->st->codec->codec_type);
03441         ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
03442     } else if (!strcmp(codec_name, "copy"))
03443         ost->stream_copy = 1;
03444     else {
03445         ost->enc = find_codec_or_die(codec_name, ost->st->codec->codec_type, 1);
03446         ost->st->codec->codec_id = ost->enc->id;
03447     }
03448 }
03449 
03450 static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
03451 {
03452     OutputStream *ost;
03453     AVStream *st = avformat_new_stream(oc, NULL);
03454     int idx      = oc->nb_streams - 1, ret = 0;
03455     char *bsf = NULL, *next, *codec_tag = NULL;
03456     AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
03457     double qscale = -1;
03458     char *buf = NULL, *arg = NULL, *preset = NULL;
03459     AVIOContext *s = NULL;
03460 
03461     if (!st) {
03462         av_log(NULL, AV_LOG_FATAL, "Could not alloc stream.\n");
03463         exit_program(1);
03464     }
03465 
03466     if (oc->nb_streams - 1 < o->nb_streamid_map)
03467         st->id = o->streamid_map[oc->nb_streams - 1];
03468 
03469     output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
03470                                 nb_output_streams + 1);
03471     ost = &output_streams[nb_output_streams - 1];
03472     ost->file_index = nb_output_files;
03473     ost->index      = idx;
03474     ost->st         = st;
03475     st->codec->codec_type = type;
03476     choose_encoder(o, oc, ost);
03477     if (ost->enc) {
03478         ost->opts  = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
03479     }
03480 
03481     avcodec_get_context_defaults3(st->codec, ost->enc);
03482     st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
03483 
03484     MATCH_PER_STREAM_OPT(presets, str, preset, oc, st);
03485     if (preset && (!(ret = get_preset_file_2(preset, ost->enc->name, &s)))) {
03486         do  {
03487             buf = get_line(s);
03488             if (!buf[0] || buf[0] == '#') {
03489                 av_free(buf);
03490                 continue;
03491             }
03492             if (!(arg = strchr(buf, '='))) {
03493                 av_log(NULL, AV_LOG_FATAL, "Invalid line found in the preset file.\n");
03494                 exit_program(1);
03495             }
03496             *arg++ = 0;
03497             av_dict_set(&ost->opts, buf, arg, AV_DICT_DONT_OVERWRITE);
03498             av_free(buf);
03499         } while (!s->eof_reached);
03500         avio_close(s);
03501     }
03502     if (ret) {
03503         av_log(NULL, AV_LOG_FATAL,
03504                "Preset %s specified for stream %d:%d, but could not be opened.\n",
03505                preset, ost->file_index, ost->index);
03506         exit_program(1);
03507     }
03508 
03509     ost->max_frames = INT64_MAX;
03510     MATCH_PER_STREAM_OPT(max_frames, i64, ost->max_frames, oc, st);
03511 
03512     MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
03513     while (bsf) {
03514         if (next = strchr(bsf, ','))
03515             *next++ = 0;
03516         if (!(bsfc = av_bitstream_filter_init(bsf))) {
03517             av_log(NULL, AV_LOG_FATAL, "Unknown bitstream filter %s\n", bsf);
03518             exit_program(1);
03519         }
03520         if (bsfc_prev)
03521             bsfc_prev->next = bsfc;
03522         else
03523             ost->bitstream_filters = bsfc;
03524 
03525         bsfc_prev = bsfc;
03526         bsf       = next;
03527     }
03528 
03529     MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
03530     if (codec_tag) {
03531         uint32_t tag = strtol(codec_tag, &next, 0);
03532         if (*next)
03533             tag = AV_RL32(codec_tag);
03534         st->codec->codec_tag = tag;
03535     }
03536 
03537     MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
03538     if (qscale >= 0 || same_quant) {
03539         st->codec->flags |= CODEC_FLAG_QSCALE;
03540         st->codec->global_quality = FF_QP2LAMBDA * qscale;
03541     }
03542 
03543     if (oc->oformat->flags & AVFMT_GLOBALHEADER)
03544         st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
03545 
03546     av_opt_get_int(sws_opts, "sws_flags", 0, &ost->sws_flags);
03547     return ost;
03548 }
03549 
03550 static void parse_matrix_coeffs(uint16_t *dest, const char *str)
03551 {
03552     int i;
03553     const char *p = str;
03554     for (i = 0;; i++) {
03555         dest[i] = atoi(p);
03556         if (i == 63)
03557             break;
03558         p = strchr(p, ',');
03559         if (!p) {
03560             av_log(NULL, AV_LOG_FATAL, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
03561             exit_program(1);
03562         }
03563         p++;
03564     }
03565 }
03566 
03567 static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
03568 {
03569     AVStream *st;
03570     OutputStream *ost;
03571     AVCodecContext *video_enc;
03572 
03573     ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
03574     st  = ost->st;
03575     video_enc = st->codec;
03576 
03577     if (!ost->stream_copy) {
03578         const char *p = NULL;
03579         char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
03580         char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
03581         char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
03582         int i;
03583 
03584         MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
03585         if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
03586             av_log(NULL, AV_LOG_FATAL, "Invalid framerate value: %s\n", frame_rate);
03587             exit_program(1);
03588         }
03589 
03590         MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
03591         if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
03592             av_log(NULL, AV_LOG_FATAL, "Invalid frame size: %s.\n", frame_size);
03593             exit_program(1);
03594         }
03595 
03596         MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
03597         if (frame_aspect_ratio)
03598             ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
03599 
03600         MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
03601         if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
03602             av_log(NULL, AV_LOG_FATAL, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
03603             exit_program(1);
03604         }
03605         st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
03606 
03607         MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
03608         if (intra_matrix) {
03609             if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
03610                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for intra matrix.\n");
03611                 exit_program(1);
03612             }
03613             parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
03614         }
03615         MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
03616         if (inter_matrix) {
03617             if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
03618                 av_log(NULL, AV_LOG_FATAL, "Could not allocate memory for inter matrix.\n");
03619                 exit_program(1);
03620             }
03621             parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
03622         }
03623 
03624         MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
03625         for (i = 0; p; i++) {
03626             int start, end, q;
03627             int e = sscanf(p, "%d,%d,%d", &start, &end, &q);
03628             if (e != 3) {
03629                 av_log(NULL, AV_LOG_FATAL, "error parsing rc_override\n");
03630                 exit_program(1);
03631             }
03632             video_enc->rc_override =
03633                 av_realloc(video_enc->rc_override,
03634                            sizeof(RcOverride) * (i + 1));
03635             video_enc->rc_override[i].start_frame = start;
03636             video_enc->rc_override[i].end_frame   = end;
03637             if (q > 0) {
03638                 video_enc->rc_override[i].qscale         = q;
03639                 video_enc->rc_override[i].quality_factor = 1.0;
03640             }
03641             else {
03642                 video_enc->rc_override[i].qscale         = 0;
03643                 video_enc->rc_override[i].quality_factor = -q/100.0;
03644             }
03645             p = strchr(p, '/');
03646             if (p) p++;
03647         }
03648         video_enc->rc_override_count = i;
03649         if (!video_enc->rc_initial_buffer_occupancy)
03650             video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size * 3 / 4;
03651         video_enc->intra_dc_precision = intra_dc_precision - 8;
03652 
03653         /* two pass mode */
03654         if (do_pass) {
03655             if (do_pass == 1) {
03656                 video_enc->flags |= CODEC_FLAG_PASS1;
03657             } else {
03658                 video_enc->flags |= CODEC_FLAG_PASS2;
03659             }
03660         }
03661 
03662         MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
03663         if (forced_key_frames)
03664             parse_forced_key_frames(forced_key_frames, ost, video_enc);
03665 
03666         MATCH_PER_STREAM_OPT(force_fps, i, ost->force_fps, oc, st);
03667 
03668         ost->top_field_first = -1;
03669         MATCH_PER_STREAM_OPT(top_field_first, i, ost->top_field_first, oc, st);
03670 
03671 #if CONFIG_AVFILTER
03672         MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
03673         if (filters)
03674             ost->avfilter = av_strdup(filters);
03675 #endif
03676     } else {
03677         MATCH_PER_STREAM_OPT(copy_initial_nonkeyframes, i, ost->copy_initial_nonkeyframes, oc ,st);
03678     }
03679 
03680     return ost;
03681 }
03682 
03683 static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
03684 {
03685     AVStream *st;
03686     OutputStream *ost;
03687     AVCodecContext *audio_enc;
03688 
03689     ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
03690     st  = ost->st;
03691 
03692     audio_enc = st->codec;
03693     audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
03694 
03695     if (!ost->stream_copy) {
03696         char *sample_fmt = NULL;
03697 
03698         MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
03699 
03700         MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
03701         if (sample_fmt &&
03702             (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
03703             av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);
03704             exit_program(1);
03705         }
03706 
03707         MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
03708     }
03709 
03710     return ost;
03711 }
03712 
03713 static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
03714 {
03715     OutputStream *ost;
03716 
03717     ost = new_output_stream(o, oc, AVMEDIA_TYPE_DATA);
03718     if (!ost->stream_copy) {
03719         av_log(NULL, AV_LOG_FATAL, "Data stream encoding not supported yet (only streamcopy)\n");
03720         exit_program(1);
03721     }
03722 
03723     return ost;
03724 }
03725 
03726 static OutputStream *new_attachment_stream(OptionsContext *o, AVFormatContext *oc)
03727 {
03728     OutputStream *ost = new_output_stream(o, oc, AVMEDIA_TYPE_ATTACHMENT);
03729     ost->stream_copy = 1;
03730     return ost;
03731 }
03732 
03733 static OutputStream *new_subtitle_stream(OptionsContext *o, AVFormatContext *oc)
03734 {
03735     AVStream *st;
03736     OutputStream *ost;
03737     AVCodecContext *subtitle_enc;
03738 
03739     ost = new_output_stream(o, oc, AVMEDIA_TYPE_SUBTITLE);
03740     st  = ost->st;
03741     subtitle_enc = st->codec;
03742 
03743     subtitle_enc->codec_type = AVMEDIA_TYPE_SUBTITLE;
03744 
03745     return ost;
03746 }
03747 
03748 /* arg format is "output-stream-index:streamid-value". */
03749 static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
03750 {
03751     int idx;
03752     char *p;
03753     char idx_str[16];
03754 
03755     av_strlcpy(idx_str, arg, sizeof(idx_str));
03756     p = strchr(idx_str, ':');
03757     if (!p) {
03758         av_log(NULL, AV_LOG_FATAL,
03759                "Invalid value '%s' for option '%s', required syntax is 'index:value'\n",
03760                arg, opt);
03761         exit_program(1);
03762     }
03763     *p++ = '\0';
03764     idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);
03765     o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
03766     o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
03767     return 0;
03768 }
03769 
03770 static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
03771 {
03772     AVFormatContext *is = ifile->ctx;
03773     AVFormatContext *os = ofile->ctx;
03774     int i;
03775 
03776     for (i = 0; i < is->nb_chapters; i++) {
03777         AVChapter *in_ch = is->chapters[i], *out_ch;
03778         int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
03779                                        AV_TIME_BASE_Q, in_ch->time_base);
03780         int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
03781                            av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
03782 
03783 
03784         if (in_ch->end < ts_off)
03785             continue;
03786         if (rt != INT64_MAX && in_ch->start > rt + ts_off)
03787             break;
03788 
03789         out_ch = av_mallocz(sizeof(AVChapter));
03790         if (!out_ch)
03791             return AVERROR(ENOMEM);
03792 
03793         out_ch->id        = in_ch->id;
03794         out_ch->time_base = in_ch->time_base;
03795         out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
03796         out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
03797 
03798         if (copy_metadata)
03799             av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
03800 
03801         os->nb_chapters++;
03802         os->chapters = av_realloc(os->chapters, sizeof(AVChapter) * os->nb_chapters);
03803         if (!os->chapters)
03804             return AVERROR(ENOMEM);
03805         os->chapters[os->nb_chapters - 1] = out_ch;
03806     }
03807     return 0;
03808 }
03809 
03810 static void opt_output_file(void *optctx, const char *filename)
03811 {
03812     OptionsContext *o = optctx;
03813     AVFormatContext *oc;
03814     int i, err;
03815     AVOutputFormat *file_oformat;
03816     OutputStream *ost;
03817     InputStream  *ist;
03818 
03819     if (!strcmp(filename, "-"))
03820         filename = "pipe:";
03821 
03822     oc = avformat_alloc_context();
03823     if (!oc) {
03824         print_error(filename, AVERROR(ENOMEM));
03825         exit_program(1);
03826     }
03827 
03828     if (o->format) {
03829         file_oformat = av_guess_format(o->format, NULL, NULL);
03830         if (!file_oformat) {
03831             av_log(NULL, AV_LOG_FATAL, "Requested output format '%s' is not a suitable output format\n", o->format);
03832             exit_program(1);
03833         }
03834     } else {
03835         file_oformat = av_guess_format(NULL, filename, NULL);
03836         if (!file_oformat) {
03837             av_log(NULL, AV_LOG_FATAL, "Unable to find a suitable output format for '%s'\n",
03838                    filename);
03839             exit_program(1);
03840         }
03841     }
03842 
03843     oc->oformat = file_oformat;
03844     oc->interrupt_callback = int_cb;
03845     av_strlcpy(oc->filename, filename, sizeof(oc->filename));
03846 
03847     if (!o->nb_stream_maps) {
03848         /* pick the "best" stream of each type */
03849 #define NEW_STREAM(type, index)\
03850         if (index >= 0) {\
03851             ost = new_ ## type ## _stream(o, oc);\
03852             ost->source_index = index;\
03853             ost->sync_ist     = &input_streams[index];\
03854             input_streams[index].discard = 0;\
03855         }
03856 
03857         /* video: highest resolution */
03858         if (!o->video_disable && oc->oformat->video_codec != CODEC_ID_NONE) {
03859             int area = 0, idx = -1;
03860             for (i = 0; i < nb_input_streams; i++) {
03861                 ist = &input_streams[i];
03862                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
03863                     ist->st->codec->width * ist->st->codec->height > area) {
03864                     area = ist->st->codec->width * ist->st->codec->height;
03865                     idx = i;
03866                 }
03867             }
03868             NEW_STREAM(video, idx);
03869         }
03870 
03871         /* audio: most channels */
03872         if (!o->audio_disable && oc->oformat->audio_codec != CODEC_ID_NONE) {
03873             int channels = 0, idx = -1;
03874             for (i = 0; i < nb_input_streams; i++) {
03875                 ist = &input_streams[i];
03876                 if (ist->st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
03877                     ist->st->codec->channels > channels) {
03878                     channels = ist->st->codec->channels;
03879                     idx = i;
03880                 }
03881             }
03882             NEW_STREAM(audio, idx);
03883         }
03884 
03885         /* subtitles: pick first */
03886         if (!o->subtitle_disable && oc->oformat->subtitle_codec != CODEC_ID_NONE) {
03887             for (i = 0; i < nb_input_streams; i++)
03888                 if (input_streams[i].st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
03889                     NEW_STREAM(subtitle, i);
03890                     break;
03891                 }
03892         }
03893         /* do something with data? */
03894     } else {
03895         for (i = 0; i < o->nb_stream_maps; i++) {
03896             StreamMap *map = &o->stream_maps[i];
03897 
03898             if (map->disabled)
03899                 continue;
03900 
03901             ist = &input_streams[input_files[map->file_index].ist_index + map->stream_index];
03902             switch (ist->st->codec->codec_type) {
03903             case AVMEDIA_TYPE_VIDEO:    ost = new_video_stream(o, oc);    break;
03904             case AVMEDIA_TYPE_AUDIO:    ost = new_audio_stream(o, oc);    break;
03905             case AVMEDIA_TYPE_SUBTITLE: ost = new_subtitle_stream(o, oc); break;
03906             case AVMEDIA_TYPE_DATA:     ost = new_data_stream(o, oc);     break;
03907             case AVMEDIA_TYPE_ATTACHMENT: ost = new_attachment_stream(o, oc); break;
03908             default:
03909                 av_log(NULL, AV_LOG_FATAL, "Cannot map stream #%d:%d - unsupported type.\n",
03910                        map->file_index, map->stream_index);
03911                 exit_program(1);
03912             }
03913 
03914             ost->source_index = input_files[map->file_index].ist_index + map->stream_index;
03915             ost->sync_ist     = &input_streams[input_files[map->sync_file_index].ist_index +
03916                                            map->sync_stream_index];
03917             ist->discard = 0;
03918         }
03919     }
03920 
03921     /* handle attached files */
03922     for (i = 0; i < o->nb_attachments; i++) {
03923         AVIOContext *pb;
03924         uint8_t *attachment;
03925         const char *p;
03926         int64_t len;
03927 
03928         if ((err = avio_open2(&pb, o->attachments[i], AVIO_FLAG_READ, &int_cb, NULL)) < 0) {
03929             av_log(NULL, AV_LOG_FATAL, "Could not open attachment file %s.\n",
03930                    o->attachments[i]);
03931             exit_program(1);
03932         }
03933         if ((len = avio_size(pb)) <= 0) {
03934             av_log(NULL, AV_LOG_FATAL, "Could not get size of the attachment %s.\n",
03935                    o->attachments[i]);
03936             exit_program(1);
03937         }
03938         if (!(attachment = av_malloc(len))) {
03939             av_log(NULL, AV_LOG_FATAL, "Attachment %s too large to fit into memory.\n",
03940                    o->attachments[i]);
03941             exit_program(1);
03942         }
03943         avio_read(pb, attachment, len);
03944 
03945         ost = new_attachment_stream(o, oc);
03946         ost->stream_copy               = 0;
03947         ost->source_index              = -1;
03948         ost->attachment_filename       = o->attachments[i];
03949         ost->st->codec->extradata      = attachment;
03950         ost->st->codec->extradata_size = len;
03951 
03952         p = strrchr(o->attachments[i], '/');
03953         av_dict_set(&ost->st->metadata, "filename", (p && *p) ? p + 1 : o->attachments[i], AV_DICT_DONT_OVERWRITE);
03954         avio_close(pb);
03955     }
03956 
03957     output_files = grow_array(output_files, sizeof(*output_files), &nb_output_files, nb_output_files + 1);
03958     output_files[nb_output_files - 1].ctx       = oc;
03959     output_files[nb_output_files - 1].ost_index = nb_output_streams - oc->nb_streams;
03960     output_files[nb_output_files - 1].recording_time = o->recording_time;
03961     output_files[nb_output_files - 1].start_time     = o->start_time;
03962     output_files[nb_output_files - 1].limit_filesize = o->limit_filesize;
03963     av_dict_copy(&output_files[nb_output_files - 1].opts, format_opts, 0);
03964 
03965     /* check filename in case of an image number is expected */
03966     if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
03967         if (!av_filename_number_test(oc->filename)) {
03968             print_error(oc->filename, AVERROR(EINVAL));
03969             exit_program(1);
03970         }
03971     }
03972 
03973     if (!(oc->oformat->flags & AVFMT_NOFILE)) {
03974         /* test if it already exists to avoid losing precious files */
03975         assert_file_overwrite(filename);
03976 
03977         /* open the file */
03978         if ((err = avio_open2(&oc->pb, filename, AVIO_FLAG_WRITE,
03979                               &oc->interrupt_callback,
03980                               &output_files[nb_output_files - 1].opts)) < 0) {
03981             print_error(filename, err);
03982             exit_program(1);
03983         }
03984     }
03985 
03986     if (o->mux_preload) {
03987         uint8_t buf[64];
03988         snprintf(buf, sizeof(buf), "%d", (int)(o->mux_preload*AV_TIME_BASE));
03989         av_dict_set(&output_files[nb_output_files - 1].opts, "preload", buf, 0);
03990     }
03991     oc->max_delay = (int)(o->mux_max_delay * AV_TIME_BASE);
03992     oc->flags |= AVFMT_FLAG_NONBLOCK;
03993 
03994     /* copy metadata */
03995     for (i = 0; i < o->nb_metadata_map; i++) {
03996         char *p;
03997         int in_file_index = strtol(o->metadata_map[i].u.str, &p, 0);
03998 
03999         if (in_file_index < 0)
04000             continue;
04001         if (in_file_index >= nb_input_files) {
04002             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d while processing metadata maps\n", in_file_index);
04003             exit_program(1);
04004         }
04005         copy_metadata(o->metadata_map[i].specifier, *p ? p + 1 : p, oc, input_files[in_file_index].ctx, o);
04006     }
04007 
04008     /* copy chapters */
04009     if (o->chapters_input_file >= nb_input_files) {
04010         if (o->chapters_input_file == INT_MAX) {
04011             /* copy chapters from the first input file that has them*/
04012             o->chapters_input_file = -1;
04013             for (i = 0; i < nb_input_files; i++)
04014                 if (input_files[i].ctx->nb_chapters) {
04015                     o->chapters_input_file = i;
04016                     break;
04017                 }
04018         } else {
04019             av_log(NULL, AV_LOG_FATAL, "Invalid input file index %d in chapter mapping.\n",
04020                    o->chapters_input_file);
04021             exit_program(1);
04022         }
04023     }
04024     if (o->chapters_input_file >= 0)
04025         copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
04026                       !o->metadata_chapters_manual);
04027 
04028     /* copy global metadata by default */
04029     if (!o->metadata_global_manual && nb_input_files)
04030         av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
04031                      AV_DICT_DONT_OVERWRITE);
04032     if (!o->metadata_streams_manual)
04033         for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
04034             InputStream *ist;
04035             if (output_streams[i].source_index < 0)         /* this is true e.g. for attached files */
04036                 continue;
04037             ist = &input_streams[output_streams[i].source_index];
04038             av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
04039         }
04040 
04041     /* process manually set metadata */
04042     for (i = 0; i < o->nb_metadata; i++) {
04043         AVDictionary **m;
04044         char type, *val;
04045         const char *stream_spec;
04046         int index = 0, j, ret;
04047 
04048         val = strchr(o->metadata[i].u.str, '=');
04049         if (!val) {
04050             av_log(NULL, AV_LOG_FATAL, "No '=' character in metadata string %s.\n",
04051                    o->metadata[i].u.str);
04052             exit_program(1);
04053         }
04054         *val++ = 0;
04055 
04056         parse_meta_type(o->metadata[i].specifier, &type, &index, &stream_spec);
04057         if (type == 's') {
04058             for (j = 0; j < oc->nb_streams; j++) {
04059                 if ((ret = check_stream_specifier(oc, oc->streams[j], stream_spec)) > 0) {
04060                     av_dict_set(&oc->streams[j]->metadata, o->metadata[i].u.str, *val ? val : NULL, 0);
04061                 } else if (ret < 0)
04062                     exit_program(1);
04063             }
04064             printf("ret %d, stream_spec %s\n", ret, stream_spec);
04065         }
04066         else {
04067             switch (type) {
04068             case 'g':
04069                 m = &oc->metadata;
04070                 break;
04071             case 'c':
04072                 if (index < 0 || index >= oc->nb_chapters) {
04073                     av_log(NULL, AV_LOG_FATAL, "Invalid chapter index %d in metadata specifier.\n", index);
04074                     exit_program(1);
04075                 }
04076                 m = &oc->chapters[index]->metadata;
04077                 break;
04078             default:
04079                 av_log(NULL, AV_LOG_FATAL, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
04080                 exit_program(1);
04081             }
04082             av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
04083         }
04084     }
04085 
04086     reset_options(o);
04087 }
04088 
04089 /* same option as mencoder */
04090 static int opt_pass(const char *opt, const char *arg)
04091 {
04092     do_pass = parse_number_or_die(opt, arg, OPT_INT, 1, 2);
04093     return 0;
04094 }
04095 
04096 static int64_t getutime(void)
04097 {
04098 #if HAVE_GETRUSAGE
04099     struct rusage rusage;
04100 
04101     getrusage(RUSAGE_SELF, &rusage);
04102     return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
04103 #elif HAVE_GETPROCESSTIMES
04104     HANDLE proc;
04105     FILETIME c, e, k, u;
04106     proc = GetCurrentProcess();
04107     GetProcessTimes(proc, &c, &e, &k, &u);
04108     return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
04109 #else
04110     return av_gettime();
04111 #endif
04112 }
04113 
04114 static int64_t getmaxrss(void)
04115 {
04116 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
04117     struct rusage rusage;
04118     getrusage(RUSAGE_SELF, &rusage);
04119     return (int64_t)rusage.ru_maxrss * 1024;
04120 #elif HAVE_GETPROCESSMEMORYINFO
04121     HANDLE proc;
04122     PROCESS_MEMORY_COUNTERS memcounters;
04123     proc = GetCurrentProcess();
04124     memcounters.cb = sizeof(memcounters);
04125     GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
04126     return memcounters.PeakPagefileUsage;
04127 #else
04128     return 0;
04129 #endif
04130 }
04131 
04132 static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
04133 {
04134     return parse_option(o, "q:a", arg, options);
04135 }
04136 
04137 static void show_usage(void)
04138 {
04139     printf("Hyper fast Audio and Video encoder\n");
04140     printf("usage: %s [options] [[infile options] -i infile]... {[outfile options] outfile}...\n", program_name);
04141     printf("\n");
04142 }
04143 
04144 static void show_help(void)
04145 {
04146     int flags = AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_ENCODING_PARAM;
04147     av_log_set_callback(log_callback_help);
04148     show_usage();
04149     show_help_options(options, "Main options:\n",
04150                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB, 0);
04151     show_help_options(options, "\nAdvanced options:\n",
04152                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_SUBTITLE | OPT_GRAB,
04153                       OPT_EXPERT);
04154     show_help_options(options, "\nVideo options:\n",
04155                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04156                       OPT_VIDEO);
04157     show_help_options(options, "\nAdvanced Video options:\n",
04158                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04159                       OPT_VIDEO | OPT_EXPERT);
04160     show_help_options(options, "\nAudio options:\n",
04161                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04162                       OPT_AUDIO);
04163     show_help_options(options, "\nAdvanced Audio options:\n",
04164                       OPT_EXPERT | OPT_AUDIO | OPT_VIDEO | OPT_GRAB,
04165                       OPT_AUDIO | OPT_EXPERT);
04166     show_help_options(options, "\nSubtitle options:\n",
04167                       OPT_SUBTITLE | OPT_GRAB,
04168                       OPT_SUBTITLE);
04169     show_help_options(options, "\nAudio/Video grab options:\n",
04170                       OPT_GRAB,
04171                       OPT_GRAB);
04172     printf("\n");
04173     show_help_children(avcodec_get_class(), flags);
04174     show_help_children(avformat_get_class(), flags);
04175     show_help_children(sws_get_class(), flags);
04176 }
04177 
04178 static int opt_target(OptionsContext *o, const char *opt, const char *arg)
04179 {
04180     enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;
04181     static const char *const frame_rates[] = { "25", "30000/1001", "24000/1001" };
04182 
04183     if (!strncmp(arg, "pal-", 4)) {
04184         norm = PAL;
04185         arg += 4;
04186     } else if (!strncmp(arg, "ntsc-", 5)) {
04187         norm = NTSC;
04188         arg += 5;
04189     } else if (!strncmp(arg, "film-", 5)) {
04190         norm = FILM;
04191         arg += 5;
04192     } else {
04193         /* Try to determine PAL/NTSC by peeking in the input files */
04194         if (nb_input_files) {
04195             int i, j, fr;
04196             for (j = 0; j < nb_input_files; j++) {
04197                 for (i = 0; i < input_files[j].nb_streams; i++) {
04198                     AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
04199                     if (c->codec_type != AVMEDIA_TYPE_VIDEO)
04200                         continue;
04201                     fr = c->time_base.den * 1000 / c->time_base.num;
04202                     if (fr == 25000) {
04203                         norm = PAL;
04204                         break;
04205                     } else if ((fr == 29970) || (fr == 23976)) {
04206                         norm = NTSC;
04207                         break;
04208                     }
04209                 }
04210                 if (norm != UNKNOWN)
04211                     break;
04212             }
04213         }
04214         if (norm != UNKNOWN)
04215             av_log(NULL, AV_LOG_INFO, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");
04216     }
04217 
04218     if (norm == UNKNOWN) {
04219         av_log(NULL, AV_LOG_FATAL, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");
04220         av_log(NULL, AV_LOG_FATAL, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");
04221         av_log(NULL, AV_LOG_FATAL, "or set a framerate with \"-r xxx\".\n");
04222         exit_program(1);
04223     }
04224 
04225     if (!strcmp(arg, "vcd")) {
04226         opt_video_codec(o, "c:v", "mpeg1video");
04227         opt_audio_codec(o, "c:a", "mp2");
04228         parse_option(o, "f", "vcd", options);
04229 
04230         parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
04231         parse_option(o, "r", frame_rates[norm], options);
04232         opt_default("g", norm == PAL ? "15" : "18");
04233 
04234         opt_default("b", "1150000");
04235         opt_default("maxrate", "1150000");
04236         opt_default("minrate", "1150000");
04237         opt_default("bufsize", "327680"); // 40*1024*8;
04238 
04239         opt_default("b:a", "224000");
04240         parse_option(o, "ar", "44100", options);
04241         parse_option(o, "ac", "2", options);
04242 
04243         opt_default("packetsize", "2324");
04244         opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
04245 
04246         /* We have to offset the PTS, so that it is consistent with the SCR.
04247            SCR starts at 36000, but the first two packs contain only padding
04248            and the first pack from the other stream, respectively, may also have
04249            been written before.
04250            So the real data starts at SCR 36000+3*1200. */
04251         o->mux_preload = (36000 + 3 * 1200) / 90000.0; // 0.44
04252     } else if (!strcmp(arg, "svcd")) {
04253 
04254         opt_video_codec(o, "c:v", "mpeg2video");
04255         opt_audio_codec(o, "c:a", "mp2");
04256         parse_option(o, "f", "svcd", options);
04257 
04258         parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
04259         parse_option(o, "r", frame_rates[norm], options);
04260         opt_default("g", norm == PAL ? "15" : "18");
04261 
04262         opt_default("b", "2040000");
04263         opt_default("maxrate", "2516000");
04264         opt_default("minrate", "0"); // 1145000;
04265         opt_default("bufsize", "1835008"); // 224*1024*8;
04266         opt_default("flags", "+scan_offset");
04267 
04268 
04269         opt_default("b:a", "224000");
04270         parse_option(o, "ar", "44100", options);
04271 
04272         opt_default("packetsize", "2324");
04273 
04274     } else if (!strcmp(arg, "dvd")) {
04275 
04276         opt_video_codec(o, "c:v", "mpeg2video");
04277         opt_audio_codec(o, "c:a", "ac3");
04278         parse_option(o, "f", "dvd", options);
04279 
04280         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
04281         parse_option(o, "r", frame_rates[norm], options);
04282         opt_default("g", norm == PAL ? "15" : "18");
04283 
04284         opt_default("b", "6000000");
04285         opt_default("maxrate", "9000000");
04286         opt_default("minrate", "0"); // 1500000;
04287         opt_default("bufsize", "1835008"); // 224*1024*8;
04288 
04289         opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
04290         opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
04291 
04292         opt_default("b:a", "448000");
04293         parse_option(o, "ar", "48000", options);
04294 
04295     } else if (!strncmp(arg, "dv", 2)) {
04296 
04297         parse_option(o, "f", "dv", options);
04298 
04299         parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
04300         parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
04301                           norm == PAL ? "yuv420p" : "yuv411p", options);
04302         parse_option(o, "r", frame_rates[norm], options);
04303 
04304         parse_option(o, "ar", "48000", options);
04305         parse_option(o, "ac", "2", options);
04306 
04307     } else {
04308         av_log(NULL, AV_LOG_ERROR, "Unknown target: %s\n", arg);
04309         return AVERROR(EINVAL);
04310     }
04311     return 0;
04312 }
04313 
04314 static int opt_vstats_file(const char *opt, const char *arg)
04315 {
04316     av_free (vstats_filename);
04317     vstats_filename = av_strdup (arg);
04318     return 0;
04319 }
04320 
04321 static int opt_vstats(const char *opt, const char *arg)
04322 {
04323     char filename[40];
04324     time_t today2 = time(NULL);
04325     struct tm *today = localtime(&today2);
04326 
04327     snprintf(filename, sizeof(filename), "vstats_%02d%02d%02d.log", today->tm_hour, today->tm_min,
04328              today->tm_sec);
04329     return opt_vstats_file(opt, filename);
04330 }
04331 
04332 static int opt_video_frames(OptionsContext *o, const char *opt, const char *arg)
04333 {
04334     return parse_option(o, "frames:v", arg, options);
04335 }
04336 
04337 static int opt_audio_frames(OptionsContext *o, const char *opt, const char *arg)
04338 {
04339     return parse_option(o, "frames:a", arg, options);
04340 }
04341 
04342 static int opt_data_frames(OptionsContext *o, const char *opt, const char *arg)
04343 {
04344     return parse_option(o, "frames:d", arg, options);
04345 }
04346 
04347 static int opt_video_tag(OptionsContext *o, const char *opt, const char *arg)
04348 {
04349     return parse_option(o, "tag:v", arg, options);
04350 }
04351 
04352 static int opt_audio_tag(OptionsContext *o, const char *opt, const char *arg)
04353 {
04354     return parse_option(o, "tag:a", arg, options);
04355 }
04356 
04357 static int opt_subtitle_tag(OptionsContext *o, const char *opt, const char *arg)
04358 {
04359     return parse_option(o, "tag:s", arg, options);
04360 }
04361 
04362 static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
04363 {
04364     return parse_option(o, "filter:v", arg, options);
04365 }
04366 
04367 static int opt_vsync(const char *opt, const char *arg)
04368 {
04369     if      (!av_strcasecmp(arg, "cfr"))         video_sync_method = VSYNC_CFR;
04370     else if (!av_strcasecmp(arg, "vfr"))         video_sync_method = VSYNC_VFR;
04371     else if (!av_strcasecmp(arg, "passthrough")) video_sync_method = VSYNC_PASSTHROUGH;
04372 
04373     if (video_sync_method == VSYNC_AUTO)
04374         video_sync_method = parse_number_or_die("vsync", arg, OPT_INT, VSYNC_AUTO, VSYNC_VFR);
04375     return 0;
04376 }
04377 
04378 #define OFFSET(x) offsetof(OptionsContext, x)
04379 static const OptionDef options[] = {
04380     /* main options */
04381 #include "cmdutils_common_opts.h"
04382     { "f", HAS_ARG | OPT_STRING | OPT_OFFSET, {.off = OFFSET(format)}, "force format", "fmt" },
04383     { "i", HAS_ARG | OPT_FUNC2, {(void*)opt_input_file}, "input file name", "filename" },
04384     { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
04385     { "c", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
04386     { "codec", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(codec_names)}, "codec name", "codec" },
04387     { "pre", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(presets)}, "preset name", "preset" },
04388     { "map", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_map}, "set input stream mapping", "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
04389     { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata_map)}, "set metadata information of outfile from infile",
04390       "outfile[,metadata]:infile[,metadata]" },
04391     { "map_chapters",  OPT_INT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(chapters_input_file)},  "set chapters mapping", "input_file_index" },
04392     { "t", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(recording_time)}, "record or transcode \"duration\" seconds of audio/video", "duration" },
04393     { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET, {.off = OFFSET(limit_filesize)}, "set the limit file size in bytes", "limit_size" }, //
04394     { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(start_time)}, "set the start time offset", "time_off" },
04395     { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET, {.off = OFFSET(input_ts_offset)}, "set the input ts offset", "time_off" },
04396     { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(ts_scale)}, "set the input ts scale", "scale" },
04397     { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(metadata)}, "add metadata", "string=string" },
04398     { "dframes", HAS_ARG | OPT_FUNC2, {(void*)opt_data_frames}, "set the number of data frames to record", "number" },
04399     { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
04400       "add timings for benchmarking" },
04401     { "timelimit", HAS_ARG, {(void*)opt_timelimit}, "set max runtime in seconds", "limit" },
04402     { "dump", OPT_BOOL | OPT_EXPERT, {(void*)&do_pkt_dump},
04403       "dump each input packet" },
04404     { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
04405       "when dumping packets, also dump the payload" },
04406     { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
04407     { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
04408     { "vsync", HAS_ARG | OPT_EXPERT, {(void*)opt_vsync}, "video sync method", "" },
04409     { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
04410     { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
04411     { "copyts", OPT_BOOL | OPT_EXPERT, {(void*)&copy_ts}, "copy timestamps" },
04412     { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
04413     { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
04414     { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
04415     { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
04416     { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC, {.off = OFFSET(copy_initial_nonkeyframes)}, "copy initial non-keyframes" },
04417     { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
04418     { "tag",   OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
04419     { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
04420     { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
04421 #if CONFIG_AVFILTER
04422     { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
04423 #endif
04424     { "stats", OPT_BOOL, {&print_stats}, "print progress report during encoding", },
04425     { "attach", HAS_ARG | OPT_FUNC2, {(void*)opt_attach}, "add an attachment to the output file", "filename" },
04426     { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(dump_attachment)}, "extract an attachment into a file", "filename" },
04427 
04428     /* video options */
04429     { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
04430     { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
04431     { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
04432     { "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" },
04433     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
04434     { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
04435     { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
04436     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
04437     { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
04438     { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
04439       "use same quantizer as source (implies VBR)" },
04440     { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
04441     { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
04442     { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
04443       "deinterlace pictures" },
04444     { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
04445     { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
04446 #if CONFIG_AVFILTER
04447     { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
04448 #endif
04449     { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
04450     { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
04451     { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
04452     { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
04453     { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_tag}, "force video tag/fourcc", "fourcc/tag" },
04454     { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
04455     { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
04456     { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
04457     { "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" },
04458 
04459     /* audio options */
04460     { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
04461     { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
04462     { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
04463     { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
04464     { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
04465     { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
04466     { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_tag}, "force audio tag/fourcc", "fourcc/tag" },
04467     { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
04468     { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
04469 
04470     /* subtitle options */
04471     { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
04472     { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
04473     { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
04474 
04475     /* grab options */
04476     { "isync", OPT_BOOL | OPT_EXPERT | OPT_GRAB, {(void*)&input_sync}, "sync read on input", "" },
04477 
04478     /* muxer options */
04479     { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT   | OPT_OFFSET, {.off = OFFSET(mux_max_delay)}, "set the maximum demux-decode delay", "seconds" },
04480     { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(mux_preload)},   "set the initial demux-decode delay", "seconds" },
04481 
04482     { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(bitstream_filters)}, "A comma-separated list of bitstream filters", "bitstream_filters" },
04483 
04484     /* data codec support */
04485     { "dcodec", HAS_ARG | OPT_DATA | OPT_FUNC2, {(void*)opt_data_codec}, "force data codec ('copy' to copy stream)", "codec" },
04486 
04487     { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
04488     { NULL, },
04489 };
04490 
04491 int main(int argc, char **argv)
04492 {
04493     OptionsContext o = { 0 };
04494     int64_t ti;
04495 
04496     reset_options(&o);
04497 
04498     av_log_set_flags(AV_LOG_SKIP_REPEATED);
04499     parse_loglevel(argc, argv, options);
04500 
04501     avcodec_register_all();
04502 #if CONFIG_AVDEVICE
04503     avdevice_register_all();
04504 #endif
04505 #if CONFIG_AVFILTER
04506     avfilter_register_all();
04507 #endif
04508     av_register_all();
04509     avformat_network_init();
04510 
04511     show_banner();
04512 
04513     /* parse options */
04514     parse_options(&o, argc, argv, options, opt_output_file);
04515 
04516     if (nb_output_files <= 0 && nb_input_files == 0) {
04517         show_usage();
04518         av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
04519         exit_program(1);
04520     }
04521 
04522     /* file converter / grab */
04523     if (nb_output_files <= 0) {
04524         fprintf(stderr, "At least one output file must be specified\n");
04525         exit_program(1);
04526     }
04527 
04528     if (nb_input_files == 0) {
04529         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
04530         exit_program(1);
04531     }
04532 
04533     ti = getutime();
04534     if (transcode(output_files, nb_output_files, input_files, nb_input_files) < 0)
04535         exit_program(1);
04536     ti = getutime() - ti;
04537     if (do_benchmark) {
04538         int maxrss = getmaxrss() / 1024;
04539         printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
04540     }
04541 
04542     exit_program(0);
04543     return 0;
04544 }