AOMedia AV1 Codec
rc_utils.h
1 /*
2  * Copyright (c) 2020, Alliance for Open Media. All rights reserved.
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #ifndef AOM_AV1_ENCODER_RC_UTILS_H_
13 #define AOM_AV1_ENCODER_RC_UTILS_H_
14 
15 #include "av1/encoder/encoder.h"
16 #include "aom_dsp/psnr.h"
17 
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21 
22 static inline void check_reset_rc_flag(AV1_COMP *cpi) {
23  RATE_CONTROL *rc = &cpi->rc;
24  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
25  if (cpi->common.current_frame.frame_number >
26  (unsigned int)cpi->svc.number_spatial_layers) {
27  if (cpi->ppi->use_svc) {
28  av1_svc_check_reset_layer_rc_flag(cpi);
29  } else {
30  if (rc->avg_frame_bandwidth / 3 > (rc->prev_avg_frame_bandwidth >> 1) ||
31  rc->avg_frame_bandwidth < (rc->prev_avg_frame_bandwidth >> 1)) {
32  rc->rc_1_frame = 0;
33  rc->rc_2_frame = 0;
35  p_rc->buffer_level = p_rc->optimal_buffer_level;
36  }
37  }
38  }
39 }
40 
41 static inline void set_primary_rc_buffer_sizes(const AV1EncoderConfig *oxcf,
42  AV1_PRIMARY *ppi) {
43  PRIMARY_RATE_CONTROL *p_rc = &ppi->p_rc;
44  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
45 
46  const int64_t bandwidth = rc_cfg->target_bandwidth;
47  const int64_t starting = rc_cfg->starting_buffer_level_ms;
48  const int64_t optimal = rc_cfg->optimal_buffer_level_ms;
49  const int64_t maximum = rc_cfg->maximum_buffer_size_ms;
50 
51  p_rc->starting_buffer_level = starting * bandwidth / 1000;
52  p_rc->optimal_buffer_level =
53  (optimal == 0) ? bandwidth / 8 : optimal * bandwidth / 1000;
54  p_rc->maximum_buffer_size =
55  (maximum == 0) ? bandwidth / 8 : maximum * bandwidth / 1000;
56 
57  // Under a configuration change, where maximum_buffer_size may change,
58  // keep buffer level clipped to the maximum allowed buffer size.
59  p_rc->bits_off_target =
60  AOMMIN(p_rc->bits_off_target, p_rc->maximum_buffer_size);
61  p_rc->buffer_level = AOMMIN(p_rc->buffer_level, p_rc->maximum_buffer_size);
62 }
63 
64 static inline void config_target_level(AV1_COMP *const cpi,
65  AV1_LEVEL target_level, int tier) {
66  AV1EncoderConfig *const oxcf = &cpi->oxcf;
67  SequenceHeader *const seq_params = cpi->common.seq_params;
68  TileConfig *const tile_cfg = &oxcf->tile_cfg;
69  RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
70 
71  // Adjust target bitrate to be no larger than 70% of level limit.
72  const BITSTREAM_PROFILE profile = seq_params->profile;
73  const double level_bitrate_limit =
74  av1_get_max_bitrate_for_level(target_level, tier, profile);
75  const int64_t max_bitrate = (int64_t)(level_bitrate_limit * 0.70);
76  rc_cfg->target_bandwidth = AOMMIN(rc_cfg->target_bandwidth, max_bitrate);
77 #if !CONFIG_REALTIME_ONLY
78  // Also need to update cpi->ppi->twopass.bits_left.
79  TWO_PASS *const twopass = &cpi->ppi->twopass;
80  FIRSTPASS_STATS *stats = twopass->stats_buf_ctx->total_stats;
81  if (stats != NULL)
82  cpi->ppi->twopass.bits_left =
83  (int64_t)(stats->duration * rc_cfg->target_bandwidth / 10000000.0);
84 #endif
85 
86  // Adjust max over-shoot percentage.
87  rc_cfg->over_shoot_pct = 0;
88 
89  // Adjust max quantizer.
90  rc_cfg->worst_allowed_q = 255;
91 
92  // Adjust number of tiles and tile columns to be under level limit.
93  int max_tiles, max_tile_cols;
94  av1_get_max_tiles_for_level(target_level, &max_tiles, &max_tile_cols);
95  while (tile_cfg->tile_columns > 0 &&
96  (1 << tile_cfg->tile_columns) > max_tile_cols) {
97  --tile_cfg->tile_columns;
98  }
99  const int tile_cols = (1 << tile_cfg->tile_columns);
100  while (tile_cfg->tile_rows > 0 &&
101  tile_cols * (1 << tile_cfg->tile_rows) > max_tiles) {
102  --tile_cfg->tile_rows;
103  }
104 
105  // Adjust min compression ratio.
106  const int still_picture = seq_params->still_picture;
107  const double min_cr =
108  av1_get_min_cr_for_level(target_level, tier, still_picture);
109  rc_cfg->min_cr = AOMMAX(rc_cfg->min_cr, (unsigned int)(min_cr * 100));
110 }
111 
112 #if !CONFIG_REALTIME_ONLY
113 
130 static inline int recode_loop_test(AV1_COMP *cpi, int high_limit, int low_limit,
131  int q, int maxq, int minq) {
132  const RATE_CONTROL *const rc = &cpi->rc;
133  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
134  const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
135  int force_recode = 0;
136 
137  if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
138  (cpi->sf.hl_sf.recode_loop == ALLOW_RECODE) ||
139  (frame_is_kfgfarf &&
140  (cpi->sf.hl_sf.recode_loop == ALLOW_RECODE_KFARFGF))) {
141  // TODO(agrange) high_limit could be greater than the scale-down threshold.
142  if ((rc->projected_frame_size > high_limit && q < maxq) ||
143  (rc->projected_frame_size < low_limit && q > minq)) {
144  force_recode = 1;
145  } else if (cpi->oxcf.rc_cfg.mode == AOM_CQ) {
146  // Deal with frame undershoot and whether or not we are
147  // below the automatically set cq level.
148  if (q > oxcf->rc_cfg.cq_level &&
150  (((int64_t)rc->this_frame_target * 7) >> 3)) {
151  force_recode = 1;
152  }
153  }
154  }
155  return force_recode;
156 }
157 
158 static inline double av1_get_gfu_boost_projection_factor(double min_factor,
159  double max_factor,
160  int frame_count) {
161  double factor = sqrt((double)frame_count);
162  factor = AOMMIN(factor, max_factor);
163  factor = AOMMAX(factor, min_factor);
164  factor = (200.0 + 10.0 * factor);
165  return factor;
166 }
167 
168 static inline int get_gfu_boost_from_r0_lap(double min_factor,
169  double max_factor, double r0,
170  int frames_to_key) {
171  double factor = av1_get_gfu_boost_projection_factor(min_factor, max_factor,
172  frames_to_key);
173  const int boost = (int)rint(factor / r0);
174  return boost;
175 }
176 
177 static inline double av1_get_kf_boost_projection_factor(int frame_count) {
178  double factor = sqrt((double)frame_count);
179  factor = AOMMIN(factor, 10.0);
180  factor = AOMMAX(factor, 4.0);
181  factor = (75.0 + 14.0 * factor);
182  return factor;
183 }
184 
185 static inline int get_regulated_q_overshoot(AV1_COMP *const cpi,
186  int is_encode_stage, int q_low,
187  int q_high, int top_index,
188  int bottom_index) {
189  const AV1_COMMON *const cm = &cpi->common;
190  const RATE_CONTROL *const rc = &cpi->rc;
191 
192  av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
193  cm->height);
194 
195  int q_regulated =
196  av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
197  AOMMAX(q_high, top_index), cm->width, cm->height);
198 
199  int retries = 0;
200  while (q_regulated < q_low && retries < 10) {
201  av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
202  cm->height);
203  q_regulated =
204  av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
205  AOMMAX(q_high, top_index), cm->width, cm->height);
206  retries++;
207  }
208  return q_regulated;
209 }
210 
211 static inline int get_regulated_q_undershoot(AV1_COMP *const cpi,
212  int is_encode_stage, int q_high,
213  int top_index, int bottom_index) {
214  const AV1_COMMON *const cm = &cpi->common;
215  const RATE_CONTROL *const rc = &cpi->rc;
216 
217  av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
218  cm->height);
219  int q_regulated = av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
220  top_index, cm->width, cm->height);
221 
222  int retries = 0;
223  while (q_regulated > q_high && retries < 10) {
224  av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
225  cm->height);
226  q_regulated = av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
227  top_index, cm->width, cm->height);
228  retries++;
229  }
230  return q_regulated;
231 }
232 
255 static inline void recode_loop_update_q(
256  AV1_COMP *const cpi, int *const loop, int *const q, int *const q_low,
257  int *const q_high, const int top_index, const int bottom_index,
258  int *const undershoot_seen, int *const overshoot_seen,
259  int *const low_cr_seen, const int loop_count) {
260  AV1_COMMON *const cm = &cpi->common;
261  RATE_CONTROL *const rc = &cpi->rc;
262  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
263  const RateControlCfg *const rc_cfg = &cpi->oxcf.rc_cfg;
264  *loop = 0;
265 
266  // Special case for overlay frame.
267  if (rc->is_src_frame_alt_ref &&
268  rc->projected_frame_size < rc->max_frame_bandwidth)
269  return;
270 
271  const int min_cr = rc_cfg->min_cr;
272  if (min_cr > 0) {
273  const double compression_ratio =
274  av1_get_compression_ratio(cm, rc->projected_frame_size >> 3);
275  const double target_cr = min_cr / 100.0;
276  if (compression_ratio < target_cr) {
277  *low_cr_seen = 1;
278  if (*q < rc->worst_quality) {
279  const double cr_ratio = target_cr / compression_ratio;
280  const int projected_q = AOMMAX(*q + 1, (int)(*q * cr_ratio * cr_ratio));
281  *q = AOMMIN(AOMMIN(projected_q, *q + 32), rc->worst_quality);
282  *q_low = AOMMAX(*q, *q_low);
283  *q_high = AOMMAX(*q, *q_high);
284  *loop = 1;
285  }
286  }
287  if (*low_cr_seen) return;
288  }
289 
290  if (cpi->ppi->level_params.keep_level_stats &&
291  !is_stat_generation_stage(cpi)) {
292  // Initialize level info. at the beginning of each sequence.
293  if (cm->current_frame.frame_type == KEY_FRAME &&
294  cpi->ppi->gf_group.refbuf_state[cpi->gf_frame_index] == REFBUF_RESET) {
295  av1_init_level_info(cpi);
296  }
297  const AV1LevelParams *const level_params = &cpi->ppi->level_params;
298  // TODO(any): currently only checking operating point 0
299  const AV1LevelInfo *const level_info = level_params->level_info[0];
300  const DECODER_MODEL *const decoder_models = level_info->decoder_models;
301  const AV1_LEVEL target_level = level_params->target_seq_level_idx[0];
302 
303  if (target_level < SEQ_LEVELS &&
304  decoder_models[target_level].status == DECODER_MODEL_OK) {
305  DECODER_MODEL_STATUS status = av1_decoder_model_try_smooth_buf(
306  cpi, rc->projected_frame_size, &decoder_models[target_level]);
307 
308  if ((status == SMOOTHING_BUFFER_UNDERFLOW ||
309  status == SMOOTHING_BUFFER_OVERFLOW) &&
310  *q < rc->worst_quality) {
311  *q = AOMMIN(*q + 10, rc->worst_quality);
312  *q_low = AOMMAX(*q, *q_low);
313  *q_high = AOMMAX(*q, *q_high);
314  *loop = 1;
315  return;
316  }
317  }
318  }
319 
320  if (rc_cfg->mode == AOM_Q) return;
321 
322  const int last_q = *q;
323  int frame_over_shoot_limit = 0, frame_under_shoot_limit = 0;
324  av1_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
325  &frame_under_shoot_limit,
326  &frame_over_shoot_limit);
327  if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
328 
329  if (cm->current_frame.frame_type == KEY_FRAME &&
330  p_rc->this_key_frame_forced &&
331  rc->projected_frame_size < rc->max_frame_bandwidth) {
332  int64_t kf_err;
333  const int64_t high_err_target = cpi->ambient_err;
334  const int64_t low_err_target = cpi->ambient_err >> 1;
335 
336 #if CONFIG_AV1_HIGHBITDEPTH
337  if (cm->seq_params->use_highbitdepth) {
338  kf_err = aom_highbd_get_y_sse(cpi->source, &cm->cur_frame->buf);
339  } else {
340  kf_err = aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
341  }
342 #else
343  kf_err = aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
344 #endif
345  // Prevent possible divide by zero error below for perfect KF
346  kf_err += !kf_err;
347 
348  // The key frame is not good enough or we can afford
349  // to make it better without undue risk of popping.
350  if ((kf_err > high_err_target &&
351  rc->projected_frame_size <= frame_over_shoot_limit) ||
352  (kf_err > low_err_target &&
353  rc->projected_frame_size <= frame_under_shoot_limit)) {
354  // Lower q_high
355  *q_high = AOMMAX(*q - 1, *q_low);
356 
357  // Adjust Q
358  *q = (int)((*q * high_err_target) / kf_err);
359  *q = AOMMIN(*q, (*q_high + *q_low) >> 1);
360  } else if (kf_err < low_err_target &&
361  rc->projected_frame_size >= frame_under_shoot_limit) {
362  // The key frame is much better than the previous frame
363  // Raise q_low
364  *q_low = AOMMIN(*q + 1, *q_high);
365 
366  // Adjust Q
367  *q = (int)((*q * low_err_target) / kf_err);
368  *q = AOMMIN(*q, (*q_high + *q_low + 1) >> 1);
369  }
370 
371  // Clamp Q to upper and lower limits:
372  *q = clamp(*q, *q_low, *q_high);
373  *loop = (*q != last_q);
374  return;
375  }
376 
377  if (recode_loop_test(cpi, frame_over_shoot_limit, frame_under_shoot_limit, *q,
378  AOMMAX(*q_high, top_index), bottom_index)) {
379  // Is the projected frame size out of range and are we allowed
380  // to attempt to recode.
381 
382  // Frame size out of permitted range:
383  // Update correction factor & compute new Q to try...
384  // Frame is too large
385  if (rc->projected_frame_size > rc->this_frame_target) {
386  // Special case if the projected size is > the max allowed.
387  if (*q == *q_high &&
388  rc->projected_frame_size >= rc->max_frame_bandwidth) {
389  const double q_val_high_current =
390  av1_convert_qindex_to_q(*q_high, cm->seq_params->bit_depth);
391  const double q_val_high_new =
392  q_val_high_current *
393  ((double)rc->projected_frame_size / rc->max_frame_bandwidth);
394  *q_high = av1_find_qindex(q_val_high_new, cm->seq_params->bit_depth,
395  rc->best_quality, rc->worst_quality);
396  }
397 
398  // Raise Qlow as to at least the current value
399  *q_low = AOMMIN(*q + 1, *q_high);
400 
401  if (*undershoot_seen || loop_count > 2 ||
402  (loop_count == 2 && !frame_is_intra_only(cm))) {
404 
405  *q = (*q_high + *q_low + 1) / 2;
406  } else if (loop_count == 2 && frame_is_intra_only(cm)) {
407  const int q_mid = (*q_high + *q_low + 1) / 2;
408  const int q_regulated = get_regulated_q_overshoot(
409  cpi, 1, *q_low, *q_high, top_index, bottom_index);
410  // Get 'q' in-between 'q_mid' and 'q_regulated' for a smooth
411  // transition between loop_count < 2 and loop_count > 2.
412  *q = (q_mid + q_regulated + 1) / 2;
413  } else {
414  *q = get_regulated_q_overshoot(cpi, 1, *q_low, *q_high, top_index,
415  bottom_index);
416  }
417 
418  *overshoot_seen = 1;
419  } else {
420  // Frame is too small
421  *q_high = AOMMAX(*q - 1, *q_low);
422 
423  if (*overshoot_seen || loop_count > 2 ||
424  (loop_count == 2 && !frame_is_intra_only(cm))) {
426  *q = (*q_high + *q_low) / 2;
427  } else if (loop_count == 2 && frame_is_intra_only(cm)) {
428  const int q_mid = (*q_high + *q_low) / 2;
429  const int q_regulated = get_regulated_q_undershoot(
430  cpi, 1, *q_high, top_index, bottom_index);
431  // Get 'q' in-between 'q_mid' and 'q_regulated' for a smooth
432  // transition between loop_count < 2 and loop_count > 2.
433  *q = (q_mid + q_regulated) / 2;
434 
435  // Special case reset for qlow for constrained quality.
436  // This should only trigger where there is very substantial
437  // undershoot on a frame and the auto cq level is above
438  // the user passsed in value.
439  if (rc_cfg->mode == AOM_CQ && q_regulated < *q_low) {
440  *q_low = *q;
441  }
442  } else {
443  *q = get_regulated_q_undershoot(cpi, 1, *q_high, top_index,
444  bottom_index);
445 
446  // Special case reset for qlow for constrained quality.
447  // This should only trigger where there is very substantial
448  // undershoot on a frame and the auto cq level is above
449  // the user passsed in value.
450  if (rc_cfg->mode == AOM_CQ && *q < *q_low) {
451  *q_low = *q;
452  }
453  }
454 
455  *undershoot_seen = 1;
456  }
457 
458  // Clamp Q to upper and lower limits:
459  *q = clamp(*q, *q_low, *q_high);
460  }
461 
462  *loop = (*q != last_q);
463 }
464 #endif
465 
466 #ifdef __cplusplus
467 } // extern "C"
468 #endif
469 
470 #endif // AOM_AV1_ENCODER_RC_UTILS_H_
RATE_CONTROL rc
Definition: encoder.h:3119
int over_shoot_pct
Definition: encoder.h:579
AV1_COMMON common
Definition: encoder.h:2950
static void recode_loop_update_q(AV1_COMP *const cpi, int *const loop, int *const q, int *const q_low, int *const q_high, const int top_index, const int bottom_index, int *const undershoot_seen, int *const overshoot_seen, int *const low_cr_seen, const int loop_count)
Called after encode_with_recode_loop() has just encoded a frame. This function works out whether we u...
Definition: rc_utils.h:255
int cq_level
Definition: encoder.h:593
RateControlCfg rc_cfg
Definition: encoder.h:966
Rate Control parameters and status.
Definition: ratectrl.h:134
AV1LevelParams level_params
Definition: encoder.h:2735
int av1_rc_regulate_q(const struct AV1_COMP *cpi, int target_bits_per_frame, int active_best_quality, int active_worst_quality, int width, int height)
Estimates q to achieve a target bits per frame.
Encoder rate control configuration parameters.
Definition: encoder.h:514
PRIMARY_RATE_CONTROL p_rc
Definition: encoder.h:2755
int64_t bits_off_target
Definition: ratectrl.h:573
AV1EncoderConfig oxcf
Definition: encoder.h:2955
enum aom_rc_mode mode
Definition: encoder.h:598
YV12_BUFFER_CONFIG * source
Definition: encoder.h:2968
SVC svc
Definition: encoder.h:3467
int64_t starting_buffer_level_ms
Definition: encoder.h:523
Top level primary encoder structure.
Definition: encoder.h:2600
TWO_PASS twopass
Definition: encoder.h:2750
Two pass status and control data.
Definition: firstpass.h:425
static int recode_loop_test(AV1_COMP *cpi, int high_limit, int low_limit, int q, int maxq, int minq)
Function to test for conditions that indicate we should loop back and recode a frame.
Definition: rc_utils.h:130
SPEED_FEATURES sf
Definition: encoder.h:3139
int width
Definition: av1_common_int.h:791
int64_t ambient_err
Definition: encoder.h:3088
int worst_allowed_q
Definition: encoder.h:584
GF_GROUP gf_group
Definition: encoder.h:2720
int64_t buffer_level
Definition: ratectrl.h:552
SequenceHeader * seq_params
Definition: av1_common_int.h:992
AV1_PRIMARY * ppi
Definition: encoder.h:2911
HIGH_LEVEL_SPEED_FEATURES hl_sf
Definition: speed_features.h:2117
int64_t starting_buffer_level
Definition: ratectrl.h:365
Definition: aom_encoder.h:188
int64_t optimal_buffer_level
Definition: ratectrl.h:370
int use_svc
Definition: encoder.h:2770
CurrentFrame current_frame
Definition: av1_common_int.h:770
int projected_frame_size
Definition: ratectrl.h:150
The stucture of acummulated frame stats in the first pass.
Definition: firstpass.h:43
unsigned int min_cr
Definition: encoder.h:563
RefCntBuffer * cur_frame
Definition: av1_common_int.h:848
int64_t maximum_buffer_size_ms
Definition: encoder.h:533
int best_quality
Definition: ratectrl.h:247
int64_t target_bandwidth
Definition: encoder.h:538
double duration
Definition: firstpass.h:148
Top level encoder structure.
Definition: encoder.h:2907
Declares top-level encoder structures and functions.
Top level common structure used by both encoder and decoder.
Definition: av1_common_int.h:766
RECODE_LOOP_TYPE recode_loop
Definition: speed_features.h:421
Definition: aom_encoder.h:189
void av1_rc_update_rate_correction_factors(AV1_COMP *cpi, int is_encode_stage, int width, int height)
Updates the rate correction factor linking Q to output bits.
Definition: ratectrl.c:940
int this_frame_target
Definition: ratectrl.h:145
int64_t optimal_buffer_level_ms
Definition: encoder.h:528
Main encoder configuration data structure.
Definition: encoder.h:944
int height
Definition: av1_common_int.h:792
int64_t maximum_buffer_size
Definition: ratectrl.h:375
Primary Rate Control parameters and status.
Definition: ratectrl.h:313
unsigned char gf_frame_index
Definition: encoder.h:3170
int worst_quality
Definition: ratectrl.h:243