• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "vpx_ports/system_state.h"
15 
16 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
17 
18 #include "vp9/common/vp9_seg_common.h"
19 
20 #include "vp9/encoder/vp9_ratectrl.h"
21 #include "vp9/encoder/vp9_segmentation.h"
22 
23 struct CYCLIC_REFRESH {
24   // Percentage of blocks per frame that are targeted as candidates
25   // for cyclic refresh.
26   int percent_refresh;
27   // Maximum q-delta as percentage of base q.
28   int max_qdelta_perc;
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.
36   int target_num_seg_blocks;
37   // Actual number of (8x8) blocks that were applied delta-q.
38   int actual_num_seg1_blocks;
39   int actual_num_seg2_blocks;
40   // RD mult. parameters for segment 1.
41   int rdmult;
42   // Cyclic refresh map.
43   signed char *map;
44   // Map of the last q a block was coded at.
45   uint8_t *last_coded_q_map;
46   // Thresholds applied to the projected rate/distortion of the coding block,
47   // when deciding whether block should be refreshed.
48   int64_t thresh_rate_sb;
49   int64_t thresh_dist_sb;
50   // Threshold applied to the motion vector (in units of 1/8 pel) of the
51   // coding block, when deciding whether block should be refreshed.
52   int16_t motion_thresh;
53   // Rate target ratio to set q delta.
54   double rate_ratio_qdelta;
55   // Boost factor for rate target ratio, for segment CR_SEGMENT_ID_BOOST2.
56   int rate_boost_fac;
57   double low_content_avg;
58   int qindex_delta[3];
59 };
60 
vp9_cyclic_refresh_alloc(int mi_rows,int mi_cols)61 CYCLIC_REFRESH *vp9_cyclic_refresh_alloc(int mi_rows, int mi_cols) {
62   size_t last_coded_q_map_size;
63   CYCLIC_REFRESH *const cr = vpx_calloc(1, sizeof(*cr));
64   if (cr == NULL)
65     return NULL;
66 
67   cr->map = vpx_calloc(mi_rows * mi_cols, sizeof(*cr->map));
68   if (cr->map == NULL) {
69     vpx_free(cr);
70     return NULL;
71   }
72   last_coded_q_map_size = mi_rows * mi_cols * sizeof(*cr->last_coded_q_map);
73   cr->last_coded_q_map = vpx_malloc(last_coded_q_map_size);
74   if (cr->last_coded_q_map == NULL) {
75     vpx_free(cr);
76     return NULL;
77   }
78   assert(MAXQ <= 255);
79   memset(cr->last_coded_q_map, MAXQ, last_coded_q_map_size);
80 
81   return cr;
82 }
83 
vp9_cyclic_refresh_free(CYCLIC_REFRESH * cr)84 void vp9_cyclic_refresh_free(CYCLIC_REFRESH *cr) {
85   vpx_free(cr->map);
86   vpx_free(cr->last_coded_q_map);
87   vpx_free(cr);
88 }
89 
90 // Check if we should turn off cyclic refresh based on bitrate condition.
apply_cyclic_refresh_bitrate(const VP9_COMMON * cm,const RATE_CONTROL * rc)91 static int apply_cyclic_refresh_bitrate(const VP9_COMMON *cm,
92                                         const RATE_CONTROL *rc) {
93   // Turn off cyclic refresh if bits available per frame is not sufficiently
94   // larger than bit cost of segmentation. Segment map bit cost should scale
95   // with number of seg blocks, so compare available bits to number of blocks.
96   // Average bits available per frame = avg_frame_bandwidth
97   // Number of (8x8) blocks in frame = mi_rows * mi_cols;
98   const float factor = 0.25;
99   const int number_blocks = cm->mi_rows  * cm->mi_cols;
100   // The condition below corresponds to turning off at target bitrates:
101   // (at 30fps), ~12kbps for CIF, 36kbps for VGA, 100kps for HD/720p.
102   // Also turn off at very small frame sizes, to avoid too large fraction of
103   // superblocks to be refreshed per frame. Threshold below is less than QCIF.
104   if (rc->avg_frame_bandwidth < factor * number_blocks ||
105       number_blocks / 64 < 5)
106     return 0;
107   else
108     return 1;
109 }
110 
111 // Check if this coding block, of size bsize, should be considered for refresh
112 // (lower-qp coding). Decision can be based on various factors, such as
113 // size of the coding block (i.e., below min_block size rejected), coding
114 // mode, and rate/distortion.
candidate_refresh_aq(const CYCLIC_REFRESH * cr,const MB_MODE_INFO * mbmi,int64_t rate,int64_t dist,int bsize)115 static int candidate_refresh_aq(const CYCLIC_REFRESH *cr,
116                                 const MB_MODE_INFO *mbmi,
117                                 int64_t rate,
118                                 int64_t dist,
119                                 int bsize) {
120   MV mv = mbmi->mv[0].as_mv;
121   // Reject the block for lower-qp coding if projected distortion
122   // is above the threshold, and any of the following is true:
123   // 1) mode uses large mv
124   // 2) mode is an intra-mode
125   // Otherwise accept for refresh.
126   if (dist > cr->thresh_dist_sb &&
127       (mv.row > cr->motion_thresh || mv.row < -cr->motion_thresh ||
128        mv.col > cr->motion_thresh || mv.col < -cr->motion_thresh ||
129        !is_inter_block(mbmi)))
130     return CR_SEGMENT_ID_BASE;
131   else  if (bsize >= BLOCK_16X16 &&
132             rate < cr->thresh_rate_sb &&
133             is_inter_block(mbmi) &&
134             mbmi->mv[0].as_int == 0 &&
135             cr->rate_boost_fac > 10)
136     // More aggressive delta-q for bigger blocks with zero motion.
137     return CR_SEGMENT_ID_BOOST2;
138   else
139     return CR_SEGMENT_ID_BOOST1;
140 }
141 
142 // Compute delta-q for the segment.
compute_deltaq(const VP9_COMP * cpi,int q,double rate_factor)143 static int compute_deltaq(const VP9_COMP *cpi, int q, double rate_factor) {
144   const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
145   const RATE_CONTROL *const rc = &cpi->rc;
146   int deltaq = vp9_compute_qdelta_by_rate(rc, cpi->common.frame_type,
147                                           q, rate_factor,
148                                           cpi->common.bit_depth);
149   if ((-deltaq) > cr->max_qdelta_perc * q / 100) {
150     deltaq = -cr->max_qdelta_perc * q / 100;
151   }
152   return deltaq;
153 }
154 
155 // For the just encoded frame, estimate the bits, incorporating the delta-q
156 // from non-base segment. For now ignore effect of multiple segments
157 // (with different delta-q). Note this function is called in the postencode
158 // (called from rc_update_rate_correction_factors()).
vp9_cyclic_refresh_estimate_bits_at_q(const VP9_COMP * cpi,double correction_factor)159 int vp9_cyclic_refresh_estimate_bits_at_q(const VP9_COMP *cpi,
160                                           double correction_factor) {
161   const VP9_COMMON *const cm = &cpi->common;
162   const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
163   int estimated_bits;
164   int mbs = cm->MBs;
165   int num8x8bl = mbs << 2;
166   // Weight for non-base segments: use actual number of blocks refreshed in
167   // previous/just encoded frame. Note number of blocks here is in 8x8 units.
168   double weight_segment1 = (double)cr->actual_num_seg1_blocks / num8x8bl;
169   double weight_segment2 = (double)cr->actual_num_seg2_blocks / num8x8bl;
170   // Take segment weighted average for estimated bits.
171   estimated_bits = (int)((1.0 - weight_segment1 - weight_segment2) *
172       vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex, mbs,
173                              correction_factor, cm->bit_depth) +
174                              weight_segment1 *
175       vp9_estimate_bits_at_q(cm->frame_type,
176                              cm->base_qindex + cr->qindex_delta[1], mbs,
177                              correction_factor, cm->bit_depth) +
178                              weight_segment2 *
179       vp9_estimate_bits_at_q(cm->frame_type,
180                              cm->base_qindex + cr->qindex_delta[2], mbs,
181                              correction_factor, cm->bit_depth));
182   return estimated_bits;
183 }
184 
185 // Prior to encoding the frame, estimate the bits per mb, for a given q = i and
186 // a corresponding delta-q (for segment 1). This function is called in the
187 // rc_regulate_q() to set the base qp index.
188 // Note: the segment map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or
189 // to 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock, prior to encoding.
vp9_cyclic_refresh_rc_bits_per_mb(const VP9_COMP * cpi,int i,double correction_factor)190 int vp9_cyclic_refresh_rc_bits_per_mb(const VP9_COMP *cpi, int i,
191                                       double correction_factor) {
192   const VP9_COMMON *const cm = &cpi->common;
193   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
194   int bits_per_mb;
195   int num8x8bl = cm->MBs << 2;
196   // Weight for segment prior to encoding: take the average of the target
197   // number for the frame to be encoded and the actual from the previous frame.
198   double weight_segment = (double)((cr->target_num_seg_blocks +
199       cr->actual_num_seg1_blocks + cr->actual_num_seg2_blocks) >> 1) /
200       num8x8bl;
201   // Compute delta-q corresponding to qindex i.
202   int deltaq = compute_deltaq(cpi, i, cr->rate_ratio_qdelta);
203   // Take segment weighted average for bits per mb.
204   bits_per_mb = (int)((1.0 - weight_segment) *
205       vp9_rc_bits_per_mb(cm->frame_type, i, correction_factor, cm->bit_depth) +
206       weight_segment *
207       vp9_rc_bits_per_mb(cm->frame_type, i + deltaq, correction_factor,
208                          cm->bit_depth));
209   return bits_per_mb;
210 }
211 
212 // Prior to coding a given prediction block, of size bsize at (mi_row, mi_col),
213 // check if we should reset the segment_id, and update the cyclic_refresh map
214 // 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,int64_t rate,int64_t dist,int skip)215 void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi,
216                                        MB_MODE_INFO *const mbmi,
217                                        int mi_row, int mi_col,
218                                        BLOCK_SIZE bsize,
219                                        int64_t rate,
220                                        int64_t dist,
221                                        int skip) {
222   const VP9_COMMON *const cm = &cpi->common;
223   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
224   const int bw = num_8x8_blocks_wide_lookup[bsize];
225   const int bh = num_8x8_blocks_high_lookup[bsize];
226   const int xmis = MIN(cm->mi_cols - mi_col, bw);
227   const int ymis = MIN(cm->mi_rows - mi_row, bh);
228   const int block_index = mi_row * cm->mi_cols + mi_col;
229   const int refresh_this_block = candidate_refresh_aq(cr, mbmi, rate, dist,
230                                                       bsize);
231   // Default is to not update the refresh map.
232   int new_map_value = cr->map[block_index];
233   int x = 0; int y = 0;
234 
235   // If this block is labeled for refresh, check if we should reset the
236   // segment_id.
237   if (cyclic_refresh_segment_id_boosted(mbmi->segment_id)) {
238     mbmi->segment_id = refresh_this_block;
239     // Reset segment_id if will be skipped.
240     if (skip)
241       mbmi->segment_id = CR_SEGMENT_ID_BASE;
242   }
243 
244   // Update the cyclic refresh map, to be used for setting segmentation map
245   // for the next frame. If the block  will be refreshed this frame, mark it
246   // as clean. The magnitude of the -ve influences how long before we consider
247   // it for refresh again.
248   if (cyclic_refresh_segment_id_boosted(mbmi->segment_id)) {
249     new_map_value = -cr->time_for_refresh;
250   } else if (refresh_this_block) {
251     // Else if it is accepted as candidate for refresh, and has not already
252     // been refreshed (marked as 1) then mark it as a candidate for cleanup
253     // for future time (marked as 0), otherwise don't update it.
254     if (cr->map[block_index] == 1)
255       new_map_value = 0;
256   } else {
257     // Leave it marked as block that is not candidate for refresh.
258     new_map_value = 1;
259   }
260 
261   // Update entries in the cyclic refresh map with new_map_value, and
262   // copy mbmi->segment_id into global segmentation map.
263   for (y = 0; y < ymis; y++)
264     for (x = 0; x < xmis; x++) {
265       int map_offset = block_index + y * cm->mi_cols + x;
266       cr->map[map_offset] = new_map_value;
267       cpi->segmentation_map[map_offset] = mbmi->segment_id;
268       // Inter skip blocks were clearly not coded at the current qindex, so
269       // don't update the map for them. For cases where motion is non-zero or
270       // the reference frame isn't the previous frame, the previous value in
271       // the map for this spatial location is not entirely correct.
272       if (!is_inter_block(mbmi) || !skip)
273         cr->last_coded_q_map[map_offset] = clamp(
274             cm->base_qindex + cr->qindex_delta[mbmi->segment_id], 0, MAXQ);
275     }
276 }
277 
278 // Update the actual number of blocks that were applied the segment delta q.
vp9_cyclic_refresh_postencode(VP9_COMP * const cpi)279 void vp9_cyclic_refresh_postencode(VP9_COMP *const cpi) {
280   VP9_COMMON *const cm = &cpi->common;
281   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
282   unsigned char *const seg_map = cpi->segmentation_map;
283   int mi_row, mi_col;
284   cr->actual_num_seg1_blocks = 0;
285   cr->actual_num_seg2_blocks = 0;
286   for (mi_row = 0; mi_row < cm->mi_rows; mi_row++)
287     for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
288       if (cyclic_refresh_segment_id(
289           seg_map[mi_row * cm->mi_cols + mi_col]) == CR_SEGMENT_ID_BOOST1)
290         cr->actual_num_seg1_blocks++;
291       else if (cyclic_refresh_segment_id(
292           seg_map[mi_row * cm->mi_cols + mi_col]) == CR_SEGMENT_ID_BOOST2)
293         cr->actual_num_seg2_blocks++;
294     }
295 }
296 
297 // Set golden frame update interval, for non-svc 1 pass CBR mode.
vp9_cyclic_refresh_set_golden_update(VP9_COMP * const cpi)298 void vp9_cyclic_refresh_set_golden_update(VP9_COMP *const cpi) {
299   RATE_CONTROL *const rc = &cpi->rc;
300   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
301   // Set minimum gf_interval for GF update to a multiple (== 2) of refresh
302   // period. Depending on past encoding stats, GF flag may be reset and update
303   // may not occur until next baseline_gf_interval.
304   if (cr->percent_refresh > 0)
305     rc->baseline_gf_interval = 4 * (100 / cr->percent_refresh);
306   else
307     rc->baseline_gf_interval = 40;
308 }
309 
310 // Update some encoding stats (from the just encoded frame). If this frame's
311 // background has high motion, refresh the golden frame. Otherwise, if the
312 // golden reference is to be updated check if we should NOT update the golden
313 // ref.
vp9_cyclic_refresh_check_golden_update(VP9_COMP * const cpi)314 void vp9_cyclic_refresh_check_golden_update(VP9_COMP *const cpi) {
315   VP9_COMMON *const cm = &cpi->common;
316   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
317   int mi_row, mi_col;
318   double fraction_low = 0.0;
319   int low_content_frame = 0;
320 
321   MODE_INFO **mi = cm->mi_grid_visible;
322   RATE_CONTROL *const rc = &cpi->rc;
323   const int rows = cm->mi_rows, cols = cm->mi_cols;
324   int cnt1 = 0, cnt2 = 0;
325   int force_gf_refresh = 0;
326 
327   for (mi_row = 0; mi_row < rows; mi_row++) {
328     for (mi_col = 0; mi_col < cols; mi_col++) {
329       int16_t abs_mvr = mi[0]->mbmi.mv[0].as_mv.row >= 0 ?
330           mi[0]->mbmi.mv[0].as_mv.row : -1 * mi[0]->mbmi.mv[0].as_mv.row;
331       int16_t abs_mvc = mi[0]->mbmi.mv[0].as_mv.col >= 0 ?
332           mi[0]->mbmi.mv[0].as_mv.col : -1 * mi[0]->mbmi.mv[0].as_mv.col;
333 
334       // Calculate the motion of the background.
335       if (abs_mvr <= 16 && abs_mvc <= 16) {
336         cnt1++;
337         if (abs_mvr == 0 && abs_mvc == 0)
338           cnt2++;
339       }
340       mi++;
341 
342       // Accumulate low_content_frame.
343       if (cr->map[mi_row * cols + mi_col] < 1)
344         low_content_frame++;
345     }
346     mi += 8;
347   }
348 
349   // For video conference clips, if the background has high motion in current
350   // frame because of the camera movement, set this frame as the golden frame.
351   // Use 70% and 5% as the thresholds for golden frame refreshing.
352   // Also, force this frame as a golden update frame if this frame will change
353   // the resolution (resize_pending != 0).
354   if (cpi->resize_pending != 0 ||
355      (cnt1 * 10 > (70 * rows * cols) && cnt2 * 20 < cnt1)) {
356     vp9_cyclic_refresh_set_golden_update(cpi);
357     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
358 
359     if (rc->frames_till_gf_update_due > rc->frames_to_key)
360       rc->frames_till_gf_update_due = rc->frames_to_key;
361     cpi->refresh_golden_frame = 1;
362     force_gf_refresh = 1;
363   }
364 
365   fraction_low =
366       (double)low_content_frame / (rows * cols);
367   // Update average.
368   cr->low_content_avg = (fraction_low + 3 * cr->low_content_avg) / 4;
369   if (!force_gf_refresh && cpi->refresh_golden_frame == 1) {
370     // Don't update golden reference if the amount of low_content for the
371     // current encoded frame is small, or if the recursive average of the
372     // low_content over the update interval window falls below threshold.
373     if (fraction_low < 0.8 || cr->low_content_avg < 0.7)
374       cpi->refresh_golden_frame = 0;
375     // Reset for next internal.
376     cr->low_content_avg = fraction_low;
377   }
378 }
379 
380 // Update the segmentation map, and related quantities: cyclic refresh map,
381 // refresh sb_index, and target number of blocks to be refreshed.
382 // The map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or to
383 // 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock.
384 // Blocks labeled as BOOST1 may later get set to BOOST2 (during the
385 // encoding of the superblock).
cyclic_refresh_update_map(VP9_COMP * const cpi)386 static void cyclic_refresh_update_map(VP9_COMP *const cpi) {
387   VP9_COMMON *const cm = &cpi->common;
388   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
389   unsigned char *const seg_map = cpi->segmentation_map;
390   int i, block_count, bl_index, sb_rows, sb_cols, sbs_in_frame;
391   int xmis, ymis, x, y;
392   memset(seg_map, CR_SEGMENT_ID_BASE, cm->mi_rows * cm->mi_cols);
393   sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
394   sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
395   sbs_in_frame = sb_cols * sb_rows;
396   // Number of target blocks to get the q delta (segment 1).
397   block_count = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100;
398   // Set the segmentation map: cycle through the superblocks, starting at
399   // cr->mb_index, and stopping when either block_count blocks have been found
400   // to be refreshed, or we have passed through whole frame.
401   assert(cr->sb_index < sbs_in_frame);
402   i = cr->sb_index;
403   cr->target_num_seg_blocks = 0;
404   do {
405     int sum_map = 0;
406     // Get the mi_row/mi_col corresponding to superblock index i.
407     int sb_row_index = (i / sb_cols);
408     int sb_col_index = i - sb_row_index * sb_cols;
409     int mi_row = sb_row_index * MI_BLOCK_SIZE;
410     int mi_col = sb_col_index * MI_BLOCK_SIZE;
411     int qindex_thresh =
412         cpi->oxcf.content == VP9E_CONTENT_SCREEN
413             ? vp9_get_qindex(&cm->seg, CR_SEGMENT_ID_BOOST2, cm->base_qindex)
414             : 0;
415     assert(mi_row >= 0 && mi_row < cm->mi_rows);
416     assert(mi_col >= 0 && mi_col < cm->mi_cols);
417     bl_index = mi_row * cm->mi_cols + mi_col;
418     // Loop through all 8x8 blocks in superblock and update map.
419     xmis = MIN(cm->mi_cols - mi_col,
420                num_8x8_blocks_wide_lookup[BLOCK_64X64]);
421     ymis = MIN(cm->mi_rows - mi_row,
422                num_8x8_blocks_high_lookup[BLOCK_64X64]);
423     for (y = 0; y < ymis; y++) {
424       for (x = 0; x < xmis; x++) {
425         const int bl_index2 = bl_index + y * cm->mi_cols + x;
426         // If the block is as a candidate for clean up then mark it
427         // for possible boost/refresh (segment 1). The segment id may get
428         // reset to 0 later if block gets coded anything other than ZEROMV.
429         if (cr->map[bl_index2] == 0) {
430           if (cr->last_coded_q_map[bl_index2] > qindex_thresh)
431             sum_map++;
432         } else if (cr->map[bl_index2] < 0) {
433           cr->map[bl_index2]++;
434         }
435       }
436     }
437     // Enforce constant segment over superblock.
438     // If segment is at least half of superblock, set to 1.
439     if (sum_map >= xmis * ymis / 2) {
440       for (y = 0; y < ymis; y++)
441         for (x = 0; x < xmis; x++) {
442           seg_map[bl_index + y * cm->mi_cols + x] = CR_SEGMENT_ID_BOOST1;
443         }
444       cr->target_num_seg_blocks += xmis * ymis;
445     }
446     i++;
447     if (i == sbs_in_frame) {
448       i = 0;
449     }
450   } while (cr->target_num_seg_blocks < block_count && i != cr->sb_index);
451   cr->sb_index = i;
452 }
453 
454 // Set cyclic refresh parameters.
vp9_cyclic_refresh_update_parameters(VP9_COMP * const cpi)455 void vp9_cyclic_refresh_update_parameters(VP9_COMP *const cpi) {
456   const RATE_CONTROL *const rc = &cpi->rc;
457   const VP9_COMMON *const cm = &cpi->common;
458   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
459   cr->percent_refresh = 10;
460   cr->max_qdelta_perc = 50;
461   cr->time_for_refresh = 0;
462   // Use larger delta-qp (increase rate_ratio_qdelta) for first few (~4)
463   // periods of the refresh cycle, after a key frame.
464   // Account for larger interval on base layer for temporal layers.
465   if (cr->percent_refresh > 0 &&
466       rc->frames_since_key <  (4 * cpi->svc.number_temporal_layers) *
467       (100 / cr->percent_refresh))
468     cr->rate_ratio_qdelta = 3.0;
469   else
470     cr->rate_ratio_qdelta = 2.0;
471   // Adjust some parameters for low resolutions at low bitrates.
472   if (cm->width <= 352 &&
473       cm->height <= 288 &&
474       rc->avg_frame_bandwidth < 3400) {
475     cr->motion_thresh = 4;
476     cr->rate_boost_fac = 10;
477   } else {
478     cr->motion_thresh = 32;
479     cr->rate_boost_fac = 17;
480   }
481 }
482 
483 // Setup cyclic background refresh: set delta q and segmentation map.
vp9_cyclic_refresh_setup(VP9_COMP * const cpi)484 void vp9_cyclic_refresh_setup(VP9_COMP *const cpi) {
485   VP9_COMMON *const cm = &cpi->common;
486   const RATE_CONTROL *const rc = &cpi->rc;
487   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
488   struct segmentation *const seg = &cm->seg;
489   const int apply_cyclic_refresh  = apply_cyclic_refresh_bitrate(cm, rc);
490   if (cm->current_video_frame == 0)
491     cr->low_content_avg = 0.0;
492   // Don't apply refresh on key frame or enhancement layer frames.
493   if (!apply_cyclic_refresh ||
494       (cm->frame_type == KEY_FRAME) ||
495       (cpi->svc.temporal_layer_id > 0) ||
496       (cpi->svc.spatial_layer_id > 0)) {
497     // Set segmentation map to 0 and disable.
498     unsigned char *const seg_map = cpi->segmentation_map;
499     memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
500     vp9_disable_segmentation(&cm->seg);
501     if (cm->frame_type == KEY_FRAME) {
502       memset(cr->last_coded_q_map, MAXQ,
503              cm->mi_rows * cm->mi_cols * sizeof(*cr->last_coded_q_map));
504       cr->sb_index = 0;
505     }
506     return;
507   } else {
508     int qindex_delta = 0;
509     int qindex2;
510     const double q = vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth);
511     vpx_clear_system_state();
512     // Set rate threshold to some multiple (set to 2 for now) of the target
513     // rate (target is given by sb64_target_rate and scaled by 256).
514     cr->thresh_rate_sb = ((int64_t)(rc->sb64_target_rate) << 8) << 2;
515     // Distortion threshold, quadratic in Q, scale factor to be adjusted.
516     // q will not exceed 457, so (q * q) is within 32bit; see:
517     // vp9_convert_qindex_to_q(), vp9_ac_quant(), ac_qlookup*[].
518     cr->thresh_dist_sb = ((int64_t)(q * q)) << 2;
519 
520     // Set up segmentation.
521     // Clear down the segment map.
522     vp9_enable_segmentation(&cm->seg);
523     vp9_clearall_segfeatures(seg);
524     // Select delta coding method.
525     seg->abs_delta = SEGMENT_DELTADATA;
526 
527     // Note: setting temporal_update has no effect, as the seg-map coding method
528     // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(),
529     // based on the coding cost of each method. For error_resilient mode on the
530     // last_frame_seg_map is set to 0, so if temporal coding is used, it is
531     // relative to 0 previous map.
532     // seg->temporal_update = 0;
533 
534     // Segment BASE "Q" feature is disabled so it defaults to the baseline Q.
535     vp9_disable_segfeature(seg, CR_SEGMENT_ID_BASE, SEG_LVL_ALT_Q);
536     // Use segment BOOST1 for in-frame Q adjustment.
537     vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q);
538     // Use segment BOOST2 for more aggressive in-frame Q adjustment.
539     vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q);
540 
541     // Set the q delta for segment BOOST1.
542     qindex_delta = compute_deltaq(cpi, cm->base_qindex, cr->rate_ratio_qdelta);
543     cr->qindex_delta[1] = qindex_delta;
544 
545     // Compute rd-mult for segment BOOST1.
546     qindex2 = clamp(cm->base_qindex + cm->y_dc_delta_q + qindex_delta, 0, MAXQ);
547 
548     cr->rdmult = vp9_compute_rd_mult(cpi, qindex2);
549 
550     vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q, qindex_delta);
551 
552     // Set a more aggressive (higher) q delta for segment BOOST2.
553     qindex_delta = compute_deltaq(
554         cpi, cm->base_qindex, MIN(CR_MAX_RATE_TARGET_RATIO,
555         0.1 * cr->rate_boost_fac * cr->rate_ratio_qdelta));
556     cr->qindex_delta[2] = qindex_delta;
557     vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q, qindex_delta);
558 
559     // Update the segmentation and refresh map.
560     cyclic_refresh_update_map(cpi);
561   }
562 }
563 
vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH * cr)564 int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) {
565   return cr->rdmult;
566 }
567 
vp9_cyclic_refresh_reset_resize(VP9_COMP * const cpi)568 void vp9_cyclic_refresh_reset_resize(VP9_COMP *const cpi) {
569   const VP9_COMMON *const cm = &cpi->common;
570   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
571   memset(cr->map, 0, cm->mi_rows * cm->mi_cols);
572   cr->sb_index = 0;
573   cpi->refresh_golden_frame = 1;
574 }
575