Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung
 
 
 
 


Quelle  vp9_cx_iface.c   Sprache: C

 
/*
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */


#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include "./vpx_config.h"
#include "vpx/vpx_encoder.h"
#include "vpx/vpx_ext_ratectrl.h"
#include "vpx_dsp/psnr.h"
#include "vpx_ports/static_assert.h"
#include "vpx_ports/system_state.h"
#include "vpx_util/vpx_timestamp.h"
#include "vpx/internal/vpx_codec_internal.h"
#include "./vpx_version.h"
#include "vp9/encoder/vp9_encoder.h"
#include "vp9/encoder/vp9_ethread.h"
#include "vpx/vp8cx.h"
#include "vp9/common/vp9_alloccommon.h"
#include "vp9/common/vp9_scale.h"
#include "vp9/vp9_cx_iface.h"
#include "vp9/encoder/vp9_firstpass.h"
#include "vp9/encoder/vp9_lookahead.h"
#include "vp9/vp9_cx_iface.h"
#include "vp9/vp9_iface_common.h"

#include "vpx/vpx_tpl.h"

typedef struct vp9_extracfg {
  int cpu_used;  // available cpu percentage in 1/16
  unsigned int enable_auto_alt_ref;
  unsigned int noise_sensitivity;
  unsigned int sharpness;
  unsigned int static_thresh;
  unsigned int tile_columns;
  unsigned int tile_rows;
  unsigned int enable_tpl_model;
  unsigned int enable_keyframe_filtering;
  unsigned int arnr_max_frames;
  unsigned int arnr_strength;
  unsigned int min_gf_interval;
  unsigned int max_gf_interval;
  vp8e_tuning tuning;
  unsigned int cq_level;  // constrained quality level
  unsigned int rc_max_intra_bitrate_pct;
  unsigned int rc_max_inter_bitrate_pct;
  unsigned int gf_cbr_boost_pct;
  unsigned int lossless;
  unsigned int target_level;
  unsigned int frame_parallel_decoding_mode;
  AQ_MODE aq_mode;
  int alt_ref_aq;
  unsigned int frame_periodic_boost;
  vpx_bit_depth_t bit_depth;
  vp9e_tune_content content;
  vpx_color_space_t color_space;
  vpx_color_range_t color_range;
  int render_width;
  int render_height;
  unsigned int row_mt;
  unsigned int motion_vector_unit_test;
  int delta_q_uv;
} vp9_extracfg;

static struct vp9_extracfg default_extra_cfg = {
#if CONFIG_REALTIME_ONLY
  5,  // cpu_used
#else
  0,  // cpu_used
#endif
  1,                     // enable_auto_alt_ref
  0,                     // noise_sensitivity
  0,                     // sharpness
  0,                     // static_thresh
  6,                     // tile_columns
  0,                     // tile_rows
  1,                     // enable_tpl_model
  0,                     // enable_keyframe_filtering
  7,                     // arnr_max_frames
  5,                     // arnr_strength
  0,                     // min_gf_interval; 0 -> default decision
  0,                     // max_gf_interval; 0 -> default decision
  VP8_TUNE_PSNR,         // tuning
  10,                    // cq_level
  0,                     // rc_max_intra_bitrate_pct
  0,                     // rc_max_inter_bitrate_pct
  0,                     // gf_cbr_boost_pct
  0,                     // lossless
  255,                   // target_level
  1,                     // frame_parallel_decoding_mode
  NO_AQ,                 // aq_mode
  0,                     // alt_ref_aq
  0,                     // frame_periodic_delta_q
  VPX_BITS_8,            // Bit depth
  VP9E_CONTENT_DEFAULT,  // content
  VPX_CS_UNKNOWN,        // color space
  0,                     // color range
  0,                     // render width
  0,                     // render height
  0,                     // row_mt
  0,                     // motion_vector_unit_test
  0,                     // delta_q_uv
};

struct vpx_codec_alg_priv {
  vpx_codec_priv_t base;
  vpx_codec_enc_cfg_t cfg;
  struct vp9_extracfg extra_cfg;
  vpx_codec_pts_t pts_offset;
  unsigned char pts_offset_initialized;
  VP9EncoderConfig oxcf;
  VP9_COMP *cpi;
  unsigned char *cx_data;
  size_t cx_data_sz;
  unsigned char *pending_cx_data;
  size_t pending_cx_data_sz;
  int pending_frame_count;
  size_t pending_frame_sizes[8];
  size_t pending_frame_magnitude;
  vpx_image_t preview_img;
  vpx_enc_frame_flags_t next_frame_flags;
  vp8_postproc_cfg_t preview_ppcfg;
  vpx_codec_pkt_list_decl(256) pkt_list;
  unsigned int fixed_kf_cntr;
  vpx_codec_priv_output_cx_pkt_cb_pair_t output_cx_pkt_cb;
  // BufferPool that holds all reference frames.
  BufferPool *buffer_pool;
  vpx_fixed_buf_t global_headers;
  int global_header_subsampling;
};

// Called by encoder_set_config() and encoder_encode() only. Must not be called
// by encoder_init() because the `error` paramerer (cpi->common.error) will be
// destroyed by vpx_codec_enc_init_ver() after encoder_init() returns an error.
// See the "IMPORTANT" comment in vpx_codec_enc_init_ver().
static vpx_codec_err_t update_error_state(
    vpx_codec_alg_priv_t *ctx, const struct vpx_internal_error_info *error) {
  const vpx_codec_err_t res = error->error_code;

  if (res != VPX_CODEC_OK)
    ctx->base.err_detail = error->has_detail ? error->detail : NULL;

  return res;
}

#undef ERROR
#define ERROR(str)                  \
  do {                              \
    ctx->base.err_detail = str;     \
    return VPX_CODEC_INVALID_PARAM; \
  } while (0)

#define RANGE_CHECK(p, memb, lo, hi)                                     \
  do {                                                                   \
    if (!(((p)->memb == (lo) || (p)->memb > (lo)) && (p)->memb <= (hi))) \
      ERROR(#memb " out of range [" #lo ".." #hi "]");                   \
  } while (0)

#define RANGE_CHECK_HI(p, memb, hi)                                     \
  do {                                                                  \
    if (!((p)->memb <= (hi))) ERROR(#memb " out of range [.." #hi "]"); \
  } while (0)

#define RANGE_CHECK_LO(p, memb, lo)                                     \
  do {                                                                  \
    if (!((p)->memb >= (lo))) ERROR(#memb " out of range [" #lo "..]"); \
  } while (0)

#define RANGE_CHECK_BOOL(p, memb)                                     \
  do {                                                                \
    if (!!((p)->memb) != (p)->memb) ERROR(#memb " expected boolean"); \
  } while (0)

static vpx_codec_err_t validate_config(vpx_codec_alg_priv_t *ctx,
                                       const vpx_codec_enc_cfg_t *cfg,
                                       const struct vp9_extracfg *extra_cfg) {
  RANGE_CHECK(cfg, g_w, 1, 65536);  // 16 bits available
  RANGE_CHECK(cfg, g_h, 1, 65536);  // 16 bits available
  RANGE_CHECK(cfg, g_timebase.den, 1, 1000000000);
  RANGE_CHECK(cfg, g_timebase.num, 1, 1000000000);
  RANGE_CHECK_HI(cfg, g_profile, 3);

  RANGE_CHECK_HI(cfg, rc_max_quantizer, 63);
  RANGE_CHECK_HI(cfg, rc_min_quantizer, cfg->rc_max_quantizer);
  RANGE_CHECK_BOOL(extra_cfg, lossless);
  RANGE_CHECK_BOOL(extra_cfg, frame_parallel_decoding_mode);
  RANGE_CHECK(extra_cfg, aq_mode, 0, AQ_MODE_COUNT - 2);
  RANGE_CHECK(extra_cfg, alt_ref_aq, 0, 1);
  RANGE_CHECK(extra_cfg, frame_periodic_boost, 0, 1);
  RANGE_CHECK_HI(cfg, g_threads, MAX_NUM_THREADS);
  RANGE_CHECK_HI(cfg, g_lag_in_frames, MAX_LAG_BUFFERS);
  RANGE_CHECK(cfg, rc_end_usage, VPX_VBR, VPX_Q);
  RANGE_CHECK_HI(cfg, rc_undershoot_pct, 100);
  RANGE_CHECK_HI(cfg, rc_overshoot_pct, 100);
  RANGE_CHECK_HI(cfg, rc_2pass_vbr_bias_pct, 100);
  RANGE_CHECK(cfg, rc_2pass_vbr_corpus_complexity, 0, 10000);
  RANGE_CHECK(cfg, kf_mode, VPX_KF_DISABLED, VPX_KF_AUTO);
  RANGE_CHECK_BOOL(cfg, rc_resize_allowed);
  RANGE_CHECK_HI(cfg, rc_dropframe_thresh, 100);
  RANGE_CHECK_HI(cfg, rc_resize_up_thresh, 100);
  RANGE_CHECK_HI(cfg, rc_resize_down_thresh, 100);
#if CONFIG_REALTIME_ONLY
  RANGE_CHECK(cfg, g_pass, VPX_RC_ONE_PASS, VPX_RC_ONE_PASS);
#else
  RANGE_CHECK(cfg, g_pass, VPX_RC_ONE_PASS, VPX_RC_LAST_PASS);
#endif
  RANGE_CHECK(extra_cfg, min_gf_interval, 0, (MAX_LAG_BUFFERS - 1));
  RANGE_CHECK(extra_cfg, max_gf_interval, 0, (MAX_LAG_BUFFERS - 1));
  if (extra_cfg->max_gf_interval > 0) {
    RANGE_CHECK(extra_cfg, max_gf_interval, 2, (MAX_LAG_BUFFERS - 1));
  }
  if (extra_cfg->min_gf_interval > 0 && extra_cfg->max_gf_interval > 0) {
    RANGE_CHECK(extra_cfg, max_gf_interval, extra_cfg->min_gf_interval,
                (MAX_LAG_BUFFERS - 1));
  }

  // For formation of valid ARF groups lag_in _frames should be 0 or greater
  // than the max_gf_interval + 2
  if (cfg->g_lag_in_frames > 0 && extra_cfg->max_gf_interval > 0 &&
      cfg->g_lag_in_frames < extra_cfg->max_gf_interval + 2) {
    ERROR("Set lag in frames to 0 (low delay) or >= (max-gf-interval + 2)");
  }

  if (cfg->rc_resize_allowed == 1) {
    RANGE_CHECK(cfg, rc_scaled_width, 0, cfg->g_w);
    RANGE_CHECK(cfg, rc_scaled_height, 0, cfg->g_h);
  }

  RANGE_CHECK(cfg, ss_number_layers, 1, VPX_SS_MAX_LAYERS);
  RANGE_CHECK(cfg, ts_number_layers, 1, VPX_TS_MAX_LAYERS);

  {
    unsigned int level = extra_cfg->target_level;
    if (level != LEVEL_1 && level != LEVEL_1_1 && level != LEVEL_2 &&
        level != LEVEL_2_1 && level != LEVEL_3 && level != LEVEL_3_1 &&
        level != LEVEL_4 && level != LEVEL_4_1 && level != LEVEL_5 &&
        level != LEVEL_5_1 && level != LEVEL_5_2 && level != LEVEL_6 &&
        level != LEVEL_6_1 && level != LEVEL_6_2 && level != LEVEL_UNKNOWN &&
        level != LEVEL_AUTO && level != LEVEL_MAX)
      ERROR("target_level is invalid");
  }

  if (cfg->ss_number_layers * cfg->ts_number_layers > VPX_MAX_LAYERS)
    ERROR("ss_number_layers * ts_number_layers is out of range");
  if (cfg->ts_number_layers > 1) {
    unsigned int sl, tl;
    for (sl = 1; sl < cfg->ss_number_layers; ++sl) {
      for (tl = 1; tl < cfg->ts_number_layers; ++tl) {
        const int layer = LAYER_IDS_TO_IDX(sl, tl, cfg->ts_number_layers);
        if (cfg->layer_target_bitrate[layer] <
            cfg->layer_target_bitrate[layer - 1])
          ERROR("ts_target_bitrate entries are not increasing");
      }
    }

    RANGE_CHECK(cfg, ts_rate_decimator[cfg->ts_number_layers - 1], 1, 1);
    for (tl = cfg->ts_number_layers - 2; tl > 0; --tl)
      if (cfg->ts_rate_decimator[tl - 1] != 2 * cfg->ts_rate_decimator[tl])
        ERROR("ts_rate_decimator factors are not powers of 2");
  }

  // VP9 does not support a lower bound on the keyframe interval in
  // automatic keyframe placement mode.
  if (cfg->kf_mode != VPX_KF_DISABLED && cfg->kf_min_dist != cfg->kf_max_dist &&
      cfg->kf_min_dist > 0)
    ERROR(
        "kf_min_dist not supported in auto mode, use 0 "
        "or kf_max_dist instead.");

  RANGE_CHECK(extra_cfg, row_mt, 0, 1);
  RANGE_CHECK(extra_cfg, motion_vector_unit_test, 0, 2);
  RANGE_CHECK(extra_cfg, enable_auto_alt_ref, 0, MAX_ARF_LAYERS);
  RANGE_CHECK(extra_cfg, cpu_used, -9, 9);
  RANGE_CHECK_HI(extra_cfg, noise_sensitivity, 6);
  RANGE_CHECK(extra_cfg, tile_columns, 0, 6);
  RANGE_CHECK(extra_cfg, tile_rows, 0, 2);
  RANGE_CHECK_HI(extra_cfg, sharpness, 7);
  RANGE_CHECK(extra_cfg, arnr_max_frames, 0, 15);
  RANGE_CHECK_HI(extra_cfg, arnr_strength, 6);
  RANGE_CHECK(extra_cfg, cq_level, 0, 63);
  RANGE_CHECK(cfg, g_bit_depth, VPX_BITS_8, VPX_BITS_12);
  RANGE_CHECK(cfg, g_input_bit_depth, 8, 12);
  RANGE_CHECK(extra_cfg, content, VP9E_CONTENT_DEFAULT,
              VP9E_CONTENT_INVALID - 1);

#if !CONFIG_REALTIME_ONLY
  if (cfg->g_pass == VPX_RC_LAST_PASS) {
    const size_t packet_sz = sizeof(FIRSTPASS_STATS);
    const int n_packets = (int)(cfg->rc_twopass_stats_in.sz / packet_sz);
    const FIRSTPASS_STATS *stats;

    if (cfg->rc_twopass_stats_in.buf == NULL)
      ERROR("rc_twopass_stats_in.buf not set.");

    if (cfg->rc_twopass_stats_in.sz % packet_sz)
      ERROR("rc_twopass_stats_in.sz indicates truncated packet.");

    if (cfg->ss_number_layers > 1 || cfg->ts_number_layers > 1) {
      int i;
      unsigned int n_packets_per_layer[VPX_SS_MAX_LAYERS] = { 0 };

      stats = cfg->rc_twopass_stats_in.buf;
      for (i = 0; i < n_packets; ++i) {
        const int layer_id = (int)stats[i].spatial_layer_id;
        if (layer_id >= 0 && layer_id < (int)cfg->ss_number_layers) {
          ++n_packets_per_layer[layer_id];
        }
      }

      for (i = 0; i < (int)cfg->ss_number_layers; ++i) {
        unsigned int layer_id;
        if (n_packets_per_layer[i] < 2) {
          ERROR(
              "rc_twopass_stats_in requires at least two packets for each "
              "layer.");
        }

        stats = (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf +
                n_packets - cfg->ss_number_layers + i;
        layer_id = (int)stats->spatial_layer_id;

        if (layer_id >= cfg->ss_number_layers ||
            (unsigned int)(stats->count + 0.5) !=
                n_packets_per_layer[layer_id] - 1)
          ERROR("rc_twopass_stats_in missing EOS stats packet");
      }
    } else {
      if (cfg->rc_twopass_stats_in.sz < 2 * packet_sz)
        ERROR("rc_twopass_stats_in requires at least two packets.");

      stats =
          (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf + n_packets - 1;

      if ((int)(stats->count + 0.5) != n_packets - 1)
        ERROR("rc_twopass_stats_in missing EOS stats packet");
    }
  }
#endif  // !CONFIG_REALTIME_ONLY

#if !CONFIG_VP9_HIGHBITDEPTH
  if (cfg->g_profile > (unsigned int)PROFILE_1) {
    ERROR("Profile > 1 not supported in this build configuration");
  }
#endif
  if (cfg->g_profile <= (unsigned int)PROFILE_1 &&
      cfg->g_bit_depth > VPX_BITS_8) {
    ERROR("Codec high bit-depth not supported in profile < 2");
  }
  if (cfg->g_profile <= (unsigned int)PROFILE_1 && cfg->g_input_bit_depth > 8) {
    ERROR("Source high bit-depth not supported in profile < 2");
  }
  if (cfg->g_profile > (unsigned int)PROFILE_1 &&
      cfg->g_bit_depth == VPX_BITS_8) {
    ERROR("Codec bit-depth 8 not supported in profile > 1");
  }
  RANGE_CHECK(extra_cfg, color_space, VPX_CS_UNKNOWN, VPX_CS_SRGB);
  RANGE_CHECK(extra_cfg, color_range, VPX_CR_STUDIO_RANGE, VPX_CR_FULL_RANGE);

  // The range below shall be further tuned.
  RANGE_CHECK(cfg, use_vizier_rc_params, 0, 1);
  RANGE_CHECK(cfg, active_wq_factor.den, 1, 1000);
  RANGE_CHECK(cfg, err_per_mb_factor.den, 1, 1000);
  RANGE_CHECK(cfg, sr_default_decay_limit.den, 1, 1000);
  RANGE_CHECK(cfg, sr_diff_factor.den, 1, 1000);
  RANGE_CHECK(cfg, kf_err_per_mb_factor.den, 1, 1000);
  RANGE_CHECK(cfg, kf_frame_min_boost_factor.den, 1, 1000);
  RANGE_CHECK(cfg, kf_frame_max_boost_subs_factor.den, 1, 1000);
  RANGE_CHECK(cfg, kf_max_total_boost_factor.den, 1, 1000);
  RANGE_CHECK(cfg, gf_max_total_boost_factor.den, 1, 1000);
  RANGE_CHECK(cfg, gf_frame_max_boost_factor.den, 1, 1000);
  RANGE_CHECK(cfg, zm_factor.den, 1, 1000);
  RANGE_CHECK(cfg, rd_mult_inter_qp_fac.den, 1, 1000);
  RANGE_CHECK(cfg, rd_mult_arf_qp_fac.den, 1, 1000);
  RANGE_CHECK(cfg, rd_mult_key_qp_fac.den, 1, 1000);

  return VPX_CODEC_OK;
}

static vpx_codec_err_t validate_img(vpx_codec_alg_priv_t *ctx,
                                    const vpx_image_t *img) {
  switch (img->fmt) {
    case VPX_IMG_FMT_YV12:
    case VPX_IMG_FMT_I420:
    case VPX_IMG_FMT_I42016:
    case VPX_IMG_FMT_NV12: break;
    case VPX_IMG_FMT_I422:
    case VPX_IMG_FMT_I444:
    case VPX_IMG_FMT_I440:
      if (ctx->cfg.g_profile != (unsigned int)PROFILE_1) {
        ERROR(
            "Invalid image format. I422, I444, I440 images are not supported "
            "in profile.");
      }
      break;
    case VPX_IMG_FMT_I42216:
    case VPX_IMG_FMT_I44416:
    case VPX_IMG_FMT_I44016:
      if (ctx->cfg.g_profile != (unsigned int)PROFILE_1 &&
          ctx->cfg.g_profile != (unsigned int)PROFILE_3) {
        ERROR(
            "Invalid image format. 16-bit I422, I444, I440 images are "
            "not supported in profile.");
      }
      break;
    default:
      ERROR(
          "Invalid image format. Only YV12, I420, I422, I444, I440, NV12 "
          "images are supported.");
      break;
  }

  if (img->d_w != ctx->cfg.g_w || img->d_h != ctx->cfg.g_h)
    ERROR("Image size must match encoder init configuration size");

  return VPX_CODEC_OK;
}

static int get_image_bps(const vpx_image_t *img) {
  switch (img->fmt) {
    case VPX_IMG_FMT_YV12:
    case VPX_IMG_FMT_NV12:
    case VPX_IMG_FMT_I420: return 12;
    case VPX_IMG_FMT_I422: return 16;
    case VPX_IMG_FMT_I444: return 24;
    case VPX_IMG_FMT_I440: return 16;
    case VPX_IMG_FMT_I42016: return 24;
    case VPX_IMG_FMT_I42216: return 32;
    case VPX_IMG_FMT_I44416: return 48;
    case VPX_IMG_FMT_I44016: return 32;
    default: assert(0 && "Invalid image format"); break;
  }
  return 0;
}

// Modify the encoder config for the target level.
static void config_target_level(VP9EncoderConfig *oxcf) {
  double max_average_bitrate;  // in bits per second
  int max_over_shoot_pct;
  const int target_level_index = get_level_index(oxcf->target_level);

  vpx_clear_system_state();
  assert(target_level_index >= 0);
  assert(target_level_index < VP9_LEVELS);

  // Maximum target bit-rate is level_limit * 80%.
  max_average_bitrate =
      vp9_level_defs[target_level_index].average_bitrate * 800.0;
  if ((double)oxcf->target_bandwidth > max_average_bitrate)
    oxcf->target_bandwidth = (int64_t)(max_average_bitrate);
  if (oxcf->ss_number_layers == 1 && oxcf->pass != 0)
    oxcf->ss_target_bitrate[0] = (int)oxcf->target_bandwidth;

  // Adjust max over-shoot percentage.
  max_over_shoot_pct =
      (int)((max_average_bitrate * 1.10 - (double)oxcf->target_bandwidth) *
            100 / (double)(oxcf->target_bandwidth));
  if (oxcf->over_shoot_pct > max_over_shoot_pct)
    oxcf->over_shoot_pct = max_over_shoot_pct;

  // Adjust worst allowed quantizer.
  oxcf->worst_allowed_q = vp9_quantizer_to_qindex(63);

  // Adjust minimum art-ref distance.
  // min_gf_interval should be no less than min_altref_distance + 1,
  // as the encoder may produce bitstream with alt-ref distance being
  // min_gf_interval - 1.
  if (oxcf->min_gf_interval <=
      (int)vp9_level_defs[target_level_index].min_altref_distance) {
    oxcf->min_gf_interval =
        (int)vp9_level_defs[target_level_index].min_altref_distance + 1;
    // If oxcf->max_gf_interval == 0, it will be assigned with a default value
    // in vp9_rc_set_gf_interval_range().
    if (oxcf->max_gf_interval != 0) {
      oxcf->max_gf_interval =
          VPXMAX(oxcf->max_gf_interval, oxcf->min_gf_interval);
    }
  }

  // Adjust maximum column tiles.
  if (vp9_level_defs[target_level_index].max_col_tiles <
      (1 << oxcf->tile_columns)) {
    while (oxcf->tile_columns > 0 &&
           vp9_level_defs[target_level_index].max_col_tiles <
               (1 << oxcf->tile_columns))
      --oxcf->tile_columns;
  }
}

static vpx_rational64_t get_g_timebase_in_ts(vpx_rational_t g_timebase) {
  vpx_rational64_t g_timebase_in_ts;
  g_timebase_in_ts.den = g_timebase.den;
  g_timebase_in_ts.num = g_timebase.num;
  g_timebase_in_ts.num *= TICKS_PER_SEC;
  reduce_ratio(&g_timebase_in_ts);
  return g_timebase_in_ts;
}

static vpx_codec_err_t set_encoder_config(
    VP9EncoderConfig *oxcf, vpx_codec_enc_cfg_t *cfg,
    const struct vp9_extracfg *extra_cfg) {
  const int is_vbr = cfg->rc_end_usage == VPX_VBR;
  int sl, tl;
  unsigned int raw_target_rate;
  oxcf->profile = cfg->g_profile;
  oxcf->max_threads = (int)cfg->g_threads;
  oxcf->width = cfg->g_w;
  oxcf->height = cfg->g_h;
  oxcf->bit_depth = cfg->g_bit_depth;
  oxcf->input_bit_depth = cfg->g_input_bit_depth;
  // TODO(angiebird): Figure out if we can just use g_timebase to indicate the
  // inverse of framerate
  // guess a frame rate if out of whack, use 30
  oxcf->init_framerate = (double)cfg->g_timebase.den / cfg->g_timebase.num;
  if (oxcf->init_framerate > 180) oxcf->init_framerate = 30;
  oxcf->g_timebase = cfg->g_timebase;
  oxcf->g_timebase_in_ts = get_g_timebase_in_ts(oxcf->g_timebase);

  oxcf->mode = GOOD;

  switch (cfg->g_pass) {
    case VPX_RC_ONE_PASS: oxcf->pass = 0; break;
    case VPX_RC_FIRST_PASS: oxcf->pass = 1; break;
    case VPX_RC_LAST_PASS: oxcf->pass = 2; break;
  }

  oxcf->lag_in_frames =
      cfg->g_pass == VPX_RC_FIRST_PASS ? 0 : cfg->g_lag_in_frames;
  oxcf->rc_mode = cfg->rc_end_usage;

  raw_target_rate =
      (unsigned int)((int64_t)oxcf->width * oxcf->height * oxcf->bit_depth * 3 *
                     oxcf->init_framerate / 1000);
  // Cap target bitrate to raw rate or 1000Mbps, whichever is less
  cfg->rc_target_bitrate =
      VPXMIN(VPXMIN(raw_target_rate, cfg->rc_target_bitrate), 1000000);

  // Convert target bandwidth from Kbit/s to Bit/s
  oxcf->target_bandwidth = 1000 * (int64_t)cfg->rc_target_bitrate;
  oxcf->rc_max_intra_bitrate_pct = extra_cfg->rc_max_intra_bitrate_pct;
  oxcf->rc_max_inter_bitrate_pct = extra_cfg->rc_max_inter_bitrate_pct;
  oxcf->gf_cbr_boost_pct = extra_cfg->gf_cbr_boost_pct;

  oxcf->best_allowed_q =
      extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_min_quantizer);
  oxcf->worst_allowed_q =
      extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_max_quantizer);
  oxcf->cq_level = vp9_quantizer_to_qindex(extra_cfg->cq_level);
  oxcf->fixed_q = -1;

  oxcf->under_shoot_pct = cfg->rc_undershoot_pct;
  oxcf->over_shoot_pct = cfg->rc_overshoot_pct;

  oxcf->scaled_frame_width = cfg->rc_scaled_width;
  oxcf->scaled_frame_height = cfg->rc_scaled_height;
  if (cfg->rc_resize_allowed == 1) {
    oxcf->resize_mode =
        (oxcf->scaled_frame_width == 0 || oxcf->scaled_frame_height == 0)
            ? RESIZE_DYNAMIC
            : RESIZE_FIXED;
  } else {
    oxcf->resize_mode = RESIZE_NONE;
  }

  oxcf->maximum_buffer_size_ms = is_vbr ? 240000 : cfg->rc_buf_sz;
  oxcf->starting_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_initial_sz;
  oxcf->optimal_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_optimal_sz;

  oxcf->drop_frames_water_mark = cfg->rc_dropframe_thresh;

  oxcf->two_pass_vbrbias = cfg->rc_2pass_vbr_bias_pct;
  oxcf->two_pass_vbrmin_section = cfg->rc_2pass_vbr_minsection_pct;
  oxcf->two_pass_vbrmax_section = cfg->rc_2pass_vbr_maxsection_pct;
  oxcf->vbr_corpus_complexity = cfg->rc_2pass_vbr_corpus_complexity;

  oxcf->auto_key =
      cfg->kf_mode == VPX_KF_AUTO && cfg->kf_min_dist != cfg->kf_max_dist;

  oxcf->key_freq = cfg->kf_max_dist;

  oxcf->speed = abs(extra_cfg->cpu_used);
  oxcf->encode_breakout = extra_cfg->static_thresh;
  oxcf->enable_auto_arf = extra_cfg->enable_auto_alt_ref;
  if (oxcf->bit_depth == VPX_BITS_8) {
    oxcf->noise_sensitivity = extra_cfg->noise_sensitivity;
  } else {
    // Disable denoiser for high bitdepth since vp9_denoiser_filter only works
    // for 8 bits.
    oxcf->noise_sensitivity = 0;
  }
  oxcf->sharpness = extra_cfg->sharpness;

  vp9_set_first_pass_stats(oxcf, &cfg->rc_twopass_stats_in);

  oxcf->color_space = extra_cfg->color_space;
  oxcf->color_range = extra_cfg->color_range;
  oxcf->render_width = extra_cfg->render_width;
  oxcf->render_height = extra_cfg->render_height;
  oxcf->arnr_max_frames = extra_cfg->arnr_max_frames;
  oxcf->arnr_strength = extra_cfg->arnr_strength;
  oxcf->min_gf_interval = extra_cfg->min_gf_interval;
  oxcf->max_gf_interval = extra_cfg->max_gf_interval;

  oxcf->tuning = extra_cfg->tuning;
  oxcf->content = extra_cfg->content;

  oxcf->tile_columns = extra_cfg->tile_columns;

  oxcf->enable_tpl_model = extra_cfg->enable_tpl_model;

  oxcf->enable_keyframe_filtering = extra_cfg->enable_keyframe_filtering;

  // TODO(yunqing): The dependencies between row tiles cause error in multi-
  // threaded encoding. For now, tile_rows is forced to be 0 in this case.
  // The further fix can be done by adding synchronizations after a tile row
  // is encoded. But this will hurt multi-threaded encoder performance. So,
  // it is recommended to use tile-rows=0 while encoding with threads > 1.
  if (oxcf->max_threads > 1 && oxcf->tile_columns > 0)
    oxcf->tile_rows = 0;
  else
    oxcf->tile_rows = extra_cfg->tile_rows;

  oxcf->error_resilient_mode = cfg->g_error_resilient;
  oxcf->frame_parallel_decoding_mode = extra_cfg->frame_parallel_decoding_mode;

  oxcf->aq_mode = extra_cfg->aq_mode;
  oxcf->alt_ref_aq = extra_cfg->alt_ref_aq;

  oxcf->frame_periodic_boost = extra_cfg->frame_periodic_boost;

  oxcf->ss_number_layers = cfg->ss_number_layers;
  oxcf->ts_number_layers = cfg->ts_number_layers;
  oxcf->temporal_layering_mode =
      (enum vp9e_temporal_layering_mode)cfg->temporal_layering_mode;

  oxcf->target_level = extra_cfg->target_level;

  oxcf->row_mt = extra_cfg->row_mt;
  oxcf->motion_vector_unit_test = extra_cfg->motion_vector_unit_test;

  oxcf->delta_q_uv = extra_cfg->delta_q_uv;

  for (sl = 0; sl < oxcf->ss_number_layers; ++sl) {
    for (tl = 0; tl < oxcf->ts_number_layers; ++tl) {
      const int layer = sl * oxcf->ts_number_layers + tl;
      if (cfg->layer_target_bitrate[layer] > INT_MAX / 1000)
        oxcf->layer_target_bitrate[layer] = INT_MAX;
      else
        oxcf->layer_target_bitrate[layer] =
            1000 * cfg->layer_target_bitrate[layer];
    }
  }
  if (oxcf->ss_number_layers == 1 && oxcf->pass != 0) {
    oxcf->ss_target_bitrate[0] = (int)oxcf->target_bandwidth;
  }
  if (oxcf->ts_number_layers > 1) {
    for (tl = 0; tl < VPX_TS_MAX_LAYERS; ++tl) {
      oxcf->ts_rate_decimator[tl] =
          cfg->ts_rate_decimator[tl] ? cfg->ts_rate_decimator[tl] : 1;
    }
  } else if (oxcf->ts_number_layers == 1) {
    oxcf->ts_rate_decimator[0] = 1;
  }

  if (get_level_index(oxcf->target_level) >= 0) config_target_level(oxcf);
  oxcf->use_simple_encode_api = 0;
  // vp9_dump_encoder_config(oxcf, stderr);
  return VPX_CODEC_OK;
}

static vpx_codec_err_t set_twopass_params_from_config(
    const vpx_codec_enc_cfg_t *const cfg, struct VP9_COMP *cpi) {
  if (!cfg->use_vizier_rc_params) return VPX_CODEC_OK;
  if (cpi == NULL) return VPX_CODEC_ERROR;

  cpi->twopass.use_vizier_rc_params = cfg->use_vizier_rc_params;

  // The values set here are factors that will be applied to default values
  // to get the final value used in the two pass code. Hence 1.0 will
  // match the default behaviour when not using passed in values.
  // We also apply limits here to prevent the user from applying settings
  // that make no sense.
  cpi->twopass.active_wq_factor =
      (double)cfg->active_wq_factor.num / (double)cfg->active_wq_factor.den;
  if (cpi->twopass.active_wq_factor < 0.25)
    cpi->twopass.active_wq_factor = 0.25;
  else if (cpi->twopass.active_wq_factor > 16.0)
    cpi->twopass.active_wq_factor = 16.0;

  cpi->twopass.err_per_mb =
      (double)cfg->err_per_mb_factor.num / (double)cfg->err_per_mb_factor.den;
  if (cpi->twopass.err_per_mb < 0.25)
    cpi->twopass.err_per_mb = 0.25;
  else if (cpi->twopass.err_per_mb > 4.0)
    cpi->twopass.err_per_mb = 4.0;

  cpi->twopass.sr_default_decay_limit =
      (double)cfg->sr_default_decay_limit.num /
      (double)cfg->sr_default_decay_limit.den;
  if (cpi->twopass.sr_default_decay_limit < 0.25)
    cpi->twopass.sr_default_decay_limit = 0.25;
  // If the default changes this will need to change.
  else if (cpi->twopass.sr_default_decay_limit > 1.33)
    cpi->twopass.sr_default_decay_limit = 1.33;

  cpi->twopass.sr_diff_factor =
      (double)cfg->sr_diff_factor.num / (double)cfg->sr_diff_factor.den;
  if (cpi->twopass.sr_diff_factor < 0.25)
    cpi->twopass.sr_diff_factor = 0.25;
  else if (cpi->twopass.sr_diff_factor > 4.0)
    cpi->twopass.sr_diff_factor = 4.0;

  cpi->twopass.kf_err_per_mb = (double)cfg->kf_err_per_mb_factor.num /
                               (double)cfg->kf_err_per_mb_factor.den;
  if (cpi->twopass.kf_err_per_mb < 0.25)
    cpi->twopass.kf_err_per_mb = 0.25;
  else if (cpi->twopass.kf_err_per_mb > 4.0)
    cpi->twopass.kf_err_per_mb = 4.0;

  cpi->twopass.kf_frame_min_boost = (double)cfg->kf_frame_min_boost_factor.num /
                                    (double)cfg->kf_frame_min_boost_factor.den;
  if (cpi->twopass.kf_frame_min_boost < 0.25)
    cpi->twopass.kf_frame_min_boost = 0.25;
  else if (cpi->twopass.kf_frame_min_boost > 4.0)
    cpi->twopass.kf_frame_min_boost = 4.0;

  cpi->twopass.kf_frame_max_boost_first =
      (double)cfg->kf_frame_max_boost_first_factor.num /
      (double)cfg->kf_frame_max_boost_first_factor.den;
  if (cpi->twopass.kf_frame_max_boost_first < 0.25)
    cpi->twopass.kf_frame_max_boost_first = 0.25;
  else if (cpi->twopass.kf_frame_max_boost_first > 4.0)
    cpi->twopass.kf_frame_max_boost_first = 4.0;

  cpi->twopass.kf_frame_max_boost_subs =
      (double)cfg->kf_frame_max_boost_subs_factor.num /
      (double)cfg->kf_frame_max_boost_subs_factor.den;
  if (cpi->twopass.kf_frame_max_boost_subs < 0.25)
    cpi->twopass.kf_frame_max_boost_subs = 0.25;
  else if (cpi->twopass.kf_frame_max_boost_subs > 4.0)
    cpi->twopass.kf_frame_max_boost_subs = 4.0;

  cpi->twopass.kf_max_total_boost = (double)cfg->kf_max_total_boost_factor.num /
                                    (double)cfg->kf_max_total_boost_factor.den;
  if (cpi->twopass.kf_max_total_boost < 0.25)
    cpi->twopass.kf_max_total_boost = 0.25;
  else if (cpi->twopass.kf_max_total_boost > 4.0)
    cpi->twopass.kf_max_total_boost = 4.0;

  cpi->twopass.gf_max_total_boost = (double)cfg->gf_max_total_boost_factor.num /
                                    (double)cfg->gf_max_total_boost_factor.den;
  if (cpi->twopass.gf_max_total_boost < 0.25)
    cpi->twopass.gf_max_total_boost = 0.25;
  else if (cpi->twopass.gf_max_total_boost > 4.0)
    cpi->twopass.gf_max_total_boost = 4.0;

  cpi->twopass.gf_frame_max_boost = (double)cfg->gf_frame_max_boost_factor.num /
                                    (double)cfg->gf_frame_max_boost_factor.den;
  if (cpi->twopass.gf_frame_max_boost < 0.25)
    cpi->twopass.gf_frame_max_boost = 0.25;
  else if (cpi->twopass.gf_frame_max_boost > 4.0)
    cpi->twopass.gf_frame_max_boost = 4.0;

  cpi->twopass.zm_factor =
      (double)cfg->zm_factor.num / (double)cfg->zm_factor.den;
  if (cpi->twopass.zm_factor < 0.25)
    cpi->twopass.zm_factor = 0.25;
  else if (cpi->twopass.zm_factor > 2.0)
    cpi->twopass.zm_factor = 2.0;

  cpi->rd_ctrl.rd_mult_inter_qp_fac = (double)cfg->rd_mult_inter_qp_fac.num /
                                      (double)cfg->rd_mult_inter_qp_fac.den;
  if (cpi->rd_ctrl.rd_mult_inter_qp_fac < 0.25)
    cpi->rd_ctrl.rd_mult_inter_qp_fac = 0.25;
  else if (cpi->rd_ctrl.rd_mult_inter_qp_fac > 4.0)
    cpi->rd_ctrl.rd_mult_inter_qp_fac = 4.0;

  cpi->rd_ctrl.rd_mult_arf_qp_fac =
      (double)cfg->rd_mult_arf_qp_fac.num / (double)cfg->rd_mult_arf_qp_fac.den;
  if (cpi->rd_ctrl.rd_mult_arf_qp_fac < 0.25)
    cpi->rd_ctrl.rd_mult_arf_qp_fac = 0.25;
  else if (cpi->rd_ctrl.rd_mult_arf_qp_fac > 4.0)
    cpi->rd_ctrl.rd_mult_arf_qp_fac = 4.0;

  cpi->rd_ctrl.rd_mult_key_qp_fac =
      (double)cfg->rd_mult_key_qp_fac.num / (double)cfg->rd_mult_key_qp_fac.den;
  if (cpi->rd_ctrl.rd_mult_key_qp_fac < 0.25)
    cpi->rd_ctrl.rd_mult_key_qp_fac = 0.25;
  else if (cpi->rd_ctrl.rd_mult_key_qp_fac > 4.0)
    cpi->rd_ctrl.rd_mult_key_qp_fac = 4.0;

  return VPX_CODEC_OK;
}

static vpx_codec_err_t encoder_set_config(vpx_codec_alg_priv_t *ctx,
                                          const vpx_codec_enc_cfg_t *cfg) {
  vpx_codec_err_t res;
  volatile int force_key = 0;

  if (cfg->g_w != ctx->cfg.g_w || cfg->g_h != ctx->cfg.g_h) {
    if (cfg->g_lag_in_frames > 1 || cfg->g_pass != VPX_RC_ONE_PASS)
      ERROR("Cannot change width or height after initialization");
    // Note: function encoder_set_config() is allowed to be called multiple
    // times. However, when the original frame width or height is less than two
    // times of the new frame width or height, a forced key frame should be
    // used. To make sure the correct detection of a forced key frame, we need
    // to update the frame width and height only when the actual encoding is
    // performed. cpi->last_coded_width and cpi->last_coded_height are used to
    // track the actual coded frame size.
    if ((ctx->cpi->last_coded_width && ctx->cpi->last_coded_height &&
         !valid_ref_frame_size(ctx->cpi->last_coded_width,
                               ctx->cpi->last_coded_height, cfg->g_w,
                               cfg->g_h)) ||
        (ctx->cpi->initial_width && (int)cfg->g_w > ctx->cpi->initial_width) ||
        (ctx->cpi->initial_height &&
         (int)cfg->g_h > ctx->cpi->initial_height)) {
      force_key = 1;
    }
  }

  // Prevent increasing lag_in_frames. This check is stricter than it needs
  // to be -- the limit is not increasing past the first lag_in_frames
  // value, but we don't track the initial config, only the last successful
  // config.
  if (cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames)
    ERROR("Cannot increase lag_in_frames");

  res = validate_config(ctx, cfg, &ctx->extra_cfg);
  if (res != VPX_CODEC_OK) return res;

  if (setjmp(ctx->cpi->common.error.jmp)) {
    const vpx_codec_err_t codec_err =
        update_error_state(ctx, &ctx->cpi->common.error);
    ctx->cpi->common.error.setjmp = 0;
    vpx_clear_system_state();
    assert(codec_err != VPX_CODEC_OK);
    return codec_err;
  }
  ctx->cpi->common.error.setjmp = 1;

  ctx->cfg = *cfg;
  set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
  set_twopass_params_from_config(&ctx->cfg, ctx->cpi);
  // On profile change, request a key frame
  force_key |= ctx->cpi->common.profile != ctx->oxcf.profile;
  vp9_change_config(ctx->cpi, &ctx->oxcf);

  if (force_key) ctx->next_frame_flags |= VPX_EFLAG_FORCE_KF;

  ctx->cpi->common.error.setjmp = 0;
  return VPX_CODEC_OK;
}

static vpx_codec_err_t ctrl_get_quantizer(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
  *arg = vp9_get_quantizer(ctx->cpi);
  return VPX_CODEC_OK;
}

static vpx_codec_err_t ctrl_get_quantizer64(vpx_codec_alg_priv_t *ctx,
                                            va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
  *arg = vp9_qindex_to_quantizer(vp9_get_quantizer(ctx->cpi));
  return VPX_CODEC_OK;
}

static vpx_codec_err_t ctrl_get_quantizer_svc_layers(vpx_codec_alg_priv_t *ctx,
                                                     va_list args) {
  int *const arg = va_arg(args, int *);
  int i;
  if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
  for (i = 0; i < VPX_SS_MAX_LAYERS; i++) {
    arg[i] = ctx->cpi->svc.base_qindex[i];
  }
  return VPX_CODEC_OK;
}

static vpx_codec_err_t ctrl_get_loopfilter_level(vpx_codec_alg_priv_t *ctx,
                                                 va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
  *arg = ctx->cpi->common.lf.filter_level;
  return VPX_CODEC_OK;
}

static vpx_codec_err_t update_extra_cfg(vpx_codec_alg_priv_t *ctx,
                                        const struct vp9_extracfg *extra_cfg) {
  const vpx_codec_err_t res = validate_config(ctx, &ctx->cfg, extra_cfg);
  if (res == VPX_CODEC_OK) {
    ctx->extra_cfg = *extra_cfg;
    set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
    set_twopass_params_from_config(&ctx->cfg, ctx->cpi);
    vp9_change_config(ctx->cpi, &ctx->oxcf);
  }
  return res;
}

static vpx_codec_err_t ctrl_set_cpuused(vpx_codec_alg_priv_t *ctx,
                                        va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  // Use fastest speed setting (speed 9 or -9) if it's set beyond the range.
  extra_cfg.cpu_used = CAST(VP8E_SET_CPUUSED, args);
  extra_cfg.cpu_used = VPXMIN(9, extra_cfg.cpu_used);
  extra_cfg.cpu_used = VPXMAX(-9, extra_cfg.cpu_used);
#if CONFIG_REALTIME_ONLY
  if (extra_cfg.cpu_used > -5 && extra_cfg.cpu_used < 5)
    extra_cfg.cpu_used = (extra_cfg.cpu_used > 0) ? 5 : -5;
#endif
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_enable_auto_alt_ref(vpx_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_auto_alt_ref = CAST(VP8E_SET_ENABLEAUTOALTREF, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_noise_sensitivity(vpx_codec_alg_priv_t *ctx,
                                                  va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.noise_sensitivity = CAST(VP9E_SET_NOISE_SENSITIVITY, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_sharpness(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.sharpness = CAST(VP8E_SET_SHARPNESS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_static_thresh(vpx_codec_alg_priv_t *ctx,
                                              va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.static_thresh = CAST(VP8E_SET_STATIC_THRESHOLD, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_tile_columns(vpx_codec_alg_priv_t *ctx,
                                             va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.tile_columns = CAST(VP9E_SET_TILE_COLUMNS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_tile_rows(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.tile_rows = CAST(VP9E_SET_TILE_ROWS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_tpl_model(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_tpl_model = CAST(VP9E_SET_TPL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_keyframe_filtering(vpx_codec_alg_priv_t *ctx,
                                                   va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.enable_keyframe_filtering =
      CAST(VP9E_SET_KEY_FRAME_FILTERING, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_arnr_max_frames(vpx_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.arnr_max_frames = CAST(VP8E_SET_ARNR_MAXFRAMES, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_arnr_strength(vpx_codec_alg_priv_t *ctx,
                                              va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.arnr_strength = CAST(VP8E_SET_ARNR_STRENGTH, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_arnr_type(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
  (void)ctx;
  (void)args;
  return VPX_CODEC_OK;
}

static vpx_codec_err_t ctrl_set_tuning(vpx_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.tuning = CAST(VP8E_SET_TUNING, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_cq_level(vpx_codec_alg_priv_t *ctx,
                                         va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.cq_level = CAST(VP8E_SET_CQ_LEVEL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_rc_max_intra_bitrate_pct(
    vpx_codec_alg_priv_t *ctx, va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.rc_max_intra_bitrate_pct =
      CAST(VP8E_SET_MAX_INTRA_BITRATE_PCT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_rc_max_inter_bitrate_pct(
    vpx_codec_alg_priv_t *ctx, va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.rc_max_inter_bitrate_pct =
      CAST(VP9E_SET_MAX_INTER_BITRATE_PCT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_rc_gf_cbr_boost_pct(vpx_codec_alg_priv_t *ctx,
                                                    va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.gf_cbr_boost_pct = CAST(VP9E_SET_GF_CBR_BOOST_PCT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_lossless(vpx_codec_alg_priv_t *ctx,
                                         va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.lossless = CAST(VP9E_SET_LOSSLESS, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_frame_parallel_decoding_mode(
    vpx_codec_alg_priv_t *ctx, va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.frame_parallel_decoding_mode =
      CAST(VP9E_SET_FRAME_PARALLEL_DECODING, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_aq_mode(vpx_codec_alg_priv_t *ctx,
                                        va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.aq_mode = CAST(VP9E_SET_AQ_MODE, args);
  if (ctx->cpi->fixed_qp_onepass) extra_cfg.aq_mode = 0;
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_alt_ref_aq(vpx_codec_alg_priv_t *ctx,
                                           va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.alt_ref_aq = CAST(VP9E_SET_ALT_REF_AQ, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_min_gf_interval(vpx_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.min_gf_interval = CAST(VP9E_SET_MIN_GF_INTERVAL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_max_gf_interval(vpx_codec_alg_priv_t *ctx,
                                                va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.max_gf_interval = CAST(VP9E_SET_MAX_GF_INTERVAL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_frame_periodic_boost(vpx_codec_alg_priv_t *ctx,
                                                     va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.frame_periodic_boost = CAST(VP9E_SET_FRAME_PERIODIC_BOOST, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_target_level(vpx_codec_alg_priv_t *ctx,
                                             va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.target_level = CAST(VP9E_SET_TARGET_LEVEL, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_row_mt(vpx_codec_alg_priv_t *ctx,
                                       va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.row_mt = CAST(VP9E_SET_ROW_MT, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_set_rtc_external_ratectrl(vpx_codec_alg_priv_t *ctx,
                                                      va_list args) {
  VP9_COMP *const cpi = ctx->cpi;
  const unsigned int data = va_arg(args, unsigned int);
  if (data) {
    cpi->compute_frame_low_motion_onepass = 0;
    cpi->rc.constrain_gf_key_freq_onepass_vbr = 0;
    cpi->cyclic_refresh->content_mode = 0;
    cpi->disable_scene_detection_rtc_ratectrl = 1;
  }
  return VPX_CODEC_OK;
}

static vpx_codec_err_t ctrl_enable_motion_vector_unit_test(
    vpx_codec_alg_priv_t *ctx, va_list args) {
  struct vp9_extracfg extra_cfg = ctx->extra_cfg;
  extra_cfg.motion_vector_unit_test =
      CAST(VP9E_ENABLE_MOTION_VECTOR_UNIT_TEST, args);
  return update_extra_cfg(ctx, &extra_cfg);
}

static vpx_codec_err_t ctrl_get_level(vpx_codec_alg_priv_t *ctx, va_list args) {
  int *const arg = va_arg(args, int *);
  if (arg == NULL) return VPX_CODEC_INVALID_PARAM;
  *arg = (int)vp9_get_level(&ctx->cpi->level_info.level_spec);
  return VPX_CODEC_OK;
}

static vpx_codec_err_t encoder_init(vpx_codec_ctx_t *ctx,
                                    vpx_codec_priv_enc_mr_cfg_t *data) {
  vpx_codec_err_t res = VPX_CODEC_OK;
  (void)data;

  if (ctx->priv == NULL) {
    vpx_codec_alg_priv_t *const priv = vpx_calloc(1, sizeof(*priv));
    if (priv == NULL) return VPX_CODEC_MEM_ERROR;

    ctx->priv = (vpx_codec_priv_t *)priv;
    ctx->priv->init_flags = ctx->init_flags;
    ctx->priv->enc.total_encoders = 1;
    priv->buffer_pool = (BufferPool *)vpx_calloc(1, sizeof(BufferPool));
    if (priv->buffer_pool == NULL) return VPX_CODEC_MEM_ERROR;

    if (ctx->config.enc) {
      // Update the reference to the config structure to an internal copy.
      priv->cfg = *ctx->config.enc;
      ctx->config.enc = &priv->cfg;
    }

    priv->extra_cfg = default_extra_cfg;
    vp9_initialize_enc();

    res = validate_config(priv, &priv->cfg, &priv->extra_cfg);

    if (res == VPX_CODEC_OK) {
      priv->pts_offset_initialized = 0;
      priv->global_header_subsampling = -1;
      set_encoder_config(&priv->oxcf, &priv->cfg, &priv->extra_cfg);
#if CONFIG_VP9_HIGHBITDEPTH
      priv->oxcf.use_highbitdepth =
          (ctx->init_flags & VPX_CODEC_USE_HIGHBITDEPTH) ? 1 : 0;
#endif
      priv->cpi = vp9_create_compressor(&priv->oxcf, priv->buffer_pool);
      if (priv->cpi == NULL) res = VPX_CODEC_MEM_ERROR;
      set_twopass_params_from_config(&priv->cfg, priv->cpi);
    }
  }

  return res;
}

static vpx_codec_err_t encoder_destroy(vpx_codec_alg_priv_t *ctx) {
  free(ctx->cx_data);
  free(ctx->global_headers.buf);
  vp9_remove_compressor(ctx->cpi);
  vpx_free(ctx->buffer_pool);
  vpx_free(ctx);
  return VPX_CODEC_OK;
}

static vpx_codec_err_t pick_quickcompress_mode(vpx_codec_alg_priv_t *ctx,
                                               unsigned long duration,
                                               vpx_enc_deadline_t deadline) {
  MODE new_mode = BEST;

#if CONFIG_REALTIME_ONLY
  (void)duration;
  deadline = VPX_DL_REALTIME;
#else
  switch (ctx->cfg.g_pass) {
    case VPX_RC_ONE_PASS:
      if (deadline > 0) {
        // Convert duration parameter from stream timebase to microseconds.
        VPX_STATIC_ASSERT(TICKS_PER_SEC > 1000000 &&
                          (TICKS_PER_SEC % 1000000) == 0);

        if (duration > UINT64_MAX / (uint64_t)ctx->oxcf.g_timebase_in_ts.num) {
          ERROR("duration is too big");
        }
        uint64_t duration_us = duration *
                               (uint64_t)ctx->oxcf.g_timebase_in_ts.num /
                               ((uint64_t)ctx->oxcf.g_timebase_in_ts.den *
                                (TICKS_PER_SEC / 1000000));

        // If the deadline is more that the duration this frame is to be shown,
        // use good quality mode. Otherwise use realtime mode.
        new_mode = (deadline > duration_us) ? GOOD : REALTIME;
      } else {
        new_mode = BEST;
      }
      break;
    case VPX_RC_FIRST_PASS: break;
    case VPX_RC_LAST_PASS: new_mode = deadline > 0 ? GOOD : BEST; break;
  }
#endif  // CONFIG_REALTIME_ONLY

  if (deadline == VPX_DL_REALTIME) {
    ctx->oxcf.pass = 0;
    new_mode = REALTIME;
  }

  if (ctx->oxcf.mode != new_mode) {
    ctx->oxcf.mode = new_mode;
    vp9_change_config(ctx->cpi, &ctx->oxcf);
  }
  return VPX_CODEC_OK;
}

// Turn on to test if supplemental superframe data breaks decoding
// #define TEST_SUPPLEMENTAL_SUPERFRAME_DATA
static int write_superframe_index(vpx_codec_alg_priv_t *ctx) {
  uint8_t marker = 0xc0;
  unsigned int mask;
  int mag, index_sz;

  assert(ctx->pending_frame_count);
  assert(ctx->pending_frame_count <= 8);

  // Add the number of frames to the marker byte
  marker |= ctx->pending_frame_count - 1;

  // Choose the magnitude
  for (mag = 0, mask = 0xff; mag < 4; mag++) {
    if (ctx->pending_frame_magnitude < mask) break;
    mask <<= 8;
    mask |= 0xff;
  }
  marker |= mag << 3;

  // Write the index
  index_sz = 2 + (mag + 1) * ctx->pending_frame_count;
  if (ctx->pending_cx_data_sz + index_sz < ctx->cx_data_sz) {
    uint8_t *x = ctx->pending_cx_data + ctx->pending_cx_data_sz;
    int i, j;
#ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
    uint8_t marker_test = 0xc0;
    int mag_test = 2;     // 1 - 4
    int frames_test = 4;  // 1 - 8
    int index_sz_test = 2 + mag_test * frames_test;
    marker_test |= frames_test - 1;
    marker_test |= (mag_test - 1) << 3;
    *x++ = marker_test;
    for (i = 0; i < mag_test * frames_test; ++i)
      *x++ = 0;  // fill up with arbitrary data
    *x++ = marker_test;
    ctx->pending_cx_data_sz += index_sz_test;
    printf("Added supplemental superframe data\n");
#endif

    *x++ = marker;
    for (i = 0; i < ctx->pending_frame_count; i++) {
      unsigned int this_sz = (unsigned int)ctx->pending_frame_sizes[i];

      for (j = 0; j <= mag; j++) {
        *x++ = this_sz & 0xff;
        this_sz >>= 8;
      }
    }
    *x++ = marker;
    ctx->pending_cx_data_sz += index_sz;
#ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
    index_sz += index_sz_test;
#endif
  }
  return index_sz;
}

static vpx_codec_frame_flags_t get_frame_pkt_flags(const VP9_COMP *cpi,
                                                   unsigned int lib_flags) {
  vpx_codec_frame_flags_t flags = lib_flags << 16;

  if (lib_flags & FRAMEFLAGS_KEY ||
      (cpi->use_svc && cpi->svc
                           .layer_context[cpi->svc.spatial_layer_id *
                                              cpi->svc.number_temporal_layers +
                                          cpi->svc.temporal_layer_id]
                           .is_key_frame))
    flags |= VPX_FRAME_IS_KEY;

  if (!cpi->common.show_frame) {
    flags |= VPX_FRAME_IS_INVISIBLE;
  }

  if (cpi->droppable) flags |= VPX_FRAME_IS_DROPPABLE;

  return flags;
}

static INLINE vpx_codec_cx_pkt_t get_psnr_pkt(const PSNR_STATS *psnr) {
  vpx_codec_cx_pkt_t pkt;
  pkt.kind = VPX_CODEC_PSNR_PKT;
  pkt.data.psnr = *psnr;
  return pkt;
}

#if !CONFIG_REALTIME_ONLY
static INLINE vpx_codec_cx_pkt_t
get_first_pass_stats_pkt(FIRSTPASS_STATS *stats) {
  // WARNNING: This function assumes that stats will
  // exist and not be changed until the packet is processed
  // TODO(angiebird): Refactor the code to avoid using the assumption.
  vpx_codec_cx_pkt_t pkt;
  pkt.kind = VPX_CODEC_STATS_PKT;
  pkt.data.twopass_stats.buf = stats;
  pkt.data.twopass_stats.sz = sizeof(*stats);
  return pkt;
}
#endif

const size_t kMinCompressedSize = 8192;
static vpx_codec_err_t encoder_encode(vpx_codec_alg_priv_t *ctx,
                                      const vpx_image_t *img,
                                      vpx_codec_pts_t pts_val,
                                      unsigned long duration,
                                      vpx_enc_frame_flags_t enc_flags,
                                      vpx_enc_deadline_t deadline) {
  volatile vpx_codec_err_t res = VPX_CODEC_OK;
  volatile vpx_enc_frame_flags_t flags = enc_flags;
  volatile vpx_codec_pts_t pts = pts_val;
  VP9_COMP *const cpi = ctx->cpi;
  const vpx_rational64_t *const timebase_in_ts = &ctx->oxcf.g_timebase_in_ts;
  size_t data_sz;
  vpx_codec_cx_pkt_t pkt;
  memset(&pkt, 0, sizeof(pkt));

  if (cpi == NULL) return VPX_CODEC_INVALID_PARAM;

  cpi->last_coded_width = ctx->oxcf.width;
  cpi->last_coded_height = ctx->oxcf.height;

  if (img != NULL) {
    res = validate_img(ctx, img);
    if (res == VPX_CODEC_OK) {
      // There's no codec control for multiple alt-refs so check the encoder
      // instance for its status to determine the compressed data size.
      data_sz = ctx->cfg.g_w * ctx->cfg.g_h * get_image_bps(img) / 8 *
                (cpi->multi_layer_arf ? 8 : 2);
      if (data_sz < kMinCompressedSize) data_sz = kMinCompressedSize;
      if (ctx->cx_data == NULL || ctx->cx_data_sz < data_sz) {
        ctx->cx_data_sz = data_sz;
        free(ctx->cx_data);
        ctx->cx_data = (unsigned char *)malloc(ctx->cx_data_sz);
        if (ctx->cx_data == NULL) {
          return VPX_CODEC_MEM_ERROR;
        }
      }

      int chroma_subsampling = -1;
      if ((img->fmt & VPX_IMG_FMT_I420) == VPX_IMG_FMT_I420 ||
          (img->fmt & VPX_IMG_FMT_NV12) == VPX_IMG_FMT_NV12 ||
          (img->fmt & VPX_IMG_FMT_YV12) == VPX_IMG_FMT_YV12) {
        chroma_subsampling = 1;  // matches default for Codec Parameter String
      } else if ((img->fmt & VPX_IMG_FMT_I422) == VPX_IMG_FMT_I422) {
        chroma_subsampling = 2;
      } else if ((img->fmt & VPX_IMG_FMT_I444) == VPX_IMG_FMT_I444) {
        chroma_subsampling = 3;
      }
      if (chroma_subsampling > ctx->global_header_subsampling) {
        ctx->global_header_subsampling = chroma_subsampling;
      }
    }
  }

  res = pick_quickcompress_mode(ctx, duration, deadline);
  if (res != VPX_CODEC_OK) {
    return res;
  }
  vpx_codec_pkt_list_init(&ctx->pkt_list);

  // Handle Flags
  if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF)) ||
      ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF))) {
    ctx->base.err_detail = "Conflicting flags.";
    return VPX_CODEC_INVALID_PARAM;
  }

  if (setjmp(cpi->common.error.jmp)) {
    cpi->common.error.setjmp = 0;
    res = update_error_state(ctx, &cpi->common.error);
    vpx_clear_system_state();
    return res;
  }
  cpi->common.error.setjmp = 1;

  if (res == VPX_CODEC_OK) vp9_apply_encoding_flags(cpi, flags);

  // Handle fixed keyframe intervals
  if (ctx->cfg.kf_mode == VPX_KF_AUTO &&
      ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist) {
    if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist) {
      flags |= VPX_EFLAG_FORCE_KF;
      ctx->fixed_kf_cntr = 1;
    }
  }

  if (res == VPX_CODEC_OK) {
    unsigned int lib_flags = 0;
    size_t size, cx_data_sz;
    unsigned char *cx_data;

    // Set up internal flags
    if (ctx->base.init_flags & VPX_CODEC_USE_PSNR) cpi->b_calculate_psnr = 1;

    if (img != NULL) {
      YV12_BUFFER_CONFIG sd;

      if (!ctx->pts_offset_initialized) {
        ctx->pts_offset = pts;
        ctx->pts_offset_initialized = 1;
      }
      if (pts < ctx->pts_offset) {
        vpx_internal_error(&cpi->common.error, VPX_CODEC_INVALID_PARAM,
                           "pts is smaller than initial pts");
      }
      pts -= ctx->pts_offset;
      if (pts > INT64_MAX / timebase_in_ts->num) {
        vpx_internal_error(
            &cpi->common.error, VPX_CODEC_INVALID_PARAM,
            "conversion of relative pts to ticks would overflow");
      }
      const int64_t dst_time_stamp =
          timebase_units_to_ticks(timebase_in_ts, pts);

      cpi->svc.timebase_fac = timebase_units_to_ticks(timebase_in_ts, 1);
      cpi->svc.time_stamp_superframe = dst_time_stamp;

#if ULONG_MAX > INT64_MAX
      if (duration > INT64_MAX) {
        vpx_internal_error(&cpi->common.error, VPX_CODEC_INVALID_PARAM,
                           "duration is too big");
      }
#endif
      if (pts > INT64_MAX - (int64_t)duration) {
        vpx_internal_error(&cpi->common.error, VPX_CODEC_INVALID_PARAM,
                           "relative pts + duration is too big");
      }
      vpx_codec_pts_t pts_end = pts + (int64_t)duration;
      if (pts_end > INT64_MAX / timebase_in_ts->num) {
        vpx_internal_error(
            &cpi->common.error, VPX_CODEC_INVALID_PARAM,
            "conversion of relative pts + duration to ticks would overflow");
      }
      const int64_t dst_end_time_stamp =
          timebase_units_to_ticks(timebase_in_ts, pts_end);
      res = image2yuvconfig(img, &sd);

      if (sd.y_width != ctx->cfg.g_w || sd.y_height != ctx->cfg.g_h) {
        /* from vpx_encoder.h for g_w/g_h:
           "Note that the frames passed as input to the encoder must have this
           resolution"
        */

        ctx->base.err_detail = "Invalid input frame resolution";
        res = VPX_CODEC_INVALID_PARAM;
      } else {
        // Store the original flags in to the frame buffer. Will extract the
        // key frame flag when we actually encode this frame.
        if (vp9_receive_raw_frame(cpi, flags | ctx->next_frame_flags, &sd,
                                dst_time_stamp, dst_end_time_stamp)) {
          res = update_error_state(ctx, &cpi->common.error);
        }
        ctx->next_frame_flags = 0;
      }
    }

    cx_data = ctx->cx_data;
    cx_data_sz = ctx->cx_data_sz;

    /* Any pending invisible frames? */
    if (ctx->pending_cx_data) {
      assert(cx_data_sz >= ctx->pending_cx_data_sz);
      memmove(cx_data, ctx->pending_cx_data, ctx->pending_cx_data_sz);
      ctx->pending_cx_data = cx_data;
      cx_data += ctx->pending_cx_data_sz;
      cx_data_sz -= ctx->pending_cx_data_sz;

      /* TODO(webm:1844): this is a minimal check, the underlying codec doesn't
       * respect the buffer size anyway.
       */

      if (cx_data_sz < ctx->cx_data_sz / 2) {
        vpx_internal_error(&cpi->common.error, VPX_CODEC_ERROR,
                           "Compressed data buffer too small");
      }
    }

    if (cpi->oxcf.pass == 1 && !cpi->use_svc) {
#if !CONFIG_REALTIME_ONLY
      // compute first pass stats
      if (img) {
        int ret;
        int64_t dst_time_stamp;
        int64_t dst_end_time_stamp;
        vpx_codec_cx_pkt_t fps_pkt;
        ENCODE_FRAME_RESULT encode_frame_result;
        vp9_init_encode_frame_result(&encode_frame_result);
        // TODO(angiebird): Call vp9_first_pass directly
        ret = vp9_get_compressed_data(
            cpi, &lib_flags, &size, cx_data, cx_data_sz, &dst_time_stamp,
            &dst_end_time_stamp, !img, &encode_frame_result);
        assert(size == 0);  // There is no compressed data in the first pass
        (void)ret;
        assert(ret == 0);
        fps_pkt = get_first_pass_stats_pkt(&cpi->twopass.this_frame_stats);
        vpx_codec_pkt_list_add(&ctx->pkt_list.head, &fps_pkt);
      } else {
        if (!cpi->twopass.first_pass_done) {
          vpx_codec_cx_pkt_t fps_pkt;
          vp9_end_first_pass(cpi);
          fps_pkt = get_first_pass_stats_pkt(&cpi->twopass.total_stats);
          vpx_codec_pkt_list_add(&ctx->pkt_list.head, &fps_pkt);
        }
      }
#else   // !CONFIG_REALTIME_ONLY
      assert(0);
#endif  // !CONFIG_REALTIME_ONLY
    } else {
      ENCODE_FRAME_RESULT encode_frame_result;
      int64_t dst_time_stamp;
      int64_t dst_end_time_stamp;
      vp9_init_encode_frame_result(&encode_frame_result);
      while (cx_data_sz >= ctx->cx_data_sz / 2 &&
             -1 != vp9_get_compressed_data(cpi, &lib_flags, &size, cx_data,
                                           cx_data_sz, &dst_time_stamp,
                                           &dst_end_time_stamp, !img,
                                           &encode_frame_result)) {
        // Pack psnr pkt
        if (size > 0 && !cpi->use_svc) {
          // TODO(angiebird): Figure out while we don't need psnr pkt when
          // use_svc is on
          PSNR_STATS psnr;
          if (vp9_get_psnr(cpi, &psnr)) {
            vpx_codec_cx_pkt_t psnr_pkt = get_psnr_pkt(&psnr);
            vpx_codec_pkt_list_add(&ctx->pkt_list.head, &psnr_pkt);
          }
        }

        if (size || (cpi->use_svc && cpi->svc.skip_enhancement_layer)) {
          // Pack invisible frames with the next visible frame
          if (!cpi->common.show_frame ||
              (cpi->use_svc && cpi->svc.spatial_layer_id <
                                   cpi->svc.number_spatial_layers - 1)) {
            if (ctx->pending_cx_data == NULL) ctx->pending_cx_data = cx_data;
            ctx->pending_cx_data_sz += size;
            if (size)
              ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
            ctx->pending_frame_magnitude |= size;
            cx_data += size;
            cx_data_sz -= size;
            pkt.data.frame.width[cpi->svc.spatial_layer_id] = cpi->common.width;
            pkt.data.frame.height[cpi->svc.spatial_layer_id] =
                cpi->common.height;
            pkt.data.frame.spatial_layer_encoded[cpi->svc.spatial_layer_id] =
                1 - cpi->svc.drop_spatial_layer[cpi->svc.spatial_layer_id];

            if (ctx->output_cx_pkt_cb.output_cx_pkt) {
              pkt.kind = VPX_CODEC_CX_FRAME_PKT;
              pkt.data.frame.pts =
                  ticks_to_timebase_units(timebase_in_ts, dst_time_stamp) +
                  ctx->pts_offset;
              pkt.data.frame.duration = (unsigned long)ticks_to_timebase_units(
                  timebase_in_ts, dst_end_time_stamp - dst_time_stamp);
              pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
              pkt.data.frame.buf = ctx->pending_cx_data;
              pkt.data.frame.sz = size;
              ctx->pending_cx_data = NULL;
              ctx->pending_cx_data_sz = 0;
              ctx->pending_frame_count = 0;
              ctx->pending_frame_magnitude = 0;
              ctx->output_cx_pkt_cb.output_cx_pkt(
                  &pkt, ctx->output_cx_pkt_cb.user_priv);
            }
            continue;
          }

          // Add the frame packet to the list of returned packets.
          pkt.kind = VPX_CODEC_CX_FRAME_PKT;
          pkt.data.frame.pts =
              ticks_to_timebase_units(timebase_in_ts, dst_time_stamp) +
              ctx->pts_offset;
          pkt.data.frame.duration = (unsigned long)ticks_to_timebase_units(
              timebase_in_ts, dst_end_time_stamp - dst_time_stamp);
          pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
          pkt.data.frame.width[cpi->svc.spatial_layer_id] = cpi->common.width;
          pkt.data.frame.height[cpi->svc.spatial_layer_id] = cpi->common.height;
          pkt.data.frame.spatial_layer_encoded[cpi->svc.spatial_layer_id] =
              1 - cpi->svc.drop_spatial_layer[cpi->svc.spatial_layer_id];

          if (ctx->pending_cx_data) {
            if (size)
              ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
            ctx->pending_frame_magnitude |= size;
            ctx->pending_cx_data_sz += size;
            // write the superframe only for the case when
            if (!ctx->output_cx_pkt_cb.output_cx_pkt)
              size += write_superframe_index(ctx);
            pkt.data.frame.buf = ctx->pending_cx_data;
            pkt.data.frame.sz = ctx->pending_cx_data_sz;
            ctx->pending_cx_data = NULL;
            ctx->pending_cx_data_sz = 0;
            ctx->pending_frame_count = 0;
            ctx->pending_frame_magnitude = 0;
          } else {
            pkt.data.frame.buf = cx_data;
            pkt.data.frame.sz = size;
          }
          pkt.data.frame.partition_id = -1;

          if (ctx->output_cx_pkt_cb.output_cx_pkt)
            ctx->output_cx_pkt_cb.output_cx_pkt(
                &pkt, ctx->output_cx_pkt_cb.user_priv);
          else
            vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);

          cx_data += size;
          cx_data_sz -= size;
          if (is_one_pass_svc(cpi) && (cpi->svc.spatial_layer_id ==
                                       cpi->svc.number_spatial_layers - 1)) {
            // Encoded all spatial layers; exit loop.
            break;
          }
        }
      }
    }
  }

  cpi->common.error.setjmp = 0;
  return res;
}

static const vpx_codec_cx_pkt_t *encoder_get_cxdata(vpx_codec_alg_priv_t *ctx,
                                                    vpx_codec_iter_t *iter) {
  return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
}

static vpx_codec_err_t ctrl_set_reference(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
  vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);

  if (frame != NULL) {
    YV12_BUFFER_CONFIG sd;

    image2yuvconfig(&frame->img, &sd);
    vp9_set_reference_enc(ctx->cpi, ref_frame_to_vp9_reframe(frame->frame_type),
                          &sd);
    return VPX_CODEC_OK;
  }
  return VPX_CODEC_INVALID_PARAM;
}

static vpx_codec_err_t ctrl_copy_reference(vpx_codec_alg_priv_t *ctx,
                                           va_list args) {
  vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);

  if (frame != NULL) {
    YV12_BUFFER_CONFIG sd;

    image2yuvconfig(&frame->img, &sd);
    vp9_copy_reference_enc(ctx->cpi,
                           ref_frame_to_vp9_reframe(frame->frame_type), &sd);
    return VPX_CODEC_OK;
  }
  return VPX_CODEC_INVALID_PARAM;
}

static vpx_codec_err_t ctrl_get_reference(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
  vp9_ref_frame_t *const frame = va_arg(args, vp9_ref_frame_t *);

  if (frame != NULL) {
    const int fb_idx = ctx->cpi->common.cur_show_frame_fb_idx;
    YV12_BUFFER_CONFIG *fb = get_buf_frame(&ctx->cpi->common, fb_idx);
    if (fb == NULL) return VPX_CODEC_ERROR;
    yuvconfig2image(&frame->img, fb, NULL);
    return VPX_CODEC_OK;
  }
  return VPX_CODEC_INVALID_PARAM;
}

static vpx_codec_err_t ctrl_set_previewpp(vpx_codec_alg_priv_t *ctx,
                                          va_list args) {
#if CONFIG_VP9_POSTPROC
  vp8_postproc_cfg_t *config = va_arg(args, vp8_postproc_cfg_t *);
  if (config != NULL) {
    ctx->preview_ppcfg = *config;
    return VPX_CODEC_OK;
  }
  return VPX_CODEC_INVALID_PARAM;
#else
  (void)ctx;
  (void)args;
--> --------------------

--> maximum size reached

--> --------------------

Messung V0.5
C=93 H=88 G=90

¤ Dauer der Verarbeitung: 0.26 Sekunden  ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

Beweissystem der NASA

Beweissystem Isabelle

NIST Cobol Testsuite

Cephes Mathematical Library

Wiener Entwicklungsmethode

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.






                                                                                                                                                                                                                                                                                                                                                                                                     


Neuigkeiten

     Aktuelles
     Motto des Tages

Software

     Produkte
     Quellcodebibliothek

Aktivitäten

     Artikel über Sicherheit
     Anleitung zur Aktivierung von SSL

Muße

     Gedichte
     Musik
     Bilder

Jenseits des Üblichen ....
    

Besucherstatistik

Besucherstatistik

Monitoring

Montastic status badge