Home | History | Annotate | Download | only in vp8
      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 
     12 #include "vp8_rtcd.h"
     13 #include "vpx/vpx_codec.h"
     14 #include "vpx/internal/vpx_codec_internal.h"
     15 #include "vpx_version.h"
     16 #include "vp8/encoder/onyx_int.h"
     17 #include "vpx/vp8cx.h"
     18 #include "vp8/encoder/firstpass.h"
     19 #include "vp8/common/onyx.h"
     20 #include <stdlib.h>
     21 #include <string.h>
     22 
     23 struct vp8_extracfg
     24 {
     25     struct vpx_codec_pkt_list *pkt_list;
     26     int                         cpu_used;                    /** available cpu percentage in 1/16*/
     27     unsigned int                enable_auto_alt_ref;           /** if encoder decides to uses alternate reference frame */
     28     unsigned int                noise_sensitivity;
     29     unsigned int                Sharpness;
     30     unsigned int                static_thresh;
     31     unsigned int                token_partitions;
     32     unsigned int                arnr_max_frames;    /* alt_ref Noise Reduction Max Frame Count */
     33     unsigned int                arnr_strength;    /* alt_ref Noise Reduction Strength */
     34     unsigned int                arnr_type;        /* alt_ref filter type */
     35     vp8e_tuning                 tuning;
     36     unsigned int                cq_level;         /* constrained quality level */
     37     unsigned int                rc_max_intra_bitrate_pct;
     38 
     39 };
     40 
     41 struct extraconfig_map
     42 {
     43     int                 usage;
     44     struct vp8_extracfg cfg;
     45 };
     46 
     47 static const struct extraconfig_map extracfg_map[] =
     48 {
     49     {
     50         0,
     51         {
     52             NULL,
     53 #if !(CONFIG_REALTIME_ONLY)
     54             0,                          /* cpu_used      */
     55 #else
     56             4,                          /* cpu_used      */
     57 #endif
     58             0,                          /* enable_auto_alt_ref */
     59             0,                          /* noise_sensitivity */
     60             0,                          /* Sharpness */
     61             0,                          /* static_thresh */
     62 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
     63             VP8_EIGHT_TOKENPARTITION,
     64 #else
     65             VP8_ONE_TOKENPARTITION,     /* token_partitions */
     66 #endif
     67             0,                          /* arnr_max_frames */
     68             3,                          /* arnr_strength */
     69             3,                          /* arnr_type*/
     70             0,                          /* tuning*/
     71             10,                         /* cq_level */
     72             0,                          /* rc_max_intra_bitrate_pct */
     73         }
     74     }
     75 };
     76 
     77 struct vpx_codec_alg_priv
     78 {
     79     vpx_codec_priv_t        base;
     80     vpx_codec_enc_cfg_t     cfg;
     81     struct vp8_extracfg     vp8_cfg;
     82     VP8_CONFIG              oxcf;
     83     struct VP8_COMP        *cpi;
     84     unsigned char          *cx_data;
     85     unsigned int            cx_data_sz;
     86     vpx_image_t             preview_img;
     87     unsigned int            next_frame_flag;
     88     vp8_postproc_cfg_t      preview_ppcfg;
     89     /* pkt_list size depends on the maximum number of lagged frames allowed. */
     90     vpx_codec_pkt_list_decl(64) pkt_list;
     91     unsigned int                fixed_kf_cntr;
     92 };
     93 
     94 
     95 static vpx_codec_err_t
     96 update_error_state(vpx_codec_alg_priv_t                 *ctx,
     97                    const struct vpx_internal_error_info *error)
     98 {
     99     vpx_codec_err_t res;
    100 
    101     if ((res = error->error_code))
    102         ctx->base.err_detail = error->has_detail
    103                                ? error->detail
    104                                : NULL;
    105 
    106     return res;
    107 }
    108 
    109 
    110 #undef ERROR
    111 #define ERROR(str) do {\
    112         ctx->base.err_detail = str;\
    113         return VPX_CODEC_INVALID_PARAM;\
    114     } while(0)
    115 
    116 #define RANGE_CHECK(p,memb,lo,hi) do {\
    117         if(!(((p)->memb == lo || (p)->memb > (lo)) && (p)->memb <= hi)) \
    118             ERROR(#memb " out of range ["#lo".."#hi"]");\
    119     } while(0)
    120 
    121 #define RANGE_CHECK_HI(p,memb,hi) do {\
    122         if(!((p)->memb <= (hi))) \
    123             ERROR(#memb " out of range [.."#hi"]");\
    124     } while(0)
    125 
    126 #define RANGE_CHECK_LO(p,memb,lo) do {\
    127         if(!((p)->memb >= (lo))) \
    128             ERROR(#memb " out of range ["#lo"..]");\
    129     } while(0)
    130 
    131 #define RANGE_CHECK_BOOL(p,memb) do {\
    132         if(!!((p)->memb) != (p)->memb) ERROR(#memb " expected boolean");\
    133     } while(0)
    134 
    135 static vpx_codec_err_t validate_config(vpx_codec_alg_priv_t      *ctx,
    136                                        const vpx_codec_enc_cfg_t *cfg,
    137                                        const struct vp8_extracfg *vp8_cfg,
    138                                        int                        finalize)
    139 {
    140     RANGE_CHECK(cfg, g_w,                   1, 16383); /* 14 bits available */
    141     RANGE_CHECK(cfg, g_h,                   1, 16383); /* 14 bits available */
    142     RANGE_CHECK(cfg, g_timebase.den,        1, 1000000000);
    143     RANGE_CHECK(cfg, g_timebase.num,        1, cfg->g_timebase.den);
    144     RANGE_CHECK_HI(cfg, g_profile,          3);
    145     RANGE_CHECK_HI(cfg, rc_max_quantizer,   63);
    146     RANGE_CHECK_HI(cfg, rc_min_quantizer,   cfg->rc_max_quantizer);
    147     RANGE_CHECK_HI(cfg, g_threads,          64);
    148 #if CONFIG_REALTIME_ONLY
    149     RANGE_CHECK_HI(cfg, g_lag_in_frames,    0);
    150 #elif CONFIG_MULTI_RES_ENCODING
    151     if (ctx->base.enc.total_encoders > 1)
    152         RANGE_CHECK_HI(cfg, g_lag_in_frames,    0);
    153 #else
    154     RANGE_CHECK_HI(cfg, g_lag_in_frames,    25);
    155 #endif
    156     RANGE_CHECK(cfg, rc_end_usage,          VPX_VBR, VPX_Q);
    157     RANGE_CHECK_HI(cfg, rc_undershoot_pct,  1000);
    158     RANGE_CHECK_HI(cfg, rc_overshoot_pct,   1000);
    159     RANGE_CHECK_HI(cfg, rc_2pass_vbr_bias_pct, 100);
    160     RANGE_CHECK(cfg, kf_mode,               VPX_KF_DISABLED, VPX_KF_AUTO);
    161 
    162 /* TODO: add spatial re-sampling support and frame dropping in
    163  * multi-res-encoder.*/
    164 #if CONFIG_MULTI_RES_ENCODING
    165     if (ctx->base.enc.total_encoders > 1)
    166         RANGE_CHECK_HI(cfg, rc_resize_allowed,     0);
    167 #else
    168     RANGE_CHECK_BOOL(cfg, rc_resize_allowed);
    169 #endif
    170     RANGE_CHECK_HI(cfg, rc_dropframe_thresh,   100);
    171     RANGE_CHECK_HI(cfg, rc_resize_up_thresh,   100);
    172     RANGE_CHECK_HI(cfg, rc_resize_down_thresh, 100);
    173 
    174 #if CONFIG_REALTIME_ONLY
    175     RANGE_CHECK(cfg,        g_pass,         VPX_RC_ONE_PASS, VPX_RC_ONE_PASS);
    176 #elif CONFIG_MULTI_RES_ENCODING
    177     if (ctx->base.enc.total_encoders > 1)
    178         RANGE_CHECK(cfg,    g_pass,         VPX_RC_ONE_PASS, VPX_RC_ONE_PASS);
    179 #else
    180     RANGE_CHECK(cfg,        g_pass,         VPX_RC_ONE_PASS, VPX_RC_LAST_PASS);
    181 #endif
    182 
    183     /* VP8 does not support a lower bound on the keyframe interval in
    184      * automatic keyframe placement mode.
    185      */
    186     if (cfg->kf_mode != VPX_KF_DISABLED && cfg->kf_min_dist != cfg->kf_max_dist
    187         && cfg->kf_min_dist > 0)
    188         ERROR("kf_min_dist not supported in auto mode, use 0 "
    189               "or kf_max_dist instead.");
    190 
    191     RANGE_CHECK_BOOL(vp8_cfg,               enable_auto_alt_ref);
    192     RANGE_CHECK(vp8_cfg, cpu_used,           -16, 16);
    193 
    194 #if CONFIG_REALTIME_ONLY && !CONFIG_TEMPORAL_DENOISING
    195     RANGE_CHECK(vp8_cfg, noise_sensitivity,  0, 0);
    196 #else
    197     RANGE_CHECK_HI(vp8_cfg, noise_sensitivity,  6);
    198 #endif
    199 
    200     RANGE_CHECK(vp8_cfg, token_partitions,   VP8_ONE_TOKENPARTITION,
    201                 VP8_EIGHT_TOKENPARTITION);
    202     RANGE_CHECK_HI(vp8_cfg, Sharpness,       7);
    203     RANGE_CHECK(vp8_cfg, arnr_max_frames, 0, 15);
    204     RANGE_CHECK_HI(vp8_cfg, arnr_strength,   6);
    205     RANGE_CHECK(vp8_cfg, arnr_type,       1, 3);
    206     RANGE_CHECK(vp8_cfg, cq_level, 0, 63);
    207     if (finalize && (cfg->rc_end_usage == VPX_CQ || cfg->rc_end_usage == VPX_Q))
    208         RANGE_CHECK(vp8_cfg, cq_level,
    209                     cfg->rc_min_quantizer, cfg->rc_max_quantizer);
    210 
    211 #if !(CONFIG_REALTIME_ONLY)
    212     if (cfg->g_pass == VPX_RC_LAST_PASS)
    213     {
    214         size_t           packet_sz = sizeof(FIRSTPASS_STATS);
    215         int              n_packets = (int)(cfg->rc_twopass_stats_in.sz /
    216                                           packet_sz);
    217         FIRSTPASS_STATS *stats;
    218 
    219         if (!cfg->rc_twopass_stats_in.buf)
    220             ERROR("rc_twopass_stats_in.buf not set.");
    221 
    222         if (cfg->rc_twopass_stats_in.sz % packet_sz)
    223             ERROR("rc_twopass_stats_in.sz indicates truncated packet.");
    224 
    225         if (cfg->rc_twopass_stats_in.sz < 2 * packet_sz)
    226             ERROR("rc_twopass_stats_in requires at least two packets.");
    227 
    228         stats = (void*)((char *)cfg->rc_twopass_stats_in.buf
    229                 + (n_packets - 1) * packet_sz);
    230 
    231         if ((int)(stats->count + 0.5) != n_packets - 1)
    232             ERROR("rc_twopass_stats_in missing EOS stats packet");
    233     }
    234 #endif
    235 
    236     RANGE_CHECK(cfg, ts_number_layers, 1, 5);
    237 
    238     if (cfg->ts_number_layers > 1)
    239     {
    240         unsigned int i;
    241         RANGE_CHECK_HI(cfg, ts_periodicity, 16);
    242 
    243         for (i=1; i<cfg->ts_number_layers; i++)
    244             if (cfg->ts_target_bitrate[i] <= cfg->ts_target_bitrate[i-1])
    245                 ERROR("ts_target_bitrate entries are not strictly increasing");
    246 
    247         RANGE_CHECK(cfg, ts_rate_decimator[cfg->ts_number_layers-1], 1, 1);
    248         for (i=cfg->ts_number_layers-2; i>0; i--)
    249             if (cfg->ts_rate_decimator[i-1] != 2*cfg->ts_rate_decimator[i])
    250                 ERROR("ts_rate_decimator factors are not powers of 2");
    251 
    252         RANGE_CHECK_HI(cfg, ts_layer_id[i], cfg->ts_number_layers-1);
    253     }
    254 
    255 #if (CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING)
    256     if(cfg->g_threads > (1 << vp8_cfg->token_partitions))
    257         ERROR("g_threads cannot be bigger than number of token partitions");
    258 #endif
    259 
    260     return VPX_CODEC_OK;
    261 }
    262 
    263 
    264 static vpx_codec_err_t validate_img(vpx_codec_alg_priv_t *ctx,
    265                                     const vpx_image_t    *img)
    266 {
    267     switch (img->fmt)
    268     {
    269     case VPX_IMG_FMT_YV12:
    270     case VPX_IMG_FMT_I420:
    271     case VPX_IMG_FMT_VPXI420:
    272     case VPX_IMG_FMT_VPXYV12:
    273         break;
    274     default:
    275         ERROR("Invalid image format. Only YV12 and I420 images are supported");
    276     }
    277 
    278     if ((img->d_w != ctx->cfg.g_w) || (img->d_h != ctx->cfg.g_h))
    279         ERROR("Image size must match encoder init configuration size");
    280 
    281     return VPX_CODEC_OK;
    282 }
    283 
    284 
    285 static vpx_codec_err_t set_vp8e_config(VP8_CONFIG *oxcf,
    286                                        vpx_codec_enc_cfg_t cfg,
    287                                        struct vp8_extracfg vp8_cfg,
    288                                        vpx_codec_priv_enc_mr_cfg_t *mr_cfg)
    289 {
    290     oxcf->multi_threaded         = cfg.g_threads;
    291     oxcf->Version               = cfg.g_profile;
    292 
    293     oxcf->Width                 = cfg.g_w;
    294     oxcf->Height                = cfg.g_h;
    295     oxcf->timebase              = cfg.g_timebase;
    296 
    297     oxcf->error_resilient_mode = cfg.g_error_resilient;
    298 
    299     switch (cfg.g_pass)
    300     {
    301     case VPX_RC_ONE_PASS:
    302         oxcf->Mode = MODE_BESTQUALITY;
    303         break;
    304     case VPX_RC_FIRST_PASS:
    305         oxcf->Mode = MODE_FIRSTPASS;
    306         break;
    307     case VPX_RC_LAST_PASS:
    308         oxcf->Mode = MODE_SECONDPASS_BEST;
    309         break;
    310     }
    311 
    312     if (cfg.g_pass == VPX_RC_FIRST_PASS || cfg.g_pass == VPX_RC_ONE_PASS)
    313     {
    314         oxcf->allow_lag     = 0;
    315         oxcf->lag_in_frames = 0;
    316     }
    317     else
    318     {
    319         oxcf->allow_lag     = (cfg.g_lag_in_frames) > 0;
    320         oxcf->lag_in_frames = cfg.g_lag_in_frames;
    321     }
    322 
    323     oxcf->allow_df               = (cfg.rc_dropframe_thresh > 0);
    324     oxcf->drop_frames_water_mark   = cfg.rc_dropframe_thresh;
    325 
    326     oxcf->allow_spatial_resampling = cfg.rc_resize_allowed;
    327     oxcf->resample_up_water_mark   = cfg.rc_resize_up_thresh;
    328     oxcf->resample_down_water_mark = cfg.rc_resize_down_thresh;
    329 
    330     if (cfg.rc_end_usage == VPX_VBR) {
    331       oxcf->end_usage = USAGE_LOCAL_FILE_PLAYBACK;
    332     } else if (cfg.rc_end_usage == VPX_CBR) {
    333       oxcf->end_usage = USAGE_STREAM_FROM_SERVER;
    334     } else if (cfg.rc_end_usage == VPX_CQ) {
    335       oxcf->end_usage = USAGE_CONSTRAINED_QUALITY;
    336     } else if (cfg.rc_end_usage == VPX_Q) {
    337       oxcf->end_usage = USAGE_CONSTANT_QUALITY;
    338     }
    339 
    340     oxcf->target_bandwidth         = cfg.rc_target_bitrate;
    341     oxcf->rc_max_intra_bitrate_pct = vp8_cfg.rc_max_intra_bitrate_pct;
    342 
    343     oxcf->best_allowed_q           = cfg.rc_min_quantizer;
    344     oxcf->worst_allowed_q          = cfg.rc_max_quantizer;
    345     oxcf->cq_level                 = vp8_cfg.cq_level;
    346     oxcf->fixed_q = -1;
    347 
    348     oxcf->under_shoot_pct          = cfg.rc_undershoot_pct;
    349     oxcf->over_shoot_pct           = cfg.rc_overshoot_pct;
    350 
    351     oxcf->maximum_buffer_size_in_ms   = cfg.rc_buf_sz;
    352     oxcf->starting_buffer_level_in_ms = cfg.rc_buf_initial_sz;
    353     oxcf->optimal_buffer_level_in_ms  = cfg.rc_buf_optimal_sz;
    354 
    355     oxcf->maximum_buffer_size      = cfg.rc_buf_sz;
    356     oxcf->starting_buffer_level    = cfg.rc_buf_initial_sz;
    357     oxcf->optimal_buffer_level     = cfg.rc_buf_optimal_sz;
    358 
    359     oxcf->two_pass_vbrbias         = cfg.rc_2pass_vbr_bias_pct;
    360     oxcf->two_pass_vbrmin_section  = cfg.rc_2pass_vbr_minsection_pct;
    361     oxcf->two_pass_vbrmax_section  = cfg.rc_2pass_vbr_maxsection_pct;
    362 
    363     oxcf->auto_key                 = cfg.kf_mode == VPX_KF_AUTO
    364                                        && cfg.kf_min_dist != cfg.kf_max_dist;
    365     oxcf->key_freq                 = cfg.kf_max_dist;
    366 
    367     oxcf->number_of_layers         = cfg.ts_number_layers;
    368     oxcf->periodicity              = cfg.ts_periodicity;
    369 
    370     if (oxcf->number_of_layers > 1)
    371     {
    372         memcpy (oxcf->target_bitrate, cfg.ts_target_bitrate,
    373                           sizeof(cfg.ts_target_bitrate));
    374         memcpy (oxcf->rate_decimator, cfg.ts_rate_decimator,
    375                           sizeof(cfg.ts_rate_decimator));
    376         memcpy (oxcf->layer_id, cfg.ts_layer_id, sizeof(cfg.ts_layer_id));
    377     }
    378 
    379 #if CONFIG_MULTI_RES_ENCODING
    380     /* When mr_cfg is NULL, oxcf->mr_total_resolutions and oxcf->mr_encoder_id
    381      * are both memset to 0, which ensures the correct logic under this
    382      * situation.
    383      */
    384     if(mr_cfg)
    385     {
    386         oxcf->mr_total_resolutions        = mr_cfg->mr_total_resolutions;
    387         oxcf->mr_encoder_id               = mr_cfg->mr_encoder_id;
    388         oxcf->mr_down_sampling_factor.num = mr_cfg->mr_down_sampling_factor.num;
    389         oxcf->mr_down_sampling_factor.den = mr_cfg->mr_down_sampling_factor.den;
    390         oxcf->mr_low_res_mode_info        = mr_cfg->mr_low_res_mode_info;
    391     }
    392 #endif
    393 
    394     oxcf->cpu_used               = vp8_cfg.cpu_used;
    395     oxcf->encode_breakout        = vp8_cfg.static_thresh;
    396     oxcf->play_alternate         = vp8_cfg.enable_auto_alt_ref;
    397     oxcf->noise_sensitivity      = vp8_cfg.noise_sensitivity;
    398     oxcf->Sharpness              = vp8_cfg.Sharpness;
    399     oxcf->token_partitions       = vp8_cfg.token_partitions;
    400 
    401     oxcf->two_pass_stats_in      = cfg.rc_twopass_stats_in;
    402     oxcf->output_pkt_list        = vp8_cfg.pkt_list;
    403 
    404     oxcf->arnr_max_frames        = vp8_cfg.arnr_max_frames;
    405     oxcf->arnr_strength          = vp8_cfg.arnr_strength;
    406     oxcf->arnr_type              = vp8_cfg.arnr_type;
    407 
    408     oxcf->tuning                 = vp8_cfg.tuning;
    409 
    410     /*
    411         printf("Current VP8 Settings: \n");
    412         printf("target_bandwidth: %d\n", oxcf->target_bandwidth);
    413         printf("noise_sensitivity: %d\n", oxcf->noise_sensitivity);
    414         printf("Sharpness: %d\n",    oxcf->Sharpness);
    415         printf("cpu_used: %d\n",  oxcf->cpu_used);
    416         printf("Mode: %d\n",     oxcf->Mode);
    417         printf("delete_first_pass_file: %d\n",  oxcf->delete_first_pass_file);
    418         printf("auto_key: %d\n",  oxcf->auto_key);
    419         printf("key_freq: %d\n", oxcf->key_freq);
    420         printf("end_usage: %d\n", oxcf->end_usage);
    421         printf("under_shoot_pct: %d\n", oxcf->under_shoot_pct);
    422         printf("over_shoot_pct: %d\n", oxcf->over_shoot_pct);
    423         printf("starting_buffer_level: %d\n", oxcf->starting_buffer_level);
    424         printf("optimal_buffer_level: %d\n",  oxcf->optimal_buffer_level);
    425         printf("maximum_buffer_size: %d\n", oxcf->maximum_buffer_size);
    426         printf("fixed_q: %d\n",  oxcf->fixed_q);
    427         printf("worst_allowed_q: %d\n", oxcf->worst_allowed_q);
    428         printf("best_allowed_q: %d\n", oxcf->best_allowed_q);
    429         printf("allow_spatial_resampling: %d\n",  oxcf->allow_spatial_resampling);
    430         printf("resample_down_water_mark: %d\n", oxcf->resample_down_water_mark);
    431         printf("resample_up_water_mark: %d\n", oxcf->resample_up_water_mark);
    432         printf("allow_df: %d\n", oxcf->allow_df);
    433         printf("drop_frames_water_mark: %d\n", oxcf->drop_frames_water_mark);
    434         printf("two_pass_vbrbias: %d\n",  oxcf->two_pass_vbrbias);
    435         printf("two_pass_vbrmin_section: %d\n", oxcf->two_pass_vbrmin_section);
    436         printf("two_pass_vbrmax_section: %d\n", oxcf->two_pass_vbrmax_section);
    437         printf("allow_lag: %d\n", oxcf->allow_lag);
    438         printf("lag_in_frames: %d\n", oxcf->lag_in_frames);
    439         printf("play_alternate: %d\n", oxcf->play_alternate);
    440         printf("Version: %d\n", oxcf->Version);
    441         printf("multi_threaded: %d\n",   oxcf->multi_threaded);
    442         printf("encode_breakout: %d\n", oxcf->encode_breakout);
    443     */
    444     return VPX_CODEC_OK;
    445 }
    446 
    447 static vpx_codec_err_t vp8e_set_config(vpx_codec_alg_priv_t       *ctx,
    448                                        const vpx_codec_enc_cfg_t  *cfg)
    449 {
    450     vpx_codec_err_t res;
    451 
    452     if (((cfg->g_w != ctx->cfg.g_w) || (cfg->g_h != ctx->cfg.g_h))
    453         && (cfg->g_lag_in_frames > 1 || cfg->g_pass != VPX_RC_ONE_PASS))
    454         ERROR("Cannot change width or height after initialization");
    455 
    456     /* Prevent increasing lag_in_frames. This check is stricter than it needs
    457      * to be -- the limit is not increasing past the first lag_in_frames
    458      * value, but we don't track the initial config, only the last successful
    459      * config.
    460      */
    461     if ((cfg->g_lag_in_frames > ctx->cfg.g_lag_in_frames))
    462         ERROR("Cannot increase lag_in_frames");
    463 
    464     res = validate_config(ctx, cfg, &ctx->vp8_cfg, 0);
    465 
    466     if (!res)
    467     {
    468         ctx->cfg = *cfg;
    469         set_vp8e_config(&ctx->oxcf, ctx->cfg, ctx->vp8_cfg, NULL);
    470         vp8_change_config(ctx->cpi, &ctx->oxcf);
    471     }
    472 
    473     return res;
    474 }
    475 
    476 
    477 int vp8_reverse_trans(int);
    478 
    479 
    480 static vpx_codec_err_t get_param(vpx_codec_alg_priv_t *ctx,
    481                                  int                   ctrl_id,
    482                                  va_list               args)
    483 {
    484     void *arg = va_arg(args, void *);
    485 
    486 #define MAP(id, var) case id: *(RECAST(id, arg)) = var; break
    487 
    488     if (!arg)
    489         return VPX_CODEC_INVALID_PARAM;
    490 
    491     switch (ctrl_id)
    492     {
    493         MAP(VP8E_GET_LAST_QUANTIZER, vp8_get_quantizer(ctx->cpi));
    494         MAP(VP8E_GET_LAST_QUANTIZER_64, vp8_reverse_trans(vp8_get_quantizer(ctx->cpi)));
    495     }
    496 
    497     return VPX_CODEC_OK;
    498 #undef MAP
    499 }
    500 
    501 
    502 static vpx_codec_err_t set_param(vpx_codec_alg_priv_t *ctx,
    503                                  int                   ctrl_id,
    504                                  va_list               args)
    505 {
    506     vpx_codec_err_t     res  = VPX_CODEC_OK;
    507     struct vp8_extracfg xcfg = ctx->vp8_cfg;
    508 
    509 #define MAP(id, var) case id: var = CAST(id, args); break;
    510 
    511     switch (ctrl_id)
    512     {
    513         MAP(VP8E_SET_CPUUSED,               xcfg.cpu_used);
    514         MAP(VP8E_SET_ENABLEAUTOALTREF,      xcfg.enable_auto_alt_ref);
    515         MAP(VP8E_SET_NOISE_SENSITIVITY,     xcfg.noise_sensitivity);
    516         MAP(VP8E_SET_SHARPNESS,             xcfg.Sharpness);
    517         MAP(VP8E_SET_STATIC_THRESHOLD,      xcfg.static_thresh);
    518         MAP(VP8E_SET_TOKEN_PARTITIONS,      xcfg.token_partitions);
    519 
    520         MAP(VP8E_SET_ARNR_MAXFRAMES,        xcfg.arnr_max_frames);
    521         MAP(VP8E_SET_ARNR_STRENGTH ,        xcfg.arnr_strength);
    522         MAP(VP8E_SET_ARNR_TYPE     ,        xcfg.arnr_type);
    523         MAP(VP8E_SET_TUNING,                xcfg.tuning);
    524         MAP(VP8E_SET_CQ_LEVEL,              xcfg.cq_level);
    525         MAP(VP8E_SET_MAX_INTRA_BITRATE_PCT, xcfg.rc_max_intra_bitrate_pct);
    526 
    527     }
    528 
    529     res = validate_config(ctx, &ctx->cfg, &xcfg, 0);
    530 
    531     if (!res)
    532     {
    533         ctx->vp8_cfg = xcfg;
    534         set_vp8e_config(&ctx->oxcf, ctx->cfg, ctx->vp8_cfg, NULL);
    535         vp8_change_config(ctx->cpi, &ctx->oxcf);
    536     }
    537 
    538     return res;
    539 #undef MAP
    540 }
    541 
    542 static vpx_codec_err_t vp8e_mr_alloc_mem(const vpx_codec_enc_cfg_t *cfg,
    543                                         void **mem_loc)
    544 {
    545     vpx_codec_err_t res = 0;
    546 
    547 #if CONFIG_MULTI_RES_ENCODING
    548     LOWER_RES_FRAME_INFO *shared_mem_loc;
    549     int mb_rows = ((cfg->g_w + 15) >>4);
    550     int mb_cols = ((cfg->g_h + 15) >>4);
    551 
    552     shared_mem_loc = calloc(1, sizeof(LOWER_RES_FRAME_INFO));
    553     if(!shared_mem_loc)
    554     {
    555         res = VPX_CODEC_MEM_ERROR;
    556     }
    557 
    558     shared_mem_loc->mb_info = calloc(mb_rows*mb_cols, sizeof(LOWER_RES_MB_INFO));
    559     if(!(shared_mem_loc->mb_info))
    560     {
    561         res = VPX_CODEC_MEM_ERROR;
    562     }
    563     else
    564     {
    565         *mem_loc = (void *)shared_mem_loc;
    566         res = VPX_CODEC_OK;
    567     }
    568 #endif
    569     return res;
    570 }
    571 
    572 static vpx_codec_err_t vp8e_init(vpx_codec_ctx_t *ctx,
    573                                  vpx_codec_priv_enc_mr_cfg_t *mr_cfg)
    574 {
    575     vpx_codec_err_t        res = VPX_CODEC_OK;
    576     struct vpx_codec_alg_priv *priv;
    577     vpx_codec_enc_cfg_t       *cfg;
    578     unsigned int               i;
    579 
    580     struct VP8_COMP *optr;
    581 
    582     vp8_rtcd();
    583 
    584     if (!ctx->priv)
    585     {
    586         priv = calloc(1, sizeof(struct vpx_codec_alg_priv));
    587 
    588         if (!priv)
    589         {
    590             return VPX_CODEC_MEM_ERROR;
    591         }
    592 
    593         ctx->priv = &priv->base;
    594         ctx->priv->sz = sizeof(*ctx->priv);
    595         ctx->priv->iface = ctx->iface;
    596         ctx->priv->alg_priv = priv;
    597         ctx->priv->init_flags = ctx->init_flags;
    598 
    599         if (ctx->config.enc)
    600         {
    601             /* Update the reference to the config structure to an
    602              * internal copy.
    603              */
    604             ctx->priv->alg_priv->cfg = *ctx->config.enc;
    605             ctx->config.enc = &ctx->priv->alg_priv->cfg;
    606         }
    607 
    608         cfg =  &ctx->priv->alg_priv->cfg;
    609 
    610         /* Select the extra vp8 configuration table based on the current
    611          * usage value. If the current usage value isn't found, use the
    612          * values for usage case 0.
    613          */
    614         for (i = 0;
    615              extracfg_map[i].usage && extracfg_map[i].usage != cfg->g_usage;
    616              i++);
    617 
    618         priv->vp8_cfg = extracfg_map[i].cfg;
    619         priv->vp8_cfg.pkt_list = &priv->pkt_list.head;
    620 
    621         priv->cx_data_sz = priv->cfg.g_w * priv->cfg.g_h * 3 / 2 * 2;
    622 
    623         if (priv->cx_data_sz < 32768) priv->cx_data_sz = 32768;
    624 
    625         priv->cx_data = malloc(priv->cx_data_sz);
    626 
    627         if (!priv->cx_data)
    628         {
    629             return VPX_CODEC_MEM_ERROR;
    630         }
    631 
    632         if(mr_cfg)
    633             ctx->priv->enc.total_encoders   = mr_cfg->mr_total_resolutions;
    634         else
    635             ctx->priv->enc.total_encoders   = 1;
    636 
    637         res = validate_config(priv, &priv->cfg, &priv->vp8_cfg, 0);
    638 
    639         if (!res)
    640         {
    641             set_vp8e_config(&ctx->priv->alg_priv->oxcf,
    642                              ctx->priv->alg_priv->cfg,
    643                              ctx->priv->alg_priv->vp8_cfg,
    644                              mr_cfg);
    645 
    646             optr = vp8_create_compressor(&ctx->priv->alg_priv->oxcf);
    647 
    648             if (!optr)
    649                 res = VPX_CODEC_MEM_ERROR;
    650             else
    651                 ctx->priv->alg_priv->cpi = optr;
    652         }
    653     }
    654 
    655     return res;
    656 }
    657 
    658 static vpx_codec_err_t vp8e_destroy(vpx_codec_alg_priv_t *ctx)
    659 {
    660 #if CONFIG_MULTI_RES_ENCODING
    661     /* Free multi-encoder shared memory */
    662     if (ctx->oxcf.mr_total_resolutions > 0 && (ctx->oxcf.mr_encoder_id == ctx->oxcf.mr_total_resolutions-1))
    663     {
    664         LOWER_RES_FRAME_INFO *shared_mem_loc = (LOWER_RES_FRAME_INFO *)ctx->oxcf.mr_low_res_mode_info;
    665         free(shared_mem_loc->mb_info);
    666         free(ctx->oxcf.mr_low_res_mode_info);
    667     }
    668 #endif
    669 
    670     free(ctx->cx_data);
    671     vp8_remove_compressor(&ctx->cpi);
    672     free(ctx);
    673     return VPX_CODEC_OK;
    674 }
    675 
    676 static vpx_codec_err_t image2yuvconfig(const vpx_image_t   *img,
    677                                        YV12_BUFFER_CONFIG  *yv12)
    678 {
    679     vpx_codec_err_t        res = VPX_CODEC_OK;
    680     yv12->y_buffer = img->planes[VPX_PLANE_Y];
    681     yv12->u_buffer = img->planes[VPX_PLANE_U];
    682     yv12->v_buffer = img->planes[VPX_PLANE_V];
    683 
    684     yv12->y_crop_width  = img->d_w;
    685     yv12->y_crop_height = img->d_h;
    686     yv12->y_width  = img->d_w;
    687     yv12->y_height = img->d_h;
    688     yv12->uv_width = (1 + yv12->y_width) / 2;
    689     yv12->uv_height = (1 + yv12->y_height) / 2;
    690 
    691     yv12->y_stride = img->stride[VPX_PLANE_Y];
    692     yv12->uv_stride = img->stride[VPX_PLANE_U];
    693 
    694     yv12->border  = (img->stride[VPX_PLANE_Y] - img->w) / 2;
    695     return res;
    696 }
    697 
    698 static void pick_quickcompress_mode(vpx_codec_alg_priv_t  *ctx,
    699                                     unsigned long          duration,
    700                                     unsigned long          deadline)
    701 {
    702     unsigned int new_qc;
    703 
    704 #if !(CONFIG_REALTIME_ONLY)
    705     /* Use best quality mode if no deadline is given. */
    706     new_qc = MODE_BESTQUALITY;
    707 
    708     if (deadline)
    709     {
    710         uint64_t     duration_us;
    711 
    712         /* Convert duration parameter from stream timebase to microseconds */
    713         duration_us = (uint64_t)duration * 1000000
    714                       * (uint64_t)ctx->cfg.g_timebase.num
    715                       / (uint64_t)ctx->cfg.g_timebase.den;
    716 
    717         /* If the deadline is more that the duration this frame is to be shown,
    718          * use good quality mode. Otherwise use realtime mode.
    719          */
    720         new_qc = (deadline > duration_us) ? MODE_GOODQUALITY : MODE_REALTIME;
    721     }
    722 
    723 #else
    724     new_qc = MODE_REALTIME;
    725 #endif
    726 
    727     if (ctx->cfg.g_pass == VPX_RC_FIRST_PASS)
    728         new_qc = MODE_FIRSTPASS;
    729     else if (ctx->cfg.g_pass == VPX_RC_LAST_PASS)
    730         new_qc = (new_qc == MODE_BESTQUALITY)
    731                  ? MODE_SECONDPASS_BEST
    732                  : MODE_SECONDPASS;
    733 
    734     if (ctx->oxcf.Mode != new_qc)
    735     {
    736         ctx->oxcf.Mode = new_qc;
    737         vp8_change_config(ctx->cpi, &ctx->oxcf);
    738     }
    739 }
    740 
    741 
    742 static vpx_codec_err_t vp8e_encode(vpx_codec_alg_priv_t  *ctx,
    743                                    const vpx_image_t     *img,
    744                                    vpx_codec_pts_t        pts,
    745                                    unsigned long          duration,
    746                                    vpx_enc_frame_flags_t  flags,
    747                                    unsigned long          deadline)
    748 {
    749     vpx_codec_err_t res = VPX_CODEC_OK;
    750 
    751     if (!ctx->cfg.rc_target_bitrate)
    752         return res;
    753 
    754     if (!ctx->cfg.rc_target_bitrate)
    755         return res;
    756 
    757     if (img)
    758         res = validate_img(ctx, img);
    759 
    760     if (!res)
    761         res = validate_config(ctx, &ctx->cfg, &ctx->vp8_cfg, 1);
    762 
    763     pick_quickcompress_mode(ctx, duration, deadline);
    764     vpx_codec_pkt_list_init(&ctx->pkt_list);
    765 
    766     /* Handle Flags */
    767     if (((flags & VP8_EFLAG_NO_UPD_GF) && (flags & VP8_EFLAG_FORCE_GF))
    768         || ((flags & VP8_EFLAG_NO_UPD_ARF) && (flags & VP8_EFLAG_FORCE_ARF)))
    769     {
    770         ctx->base.err_detail = "Conflicting flags.";
    771         return VPX_CODEC_INVALID_PARAM;
    772     }
    773 
    774     if (flags & (VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_GF
    775                  | VP8_EFLAG_NO_REF_ARF))
    776     {
    777         int ref = 7;
    778 
    779         if (flags & VP8_EFLAG_NO_REF_LAST)
    780             ref ^= VP8_LAST_FRAME;
    781 
    782         if (flags & VP8_EFLAG_NO_REF_GF)
    783             ref ^= VP8_GOLD_FRAME;
    784 
    785         if (flags & VP8_EFLAG_NO_REF_ARF)
    786             ref ^= VP8_ALTR_FRAME;
    787 
    788         vp8_use_as_reference(ctx->cpi, ref);
    789     }
    790 
    791     if (flags & (VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF
    792                  | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_FORCE_GF
    793                  | VP8_EFLAG_FORCE_ARF))
    794     {
    795         int upd = 7;
    796 
    797         if (flags & VP8_EFLAG_NO_UPD_LAST)
    798             upd ^= VP8_LAST_FRAME;
    799 
    800         if (flags & VP8_EFLAG_NO_UPD_GF)
    801             upd ^= VP8_GOLD_FRAME;
    802 
    803         if (flags & VP8_EFLAG_NO_UPD_ARF)
    804             upd ^= VP8_ALTR_FRAME;
    805 
    806         vp8_update_reference(ctx->cpi, upd);
    807     }
    808 
    809     if (flags & VP8_EFLAG_NO_UPD_ENTROPY)
    810     {
    811         vp8_update_entropy(ctx->cpi, 0);
    812     }
    813 
    814     /* Handle fixed keyframe intervals */
    815     if (ctx->cfg.kf_mode == VPX_KF_AUTO
    816         && ctx->cfg.kf_min_dist == ctx->cfg.kf_max_dist)
    817     {
    818         if (++ctx->fixed_kf_cntr > ctx->cfg.kf_min_dist)
    819         {
    820             flags |= VPX_EFLAG_FORCE_KF;
    821             ctx->fixed_kf_cntr = 1;
    822         }
    823     }
    824 
    825     /* Initialize the encoder instance on the first frame*/
    826     if (!res && ctx->cpi)
    827     {
    828         unsigned int lib_flags;
    829         YV12_BUFFER_CONFIG sd;
    830         int64_t dst_time_stamp, dst_end_time_stamp;
    831         unsigned long size, cx_data_sz;
    832         unsigned char *cx_data;
    833         unsigned char *cx_data_end;
    834         int comp_data_state = 0;
    835 
    836         /* Set up internal flags */
    837         if (ctx->base.init_flags & VPX_CODEC_USE_PSNR)
    838             ((VP8_COMP *)ctx->cpi)->b_calculate_psnr = 1;
    839 
    840         if (ctx->base.init_flags & VPX_CODEC_USE_OUTPUT_PARTITION)
    841             ((VP8_COMP *)ctx->cpi)->output_partition = 1;
    842 
    843         /* Convert API flags to internal codec lib flags */
    844         lib_flags = (flags & VPX_EFLAG_FORCE_KF) ? FRAMEFLAGS_KEY : 0;
    845 
    846         /* vp8 use 10,000,000 ticks/second as time stamp */
    847         dst_time_stamp    = pts * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
    848         dst_end_time_stamp = (pts + duration) * 10000000 * ctx->cfg.g_timebase.num / ctx->cfg.g_timebase.den;
    849 
    850         if (img != NULL)
    851         {
    852             res = image2yuvconfig(img, &sd);
    853 
    854             if (vp8_receive_raw_frame(ctx->cpi, ctx->next_frame_flag | lib_flags,
    855                                       &sd, dst_time_stamp, dst_end_time_stamp))
    856             {
    857                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
    858                 res = update_error_state(ctx, &cpi->common.error);
    859             }
    860 
    861             /* reset for next frame */
    862             ctx->next_frame_flag = 0;
    863         }
    864 
    865         cx_data = ctx->cx_data;
    866         cx_data_sz = ctx->cx_data_sz;
    867         cx_data_end = ctx->cx_data + cx_data_sz;
    868         lib_flags = 0;
    869 
    870         while (cx_data_sz >= ctx->cx_data_sz / 2)
    871         {
    872             comp_data_state = vp8_get_compressed_data(ctx->cpi,
    873                                                   &lib_flags,
    874                                                   &size,
    875                                                   cx_data,
    876                                                   cx_data_end,
    877                                                   &dst_time_stamp,
    878                                                   &dst_end_time_stamp,
    879                                                   !img);
    880 
    881             if(comp_data_state == VPX_CODEC_CORRUPT_FRAME)
    882                 return VPX_CODEC_CORRUPT_FRAME;
    883             else if(comp_data_state == -1)
    884                 break;
    885 
    886             if (size)
    887             {
    888                 vpx_codec_pts_t    round, delta;
    889                 vpx_codec_cx_pkt_t pkt;
    890                 VP8_COMP *cpi = (VP8_COMP *)ctx->cpi;
    891 
    892                 /* Add the frame packet to the list of returned packets. */
    893                 round = (vpx_codec_pts_t)1000000
    894                         * ctx->cfg.g_timebase.num / 2 - 1;
    895                 delta = (dst_end_time_stamp - dst_time_stamp);
    896                 pkt.kind = VPX_CODEC_CX_FRAME_PKT;
    897                 pkt.data.frame.pts =
    898                     (dst_time_stamp * ctx->cfg.g_timebase.den + round)
    899                     / ctx->cfg.g_timebase.num / 10000000;
    900                 pkt.data.frame.duration = (unsigned long)
    901                     ((delta * ctx->cfg.g_timebase.den + round)
    902                     / ctx->cfg.g_timebase.num / 10000000);
    903                 pkt.data.frame.flags = lib_flags << 16;
    904 
    905                 if (lib_flags & FRAMEFLAGS_KEY)
    906                     pkt.data.frame.flags |= VPX_FRAME_IS_KEY;
    907 
    908                 if (!cpi->common.show_frame)
    909                 {
    910                     pkt.data.frame.flags |= VPX_FRAME_IS_INVISIBLE;
    911 
    912                     /* This timestamp should be as close as possible to the
    913                      * prior PTS so that if a decoder uses pts to schedule when
    914                      * to do this, we start right after last frame was decoded.
    915                      * Invisible frames have no duration.
    916                      */
    917                     pkt.data.frame.pts = ((cpi->last_time_stamp_seen
    918                         * ctx->cfg.g_timebase.den + round)
    919                         / ctx->cfg.g_timebase.num / 10000000) + 1;
    920                     pkt.data.frame.duration = 0;
    921                 }
    922 
    923                 if (cpi->droppable)
    924                     pkt.data.frame.flags |= VPX_FRAME_IS_DROPPABLE;
    925 
    926                 if (cpi->output_partition)
    927                 {
    928                     int i;
    929                     const int num_partitions =
    930                             (1 << cpi->common.multi_token_partition) + 1;
    931 
    932                     pkt.data.frame.flags |= VPX_FRAME_IS_FRAGMENT;
    933 
    934                     for (i = 0; i < num_partitions; ++i)
    935                     {
    936 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
    937                         pkt.data.frame.buf = cpi->partition_d[i];
    938 #else
    939                         pkt.data.frame.buf = cx_data;
    940                         cx_data += cpi->partition_sz[i];
    941                         cx_data_sz -= cpi->partition_sz[i];
    942 #endif
    943                         pkt.data.frame.sz = cpi->partition_sz[i];
    944                         pkt.data.frame.partition_id = i;
    945                         /* don't set the fragment bit for the last partition */
    946                         if (i == (num_partitions - 1))
    947                             pkt.data.frame.flags &= ~VPX_FRAME_IS_FRAGMENT;
    948                         vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
    949                     }
    950 #if CONFIG_REALTIME_ONLY & CONFIG_ONTHEFLY_BITPACKING
    951                     /* In lagged mode the encoder can buffer multiple frames.
    952                      * We don't want this in partitioned output because
    953                      * partitions are spread all over the output buffer.
    954                      * So, force an exit!
    955                      */
    956                     cx_data_sz -= ctx->cx_data_sz / 2;
    957 #endif
    958                 }
    959                 else
    960                 {
    961                     pkt.data.frame.buf = cx_data;
    962                     pkt.data.frame.sz  = size;
    963                     pkt.data.frame.partition_id = -1;
    964                     vpx_codec_pkt_list_add(&ctx->pkt_list.head, &pkt);
    965                     cx_data += size;
    966                     cx_data_sz -= size;
    967                 }
    968             }
    969         }
    970     }
    971 
    972     return res;
    973 }
    974 
    975 
    976 static const vpx_codec_cx_pkt_t *vp8e_get_cxdata(vpx_codec_alg_priv_t  *ctx,
    977         vpx_codec_iter_t      *iter)
    978 {
    979     return vpx_codec_pkt_list_get(&ctx->pkt_list.head, iter);
    980 }
    981 
    982 static vpx_codec_err_t vp8e_set_reference(vpx_codec_alg_priv_t *ctx,
    983         int ctr_id,
    984         va_list args)
    985 {
    986     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
    987 
    988     if (data)
    989     {
    990         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
    991         YV12_BUFFER_CONFIG sd;
    992 
    993         image2yuvconfig(&frame->img, &sd);
    994         vp8_set_reference(ctx->cpi, frame->frame_type, &sd);
    995         return VPX_CODEC_OK;
    996     }
    997     else
    998         return VPX_CODEC_INVALID_PARAM;
    999 
   1000 }
   1001 
   1002 static vpx_codec_err_t vp8e_get_reference(vpx_codec_alg_priv_t *ctx,
   1003         int ctr_id,
   1004         va_list args)
   1005 {
   1006 
   1007     vpx_ref_frame_t *data = va_arg(args, vpx_ref_frame_t *);
   1008 
   1009     if (data)
   1010     {
   1011         vpx_ref_frame_t *frame = (vpx_ref_frame_t *)data;
   1012         YV12_BUFFER_CONFIG sd;
   1013 
   1014         image2yuvconfig(&frame->img, &sd);
   1015         vp8_get_reference(ctx->cpi, frame->frame_type, &sd);
   1016         return VPX_CODEC_OK;
   1017     }
   1018     else
   1019         return VPX_CODEC_INVALID_PARAM;
   1020 }
   1021 
   1022 static vpx_codec_err_t vp8e_set_previewpp(vpx_codec_alg_priv_t *ctx,
   1023         int ctr_id,
   1024         va_list args)
   1025 {
   1026 #if CONFIG_POSTPROC
   1027     vp8_postproc_cfg_t *data = va_arg(args, vp8_postproc_cfg_t *);
   1028     (void)ctr_id;
   1029 
   1030     if (data)
   1031     {
   1032         ctx->preview_ppcfg = *((vp8_postproc_cfg_t *)data);
   1033         return VPX_CODEC_OK;
   1034     }
   1035     else
   1036         return VPX_CODEC_INVALID_PARAM;
   1037 #else
   1038     (void)ctx;
   1039     (void)ctr_id;
   1040     (void)args;
   1041     return VPX_CODEC_INCAPABLE;
   1042 #endif
   1043 }
   1044 
   1045 
   1046 static vpx_image_t *vp8e_get_preview(vpx_codec_alg_priv_t *ctx)
   1047 {
   1048 
   1049     YV12_BUFFER_CONFIG sd;
   1050     vp8_ppflags_t flags = {0};
   1051 
   1052     if (ctx->preview_ppcfg.post_proc_flag)
   1053     {
   1054         flags.post_proc_flag        = ctx->preview_ppcfg.post_proc_flag;
   1055         flags.deblocking_level      = ctx->preview_ppcfg.deblocking_level;
   1056         flags.noise_level           = ctx->preview_ppcfg.noise_level;
   1057     }
   1058 
   1059     if (0 == vp8_get_preview_raw_frame(ctx->cpi, &sd, &flags))
   1060     {
   1061 
   1062         /*
   1063         vpx_img_wrap(&ctx->preview_img, VPX_IMG_FMT_YV12,
   1064             sd.y_width + 2*VP8BORDERINPIXELS,
   1065             sd.y_height + 2*VP8BORDERINPIXELS,
   1066             1,
   1067             sd.buffer_alloc);
   1068         vpx_img_set_rect(&ctx->preview_img,
   1069             VP8BORDERINPIXELS, VP8BORDERINPIXELS,
   1070             sd.y_width, sd.y_height);
   1071             */
   1072 
   1073         ctx->preview_img.bps = 12;
   1074         ctx->preview_img.planes[VPX_PLANE_Y] = sd.y_buffer;
   1075         ctx->preview_img.planes[VPX_PLANE_U] = sd.u_buffer;
   1076         ctx->preview_img.planes[VPX_PLANE_V] = sd.v_buffer;
   1077 
   1078         ctx->preview_img.fmt = VPX_IMG_FMT_I420;
   1079         ctx->preview_img.x_chroma_shift = 1;
   1080         ctx->preview_img.y_chroma_shift = 1;
   1081 
   1082         ctx->preview_img.d_w = sd.y_width;
   1083         ctx->preview_img.d_h = sd.y_height;
   1084         ctx->preview_img.stride[VPX_PLANE_Y] = sd.y_stride;
   1085         ctx->preview_img.stride[VPX_PLANE_U] = sd.uv_stride;
   1086         ctx->preview_img.stride[VPX_PLANE_V] = sd.uv_stride;
   1087         ctx->preview_img.w   = sd.y_width;
   1088         ctx->preview_img.h   = sd.y_height;
   1089 
   1090         return &ctx->preview_img;
   1091     }
   1092     else
   1093         return NULL;
   1094 }
   1095 
   1096 static vpx_codec_err_t vp8e_update_entropy(vpx_codec_alg_priv_t *ctx,
   1097         int ctr_id,
   1098         va_list args)
   1099 {
   1100     int update = va_arg(args, int);
   1101     vp8_update_entropy(ctx->cpi, update);
   1102     return VPX_CODEC_OK;
   1103 
   1104 }
   1105 
   1106 static vpx_codec_err_t vp8e_update_reference(vpx_codec_alg_priv_t *ctx,
   1107         int ctr_id,
   1108         va_list args)
   1109 {
   1110     int update = va_arg(args, int);
   1111     vp8_update_reference(ctx->cpi, update);
   1112     return VPX_CODEC_OK;
   1113 }
   1114 
   1115 static vpx_codec_err_t vp8e_use_reference(vpx_codec_alg_priv_t *ctx,
   1116         int ctr_id,
   1117         va_list args)
   1118 {
   1119     int reference_flag = va_arg(args, int);
   1120     vp8_use_as_reference(ctx->cpi, reference_flag);
   1121     return VPX_CODEC_OK;
   1122 }
   1123 
   1124 static vpx_codec_err_t vp8e_set_roi_map(vpx_codec_alg_priv_t *ctx,
   1125                                         int ctr_id,
   1126                                         va_list args)
   1127 {
   1128     vpx_roi_map_t *data = va_arg(args, vpx_roi_map_t *);
   1129 
   1130     if (data)
   1131     {
   1132         vpx_roi_map_t *roi = (vpx_roi_map_t *)data;
   1133 
   1134         if (!vp8_set_roimap(ctx->cpi, roi->roi_map, roi->rows, roi->cols, roi->delta_q, roi->delta_lf, roi->static_threshold))
   1135             return VPX_CODEC_OK;
   1136         else
   1137             return VPX_CODEC_INVALID_PARAM;
   1138     }
   1139     else
   1140         return VPX_CODEC_INVALID_PARAM;
   1141 }
   1142 
   1143 
   1144 static vpx_codec_err_t vp8e_set_activemap(vpx_codec_alg_priv_t *ctx,
   1145         int ctr_id,
   1146         va_list args)
   1147 {
   1148     vpx_active_map_t *data = va_arg(args, vpx_active_map_t *);
   1149 
   1150     if (data)
   1151     {
   1152 
   1153         vpx_active_map_t *map = (vpx_active_map_t *)data;
   1154 
   1155         if (!vp8_set_active_map(ctx->cpi, map->active_map, map->rows, map->cols))
   1156             return VPX_CODEC_OK;
   1157         else
   1158             return VPX_CODEC_INVALID_PARAM;
   1159     }
   1160     else
   1161         return VPX_CODEC_INVALID_PARAM;
   1162 }
   1163 
   1164 static vpx_codec_err_t vp8e_set_scalemode(vpx_codec_alg_priv_t *ctx,
   1165         int ctr_id,
   1166         va_list args)
   1167 {
   1168 
   1169     vpx_scaling_mode_t *data =  va_arg(args, vpx_scaling_mode_t *);
   1170 
   1171     if (data)
   1172     {
   1173         int res;
   1174         vpx_scaling_mode_t scalemode = *(vpx_scaling_mode_t *)data ;
   1175         res = vp8_set_internal_size(ctx->cpi,
   1176                                     (VPX_SCALING)scalemode.h_scaling_mode,
   1177                                     (VPX_SCALING)scalemode.v_scaling_mode);
   1178 
   1179         if (!res)
   1180         {
   1181             /*force next frame a key frame to effect scaling mode */
   1182             ctx->next_frame_flag |= FRAMEFLAGS_KEY;
   1183             return VPX_CODEC_OK;
   1184         }
   1185         else
   1186             return VPX_CODEC_INVALID_PARAM;
   1187     }
   1188     else
   1189         return VPX_CODEC_INVALID_PARAM;
   1190 }
   1191 
   1192 
   1193 static vpx_codec_ctrl_fn_map_t vp8e_ctf_maps[] =
   1194 {
   1195     {VP8_SET_REFERENCE,                 vp8e_set_reference},
   1196     {VP8_COPY_REFERENCE,                vp8e_get_reference},
   1197     {VP8_SET_POSTPROC,                  vp8e_set_previewpp},
   1198     {VP8E_UPD_ENTROPY,                  vp8e_update_entropy},
   1199     {VP8E_UPD_REFERENCE,                vp8e_update_reference},
   1200     {VP8E_USE_REFERENCE,                vp8e_use_reference},
   1201     {VP8E_SET_ROI_MAP,                  vp8e_set_roi_map},
   1202     {VP8E_SET_ACTIVEMAP,                vp8e_set_activemap},
   1203     {VP8E_SET_SCALEMODE,                vp8e_set_scalemode},
   1204     {VP8E_SET_CPUUSED,                  set_param},
   1205     {VP8E_SET_NOISE_SENSITIVITY,        set_param},
   1206     {VP8E_SET_ENABLEAUTOALTREF,         set_param},
   1207     {VP8E_SET_SHARPNESS,                set_param},
   1208     {VP8E_SET_STATIC_THRESHOLD,         set_param},
   1209     {VP8E_SET_TOKEN_PARTITIONS,         set_param},
   1210     {VP8E_GET_LAST_QUANTIZER,           get_param},
   1211     {VP8E_GET_LAST_QUANTIZER_64,        get_param},
   1212     {VP8E_SET_ARNR_MAXFRAMES,           set_param},
   1213     {VP8E_SET_ARNR_STRENGTH ,           set_param},
   1214     {VP8E_SET_ARNR_TYPE     ,           set_param},
   1215     {VP8E_SET_TUNING,                   set_param},
   1216     {VP8E_SET_CQ_LEVEL,                 set_param},
   1217     {VP8E_SET_MAX_INTRA_BITRATE_PCT,    set_param},
   1218     { -1, NULL},
   1219 };
   1220 
   1221 static vpx_codec_enc_cfg_map_t vp8e_usage_cfg_map[] =
   1222 {
   1223     {
   1224     0,
   1225     {
   1226         0,                  /* g_usage */
   1227         0,                  /* g_threads */
   1228         0,                  /* g_profile */
   1229 
   1230         320,                /* g_width */
   1231         240,                /* g_height */
   1232         {1, 30},            /* g_timebase */
   1233 
   1234         0,                  /* g_error_resilient */
   1235 
   1236         VPX_RC_ONE_PASS,    /* g_pass */
   1237 
   1238         0,                  /* g_lag_in_frames */
   1239 
   1240         0,                  /* rc_dropframe_thresh */
   1241         0,                  /* rc_resize_allowed */
   1242         60,                 /* rc_resize_down_thresold */
   1243         30,                 /* rc_resize_up_thresold */
   1244 
   1245         VPX_VBR,            /* rc_end_usage */
   1246 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
   1247         {0},                /* rc_twopass_stats_in */
   1248 #endif
   1249         256,                /* rc_target_bandwidth */
   1250         4,                  /* rc_min_quantizer */
   1251         63,                 /* rc_max_quantizer */
   1252         100,                /* rc_undershoot_pct */
   1253         100,                /* rc_overshoot_pct */
   1254 
   1255         6000,               /* rc_max_buffer_size */
   1256         4000,               /* rc_buffer_initial_size; */
   1257         5000,               /* rc_buffer_optimal_size; */
   1258 
   1259         50,                 /* rc_two_pass_vbrbias  */
   1260         0,                  /* rc_two_pass_vbrmin_section */
   1261         400,                /* rc_two_pass_vbrmax_section */
   1262 
   1263         /* keyframing settings (kf) */
   1264         VPX_KF_AUTO,        /* g_kfmode*/
   1265         0,                  /* kf_min_dist */
   1266         128,                /* kf_max_dist */
   1267 
   1268 #if VPX_ENCODER_ABI_VERSION == (1 + VPX_CODEC_ABI_VERSION)
   1269         1,                  /* g_delete_first_pass_file */
   1270         "vp8.fpf"           /* first pass filename */
   1271 #endif
   1272         VPX_SS_DEFAULT_LAYERS, /* ss_number_layers */
   1273         1,                  /* ts_number_layers */
   1274         {0},                /* ts_target_bitrate */
   1275         {0},                /* ts_rate_decimator */
   1276         0,                  /* ts_periodicity */
   1277         {0},                /* ts_layer_id */
   1278     }},
   1279     { -1, {NOT_IMPLEMENTED}}
   1280 };
   1281 
   1282 
   1283 #ifndef VERSION_STRING
   1284 #define VERSION_STRING
   1285 #endif
   1286 CODEC_INTERFACE(vpx_codec_vp8_cx) =
   1287 {
   1288     "WebM Project VP8 Encoder" VERSION_STRING,
   1289     VPX_CODEC_INTERNAL_ABI_VERSION,
   1290     VPX_CODEC_CAP_ENCODER | VPX_CODEC_CAP_PSNR |
   1291     VPX_CODEC_CAP_OUTPUT_PARTITION,
   1292     /* vpx_codec_caps_t          caps; */
   1293     vp8e_init,          /* vpx_codec_init_fn_t       init; */
   1294     vp8e_destroy,       /* vpx_codec_destroy_fn_t    destroy; */
   1295     vp8e_ctf_maps,      /* vpx_codec_ctrl_fn_map_t  *ctrl_maps; */
   1296     NOT_IMPLEMENTED,    /* vpx_codec_get_mmap_fn_t   get_mmap; */
   1297     NOT_IMPLEMENTED,    /* vpx_codec_set_mmap_fn_t   set_mmap; */
   1298     {
   1299         NOT_IMPLEMENTED,    /* vpx_codec_peek_si_fn_t    peek_si; */
   1300         NOT_IMPLEMENTED,    /* vpx_codec_get_si_fn_t     get_si; */
   1301         NOT_IMPLEMENTED,    /* vpx_codec_decode_fn_t     decode; */
   1302         NOT_IMPLEMENTED,    /* vpx_codec_frame_get_fn_t  frame_get; */
   1303     },
   1304     {
   1305         vp8e_usage_cfg_map, /* vpx_codec_enc_cfg_map_t    peek_si; */
   1306         vp8e_encode,        /* vpx_codec_encode_fn_t      encode; */
   1307         vp8e_get_cxdata,    /* vpx_codec_get_cx_data_fn_t   frame_get; */
   1308         vp8e_set_config,
   1309         NOT_IMPLEMENTED,
   1310         vp8e_get_preview,
   1311         vp8e_mr_alloc_mem,
   1312     } /* encoder functions */
   1313 };
   1314