2 * Copyright (c) 2014 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
14 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
16 #include "vp9/common/vp9_seg_common.h"
18 #include "vp9/encoder/vp9_ratectrl.h"
19 #include "vp9/encoder/vp9_segmentation.h"
21 struct CYCLIC_REFRESH {
22 // Percentage of blocks per frame that are targeted as candidates
23 // for cyclic refresh.
25 // Maximum q-delta as percentage of base q.
27 // Superblock starting index for cycling through the frame.
29 // Controls how long block will need to wait to be refreshed again, in
30 // excess of the cycle time, i.e., in the case of all zero motion, block
31 // will be refreshed every (100/percent_refresh + time_for_refresh) frames.
33 // // Target number of (8x8) blocks that are set for delta-q (segment 1).
34 int target_num_seg_blocks;
35 // Actual number of (8x8) blocks that were applied delta-q (segment 1).
36 int actual_num_seg_blocks;
37 // RD mult. parameters for segment 1.
39 // Cyclic refresh map.
41 // Thresholds applied to the projected rate/distortion of the coding block,
42 // when deciding whether block should be refreshed.
43 int64_t thresh_rate_sb;
44 int64_t thresh_dist_sb;
45 // Threshold applied to the motion vector (in units of 1/8 pel) of the
46 // coding block, when deciding whether block should be refreshed.
47 int16_t motion_thresh;
48 // Rate target ratio to set q delta.
49 double rate_ratio_qdelta;
52 CYCLIC_REFRESH *vp9_cyclic_refresh_alloc(int mi_rows, int mi_cols) {
53 CYCLIC_REFRESH *const cr = vpx_calloc(1, sizeof(*cr));
57 cr->map = vpx_calloc(mi_rows * mi_cols, sizeof(*cr->map));
58 if (cr->map == NULL) {
66 void vp9_cyclic_refresh_free(CYCLIC_REFRESH *cr) {
71 // Check if we should turn off cyclic refresh based on bitrate condition.
72 static int apply_cyclic_refresh_bitrate(const VP9_COMMON *cm,
73 const RATE_CONTROL *rc) {
74 // Turn off cyclic refresh if bits available per frame is not sufficiently
75 // larger than bit cost of segmentation. Segment map bit cost should scale
76 // with number of seg blocks, so compare available bits to number of blocks.
77 // Average bits available per frame = avg_frame_bandwidth
78 // Number of (8x8) blocks in frame = mi_rows * mi_cols;
79 const float factor = 0.5;
80 const int number_blocks = cm->mi_rows * cm->mi_cols;
81 // The condition below corresponds to turning off at target bitrates:
82 // ~24kbps for CIF, 72kbps for VGA (at 30fps).
83 // Also turn off at very small frame sizes, to avoid too large fraction of
84 // superblocks to be refreshed per frame. Threshold below is less than QCIF.
85 if (rc->avg_frame_bandwidth < factor * number_blocks ||
86 number_blocks / 64 < 5)
92 // Check if this coding block, of size bsize, should be considered for refresh
93 // (lower-qp coding). Decision can be based on various factors, such as
94 // size of the coding block (i.e., below min_block size rejected), coding
95 // mode, and rate/distortion.
96 static int candidate_refresh_aq(const CYCLIC_REFRESH *cr,
97 const MB_MODE_INFO *mbmi,
100 MV mv = mbmi->mv[0].as_mv;
101 // If projected rate is below the thresh_rate accept it for lower-qp coding.
102 // Otherwise, reject the block for lower-qp coding if projected distortion
103 // is above the threshold, and any of the following is true:
104 // 1) mode uses large mv
105 // 2) mode is an intra-mode
106 if (rate < cr->thresh_rate_sb)
108 else if (dist > cr->thresh_dist_sb &&
109 (mv.row > cr->motion_thresh || mv.row < -cr->motion_thresh ||
110 mv.col > cr->motion_thresh || mv.col < -cr->motion_thresh ||
111 !is_inter_block(mbmi)))
117 // Compute delta-q for the segment.
118 static int compute_deltaq(const VP9_COMP *cpi, int q) {
119 const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
120 const RATE_CONTROL *const rc = &cpi->rc;
121 int deltaq = vp9_compute_qdelta_by_rate(rc, cpi->common.frame_type,
122 q, cr->rate_ratio_qdelta,
123 cpi->common.bit_depth);
124 if ((-deltaq) > cr->max_qdelta_perc * q / 100) {
125 deltaq = -cr->max_qdelta_perc * q / 100;
130 // For the just encoded frame, estimate the bits, incorporating the delta-q
131 // from segment 1. This function is called in the postencode (called from
132 // rc_update_rate_correction_factors()).
133 int vp9_cyclic_refresh_estimate_bits_at_q(const VP9_COMP *cpi,
134 double correction_factor) {
135 const VP9_COMMON *const cm = &cpi->common;
136 const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
139 int num8x8bl = mbs << 2;
140 // Weight for segment 1: use actual number of blocks refreshed in
141 // previous/just encoded frame. Note number of blocks here is in 8x8 units.
142 double weight_segment = (double)cr->actual_num_seg_blocks / num8x8bl;
143 // Compute delta-q that was used in the just encoded frame.
144 int deltaq = compute_deltaq(cpi, cm->base_qindex);
145 // Take segment weighted average for estimated bits.
146 estimated_bits = (int)((1.0 - weight_segment) *
147 vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex, mbs,
148 correction_factor, cm->bit_depth) +
150 vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex + deltaq, mbs,
151 correction_factor, cm->bit_depth));
152 return estimated_bits;
155 // Prior to encoding the frame, estimate the bits per mb, for a given q = i and
156 // a corresponding delta-q (for segment 1). This function is called in the
157 // rc_regulate_q() to set the base qp index.
158 int vp9_cyclic_refresh_rc_bits_per_mb(const VP9_COMP *cpi, int i,
159 double correction_factor) {
160 const VP9_COMMON *const cm = &cpi->common;
161 CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
163 int num8x8bl = cm->MBs << 2;
164 // Weight for segment 1 prior to encoding: take the target number for the
165 // frame to be encoded. Number of blocks here is in 8x8 units.
166 // Note that this is called in rc_regulate_q, which is called before the
167 // cyclic_refresh_setup (which sets cr->target_num_seg_blocks). So a mismatch
168 // may occur between the cr->target_num_seg_blocks value here and the
169 // cr->target_num_seg_block set for encoding the frame. For the current use
170 // case of fixed cr->percent_refresh and cr->time_for_refresh = 0, mismatch
171 // does not occur/is very small.
172 double weight_segment = (double)cr->target_num_seg_blocks / num8x8bl;
173 // Compute delta-q corresponding to qindex i.
174 int deltaq = compute_deltaq(cpi, i);
175 // Take segment weighted average for bits per mb.
176 bits_per_mb = (int)((1.0 - weight_segment) *
177 vp9_rc_bits_per_mb(cm->frame_type, i, correction_factor, cm->bit_depth) +
179 vp9_rc_bits_per_mb(cm->frame_type, i + deltaq, correction_factor,
184 // Prior to coding a given prediction block, of size bsize at (mi_row, mi_col),
185 // check if we should reset the segment_id, and update the cyclic_refresh map
186 // and segmentation map.
187 void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi,
188 MB_MODE_INFO *const mbmi,
189 int mi_row, int mi_col,
193 const VP9_COMMON *const cm = &cpi->common;
194 CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
195 const int bw = num_8x8_blocks_wide_lookup[bsize];
196 const int bh = num_8x8_blocks_high_lookup[bsize];
197 const int xmis = MIN(cm->mi_cols - mi_col, bw);
198 const int ymis = MIN(cm->mi_rows - mi_row, bh);
199 const int block_index = mi_row * cm->mi_cols + mi_col;
200 const int refresh_this_block = candidate_refresh_aq(cr, mbmi, rate, dist);
201 // Default is to not update the refresh map.
202 int new_map_value = cr->map[block_index];
203 int x = 0; int y = 0;
205 // Check if we should reset the segment_id for this block.
206 if (mbmi->segment_id > 0 && !refresh_this_block)
207 mbmi->segment_id = 0;
209 // Update the cyclic refresh map, to be used for setting segmentation map
210 // for the next frame. If the block will be refreshed this frame, mark it
211 // as clean. The magnitude of the -ve influences how long before we consider
212 // it for refresh again.
213 if (mbmi->segment_id == 1) {
214 new_map_value = -cr->time_for_refresh;
215 } else if (refresh_this_block) {
216 // Else if it is accepted as candidate for refresh, and has not already
217 // been refreshed (marked as 1) then mark it as a candidate for cleanup
218 // for future time (marked as 0), otherwise don't update it.
219 if (cr->map[block_index] == 1)
222 // Leave it marked as block that is not candidate for refresh.
226 // Update entries in the cyclic refresh map with new_map_value, and
227 // copy mbmi->segment_id into global segmentation map.
228 for (y = 0; y < ymis; y++)
229 for (x = 0; x < xmis; x++) {
230 cr->map[block_index + y * cm->mi_cols + x] = new_map_value;
231 cpi->segmentation_map[block_index + y * cm->mi_cols + x] =
236 // Update the actual number of blocks that were applied the segment delta q.
237 void vp9_cyclic_refresh_update_actual_count(struct VP9_COMP *const cpi) {
238 VP9_COMMON *const cm = &cpi->common;
239 CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
240 unsigned char *const seg_map = cpi->segmentation_map;
242 cr->actual_num_seg_blocks = 0;
243 for (mi_row = 0; mi_row < cm->mi_rows; mi_row++)
244 for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
245 if (seg_map[mi_row * cm->mi_cols + mi_col] == 1)
246 cr->actual_num_seg_blocks++;
250 // Update the segmentation map, and related quantities: cyclic refresh map,
251 // refresh sb_index, and target number of blocks to be refreshed.
252 void vp9_cyclic_refresh_update_map(VP9_COMP *const cpi) {
253 VP9_COMMON *const cm = &cpi->common;
254 CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
255 unsigned char *const seg_map = cpi->segmentation_map;
256 int i, block_count, bl_index, sb_rows, sb_cols, sbs_in_frame;
257 int xmis, ymis, x, y;
258 vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
259 sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
260 sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
261 sbs_in_frame = sb_cols * sb_rows;
262 // Number of target blocks to get the q delta (segment 1).
263 block_count = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100;
264 // Set the segmentation map: cycle through the superblocks, starting at
265 // cr->mb_index, and stopping when either block_count blocks have been found
266 // to be refreshed, or we have passed through whole frame.
267 assert(cr->sb_index < sbs_in_frame);
269 cr->target_num_seg_blocks = 0;
272 // Get the mi_row/mi_col corresponding to superblock index i.
273 int sb_row_index = (i / sb_cols);
274 int sb_col_index = i - sb_row_index * sb_cols;
275 int mi_row = sb_row_index * MI_BLOCK_SIZE;
276 int mi_col = sb_col_index * MI_BLOCK_SIZE;
277 assert(mi_row >= 0 && mi_row < cm->mi_rows);
278 assert(mi_col >= 0 && mi_col < cm->mi_cols);
279 bl_index = mi_row * cm->mi_cols + mi_col;
280 // Loop through all 8x8 blocks in superblock and update map.
281 xmis = MIN(cm->mi_cols - mi_col,
282 num_8x8_blocks_wide_lookup[BLOCK_64X64]);
283 ymis = MIN(cm->mi_rows - mi_row,
284 num_8x8_blocks_high_lookup[BLOCK_64X64]);
285 for (y = 0; y < ymis; y++) {
286 for (x = 0; x < xmis; x++) {
287 const int bl_index2 = bl_index + y * cm->mi_cols + x;
288 // If the block is as a candidate for clean up then mark it
289 // for possible boost/refresh (segment 1). The segment id may get
290 // reset to 0 later if block gets coded anything other than ZEROMV.
291 if (cr->map[bl_index2] == 0) {
293 } else if (cr->map[bl_index2] < 0) {
294 cr->map[bl_index2]++;
298 // Enforce constant segment over superblock.
299 // If segment is at least half of superblock, set to 1.
300 if (sum_map >= xmis * ymis / 2) {
301 for (y = 0; y < ymis; y++)
302 for (x = 0; x < xmis; x++) {
303 seg_map[bl_index + y * cm->mi_cols + x] = 1;
305 cr->target_num_seg_blocks += xmis * ymis;
308 if (i == sbs_in_frame) {
311 } while (cr->target_num_seg_blocks < block_count && i != cr->sb_index);
315 // Set/update global/frame level cyclic refresh parameters.
316 void vp9_cyclic_refresh_update_parameters(VP9_COMP *const cpi) {
317 const RATE_CONTROL *const rc = &cpi->rc;
318 CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
319 cr->percent_refresh = 10;
320 // Use larger delta-qp (increase rate_ratio_qdelta) for first few (~4)
321 // periods of the refresh cycle, after a key frame. This corresponds to ~40
322 // frames with cr->percent_refresh = 10.
323 if (rc->frames_since_key < 40)
324 cr->rate_ratio_qdelta = 3.0;
326 cr->rate_ratio_qdelta = 2.0;
329 // Setup cyclic background refresh: set delta q and segmentation map.
330 void vp9_cyclic_refresh_setup(VP9_COMP *const cpi) {
331 VP9_COMMON *const cm = &cpi->common;
332 const RATE_CONTROL *const rc = &cpi->rc;
333 CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
334 struct segmentation *const seg = &cm->seg;
335 const int apply_cyclic_refresh = apply_cyclic_refresh_bitrate(cm, rc);
336 // Don't apply refresh on key frame or enhancement layer frames.
337 if (!apply_cyclic_refresh ||
338 (cm->frame_type == KEY_FRAME) ||
339 (cpi->svc.temporal_layer_id > 0) ||
340 (cpi->svc.spatial_layer_id > 0)) {
341 // Set segmentation map to 0 and disable.
342 unsigned char *const seg_map = cpi->segmentation_map;
343 vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
344 vp9_disable_segmentation(&cm->seg);
345 if (cm->frame_type == KEY_FRAME)
349 int qindex_delta = 0;
351 const double q = vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth);
352 vp9_clear_system_state();
353 cr->max_qdelta_perc = 50;
354 cr->time_for_refresh = 0;
355 // Set rate threshold to some fraction (set to 1 for now) of the target
356 // rate (target is given by sb64_target_rate and scaled by 256).
357 cr->thresh_rate_sb = (rc->sb64_target_rate << 8);
358 // Distortion threshold, quadratic in Q, scale factor to be adjusted.
359 cr->thresh_dist_sb = (int)(q * q) << 5;
360 cr->motion_thresh = 32;
361 // Set up segmentation.
362 // Clear down the segment map.
363 vp9_enable_segmentation(&cm->seg);
364 vp9_clearall_segfeatures(seg);
365 // Select delta coding method.
366 seg->abs_delta = SEGMENT_DELTADATA;
368 // Note: setting temporal_update has no effect, as the seg-map coding method
369 // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(),
370 // based on the coding cost of each method. For error_resilient mode on the
371 // last_frame_seg_map is set to 0, so if temporal coding is used, it is
372 // relative to 0 previous map.
373 // seg->temporal_update = 0;
375 // Segment 0 "Q" feature is disabled so it defaults to the baseline Q.
376 vp9_disable_segfeature(seg, 0, SEG_LVL_ALT_Q);
377 // Use segment 1 for in-frame Q adjustment.
378 vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
380 // Set the q delta for segment 1.
381 qindex_delta = compute_deltaq(cpi, cm->base_qindex);
383 // Compute rd-mult for segment 1.
384 qindex2 = clamp(cm->base_qindex + cm->y_dc_delta_q + qindex_delta, 0, MAXQ);
385 cr->rdmult = vp9_compute_rd_mult(cpi, qindex2);
387 vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qindex_delta);
389 // Update the segmentation and refresh map.
390 vp9_cyclic_refresh_update_map(cpi);
394 int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) {