Home | History | Annotate | Download | only in vp9
      1 /*
      2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
      3  *
      4  *  Use of this source code is governed by a BSD-style license
      5  *  that can be found in the LICENSE file in the root of the source
      6  *  tree. An additional intellectual property rights grant can be found
      7  *  in the file PATENTS.  All contributing project authors may
      8  *  be found in the AUTHORS file in the root of the source tree.
      9  */
     10 
     11 #include <stdlib.h>
     12 #include <string.h>
     13 
     14 #include "./vpx_config.h"
     15 #include "vpx/vpx_encoder.h"
     16 #include "vpx_ports/vpx_once.h"
     17 #include "vpx/internal/vpx_codec_internal.h"
     18 #include "./vpx_version.h"
     19 #include "vp9/encoder/vp9_encoder.h"
     20 #include "vpx/vp8cx.h"
     21 #include "vp9/encoder/vp9_firstpass.h"
     22 #include "vp9/vp9_iface_common.h"
     23 
     24 struct vp9_extracfg {
     25   int                         cpu_used;  // available cpu percentage in 1/16
     26   unsigned int                enable_auto_alt_ref;
     27   unsigned int                noise_sensitivity;
     28   unsigned int                sharpness;
     29   unsigned int                static_thresh;
     30   unsigned int                tile_columns;
     31   unsigned int                tile_rows;
     32   unsigned int                arnr_max_frames;
     33   unsigned int                arnr_strength;
     34   unsigned int                min_gf_interval;
     35   unsigned int                max_gf_interval;
     36   vp8e_tuning                 tuning;
     37   unsigned int                cq_level;  // constrained quality level
     38   unsigned int                rc_max_intra_bitrate_pct;
     39   unsigned int                rc_max_inter_bitrate_pct;
     40   unsigned int                gf_cbr_boost_pct;
     41   unsigned int                lossless;
     42   unsigned int                frame_parallel_decoding_mode;
     43   AQ_MODE                     aq_mode;
     44   unsigned int                frame_periodic_boost;
     45   vpx_bit_depth_t             bit_depth;
     46   vp9e_tune_content           content;
     47   vpx_color_space_t           color_space;
     48   vpx_color_range_t           color_range;
     49   int                         render_width;
     50   int                         render_height;
     51 };
     52 
     53 static struct vp9_extracfg default_extra_cfg = {
     54   0,                          // cpu_used
     55   1,                          // enable_auto_alt_ref
     56   0,                          // noise_sensitivity
     57   0,                          // sharpness
     58   0,                          // static_thresh
     59   6,                          // tile_columns
     60   0,                          // tile_rows
     61   7,                          // arnr_max_frames
     62   5,                          // arnr_strength
     63   0,                          // min_gf_interval; 0 -> default decision
     64   0,                          // max_gf_interval; 0 -> default decision
     65   VP8_TUNE_PSNR,              // tuning
     66   10,                         // cq_level
     67   0,                          // rc_max_intra_bitrate_pct
     68   0,                          // rc_max_inter_bitrate_pct
     69   0,                          // gf_cbr_boost_pct
     70   0,                          // lossless
     71   1,                          // frame_parallel_decoding_mode
     72   NO_AQ,                      // aq_mode
     73   0,                          // frame_periodic_delta_q
     74   VPX_BITS_8,                 // Bit depth
     75   VP9E_CONTENT_DEFAULT,       // content
     76   VPX_CS_UNKNOWN,             // color space
     77   0,                          // color range
     78   0,                          // render width
     79   0,                          // render height
     80 };
     81 
     82 struct vpx_codec_alg_priv {
     83   vpx_codec_priv_t        base;
     84   vpx_codec_enc_cfg_t     cfg;
     85   struct vp9_extracfg     extra_cfg;
     86   VP9EncoderConfig        oxcf;
     87   VP9_COMP               *cpi;
     88   unsigned char          *cx_data;
     89   size_t                  cx_data_sz;
     90   unsigned char          *pending_cx_data;
     91   size_t                  pending_cx_data_sz;
     92   int                     pending_frame_count;
     93   size_t                  pending_frame_sizes[8];
     94   size_t                  pending_frame_magnitude;
     95   vpx_image_t             preview_img;
     96   vpx_enc_frame_flags_t   next_frame_flags;
     97   vp8_postproc_cfg_t      preview_ppcfg;
     98   vpx_codec_pkt_list_decl(256) pkt_list;
     99   unsigned int                 fixed_kf_cntr;
    100   vpx_codec_priv_output_cx_pkt_cb_pair_t output_cx_pkt_cb;
    101   // BufferPool that holds all reference frames.
    102   BufferPool              *buffer_pool;
    103 };
    104 
    105 static VP9_REFFRAME ref_frame_to_vp9_reframe(vpx_ref_frame_type_t frame) {
    106   switch (frame) {
    107     case VP8_LAST_FRAME:
    108       return VP9_LAST_FLAG;
    109     case VP8_GOLD_FRAME:
    110       return VP9_GOLD_FLAG;
    111     case VP8_ALTR_FRAME:
    112       return VP9_ALT_FLAG;
    113   }
    114   assert(0 && "Invalid Reference Frame");
    115   return VP9_LAST_FLAG;
    116 }
    117 
    118 static vpx_codec_err_t update_error_state(vpx_codec_alg_priv_t *ctx,
    119     const struct vpx_internal_error_info *error) {
    120   const vpx_codec_err_t res = error->error_code;
    121 
    122   if (res != VPX_CODEC_OK)
    123     ctx->base.err_detail = error->has_detail ? error->detail : NULL;
    124 
    125   return res;
    126 }
    127 
    128 
    129 #undef ERROR
    130 #define ERROR(str) do {\
    131     ctx->base.err_detail = str;\
    132     return VPX_CODEC_INVALID_PARAM;\
    133   } while (0)
    134 
    135 #define RANGE_CHECK(p, memb, lo, hi) do {\
    136     if (!(((p)->memb == lo || (p)->memb > (lo)) && (p)->memb <= hi)) \
    137       ERROR(#memb " out of range ["#lo".."#hi"]");\
    138   } while (0)
    139 
    140 #define RANGE_CHECK_HI(p, memb, hi) do {\
    141     if (!((p)->memb <= (hi))) \
    142       ERROR(#memb " out of range [.."#hi"]");\
    143   } while (0)
    144 
    145 #define RANGE_CHECK_LO(p, memb, lo) do {\
    146     if (!((p)->memb >= (lo))) \
    147       ERROR(#memb " out of range ["#lo"..]");\
    148   } while (0)
    149 
    150 #define RANGE_CHECK_BOOL(p, memb) do {\
    151     if (!!((p)->memb) != (p)->memb) ERROR(#memb " expected boolean");\
    152   } while (0)
    153 
    154 static vpx_codec_err_t validate_config(vpx_codec_alg_priv_t *ctx,
    155                                        const vpx_codec_enc_cfg_t *cfg,
    156                                        const struct vp9_extracfg *extra_cfg) {
    157   RANGE_CHECK(cfg, g_w,                   1, 65535);  // 16 bits available
    158   RANGE_CHECK(cfg, g_h,                   1, 65535);  // 16 bits available
    159   RANGE_CHECK(cfg, g_timebase.den,        1, 1000000000);
    160   RANGE_CHECK(cfg, g_timebase.num,        1, cfg->g_timebase.den);
    161   RANGE_CHECK_HI(cfg, g_profile,          3);
    162 
    163   RANGE_CHECK_HI(cfg, rc_max_quantizer,   63);
    164   RANGE_CHECK_HI(cfg, rc_min_quantizer,   cfg->rc_max_quantizer);
    165   RANGE_CHECK_BOOL(extra_cfg, lossless);
    166   RANGE_CHECK(extra_cfg, aq_mode,           0, AQ_MODE_COUNT - 1);
    167   RANGE_CHECK(extra_cfg, frame_periodic_boost, 0, 1);
    168   RANGE_CHECK_HI(cfg, g_threads,          64);
    169   RANGE_CHECK_HI(cfg, g_lag_in_frames,    MAX_LAG_BUFFERS);
    170   RANGE_CHECK(cfg, rc_end_usage,          VPX_VBR, VPX_Q);
    171   RANGE_CHECK_HI(cfg, rc_undershoot_pct,  100);
    172   RANGE_CHECK_HI(cfg, rc_overshoot_pct,   100);
    173   RANGE_CHECK_HI(cfg, rc_2pass_vbr_bias_pct, 100);
    174   RANGE_CHECK(cfg, kf_mode,               VPX_KF_DISABLED, VPX_KF_AUTO);
    175   RANGE_CHECK_BOOL(cfg,                   rc_resize_allowed);
    176   RANGE_CHECK_HI(cfg, rc_dropframe_thresh,   100);
    177   RANGE_CHECK_HI(cfg, rc_resize_up_thresh,   100);
    178   RANGE_CHECK_HI(cfg, rc_resize_down_thresh, 100);
    179   RANGE_CHECK(cfg,        g_pass,         VPX_RC_ONE_PASS, VPX_RC_LAST_PASS);
    180   RANGE_CHECK(extra_cfg, min_gf_interval, 0, (MAX_LAG_BUFFERS - 1));
    181   RANGE_CHECK(extra_cfg, max_gf_interval, 0, (MAX_LAG_BUFFERS - 1));
    182   if (extra_cfg->max_gf_interval > 0) {
    183     RANGE_CHECK(extra_cfg, max_gf_interval, 2, (MAX_LAG_BUFFERS - 1));
    184   }
    185   if (extra_cfg->min_gf_interval > 0 && extra_cfg->max_gf_interval > 0) {
    186     RANGE_CHECK(extra_cfg, max_gf_interval, extra_cfg->min_gf_interval,
    187       (MAX_LAG_BUFFERS - 1));
    188   }
    189 
    190   if (cfg->rc_resize_allowed == 1) {
    191     RANGE_CHECK(cfg, rc_scaled_width, 0, cfg->g_w);
    192     RANGE_CHECK(cfg, rc_scaled_height, 0, cfg->g_h);
    193   }
    194 
    195   RANGE_CHECK(cfg, ss_number_layers, 1, VPX_SS_MAX_LAYERS);
    196   RANGE_CHECK(cfg, ts_number_layers, 1, VPX_TS_MAX_LAYERS);
    197 
    198   if (cfg->ss_number_layers * cfg->ts_number_layers > VPX_MAX_LAYERS)
    199     ERROR("ss_number_layers * ts_number_layers is out of range");
    200   if (cfg->ts_number_layers > 1) {
    201     unsigned int sl, tl;
    202     for (sl = 1; sl < cfg->ss_number_layers; ++sl) {
    203       for (tl = 1; tl < cfg->ts_number_layers; ++tl) {
    204         const int layer =
    205             LAYER_IDS_TO_IDX(sl, tl, cfg->ts_number_layers);
    206         if (cfg->layer_target_bitrate[layer] <
    207             cfg->layer_target_bitrate[layer - 1])
    208         ERROR("ts_target_bitrate entries are not increasing");
    209       }
    210     }
    211 
    212     RANGE_CHECK(cfg, ts_rate_decimator[cfg->ts_number_layers - 1], 1, 1);
    213     for (tl = cfg->ts_number_layers - 2; tl > 0; --tl)
    214       if (cfg->ts_rate_decimator[tl - 1] != 2 * cfg->ts_rate_decimator[tl])
    215         ERROR("ts_rate_decimator factors are not powers of 2");
    216   }
    217 
    218 #if CONFIG_SPATIAL_SVC
    219 
    220   if ((cfg->ss_number_layers > 1 || cfg->ts_number_layers > 1) &&
    221       cfg->g_pass == VPX_RC_LAST_PASS) {
    222     unsigned int i, alt_ref_sum = 0;
    223     for (i = 0; i < cfg->ss_number_layers; ++i) {
    224       if (cfg->ss_enable_auto_alt_ref[i])
    225         ++alt_ref_sum;
    226     }
    227     if (alt_ref_sum > REF_FRAMES - cfg->ss_number_layers)
    228       ERROR("Not enough ref buffers for svc alt ref frames");
    229     if (cfg->ss_number_layers * cfg->ts_number_layers > 3 &&
    230         cfg->g_error_resilient == 0)
    231     ERROR("Multiple frame context are not supported for more than 3 layers");
    232   }
    233 #endif
    234 
    235   // VP9 does not support a lower bound on the keyframe interval in
    236   // automatic keyframe placement mode.
    237   if (cfg->kf_mode != VPX_KF_DISABLED &&
    238       cfg->kf_min_dist != cfg->kf_max_dist &&
    239       cfg->kf_min_dist > 0)
    240     ERROR("kf_min_dist not supported in auto mode, use 0 "
    241           "or kf_max_dist instead.");
    242 
    243   RANGE_CHECK(extra_cfg, enable_auto_alt_ref, 0, 2);
    244   RANGE_CHECK(extra_cfg, cpu_used, -8, 8);
    245   RANGE_CHECK_HI(extra_cfg, noise_sensitivity, 6);
    246   RANGE_CHECK(extra_cfg, tile_columns, 0, 6);
    247   RANGE_CHECK(extra_cfg, tile_rows, 0, 2);
    248   RANGE_CHECK_HI(extra_cfg, sharpness, 7);
    249   RANGE_CHECK(extra_cfg, arnr_max_frames, 0, 15);
    250   RANGE_CHECK_HI(extra_cfg, arnr_strength, 6);
    251   RANGE_CHECK(extra_cfg, cq_level, 0, 63);
    252   RANGE_CHECK(cfg, g_bit_depth, VPX_BITS_8, VPX_BITS_12);
    253   RANGE_CHECK(cfg, g_input_bit_depth, 8, 12);
    254   RANGE_CHECK(extra_cfg, content,
    255               VP9E_CONTENT_DEFAULT, VP9E_CONTENT_INVALID - 1);
    256 
    257   // TODO(yaowu): remove this when ssim tuning is implemented for vp9
    258   if (extra_cfg->tuning == VP8_TUNE_SSIM)
    259       ERROR("Option --tune=ssim is not currently supported in VP9.");
    260 
    261   if (cfg->g_pass == VPX_RC_LAST_PASS) {
    262     const size_t packet_sz = sizeof(FIRSTPASS_STATS);
    263     const int n_packets = (int)(cfg->rc_twopass_stats_in.sz / packet_sz);
    264     const FIRSTPASS_STATS *stats;
    265 
    266     if (cfg->rc_twopass_stats_in.buf == NULL)
    267       ERROR("rc_twopass_stats_in.buf not set.");
    268 
    269     if (cfg->rc_twopass_stats_in.sz % packet_sz)
    270       ERROR("rc_twopass_stats_in.sz indicates truncated packet.");
    271 
    272     if (cfg->ss_number_layers > 1 || cfg->ts_number_layers > 1) {
    273       int i;
    274       unsigned int n_packets_per_layer[VPX_SS_MAX_LAYERS] = {0};
    275 
    276       stats = cfg->rc_twopass_stats_in.buf;
    277       for (i = 0; i < n_packets; ++i) {
    278         const int layer_id = (int)stats[i].spatial_layer_id;
    279         if (layer_id >= 0 && layer_id < (int)cfg->ss_number_layers) {
    280           ++n_packets_per_layer[layer_id];
    281         }
    282       }
    283 
    284       for (i = 0; i < (int)cfg->ss_number_layers; ++i) {
    285         unsigned int layer_id;
    286         if (n_packets_per_layer[i] < 2) {
    287           ERROR("rc_twopass_stats_in requires at least two packets for each "
    288                 "layer.");
    289         }
    290 
    291         stats = (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf +
    292                 n_packets - cfg->ss_number_layers + i;
    293         layer_id = (int)stats->spatial_layer_id;
    294 
    295         if (layer_id >= cfg->ss_number_layers
    296             ||(unsigned int)(stats->count + 0.5) !=
    297                n_packets_per_layer[layer_id] - 1)
    298           ERROR("rc_twopass_stats_in missing EOS stats packet");
    299       }
    300     } else {
    301       if (cfg->rc_twopass_stats_in.sz < 2 * packet_sz)
    302         ERROR("rc_twopass_stats_in requires at least two packets.");
    303 
    304       stats =
    305           (const FIRSTPASS_STATS *)cfg->rc_twopass_stats_in.buf + n_packets - 1;
    306 
    307       if ((int)(stats->count + 0.5) != n_packets - 1)
    308         ERROR("rc_twopass_stats_in missing EOS stats packet");
    309     }
    310   }
    311 
    312 #if !CONFIG_VP9_HIGHBITDEPTH
    313   if (cfg->g_profile > (unsigned int)PROFILE_1) {
    314     ERROR("Profile > 1 not supported in this build configuration");
    315   }
    316 #endif
    317   if (cfg->g_profile <= (unsigned int)PROFILE_1 &&
    318       cfg->g_bit_depth > VPX_BITS_8) {
    319     ERROR("Codec high bit-depth not supported in profile < 2");
    320   }
    321   if (cfg->g_profile <= (unsigned int)PROFILE_1 &&
    322       cfg->g_input_bit_depth > 8) {
    323     ERROR("Source high bit-depth not supported in profile < 2");
    324   }
    325   if (cfg->g_profile > (unsigned int)PROFILE_1 &&
    326       cfg->g_bit_depth == VPX_BITS_8) {
    327     ERROR("Codec bit-depth 8 not supported in profile > 1");
    328   }
    329   RANGE_CHECK(extra_cfg, color_space, VPX_CS_UNKNOWN, VPX_CS_SRGB);
    330   RANGE_CHECK(extra_cfg, color_range,
    331               VPX_CR_STUDIO_RANGE, VPX_CR_FULL_RANGE);
    332   return VPX_CODEC_OK;
    333 }
    334 
    335 static vpx_codec_err_t validate_img(vpx_codec_alg_priv_t *ctx,
    336                                     const vpx_image_t *img) {
    337   switch (img->fmt) {
    338     case VPX_IMG_FMT_YV12:
    339     case VPX_IMG_FMT_I420:
    340     case VPX_IMG_FMT_I42016:
    341       break;
    342     case VPX_IMG_FMT_I422:
    343     case VPX_IMG_FMT_I444:
    344     case VPX_IMG_FMT_I440:
    345       if (ctx->cfg.g_profile != (unsigned int)PROFILE_1) {
    346         ERROR("Invalid image format. I422, I444, I440 images are "
    347               "not supported in profile.");
    348       }
    349       break;
    350     case VPX_IMG_FMT_I42216:
    351     case VPX_IMG_FMT_I44416:
    352     case VPX_IMG_FMT_I44016:
    353       if (ctx->cfg.g_profile != (unsigned int)PROFILE_1 &&
    354           ctx->cfg.g_profile != (unsigned int)PROFILE_3) {
    355         ERROR("Invalid image format. 16-bit I422, I444, I440 images are "
    356               "not supported in profile.");
    357       }
    358       break;
    359     default:
    360       ERROR("Invalid image format. Only YV12, I420, I422, I444 images are "
    361             "supported.");
    362       break;
    363   }
    364 
    365   if (img->d_w != ctx->cfg.g_w || img->d_h != ctx->cfg.g_h)
    366     ERROR("Image size must match encoder init configuration size");
    367 
    368   return VPX_CODEC_OK;
    369 }
    370 
    371 static int get_image_bps(const vpx_image_t *img) {
    372   switch (img->fmt) {
    373     case VPX_IMG_FMT_YV12:
    374     case VPX_IMG_FMT_I420: return 12;
    375     case VPX_IMG_FMT_I422: return 16;
    376     case VPX_IMG_FMT_I444: return 24;
    377     case VPX_IMG_FMT_I440: return 16;
    378     case VPX_IMG_FMT_I42016: return 24;
    379     case VPX_IMG_FMT_I42216: return 32;
    380     case VPX_IMG_FMT_I44416: return 48;
    381     case VPX_IMG_FMT_I44016: return 32;
    382     default: assert(0 && "Invalid image format"); break;
    383   }
    384   return 0;
    385 }
    386 
    387 static vpx_codec_err_t set_encoder_config(
    388   VP9EncoderConfig *oxcf,
    389   const vpx_codec_enc_cfg_t *cfg,
    390   const struct vp9_extracfg *extra_cfg) {
    391   const int is_vbr = cfg->rc_end_usage == VPX_VBR;
    392   int sl, tl;
    393   oxcf->profile = cfg->g_profile;
    394   oxcf->max_threads = (int)cfg->g_threads;
    395   oxcf->width   = cfg->g_w;
    396   oxcf->height  = cfg->g_h;
    397   oxcf->bit_depth = cfg->g_bit_depth;
    398   oxcf->input_bit_depth = cfg->g_input_bit_depth;
    399   // guess a frame rate if out of whack, use 30
    400   oxcf->init_framerate = (double)cfg->g_timebase.den / cfg->g_timebase.num;
    401   if (oxcf->init_framerate > 180)
    402     oxcf->init_framerate = 30;
    403 
    404   oxcf->mode = GOOD;
    405 
    406   switch (cfg->g_pass) {
    407     case VPX_RC_ONE_PASS:
    408       oxcf->pass = 0;
    409       break;
    410     case VPX_RC_FIRST_PASS:
    411       oxcf->pass = 1;
    412       break;
    413     case VPX_RC_LAST_PASS:
    414       oxcf->pass = 2;
    415       break;
    416   }
    417 
    418   oxcf->lag_in_frames = cfg->g_pass == VPX_RC_FIRST_PASS ? 0
    419                                                          : cfg->g_lag_in_frames;
    420   oxcf->rc_mode = cfg->rc_end_usage;
    421 
    422   // Convert target bandwidth from Kbit/s to Bit/s
    423   oxcf->target_bandwidth = 1000 * cfg->rc_target_bitrate;
    424   oxcf->rc_max_intra_bitrate_pct = extra_cfg->rc_max_intra_bitrate_pct;
    425   oxcf->rc_max_inter_bitrate_pct = extra_cfg->rc_max_inter_bitrate_pct;
    426   oxcf->gf_cbr_boost_pct = extra_cfg->gf_cbr_boost_pct;
    427 
    428   oxcf->best_allowed_q =
    429       extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_min_quantizer);
    430   oxcf->worst_allowed_q =
    431       extra_cfg->lossless ? 0 : vp9_quantizer_to_qindex(cfg->rc_max_quantizer);
    432   oxcf->cq_level        = vp9_quantizer_to_qindex(extra_cfg->cq_level);
    433   oxcf->fixed_q = -1;
    434 
    435   oxcf->under_shoot_pct         = cfg->rc_undershoot_pct;
    436   oxcf->over_shoot_pct          = cfg->rc_overshoot_pct;
    437 
    438   oxcf->scaled_frame_width  = cfg->rc_scaled_width;
    439   oxcf->scaled_frame_height = cfg->rc_scaled_height;
    440   if (cfg->rc_resize_allowed == 1) {
    441     oxcf->resize_mode =
    442         (oxcf->scaled_frame_width == 0 || oxcf->scaled_frame_height == 0) ?
    443             RESIZE_DYNAMIC : RESIZE_FIXED;
    444   } else {
    445     oxcf->resize_mode = RESIZE_NONE;
    446   }
    447 
    448   oxcf->maximum_buffer_size_ms   = is_vbr ? 240000 : cfg->rc_buf_sz;
    449   oxcf->starting_buffer_level_ms = is_vbr ? 60000 : cfg->rc_buf_initial_sz;
    450   oxcf->optimal_buffer_level_ms  = is_vbr ? 60000 : cfg->rc_buf_optimal_sz;
    451 
    452   oxcf->drop_frames_water_mark   = cfg->rc_dropframe_thresh;
    453 
    454   oxcf->two_pass_vbrbias         = cfg->rc_2pass_vbr_bias_pct;
    455   oxcf->two_pass_vbrmin_section  = cfg->rc_2pass_vbr_minsection_pct;
    456   oxcf->two_pass_vbrmax_section  = cfg->rc_2pass_vbr_maxsection_pct;
    457 
    458   oxcf->auto_key               = cfg->kf_mode == VPX_KF_AUTO &&
    459                                  cfg->kf_min_dist != cfg->kf_max_dist;
    460 
    461   oxcf->key_freq               = cfg->kf_max_dist;
    462 
    463   oxcf->speed                  =  abs(extra_cfg->cpu_used);
    464   oxcf->encode_breakout        =  extra_cfg->static_thresh;
    465   oxcf->enable_auto_arf        =  extra_cfg->enable_auto_alt_ref;
    466   oxcf->noise_sensitivity      =  extra_cfg->noise_sensitivity;
    467   oxcf->sharpness              =  extra_cfg->sharpness;
    468 
    469   oxcf->two_pass_stats_in      =  cfg->rc_twopass_stats_in;
    470 
    471 #if CONFIG_FP_MB_STATS
    472   oxcf->firstpass_mb_stats_in  = cfg->rc_firstpass_mb_stats_in;
    473 #endif
    474 
    475   oxcf->color_space = extra_cfg->color_space;
    476   oxcf->color_range = extra_cfg->color_range;
    477   oxcf->render_width  = extra_cfg->render_width;
    478   oxcf->render_height = extra_cfg->render_height;
    479   oxcf->arnr_max_frames = extra_cfg->arnr_max_frames;
    480   oxcf->arnr_strength   = extra_cfg->arnr_strength;
    481   oxcf->min_gf_interval = extra_cfg->min_gf_interval;
    482   oxcf->max_gf_interval = extra_cfg->max_gf_interval;
    483 
    484   oxcf->tuning = extra_cfg->tuning;
    485   oxcf->content = extra_cfg->content;
    486 
    487   oxcf->tile_columns = extra_cfg->tile_columns;
    488   oxcf->tile_rows    = extra_cfg->tile_rows;
    489 
    490   oxcf->error_resilient_mode         = cfg->g_error_resilient;
    491   oxcf->frame_parallel_decoding_mode = extra_cfg->frame_parallel_decoding_mode;
    492 
    493   oxcf->aq_mode = extra_cfg->aq_mode;
    494 
    495   oxcf->frame_periodic_boost =  extra_cfg->frame_periodic_boost;
    496 
    497   oxcf->ss_number_layers = cfg->ss_number_layers;
    498   oxcf->ts_number_layers = cfg->ts_number_layers;
    499   oxcf->temporal_layering_mode = (enum vp9e_temporal_layering_mode)
    500       cfg->temporal_layering_mode;
    501 
    502   for (sl = 0; sl < oxcf->ss_number_layers; ++sl) {
    503 #if CONFIG_SPATIAL_SVC
    504     oxcf->ss_enable_auto_arf[sl] = cfg->ss_enable_auto_alt_ref[sl];
    505 #endif
    506     for (tl = 0; tl < oxcf->ts_number_layers; ++tl) {
    507       oxcf->layer_target_bitrate[sl * oxcf->ts_number_layers + tl] =
    508           1000 * cfg->layer_target_bitrate[sl * oxcf->ts_number_layers + tl];
    509     }
    510   }
    511   if (oxcf->ss_number_layers == 1 && oxcf->pass != 0) {
    512     oxcf->ss_target_bitrate[0] = (int)oxcf->target_bandwidth;
    513 #if CONFIG_SPATIAL_SVC
    514     oxcf->ss_enable_auto_arf[0] = extra_cfg->enable_auto_alt_ref;
    515 #endif
    516   }
    517   if (oxcf->ts_number_layers > 1) {
    518     for (tl = 0; tl < VPX_TS_MAX_LAYERS; ++tl) {
    519       oxcf->ts_rate_decimator[tl] = cfg->ts_rate_decimator[tl] ?
    520           cfg->ts_rate_decimator[tl] : 1;
    521     }
    522   } else if (oxcf->ts_number_layers == 1) {
    523     oxcf->ts_rate_decimator[0] = 1;
    524   }
    525   /*
    526   printf("Current VP9 Settings: \n");
    527   printf("target_bandwidth: %d\n", oxcf->target_bandwidth);
    528   printf("noise_sensitivity: %d\n", oxcf->noise_sensitivity);
    529   printf("sharpness: %d\n",    oxcf->sharpness);
    530   printf("cpu_used: %d\n",  oxcf->cpu_used);
    531   printf("Mode: %d\n",     oxcf->mode);
    532   printf("auto_key: %d\n",  oxcf->auto_key);
    533   printf("key_freq: %d\n", oxcf->key_freq);
    534   printf("end_usage: %d\n", oxcf->end_usage);
    535   printf("under_shoot_pct: %d\n", oxcf->under_shoot_pct);
    536   printf("over_shoot_pct: %d\n", oxcf->over_shoot_pct);
    537   printf("starting_buffer_level: %d\n", oxcf->starting_buffer_level);
    538   printf("optimal_buffer_level: %d\n",  oxcf->optimal_buffer_level);
    539   printf("maximum_buffer_size: %d\n", oxcf->maximum_buffer_size);
    540   printf("fixed_q: %d\n",  oxcf->fixed_q);
    541   printf("worst_allowed_q: %d\n", oxcf->worst_allowed_q);
    542   printf("best_allowed_q: %d\n", oxcf->best_allowed_q);
    543   printf("allow_spatial_resampling: %d\n", oxcf->allow_spatial_resampling);
    544   printf("scaled_frame_width: %d\n", oxcf->scaled_frame_width);
    545   printf("scaled_frame_height: %d\n", oxcf->scaled_frame_height);
    546   printf("two_pass_vbrbias: %d\n",  oxcf->two_pass_vbrbias);
    547   printf("two_pass_vbrmin_section: %d\n", oxcf->two_pass_vbrmin_section);
    548   printf("two_pass_vbrmax_section: %d\n", oxcf->two_pass_vbrmax_section);
    549   printf("lag_in_frames: %d\n", oxcf->lag_in_frames);
    550   printf("enable_auto_arf: %d\n", oxcf->enable_auto_arf);
    551   printf("Version: %d\n", oxcf->Version);
    552   printf("encode_breakout: %d\n", oxcf->encode_breakout);
    553   printf("error resilient: %d\n", oxcf->error_resilient_mode);
    554   printf("frame parallel detokenization: %d\n",
    555          oxcf->frame_parallel_decoding_mode);
    556   */
    557   return VPX_CODEC_OK;
    558 }
    559 
    560 static vpx_codec_err_t encoder_set_config(vpx_codec_alg_priv_t *ctx,
    561                                           const vpx_codec_enc_cfg_t  *cfg) {
    562   vpx_codec_err_t res;
    563   int force_key = 0;
    564 
    565   if (cfg->g_w != ctx->cfg.g_w || cfg->g_h != ctx->cfg.g_h) {
    566     if (cfg->g_lag_in_frames > 1 || cfg->g_pass != VPX_RC_ONE_PASS)
    567       ERROR("Cannot change width or height after initialization");
    568     if (!valid_ref_frame_size(ctx->cfg.g_w, ctx->cfg.g_h, cfg->g_w, cfg->g_h) ||
    569         (ctx->cpi->initial_width && (int)cfg->g_w > ctx->cpi->initial_width) ||
    570         (ctx->cpi->initial_height && (int)cfg->g_h > ctx->cpi->initial_height))
    571       force_key = 1;
    572   }
    573 
    574   // Prevent increasing lag_in_frames. This check is stricter than it needs
    575   // to be -- the limit is not increasing past the first lag_in_frames
    576   // value, but we don't track the initial config, only the last successful
    577   // config.
    578   if (cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames)
    579     ERROR("Cannot increase lag_in_frames");
    580 
    581   res = validate_config(ctx, cfg, &ctx->extra_cfg);
    582 
    583   if (res == VPX_CODEC_OK) {
    584     ctx->cfg = *cfg;
    585     set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
    586     // On profile change, request a key frame
    587     force_key |= ctx->cpi->common.profile != ctx->oxcf.profile;
    588     vp9_change_config(ctx->cpi, &ctx->oxcf);
    589   }
    590 
    591   if (force_key)
    592     ctx->next_frame_flags |= VPX_EFLAG_FORCE_KF;
    593 
    594   return res;
    595 }
    596 
    597 static vpx_codec_err_t ctrl_get_quantizer(vpx_codec_alg_priv_t *ctx,
    598                                           va_list args) {
    599   int *const arg = va_arg(args, int *);
    600   if (arg == NULL)
    601     return VPX_CODEC_INVALID_PARAM;
    602   *arg = vp9_get_quantizer(ctx->cpi);
    603   return VPX_CODEC_OK;
    604 }
    605 
    606 static vpx_codec_err_t ctrl_get_quantizer64(vpx_codec_alg_priv_t *ctx,
    607                                             va_list args) {
    608   int *const arg = va_arg(args, int *);
    609   if (arg == NULL)
    610     return VPX_CODEC_INVALID_PARAM;
    611   *arg = vp9_qindex_to_quantizer(vp9_get_quantizer(ctx->cpi));
    612   return VPX_CODEC_OK;
    613 }
    614 
    615 static vpx_codec_err_t update_extra_cfg(vpx_codec_alg_priv_t *ctx,
    616                                         const struct vp9_extracfg *extra_cfg) {
    617   const vpx_codec_err_t res = validate_config(ctx, &ctx->cfg, extra_cfg);
    618   if (res == VPX_CODEC_OK) {
    619     ctx->extra_cfg = *extra_cfg;
    620     set_encoder_config(&ctx->oxcf, &ctx->cfg, &ctx->extra_cfg);
    621     vp9_change_config(ctx->cpi, &ctx->oxcf);
    622   }
    623   return res;
    624 }
    625 
    626 static vpx_codec_err_t ctrl_set_cpuused(vpx_codec_alg_priv_t *ctx,
    627                                         va_list args) {
    628   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    629   extra_cfg.cpu_used = CAST(VP8E_SET_CPUUSED, args);
    630   return update_extra_cfg(ctx, &extra_cfg);
    631 }
    632 
    633 static vpx_codec_err_t ctrl_set_enable_auto_alt_ref(vpx_codec_alg_priv_t *ctx,
    634                                                     va_list args) {
    635   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    636   extra_cfg.enable_auto_alt_ref = CAST(VP8E_SET_ENABLEAUTOALTREF, args);
    637   return update_extra_cfg(ctx, &extra_cfg);
    638 }
    639 
    640 static vpx_codec_err_t ctrl_set_noise_sensitivity(vpx_codec_alg_priv_t *ctx,
    641                                                   va_list args) {
    642   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    643   extra_cfg.noise_sensitivity = CAST(VP9E_SET_NOISE_SENSITIVITY, args);
    644   return update_extra_cfg(ctx, &extra_cfg);
    645 }
    646 
    647 static vpx_codec_err_t ctrl_set_sharpness(vpx_codec_alg_priv_t *ctx,
    648                                           va_list args) {
    649   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    650   extra_cfg.sharpness = CAST(VP8E_SET_SHARPNESS, args);
    651   return update_extra_cfg(ctx, &extra_cfg);
    652 }
    653 
    654 static vpx_codec_err_t ctrl_set_static_thresh(vpx_codec_alg_priv_t *ctx,
    655                                               va_list args) {
    656   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    657   extra_cfg.static_thresh = CAST(VP8E_SET_STATIC_THRESHOLD, args);
    658   return update_extra_cfg(ctx, &extra_cfg);
    659 }
    660 
    661 static vpx_codec_err_t ctrl_set_tile_columns(vpx_codec_alg_priv_t *ctx,
    662                                              va_list args) {
    663   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    664   extra_cfg.tile_columns = CAST(VP9E_SET_TILE_COLUMNS, args);
    665   return update_extra_cfg(ctx, &extra_cfg);
    666 }
    667 
    668 static vpx_codec_err_t ctrl_set_tile_rows(vpx_codec_alg_priv_t *ctx,
    669                                           va_list args) {
    670   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    671   extra_cfg.tile_rows = CAST(VP9E_SET_TILE_ROWS, args);
    672   return update_extra_cfg(ctx, &extra_cfg);
    673 }
    674 
    675 static vpx_codec_err_t ctrl_set_arnr_max_frames(vpx_codec_alg_priv_t *ctx,
    676                                                 va_list args) {
    677   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    678   extra_cfg.arnr_max_frames = CAST(VP8E_SET_ARNR_MAXFRAMES, args);
    679   return update_extra_cfg(ctx, &extra_cfg);
    680 }
    681 
    682 static vpx_codec_err_t ctrl_set_arnr_strength(vpx_codec_alg_priv_t *ctx,
    683                                               va_list args) {
    684   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    685   extra_cfg.arnr_strength = CAST(VP8E_SET_ARNR_STRENGTH, args);
    686   return update_extra_cfg(ctx, &extra_cfg);
    687 }
    688 
    689 static vpx_codec_err_t ctrl_set_arnr_type(vpx_codec_alg_priv_t *ctx,
    690                                           va_list args) {
    691   (void)ctx;
    692   (void)args;
    693   return VPX_CODEC_OK;
    694 }
    695 
    696 static vpx_codec_err_t ctrl_set_tuning(vpx_codec_alg_priv_t *ctx,
    697                                        va_list args) {
    698   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    699   extra_cfg.tuning = CAST(VP8E_SET_TUNING, args);
    700   return update_extra_cfg(ctx, &extra_cfg);
    701 }
    702 
    703 static vpx_codec_err_t ctrl_set_cq_level(vpx_codec_alg_priv_t *ctx,
    704                                          va_list args) {
    705   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    706   extra_cfg.cq_level = CAST(VP8E_SET_CQ_LEVEL, args);
    707   return update_extra_cfg(ctx, &extra_cfg);
    708 }
    709 
    710 static vpx_codec_err_t ctrl_set_rc_max_intra_bitrate_pct(
    711     vpx_codec_alg_priv_t *ctx, va_list args) {
    712   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    713   extra_cfg.rc_max_intra_bitrate_pct =
    714       CAST(VP8E_SET_MAX_INTRA_BITRATE_PCT, args);
    715   return update_extra_cfg(ctx, &extra_cfg);
    716 }
    717 
    718 static vpx_codec_err_t ctrl_set_rc_max_inter_bitrate_pct(
    719     vpx_codec_alg_priv_t *ctx, va_list args) {
    720   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    721   extra_cfg.rc_max_inter_bitrate_pct =
    722       CAST(VP8E_SET_MAX_INTER_BITRATE_PCT, args);
    723   return update_extra_cfg(ctx, &extra_cfg);
    724 }
    725 
    726 static vpx_codec_err_t ctrl_set_rc_gf_cbr_boost_pct(
    727     vpx_codec_alg_priv_t *ctx, va_list args) {
    728   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    729   extra_cfg.gf_cbr_boost_pct =
    730       CAST(VP9E_SET_GF_CBR_BOOST_PCT, args);
    731   return update_extra_cfg(ctx, &extra_cfg);
    732 }
    733 
    734 static vpx_codec_err_t ctrl_set_lossless(vpx_codec_alg_priv_t *ctx,
    735                                          va_list args) {
    736   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    737   extra_cfg.lossless = CAST(VP9E_SET_LOSSLESS, args);
    738   return update_extra_cfg(ctx, &extra_cfg);
    739 }
    740 
    741 static vpx_codec_err_t ctrl_set_frame_parallel_decoding_mode(
    742     vpx_codec_alg_priv_t *ctx, va_list args) {
    743   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    744   extra_cfg.frame_parallel_decoding_mode =
    745       CAST(VP9E_SET_FRAME_PARALLEL_DECODING, args);
    746   return update_extra_cfg(ctx, &extra_cfg);
    747 }
    748 
    749 static vpx_codec_err_t ctrl_set_aq_mode(vpx_codec_alg_priv_t *ctx,
    750                                         va_list args) {
    751   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    752   extra_cfg.aq_mode = CAST(VP9E_SET_AQ_MODE, args);
    753   return update_extra_cfg(ctx, &extra_cfg);
    754 }
    755 
    756 static vpx_codec_err_t ctrl_set_min_gf_interval(vpx_codec_alg_priv_t *ctx,
    757                                                 va_list args) {
    758   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    759   extra_cfg.min_gf_interval = CAST(VP9E_SET_MIN_GF_INTERVAL, args);
    760   return update_extra_cfg(ctx, &extra_cfg);
    761 }
    762 
    763 static vpx_codec_err_t ctrl_set_max_gf_interval(vpx_codec_alg_priv_t *ctx,
    764                                                 va_list args) {
    765   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    766   extra_cfg.max_gf_interval = CAST(VP9E_SET_MAX_GF_INTERVAL, args);
    767   return update_extra_cfg(ctx, &extra_cfg);
    768 }
    769 
    770 static vpx_codec_err_t ctrl_set_frame_periodic_boost(vpx_codec_alg_priv_t *ctx,
    771                                                      va_list args) {
    772   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
    773   extra_cfg.frame_periodic_boost = CAST(VP9E_SET_FRAME_PERIODIC_BOOST, args);
    774   return update_extra_cfg(ctx, &extra_cfg);
    775 }
    776 
    777 static vpx_codec_err_t encoder_init(vpx_codec_ctx_t *ctx,
    778                                     vpx_codec_priv_enc_mr_cfg_t *data) {
    779   vpx_codec_err_t res = VPX_CODEC_OK;
    780   (void)data;
    781 
    782   if (ctx->priv == NULL) {
    783     vpx_codec_alg_priv_t *const priv = vpx_calloc(1, sizeof(*priv));
    784     if (priv == NULL)
    785       return VPX_CODEC_MEM_ERROR;
    786 
    787     ctx->priv = (vpx_codec_priv_t *)priv;
    788     ctx->priv->init_flags = ctx->init_flags;
    789     ctx->priv->enc.total_encoders = 1;
    790     priv->buffer_pool =
    791         (BufferPool *)vpx_calloc(1, sizeof(BufferPool));
    792     if (priv->buffer_pool == NULL)
    793       return VPX_CODEC_MEM_ERROR;
    794 
    795 #if CONFIG_MULTITHREAD
    796     if (pthread_mutex_init(&priv->buffer_pool->pool_mutex, NULL)) {
    797       return VPX_CODEC_MEM_ERROR;
    798     }
    799 #endif
    800 
    801     if (ctx->config.enc) {
    802       // Update the reference to the config structure to an internal copy.
    803       priv->cfg = *ctx->config.enc;
    804       ctx->config.enc = &priv->cfg;
    805     }
    806 
    807     priv->extra_cfg = default_extra_cfg;
    808     once(vp9_initialize_enc);
    809 
    810     res = validate_config(priv, &priv->cfg, &priv->extra_cfg);
    811 
    812     if (res == VPX_CODEC_OK) {
    813       set_encoder_config(&priv->oxcf, &priv->cfg, &priv->extra_cfg);
    814 #if CONFIG_VP9_HIGHBITDEPTH
    815       priv->oxcf.use_highbitdepth =
    816           (ctx->init_flags & VPX_CODEC_USE_HIGHBITDEPTH) ? 1 : 0;
    817 #endif
    818       priv->cpi = vp9_create_compressor(&priv->oxcf, priv->buffer_pool);
    819       if (priv->cpi == NULL)
    820         res = VPX_CODEC_MEM_ERROR;
    821       else
    822         priv->cpi->output_pkt_list = &priv->pkt_list.head;
    823     }
    824   }
    825 
    826   return res;
    827 }
    828 
    829 static vpx_codec_err_t encoder_destroy(vpx_codec_alg_priv_t *ctx) {
    830   free(ctx->cx_data);
    831   vp9_remove_compressor(ctx->cpi);
    832 #if CONFIG_MULTITHREAD
    833   pthread_mutex_destroy(&ctx->buffer_pool->pool_mutex);
    834 #endif
    835   vpx_free(ctx->buffer_pool);
    836   vpx_free(ctx);
    837   return VPX_CODEC_OK;
    838 }
    839 
    840 static void pick_quickcompress_mode(vpx_codec_alg_priv_t *ctx,
    841                                     unsigned long duration,
    842                                     unsigned long deadline) {
    843   MODE new_mode = BEST;
    844 
    845   switch (ctx->cfg.g_pass) {
    846     case VPX_RC_ONE_PASS:
    847       if (deadline > 0) {
    848         const vpx_codec_enc_cfg_t *const cfg = &ctx->cfg;
    849 
    850         // Convert duration parameter from stream timebase to microseconds.
    851         const uint64_t duration_us = (uint64_t)duration * 1000000 *
    852            (uint64_t)cfg->g_timebase.num /(uint64_t)cfg->g_timebase.den;
    853 
    854         // If the deadline is more that the duration this frame is to be shown,
    855         // use good quality mode. Otherwise use realtime mode.
    856         new_mode = (deadline > duration_us) ? GOOD : REALTIME;
    857       } else {
    858         new_mode = BEST;
    859       }
    860       break;
    861     case VPX_RC_FIRST_PASS:
    862       break;
    863     case VPX_RC_LAST_PASS:
    864       new_mode = deadline > 0 ? GOOD : BEST;
    865       break;
    866   }
    867 
    868   if (ctx->oxcf.mode != new_mode) {
    869     ctx->oxcf.mode = new_mode;
    870     vp9_change_config(ctx->cpi, &ctx->oxcf);
    871   }
    872 }
    873 
    874 // Turn on to test if supplemental superframe data breaks decoding
    875 // #define TEST_SUPPLEMENTAL_SUPERFRAME_DATA
    876 static int write_superframe_index(vpx_codec_alg_priv_t *ctx) {
    877   uint8_t marker = 0xc0;
    878   unsigned int mask;
    879   int mag, index_sz;
    880 
    881   assert(ctx->pending_frame_count);
    882   assert(ctx->pending_frame_count <= 8);
    883 
    884   // Add the number of frames to the marker byte
    885   marker |= ctx->pending_frame_count - 1;
    886 
    887   // Choose the magnitude
    888   for (mag = 0, mask = 0xff; mag < 4; mag++) {
    889     if (ctx->pending_frame_magnitude < mask)
    890       break;
    891     mask <<= 8;
    892     mask |= 0xff;
    893   }
    894   marker |= mag << 3;
    895 
    896   // Write the index
    897   index_sz = 2 + (mag + 1) * ctx->pending_frame_count;
    898   if (ctx->pending_cx_data_sz + index_sz < ctx->cx_data_sz) {
    899     uint8_t *x = ctx->pending_cx_data + ctx->pending_cx_data_sz;
    900     int i, j;
    901 #ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
    902     uint8_t marker_test = 0xc0;
    903     int mag_test = 2;     // 1 - 4
    904     int frames_test = 4;  // 1 - 8
    905     int index_sz_test = 2 + mag_test * frames_test;
    906     marker_test |= frames_test - 1;
    907     marker_test |= (mag_test - 1) << 3;
    908     *x++ = marker_test;
    909     for (i = 0; i < mag_test * frames_test; ++i)
    910       *x++ = 0;  // fill up with arbitrary data
    911     *x++ = marker_test;
    912     ctx->pending_cx_data_sz += index_sz_test;
    913     printf("Added supplemental superframe data\n");
    914 #endif
    915 
    916     *x++ = marker;
    917     for (i = 0; i < ctx->pending_frame_count; i++) {
    918       unsigned int this_sz = (unsigned int)ctx->pending_frame_sizes[i];
    919 
    920       for (j = 0; j <= mag; j++) {
    921         *x++ = this_sz & 0xff;
    922         this_sz >>= 8;
    923       }
    924     }
    925     *x++ = marker;
    926     ctx->pending_cx_data_sz += index_sz;
    927 #ifdef TEST_SUPPLEMENTAL_SUPERFRAME_DATA
    928     index_sz += index_sz_test;
    929 #endif
    930   }
    931   return index_sz;
    932 }
    933 
    934 // vp9 uses 10,000,000 ticks/second as time stamp
    935 #define TICKS_PER_SEC 10000000LL
    936 
    937 static int64_t timebase_units_to_ticks(const vpx_rational_t *timebase,
    938                                        int64_t n) {
    939   return n * TICKS_PER_SEC * timebase->num / timebase->den;
    940 }
    941 
    942 static int64_t ticks_to_timebase_units(const vpx_rational_t *timebase,
    943                                        int64_t n) {
    944   const int64_t round = TICKS_PER_SEC * timebase->num / 2 - 1;
    945   return (n * timebase->den + round) / timebase->num / TICKS_PER_SEC;
    946 }
    947 
    948 static vpx_codec_frame_flags_t get_frame_pkt_flags(const VP9_COMP *cpi,
    949                                                    unsigned int lib_flags) {
    950   vpx_codec_frame_flags_t flags = lib_flags << 16;
    951 
    952   if (lib_flags & FRAMEFLAGS_KEY ||
    953       (cpi->use_svc &&
    954           cpi->svc.layer_context[cpi->svc.spatial_layer_id *
    955               cpi->svc.number_temporal_layers +
    956               cpi->svc.temporal_layer_id].is_key_frame)
    957      )
    958     flags |= VPX_FRAME_IS_KEY;
    959 
    960   if (cpi->droppable)
    961     flags |= VPX_FRAME_IS_DROPPABLE;
    962 
    963   return flags;
    964 }
    965 
    966 static vpx_codec_err_t encoder_encode(vpx_codec_alg_priv_t  *ctx,
    967                                       const vpx_image_t *img,
    968                                       vpx_codec_pts_t pts,
    969                                       unsigned long duration,
    970                                       vpx_enc_frame_flags_t flags,
    971                                       unsigned long deadline) {
    972   vpx_codec_err_t res = VPX_CODEC_OK;
    973   VP9_COMP *const cpi = ctx->cpi;
    974   const vpx_rational_t *const timebase = &ctx->cfg.g_timebase;
    975   size_t data_sz;
    976 
    977   if (img != NULL) {
    978     res = validate_img(ctx, img);
    979     // TODO(jzern) the checks related to cpi's validity should be treated as a
    980     // failure condition, encoder setup is done fully in init() currently.
    981     if (res == VPX_CODEC_OK && cpi != NULL) {
    982       // There's no codec control for multiple alt-refs so check the encoder
    983       // instance for its status to determine the compressed data size.
    984       data_sz = ctx->cfg.g_w * ctx->cfg.g_h * get_image_bps(img) / 8 *
    985                 (cpi->multi_arf_allowed ? 8 : 2);
    986       if (data_sz < 4096)
    987         data_sz = 4096;
    988       if (ctx->cx_data == NULL || ctx->cx_data_sz < data_sz) {
    989         ctx->cx_data_sz = data_sz;
    990         free(ctx->cx_data);
    991         ctx->cx_data = (unsigned char*)malloc(ctx->cx_data_sz);
    992         if (ctx->cx_data == NULL) {
    993           return VPX_CODEC_MEM_ERROR;
    994         }
    995       }
    996     }
    997   }
    998 
    999   pick_quickcompress_mode(ctx, duration, deadline);
   1000   vpx_codec_pkt_list_init(&ctx->pkt_list);
   1001 
   1002   // Handle Flags
   1003   if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF)) ||
   1004        ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF))) {
   1005     ctx->base.err_detail = "Conflicting flags.";
   1006     return VPX_CODEC_INVALID_PARAM;
   1007   }
   1008 
   1009   vp9_apply_encoding_flags(cpi, flags);
   1010 
   1011   // Handle fixed keyframe intervals
   1012   if (ctx->cfg.kf_mode == VPX_KF_AUTO &&
   1013       ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist) {
   1014     if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist) {
   1015       flags |= VPX_EFLAG_FORCE_KF;
   1016       ctx->fixed_kf_cntr = 1;
   1017     }
   1018   }
   1019 
   1020   // Initialize the encoder instance on the first frame.
   1021   if (res == VPX_CODEC_OK && cpi != NULL) {
   1022     unsigned int lib_flags = 0;
   1023     YV12_BUFFER_CONFIG sd;
   1024     int64_t dst_time_stamp = timebase_units_to_ticks(timebase, pts);
   1025     int64_t dst_end_time_stamp =
   1026         timebase_units_to_ticks(timebase, pts + duration);
   1027     size_t size, cx_data_sz;
   1028     unsigned char *cx_data;
   1029 
   1030     // Set up internal flags
   1031     if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
   1032       cpi->b_calculate_psnr = 1;
   1033 
   1034     if (img != NULL) {
   1035       res = image2yuvconfig(img, &sd);
   1036 
   1037       // Store the original flags in to the frame buffer. Will extract the
   1038       // key frame flag when we actually encode this frame.
   1039       if (vp9_receive_raw_frame(cpi, flags | ctx->next_frame_flags,
   1040                                 &sd, dst_time_stamp, dst_end_time_stamp)) {
   1041         res = update_error_state(ctx, &cpi->common.error);
   1042       }
   1043       ctx->next_frame_flags = 0;
   1044     }
   1045 
   1046     cx_data = ctx->cx_data;
   1047     cx_data_sz = ctx->cx_data_sz;
   1048 
   1049     /* Any pending invisible frames? */
   1050     if (ctx->pending_cx_data) {
   1051       memmove(cx_data, ctx->pending_cx_data, ctx->pending_cx_data_sz);
   1052       ctx->pending_cx_data = cx_data;
   1053       cx_data += ctx->pending_cx_data_sz;
   1054       cx_data_sz -= ctx->pending_cx_data_sz;
   1055 
   1056       /* TODO: this is a minimal check, the underlying codec doesn't respect
   1057        * the buffer size anyway.
   1058        */
   1059       if (cx_data_sz < ctx->cx_data_sz / 2) {
   1060         ctx->base.err_detail = "Compressed data buffer too small";
   1061         return VPX_CODEC_ERROR;
   1062       }
   1063     }
   1064 
   1065     while (cx_data_sz >= ctx->cx_data_sz / 2 &&
   1066            -1 != vp9_get_compressed_data(cpi, &lib_flags, &size,
   1067                                          cx_data, &dst_time_stamp,
   1068                                          &dst_end_time_stamp, !img)) {
   1069       if (size) {
   1070         vpx_codec_cx_pkt_t pkt;
   1071 
   1072 #if CONFIG_SPATIAL_SVC
   1073         if (cpi->use_svc)
   1074           cpi->svc.layer_context[cpi->svc.spatial_layer_id *
   1075               cpi->svc.number_temporal_layers].layer_size += size;
   1076 #endif
   1077 
   1078         // Pack invisible frames with the next visible frame
   1079         if (!cpi->common.show_frame ||
   1080             (cpi->use_svc &&
   1081              cpi->svc.spatial_layer_id < cpi->svc.number_spatial_layers - 1)
   1082             ) {
   1083           if (ctx->pending_cx_data == 0)
   1084             ctx->pending_cx_data = cx_data;
   1085           ctx->pending_cx_data_sz += size;
   1086           ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
   1087           ctx->pending_frame_magnitude |= size;
   1088           cx_data += size;
   1089           cx_data_sz -= size;
   1090 
   1091           if (ctx->output_cx_pkt_cb.output_cx_pkt) {
   1092             pkt.kind = VPX_CODEC_CX_FRAME_PKT;
   1093             pkt.data.frame.pts = ticks_to_timebase_units(timebase,
   1094                                                          dst_time_stamp);
   1095             pkt.data.frame.duration =
   1096                (unsigned long)ticks_to_timebase_units(timebase,
   1097                    dst_end_time_stamp - dst_time_stamp);
   1098             pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
   1099             pkt.data.frame.buf = ctx->pending_cx_data;
   1100             pkt.data.frame.sz  = size;
   1101             ctx->pending_cx_data = NULL;
   1102             ctx->pending_cx_data_sz = 0;
   1103             ctx->pending_frame_count = 0;
   1104             ctx->pending_frame_magnitude = 0;
   1105             ctx->output_cx_pkt_cb.output_cx_pkt(
   1106                 &pkt, ctx->output_cx_pkt_cb.user_priv);
   1107           }
   1108           continue;
   1109         }
   1110 
   1111         // Add the frame packet to the list of returned packets.
   1112         pkt.kind = VPX_CODEC_CX_FRAME_PKT;
   1113         pkt.data.frame.pts = ticks_to_timebase_units(timebase, dst_time_stamp);
   1114         pkt.data.frame.duration =
   1115            (unsigned long)ticks_to_timebase_units(timebase,
   1116                dst_end_time_stamp - dst_time_stamp);
   1117         pkt.data.frame.flags = get_frame_pkt_flags(cpi, lib_flags);
   1118 
   1119         if (ctx->pending_cx_data) {
   1120           ctx->pending_frame_sizes[ctx->pending_frame_count++] = size;
   1121           ctx->pending_frame_magnitude |= size;
   1122           ctx->pending_cx_data_sz += size;
   1123           // write the superframe only for the case when
   1124           if (!ctx->output_cx_pkt_cb.output_cx_pkt)
   1125             size += write_superframe_index(ctx);
   1126           pkt.data.frame.buf = ctx->pending_cx_data;
   1127           pkt.data.frame.sz  = ctx->pending_cx_data_sz;
   1128           ctx->pending_cx_data = NULL;
   1129           ctx->pending_cx_data_sz = 0;
   1130           ctx->pending_frame_count = 0;
   1131           ctx->pending_frame_magnitude = 0;
   1132         } else {
   1133           pkt.data.frame.buf = cx_data;
   1134           pkt.data.frame.sz  = size;
   1135         }
   1136         pkt.data.frame.partition_id = -1;
   1137 
   1138         if(ctx->output_cx_pkt_cb.output_cx_pkt)
   1139           ctx->output_cx_pkt_cb.output_cx_pkt(&pkt,
   1140                                               ctx->output_cx_pkt_cb.user_priv);
   1141         else
   1142           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
   1143 
   1144         cx_data += size;
   1145         cx_data_sz -= size;
   1146 #if VPX_ENCODER_ABI_VERSION > (5 + VPX_CODEC_ABI_VERSION)
   1147 #if CONFIG_SPATIAL_SVC
   1148         if (cpi->use_svc && !ctx->output_cx_pkt_cb.output_cx_pkt) {
   1149           vpx_codec_cx_pkt_t pkt_sizes, pkt_psnr;
   1150           int sl;
   1151           vp9_zero(pkt_sizes);
   1152           vp9_zero(pkt_psnr);
   1153           pkt_sizes.kind = VPX_CODEC_SPATIAL_SVC_LAYER_SIZES;
   1154           pkt_psnr.kind = VPX_CODEC_SPATIAL_SVC_LAYER_PSNR;
   1155           for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
   1156             LAYER_CONTEXT *lc =
   1157                 &cpi->svc.layer_context[sl * cpi->svc.number_temporal_layers];
   1158             pkt_sizes.data.layer_sizes[sl] = lc->layer_size;
   1159             pkt_psnr.data.layer_psnr[sl] = lc->psnr_pkt;
   1160             lc->layer_size = 0;
   1161           }
   1162 
   1163           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt_sizes);
   1164 
   1165           vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt_psnr);
   1166         }
   1167 #endif
   1168 #endif
   1169         if (is_one_pass_cbr_svc(cpi) &&
   1170             (cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1)) {
   1171           // Encoded all spatial layers; exit loop.
   1172           break;
   1173         }
   1174       }
   1175     }
   1176   }
   1177 
   1178   return res;
   1179 }
   1180 
   1181 static const vpx_codec_cx_pkt_t *encoder_get_cxdata(vpx_codec_alg_priv_t *ctx,
   1182                                                     vpx_codec_iter_t *iter) {
   1183   return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
   1184 }
   1185 
   1186 static vpx_codec_err_t ctrl_set_reference(vpx_codec_alg_priv_t *ctx,
   1187                                           va_list args) {
   1188   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
   1189 
   1190   if (frame != NULL) {
   1191     YV12_BUFFER_CONFIG sd;
   1192 
   1193     image2yuvconfig(&frame->img, &sd);
   1194     vp9_set_reference_enc(ctx->cpi, ref_frame_to_vp9_reframe(frame->frame_type),
   1195                           &sd);
   1196     return VPX_CODEC_OK;
   1197   } else {
   1198     return VPX_CODEC_INVALID_PARAM;
   1199   }
   1200 }
   1201 
   1202 static vpx_codec_err_t ctrl_copy_reference(vpx_codec_alg_priv_t *ctx,
   1203                                            va_list args) {
   1204   vpx_ref_frame_t *const frame = va_arg(args, vpx_ref_frame_t *);
   1205 
   1206   if (frame != NULL) {
   1207     YV12_BUFFER_CONFIG sd;
   1208 
   1209     image2yuvconfig(&frame->img, &sd);
   1210     vp9_copy_reference_enc(ctx->cpi,
   1211                            ref_frame_to_vp9_reframe(frame->frame_type), &sd);
   1212     return VPX_CODEC_OK;
   1213   } else {
   1214     return VPX_CODEC_INVALID_PARAM;
   1215   }
   1216 }
   1217 
   1218 static vpx_codec_err_t ctrl_get_reference(vpx_codec_alg_priv_t *ctx,
   1219                                           va_list args) {
   1220   vp9_ref_frame_t *const frame = va_arg(args, vp9_ref_frame_t *);
   1221 
   1222   if (frame != NULL) {
   1223     YV12_BUFFER_CONFIG *fb = get_ref_frame(&ctx->cpi->common, frame->idx);
   1224     if (fb == NULL) return VPX_CODEC_ERROR;
   1225 
   1226     yuvconfig2image(&frame->img, fb, NULL);
   1227     return VPX_CODEC_OK;
   1228   } else {
   1229     return VPX_CODEC_INVALID_PARAM;
   1230   }
   1231 }
   1232 
   1233 static vpx_codec_err_t ctrl_set_previewpp(vpx_codec_alg_priv_t *ctx,
   1234                                           va_list args) {
   1235 #if CONFIG_VP9_POSTPROC
   1236   vp8_postproc_cfg_t *config = va_arg(args, vp8_postproc_cfg_t *);
   1237   if (config != NULL) {
   1238     ctx->preview_ppcfg = *config;
   1239     return VPX_CODEC_OK;
   1240   } else {
   1241     return VPX_CODEC_INVALID_PARAM;
   1242   }
   1243 #else
   1244   (void)ctx;
   1245   (void)args;
   1246   return VPX_CODEC_INCAPABLE;
   1247 #endif
   1248 }
   1249 
   1250 
   1251 static vpx_image_t *encoder_get_preview(vpx_codec_alg_priv_t *ctx) {
   1252   YV12_BUFFER_CONFIG sd;
   1253   vp9_ppflags_t flags;
   1254   vp9_zero(flags);
   1255 
   1256   if (ctx->preview_ppcfg.post_proc_flag) {
   1257     flags.post_proc_flag   = ctx->preview_ppcfg.post_proc_flag;
   1258     flags.deblocking_level = ctx->preview_ppcfg.deblocking_level;
   1259     flags.noise_level      = ctx->preview_ppcfg.noise_level;
   1260   }
   1261 
   1262   if (vp9_get_preview_raw_frame(ctx->cpi, &sd, &flags) == 0) {
   1263     yuvconfig2image(&ctx->preview_img, &sd, NULL);
   1264     return &ctx->preview_img;
   1265   } else {
   1266     return NULL;
   1267   }
   1268 }
   1269 
   1270 static vpx_codec_err_t ctrl_set_roi_map(vpx_codec_alg_priv_t *ctx,
   1271                                         va_list args) {
   1272   (void)ctx;
   1273   (void)args;
   1274 
   1275   // TODO(yaowu): Need to re-implement and test for VP9.
   1276   return VPX_CODEC_INVALID_PARAM;
   1277 }
   1278 
   1279 
   1280 static vpx_codec_err_t ctrl_set_active_map(vpx_codec_alg_priv_t *ctx,
   1281                                            va_list args) {
   1282   vpx_active_map_t *const map = va_arg(args, vpx_active_map_t *);
   1283 
   1284   if (map) {
   1285     if (!vp9_set_active_map(ctx->cpi, map->active_map,
   1286                             (int)map->rows, (int)map->cols))
   1287       return VPX_CODEC_OK;
   1288     else
   1289       return VPX_CODEC_INVALID_PARAM;
   1290   } else {
   1291     return VPX_CODEC_INVALID_PARAM;
   1292   }
   1293 }
   1294 
   1295 static vpx_codec_err_t ctrl_get_active_map(vpx_codec_alg_priv_t *ctx,
   1296                                            va_list args) {
   1297   vpx_active_map_t *const map = va_arg(args, vpx_active_map_t *);
   1298 
   1299   if (map) {
   1300     if (!vp9_get_active_map(ctx->cpi, map->active_map,
   1301                             (int)map->rows, (int)map->cols))
   1302       return VPX_CODEC_OK;
   1303     else
   1304       return VPX_CODEC_INVALID_PARAM;
   1305   } else {
   1306     return VPX_CODEC_INVALID_PARAM;
   1307   }
   1308 }
   1309 
   1310 static vpx_codec_err_t ctrl_set_scale_mode(vpx_codec_alg_priv_t *ctx,
   1311                                            va_list args) {
   1312   vpx_scaling_mode_t *const mode = va_arg(args, vpx_scaling_mode_t *);
   1313 
   1314   if (mode) {
   1315     const int res = vp9_set_internal_size(ctx->cpi,
   1316                                           (VPX_SCALING)mode->h_scaling_mode,
   1317                                           (VPX_SCALING)mode->v_scaling_mode);
   1318     return (res == 0) ? VPX_CODEC_OK : VPX_CODEC_INVALID_PARAM;
   1319   } else {
   1320     return VPX_CODEC_INVALID_PARAM;
   1321   }
   1322 }
   1323 
   1324 static vpx_codec_err_t ctrl_set_svc(vpx_codec_alg_priv_t *ctx, va_list args) {
   1325   int data = va_arg(args, int);
   1326   const vpx_codec_enc_cfg_t *cfg = &ctx->cfg;
   1327   // Both one-pass and two-pass RC are supported now.
   1328   // User setting this has to make sure of the following.
   1329   // In two-pass setting: either (but not both)
   1330   //      cfg->ss_number_layers > 1, or cfg->ts_number_layers > 1
   1331   // In one-pass setting:
   1332   //      either or both cfg->ss_number_layers > 1, or cfg->ts_number_layers > 1
   1333 
   1334   vp9_set_svc(ctx->cpi, data);
   1335 
   1336   if (data == 1 &&
   1337       (cfg->g_pass == VPX_RC_FIRST_PASS ||
   1338        cfg->g_pass == VPX_RC_LAST_PASS) &&
   1339        cfg->ss_number_layers > 1 &&
   1340        cfg->ts_number_layers > 1) {
   1341     return VPX_CODEC_INVALID_PARAM;
   1342   }
   1343   return VPX_CODEC_OK;
   1344 }
   1345 
   1346 static vpx_codec_err_t ctrl_set_svc_layer_id(vpx_codec_alg_priv_t *ctx,
   1347                                              va_list args) {
   1348   vpx_svc_layer_id_t *const data = va_arg(args, vpx_svc_layer_id_t *);
   1349   VP9_COMP *const cpi = (VP9_COMP *)ctx->cpi;
   1350   SVC *const svc = &cpi->svc;
   1351 
   1352   svc->first_spatial_layer_to_encode = data->spatial_layer_id;
   1353   svc->spatial_layer_to_encode = data->spatial_layer_id;
   1354   svc->temporal_layer_id = data->temporal_layer_id;
   1355   // Checks on valid layer_id input.
   1356   if (svc->temporal_layer_id < 0 ||
   1357       svc->temporal_layer_id >= (int)ctx->cfg.ts_number_layers) {
   1358     return VPX_CODEC_INVALID_PARAM;
   1359   }
   1360   if (svc->first_spatial_layer_to_encode < 0 ||
   1361       svc->first_spatial_layer_to_encode >= (int)ctx->cfg.ss_number_layers) {
   1362     return VPX_CODEC_INVALID_PARAM;
   1363   }
   1364   // First spatial layer to encode not implemented for two-pass.
   1365   if (is_two_pass_svc(cpi) && svc->first_spatial_layer_to_encode > 0)
   1366     return VPX_CODEC_INVALID_PARAM;
   1367   return VPX_CODEC_OK;
   1368 }
   1369 
   1370 static vpx_codec_err_t ctrl_get_svc_layer_id(vpx_codec_alg_priv_t *ctx,
   1371                                              va_list args) {
   1372   vpx_svc_layer_id_t *data = va_arg(args, vpx_svc_layer_id_t *);
   1373   VP9_COMP *const cpi = (VP9_COMP *)ctx->cpi;
   1374   SVC *const svc = &cpi->svc;
   1375 
   1376   data->spatial_layer_id = svc->spatial_layer_id;
   1377   data->temporal_layer_id = svc->temporal_layer_id;
   1378 
   1379   return VPX_CODEC_OK;
   1380 }
   1381 
   1382 static vpx_codec_err_t ctrl_set_svc_parameters(vpx_codec_alg_priv_t *ctx,
   1383                                                va_list args) {
   1384   VP9_COMP *const cpi = ctx->cpi;
   1385   vpx_svc_extra_cfg_t *const params = va_arg(args, vpx_svc_extra_cfg_t *);
   1386   int sl, tl;
   1387 
   1388   // Number of temporal layers and number of spatial layers have to be set
   1389   // properly before calling this control function.
   1390   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
   1391     for (tl = 0; tl < cpi->svc.number_temporal_layers; ++tl) {
   1392       const int layer =
   1393           LAYER_IDS_TO_IDX(sl, tl, cpi->svc.number_temporal_layers);
   1394       LAYER_CONTEXT *lc =
   1395           &cpi->svc.layer_context[layer];
   1396       lc->max_q = params->max_quantizers[sl];
   1397       lc->min_q = params->min_quantizers[sl];
   1398       lc->scaling_factor_num = params->scaling_factor_num[sl];
   1399       lc->scaling_factor_den = params->scaling_factor_den[sl];
   1400     }
   1401   }
   1402 
   1403   return VPX_CODEC_OK;
   1404 }
   1405 
   1406 static vpx_codec_err_t ctrl_set_svc_ref_frame_config(vpx_codec_alg_priv_t *ctx,
   1407                                                      va_list args) {
   1408   VP9_COMP *const cpi = ctx->cpi;
   1409   vpx_svc_ref_frame_config_t *data = va_arg(args, vpx_svc_ref_frame_config_t *);
   1410   int sl;
   1411   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
   1412     cpi->svc.ext_frame_flags[sl] = data->frame_flags[sl];
   1413     cpi->svc.ext_lst_fb_idx[sl] = data->lst_fb_idx[sl];
   1414     cpi->svc.ext_gld_fb_idx[sl] = data->gld_fb_idx[sl];
   1415     cpi->svc.ext_alt_fb_idx[sl] = data->alt_fb_idx[sl];
   1416   }
   1417   return VPX_CODEC_OK;
   1418 }
   1419 
   1420 static vpx_codec_err_t ctrl_register_cx_callback(vpx_codec_alg_priv_t *ctx,
   1421                                                  va_list args) {
   1422   vpx_codec_priv_output_cx_pkt_cb_pair_t *cbp =
   1423       (vpx_codec_priv_output_cx_pkt_cb_pair_t *)va_arg(args, void *);
   1424   ctx->output_cx_pkt_cb.output_cx_pkt = cbp->output_cx_pkt;
   1425   ctx->output_cx_pkt_cb.user_priv = cbp->user_priv;
   1426 
   1427   return VPX_CODEC_OK;
   1428 }
   1429 
   1430 static vpx_codec_err_t ctrl_set_tune_content(vpx_codec_alg_priv_t *ctx,
   1431                                              va_list args) {
   1432   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
   1433   extra_cfg.content = CAST(VP9E_SET_TUNE_CONTENT, args);
   1434   return update_extra_cfg(ctx, &extra_cfg);
   1435 }
   1436 
   1437 static vpx_codec_err_t ctrl_set_color_space(vpx_codec_alg_priv_t *ctx,
   1438                                             va_list args) {
   1439   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
   1440   extra_cfg.color_space = CAST(VP9E_SET_COLOR_SPACE, args);
   1441   return update_extra_cfg(ctx, &extra_cfg);
   1442 }
   1443 
   1444 static vpx_codec_err_t ctrl_set_color_range(vpx_codec_alg_priv_t *ctx,
   1445                                             va_list args) {
   1446   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
   1447   extra_cfg.color_range = CAST(VP9E_SET_COLOR_RANGE, args);
   1448   return update_extra_cfg(ctx, &extra_cfg);
   1449 }
   1450 
   1451 static vpx_codec_err_t ctrl_set_render_size(vpx_codec_alg_priv_t *ctx,
   1452                                             va_list args) {
   1453   struct vp9_extracfg extra_cfg = ctx->extra_cfg;
   1454   int *const render_size = va_arg(args, int *);
   1455   extra_cfg.render_width  = render_size[0];
   1456   extra_cfg.render_height = render_size[1];
   1457   return update_extra_cfg(ctx, &extra_cfg);
   1458 }
   1459 
   1460 static vpx_codec_ctrl_fn_map_t encoder_ctrl_maps[] = {
   1461   {VP8_COPY_REFERENCE,                ctrl_copy_reference},
   1462 
   1463   // Setters
   1464   {VP8_SET_REFERENCE,                 ctrl_set_reference},
   1465   {VP8_SET_POSTPROC,                  ctrl_set_previewpp},
   1466   {VP8E_SET_ROI_MAP,                  ctrl_set_roi_map},
   1467   {VP8E_SET_ACTIVEMAP,                ctrl_set_active_map},
   1468   {VP8E_SET_SCALEMODE,                ctrl_set_scale_mode},
   1469   {VP8E_SET_CPUUSED,                  ctrl_set_cpuused},
   1470   {VP8E_SET_ENABLEAUTOALTREF,         ctrl_set_enable_auto_alt_ref},
   1471   {VP8E_SET_SHARPNESS,                ctrl_set_sharpness},
   1472   {VP8E_SET_STATIC_THRESHOLD,         ctrl_set_static_thresh},
   1473   {VP9E_SET_TILE_COLUMNS,             ctrl_set_tile_columns},
   1474   {VP9E_SET_TILE_ROWS,                ctrl_set_tile_rows},
   1475   {VP8E_SET_ARNR_MAXFRAMES,           ctrl_set_arnr_max_frames},
   1476   {VP8E_SET_ARNR_STRENGTH,            ctrl_set_arnr_strength},
   1477   {VP8E_SET_ARNR_TYPE,                ctrl_set_arnr_type},
   1478   {VP8E_SET_TUNING,                   ctrl_set_tuning},
   1479   {VP8E_SET_CQ_LEVEL,                 ctrl_set_cq_level},
   1480   {VP8E_SET_MAX_INTRA_BITRATE_PCT,    ctrl_set_rc_max_intra_bitrate_pct},
   1481   {VP9E_SET_MAX_INTER_BITRATE_PCT,    ctrl_set_rc_max_inter_bitrate_pct},
   1482   {VP9E_SET_GF_CBR_BOOST_PCT,         ctrl_set_rc_gf_cbr_boost_pct},
   1483   {VP9E_SET_LOSSLESS,                 ctrl_set_lossless},
   1484   {VP9E_SET_FRAME_PARALLEL_DECODING,  ctrl_set_frame_parallel_decoding_mode},
   1485   {VP9E_SET_AQ_MODE,                  ctrl_set_aq_mode},
   1486   {VP9E_SET_FRAME_PERIODIC_BOOST,     ctrl_set_frame_periodic_boost},
   1487   {VP9E_SET_SVC,                      ctrl_set_svc},
   1488   {VP9E_SET_SVC_PARAMETERS,           ctrl_set_svc_parameters},
   1489   {VP9E_REGISTER_CX_CALLBACK,         ctrl_register_cx_callback},
   1490   {VP9E_SET_SVC_LAYER_ID,             ctrl_set_svc_layer_id},
   1491   {VP9E_SET_TUNE_CONTENT,             ctrl_set_tune_content},
   1492   {VP9E_SET_COLOR_SPACE,              ctrl_set_color_space},
   1493   {VP9E_SET_COLOR_RANGE,              ctrl_set_color_range},
   1494   {VP9E_SET_NOISE_SENSITIVITY,        ctrl_set_noise_sensitivity},
   1495   {VP9E_SET_MIN_GF_INTERVAL,          ctrl_set_min_gf_interval},
   1496   {VP9E_SET_MAX_GF_INTERVAL,          ctrl_set_max_gf_interval},
   1497   {VP9E_SET_SVC_REF_FRAME_CONFIG,     ctrl_set_svc_ref_frame_config},
   1498   {VP9E_SET_RENDER_SIZE,              ctrl_set_render_size},
   1499 
   1500   // Getters
   1501   {VP8E_GET_LAST_QUANTIZER,           ctrl_get_quantizer},
   1502   {VP8E_GET_LAST_QUANTIZER_64,        ctrl_get_quantizer64},
   1503   {VP9_GET_REFERENCE,                 ctrl_get_reference},
   1504   {VP9E_GET_SVC_LAYER_ID,             ctrl_get_svc_layer_id},
   1505   {VP9E_GET_ACTIVEMAP,                ctrl_get_active_map},
   1506 
   1507   { -1, NULL},
   1508 };
   1509 
   1510 static vpx_codec_enc_cfg_map_t encoder_usage_cfg_map[] = {
   1511   {
   1512     0,
   1513     {  // NOLINT
   1514       0,                  // g_usage
   1515       8,                  // g_threads
   1516       0,                  // g_profile
   1517 
   1518       320,                // g_width
   1519       240,                // g_height
   1520       VPX_BITS_8,         // g_bit_depth
   1521       8,                  // g_input_bit_depth
   1522 
   1523       {1, 30},            // g_timebase
   1524 
   1525       0,                  // g_error_resilient
   1526 
   1527       VPX_RC_ONE_PASS,    // g_pass
   1528 
   1529       25,                 // g_lag_in_frames
   1530 
   1531       0,                  // rc_dropframe_thresh
   1532       0,                  // rc_resize_allowed
   1533       0,                  // rc_scaled_width
   1534       0,                  // rc_scaled_height
   1535       60,                 // rc_resize_down_thresold
   1536       30,                 // rc_resize_up_thresold
   1537 
   1538       VPX_VBR,            // rc_end_usage
   1539       {NULL, 0},          // rc_twopass_stats_in
   1540       {NULL, 0},          // rc_firstpass_mb_stats_in
   1541       256,                // rc_target_bandwidth
   1542       0,                  // rc_min_quantizer
   1543       63,                 // rc_max_quantizer
   1544       25,                 // rc_undershoot_pct
   1545       25,                 // rc_overshoot_pct
   1546 
   1547       6000,               // rc_max_buffer_size
   1548       4000,               // rc_buffer_initial_size
   1549       5000,               // rc_buffer_optimal_size
   1550 
   1551       50,                 // rc_two_pass_vbrbias
   1552       0,                  // rc_two_pass_vbrmin_section
   1553       2000,               // rc_two_pass_vbrmax_section
   1554 
   1555       // keyframing settings (kf)
   1556       VPX_KF_AUTO,        // g_kfmode
   1557       0,                  // kf_min_dist
   1558       9999,               // kf_max_dist
   1559 
   1560       VPX_SS_DEFAULT_LAYERS,  // ss_number_layers
   1561       {0},
   1562       {0},                    // ss_target_bitrate
   1563       1,                      // ts_number_layers
   1564       {0},                    // ts_target_bitrate
   1565       {0},                    // ts_rate_decimator
   1566       0,                      // ts_periodicity
   1567       {0},                    // ts_layer_id
   1568       {0},                  // layer_taget_bitrate
   1569       0                     // temporal_layering_mode
   1570     }
   1571   },
   1572 };
   1573 
   1574 #ifndef VERSION_STRING
   1575 #define VERSION_STRING
   1576 #endif
   1577 CODEC_INTERFACE(vpx_codec_vp9_cx) = {
   1578   "WebM Project VP9 Encoder" VERSION_STRING,
   1579   VPX_CODEC_INTERNAL_ABI_VERSION,
   1580 #if CONFIG_VP9_HIGHBITDEPTH
   1581   VPX_CODEC_CAP_HIGHBITDEPTH |
   1582 #endif
   1583   VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR,  // vpx_codec_caps_t
   1584   encoder_init,       // vpx_codec_init_fn_t
   1585   encoder_destroy,    // vpx_codec_destroy_fn_t
   1586   encoder_ctrl_maps,  // vpx_codec_ctrl_fn_map_t
   1587   {  // NOLINT
   1588     NULL,  // vpx_codec_peek_si_fn_t
   1589     NULL,  // vpx_codec_get_si_fn_t
   1590     NULL,  // vpx_codec_decode_fn_t
   1591     NULL,  // vpx_codec_frame_get_fn_t
   1592     NULL   // vpx_codec_set_fb_fn_t
   1593   },
   1594   {  // NOLINT
   1595     1,                      // 1 cfg map
   1596     encoder_usage_cfg_map,  // vpx_codec_enc_cfg_map_t
   1597     encoder_encode,         // vpx_codec_encode_fn_t
   1598     encoder_get_cxdata,     // vpx_codec_get_cx_data_fn_t
   1599     encoder_set_config,     // vpx_codec_enc_config_set_fn_t
   1600     NULL,        // vpx_codec_get_global_headers_fn_t
   1601     encoder_get_preview,    // vpx_codec_get_preview_frame_fn_t
   1602     NULL         // vpx_codec_enc_mr_get_mem_loc_fn_t
   1603   }
   1604 };
   1605