vp9_aq_cyclicrefresh.c 25.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/*
 *  Copyright (c) 2014 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <limits.h>
#include <math.h>

14
#include "vpx_dsp/vpx_dsp_common.h"
15 16
#include "vpx_ports/system_state.h"

17
#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
18 19 20 21 22 23

#include "vp9/common/vp9_seg_common.h"

#include "vp9/encoder/vp9_ratectrl.h"
#include "vp9/encoder/vp9_segmentation.h"

24
CYCLIC_REFRESH *vp9_cyclic_refresh_alloc(int mi_rows, int mi_cols) {
25
  size_t last_coded_q_map_size;
26
  size_t consec_zero_mv_size;
27 28 29 30 31 32 33 34 35
  CYCLIC_REFRESH *const cr = vpx_calloc(1, sizeof(*cr));
  if (cr == NULL)
    return NULL;

  cr->map = vpx_calloc(mi_rows * mi_cols, sizeof(*cr->map));
  if (cr->map == NULL) {
    vpx_free(cr);
    return NULL;
  }
36 37 38 39 40 41 42 43
  last_coded_q_map_size = mi_rows * mi_cols * sizeof(*cr->last_coded_q_map);
  cr->last_coded_q_map = vpx_malloc(last_coded_q_map_size);
  if (cr->last_coded_q_map == NULL) {
    vpx_free(cr);
    return NULL;
  }
  assert(MAXQ <= 255);
  memset(cr->last_coded_q_map, MAXQ, last_coded_q_map_size);
44

45 46 47 48 49 50 51
  consec_zero_mv_size = mi_rows * mi_cols * sizeof(*cr->consec_zero_mv);
  cr->consec_zero_mv = vpx_malloc(consec_zero_mv_size);
  if (cr->consec_zero_mv == NULL) {
    vpx_free(cr);
    return NULL;
  }
  memset(cr->consec_zero_mv, 0, consec_zero_mv_size);
52 53 54 55 56
  return cr;
}

void vp9_cyclic_refresh_free(CYCLIC_REFRESH *cr) {
  vpx_free(cr->map);
57
  vpx_free(cr->last_coded_q_map);
58
  vpx_free(cr->consec_zero_mv);
59 60
  vpx_free(cr);
}
61 62

// Check if we should turn off cyclic refresh based on bitrate condition.
63 64
// TODO(marpan): May be better in some cases to just reduce the amount/delta-qp
// instead of completely shutting off.
65 66
static int apply_cyclic_refresh_bitrate(const VP9_COMMON *cm,
                                        const RATE_CONTROL *rc) {
67 68 69
  // Turn off cyclic refresh if bits available per frame is not sufficiently
  // larger than bit cost of segmentation. Segment map bit cost should scale
  // with number of seg blocks, so compare available bits to number of blocks.
70
  // Average bits available per frame = avg_frame_bandwidth
71
  // Number of (8x8) blocks in frame = mi_rows * mi_cols;
72
  const float factor = 0.15f;
73
  const int number_blocks = cm->mi_rows  * cm->mi_cols;
74
  // The condition below corresponds to turning off at target bitrates:
75
  // (at 30fps), ~8kbps for CIF, 20kbps for VGA, 60kps for HD/720p.
76 77
  // Also turn off at very small frame sizes, to avoid too large fraction of
  // superblocks to be refreshed per frame. Threshold below is less than QCIF.
78
  if (rc->avg_frame_bandwidth < factor * number_blocks ||
79 80 81 82
      number_blocks / 64 < 5)
    return 0;
  else
    return 1;
83 84 85 86 87 88
}

// Check if this coding block, of size bsize, should be considered for refresh
// (lower-qp coding). Decision can be based on various factors, such as
// size of the coding block (i.e., below min_block size rejected), coding
// mode, and rate/distortion.
89
static int candidate_refresh_aq(const CYCLIC_REFRESH *cr,
90
                                const MODE_INFO *mi,
91
                                int64_t rate,
92 93
                                int64_t dist,
                                int bsize) {
94
  MV mv = mi->mv[0].as_mv;
95
  // Reject the block for lower-qp coding if projected distortion
96 97 98
  // is above the threshold, and any of the following is true:
  // 1) mode uses large mv
  // 2) mode is an intra-mode
99 100 101 102
  // Otherwise accept for refresh.
  if (dist > cr->thresh_dist_sb &&
      (mv.row > cr->motion_thresh || mv.row < -cr->motion_thresh ||
       mv.col > cr->motion_thresh || mv.col < -cr->motion_thresh ||
103
       !is_inter_block(mi)))
104
    return CR_SEGMENT_ID_BASE;
Marco's avatar
Marco committed
105
  else  if (bsize >= BLOCK_16X16 &&
106
            rate < cr->thresh_rate_sb &&
107 108
            is_inter_block(mi) &&
            mi->mv[0].as_int == 0 &&
109
            cr->rate_boost_fac > 10)
110 111
    // More aggressive delta-q for bigger blocks with zero motion.
    return CR_SEGMENT_ID_BOOST2;
112
  else
113
    return CR_SEGMENT_ID_BOOST1;
114 115
}

116
// Compute delta-q for the segment.
117
static int compute_deltaq(const VP9_COMP *cpi, int q, double rate_factor) {
118 119 120
  const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  const RATE_CONTROL *const rc = &cpi->rc;
  int deltaq = vp9_compute_qdelta_by_rate(rc, cpi->common.frame_type,
121
                                          q, rate_factor,
122 123 124 125 126 127 128 129
                                          cpi->common.bit_depth);
  if ((-deltaq) > cr->max_qdelta_perc * q / 100) {
    deltaq = -cr->max_qdelta_perc * q / 100;
  }
  return deltaq;
}

// For the just encoded frame, estimate the bits, incorporating the delta-q
130 131 132
// from non-base segment. For now ignore effect of multiple segments
// (with different delta-q). Note this function is called in the postencode
// (called from rc_update_rate_correction_factors()).
133 134 135 136 137 138 139
int vp9_cyclic_refresh_estimate_bits_at_q(const VP9_COMP *cpi,
                                          double correction_factor) {
  const VP9_COMMON *const cm = &cpi->common;
  const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  int estimated_bits;
  int mbs = cm->MBs;
  int num8x8bl = mbs << 2;
140
  // Weight for non-base segments: use actual number of blocks refreshed in
141
  // previous/just encoded frame. Note number of blocks here is in 8x8 units.
Marco's avatar
Marco committed
142 143
  double weight_segment1 = (double)cr->actual_num_seg1_blocks / num8x8bl;
  double weight_segment2 = (double)cr->actual_num_seg2_blocks / num8x8bl;
144
  // Take segment weighted average for estimated bits.
Marco's avatar
Marco committed
145
  estimated_bits = (int)((1.0 - weight_segment1 - weight_segment2) *
146 147
      vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex, mbs,
                             correction_factor, cm->bit_depth) +
Marco's avatar
Marco committed
148 149
                             weight_segment1 *
      vp9_estimate_bits_at_q(cm->frame_type,
150
                             cm->base_qindex + cr->qindex_delta[1], mbs,
Marco's avatar
Marco committed
151 152 153
                             correction_factor, cm->bit_depth) +
                             weight_segment2 *
      vp9_estimate_bits_at_q(cm->frame_type,
154
                             cm->base_qindex + cr->qindex_delta[2], mbs,
155 156 157 158 159 160 161
                             correction_factor, cm->bit_depth));
  return estimated_bits;
}

// Prior to encoding the frame, estimate the bits per mb, for a given q = i and
// a corresponding delta-q (for segment 1). This function is called in the
// rc_regulate_q() to set the base qp index.
162 163
// Note: the segment map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or
// to 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock, prior to encoding.
164 165 166 167 168 169
int vp9_cyclic_refresh_rc_bits_per_mb(const VP9_COMP *cpi, int i,
                                      double correction_factor) {
  const VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  int bits_per_mb;
  int num8x8bl = cm->MBs << 2;
Marco's avatar
Marco committed
170 171
  // Weight for segment prior to encoding: take the average of the target
  // number for the frame to be encoded and the actual from the previous frame.
172 173
  int target_refresh = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100;
  double weight_segment = (double)((target_refresh +
Marco's avatar
Marco committed
174 175
      cr->actual_num_seg1_blocks + cr->actual_num_seg2_blocks) >> 1) /
      num8x8bl;
176
  // Compute delta-q corresponding to qindex i.
177
  int deltaq = compute_deltaq(cpi, i, cr->rate_ratio_qdelta);
178 179 180 181 182 183 184 185 186
  // Take segment weighted average for bits per mb.
  bits_per_mb = (int)((1.0 - weight_segment) *
      vp9_rc_bits_per_mb(cm->frame_type, i, correction_factor, cm->bit_depth) +
      weight_segment *
      vp9_rc_bits_per_mb(cm->frame_type, i + deltaq, correction_factor,
                         cm->bit_depth));
  return bits_per_mb;
}

187 188 189
// Prior to coding a given prediction block, of size bsize at (mi_row, mi_col),
// check if we should reset the segment_id, and update the cyclic_refresh map
// and segmentation map.
190
void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi,
191
                                       MODE_INFO *const mi,
192
                                       int mi_row, int mi_col,
193 194
                                       BLOCK_SIZE bsize,
                                       int64_t rate,
Marco's avatar
Marco committed
195
                                       int64_t dist,
196 197
                                       int skip,
                                       struct macroblock_plane *const p) {
198
  const VP9_COMMON *const cm = &cpi->common;
199
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
200 201
  const int bw = num_8x8_blocks_wide_lookup[bsize];
  const int bh = num_8x8_blocks_high_lookup[bsize];
202 203
  const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
  const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
204
  const int block_index = mi_row * cm->mi_cols + mi_col;
205
  int refresh_this_block = candidate_refresh_aq(cr, mi, rate, dist, bsize);
206 207 208
  // Default is to not update the refresh map.
  int new_map_value = cr->map[block_index];
  int x = 0; int y = 0;
209

210 211 212 213
  int is_skin = 0;
  if (refresh_this_block == 0 &&
      bsize <= BLOCK_16X16 &&
      cpi->oxcf.content != VP9E_CONTENT_SCREEN) {
Marco's avatar
Marco committed
214 215 216 217 218 219
    is_skin = vp9_compute_skin_block(p[0].src.buf,
                                     p[1].src.buf,
                                     p[2].src.buf,
                                     p[0].src.stride,
                                     p[1].src.stride,
                                     bsize);
220 221 222 223
    if (is_skin)
      refresh_this_block = 1;
  }

224 225
  // If this block is labeled for refresh, check if we should reset the
  // segment_id.
226 227
  if (cyclic_refresh_segment_id_boosted(mi->segment_id)) {
    mi->segment_id = refresh_this_block;
228
    // Reset segment_id if it will be skipped.
Marco's avatar
Marco committed
229
    if (skip)
230
      mi->segment_id = CR_SEGMENT_ID_BASE;
Marco's avatar
Marco committed
231
  }
232 233 234 235 236

  // Update the cyclic refresh map, to be used for setting segmentation map
  // for the next frame. If the block  will be refreshed this frame, mark it
  // as clean. The magnitude of the -ve influences how long before we consider
  // it for refresh again.
237
  if (cyclic_refresh_segment_id_boosted(mi->segment_id)) {
238 239 240 241 242 243 244 245 246 247 248
    new_map_value = -cr->time_for_refresh;
  } else if (refresh_this_block) {
    // Else if it is accepted as candidate for refresh, and has not already
    // been refreshed (marked as 1) then mark it as a candidate for cleanup
    // for future time (marked as 0), otherwise don't update it.
    if (cr->map[block_index] == 1)
      new_map_value = 0;
  } else {
    // Leave it marked as block that is not candidate for refresh.
    new_map_value = 1;
  }
249

250 251 252 253
  // Update entries in the cyclic refresh map with new_map_value, and
  // copy mbmi->segment_id into global segmentation map.
  for (y = 0; y < ymis; y++)
    for (x = 0; x < xmis; x++) {
254 255
      int map_offset = block_index + y * cm->mi_cols + x;
      cr->map[map_offset] = new_map_value;
256
      cpi->segmentation_map[map_offset] = mi->segment_id;
257 258 259 260
    }
}

void vp9_cyclic_refresh_update_sb_postencode(VP9_COMP *const cpi,
261
                                             const MODE_INFO *const mi,
262 263 264 265
                                             int mi_row, int mi_col,
                                             BLOCK_SIZE bsize) {
  const VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
266
  MV mv = mi->mv[0].as_mv;
267 268 269 270 271 272 273 274 275
  const int bw = num_8x8_blocks_wide_lookup[bsize];
  const int bh = num_8x8_blocks_high_lookup[bsize];
  const int xmis = VPXMIN(cm->mi_cols - mi_col, bw);
  const int ymis = VPXMIN(cm->mi_rows - mi_row, bh);
  const int block_index = mi_row * cm->mi_cols + mi_col;
  int x, y;
  for (y = 0; y < ymis; y++)
    for (x = 0; x < xmis; x++) {
      int map_offset = block_index + y * cm->mi_cols + x;
276 277 278 279
      // Inter skip blocks were clearly not coded at the current qindex, so
      // don't update the map for them. For cases where motion is non-zero or
      // the reference frame isn't the previous frame, the previous value in
      // the map for this spatial location is not entirely correct.
280 281
      if ((!is_inter_block(mi) || !mi->skip) &&
          mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
282
        cr->last_coded_q_map[map_offset] = clamp(
283 284 285
            cm->base_qindex + cr->qindex_delta[mi->segment_id], 0, MAXQ);
      } else if (is_inter_block(mi) && mi->skip &&
                 mi->segment_id <= CR_SEGMENT_ID_BOOST2) {
286
        cr->last_coded_q_map[map_offset] = VPXMIN(
287
            clamp(cm->base_qindex + cr->qindex_delta[mi->segment_id],
288 289
                  0, MAXQ),
            cr->last_coded_q_map[map_offset]);
290
      // Update the consecutive zero/low_mv count.
291
      if (is_inter_block(mi) && (abs(mv.row) < 8 && abs(mv.col) < 8)) {
292 293 294 295
        if (cr->consec_zero_mv[map_offset] < 255)
          cr->consec_zero_mv[map_offset]++;
      } else {
        cr->consec_zero_mv[map_offset] = 0;
296
      }
297
    }
298
  }
299 300 301
}

// Update the actual number of blocks that were applied the segment delta q.
302
void vp9_cyclic_refresh_postencode(VP9_COMP *const cpi) {
303 304 305 306
  VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  unsigned char *const seg_map = cpi->segmentation_map;
  int mi_row, mi_col;
Marco's avatar
Marco committed
307 308
  cr->actual_num_seg1_blocks = 0;
  cr->actual_num_seg2_blocks = 0;
309
  for (mi_row = 0; mi_row < cm->mi_rows; mi_row++)
310
    for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
Marco's avatar
Marco committed
311 312 313 314 315 316
      if (cyclic_refresh_segment_id(
          seg_map[mi_row * cm->mi_cols + mi_col]) == CR_SEGMENT_ID_BOOST1)
        cr->actual_num_seg1_blocks++;
      else if (cyclic_refresh_segment_id(
          seg_map[mi_row * cm->mi_cols + mi_col]) == CR_SEGMENT_ID_BOOST2)
        cr->actual_num_seg2_blocks++;
317
    }
318 319
}

320 321 322 323 324 325 326 327
// Set golden frame update interval, for non-svc 1 pass CBR mode.
void vp9_cyclic_refresh_set_golden_update(VP9_COMP *const cpi) {
  RATE_CONTROL *const rc = &cpi->rc;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  // Set minimum gf_interval for GF update to a multiple (== 2) of refresh
  // period. Depending on past encoding stats, GF flag may be reset and update
  // may not occur until next baseline_gf_interval.
  if (cr->percent_refresh > 0)
328
    rc->baseline_gf_interval = 4 * (100 / cr->percent_refresh);
329
  else
330
    rc->baseline_gf_interval = 40;
331 332
}

333 334 335 336
// Update some encoding stats (from the just encoded frame). If this frame's
// background has high motion, refresh the golden frame. Otherwise, if the
// golden reference is to be updated check if we should NOT update the golden
// ref.
337 338 339 340 341 342
void vp9_cyclic_refresh_check_golden_update(VP9_COMP *const cpi) {
  VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  int mi_row, mi_col;
  double fraction_low = 0.0;
  int low_content_frame = 0;
343 344 345 346 347 348 349 350 351

  MODE_INFO **mi = cm->mi_grid_visible;
  RATE_CONTROL *const rc = &cpi->rc;
  const int rows = cm->mi_rows, cols = cm->mi_cols;
  int cnt1 = 0, cnt2 = 0;
  int force_gf_refresh = 0;

  for (mi_row = 0; mi_row < rows; mi_row++) {
    for (mi_col = 0; mi_col < cols; mi_col++) {
352 353 354 355
      int16_t abs_mvr = mi[0]->mv[0].as_mv.row >= 0 ?
          mi[0]->mv[0].as_mv.row : -1 * mi[0]->mv[0].as_mv.row;
      int16_t abs_mvc = mi[0]->mv[0].as_mv.col >= 0 ?
          mi[0]->mv[0].as_mv.col : -1 * mi[0]->mv[0].as_mv.col;
356 357 358 359 360 361 362 363 364 365 366

      // Calculate the motion of the background.
      if (abs_mvr <= 16 && abs_mvc <= 16) {
        cnt1++;
        if (abs_mvr == 0 && abs_mvc == 0)
          cnt2++;
      }
      mi++;

      // Accumulate low_content_frame.
      if (cr->map[mi_row * cols + mi_col] < 1)
367 368
        low_content_frame++;
    }
369 370 371 372 373 374
    mi += 8;
  }

  // For video conference clips, if the background has high motion in current
  // frame because of the camera movement, set this frame as the golden frame.
  // Use 70% and 5% as the thresholds for golden frame refreshing.
375 376 377 378
  // Also, force this frame as a golden update frame if this frame will change
  // the resolution (resize_pending != 0).
  if (cpi->resize_pending != 0 ||
     (cnt1 * 10 > (70 * rows * cols) && cnt2 * 20 < cnt1)) {
379 380 381 382 383 384 385 386 387
    vp9_cyclic_refresh_set_golden_update(cpi);
    rc->frames_till_gf_update_due = rc->baseline_gf_interval;

    if (rc->frames_till_gf_update_due > rc->frames_to_key)
      rc->frames_till_gf_update_due = rc->frames_to_key;
    cpi->refresh_golden_frame = 1;
    force_gf_refresh = 1;
  }

388
  fraction_low =
389
      (double)low_content_frame / (rows * cols);
390 391
  // Update average.
  cr->low_content_avg = (fraction_low + 3 * cr->low_content_avg) / 4;
392
  if (!force_gf_refresh && cpi->refresh_golden_frame == 1) {
393 394 395 396 397 398 399 400 401 402
    // Don't update golden reference if the amount of low_content for the
    // current encoded frame is small, or if the recursive average of the
    // low_content over the update interval window falls below threshold.
    if (fraction_low < 0.8 || cr->low_content_avg < 0.7)
      cpi->refresh_golden_frame = 0;
    // Reset for next internal.
    cr->low_content_avg = fraction_low;
  }
}

403 404
// Update the segmentation map, and related quantities: cyclic refresh map,
// refresh sb_index, and target number of blocks to be refreshed.
405 406 407 408
// The map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or to
// 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock.
// Blocks labeled as BOOST1 may later get set to BOOST2 (during the
// encoding of the superblock).
409
static void cyclic_refresh_update_map(VP9_COMP *const cpi) {
410 411 412 413 414
  VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  unsigned char *const seg_map = cpi->segmentation_map;
  int i, block_count, bl_index, sb_rows, sb_cols, sbs_in_frame;
  int xmis, ymis, x, y;
415
  int consec_zero_mv_thresh = 0;
416 417 418
  int qindex_thresh = 0;
  int count_sel = 0;
  int count_tot = 0;
James Zern's avatar
James Zern committed
419
  memset(seg_map, CR_SEGMENT_ID_BASE, cm->mi_rows * cm->mi_cols);
420 421 422 423 424 425 426 427 428 429 430
  sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
  sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
  sbs_in_frame = sb_cols * sb_rows;
  // Number of target blocks to get the q delta (segment 1).
  block_count = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100;
  // Set the segmentation map: cycle through the superblocks, starting at
  // cr->mb_index, and stopping when either block_count blocks have been found
  // to be refreshed, or we have passed through whole frame.
  assert(cr->sb_index < sbs_in_frame);
  i = cr->sb_index;
  cr->target_num_seg_blocks = 0;
431
  if (cpi->oxcf.content != VP9E_CONTENT_SCREEN) {
432
    consec_zero_mv_thresh = 100;
433 434 435
   if (cpi->noise_estimate.enabled && cpi->noise_estimate.level >= kMedium)
     consec_zero_mv_thresh = 80;
  }
436 437 438 439
  qindex_thresh =
      cpi->oxcf.content == VP9E_CONTENT_SCREEN
      ? vp9_get_qindex(&cm->seg, CR_SEGMENT_ID_BOOST2, cm->base_qindex)
      : vp9_get_qindex(&cm->seg, CR_SEGMENT_ID_BOOST1, cm->base_qindex);
440 441 442 443 444 445 446 447 448 449 450
  do {
    int sum_map = 0;
    // Get the mi_row/mi_col corresponding to superblock index i.
    int sb_row_index = (i / sb_cols);
    int sb_col_index = i - sb_row_index * sb_cols;
    int mi_row = sb_row_index * MI_BLOCK_SIZE;
    int mi_col = sb_col_index * MI_BLOCK_SIZE;
    assert(mi_row >= 0 && mi_row < cm->mi_rows);
    assert(mi_col >= 0 && mi_col < cm->mi_cols);
    bl_index = mi_row * cm->mi_cols + mi_col;
    // Loop through all 8x8 blocks in superblock and update map.
451 452 453 454
    xmis =
        VPXMIN(cm->mi_cols - mi_col, num_8x8_blocks_wide_lookup[BLOCK_64X64]);
    ymis =
        VPXMIN(cm->mi_rows - mi_row, num_8x8_blocks_high_lookup[BLOCK_64X64]);
455 456 457 458 459 460 461
    for (y = 0; y < ymis; y++) {
      for (x = 0; x < xmis; x++) {
        const int bl_index2 = bl_index + y * cm->mi_cols + x;
        // If the block is as a candidate for clean up then mark it
        // for possible boost/refresh (segment 1). The segment id may get
        // reset to 0 later if block gets coded anything other than ZEROMV.
        if (cr->map[bl_index2] == 0) {
462
          count_tot++;
463
          if (cr->last_coded_q_map[bl_index2] > qindex_thresh ||
464
              cr->consec_zero_mv[bl_index2] < consec_zero_mv_thresh) {
465
            sum_map++;
466 467
            count_sel++;
          }
468 469 470 471 472 473 474 475 476 477
        } else if (cr->map[bl_index2] < 0) {
          cr->map[bl_index2]++;
        }
      }
    }
    // Enforce constant segment over superblock.
    // If segment is at least half of superblock, set to 1.
    if (sum_map >= xmis * ymis / 2) {
      for (y = 0; y < ymis; y++)
        for (x = 0; x < xmis; x++) {
478
          seg_map[bl_index + y * cm->mi_cols + x] = CR_SEGMENT_ID_BOOST1;
479 480 481 482 483 484 485 486 487
        }
      cr->target_num_seg_blocks += xmis * ymis;
    }
    i++;
    if (i == sbs_in_frame) {
      i = 0;
    }
  } while (cr->target_num_seg_blocks < block_count && i != cr->sb_index);
  cr->sb_index = i;
488 489 490
  cr->reduce_refresh = 0;
  if (count_sel < (3 * count_tot) >> 2)
    cr->reduce_refresh = 1;
491 492
}

493
// Set cyclic refresh parameters.
494 495
void vp9_cyclic_refresh_update_parameters(VP9_COMP *const cpi) {
  const RATE_CONTROL *const rc = &cpi->rc;
496
  const VP9_COMMON *const cm = &cpi->common;
497 498
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  cr->percent_refresh = 10;
499 500
  if (cr->reduce_refresh)
    cr->percent_refresh = 5;
501 502
  cr->max_qdelta_perc = 50;
  cr->time_for_refresh = 0;
503
  // Use larger delta-qp (increase rate_ratio_qdelta) for first few (~4)
504
  // periods of the refresh cycle, after a key frame.
Marco's avatar
Marco committed
505 506 507
  // Account for larger interval on base layer for temporal layers.
  if (cr->percent_refresh > 0 &&
      rc->frames_since_key <  (4 * cpi->svc.number_temporal_layers) *
Marco's avatar
Marco committed
508
      (100 / cr->percent_refresh)) {
509
    cr->rate_ratio_qdelta = 3.0;
Marco's avatar
Marco committed
510
  } else {
511
    cr->rate_ratio_qdelta = 2.0;
512
  if (cpi->noise_estimate.enabled && cpi->noise_estimate.level >= kMedium)
Marco's avatar
Marco committed
513 514 515
    // Reduce the delta-qp if the estimated source noise is above threshold.
    cr->rate_ratio_qdelta = 1.5;
  }
516 517 518 519 520
  // Adjust some parameters for low resolutions at low bitrates.
  if (cm->width <= 352 &&
      cm->height <= 288 &&
      rc->avg_frame_bandwidth < 3400) {
    cr->motion_thresh = 4;
521
    cr->rate_boost_fac = 10;
522 523
  } else {
    cr->motion_thresh = 32;
524
    cr->rate_boost_fac = 15;
525
  }
526 527 528 529
  if (cpi->svc.spatial_layer_id > 0) {
    cr->motion_thresh = 4;
    cr->rate_boost_fac = 12;
  }
530 531
}

532
// Setup cyclic background refresh: set delta q and segmentation map.
533
void vp9_cyclic_refresh_setup(VP9_COMP *const cpi) {
534
  VP9_COMMON *const cm = &cpi->common;
535
  const RATE_CONTROL *const rc = &cpi->rc;
536
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
537
  struct segmentation *const seg = &cm->seg;
538
  const int apply_cyclic_refresh  = apply_cyclic_refresh_bitrate(cm, rc);
539 540
  if (cm->current_video_frame == 0)
    cr->low_content_avg = 0.0;
541
  // Don't apply refresh on key frame or temporal enhancement layer frames.
542
  if (!apply_cyclic_refresh ||
543
      (cm->frame_type == KEY_FRAME) ||
544
      (cpi->svc.temporal_layer_id > 0)) {
545
    // Set segmentation map to 0 and disable.
546
    unsigned char *const seg_map = cpi->segmentation_map;
James Zern's avatar
James Zern committed
547
    memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
548
    vp9_disable_segmentation(&cm->seg);
549 550 551
    if (cm->frame_type == KEY_FRAME) {
      memset(cr->last_coded_q_map, MAXQ,
             cm->mi_rows * cm->mi_cols * sizeof(*cr->last_coded_q_map));
552 553
      memset(cr->consec_zero_mv, 0,
             cm->mi_rows * cm->mi_cols * sizeof(*cr->consec_zero_mv));
554
      cr->sb_index = 0;
555
    }
556 557 558
    return;
  } else {
    int qindex_delta = 0;
559
    int qindex2;
560
    const double q = vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth);
561
    vpx_clear_system_state();
562
    // Set rate threshold to some multiple (set to 2 for now) of the target
563
    // rate (target is given by sb64_target_rate and scaled by 256).
Marco's avatar
Marco committed
564
    cr->thresh_rate_sb = ((int64_t)(rc->sb64_target_rate) << 8) << 2;
565
    // Distortion threshold, quadratic in Q, scale factor to be adjusted.
566 567 568
    // q will not exceed 457, so (q * q) is within 32bit; see:
    // vp9_convert_qindex_to_q(), vp9_ac_quant(), ac_qlookup*[].
    cr->thresh_dist_sb = ((int64_t)(q * q)) << 2;
569

570 571 572 573 574 575 576 577 578 579 580 581 582 583
    // Set up segmentation.
    // Clear down the segment map.
    vp9_enable_segmentation(&cm->seg);
    vp9_clearall_segfeatures(seg);
    // Select delta coding method.
    seg->abs_delta = SEGMENT_DELTADATA;

    // Note: setting temporal_update has no effect, as the seg-map coding method
    // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(),
    // based on the coding cost of each method. For error_resilient mode on the
    // last_frame_seg_map is set to 0, so if temporal coding is used, it is
    // relative to 0 previous map.
    // seg->temporal_update = 0;

584 585 586 587 588 589
    // Segment BASE "Q" feature is disabled so it defaults to the baseline Q.
    vp9_disable_segfeature(seg, CR_SEGMENT_ID_BASE, SEG_LVL_ALT_Q);
    // Use segment BOOST1 for in-frame Q adjustment.
    vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q);
    // Use segment BOOST2 for more aggressive in-frame Q adjustment.
    vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q);
590

591 592
    // Set the q delta for segment BOOST1.
    qindex_delta = compute_deltaq(cpi, cm->base_qindex, cr->rate_ratio_qdelta);
593
    cr->qindex_delta[1] = qindex_delta;
594

595
    // Compute rd-mult for segment BOOST1.
596
    qindex2 = clamp(cm->base_qindex + cm->y_dc_delta_q + qindex_delta, 0, MAXQ);
Marco's avatar
Marco committed
597

598 599
    cr->rdmult = vp9_compute_rd_mult(cpi, qindex2);

600 601 602
    vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q, qindex_delta);

    // Set a more aggressive (higher) q delta for segment BOOST2.
603
    qindex_delta = compute_deltaq(
604 605 606
        cpi, cm->base_qindex,
        VPXMIN(CR_MAX_RATE_TARGET_RATIO,
               0.1 * cr->rate_boost_fac * cr->rate_ratio_qdelta));
607
    cr->qindex_delta[2] = qindex_delta;
608
    vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q, qindex_delta);
609

610 611 612 613
    // Reset if resoluton change has occurred.
    if (cpi->resize_pending != 0)
      vp9_cyclic_refresh_reset_resize(cpi);

614
    // Update the segmentation and refresh map.
615
    cyclic_refresh_update_map(cpi);
616 617
  }
}
618 619 620 621

int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) {
  return cr->rdmult;
}
622 623 624 625 626

void vp9_cyclic_refresh_reset_resize(VP9_COMP *const cpi) {
  const VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  memset(cr->map, 0, cm->mi_rows * cm->mi_cols);
627 628
  memset(cr->last_coded_q_map, MAXQ, cm->mi_rows * cm->mi_cols);
  memset(cr->consec_zero_mv, 0, cm->mi_rows * cm->mi_cols);
629
  cr->sb_index = 0;
630
  cpi->refresh_golden_frame = 1;
631
}