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_rdopt.h"
20 #include "vp9/encoder/vp9_segmentation.h"
21 
22 struct CYCLIC_REFRESH {
23   // Percentage of super-blocks per frame that are targeted as candidates
24   // for cyclic refresh.
25   int max_sbs_perframe;
26   // Maximum q-delta as percentage of base q.
27   int max_qdelta_perc;
28   // Block size below which we don't apply cyclic refresh.
29   BLOCK_SIZE min_block_size;
30   // Superblock starting index for cycling through the frame.
31   int sb_index;
32   // Controls how long a block will need to wait to be refreshed again.
33   int time_for_refresh;
34   // Actual number of (8x8) blocks that were applied delta-q (segment 1).
35   int num_seg_blocks;
36   // Actual encoding bits for segment 1.
37   int actual_seg_bits;
38   // RD mult. parameters for segment 1.
39   int rdmult;
40   // Cyclic refresh map.
41   signed char *map;
42   // Projected rate and distortion for the current superblock.
43   int64_t projected_rate_sb;
44   int64_t projected_dist_sb;
45   // Thresholds applied to projected rate/distortion of the superblock.
46   int64_t thresh_rate_sb;
47   int64_t thresh_dist_sb;
48 };
49 
vp9_cyclic_refresh_alloc(int mi_rows,int mi_cols)50 CYCLIC_REFRESH *vp9_cyclic_refresh_alloc(int mi_rows, int mi_cols) {
51   CYCLIC_REFRESH *const cr = vpx_calloc(1, sizeof(*cr));
52   if (cr == NULL)
53     return NULL;
54 
55   cr->map = vpx_calloc(mi_rows * mi_cols, sizeof(*cr->map));
56   if (cr->map == NULL) {
57     vpx_free(cr);
58     return NULL;
59   }
60 
61   return cr;
62 }
63 
vp9_cyclic_refresh_free(CYCLIC_REFRESH * cr)64 void vp9_cyclic_refresh_free(CYCLIC_REFRESH *cr) {
65   vpx_free(cr->map);
66   vpx_free(cr);
67 }
68 
69 // Check if we should turn off cyclic refresh based on bitrate condition.
apply_cyclic_refresh_bitrate(const VP9_COMMON * cm,const RATE_CONTROL * rc)70 static int apply_cyclic_refresh_bitrate(const VP9_COMMON *cm,
71                                         const RATE_CONTROL *rc) {
72   // Turn off cyclic refresh if bits available per frame is not sufficiently
73   // larger than bit cost of segmentation. Segment map bit cost should scale
74   // with number of seg blocks, so compare available bits to number of blocks.
75   // Average bits available per frame = av_per_frame_bandwidth
76   // Number of (8x8) blocks in frame = mi_rows * mi_cols;
77   const float factor  = 0.5;
78   const int number_blocks = cm->mi_rows  * cm->mi_cols;
79   // The condition below corresponds to turning off at target bitrates:
80   // ~24kbps for CIF, 72kbps for VGA (at 30fps).
81   // Also turn off at very small frame sizes, to avoid too large fraction of
82   // superblocks to be refreshed per frame. Threshold below is less than QCIF.
83   if (rc->av_per_frame_bandwidth < factor * number_blocks ||
84       number_blocks / 64 < 5)
85     return 0;
86   else
87     return 1;
88 }
89 
90 // Check if this coding block, of size bsize, should be considered for refresh
91 // (lower-qp coding). Decision can be based on various factors, such as
92 // size of the coding block (i.e., below min_block size rejected), coding
93 // mode, and rate/distortion.
candidate_refresh_aq(const CYCLIC_REFRESH * cr,const MB_MODE_INFO * mbmi,BLOCK_SIZE bsize,int use_rd)94 static int candidate_refresh_aq(const CYCLIC_REFRESH *cr,
95                                 const MB_MODE_INFO *mbmi,
96                                 BLOCK_SIZE bsize, int use_rd) {
97   if (use_rd) {
98     // If projected rate is below the thresh_rate (well below target,
99     // so undershoot expected), accept it for lower-qp coding.
100     if (cr->projected_rate_sb < cr->thresh_rate_sb)
101       return 1;
102     // Otherwise, reject the block for lower-qp coding if any of the following:
103     // 1) prediction block size is below min_block_size
104     // 2) mode is non-zero mv and projected distortion is above thresh_dist
105     // 3) mode is an intra-mode (we may want to allow some of this under
106     // another thresh_dist)
107     else if (bsize < cr->min_block_size ||
108              (mbmi->mv[0].as_int != 0 &&
109               cr->projected_dist_sb > cr->thresh_dist_sb) ||
110              !is_inter_block(mbmi))
111       return 0;
112     else
113       return 1;
114   } else {
115     // Rate/distortion not used for update.
116     if (bsize < cr->min_block_size ||
117         mbmi->mv[0].as_int != 0 ||
118         !is_inter_block(mbmi))
119       return 0;
120     else
121       return 1;
122   }
123 }
124 
125 // Prior to coding a given prediction block, of size bsize at (mi_row, mi_col),
126 // check if we should reset the segment_id, and update the cyclic_refresh map
127 // and segmentation map.
vp9_cyclic_refresh_update_segment(VP9_COMP * const cpi,MB_MODE_INFO * const mbmi,int mi_row,int mi_col,BLOCK_SIZE bsize,int use_rd)128 void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi,
129                                        MB_MODE_INFO *const mbmi,
130                                        int mi_row, int mi_col,
131                                        BLOCK_SIZE bsize, int use_rd) {
132   const VP9_COMMON *const cm = &cpi->common;
133   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
134   const int bw = num_8x8_blocks_wide_lookup[bsize];
135   const int bh = num_8x8_blocks_high_lookup[bsize];
136   const int xmis = MIN(cm->mi_cols - mi_col, bw);
137   const int ymis = MIN(cm->mi_rows - mi_row, bh);
138   const int block_index = mi_row * cm->mi_cols + mi_col;
139   const int refresh_this_block = 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.
vp9_cyclic_refresh_setup(VP9_COMP * const cpi)179 void 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     vp9_clear_system_state();
204     // Some of these parameters may be set via codec-control function later.
205     cr->max_sbs_perframe = 10;
206     cr->max_qdelta_perc = 50;
207     cr->min_block_size = BLOCK_8X8;
208     cr->time_for_refresh = 1;
209     // Set rate threshold to some fraction of target (and scaled by 256).
210     cr->thresh_rate_sb = (rc->sb64_target_rate * 256) >> 2;
211     // Distortion threshold, quadratic in Q, scale factor to be adjusted.
212     cr->thresh_dist_sb = 8 * (int)(vp9_convert_qindex_to_q(cm->base_qindex) *
213         vp9_convert_qindex_to_q(cm->base_qindex));
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)(vp9_convert_qindex_to_q(cm->base_qindex) *
219           vp9_convert_qindex_to_q(cm->base_qindex));
220     }
221 
222     cr->num_seg_blocks = 0;
223     // Set up segmentation.
224     // Clear down the segment map.
225     vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
226     vp9_enable_segmentation(&cm->seg);
227     vp9_clearall_segfeatures(seg);
228     // Select delta coding method.
229     seg->abs_delta = SEGMENT_DELTADATA;
230 
231     // Note: setting temporal_update has no effect, as the seg-map coding method
232     // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(),
233     // based on the coding cost of each method. For error_resilient mode on the
234     // last_frame_seg_map is set to 0, so if temporal coding is used, it is
235     // relative to 0 previous map.
236     // seg->temporal_update = 0;
237 
238     // Segment 0 "Q" feature is disabled so it defaults to the baseline Q.
239     vp9_disable_segfeature(seg, 0, SEG_LVL_ALT_Q);
240     // Use segment 1 for in-frame Q adjustment.
241     vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
242 
243     // Set the q delta for segment 1.
244     qindex_delta = vp9_compute_qdelta_by_rate(cpi,
245                                               cm->base_qindex,
246                                               rate_ratio_qdelta);
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 
vp9_cyclic_refresh_set_rate_and_dist_sb(CYCLIC_REFRESH * cr,int64_t rate_sb,int64_t dist_sb)316 void 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 
vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH * cr)322 int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) {
323   return cr->rdmult;
324 }
325