media/libvpx/vp8/encoder/ratectrl.c

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/media/libvpx/vp8/encoder/ratectrl.c	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,1564 @@
     1.4 +/*
     1.5 + *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
     1.6 + *
     1.7 + *  Use of this source code is governed by a BSD-style license
     1.8 + *  that can be found in the LICENSE file in the root of the source
     1.9 + *  tree. An additional intellectual property rights grant can be found
    1.10 + *  in the file PATENTS.  All contributing project authors may
    1.11 + *  be found in the AUTHORS file in the root of the source tree.
    1.12 + */
    1.13 +
    1.14 +
    1.15 +#include <stdlib.h>
    1.16 +#include <stdio.h>
    1.17 +#include <string.h>
    1.18 +#include <limits.h>
    1.19 +#include <assert.h>
    1.20 +
    1.21 +#include "math.h"
    1.22 +#include "vp8/common/common.h"
    1.23 +#include "ratectrl.h"
    1.24 +#include "vp8/common/entropymode.h"
    1.25 +#include "vpx_mem/vpx_mem.h"
    1.26 +#include "vp8/common/systemdependent.h"
    1.27 +#include "encodemv.h"
    1.28 +
    1.29 +
    1.30 +#define MIN_BPB_FACTOR          0.01
    1.31 +#define MAX_BPB_FACTOR          50
    1.32 +
    1.33 +extern const MB_PREDICTION_MODE vp8_mode_order[MAX_MODES];
    1.34 +
    1.35 +
    1.36 +
    1.37 +#ifdef MODE_STATS
    1.38 +extern int y_modes[5];
    1.39 +extern int uv_modes[4];
    1.40 +extern int b_modes[10];
    1.41 +
    1.42 +extern int inter_y_modes[10];
    1.43 +extern int inter_uv_modes[4];
    1.44 +extern int inter_b_modes[10];
    1.45 +#endif
    1.46 +
    1.47 +/* Bits Per MB at different Q (Multiplied by 512) */
    1.48 +#define BPER_MB_NORMBITS    9
    1.49 +
    1.50 +/* Work in progress recalibration of baseline rate tables based on
    1.51 + * the assumption that bits per mb is inversely proportional to the
    1.52 + * quantizer value.
    1.53 + */
    1.54 +const int vp8_bits_per_mb[2][QINDEX_RANGE] =
    1.55 +{
    1.56 +    /* Intra case 450000/Qintra */
    1.57 +    {
    1.58 +        1125000,900000, 750000, 642857, 562500, 500000, 450000, 450000,
    1.59 +        409090, 375000, 346153, 321428, 300000, 281250, 264705, 264705,
    1.60 +        250000, 236842, 225000, 225000, 214285, 214285, 204545, 204545,
    1.61 +        195652, 195652, 187500, 180000, 180000, 173076, 166666, 160714,
    1.62 +        155172, 150000, 145161, 140625, 136363, 132352, 128571, 125000,
    1.63 +        121621, 121621, 118421, 115384, 112500, 109756, 107142, 104651,
    1.64 +        102272, 100000, 97826,  97826,  95744,  93750,  91836,  90000,
    1.65 +        88235,  86538,  84905,  83333,  81818,  80357,  78947,  77586,
    1.66 +        76271,  75000,  73770,  72580,  71428,  70312,  69230,  68181,
    1.67 +        67164,  66176,  65217,  64285,  63380,  62500,  61643,  60810,
    1.68 +        60000,  59210,  59210,  58441,  57692,  56962,  56250,  55555,
    1.69 +        54878,  54216,  53571,  52941,  52325,  51724,  51136,  50561,
    1.70 +        49450,  48387,  47368,  46875,  45918,  45000,  44554,  44117,
    1.71 +        43269,  42452,  41666,  40909,  40178,  39473,  38793,  38135,
    1.72 +        36885,  36290,  35714,  35156,  34615,  34090,  33582,  33088,
    1.73 +        32608,  32142,  31468,  31034,  30405,  29801,  29220,  28662,
    1.74 +    },
    1.75 +    /* Inter case 285000/Qinter */
    1.76 +    {
    1.77 +        712500, 570000, 475000, 407142, 356250, 316666, 285000, 259090,
    1.78 +        237500, 219230, 203571, 190000, 178125, 167647, 158333, 150000,
    1.79 +        142500, 135714, 129545, 123913, 118750, 114000, 109615, 105555,
    1.80 +        101785, 98275,  95000,  91935,  89062,  86363,  83823,  81428,
    1.81 +        79166,  77027,  75000,  73076,  71250,  69512,  67857,  66279,
    1.82 +        64772,  63333,  61956,  60638,  59375,  58163,  57000,  55882,
    1.83 +        54807,  53773,  52777,  51818,  50892,  50000,  49137,  47500,
    1.84 +        45967,  44531,  43181,  41911,  40714,  39583,  38513,  37500,
    1.85 +        36538,  35625,  34756,  33928,  33139,  32386,  31666,  30978,
    1.86 +        30319,  29687,  29081,  28500,  27941,  27403,  26886,  26388,
    1.87 +        25909,  25446,  25000,  24568,  23949,  23360,  22800,  22265,
    1.88 +        21755,  21268,  20802,  20357,  19930,  19520,  19127,  18750,
    1.89 +        18387,  18037,  17701,  17378,  17065,  16764,  16473,  16101,
    1.90 +        15745,  15405,  15079,  14766,  14467,  14179,  13902,  13636,
    1.91 +        13380,  13133,  12895,  12666,  12445,  12179,  11924,  11632,
    1.92 +        11445,  11220,  11003,  10795,  10594,  10401,  10215,  10035,
    1.93 +    }
    1.94 +};
    1.95 +
    1.96 +static const int kf_boost_qadjustment[QINDEX_RANGE] =
    1.97 +{
    1.98 +    128, 129, 130, 131, 132, 133, 134, 135,
    1.99 +    136, 137, 138, 139, 140, 141, 142, 143,
   1.100 +    144, 145, 146, 147, 148, 149, 150, 151,
   1.101 +    152, 153, 154, 155, 156, 157, 158, 159,
   1.102 +    160, 161, 162, 163, 164, 165, 166, 167,
   1.103 +    168, 169, 170, 171, 172, 173, 174, 175,
   1.104 +    176, 177, 178, 179, 180, 181, 182, 183,
   1.105 +    184, 185, 186, 187, 188, 189, 190, 191,
   1.106 +    192, 193, 194, 195, 196, 197, 198, 199,
   1.107 +    200, 200, 201, 201, 202, 203, 203, 203,
   1.108 +    204, 204, 205, 205, 206, 206, 207, 207,
   1.109 +    208, 208, 209, 209, 210, 210, 211, 211,
   1.110 +    212, 212, 213, 213, 214, 214, 215, 215,
   1.111 +    216, 216, 217, 217, 218, 218, 219, 219,
   1.112 +    220, 220, 220, 220, 220, 220, 220, 220,
   1.113 +    220, 220, 220, 220, 220, 220, 220, 220,
   1.114 +};
   1.115 +
   1.116 +/* #define GFQ_ADJUSTMENT (Q+100) */
   1.117 +#define GFQ_ADJUSTMENT vp8_gf_boost_qadjustment[Q]
   1.118 +const int vp8_gf_boost_qadjustment[QINDEX_RANGE] =
   1.119 +{
   1.120 +    80, 82, 84, 86, 88, 90, 92, 94,
   1.121 +    96, 97, 98, 99, 100, 101, 102, 103,
   1.122 +    104, 105, 106, 107, 108, 109, 110, 111,
   1.123 +    112, 113, 114, 115, 116, 117, 118, 119,
   1.124 +    120, 121, 122, 123, 124, 125, 126, 127,
   1.125 +    128, 129, 130, 131, 132, 133, 134, 135,
   1.126 +    136, 137, 138, 139, 140, 141, 142, 143,
   1.127 +    144, 145, 146, 147, 148, 149, 150, 151,
   1.128 +    152, 153, 154, 155, 156, 157, 158, 159,
   1.129 +    160, 161, 162, 163, 164, 165, 166, 167,
   1.130 +    168, 169, 170, 171, 172, 173, 174, 175,
   1.131 +    176, 177, 178, 179, 180, 181, 182, 183,
   1.132 +    184, 184, 185, 185, 186, 186, 187, 187,
   1.133 +    188, 188, 189, 189, 190, 190, 191, 191,
   1.134 +    192, 192, 193, 193, 194, 194, 194, 194,
   1.135 +    195, 195, 196, 196, 197, 197, 198, 198
   1.136 +};
   1.137 +
   1.138 +/*
   1.139 +const int vp8_gf_boost_qadjustment[QINDEX_RANGE] =
   1.140 +{
   1.141 +    100,101,102,103,104,105,105,106,
   1.142 +    106,107,107,108,109,109,110,111,
   1.143 +    112,113,114,115,116,117,118,119,
   1.144 +    120,121,122,123,124,125,126,127,
   1.145 +    128,129,130,131,132,133,134,135,
   1.146 +    136,137,138,139,140,141,142,143,
   1.147 +    144,145,146,147,148,149,150,151,
   1.148 +    152,153,154,155,156,157,158,159,
   1.149 +    160,161,162,163,164,165,166,167,
   1.150 +    168,169,170,170,171,171,172,172,
   1.151 +    173,173,173,174,174,174,175,175,
   1.152 +    175,176,176,176,177,177,177,177,
   1.153 +    178,178,179,179,180,180,181,181,
   1.154 +    182,182,183,183,184,184,185,185,
   1.155 +    186,186,187,187,188,188,189,189,
   1.156 +    190,190,191,191,192,192,193,193,
   1.157 +};
   1.158 +*/
   1.159 +
   1.160 +static const int kf_gf_boost_qlimits[QINDEX_RANGE] =
   1.161 +{
   1.162 +    150, 155, 160, 165, 170, 175, 180, 185,
   1.163 +    190, 195, 200, 205, 210, 215, 220, 225,
   1.164 +    230, 235, 240, 245, 250, 255, 260, 265,
   1.165 +    270, 275, 280, 285, 290, 295, 300, 305,
   1.166 +    310, 320, 330, 340, 350, 360, 370, 380,
   1.167 +    390, 400, 410, 420, 430, 440, 450, 460,
   1.168 +    470, 480, 490, 500, 510, 520, 530, 540,
   1.169 +    550, 560, 570, 580, 590, 600, 600, 600,
   1.170 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.171 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.172 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.173 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.174 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.175 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.176 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.177 +    600, 600, 600, 600, 600, 600, 600, 600,
   1.178 +};
   1.179 +
   1.180 +/* % adjustment to target kf size based on seperation from previous frame */
   1.181 +static const int kf_boost_seperation_adjustment[16] =
   1.182 +{
   1.183 +    30,   40,   50,   55,   60,   65,   70,   75,
   1.184 +    80,   85,   90,   95,  100,  100,  100,  100,
   1.185 +};
   1.186 +
   1.187 +
   1.188 +static const int gf_adjust_table[101] =
   1.189 +{
   1.190 +    100,
   1.191 +    115, 130, 145, 160, 175, 190, 200, 210, 220, 230,
   1.192 +    240, 260, 270, 280, 290, 300, 310, 320, 330, 340,
   1.193 +    350, 360, 370, 380, 390, 400, 400, 400, 400, 400,
   1.194 +    400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
   1.195 +    400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
   1.196 +    400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
   1.197 +    400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
   1.198 +    400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
   1.199 +    400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
   1.200 +    400, 400, 400, 400, 400, 400, 400, 400, 400, 400,
   1.201 +};
   1.202 +
   1.203 +static const int gf_intra_usage_adjustment[20] =
   1.204 +{
   1.205 +    125, 120, 115, 110, 105, 100,  95,  85,  80,  75,
   1.206 +    70,  65,  60,  55,  50,  50,  50,  50,  50,  50,
   1.207 +};
   1.208 +
   1.209 +static const int gf_interval_table[101] =
   1.210 +{
   1.211 +    7,
   1.212 +    7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
   1.213 +    7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
   1.214 +    7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
   1.215 +    8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
   1.216 +    8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
   1.217 +    9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
   1.218 +    9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
   1.219 +    10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
   1.220 +    10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
   1.221 +    11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
   1.222 +};
   1.223 +
   1.224 +static const unsigned int prior_key_frame_weight[KEY_FRAME_CONTEXT] = { 1, 2, 3, 4, 5 };
   1.225 +
   1.226 +
   1.227 +void vp8_save_coding_context(VP8_COMP *cpi)
   1.228 +{
   1.229 +    CODING_CONTEXT *const cc = & cpi->coding_context;
   1.230 +
   1.231 +    /* Stores a snapshot of key state variables which can subsequently be
   1.232 +     * restored with a call to vp8_restore_coding_context. These functions are
   1.233 +     * intended for use in a re-code loop in vp8_compress_frame where the
   1.234 +     * quantizer value is adjusted between loop iterations.
   1.235 +     */
   1.236 +
   1.237 +    cc->frames_since_key          = cpi->frames_since_key;
   1.238 +    cc->filter_level             = cpi->common.filter_level;
   1.239 +    cc->frames_till_gf_update_due   = cpi->frames_till_gf_update_due;
   1.240 +    cc->frames_since_golden       = cpi->frames_since_golden;
   1.241 +
   1.242 +    vp8_copy(cc->mvc,      cpi->common.fc.mvc);
   1.243 +    vp8_copy(cc->mvcosts,  cpi->rd_costs.mvcosts);
   1.244 +
   1.245 +    vp8_copy(cc->ymode_prob,   cpi->common.fc.ymode_prob);
   1.246 +    vp8_copy(cc->uv_mode_prob,  cpi->common.fc.uv_mode_prob);
   1.247 +
   1.248 +    vp8_copy(cc->ymode_count, cpi->mb.ymode_count);
   1.249 +    vp8_copy(cc->uv_mode_count, cpi->mb.uv_mode_count);
   1.250 +
   1.251 +
   1.252 +    /* Stats */
   1.253 +#ifdef MODE_STATS
   1.254 +    vp8_copy(cc->y_modes,       y_modes);
   1.255 +    vp8_copy(cc->uv_modes,      uv_modes);
   1.256 +    vp8_copy(cc->b_modes,       b_modes);
   1.257 +    vp8_copy(cc->inter_y_modes,  inter_y_modes);
   1.258 +    vp8_copy(cc->inter_uv_modes, inter_uv_modes);
   1.259 +    vp8_copy(cc->inter_b_modes,  inter_b_modes);
   1.260 +#endif
   1.261 +
   1.262 +    cc->this_frame_percent_intra = cpi->this_frame_percent_intra;
   1.263 +}
   1.264 +
   1.265 +
   1.266 +void vp8_restore_coding_context(VP8_COMP *cpi)
   1.267 +{
   1.268 +    CODING_CONTEXT *const cc = & cpi->coding_context;
   1.269 +
   1.270 +    /* Restore key state variables to the snapshot state stored in the
   1.271 +     * previous call to vp8_save_coding_context.
   1.272 +     */
   1.273 +
   1.274 +    cpi->frames_since_key         =   cc->frames_since_key;
   1.275 +    cpi->common.filter_level     =   cc->filter_level;
   1.276 +    cpi->frames_till_gf_update_due  =   cc->frames_till_gf_update_due;
   1.277 +    cpi->frames_since_golden       =   cc->frames_since_golden;
   1.278 +
   1.279 +    vp8_copy(cpi->common.fc.mvc, cc->mvc);
   1.280 +
   1.281 +    vp8_copy(cpi->rd_costs.mvcosts, cc->mvcosts);
   1.282 +
   1.283 +    vp8_copy(cpi->common.fc.ymode_prob,   cc->ymode_prob);
   1.284 +    vp8_copy(cpi->common.fc.uv_mode_prob,  cc->uv_mode_prob);
   1.285 +
   1.286 +    vp8_copy(cpi->mb.ymode_count, cc->ymode_count);
   1.287 +    vp8_copy(cpi->mb.uv_mode_count, cc->uv_mode_count);
   1.288 +
   1.289 +    /* Stats */
   1.290 +#ifdef MODE_STATS
   1.291 +    vp8_copy(y_modes, cc->y_modes);
   1.292 +    vp8_copy(uv_modes, cc->uv_modes);
   1.293 +    vp8_copy(b_modes, cc->b_modes);
   1.294 +    vp8_copy(inter_y_modes, cc->inter_y_modes);
   1.295 +    vp8_copy(inter_uv_modes, cc->inter_uv_modes);
   1.296 +    vp8_copy(inter_b_modes, cc->inter_b_modes);
   1.297 +#endif
   1.298 +
   1.299 +
   1.300 +    cpi->this_frame_percent_intra = cc->this_frame_percent_intra;
   1.301 +}
   1.302 +
   1.303 +
   1.304 +void vp8_setup_key_frame(VP8_COMP *cpi)
   1.305 +{
   1.306 +    /* Setup for Key frame: */
   1.307 +
   1.308 +    vp8_default_coef_probs(& cpi->common);
   1.309 +
   1.310 +    vpx_memcpy(cpi->common.fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
   1.311 +    {
   1.312 +        int flag[2] = {1, 1};
   1.313 +        vp8_build_component_cost_table(cpi->mb.mvcost, (const MV_CONTEXT *) cpi->common.fc.mvc, flag);
   1.314 +    }
   1.315 +
   1.316 +    /* Make sure we initialize separate contexts for altref,gold, and normal.
   1.317 +     * TODO shouldn't need 3 different copies of structure to do this!
   1.318 +     */
   1.319 +    vpx_memcpy(&cpi->lfc_a, &cpi->common.fc, sizeof(cpi->common.fc));
   1.320 +    vpx_memcpy(&cpi->lfc_g, &cpi->common.fc, sizeof(cpi->common.fc));
   1.321 +    vpx_memcpy(&cpi->lfc_n, &cpi->common.fc, sizeof(cpi->common.fc));
   1.322 +
   1.323 +    cpi->common.filter_level = cpi->common.base_qindex * 3 / 8 ;
   1.324 +
   1.325 +    /* Provisional interval before next GF */
   1.326 +    if (cpi->auto_gold)
   1.327 +        cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
   1.328 +    else
   1.329 +        cpi->frames_till_gf_update_due = DEFAULT_GF_INTERVAL;
   1.330 +
   1.331 +    cpi->common.refresh_golden_frame = 1;
   1.332 +    cpi->common.refresh_alt_ref_frame = 1;
   1.333 +}
   1.334 +
   1.335 +
   1.336 +static int estimate_bits_at_q(int frame_kind, int Q, int MBs,
   1.337 +                              double correction_factor)
   1.338 +{
   1.339 +    int Bpm = (int)(.5 + correction_factor * vp8_bits_per_mb[frame_kind][Q]);
   1.340 +
   1.341 +    /* Attempt to retain reasonable accuracy without overflow. The cutoff is
   1.342 +     * chosen such that the maximum product of Bpm and MBs fits 31 bits. The
   1.343 +     * largest Bpm takes 20 bits.
   1.344 +     */
   1.345 +    if (MBs > (1 << 11))
   1.346 +        return (Bpm >> BPER_MB_NORMBITS) * MBs;
   1.347 +    else
   1.348 +        return (Bpm * MBs) >> BPER_MB_NORMBITS;
   1.349 +}
   1.350 +
   1.351 +
   1.352 +static void calc_iframe_target_size(VP8_COMP *cpi)
   1.353 +{
   1.354 +    /* boost defaults to half second */
   1.355 +    int kf_boost;
   1.356 +    uint64_t target;
   1.357 +
   1.358 +    /* Clear down mmx registers to allow floating point in what follows */
   1.359 +    vp8_clear_system_state();
   1.360 +
   1.361 +    if (cpi->oxcf.fixed_q >= 0)
   1.362 +    {
   1.363 +        int Q = cpi->oxcf.key_q;
   1.364 +
   1.365 +        target = estimate_bits_at_q(INTRA_FRAME, Q, cpi->common.MBs,
   1.366 +                                    cpi->key_frame_rate_correction_factor);
   1.367 +    }
   1.368 +    else if (cpi->pass == 2)
   1.369 +    {
   1.370 +        /* New Two pass RC */
   1.371 +        target = cpi->per_frame_bandwidth;
   1.372 +    }
   1.373 +    /* First Frame is a special case */
   1.374 +    else if (cpi->common.current_video_frame == 0)
   1.375 +    {
   1.376 +        /* 1 Pass there is no information on which to base size so use
   1.377 +         * bandwidth per second * fraction of the initial buffer
   1.378 +         * level
   1.379 +         */
   1.380 +        target = cpi->oxcf.starting_buffer_level / 2;
   1.381 +
   1.382 +        if(target > cpi->oxcf.target_bandwidth * 3 / 2)
   1.383 +            target = cpi->oxcf.target_bandwidth * 3 / 2;
   1.384 +    }
   1.385 +    else
   1.386 +    {
   1.387 +        /* if this keyframe was forced, use a more recent Q estimate */
   1.388 +        int Q = (cpi->common.frame_flags & FRAMEFLAGS_KEY)
   1.389 +                ? cpi->avg_frame_qindex : cpi->ni_av_qi;
   1.390 +
   1.391 +        int initial_boost = 32; /* |3.0 * per_frame_bandwidth| */
   1.392 +        /* Boost depends somewhat on frame rate: only used for 1 layer case. */
   1.393 +        if (cpi->oxcf.number_of_layers == 1) {
   1.394 +          kf_boost = MAX(initial_boost, (int)(2 * cpi->output_framerate - 16));
   1.395 +        }
   1.396 +        else {
   1.397 +          /* Initial factor: set target size to: |3.0 * per_frame_bandwidth|. */
   1.398 +          kf_boost = initial_boost;
   1.399 +        }
   1.400 +
   1.401 +        /* adjustment up based on q: this factor ranges from ~1.2 to 2.2. */
   1.402 +        kf_boost = kf_boost * kf_boost_qadjustment[Q] / 100;
   1.403 +
   1.404 +        /* frame separation adjustment ( down) */
   1.405 +        if (cpi->frames_since_key  < cpi->output_framerate / 2)
   1.406 +            kf_boost = (int)(kf_boost
   1.407 +                       * cpi->frames_since_key / (cpi->output_framerate / 2));
   1.408 +
   1.409 +        /* Minimal target size is |2* per_frame_bandwidth|. */
   1.410 +        if (kf_boost < 16)
   1.411 +            kf_boost = 16;
   1.412 +
   1.413 +        target = ((16 + kf_boost) * cpi->per_frame_bandwidth) >> 4;
   1.414 +    }
   1.415 +
   1.416 +
   1.417 +    if (cpi->oxcf.rc_max_intra_bitrate_pct)
   1.418 +    {
   1.419 +        unsigned int max_rate = cpi->per_frame_bandwidth
   1.420 +                                * cpi->oxcf.rc_max_intra_bitrate_pct / 100;
   1.421 +
   1.422 +        if (target > max_rate)
   1.423 +            target = max_rate;
   1.424 +    }
   1.425 +
   1.426 +    cpi->this_frame_target = (int)target;
   1.427 +
   1.428 +    /* TODO: if we separate rate targeting from Q targetting, move this.
   1.429 +     * Reset the active worst quality to the baseline value for key frames.
   1.430 +     */
   1.431 +    if (cpi->pass != 2)
   1.432 +        cpi->active_worst_quality = cpi->worst_quality;
   1.433 +
   1.434 +#if 0
   1.435 +    {
   1.436 +        FILE *f;
   1.437 +
   1.438 +        f = fopen("kf_boost.stt", "a");
   1.439 +        fprintf(f, " %8u %10d %10d %10d\n",
   1.440 +                cpi->common.current_video_frame,  cpi->gfu_boost, cpi->baseline_gf_interval, cpi->source_alt_ref_pending);
   1.441 +
   1.442 +        fclose(f);
   1.443 +    }
   1.444 +#endif
   1.445 +}
   1.446 +
   1.447 +
   1.448 +/* Do the best we can to define the parameters for the next GF based on what
   1.449 + * information we have available.
   1.450 + */
   1.451 +static void calc_gf_params(VP8_COMP *cpi)
   1.452 +{
   1.453 +    int Q = (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
   1.454 +    int Boost = 0;
   1.455 +
   1.456 +    int gf_frame_useage = 0;      /* Golden frame useage since last GF */
   1.457 +    int tot_mbs = cpi->recent_ref_frame_usage[INTRA_FRAME]  +
   1.458 +                  cpi->recent_ref_frame_usage[LAST_FRAME]   +
   1.459 +                  cpi->recent_ref_frame_usage[GOLDEN_FRAME] +
   1.460 +                  cpi->recent_ref_frame_usage[ALTREF_FRAME];
   1.461 +
   1.462 +    int pct_gf_active = (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols);
   1.463 +
   1.464 +    if (tot_mbs)
   1.465 +        gf_frame_useage = (cpi->recent_ref_frame_usage[GOLDEN_FRAME] + cpi->recent_ref_frame_usage[ALTREF_FRAME]) * 100 / tot_mbs;
   1.466 +
   1.467 +    if (pct_gf_active > gf_frame_useage)
   1.468 +        gf_frame_useage = pct_gf_active;
   1.469 +
   1.470 +    /* Not two pass */
   1.471 +    if (cpi->pass != 2)
   1.472 +    {
   1.473 +        /* Single Pass lagged mode: TBD */
   1.474 +        if (0)
   1.475 +        {
   1.476 +        }
   1.477 +
   1.478 +        /* Single Pass compression: Has to use current and historical data */
   1.479 +        else
   1.480 +        {
   1.481 +#if 0
   1.482 +            /* Experimental code */
   1.483 +            int index = cpi->one_pass_frame_index;
   1.484 +            int frames_to_scan = (cpi->max_gf_interval <= MAX_LAG_BUFFERS) ? cpi->max_gf_interval : MAX_LAG_BUFFERS;
   1.485 +
   1.486 +            /* ************** Experimental code - incomplete */
   1.487 +            /*
   1.488 +            double decay_val = 1.0;
   1.489 +            double IIAccumulator = 0.0;
   1.490 +            double last_iiaccumulator = 0.0;
   1.491 +            double IIRatio;
   1.492 +
   1.493 +            cpi->one_pass_frame_index = cpi->common.current_video_frame%MAX_LAG_BUFFERS;
   1.494 +
   1.495 +            for ( i = 0; i < (frames_to_scan - 1); i++ )
   1.496 +            {
   1.497 +                if ( index < 0 )
   1.498 +                    index = MAX_LAG_BUFFERS;
   1.499 +                index --;
   1.500 +
   1.501 +                if ( cpi->one_pass_frame_stats[index].frame_coded_error > 0.0 )
   1.502 +                {
   1.503 +                    IIRatio = cpi->one_pass_frame_stats[index].frame_intra_error / cpi->one_pass_frame_stats[index].frame_coded_error;
   1.504 +
   1.505 +                    if ( IIRatio > 30.0 )
   1.506 +                        IIRatio = 30.0;
   1.507 +                }
   1.508 +                else
   1.509 +                    IIRatio = 30.0;
   1.510 +
   1.511 +                IIAccumulator += IIRatio * decay_val;
   1.512 +
   1.513 +                decay_val = decay_val * cpi->one_pass_frame_stats[index].frame_pcnt_inter;
   1.514 +
   1.515 +                if (    (i > MIN_GF_INTERVAL) &&
   1.516 +                        ((IIAccumulator - last_iiaccumulator) < 2.0) )
   1.517 +                {
   1.518 +                    break;
   1.519 +                }
   1.520 +                last_iiaccumulator = IIAccumulator;
   1.521 +            }
   1.522 +
   1.523 +            Boost = IIAccumulator*100.0/16.0;
   1.524 +            cpi->baseline_gf_interval = i;
   1.525 +
   1.526 +            */
   1.527 +#else
   1.528 +
   1.529 +            /*************************************************************/
   1.530 +            /* OLD code */
   1.531 +
   1.532 +            /* Adjust boost based upon ambient Q */
   1.533 +            Boost = GFQ_ADJUSTMENT;
   1.534 +
   1.535 +            /* Adjust based upon most recently measure intra useage */
   1.536 +            Boost = Boost * gf_intra_usage_adjustment[(cpi->this_frame_percent_intra < 15) ? cpi->this_frame_percent_intra : 14] / 100;
   1.537 +
   1.538 +            /* Adjust gf boost based upon GF usage since last GF */
   1.539 +            Boost = Boost * gf_adjust_table[gf_frame_useage] / 100;
   1.540 +#endif
   1.541 +        }
   1.542 +
   1.543 +        /* golden frame boost without recode loop often goes awry.  be
   1.544 +         * safe by keeping numbers down.
   1.545 +         */
   1.546 +        if (!cpi->sf.recode_loop)
   1.547 +        {
   1.548 +            if (cpi->compressor_speed == 2)
   1.549 +                Boost = Boost / 2;
   1.550 +        }
   1.551 +
   1.552 +        /* Apply an upper limit based on Q for 1 pass encodes */
   1.553 +        if (Boost > kf_gf_boost_qlimits[Q] && (cpi->pass == 0))
   1.554 +            Boost = kf_gf_boost_qlimits[Q];
   1.555 +
   1.556 +        /* Apply lower limits to boost. */
   1.557 +        else if (Boost < 110)
   1.558 +            Boost = 110;
   1.559 +
   1.560 +        /* Note the boost used */
   1.561 +        cpi->last_boost = Boost;
   1.562 +
   1.563 +    }
   1.564 +
   1.565 +    /* Estimate next interval
   1.566 +     * This is updated once the real frame size/boost is known.
   1.567 +     */
   1.568 +    if (cpi->oxcf.fixed_q == -1)
   1.569 +    {
   1.570 +        if (cpi->pass == 2)         /* 2 Pass */
   1.571 +        {
   1.572 +            cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
   1.573 +        }
   1.574 +        else                            /* 1 Pass */
   1.575 +        {
   1.576 +            cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
   1.577 +
   1.578 +            if (cpi->last_boost > 750)
   1.579 +                cpi->frames_till_gf_update_due++;
   1.580 +
   1.581 +            if (cpi->last_boost > 1000)
   1.582 +                cpi->frames_till_gf_update_due++;
   1.583 +
   1.584 +            if (cpi->last_boost > 1250)
   1.585 +                cpi->frames_till_gf_update_due++;
   1.586 +
   1.587 +            if (cpi->last_boost >= 1500)
   1.588 +                cpi->frames_till_gf_update_due ++;
   1.589 +
   1.590 +            if (gf_interval_table[gf_frame_useage] > cpi->frames_till_gf_update_due)
   1.591 +                cpi->frames_till_gf_update_due = gf_interval_table[gf_frame_useage];
   1.592 +
   1.593 +            if (cpi->frames_till_gf_update_due > cpi->max_gf_interval)
   1.594 +                cpi->frames_till_gf_update_due = cpi->max_gf_interval;
   1.595 +        }
   1.596 +    }
   1.597 +    else
   1.598 +        cpi->frames_till_gf_update_due = cpi->baseline_gf_interval;
   1.599 +
   1.600 +    /* ARF on or off */
   1.601 +    if (cpi->pass != 2)
   1.602 +    {
   1.603 +        /* For now Alt ref is not allowed except in 2 pass modes. */
   1.604 +        cpi->source_alt_ref_pending = 0;
   1.605 +
   1.606 +        /*if ( cpi->oxcf.fixed_q == -1)
   1.607 +        {
   1.608 +            if ( cpi->oxcf.play_alternate && (cpi->last_boost > (100 + (AF_THRESH*cpi->frames_till_gf_update_due)) ) )
   1.609 +                cpi->source_alt_ref_pending = 1;
   1.610 +            else
   1.611 +                cpi->source_alt_ref_pending = 0;
   1.612 +        }*/
   1.613 +    }
   1.614 +}
   1.615 +
   1.616 +
   1.617 +static void calc_pframe_target_size(VP8_COMP *cpi)
   1.618 +{
   1.619 +    int min_frame_target;
   1.620 +    int old_per_frame_bandwidth = cpi->per_frame_bandwidth;
   1.621 +
   1.622 +    if ( cpi->current_layer > 0)
   1.623 +        cpi->per_frame_bandwidth =
   1.624 +            cpi->layer_context[cpi->current_layer].avg_frame_size_for_layer;
   1.625 +
   1.626 +    min_frame_target = 0;
   1.627 +
   1.628 +    if (cpi->pass == 2)
   1.629 +    {
   1.630 +        min_frame_target = cpi->min_frame_bandwidth;
   1.631 +
   1.632 +        if (min_frame_target < (cpi->av_per_frame_bandwidth >> 5))
   1.633 +            min_frame_target = cpi->av_per_frame_bandwidth >> 5;
   1.634 +    }
   1.635 +    else if (min_frame_target < cpi->per_frame_bandwidth / 4)
   1.636 +        min_frame_target = cpi->per_frame_bandwidth / 4;
   1.637 +
   1.638 +
   1.639 +    /* Special alt reference frame case */
   1.640 +    if((cpi->common.refresh_alt_ref_frame) && (cpi->oxcf.number_of_layers == 1))
   1.641 +    {
   1.642 +        if (cpi->pass == 2)
   1.643 +        {
   1.644 +            /* Per frame bit target for the alt ref frame */
   1.645 +            cpi->per_frame_bandwidth = cpi->twopass.gf_bits;
   1.646 +            cpi->this_frame_target = cpi->per_frame_bandwidth;
   1.647 +        }
   1.648 +
   1.649 +        /* One Pass ??? TBD */
   1.650 +    }
   1.651 +
   1.652 +    /* Normal frames (gf,and inter) */
   1.653 +    else
   1.654 +    {
   1.655 +        /* 2 pass */
   1.656 +        if (cpi->pass == 2)
   1.657 +        {
   1.658 +            cpi->this_frame_target = cpi->per_frame_bandwidth;
   1.659 +        }
   1.660 +        /* 1 pass */
   1.661 +        else
   1.662 +        {
   1.663 +            int Adjustment;
   1.664 +            /* Make rate adjustment to recover bits spent in key frame
   1.665 +             * Test to see if the key frame inter data rate correction
   1.666 +             * should still be in force
   1.667 +             */
   1.668 +            if (cpi->kf_overspend_bits > 0)
   1.669 +            {
   1.670 +                Adjustment = (cpi->kf_bitrate_adjustment <= cpi->kf_overspend_bits) ? cpi->kf_bitrate_adjustment : cpi->kf_overspend_bits;
   1.671 +
   1.672 +                if (Adjustment > (cpi->per_frame_bandwidth - min_frame_target))
   1.673 +                    Adjustment = (cpi->per_frame_bandwidth - min_frame_target);
   1.674 +
   1.675 +                cpi->kf_overspend_bits -= Adjustment;
   1.676 +
   1.677 +                /* Calculate an inter frame bandwidth target for the next
   1.678 +                 * few frames designed to recover any extra bits spent on
   1.679 +                 * the key frame.
   1.680 +                 */
   1.681 +                cpi->this_frame_target = cpi->per_frame_bandwidth - Adjustment;
   1.682 +
   1.683 +                if (cpi->this_frame_target < min_frame_target)
   1.684 +                    cpi->this_frame_target = min_frame_target;
   1.685 +            }
   1.686 +            else
   1.687 +                cpi->this_frame_target = cpi->per_frame_bandwidth;
   1.688 +
   1.689 +            /* If appropriate make an adjustment to recover bits spent on a
   1.690 +             * recent GF
   1.691 +             */
   1.692 +            if ((cpi->gf_overspend_bits > 0) && (cpi->this_frame_target > min_frame_target))
   1.693 +            {
   1.694 +                Adjustment = (cpi->non_gf_bitrate_adjustment <= cpi->gf_overspend_bits) ? cpi->non_gf_bitrate_adjustment : cpi->gf_overspend_bits;
   1.695 +
   1.696 +                if (Adjustment > (cpi->this_frame_target - min_frame_target))
   1.697 +                    Adjustment = (cpi->this_frame_target - min_frame_target);
   1.698 +
   1.699 +                cpi->gf_overspend_bits -= Adjustment;
   1.700 +                cpi->this_frame_target -= Adjustment;
   1.701 +            }
   1.702 +
   1.703 +            /* Apply small + and - boosts for non gf frames */
   1.704 +            if ((cpi->last_boost > 150) && (cpi->frames_till_gf_update_due > 0) &&
   1.705 +                (cpi->current_gf_interval >= (MIN_GF_INTERVAL << 1)))
   1.706 +            {
   1.707 +                /* % Adjustment limited to the range 1% to 10% */
   1.708 +                Adjustment = (cpi->last_boost - 100) >> 5;
   1.709 +
   1.710 +                if (Adjustment < 1)
   1.711 +                    Adjustment = 1;
   1.712 +                else if (Adjustment > 10)
   1.713 +                    Adjustment = 10;
   1.714 +
   1.715 +                /* Convert to bits */
   1.716 +                Adjustment = (cpi->this_frame_target * Adjustment) / 100;
   1.717 +
   1.718 +                if (Adjustment > (cpi->this_frame_target - min_frame_target))
   1.719 +                    Adjustment = (cpi->this_frame_target - min_frame_target);
   1.720 +
   1.721 +                if (cpi->frames_since_golden == (cpi->current_gf_interval >> 1))
   1.722 +                    cpi->this_frame_target += ((cpi->current_gf_interval - 1) * Adjustment);
   1.723 +                else
   1.724 +                    cpi->this_frame_target -= Adjustment;
   1.725 +            }
   1.726 +        }
   1.727 +    }
   1.728 +
   1.729 +    /* Sanity check that the total sum of adjustments is not above the
   1.730 +     * maximum allowed That is that having allowed for KF and GF penalties
   1.731 +     * we have not pushed the current interframe target to low. If the
   1.732 +     * adjustment we apply here is not capable of recovering all the extra
   1.733 +     * bits we have spent in the KF or GF then the remainder will have to
   1.734 +     * be recovered over a longer time span via other buffer / rate control
   1.735 +     * mechanisms.
   1.736 +     */
   1.737 +    if (cpi->this_frame_target < min_frame_target)
   1.738 +        cpi->this_frame_target = min_frame_target;
   1.739 +
   1.740 +    if (!cpi->common.refresh_alt_ref_frame)
   1.741 +        /* Note the baseline target data rate for this inter frame. */
   1.742 +        cpi->inter_frame_target = cpi->this_frame_target;
   1.743 +
   1.744 +    /* One Pass specific code */
   1.745 +    if (cpi->pass == 0)
   1.746 +    {
   1.747 +        /* Adapt target frame size with respect to any buffering constraints: */
   1.748 +        if (cpi->buffered_mode)
   1.749 +        {
   1.750 +            int one_percent_bits = (int)
   1.751 +                (1 + cpi->oxcf.optimal_buffer_level / 100);
   1.752 +
   1.753 +            if ((cpi->buffer_level < cpi->oxcf.optimal_buffer_level) ||
   1.754 +                (cpi->bits_off_target < cpi->oxcf.optimal_buffer_level))
   1.755 +            {
   1.756 +                int percent_low = 0;
   1.757 +
   1.758 +                /* Decide whether or not we need to adjust the frame data
   1.759 +                 * rate target.
   1.760 +                 *
   1.761 +                 * If we are are below the optimal buffer fullness level
   1.762 +                 * and adherence to buffering constraints is important to
   1.763 +                 * the end usage then adjust the per frame target.
   1.764 +                 */
   1.765 +                if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
   1.766 +                    (cpi->buffer_level < cpi->oxcf.optimal_buffer_level))
   1.767 +                {
   1.768 +                    percent_low = (int)
   1.769 +                        ((cpi->oxcf.optimal_buffer_level - cpi->buffer_level) /
   1.770 +                        one_percent_bits);
   1.771 +                }
   1.772 +                /* Are we overshooting the long term clip data rate... */
   1.773 +                else if (cpi->bits_off_target < 0)
   1.774 +                {
   1.775 +                    /* Adjust per frame data target downwards to compensate. */
   1.776 +                    percent_low = (int)(100 * -cpi->bits_off_target /
   1.777 +                                       (cpi->total_byte_count * 8));
   1.778 +                }
   1.779 +
   1.780 +                if (percent_low > cpi->oxcf.under_shoot_pct)
   1.781 +                    percent_low = cpi->oxcf.under_shoot_pct;
   1.782 +                else if (percent_low < 0)
   1.783 +                    percent_low = 0;
   1.784 +
   1.785 +                /* lower the target bandwidth for this frame. */
   1.786 +                cpi->this_frame_target -=
   1.787 +                        (cpi->this_frame_target * percent_low) / 200;
   1.788 +
   1.789 +                /* Are we using allowing control of active_worst_allowed_q
   1.790 +                 * according to buffer level.
   1.791 +                 */
   1.792 +                if (cpi->auto_worst_q && cpi->ni_frames > 150)
   1.793 +                {
   1.794 +                    int64_t critical_buffer_level;
   1.795 +
   1.796 +                    /* For streaming applications the most important factor is
   1.797 +                     * cpi->buffer_level as this takes into account the
   1.798 +                     * specified short term buffering constraints. However,
   1.799 +                     * hitting the long term clip data rate target is also
   1.800 +                     * important.
   1.801 +                     */
   1.802 +                    if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
   1.803 +                    {
   1.804 +                        /* Take the smaller of cpi->buffer_level and
   1.805 +                         * cpi->bits_off_target
   1.806 +                         */
   1.807 +                        critical_buffer_level =
   1.808 +                            (cpi->buffer_level < cpi->bits_off_target)
   1.809 +                            ? cpi->buffer_level : cpi->bits_off_target;
   1.810 +                    }
   1.811 +                    /* For local file playback short term buffering constraints
   1.812 +                     * are less of an issue
   1.813 +                     */
   1.814 +                    else
   1.815 +                    {
   1.816 +                        /* Consider only how we are doing for the clip as a
   1.817 +                         * whole
   1.818 +                         */
   1.819 +                        critical_buffer_level = cpi->bits_off_target;
   1.820 +                    }
   1.821 +
   1.822 +                    /* Set the active worst quality based upon the selected
   1.823 +                     * buffer fullness number.
   1.824 +                     */
   1.825 +                    if (critical_buffer_level < cpi->oxcf.optimal_buffer_level)
   1.826 +                    {
   1.827 +                        if ( critical_buffer_level >
   1.828 +                             (cpi->oxcf.optimal_buffer_level >> 2) )
   1.829 +                        {
   1.830 +                            int64_t qadjustment_range =
   1.831 +                                      cpi->worst_quality - cpi->ni_av_qi;
   1.832 +                            int64_t above_base =
   1.833 +                                      (critical_buffer_level -
   1.834 +                                       (cpi->oxcf.optimal_buffer_level >> 2));
   1.835 +
   1.836 +                            /* Step active worst quality down from
   1.837 +                             * cpi->ni_av_qi when (critical_buffer_level ==
   1.838 +                             * cpi->optimal_buffer_level) to
   1.839 +                             * cpi->worst_quality when
   1.840 +                             * (critical_buffer_level ==
   1.841 +                             *     cpi->optimal_buffer_level >> 2)
   1.842 +                             */
   1.843 +                            cpi->active_worst_quality =
   1.844 +                                cpi->worst_quality -
   1.845 +                                (int)((qadjustment_range * above_base) /
   1.846 +                                 (cpi->oxcf.optimal_buffer_level*3>>2));
   1.847 +                        }
   1.848 +                        else
   1.849 +                        {
   1.850 +                            cpi->active_worst_quality = cpi->worst_quality;
   1.851 +                        }
   1.852 +                    }
   1.853 +                    else
   1.854 +                    {
   1.855 +                        cpi->active_worst_quality = cpi->ni_av_qi;
   1.856 +                    }
   1.857 +                }
   1.858 +                else
   1.859 +                {
   1.860 +                    cpi->active_worst_quality = cpi->worst_quality;
   1.861 +                }
   1.862 +            }
   1.863 +            else
   1.864 +            {
   1.865 +                int percent_high = 0;
   1.866 +
   1.867 +                if ((cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
   1.868 +                     && (cpi->buffer_level > cpi->oxcf.optimal_buffer_level))
   1.869 +                {
   1.870 +                    percent_high = (int)((cpi->buffer_level
   1.871 +                                    - cpi->oxcf.optimal_buffer_level)
   1.872 +                                   / one_percent_bits);
   1.873 +                }
   1.874 +                else if (cpi->bits_off_target > cpi->oxcf.optimal_buffer_level)
   1.875 +                {
   1.876 +                    percent_high = (int)((100 * cpi->bits_off_target)
   1.877 +                                         / (cpi->total_byte_count * 8));
   1.878 +                }
   1.879 +
   1.880 +                if (percent_high > cpi->oxcf.over_shoot_pct)
   1.881 +                    percent_high = cpi->oxcf.over_shoot_pct;
   1.882 +                else if (percent_high < 0)
   1.883 +                    percent_high = 0;
   1.884 +
   1.885 +                cpi->this_frame_target += (cpi->this_frame_target *
   1.886 +                                          percent_high) / 200;
   1.887 +
   1.888 +                /* Are we allowing control of active_worst_allowed_q according
   1.889 +                 * to buffer level.
   1.890 +                 */
   1.891 +                if (cpi->auto_worst_q && cpi->ni_frames > 150)
   1.892 +                {
   1.893 +                    /* When using the relaxed buffer model stick to the
   1.894 +                     * user specified value
   1.895 +                     */
   1.896 +                    cpi->active_worst_quality = cpi->ni_av_qi;
   1.897 +                }
   1.898 +                else
   1.899 +                {
   1.900 +                    cpi->active_worst_quality = cpi->worst_quality;
   1.901 +                }
   1.902 +            }
   1.903 +
   1.904 +            /* Set active_best_quality to prevent quality rising too high */
   1.905 +            cpi->active_best_quality = cpi->best_quality;
   1.906 +
   1.907 +            /* Worst quality obviously must not be better than best quality */
   1.908 +            if (cpi->active_worst_quality <= cpi->active_best_quality)
   1.909 +                cpi->active_worst_quality = cpi->active_best_quality + 1;
   1.910 +
   1.911 +            if(cpi->active_worst_quality > 127)
   1.912 +                cpi->active_worst_quality = 127;
   1.913 +        }
   1.914 +        /* Unbuffered mode (eg. video conferencing) */
   1.915 +        else
   1.916 +        {
   1.917 +            /* Set the active worst quality */
   1.918 +            cpi->active_worst_quality = cpi->worst_quality;
   1.919 +        }
   1.920 +
   1.921 +        /* Special trap for constrained quality mode
   1.922 +         * "active_worst_quality" may never drop below cq level
   1.923 +         * for any frame type.
   1.924 +         */
   1.925 +        if ( cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY &&
   1.926 +             cpi->active_worst_quality < cpi->cq_target_quality)
   1.927 +        {
   1.928 +            cpi->active_worst_quality = cpi->cq_target_quality;
   1.929 +        }
   1.930 +    }
   1.931 +
   1.932 +    /* Test to see if we have to drop a frame
   1.933 +     * The auto-drop frame code is only used in buffered mode.
   1.934 +     * In unbufferd mode (eg vide conferencing) the descision to
   1.935 +     * code or drop a frame is made outside the codec in response to real
   1.936 +     * world comms or buffer considerations.
   1.937 +     */
   1.938 +    if (cpi->drop_frames_allowed &&
   1.939 +        (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) &&
   1.940 +        ((cpi->common.frame_type != KEY_FRAME)))
   1.941 +    {
   1.942 +        /* Check for a buffer underun-crisis in which case we have to drop
   1.943 +         * a frame
   1.944 +         */
   1.945 +        if ((cpi->buffer_level < 0))
   1.946 +        {
   1.947 +#if 0
   1.948 +            FILE *f = fopen("dec.stt", "a");
   1.949 +            fprintf(f, "%10d %10d %10d %10d ***** BUFFER EMPTY\n",
   1.950 +                    (int) cpi->common.current_video_frame,
   1.951 +                    cpi->decimation_factor, cpi->common.horiz_scale,
   1.952 +                    (cpi->buffer_level * 100) / cpi->oxcf.optimal_buffer_level);
   1.953 +            fclose(f);
   1.954 +#endif
   1.955 +            cpi->drop_frame = 1;
   1.956 +
   1.957 +            /* Update the buffer level variable. */
   1.958 +            cpi->bits_off_target += cpi->av_per_frame_bandwidth;
   1.959 +            if (cpi->bits_off_target > cpi->oxcf.maximum_buffer_size)
   1.960 +              cpi->bits_off_target = (int)cpi->oxcf.maximum_buffer_size;
   1.961 +            cpi->buffer_level = cpi->bits_off_target;
   1.962 +
   1.963 +            if (cpi->oxcf.number_of_layers > 1) {
   1.964 +              unsigned int i;
   1.965 +
   1.966 +              // Propagate bits saved by dropping the frame to higher layers.
   1.967 +              for (i = cpi->current_layer + 1; i < cpi->oxcf.number_of_layers;
   1.968 +                  i++) {
   1.969 +                LAYER_CONTEXT *lc = &cpi->layer_context[i];
   1.970 +                lc->bits_off_target += (int)(lc->target_bandwidth /
   1.971 +                                             lc->framerate);
   1.972 +                if (lc->bits_off_target > lc->maximum_buffer_size)
   1.973 +                  lc->bits_off_target = lc->maximum_buffer_size;
   1.974 +                lc->buffer_level = lc->bits_off_target;
   1.975 +              }
   1.976 +            }
   1.977 +        }
   1.978 +    }
   1.979 +
   1.980 +    /* Adjust target frame size for Golden Frames: */
   1.981 +    if (cpi->oxcf.error_resilient_mode == 0 &&
   1.982 +        (cpi->frames_till_gf_update_due == 0) && !cpi->drop_frame)
   1.983 +    {
   1.984 +        int Q = (cpi->oxcf.fixed_q < 0) ? cpi->last_q[INTER_FRAME] : cpi->oxcf.fixed_q;
   1.985 +
   1.986 +        int gf_frame_useage = 0;      /* Golden frame useage since last GF */
   1.987 +        int tot_mbs = cpi->recent_ref_frame_usage[INTRA_FRAME]  +
   1.988 +                      cpi->recent_ref_frame_usage[LAST_FRAME]   +
   1.989 +                      cpi->recent_ref_frame_usage[GOLDEN_FRAME] +
   1.990 +                      cpi->recent_ref_frame_usage[ALTREF_FRAME];
   1.991 +
   1.992 +        int pct_gf_active = (100 * cpi->gf_active_count) / (cpi->common.mb_rows * cpi->common.mb_cols);
   1.993 +
   1.994 +        if (tot_mbs)
   1.995 +            gf_frame_useage = (cpi->recent_ref_frame_usage[GOLDEN_FRAME] + cpi->recent_ref_frame_usage[ALTREF_FRAME]) * 100 / tot_mbs;
   1.996 +
   1.997 +        if (pct_gf_active > gf_frame_useage)
   1.998 +            gf_frame_useage = pct_gf_active;
   1.999 +
  1.1000 +        /* Is a fixed manual GF frequency being used */
  1.1001 +        if (cpi->auto_gold)
  1.1002 +        {
  1.1003 +            /* For one pass throw a GF if recent frame intra useage is
  1.1004 +             * low or the GF useage is high
  1.1005 +             */
  1.1006 +            if ((cpi->pass == 0) && (cpi->this_frame_percent_intra < 15 || gf_frame_useage >= 5))
  1.1007 +                cpi->common.refresh_golden_frame = 1;
  1.1008 +
  1.1009 +            /* Two pass GF descision */
  1.1010 +            else if (cpi->pass == 2)
  1.1011 +                cpi->common.refresh_golden_frame = 1;
  1.1012 +        }
  1.1013 +
  1.1014 +#if 0
  1.1015 +
  1.1016 +        /* Debug stats */
  1.1017 +        if (0)
  1.1018 +        {
  1.1019 +            FILE *f;
  1.1020 +
  1.1021 +            f = fopen("gf_useaget.stt", "a");
  1.1022 +            fprintf(f, " %8ld %10ld %10ld %10ld %10ld\n",
  1.1023 +                    cpi->common.current_video_frame,  cpi->gfu_boost, GFQ_ADJUSTMENT, cpi->gfu_boost, gf_frame_useage);
  1.1024 +            fclose(f);
  1.1025 +        }
  1.1026 +
  1.1027 +#endif
  1.1028 +
  1.1029 +        if (cpi->common.refresh_golden_frame == 1)
  1.1030 +        {
  1.1031 +#if 0
  1.1032 +
  1.1033 +            if (0)
  1.1034 +            {
  1.1035 +                FILE *f;
  1.1036 +
  1.1037 +                f = fopen("GFexit.stt", "a");
  1.1038 +                fprintf(f, "%8ld GF coded\n", cpi->common.current_video_frame);
  1.1039 +                fclose(f);
  1.1040 +            }
  1.1041 +
  1.1042 +#endif
  1.1043 +
  1.1044 +            if (cpi->auto_adjust_gold_quantizer)
  1.1045 +            {
  1.1046 +                calc_gf_params(cpi);
  1.1047 +            }
  1.1048 +
  1.1049 +            /* If we are using alternate ref instead of gf then do not apply the
  1.1050 +             * boost It will instead be applied to the altref update Jims
  1.1051 +             * modified boost
  1.1052 +             */
  1.1053 +            if (!cpi->source_alt_ref_active)
  1.1054 +            {
  1.1055 +                if (cpi->oxcf.fixed_q < 0)
  1.1056 +                {
  1.1057 +                    if (cpi->pass == 2)
  1.1058 +                    {
  1.1059 +                        /* The spend on the GF is defined in the two pass
  1.1060 +                         * code for two pass encodes
  1.1061 +                         */
  1.1062 +                        cpi->this_frame_target = cpi->per_frame_bandwidth;
  1.1063 +                    }
  1.1064 +                    else
  1.1065 +                    {
  1.1066 +                        int Boost = cpi->last_boost;
  1.1067 +                        int frames_in_section = cpi->frames_till_gf_update_due + 1;
  1.1068 +                        int allocation_chunks = (frames_in_section * 100) + (Boost - 100);
  1.1069 +                        int bits_in_section = cpi->inter_frame_target * frames_in_section;
  1.1070 +
  1.1071 +                        /* Normalize Altboost and allocations chunck down to
  1.1072 +                         * prevent overflow
  1.1073 +                         */
  1.1074 +                        while (Boost > 1000)
  1.1075 +                        {
  1.1076 +                            Boost /= 2;
  1.1077 +                            allocation_chunks /= 2;
  1.1078 +                        }
  1.1079 +
  1.1080 +                        /* Avoid loss of precision but avoid overflow */
  1.1081 +                        if ((bits_in_section >> 7) > allocation_chunks)
  1.1082 +                            cpi->this_frame_target = Boost * (bits_in_section / allocation_chunks);
  1.1083 +                        else
  1.1084 +                            cpi->this_frame_target = (Boost * bits_in_section) / allocation_chunks;
  1.1085 +                    }
  1.1086 +                }
  1.1087 +                else
  1.1088 +                    cpi->this_frame_target =
  1.1089 +                        (estimate_bits_at_q(1, Q, cpi->common.MBs, 1.0)
  1.1090 +                         * cpi->last_boost) / 100;
  1.1091 +
  1.1092 +            }
  1.1093 +            /* If there is an active ARF at this location use the minimum
  1.1094 +             * bits on this frame even if it is a contructed arf.
  1.1095 +             * The active maximum quantizer insures that an appropriate
  1.1096 +             * number of bits will be spent if needed for contstructed ARFs.
  1.1097 +             */
  1.1098 +            else
  1.1099 +            {
  1.1100 +                cpi->this_frame_target = 0;
  1.1101 +            }
  1.1102 +
  1.1103 +            cpi->current_gf_interval = cpi->frames_till_gf_update_due;
  1.1104 +
  1.1105 +        }
  1.1106 +    }
  1.1107 +
  1.1108 +    cpi->per_frame_bandwidth = old_per_frame_bandwidth;
  1.1109 +}
  1.1110 +
  1.1111 +
  1.1112 +void vp8_update_rate_correction_factors(VP8_COMP *cpi, int damp_var)
  1.1113 +{
  1.1114 +    int    Q = cpi->common.base_qindex;
  1.1115 +    int    correction_factor = 100;
  1.1116 +    double rate_correction_factor;
  1.1117 +    double adjustment_limit;
  1.1118 +
  1.1119 +    int    projected_size_based_on_q = 0;
  1.1120 +
  1.1121 +    /* Clear down mmx registers to allow floating point in what follows */
  1.1122 +    vp8_clear_system_state();
  1.1123 +
  1.1124 +    if (cpi->common.frame_type == KEY_FRAME)
  1.1125 +    {
  1.1126 +        rate_correction_factor = cpi->key_frame_rate_correction_factor;
  1.1127 +    }
  1.1128 +    else
  1.1129 +    {
  1.1130 +        if (cpi->oxcf.number_of_layers == 1 &&
  1.1131 +           (cpi->common.refresh_alt_ref_frame ||
  1.1132 +            cpi->common.refresh_golden_frame))
  1.1133 +            rate_correction_factor = cpi->gf_rate_correction_factor;
  1.1134 +        else
  1.1135 +            rate_correction_factor = cpi->rate_correction_factor;
  1.1136 +    }
  1.1137 +
  1.1138 +    /* Work out how big we would have expected the frame to be at this Q
  1.1139 +     * given the current correction factor. Stay in double to avoid int
  1.1140 +     * overflow when values are large
  1.1141 +     */
  1.1142 +    projected_size_based_on_q = (int)(((.5 + rate_correction_factor * vp8_bits_per_mb[cpi->common.frame_type][Q]) * cpi->common.MBs) / (1 << BPER_MB_NORMBITS));
  1.1143 +
  1.1144 +    /* Make some allowance for cpi->zbin_over_quant */
  1.1145 +    if (cpi->mb.zbin_over_quant > 0)
  1.1146 +    {
  1.1147 +        int Z = cpi->mb.zbin_over_quant;
  1.1148 +        double Factor = 0.99;
  1.1149 +        double factor_adjustment = 0.01 / 256.0;
  1.1150 +
  1.1151 +        while (Z > 0)
  1.1152 +        {
  1.1153 +            Z --;
  1.1154 +            projected_size_based_on_q =
  1.1155 +                (int)(Factor * projected_size_based_on_q);
  1.1156 +            Factor += factor_adjustment;
  1.1157 +
  1.1158 +            if (Factor  >= 0.999)
  1.1159 +                Factor = 0.999;
  1.1160 +        }
  1.1161 +    }
  1.1162 +
  1.1163 +    /* Work out a size correction factor. */
  1.1164 +    if (projected_size_based_on_q > 0)
  1.1165 +        correction_factor = (100 * cpi->projected_frame_size) / projected_size_based_on_q;
  1.1166 +
  1.1167 +    /* More heavily damped adjustment used if we have been oscillating
  1.1168 +     * either side of target
  1.1169 +     */
  1.1170 +    switch (damp_var)
  1.1171 +    {
  1.1172 +    case 0:
  1.1173 +        adjustment_limit = 0.75;
  1.1174 +        break;
  1.1175 +    case 1:
  1.1176 +        adjustment_limit = 0.375;
  1.1177 +        break;
  1.1178 +    case 2:
  1.1179 +    default:
  1.1180 +        adjustment_limit = 0.25;
  1.1181 +        break;
  1.1182 +    }
  1.1183 +
  1.1184 +    if (correction_factor > 102)
  1.1185 +    {
  1.1186 +        /* We are not already at the worst allowable quality */
  1.1187 +        correction_factor = (int)(100.5 + ((correction_factor - 100) * adjustment_limit));
  1.1188 +        rate_correction_factor = ((rate_correction_factor * correction_factor) / 100);
  1.1189 +
  1.1190 +        /* Keep rate_correction_factor within limits */
  1.1191 +        if (rate_correction_factor > MAX_BPB_FACTOR)
  1.1192 +            rate_correction_factor = MAX_BPB_FACTOR;
  1.1193 +    }
  1.1194 +    else if (correction_factor < 99)
  1.1195 +    {
  1.1196 +        /* We are not already at the best allowable quality */
  1.1197 +        correction_factor = (int)(100.5 - ((100 - correction_factor) * adjustment_limit));
  1.1198 +        rate_correction_factor = ((rate_correction_factor * correction_factor) / 100);
  1.1199 +
  1.1200 +        /* Keep rate_correction_factor within limits */
  1.1201 +        if (rate_correction_factor < MIN_BPB_FACTOR)
  1.1202 +            rate_correction_factor = MIN_BPB_FACTOR;
  1.1203 +    }
  1.1204 +
  1.1205 +    if (cpi->common.frame_type == KEY_FRAME)
  1.1206 +        cpi->key_frame_rate_correction_factor = rate_correction_factor;
  1.1207 +    else
  1.1208 +    {
  1.1209 +        if (cpi->oxcf.number_of_layers == 1 &&
  1.1210 +           (cpi->common.refresh_alt_ref_frame ||
  1.1211 +            cpi->common.refresh_golden_frame))
  1.1212 +            cpi->gf_rate_correction_factor = rate_correction_factor;
  1.1213 +        else
  1.1214 +            cpi->rate_correction_factor = rate_correction_factor;
  1.1215 +    }
  1.1216 +}
  1.1217 +
  1.1218 +
  1.1219 +int vp8_regulate_q(VP8_COMP *cpi, int target_bits_per_frame)
  1.1220 +{
  1.1221 +    int Q = cpi->active_worst_quality;
  1.1222 +
  1.1223 +    /* Reset Zbin OQ value */
  1.1224 +    cpi->mb.zbin_over_quant = 0;
  1.1225 +
  1.1226 +    if (cpi->oxcf.fixed_q >= 0)
  1.1227 +    {
  1.1228 +        Q = cpi->oxcf.fixed_q;
  1.1229 +
  1.1230 +        if (cpi->common.frame_type == KEY_FRAME)
  1.1231 +        {
  1.1232 +            Q = cpi->oxcf.key_q;
  1.1233 +        }
  1.1234 +        else if (cpi->oxcf.number_of_layers == 1 &&
  1.1235 +            cpi->common.refresh_alt_ref_frame)
  1.1236 +        {
  1.1237 +            Q = cpi->oxcf.alt_q;
  1.1238 +        }
  1.1239 +        else if (cpi->oxcf.number_of_layers == 1  &&
  1.1240 +            cpi->common.refresh_golden_frame)
  1.1241 +        {
  1.1242 +            Q = cpi->oxcf.gold_q;
  1.1243 +        }
  1.1244 +
  1.1245 +    }
  1.1246 +    else
  1.1247 +    {
  1.1248 +        int i;
  1.1249 +        int last_error = INT_MAX;
  1.1250 +        int target_bits_per_mb;
  1.1251 +        int bits_per_mb_at_this_q;
  1.1252 +        double correction_factor;
  1.1253 +
  1.1254 +        /* Select the appropriate correction factor based upon type of frame. */
  1.1255 +        if (cpi->common.frame_type == KEY_FRAME)
  1.1256 +            correction_factor = cpi->key_frame_rate_correction_factor;
  1.1257 +        else
  1.1258 +        {
  1.1259 +            if (cpi->oxcf.number_of_layers == 1 &&
  1.1260 +               (cpi->common.refresh_alt_ref_frame ||
  1.1261 +                cpi->common.refresh_golden_frame))
  1.1262 +                correction_factor = cpi->gf_rate_correction_factor;
  1.1263 +            else
  1.1264 +                correction_factor = cpi->rate_correction_factor;
  1.1265 +        }
  1.1266 +
  1.1267 +        /* Calculate required scaling factor based on target frame size and
  1.1268 +         * size of frame produced using previous Q
  1.1269 +         */
  1.1270 +        if (target_bits_per_frame >= (INT_MAX >> BPER_MB_NORMBITS))
  1.1271 +            /* Case where we would overflow int */
  1.1272 +            target_bits_per_mb = (target_bits_per_frame / cpi->common.MBs) << BPER_MB_NORMBITS;
  1.1273 +        else
  1.1274 +            target_bits_per_mb = (target_bits_per_frame << BPER_MB_NORMBITS) / cpi->common.MBs;
  1.1275 +
  1.1276 +        i = cpi->active_best_quality;
  1.1277 +
  1.1278 +        do
  1.1279 +        {
  1.1280 +            bits_per_mb_at_this_q = (int)(.5 + correction_factor * vp8_bits_per_mb[cpi->common.frame_type][i]);
  1.1281 +
  1.1282 +            if (bits_per_mb_at_this_q <= target_bits_per_mb)
  1.1283 +            {
  1.1284 +                if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
  1.1285 +                    Q = i;
  1.1286 +                else
  1.1287 +                    Q = i - 1;
  1.1288 +
  1.1289 +                break;
  1.1290 +            }
  1.1291 +            else
  1.1292 +                last_error = bits_per_mb_at_this_q - target_bits_per_mb;
  1.1293 +        }
  1.1294 +        while (++i <= cpi->active_worst_quality);
  1.1295 +
  1.1296 +
  1.1297 +        /* If we are at MAXQ then enable Q over-run which seeks to claw
  1.1298 +         * back additional bits through things like the RD multiplier
  1.1299 +         * and zero bin size.
  1.1300 +         */
  1.1301 +        if (Q >= MAXQ)
  1.1302 +        {
  1.1303 +            int zbin_oqmax;
  1.1304 +
  1.1305 +            double Factor = 0.99;
  1.1306 +            double factor_adjustment = 0.01 / 256.0;
  1.1307 +
  1.1308 +            if (cpi->common.frame_type == KEY_FRAME)
  1.1309 +                zbin_oqmax = 0;
  1.1310 +            else if (cpi->oxcf.number_of_layers == 1 &&
  1.1311 +                (cpi->common.refresh_alt_ref_frame ||
  1.1312 +                (cpi->common.refresh_golden_frame &&
  1.1313 +                 !cpi->source_alt_ref_active)))
  1.1314 +                zbin_oqmax = 16;
  1.1315 +            else
  1.1316 +                zbin_oqmax = ZBIN_OQ_MAX;
  1.1317 +
  1.1318 +            /*{
  1.1319 +                double Factor = (double)target_bits_per_mb/(double)bits_per_mb_at_this_q;
  1.1320 +                double Oq;
  1.1321 +
  1.1322 +                Factor = Factor/1.2683;
  1.1323 +
  1.1324 +                Oq = pow( Factor, (1.0/-0.165) );
  1.1325 +
  1.1326 +                if ( Oq > zbin_oqmax )
  1.1327 +                    Oq = zbin_oqmax;
  1.1328 +
  1.1329 +                cpi->zbin_over_quant = (int)Oq;
  1.1330 +            }*/
  1.1331 +
  1.1332 +            /* Each incrment in the zbin is assumed to have a fixed effect
  1.1333 +             * on bitrate. This is not of course true. The effect will be
  1.1334 +             * highly clip dependent and may well have sudden steps. The
  1.1335 +             * idea here is to acheive higher effective quantizers than the
  1.1336 +             * normal maximum by expanding the zero bin and hence
  1.1337 +             * decreasing the number of low magnitude non zero coefficients.
  1.1338 +             */
  1.1339 +            while (cpi->mb.zbin_over_quant < zbin_oqmax)
  1.1340 +            {
  1.1341 +                cpi->mb.zbin_over_quant ++;
  1.1342 +
  1.1343 +                if (cpi->mb.zbin_over_quant > zbin_oqmax)
  1.1344 +                    cpi->mb.zbin_over_quant = zbin_oqmax;
  1.1345 +
  1.1346 +                /* Adjust bits_per_mb_at_this_q estimate */
  1.1347 +                bits_per_mb_at_this_q = (int)(Factor * bits_per_mb_at_this_q);
  1.1348 +                Factor += factor_adjustment;
  1.1349 +
  1.1350 +                if (Factor  >= 0.999)
  1.1351 +                    Factor = 0.999;
  1.1352 +
  1.1353 +                /* Break out if we get down to the target rate */
  1.1354 +                if (bits_per_mb_at_this_q <= target_bits_per_mb)
  1.1355 +                    break;
  1.1356 +            }
  1.1357 +
  1.1358 +        }
  1.1359 +    }
  1.1360 +
  1.1361 +    return Q;
  1.1362 +}
  1.1363 +
  1.1364 +
  1.1365 +static int estimate_keyframe_frequency(VP8_COMP *cpi)
  1.1366 +{
  1.1367 +    int i;
  1.1368 +
  1.1369 +    /* Average key frame frequency */
  1.1370 +    int av_key_frame_frequency = 0;
  1.1371 +
  1.1372 +    /* First key frame at start of sequence is a special case. We have no
  1.1373 +     * frequency data.
  1.1374 +     */
  1.1375 +    if (cpi->key_frame_count == 1)
  1.1376 +    {
  1.1377 +        /* Assume a default of 1 kf every 2 seconds, or the max kf interval,
  1.1378 +         * whichever is smaller.
  1.1379 +         */
  1.1380 +        int key_freq = cpi->oxcf.key_freq>0 ? cpi->oxcf.key_freq : 1;
  1.1381 +        av_key_frame_frequency = 1 + (int)cpi->output_framerate * 2;
  1.1382 +
  1.1383 +        if (cpi->oxcf.auto_key && av_key_frame_frequency > key_freq)
  1.1384 +            av_key_frame_frequency = key_freq;
  1.1385 +
  1.1386 +        cpi->prior_key_frame_distance[KEY_FRAME_CONTEXT - 1]
  1.1387 +            = av_key_frame_frequency;
  1.1388 +    }
  1.1389 +    else
  1.1390 +    {
  1.1391 +        unsigned int total_weight = 0;
  1.1392 +        int last_kf_interval =
  1.1393 +                (cpi->frames_since_key > 0) ? cpi->frames_since_key : 1;
  1.1394 +
  1.1395 +        /* reset keyframe context and calculate weighted average of last
  1.1396 +         * KEY_FRAME_CONTEXT keyframes
  1.1397 +         */
  1.1398 +        for (i = 0; i < KEY_FRAME_CONTEXT; i++)
  1.1399 +        {
  1.1400 +            if (i < KEY_FRAME_CONTEXT - 1)
  1.1401 +                cpi->prior_key_frame_distance[i]
  1.1402 +                    = cpi->prior_key_frame_distance[i+1];
  1.1403 +            else
  1.1404 +                cpi->prior_key_frame_distance[i] = last_kf_interval;
  1.1405 +
  1.1406 +            av_key_frame_frequency += prior_key_frame_weight[i]
  1.1407 +                                      * cpi->prior_key_frame_distance[i];
  1.1408 +            total_weight += prior_key_frame_weight[i];
  1.1409 +        }
  1.1410 +
  1.1411 +        av_key_frame_frequency  /= total_weight;
  1.1412 +
  1.1413 +    }
  1.1414 +    // TODO (marpan): Given the checks above, |av_key_frame_frequency|
  1.1415 +    // should always be above 0. But for now we keep the sanity check in.
  1.1416 +    if (av_key_frame_frequency == 0)
  1.1417 +        av_key_frame_frequency = 1;
  1.1418 +    return av_key_frame_frequency;
  1.1419 +}
  1.1420 +
  1.1421 +
  1.1422 +void vp8_adjust_key_frame_context(VP8_COMP *cpi)
  1.1423 +{
  1.1424 +    /* Clear down mmx registers to allow floating point in what follows */
  1.1425 +    vp8_clear_system_state();
  1.1426 +
  1.1427 +    /* Do we have any key frame overspend to recover? */
  1.1428 +    /* Two-pass overspend handled elsewhere. */
  1.1429 +    if ((cpi->pass != 2)
  1.1430 +         && (cpi->projected_frame_size > cpi->per_frame_bandwidth))
  1.1431 +    {
  1.1432 +        int overspend;
  1.1433 +
  1.1434 +        /* Update the count of key frame overspend to be recovered in
  1.1435 +         * subsequent frames. A portion of the KF overspend is treated as gf
  1.1436 +         * overspend (and hence recovered more quickly) as the kf is also a
  1.1437 +         * gf. Otherwise the few frames following each kf tend to get more
  1.1438 +         * bits allocated than those following other gfs.
  1.1439 +         */
  1.1440 +        overspend = (cpi->projected_frame_size - cpi->per_frame_bandwidth);
  1.1441 +
  1.1442 +        if (cpi->oxcf.number_of_layers > 1)
  1.1443 +            cpi->kf_overspend_bits += overspend;
  1.1444 +        else
  1.1445 +        {
  1.1446 +            cpi->kf_overspend_bits += overspend * 7 / 8;
  1.1447 +            cpi->gf_overspend_bits += overspend * 1 / 8;
  1.1448 +        }
  1.1449 +
  1.1450 +        /* Work out how much to try and recover per frame. */
  1.1451 +        cpi->kf_bitrate_adjustment = cpi->kf_overspend_bits
  1.1452 +                                     / estimate_keyframe_frequency(cpi);
  1.1453 +    }
  1.1454 +
  1.1455 +    cpi->frames_since_key = 0;
  1.1456 +    cpi->key_frame_count++;
  1.1457 +}
  1.1458 +
  1.1459 +
  1.1460 +void vp8_compute_frame_size_bounds(VP8_COMP *cpi, int *frame_under_shoot_limit, int *frame_over_shoot_limit)
  1.1461 +{
  1.1462 +    /* Set-up bounds on acceptable frame size: */
  1.1463 +    if (cpi->oxcf.fixed_q >= 0)
  1.1464 +    {
  1.1465 +        /* Fixed Q scenario: frame size never outranges target
  1.1466 +         * (there is no target!)
  1.1467 +         */
  1.1468 +        *frame_under_shoot_limit = 0;
  1.1469 +        *frame_over_shoot_limit  = INT_MAX;
  1.1470 +    }
  1.1471 +    else
  1.1472 +    {
  1.1473 +        if (cpi->common.frame_type == KEY_FRAME)
  1.1474 +        {
  1.1475 +            *frame_over_shoot_limit  = cpi->this_frame_target * 9 / 8;
  1.1476 +            *frame_under_shoot_limit = cpi->this_frame_target * 7 / 8;
  1.1477 +        }
  1.1478 +        else
  1.1479 +        {
  1.1480 +            if (cpi->oxcf.number_of_layers > 1 ||
  1.1481 +                cpi->common.refresh_alt_ref_frame ||
  1.1482 +                cpi->common.refresh_golden_frame)
  1.1483 +            {
  1.1484 +                *frame_over_shoot_limit  = cpi->this_frame_target * 9 / 8;
  1.1485 +                *frame_under_shoot_limit = cpi->this_frame_target * 7 / 8;
  1.1486 +            }
  1.1487 +            else
  1.1488 +            {
  1.1489 +                /* For CBR take buffer fullness into account */
  1.1490 +                if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
  1.1491 +                {
  1.1492 +                    if (cpi->buffer_level >= ((cpi->oxcf.optimal_buffer_level + cpi->oxcf.maximum_buffer_size) >> 1))
  1.1493 +                    {
  1.1494 +                        /* Buffer is too full so relax overshoot and tighten
  1.1495 +                         * undershoot
  1.1496 +                         */
  1.1497 +                        *frame_over_shoot_limit  = cpi->this_frame_target * 12 / 8;
  1.1498 +                        *frame_under_shoot_limit = cpi->this_frame_target * 6 / 8;
  1.1499 +                    }
  1.1500 +                    else if (cpi->buffer_level <= (cpi->oxcf.optimal_buffer_level >> 1))
  1.1501 +                    {
  1.1502 +                        /* Buffer is too low so relax undershoot and tighten
  1.1503 +                         * overshoot
  1.1504 +                         */
  1.1505 +                        *frame_over_shoot_limit  = cpi->this_frame_target * 10 / 8;
  1.1506 +                        *frame_under_shoot_limit = cpi->this_frame_target * 4 / 8;
  1.1507 +                    }
  1.1508 +                    else
  1.1509 +                    {
  1.1510 +                        *frame_over_shoot_limit  = cpi->this_frame_target * 11 / 8;
  1.1511 +                        *frame_under_shoot_limit = cpi->this_frame_target * 5 / 8;
  1.1512 +                    }
  1.1513 +                }
  1.1514 +                /* VBR and CQ mode */
  1.1515 +                /* Note that tighter restrictions here can help quality
  1.1516 +                 * but hurt encode speed
  1.1517 +                 */
  1.1518 +                else
  1.1519 +                {
  1.1520 +                    /* Stron overshoot limit for constrained quality */
  1.1521 +                    if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY)
  1.1522 +                    {
  1.1523 +                        *frame_over_shoot_limit  = cpi->this_frame_target * 11 / 8;
  1.1524 +                        *frame_under_shoot_limit = cpi->this_frame_target * 2 / 8;
  1.1525 +                    }
  1.1526 +                    else
  1.1527 +                    {
  1.1528 +                        *frame_over_shoot_limit  = cpi->this_frame_target * 11 / 8;
  1.1529 +                        *frame_under_shoot_limit = cpi->this_frame_target * 5 / 8;
  1.1530 +                    }
  1.1531 +                }
  1.1532 +            }
  1.1533 +        }
  1.1534 +
  1.1535 +        /* For very small rate targets where the fractional adjustment
  1.1536 +         * (eg * 7/8) may be tiny make sure there is at least a minimum
  1.1537 +         * range.
  1.1538 +         */
  1.1539 +        *frame_over_shoot_limit += 200;
  1.1540 +        *frame_under_shoot_limit -= 200;
  1.1541 +        if ( *frame_under_shoot_limit < 0 )
  1.1542 +            *frame_under_shoot_limit = 0;
  1.1543 +
  1.1544 +    }
  1.1545 +}
  1.1546 +
  1.1547 +
  1.1548 +/* return of 0 means drop frame */
  1.1549 +int vp8_pick_frame_size(VP8_COMP *cpi)
  1.1550 +{
  1.1551 +    VP8_COMMON *cm = &cpi->common;
  1.1552 +
  1.1553 +    if (cm->frame_type == KEY_FRAME)
  1.1554 +        calc_iframe_target_size(cpi);
  1.1555 +    else
  1.1556 +    {
  1.1557 +        calc_pframe_target_size(cpi);
  1.1558 +
  1.1559 +        /* Check if we're dropping the frame: */
  1.1560 +        if (cpi->drop_frame)
  1.1561 +        {
  1.1562 +            cpi->drop_frame = 0;
  1.1563 +            return 0;
  1.1564 +        }
  1.1565 +    }
  1.1566 +    return 1;
  1.1567 +}

mercurial