]> git.sesse.net Git - ffmpeg/commitdiff
Merge remote-tracking branch 'qatar/master'
authorMichael Niedermayer <michaelni@gmx.at>
Sun, 11 Sep 2011 21:35:35 +0000 (23:35 +0200)
committerMichael Niedermayer <michaelni@gmx.at>
Sun, 11 Sep 2011 22:32:54 +0000 (00:32 +0200)
* qatar/master: (31 commits)
  audioconvert: add explanatory comments to channel_names array
  audioconvert: K&R whitespace cosmetics
  avconv: use correct index when selecting metadata to write to.
  avconv: fix inverted variable
  doc/avconv: document option types (input/output/per-stream/...)
  doc/avtools-common-opts: write a section about stream specifiers.
  doc/avconv: remove two pointless paragraphs.
  doc/avconv: document that global options should be specified first.
  doc/avconv: remove entries for nonexistent options
  doc/avconv: remove documentation for removed 'timestamp' option
  doc: cosmetics, rename fftools-common-opts to avtools-....
  avconv: move streamid_map to options context.
  avconv: extend -vf syntax
  avconv: move top_field_first to options context.
  avconv: move inter/intra matrix to options context.
  avconv: remove -psnr option.
  avconv: remove me_threshold option.
  avconv: move video_rc_override_string to options context.
  avconv: move frame pixel format to the options context.
  avconv: move frame aspect ratio to the options context.
  ...

Conflicts:
avconv.c
cmdutils_common_opts.h
doc/avconv.texi

Merged-by: Michael Niedermayer <michaelni@gmx.at>
17 files changed:
1  2 
avconv.c
cmdutils.c
cmdutils.h
cmdutils_common_opts.h
doc/avconv.texi
doc/avtools-common-opts.texi
doc/faq.texi
doc/ffmpeg.texi
doc/ffplay.texi
doc/ffprobe.texi
doc/ffserver.texi
ffmpeg.c
libavcodec/options.c
libavformat/mpegts.c
libavformat/utils.c
libavutil/audioconvert.c
tests/lavf-regression.sh

diff --cc avconv.c
index d80e93077bad4b3506284bddadfbf3a7b0269385,74120c8c5e1e3ffe7382f60f924e6e768523dbee..75186544a2bd0dee8d7304726c29cb6a6c073481
+++ b/avconv.c
@@@ -109,23 -97,6 +109,9 @@@ typedef struct MetadataMap 
  
  static const OptionDef options[];
  
- /* indexed by output file stream index */
- static int *streamid_map = NULL;
- static int nb_streamid_map = 0;
- static int frame_width  = 0;
- static int frame_height = 0;
- static float frame_aspect_ratio = 0;
- static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
 +#define MAX_STREAMS 1024    /* arbitrary sanity check value */
 +
- static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
- static AVRational frame_rate;
- static float video_qscale = 0;
- static uint16_t *intra_matrix = NULL;
- static uint16_t *inter_matrix = NULL;
- static const char *video_rc_override_string=NULL;
 +static int frame_bits_per_raw_sample = 0;
  static int video_discard = 0;
  static int same_quant = 0;
  static int do_deinterlace = 0;
@@@ -145,9 -107,8 +122,8 @@@ static int file_overwrite = 0
  static int do_benchmark = 0;
  static int do_hex_dump = 0;
  static int do_pkt_dump = 0;
- static int do_psnr = 0;
  static int do_pass = 0;
 -static char *pass_logfilename_prefix = NULL;
 +static const char *pass_logfilename_prefix;
  static int video_sync_method= -1;
  static int audio_sync_method= 0;
  static float audio_drift_threshold= 0.1;
@@@ -2949,9 -2768,9 +2889,7 @@@ static void add_input_streams(OptionsCo
              rfps_base = ic->streams[i]->r_frame_rate.den;
              if (dec->lowres) {
                  dec->flags |= CODEC_FLAG_EMU_EDGE;
 -                dec->height >>= dec->lowres;
 -                dec->width  >>= dec->lowres;
              }
-             if(me_threshold)
-                 dec->debug |= FF_DEBUG_MV;
  
              if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
  
@@@ -3398,9 -3225,9 +3346,9 @@@ static int opt_streamid(OptionsContext 
          exit_program(1);
      }
      *p++ = '\0';
 -    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);
 +    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
-     streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
-     streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
+     o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
+     o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
      return 0;
  }
  
@@@ -4164,24 -3954,20 +4074,21 @@@ static const OptionDef options[] = 
  
      /* video options */
      { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
-     { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
-     { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
-     { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
-     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format, 'list' as argument shows all the pixel formats supported", "format" },
+     { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
+     { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
+     { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
+     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
 +    { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
      { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
      { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
-     { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
-     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
+     { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
      { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
-     { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimation threshold",  "threshold" },
      { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
        "use same quantizer as source (implies VBR)" },
      { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
 -    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
 +    { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
      { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
        "deinterlace pictures" },
-     { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
      { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
      { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
  #if CONFIG_AVFILTER
diff --cc cmdutils.c
index c72c74737b8d0dc5207a091ea9aa59e0e4675636,16b64aff23dd80bb1247b4ae0c5fad5388b35e00..f7b24f65bda0943cfbce1cb9e4ff59a8004187f4
@@@ -727,9 -715,17 +727,18 @@@ int opt_pix_fmts(const char *opt, cons
                 pix_desc->nb_components,
                 av_get_bits_per_pixel(pix_desc));
      }
 +    return 0;
  }
  
+ int show_sample_fmts(const char *opt, const char *arg)
+ {
+     int i;
+     char fmt_str[128];
+     for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
+         printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
+     return 0;
+ }
  int read_yesno(void)
  {
      int c = getchar();
diff --cc cmdutils.h
index 586cff6c5fa1c8a641e7eaece39472b200ee038d,dc194868340651fc21f18a923aedbc7d4f9de281..005697e7c5f91c05fcb9e2c1775f37481e39290f
@@@ -285,9 -274,14 +285,15 @@@ int opt_protocols(const char *opt, cons
  /**
   * Print a listing containing all the pixel formats supported by the
   * program.
 + * This option processing function does not utilize the arguments.
   */
 -void show_pix_fmts(void);
 +int opt_pix_fmts(const char *opt, const char *arg);
+ /**
+  * Print a listing containing all the sample formats supported by the
+  * program.
+  */
+ int show_sample_fmts(const char *opt, const char *arg);
  
  /**
   * Return a positive value if a line read from standard input
index 8e680490fef02b45b6aafa848ab053d0bad0e27e,36b2e322e5ce0b225ef3701760aee2fd21e44150..3a731f2bf92626579bb21d689bd43bc942ac6160
@@@ -1,13 -1,14 +1,14 @@@
 -    { "L", OPT_EXIT, {(void*)show_license}, "show license" },
 -    { "h", OPT_EXIT, {(void*)show_help}, "show help" },
 -    { "?", OPT_EXIT, {(void*)show_help}, "show help" },
 -    { "help", OPT_EXIT, {(void*)show_help}, "show help" },
 -    { "-help", OPT_EXIT, {(void*)show_help}, "show help" },
 -    { "version", OPT_EXIT, {(void*)show_version}, "show version" },
 -    { "formats"  , OPT_EXIT, {(void*)show_formats  }, "show available formats" },
 -    { "codecs"   , OPT_EXIT, {(void*)show_codecs   }, "show available codecs" },
 -    { "bsfs"     , OPT_EXIT, {(void*)show_bsfs     }, "show available bit stream filters" },
 -    { "protocols", OPT_EXIT, {(void*)show_protocols}, "show available protocols" },
 -    { "filters",   OPT_EXIT, {(void*)show_filters  }, "show available filters" },
 -    { "pix_fmts" , OPT_EXIT, {(void*)show_pix_fmts }, "show available pixel formats" },
 +    { "L", OPT_EXIT, {(void*)opt_license}, "show license" },
 +    { "h", OPT_EXIT, {(void*)opt_help}, "show help" },
 +    { "?", OPT_EXIT, {(void*)opt_help}, "show help" },
 +    { "help", OPT_EXIT, {(void*)opt_help}, "show help" },
 +    { "-help", OPT_EXIT, {(void*)opt_help}, "show help" },
 +    { "version", OPT_EXIT, {(void*)opt_version}, "show version" },
 +    { "formats"  , OPT_EXIT, {(void*)opt_formats  }, "show available formats" },
 +    { "codecs"   , OPT_EXIT, {(void*)opt_codecs   }, "show available codecs" },
 +    { "bsfs"     , OPT_EXIT, {(void*)opt_bsfs     }, "show available bit stream filters" },
 +    { "protocols", OPT_EXIT, {(void*)opt_protocols}, "show available protocols" },
 +    { "filters",   OPT_EXIT, {(void*)opt_filters  }, "show available filters" },
 +    { "pix_fmts" , OPT_EXIT, {(void*)opt_pix_fmts }, "show available pixel formats" },
+     { "sample_fmts", OPT_EXIT, {.func_arg = show_sample_fmts }, "show available audio sample formats" },
      { "loglevel", HAS_ARG, {(void*)opt_loglevel}, "set libav* logging level", "loglevel" },
diff --cc doc/avconv.texi
Simple merge
Simple merge
diff --cc doc/faq.texi
Simple merge
diff --cc doc/ffmpeg.texi
Simple merge
diff --cc doc/ffplay.texi
Simple merge
Simple merge
Simple merge
diff --cc ffmpeg.c
index 048d2fabe1dbea2c33ce4938e4854fab07306869,a440b9dacb8bb7d33bc0ffc714a9cf90945505fc..fa7a3943b511cf80ccb738f175a0981d1acc7e84
+++ b/ffmpeg.c
@@@ -107,55 -94,105 +107,31 @@@ typedef struct MetadataMap 
      int  index;     ///< stream/chapter/program number
  } MetadataMap;
  
 -typedef struct ChapterMap {
 -    int in_file;
 -    int out_file;
 -} ChapterMap;
 -
  static const OptionDef options[];
  
 -#define MAX_FILES 100
 -
 -static const char *last_asked_format = NULL;
 -static double *ts_scale;
 -static int  nb_ts_scale;
 -
 -static AVFormatContext *output_files[MAX_FILES];
 -static AVDictionary *output_opts[MAX_FILES];
 -static int nb_output_files = 0;
 -
 -static StreamMap *stream_maps = NULL;
 -static int nb_stream_maps;
 -
 -/* first item specifies output metadata, second is input */
 -static MetadataMap (*meta_data_maps)[2] = NULL;
 -static int nb_meta_data_maps;
 -static int metadata_global_autocopy   = 1;
 -static int metadata_streams_autocopy  = 1;
 -static int metadata_chapters_autocopy = 1;
 -
 -static ChapterMap *chapter_maps = NULL;
 -static int nb_chapter_maps;
 -
 -/* indexed by output file stream index */
 -static int *streamid_map = NULL;
 -static int nb_streamid_map = 0;
 -
 -static int frame_width  = 0;
 -static int frame_height = 0;
 -static float frame_aspect_ratio = 0;
 -static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
 -static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
 -static int max_frames[4] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
 -static AVRational frame_rate;
 -static float video_qscale = 0;
 -static uint16_t *intra_matrix = NULL;
 -static uint16_t *inter_matrix = NULL;
 -static const char *video_rc_override_string=NULL;
 -static int video_disable = 0;
 +#define MAX_STREAMS 1024    /* arbitrary sanity check value */
 +
- /* indexed by output file stream index */
- static int *streamid_map = NULL;
- static int nb_streamid_map = 0;
- static int frame_width  = 0;
- static int frame_height = 0;
- static float frame_aspect_ratio = 0;
- static enum PixelFormat frame_pix_fmt = PIX_FMT_NONE;
 +static int frame_bits_per_raw_sample = 0;
- static enum AVSampleFormat audio_sample_fmt = AV_SAMPLE_FMT_NONE;
- static AVRational frame_rate;
- static float video_qscale = 0;
- static uint16_t *intra_matrix = NULL;
- static uint16_t *inter_matrix = NULL;
- static const char *video_rc_override_string=NULL;
  static int video_discard = 0;
  static char *video_codec_name = NULL;
 -static unsigned int video_codec_tag = 0;
 -static char *video_language = NULL;
 -static int same_quality = 0;
 +static int same_quant = 0;
  static int do_deinterlace = 0;
--static int top_field_first = -1;
--static int me_threshold = 0;
  static int intra_dc_precision = 8;
  static int loop_input = 0;
  static int loop_output = AVFMT_NOOUTPUTLOOP;
  static int qp_hist = 0;
--#if CONFIG_AVFILTER
--static char *vfilters = NULL;
--#endif
--
  static int intra_only = 0;
--static int audio_sample_rate = 0;
--#define QSCALE_NONE -99999
--static float audio_qscale = QSCALE_NONE;
 -static int audio_disable = 0;
 -static int audio_channels = 0;
  static char  *audio_codec_name = NULL;
 -static unsigned int audio_codec_tag = 0;
 -static char *audio_language = NULL;
 -
 -static int subtitle_disable = 0;
  static char *subtitle_codec_name = NULL;
 -static char *subtitle_language = NULL;
 -static unsigned int subtitle_codec_tag = 0;
  
 -static int data_disable = 0;
  static char *data_codec_name = NULL;
 -static unsigned int data_codec_tag = 0;
 -
 -static float mux_preload= 0.5;
 -static float mux_max_delay= 0.7;
  
 -static int64_t recording_time = INT64_MAX;
 -static int64_t start_time = 0;
 -static int64_t input_ts_offset = 0;
  static int file_overwrite = 0;
 -static AVDictionary *metadata;
  static int do_benchmark = 0;
  static int do_hex_dump = 0;
  static int do_pkt_dump = 0;
--static int do_psnr = 0;
  static int do_pass = 0;
 -static char *pass_logfilename_prefix = NULL;
 -static int audio_stream_copy = 0;
 -static int video_stream_copy = 0;
 -static int subtitle_stream_copy = 0;
 -static int data_stream_copy = 0;
 +static const char *pass_logfilename_prefix;
  static int video_sync_method= -1;
  static int audio_sync_method= 0;
  static float audio_drift_threshold= 0.1;
@@@ -164,25 -201,26 +140,21 @@@ static int copy_tb= 0
  static int opt_shortest = 0;
  static char *vstats_filename;
  static FILE *vstats_file;
--static int opt_programid = 0;
  static int copy_initial_nonkeyframes = 0;
  
 -static int rate_emu = 0;
 -
  static int audio_volume = 256;
  
  static int exit_on_error = 0;
  static int using_stdin = 0;
  static int verbose = 1;
 -static int thread_count= 1;
 +static int run_as_daemon  = 0;
- static int thread_count= 1;
 +static int q_pressed = 0;
  static int64_t video_size = 0;
  static int64_t audio_size = 0;
  static int64_t extra_size = 0;
  static int nb_frames_dup = 0;
  static int nb_frames_drop = 0;
  static int input_sync;
 -static uint64_t limit_filesize = 0;
--static int force_fps = 0;
--static char *forced_key_frames = NULL;
  
  static float dts_delta_threshold = 10;
  
@@@ -247,6 -263,6 +219,8 @@@ typedef struct OutputStream 
      int resample_width;
      int resample_pix_fmt;
      AVRational frame_rate;
++    int force_fps;
++    int top_field_first;
  
      float frame_aspect_ratio;
  
@@@ -300,112 -329,6 +274,147 @@@ static int         nb_input_streams = 0
  static InputFile   *input_files   = NULL;
  static int         nb_input_files   = 0;
  
 +static OutputStream *output_streams = NULL;
 +static int        nb_output_streams = 0;
 +static OutputFile   *output_files   = NULL;
 +static int        nb_output_files   = 0;
 +
 +typedef struct OptionsContext {
 +    /* input/output options */
 +    int64_t start_time;
 +    const char *format;
 +
 +    SpecifierOpt *codec_names;
 +    int        nb_codec_names;
 +    SpecifierOpt *audio_channels;
 +    int        nb_audio_channels;
++    SpecifierOpt *audio_sample_rate;
++    int        nb_audio_sample_rate;
++    SpecifierOpt *frame_rates;
++    int        nb_frame_rates;
++    SpecifierOpt *frame_sizes;
++    int        nb_frame_sizes;
++    SpecifierOpt *frame_pix_fmts;
++    int        nb_frame_pix_fmts;
 +
 +    /* input options */
 +    int64_t input_ts_offset;
 +    int rate_emu;
 +
 +    SpecifierOpt *ts_scale;
 +    int        nb_ts_scale;
 +
 +    /* output options */
 +    StreamMap *stream_maps;
 +    int     nb_stream_maps;
 +    /* first item specifies output metadata, second is input */
 +    MetadataMap (*meta_data_maps)[2];
 +    int nb_meta_data_maps;
 +    int metadata_global_manual;
 +    int metadata_streams_manual;
 +    int metadata_chapters_manual;
 +
 +    int chapters_input_file;
 +
 +    int64_t recording_time;
 +    uint64_t limit_filesize;
 +    float mux_preload;
 +    float mux_max_delay;
 +
 +    int video_disable;
 +    int audio_disable;
 +    int subtitle_disable;
 +    int data_disable;
 +
++    /* indexed by output file stream index */
++    int   *streamid_map;
++    int nb_streamid_map;
++
 +    SpecifierOpt *metadata;
 +    int        nb_metadata;
 +    SpecifierOpt *max_frames;
 +    int        nb_max_frames;
 +    SpecifierOpt *bitstream_filters;
 +    int        nb_bitstream_filters;
 +    SpecifierOpt *codec_tags;
 +    int        nb_codec_tags;
++    SpecifierOpt *sample_fmts;
++    int        nb_sample_fmts;
++    SpecifierOpt *qscale;
++    int        nb_qscale;
++    SpecifierOpt *forced_key_frames;
++    int        nb_forced_key_frames;
++    SpecifierOpt *force_fps;
++    int        nb_force_fps;
++    SpecifierOpt *frame_aspect_ratios;
++    int        nb_frame_aspect_ratios;
++    SpecifierOpt *rc_overrides;
++    int        nb_rc_overrides;
++    SpecifierOpt *intra_matrices;
++    int        nb_intra_matrices;
++    SpecifierOpt *inter_matrices;
++    int        nb_inter_matrices;
++    SpecifierOpt *top_field_first;
++    int        nb_top_field_first;
++#if CONFIG_AVFILTER
++    SpecifierOpt *filters;
++    int        nb_filters;
++#endif
 +} OptionsContext;
 +
 +#define MATCH_PER_STREAM_OPT(name, type, outvar, fmtctx, st)\
 +{\
 +    int i, ret;\
 +    for (i = 0; i < o->nb_ ## name; i++) {\
 +        char *spec = o->name[i].specifier;\
 +        if ((ret = check_stream_specifier(fmtctx, st, spec)) > 0)\
 +            outvar = o->name[i].u.type;\
 +        else if (ret < 0)\
 +            exit_program(1);\
 +    }\
 +}
 +
 +static void reset_options(OptionsContext *o, int is_input)
 +{
 +    const OptionDef *po = options;
 +    OptionsContext bak= *o;
 +
 +    /* all OPT_SPEC and OPT_STRING can be freed in generic way */
 +    while (po->name) {
 +        void *dst = (uint8_t*)o + po->u.off;
 +
 +        if (po->flags & OPT_SPEC) {
 +            SpecifierOpt **so = dst;
 +            int i, *count = (int*)(so + 1);
 +            for (i = 0; i < *count; i++) {
 +                av_freep(&(*so)[i].specifier);
 +                if (po->flags & OPT_STRING)
 +                    av_freep(&(*so)[i].u.str);
 +            }
 +            av_freep(so);
 +            *count = 0;
 +        } else if (po->flags & OPT_OFFSET && po->flags & OPT_STRING)
 +            av_freep(dst);
 +        po++;
 +    }
 +
 +    av_freep(&o->stream_maps);
 +    av_freep(&o->meta_data_maps);
++    av_freep(&o->streamid_map);
 +
 +    memset(o, 0, sizeof(*o));
 +
 +    if(is_input) o->recording_time = bak.recording_time;
 +    else         o->recording_time = INT64_MAX;
 +    o->mux_preload    = 0.5;
 +    o->mux_max_delay  = 0.7;
 +    o->limit_filesize = UINT64_MAX;
 +    o->chapters_input_file = INT_MAX;
 +
 +    uninit_opts();
 +    init_opts();
 +}
 +
  #if CONFIG_AVFILTER
  
  static int configure_video_filters(InputStream *ist, OutputStream *ost)
@@@ -631,9 -464,9 +640,6 @@@ void exit_program(int ret
      for (i = 0; i < nb_input_streams; i++)
          av_dict_free(&input_streams[i].opts);
  
--    av_free(intra_matrix);
--    av_free(inter_matrix);
--
      if (vstats_file)
          fclose(vstats_file);
      av_free(vstats_filename);
@@@ -1288,16 -1221,16 +1294,16 @@@ static void do_video_out(AVFormatContex
                 settings */
              big_picture.interlaced_frame = in_picture->interlaced_frame;
              if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
--                if(top_field_first == -1)
++                if (ost->top_field_first == -1)
                      big_picture.top_field_first = in_picture->top_field_first;
                  else
--                    big_picture.top_field_first = top_field_first;
++                    big_picture.top_field_first = !!ost->top_field_first;
              }
  
 -            /* handles sameq here. This is not correct because it may
 +            /* handles same_quant here. This is not correct because it may
                 not be a global option */
              big_picture.quality = quality;
--            if(!me_threshold)
++            if (!enc->me_threshold)
                  big_picture.pict_type = 0;
  //            big_picture.pts = AV_NOPTS_VALUE;
              big_picture.pts= ost->sync_opts;
@@@ -1956,45 -1856,84 +1962,45 @@@ static void print_sdp(OutputFile *outpu
      av_sdp_create(avc, n, sdp, sizeof(sdp));
      printf("SDP:\n%s\n", sdp);
      fflush(stdout);
 +    av_freep(&avc);
  }
  
 -static int copy_chapters(int infile, int outfile)
 +static int init_input_stream(int ist_index, OutputStream *output_streams, int nb_output_streams,
 +                             char *error, int error_len)
  {
 -    AVFormatContext *is = input_files[infile].ctx;
 -    AVFormatContext *os = output_files[outfile];
 -    int i;
 -
 -    for (i = 0; i < is->nb_chapters; i++) {
 -        AVChapter *in_ch = is->chapters[i], *out_ch;
 -        int64_t ts_off   = av_rescale_q(start_time - input_files[infile].ts_offset,
 -                                      AV_TIME_BASE_Q, in_ch->time_base);
 -        int64_t rt       = (recording_time == INT64_MAX) ? INT64_MAX :
 -                           av_rescale_q(recording_time, AV_TIME_BASE_Q, in_ch->time_base);
 -
 -
 -        if (in_ch->end < ts_off)
 -            continue;
 -        if (rt != INT64_MAX && in_ch->start > rt + ts_off)
 -            break;
 -
 -        out_ch = av_mallocz(sizeof(AVChapter));
 -        if (!out_ch)
 -            return AVERROR(ENOMEM);
 -
 -        out_ch->id        = in_ch->id;
 -        out_ch->time_base = in_ch->time_base;
 -        out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
 -        out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
 -
 -        if (metadata_chapters_autocopy)
 -            av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
 -
 -        os->nb_chapters++;
 -        os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
 -        if (!os->chapters)
 -            return AVERROR(ENOMEM);
 -        os->chapters[os->nb_chapters - 1] = out_ch;
 +    InputStream *ist = &input_streams[ist_index];
 +    if (ist->decoding_needed) {
 +        AVCodec *codec = ist->dec;
 +        if (!codec) {
 +            snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d.%d",
 +                    avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
 +            return AVERROR(EINVAL);
 +        }
 +        if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
 +            snprintf(error, error_len, "Error while opening decoder for input stream #%d.%d",
 +                    ist->file_index, ist->st->index);
 +            return AVERROR(EINVAL);
 +        }
 +        assert_codec_experimental(ist->st->codec, 0);
 +        assert_avoptions(ist->opts);
      }
 -    return 0;
 -}
  
 -static void parse_forced_key_frames(char *kf, OutputStream *ost,
 -                                    AVCodecContext *avctx)
 -{
 -    char *p;
 -    int n = 1, i;
 -    int64_t t;
 +    ist->pts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames*AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
 +    ist->next_pts = AV_NOPTS_VALUE;
 +    ist->is_start = 1;
  
 -    for (p = kf; *p; p++)
 -        if (*p == ',')
 -            n++;
 -    ost->forced_kf_count = n;
 -    ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
 -    if (!ost->forced_kf_pts) {
 -        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
 -        exit_program(1);
 -    }
 -    for (i = 0; i < n; i++) {
 -        p = i ? strchr(p, ',') + 1 : kf;
 -        t = parse_time_or_die("force_key_frames", p, 1);
 -        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
 -    }
 +    return 0;
  }
  
 -/*
 - * The following code is the main loop of the file converter
 - */
 -static int transcode(AVFormatContext **output_files,
 -                     int nb_output_files,
 -                     InputFile *input_files,
 -                     int nb_input_files,
 -                     StreamMap *stream_maps, int nb_stream_maps)
 +static int transcode_init(OutputFile *output_files,
 +                          int nb_output_files,
 +                          InputFile *input_files,
 +                          int nb_input_files)
  {
-     int ret = 0, i, j;
 -    int ret = 0, i, j, k, n, nb_ostreams = 0;
 -    AVFormatContext *is, *os;
++    int ret = 0, i, j, k;
 +    AVFormatContext *os;
      AVCodecContext *codec, *icodec;
 -    OutputStream *ost, **ost_table = NULL;
 +    OutputStream *ost;
      InputStream *ist;
      char error[1024];
      int want_sdp = 1;
  
                  if (!ost->frame_rate.num)
                      ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25,1};
--                if (ost->enc && ost->enc->supported_framerates && !force_fps) {
++                if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
                      int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
                      ost->frame_rate = ost->enc->supported_framerates[idx];
                  }
                  av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
                                               "It takes bits/s as argument, not kbits/s\n");
              extra_size += ost->st->codec->extradata_size;
++
++            if (ost->st->codec->me_threshold)
++                input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
          }
      }
  
 -    /* open each decoder */
 -    for (i = 0; i < nb_input_streams; i++) {
 -        ist = &input_streams[i];
 -        if (ist->decoding_needed) {
 -            AVCodec *codec = ist->dec;
 -            if (!codec)
 -                codec = avcodec_find_decoder(ist->st->codec->codec_id);
 -            if (!codec) {
 -                snprintf(error, sizeof(error), "Decoder (codec id %d) not found for input stream #%d.%d",
 -                        ist->st->codec->codec_id, ist->file_index, ist->st->index);
 -                ret = AVERROR(EINVAL);
 -                goto dump_format;
 -            }
 +    /* init input streams */
 +    for (i = 0; i < nb_input_streams; i++)
 +        if ((ret = init_input_stream(i, output_streams, nb_output_streams, error, sizeof(error))) < 0)
 +            goto dump_format;
  
 -            /* update requested sample format for the decoder based on the
 -               corresponding encoder sample format */
 -            for (j = 0; j < nb_ostreams; j++) {
 -                ost = ost_table[j];
 -                if (ost->source_index == i) {
 -                    update_sample_fmt(ist->st->codec, codec, ost->st->codec);
++    /* discard unused programs */
++    for (i = 0; i < nb_input_files; i++) {
++        InputFile *ifile = &input_files[i];
++        for (j = 0; j < ifile->ctx->nb_programs; j++) {
++            AVProgram *p = ifile->ctx->programs[j];
++            int discard  = AVDISCARD_ALL;
++
++            for (k = 0; k < p->nb_stream_indexes; k++)
++                if (!input_streams[ifile->ist_index + p->stream_index[k]].discard) {
++                    discard = AVDISCARD_DEFAULT;
+                     break;
+                 }
 -            }
 -
 -            if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
 -                snprintf(error, sizeof(error), "Error while opening decoder for input stream #%d.%d",
 -                        ist->file_index, ist->st->index);
 -                ret = AVERROR(EINVAL);
 -                goto dump_format;
 -            }
 -            assert_codec_experimental(ist->st->codec, 0);
 -            assert_avoptions(ost->opts);
++            p->discard = discard;
+         }
+     }
 -    /* init pts */
 -    for (i = 0; i < nb_input_streams; i++) {
 -        AVStream *st;
 -        ist = &input_streams[i];
 -        st= ist->st;
 -        ist->pts = st->avg_frame_rate.num ? - st->codec->has_b_frames*AV_TIME_BASE / av_q2d(st->avg_frame_rate) : 0;
 -        ist->next_pts = AV_NOPTS_VALUE;
 -        init_pts_correction(&ist->pts_ctx);
 -        ist->is_start = 1;
 +    /* open files and write file headers */
 +    for (i = 0; i < nb_output_files; i++) {
 +        os = output_files[i].ctx;
 +        if (avformat_write_header(os, &output_files[i].opts) < 0) {
 +            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
 +            ret = AVERROR(EINVAL);
 +            goto dump_format;
 +        }
 +//        assert_avoptions(output_files[i].opts);
 +        if (strcmp(os->oformat->name, "rtp")) {
 +            want_sdp = 0;
 +        }
      }
  
 -    /* set meta data information from input file if required */
 -    for (i=0;i<nb_meta_data_maps;i++) {
 -        AVFormatContext *files[2];
 -        AVDictionary    **meta[2];
 -        int j;
 + dump_format:
 +    /* dump the file output parameters - cannot be done before in case
 +       of stream copy */
 +    for(i=0;i<nb_output_files;i++) {
 +        av_dump_format(output_files[i].ctx, i, output_files[i].ctx->filename, 1);
 +    }
  
 -#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
 -        if ((index) < 0 || (index) >= (nb_elems)) {\
 -            snprintf(error, sizeof(error), "Invalid %s index %d while processing metadata maps\n",\
 -                     (desc), (index));\
 -            ret = AVERROR(EINVAL);\
 -            goto dump_format;\
 +    /* dump the stream mapping */
 +    if (verbose >= 0) {
 +        fprintf(stderr, "Stream mapping:\n");
 +        for (i = 0; i < nb_output_streams;i ++) {
 +            ost = &output_streams[i];
 +            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
 +                    input_streams[ost->source_index].file_index,
 +                    input_streams[ost->source_index].st->index,
 +                    ost->file_index,
 +                    ost->index);
 +            if (ost->sync_ist != &input_streams[ost->source_index])
 +                fprintf(stderr, " [sync #%d.%d]",
 +                        ost->sync_ist->file_index,
 +                        ost->sync_ist->st->index);
 +            if (ost->st->stream_copy)
 +                fprintf(stderr, " (copy)");
 +            else
 +                fprintf(stderr, " (%s -> %s)", input_streams[ost->source_index].dec ?
 +                        input_streams[ost->source_index].dec->name : "?",
 +                        ost->enc ? ost->enc->name : "?");
 +            fprintf(stderr, "\n");
          }
 +    }
  
 -        int out_file_index = meta_data_maps[i][0].file;
 -        int in_file_index = meta_data_maps[i][1].file;
 -        if (in_file_index < 0 || out_file_index < 0)
 -            continue;
 -        METADATA_CHECK_INDEX(out_file_index, nb_output_files, "output file")
 -        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
 +    if (ret) {
 +        fprintf(stderr, "%s\n", error);
 +        return ret;
 +    }
  
 -        files[0] = output_files[out_file_index];
 -        files[1] = input_files[in_file_index].ctx;
 +    if (want_sdp) {
 +        print_sdp(output_files, nb_output_files);
 +    }
  
 -        for (j = 0; j < 2; j++) {
 -            MetadataMap *map = &meta_data_maps[i][j];
 +    return 0;
 +}
  
 -            switch (map->type) {
 -            case 'g':
 -                meta[j] = &files[j]->metadata;
 -                break;
 -            case 's':
 -                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
 -                meta[j] = &files[j]->streams[map->index]->metadata;
 -                break;
 -            case 'c':
 -                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
 -                meta[j] = &files[j]->chapters[map->index]->metadata;
 -                break;
 -            case 'p':
 -                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
 -                meta[j] = &files[j]->programs[map->index]->metadata;
 -                break;
 -            }
 -        }
 -
 -        av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
 -    }
 -
 -    /* copy global metadata by default */
 -    if (metadata_global_autocopy) {
 -
 -        for (i = 0; i < nb_output_files; i++)
 -            av_dict_copy(&output_files[i]->metadata, input_files[0].ctx->metadata,
 -                         AV_DICT_DONT_OVERWRITE);
 -    }
 -
 -    /* copy chapters according to chapter maps */
 -    for (i = 0; i < nb_chapter_maps; i++) {
 -        int infile  = chapter_maps[i].in_file;
 -        int outfile = chapter_maps[i].out_file;
 -
 -        if (infile < 0 || outfile < 0)
 -            continue;
 -        if (infile >= nb_input_files) {
 -            snprintf(error, sizeof(error), "Invalid input file index %d in chapter mapping.\n", infile);
 -            ret = AVERROR(EINVAL);
 -            goto dump_format;
 -        }
 -        if (outfile >= nb_output_files) {
 -            snprintf(error, sizeof(error), "Invalid output file index %d in chapter mapping.\n",outfile);
 -            ret = AVERROR(EINVAL);
 -            goto dump_format;
 -        }
 -        copy_chapters(infile, outfile);
 -    }
 -
 -    /* copy chapters from the first input file that has them*/
 -    if (!nb_chapter_maps)
 -        for (i = 0; i < nb_input_files; i++) {
 -            if (!input_files[i].ctx->nb_chapters)
 -                continue;
 -
 -            for (j = 0; j < nb_output_files; j++)
 -                if ((ret = copy_chapters(i, j)) < 0)
 -                    goto dump_format;
 -            break;
 -        }
 -
 -    /* open files and write file headers */
 -    for(i=0;i<nb_output_files;i++) {
 -        os = output_files[i];
 -        if (avformat_write_header(os, &output_opts[i]) < 0) {
 -            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);
 -            ret = AVERROR(EINVAL);
 -            goto dump_format;
 -        }
 -        assert_avoptions(output_opts[i]);
 -        if (strcmp(output_files[i]->oformat->name, "rtp")) {
 -            want_sdp = 0;
 -        }
 -    }
 -
 - dump_format:
 -    /* dump the file output parameters - cannot be done before in case
 -       of stream copy */
 -    for(i=0;i<nb_output_files;i++) {
 -        av_dump_format(output_files[i], i, output_files[i]->filename, 1);
 -    }
 +/*
 + * The following code is the main loop of the file converter
 + */
 +static int transcode(OutputFile *output_files,
 +                     int nb_output_files,
 +                     InputFile *input_files,
 +                     int nb_input_files)
 +{
 +    int ret, i;
 +    AVFormatContext *is, *os;
 +    OutputStream *ost;
 +    InputStream *ist;
 +    uint8_t *no_packet;
 +    int no_packet_count=0;
 +    int64_t timer_start;
 +    int key;
  
 -    /* dump the stream mapping */
 -    if (verbose >= 0) {
 -        fprintf(stderr, "Stream mapping:\n");
 -        for(i=0;i<nb_ostreams;i++) {
 -            ost = ost_table[i];
 -            fprintf(stderr, "  Stream #%d.%d -> #%d.%d",
 -                    input_streams[ost->source_index].file_index,
 -                    input_streams[ost->source_index].st->index,
 -                    ost->file_index,
 -                    ost->index);
 -            if (ost->sync_ist != &input_streams[ost->source_index])
 -                fprintf(stderr, " [sync #%d.%d]",
 -                        ost->sync_ist->file_index,
 -                        ost->sync_ist->st->index);
 -            fprintf(stderr, "\n");
 -        }
 -    }
 +    if (!(no_packet = av_mallocz(nb_input_files)))
 +        exit_program(1);
  
 -    if (ret) {
 -        fprintf(stderr, "%s\n", error);
 +    ret = transcode_init(output_files, nb_output_files, input_files, nb_input_files);
 +    if (ret < 0)
          goto fail;
 -    }
  
 -    if (want_sdp) {
 -        print_sdp(output_files, nb_output_files);
 +    if (!using_stdin) {
 +        if(verbose >= 0)
 +            fprintf(stderr, "Press [q] to stop, [?] for help\n");
 +        avio_set_interrupt_cb(decode_interrupt_cb);
      }
 -
 -    if (verbose >= 0)
 -        fprintf(stderr, "Press ctrl-c to stop encoding\n");
      term_init();
  
      timer_start = av_gettime();
      return ret;
  }
  
 -static int opt_format(const char *opt, const char *arg)
 -{
 -    last_asked_format = arg;
 -    return 0;
 -}
 -
--static int opt_video_rc_override_string(const char *opt, const char *arg)
--{
--    video_rc_override_string = arg;
--    return 0;
--}
--
--static int opt_me_threshold(const char *opt, const char *arg)
--{
--    me_threshold = parse_number_or_die(opt, arg, OPT_INT64, INT_MIN, INT_MAX);
--    return 0;
--}
--
  static int opt_verbose(const char *opt, const char *arg)
  {
      verbose = parse_number_or_die(opt, arg, OPT_INT64, -10, 10);
      return 0;
  }
  
--static int opt_frame_rate(const char *opt, const char *arg)
--{
--    if (av_parse_video_rate(&frame_rate, arg) < 0) {
--        fprintf(stderr, "Incorrect value for %s: %s\n", opt, arg);
--        exit_program(1);
--    }
--    return 0;
--}
--
  static int opt_frame_crop(const char *opt, const char *arg)
  {
      fprintf(stderr, "Option '%s' has been removed, use the crop filter instead\n", opt);
      return AVERROR(EINVAL);
  }
  
--static int opt_frame_size(const char *opt, const char *arg)
--{
--    if (av_parse_video_size(&frame_width, &frame_height, arg) < 0) {
--        fprintf(stderr, "Incorrect frame size\n");
--        return AVERROR(EINVAL);
--    }
--    return 0;
--}
--
  static int opt_pad(const char *opt, const char *arg) {
      fprintf(stderr, "Option '%s' has been removed, use the pad filter instead\n", opt);
      return -1;
  }
  
--static int opt_frame_pix_fmt(const char *opt, const char *arg)
--{
--    if (strcmp(arg, "list")) {
--        frame_pix_fmt = av_get_pix_fmt(arg);
--        if (frame_pix_fmt == PIX_FMT_NONE) {
--            fprintf(stderr, "Unknown pixel format requested: %s\n", arg);
--            return AVERROR(EINVAL);
--        }
--    } else {
-         opt_pix_fmts(NULL, NULL);
 -        show_pix_fmts();
--        exit_program(0);
--    }
--    return 0;
--}
--
--static int opt_frame_aspect_ratio(const char *opt, const char *arg)
++static double parse_frame_aspect_ratio(const char *arg)
  {
      int x = 0, y = 0;
      double ar = 0;
  
      if (!ar) {
          fprintf(stderr, "Incorrect aspect ratio specification.\n");
--        return AVERROR(EINVAL);
--    }
--    frame_aspect_ratio = ar;
-     return 0;
- }
- static int opt_qscale(const char *opt, const char *arg)
- {
-     video_qscale = parse_number_or_die(opt, arg, OPT_FLOAT, 0, 255);
-     if (video_qscale <= 0 || video_qscale > 255) {
-         fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
-         return AVERROR(EINVAL);
-     }
--    return 0;
- }
- static int opt_top_field_first(const char *opt, const char *arg)
- {
-     top_field_first = parse_number_or_die(opt, arg, OPT_INT, 0, 1);
-     return opt_default(opt, arg);
--}
--
- static int opt_thread_count(const char *opt, const char *arg)
 -static int opt_metadata(const char *opt, const char *arg)
--{
-     thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
- #if !HAVE_THREADS
-     if (verbose >= 0)
-         fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
- #endif
-     return 0;
- }
 -    char *mid= strchr(arg, '=');
--
- static int opt_audio_sample_fmt(const char *opt, const char *arg)
- {
-     if (strcmp(arg, "list")) {
-         audio_sample_fmt = av_get_sample_fmt(arg);
-         if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
-             av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
-             return AVERROR(EINVAL);
-         }
-     } else {
-         int i;
-         char fmt_str[128];
-         for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
-             printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
-         exit_program(0);
 -    if(!mid){
 -        fprintf(stderr, "Missing =\n");
+         exit_program(1);
      }
 -    *mid++= 0;
 -
 -    av_dict_set(&metadata, arg, mid, 0);
 -
 -    return 0;
 -}
 -
 -static int opt_qscale(const char *opt, const char *arg)
 -{
 -    video_qscale = parse_number_or_die(opt, arg, OPT_FLOAT, 0, 255);
 -    if (video_qscale == 0) {
 -        fprintf(stderr, "qscale must be > 0.0 and <= 255\n");
 -        return AVERROR(EINVAL);
 -    }
 -    return 0;
 -}
 -
 -static int opt_top_field_first(const char *opt, const char *arg)
 -{
 -    top_field_first = parse_number_or_die(opt, arg, OPT_INT, 0, 1);
 -    return 0;
 -}
 -
 -static int opt_thread_count(const char *opt, const char *arg)
 -{
 -    thread_count= parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
 -#if !HAVE_THREADS
 -    if (verbose >= 0)
 -        fprintf(stderr, "Warning: not compiled with thread support, using thread emulation\n");
 -#endif
 -    return 0;
 -}
 -
 -static int opt_audio_sample_fmt(const char *opt, const char *arg)
 -{
 -    if (strcmp(arg, "list")) {
 -        audio_sample_fmt = av_get_sample_fmt(arg);
 -        if (audio_sample_fmt == AV_SAMPLE_FMT_NONE) {
 -            av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", arg);
 -            return AVERROR(EINVAL);
 -        }
 -    } else {
 -        int i;
 -        char fmt_str[128];
 -        for (i = -1; i < AV_SAMPLE_FMT_NB; i++)
 -            printf("%s\n", av_get_sample_fmt_string(fmt_str, sizeof(fmt_str), i));
 -        exit_program(0);
 -    }
--    return 0;
--}
--
--static int opt_audio_rate(const char *opt, const char *arg)
--{
--    audio_sample_rate = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
 -    return 0;
 -}
 -
 -static int opt_audio_channels(const char *opt, const char *arg)
 -{
 -    audio_channels = parse_number_or_die(opt, arg, OPT_INT64, 0, INT_MAX);
--    return 0;
++    return ar;
  }
  
  static int opt_video_channel(const char *opt, const char *arg)
@@@ -3006,108 -3130,7 +2935,104 @@@ static enum CodecID find_codec_or_die(c
      return codec->id;
  }
  
 -static int opt_input_file(const char *opt, const char *filename)
 +static AVCodec *choose_codec(OptionsContext *o, AVFormatContext *s, AVStream *st, enum AVMediaType type)
 +{
 +    char *codec_name = NULL;
 +
 +    MATCH_PER_STREAM_OPT(codec_names, str, codec_name, s, st);
 +
 +    if (!codec_name) {
 +        if (s->oformat) {
 +            st->codec->codec_id = av_guess_codec(s->oformat, NULL, s->filename, NULL, type);
 +            return avcodec_find_encoder(st->codec->codec_id);
 +        }
 +    } else if (!strcmp(codec_name, "copy"))
 +        st->stream_copy = 1;
 +    else {
 +        st->codec->codec_id = find_codec_or_die(codec_name, type, s->iformat == NULL);
 +        return s->oformat ? avcodec_find_encoder_by_name(codec_name) :
 +                            avcodec_find_decoder_by_name(codec_name);
 +    }
 +
 +    return NULL;
 +}
 +
 +/**
 + * Add all the streams from the given input file to the global
 + * list of input streams.
 + */
 +static void add_input_streams(OptionsContext *o, AVFormatContext *ic)
 +{
 +    int i, rfps, rfps_base;
 +
 +    for (i = 0; i < ic->nb_streams; i++) {
 +        AVStream *st = ic->streams[i];
 +        AVCodecContext *dec = st->codec;
 +        InputStream *ist;
 +        double scale = 1.0;
 +
-         dec->thread_count = thread_count;
 +        input_streams = grow_array(input_streams, sizeof(*input_streams), &nb_input_streams, nb_input_streams + 1);
 +        ist = &input_streams[nb_input_streams - 1];
 +        ist->st = st;
 +        ist->file_index = nb_input_files;
 +        ist->discard = 1;
 +        ist->opts = filter_codec_opts(codec_opts, ist->st->codec->codec_id, ic, st);
 +
 +        MATCH_PER_STREAM_OPT(ts_scale, dbl, scale, ic, st);
 +        ist->ts_scale = scale;
 +
 +        ist->dec = choose_codec(o, ic, st, dec->codec_type);
 +        if (!ist->dec)
 +            ist->dec = avcodec_find_decoder(dec->codec_id);
 +
 +        switch (dec->codec_type) {
 +        case AVMEDIA_TYPE_AUDIO:
 +            if(!ist->dec)
 +                ist->dec = avcodec_find_decoder(dec->codec_id);
 +            if(o->audio_disable)
 +                st->discard= AVDISCARD_ALL;
 +            break;
 +        case AVMEDIA_TYPE_VIDEO:
 +            if(!ist->dec)
 +                ist->dec = avcodec_find_decoder(dec->codec_id);
 +            rfps      = ic->streams[i]->r_frame_rate.num;
 +            rfps_base = ic->streams[i]->r_frame_rate.den;
 +            if (dec->lowres) {
 +                dec->flags |= CODEC_FLAG_EMU_EDGE;
 +            }
-             if(me_threshold)
-                 dec->debug |= FF_DEBUG_MV;
 +
 +            if (dec->time_base.den != rfps*dec->ticks_per_frame || dec->time_base.num != rfps_base) {
 +
 +                if (verbose >= 0)
 +                    fprintf(stderr,"\nSeems stream %d codec frame rate differs from container frame rate: %2.2f (%d/%d) -> %2.2f (%d/%d)\n",
 +                            i, (float)dec->time_base.den / dec->time_base.num, dec->time_base.den, dec->time_base.num,
 +
 +                    (float)rfps / rfps_base, rfps, rfps_base);
 +            }
 +
 +            if (o->video_disable)
 +                st->discard= AVDISCARD_ALL;
 +            else if(video_discard)
 +                st->discard= video_discard;
 +            break;
 +        case AVMEDIA_TYPE_DATA:
 +            break;
 +        case AVMEDIA_TYPE_SUBTITLE:
 +            if(!ist->dec)
 +                ist->dec = avcodec_find_decoder(dec->codec_id);
 +            if(o->subtitle_disable)
 +                st->discard = AVDISCARD_ALL;
 +            break;
 +        case AVMEDIA_TYPE_ATTACHMENT:
 +        case AVMEDIA_TYPE_UNKNOWN:
 +            break;
 +        default:
 +            abort();
 +        }
 +    }
 +}
 +
 +static int opt_input_file(OptionsContext *o, const char *opt, const char *filename)
  {
      AVFormatContext *ic;
      AVInputFormat *file_iformat = NULL;
          print_error(filename, AVERROR(ENOMEM));
          exit_program(1);
      }
--    if (audio_sample_rate) {
--        snprintf(buf, sizeof(buf), "%d", audio_sample_rate);
++    if (o->nb_audio_sample_rate) {
++        snprintf(buf, sizeof(buf), "%d", o->audio_sample_rate[o->nb_audio_sample_rate - 1].u.i);
          av_dict_set(&format_opts, "sample_rate", buf, 0);
      }
 -    if (audio_channels) {
 -        snprintf(buf, sizeof(buf), "%d", audio_channels);
 +    if (o->nb_audio_channels) {
 +        snprintf(buf, sizeof(buf), "%d", o->audio_channels[o->nb_audio_channels - 1].u.i);
          av_dict_set(&format_opts, "channels", buf, 0);
      }
--    if (frame_rate.num) {
--        snprintf(buf, sizeof(buf), "%d/%d", frame_rate.num, frame_rate.den);
--        av_dict_set(&format_opts, "framerate", buf, 0);
++    if (o->nb_frame_rates) {
++        av_dict_set(&format_opts, "framerate", o->frame_rates[o->nb_frame_rates - 1].u.str, 0);
      }
--    if (frame_width && frame_height) {
--        snprintf(buf, sizeof(buf), "%dx%d", frame_width, frame_height);
--        av_dict_set(&format_opts, "video_size", buf, 0);
++    if (o->nb_frame_sizes) {
++        av_dict_set(&format_opts, "video_size", o->frame_sizes[o->nb_frame_sizes - 1].u.str, 0);
      }
--    if (frame_pix_fmt != PIX_FMT_NONE)
--        av_dict_set(&format_opts, "pixel_format", av_get_pix_fmt_name(frame_pix_fmt), 0);
 -
 -    ic->video_codec_id   =
 -        find_codec_or_die(video_codec_name   , AVMEDIA_TYPE_VIDEO   , 0);
 -    ic->audio_codec_id   =
 -        find_codec_or_die(audio_codec_name   , AVMEDIA_TYPE_AUDIO   , 0);
 -    ic->subtitle_codec_id=
 -        find_codec_or_die(subtitle_codec_name, AVMEDIA_TYPE_SUBTITLE, 0);
++    if (o->nb_frame_pix_fmts)
++        av_dict_set(&format_opts, "pixel_format", o->frame_pix_fmts[o->nb_frame_pix_fmts - 1].u.str, 0);
 +
      ic->flags |= AVFMT_FLAG_NONBLOCK;
  
 +    if (loop_input) {
 +        av_log(NULL, AV_LOG_WARNING, "-loop_input is deprecated, use -loop 1\n");
 +        ic->loop_input = loop_input;
 +    }
 +
      /* open the input file with generic libav function */
      err = avformat_open_input(&ic, filename, file_iformat, &format_opts);
      if (err < 0) {
      }
      assert_avoptions(format_opts);
  
--    if(opt_programid) {
--        int i, j;
--        int found=0;
--        for(i=0; i<ic->nb_streams; i++){
--            ic->streams[i]->discard= AVDISCARD_ALL;
--        }
--        for(i=0; i<ic->nb_programs; i++){
--            AVProgram *p= ic->programs[i];
--            if(p->id != opt_programid){
--                p->discard = AVDISCARD_ALL;
--            }else{
--                found=1;
--                for(j=0; j<p->nb_stream_indexes; j++){
--                    ic->streams[p->stream_index[j]]->discard= AVDISCARD_DEFAULT;
--                }
--            }
--        }
--        if(!found){
--            fprintf(stderr, "Specified program id not found\n");
--            exit_program(1);
--        }
--        opt_programid=0;
--    }
--
 -    if (loop_input) {
 -        av_log(NULL, AV_LOG_WARNING, "-loop_input is deprecated, use -loop 1\n");
 -        ic->loop_input = loop_input;
 -    }
 +    /* apply forced codec ids */
 +    for (i = 0; i < ic->nb_streams; i++)
 +        choose_codec(o, ic, ic->streams[i], ic->streams[i]->codec->codec_type);
  
      /* Set AVCodecContext options for avformat_find_stream_info */
      opts = setup_find_stream_info_opts(ic, codec_opts);
      input_files = grow_array(input_files, sizeof(*input_files), &nb_input_files, nb_input_files + 1);
      input_files[nb_input_files - 1].ctx        = ic;
      input_files[nb_input_files - 1].ist_index  = nb_input_streams - ic->nb_streams;
 -    input_files[nb_input_files - 1].ts_offset  = input_ts_offset - (copy_ts ? 0 : timestamp);
 -
 -    frame_rate    = (AVRational){0, 0};
 -    frame_pix_fmt = PIX_FMT_NONE;
 -    frame_height = 0;
 -    frame_width  = 0;
 -    audio_sample_rate = 0;
 -    audio_channels    = 0;
 -    audio_sample_fmt  = AV_SAMPLE_FMT_NONE;
 -    av_freep(&ts_scale);
 -    nb_ts_scale = 0;
 +    input_files[nb_input_files - 1].ts_offset  = o->input_ts_offset - (copy_ts ? 0 : timestamp);
 +    input_files[nb_input_files - 1].nb_streams = ic->nb_streams;
 +    input_files[nb_input_files - 1].rate_emu   = o->rate_emu;
  
-     top_field_first = -1;
-     frame_rate    = (AVRational){0, 0};
-     frame_pix_fmt = PIX_FMT_NONE;
-     frame_height = 0;
-     frame_width  = 0;
-     audio_sample_rate = 0;
-     audio_sample_fmt  = AV_SAMPLE_FMT_NONE;
      for (i = 0; i < orig_nb_streams; i++)
          av_dict_free(&opts[i]);
      av_freep(&opts);
      return 0;
  }
  
 -static void check_inputs(int *has_video_ptr,
 -                         int *has_audio_ptr,
 -                         int *has_subtitle_ptr,
 -                         int *has_data_ptr)
 +static void parse_forced_key_frames(char *kf, OutputStream *ost,
 +                                    AVCodecContext *avctx)
  {
 -    int has_video, has_audio, has_subtitle, has_data, i, j;
 -    AVFormatContext *ic;
 -
 -    has_video = 0;
 -    has_audio = 0;
 -    has_subtitle = 0;
 -    has_data = 0;
 +    char *p;
 +    int n = 1, i;
 +    int64_t t;
  
 -    for(j=0;j<nb_input_files;j++) {
 -        ic = input_files[j].ctx;
 -        for(i=0;i<ic->nb_streams;i++) {
 -            AVCodecContext *enc = ic->streams[i]->codec;
 -            switch(enc->codec_type) {
 -            case AVMEDIA_TYPE_AUDIO:
 -                has_audio = 1;
 -                break;
 -            case AVMEDIA_TYPE_VIDEO:
 -                has_video = 1;
 -                break;
 -            case AVMEDIA_TYPE_SUBTITLE:
 -                has_subtitle = 1;
 -                break;
 -            case AVMEDIA_TYPE_DATA:
 -            case AVMEDIA_TYPE_ATTACHMENT:
 -            case AVMEDIA_TYPE_UNKNOWN:
 -                has_data = 1;
 -                break;
 -            default:
 -                abort();
 -            }
 -        }
 +    for (p = kf; *p; p++)
 +        if (*p == ',')
 +            n++;
 +    ost->forced_kf_count = n;
 +    ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
 +    if (!ost->forced_kf_pts) {
 +        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
 +        exit_program(1);
 +    }
 +    for (i = 0; i < n; i++) {
 +        p = i ? strchr(p, ',') + 1 : kf;
 +        t = parse_time_or_die("force_key_frames", p, 1);
 +        ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
      }
 -    *has_video_ptr = has_video;
 -    *has_audio_ptr = has_audio;
 -    *has_subtitle_ptr = has_subtitle;
 -    *has_data_ptr = has_data;
  }
  
 -static void new_video_stream(AVFormatContext *oc, int file_idx)
 +static OutputStream *new_output_stream(OptionsContext *o, AVFormatContext *oc, enum AVMediaType type)
  {
 -    AVStream *st;
      OutputStream *ost;
-     AVStream *st = av_new_stream(oc, oc->nb_streams < nb_streamid_map ? streamid_map[oc->nb_streams] : 0);
 -    AVCodecContext *video_enc;
 -    enum CodecID codec_id = CODEC_ID_NONE;
 -    AVCodec *codec= NULL;
++    AVStream *st = av_new_stream(oc, oc->nb_streams < o->nb_streamid_map ? o->streamid_map[oc->nb_streams] : 0);
 +    int idx      = oc->nb_streams - 1;
 +    int64_t max_frames = INT64_MAX;
 +    char *bsf = NULL, *next, *codec_tag = NULL;
 +    AVBitStreamFilterContext *bsfc, *bsfc_prev = NULL;
++    double qscale = -1;
  
 -    if(!video_stream_copy){
 -        if (video_codec_name) {
 -            codec_id = find_codec_or_die(video_codec_name, AVMEDIA_TYPE_VIDEO, 1);
 -            codec = avcodec_find_encoder_by_name(video_codec_name);
 -        } else {
 -            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_VIDEO);
 -            codec = avcodec_find_encoder(codec_id);
 +    if (!st) {
 +        av_log(NULL, AV_LOG_ERROR, "Could not alloc stream.\n");
 +        exit_program(1);
 +    }
 +
 +    output_streams = grow_array(output_streams, sizeof(*output_streams), &nb_output_streams,
 +                                nb_output_streams + 1);
 +    ost = &output_streams[nb_output_streams - 1];
 +    ost->file_index = nb_output_files;
 +    ost->index = idx;
 +    ost->st    = st;
 +    st->codec->codec_type = type;
 +    ost->enc = choose_codec(o, oc, st, type);
 +    if (ost->enc) {
 +        ost->opts  = filter_codec_opts(codec_opts, ost->enc->id, oc, st);
 +    }
 +
 +    avcodec_get_context_defaults3(st->codec, ost->enc);
 +    st->codec->codec_type = type; // XXX hack, avcodec_get_context_defaults2() sets type to unknown for stream copy
 +
 +    MATCH_PER_STREAM_OPT(max_frames, i64, max_frames, oc, st);
 +    ost->max_frames = max_frames;
 +
 +    MATCH_PER_STREAM_OPT(bitstream_filters, str, bsf, oc, st);
 +    while (bsf) {
 +        if (next = strchr(bsf, ','))
 +            *next++ = 0;
 +        if (!(bsfc = av_bitstream_filter_init(bsf))) {
 +            av_log(NULL, AV_LOG_ERROR, "Unknown bitstream filter %s\n", bsf);
 +            exit_program(1);
          }
 +        if (bsfc_prev)
 +            bsfc_prev->next = bsfc;
 +        else
 +            ost->bitstream_filters = bsfc;
 +
 +        bsfc_prev = bsfc;
 +        bsf       = next;
      }
  
 -    ost = new_output_stream(oc, file_idx, codec);
 -    st  = ost->st;
 -    if (!video_stream_copy) {
 -        ost->frame_aspect_ratio = frame_aspect_ratio;
 -        frame_aspect_ratio = 0;
 -#if CONFIG_AVFILTER
 -        ost->avfilter= vfilters;
 -        vfilters = NULL;
 -#endif
 +    MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, oc, st);
 +    if (codec_tag) {
 +        uint32_t tag = strtol(codec_tag, &next, 0);
 +        if (*next)
 +            tag = AV_RL32(codec_tag);
 +        st->codec->codec_tag = tag;
      }
  
 -    ost->bitstream_filters = video_bitstream_filters;
 -    video_bitstream_filters= NULL;
++    MATCH_PER_STREAM_OPT(qscale, dbl, qscale, oc, st);
++    if (qscale >= 0 || same_quant) {
++        st->codec->flags |= CODEC_FLAG_QSCALE;
++        st->codec->global_quality = FF_QP2LAMBDA * qscale;
++    }
 -    st->codec->thread_count= thread_count;
 +    ost->sws_flags = av_get_int(sws_opts, "sws_flags", NULL);
 +    return ost;
 +}
  
 -    video_enc = st->codec;
++static void parse_matrix_coeffs(uint16_t *dest, const char *str)
++{
++    int i;
++    const char *p = str;
++    for(i = 0;; i++) {
++        dest[i] = atoi(p);
++        if(i == 63)
++            break;
++        p = strchr(p, ',');
++        if(!p) {
++            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
++            exit_program(1);
++        }
++        p++;
++    }
++}
 -    if(video_codec_tag)
 -        video_enc->codec_tag= video_codec_tag;
 +static OutputStream *new_video_stream(OptionsContext *o, AVFormatContext *oc)
 +{
 +    AVStream *st;
 +    OutputStream *ost;
 +    AVCodecContext *video_enc;
 +
 +    ost = new_output_stream(o, oc, AVMEDIA_TYPE_VIDEO);
 +    st  = ost->st;
-     if (!st->stream_copy) {
-         ost->frame_aspect_ratio = frame_aspect_ratio;
-         frame_aspect_ratio = 0;
- #if CONFIG_AVFILTER
-         ost->avfilter = vfilters;
-         vfilters = NULL;
- #endif
-     }
-     st->codec->thread_count= thread_count;
 +    video_enc = st->codec;
  
      if(oc->oformat->flags & AVFMT_GLOBALHEADER) {
          video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
      }
  
-     if (st->stream_copy) {
 -    video_enc->codec_type = AVMEDIA_TYPE_VIDEO;
 -    if (video_stream_copy) {
 -        st->stream_copy = 1;
--        video_enc->sample_aspect_ratio =
--        st->sample_aspect_ratio = av_d2q(frame_aspect_ratio*frame_height/frame_width, 255);
--    } else {
--        const char *p;
--        int i;
++    if (!st->stream_copy) {
++        const char *p = NULL;
++        char *forced_key_frames = NULL, *frame_rate = NULL, *frame_size = NULL;
++        char *frame_aspect_ratio = NULL, *frame_pix_fmt = NULL;
++        char *intra_matrix = NULL, *inter_matrix = NULL, *filters = NULL;
++        int i, force_fps = 0, top_field_first = -1;
++
++        MATCH_PER_STREAM_OPT(frame_rates, str, frame_rate, oc, st);
++        if (frame_rate && av_parse_video_rate(&ost->frame_rate, frame_rate) < 0) {
++            av_log(NULL, AV_LOG_ERROR, "Invalid framerate value: %s\n", frame_rate);
++            exit_program(1);
++        }
 +
-         if (frame_rate.num)
-             ost->frame_rate = frame_rate;
++        MATCH_PER_STREAM_OPT(frame_sizes, str, frame_size, oc, st);
++        if (frame_size && av_parse_video_size(&video_enc->width, &video_enc->height, frame_size) < 0) {
++            av_log(NULL, AV_LOG_ERROR, "Invalid frame size: %s.\n", frame_size);
++            exit_program(1);
++        }
 -        if (frame_rate.num)
 -            ost->frame_rate = frame_rate;
 -        video_enc->codec_id = codec_id;
++        MATCH_PER_STREAM_OPT(frame_aspect_ratios, str, frame_aspect_ratio, oc, st);
++        if (frame_aspect_ratio)
++            ost->frame_aspect_ratio = parse_frame_aspect_ratio(frame_aspect_ratio);
  
--        video_enc->width = frame_width;
--        video_enc->height = frame_height;
--        video_enc->pix_fmt = frame_pix_fmt;
 +        video_enc->bits_per_raw_sample = frame_bits_per_raw_sample;
++        MATCH_PER_STREAM_OPT(frame_pix_fmts, str, frame_pix_fmt, oc, st);
++        if (frame_pix_fmt && (video_enc->pix_fmt = av_get_pix_fmt(frame_pix_fmt)) == PIX_FMT_NONE) {
++            av_log(NULL, AV_LOG_ERROR, "Unknown pixel format requested: %s.\n", frame_pix_fmt);
++            exit_program(1);
++        }
          st->sample_aspect_ratio = video_enc->sample_aspect_ratio;
  
          if (intra_only)
              video_enc->gop_size = 0;
-         if (video_qscale || same_quant) {
 -        if (video_qscale || same_quality) {
--            video_enc->flags |= CODEC_FLAG_QSCALE;
--            video_enc->global_quality = FF_QP2LAMBDA * video_qscale;
++        MATCH_PER_STREAM_OPT(intra_matrices, str, intra_matrix, oc, st);
++        if (intra_matrix) {
++            if (!(video_enc->intra_matrix = av_mallocz(sizeof(*video_enc->intra_matrix) * 64))) {
++                av_log(NULL, AV_LOG_ERROR, "Could not allocate memory for intra matrix.\n");
++                exit_program(1);
++            }
++            parse_matrix_coeffs(video_enc->intra_matrix, intra_matrix);
++        }
++        MATCH_PER_STREAM_OPT(inter_matrices, str, inter_matrix, oc, st);
++        if (inter_matrix) {
++            if (!(video_enc->inter_matrix = av_mallocz(sizeof(*video_enc->inter_matrix) * 64))) {
++                av_log(NULL, AV_LOG_ERROR, "Could not allocate memory for inter matrix.\n");
++                exit_program(1);
++            }
++            parse_matrix_coeffs(video_enc->inter_matrix, inter_matrix);
          }
  
--        if(intra_matrix)
--            video_enc->intra_matrix = intra_matrix;
--        if(inter_matrix)
--            video_enc->inter_matrix = inter_matrix;
--
--        p= video_rc_override_string;
++        MATCH_PER_STREAM_OPT(rc_overrides, str, p, oc, st);
          for(i=0; p; i++){
              int start, end, q;
              int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
          video_enc->rc_override_count=i;
          if (!video_enc->rc_initial_buffer_occupancy)
              video_enc->rc_initial_buffer_occupancy = video_enc->rc_buffer_size*3/4;
--        video_enc->me_threshold= me_threshold;
          video_enc->intra_dc_precision= intra_dc_precision - 8;
  
--        if (do_psnr)
--            video_enc->flags|= CODEC_FLAG_PSNR;
--
          /* two pass mode */
          if (do_pass) {
              if (do_pass == 1) {
              }
          }
  
++        MATCH_PER_STREAM_OPT(forced_key_frames, str, forced_key_frames, oc, st);
          if (forced_key_frames)
              parse_forced_key_frames(forced_key_frames, ost, video_enc);
 -    }
 -    if (video_language) {
 -        av_dict_set(&st->metadata, "language", video_language, 0);
 -        av_freep(&video_language);
++
++        MATCH_PER_STREAM_OPT(force_fps, i, force_fps, oc, st);
++        ost->force_fps = force_fps;
++
++        MATCH_PER_STREAM_OPT(top_field_first, i, top_field_first, oc, st);
++        ost->top_field_first = top_field_first;
++
++#if CONFIG_AVFILTER
++        MATCH_PER_STREAM_OPT(filters, str, filters, oc, st);
++        if (filters)
++            ost->avfilter = av_strdup(filters);
++#endif
      }
  
--    /* reset some key parameters */
 -    video_disable = 0;
 -    av_freep(&video_codec_name);
--    av_freep(&forced_key_frames);
 -    video_stream_copy = 0;
--    frame_pix_fmt = PIX_FMT_NONE;
 +    return ost;
  }
  
 -static void new_audio_stream(AVFormatContext *oc, int file_idx)
 +static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc)
  {
      AVStream *st;
      OutputStream *ost;
 -    AVCodec *codec= NULL;
      AVCodecContext *audio_enc;
 -    enum CodecID codec_id = CODEC_ID_NONE;
  
 -    if(!audio_stream_copy){
 -        if (audio_codec_name) {
 -            codec_id = find_codec_or_die(audio_codec_name, AVMEDIA_TYPE_AUDIO, 1);
 -            codec = avcodec_find_encoder_by_name(audio_codec_name);
 -        } else {
 -            codec_id = av_guess_codec(oc->oformat, NULL, oc->filename, NULL, AVMEDIA_TYPE_AUDIO);
 -            codec = avcodec_find_encoder(codec_id);
 -        }
 -    }
 -    ost = new_output_stream(oc, file_idx, codec);
 +    ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO);
      st  = ost->st;
  
 -    ost->bitstream_filters = audio_bitstream_filters;
 -    audio_bitstream_filters= NULL;
 -
--    st->codec->thread_count= thread_count;
--
      audio_enc = st->codec;
      audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;
  
      if (oc->oformat->flags & AVFMT_GLOBALHEADER) {
          audio_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
      }
 -    if (audio_stream_copy) {
 -        st->stream_copy = 1;
 -    } else {
 -        audio_enc->codec_id = codec_id;
 +    if (!st->stream_copy) {
-         if (audio_qscale > QSCALE_NONE) {
-             audio_enc->flags |= CODEC_FLAG_QSCALE;
-             audio_enc->global_quality = FF_QP2LAMBDA * audio_qscale;
-         }
++        char *sample_fmt = NULL;
 -        if (audio_qscale > QSCALE_NONE) {
 -            audio_enc->flags |= CODEC_FLAG_QSCALE;
 -            audio_enc->global_quality = FF_QP2LAMBDA * audio_qscale;
 +        MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);
 +
-         if (audio_sample_fmt != AV_SAMPLE_FMT_NONE)
-             audio_enc->sample_fmt = audio_sample_fmt;
-         if (audio_sample_rate)
-             audio_enc->sample_rate = audio_sample_rate;
++        MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);
++        if (sample_fmt &&
++            (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {
++            av_log(NULL, AV_LOG_ERROR, "Invalid sample format '%s'\n", sample_fmt);
++            exit_program(1);
+         }
 -        if (audio_channels)
 -            audio_enc->channels = audio_channels;
 -        if (audio_sample_fmt != AV_SAMPLE_FMT_NONE)
 -            audio_enc->sample_fmt = audio_sample_fmt;
 -        if (audio_sample_rate)
 -            audio_enc->sample_rate = audio_sample_rate;
 -    }
 -    if (audio_language) {
 -        av_dict_set(&st->metadata, "language", audio_language, 0);
 -        av_freep(&audio_language);
++
++        MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);
      }
  
 -    /* reset some key parameters */
 -    audio_disable = 0;
 -    av_freep(&audio_codec_name);
 -    audio_stream_copy = 0;
 +    return ost;
  }
  
 -static void new_data_stream(AVFormatContext *oc, int file_idx)
 +static OutputStream *new_data_stream(OptionsContext *o, AVFormatContext *oc)
  {
      AVStream *st;
      OutputStream *ost;
@@@ -3518,7 -3681,7 +3450,7 @@@ static OutputStream *new_subtitle_strea
  }
  
  /* arg format is "output-stream-index:streamid-value". */
--static int opt_streamid(const char *opt, const char *arg)
++static int opt_streamid(OptionsContext *o, const char *opt, const char *arg)
  {
      int idx;
      char *p;
          exit_program(1);
      }
      *p++ = '\0';
 -    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, INT_MAX);
 -    streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
 -    streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
 +    idx = parse_number_or_die(opt, idx_str, OPT_INT, 0, MAX_STREAMS-1);
-     streamid_map = grow_array(streamid_map, sizeof(*streamid_map), &nb_streamid_map, idx+1);
-     streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
++    o->streamid_map = grow_array(o->streamid_map, sizeof(*o->streamid_map), &o->nb_streamid_map, idx+1);
++    o->streamid_map[idx] = parse_number_or_die(opt, p, OPT_INT, 0, INT_MAX);
 +    return 0;
 +}
 +
 +static int copy_chapters(InputFile *ifile, OutputFile *ofile, int copy_metadata)
 +{
 +    AVFormatContext *is = ifile->ctx;
 +    AVFormatContext *os = ofile->ctx;
 +    int i;
 +
 +    for (i = 0; i < is->nb_chapters; i++) {
 +        AVChapter *in_ch = is->chapters[i], *out_ch;
 +        int64_t ts_off   = av_rescale_q(ofile->start_time - ifile->ts_offset,
 +                                      AV_TIME_BASE_Q, in_ch->time_base);
 +        int64_t rt       = (ofile->recording_time == INT64_MAX) ? INT64_MAX :
 +                           av_rescale_q(ofile->recording_time, AV_TIME_BASE_Q, in_ch->time_base);
 +
 +
 +        if (in_ch->end < ts_off)
 +            continue;
 +        if (rt != INT64_MAX && in_ch->start > rt + ts_off)
 +            break;
 +
 +        out_ch = av_mallocz(sizeof(AVChapter));
 +        if (!out_ch)
 +            return AVERROR(ENOMEM);
 +
 +        out_ch->id        = in_ch->id;
 +        out_ch->time_base = in_ch->time_base;
 +        out_ch->start     = FFMAX(0,  in_ch->start - ts_off);
 +        out_ch->end       = FFMIN(rt, in_ch->end   - ts_off);
 +
 +        if (copy_metadata)
 +            av_dict_copy(&out_ch->metadata, in_ch->metadata, 0);
 +
 +        os->nb_chapters++;
 +        os->chapters = av_realloc(os->chapters, sizeof(AVChapter)*os->nb_chapters);
 +        if (!os->chapters)
 +            return AVERROR(ENOMEM);
 +        os->chapters[os->nb_chapters - 1] = out_ch;
 +    }
 +    return 0;
 +}
 +
 +static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)
 +{
 +    int i, err;
 +    AVFormatContext *ic = NULL;
 +
 +    err = avformat_open_input(&ic, filename, NULL, NULL);
 +    if (err < 0)
 +        return err;
 +    /* copy stream format */
 +    for(i=0;i<ic->nb_streams;i++) {
 +        AVStream *st;
 +        OutputStream *ost;
 +        AVCodec *codec;
 +
 +        codec = avcodec_find_encoder(ic->streams[i]->codec->codec_id);
 +        ost   = new_output_stream(o, s, codec->type);
 +        st    = ost->st;
 +
 +        // FIXME: a more elegant solution is needed
 +        memcpy(st, ic->streams[i], sizeof(AVStream));
 +        st->info = av_malloc(sizeof(*st->info));
 +        memcpy(st->info, ic->streams[i]->info, sizeof(*st->info));
 +        avcodec_copy_context(st->codec, ic->streams[i]->codec);
 +
 +        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO && !st->stream_copy)
 +            choose_sample_fmt(st, codec);
 +        else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO && !st->stream_copy)
 +            choose_pixel_fmt(st, codec);
 +    }
 +
 +    av_close_input_file(ic);
      return 0;
  }
  
@@@ -3766,138 -3828,18 +3698,128 @@@ static void opt_output_file(void *optct
          av_log(NULL, AV_LOG_WARNING, "-loop_output is deprecated, use -loop\n");
          oc->loop_output = loop_output;
      }
 -    oc->flags |= AVFMT_FLAG_NONBLOCK;
  
 -    frame_rate    = (AVRational){0, 0};
 -    frame_width   = 0;
 -    frame_height  = 0;
 -    audio_sample_rate = 0;
 -    audio_channels    = 0;
 -    audio_sample_fmt  = AV_SAMPLE_FMT_NONE;
 +    /* copy chapters */
 +    if (o->chapters_input_file >= nb_input_files) {
 +        if (o->chapters_input_file == INT_MAX) {
 +            /* copy chapters from the first input file that has them*/
 +            o->chapters_input_file = -1;
 +            for (i = 0; i < nb_input_files; i++)
 +                if (input_files[i].ctx->nb_chapters) {
 +                    o->chapters_input_file = i;
 +                    break;
 +                }
 +        } else {
 +            av_log(NULL, AV_LOG_ERROR, "Invalid input file index %d in chapter mapping.\n",
 +                   o->chapters_input_file);
 +            exit_program(1);
 +        }
 +    }
 +    if (o->chapters_input_file >= 0)
 +        copy_chapters(&input_files[o->chapters_input_file], &output_files[nb_output_files - 1],
-                       o->metadata_chapters_manual);
++                      !o->metadata_chapters_manual);
 +
 +    /* copy metadata */
 +    for (i = 0; i < o->nb_meta_data_maps; i++) {
 +        AVFormatContext *files[2];
 +        AVDictionary    **meta[2];
 +        int j;
 +
 +#define METADATA_CHECK_INDEX(index, nb_elems, desc)\
 +        if ((index) < 0 || (index) >= (nb_elems)) {\
 +            av_log(NULL, AV_LOG_ERROR, "Invalid %s index %d while processing metadata maps\n",\
 +                     (desc), (index));\
 +            exit_program(1);\
 +        }
  
 -    av_freep(&forced_key_frames);
 -    uninit_opts();
 -    init_opts();
 +        int in_file_index = o->meta_data_maps[i][1].file;
 +        if (in_file_index < 0)
 +            continue;
 +        METADATA_CHECK_INDEX(in_file_index, nb_input_files, "input file")
 +
 +        files[0] = oc;
 +        files[1] = input_files[in_file_index].ctx;
 +
 +        for (j = 0; j < 2; j++) {
 +            MetadataMap *map = &o->meta_data_maps[i][j];
 +
 +            switch (map->type) {
 +            case 'g':
 +                meta[j] = &files[j]->metadata;
 +                break;
 +            case 's':
 +                METADATA_CHECK_INDEX(map->index, files[j]->nb_streams, "stream")
 +                meta[j] = &files[j]->streams[map->index]->metadata;
 +                break;
 +            case 'c':
 +                METADATA_CHECK_INDEX(map->index, files[j]->nb_chapters, "chapter")
 +                meta[j] = &files[j]->chapters[map->index]->metadata;
 +                break;
 +            case 'p':
 +                METADATA_CHECK_INDEX(map->index, files[j]->nb_programs, "program")
 +                meta[j] = &files[j]->programs[map->index]->metadata;
 +                break;
 +            }
 +        }
 +
 +        av_dict_copy(meta[0], *meta[1], AV_DICT_DONT_OVERWRITE);
 +    }
 +
 +    /* copy global metadata by default */
 +    if (!o->metadata_global_manual && nb_input_files){
 +        av_dict_copy(&oc->metadata, input_files[0].ctx->metadata,
 +                     AV_DICT_DONT_OVERWRITE);
 +        if(o->recording_time != INT64_MAX)
 +            av_dict_set(&oc->metadata, "duration", NULL, 0);
 +    }
 +    if (!o->metadata_streams_manual)
 +        for (i = output_files[nb_output_files - 1].ost_index; i < nb_output_streams; i++) {
 +            InputStream *ist = &input_streams[output_streams[i].source_index];
 +            av_dict_copy(&output_streams[i].st->metadata, ist->st->metadata, AV_DICT_DONT_OVERWRITE);
 +        }
 +
 +    /* process manually set metadata */
 +    for (i = 0; i < o->nb_metadata; i++) {
 +        AVDictionary **m;
 +        char type, *val;
 +        int index = 0;
 +
 +        val = strchr(o->metadata[i].u.str, '=');
 +        if (!val) {
 +            av_log(NULL, AV_LOG_ERROR, "No '=' character in metadata string %s.\n",
 +                   o->metadata[i].u.str);
 +            exit_program(1);
 +        }
 +        *val++ = 0;
 +
 +        parse_meta_type(o->metadata[i].specifier, &type, &index);
 +        switch (type) {
 +        case 'g':
 +            m = &oc->metadata;
 +            break;
 +        case 's':
 +            if (index < 0 || index >= oc->nb_streams) {
 +                av_log(NULL, AV_LOG_ERROR, "Invalid stream index %d in metadata specifier.\n", index);
 +                exit_program(1);
 +            }
-             m = &oc->streams[i]->metadata;
++            m = &oc->streams[index]->metadata;
 +            break;
 +        case 'c':
 +            if (index < 0 || index >= oc->nb_chapters) {
 +                av_log(NULL, AV_LOG_ERROR, "Invalid chapter index %d in metadata specifier.\n", index);
 +                exit_program(1);
 +            }
-             m = &oc->chapters[i]->metadata;
++            m = &oc->chapters[index]->metadata;
 +            break;
 +        default:
 +            av_log(NULL, AV_LOG_ERROR, "Invalid metadata specifier %s.\n", o->metadata[i].specifier);
 +            exit_program(1);
 +        }
 +
 +        av_dict_set(m, o->metadata[i].u.str, *val ? val : NULL, 0);
 +    }
 +
-     frame_rate    = (AVRational){0, 0};
-     frame_width   = 0;
-     frame_height  = 0;
-     audio_sample_rate = 0;
-     audio_sample_fmt  = AV_SAMPLE_FMT_NONE;
-     av_freep(&streamid_map);
-     nb_streamid_map = 0;
-     av_freep(&forced_key_frames);
 +    reset_options(o, 0);
  }
  
  /* same option as mencoder */
@@@ -3943,35 -3885,33 +3865,9 @@@ static int64_t getmaxrss(void
  #endif
  }
  
--static void parse_matrix_coeffs(uint16_t *dest, const char *str)
--{
--    int i;
--    const char *p = str;
--    for(i = 0;; i++) {
--        dest[i] = atoi(p);
--        if(i == 63)
--            break;
--        p = strchr(p, ',');
--        if(!p) {
--            fprintf(stderr, "Syntax error in matrix \"%s\" at coeff %d\n", str, i);
--            exit_program(1);
--        }
--        p++;
--    }
--}
--
- static int opt_inter_matrix(const char *opt, const char *arg)
 -static void opt_inter_matrix(const char *arg)
 -{
 -    inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
 -    parse_matrix_coeffs(inter_matrix, arg);
 -}
 -
 -static void opt_intra_matrix(const char *arg)
++static int opt_audio_qscale(OptionsContext *o, const char *opt, const char *arg)
  {
-     inter_matrix = av_mallocz(sizeof(uint16_t) * 64);
-     parse_matrix_coeffs(inter_matrix, arg);
-     return 0;
- }
- static int opt_intra_matrix(const char *opt, const char *arg)
- {
--    intra_matrix = av_mallocz(sizeof(uint16_t) * 64);
--    parse_matrix_coeffs(intra_matrix, arg);
-     return 0;
++    return parse_option(o, "q:a", arg, options);
  }
  
  static void show_usage(void)
@@@ -4067,34 -4006,34 +3963,25 @@@ static int opt_target(OptionsContext *o
          norm = FILM;
          arg += 5;
      } else {
--        int fr;
--        /* Calculate FR via float to avoid int overflow */
--        fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);
--        if(fr == 25000) {
--            norm = PAL;
--        } else if((fr == 29970) || (fr == 23976)) {
--            norm = NTSC;
--        } else {
--            /* Try to determine PAL/NTSC by peeking in the input files */
--            if(nb_input_files) {
--                int i, j;
--                for (j = 0; j < nb_input_files; j++) {
-                     for (i = 0; i < input_files[j].nb_streams; i++) {
 -                    for (i = 0; i < input_files[j].ctx->nb_streams; i++) {
--                        AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
--                        if(c->codec_type != AVMEDIA_TYPE_VIDEO)
--                            continue;
--                        fr = c->time_base.den * 1000 / c->time_base.num;
--                        if(fr == 25000) {
--                            norm = PAL;
--                            break;
--                        } else if((fr == 29970) || (fr == 23976)) {
--                            norm = NTSC;
--                            break;
--                        }
--                    }
--                    if(norm != UNKNOWN)
++        /* Try to determine PAL/NTSC by peeking in the input files */
++        if(nb_input_files) {
++            int i, j, fr;
++            for (j = 0; j < nb_input_files; j++) {
++                for (i = 0; i < input_files[j].nb_streams; i++) {
++                    AVCodecContext *c = input_files[j].ctx->streams[i]->codec;
++                    if(c->codec_type != AVMEDIA_TYPE_VIDEO)
++                        continue;
++                    fr = c->time_base.den * 1000 / c->time_base.num;
++                    if(fr == 25000) {
++                        norm = PAL;
 +                        break;
++                    } else if((fr == 29970) || (fr == 23976)) {
++                        norm = NTSC;
+                         break;
++                    }
                  }
++                if(norm != UNKNOWN)
++                    break;
              }
          }
          if(verbose > 0 && norm != UNKNOWN)
      }
  
      if(!strcmp(arg, "vcd")) {
 -        opt_video_codec("vcodec", "mpeg1video");
 -        opt_audio_codec("vcodec", "mp2");
 -        opt_format("f", "vcd");
 +        opt_video_codec(o, "c:v", "mpeg1video");
 +        opt_audio_codec(o, "c:a", "mp2");
 +        parse_option(o, "f", "vcd", options);
  
--        opt_frame_size("s", norm == PAL ? "352x288" : "352x240");
--        opt_frame_rate("r", frame_rates[norm]);
++        parse_option(o, "s", norm == PAL ? "352x288" : "352x240", options);
++        parse_option(o, "r", frame_rates[norm], options);
          opt_default("g", norm == PAL ? "15" : "18");
  
          opt_default("b", "1150000");
          opt_default("minrate", "1150000");
          opt_default("bufsize", "327680"); // 40*1024*8;
  
 -        opt_default("ab", "224000");
 -        audio_sample_rate = 44100;
 -        audio_channels = 2;
 +        opt_default("b:a", "224000");
-         audio_sample_rate = 44100;
++        parse_option(o, "ar", "44100", options);
 +        parse_option(o, "ac", "2", options);
  
          opt_default("packetsize", "2324");
          opt_default("muxrate", "1411200"); // 2352 * 75 * 8;
             and the first pack from the other stream, respectively, may also have
             been written before.
             So the real data starts at SCR 36000+3*1200. */
 -        mux_preload= (36000+3*1200) / 90000.0; //0.44
 +        o->mux_preload = (36000+3*1200) / 90000.0; //0.44
      } else if(!strcmp(arg, "svcd")) {
  
 -        opt_video_codec("vcodec", "mpeg2video");
 -        opt_audio_codec("acodec", "mp2");
 -        opt_format("f", "svcd");
 +        opt_video_codec(o, "c:v", "mpeg2video");
 +        opt_audio_codec(o, "c:a", "mp2");
 +        parse_option(o, "f", "svcd", options);
  
--        opt_frame_size("s", norm == PAL ? "480x576" : "480x480");
--        opt_frame_rate("r", frame_rates[norm]);
-         opt_frame_pix_fmt("pix_fmt", "yuv420p");
++        parse_option(o, "s", norm == PAL ? "480x576" : "480x480", options);
++        parse_option(o, "r", frame_rates[norm], options);
++        parse_option(o, "pix_fmt", "yuv420p", options);
          opt_default("g", norm == PAL ? "15" : "18");
  
          opt_default("b", "2040000");
          opt_default("flags", "+scan_offset");
  
  
 -        opt_default("ab", "224000");
 -        audio_sample_rate = 44100;
 +        opt_default("b:a", "224000");
-         audio_sample_rate = 44100;
++        parse_option(o, "ar", "44100", options);
  
          opt_default("packetsize", "2324");
  
      } else if(!strcmp(arg, "dvd")) {
  
 -        opt_video_codec("vcodec", "mpeg2video");
 -        opt_audio_codec("vcodec", "ac3");
 -        opt_format("f", "dvd");
 +        opt_video_codec(o, "c:v", "mpeg2video");
 +        opt_audio_codec(o, "c:a", "ac3");
 +        parse_option(o, "f", "dvd", options);
  
--        opt_frame_size("vcodec", norm == PAL ? "720x576" : "720x480");
--        opt_frame_rate("r", frame_rates[norm]);
-         opt_frame_pix_fmt("pix_fmt", "yuv420p");
++        parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
++        parse_option(o, "r", frame_rates[norm], options);
++        parse_option(o, "pix_fmt", "yuv420p", options);
          opt_default("g", norm == PAL ? "15" : "18");
  
          opt_default("b", "6000000");
          opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.
          opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8
  
 -        opt_default("ab", "448000");
 -        audio_sample_rate = 48000;
 +        opt_default("b:a", "448000");
-         audio_sample_rate = 48000;
++        parse_option(o, "ar", "48000", options);
  
      } else if(!strncmp(arg, "dv", 2)) {
  
 -        opt_format("f", "dv");
 +        parse_option(o, "f", "dv", options);
  
--        opt_frame_size("s", norm == PAL ? "720x576" : "720x480");
--        opt_frame_pix_fmt("pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
--                          norm == PAL ? "yuv420p" : "yuv411p");
--        opt_frame_rate("r", frame_rates[norm]);
++        parse_option(o, "s", norm == PAL ? "720x576" : "720x480", options);
++        parse_option(o, "pix_fmt", !strncmp(arg, "dv50", 4) ? "yuv422p" :
++                          norm == PAL ? "yuv420p" : "yuv411p", options);
++        parse_option(o, "r", frame_rates[norm], options);
  
--        audio_sample_rate = 48000;
 -        audio_channels = 2;
++        parse_option(o, "ar", "48000", options);
 +        parse_option(o, "ac", "2", options);
  
      } else {
          fprintf(stderr, "Unknown target: %s\n", arg);
@@@ -4273,28 -4216,6 +4160,32 @@@ static int opt_preset(OptionsContext *o
      return 0;
  }
  
 +static void log_callback_null(void* ptr, int level, const char* fmt, va_list vl)
 +{
 +}
 +
 +static int opt_passlogfile(const char *opt, const char *arg)
 +{
 +    pass_logfilename_prefix = arg;
 +#if CONFIG_LIBX264_ENCODER
 +    return opt_default("passlogfile", arg);
 +#else
 +    return 0;
 +#endif
 +}
 +
 +static int opt_old2new(OptionsContext *o, const char *opt, const char *arg){
 +    char *s= av_malloc(strlen(opt)+2);
 +    snprintf(s, strlen(opt)+2, "%s:%c", opt+1, *opt);
 +    return parse_option(o, s, arg, options);
 +}
 +
++static int opt_video_filters(OptionsContext *o, const char *opt, const char *arg)
++{
++    return parse_option(o, "filter:v", arg, options);
++}
 +
 +#define OFFSET(x) offsetof(OptionsContext, x)
  static const OptionDef options[] = {
      /* main options */
  #include "cmdutils_common_opts.h"
        "dump each input packet" },
      { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
        "when dumping packets, also dump the payload" },
 -    { "re", OPT_BOOL | OPT_EXPERT, {(void*)&rate_emu}, "read input at native frame rate", "" },
 +    { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET, {.off = OFFSET(rate_emu)}, "read input at native frame rate", "" },
      { "loop_input", OPT_BOOL | OPT_EXPERT, {(void*)&loop_input}, "deprecated, use -loop" },
      { "loop_output", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&loop_output}, "deprecated, use -loop", "" },
 -    { "v", HAS_ARG, {(void*)opt_verbose}, "set ffmpeg verbosity level", "number" },
 -    { "target", HAS_ARG, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
 -    { "threads",  HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
 +    { "v", HAS_ARG, {(void*)opt_verbose}, "set the verbosity level", "number" },
 +    { "target", HAS_ARG | OPT_FUNC2, {(void*)opt_target}, "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\", \"dv50\", \"pal-vcd\", \"ntsc-svcd\", ...)", "type" },
-     { "threads",  HAS_ARG | OPT_EXPERT, {(void*)opt_thread_count}, "thread count", "count" },
      { "vsync", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&video_sync_method}, "video sync method", "" },
      { "async", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&audio_sync_method}, "audio sync method", "" },
      { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&audio_drift_threshold}, "audio drift threshold", "threshold" },
      { "copytb", OPT_BOOL | OPT_EXPERT, {(void*)&copy_tb}, "copy input stream time base when stream copying" },
      { "shortest", OPT_BOOL | OPT_EXPERT, {(void*)&opt_shortest}, "finish encoding within shortest input" }, //
      { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, {(void*)&dts_delta_threshold}, "timestamp discontinuity delta threshold", "threshold" },
--    { "programid", HAS_ARG | OPT_INT | OPT_EXPERT, {(void*)&opt_programid}, "desired program number", "" },
      { "xerror", OPT_BOOL, {(void*)&exit_on_error}, "exit on error", "error" },
      { "copyinkf", OPT_BOOL | OPT_EXPERT, {(void*)&copy_initial_nonkeyframes}, "copy initial non-keyframes" },
 +    { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC, {.off = OFFSET(max_frames)}, "set the number of frames to record", "number" },
 +    { "tag",   OPT_STRING | HAS_ARG | OPT_SPEC, {.off = OFFSET(codec_tags)}, "force codec tag/fourcc", "fourcc/tag" },
++    { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
++    { "qscale", HAS_ARG | OPT_EXPERT | OPT_DOUBLE | OPT_SPEC, {.off = OFFSET(qscale)}, "use fixed quality scale (VBR)", "q" },
++#if CONFIG_AVFILTER
++    { "filter", HAS_ARG | OPT_STRING | OPT_SPEC, {.off = OFFSET(filters)}, "set stream filterchain", "filter_list" },
++#endif
  
      /* video options */
 -    { "vframes", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&max_frames[AVMEDIA_TYPE_VIDEO]}, "set the number of video frames to record", "number" },
 -    { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
 -    { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
 -    { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
 -    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format, 'list' as argument shows all the pixel formats supported", "format" },
 -    { "croptop", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
 +    { "vframes", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_frames}, "set the number of video frames to record", "number" },
-     { "r", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_rate}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
-     { "s", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
-     { "aspect", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_aspect_ratio}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
-     { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_frame_pix_fmt}, "set pixel format, 'list' as argument shows all the pixel formats supported", "format" },
++    { "r", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_rates)}, "set frame rate (Hz value, fraction or abbreviation)", "rate" },
++    { "s", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_sizes)}, "set frame size (WxH or abbreviation)", "size" },
++    { "aspect", HAS_ARG | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_aspect_ratios)}, "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
++    { "pix_fmt", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(frame_pix_fmts)}, "set pixel format", "format" },
 +    { "bits_per_raw_sample", OPT_INT | HAS_ARG | OPT_VIDEO, {(void*)&frame_bits_per_raw_sample}, "set the number of bits per raw sample", "number" },
 +    { "croptop",  HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
      { "cropbottom", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
      { "cropleft", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
      { "cropright", HAS_ARG | OPT_VIDEO, {(void*)opt_frame_crop}, "Removed, use the crop filter instead", "size" },
      { "padright", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "size" },
      { "padcolor", HAS_ARG | OPT_VIDEO, {(void*)opt_pad}, "Removed, use the pad filter instead", "color" },
      { "intra", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_only}, "use only intra frames"},
 -    { "vn", OPT_BOOL | OPT_VIDEO, {(void*)&video_disable}, "disable video" },
 +    { "vn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET, {.off = OFFSET(video_disable)}, "disable video" },
      { "vdt", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&video_discard}, "discard threshold", "n" },
--    { "qscale", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_qscale}, "use fixed video quantizer scale (VBR)", "q" },
--    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_video_rc_override_string}, "rate control override for specific intervals", "override" },
 -    { "vcodec", HAS_ARG | OPT_VIDEO, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
 -    { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimaton threshold",  "threshold" },
 -    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quality},
++    { "rc_override", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(rc_overrides)}, "rate control override for specific intervals", "override" },
 +    { "vcodec", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
-     { "me_threshold", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_me_threshold}, "motion estimation threshold",  "threshold" },
 +    { "sameq", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
-     { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant}, "use same quantizer as source (implies VBR)" },
++    { "same_quant", OPT_BOOL | OPT_VIDEO, {(void*)&same_quant},
+       "use same quantizer as source (implies VBR)" },
      { "pass", HAS_ARG | OPT_VIDEO, {(void*)opt_pass}, "select the pass number (1 or 2)", "n" },
 -    { "passlogfile", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void*)&pass_logfilename_prefix}, "select two pass log file name prefix", "prefix" },
 +    { "passlogfile", HAS_ARG | OPT_VIDEO, {(void*)&opt_passlogfile}, "select two pass log file name prefix", "prefix" },
      { "deinterlace", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_deinterlace},
        "deinterlace pictures" },
--    { "psnr", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
      { "vstats", OPT_EXPERT | OPT_VIDEO, {(void*)&opt_vstats}, "dump video coding statistics to file" },
      { "vstats_file", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_vstats_file}, "dump video coding statistics to file", "file" },
  #if CONFIG_AVFILTER
--    { "vf", OPT_STRING | HAS_ARG, {(void*)&vfilters}, "video filters", "filter list" },
++    { "vf", HAS_ARG | OPT_VIDEO | OPT_FUNC2, {(void*)opt_video_filters}, "video filters", "filter list" },
  #endif
--    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_intra_matrix}, "specify intra matrix coeffs", "matrix" },
--    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_inter_matrix}, "specify inter matrix coeffs", "matrix" },
--    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_top_field_first}, "top=1/bottom=0/auto=-1 field first", "" },
++    { "intra_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(intra_matrices)}, "specify intra matrix coeffs", "matrix" },
++    { "inter_matrix", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_STRING | OPT_SPEC, {.off = OFFSET(inter_matrices)}, "specify inter matrix coeffs", "matrix" },
++    { "top", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_INT| OPT_SPEC, {.off = OFFSET(top_field_first)}, "top=1/bottom=0/auto=-1 field first", "" },
      { "dc", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)&intra_dc_precision}, "intra_dc_precision", "precision" },
 -    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void*)opt_codec_tag}, "force video tag/fourcc", "fourcc/tag" },
 -    { "newvideo", OPT_VIDEO, {(void*)opt_new_stream}, "add a new video stream to the current output stream" },
 -    { "vlang", HAS_ARG | OPT_STRING | OPT_VIDEO, {(void *)&video_language}, "set the ISO 639 language code (3 letters) of the current video stream" , "code" },
 +    { "vtag", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_FUNC2, {(void*)opt_old2new}, "force video tag/fourcc", "fourcc/tag" },
      { "qphist", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, { (void *)&qp_hist }, "show QP histogram" },
--    { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO, {(void*)&force_fps}, "force the selected framerate, disable the best supported framerate selection" },
--    { "streamid", HAS_ARG | OPT_EXPERT, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
--    { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO, {(void *)&forced_key_frames}, "force key frames at specified timestamps", "timestamps" },
++    { "force_fps", OPT_BOOL | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(force_fps)}, "force the selected framerate, disable the best supported framerate selection" },
++    { "streamid", HAS_ARG | OPT_EXPERT | OPT_FUNC2, {(void*)opt_streamid}, "set the value of an outfile streamid", "streamIndex:value" },
++    { "force_key_frames", OPT_STRING | HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_SPEC, {.off = OFFSET(forced_key_frames)}, "force key frames at specified timestamps", "timestamps" },
  
      /* audio options */
 -    { "aframes", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&max_frames[AVMEDIA_TYPE_AUDIO]}, "set the number of audio frames to record", "number" },
 -    { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
 -    { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
 -    { "ac", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
 -    { "an", OPT_BOOL | OPT_AUDIO, {(void*)&audio_disable}, "disable audio" },
 -    { "acodec", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
 -    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_codec_tag}, "force audio tag/fourcc", "fourcc/tag" },
 +    { "aframes", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_frames}, "set the number of audio frames to record", "number" },
-     { "aq", OPT_FLOAT | HAS_ARG | OPT_AUDIO, {(void*)&audio_qscale}, "set audio quality (codec-specific)", "quality", },
-     { "ar", HAS_ARG | OPT_AUDIO, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
++    { "aq", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_qscale}, "set audio quality (codec-specific)", "quality", },
++    { "ar", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_sample_rate)}, "set audio sampling rate (in Hz)", "rate" },
 +    { "ac", HAS_ARG | OPT_AUDIO | OPT_INT | OPT_SPEC, {.off = OFFSET(audio_channels)}, "set number of audio channels", "channels" },
 +    { "an", OPT_BOOL | OPT_AUDIO | OPT_OFFSET, {.off = OFFSET(audio_disable)}, "disable audio" },
 +    { "acodec", HAS_ARG | OPT_AUDIO | OPT_FUNC2, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
 +    { "atag", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_FUNC2, {(void*)opt_old2new}, "force audio tag/fourcc", "fourcc/tag" },
      { "vol", OPT_INT | HAS_ARG | OPT_AUDIO, {(void*)&audio_volume}, "change audio volume (256=normal)" , "volume" }, //
 -    { "newaudio", OPT_AUDIO, {(void*)opt_new_stream}, "add a new audio stream to the current output stream" },
 -    { "alang", HAS_ARG | OPT_STRING | OPT_AUDIO, {(void *)&audio_language}, "set the ISO 639 language code (3 letters) of the current audio stream" , "code" },
--    { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO, {(void*)opt_audio_sample_fmt}, "set sample format, 'list' as argument shows all the sample formats supported", "format" },
++    { "sample_fmt", HAS_ARG | OPT_EXPERT | OPT_AUDIO | OPT_SPEC | OPT_STRING, {.off = OFFSET(sample_fmts)}, "set sample format", "format" },
  
      /* subtitle options */
 -    { "sn", OPT_BOOL | OPT_SUBTITLE, {(void*)&subtitle_disable}, "disable subtitle" },
 -    { "scodec", HAS_ARG | OPT_SUBTITLE, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
 -    { "newsubtitle", OPT_SUBTITLE, {(void*)opt_new_stream}, "add a new subtitle stream to the current output stream" },
 -    { "slang", HAS_ARG | OPT_STRING | OPT_SUBTITLE, {(void *)&subtitle_language}, "set the ISO 639 language code (3 letters) of the current subtitle stream" , "code" },
 -    { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE, {(void*)opt_codec_tag}, "force subtitle tag/fourcc", "fourcc/tag" },
 +    { "sn", OPT_BOOL | OPT_SUBTITLE | OPT_OFFSET, {.off = OFFSET(subtitle_disable)}, "disable subtitle" },
 +    { "scodec", HAS_ARG | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_subtitle_codec}, "force subtitle codec ('copy' to copy stream)", "codec" },
 +    { "stag", HAS_ARG | OPT_EXPERT | OPT_SUBTITLE | OPT_FUNC2, {(void*)opt_old2new}, "force subtitle tag/fourcc", "fourcc/tag" },
  
      /* grab options */
      { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO | OPT_GRAB, {(void*)opt_video_channel}, "deprecated, use -channel", "channel" },
Simple merge
index b8c7f5f9211a442f4f71c7b5243459a501676b24,16f69328a04969c023184379028d83a6dc3e98b4..49dd1b1e20f88ed36f446a320a21340169792e84
@@@ -1436,15 -1409,17 +1438,17 @@@ static int handle_packets(MpegTSContex
  
      if (avio_tell(s->pb) != ts->last_pos) {
          int i;
 -        av_dlog("Skipping after seek\n");
 +//        av_dlog("Skipping after seek\n");
          /* seek detected, flush pes buffer */
          for (i = 0; i < NB_PID_MAX; i++) {
-             if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) {
-                 PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
-                 av_freep(&pes->buffer);
+             if (ts->pids[i]) {
+                 if (ts->pids[i]->type == MPEGTS_PES) {
+                    PESContext *pes = ts->pids[i]->u.pes_filter.opaque;
+                    av_freep(&pes->buffer);
+                    pes->data_index = 0;
+                    pes->state = MPEGTS_SKIP; /* skip until pes header */
+                 }
                  ts->pids[i]->last_cc = -1;
-                 pes->data_index = 0;
-                 pes->state = MPEGTS_SKIP; /* skip until pes header */
              }
          }
      }
index dbe1a6359ef5bd7f29b47565e5b06933fa4d7b71,6077be99a4ebaf3005160d37352c59a4b571cd4b..d25f10e8f8282ed8fc572bdd8f339e576f77d4b4
@@@ -2320,8 -2259,8 +2320,15 @@@ int avformat_find_stream_info(AVFormatC
  
          //try to just open decoders, in case this is enough to get parameters
          if(!has_codec_parameters(st->codec)){
--            if (codec && !st->codec->codec)
--                avcodec_open2(st->codec, codec, options ? &options[i] : NULL);
++            if (codec && !st->codec->codec){
++                AVDictionary *tmp = NULL;
++                if (options){
++                    av_dict_copy(&tmp, options[i], 0);
++                    av_dict_set(&tmp, "threads", 0, 0);
++                }
++                avcodec_open2(st->codec, codec, options ? &tmp : NULL);
++                av_dict_free(&tmp);
++            }
          }
      }
  
Simple merge
Simple merge