1/*
2 *  Copyright (c) 2014 The WebM project authors. All Rights Reserved.
3 *
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.
9 */
10
11#include <limits.h>
12#include <math.h>
13
14#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
15
16#include "vp9/common/vp9_seg_common.h"
17
18#include "vp9/encoder/vp9_ratectrl.h"
19#include "vp9/encoder/vp9_segmentation.h"
20
21struct CYCLIC_REFRESH {
22  // Percentage of super-blocks per frame that are targeted as candidates
23  // for cyclic refresh.
24  int max_sbs_perframe;
25  // Maximum q-delta as percentage of base q.
26  int max_qdelta_perc;
27  // Block size below which we don't apply cyclic refresh.
28  BLOCK_SIZE min_block_size;
29  // Superblock starting index for cycling through the frame.
30  int sb_index;
31  // Controls how long a block will need to wait to be refreshed again.
32  int time_for_refresh;
33  // Actual number of (8x8) blocks that were applied delta-q (segment 1).
34  int num_seg_blocks;
35  // Actual encoding bits for segment 1.
36  int actual_seg_bits;
37  // RD mult. parameters for segment 1.
38  int rdmult;
39  // Cyclic refresh map.
40  signed char *map;
41  // Projected rate and distortion for the current superblock.
42  int64_t projected_rate_sb;
43  int64_t projected_dist_sb;
44  // Thresholds applied to projected rate/distortion of the superblock.
45  int64_t thresh_rate_sb;
46  int64_t thresh_dist_sb;
47};
48
49CYCLIC_REFRESH *vp9_cyclic_refresh_alloc(int mi_rows, int mi_cols) {
50  CYCLIC_REFRESH *const cr = vpx_calloc(1, sizeof(*cr));
51  if (cr == NULL)
52    return NULL;
53
54  cr->map = vpx_calloc(mi_rows * mi_cols, sizeof(*cr->map));
55  if (cr->map == NULL) {
56    vpx_free(cr);
57    return NULL;
58  }
59
60  return cr;
61}
62
63void vp9_cyclic_refresh_free(CYCLIC_REFRESH *cr) {
64  vpx_free(cr->map);
65  vpx_free(cr);
66}
67
68// Check if we should turn off cyclic refresh based on bitrate condition.
69static int apply_cyclic_refresh_bitrate(const VP9_COMMON *cm,
70                                        const RATE_CONTROL *rc) {
71  // Turn off cyclic refresh if bits available per frame is not sufficiently
72  // larger than bit cost of segmentation. Segment map bit cost should scale
73  // with number of seg blocks, so compare available bits to number of blocks.
74  // Average bits available per frame = avg_frame_bandwidth
75  // Number of (8x8) blocks in frame = mi_rows * mi_cols;
76  const float factor  = 0.5;
77  const int number_blocks = cm->mi_rows  * cm->mi_cols;
78  // The condition below corresponds to turning off at target bitrates:
79  // ~24kbps for CIF, 72kbps for VGA (at 30fps).
80  // Also turn off at very small frame sizes, to avoid too large fraction of
81  // superblocks to be refreshed per frame. Threshold below is less than QCIF.
82  if (rc->avg_frame_bandwidth < factor * number_blocks ||
83      number_blocks / 64 < 5)
84    return 0;
85  else
86    return 1;
87}
88
89// Check if this coding block, of size bsize, should be considered for refresh
90// (lower-qp coding). Decision can be based on various factors, such as
91// size of the coding block (i.e., below min_block size rejected), coding
92// mode, and rate/distortion.
93static int candidate_refresh_aq(const CYCLIC_REFRESH *cr,
94                                const MB_MODE_INFO *mbmi,
95                                BLOCK_SIZE bsize, int use_rd) {
96  if (use_rd) {
97    // If projected rate is below the thresh_rate (well below target,
98    // so undershoot expected), accept it for lower-qp coding.
99    if (cr->projected_rate_sb < cr->thresh_rate_sb)
100      return 1;
101    // Otherwise, reject the block for lower-qp coding if any of the following:
102    // 1) prediction block size is below min_block_size
103    // 2) mode is non-zero mv and projected distortion is above thresh_dist
104    // 3) mode is an intra-mode (we may want to allow some of this under
105    // another thresh_dist)
106    else if (bsize < cr->min_block_size ||
107             (mbmi->mv[0].as_int != 0 &&
108              cr->projected_dist_sb > cr->thresh_dist_sb) ||
109             !is_inter_block(mbmi))
110      return 0;
111    else
112      return 1;
113  } else {
114    // Rate/distortion not used for update.
115    if (bsize < cr->min_block_size ||
116        mbmi->mv[0].as_int != 0 ||
117        !is_inter_block(mbmi))
118      return 0;
119    else
120      return 1;
121  }
122}
123
124// Prior to coding a given prediction block, of size bsize at (mi_row, mi_col),
125// check if we should reset the segment_id, and update the cyclic_refresh map
126// and segmentation map.
127void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi,
128                                       MB_MODE_INFO *const mbmi,
129                                       int mi_row, int mi_col,
130                                       BLOCK_SIZE bsize, int use_rd) {
131  const VP9_COMMON *const cm = &cpi->common;
132  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
133  const int bw = num_8x8_blocks_wide_lookup[bsize];
134  const int bh = num_8x8_blocks_high_lookup[bsize];
135  const int xmis = MIN(cm->mi_cols - mi_col, bw);
136  const int ymis = MIN(cm->mi_rows - mi_row, bh);
137  const int block_index = mi_row * cm->mi_cols + mi_col;
138  const int refresh_this_block = cpi->mb.in_static_area ||
139                                 candidate_refresh_aq(cr, mbmi, bsize, use_rd);
140  // Default is to not update the refresh map.
141  int new_map_value = cr->map[block_index];
142  int x = 0; int y = 0;
143
144  // Check if we should reset the segment_id for this block.
145  if (mbmi->segment_id > 0 && !refresh_this_block)
146    mbmi->segment_id = 0;
147
148  // Update the cyclic refresh map, to be used for setting segmentation map
149  // for the next frame. If the block  will be refreshed this frame, mark it
150  // as clean. The magnitude of the -ve influences how long before we consider
151  // it for refresh again.
152  if (mbmi->segment_id == 1) {
153    new_map_value = -cr->time_for_refresh;
154  } else if (refresh_this_block) {
155    // Else if it is accepted as candidate for refresh, and has not already
156    // been refreshed (marked as 1) then mark it as a candidate for cleanup
157    // for future time (marked as 0), otherwise don't update it.
158    if (cr->map[block_index] == 1)
159      new_map_value = 0;
160  } else {
161    // Leave it marked as block that is not candidate for refresh.
162    new_map_value = 1;
163  }
164  // Update entries in the cyclic refresh map with new_map_value, and
165  // copy mbmi->segment_id into global segmentation map.
166  for (y = 0; y < ymis; y++)
167    for (x = 0; x < xmis; x++) {
168      cr->map[block_index + y * cm->mi_cols + x] = new_map_value;
169      cpi->segmentation_map[block_index + y * cm->mi_cols + x] =
170          mbmi->segment_id;
171    }
172  // Keep track of actual number (in units of 8x8) of blocks in segment 1 used
173  // for encoding this frame.
174  if (mbmi->segment_id)
175    cr->num_seg_blocks += xmis * ymis;
176}
177
178// Setup cyclic background refresh: set delta q and segmentation map.
179void vp9_cyclic_refresh_setup(VP9_COMP *const cpi) {
180  VP9_COMMON *const cm = &cpi->common;
181  const RATE_CONTROL *const rc = &cpi->rc;
182  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
183  struct segmentation *const seg = &cm->seg;
184  unsigned char *const seg_map = cpi->segmentation_map;
185  const int apply_cyclic_refresh  = apply_cyclic_refresh_bitrate(cm, rc);
186  // Don't apply refresh on key frame or enhancement layer frames.
187  if (!apply_cyclic_refresh ||
188      (cm->frame_type == KEY_FRAME) ||
189      (cpi->svc.temporal_layer_id > 0)) {
190    // Set segmentation map to 0 and disable.
191    vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
192    vp9_disable_segmentation(&cm->seg);
193    if (cm->frame_type == KEY_FRAME)
194      cr->sb_index = 0;
195    return;
196  } else {
197    int qindex_delta = 0;
198    int i, block_count, bl_index, sb_rows, sb_cols, sbs_in_frame;
199    int xmis, ymis, x, y, qindex2;
200
201    // Rate target ratio to set q delta.
202    const float rate_ratio_qdelta = 2.0;
203    const double q = vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth);
204    vp9_clear_system_state();
205    // Some of these parameters may be set via codec-control function later.
206    cr->max_sbs_perframe = 10;
207    cr->max_qdelta_perc = 50;
208    cr->min_block_size = BLOCK_8X8;
209    cr->time_for_refresh = 1;
210    // Set rate threshold to some fraction of target (and scaled by 256).
211    cr->thresh_rate_sb = (rc->sb64_target_rate * 256) >> 2;
212    // Distortion threshold, quadratic in Q, scale factor to be adjusted.
213    cr->thresh_dist_sb = 8 * (int)(q * q);
214    if (cpi->sf.use_nonrd_pick_mode) {
215      // May want to be more conservative with thresholds in non-rd mode for now
216      // as rate/distortion are derived from model based on prediction residual.
217      cr->thresh_rate_sb = (rc->sb64_target_rate * 256) >> 3;
218      cr->thresh_dist_sb = 4 * (int)(q * q);
219    }
220
221    cr->num_seg_blocks = 0;
222    // Set up segmentation.
223    // Clear down the segment map.
224    vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
225    vp9_enable_segmentation(&cm->seg);
226    vp9_clearall_segfeatures(seg);
227    // Select delta coding method.
228    seg->abs_delta = SEGMENT_DELTADATA;
229
230    // Note: setting temporal_update has no effect, as the seg-map coding method
231    // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(),
232    // based on the coding cost of each method. For error_resilient mode on the
233    // last_frame_seg_map is set to 0, so if temporal coding is used, it is
234    // relative to 0 previous map.
235    // seg->temporal_update = 0;
236
237    // Segment 0 "Q" feature is disabled so it defaults to the baseline Q.
238    vp9_disable_segfeature(seg, 0, SEG_LVL_ALT_Q);
239    // Use segment 1 for in-frame Q adjustment.
240    vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
241
242    // Set the q delta for segment 1.
243    qindex_delta = vp9_compute_qdelta_by_rate(rc, cm->frame_type,
244                                              cm->base_qindex,
245                                              rate_ratio_qdelta,
246                                              cm->bit_depth);
247    // TODO(marpan): Incorporate the actual-vs-target rate over/undershoot from
248    // previous encoded frame.
249    if (-qindex_delta > cr->max_qdelta_perc * cm->base_qindex / 100)
250      qindex_delta = -cr->max_qdelta_perc * cm->base_qindex / 100;
251
252    // Compute rd-mult for segment 1.
253    qindex2 = clamp(cm->base_qindex + cm->y_dc_delta_q + qindex_delta, 0, MAXQ);
254    cr->rdmult = vp9_compute_rd_mult(cpi, qindex2);
255
256    vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qindex_delta);
257
258    sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
259    sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
260    sbs_in_frame = sb_cols * sb_rows;
261    // Number of target superblocks to get the q delta (segment 1).
262    block_count = cr->max_sbs_perframe * sbs_in_frame / 100;
263    // Set the segmentation map: cycle through the superblocks, starting at
264    // cr->mb_index, and stopping when either block_count blocks have been found
265    // to be refreshed, or we have passed through whole frame.
266    assert(cr->sb_index < sbs_in_frame);
267    i = cr->sb_index;
268    do {
269      int sum_map = 0;
270      // Get the mi_row/mi_col corresponding to superblock index i.
271      int sb_row_index = (i / sb_cols);
272      int sb_col_index = i - sb_row_index * sb_cols;
273      int mi_row = sb_row_index * MI_BLOCK_SIZE;
274      int mi_col = sb_col_index * MI_BLOCK_SIZE;
275      assert(mi_row >= 0 && mi_row < cm->mi_rows);
276      assert(mi_col >= 0 && mi_col < cm->mi_cols);
277      bl_index = mi_row * cm->mi_cols + mi_col;
278      // Loop through all 8x8 blocks in superblock and update map.
279      xmis = MIN(cm->mi_cols - mi_col,
280                 num_8x8_blocks_wide_lookup[BLOCK_64X64]);
281      ymis = MIN(cm->mi_rows - mi_row,
282                 num_8x8_blocks_high_lookup[BLOCK_64X64]);
283      for (y = 0; y < ymis; y++) {
284        for (x = 0; x < xmis; x++) {
285          const int bl_index2 = bl_index + y * cm->mi_cols + x;
286          // If the block is as a candidate for clean up then mark it
287          // for possible boost/refresh (segment 1). The segment id may get
288          // reset to 0 later if block gets coded anything other than ZEROMV.
289          if (cr->map[bl_index2] == 0) {
290            seg_map[bl_index2] = 1;
291            sum_map++;
292          } else if (cr->map[bl_index2] < 0) {
293            cr->map[bl_index2]++;
294          }
295        }
296      }
297      // Enforce constant segment over superblock.
298      // If segment is partial over superblock, reset to either all 1 or 0.
299      if (sum_map > 0 && sum_map < xmis * ymis) {
300        const int new_value = (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] = new_value;
304      }
305      i++;
306      if (i == sbs_in_frame) {
307        i = 0;
308      }
309      if (sum_map >= xmis * ymis /2)
310        block_count--;
311    } while (block_count && i != cr->sb_index);
312    cr->sb_index = i;
313  }
314}
315
316void vp9_cyclic_refresh_set_rate_and_dist_sb(CYCLIC_REFRESH *cr,
317                                             int64_t rate_sb, int64_t dist_sb) {
318  cr->projected_rate_sb = rate_sb;
319  cr->projected_dist_sb = dist_sb;
320}
321
322int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) {
323  return cr->rdmult;
324}
325