vp9_ratectrl.c 77.1 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

18
#include "vpx_dsp/vpx_dsp_common.h"
19
#include "vpx_mem/vpx_mem.h"
20
#include "vpx_ports/mem.h"
21
#include "vpx_ports/system_state.h"
John Koleszar's avatar
John Koleszar committed
22

23
#include "vp9/common/vp9_alloccommon.h"
24
#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
25 26 27
#include "vp9/common/vp9_common.h"
#include "vp9/common/vp9_entropymode.h"
#include "vp9/common/vp9_quant_common.h"
28
#include "vp9/common/vp9_seg_common.h"
29 30 31

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

33 34 35 36 37
// 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

38 39 40
#define DEFAULT_KF_BOOST 2000
#define DEFAULT_GF_BOOST 2000

Deb Mukherjee's avatar
Deb Mukherjee committed
41
#define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
42

Dmitry Kovalev's avatar
Dmitry Kovalev committed
43 44
#define MIN_BPB_FACTOR 0.005
#define MAX_BPB_FACTOR 50
John Koleszar's avatar
John Koleszar committed
45

46 47
#define FRAME_OVERHEAD_BITS 200

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
#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

75
// Tables relating active max Q to active min Q
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
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
98 99 100 101
static int gf_high = 2000;
static int gf_low = 400;
static int kf_high = 5000;
static int kf_low = 400;
102 103 104 105 106

// 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))
107 108
static int get_minq_index(double maxq, double x3, double x2, double x1,
                          vpx_bit_depth_t bit_depth) {
109
  int i;
110 111
  const double minqtarget = VPXMIN(((x3 * maxq + x2) * maxq + x1) * maxq,
                                   maxq);
112 113 114 115 116 117

  // 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;

118 119
  for (i = 0; i < QINDEX_RANGE; i++) {
    if (minqtarget <= vp9_convert_qindex_to_q(i, bit_depth))
120
      return i;
121
  }
122 123 124 125

  return QINDEX_RANGE - 1;
}

126 127 128
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) {
129 130
  int i;
  for (i = 0; i < QINDEX_RANGE; i++) {
131
    const double maxq = vp9_convert_qindex_to_q(i, bit_depth);
132 133
    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);
134
    arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
135
    arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
136 137
    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);
138 139 140
  }
}

141
void vp9_rc_init_minq_luts(void) {
142 143 144 145 146 147 148 149 150 151 152 153 154
  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
155 156 157
// 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
158
double vp9_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
John Koleszar's avatar
John Koleszar committed
159
  // Convert the index to a real Q value (scaled down to match old Q values)
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
#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
175 176
}

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

Paul Wilkins's avatar
Paul Wilkins committed
183 184 185
  assert(correction_factor <= MAX_BPB_FACTOR &&
         correction_factor >= MIN_BPB_FACTOR);

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

191 192 193
int vp9_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
                           double correction_factor,
                           vpx_bit_depth_t bit_depth) {
194 195
  const int bpm = (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor,
                                           bit_depth));
196 197
  return VPXMAX(FRAME_OVERHEAD_BITS,
                (int)((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS);
198
}
199

200 201
int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
  const RATE_CONTROL *rc = &cpi->rc;
202
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
203 204
  const int min_frame_target = VPXMAX(rc->min_frame_bandwidth,
                                      rc->avg_frame_bandwidth >> 5);
205 206
  if (target < min_frame_target)
    target = min_frame_target;
207
  if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
208 209 210 211
    // 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.
212
    target = min_frame_target;
213 214 215 216
  }
  // Clip the frame target to the maximum allowed value.
  if (target > rc->max_frame_bandwidth)
    target = rc->max_frame_bandwidth;
217 218 219
  if (oxcf->rc_max_inter_bitrate_pct) {
    const int max_rate = rc->avg_frame_bandwidth *
                         oxcf->rc_max_inter_bitrate_pct / 100;
220
    target = VPXMIN(target, max_rate);
221
  }
222 223
  return target;
}
224

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

238 239
// Update the buffer level for higher temporal layers, given the encoded current
// temporal layer.
240
static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
241
  int i = 0;
242
  int current_temporal_layer = svc->temporal_layer_id;
243 244 245 246 247
  for (i = current_temporal_layer + 1;
      i < svc->number_temporal_layers; ++i) {
    const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
                                       svc->number_temporal_layers);
    LAYER_CONTEXT *lc = &svc->layer_context[layer];
248 249 250 251 252 253
    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.
254 255
    lrc->bits_off_target =
        VPXMIN(lrc->bits_off_target, lrc->maximum_buffer_size);
256 257 258 259
    lrc->buffer_level = lrc->bits_off_target;
  }
}

260
// Update the buffer level: leaky bucket model.
261
static void update_buffer_level(VP9_COMP *cpi, int encoded_frame_size) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
262
  const VP9_COMMON *const cm = &cpi->common;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
263
  RATE_CONTROL *const rc = &cpi->rc;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
264

265 266
  // Non-viewable frames are a special case and are treated as pure overhead.
  if (!cm->show_frame) {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
267
    rc->bits_off_target -= encoded_frame_size;
268
  } else {
269
    rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
270
  }
Dmitry Kovalev's avatar
Dmitry Kovalev committed
271

272
  // Clip the buffer level to the maximum specified buffer size.
273
  rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
274 275 276 277 278 279 280

  // For screen-content mode, and if frame-dropper is off, don't let buffer
  // level go below threshold, given here as -rc->maximum_ buffer_size.
  if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
      cpi->oxcf.drop_frames_water_mark == 0)
    rc->bits_off_target = VPXMAX(rc->bits_off_target, -rc->maximum_buffer_size);

281 282
  rc->buffer_level = rc->bits_off_target;

283
  if (is_one_pass_cbr_svc(cpi)) {
284
    update_layer_buffer_level(&cpi->svc, encoded_frame_size);
285
  }
286 287
}

288 289 290 291 292
int vp9_rc_get_default_min_gf_interval(
    int width, int height, double framerate) {
  // Assume we do not need any constraint lower than 4K 20 fps
  static const double factor_safe = 3840 * 2160 * 20.0;
  const double factor = width * height * framerate;
Alex Converse's avatar
Alex Converse committed
293 294
  const int default_interval =
      clamp((int)(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
295 296

  if (factor <= factor_safe)
Alex Converse's avatar
Alex Converse committed
297
    return default_interval;
298
  else
299 300
    return VPXMAX(default_interval,
                  (int)(MIN_GF_INTERVAL * factor / factor_safe + 0.5));
301 302 303 304 305 306 307
  // Note this logic makes:
  // 4K24: 5
  // 4K30: 6
  // 4K60: 12
}

int vp9_rc_get_default_max_gf_interval(double framerate, int min_gf_interval) {
308
  int interval = VPXMIN(MAX_GF_INTERVAL, (int)(framerate * 0.75));
309
  interval += (interval & 0x01);  // Round to even value
310
  return VPXMAX(interval, min_gf_interval);
311 312
}

313
void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
314 315
  int i;

316
  if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
317 318
    rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
    rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
319
  } else {
320
    rc->avg_frame_qindex[KEY_FRAME] = (oxcf->worst_allowed_q +
321
                                       oxcf->best_allowed_q) / 2;
322
    rc->avg_frame_qindex[INTER_FRAME] = (oxcf->worst_allowed_q +
323
                                         oxcf->best_allowed_q) / 2;
324 325
  }

326
  rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
Paul Wilkins's avatar
Paul Wilkins committed
327
  rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
328

329 330
  rc->buffer_level =    rc->starting_buffer_level;
  rc->bits_off_target = rc->starting_buffer_level;
331

332 333 334 335
  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;
336 337

  rc->total_actual_bits = 0;
338
  rc->total_target_bits = 0;
339 340 341 342 343 344 345 346 347 348 349 350 351 352
  rc->total_target_vs_actual = 0;

  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;
353
  rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
354

355 356 357
  for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
    rc->rate_correction_factors[i] = 1.0;
  }
358 359 360 361 362 363 364 365 366 367

  rc->min_gf_interval = oxcf->min_gf_interval;
  rc->max_gf_interval = oxcf->max_gf_interval;
  if (rc->min_gf_interval == 0)
    rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
        oxcf->width, oxcf->height, oxcf->init_framerate);
  if (rc->max_gf_interval == 0)
    rc->max_gf_interval = vp9_rc_get_default_max_gf_interval(
        oxcf->init_framerate, rc->min_gf_interval);
  rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
368 369
}

370
int vp9_rc_drop_frame(VP9_COMP *cpi) {
371
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
372 373
  RATE_CONTROL *const rc = &cpi->rc;

Dmitry Kovalev's avatar
Dmitry Kovalev committed
374
  if (!oxcf->drop_frames_water_mark) {
375 376
    return 0;
  } else {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
377
    if (rc->buffer_level < 0) {
378 379 380 381 382
      // 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
383
      int drop_mark = (int)(oxcf->drop_frames_water_mark *
384
          rc->optimal_buffer_level / 100);
Dmitry Kovalev's avatar
Dmitry Kovalev committed
385 386 387 388 389 390
      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;
391
      }
Dmitry Kovalev's avatar
Dmitry Kovalev committed
392 393 394
      if (rc->decimation_factor > 0) {
        if (rc->decimation_count > 0) {
          --rc->decimation_count;
395 396
          return 1;
        } else {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
397
          rc->decimation_count = rc->decimation_factor;
398 399 400
          return 0;
        }
      } else {
Dmitry Kovalev's avatar
Dmitry Kovalev committed
401
        rc->decimation_count = 0;
402 403 404 405 406 407
        return 0;
      }
    }
  }
}

408
static double get_rate_correction_factor(const VP9_COMP *cpi) {
409
  const RATE_CONTROL *const rc = &cpi->rc;
410
  double rcf;
411

412
  if (cpi->common.frame_type == KEY_FRAME) {
413
    rcf = rc->rate_correction_factors[KF_STD];
414
  } else if (cpi->oxcf.pass == 2) {
415 416
    RATE_FACTOR_LEVEL rf_lvl =
      cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
417
    rcf = rc->rate_correction_factors[rf_lvl];
418
  } else {
419
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
420
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
421
        (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
422
      rcf = rc->rate_correction_factors[GF_ARF_STD];
423
    else
424
      rcf = rc->rate_correction_factors[INTER_NORMAL];
425
  }
426
  rcf *= rcf_mult[rc->frame_size_selector];
427
  return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
428 429 430
}

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

433 434 435
  // Normalize RCF to account for the size-dependent scaling factor.
  factor /= rcf_mult[cpi->rc.frame_size_selector];

436 437
  factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);

438
  if (cpi->common.frame_type == KEY_FRAME) {
439
    rc->rate_correction_factors[KF_STD] = factor;
440
  } else if (cpi->oxcf.pass == 2) {
441 442 443
    RATE_FACTOR_LEVEL rf_lvl =
      cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
    rc->rate_correction_factors[rf_lvl] = factor;
444
  } else {
445
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
446
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
447
        (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
448
      rc->rate_correction_factors[GF_ARF_STD] = factor;
449
    else
450
      rc->rate_correction_factors[INTER_NORMAL] = factor;
451 452 453
  }
}

454
void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi) {
455
  const VP9_COMMON *const cm = &cpi->common;
456
  int correction_factor = 100;
457
  double rate_correction_factor = get_rate_correction_factor(cpi);
John Koleszar's avatar
John Koleszar committed
458
  double adjustment_limit;
John Koleszar's avatar
John Koleszar committed
459

460
  int projected_size_based_on_q = 0;
John Koleszar's avatar
John Koleszar committed
461

Paul Wilkins's avatar
Paul Wilkins committed
462 463 464 465
  // 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
466
  // Clear down mmx registers to allow floating point in what follows
467
  vpx_clear_system_state();
John Koleszar's avatar
John Koleszar committed
468

469 470
  // 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
471
  // Stay in double to avoid int overflow when values are large
472 473 474 475 476 477 478 479 480 481
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled) {
    projected_size_based_on_q =
        vp9_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
  } else {
    projected_size_based_on_q = vp9_estimate_bits_at_q(cpi->common.frame_type,
                                                       cm->base_qindex,
                                                       cm->MBs,
                                                       rate_correction_factor,
                                                       cm->bit_depth);
  }
John Koleszar's avatar
John Koleszar committed
482
  // Work out a size correction factor.
Paul Wilkins's avatar
Paul Wilkins committed
483
  if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
484 485
    correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
                        projected_size_based_on_q);
John Koleszar's avatar
John Koleszar committed
486

487 488
  // More heavily damped adjustment used if we have been oscillating either side
  // of target.
489
  adjustment_limit = 0.25 +
490
      0.5 * VPXMIN(1, fabs(log10(0.01 * correction_factor)));
John Koleszar's avatar
John Koleszar committed
491

492 493 494 495 496 497 498 499 500 501
  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
502 503
  if (correction_factor > 102) {
    // We are not already at the worst allowable quality
504 505 506
    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
507 508 509
    // Keep rate_correction_factor within limits
    if (rate_correction_factor > MAX_BPB_FACTOR)
      rate_correction_factor = MAX_BPB_FACTOR;
510
  } else if (correction_factor < 99) {
John Koleszar's avatar
John Koleszar committed
511
    // We are not already at the best allowable quality
512 513 514
    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
515 516 517 518 519 520

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

521
  set_rate_correction_factor(cpi, rate_correction_factor);
John Koleszar's avatar
John Koleszar committed
522 523 524
}


Deb Mukherjee's avatar
Deb Mukherjee committed
525 526
int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
                      int active_best_quality, int active_worst_quality) {
527
  const VP9_COMMON *const cm = &cpi->common;
Deb Mukherjee's avatar
Deb Mukherjee committed
528
  int q = active_worst_quality;
John Koleszar's avatar
John Koleszar committed
529
  int last_error = INT_MAX;
530
  int i, target_bits_per_mb, bits_per_mb_at_this_q;
531
  const double correction_factor = get_rate_correction_factor(cpi);
John Koleszar's avatar
John Koleszar committed
532

533 534
  // Calculate required scaling factor based on target frame size and size of
  // frame produced using previous Q.
535 536
  target_bits_per_mb =
      ((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs;
John Koleszar's avatar
John Koleszar committed
537

Deb Mukherjee's avatar
Deb Mukherjee committed
538
  i = active_best_quality;
John Koleszar's avatar
John Koleszar committed
539

John Koleszar's avatar
John Koleszar committed
540
  do {
541 542
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
        cm->seg.enabled &&
543
        cpi->svc.temporal_layer_id == 0) {
544 545 546 547 548 549 550
      bits_per_mb_at_this_q =
          (int)vp9_cyclic_refresh_rc_bits_per_mb(cpi, i, correction_factor);
    } else {
      bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cm->frame_type, i,
                                                      correction_factor,
                                                      cm->bit_depth);
    }
John Koleszar's avatar
John Koleszar committed
551

John Koleszar's avatar
John Koleszar committed
552 553
    if (bits_per_mb_at_this_q <= target_bits_per_mb) {
      if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
554
        q = i;
John Koleszar's avatar
John Koleszar committed
555
      else
556
        q = i - 1;
John Koleszar's avatar
John Koleszar committed
557

John Koleszar's avatar
John Koleszar committed
558
      break;
559
    } else {
John Koleszar's avatar
John Koleszar committed
560
      last_error = bits_per_mb_at_this_q - target_bits_per_mb;
561
    }
Deb Mukherjee's avatar
Deb Mukherjee committed
562
  } while (++i <= active_worst_quality);
563

564 565 566 567 568
  // 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) {
569 570
    q = clamp(q, VPXMIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
              VPXMAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
571
  }
572 573 574
  return q;
}

575 576
static int get_active_quality(int q, int gfu_boost, int low, int high,
                              int *low_motion_minq, int *high_motion_minq) {
577
  if (gfu_boost > high) {
578
    return low_motion_minq[q];
579
  } else if (gfu_boost < low) {
580
    return high_motion_minq[q];
581 582 583 584 585
  } 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;
586
    return low_motion_minq[q] + adjustment;
587 588 589
  }
}

590 591 592 593 594 595
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);
596 597 598 599
  return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
                            kf_low_motion_minq, kf_high_motion_minq);
}

600 601 602 603 604 605
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);
606 607 608 609
  return get_active_quality(q, rc->gfu_boost, gf_low, gf_high,
                            arfgf_low_motion_minq, arfgf_high_motion_minq);
}

610
static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
611 612
  const RATE_CONTROL *const rc = &cpi->rc;
  const unsigned int curr_frame = cpi->common.current_video_frame;
613
  int active_worst_quality;
614

615
  if (cpi->common.frame_type == KEY_FRAME) {
616 617
    active_worst_quality = curr_frame == 0 ? rc->worst_quality
                                           : rc->last_q[KEY_FRAME] * 2;
618
  } else {
619 620 621 622
    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];
623
    } else {
624 625
      active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 2
                                             : rc->last_q[INTER_FRAME] * 2;
626 627
    }
  }
628
  return VPXMIN(active_worst_quality, rc->worst_quality);
629 630 631 632 633 634 635 636 637
}

// 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).
638
  const VP9_COMMON *const cm = &cpi->common;
639 640
  const RATE_CONTROL *rc = &cpi->rc;
  // Buffer level below which we push active_worst to worst_quality.
641
  int64_t critical_level = rc->optimal_buffer_level >> 3;
642
  int64_t buff_lvl_step = 0;
643 644
  int adjustment = 0;
  int active_worst_quality;
645
  int ambient_qp;
646
  unsigned int num_frames_weight_key = 5 * cpi->svc.number_temporal_layers;
647
  if (cm->frame_type == KEY_FRAME)
648 649 650 651 652 653
    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.
654
  ambient_qp = (cm->current_video_frame < num_frames_weight_key) ?
655 656 657 658
                   VPXMIN(rc->avg_frame_qindex[INTER_FRAME],
                          rc->avg_frame_qindex[KEY_FRAME]) :
                   rc->avg_frame_qindex[INTER_FRAME];
  active_worst_quality = VPXMIN(rc->worst_quality, ambient_qp * 5 / 4);
659
  if (rc->buffer_level > rc->optimal_buffer_level) {
660
    // Adjust down.
661
    // Maximum limit for down adjustment, ~30%.
662 663
    int max_adjustment_down = active_worst_quality / 3;
    if (max_adjustment_down) {
664 665
      buff_lvl_step = ((rc->maximum_buffer_size -
                        rc->optimal_buffer_level) / max_adjustment_down);
666
      if (buff_lvl_step)
667
        adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
668 669 670 671 672 673
                            buff_lvl_step);
      active_worst_quality -= adjustment;
    }
  } else if (rc->buffer_level > critical_level) {
    // Adjust up from ambient Q.
    if (critical_level) {
674
      buff_lvl_step = (rc->optimal_buffer_level - critical_level);
675
      if (buff_lvl_step) {
676 677 678
        adjustment = (int)((rc->worst_quality - ambient_qp) *
                           (rc->optimal_buffer_level - rc->buffer_level) /
                           buff_lvl_step);
679
      }
680
      active_worst_quality = ambient_qp + adjustment;
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
    }
  } 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;
697 698
  int *rtc_minq;
  ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
699 700 701

  if (frame_is_intra_only(cm)) {
    active_best_quality = rc->best_quality;
702
    // Handle the special case for key frames forced when we have reached
703 704 705 706
    // 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;
707
      double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
708
      int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
709 710
                                            (last_boosted_q * 0.75),
                                            cm->bit_depth);
711
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
712 713 714 715 716
    } 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;

717
      active_best_quality =
718 719
          get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
                                cm->bit_depth);
720 721 722 723 724 725 726 727

      // 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.
728
      q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
729
      active_best_quality += vp9_compute_qdelta(rc, q_val,
730 731
                                                q_val * q_adj_factor,
                                                cm->bit_depth);
732 733
    }
  } else if (!rc->is_src_frame_alt_ref &&
734
             !cpi->use_svc &&
735 736 737 738 739 740 741 742 743 744
             (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;
    }
745
    active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
746 747 748 749
  } 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)
750
        active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
751
      else
752
        active_best_quality = rtc_minq[active_worst_quality];
753 754
    } else {
      if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
755
        active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
756
      else
757
        active_best_quality = rtc_minq[active_worst_quality];
758 759 760 761 762 763 764 765 766 767 768 769 770 771
    }
  }

  // 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
772 773 774 775
  if (cm->frame_type == KEY_FRAME &&
      !rc->this_key_frame_forced  &&
      !(cm->current_video_frame == 0)) {
    int qdelta = 0;
776
    vpx_clear_system_state();
Paul Wilkins's avatar
Paul Wilkins committed
777
    qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
778 779
                                        active_worst_quality, 2.0,
                                        cm->bit_depth);
Paul Wilkins's avatar
Paul Wilkins committed
780 781
    *top_index = active_worst_quality + qdelta;
    *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
782 783
  }
#endif
Paul Wilkins's avatar
Paul Wilkins committed
784

785 786 787 788 789 790 791 792
  // 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
793
      if (rc->this_frame_target >= rc->max_frame_bandwidth)
794 795 796 797 798 799 800 801 802 803 804 805 806
        *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;
}

807 808
static int get_active_cq_level(const RATE_CONTROL *rc,
                               const VP9EncoderConfig *const oxcf) {
809
  static const double cq_adjust_threshold = 0.1;
810
  int active_cq_level = oxcf->cq_level;
811
  if (oxcf->rc_mode == VPX_CQ &&
812
      rc->total_target_bits > 0) {
813
    const double x = (double)rc->total_actual_bits / rc->total_target_bits;
814
    if (x < cq_adjust_threshold) {
815
      active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
816 817 818 819 820
    }
  }
  return active_cq_level;
}

821 822 823
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
824
  const VP9_COMMON *const cm = &cpi->common;
Dmitry Kovalev's avatar
Dmitry Kovalev committed
825
  const RATE_CONTROL *const rc = &cpi->rc;
826
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
827
  const int cq_level = get_active_cq_level(rc, oxcf);
Deb Mukherjee's avatar
Deb Mukherjee committed
828
  int active_best_quality;
829
  int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
Deb Mukherjee's avatar
Deb Mukherjee committed
830
  int q;
831 832
  int *inter_minq;
  ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
833 834

  if (frame_is_intra_only(cm)) {
835
    // Handle the special case for key frames forced when we have reached
836 837
    // 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
838 839
    if (rc->this_key_frame_forced) {
      int qindex = rc