vp9_ratectrl.c 60.9 KB
Newer Older
John Koleszar's avatar
John Koleszar committed
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
John Koleszar's avatar
John Koleszar committed
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5 6
 *  that can be found in the LICENSE file in the root of the source
 *  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.
John Koleszar's avatar
John Koleszar committed
9 10 11
 */

#include <assert.h>
12
#include <limits.h>
Dmitry Kovalev's avatar
Dmitry Kovalev committed
13
#include <math.h>
14 15 16 17 18
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "vpx_mem/vpx_mem.h"
John Koleszar's avatar
John Koleszar committed
19

20 21 22 23
#include "vp9/common/vp9_alloccommon.h"
#include "vp9/common/vp9_common.h"
#include "vp9/common/vp9_entropymode.h"
#include "vp9/common/vp9_quant_common.h"
24
#include "vp9/common/vp9_seg_common.h"
25 26 27 28
#include "vp9/common/vp9_systemdependent.h"

#include "vp9/encoder/vp9_encodemv.h"
#include "vp9/encoder/vp9_ratectrl.h"
John Koleszar's avatar
John Koleszar committed
29

30 31 32 33 34
// Max rate target for 1080P and below encodes under normal circumstances
// (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
#define MAX_MB_RATE 250
#define MAXRATE_1080P 2025000

35 36 37
#define DEFAULT_KF_BOOST 2000
#define DEFAULT_GF_BOOST 2000

Deb Mukherjee's avatar
Deb Mukherjee committed
38
#define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
39

Dmitry Kovalev's avatar
Dmitry Kovalev committed
40 41
#define MIN_BPB_FACTOR 0.005
#define MAX_BPB_FACTOR 50
John Koleszar's avatar
John Koleszar committed
42

43 44
#define FRAME_OVERHEAD_BITS 200

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#if CONFIG_VP9_HIGHBITDEPTH
#define ASSIGN_MINQ_TABLE(bit_depth, name) \
  do { \
    switch (bit_depth) { \
      case VPX_BITS_8: \
        name = name##_8; \
        break; \
      case VPX_BITS_10: \
        name = name##_10; \
        break; \
      case VPX_BITS_12: \
        name = name##_12; \
        break; \
      default: \
        assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10" \
                    " or VPX_BITS_12"); \
        name = NULL; \
    } \
  } while (0)
#else
#define ASSIGN_MINQ_TABLE(bit_depth, name) \
  do { \
    (void) bit_depth; \
    name = name##_8; \
  } while (0)
#endif

72
// Tables relating active max Q to active min Q
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
static int kf_low_motion_minq_8[QINDEX_RANGE];
static int kf_high_motion_minq_8[QINDEX_RANGE];
static int arfgf_low_motion_minq_8[QINDEX_RANGE];
static int arfgf_high_motion_minq_8[QINDEX_RANGE];
static int inter_minq_8[QINDEX_RANGE];
static int rtc_minq_8[QINDEX_RANGE];

#if CONFIG_VP9_HIGHBITDEPTH
static int kf_low_motion_minq_10[QINDEX_RANGE];
static int kf_high_motion_minq_10[QINDEX_RANGE];
static int arfgf_low_motion_minq_10[QINDEX_RANGE];
static int arfgf_high_motion_minq_10[QINDEX_RANGE];
static int inter_minq_10[QINDEX_RANGE];
static int rtc_minq_10[QINDEX_RANGE];
static int kf_low_motion_minq_12[QINDEX_RANGE];
static int kf_high_motion_minq_12[QINDEX_RANGE];
static int arfgf_low_motion_minq_12[QINDEX_RANGE];
static int arfgf_high_motion_minq_12[QINDEX_RANGE];
static int inter_minq_12[QINDEX_RANGE];
static int rtc_minq_12[QINDEX_RANGE];
#endif

Deb Mukherjee's avatar
Deb Mukherjee committed
95 96 97 98
static int gf_high = 2000;
static int gf_low = 400;
static int kf_high = 5000;
static int kf_low = 400;
99 100 101 102 103

// Functions to compute the active minq lookup table entries based on a
// formulaic approach to facilitate easier adjustment of the Q tables.
// The formulae were derived from computing a 3rd order polynomial best
// fit to the original data (after plotting real maxq vs minq (not q index))
104 105
static int get_minq_index(double maxq, double x3, double x2, double x1,
                          vpx_bit_depth_t bit_depth) {
106
  int i;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
107
  const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq,
108 109 110 111 112 113 114
                                maxq);

  // Special case handling to deal with the step from q2.0
  // down to lossless mode represented by q 1.0.
  if (minqtarget <= 2.0)
    return 0;

115 116
  for (i = 0; i < QINDEX_RANGE; i++) {
    if (minqtarget <= vp9_convert_qindex_to_q(i, bit_depth))
117
      return i;
118
  }
119 120 121 122

  return QINDEX_RANGE - 1;
}

123 124 125
static void init_minq_luts(int *kf_low_m, int *kf_high_m,
                           int *arfgf_low, int *arfgf_high,
                           int *inter, int *rtc, vpx_bit_depth_t bit_depth) {
126 127
  int i;
  for (i = 0; i < QINDEX_RANGE; i++) {
128
    const double maxq = vp9_convert_qindex_to_q(i, bit_depth);
129 130
    kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
    kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
131
    arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
132
    arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
133 134
    inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.90, bit_depth);
    rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
135 136 137
  }
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151
void vp9_rc_init_minq_luts() {
  init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
                 arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
                 inter_minq_8, rtc_minq_8, VPX_BITS_8);
#if CONFIG_VP9_HIGHBITDEPTH
  init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
                 arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
                 inter_minq_10, rtc_minq_10, VPX_BITS_10);
  init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
                 arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
                 inter_minq_12, rtc_minq_12, VPX_BITS_12);
#endif
}

Paul Wilkins's avatar
Paul Wilkins committed
152 153 154
// These functions use formulaic calculations to make playing with the
// quantizer tables easier. If necessary they can be replaced by lookup
// tables if and when things settle down in the experimental bitstream
155
double vp9_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
John Koleszar's avatar
John Koleszar committed
156
  // Convert the index to a real Q value (scaled down to match old Q values)
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
#if CONFIG_VP9_HIGHBITDEPTH
  switch (bit_depth) {
    case VPX_BITS_8:
      return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
    case VPX_BITS_10:
      return vp9_ac_quant(qindex, 0, bit_depth) / 16.0;
    case VPX_BITS_12:
      return vp9_ac_quant(qindex, 0, bit_depth) / 64.0;
    default:
      assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
      return -1.0;
  }
#else
  return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
#endif
Paul Wilkins's avatar
Paul Wilkins committed
172 173
}

174
int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
175 176 177
                       double correction_factor,
                       vpx_bit_depth_t bit_depth) {
  const double q = vp9_convert_qindex_to_q(qindex, bit_depth);
178
  int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
Paul Wilkins's avatar
Paul Wilkins committed
179

Paul Wilkins's avatar
Paul Wilkins committed
180 181 182
  assert(correction_factor <= MAX_BPB_FACTOR &&
         correction_factor >= MIN_BPB_FACTOR);

183
  // q based adjustment to baseline enumerator
Paul Wilkins's avatar
Paul Wilkins committed
184
  enumerator += (int)(enumerator * q) >> 12;
185
  return (int)(enumerator * correction_factor / q);
186
}
John Koleszar's avatar
John Koleszar committed
187

188
static int estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
189 190 191 192
                              double correction_factor,
                              vpx_bit_depth_t bit_depth) {
  const int bpm = (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor,
                                           bit_depth));
Paul Wilkins's avatar
Paul Wilkins committed
193 194
  return MAX(FRAME_OVERHEAD_BITS,
             (int)((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS);
195
}
196

197 198
int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
  const RATE_CONTROL *rc = &cpi->rc;
199
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
200
  const int min_frame_target = MAX(rc->min_frame_bandwidth,
201
                                   rc->avg_frame_bandwidth >> 5);
202 203
  if (target < min_frame_target)
    target = min_frame_target;
204
  if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
205 206 207 208
    // If there is an active ARF at this location use the minimum
    // bits on this frame even if it is a constructed arf.
    // The active maximum quantizer insures that an appropriate
    // number of bits will be spent if needed for constructed ARFs.
209
    target = min_frame_target;
210 211 212 213
  }
  // Clip the frame target to the maximum allowed value.
  if (target > rc->max_frame_bandwidth)
    target = rc->max_frame_bandwidth;
214 215 216 217 218
  if (oxcf->rc_max_inter_bitrate_pct) {
    const int max_rate = rc->avg_frame_bandwidth *
                         oxcf->rc_max_inter_bitrate_pct / 100;
    target = MIN(target, max_rate);
  }
219 220
  return target;
}
221

222 223
int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
  const RATE_CONTROL *rc = &cpi->rc;
224
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
225
  if (oxcf->rc_max_intra_bitrate_pct) {
226 227
    const int max_rate = rc->avg_frame_bandwidth *
                             oxcf->rc_max_intra_bitrate_pct / 100;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
228
    target = MIN(target, max_rate);
John Koleszar's avatar
John Koleszar committed
229
  }
230 231 232
  if (target > rc->max_frame_bandwidth)
    target = rc->max_frame_bandwidth;
  return target;
John Koleszar's avatar
John Koleszar committed
233 234
}

235 236

// Update the buffer level for higher layers, given the encoded current layer.
237
static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
238
  int temporal_layer = 0;
239
  int current_temporal_layer = svc->temporal_layer_id;
240
  for (temporal_layer = current_temporal_layer + 1;
241 242
      temporal_layer < svc->number_temporal_layers; ++temporal_layer) {
    LAYER_CONTEXT *lc = &svc->layer_context[temporal_layer];
243 244 245 246 247 248
    RATE_CONTROL *lrc = &lc->rc;
    int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
        encoded_frame_size);
    lrc->bits_off_target += bits_off_for_this_layer;

    // Clip buffer level to maximum buffer size for the layer.
249
    lrc->bits_off_target = MIN(lrc->bits_off_target, lrc->maximum_buffer_size);
250 251 252 253
    lrc->buffer_level = lrc->bits_off_target;
  }
}

254
// Update the buffer level: leaky bucket model.
255
static void update_buffer_level(VP9_COMP *cpi, int encoded_frame_size) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
256
  const VP9_COMMON *const cm = &cpi->common;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
257
  RATE_CONTROL *const rc = &cpi->rc;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
258

259 260
  // Non-viewable frames are a special case and are treated as pure overhead.
  if (!cm->show_frame) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
261
    rc->bits_off_target -= encoded_frame_size;
262
  } else {
263
    rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
264
  }
Dmitry Kovalev's avatar
Dmitry Kovalev committed
265

266
  // Clip the buffer level to the maximum specified buffer size.
267
  rc->bits_off_target = MIN(rc->bits_off_target, rc->maximum_buffer_size);
268 269
  rc->buffer_level = rc->bits_off_target;

270
  if (cpi->use_svc && cpi->oxcf.rc_mode == VPX_CBR) {
271
    update_layer_buffer_level(&cpi->svc, encoded_frame_size);
272
  }
273 274
}

275
void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
276 277
  int i;

278
  if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
279 280
    rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
    rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
281
  } else {
282 283 284 285
    rc->avg_frame_qindex[KEY_FRAME] = (oxcf->worst_allowed_q +
                                           oxcf->best_allowed_q) / 2;
    rc->avg_frame_qindex[INTER_FRAME] = (oxcf->worst_allowed_q +
                                           oxcf->best_allowed_q) / 2;
286 287
  }

288
  rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
Paul Wilkins's avatar
Paul Wilkins committed
289
  rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
290

291 292
  rc->buffer_level =    rc->starting_buffer_level;
  rc->bits_off_target = rc->starting_buffer_level;
293

294 295 296 297
  rc->rolling_target_bits      = rc->avg_frame_bandwidth;
  rc->rolling_actual_bits      = rc->avg_frame_bandwidth;
  rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
  rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
298 299

  rc->total_actual_bits = 0;
300
  rc->total_target_bits = 0;
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
  rc->total_target_vs_actual = 0;

  rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
  rc->frames_since_key = 8;  // Sensible default for first frame.
  rc->this_key_frame_forced = 0;
  rc->next_key_frame_forced = 0;
  rc->source_alt_ref_pending = 0;
  rc->source_alt_ref_active = 0;

  rc->frames_till_gf_update_due = 0;
  rc->ni_av_qi = oxcf->worst_allowed_q;
  rc->ni_tot_qi = 0;
  rc->ni_frames = 0;

  rc->tot_q = 0.0;
316
  rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
317

318 319 320
  for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
    rc->rate_correction_factors[i] = 1.0;
  }
321 322
}

323
int vp9_rc_drop_frame(VP9_COMP *cpi) {
324
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
325 326
  RATE_CONTROL *const rc = &cpi->rc;

Dmitry Kovalev's avatar
Dmitry Kovalev committed
327
  if (!oxcf->drop_frames_water_mark) {
328 329
    return 0;
  } else {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
330
    if (rc->buffer_level < 0) {
331 332 333 334 335
      // Always drop if buffer is below 0.
      return 1;
    } else {
      // If buffer is below drop_mark, for now just drop every other frame
      // (starting with the next frame) until it increases back over drop_mark.
Dmitry Kovalev's avatar
Dmitry Kovalev committed
336
      int drop_mark = (int)(oxcf->drop_frames_water_mark *
337
          rc->optimal_buffer_level / 100);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
338 339 340 341 342 343
      if ((rc->buffer_level > drop_mark) &&
          (rc->decimation_factor > 0)) {
        --rc->decimation_factor;
      } else if (rc->buffer_level <= drop_mark &&
          rc->decimation_factor == 0) {
        rc->decimation_factor = 1;
344
      }
Dmitry Kovalev's avatar
Dmitry Kovalev committed
345 346 347
      if (rc->decimation_factor > 0) {
        if (rc->decimation_count > 0) {
          --rc->decimation_count;
348 349
          return 1;
        } else {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
350
          rc->decimation_count = rc->decimation_factor;
351 352 353
          return 0;
        }
      } else {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
354
        rc->decimation_count = 0;
355 356 357 358 359 360
        return 0;
      }
    }
  }
}

361
static double get_rate_correction_factor(const VP9_COMP *cpi) {
362 363
  const RATE_CONTROL *const rc = &cpi->rc;

364
  if (cpi->common.frame_type == KEY_FRAME) {
365
    return rc->rate_correction_factors[KF_STD];
366
  } else if (cpi->oxcf.pass == 2) {
367 368 369
    RATE_FACTOR_LEVEL rf_lvl =
      cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
    return rc->rate_correction_factors[rf_lvl];
370
  } else {
371
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
372 373
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
        cpi->oxcf.rc_mode != VPX_CBR)
374
      return rc->rate_correction_factors[GF_ARF_STD];
375
    else
376
      return rc->rate_correction_factors[INTER_NORMAL];
377 378 379 380
  }
}

static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
381 382
  RATE_CONTROL *const rc = &cpi->rc;

383
  if (cpi->common.frame_type == KEY_FRAME) {
384
    rc->rate_correction_factors[KF_STD] = factor;
385
  } else if (cpi->oxcf.pass == 2) {
386 387 388
    RATE_FACTOR_LEVEL rf_lvl =
      cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
    rc->rate_correction_factors[rf_lvl] = factor;
389
  } else {
390
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
391 392
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
        cpi->oxcf.rc_mode != VPX_CBR)
393
      rc->rate_correction_factors[GF_ARF_STD] = factor;
394
    else
395
      rc->rate_correction_factors[INTER_NORMAL] = factor;
396 397 398
  }
}

399
void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi, int damp_var) {
400
  const VP9_COMMON *const cm = &cpi->common;
401
  int correction_factor = 100;
402
  double rate_correction_factor = get_rate_correction_factor(cpi);
John Koleszar's avatar
John Koleszar committed
403
  double adjustment_limit;
John Koleszar's avatar
John Koleszar committed
404

405
  int projected_size_based_on_q = 0;
John Koleszar's avatar
John Koleszar committed
406

Paul Wilkins's avatar
Paul Wilkins committed
407 408 409 410
  // Do not update the rate factors for arf overlay frames.
  if (cpi->rc.is_src_frame_alt_ref)
    return;

John Koleszar's avatar
John Koleszar committed
411
  // Clear down mmx registers to allow floating point in what follows
412
  vp9_clear_system_state();
John Koleszar's avatar
John Koleszar committed
413

414 415
  // Work out how big we would have expected the frame to be at this Q given
  // the current correction factor.
John Koleszar's avatar
John Koleszar committed
416
  // Stay in double to avoid int overflow when values are large
417 418
  projected_size_based_on_q = estimate_bits_at_q(cm->frame_type,
                                                 cm->base_qindex, cm->MBs,
419 420
                                                 rate_correction_factor,
                                                 cm->bit_depth);
John Koleszar's avatar
John Koleszar committed
421
  // Work out a size correction factor.
Paul Wilkins's avatar
Paul Wilkins committed
422
  if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
423 424
    correction_factor = (100 * cpi->rc.projected_frame_size) /
                            projected_size_based_on_q;
John Koleszar's avatar
John Koleszar committed
425

426 427
  // More heavily damped adjustment used if we have been oscillating either side
  // of target.
John Koleszar's avatar
John Koleszar committed
428
  switch (damp_var) {
John Koleszar's avatar
John Koleszar committed
429
    case 0:
John Koleszar's avatar
John Koleszar committed
430 431
      adjustment_limit = 0.75;
      break;
John Koleszar's avatar
John Koleszar committed
432
    case 1:
433 434
      adjustment_limit = 0.25 +
          0.5 * MIN(1, fabs(log10(0.01 * correction_factor)));
John Koleszar's avatar
John Koleszar committed
435
      break;
John Koleszar's avatar
John Koleszar committed
436 437
    case 2:
    default:
John Koleszar's avatar
John Koleszar committed
438 439 440 441
      adjustment_limit = 0.25;
      break;
  }

442 443 444 445 446 447 448 449 450 451
  cpi->rc.q_2_frame = cpi->rc.q_1_frame;
  cpi->rc.q_1_frame = cm->base_qindex;
  cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
  if (correction_factor > 110)
    cpi->rc.rc_1_frame = -1;
  else if (correction_factor < 90)
    cpi->rc.rc_1_frame = 1;
  else
    cpi->rc.rc_1_frame = 0;

John Koleszar's avatar
John Koleszar committed
452 453
  if (correction_factor > 102) {
    // We are not already at the worst allowable quality
454 455 456
    correction_factor = (int)(100 + ((correction_factor - 100) *
                                  adjustment_limit));
    rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
John Koleszar's avatar
John Koleszar committed
457 458 459
    // Keep rate_correction_factor within limits
    if (rate_correction_factor > MAX_BPB_FACTOR)
      rate_correction_factor = MAX_BPB_FACTOR;
460
  } else if (correction_factor < 99) {
John Koleszar's avatar
John Koleszar committed
461
    // We are not already at the best allowable quality
462 463 464
    correction_factor = (int)(100 - ((100 - correction_factor) *
                                  adjustment_limit));
    rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
John Koleszar's avatar
John Koleszar committed
465 466 467 468 469 470

    // Keep rate_correction_factor within limits
    if (rate_correction_factor < MIN_BPB_FACTOR)
      rate_correction_factor = MIN_BPB_FACTOR;
  }

471
  set_rate_correction_factor(cpi, rate_correction_factor);
John Koleszar's avatar
John Koleszar committed
472 473 474
}


Deb Mukherjee's avatar
Deb Mukherjee committed
475 476
int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
                      int active_best_quality, int active_worst_quality) {
477
  const VP9_COMMON *const cm = &cpi->common;
Deb Mukherjee's avatar
Deb Mukherjee committed
478
  int q = active_worst_quality;
John Koleszar's avatar
John Koleszar committed
479
  int last_error = INT_MAX;
480
  int i, target_bits_per_mb;
481
  const double correction_factor = get_rate_correction_factor(cpi);
John Koleszar's avatar
John Koleszar committed
482

483 484
  // Calculate required scaling factor based on target frame size and size of
  // frame produced using previous Q.
485 486
  target_bits_per_mb =
      ((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs;
John Koleszar's avatar
John Koleszar committed
487

Deb Mukherjee's avatar
Deb Mukherjee committed
488
  i = active_best_quality;
John Koleszar's avatar
John Koleszar committed
489

John Koleszar's avatar
John Koleszar committed
490
  do {
491
    const int bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cm->frame_type, i,
492 493
                                                              correction_factor,
                                                              cm->bit_depth);
John Koleszar's avatar
John Koleszar committed
494

John Koleszar's avatar
John Koleszar committed
495 496
    if (bits_per_mb_at_this_q <= target_bits_per_mb) {
      if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
497
        q = i;
John Koleszar's avatar
John Koleszar committed
498
      else
499
        q = i - 1;
John Koleszar's avatar
John Koleszar committed
500

John Koleszar's avatar
John Koleszar committed
501
      break;
502
    } else {
John Koleszar's avatar
John Koleszar committed
503
      last_error = bits_per_mb_at_this_q - target_bits_per_mb;
504
    }
Deb Mukherjee's avatar
Deb Mukherjee committed
505
  } while (++i <= active_worst_quality);
506

507 508 509 510 511 512 513 514
  // In CBR mode, this makes sure q is between oscillating Qs to prevent
  // resonance.
  if (cpi->oxcf.rc_mode == VPX_CBR &&
      (cpi->rc.rc_1_frame * cpi->rc.rc_2_frame == -1) &&
      cpi->rc.q_1_frame != cpi->rc.q_2_frame) {
    q = clamp(q, MIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
              MAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
  }
515 516 517
  return q;
}

518 519
static int get_active_quality(int q, int gfu_boost, int low, int high,
                              int *low_motion_minq, int *high_motion_minq) {
520
  if (gfu_boost > high) {
521
    return low_motion_minq[q];
522
  } else if (gfu_boost < low) {
523
    return high_motion_minq[q];
524 525 526 527 528
  } else {
    const int gap = high - low;
    const int offset = high - gfu_boost;
    const int qdiff = high_motion_minq[q] - low_motion_minq[q];
    const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
529
    return low_motion_minq[q] + adjustment;
530 531 532
  }
}

533 534 535 536 537 538
static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
                                 vpx_bit_depth_t bit_depth) {
  int *kf_low_motion_minq;
  int *kf_high_motion_minq;
  ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
  ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
539 540 541 542
  return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
                            kf_low_motion_minq, kf_high_motion_minq);
}

543 544 545 546 547 548
static int get_gf_active_quality(const RATE_CONTROL *const rc, int q,
                                 vpx_bit_depth_t bit_depth) {
  int *arfgf_low_motion_minq;
  int *arfgf_high_motion_minq;
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
549 550 551 552
  return get_active_quality(q, rc->gfu_boost, gf_low, gf_high,
                            arfgf_low_motion_minq, arfgf_high_motion_minq);
}

553
static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
554 555
  const RATE_CONTROL *const rc = &cpi->rc;
  const unsigned int curr_frame = cpi->common.current_video_frame;
556
  int active_worst_quality;
557

558
  if (cpi->common.frame_type == KEY_FRAME) {
559 560
    active_worst_quality = curr_frame == 0 ? rc->worst_quality
                                           : rc->last_q[KEY_FRAME] * 2;
561
  } else {
562 563 564 565
    if (!rc->is_src_frame_alt_ref &&
        (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
      active_worst_quality =  curr_frame == 1 ? rc->last_q[KEY_FRAME] * 5 / 4
                                              : rc->last_q[INTER_FRAME];
566
    } else {
567 568
      active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 2
                                             : rc->last_q[INTER_FRAME] * 2;
569 570
    }
  }
571
  return MIN(active_worst_quality, rc->worst_quality);
572 573 574 575 576 577 578 579 580
}

// Adjust active_worst_quality level based on buffer level.
static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
  // Adjust active_worst_quality: If buffer is above the optimal/target level,
  // bring active_worst_quality down depending on fullness of buffer.
  // If buffer is below the optimal level, let the active_worst_quality go from
  // ambient Q (at buffer = optimal level) to worst_quality level
  // (at buffer = critical level).
581
  const VP9_COMMON *const cm = &cpi->common;
582 583
  const RATE_CONTROL *rc = &cpi->rc;
  // Buffer level below which we push active_worst to worst_quality.
584
  int64_t critical_level = rc->optimal_buffer_level >> 3;
585
  int64_t buff_lvl_step = 0;
586 587
  int adjustment = 0;
  int active_worst_quality;
588
  int ambient_qp;
589
  if (cm->frame_type == KEY_FRAME)
590 591 592 593 594 595 596 597 598 599 600
    return rc->worst_quality;
  // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
  // for the first few frames following key frame. These are both initialized
  // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
  // So for first few frames following key, the qp of that key frame is weighted
  // into the active_worst_quality setting.
  ambient_qp = (cm->current_video_frame < 5) ?
      MIN(rc->avg_frame_qindex[INTER_FRAME], rc->avg_frame_qindex[KEY_FRAME]) :
      rc->avg_frame_qindex[INTER_FRAME];
  active_worst_quality = MIN(rc->worst_quality,
                             ambient_qp * 5 / 4);
601
  if (rc->buffer_level > rc->optimal_buffer_level) {
602
    // Adjust down.
603
    // Maximum limit for down adjustment, ~30%.
604 605
    int max_adjustment_down = active_worst_quality / 3;
    if (max_adjustment_down) {
606 607
      buff_lvl_step = ((rc->maximum_buffer_size -
                        rc->optimal_buffer_level) / max_adjustment_down);
608
      if (buff_lvl_step)
609
        adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
610 611 612 613 614 615
                            buff_lvl_step);
      active_worst_quality -= adjustment;
    }
  } else if (rc->buffer_level > critical_level) {
    // Adjust up from ambient Q.
    if (critical_level) {
616
      buff_lvl_step = (rc->optimal_buffer_level - critical_level);
617
      if (buff_lvl_step) {
618 619 620
        adjustment = (int)((rc->worst_quality - ambient_qp) *
                           (rc->optimal_buffer_level - rc->buffer_level) /
                           buff_lvl_step);
621
      }
622
      active_worst_quality = ambient_qp + adjustment;
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
    }
  } else {
    // Set to worst_quality if buffer is below critical level.
    active_worst_quality = rc->worst_quality;
  }
  return active_worst_quality;
}

static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
                                             int *bottom_index,
                                             int *top_index) {
  const VP9_COMMON *const cm = &cpi->common;
  const RATE_CONTROL *const rc = &cpi->rc;
  int active_best_quality;
  int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
  int q;
639 640
  int *rtc_minq;
  ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
641 642 643

  if (frame_is_intra_only(cm)) {
    active_best_quality = rc->best_quality;
644
    // Handle the special case for key frames forced when we have reached
645 646 647 648
    // the maximum key frame interval. Here force the Q to a range
    // based on the ambient Q to reduce the risk of popping.
    if (rc->this_key_frame_forced) {
      int qindex = rc->last_boosted_qindex;
649
      double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
650
      int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
651 652
                                            (last_boosted_q * 0.75),
                                            cm->bit_depth);
653 654 655 656 657 658
      active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
    } else if (cm->current_video_frame > 0) {
      // not first frame of one pass and kf_boost is set
      double q_adj_factor = 1.0;
      double q_val;

659
      active_best_quality =
660 661
          get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
                                cm->bit_depth);
662 663 664 665 666 667 668 669

      // Allow somewhat lower kf minq with small image formats.
      if ((cm->width * cm->height) <= (352 * 288)) {
        q_adj_factor -= 0.25;
      }

      // Convert the adjustment factor to a qindex delta
      // on active_best_quality.
670
      q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
671
      active_best_quality += vp9_compute_qdelta(rc, q_val,
672 673
                                                q_val * q_adj_factor,
                                                cm->bit_depth);
674 675
    }
  } else if (!rc->is_src_frame_alt_ref &&
676
             !cpi->use_svc &&
677 678 679 680 681 682 683 684 685 686
             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
    // Use the lower of active_worst_quality and recent
    // average Q as basis for GF/ARF best Q limit unless last frame was
    // a key frame.
    if (rc->frames_since_key > 1 &&
        rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
      q = rc->avg_frame_qindex[INTER_FRAME];
    } else {
      q = active_worst_quality;
    }
687
    active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
688 689 690 691
  } else {
    // Use the lower of active_worst_quality and recent/average Q.
    if (cm->current_video_frame > 1) {
      if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
692
        active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
693
      else
694
        active_best_quality = rtc_minq[active_worst_quality];
695 696
    } else {
      if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
697
        active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
698
      else
699
        active_best_quality = rtc_minq[active_worst_quality];
700 701 702 703 704 705 706 707 708 709 710 711 712 713
    }
  }

  // Clip the active best and worst quality values to limits
  active_best_quality = clamp(active_best_quality,
                              rc->best_quality, rc->worst_quality);
  active_worst_quality = clamp(active_worst_quality,
                               active_best_quality, rc->worst_quality);

  *top_index = active_worst_quality;
  *bottom_index = active_best_quality;

#if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
  // Limit Q range for the adaptive loop.
Paul Wilkins's avatar
Paul Wilkins committed
714 715 716 717 718 719
  if (cm->frame_type == KEY_FRAME &&
      !rc->this_key_frame_forced  &&
      !(cm->current_video_frame == 0)) {
    int qdelta = 0;
    vp9_clear_system_state();
    qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
720 721
                                        active_worst_quality, 2.0,
                                        cm->bit_depth);
Paul Wilkins's avatar
Paul Wilkins committed
722 723
    *top_index = active_worst_quality + qdelta;
    *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
724 725
  }
#endif
Paul Wilkins's avatar
Paul Wilkins committed
726

727 728 729 730 731 732 733 734
  // Special case code to try and match quality with forced key frames
  if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
    q = rc->last_boosted_qindex;
  } else {
    q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
                          active_best_quality, active_worst_quality);
    if (q > *top_index) {
      // Special case when we are targeting the max allowed rate
735
      if (rc->this_frame_target >= rc->max_frame_bandwidth)
736 737 738 739 740 741 742 743 744 745 746 747 748
        *top_index = q;
      else
        q = *top_index;
    }
  }
  assert(*top_index <= rc->worst_quality &&
         *top_index >= rc->best_quality);
  assert(*bottom_index <= rc->worst_quality &&
         *bottom_index >= rc->best_quality);
  assert(q <= rc->worst_quality && q >= rc->best_quality);
  return q;
}

749 750 751 752
static int get_active_cq_level(const RATE_CONTROL *rc,
                               const VP9EncoderConfig *const oxcf) {
  static const double cq_adjust_threshold = 0.5;
  int active_cq_level = oxcf->cq_level;
753
  if (oxcf->rc_mode == VPX_CQ &&
754
      rc->total_target_bits > 0) {
755
    const double x = (double)rc->total_actual_bits / rc->total_target_bits;
756
    if (x < cq_adjust_threshold) {
757
      active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
758 759 760 761 762
    }
  }
  return active_cq_level;
}

763 764 765
static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
                                             int *bottom_index,
                                             int *top_index) {
Deb Mukherjee's avatar
Deb Mukherjee committed
766
  const VP9_COMMON *const cm = &cpi->common;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
767
  const RATE_CONTROL *const rc = &cpi->rc;
768
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
769
  const int cq_level = get_active_cq_level(rc, oxcf);
Deb Mukherjee's avatar
Deb Mukherjee committed
770
  int active_best_quality;
771
  int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
Deb Mukherjee's avatar
Deb Mukherjee committed
772
  int q;
773 774
  int *inter_minq;
  ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
775 776

  if (frame_is_intra_only(cm)) {
777 778

    // Handle the special case for key frames forced when we have reached
779 780
    // the maximum key frame interval. Here force the Q to a range
    // based on the ambient Q to reduce the risk of popping.
Dmitry Kovalev's avatar
Dmitry Kovalev committed
781 782
    if (rc->this_key_frame_forced) {
      int qindex = rc->last_boosted_qindex;
783
      double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
784
      int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
785 786
                                            last_boosted_q * 0.75,
                                            cm->bit_depth);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
787
      active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
788
    } else {
Alex Converse's avatar
Alex Converse committed
789
      // not first frame of one pass and kf_boost is set
790 791 792
      double q_adj_factor = 1.0;
      double q_val;

793
      active_best_quality =
794 795
          get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
                                cm->bit_depth);
796 797 798 799 800 801 802 803

      // Allow somewhat lower kf minq with small image formats.
      if ((cm->width * cm->height) <= (352 * 288)) {
        q_adj_factor -= 0.25;
      }

      // Convert the adjustment factor to a qindex delta
      // on active_best_quality.
804
      q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
805
      active_best_quality += vp9_compute_qdelta(rc, q_val,
806 807
                                                q_val * q_adj_factor,
                                                cm->bit_depth);
808
    }
Dmitry Kovalev's avatar
Dmitry Kovalev committed
809
  } else if (!rc->is_src_frame_alt_ref &&
810
             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
Deb Mukherjee's avatar
Deb Mukherjee committed
811
    // Use the lower of active_worst_quality and recent
812 813
    // average Q as basis for GF/ARF best Q limit unless last frame was
    // a key frame.
Dmitry Kovalev's avatar
Dmitry Kovalev committed
814 815 816
    if (rc->frames_since_key > 1 &&
        rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
      q = rc->avg_frame_qindex[INTER_FRAME];
Deb Mukherjee's avatar
Deb Mukherjee committed
817
    } else {
818
      q = rc->avg_frame_qindex[KEY_FRAME];
819 820
    }
    // For constrained quality dont allow Q less than the cq level
821
    if (oxcf->rc_mode == VPX_CQ) {
822 823
      if (q < cq_level)
        q = cq_level;
824

825
      active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
826

827
      // Constrained quality use slightly lower active best.
Deb Mukherjee's avatar
Deb Mukherjee committed
828
      active_best_quality = active_best_quality * 15 / 16;
829

830
    } else if (oxcf->rc_mode == VPX_Q) {
831
      if (!cpi->refresh_alt_ref_frame) {
832
        active_best_quality = cq_level;