Ensure the error-concealment code is available
[platform/upstream/libvpx.git] / vp9 / encoder / vp9_aq_cyclicrefresh.c
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
21 struct CYCLIC_REFRESH {
22   // Percentage of blocks per frame that are targeted as candidates
23   // for cyclic refresh.
24   int percent_refresh;
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 block will need to wait to be refreshed again, in
32   // excess of the cycle time, i.e., in the case of all zero motion, block
33   // will be refreshed every (100/percent_refresh + time_for_refresh) frames.
34   int time_for_refresh;
35   // // Target number of (8x8) blocks that are set for delta-q (segment 1).
36   int target_num_seg_blocks;
37   // Actual number of (8x8) blocks that were applied delta-q (segment 1).
38   int actual_num_seg_blocks;
39   // RD mult. parameters for segment 1.
40   int rdmult;
41   // Cyclic refresh map.
42   signed char *map;
43   // Thresholds applied to projected rate/distortion of the superblock.
44   int64_t thresh_rate_sb;
45   int64_t thresh_dist_sb;
46   // Rate target ratio to set q delta.
47   double rate_ratio_qdelta;
48 };
49
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
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.
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 = avg_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->avg_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.
94 static int candidate_refresh_aq(const CYCLIC_REFRESH *cr,
95                                 const MB_MODE_INFO *mbmi,
96                                 BLOCK_SIZE bsize, int use_rd,
97                                 int64_t rate_sb) {
98   if (use_rd) {
99     MV mv = mbmi->mv[0].as_mv;
100     // If projected rate is below the thresh_rate (well below target,
101     // so undershoot expected), accept it for lower-qp coding.
102     if (rate_sb < cr->thresh_rate_sb)
103       return 1;
104     // Otherwise, reject the block for lower-qp coding if any of the following:
105     // 1) mode uses large mv
106     // 2) mode is an intra-mode (we may want to allow some of this under
107     // another thresh_dist)
108     else if (mv.row > 32 || mv.row < -32 ||
109              mv.col > 32 || mv.col < -32 || !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 // Compute delta-q for the segment.
125 static int compute_deltaq(const VP9_COMP *cpi, int q) {
126   const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
127   const RATE_CONTROL *const rc = &cpi->rc;
128   int deltaq = vp9_compute_qdelta_by_rate(rc, cpi->common.frame_type,
129                                           q, cr->rate_ratio_qdelta,
130                                           cpi->common.bit_depth);
131   if ((-deltaq) > cr->max_qdelta_perc * q / 100) {
132     deltaq = -cr->max_qdelta_perc * q / 100;
133   }
134   return deltaq;
135 }
136
137 // For the just encoded frame, estimate the bits, incorporating the delta-q
138 // from segment 1. This function is called in the postencode (called from
139 // rc_update_rate_correction_factors()).
140 int vp9_cyclic_refresh_estimate_bits_at_q(const VP9_COMP *cpi,
141                                           double correction_factor) {
142   const VP9_COMMON *const cm = &cpi->common;
143   const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
144   int estimated_bits;
145   int mbs = cm->MBs;
146   int num8x8bl = mbs << 2;
147   // Weight for segment 1: use actual number of blocks refreshed in
148   // previous/just encoded frame. Note number of blocks here is in 8x8 units.
149   double weight_segment = (double)cr->actual_num_seg_blocks / num8x8bl;
150   // Compute delta-q that was used in the just encoded frame.
151   int deltaq = compute_deltaq(cpi, cm->base_qindex);
152   // Take segment weighted average for estimated bits.
153   estimated_bits = (int)((1.0 - weight_segment) *
154       vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex, mbs,
155                              correction_factor, cm->bit_depth) +
156                              weight_segment *
157       vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex + deltaq, mbs,
158                              correction_factor, cm->bit_depth));
159   return estimated_bits;
160 }
161
162 // Prior to encoding the frame, estimate the bits per mb, for a given q = i and
163 // a corresponding delta-q (for segment 1). This function is called in the
164 // rc_regulate_q() to set the base qp index.
165 int vp9_cyclic_refresh_rc_bits_per_mb(const VP9_COMP *cpi, int i,
166                                       double correction_factor) {
167   const VP9_COMMON *const cm = &cpi->common;
168   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
169   int bits_per_mb;
170   int num8x8bl = cm->MBs << 2;
171   // Weight for segment 1 prior to encoding: take the target number for the
172   // frame to be encoded. Number of blocks here is in 8x8 units.
173   // Note that this is called in rc_regulate_q, which is called before the
174   // cyclic_refresh_setup (which sets cr->target_num_seg_blocks). So a mismatch
175   // may occur between the cr->target_num_seg_blocks value here and the
176   // cr->target_num_seg_block set for encoding the frame. For the current use
177   // case of fixed cr->percent_refresh and cr->time_for_refresh = 0, mismatch
178   // does not occur/is very small.
179   double weight_segment = (double)cr->target_num_seg_blocks / num8x8bl;
180   // Compute delta-q corresponding to qindex i.
181   int deltaq = compute_deltaq(cpi, i);
182   // Take segment weighted average for bits per mb.
183   bits_per_mb = (int)((1.0 - weight_segment) *
184       vp9_rc_bits_per_mb(cm->frame_type, i, correction_factor, cm->bit_depth) +
185       weight_segment *
186       vp9_rc_bits_per_mb(cm->frame_type, i + deltaq, correction_factor,
187                          cm->bit_depth));
188   return bits_per_mb;
189 }
190
191 // Prior to coding a given prediction block, of size bsize at (mi_row, mi_col),
192 // check if we should reset the segment_id, and update the cyclic_refresh map
193 // and segmentation map.
194 void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi,
195                                        MB_MODE_INFO *const mbmi,
196                                        int mi_row, int mi_col,
197                                        BLOCK_SIZE bsize, int use_rd,
198                                        int64_t rate_sb) {
199   const VP9_COMMON *const cm = &cpi->common;
200   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
201   const int bw = num_8x8_blocks_wide_lookup[bsize];
202   const int bh = num_8x8_blocks_high_lookup[bsize];
203   const int xmis = MIN(cm->mi_cols - mi_col, bw);
204   const int ymis = MIN(cm->mi_rows - mi_row, bh);
205   const int block_index = mi_row * cm->mi_cols + mi_col;
206   const int refresh_this_block = candidate_refresh_aq(cr, mbmi, bsize, use_rd,
207                                                       rate_sb);
208   // Default is to not update the refresh map.
209   int new_map_value = cr->map[block_index];
210   int x = 0; int y = 0;
211
212   // Check if we should reset the segment_id for this block.
213   if (mbmi->segment_id > 0 && !refresh_this_block)
214     mbmi->segment_id = 0;
215
216   // Update the cyclic refresh map, to be used for setting segmentation map
217   // for the next frame. If the block  will be refreshed this frame, mark it
218   // as clean. The magnitude of the -ve influences how long before we consider
219   // it for refresh again.
220   if (mbmi->segment_id == 1) {
221     new_map_value = -cr->time_for_refresh;
222   } else if (refresh_this_block) {
223     // Else if it is accepted as candidate for refresh, and has not already
224     // been refreshed (marked as 1) then mark it as a candidate for cleanup
225     // for future time (marked as 0), otherwise don't update it.
226     if (cr->map[block_index] == 1)
227       new_map_value = 0;
228   } else {
229     // Leave it marked as block that is not candidate for refresh.
230     new_map_value = 1;
231   }
232
233   // Update entries in the cyclic refresh map with new_map_value, and
234   // copy mbmi->segment_id into global segmentation map.
235   for (y = 0; y < ymis; y++)
236     for (x = 0; x < xmis; x++) {
237       cr->map[block_index + y * cm->mi_cols + x] = new_map_value;
238       cpi->segmentation_map[block_index + y * cm->mi_cols + x] =
239           mbmi->segment_id;
240     }
241 }
242
243 // Update the actual number of blocks that were applied the segment delta q.
244 void vp9_cyclic_refresh_update_actual_count(struct VP9_COMP *const cpi) {
245   VP9_COMMON *const cm = &cpi->common;
246   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
247   unsigned char *const seg_map = cpi->segmentation_map;
248   int mi_row, mi_col;
249   cr->actual_num_seg_blocks = 0;
250   for (mi_row = 0; mi_row < cm->mi_rows; mi_row++)
251   for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
252     if (seg_map[mi_row * cm->mi_cols + mi_col] == 1)
253       cr->actual_num_seg_blocks++;
254   }
255 }
256
257 // Update the segmentation map, and related quantities: cyclic refresh map,
258 // refresh sb_index, and target number of blocks to be refreshed.
259 void vp9_cyclic_refresh_update_map(VP9_COMP *const cpi) {
260   VP9_COMMON *const cm = &cpi->common;
261   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
262   unsigned char *const seg_map = cpi->segmentation_map;
263   int i, block_count, bl_index, sb_rows, sb_cols, sbs_in_frame;
264   int xmis, ymis, x, y;
265   vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
266   sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
267   sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
268   sbs_in_frame = sb_cols * sb_rows;
269   // Number of target blocks to get the q delta (segment 1).
270   block_count = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100;
271   // Set the segmentation map: cycle through the superblocks, starting at
272   // cr->mb_index, and stopping when either block_count blocks have been found
273   // to be refreshed, or we have passed through whole frame.
274   assert(cr->sb_index < sbs_in_frame);
275   i = cr->sb_index;
276   cr->target_num_seg_blocks = 0;
277   do {
278     int sum_map = 0;
279     // Get the mi_row/mi_col corresponding to superblock index i.
280     int sb_row_index = (i / sb_cols);
281     int sb_col_index = i - sb_row_index * sb_cols;
282     int mi_row = sb_row_index * MI_BLOCK_SIZE;
283     int mi_col = sb_col_index * MI_BLOCK_SIZE;
284     assert(mi_row >= 0 && mi_row < cm->mi_rows);
285     assert(mi_col >= 0 && mi_col < cm->mi_cols);
286     bl_index = mi_row * cm->mi_cols + mi_col;
287     // Loop through all 8x8 blocks in superblock and update map.
288     xmis = MIN(cm->mi_cols - mi_col,
289                num_8x8_blocks_wide_lookup[BLOCK_64X64]);
290     ymis = MIN(cm->mi_rows - mi_row,
291                num_8x8_blocks_high_lookup[BLOCK_64X64]);
292     for (y = 0; y < ymis; y++) {
293       for (x = 0; x < xmis; x++) {
294         const int bl_index2 = bl_index + y * cm->mi_cols + x;
295         // If the block is as a candidate for clean up then mark it
296         // for possible boost/refresh (segment 1). The segment id may get
297         // reset to 0 later if block gets coded anything other than ZEROMV.
298         if (cr->map[bl_index2] == 0) {
299           sum_map++;
300         } else if (cr->map[bl_index2] < 0) {
301           cr->map[bl_index2]++;
302         }
303       }
304     }
305     // Enforce constant segment over superblock.
306     // If segment is at least half of superblock, set to 1.
307     if (sum_map >= xmis * ymis / 2) {
308       for (y = 0; y < ymis; y++)
309         for (x = 0; x < xmis; x++) {
310           seg_map[bl_index + y * cm->mi_cols + x] = 1;
311         }
312       cr->target_num_seg_blocks += xmis * ymis;
313     }
314     i++;
315     if (i == sbs_in_frame) {
316       i = 0;
317     }
318   } while (cr->target_num_seg_blocks < block_count && i != cr->sb_index);
319   cr->sb_index = i;
320 }
321
322 // Set/update global/frame level cyclic refresh parameters.
323 void vp9_cyclic_refresh_update_parameters(VP9_COMP *const cpi) {
324   const RATE_CONTROL *const rc = &cpi->rc;
325   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
326   cr->percent_refresh = 10;
327   // Use larger delta-qp (increase rate_ratio_qdelta) for first few (~4)
328   // periods of the refresh cycle, after a key frame. This corresponds to ~40
329   // frames with cr->percent_refresh = 10.
330   if (rc->frames_since_key <  40)
331     cr->rate_ratio_qdelta = 3.0;
332   else
333     cr->rate_ratio_qdelta = 2.0;
334 }
335
336 // Setup cyclic background refresh: set delta q and segmentation map.
337 void vp9_cyclic_refresh_setup(VP9_COMP *const cpi) {
338   VP9_COMMON *const cm = &cpi->common;
339   const RATE_CONTROL *const rc = &cpi->rc;
340   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
341   struct segmentation *const seg = &cm->seg;
342   const int apply_cyclic_refresh  = apply_cyclic_refresh_bitrate(cm, rc);
343   // Don't apply refresh on key frame or enhancement layer frames.
344   if (!apply_cyclic_refresh ||
345       (cm->frame_type == KEY_FRAME) ||
346       (cpi->svc.temporal_layer_id > 0) ||
347       (cpi->svc.spatial_layer_id > 0)) {
348     // Set segmentation map to 0 and disable.
349     unsigned char *const seg_map = cpi->segmentation_map;
350     vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
351     vp9_disable_segmentation(&cm->seg);
352     if (cm->frame_type == KEY_FRAME)
353       cr->sb_index = 0;
354     return;
355   } else {
356     int qindex_delta = 0;
357     int qindex2;
358     const double q = vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth);
359     vp9_clear_system_state();
360     cr->max_qdelta_perc = 50;
361     cr->min_block_size = BLOCK_8X8;
362     cr->time_for_refresh = 0;
363     // Set rate threshold to some fraction of target (and scaled by 256).
364     cr->thresh_rate_sb = (rc->sb64_target_rate * 256) >> 2;
365     // Distortion threshold, quadratic in Q, scale factor to be adjusted.
366     cr->thresh_dist_sb = 8 * (int)(q * q);
367     if (cpi->sf.use_nonrd_pick_mode) {
368       // May want to be more conservative with thresholds in non-rd mode for now
369       // as rate/distortion are derived from model based on prediction residual.
370       cr->thresh_rate_sb = (rc->sb64_target_rate * 256);
371       cr->thresh_dist_sb = 16 * (int)(q * q);
372     }
373
374     // Set up segmentation.
375     // Clear down the segment map.
376     vp9_enable_segmentation(&cm->seg);
377     vp9_clearall_segfeatures(seg);
378     // Select delta coding method.
379     seg->abs_delta = SEGMENT_DELTADATA;
380
381     // Note: setting temporal_update has no effect, as the seg-map coding method
382     // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(),
383     // based on the coding cost of each method. For error_resilient mode on the
384     // last_frame_seg_map is set to 0, so if temporal coding is used, it is
385     // relative to 0 previous map.
386     // seg->temporal_update = 0;
387
388     // Segment 0 "Q" feature is disabled so it defaults to the baseline Q.
389     vp9_disable_segfeature(seg, 0, SEG_LVL_ALT_Q);
390     // Use segment 1 for in-frame Q adjustment.
391     vp9_enable_segfeature(seg, 1, SEG_LVL_ALT_Q);
392
393     // Set the q delta for segment 1.
394     qindex_delta = compute_deltaq(cpi, cm->base_qindex);
395
396     // Compute rd-mult for segment 1.
397     qindex2 = clamp(cm->base_qindex + cm->y_dc_delta_q + qindex_delta, 0, MAXQ);
398     cr->rdmult = vp9_compute_rd_mult(cpi, qindex2);
399
400     vp9_set_segdata(seg, 1, SEG_LVL_ALT_Q, qindex_delta);
401
402     // Update the segmentation and refresh map.
403     vp9_cyclic_refresh_update_map(cpi);
404   }
405 }
406
407 int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) {
408   return cr->rdmult;
409 }