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

ffmpeg.c

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