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
19extern "C" {
20#endif
21
22static 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;
36 }
37 }
38 }
39}
40
41static 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;
53 (optimal == 0) ? bandwidth / 8 : optimal * bandwidth / 1000;
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
64static 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 // Also need to update cpi->ppi->twopass.bits_left.
78 TWO_PASS *const twopass = &cpi->ppi->twopass;
79 FIRSTPASS_STATS *stats = twopass->stats_buf_ctx->total_stats;
80 if (stats != NULL)
81 cpi->ppi->twopass.bits_left =
82 (int64_t)(stats->duration * rc_cfg->target_bandwidth / 10000000.0);
83
84 // Adjust max over-shoot percentage.
85 rc_cfg->over_shoot_pct = 0;
86
87 // Adjust max quantizer.
88 rc_cfg->worst_allowed_q = 255;
89
90 // Adjust number of tiles and tile columns to be under level limit.
91 int max_tiles, max_tile_cols;
92 av1_get_max_tiles_for_level(target_level, &max_tiles, &max_tile_cols);
93 while (tile_cfg->tile_columns > 0 &&
94 (1 << tile_cfg->tile_columns) > max_tile_cols) {
95 --tile_cfg->tile_columns;
96 }
97 const int tile_cols = (1 << tile_cfg->tile_columns);
98 while (tile_cfg->tile_rows > 0 &&
99 tile_cols * (1 << tile_cfg->tile_rows) > max_tiles) {
100 --tile_cfg->tile_rows;
101 }
102
103 // Adjust min compression ratio.
104 const int still_picture = seq_params->still_picture;
105 const double min_cr =
106 av1_get_min_cr_for_level(target_level, tier, still_picture);
107 rc_cfg->min_cr = AOMMAX(rc_cfg->min_cr, (unsigned int)(min_cr * 100));
108}
109
110#if !CONFIG_REALTIME_ONLY
111
128static inline int recode_loop_test(AV1_COMP *cpi, int high_limit, int low_limit,
129 int q, int maxq, int minq) {
130 const RATE_CONTROL *const rc = &cpi->rc;
131 const AV1EncoderConfig *const oxcf = &cpi->oxcf;
132 const int frame_is_kfgfarf = frame_is_kf_gf_arf(cpi);
133 int force_recode = 0;
134
135 if ((rc->projected_frame_size >= rc->max_frame_bandwidth) ||
136 (cpi->sf.hl_sf.recode_loop == ALLOW_RECODE) ||
137 (frame_is_kfgfarf &&
138 (cpi->sf.hl_sf.recode_loop == ALLOW_RECODE_KFARFGF))) {
139 // TODO(agrange) high_limit could be greater than the scale-down threshold.
140 if ((rc->projected_frame_size > high_limit && q < maxq) ||
141 (rc->projected_frame_size < low_limit && q > minq)) {
142 force_recode = 1;
143 } else if (cpi->oxcf.rc_cfg.mode == AOM_CQ) {
144 // Deal with frame undershoot and whether or not we are
145 // below the automatically set cq level.
146 if (q > oxcf->rc_cfg.cq_level &&
147 rc->projected_frame_size < ((rc->this_frame_target * 7) >> 3)) {
148 force_recode = 1;
149 }
150 }
151 }
152 return force_recode;
153}
154
155static inline double av1_get_gfu_boost_projection_factor(double min_factor,
156 double max_factor,
157 int frame_count) {
158 double factor = sqrt((double)frame_count);
159 factor = AOMMIN(factor, max_factor);
160 factor = AOMMAX(factor, min_factor);
161 factor = (200.0 + 10.0 * factor);
162 return factor;
163}
164
165static inline int get_gfu_boost_from_r0_lap(double min_factor,
166 double max_factor, double r0,
167 int frames_to_key) {
168 double factor = av1_get_gfu_boost_projection_factor(min_factor, max_factor,
169 frames_to_key);
170 const int boost = (int)rint(factor / r0);
171 return boost;
172}
173
174static inline double av1_get_kf_boost_projection_factor(int frame_count) {
175 double factor = sqrt((double)frame_count);
176 factor = AOMMIN(factor, 10.0);
177 factor = AOMMAX(factor, 4.0);
178 factor = (75.0 + 14.0 * factor);
179 return factor;
180}
181
182static inline int get_regulated_q_overshoot(AV1_COMP *const cpi,
183 int is_encode_stage, int q_low,
184 int q_high, int top_index,
185 int bottom_index) {
186 const AV1_COMMON *const cm = &cpi->common;
187 const RATE_CONTROL *const rc = &cpi->rc;
188
189 av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
190 cm->height);
191
192 int q_regulated =
193 av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
194 AOMMAX(q_high, top_index), cm->width, cm->height);
195
196 int retries = 0;
197 while (q_regulated < q_low && retries < 10) {
198 av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
199 cm->height);
200 q_regulated =
201 av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
202 AOMMAX(q_high, top_index), cm->width, cm->height);
203 retries++;
204 }
205 return q_regulated;
206}
207
208static inline int get_regulated_q_undershoot(AV1_COMP *const cpi,
209 int is_encode_stage, int q_high,
210 int top_index, int bottom_index) {
211 const AV1_COMMON *const cm = &cpi->common;
212 const RATE_CONTROL *const rc = &cpi->rc;
213
214 av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
215 cm->height);
216 int q_regulated = av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
217 top_index, cm->width, cm->height);
218
219 int retries = 0;
220 while (q_regulated > q_high && retries < 10) {
221 av1_rc_update_rate_correction_factors(cpi, is_encode_stage, cm->width,
222 cm->height);
223 q_regulated = av1_rc_regulate_q(cpi, rc->this_frame_target, bottom_index,
224 top_index, cm->width, cm->height);
225 retries++;
226 }
227 return q_regulated;
228}
229
252static inline void recode_loop_update_q(
253 AV1_COMP *const cpi, int *const loop, int *const q, int *const q_low,
254 int *const q_high, const int top_index, const int bottom_index,
255 int *const undershoot_seen, int *const overshoot_seen,
256 int *const low_cr_seen, const int loop_count) {
257 AV1_COMMON *const cm = &cpi->common;
258 RATE_CONTROL *const rc = &cpi->rc;
259 PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
260 const RateControlCfg *const rc_cfg = &cpi->oxcf.rc_cfg;
261 *loop = 0;
262
263 // Special case for overlay frame.
264 if (rc->is_src_frame_alt_ref &&
265 rc->projected_frame_size < rc->max_frame_bandwidth)
266 return;
267
268 const int min_cr = rc_cfg->min_cr;
269 if (min_cr > 0) {
270 const double compression_ratio =
271 av1_get_compression_ratio(cm, rc->projected_frame_size >> 3);
272 const double target_cr = min_cr / 100.0;
273 if (compression_ratio < target_cr) {
274 *low_cr_seen = 1;
275 if (*q < rc->worst_quality) {
276 const double cr_ratio = target_cr / compression_ratio;
277 const int projected_q = AOMMAX(*q + 1, (int)(*q * cr_ratio * cr_ratio));
278 *q = AOMMIN(AOMMIN(projected_q, *q + 32), rc->worst_quality);
279 *q_low = AOMMAX(*q, *q_low);
280 *q_high = AOMMAX(*q, *q_high);
281 *loop = 1;
282 }
283 }
284 if (*low_cr_seen) return;
285 }
286
287 if (cpi->ppi->level_params.keep_level_stats &&
288 !is_stat_generation_stage(cpi)) {
289 // Initialize level info. at the beginning of each sequence.
290 if (cm->current_frame.frame_type == KEY_FRAME &&
291 cpi->ppi->gf_group.refbuf_state[cpi->gf_frame_index] == REFBUF_RESET) {
292 av1_init_level_info(cpi);
293 }
294 const AV1LevelParams *const level_params = &cpi->ppi->level_params;
295 // TODO(any): currently only checking operating point 0
296 const AV1LevelInfo *const level_info = level_params->level_info[0];
297 const DECODER_MODEL *const decoder_models = level_info->decoder_models;
298 const AV1_LEVEL target_level = level_params->target_seq_level_idx[0];
299
300 if (target_level < SEQ_LEVELS &&
301 decoder_models[target_level].status == DECODER_MODEL_OK) {
302 DECODER_MODEL_STATUS status = av1_decoder_model_try_smooth_buf(
303 cpi, rc->projected_frame_size, &decoder_models[target_level]);
304
305 if ((status == SMOOTHING_BUFFER_UNDERFLOW ||
306 status == SMOOTHING_BUFFER_OVERFLOW) &&
307 *q < rc->worst_quality) {
308 *q = AOMMIN(*q + 10, rc->worst_quality);
309 *q_low = AOMMAX(*q, *q_low);
310 *q_high = AOMMAX(*q, *q_high);
311 *loop = 1;
312 return;
313 }
314 }
315 }
316
317 if (rc_cfg->mode == AOM_Q) return;
318
319 const int last_q = *q;
320 int frame_over_shoot_limit = 0, frame_under_shoot_limit = 0;
321 av1_rc_compute_frame_size_bounds(cpi, rc->this_frame_target,
322 &frame_under_shoot_limit,
323 &frame_over_shoot_limit);
324 if (frame_over_shoot_limit == 0) frame_over_shoot_limit = 1;
325
326 if (cm->current_frame.frame_type == KEY_FRAME &&
327 p_rc->this_key_frame_forced &&
328 rc->projected_frame_size < rc->max_frame_bandwidth) {
329 int64_t kf_err;
330 const int64_t high_err_target = cpi->ambient_err;
331 const int64_t low_err_target = cpi->ambient_err >> 1;
332
333#if CONFIG_AV1_HIGHBITDEPTH
334 if (cm->seq_params->use_highbitdepth) {
335 kf_err = aom_highbd_get_y_sse(cpi->source, &cm->cur_frame->buf);
336 } else {
337 kf_err = aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
338 }
339#else
340 kf_err = aom_get_y_sse(cpi->source, &cm->cur_frame->buf);
341#endif
342 // Prevent possible divide by zero error below for perfect KF
343 kf_err += !kf_err;
344
345 // The key frame is not good enough or we can afford
346 // to make it better without undue risk of popping.
347 if ((kf_err > high_err_target &&
348 rc->projected_frame_size <= frame_over_shoot_limit) ||
349 (kf_err > low_err_target &&
350 rc->projected_frame_size <= frame_under_shoot_limit)) {
351 // Lower q_high
352 *q_high = AOMMAX(*q - 1, *q_low);
353
354 // Adjust Q
355 *q = (int)((*q * high_err_target) / kf_err);
356 *q = AOMMIN(*q, (*q_high + *q_low) >> 1);
357 } else if (kf_err < low_err_target &&
358 rc->projected_frame_size >= frame_under_shoot_limit) {
359 // The key frame is much better than the previous frame
360 // Raise q_low
361 *q_low = AOMMIN(*q + 1, *q_high);
362
363 // Adjust Q
364 *q = (int)((*q * low_err_target) / kf_err);
365 *q = AOMMIN(*q, (*q_high + *q_low + 1) >> 1);
366 }
367
368 // Clamp Q to upper and lower limits:
369 *q = clamp(*q, *q_low, *q_high);
370 *loop = (*q != last_q);
371 return;
372 }
373
374 if (recode_loop_test(cpi, frame_over_shoot_limit, frame_under_shoot_limit, *q,
375 AOMMAX(*q_high, top_index), bottom_index)) {
376 // Is the projected frame size out of range and are we allowed
377 // to attempt to recode.
378
379 // Frame size out of permitted range:
380 // Update correction factor & compute new Q to try...
381 // Frame is too large
383 // Special case if the projected size is > the max allowed.
384 if (*q == *q_high &&
385 rc->projected_frame_size >= rc->max_frame_bandwidth) {
386 const double q_val_high_current =
387 av1_convert_qindex_to_q(*q_high, cm->seq_params->bit_depth);
388 const double q_val_high_new =
389 q_val_high_current *
390 ((double)rc->projected_frame_size / rc->max_frame_bandwidth);
391 *q_high = av1_find_qindex(q_val_high_new, cm->seq_params->bit_depth,
392 rc->best_quality, rc->worst_quality);
393 }
394
395 // Raise Qlow as to at least the current value
396 *q_low = AOMMIN(*q + 1, *q_high);
397
398 if (*undershoot_seen || loop_count > 2 ||
399 (loop_count == 2 && !frame_is_intra_only(cm))) {
401
402 *q = (*q_high + *q_low + 1) / 2;
403 } else if (loop_count == 2 && frame_is_intra_only(cm)) {
404 const int q_mid = (*q_high + *q_low + 1) / 2;
405 const int q_regulated = get_regulated_q_overshoot(
406 cpi, 1, *q_low, *q_high, top_index, bottom_index);
407 // Get 'q' in-between 'q_mid' and 'q_regulated' for a smooth
408 // transition between loop_count < 2 and loop_count > 2.
409 *q = (q_mid + q_regulated + 1) / 2;
410 } else {
411 *q = get_regulated_q_overshoot(cpi, 1, *q_low, *q_high, top_index,
412 bottom_index);
413 }
414
415 *overshoot_seen = 1;
416 } else {
417 // Frame is too small
418 *q_high = AOMMAX(*q - 1, *q_low);
419
420 if (*overshoot_seen || loop_count > 2 ||
421 (loop_count == 2 && !frame_is_intra_only(cm))) {
423 *q = (*q_high + *q_low) / 2;
424 } else if (loop_count == 2 && frame_is_intra_only(cm)) {
425 const int q_mid = (*q_high + *q_low) / 2;
426 const int q_regulated = get_regulated_q_undershoot(
427 cpi, 1, *q_high, top_index, bottom_index);
428 // Get 'q' in-between 'q_mid' and 'q_regulated' for a smooth
429 // transition between loop_count < 2 and loop_count > 2.
430 *q = (q_mid + q_regulated) / 2;
431
432 // Special case reset for qlow for constrained quality.
433 // This should only trigger where there is very substantial
434 // undershoot on a frame and the auto cq level is above
435 // the user passsed in value.
436 if (rc_cfg->mode == AOM_CQ && q_regulated < *q_low) {
437 *q_low = *q;
438 }
439 } else {
440 *q = get_regulated_q_undershoot(cpi, 1, *q_high, top_index,
441 bottom_index);
442
443 // Special case reset for qlow for constrained quality.
444 // This should only trigger where there is very substantial
445 // undershoot on a frame and the auto cq level is above
446 // the user passsed in value.
447 if (rc_cfg->mode == AOM_CQ && *q < *q_low) {
448 *q_low = *q;
449 }
450 }
451
452 *undershoot_seen = 1;
453 }
454
455 // Clamp Q to upper and lower limits:
456 *q = clamp(*q, *q_low, *q_high);
457 }
458
459 *loop = (*q != last_q);
460}
461#endif
462
463#ifdef __cplusplus
464} // extern "C"
465#endif
466
467#endif // AOM_AV1_ENCODER_RC_UTILS_H_
Declares top-level encoder structures and functions.
@ AOM_CQ
Definition aom_encoder.h:186
@ AOM_Q
Definition aom_encoder.h:187
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:858
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:128
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:252
Top level common structure used by both encoder and decoder.
Definition av1_common_int.h:757
SequenceHeader * seq_params
Definition av1_common_int.h:983
int width
Definition av1_common_int.h:782
RefCntBuffer * cur_frame
Definition av1_common_int.h:839
CurrentFrame current_frame
Definition av1_common_int.h:761
int height
Definition av1_common_int.h:783
Main encoder configuration data structure.
Definition encoder.h:923
RateControlCfg rc_cfg
Definition encoder.h:945
Top level encoder structure.
Definition encoder.h:2873
RATE_CONTROL rc
Definition encoder.h:3080
int64_t ambient_err
Definition encoder.h:3049
SPEED_FEATURES sf
Definition encoder.h:3100
unsigned char gf_frame_index
Definition encoder.h:3131
AV1EncoderConfig oxcf
Definition encoder.h:2921
AV1_COMMON common
Definition encoder.h:2916
AV1_PRIMARY * ppi
Definition encoder.h:2877
YV12_BUFFER_CONFIG * source
Definition encoder.h:2934
SVC svc
Definition encoder.h:3414
Top level primary encoder structure.
Definition encoder.h:2577
AV1LevelParams level_params
Definition encoder.h:2708
TWO_PASS twopass
Definition encoder.h:2723
PRIMARY_RATE_CONTROL p_rc
Definition encoder.h:2728
int use_svc
Definition encoder.h:2743
GF_GROUP gf_group
Definition encoder.h:2693
The stucture of acummulated frame stats in the first pass.
Definition firstpass.h:43
double duration
Definition firstpass.h:144
RECODE_LOOP_TYPE recode_loop
Definition speed_features.h:414
Primary Rate Control parameters and status.
Definition ratectrl.h:299
int64_t bits_off_target
Definition ratectrl.h:554
int64_t maximum_buffer_size
Definition ratectrl.h:356
int64_t starting_buffer_level
Definition ratectrl.h:346
int64_t buffer_level
Definition ratectrl.h:533
int64_t optimal_buffer_level
Definition ratectrl.h:351
Rate Control parameters and status.
Definition ratectrl.h:134
int best_quality
Definition ratectrl.h:233
int this_frame_target
Definition ratectrl.h:145
int projected_frame_size
Definition ratectrl.h:150
int worst_quality
Definition ratectrl.h:229
Encoder rate control configuration parameters.
Definition encoder.h:521
int worst_allowed_q
Definition encoder.h:591
int over_shoot_pct
Definition encoder.h:586
int64_t maximum_buffer_size_ms
Definition encoder.h:540
unsigned int min_cr
Definition encoder.h:570
enum aom_rc_mode mode
Definition encoder.h:605
int64_t starting_buffer_level_ms
Definition encoder.h:530
int64_t target_bandwidth
Definition encoder.h:545
int64_t optimal_buffer_level_ms
Definition encoder.h:535
int cq_level
Definition encoder.h:600
HIGH_LEVEL_SPEED_FEATURES hl_sf
Definition speed_features.h:1936
Two pass status and control data.
Definition firstpass.h:416