Coverage Report

Created: 2025-12-14 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libavif/ext/aom/av1/encoder/ratectrl.c
Line
Count
Source
1
/*
2
 * Copyright (c) 2016, 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
#include <assert.h>
13
#include <limits.h>
14
#include <math.h>
15
#include <stdint.h>
16
#include <stdio.h>
17
#include <stdlib.h>
18
#include <string.h>
19
20
#include "aom_dsp/aom_dsp_common.h"
21
#include "aom_mem/aom_mem.h"
22
#include "aom_ports/mem.h"
23
#include "aom_ports/aom_once.h"
24
25
#include "av1/common/alloccommon.h"
26
#include "av1/encoder/aq_cyclicrefresh.h"
27
#include "av1/common/common.h"
28
#include "av1/common/entropymode.h"
29
#include "av1/common/quant_common.h"
30
#include "av1/common/seg_common.h"
31
32
#include "av1/encoder/encodemv.h"
33
#include "av1/encoder/encoder_utils.h"
34
#include "av1/encoder/encode_strategy.h"
35
#include "av1/encoder/gop_structure.h"
36
#include "av1/encoder/mcomp.h"
37
#include "av1/encoder/random.h"
38
#include "av1/encoder/ratectrl.h"
39
40
#include "config/aom_dsp_rtcd.h"
41
42
#define USE_UNRESTRICTED_Q_IN_CQ_MODE 0
43
44
// Max rate target for 1080P and below encodes under normal circumstances
45
// (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
46
#define MAX_MB_RATE 250
47
#define MAXRATE_1080P 2025000
48
49
250k
#define MIN_BPB_FACTOR 0.005
50
297k
#define MAX_BPB_FACTOR 50
51
52
0
#define SUPERRES_QADJ_PER_DENOM_KEYFRAME_SOLO 0
53
0
#define SUPERRES_QADJ_PER_DENOM_KEYFRAME 2
54
0
#define SUPERRES_QADJ_PER_DENOM_ARFFRAME 0
55
56
108k
#define FRAME_OVERHEAD_BITS 200
57
#define ASSIGN_MINQ_TABLE(bit_depth, name)                   \
58
105k
  do {                                                       \
59
105k
    switch (bit_depth) {                                     \
60
77.7k
      case AOM_BITS_8: name = name##_8; break;               \
61
13.2k
      case AOM_BITS_10: name = name##_10; break;             \
62
14.9k
      case AOM_BITS_12: name = name##_12; break;             \
63
0
      default:                                               \
64
0
        assert(0 &&                                          \
65
0
               "bit_depth should be AOM_BITS_8, AOM_BITS_10" \
66
0
               " or AOM_BITS_12");                           \
67
0
        name = NULL;                                         \
68
105k
    }                                                        \
69
105k
  } while (0)
70
71
// Tables relating active max Q to active min Q
72
static int kf_low_motion_minq_8[QINDEX_RANGE];
73
static int kf_high_motion_minq_8[QINDEX_RANGE];
74
static int arfgf_low_motion_minq_8[QINDEX_RANGE];
75
static int arfgf_high_motion_minq_8[QINDEX_RANGE];
76
static int inter_minq_8[QINDEX_RANGE];
77
static int rtc_minq_8[QINDEX_RANGE];
78
79
static int kf_low_motion_minq_10[QINDEX_RANGE];
80
static int kf_high_motion_minq_10[QINDEX_RANGE];
81
static int arfgf_low_motion_minq_10[QINDEX_RANGE];
82
static int arfgf_high_motion_minq_10[QINDEX_RANGE];
83
static int inter_minq_10[QINDEX_RANGE];
84
static int rtc_minq_10[QINDEX_RANGE];
85
static int kf_low_motion_minq_12[QINDEX_RANGE];
86
static int kf_high_motion_minq_12[QINDEX_RANGE];
87
static int arfgf_low_motion_minq_12[QINDEX_RANGE];
88
static int arfgf_high_motion_minq_12[QINDEX_RANGE];
89
static int inter_minq_12[QINDEX_RANGE];
90
static int rtc_minq_12[QINDEX_RANGE];
91
92
static int gf_high = 2400;
93
static int gf_low = 300;
94
#ifdef STRICT_RC
95
static int kf_high = 3200;
96
#else
97
static int kf_high = 5000;
98
#endif
99
static int kf_low = 400;
100
101
// How many times less pixels there are to encode given the current scaling.
102
// Temporary replacement for rcf_mult and rate_thresh_mult.
103
static double resize_rate_factor(const FrameDimensionCfg *const frm_dim_cfg,
104
239k
                                 int width, int height) {
105
239k
  return (double)(frm_dim_cfg->width * frm_dim_cfg->height) / (width * height);
106
239k
}
107
108
// Functions to compute the active minq lookup table entries based on a
109
// formulaic approach to facilitate easier adjustment of the Q tables.
110
// The formulae were derived from computing a 3rd order polynomial best
111
// fit to the original data (after plotting real maxq vs minq (not q index))
112
static int get_minq_index(double maxq, double x3, double x2, double x1,
113
4.60k
                          aom_bit_depth_t bit_depth) {
114
4.60k
  const double minqtarget = AOMMIN(((x3 * maxq + x2) * maxq + x1) * maxq, maxq);
115
116
  // Special case handling to deal with the step from q2.0
117
  // down to lossless mode represented by q 1.0.
118
4.60k
  if (minqtarget <= 2.0) return 0;
119
120
4.20k
  return av1_find_qindex(minqtarget, bit_depth, 0, QINDEX_RANGE - 1);
121
4.60k
}
122
123
static void init_minq_luts(int *kf_low_m, int *kf_high_m, int *arfgf_low,
124
                           int *arfgf_high, int *inter, int *rtc,
125
3
                           aom_bit_depth_t bit_depth) {
126
3
  int i;
127
771
  for (i = 0; i < QINDEX_RANGE; i++) {
128
768
    const double maxq = av1_convert_qindex_to_q(i, bit_depth);
129
768
    kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
130
768
    kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.45, bit_depth);
131
768
    arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
132
768
    arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
133
768
    inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.90, bit_depth);
134
768
    rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
135
768
  }
136
3
}
137
138
1
static void rc_init_minq_luts(void) {
139
1
  init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
140
1
                 arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
141
1
                 inter_minq_8, rtc_minq_8, AOM_BITS_8);
142
1
  init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
143
1
                 arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
144
1
                 inter_minq_10, rtc_minq_10, AOM_BITS_10);
145
1
  init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
146
1
                 arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
147
1
                 inter_minq_12, rtc_minq_12, AOM_BITS_12);
148
1
}
149
150
22.4k
void av1_rc_init_minq_luts(void) { aom_once(rc_init_minq_luts); }
151
152
// These functions use formulaic calculations to make playing with the
153
// quantizer tables easier. If necessary they can be replaced by lookup
154
// tables if and when things settle down in the experimental bitstream
155
1.57M
double av1_convert_qindex_to_q(int qindex, aom_bit_depth_t bit_depth) {
156
  // Convert the index to a real Q value (scaled down to match old Q values)
157
1.57M
  switch (bit_depth) {
158
1.17M
    case AOM_BITS_8: return av1_ac_quant_QTX(qindex, 0, bit_depth) / 4.0;
159
204k
    case AOM_BITS_10: return av1_ac_quant_QTX(qindex, 0, bit_depth) / 16.0;
160
202k
    case AOM_BITS_12: return av1_ac_quant_QTX(qindex, 0, bit_depth) / 64.0;
161
0
    default:
162
0
      assert(0 && "bit_depth should be AOM_BITS_8, AOM_BITS_10 or AOM_BITS_12");
163
0
      return -1.0;
164
1.57M
  }
165
1.57M
}
166
167
0
int av1_convert_q_to_qindex(double q, aom_bit_depth_t bit_depth) {
168
0
  int qindex = MINQ;
169
170
  // Find the first qindex that matches or exceeds q.
171
  // Note: this operation can also be done with a binary search, as
172
  // av1_convert_qindex_to_q() is monotonically increasing with respect to
173
  // increasing qindex.
174
0
  while (qindex < MAXQ && av1_convert_qindex_to_q(qindex, bit_depth) < q) {
175
0
    qindex++;
176
0
  }
177
178
0
  return qindex;
179
0
}
180
181
// Gets the appropriate bpmb enumerator based on the frame and content type
182
static int get_bpmb_enumerator(FRAME_TYPE frame_type,
183
229k
                               const int is_screen_content_type) {
184
229k
  int enumerator;
185
186
229k
  if (is_screen_content_type) {
187
0
    enumerator = (frame_type == KEY_FRAME) ? 1000000 : 750000;
188
229k
  } else {
189
229k
    enumerator = (frame_type == KEY_FRAME) ? 2000000 : 1500000;
190
229k
  }
191
192
229k
  return enumerator;
193
229k
}
194
195
0
static int get_init_ratio(double sse) { return (int)(300000 / sse); }
196
197
// Adjustment based on spatial content and last encoded keyframe.
198
// Allow for increase in enumerator to reduce overshoot.
199
0
static int adjust_rtc_keyframe(const RATE_CONTROL *rc, int enumerator) {
200
  // Don't adjust if most of the image is flat.
201
0
  if (rc->perc_spatial_flat_blocks > 70) return enumerator;
202
0
  if (rc->last_encoded_size_keyframe == 0 ||
203
0
      rc->frames_since_scene_change < rc->frames_since_key) {
204
    // Very first frame, or if scene change happened after last keyframe.
205
0
    if (rc->frame_spatial_variance > 1000 ||
206
0
        (rc->frame_spatial_variance > 500 && rc->perc_spatial_flat_blocks == 0))
207
0
      return enumerator << 3;
208
0
    else if (rc->frame_spatial_variance > 500 &&
209
0
             rc->perc_spatial_flat_blocks < 10)
210
0
      return enumerator << 2;
211
0
    else if (rc->frame_spatial_variance > 400)
212
0
      return enumerator << 1;
213
0
  } else if (rc->frames_since_scene_change >= rc->frames_since_key) {
214
    // There was no scene change before previous encoded keyframe, so
215
    // use the last_encoded/target_size_keyframe.
216
0
    if (rc->last_encoded_size_keyframe > 4 * rc->last_target_size_keyframe &&
217
0
        rc->frame_spatial_variance > 500)
218
0
      return enumerator << 3;
219
0
    else if (rc->last_encoded_size_keyframe >
220
0
                 2 * rc->last_target_size_keyframe &&
221
0
             rc->frame_spatial_variance > 200)
222
0
      return enumerator << 2;
223
0
    else if (rc->last_encoded_size_keyframe > rc->last_target_size_keyframe)
224
0
      return enumerator << 1;
225
0
  }
226
0
  return enumerator;
227
0
}
228
229
int av1_rc_bits_per_mb(const AV1_COMP *cpi, FRAME_TYPE frame_type, int qindex,
230
229k
                       double correction_factor, int accurate_estimate) {
231
229k
  const AV1_COMMON *const cm = &cpi->common;
232
229k
  const int is_screen_content_type = cpi->is_screen_content_type;
233
229k
  const aom_bit_depth_t bit_depth = cm->seq_params->bit_depth;
234
229k
  const double q = av1_convert_qindex_to_q(qindex, bit_depth);
235
229k
  int enumerator = get_bpmb_enumerator(frame_type, is_screen_content_type);
236
237
229k
  assert(correction_factor <= MAX_BPB_FACTOR &&
238
229k
         correction_factor >= MIN_BPB_FACTOR);
239
240
229k
  if (cpi->oxcf.rc_cfg.mode == AOM_CBR && frame_type != KEY_FRAME &&
241
62.0k
      accurate_estimate && cpi->rec_sse != UINT64_MAX) {
242
0
    const int mbs = cm->mi_params.MBs;
243
0
    const double sse_sqrt =
244
0
        (double)((int)sqrt((double)(cpi->rec_sse)) << BPER_MB_NORMBITS) /
245
0
        (double)mbs;
246
0
    const int ratio = (cpi->rc.bit_est_ratio == 0) ? get_init_ratio(sse_sqrt)
247
0
                                                   : cpi->rc.bit_est_ratio;
248
    // Clamp the enumerator to lower the q fluctuations.
249
0
    enumerator = clamp((int)(ratio * sse_sqrt), 20000, 170000);
250
229k
  } else if (cpi->oxcf.rc_cfg.mode == AOM_CBR && frame_type == KEY_FRAME &&
251
80.3k
             cpi->sf.rt_sf.rc_adjust_keyframe && bit_depth == 8 &&
252
0
             cpi->oxcf.rc_cfg.max_intra_bitrate_pct > 0 &&
253
0
             cpi->svc.spatial_layer_id == 0) {
254
0
    enumerator = adjust_rtc_keyframe(&cpi->rc, enumerator);
255
0
  }
256
  // q based adjustment to baseline enumerator
257
229k
  return (int)(enumerator * correction_factor / q);
258
229k
}
259
260
int av1_estimate_bits_at_q(const AV1_COMP *cpi, int q,
261
108k
                           double correction_factor) {
262
108k
  const AV1_COMMON *const cm = &cpi->common;
263
108k
  const FRAME_TYPE frame_type = cm->current_frame.frame_type;
264
108k
  const int mbs = cm->mi_params.MBs;
265
108k
  const int bpm =
266
108k
      (int)(av1_rc_bits_per_mb(cpi, frame_type, q, correction_factor,
267
108k
                               cpi->sf.hl_sf.accurate_bit_estimate));
268
108k
  return AOMMAX(FRAME_OVERHEAD_BITS,
269
108k
                (int)((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS);
270
108k
}
271
272
static int clamp_pframe_target_size(const AV1_COMP *const cpi, int64_t target,
273
19.2k
                                    FRAME_UPDATE_TYPE frame_update_type) {
274
19.2k
  const RATE_CONTROL *rc = &cpi->rc;
275
19.2k
  const RateControlCfg *const rc_cfg = &cpi->oxcf.rc_cfg;
276
19.2k
  const int min_frame_target =
277
19.2k
      AOMMAX(rc->min_frame_bandwidth, rc->avg_frame_bandwidth >> 5);
278
  // Clip the frame target to the minimum setup value.
279
19.2k
  if (frame_update_type == OVERLAY_UPDATE ||
280
19.2k
      frame_update_type == INTNL_OVERLAY_UPDATE) {
281
    // If there is an active ARF at this location use the minimum
282
    // bits on this frame even if it is a constructed arf.
283
    // The active maximum quantizer insures that an appropriate
284
    // number of bits will be spent if needed for constructed ARFs.
285
0
    target = min_frame_target;
286
19.2k
  } else if (target < min_frame_target) {
287
19.2k
    target = min_frame_target;
288
19.2k
  }
289
290
  // Clip the frame target to the maximum allowed value.
291
19.2k
  if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
292
19.2k
  if (rc_cfg->max_inter_bitrate_pct) {
293
0
    const int64_t max_rate =
294
0
        (int64_t)rc->avg_frame_bandwidth * rc_cfg->max_inter_bitrate_pct / 100;
295
0
    target = AOMMIN(target, max_rate);
296
0
  }
297
298
19.2k
  return (int)target;
299
19.2k
}
300
301
128k
static int clamp_iframe_target_size(const AV1_COMP *const cpi, int64_t target) {
302
128k
  const RATE_CONTROL *rc = &cpi->rc;
303
128k
  const RateControlCfg *const rc_cfg = &cpi->oxcf.rc_cfg;
304
128k
  if (rc_cfg->max_intra_bitrate_pct) {
305
0
    const int64_t max_rate =
306
0
        (int64_t)rc->avg_frame_bandwidth * rc_cfg->max_intra_bitrate_pct / 100;
307
0
    target = AOMMIN(target, max_rate);
308
0
  }
309
128k
  if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
310
128k
  return (int)target;
311
128k
}
312
313
// Update the buffer level for higher temporal layers, given the encoded current
314
// temporal layer.
315
static void update_layer_buffer_level(SVC *svc, int encoded_frame_size,
316
0
                                      bool is_screen) {
317
0
  const int current_temporal_layer = svc->temporal_layer_id;
318
0
  for (int i = current_temporal_layer + 1; i < svc->number_temporal_layers;
319
0
       ++i) {
320
0
    const int layer =
321
0
        LAYER_IDS_TO_IDX(svc->spatial_layer_id, i, svc->number_temporal_layers);
322
0
    LAYER_CONTEXT *lc = &svc->layer_context[layer];
323
0
    PRIMARY_RATE_CONTROL *lp_rc = &lc->p_rc;
324
0
    lp_rc->bits_off_target +=
325
0
        (int)round(lc->target_bandwidth / lc->framerate) - encoded_frame_size;
326
    // Clip buffer level to maximum buffer size for the layer.
327
0
    lp_rc->bits_off_target =
328
0
        AOMMIN(lp_rc->bits_off_target, lp_rc->maximum_buffer_size);
329
0
    lp_rc->buffer_level = lp_rc->bits_off_target;
330
331
    // For screen-content mode: don't let buffer level go below threshold,
332
    // given here as -rc->maximum_ buffer_size, to allow buffer to come back
333
    // up sooner after slide change with big overshoot.
334
0
    if (is_screen) {
335
0
      lp_rc->bits_off_target =
336
0
          AOMMAX(lp_rc->bits_off_target, -lp_rc->maximum_buffer_size);
337
0
      lp_rc->buffer_level = lp_rc->bits_off_target;
338
0
    }
339
0
  }
340
0
}
341
// Update the buffer level: leaky bucket model.
342
108k
static void update_buffer_level(AV1_COMP *cpi, int encoded_frame_size) {
343
108k
  const AV1_COMMON *const cm = &cpi->common;
344
108k
  RATE_CONTROL *const rc = &cpi->rc;
345
108k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
346
347
  // Non-viewable frames are a special case and are treated as pure overhead.
348
108k
  if (!cm->show_frame)
349
0
    p_rc->bits_off_target -= encoded_frame_size;
350
108k
  else
351
108k
    p_rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
352
353
  // Clip the buffer level to the maximum specified buffer size.
354
108k
  p_rc->bits_off_target =
355
108k
      AOMMIN(p_rc->bits_off_target, p_rc->maximum_buffer_size);
356
  // For screen-content mode: don't let buffer level go below threshold,
357
  // given here as -rc->maximum_ buffer_size, to allow buffer to come back
358
  // up sooner after slide change with big overshoot.
359
108k
  if (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN)
360
0
    p_rc->bits_off_target =
361
0
        AOMMAX(p_rc->bits_off_target, -p_rc->maximum_buffer_size);
362
108k
  p_rc->buffer_level = p_rc->bits_off_target;
363
364
108k
  if (cpi->ppi->use_svc)
365
0
    update_layer_buffer_level(&cpi->svc, encoded_frame_size,
366
0
                              cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN);
367
368
#if CONFIG_FPMT_TEST
369
  /* The variable temp_buffer_level is introduced for quality
370
   * simulation purpose, it retains the value previous to the parallel
371
   * encode frames. The variable is updated based on the update flag.
372
   *
373
   * If there exist show_existing_frames between parallel frames, then to
374
   * retain the temp state do not update it. */
375
  int show_existing_between_parallel_frames =
376
      (cpi->ppi->gf_group.update_type[cpi->gf_frame_index] ==
377
           INTNL_OVERLAY_UPDATE &&
378
       cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index + 1] == 2);
379
380
  if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
381
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) {
382
    p_rc->temp_buffer_level = p_rc->buffer_level;
383
  }
384
#endif
385
108k
}
386
387
int av1_rc_get_default_min_gf_interval(int width, int height,
388
336k
                                       double framerate) {
389
  // Assume we do not need any constraint lower than 4K 20 fps
390
336k
  static const double factor_safe = 3840 * 2160 * 20.0;
391
336k
  const double factor = (double)width * height * framerate;
392
336k
  const int default_interval =
393
336k
      clamp((int)(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
394
395
336k
  if (factor <= factor_safe)
396
336k
    return default_interval;
397
0
  else
398
0
    return AOMMAX(default_interval,
399
336k
                  (int)(MIN_GF_INTERVAL * factor / factor_safe + 0.5));
400
  // Note this logic makes:
401
  // 4K24: 5
402
  // 4K30: 6
403
  // 4K60: 12
404
336k
}
405
406
// Note get_default_max_gf_interval() requires the min_gf_interval to
407
// be passed in to ensure that the max_gf_interval returned is at least as big
408
// as that.
409
336k
static int get_default_max_gf_interval(double framerate, int min_gf_interval) {
410
336k
  int interval = AOMMIN(MAX_GF_INTERVAL, (int)(framerate * 0.75));
411
336k
  interval += (interval & 0x01);  // Round to even value
412
336k
  interval = AOMMAX(MAX_GF_INTERVAL, interval);
413
336k
  return AOMMAX(interval, min_gf_interval);
414
336k
}
415
416
void av1_primary_rc_init(const AV1EncoderConfig *oxcf,
417
66.8k
                         PRIMARY_RATE_CONTROL *p_rc) {
418
66.8k
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
419
420
66.8k
  int worst_allowed_q = rc_cfg->worst_allowed_q;
421
422
66.8k
  int min_gf_interval = oxcf->gf_cfg.min_gf_interval;
423
66.8k
  int max_gf_interval = oxcf->gf_cfg.max_gf_interval;
424
66.8k
  if (min_gf_interval == 0)
425
66.8k
    min_gf_interval = av1_rc_get_default_min_gf_interval(
426
66.8k
        oxcf->frm_dim_cfg.width, oxcf->frm_dim_cfg.height,
427
66.8k
        oxcf->input_cfg.init_framerate);
428
66.8k
  if (max_gf_interval == 0)
429
66.8k
    max_gf_interval = get_default_max_gf_interval(
430
66.8k
        oxcf->input_cfg.init_framerate, min_gf_interval);
431
66.8k
  p_rc->baseline_gf_interval = (min_gf_interval + max_gf_interval) / 2;
432
66.8k
  p_rc->this_key_frame_forced = 0;
433
66.8k
  p_rc->next_key_frame_forced = 0;
434
66.8k
  p_rc->ni_frames = 0;
435
436
66.8k
  p_rc->tot_q = 0.0;
437
66.8k
  p_rc->total_actual_bits = 0;
438
66.8k
  p_rc->total_target_bits = 0;
439
66.8k
  p_rc->buffer_level = p_rc->starting_buffer_level;
440
441
66.8k
  if (oxcf->target_seq_level_idx[0] < SEQ_LEVELS) {
442
0
    worst_allowed_q = 255;
443
0
  }
444
66.8k
  if (oxcf->pass == AOM_RC_ONE_PASS && rc_cfg->mode == AOM_CBR) {
445
7.30k
    p_rc->avg_frame_qindex[KEY_FRAME] = worst_allowed_q;
446
7.30k
    p_rc->avg_frame_qindex[INTER_FRAME] = worst_allowed_q;
447
59.5k
  } else {
448
59.5k
    p_rc->avg_frame_qindex[KEY_FRAME] =
449
59.5k
        (worst_allowed_q + rc_cfg->best_allowed_q) / 2;
450
59.5k
    p_rc->avg_frame_qindex[INTER_FRAME] =
451
59.5k
        (worst_allowed_q + rc_cfg->best_allowed_q) / 2;
452
59.5k
  }
453
66.8k
  p_rc->avg_q = av1_convert_qindex_to_q(rc_cfg->worst_allowed_q,
454
66.8k
                                        oxcf->tool_cfg.bit_depth);
455
66.8k
  p_rc->last_q[KEY_FRAME] = rc_cfg->best_allowed_q;
456
66.8k
  p_rc->last_q[INTER_FRAME] = rc_cfg->worst_allowed_q;
457
458
334k
  for (int i = 0; i < RATE_FACTOR_LEVELS; ++i) {
459
267k
    p_rc->rate_correction_factors[i] = 0.7;
460
267k
  }
461
66.8k
  p_rc->rate_correction_factors[KF_STD] = 1.0;
462
66.8k
  p_rc->bits_off_target = p_rc->starting_buffer_level;
463
464
66.8k
  p_rc->rolling_target_bits = AOMMAX(
465
66.8k
      1, (int)(oxcf->rc_cfg.target_bandwidth / oxcf->input_cfg.init_framerate));
466
66.8k
  p_rc->rolling_actual_bits = AOMMAX(
467
66.8k
      1, (int)(oxcf->rc_cfg.target_bandwidth / oxcf->input_cfg.init_framerate));
468
66.8k
}
469
470
73.7k
void av1_rc_init(const AV1EncoderConfig *oxcf, RATE_CONTROL *rc) {
471
73.7k
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
472
473
73.7k
  rc->frames_since_key = 8;  // Sensible default for first frame.
474
73.7k
  rc->frames_to_fwd_kf = oxcf->kf_cfg.fwd_kf_dist;
475
476
73.7k
  rc->frames_till_gf_update_due = 0;
477
73.7k
  rc->ni_av_qi = rc_cfg->worst_allowed_q;
478
73.7k
  rc->ni_tot_qi = 0;
479
480
73.7k
  rc->min_gf_interval = oxcf->gf_cfg.min_gf_interval;
481
73.7k
  rc->max_gf_interval = oxcf->gf_cfg.max_gf_interval;
482
73.7k
  if (rc->min_gf_interval == 0)
483
73.7k
    rc->min_gf_interval = av1_rc_get_default_min_gf_interval(
484
73.7k
        oxcf->frm_dim_cfg.width, oxcf->frm_dim_cfg.height,
485
73.7k
        oxcf->input_cfg.init_framerate);
486
73.7k
  if (rc->max_gf_interval == 0)
487
73.7k
    rc->max_gf_interval = get_default_max_gf_interval(
488
73.7k
        oxcf->input_cfg.init_framerate, rc->min_gf_interval);
489
73.7k
  rc->avg_frame_low_motion = 0;
490
491
73.7k
  rc->resize_state = ORIG;
492
73.7k
  rc->resize_avg_qp = 0;
493
73.7k
  rc->resize_buffer_underflow = 0;
494
73.7k
  rc->resize_count = 0;
495
73.7k
  rc->rtc_external_ratectrl = 0;
496
73.7k
  rc->frame_level_fast_extra_bits = 0;
497
73.7k
  rc->use_external_qp_one_pass = 0;
498
73.7k
  rc->percent_blocks_inactive = 0;
499
73.7k
  rc->force_max_q = 0;
500
73.7k
  rc->postencode_drop = 0;
501
73.7k
  rc->frames_since_scene_change = 0;
502
73.7k
}
503
504
static bool check_buffer_below_thresh(AV1_COMP *cpi, int64_t buffer_level,
505
0
                                      int drop_mark) {
506
0
  SVC *svc = &cpi->svc;
507
0
  if (!cpi->ppi->use_svc || cpi->svc.number_spatial_layers == 1 ||
508
0
      cpi->svc.framedrop_mode == AOM_LAYER_DROP) {
509
0
    return (buffer_level <= drop_mark);
510
0
  } else {
511
    // For SVC in the AOM_FULL_SUPERFRAME_DROP): the condition on
512
    // buffer is checked on current and upper spatial layers.
513
0
    for (int i = svc->spatial_layer_id; i < svc->number_spatial_layers; ++i) {
514
0
      const int layer = LAYER_IDS_TO_IDX(i, svc->temporal_layer_id,
515
0
                                         svc->number_temporal_layers);
516
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
517
0
      PRIMARY_RATE_CONTROL *lrc = &lc->p_rc;
518
      // Exclude check for layer whose bitrate is 0.
519
0
      if (lc->target_bandwidth > 0) {
520
0
        const int drop_thresh = cpi->oxcf.rc_cfg.drop_frames_water_mark;
521
0
        const int drop_mark_layer =
522
0
            (int)(drop_thresh * lrc->optimal_buffer_level / 100);
523
0
        if (lrc->buffer_level <= drop_mark_layer) return true;
524
0
      }
525
0
    }
526
0
    return false;
527
0
  }
528
0
}
529
530
21.6k
int av1_rc_drop_frame(AV1_COMP *cpi) {
531
21.6k
  const AV1EncoderConfig *oxcf = &cpi->oxcf;
532
21.6k
  RATE_CONTROL *const rc = &cpi->rc;
533
21.6k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
534
#if CONFIG_FPMT_TEST
535
  const int simulate_parallel_frame =
536
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
537
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
538
  int64_t buffer_level =
539
      simulate_parallel_frame ? p_rc->temp_buffer_level : p_rc->buffer_level;
540
#else
541
21.6k
  int64_t buffer_level = p_rc->buffer_level;
542
21.6k
#endif
543
  // Never drop on key frame, or for frame whose base layer is key.
544
  // If drop_count_consec hits or exceeds max_consec_drop then don't drop.
545
21.6k
  if (cpi->common.current_frame.frame_type == KEY_FRAME ||
546
10.2k
      (cpi->ppi->use_svc &&
547
0
       cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame) ||
548
10.2k
      !oxcf->rc_cfg.drop_frames_water_mark ||
549
0
      (rc->max_consec_drop > 0 &&
550
21.6k
       rc->drop_count_consec >= rc->max_consec_drop)) {
551
21.6k
    return 0;
552
21.6k
  } else {
553
0
    SVC *svc = &cpi->svc;
554
    // In the full_superframe framedrop mode for svc, if the previous spatial
555
    // layer was dropped, drop the current spatial layer.
556
0
    if (cpi->ppi->use_svc && svc->spatial_layer_id > 0 &&
557
0
        svc->drop_spatial_layer[svc->spatial_layer_id - 1] &&
558
0
        svc->framedrop_mode == AOM_FULL_SUPERFRAME_DROP)
559
0
      return 1;
560
    // -1 is passed here for drop_mark since we are checking if
561
    // buffer goes below 0 (<= -1).
562
0
    if (check_buffer_below_thresh(cpi, buffer_level, -1)) {
563
      // Always drop if buffer is below 0.
564
0
      rc->drop_count_consec++;
565
0
      return 1;
566
0
    } else {
567
      // If buffer is below drop_mark, for now just drop every other frame
568
      // (starting with the next frame) until it increases back over drop_mark.
569
0
      const int drop_mark = (int)(oxcf->rc_cfg.drop_frames_water_mark *
570
0
                                  p_rc->optimal_buffer_level / 100);
571
0
      const bool buffer_below_thresh =
572
0
          check_buffer_below_thresh(cpi, buffer_level, drop_mark);
573
0
      if (!buffer_below_thresh && rc->decimation_factor > 0) {
574
0
        --rc->decimation_factor;
575
0
      } else if (buffer_below_thresh && rc->decimation_factor == 0) {
576
0
        rc->decimation_factor = 1;
577
0
      }
578
0
      if (rc->decimation_factor > 0) {
579
0
        if (rc->decimation_count > 0) {
580
0
          --rc->decimation_count;
581
0
          rc->drop_count_consec++;
582
0
          return 1;
583
0
        } else {
584
0
          rc->decimation_count = rc->decimation_factor;
585
0
          return 0;
586
0
        }
587
0
      } else {
588
0
        rc->decimation_count = 0;
589
0
        return 0;
590
0
      }
591
0
    }
592
0
  }
593
21.6k
}
594
595
static int adjust_q_cbr(const AV1_COMP *cpi, int q, int active_worst_quality,
596
21.6k
                        int width, int height) {
597
21.6k
  const RATE_CONTROL *const rc = &cpi->rc;
598
21.6k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
599
21.6k
  const AV1_COMMON *const cm = &cpi->common;
600
21.6k
  const SVC *const svc = &cpi->svc;
601
21.6k
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
602
  // Flag to indicate previous frame has overshoot, and buffer level
603
  // for current frame is low (less than ~half of optimal). For such
604
  // (inter) frames, if the source_sad is non-zero, relax the max_delta_up
605
  // and clamp applied below.
606
21.6k
  const bool overshoot_buffer_low =
607
21.6k
      cpi->rc.rc_1_frame == -1 && rc->frame_source_sad > 1000 &&
608
6.60k
      p_rc->buffer_level < (p_rc->optimal_buffer_level >> 1) &&
609
999
      rc->frames_since_key > 4;
610
21.6k
  int max_delta_down;
611
21.6k
  int max_delta_up = overshoot_buffer_low ? 120 : 20;
612
21.6k
  const int change_avg_frame_bandwidth =
613
21.6k
      abs(rc->avg_frame_bandwidth - rc->prev_avg_frame_bandwidth) >
614
21.6k
      0.1 * (rc->avg_frame_bandwidth);
615
616
  // Set the maximum adjustment down for Q for this frame.
617
21.6k
  if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
618
0
      cpi->cyclic_refresh->apply_cyclic_refresh) {
619
    // For static screen type content limit the Q drop till the start of the
620
    // next refresh cycle.
621
0
    if (cpi->is_screen_content_type &&
622
0
        (cpi->cyclic_refresh->sb_index > cpi->cyclic_refresh->last_sb_index)) {
623
0
      max_delta_down = clamp(rc->q_1_frame / 32, 1, 8);
624
0
    } else {
625
0
      max_delta_down = clamp(rc->q_1_frame / 8, 1, 16);
626
0
    }
627
0
    if (!cpi->ppi->use_svc && cpi->is_screen_content_type) {
628
      // Link max_delta_up to max_delta_down and buffer status.
629
0
      if (p_rc->buffer_level > p_rc->optimal_buffer_level) {
630
0
        max_delta_up = AOMMAX(4, max_delta_down);
631
0
      } else if (!overshoot_buffer_low) {
632
0
        max_delta_up = AOMMAX(8, max_delta_down);
633
0
      }
634
0
    }
635
21.6k
  } else {
636
21.6k
    max_delta_down = cpi->is_screen_content_type
637
21.6k
                         ? clamp(rc->q_1_frame / 16, 1, 8)
638
21.6k
                         : clamp(rc->q_1_frame / 8, 1, 16);
639
21.6k
  }
640
  // For screen static content with stable buffer level: relax the
641
  // limit on max_delta_down and apply bias qp, based on buffer fullness.
642
  // Only for high speeds levels for now to avoid bdrate regression.
643
21.6k
  if (cpi->sf.rt_sf.rc_faster_convergence_static == 1 &&
644
0
      cpi->sf.rt_sf.check_scene_detection && rc->frame_source_sad == 0 &&
645
0
      rc->static_since_last_scene_change &&
646
0
      p_rc->buffer_level > (p_rc->optimal_buffer_level >> 1) &&
647
0
      cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
648
0
      cpi->cyclic_refresh->counter_encode_maxq_scene_change > 4) {
649
0
    int qp_delta = 32;
650
0
    int qp_bias = 16;
651
0
    if (p_rc->buffer_level > p_rc->optimal_buffer_level) {
652
0
      qp_delta = 60;
653
0
      qp_bias = 32;
654
0
    }
655
0
    if (cpi->rc.rc_1_frame == 1) q = q - qp_bias;
656
0
    max_delta_down = AOMMAX(max_delta_down, qp_delta);
657
0
    max_delta_up = AOMMIN(max_delta_up, 4);
658
0
  }
659
660
  // If resolution changes or avg_frame_bandwidth significantly changed,
661
  // then set this flag to indicate change in target bits per macroblock.
662
21.6k
  const int change_target_bits_mb =
663
21.6k
      cm->prev_frame &&
664
10.2k
      (width != cm->prev_frame->width || height != cm->prev_frame->height ||
665
10.2k
       change_avg_frame_bandwidth);
666
  // Apply some control/clamp to QP under certain conditions.
667
  // Delay the use of the clamping for svc until after num_temporal_layers,
668
  // to make they have been set for each temporal layer.
669
  // Check for rc->q_1/2_frame > 0 in case they have not been set due to
670
  // dropped frames.
671
21.6k
  if (!frame_is_intra_only(cm) && rc->frames_since_key > 1 &&
672
4.68k
      rc->q_1_frame > 0 && rc->q_2_frame > 0 &&
673
4.48k
      (!cpi->ppi->use_svc ||
674
0
       svc->current_superframe > (unsigned int)svc->number_temporal_layers) &&
675
4.48k
      !change_target_bits_mb && !cpi->rc.rtc_external_ratectrl &&
676
4.48k
      (!cpi->oxcf.rc_cfg.gf_cbr_boost_pct ||
677
4.48k
       !(refresh_frame->alt_ref_frame || refresh_frame->golden_frame))) {
678
    // If in the previous two frames we have seen both overshoot and undershoot
679
    // clamp Q between the two.
680
4.48k
    if (rc->rc_1_frame * rc->rc_2_frame == -1 &&
681
108
        rc->q_1_frame != rc->q_2_frame && !overshoot_buffer_low) {
682
51
      int qclamp = clamp(q, AOMMIN(rc->q_1_frame, rc->q_2_frame),
683
51
                         AOMMAX(rc->q_1_frame, rc->q_2_frame));
684
      // If the previous frame had overshoot and the current q needs to
685
      // increase above the clamped value, reduce the clamp for faster reaction
686
      // to overshoot.
687
51
      if (cpi->rc.rc_1_frame == -1 && q > qclamp && rc->frames_since_key > 10)
688
0
        q = (q + qclamp) >> 1;
689
51
      else
690
51
        q = qclamp;
691
51
    }
692
    // Adjust Q base on source content change from scene detection.
693
4.48k
    if (cpi->sf.rt_sf.check_scene_detection && rc->prev_avg_source_sad > 0 &&
694
4.44k
        rc->frames_since_key > 10 && rc->frame_source_sad > 0 &&
695
0
        !cpi->rc.rtc_external_ratectrl) {
696
0
      const int bit_depth = cm->seq_params->bit_depth;
697
0
      double delta =
698
0
          (double)rc->avg_source_sad / (double)rc->prev_avg_source_sad - 1.0;
699
      // Push Q downwards if content change is decreasing and buffer level
700
      // is stable (at least 1/4-optimal level), so not overshooting. Do so
701
      // only for high Q to avoid excess overshoot.
702
      // Else reduce decrease in Q from previous frame if content change is
703
      // increasing and buffer is below max (so not undershooting).
704
0
      if (delta < 0.0 &&
705
0
          p_rc->buffer_level > (p_rc->optimal_buffer_level >> 2) &&
706
0
          q > (rc->worst_quality >> 1)) {
707
0
        double q_adj_factor = 1.0 + 0.5 * tanh(4.0 * delta);
708
0
        double q_val = av1_convert_qindex_to_q(q, bit_depth);
709
0
        q += av1_compute_qdelta(rc, q_val, q_val * q_adj_factor, bit_depth);
710
0
      } else if (rc->q_1_frame - q > 0 && delta > 0.1 &&
711
0
                 p_rc->buffer_level < AOMMIN(p_rc->maximum_buffer_size,
712
0
                                             p_rc->optimal_buffer_level << 1)) {
713
0
        q = (3 * q + rc->q_1_frame) >> 2;
714
0
      }
715
0
    }
716
    // Limit the decrease in Q from previous frame.
717
4.48k
    if (rc->q_1_frame - q > max_delta_down) q = rc->q_1_frame - max_delta_down;
718
    // Limit the increase in Q from previous frame.
719
4.47k
    else if (q - rc->q_1_frame > max_delta_up)
720
215
      q = rc->q_1_frame + max_delta_up;
721
4.48k
  }
722
  // Adjustment for temporal layers.
723
21.6k
  if (svc->number_temporal_layers > 1 && svc->spatial_layer_id == 0 &&
724
0
      !change_target_bits_mb && !cpi->rc.rtc_external_ratectrl &&
725
0
      cpi->oxcf.resize_cfg.resize_mode != RESIZE_DYNAMIC) {
726
0
    if (svc->temporal_layer_id > 0) {
727
      // Constrain enhancement relative to the previous base TL0.
728
      // Get base temporal layer TL0.
729
0
      const int layer = LAYER_IDS_TO_IDX(0, 0, svc->number_temporal_layers);
730
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
731
      // lc->rc.avg_frame_bandwidth and lc->p_rc.last_q correspond to the
732
      // last TL0 frame.
733
0
      const int last_qindex_tl0 =
734
0
          rc->frames_since_key < svc->number_temporal_layers
735
0
              ? lc->p_rc.last_q[KEY_FRAME]
736
0
              : lc->p_rc.last_q[INTER_FRAME];
737
0
      if (rc->avg_frame_bandwidth < lc->rc.avg_frame_bandwidth &&
738
0
          q < last_qindex_tl0 - 4)
739
0
        q = last_qindex_tl0 - 4;
740
0
    } else if (cpi->svc.temporal_layer_id == 0 && !frame_is_intra_only(cm) &&
741
0
               p_rc->buffer_level > (p_rc->optimal_buffer_level >> 2) &&
742
0
               rc->frame_source_sad < 100000) {
743
      // Push base TL0 Q down if buffer is stable and frame_source_sad
744
      // is below threshold.
745
0
      int delta = (svc->number_temporal_layers == 2) ? 4 : 10;
746
0
      q = q - delta;
747
0
    }
748
0
  }
749
  // For non-svc (single layer): if resolution has increased push q closer
750
  // to the active_worst to avoid excess overshoot.
751
21.6k
  if (!cpi->ppi->use_svc && cm->prev_frame &&
752
10.2k
      (width * height > 1.5 * cm->prev_frame->width * cm->prev_frame->height))
753
0
    q = (q + active_worst_quality) >> 1;
754
  // For single layer RPS: Bias Q based on distance of closest reference.
755
21.6k
  if (cpi->ppi->rtc_ref.bias_recovery_frame) {
756
0
    const int min_dist = av1_svc_get_min_ref_dist(cpi);
757
0
    q = q - AOMMIN(min_dist, 20);
758
0
  }
759
21.6k
  return clamp(q, cpi->rc.best_quality, cpi->rc.worst_quality);
760
21.6k
}
761
762
static const RATE_FACTOR_LEVEL rate_factor_levels[FRAME_UPDATE_TYPES] = {
763
  KF_STD,        // KF_UPDATE
764
  INTER_NORMAL,  // LF_UPDATE
765
  GF_ARF_STD,    // GF_UPDATE
766
  GF_ARF_STD,    // ARF_UPDATE
767
  INTER_NORMAL,  // OVERLAY_UPDATE
768
  INTER_NORMAL,  // INTNL_OVERLAY_UPDATE
769
  GF_ARF_LOW,    // INTNL_ARF_UPDATE
770
};
771
772
static RATE_FACTOR_LEVEL get_rate_factor_level(const GF_GROUP *const gf_group,
773
14.8k
                                               int gf_frame_index) {
774
14.8k
  const FRAME_UPDATE_TYPE update_type = gf_group->update_type[gf_frame_index];
775
14.8k
  assert(update_type < FRAME_UPDATE_TYPES);
776
14.8k
  return rate_factor_levels[update_type];
777
14.8k
}
778
779
/*!\brief Gets a rate vs Q correction factor
780
 *
781
 * This function returns the current value of a correction factor used to
782
 * dynamically adjust the relationship between Q and the expected number
783
 * of bits for the frame.
784
 *
785
 * \ingroup rate_control
786
 * \param[in]   cpi                   Top level encoder instance structure
787
 * \param[in]   width                 Frame width
788
 * \param[in]   height                Frame height
789
 *
790
 * \return Returns a correction factor for the current frame
791
 */
792
static double get_rate_correction_factor(const AV1_COMP *cpi, int width,
793
130k
                                         int height) {
794
130k
  const RATE_CONTROL *const rc = &cpi->rc;
795
130k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
796
130k
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
797
130k
  double rcf;
798
130k
  double rate_correction_factors_kfstd;
799
130k
  double rate_correction_factors_gfarfstd;
800
130k
  double rate_correction_factors_internormal;
801
802
130k
  rate_correction_factors_kfstd =
803
130k
      (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
804
130k
          ? rc->frame_level_rate_correction_factors[KF_STD]
805
130k
          : p_rc->rate_correction_factors[KF_STD];
806
130k
  rate_correction_factors_gfarfstd =
807
130k
      (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
808
130k
          ? rc->frame_level_rate_correction_factors[GF_ARF_STD]
809
130k
          : p_rc->rate_correction_factors[GF_ARF_STD];
810
130k
  rate_correction_factors_internormal =
811
130k
      (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
812
130k
          ? rc->frame_level_rate_correction_factors[INTER_NORMAL]
813
130k
          : p_rc->rate_correction_factors[INTER_NORMAL];
814
815
130k
  if (cpi->common.current_frame.frame_type == KEY_FRAME) {
816
92.7k
    rcf = rate_correction_factors_kfstd;
817
92.7k
  } else if (is_stat_consumption_stage(cpi)) {
818
7.41k
    const RATE_FACTOR_LEVEL rf_lvl =
819
7.41k
        get_rate_factor_level(&cpi->ppi->gf_group, cpi->gf_frame_index);
820
7.41k
    double rate_correction_factors_rflvl =
821
7.41k
        (cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0)
822
7.41k
            ? rc->frame_level_rate_correction_factors[rf_lvl]
823
7.41k
            : p_rc->rate_correction_factors[rf_lvl];
824
7.41k
    rcf = rate_correction_factors_rflvl;
825
30.1k
  } else {
826
30.1k
    if ((refresh_frame->alt_ref_frame || refresh_frame->golden_frame) &&
827
9.64k
        !rc->is_src_frame_alt_ref && !cpi->ppi->use_svc &&
828
9.64k
        (cpi->oxcf.rc_cfg.mode != AOM_CBR ||
829
0
         cpi->oxcf.rc_cfg.gf_cbr_boost_pct > 20))
830
9.64k
      rcf = rate_correction_factors_gfarfstd;
831
20.5k
    else
832
20.5k
      rcf = rate_correction_factors_internormal;
833
30.1k
  }
834
130k
  rcf *= resize_rate_factor(&cpi->oxcf.frm_dim_cfg, width, height);
835
130k
  return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
836
130k
}
837
838
/*!\brief Sets a rate vs Q correction factor
839
 *
840
 * This function updates the current value of a correction factor used to
841
 * dynamically adjust the relationship between Q and the expected number
842
 * of bits for the frame.
843
 *
844
 * \ingroup rate_control
845
 * \param[in]   cpi                   Top level encoder instance structure
846
 * \param[in]   is_encode_stage       Indicates if recode loop or post-encode
847
 * \param[in]   factor                New correction factor
848
 * \param[in]   width                 Frame width
849
 * \param[in]   height                Frame height
850
 *
851
 * \remark Updates the rate correction factor for the
852
 *         current frame type in cpi->rc.
853
 */
854
static void set_rate_correction_factor(AV1_COMP *cpi, int is_encode_stage,
855
108k
                                       double factor, int width, int height) {
856
108k
  RATE_CONTROL *const rc = &cpi->rc;
857
108k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
858
108k
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
859
108k
  int update_default_rcf = 1;
860
  // Normalize RCF to account for the size-dependent scaling factor.
861
108k
  factor /= resize_rate_factor(&cpi->oxcf.frm_dim_cfg, width, height);
862
863
108k
  factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
864
865
108k
  if (cpi->common.current_frame.frame_type == KEY_FRAME) {
866
81.3k
    p_rc->rate_correction_factors[KF_STD] = factor;
867
81.3k
  } else if (is_stat_consumption_stage(cpi)) {
868
7.41k
    const RATE_FACTOR_LEVEL rf_lvl =
869
7.41k
        get_rate_factor_level(&cpi->ppi->gf_group, cpi->gf_frame_index);
870
7.41k
    if (is_encode_stage &&
871
0
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
872
0
      rc->frame_level_rate_correction_factors[rf_lvl] = factor;
873
0
      update_default_rcf = 0;
874
0
    }
875
7.41k
    if (update_default_rcf) p_rc->rate_correction_factors[rf_lvl] = factor;
876
19.9k
  } else {
877
19.9k
    if ((refresh_frame->alt_ref_frame || refresh_frame->golden_frame) &&
878
9.64k
        !rc->is_src_frame_alt_ref && !cpi->ppi->use_svc &&
879
9.64k
        (cpi->oxcf.rc_cfg.mode != AOM_CBR ||
880
9.64k
         cpi->oxcf.rc_cfg.gf_cbr_boost_pct > 20)) {
881
9.64k
      p_rc->rate_correction_factors[GF_ARF_STD] = factor;
882
10.2k
    } else {
883
10.2k
      if (is_encode_stage &&
884
0
          cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0) {
885
0
        rc->frame_level_rate_correction_factors[INTER_NORMAL] = factor;
886
0
        update_default_rcf = 0;
887
0
      }
888
10.2k
      if (update_default_rcf)
889
10.2k
        p_rc->rate_correction_factors[INTER_NORMAL] = factor;
890
10.2k
    }
891
19.9k
  }
892
108k
}
893
894
void av1_rc_update_rate_correction_factors(AV1_COMP *cpi, int is_encode_stage,
895
108k
                                           int width, int height) {
896
108k
  const AV1_COMMON *const cm = &cpi->common;
897
108k
  double correction_factor = 1.0;
898
108k
  double rate_correction_factor =
899
108k
      get_rate_correction_factor(cpi, width, height);
900
108k
  double adjustment_limit;
901
108k
  int projected_size_based_on_q = 0;
902
108k
  int cyclic_refresh_active =
903
108k
      cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled;
904
905
  // Do not update the rate factors for arf overlay frames.
906
108k
  if (cpi->rc.is_src_frame_alt_ref) return;
907
908
  // Don't update rate correction factors here on scene changes as
909
  // it is already reset in av1_encodedframe_overshoot_cbr(),
910
  // but reset variables related to previous frame q and size.
911
  // Note that the counter of frames since the last scene change
912
  // is only valid when cyclic refresh mode is enabled and that
913
  // this break out only applies to scene changes that are not
914
  // recorded as INTRA only key frames.
915
  // Note that av1_encodedframe_overshoot_cbr() is only entered
916
  // if cpi->sf.rt_sf.overshoot_detection_cbr == FAST_DETECTION_MAXQ
917
  // and cpi->rc.high_source_sad = 1.
918
108k
  if ((cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ) &&
919
0
      (cpi->sf.rt_sf.overshoot_detection_cbr == FAST_DETECTION_MAXQ) &&
920
0
      cpi->rc.high_source_sad &&
921
0
      (cpi->cyclic_refresh->counter_encode_maxq_scene_change == 0) &&
922
0
      !frame_is_intra_only(cm) && !cpi->ppi->use_svc) {
923
0
    cpi->rc.q_2_frame = cm->quant_params.base_qindex;
924
0
    cpi->rc.q_1_frame = cm->quant_params.base_qindex;
925
0
    cpi->rc.rc_2_frame = 0;
926
0
    cpi->rc.rc_1_frame = 0;
927
0
    return;
928
0
  }
929
930
  // Clear down mmx registers to allow floating point in what follows
931
932
  // Work out how big we would have expected the frame to be at this Q given
933
  // the current correction factor.
934
  // Stay in double to avoid int overflow when values are large
935
108k
  if (cyclic_refresh_active) {
936
0
    projected_size_based_on_q =
937
0
        av1_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
938
108k
  } else {
939
108k
    projected_size_based_on_q = av1_estimate_bits_at_q(
940
108k
        cpi, cm->quant_params.base_qindex, rate_correction_factor);
941
108k
  }
942
  // Work out a size correction factor.
943
108k
  if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
944
69.9k
    correction_factor = (double)cpi->rc.projected_frame_size /
945
69.9k
                        (double)projected_size_based_on_q;
946
947
  // Clamp correction factor to prevent anything too extreme
948
108k
  correction_factor = AOMMAX(correction_factor, 0.25);
949
950
108k
  cpi->rc.q_2_frame = cpi->rc.q_1_frame;
951
108k
  cpi->rc.q_1_frame = cm->quant_params.base_qindex;
952
108k
  cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
953
108k
  if (correction_factor > 1.1)
954
56.9k
    cpi->rc.rc_1_frame = -1;
955
51.7k
  else if (correction_factor < 0.9)
956
9.85k
    cpi->rc.rc_1_frame = 1;
957
41.9k
  else
958
41.9k
    cpi->rc.rc_1_frame = 0;
959
960
  // Decide how heavily to dampen the adjustment
961
108k
  if (correction_factor > 0.0) {
962
108k
    if (cpi->is_screen_content_type) {
963
0
      adjustment_limit =
964
0
          0.25 + 0.5 * AOMMIN(0.5, fabs(log10(correction_factor)));
965
108k
    } else {
966
108k
      adjustment_limit =
967
108k
          0.25 + 0.75 * AOMMIN(0.5, fabs(log10(correction_factor)));
968
108k
    }
969
108k
  } else {
970
0
    adjustment_limit = 0.75;
971
0
  }
972
973
  // Adjustment to delta Q and number of blocks updated in cyclic refresh
974
  // based on over or under shoot of target in current frame.
975
108k
  if (cyclic_refresh_active && cpi->rc.this_frame_target > 0) {
976
0
    CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
977
0
    if (correction_factor > 1.25) {
978
0
      cr->percent_refresh_adjustment =
979
0
          AOMMAX(cr->percent_refresh_adjustment - 1, -5);
980
0
      cr->rate_ratio_qdelta_adjustment =
981
0
          AOMMAX(cr->rate_ratio_qdelta_adjustment - 0.05, -0.0);
982
0
    } else if (correction_factor < 0.5) {
983
0
      cr->percent_refresh_adjustment =
984
0
          AOMMIN(cr->percent_refresh_adjustment + 1, 5);
985
0
      cr->rate_ratio_qdelta_adjustment =
986
0
          AOMMIN(cr->rate_ratio_qdelta_adjustment + 0.05, 0.25);
987
0
    }
988
0
  }
989
990
108k
  if (correction_factor > 1.01) {
991
    // We are not already at the worst allowable quality
992
58.6k
    correction_factor = (1.0 + ((correction_factor - 1.0) * adjustment_limit));
993
58.6k
    rate_correction_factor = rate_correction_factor * correction_factor;
994
    // Keep rate_correction_factor within limits
995
58.6k
    if (rate_correction_factor > MAX_BPB_FACTOR)
996
80
      rate_correction_factor = MAX_BPB_FACTOR;
997
58.6k
  } else if (correction_factor < 0.99) {
998
    // We are not already at the best allowable quality
999
11.1k
    correction_factor = 1.0 / correction_factor;
1000
11.1k
    correction_factor = (1.0 + ((correction_factor - 1.0) * adjustment_limit));
1001
11.1k
    correction_factor = 1.0 / correction_factor;
1002
1003
11.1k
    rate_correction_factor = rate_correction_factor * correction_factor;
1004
1005
    // Keep rate_correction_factor within limits
1006
11.1k
    if (rate_correction_factor < MIN_BPB_FACTOR)
1007
0
      rate_correction_factor = MIN_BPB_FACTOR;
1008
11.1k
  }
1009
1010
108k
  set_rate_correction_factor(cpi, is_encode_stage, rate_correction_factor,
1011
108k
                             width, height);
1012
108k
}
1013
1014
// Calculate rate for the given 'q'.
1015
static int get_bits_per_mb(const AV1_COMP *cpi, int use_cyclic_refresh,
1016
120k
                           double correction_factor, int q) {
1017
120k
  const AV1_COMMON *const cm = &cpi->common;
1018
120k
  return use_cyclic_refresh
1019
120k
             ? av1_cyclic_refresh_rc_bits_per_mb(cpi, q, correction_factor)
1020
120k
             : av1_rc_bits_per_mb(cpi, cm->current_frame.frame_type, q,
1021
120k
                                  correction_factor,
1022
120k
                                  cpi->sf.hl_sf.accurate_bit_estimate);
1023
120k
}
1024
1025
/*!\brief Searches for a Q index value predicted to give an average macro
1026
 * block rate closest to the target value.
1027
 *
1028
 * Similar to find_qindex_by_rate() function, but returns a q index with a
1029
 * rate just above or below the desired rate, depending on which of the two
1030
 * rates is closer to the desired rate.
1031
 * Also, respects the selected aq_mode when computing the rate.
1032
 *
1033
 * \ingroup rate_control
1034
 * \param[in]   desired_bits_per_mb   Target bits per mb
1035
 * \param[in]   cpi                   Top level encoder instance structure
1036
 * \param[in]   correction_factor     Current Q to rate correction factor
1037
 * \param[in]   best_qindex           Min allowed Q value.
1038
 * \param[in]   worst_qindex          Max allowed Q value.
1039
 *
1040
 * \return Returns a correction factor for the current frame
1041
 */
1042
static int find_closest_qindex_by_rate(int desired_bits_per_mb,
1043
                                       const AV1_COMP *cpi,
1044
                                       double correction_factor,
1045
21.6k
                                       int best_qindex, int worst_qindex) {
1046
21.6k
  const int use_cyclic_refresh = cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ &&
1047
0
                                 cpi->cyclic_refresh->apply_cyclic_refresh;
1048
1049
  // Find 'qindex' based on 'desired_bits_per_mb'.
1050
21.6k
  assert(best_qindex <= worst_qindex);
1051
21.6k
  int low = best_qindex;
1052
21.6k
  int high = worst_qindex;
1053
120k
  while (low < high) {
1054
98.7k
    const int mid = (low + high) >> 1;
1055
98.7k
    const int mid_bits_per_mb =
1056
98.7k
        get_bits_per_mb(cpi, use_cyclic_refresh, correction_factor, mid);
1057
98.7k
    if (mid_bits_per_mb > desired_bits_per_mb) {
1058
5.49k
      low = mid + 1;
1059
93.2k
    } else {
1060
93.2k
      high = mid;
1061
93.2k
    }
1062
98.7k
  }
1063
21.6k
  assert(low == high);
1064
1065
  // Calculate rate difference of this q index from the desired rate.
1066
21.6k
  const int curr_q = low;
1067
21.6k
  const int curr_bits_per_mb =
1068
21.6k
      get_bits_per_mb(cpi, use_cyclic_refresh, correction_factor, curr_q);
1069
21.6k
  const int curr_bit_diff = (curr_bits_per_mb <= desired_bits_per_mb)
1070
21.6k
                                ? desired_bits_per_mb - curr_bits_per_mb
1071
21.6k
                                : INT_MAX;
1072
21.6k
  assert((curr_bit_diff != INT_MAX && curr_bit_diff >= 0) ||
1073
21.6k
         curr_q == worst_qindex);
1074
1075
  // Calculate rate difference for previous q index too.
1076
21.6k
  const int prev_q = curr_q - 1;
1077
21.6k
  int prev_bit_diff;
1078
21.6k
  if (curr_bit_diff == INT_MAX || curr_q == best_qindex) {
1079
21.2k
    prev_bit_diff = INT_MAX;
1080
21.2k
  } else {
1081
379
    const int prev_bits_per_mb =
1082
379
        get_bits_per_mb(cpi, use_cyclic_refresh, correction_factor, prev_q);
1083
379
    assert(prev_bits_per_mb > desired_bits_per_mb);
1084
379
    prev_bit_diff = prev_bits_per_mb - desired_bits_per_mb;
1085
379
  }
1086
1087
  // Pick one of the two q indices, depending on which one has rate closer to
1088
  // the desired rate.
1089
21.6k
  return (curr_bit_diff <= prev_bit_diff) ? curr_q : prev_q;
1090
21.6k
}
1091
1092
int av1_rc_regulate_q(const AV1_COMP *cpi, int target_bits_per_frame,
1093
                      int active_best_quality, int active_worst_quality,
1094
21.6k
                      int width, int height) {
1095
21.6k
  const int MBs = av1_get_MBs(width, height);
1096
21.6k
  const double correction_factor =
1097
21.6k
      get_rate_correction_factor(cpi, width, height);
1098
21.6k
  const int target_bits_per_mb =
1099
21.6k
      (int)(((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / MBs);
1100
1101
21.6k
  int q =
1102
21.6k
      find_closest_qindex_by_rate(target_bits_per_mb, cpi, correction_factor,
1103
21.6k
                                  active_best_quality, active_worst_quality);
1104
21.6k
  if (cpi->oxcf.rc_cfg.mode == AOM_CBR && has_no_stats_stage(cpi))
1105
21.6k
    return adjust_q_cbr(cpi, q, active_worst_quality, width, height);
1106
1107
0
  return q;
1108
21.6k
}
1109
1110
static int get_active_quality(int q, int gfu_boost, int low, int high,
1111
25.0k
                              int *low_motion_minq, int *high_motion_minq) {
1112
25.0k
  if (gfu_boost > high) {
1113
0
    return low_motion_minq[q];
1114
25.0k
  } else if (gfu_boost < low) {
1115
0
    return high_motion_minq[q];
1116
25.0k
  } else {
1117
25.0k
    const int gap = high - low;
1118
25.0k
    const int offset = high - gfu_boost;
1119
25.0k
    const int qdiff = high_motion_minq[q] - low_motion_minq[q];
1120
25.0k
    const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
1121
25.0k
    return low_motion_minq[q] + adjustment;
1122
25.0k
  }
1123
25.0k
}
1124
1125
static int get_kf_active_quality(const PRIMARY_RATE_CONTROL *const p_rc, int q,
1126
15.3k
                                 aom_bit_depth_t bit_depth) {
1127
15.3k
  int *kf_low_motion_minq;
1128
15.3k
  int *kf_high_motion_minq;
1129
15.3k
  ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
1130
15.3k
  ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
1131
15.3k
  return get_active_quality(q, p_rc->kf_boost, kf_low, kf_high,
1132
15.3k
                            kf_low_motion_minq, kf_high_motion_minq);
1133
15.3k
}
1134
1135
static int get_gf_active_quality_no_rc(int gfu_boost, int q,
1136
9.64k
                                       aom_bit_depth_t bit_depth) {
1137
9.64k
  int *arfgf_low_motion_minq;
1138
9.64k
  int *arfgf_high_motion_minq;
1139
9.64k
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
1140
9.64k
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
1141
9.64k
  return get_active_quality(q, gfu_boost, gf_low, gf_high,
1142
9.64k
                            arfgf_low_motion_minq, arfgf_high_motion_minq);
1143
9.64k
}
1144
1145
static int get_gf_active_quality(const PRIMARY_RATE_CONTROL *const p_rc, int q,
1146
9.64k
                                 aom_bit_depth_t bit_depth) {
1147
9.64k
  return get_gf_active_quality_no_rc(p_rc->gfu_boost, q, bit_depth);
1148
9.64k
}
1149
1150
9.64k
static int get_gf_high_motion_quality(int q, aom_bit_depth_t bit_depth) {
1151
9.64k
  int *arfgf_high_motion_minq;
1152
9.64k
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
1153
9.64k
  return arfgf_high_motion_minq[q];
1154
9.64k
}
1155
1156
0
static int calc_active_worst_quality_no_stats_vbr(const AV1_COMP *cpi) {
1157
0
  const RATE_CONTROL *const rc = &cpi->rc;
1158
0
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1159
0
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
1160
0
  const unsigned int curr_frame = cpi->common.current_frame.frame_number;
1161
0
  int active_worst_quality;
1162
0
  int last_q_key_frame;
1163
0
  int last_q_inter_frame;
1164
#if CONFIG_FPMT_TEST
1165
  const int simulate_parallel_frame =
1166
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
1167
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
1168
  last_q_key_frame = simulate_parallel_frame ? p_rc->temp_last_q[KEY_FRAME]
1169
                                             : p_rc->last_q[KEY_FRAME];
1170
  last_q_inter_frame = simulate_parallel_frame ? p_rc->temp_last_q[INTER_FRAME]
1171
                                               : p_rc->last_q[INTER_FRAME];
1172
#else
1173
0
  last_q_key_frame = p_rc->last_q[KEY_FRAME];
1174
0
  last_q_inter_frame = p_rc->last_q[INTER_FRAME];
1175
0
#endif
1176
1177
0
  if (cpi->common.current_frame.frame_type == KEY_FRAME) {
1178
0
    active_worst_quality =
1179
0
        curr_frame == 0 ? rc->worst_quality : last_q_key_frame * 2;
1180
0
  } else {
1181
0
    if (!rc->is_src_frame_alt_ref &&
1182
0
        (refresh_frame->golden_frame || refresh_frame->bwd_ref_frame ||
1183
0
         refresh_frame->alt_ref_frame)) {
1184
0
      active_worst_quality =
1185
0
          curr_frame == 1 ? last_q_key_frame * 5 / 4 : last_q_inter_frame;
1186
0
    } else {
1187
0
      active_worst_quality =
1188
0
          curr_frame == 1 ? last_q_key_frame * 2 : last_q_inter_frame * 2;
1189
0
    }
1190
0
  }
1191
0
  return AOMMIN(active_worst_quality, rc->worst_quality);
1192
0
}
1193
1194
// Adjust active_worst_quality level based on buffer level.
1195
21.6k
static int calc_active_worst_quality_no_stats_cbr(const AV1_COMP *cpi) {
1196
  // Adjust active_worst_quality: If buffer is above the optimal/target level,
1197
  // bring active_worst_quality down depending on fullness of buffer.
1198
  // If buffer is below the optimal level, let the active_worst_quality go from
1199
  // ambient Q (at buffer = optimal level) to worst_quality level
1200
  // (at buffer = critical level).
1201
21.6k
  const AV1_COMMON *const cm = &cpi->common;
1202
21.6k
  const RATE_CONTROL *rc = &cpi->rc;
1203
21.6k
  const PRIMARY_RATE_CONTROL *p_rc = &cpi->ppi->p_rc;
1204
21.6k
  const SVC *const svc = &cpi->svc;
1205
21.6k
  unsigned int num_frames_weight_key = 5 * cpi->svc.number_temporal_layers;
1206
  // Buffer level below which we push active_worst to worst_quality.
1207
21.6k
  int64_t critical_level = p_rc->optimal_buffer_level >> 3;
1208
21.6k
  int64_t buff_lvl_step = 0;
1209
21.6k
  int adjustment = 0;
1210
21.6k
  int active_worst_quality;
1211
21.6k
  int ambient_qp;
1212
21.6k
  if (frame_is_intra_only(cm)) return rc->worst_quality;
1213
  // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
1214
  // for the first few frames following key frame. These are both initialized
1215
  // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
1216
  // So for first few frames following key, the qp of that key frame is weighted
1217
  // into the active_worst_quality setting. For SVC the key frame should
1218
  // correspond to layer (0, 0), so use that for layer context.
1219
10.2k
  int avg_qindex_key = p_rc->avg_frame_qindex[KEY_FRAME];
1220
10.2k
  if (svc->number_temporal_layers > 1) {
1221
0
    int layer = LAYER_IDS_TO_IDX(0, 0, svc->number_temporal_layers);
1222
0
    const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1223
0
    const PRIMARY_RATE_CONTROL *const lp_rc = &lc->p_rc;
1224
0
    avg_qindex_key =
1225
0
        AOMMIN(lp_rc->avg_frame_qindex[KEY_FRAME], lp_rc->last_q[KEY_FRAME]);
1226
0
  }
1227
10.2k
  if (svc->temporal_layer_id > 0 &&
1228
0
      rc->frames_since_key < 2 * svc->number_temporal_layers) {
1229
0
    ambient_qp = avg_qindex_key;
1230
10.2k
  } else {
1231
10.2k
    ambient_qp =
1232
10.2k
        (cm->current_frame.frame_number < num_frames_weight_key)
1233
10.2k
            ? AOMMIN(p_rc->avg_frame_qindex[INTER_FRAME], avg_qindex_key)
1234
10.2k
            : p_rc->avg_frame_qindex[INTER_FRAME];
1235
10.2k
  }
1236
10.2k
  ambient_qp = AOMMIN(rc->worst_quality, ambient_qp);
1237
1238
10.2k
  if (p_rc->buffer_level > p_rc->optimal_buffer_level) {
1239
    // Adjust down.
1240
8.38k
    int max_adjustment_down;  // Maximum adjustment down for Q
1241
1242
8.38k
    if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ && !cpi->ppi->use_svc &&
1243
0
        (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN)) {
1244
0
      active_worst_quality = AOMMIN(rc->worst_quality, ambient_qp);
1245
0
      max_adjustment_down = AOMMIN(4, active_worst_quality / 16);
1246
8.38k
    } else {
1247
8.38k
      active_worst_quality = AOMMIN(rc->worst_quality, ambient_qp * 5 / 4);
1248
8.38k
      max_adjustment_down = active_worst_quality / 3;
1249
8.38k
    }
1250
1251
8.38k
    if (max_adjustment_down) {
1252
8.14k
      buff_lvl_step =
1253
8.14k
          ((p_rc->maximum_buffer_size - p_rc->optimal_buffer_level) /
1254
8.14k
           max_adjustment_down);
1255
8.14k
      if (buff_lvl_step)
1256
8.14k
        adjustment = (int)((p_rc->buffer_level - p_rc->optimal_buffer_level) /
1257
8.14k
                           buff_lvl_step);
1258
8.14k
      active_worst_quality -= adjustment;
1259
8.14k
    }
1260
8.38k
  } else if (p_rc->buffer_level > critical_level) {
1261
    // Adjust up from ambient Q.
1262
1.30k
    active_worst_quality = AOMMIN(rc->worst_quality, ambient_qp);
1263
1.30k
    if (critical_level) {
1264
1.30k
      buff_lvl_step = (p_rc->optimal_buffer_level - critical_level);
1265
1.30k
      if (buff_lvl_step) {
1266
1.30k
        adjustment = (int)((rc->worst_quality - ambient_qp) *
1267
1.30k
                           (p_rc->optimal_buffer_level - p_rc->buffer_level) /
1268
1.30k
                           buff_lvl_step);
1269
1.30k
      }
1270
1.30k
      active_worst_quality += adjustment;
1271
1.30k
    }
1272
1.30k
  } else {
1273
    // Set to worst_quality if buffer is below critical level.
1274
572
    active_worst_quality = rc->worst_quality;
1275
572
  }
1276
10.2k
  return active_worst_quality;
1277
21.6k
}
1278
1279
// Calculate the active_best_quality level.
1280
static int calc_active_best_quality_no_stats_cbr(const AV1_COMP *cpi,
1281
                                                 int active_worst_quality,
1282
21.6k
                                                 int width, int height) {
1283
21.6k
  const AV1_COMMON *const cm = &cpi->common;
1284
21.6k
  const RATE_CONTROL *const rc = &cpi->rc;
1285
21.6k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1286
21.6k
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
1287
21.6k
  const CurrentFrame *const current_frame = &cm->current_frame;
1288
21.6k
  int *rtc_minq;
1289
21.6k
  const int bit_depth = cm->seq_params->bit_depth;
1290
21.6k
  int active_best_quality = rc->best_quality;
1291
21.6k
  ASSIGN_MINQ_TABLE(bit_depth, rtc_minq);
1292
1293
21.6k
  if (frame_is_intra_only(cm)) {
1294
    // Handle the special case for key frames forced when we have reached
1295
    // the maximum key frame interval. Here force the Q to a range
1296
    // based on the ambient Q to reduce the risk of popping.
1297
11.4k
    if (p_rc->this_key_frame_forced) {
1298
0
      int qindex = p_rc->last_boosted_qindex;
1299
0
      double last_boosted_q = av1_convert_qindex_to_q(qindex, bit_depth);
1300
0
      int delta_qindex = av1_compute_qdelta(rc, last_boosted_q,
1301
0
                                            (last_boosted_q * 0.75), bit_depth);
1302
0
      active_best_quality = AOMMAX(qindex + delta_qindex, rc->best_quality);
1303
11.4k
    } else if (current_frame->frame_number > 0) {
1304
      // not first frame of one pass and kf_boost is set
1305
0
      double q_adj_factor = 1.0;
1306
0
      double q_val;
1307
0
      active_best_quality = get_kf_active_quality(
1308
0
          p_rc, p_rc->avg_frame_qindex[KEY_FRAME], bit_depth);
1309
      // Allow somewhat lower kf minq with small image formats.
1310
0
      if ((width * height) <= (352 * 288)) {
1311
0
        q_adj_factor -= 0.25;
1312
0
      }
1313
      // Convert the adjustment factor to a qindex delta
1314
      // on active_best_quality.
1315
0
      q_val = av1_convert_qindex_to_q(active_best_quality, bit_depth);
1316
0
      active_best_quality +=
1317
0
          av1_compute_qdelta(rc, q_val, q_val * q_adj_factor, bit_depth);
1318
0
    }
1319
11.4k
  } else if (!rc->is_src_frame_alt_ref && !cpi->ppi->use_svc &&
1320
10.2k
             cpi->oxcf.rc_cfg.gf_cbr_boost_pct &&
1321
0
             (refresh_frame->golden_frame || refresh_frame->alt_ref_frame)) {
1322
    // Use the lower of active_worst_quality and recent
1323
    // average Q as basis for GF/ARF best Q limit unless last frame was
1324
    // a key frame.
1325
0
    int q = active_worst_quality;
1326
0
    if (rc->frames_since_key > 1 &&
1327
0
        p_rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1328
0
      q = p_rc->avg_frame_qindex[INTER_FRAME];
1329
0
    }
1330
0
    active_best_quality = get_gf_active_quality(p_rc, q, bit_depth);
1331
10.2k
  } else {
1332
    // Use the lower of active_worst_quality and recent/average Q.
1333
10.2k
    FRAME_TYPE frame_type =
1334
10.2k
        (current_frame->frame_number > 1) ? INTER_FRAME : KEY_FRAME;
1335
10.2k
    if (p_rc->avg_frame_qindex[frame_type] < active_worst_quality)
1336
6.60k
      active_best_quality = rtc_minq[p_rc->avg_frame_qindex[frame_type]];
1337
3.64k
    else
1338
3.64k
      active_best_quality = rtc_minq[active_worst_quality];
1339
10.2k
  }
1340
21.6k
  return active_best_quality;
1341
21.6k
}
1342
1343
#if RT_PASSIVE_STRATEGY
1344
static int get_q_passive_strategy(const AV1_COMP *const cpi,
1345
                                  const int q_candidate, const int threshold) {
1346
  const AV1_COMMON *const cm = &cpi->common;
1347
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1348
  const CurrentFrame *const current_frame = &cm->current_frame;
1349
  int sum = 0;
1350
  int count = 0;
1351
  int i = 1;
1352
  while (i < MAX_Q_HISTORY) {
1353
    int frame_id = current_frame->frame_number - i;
1354
    if (frame_id <= 0) break;
1355
    sum += p_rc->q_history[frame_id % MAX_Q_HISTORY];
1356
    ++count;
1357
    ++i;
1358
  }
1359
  if (count > 0) {
1360
    const int avg_q = sum / count;
1361
    if (abs(avg_q - q_candidate) <= threshold) return avg_q;
1362
  }
1363
  return q_candidate;
1364
}
1365
#endif  // RT_PASSIVE_STRATEGY
1366
1367
/*!\brief Picks q and q bounds given CBR rate control parameters in \c cpi->rc.
1368
 *
1369
 * Handles the special case when using:
1370
 * - Constant bit-rate mode: \c cpi->oxcf.rc_cfg.mode == \ref AOM_CBR, and
1371
 * - 1-pass encoding without LAP (look-ahead processing), so 1st pass stats are
1372
 * NOT available.
1373
 *
1374
 * \ingroup rate_control
1375
 * \param[in]       cpi          Top level encoder structure
1376
 * \param[in]       width        Coded frame width
1377
 * \param[in]       height       Coded frame height
1378
 * \param[out]      bottom_index Bottom bound for q index (best quality)
1379
 * \param[out]      top_index    Top bound for q index (worst quality)
1380
 * \return Returns selected q index to be used for encoding this frame.
1381
 */
1382
static int rc_pick_q_and_bounds_no_stats_cbr(const AV1_COMP *cpi, int width,
1383
                                             int height, int *bottom_index,
1384
21.6k
                                             int *top_index) {
1385
21.6k
  const AV1_COMMON *const cm = &cpi->common;
1386
21.6k
  const RATE_CONTROL *const rc = &cpi->rc;
1387
21.6k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1388
21.6k
  const CurrentFrame *const current_frame = &cm->current_frame;
1389
21.6k
  int q;
1390
21.6k
  int active_worst_quality = calc_active_worst_quality_no_stats_cbr(cpi);
1391
21.6k
  int active_best_quality = calc_active_best_quality_no_stats_cbr(
1392
21.6k
      cpi, active_worst_quality, width, height);
1393
21.6k
  assert(has_no_stats_stage(cpi));
1394
21.6k
  assert(cpi->oxcf.rc_cfg.mode == AOM_CBR);
1395
1396
  // Clip the active best and worst quality values to limits
1397
21.6k
  active_best_quality =
1398
21.6k
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1399
21.6k
  active_worst_quality =
1400
21.6k
      clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1401
1402
21.6k
  *top_index = active_worst_quality;
1403
21.6k
  *bottom_index = active_best_quality;
1404
1405
  // Limit Q range for the adaptive loop.
1406
21.6k
  if (current_frame->frame_type == KEY_FRAME && !p_rc->this_key_frame_forced &&
1407
11.4k
      current_frame->frame_number != 0) {
1408
0
    int qdelta = 0;
1409
0
    qdelta = av1_compute_qdelta_by_rate(cpi, current_frame->frame_type,
1410
0
                                        active_worst_quality, 2.0);
1411
0
    *top_index = active_worst_quality + qdelta;
1412
0
    *top_index = AOMMAX(*top_index, *bottom_index);
1413
0
  }
1414
1415
21.6k
  q = av1_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1416
21.6k
                        active_worst_quality, width, height);
1417
#if RT_PASSIVE_STRATEGY
1418
  if (current_frame->frame_type != KEY_FRAME &&
1419
      cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN) {
1420
    q = get_q_passive_strategy(cpi, q, 50);
1421
  }
1422
#endif  // RT_PASSIVE_STRATEGY
1423
21.6k
  if (q > *top_index) {
1424
    // Special case when we are targeting the max allowed rate
1425
0
    if (rc->this_frame_target >= rc->max_frame_bandwidth)
1426
0
      *top_index = q;
1427
0
    else
1428
0
      q = *top_index;
1429
0
  }
1430
1431
21.6k
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1432
21.6k
  assert(*bottom_index <= rc->worst_quality &&
1433
21.6k
         *bottom_index >= rc->best_quality);
1434
21.6k
  assert(q <= rc->worst_quality && q >= rc->best_quality);
1435
21.6k
  return q;
1436
21.6k
}
1437
1438
0
static int gf_group_pyramid_level(const GF_GROUP *gf_group, int gf_index) {
1439
0
  return gf_group->layer_depth[gf_index];
1440
0
}
1441
1442
static int get_active_cq_level(const RATE_CONTROL *rc,
1443
                               const PRIMARY_RATE_CONTROL *p_rc,
1444
                               const AV1EncoderConfig *const oxcf,
1445
                               int intra_only, aom_superres_mode superres_mode,
1446
214k
                               int superres_denom) {
1447
214k
  const RateControlCfg *const rc_cfg = &oxcf->rc_cfg;
1448
214k
  static const double cq_adjust_threshold = 0.1;
1449
214k
  int active_cq_level = rc_cfg->cq_level;
1450
214k
  if (rc_cfg->mode == AOM_CQ || rc_cfg->mode == AOM_Q) {
1451
214k
    if ((superres_mode == AOM_SUPERRES_QTHRESH ||
1452
214k
         superres_mode == AOM_SUPERRES_AUTO) &&
1453
0
        superres_denom != SCALE_NUMERATOR) {
1454
0
      int mult = SUPERRES_QADJ_PER_DENOM_KEYFRAME_SOLO;
1455
0
      if (intra_only && rc->frames_to_key <= 1) {
1456
0
        mult = 0;
1457
0
      } else if (intra_only) {
1458
0
        mult = SUPERRES_QADJ_PER_DENOM_KEYFRAME;
1459
0
      } else {
1460
0
        mult = SUPERRES_QADJ_PER_DENOM_ARFFRAME;
1461
0
      }
1462
0
      active_cq_level = AOMMAX(
1463
0
          active_cq_level - ((superres_denom - SCALE_NUMERATOR) * mult), 0);
1464
0
    }
1465
214k
  }
1466
214k
  if (rc_cfg->mode == AOM_CQ && p_rc->total_target_bits > 0) {
1467
0
    const double x = (double)p_rc->total_actual_bits / p_rc->total_target_bits;
1468
0
    if (x < cq_adjust_threshold) {
1469
0
      active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
1470
0
    }
1471
0
  }
1472
214k
  return active_cq_level;
1473
214k
}
1474
1475
/*!\brief Picks q and q bounds given non-CBR rate control params in \c cpi->rc.
1476
 *
1477
 * Handles the special case when using:
1478
 * - Any rate control other than constant bit-rate mode:
1479
 * \c cpi->oxcf.rc_cfg.mode != \ref AOM_CBR, and
1480
 * - 1-pass encoding without LAP (look-ahead processing), so 1st pass stats are
1481
 * NOT available.
1482
 *
1483
 * \ingroup rate_control
1484
 * \param[in]       cpi          Top level encoder structure
1485
 * \param[in]       width        Coded frame width
1486
 * \param[in]       height       Coded frame height
1487
 * \param[out]      bottom_index Bottom bound for q index (best quality)
1488
 * \param[out]      top_index    Top bound for q index (worst quality)
1489
 * \return Returns selected q index to be used for encoding this frame.
1490
 */
1491
static int rc_pick_q_and_bounds_no_stats(const AV1_COMP *cpi, int width,
1492
                                         int height, int *bottom_index,
1493
0
                                         int *top_index) {
1494
0
  const AV1_COMMON *const cm = &cpi->common;
1495
0
  const RATE_CONTROL *const rc = &cpi->rc;
1496
0
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1497
0
  const CurrentFrame *const current_frame = &cm->current_frame;
1498
0
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1499
0
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
1500
0
  const enum aom_rc_mode rc_mode = oxcf->rc_cfg.mode;
1501
1502
0
  assert(has_no_stats_stage(cpi));
1503
0
  assert(rc_mode == AOM_VBR ||
1504
0
         (!USE_UNRESTRICTED_Q_IN_CQ_MODE && rc_mode == AOM_CQ) ||
1505
0
         rc_mode == AOM_Q);
1506
1507
0
  const int cq_level =
1508
0
      get_active_cq_level(rc, p_rc, oxcf, frame_is_intra_only(cm),
1509
0
                          cpi->superres_mode, cm->superres_scale_denominator);
1510
0
  const int bit_depth = cm->seq_params->bit_depth;
1511
1512
0
  int active_best_quality;
1513
0
  int active_worst_quality = calc_active_worst_quality_no_stats_vbr(cpi);
1514
0
  int q;
1515
0
  int *inter_minq;
1516
0
  ASSIGN_MINQ_TABLE(bit_depth, inter_minq);
1517
1518
0
  if (frame_is_intra_only(cm)) {
1519
0
    if (rc_mode == AOM_Q) {
1520
0
      const int qindex = cq_level;
1521
0
      const double q_val = av1_convert_qindex_to_q(qindex, bit_depth);
1522
0
      const int delta_qindex =
1523
0
          av1_compute_qdelta(rc, q_val, q_val * 0.25, bit_depth);
1524
0
      active_best_quality = AOMMAX(qindex + delta_qindex, rc->best_quality);
1525
0
    } else if (p_rc->this_key_frame_forced) {
1526
#if CONFIG_FPMT_TEST
1527
      const int simulate_parallel_frame =
1528
          cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
1529
          cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
1530
      int qindex = simulate_parallel_frame ? p_rc->temp_last_boosted_qindex
1531
                                           : p_rc->last_boosted_qindex;
1532
#else
1533
0
      int qindex = p_rc->last_boosted_qindex;
1534
0
#endif
1535
0
      const double last_boosted_q = av1_convert_qindex_to_q(qindex, bit_depth);
1536
0
      const int delta_qindex = av1_compute_qdelta(
1537
0
          rc, last_boosted_q, last_boosted_q * 0.75, bit_depth);
1538
0
      active_best_quality = AOMMAX(qindex + delta_qindex, rc->best_quality);
1539
0
    } else {  // not first frame of one pass and kf_boost is set
1540
0
      double q_adj_factor = 1.0;
1541
1542
0
      active_best_quality = get_kf_active_quality(
1543
0
          p_rc, p_rc->avg_frame_qindex[KEY_FRAME], bit_depth);
1544
1545
      // Allow somewhat lower kf minq with small image formats.
1546
0
      if ((width * height) <= (352 * 288)) {
1547
0
        q_adj_factor -= 0.25;
1548
0
      }
1549
1550
      // Convert the adjustment factor to a qindex delta on active_best_quality.
1551
0
      {
1552
0
        const double q_val =
1553
0
            av1_convert_qindex_to_q(active_best_quality, bit_depth);
1554
0
        active_best_quality +=
1555
0
            av1_compute_qdelta(rc, q_val, q_val * q_adj_factor, bit_depth);
1556
0
      }
1557
0
    }
1558
0
  } else if (!rc->is_src_frame_alt_ref &&
1559
0
             (refresh_frame->golden_frame || refresh_frame->alt_ref_frame)) {
1560
    // Use the lower of active_worst_quality and recent
1561
    // average Q as basis for GF/ARF best Q limit unless last frame was
1562
    // a key frame.
1563
0
    q = (rc->frames_since_key > 1 &&
1564
0
         p_rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
1565
0
            ? p_rc->avg_frame_qindex[INTER_FRAME]
1566
0
            : p_rc->avg_frame_qindex[KEY_FRAME];
1567
    // For constrained quality don't allow Q less than the cq level
1568
0
    if (rc_mode == AOM_CQ) {
1569
0
      if (q < cq_level) q = cq_level;
1570
0
      active_best_quality = get_gf_active_quality(p_rc, q, bit_depth);
1571
      // Constrained quality use slightly lower active best.
1572
0
      active_best_quality = active_best_quality * 15 / 16;
1573
0
    } else if (rc_mode == AOM_Q) {
1574
0
      const int qindex = cq_level;
1575
0
      const double q_val = av1_convert_qindex_to_q(qindex, bit_depth);
1576
0
      const int delta_qindex =
1577
0
          (refresh_frame->alt_ref_frame)
1578
0
              ? av1_compute_qdelta(rc, q_val, q_val * 0.40, bit_depth)
1579
0
              : av1_compute_qdelta(rc, q_val, q_val * 0.50, bit_depth);
1580
0
      active_best_quality = AOMMAX(qindex + delta_qindex, rc->best_quality);
1581
0
    } else {
1582
0
      active_best_quality = get_gf_active_quality(p_rc, q, bit_depth);
1583
0
    }
1584
0
  } else {
1585
0
    if (rc_mode == AOM_Q) {
1586
0
      const int qindex = cq_level;
1587
0
      const double q_val = av1_convert_qindex_to_q(qindex, bit_depth);
1588
0
      const double delta_rate[FIXED_GF_INTERVAL] = { 0.50, 1.0, 0.85, 1.0,
1589
0
                                                     0.70, 1.0, 0.85, 1.0 };
1590
0
      const int delta_qindex = av1_compute_qdelta(
1591
0
          rc, q_val,
1592
0
          q_val * delta_rate[current_frame->frame_number % FIXED_GF_INTERVAL],
1593
0
          bit_depth);
1594
0
      active_best_quality = AOMMAX(qindex + delta_qindex, rc->best_quality);
1595
0
    } else {
1596
      // Use the lower of active_worst_quality and recent/average Q.
1597
0
      active_best_quality =
1598
0
          (current_frame->frame_number > 1)
1599
0
              ? inter_minq[p_rc->avg_frame_qindex[INTER_FRAME]]
1600
0
              : inter_minq[p_rc->avg_frame_qindex[KEY_FRAME]];
1601
      // For the constrained quality mode we don't want
1602
      // q to fall below the cq level.
1603
0
      if ((rc_mode == AOM_CQ) && (active_best_quality < cq_level)) {
1604
0
        active_best_quality = cq_level;
1605
0
      }
1606
0
    }
1607
0
  }
1608
1609
  // Clip the active best and worst quality values to limits
1610
0
  active_best_quality =
1611
0
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1612
0
  active_worst_quality =
1613
0
      clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1614
1615
0
  *top_index = active_worst_quality;
1616
0
  *bottom_index = active_best_quality;
1617
1618
  // Limit Q range for the adaptive loop.
1619
0
  {
1620
0
    int qdelta = 0;
1621
0
    if (current_frame->frame_type == KEY_FRAME &&
1622
0
        !p_rc->this_key_frame_forced && current_frame->frame_number != 0) {
1623
0
      qdelta = av1_compute_qdelta_by_rate(cpi, current_frame->frame_type,
1624
0
                                          active_worst_quality, 2.0);
1625
0
    } else if (!rc->is_src_frame_alt_ref &&
1626
0
               (refresh_frame->golden_frame || refresh_frame->alt_ref_frame)) {
1627
0
      qdelta = av1_compute_qdelta_by_rate(cpi, current_frame->frame_type,
1628
0
                                          active_worst_quality, 1.75);
1629
0
    }
1630
0
    *top_index = active_worst_quality + qdelta;
1631
0
    *top_index = AOMMAX(*top_index, *bottom_index);
1632
0
  }
1633
1634
0
  if (rc_mode == AOM_Q) {
1635
0
    q = active_best_quality;
1636
    // Special case code to try and match quality with forced key frames
1637
0
  } else if ((current_frame->frame_type == KEY_FRAME) &&
1638
0
             p_rc->this_key_frame_forced) {
1639
#if CONFIG_FPMT_TEST
1640
    const int simulate_parallel_frame =
1641
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
1642
        cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
1643
    q = simulate_parallel_frame ? p_rc->temp_last_boosted_qindex
1644
                                : p_rc->last_boosted_qindex;
1645
#else
1646
0
    q = p_rc->last_boosted_qindex;
1647
0
#endif
1648
0
  } else {
1649
0
    q = av1_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1650
0
                          active_worst_quality, width, height);
1651
0
    if (q > *top_index) {
1652
      // Special case when we are targeting the max allowed rate
1653
0
      if (rc->this_frame_target >= rc->max_frame_bandwidth)
1654
0
        *top_index = q;
1655
0
      else
1656
0
        q = *top_index;
1657
0
    }
1658
0
  }
1659
1660
0
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1661
0
  assert(*bottom_index <= rc->worst_quality &&
1662
0
         *bottom_index >= rc->best_quality);
1663
0
  assert(q <= rc->worst_quality && q >= rc->best_quality);
1664
0
  return q;
1665
0
}
1666
1667
static const double arf_layer_deltas[MAX_ARF_LAYERS + 1] = { 2.50, 2.00, 1.75,
1668
                                                             1.50, 1.25, 1.15,
1669
                                                             1.0 };
1670
0
static int frame_type_qdelta(const AV1_COMP *cpi, int q) {
1671
0
  const GF_GROUP *const gf_group = &cpi->ppi->gf_group;
1672
0
  const RATE_FACTOR_LEVEL rf_lvl =
1673
0
      get_rate_factor_level(gf_group, cpi->gf_frame_index);
1674
0
  const FRAME_TYPE frame_type = gf_group->frame_type[cpi->gf_frame_index];
1675
0
  const int arf_layer = AOMMIN(gf_group->layer_depth[cpi->gf_frame_index], 6);
1676
0
  const double rate_factor =
1677
0
      (rf_lvl == INTER_NORMAL) ? 1.0 : arf_layer_deltas[arf_layer];
1678
1679
0
  return av1_compute_qdelta_by_rate(cpi, frame_type, q, rate_factor);
1680
0
}
1681
1682
// This unrestricted Q selection on CQ mode is useful when testing new features,
1683
// but may lead to Q being out of range on current RC restrictions
1684
#if USE_UNRESTRICTED_Q_IN_CQ_MODE
1685
static int rc_pick_q_and_bounds_no_stats_cq(const AV1_COMP *cpi, int width,
1686
                                            int height, int *bottom_index,
1687
                                            int *top_index) {
1688
  const AV1_COMMON *const cm = &cpi->common;
1689
  const RATE_CONTROL *const rc = &cpi->rc;
1690
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1691
  const int cq_level =
1692
      get_active_cq_level(rc, oxcf, frame_is_intra_only(cm), cpi->superres_mode,
1693
                          cm->superres_scale_denominator);
1694
  const int bit_depth = cm->seq_params->bit_depth;
1695
  const int q = (int)av1_convert_qindex_to_q(cq_level, bit_depth);
1696
  (void)width;
1697
  (void)height;
1698
  assert(has_no_stats_stage(cpi));
1699
  assert(cpi->oxcf.rc_cfg.mode == AOM_CQ);
1700
1701
  *top_index = q;
1702
  *bottom_index = q;
1703
1704
  return q;
1705
}
1706
#endif  // USE_UNRESTRICTED_Q_IN_CQ_MODE
1707
1708
0
#define STATIC_MOTION_THRESH 95
1709
static void get_intra_q_and_bounds(const AV1_COMP *cpi, int width, int height,
1710
                                   int *active_best, int *active_worst,
1711
82.8k
                                   int cq_level) {
1712
82.8k
  const AV1_COMMON *const cm = &cpi->common;
1713
82.8k
  const RATE_CONTROL *const rc = &cpi->rc;
1714
82.8k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1715
82.8k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1716
82.8k
  int active_best_quality;
1717
82.8k
  int active_worst_quality = *active_worst;
1718
82.8k
  const int bit_depth = cm->seq_params->bit_depth;
1719
1720
82.8k
  if (rc->frames_to_key <= 1 && oxcf->rc_cfg.mode == AOM_Q) {
1721
    // If the next frame is also a key frame or the current frame is the
1722
    // only frame in the sequence in AOM_Q mode, just use the cq_level
1723
    // as q.
1724
65.9k
    active_best_quality = cq_level;
1725
65.9k
    active_worst_quality = cq_level;
1726
65.9k
  } else if (p_rc->this_key_frame_forced) {
1727
    // Handle the special case for key frames forced when we have reached
1728
    // the maximum key frame interval. Here force the Q to a range
1729
    // based on the ambient Q to reduce the risk of popping.
1730
1.53k
    double last_boosted_q;
1731
1.53k
    int delta_qindex;
1732
1.53k
    int qindex;
1733
#if CONFIG_FPMT_TEST
1734
    const int simulate_parallel_frame =
1735
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
1736
        cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
1737
    int last_boosted_qindex = simulate_parallel_frame
1738
                                  ? p_rc->temp_last_boosted_qindex
1739
                                  : p_rc->last_boosted_qindex;
1740
#else
1741
1.53k
    int last_boosted_qindex = p_rc->last_boosted_qindex;
1742
1.53k
#endif
1743
1.53k
    if (is_stat_consumption_stage_twopass(cpi) &&
1744
0
        cpi->ppi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1745
0
      qindex = AOMMIN(p_rc->last_kf_qindex, last_boosted_qindex);
1746
0
      active_best_quality = qindex;
1747
0
      last_boosted_q = av1_convert_qindex_to_q(qindex, bit_depth);
1748
0
      delta_qindex = av1_compute_qdelta(rc, last_boosted_q,
1749
0
                                        last_boosted_q * 1.25, bit_depth);
1750
0
      active_worst_quality =
1751
0
          AOMMIN(qindex + delta_qindex, active_worst_quality);
1752
1.53k
    } else {
1753
1.53k
      qindex = last_boosted_qindex;
1754
1.53k
      last_boosted_q = av1_convert_qindex_to_q(qindex, bit_depth);
1755
1.53k
      delta_qindex = av1_compute_qdelta(rc, last_boosted_q,
1756
1.53k
                                        last_boosted_q * 0.50, bit_depth);
1757
1.53k
      active_best_quality = AOMMAX(qindex + delta_qindex, rc->best_quality);
1758
1.53k
    }
1759
15.3k
  } else {
1760
    // Not forced keyframe.
1761
15.3k
    double q_adj_factor = 1.0;
1762
15.3k
    double q_val;
1763
1764
    // Baseline value derived from active_worst_quality and kf boost.
1765
15.3k
    active_best_quality =
1766
15.3k
        get_kf_active_quality(p_rc, active_worst_quality, bit_depth);
1767
15.3k
    if (cpi->is_screen_content_type) {
1768
0
      active_best_quality /= 2;
1769
0
    }
1770
1771
15.3k
    if (is_stat_consumption_stage_twopass(cpi) &&
1772
0
        cpi->ppi->twopass.kf_zeromotion_pct >= STATIC_KF_GROUP_THRESH) {
1773
0
      active_best_quality /= 3;
1774
0
    }
1775
1776
    // Allow somewhat lower kf minq with small image formats.
1777
15.3k
    if ((width * height) <= (352 * 288)) {
1778
15.3k
      q_adj_factor -= 0.25;
1779
15.3k
    }
1780
1781
    // Make a further adjustment based on the kf zero motion measure.
1782
15.3k
    if (is_stat_consumption_stage_twopass(cpi))
1783
0
      q_adj_factor +=
1784
0
          0.05 - (0.001 * (double)cpi->ppi->twopass.kf_zeromotion_pct);
1785
1786
    // Convert the adjustment factor to a qindex delta
1787
    // on active_best_quality.
1788
15.3k
    q_val = av1_convert_qindex_to_q(active_best_quality, bit_depth);
1789
15.3k
    active_best_quality +=
1790
15.3k
        av1_compute_qdelta(rc, q_val, q_val * q_adj_factor, bit_depth);
1791
1792
    // Tweak active_best_quality for AOM_Q mode when superres is on, as this
1793
    // will be used directly as 'q' later.
1794
15.3k
    if (oxcf->rc_cfg.mode == AOM_Q &&
1795
15.3k
        (cpi->superres_mode == AOM_SUPERRES_QTHRESH ||
1796
15.3k
         cpi->superres_mode == AOM_SUPERRES_AUTO) &&
1797
0
        cm->superres_scale_denominator != SCALE_NUMERATOR) {
1798
0
      active_best_quality =
1799
0
          AOMMAX(active_best_quality -
1800
0
                     ((cm->superres_scale_denominator - SCALE_NUMERATOR) *
1801
0
                      SUPERRES_QADJ_PER_DENOM_KEYFRAME),
1802
0
                 0);
1803
0
    }
1804
15.3k
  }
1805
82.8k
  *active_best = active_best_quality;
1806
82.8k
  *active_worst = active_worst_quality;
1807
82.8k
}
1808
1809
static void adjust_active_best_and_worst_quality(const AV1_COMP *cpi,
1810
                                                 const int is_intrl_arf_boost,
1811
                                                 int *active_worst,
1812
0
                                                 int *active_best) {
1813
0
  const AV1_COMMON *const cm = &cpi->common;
1814
0
  const RATE_CONTROL *const rc = &cpi->rc;
1815
0
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1816
0
  int active_best_quality = *active_best;
1817
0
  int active_worst_quality = *active_worst;
1818
#if CONFIG_FPMT_TEST
1819
#endif
1820
  // Extension to max or min Q if undershoot or overshoot is outside
1821
  // the permitted range.
1822
0
  if (cpi->oxcf.rc_cfg.mode != AOM_Q) {
1823
#if CONFIG_FPMT_TEST
1824
    const int simulate_parallel_frame =
1825
        cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
1826
        cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
1827
    const int extend_minq = simulate_parallel_frame
1828
                                ? p_rc->temp_extend_minq
1829
                                : cpi->ppi->twopass.extend_minq;
1830
    const int extend_maxq = simulate_parallel_frame
1831
                                ? p_rc->temp_extend_maxq
1832
                                : cpi->ppi->twopass.extend_maxq;
1833
    const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
1834
    if (frame_is_intra_only(cm) ||
1835
        (!rc->is_src_frame_alt_ref &&
1836
         (refresh_frame->golden_frame || is_intrl_arf_boost ||
1837
          refresh_frame->alt_ref_frame))) {
1838
      active_best_quality -= extend_minq;
1839
      active_worst_quality += (extend_maxq / 2);
1840
    } else {
1841
      active_best_quality -= extend_minq / 2;
1842
      active_worst_quality += extend_maxq;
1843
    }
1844
#else
1845
0
    (void)is_intrl_arf_boost;
1846
0
    active_best_quality -= cpi->ppi->twopass.extend_minq / 8;
1847
0
    active_worst_quality += cpi->ppi->twopass.extend_maxq / 4;
1848
0
#endif
1849
0
  }
1850
1851
0
#ifndef STRICT_RC
1852
  // Static forced key frames Q restrictions dealt with elsewhere.
1853
0
  if (!(frame_is_intra_only(cm)) || !p_rc->this_key_frame_forced ||
1854
0
      (cpi->ppi->twopass.last_kfgroup_zeromotion_pct < STATIC_MOTION_THRESH)) {
1855
0
    const int qdelta = frame_type_qdelta(cpi, active_worst_quality);
1856
0
    active_worst_quality =
1857
0
        AOMMAX(active_worst_quality + qdelta, active_best_quality);
1858
0
  }
1859
0
#endif
1860
1861
  // Modify active_best_quality for downscaled normal frames.
1862
0
  if (av1_frame_scaled(cm) && !frame_is_kf_gf_arf(cpi)) {
1863
0
    int qdelta = av1_compute_qdelta_by_rate(cpi, cm->current_frame.frame_type,
1864
0
                                            active_best_quality, 2.0);
1865
0
    active_best_quality =
1866
0
        AOMMAX(active_best_quality + qdelta, rc->best_quality);
1867
0
  }
1868
1869
0
  active_best_quality =
1870
0
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1871
0
  active_worst_quality =
1872
0
      clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1873
1874
0
  *active_best = active_best_quality;
1875
0
  *active_worst = active_worst_quality;
1876
0
}
1877
1878
/*!\brief Gets a Q value to use  for the current frame
1879
 *
1880
 *
1881
 * Selects a Q value from a permitted range that we estimate
1882
 * will result in approximately the target number of bits.
1883
 *
1884
 * \ingroup rate_control
1885
 * \param[in]   cpi                   Top level encoder instance structure
1886
 * \param[in]   width                 Width of frame
1887
 * \param[in]   height                Height of frame
1888
 * \param[in]   active_worst_quality  Max Q allowed
1889
 * \param[in]   active_best_quality   Min Q allowed
1890
 *
1891
 * \return The suggested Q for this frame.
1892
 */
1893
static int get_q(const AV1_COMP *cpi, const int width, const int height,
1894
                 const int active_worst_quality,
1895
0
                 const int active_best_quality) {
1896
0
  const AV1_COMMON *const cm = &cpi->common;
1897
0
  const RATE_CONTROL *const rc = &cpi->rc;
1898
0
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1899
0
  int q;
1900
#if CONFIG_FPMT_TEST
1901
  const int simulate_parallel_frame =
1902
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
1903
      cpi->ppi->fpmt_unit_test_cfg;
1904
  int last_boosted_qindex = simulate_parallel_frame
1905
                                ? p_rc->temp_last_boosted_qindex
1906
                                : p_rc->last_boosted_qindex;
1907
#else
1908
0
  int last_boosted_qindex = p_rc->last_boosted_qindex;
1909
0
#endif
1910
1911
0
  if (cpi->oxcf.rc_cfg.mode == AOM_Q ||
1912
0
      (frame_is_intra_only(cm) && !p_rc->this_key_frame_forced &&
1913
0
       cpi->ppi->twopass.kf_zeromotion_pct >= STATIC_KF_GROUP_THRESH &&
1914
0
       rc->frames_to_key > 1)) {
1915
0
    q = active_best_quality;
1916
    // Special case code to try and match quality with forced key frames.
1917
0
  } else if (frame_is_intra_only(cm) && p_rc->this_key_frame_forced) {
1918
    // If static since last kf use better of last boosted and last kf q.
1919
0
    if (cpi->ppi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1920
0
      q = AOMMIN(p_rc->last_kf_qindex, last_boosted_qindex);
1921
0
    } else {
1922
0
      q = AOMMIN(last_boosted_qindex,
1923
0
                 (active_best_quality + active_worst_quality) / 2);
1924
0
    }
1925
0
    q = clamp(q, active_best_quality, active_worst_quality);
1926
0
  } else {
1927
0
    q = av1_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1928
0
                          active_worst_quality, width, height);
1929
0
    if (q > active_worst_quality) {
1930
      // Special case when we are targeting the max allowed rate.
1931
0
      if (rc->this_frame_target < rc->max_frame_bandwidth) {
1932
0
        q = active_worst_quality;
1933
0
      }
1934
0
    }
1935
0
    q = AOMMAX(q, active_best_quality);
1936
0
  }
1937
0
  return q;
1938
0
}
1939
1940
// Returns |active_best_quality| for an inter frame.
1941
// The |active_best_quality| depends on different rate control modes:
1942
// VBR, Q, CQ, CBR.
1943
// The returning active_best_quality could further be adjusted in
1944
// adjust_active_best_and_worst_quality().
1945
static int get_active_best_quality(const AV1_COMP *const cpi,
1946
                                   const int active_worst_quality,
1947
24.6k
                                   const int cq_level, const int gf_index) {
1948
24.6k
  const AV1_COMMON *const cm = &cpi->common;
1949
24.6k
  const int bit_depth = cm->seq_params->bit_depth;
1950
24.6k
  const RATE_CONTROL *const rc = &cpi->rc;
1951
24.6k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
1952
24.6k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
1953
24.6k
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
1954
24.6k
  const GF_GROUP *gf_group = &cpi->ppi->gf_group;
1955
24.6k
  const enum aom_rc_mode rc_mode = oxcf->rc_cfg.mode;
1956
24.6k
  int *inter_minq;
1957
24.6k
  ASSIGN_MINQ_TABLE(bit_depth, inter_minq);
1958
24.6k
  int active_best_quality = 0;
1959
24.6k
  const int is_intrl_arf_boost =
1960
24.6k
      gf_group->update_type[gf_index] == INTNL_ARF_UPDATE;
1961
24.6k
  int is_leaf_frame =
1962
24.6k
      !(gf_group->update_type[gf_index] == ARF_UPDATE ||
1963
24.6k
        gf_group->update_type[gf_index] == GF_UPDATE || is_intrl_arf_boost);
1964
1965
  // TODO(jingning): Consider to rework this hack that covers issues incurred
1966
  // in lightfield setting.
1967
24.6k
  if (cm->tiles.large_scale) {
1968
0
    is_leaf_frame = !(refresh_frame->golden_frame ||
1969
0
                      refresh_frame->alt_ref_frame || is_intrl_arf_boost);
1970
0
  }
1971
24.6k
  const int is_overlay_frame = rc->is_src_frame_alt_ref;
1972
1973
24.6k
  if (is_leaf_frame || is_overlay_frame) {
1974
14.9k
    if (rc_mode == AOM_Q) return cq_level;
1975
1976
0
    active_best_quality = inter_minq[active_worst_quality];
1977
    // For the constrained quality mode we don't want
1978
    // q to fall below the cq level.
1979
0
    if ((rc_mode == AOM_CQ) && (active_best_quality < cq_level)) {
1980
0
      active_best_quality = cq_level;
1981
0
    }
1982
0
    return active_best_quality;
1983
14.9k
  }
1984
1985
  // Determine active_best_quality for frames that are not leaf or overlay.
1986
9.64k
  int q = active_worst_quality;
1987
  // Use the lower of active_worst_quality and recent
1988
  // average Q as basis for GF/ARF best Q limit unless last frame was
1989
  // a key frame.
1990
9.64k
  if (rc->frames_since_key > 1 &&
1991
4.48k
      p_rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1992
34
    q = p_rc->avg_frame_qindex[INTER_FRAME];
1993
34
  }
1994
9.64k
  if (rc_mode == AOM_CQ && q < cq_level) q = cq_level;
1995
9.64k
  active_best_quality = get_gf_active_quality(p_rc, q, bit_depth);
1996
  // Constrained quality use slightly lower active best.
1997
9.64k
  if (rc_mode == AOM_CQ) active_best_quality = active_best_quality * 15 / 16;
1998
9.64k
  const int min_boost = get_gf_high_motion_quality(q, bit_depth);
1999
9.64k
  const int boost = min_boost - active_best_quality;
2000
9.64k
  active_best_quality = min_boost - (int)(boost * p_rc->arf_boost_factor);
2001
9.64k
  if (!is_intrl_arf_boost) return active_best_quality;
2002
2003
0
  if (rc_mode == AOM_Q || rc_mode == AOM_CQ) active_best_quality = p_rc->arf_q;
2004
0
  int this_height = gf_group_pyramid_level(gf_group, gf_index);
2005
0
  while (this_height > 1) {
2006
0
    active_best_quality = (active_best_quality + active_worst_quality + 1) / 2;
2007
0
    --this_height;
2008
0
  }
2009
0
  return active_best_quality;
2010
9.64k
}
2011
2012
static int rc_pick_q_and_bounds_q_mode(const AV1_COMP *cpi, int width,
2013
                                       int height, int gf_index,
2014
107k
                                       int *bottom_index, int *top_index) {
2015
107k
  const AV1_COMMON *const cm = &cpi->common;
2016
107k
  const RATE_CONTROL *const rc = &cpi->rc;
2017
107k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2018
107k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2019
107k
  const int cq_level =
2020
107k
      get_active_cq_level(rc, p_rc, oxcf, frame_is_intra_only(cm),
2021
107k
                          cpi->superres_mode, cm->superres_scale_denominator);
2022
107k
  int active_best_quality = 0;
2023
107k
  int active_worst_quality = rc->active_worst_quality;
2024
107k
  int q;
2025
2026
107k
  if (frame_is_intra_only(cm)) {
2027
82.8k
    get_intra_q_and_bounds(cpi, width, height, &active_best_quality,
2028
82.8k
                           &active_worst_quality, cq_level);
2029
82.8k
  } else {
2030
    //  Active best quality limited by previous layer.
2031
24.6k
    active_best_quality =
2032
24.6k
        get_active_best_quality(cpi, active_worst_quality, cq_level, gf_index);
2033
24.6k
  }
2034
2035
107k
  if (cq_level > 0) active_best_quality = AOMMAX(1, active_best_quality);
2036
2037
107k
  *top_index = clamp(active_worst_quality, rc->best_quality, rc->worst_quality);
2038
2039
107k
  *bottom_index =
2040
107k
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
2041
2042
107k
  q = *bottom_index;
2043
2044
107k
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
2045
107k
  assert(*bottom_index <= rc->worst_quality &&
2046
107k
         *bottom_index >= rc->best_quality);
2047
107k
  assert(q <= rc->worst_quality && q >= rc->best_quality);
2048
2049
107k
  return q;
2050
107k
}
2051
2052
/*!\brief Picks q and q bounds given rate control parameters in \c cpi->rc.
2053
 *
2054
 * Handles the general cases not covered by
2055
 * \ref rc_pick_q_and_bounds_no_stats_cbr() and
2056
 * \ref rc_pick_q_and_bounds_no_stats()
2057
 *
2058
 * \ingroup rate_control
2059
 * \param[in]       cpi          Top level encoder structure
2060
 * \param[in]       width        Coded frame width
2061
 * \param[in]       height       Coded frame height
2062
 * \param[in]       gf_index     Index of this frame in the golden frame group
2063
 * \param[out]      bottom_index Bottom bound for q index (best quality)
2064
 * \param[out]      top_index    Top bound for q index (worst quality)
2065
 * \return Returns selected q index to be used for encoding this frame.
2066
 */
2067
static int rc_pick_q_and_bounds(const AV1_COMP *cpi, int width, int height,
2068
                                int gf_index, int *bottom_index,
2069
107k
                                int *top_index) {
2070
107k
  const AV1_COMMON *const cm = &cpi->common;
2071
107k
  const RATE_CONTROL *const rc = &cpi->rc;
2072
107k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2073
107k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2074
107k
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
2075
107k
  const GF_GROUP *gf_group = &cpi->ppi->gf_group;
2076
107k
  assert(IMPLIES(has_no_stats_stage(cpi),
2077
107k
                 cpi->oxcf.rc_cfg.mode == AOM_Q &&
2078
107k
                     gf_group->update_type[gf_index] != ARF_UPDATE));
2079
107k
  const int cq_level =
2080
107k
      get_active_cq_level(rc, p_rc, oxcf, frame_is_intra_only(cm),
2081
107k
                          cpi->superres_mode, cm->superres_scale_denominator);
2082
2083
107k
  if (oxcf->rc_cfg.mode == AOM_Q) {
2084
107k
    return rc_pick_q_and_bounds_q_mode(cpi, width, height, gf_index,
2085
107k
                                       bottom_index, top_index);
2086
107k
  }
2087
2088
0
  int active_best_quality = 0;
2089
0
  int active_worst_quality = rc->active_worst_quality;
2090
0
  int q;
2091
2092
0
  const int is_intrl_arf_boost =
2093
0
      gf_group->update_type[gf_index] == INTNL_ARF_UPDATE;
2094
2095
0
  if (frame_is_intra_only(cm)) {
2096
0
    get_intra_q_and_bounds(cpi, width, height, &active_best_quality,
2097
0
                           &active_worst_quality, cq_level);
2098
#ifdef STRICT_RC
2099
    active_best_quality = 0;
2100
#endif
2101
0
  } else {
2102
    //  Active best quality limited by previous layer.
2103
0
    const int pyramid_level = gf_group_pyramid_level(gf_group, gf_index);
2104
2105
0
    if ((pyramid_level <= 1) || (pyramid_level > MAX_ARF_LAYERS)) {
2106
0
      active_best_quality = get_active_best_quality(cpi, active_worst_quality,
2107
0
                                                    cq_level, gf_index);
2108
0
    } else {
2109
#if CONFIG_FPMT_TEST
2110
      const int simulate_parallel_frame =
2111
          cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
2112
          cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
2113
      int local_active_best_quality =
2114
          simulate_parallel_frame
2115
              ? p_rc->temp_active_best_quality[pyramid_level - 1]
2116
              : p_rc->active_best_quality[pyramid_level - 1];
2117
      active_best_quality = local_active_best_quality + 1;
2118
#else
2119
0
      active_best_quality = p_rc->active_best_quality[pyramid_level - 1] + 1;
2120
0
#endif
2121
2122
0
      active_best_quality = AOMMIN(active_best_quality, active_worst_quality);
2123
#ifdef STRICT_RC
2124
      active_best_quality += (active_worst_quality - active_best_quality) / 16;
2125
#else
2126
0
      active_best_quality += (active_worst_quality - active_best_quality) / 2;
2127
0
#endif
2128
0
    }
2129
2130
    // For alt_ref and GF frames (including internal arf frames) adjust the
2131
    // worst allowed quality as well. This insures that even on hard
2132
    // sections we don't clamp the Q at the same value for arf frames and
2133
    // leaf (non arf) frames. This is important to the TPL model which assumes
2134
    // Q drops with each arf level.
2135
0
    if (!(rc->is_src_frame_alt_ref) &&
2136
0
        (refresh_frame->golden_frame || refresh_frame->alt_ref_frame ||
2137
0
         is_intrl_arf_boost)) {
2138
0
      active_worst_quality =
2139
0
          (active_best_quality + (3 * active_worst_quality) + 2) / 4;
2140
0
    }
2141
0
  }
2142
2143
0
  adjust_active_best_and_worst_quality(
2144
0
      cpi, is_intrl_arf_boost, &active_worst_quality, &active_best_quality);
2145
0
  q = get_q(cpi, width, height, active_worst_quality, active_best_quality);
2146
2147
  // Special case when we are targeting the max allowed rate.
2148
0
  if (rc->this_frame_target >= rc->max_frame_bandwidth &&
2149
0
      q > active_worst_quality) {
2150
0
    active_worst_quality = q;
2151
0
  }
2152
2153
0
  *top_index = active_worst_quality;
2154
0
  *bottom_index = active_best_quality;
2155
2156
0
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
2157
0
  assert(*bottom_index <= rc->worst_quality &&
2158
0
         *bottom_index >= rc->best_quality);
2159
0
  assert(q <= rc->worst_quality && q >= rc->best_quality);
2160
2161
0
  return q;
2162
107k
}
2163
2164
0
static void rc_compute_variance_onepass_rt(AV1_COMP *cpi) {
2165
0
  AV1_COMMON *const cm = &cpi->common;
2166
0
  YV12_BUFFER_CONFIG const *const unscaled_src = cpi->unscaled_source;
2167
0
  if (unscaled_src == NULL) return;
2168
2169
0
  const uint8_t *src_y = unscaled_src->y_buffer;
2170
0
  const int src_ystride = unscaled_src->y_stride;
2171
0
  const YV12_BUFFER_CONFIG *yv12 = get_ref_frame_yv12_buf(cm, LAST_FRAME);
2172
0
  const uint8_t *pre_y = yv12->buffers[0];
2173
0
  const int pre_ystride = yv12->strides[0];
2174
2175
  // TODO(yunqing): support scaled reference frames.
2176
0
  if (cpi->scaled_ref_buf[LAST_FRAME - 1]) return;
2177
2178
0
  for (int i = 0; i < 2; ++i) {
2179
0
    if (unscaled_src->widths[i] != yv12->widths[i] ||
2180
0
        unscaled_src->heights[i] != yv12->heights[i]) {
2181
0
      return;
2182
0
    }
2183
0
  }
2184
2185
0
  const int num_mi_cols = cm->mi_params.mi_cols;
2186
0
  const int num_mi_rows = cm->mi_params.mi_rows;
2187
0
  const BLOCK_SIZE bsize = BLOCK_64X64;
2188
0
  int num_samples = 0;
2189
  // sse is computed on 64x64 blocks
2190
0
  const int sb_size_by_mb = (cm->seq_params->sb_size == BLOCK_128X128)
2191
0
                                ? (cm->seq_params->mib_size >> 1)
2192
0
                                : cm->seq_params->mib_size;
2193
0
  const int sb_cols = (num_mi_cols + sb_size_by_mb - 1) / sb_size_by_mb;
2194
0
  const int sb_rows = (num_mi_rows + sb_size_by_mb - 1) / sb_size_by_mb;
2195
2196
0
  uint64_t fsse = 0;
2197
0
  cpi->rec_sse = 0;
2198
2199
0
  for (int sbi_row = 0; sbi_row < sb_rows; ++sbi_row) {
2200
0
    for (int sbi_col = 0; sbi_col < sb_cols; ++sbi_col) {
2201
0
      unsigned int sse;
2202
0
      uint8_t src[64 * 64] = { 0 };
2203
      // Apply 4x4 block averaging/denoising on source frame.
2204
0
      for (int i = 0; i < 64; i += 4) {
2205
0
        for (int j = 0; j < 64; j += 4) {
2206
0
          const unsigned int avg =
2207
0
              aom_avg_4x4(src_y + i * src_ystride + j, src_ystride);
2208
2209
0
          for (int m = 0; m < 4; ++m) {
2210
0
            for (int n = 0; n < 4; ++n) src[i * 64 + j + m * 64 + n] = avg;
2211
0
          }
2212
0
        }
2213
0
      }
2214
2215
0
      cpi->ppi->fn_ptr[bsize].vf(src, 64, pre_y, pre_ystride, &sse);
2216
0
      fsse += sse;
2217
0
      num_samples++;
2218
0
      src_y += 64;
2219
0
      pre_y += 64;
2220
0
    }
2221
0
    src_y += (src_ystride << 6) - (sb_cols << 6);
2222
0
    pre_y += (pre_ystride << 6) - (sb_cols << 6);
2223
0
  }
2224
0
  assert(num_samples > 0);
2225
  // Ensure rec_sse > 0
2226
0
  if (num_samples > 0) cpi->rec_sse = fsse > 0 ? fsse : 1;
2227
0
}
2228
2229
int av1_rc_pick_q_and_bounds(AV1_COMP *cpi, int width, int height, int gf_index,
2230
129k
                             int *bottom_index, int *top_index) {
2231
129k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2232
129k
  int q;
2233
  // TODO(sarahparker) merge no-stats vbr and altref q computation
2234
  // with rc_pick_q_and_bounds().
2235
129k
  const GF_GROUP *gf_group = &cpi->ppi->gf_group;
2236
129k
  if ((cpi->oxcf.rc_cfg.mode != AOM_Q ||
2237
107k
       gf_group->update_type[gf_index] == ARF_UPDATE) &&
2238
21.6k
      has_no_stats_stage(cpi)) {
2239
21.6k
    if (cpi->oxcf.rc_cfg.mode == AOM_CBR) {
2240
      // TODO(yunqing): the results could be used for encoder optimization.
2241
21.6k
      cpi->rec_sse = UINT64_MAX;
2242
21.6k
      if (cpi->sf.hl_sf.accurate_bit_estimate &&
2243
0
          cpi->common.current_frame.frame_type != KEY_FRAME)
2244
0
        rc_compute_variance_onepass_rt(cpi);
2245
2246
21.6k
      q = rc_pick_q_and_bounds_no_stats_cbr(cpi, width, height, bottom_index,
2247
21.6k
                                            top_index);
2248
      // preserve copy of active worst quality selected.
2249
21.6k
      cpi->rc.active_worst_quality = *top_index;
2250
2251
#if USE_UNRESTRICTED_Q_IN_CQ_MODE
2252
    } else if (cpi->oxcf.rc_cfg.mode == AOM_CQ) {
2253
      q = rc_pick_q_and_bounds_no_stats_cq(cpi, width, height, bottom_index,
2254
                                           top_index);
2255
#endif  // USE_UNRESTRICTED_Q_IN_CQ_MODE
2256
21.6k
    } else {
2257
0
      q = rc_pick_q_and_bounds_no_stats(cpi, width, height, bottom_index,
2258
0
                                        top_index);
2259
0
    }
2260
107k
  } else {
2261
107k
    q = rc_pick_q_and_bounds(cpi, width, height, gf_index, bottom_index,
2262
107k
                             top_index);
2263
107k
  }
2264
129k
  if (gf_group->update_type[gf_index] == ARF_UPDATE) p_rc->arf_q = q;
2265
2266
129k
  return q;
2267
129k
}
2268
2269
void av1_rc_compute_frame_size_bounds(const AV1_COMP *cpi, int frame_target,
2270
                                      int *frame_under_shoot_limit,
2271
0
                                      int *frame_over_shoot_limit) {
2272
0
  if (cpi->oxcf.rc_cfg.mode == AOM_Q) {
2273
0
    *frame_under_shoot_limit = 0;
2274
0
    *frame_over_shoot_limit = INT_MAX;
2275
0
  } else {
2276
    // For very small rate targets where the fractional adjustment
2277
    // may be tiny make sure there is at least a minimum range.
2278
0
    assert(cpi->sf.hl_sf.recode_tolerance <= 100);
2279
0
    const int tolerance = (int)AOMMAX(
2280
0
        100, ((int64_t)cpi->sf.hl_sf.recode_tolerance * frame_target) / 100);
2281
0
    *frame_under_shoot_limit = AOMMAX(frame_target - tolerance, 0);
2282
0
    *frame_over_shoot_limit = (int)AOMMIN((int64_t)frame_target + tolerance,
2283
0
                                          cpi->rc.max_frame_bandwidth);
2284
0
  }
2285
0
}
2286
2287
127k
void av1_rc_set_frame_target(AV1_COMP *cpi, int target, int width, int height) {
2288
127k
  const AV1_COMMON *const cm = &cpi->common;
2289
127k
  RATE_CONTROL *const rc = &cpi->rc;
2290
2291
127k
  rc->this_frame_target = target;
2292
2293
  // Modify frame size target when down-scaled.
2294
127k
  if (av1_frame_scaled(cm) && cpi->oxcf.rc_cfg.mode != AOM_CBR) {
2295
0
    rc->this_frame_target = saturate_cast_double_to_int(
2296
0
        rc->this_frame_target *
2297
0
        resize_rate_factor(&cpi->oxcf.frm_dim_cfg, width, height));
2298
0
  }
2299
2300
  // Target rate per SB64 (including partial SB64s.
2301
127k
  const int64_t sb64_target_rate =
2302
127k
      ((int64_t)rc->this_frame_target << 12) / (width * height);
2303
127k
  rc->sb64_target_rate = (int)AOMMIN(sb64_target_rate, INT_MAX);
2304
127k
}
2305
2306
0
static void update_alt_ref_frame_stats(AV1_COMP *cpi) {
2307
  // this frame refreshes means next frames don't unless specified by user
2308
0
  RATE_CONTROL *const rc = &cpi->rc;
2309
0
  rc->frames_since_golden = 0;
2310
0
}
2311
2312
108k
static void update_golden_frame_stats(AV1_COMP *cpi) {
2313
108k
  RATE_CONTROL *const rc = &cpi->rc;
2314
2315
  // Update the Golden frame usage counts.
2316
108k
  if (cpi->refresh_frame.golden_frame || rc->is_src_frame_alt_ref) {
2317
91.0k
    rc->frames_since_golden = 0;
2318
91.0k
  } else if (cpi->common.show_frame) {
2319
17.6k
    rc->frames_since_golden++;
2320
17.6k
  }
2321
108k
}
2322
2323
108k
void av1_rc_postencode_update(AV1_COMP *cpi, uint64_t bytes_used) {
2324
108k
  const AV1_COMMON *const cm = &cpi->common;
2325
108k
  const CurrentFrame *const current_frame = &cm->current_frame;
2326
108k
  RATE_CONTROL *const rc = &cpi->rc;
2327
108k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2328
108k
  const GF_GROUP *const gf_group = &cpi->ppi->gf_group;
2329
108k
  const RefreshFrameInfo *const refresh_frame = &cpi->refresh_frame;
2330
2331
108k
  const int is_intrnl_arf =
2332
108k
      gf_group->update_type[cpi->gf_frame_index] == INTNL_ARF_UPDATE;
2333
2334
108k
  const int qindex = cm->quant_params.base_qindex;
2335
2336
#if RT_PASSIVE_STRATEGY
2337
  const int frame_number = current_frame->frame_number % MAX_Q_HISTORY;
2338
  p_rc->q_history[frame_number] = qindex;
2339
#endif  // RT_PASSIVE_STRATEGY
2340
2341
  // Update rate control heuristics
2342
108k
  rc->projected_frame_size = (int)(bytes_used << 3);
2343
2344
  // Post encode loop adjustment of Q prediction.
2345
108k
  av1_rc_update_rate_correction_factors(cpi, 0, cm->width, cm->height);
2346
2347
  // Update bit estimation ratio.
2348
108k
  if (cpi->oxcf.rc_cfg.mode == AOM_CBR &&
2349
21.6k
      cm->current_frame.frame_type != KEY_FRAME &&
2350
10.2k
      cpi->sf.hl_sf.accurate_bit_estimate) {
2351
0
    const double q = av1_convert_qindex_to_q(cm->quant_params.base_qindex,
2352
0
                                             cm->seq_params->bit_depth);
2353
0
    const int this_bit_est_ratio =
2354
0
        (int)(rc->projected_frame_size * q / sqrt((double)cpi->rec_sse));
2355
0
    cpi->rc.bit_est_ratio =
2356
0
        cpi->rc.bit_est_ratio == 0
2357
0
            ? this_bit_est_ratio
2358
0
            : (7 * cpi->rc.bit_est_ratio + this_bit_est_ratio) / 8;
2359
0
  }
2360
2361
  // Keep a record of last Q and ambient average Q.
2362
108k
  if (current_frame->frame_type == KEY_FRAME) {
2363
81.3k
    p_rc->last_q[KEY_FRAME] = qindex;
2364
81.3k
    p_rc->avg_frame_qindex[KEY_FRAME] =
2365
81.3k
        ROUND_POWER_OF_TWO(3 * p_rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
2366
81.3k
    if (cpi->svc.spatial_layer_id == 0) {
2367
81.3k
      rc->last_encoded_size_keyframe = rc->projected_frame_size;
2368
81.3k
      rc->last_target_size_keyframe = rc->this_frame_target;
2369
81.3k
    }
2370
81.3k
  } else {
2371
27.3k
    if ((cpi->ppi->use_svc && cpi->oxcf.rc_cfg.mode == AOM_CBR) ||
2372
27.3k
        cpi->rc.rtc_external_ratectrl ||
2373
27.3k
        (!rc->is_src_frame_alt_ref &&
2374
27.3k
         !(refresh_frame->golden_frame || is_intrnl_arf ||
2375
17.6k
           refresh_frame->alt_ref_frame))) {
2376
17.6k
      p_rc->last_q[INTER_FRAME] = qindex;
2377
17.6k
      p_rc->avg_frame_qindex[INTER_FRAME] = ROUND_POWER_OF_TWO(
2378
17.6k
          3 * p_rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
2379
17.6k
      p_rc->ni_frames++;
2380
17.6k
      p_rc->tot_q += av1_convert_qindex_to_q(qindex, cm->seq_params->bit_depth);
2381
17.6k
      p_rc->avg_q = p_rc->tot_q / p_rc->ni_frames;
2382
      // Calculate the average Q for normal inter frames (not key or GFU
2383
      // frames).
2384
17.6k
      rc->ni_tot_qi += qindex;
2385
17.6k
      rc->ni_av_qi = rc->ni_tot_qi / p_rc->ni_frames;
2386
17.6k
    }
2387
27.3k
  }
2388
  // Keep record of last boosted (KF/GF/ARF) Q value.
2389
  // If the current frame is coded at a lower Q then we also update it.
2390
  // If all mbs in this group are skipped only update if the Q value is
2391
  // better than that already stored.
2392
  // This is used to help set quality in forced key frames to reduce popping
2393
108k
  if ((qindex < p_rc->last_boosted_qindex) ||
2394
106k
      (current_frame->frame_type == KEY_FRAME) ||
2395
26.8k
      (!p_rc->constrained_gf_group &&
2396
19.7k
       (refresh_frame->alt_ref_frame || is_intrnl_arf ||
2397
91.3k
        (refresh_frame->golden_frame && !rc->is_src_frame_alt_ref)))) {
2398
91.3k
    p_rc->last_boosted_qindex = qindex;
2399
91.3k
  }
2400
108k
  if (current_frame->frame_type == KEY_FRAME) p_rc->last_kf_qindex = qindex;
2401
2402
108k
  update_buffer_level(cpi, rc->projected_frame_size);
2403
108k
  rc->prev_avg_frame_bandwidth = rc->avg_frame_bandwidth;
2404
2405
  // Rolling monitors of whether we are over or underspending used to help
2406
  // regulate min and Max Q in two pass.
2407
108k
  if (av1_frame_scaled(cm))
2408
0
    rc->this_frame_target = saturate_cast_double_to_int(
2409
0
        rc->this_frame_target /
2410
0
        resize_rate_factor(&cpi->oxcf.frm_dim_cfg, cm->width, cm->height));
2411
108k
  if (current_frame->frame_type != KEY_FRAME) {
2412
27.3k
    p_rc->rolling_target_bits = (int)ROUND_POWER_OF_TWO_64(
2413
27.3k
        (int64_t)p_rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
2414
27.3k
    p_rc->rolling_actual_bits = (int)ROUND_POWER_OF_TWO_64(
2415
27.3k
        (int64_t)p_rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
2416
27.3k
  }
2417
2418
  // Actual bits spent
2419
108k
  p_rc->total_actual_bits += rc->projected_frame_size;
2420
108k
  p_rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
2421
2422
108k
  if (is_altref_enabled(cpi->oxcf.gf_cfg.lag_in_frames,
2423
108k
                        cpi->oxcf.gf_cfg.enable_auto_arf) &&
2424
18.7k
      refresh_frame->alt_ref_frame &&
2425
11.3k
      (current_frame->frame_type != KEY_FRAME && !frame_is_sframe(cm)))
2426
    // Update the alternate reference frame stats as appropriate.
2427
0
    update_alt_ref_frame_stats(cpi);
2428
108k
  else
2429
    // Update the Golden frame stats as appropriate.
2430
108k
    update_golden_frame_stats(cpi);
2431
2432
#if CONFIG_FPMT_TEST
2433
  /*The variables temp_avg_frame_qindex, temp_last_q, temp_avg_q,
2434
   * temp_last_boosted_qindex are introduced only for quality simulation
2435
   * purpose, it retains the value previous to the parallel encode frames. The
2436
   * variables are updated based on the update flag.
2437
   *
2438
   * If there exist show_existing_frames between parallel frames, then to
2439
   * retain the temp state do not update it. */
2440
  int show_existing_between_parallel_frames =
2441
      (cpi->ppi->gf_group.update_type[cpi->gf_frame_index] ==
2442
           INTNL_OVERLAY_UPDATE &&
2443
       cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index + 1] == 2);
2444
2445
  if (cpi->do_frame_data_update && !show_existing_between_parallel_frames &&
2446
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE) {
2447
    for (int i = 0; i < FRAME_TYPES; i++) {
2448
      p_rc->temp_last_q[i] = p_rc->last_q[i];
2449
    }
2450
    p_rc->temp_avg_q = p_rc->avg_q;
2451
    p_rc->temp_last_boosted_qindex = p_rc->last_boosted_qindex;
2452
    p_rc->temp_total_actual_bits = p_rc->total_actual_bits;
2453
    p_rc->temp_projected_frame_size = rc->projected_frame_size;
2454
    for (int i = 0; i < RATE_FACTOR_LEVELS; i++)
2455
      p_rc->temp_rate_correction_factors[i] = p_rc->rate_correction_factors[i];
2456
  }
2457
#endif
2458
108k
  if (current_frame->frame_type == KEY_FRAME) {
2459
81.3k
    rc->frames_since_key = 0;
2460
81.3k
    rc->frames_since_scene_change = 0;
2461
81.3k
  }
2462
108k
  if (cpi->refresh_frame.golden_frame)
2463
91.0k
    rc->frame_num_last_gf_refresh = current_frame->frame_number;
2464
108k
  rc->prev_coded_width = cm->width;
2465
108k
  rc->prev_coded_height = cm->height;
2466
108k
  rc->frame_number_encoded++;
2467
108k
  rc->prev_frame_is_dropped = 0;
2468
108k
  rc->drop_count_consec = 0;
2469
108k
}
2470
2471
0
void av1_rc_postencode_update_drop_frame(AV1_COMP *cpi) {
2472
  // Update buffer level with zero size, update frame counters, and return.
2473
0
  update_buffer_level(cpi, 0);
2474
0
  cpi->rc.rc_2_frame = 0;
2475
0
  cpi->rc.rc_1_frame = 0;
2476
0
  cpi->rc.prev_avg_frame_bandwidth = cpi->rc.avg_frame_bandwidth;
2477
0
  cpi->rc.prev_coded_width = cpi->common.width;
2478
0
  cpi->rc.prev_coded_height = cpi->common.height;
2479
0
  cpi->rc.prev_frame_is_dropped = 1;
2480
  // On a scene/slide change for dropped frame: reset the avg_source_sad to 0,
2481
  // otherwise the avg_source_sad can get too large and subsequent frames
2482
  // may miss the scene/slide detection.
2483
0
  if (cpi->rc.high_source_sad) cpi->rc.avg_source_sad = 0;
2484
0
  if (cpi->ppi->use_svc && cpi->svc.number_spatial_layers > 1) {
2485
0
    cpi->svc.last_layer_dropped[cpi->svc.spatial_layer_id] = true;
2486
0
    cpi->svc.drop_spatial_layer[cpi->svc.spatial_layer_id] = true;
2487
0
  }
2488
0
  if (cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1) {
2489
0
    cpi->svc.prev_number_spatial_layers = cpi->svc.number_spatial_layers;
2490
0
  }
2491
0
  cpi->svc.prev_number_temporal_layers = cpi->svc.number_temporal_layers;
2492
0
}
2493
2494
int av1_find_qindex(double desired_q, aom_bit_depth_t bit_depth,
2495
152k
                    int best_qindex, int worst_qindex) {
2496
152k
  assert(best_qindex <= worst_qindex);
2497
152k
  int low = best_qindex;
2498
152k
  int high = worst_qindex;
2499
1.29M
  while (low < high) {
2500
1.14M
    const int mid = (low + high) >> 1;
2501
1.14M
    const double mid_q = av1_convert_qindex_to_q(mid, bit_depth);
2502
1.14M
    if (mid_q < desired_q) {
2503
293k
      low = mid + 1;
2504
850k
    } else {
2505
850k
      high = mid;
2506
850k
    }
2507
1.14M
  }
2508
152k
  assert(low == high);
2509
152k
  assert(av1_convert_qindex_to_q(low, bit_depth) >= desired_q ||
2510
152k
         low == worst_qindex);
2511
152k
  return low;
2512
152k
}
2513
2514
int av1_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
2515
16.9k
                       aom_bit_depth_t bit_depth) {
2516
16.9k
  const int start_index =
2517
16.9k
      av1_find_qindex(qstart, bit_depth, rc->best_quality, rc->worst_quality);
2518
16.9k
  const int target_index =
2519
16.9k
      av1_find_qindex(qtarget, bit_depth, rc->best_quality, rc->worst_quality);
2520
16.9k
  return target_index - start_index;
2521
16.9k
}
2522
2523
// Find q_index for the desired_bits_per_mb, within [best_qindex, worst_qindex],
2524
// assuming 'correction_factor' is 1.0.
2525
// To be precise, 'q_index' is the smallest integer, for which the corresponding
2526
// bits per mb <= desired_bits_per_mb.
2527
// If no such q index is found, returns 'worst_qindex'.
2528
static int find_qindex_by_rate(const AV1_COMP *const cpi,
2529
                               int desired_bits_per_mb, FRAME_TYPE frame_type,
2530
0
                               int best_qindex, int worst_qindex) {
2531
0
  assert(best_qindex <= worst_qindex);
2532
0
  int low = best_qindex;
2533
0
  int high = worst_qindex;
2534
0
  while (low < high) {
2535
0
    const int mid = (low + high) >> 1;
2536
0
    const int mid_bits_per_mb =
2537
0
        av1_rc_bits_per_mb(cpi, frame_type, mid, 1.0, 0);
2538
0
    if (mid_bits_per_mb > desired_bits_per_mb) {
2539
0
      low = mid + 1;
2540
0
    } else {
2541
0
      high = mid;
2542
0
    }
2543
0
  }
2544
0
  assert(low == high);
2545
0
  assert(av1_rc_bits_per_mb(cpi, frame_type, low, 1.0, 0) <=
2546
0
             desired_bits_per_mb ||
2547
0
         low == worst_qindex);
2548
0
  return low;
2549
0
}
2550
2551
int av1_compute_qdelta_by_rate(const AV1_COMP *cpi, FRAME_TYPE frame_type,
2552
0
                               int qindex, double rate_target_ratio) {
2553
0
  const RATE_CONTROL *rc = &cpi->rc;
2554
2555
  // Look up the current projected bits per block for the base index
2556
0
  const int base_bits_per_mb =
2557
0
      av1_rc_bits_per_mb(cpi, frame_type, qindex, 1.0, 0);
2558
2559
  // Find the target bits per mb based on the base value and given ratio.
2560
0
  const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
2561
2562
0
  const int target_index = find_qindex_by_rate(
2563
0
      cpi, target_bits_per_mb, frame_type, rc->best_quality, rc->worst_quality);
2564
0
  return target_index - qindex;
2565
0
}
2566
2567
static void set_gf_interval_range(const AV1_COMP *const cpi,
2568
668k
                                  RATE_CONTROL *const rc) {
2569
668k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2570
2571
  // Special case code for 1 pass fixed Q mode tests
2572
668k
  if ((has_no_stats_stage(cpi)) && (oxcf->rc_cfg.mode == AOM_Q)) {
2573
472k
    rc->max_gf_interval = oxcf->gf_cfg.max_gf_interval;
2574
472k
    rc->min_gf_interval = oxcf->gf_cfg.min_gf_interval;
2575
472k
    rc->static_scene_max_gf_interval = rc->min_gf_interval + 1;
2576
472k
  } else {
2577
    // Set Maximum gf/arf interval
2578
195k
    rc->max_gf_interval = oxcf->gf_cfg.max_gf_interval;
2579
195k
    rc->min_gf_interval = oxcf->gf_cfg.min_gf_interval;
2580
195k
    if (rc->min_gf_interval == 0)
2581
195k
      rc->min_gf_interval = av1_rc_get_default_min_gf_interval(
2582
195k
          oxcf->frm_dim_cfg.width, oxcf->frm_dim_cfg.height, cpi->framerate);
2583
195k
    if (rc->max_gf_interval == 0)
2584
195k
      rc->max_gf_interval =
2585
195k
          get_default_max_gf_interval(cpi->framerate, rc->min_gf_interval);
2586
    /*
2587
     * Extended max interval for genuinely static scenes like slide shows.
2588
     * The no.of.stats available in the case of LAP is limited,
2589
     * hence setting to max_gf_interval.
2590
     */
2591
195k
    if (cpi->ppi->lap_enabled)
2592
131k
      rc->static_scene_max_gf_interval = rc->max_gf_interval + 1;
2593
64.0k
    else
2594
64.0k
      rc->static_scene_max_gf_interval = MAX_STATIC_GF_GROUP_LENGTH;
2595
2596
195k
    if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
2597
0
      rc->max_gf_interval = rc->static_scene_max_gf_interval;
2598
2599
    // Clamp min to max
2600
195k
    rc->min_gf_interval = AOMMIN(rc->min_gf_interval, rc->max_gf_interval);
2601
195k
  }
2602
668k
}
2603
2604
668k
void av1_rc_update_framerate(AV1_COMP *cpi, int width, int height) {
2605
668k
  const AV1EncoderConfig *const oxcf = &cpi->oxcf;
2606
668k
  RATE_CONTROL *const rc = &cpi->rc;
2607
668k
  const int MBs = av1_get_MBs(width, height);
2608
2609
668k
  rc->avg_frame_bandwidth = saturate_cast_double_to_int(
2610
668k
      round(oxcf->rc_cfg.target_bandwidth / cpi->framerate));
2611
2612
668k
  int64_t vbr_min_bits =
2613
668k
      (int64_t)rc->avg_frame_bandwidth * oxcf->rc_cfg.vbrmin_section / 100;
2614
668k
  vbr_min_bits = AOMMIN(vbr_min_bits, INT_MAX);
2615
2616
668k
  rc->min_frame_bandwidth = AOMMAX((int)vbr_min_bits, FRAME_OVERHEAD_BITS);
2617
2618
  // A maximum bitrate for a frame is defined.
2619
  // The baseline for this aligns with HW implementations that
2620
  // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
2621
  // per 16x16 MB (averaged over a frame). However this limit is extended if
2622
  // a very high rate is given on the command line or the rate cannot
2623
  // be achieved because of a user specified max q (e.g. when the user
2624
  // specifies lossless encode.
2625
668k
  int64_t vbr_max_bits =
2626
668k
      (int64_t)rc->avg_frame_bandwidth * oxcf->rc_cfg.vbrmax_section / 100;
2627
668k
  vbr_max_bits = AOMMIN(vbr_max_bits, INT_MAX);
2628
2629
668k
  rc->max_frame_bandwidth =
2630
668k
      AOMMAX(AOMMAX((MBs * MAX_MB_RATE), MAXRATE_1080P), (int)vbr_max_bits);
2631
2632
668k
  set_gf_interval_range(cpi, rc);
2633
668k
}
2634
2635
#define VBR_PCT_ADJUSTMENT_LIMIT 50
2636
// For VBR...adjustment to the frame target based on error from previous frames
2637
0
static void vbr_rate_correction(AV1_COMP *cpi, int *this_frame_target) {
2638
0
  RATE_CONTROL *const rc = &cpi->rc;
2639
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2640
#if CONFIG_FPMT_TEST
2641
  const int simulate_parallel_frame =
2642
      cpi->ppi->gf_group.frame_parallel_level[cpi->gf_frame_index] > 0 &&
2643
      cpi->ppi->fpmt_unit_test_cfg == PARALLEL_SIMULATION_ENCODE;
2644
  int64_t vbr_bits_off_target = simulate_parallel_frame
2645
                                    ? cpi->ppi->p_rc.temp_vbr_bits_off_target
2646
                                    : p_rc->vbr_bits_off_target;
2647
#else
2648
0
  int64_t vbr_bits_off_target = p_rc->vbr_bits_off_target;
2649
0
#endif
2650
0
  int64_t frame_target = *this_frame_target;
2651
2652
0
  const double stats_count =
2653
0
      cpi->ppi->twopass.stats_buf_ctx->total_stats != NULL
2654
0
          ? cpi->ppi->twopass.stats_buf_ctx->total_stats->count
2655
0
          : 0.0;
2656
0
  const int frame_window =
2657
0
      (int)AOMMIN(16, stats_count - cpi->common.current_frame.frame_number);
2658
0
  assert(VBR_PCT_ADJUSTMENT_LIMIT <= 100);
2659
0
  if (frame_window > 0) {
2660
0
    const int64_t max_delta =
2661
0
        AOMMIN(llabs((vbr_bits_off_target / frame_window)),
2662
0
               (frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100);
2663
2664
    // vbr_bits_off_target > 0 means we have extra bits to spend
2665
    // vbr_bits_off_target < 0 we are currently overshooting
2666
0
    frame_target += (vbr_bits_off_target >= 0) ? max_delta : -max_delta;
2667
0
  }
2668
2669
#if CONFIG_FPMT_TEST
2670
  int64_t vbr_bits_off_target_fast =
2671
      simulate_parallel_frame ? cpi->ppi->p_rc.temp_vbr_bits_off_target_fast
2672
                              : p_rc->vbr_bits_off_target_fast;
2673
#endif
2674
  // Fast redistribution of bits arising from massive local undershoot.
2675
  // Don't do it for kf,arf,gf or overlay frames.
2676
0
  if (!frame_is_kf_gf_arf(cpi) &&
2677
#if CONFIG_FPMT_TEST
2678
      vbr_bits_off_target_fast &&
2679
#else
2680
0
      p_rc->vbr_bits_off_target_fast &&
2681
0
#endif
2682
0
      !rc->is_src_frame_alt_ref) {
2683
0
    int64_t one_frame_bits = AOMMAX(rc->avg_frame_bandwidth, frame_target);
2684
0
    int64_t fast_extra_bits;
2685
#if CONFIG_FPMT_TEST
2686
    fast_extra_bits = AOMMIN(vbr_bits_off_target_fast, one_frame_bits);
2687
    fast_extra_bits =
2688
        AOMMIN(fast_extra_bits,
2689
               AOMMAX(one_frame_bits / 8, vbr_bits_off_target_fast / 8));
2690
#else
2691
0
    fast_extra_bits = AOMMIN(p_rc->vbr_bits_off_target_fast, one_frame_bits);
2692
0
    fast_extra_bits =
2693
0
        AOMMIN(fast_extra_bits,
2694
0
               AOMMAX(one_frame_bits / 8, p_rc->vbr_bits_off_target_fast / 8));
2695
0
#endif
2696
0
    fast_extra_bits = AOMMIN(fast_extra_bits, INT_MAX);
2697
0
    if (fast_extra_bits > 0) {
2698
      // Update frame_target only if additional bits are available from
2699
      // local undershoot.
2700
0
      frame_target += fast_extra_bits;
2701
0
    }
2702
    // Store the fast_extra_bits of the frame and reduce it from
2703
    // vbr_bits_off_target_fast during postencode stage.
2704
0
    rc->frame_level_fast_extra_bits = (int)fast_extra_bits;
2705
    // Retaining the condition to update during postencode stage since
2706
    // fast_extra_bits are calculated based on vbr_bits_off_target_fast.
2707
0
    cpi->do_update_vbr_bits_off_target_fast = 1;
2708
0
  }
2709
2710
  // Clamp the target for the frame to the maximum allowed for one frame.
2711
0
  *this_frame_target = (int)AOMMIN(frame_target, INT_MAX);
2712
0
}
2713
2714
37.5k
void av1_set_target_rate(AV1_COMP *cpi, int width, int height) {
2715
37.5k
  RATE_CONTROL *const rc = &cpi->rc;
2716
37.5k
  int target_rate = rc->base_frame_target;
2717
2718
  // Correction to rate target based on prior over or under shoot.
2719
37.5k
  if (cpi->oxcf.rc_cfg.mode == AOM_VBR || cpi->oxcf.rc_cfg.mode == AOM_CQ)
2720
0
    vbr_rate_correction(cpi, &target_rate);
2721
37.5k
  av1_rc_set_frame_target(cpi, target_rate, width, height);
2722
37.5k
}
2723
2724
int av1_calc_pframe_target_size_one_pass_vbr(
2725
19.2k
    const AV1_COMP *const cpi, FRAME_UPDATE_TYPE frame_update_type) {
2726
19.2k
  static const int af_ratio = 10;
2727
19.2k
  const RATE_CONTROL *const rc = &cpi->rc;
2728
19.2k
  const PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2729
19.2k
  int64_t target;
2730
19.2k
#if USE_ALTREF_FOR_ONE_PASS
2731
19.2k
  if (frame_update_type == KF_UPDATE || frame_update_type == GF_UPDATE ||
2732
19.2k
      frame_update_type == ARF_UPDATE) {
2733
19.2k
    target = ((int64_t)rc->avg_frame_bandwidth * p_rc->baseline_gf_interval *
2734
19.2k
              af_ratio) /
2735
19.2k
             (p_rc->baseline_gf_interval + af_ratio - 1);
2736
19.2k
  } else {
2737
0
    target = ((int64_t)rc->avg_frame_bandwidth * p_rc->baseline_gf_interval) /
2738
0
             (p_rc->baseline_gf_interval + af_ratio - 1);
2739
0
  }
2740
#else
2741
  target = rc->avg_frame_bandwidth;
2742
#endif
2743
19.2k
  return clamp_pframe_target_size(cpi, target, frame_update_type);
2744
19.2k
}
2745
2746
117k
int av1_calc_iframe_target_size_one_pass_vbr(const AV1_COMP *const cpi) {
2747
117k
  static const int kf_ratio = 25;
2748
117k
  const RATE_CONTROL *rc = &cpi->rc;
2749
117k
  const int64_t target = (int64_t)rc->avg_frame_bandwidth * kf_ratio;
2750
117k
  return clamp_iframe_target_size(cpi, target);
2751
117k
}
2752
2753
int av1_calc_pframe_target_size_one_pass_cbr(
2754
10.2k
    const AV1_COMP *cpi, FRAME_UPDATE_TYPE frame_update_type) {
2755
10.2k
  const AV1EncoderConfig *oxcf = &cpi->oxcf;
2756
10.2k
  const RATE_CONTROL *rc = &cpi->rc;
2757
10.2k
  const PRIMARY_RATE_CONTROL *p_rc = &cpi->ppi->p_rc;
2758
10.2k
  const RateControlCfg *rc_cfg = &oxcf->rc_cfg;
2759
10.2k
  const int64_t diff = p_rc->optimal_buffer_level - p_rc->buffer_level;
2760
10.2k
  const int64_t one_pct_bits = 1 + p_rc->optimal_buffer_level / 100;
2761
10.2k
  int min_frame_target =
2762
10.2k
      AOMMAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
2763
10.2k
  int64_t target;
2764
2765
10.2k
  if (rc_cfg->gf_cbr_boost_pct) {
2766
0
    const int af_ratio_pct = rc_cfg->gf_cbr_boost_pct + 100;
2767
0
    if (frame_update_type == GF_UPDATE || frame_update_type == OVERLAY_UPDATE) {
2768
0
      target = ((int64_t)rc->avg_frame_bandwidth * p_rc->baseline_gf_interval *
2769
0
                af_ratio_pct) /
2770
0
               (p_rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
2771
0
    } else {
2772
0
      target = ((int64_t)rc->avg_frame_bandwidth * p_rc->baseline_gf_interval *
2773
0
                100) /
2774
0
               (p_rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
2775
0
    }
2776
10.2k
  } else {
2777
10.2k
    target = rc->avg_frame_bandwidth;
2778
10.2k
  }
2779
10.2k
  if (cpi->ppi->use_svc) {
2780
    // Note that for layers, avg_frame_bandwidth is the cumulative
2781
    // per-frame-bandwidth. For the target size of this frame, use the
2782
    // layer average frame size (i.e., non-cumulative per-frame-bw).
2783
0
    int layer =
2784
0
        LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id, cpi->svc.temporal_layer_id,
2785
0
                         cpi->svc.number_temporal_layers);
2786
0
    const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
2787
0
    target = lc->avg_frame_size;
2788
0
    min_frame_target = AOMMAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
2789
0
  }
2790
10.2k
  if (diff > 0) {
2791
    // Lower the target bandwidth for this frame.
2792
1.87k
    const int pct_low =
2793
1.87k
        (int)AOMMIN(diff / one_pct_bits, rc_cfg->under_shoot_pct);
2794
1.87k
    target -= (target * pct_low) / 200;
2795
8.38k
  } else if (diff < 0) {
2796
    // Increase the target bandwidth for this frame.
2797
8.38k
    const int pct_high =
2798
8.38k
        (int)AOMMIN(-diff / one_pct_bits, rc_cfg->over_shoot_pct);
2799
8.38k
    target += (target * pct_high) / 200;
2800
8.38k
  }
2801
10.2k
  if (rc_cfg->max_inter_bitrate_pct) {
2802
0
    const int64_t max_rate =
2803
0
        (int64_t)rc->avg_frame_bandwidth * rc_cfg->max_inter_bitrate_pct / 100;
2804
0
    target = AOMMIN(target, max_rate);
2805
0
  }
2806
10.2k
  if (target > INT_MAX) target = INT_MAX;
2807
10.2k
  return AOMMAX(min_frame_target, (int)target);
2808
10.2k
}
2809
2810
11.4k
int av1_calc_iframe_target_size_one_pass_cbr(const AV1_COMP *cpi) {
2811
11.4k
  const RATE_CONTROL *rc = &cpi->rc;
2812
11.4k
  const PRIMARY_RATE_CONTROL *p_rc = &cpi->ppi->p_rc;
2813
11.4k
  int64_t target;
2814
11.4k
  if (cpi->common.current_frame.frame_number == 0) {
2815
7.30k
    target = ((p_rc->starting_buffer_level / 2) > INT_MAX)
2816
7.30k
                 ? INT_MAX
2817
7.30k
                 : (int)(p_rc->starting_buffer_level / 2);
2818
7.30k
    if (cpi->svc.number_temporal_layers > 1 && target < (INT_MAX >> 2)) {
2819
0
      target = target << AOMMIN(2, (cpi->svc.number_temporal_layers - 1));
2820
0
    }
2821
7.30k
  } else {
2822
4.09k
    int kf_boost = 32;
2823
4.09k
    double framerate = cpi->framerate;
2824
2825
4.09k
    kf_boost = AOMMAX(kf_boost, (int)round(2 * framerate - 16));
2826
4.09k
    if (rc->frames_since_key < framerate / 2) {
2827
4.09k
      kf_boost = (int)(kf_boost * rc->frames_since_key / (framerate / 2));
2828
4.09k
    }
2829
4.09k
    target = ((int64_t)(16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
2830
4.09k
  }
2831
11.4k
  return clamp_iframe_target_size(cpi, target);
2832
11.4k
}
2833
2834
7.30k
static void set_golden_update(AV1_COMP *const cpi) {
2835
7.30k
  RATE_CONTROL *const rc = &cpi->rc;
2836
7.30k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2837
7.30k
  int divisor = 10;
2838
7.30k
  if (cpi->oxcf.q_cfg.aq_mode == CYCLIC_REFRESH_AQ)
2839
0
    divisor = cpi->cyclic_refresh->percent_refresh;
2840
2841
  // Set minimum gf_interval for GF update to a multiple of the refresh period,
2842
  // with some max limit. Depending on past encoding stats, GF flag may be
2843
  // reset and update may not occur until next baseline_gf_interval.
2844
7.30k
  const int gf_length_mult[2] = { 8, 4 };
2845
7.30k
  if (divisor > 0)
2846
7.30k
    p_rc->baseline_gf_interval =
2847
7.30k
        AOMMIN(gf_length_mult[cpi->sf.rt_sf.gf_length_lvl] * (100 / divisor),
2848
7.30k
               MAX_GF_INTERVAL_RT);
2849
0
  else
2850
0
    p_rc->baseline_gf_interval = FIXED_GF_INTERVAL_RT;
2851
7.30k
  if (rc->avg_frame_low_motion && rc->avg_frame_low_motion < 40)
2852
0
    p_rc->baseline_gf_interval = 16;
2853
7.30k
}
2854
2855
7.30k
static void set_baseline_gf_interval(AV1_COMP *cpi, FRAME_TYPE frame_type) {
2856
7.30k
  RATE_CONTROL *const rc = &cpi->rc;
2857
7.30k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
2858
7.30k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
2859
2860
7.30k
  set_golden_update(cpi);
2861
2862
7.30k
  if (p_rc->baseline_gf_interval > rc->frames_to_key &&
2863
0
      cpi->oxcf.kf_cfg.auto_key)
2864
0
    p_rc->baseline_gf_interval = rc->frames_to_key;
2865
7.30k
  p_rc->gfu_boost = DEFAULT_GF_BOOST_RT;
2866
7.30k
  p_rc->constrained_gf_group =
2867
7.30k
      (p_rc->baseline_gf_interval >= rc->frames_to_key &&
2868
0
       cpi->oxcf.kf_cfg.auto_key)
2869
7.30k
          ? 1
2870
7.30k
          : 0;
2871
7.30k
  rc->frames_till_gf_update_due = p_rc->baseline_gf_interval;
2872
7.30k
  cpi->gf_frame_index = 0;
2873
  // SVC does not use GF as periodic boost.
2874
  // TODO(marpan): Find better way to disable this for SVC.
2875
7.30k
  if (cpi->ppi->use_svc) {
2876
0
    SVC *const svc = &cpi->svc;
2877
0
    p_rc->baseline_gf_interval = MAX_STATIC_GF_GROUP_LENGTH - 1;
2878
0
    p_rc->gfu_boost = 1;
2879
0
    p_rc->constrained_gf_group = 0;
2880
0
    rc->frames_till_gf_update_due = p_rc->baseline_gf_interval;
2881
0
    for (int layer = 0;
2882
0
         layer < svc->number_spatial_layers * svc->number_temporal_layers;
2883
0
         ++layer) {
2884
0
      LAYER_CONTEXT *const lc = &svc->layer_context[layer];
2885
0
      lc->p_rc.baseline_gf_interval = p_rc->baseline_gf_interval;
2886
0
      lc->p_rc.gfu_boost = p_rc->gfu_boost;
2887
0
      lc->p_rc.constrained_gf_group = p_rc->constrained_gf_group;
2888
0
      lc->rc.frames_till_gf_update_due = rc->frames_till_gf_update_due;
2889
0
      lc->group_index = 0;
2890
0
    }
2891
0
  }
2892
7.30k
  gf_group->size = p_rc->baseline_gf_interval;
2893
7.30k
  gf_group->update_type[0] = (frame_type == KEY_FRAME) ? KF_UPDATE : GF_UPDATE;
2894
7.30k
  gf_group->refbuf_state[cpi->gf_frame_index] =
2895
7.30k
      (frame_type == KEY_FRAME) ? REFBUF_RESET : REFBUF_UPDATE;
2896
7.30k
}
2897
2898
10.2k
void av1_adjust_gf_refresh_qp_one_pass_rt(AV1_COMP *cpi) {
2899
10.2k
  AV1_COMMON *const cm = &cpi->common;
2900
10.2k
  RATE_CONTROL *const rc = &cpi->rc;
2901
10.2k
  RTC_REF *const rtc_ref = &cpi->ppi->rtc_ref;
2902
10.2k
  const int resize_pending = is_frame_resize_pending(cpi);
2903
10.2k
  if (!resize_pending && !rc->high_source_sad) {
2904
    // Check if we should disable GF refresh (if period is up),
2905
    // or force a GF refresh update (if we are at least halfway through
2906
    // period) based on QP. Look into add info on segment deltaq.
2907
10.2k
    PRIMARY_RATE_CONTROL *p_rc = &cpi->ppi->p_rc;
2908
10.2k
    const int avg_qp = p_rc->avg_frame_qindex[INTER_FRAME];
2909
10.2k
    const int allow_gf_update =
2910
10.2k
        rc->frames_till_gf_update_due <= (p_rc->baseline_gf_interval - 10);
2911
10.2k
    int gf_update_changed = 0;
2912
10.2k
    int thresh = 87;
2913
10.2k
    if ((cm->current_frame.frame_number - cpi->rc.frame_num_last_gf_refresh) <
2914
10.2k
            FIXED_GF_INTERVAL_RT &&
2915
10.2k
        rc->frames_till_gf_update_due == 1 &&
2916
0
        cm->quant_params.base_qindex > avg_qp) {
2917
      // Disable GF refresh since QP is above the running average QP.
2918
0
      rtc_ref->refresh[rtc_ref->gld_idx_1layer] = 0;
2919
0
      gf_update_changed = 1;
2920
0
      cpi->refresh_frame.golden_frame = 0;
2921
10.2k
    } else if (allow_gf_update &&
2922
0
               ((cm->quant_params.base_qindex < thresh * avg_qp / 100) ||
2923
0
                (rc->avg_frame_low_motion && rc->avg_frame_low_motion < 20))) {
2924
      // Force refresh since QP is well below average QP or this is a high
2925
      // motion frame.
2926
0
      rtc_ref->refresh[rtc_ref->gld_idx_1layer] = 1;
2927
0
      gf_update_changed = 1;
2928
0
      cpi->refresh_frame.golden_frame = 1;
2929
0
    }
2930
10.2k
    if (gf_update_changed) {
2931
0
      set_baseline_gf_interval(cpi, INTER_FRAME);
2932
0
      int refresh_mask = 0;
2933
0
      for (unsigned int i = 0; i < INTER_REFS_PER_FRAME; i++) {
2934
0
        int ref_frame_map_idx = rtc_ref->ref_idx[i];
2935
0
        refresh_mask |= rtc_ref->refresh[ref_frame_map_idx]
2936
0
                        << ref_frame_map_idx;
2937
0
      }
2938
0
      cm->current_frame.refresh_frame_flags = refresh_mask;
2939
0
    }
2940
10.2k
  }
2941
10.2k
}
2942
2943
/*!\brief Setup the reference prediction structure for 1 pass real-time
2944
 *
2945
 * Set the reference prediction structure for 1 layer.
2946
 * Current structure is to use 3 references (LAST, GOLDEN, ALTREF),
2947
 * where ALT_REF always behind current by lag_alt frames, and GOLDEN is
2948
 * either updated on LAST with period baseline_gf_interval (fixed slot)
2949
 * or always behind current by lag_gld (gld_fixed_slot = 0, lag_gld <= 7).
2950
 *
2951
 * \ingroup rate_control
2952
 * \param[in]       cpi          Top level encoder structure
2953
 * \param[in]       gf_update    Flag to indicate if GF is updated
2954
 *
2955
 * \remark Nothing is returned. Instead the settings for the prediction
2956
 * structure are set in \c cpi-ext_flags; and the buffer slot index
2957
 * (for each of 7 references) and refresh flags (for each of the 8 slots)
2958
 * are set in \c cpi->svc.ref_idx[] and \c cpi->svc.refresh[].
2959
 */
2960
21.6k
void av1_set_rtc_reference_structure_one_layer(AV1_COMP *cpi, int gf_update) {
2961
21.6k
  AV1_COMMON *const cm = &cpi->common;
2962
21.6k
  ExternalFlags *const ext_flags = &cpi->ext_flags;
2963
21.6k
  RATE_CONTROL *const rc = &cpi->rc;
2964
21.6k
  ExtRefreshFrameFlagsInfo *const ext_refresh_frame_flags =
2965
21.6k
      &ext_flags->refresh_frame;
2966
21.6k
  RTC_REF *const rtc_ref = &cpi->ppi->rtc_ref;
2967
21.6k
  unsigned int frame_number = (cpi->oxcf.rc_cfg.drop_frames_water_mark)
2968
21.6k
                                  ? rc->frame_number_encoded
2969
21.6k
                                  : cm->current_frame.frame_number;
2970
21.6k
  unsigned int lag_alt = 4;
2971
21.6k
  int last_idx = 0;
2972
21.6k
  int last_idx_refresh = 0;
2973
21.6k
  int gld_idx = 0;
2974
21.6k
  int alt_ref_idx = 0;
2975
21.6k
  int last2_idx = 0;
2976
21.6k
  ext_refresh_frame_flags->update_pending = 1;
2977
21.6k
  ext_flags->ref_frame_flags = 0;
2978
21.6k
  ext_refresh_frame_flags->last_frame = 1;
2979
21.6k
  ext_refresh_frame_flags->golden_frame = 0;
2980
21.6k
  ext_refresh_frame_flags->alt_ref_frame = 0;
2981
  // Decide altref lag adaptively for rt
2982
21.6k
  if (cpi->sf.rt_sf.sad_based_adp_altref_lag) {
2983
0
    lag_alt = 6;
2984
0
    const uint64_t th_frame_sad[4][3] = {
2985
0
      { 18000, 18000, 18000 },  // HDRES CPU 9
2986
0
      { 25000, 25000, 25000 },  // MIDRES CPU 9
2987
0
      { 40000, 30000, 20000 },  // HDRES CPU 10
2988
0
      { 30000, 25000, 20000 }   // MIDRES CPU 10
2989
0
    };
2990
0
    int th_idx = cpi->sf.rt_sf.sad_based_adp_altref_lag - 1;
2991
0
    assert(th_idx < 4);
2992
0
    if (rc->avg_source_sad > th_frame_sad[th_idx][0])
2993
0
      lag_alt = 3;
2994
0
    else if (rc->avg_source_sad > th_frame_sad[th_idx][1])
2995
0
      lag_alt = 4;
2996
0
    else if (rc->avg_source_sad > th_frame_sad[th_idx][2])
2997
0
      lag_alt = 5;
2998
0
  }
2999
  // This defines the reference structure for 1 layer (non-svc) RTC encoding.
3000
  // To avoid the internal/default reference structure for non-realtime
3001
  // overwriting this behavior, we use the "svc" ref parameters from the
3002
  // external control SET_SVC_REF_FRAME_CONFIG.
3003
  // TODO(marpan): rename that control and the related internal parameters
3004
  // to rtc_ref.
3005
173k
  for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) rtc_ref->ref_idx[i] = 7;
3006
194k
  for (int i = 0; i < REF_FRAMES; ++i) rtc_ref->refresh[i] = 0;
3007
  // Set the reference frame flags.
3008
21.6k
  ext_flags->ref_frame_flags ^= AOM_LAST_FLAG;
3009
21.6k
  if (!cpi->sf.rt_sf.force_only_last_ref) {
3010
21.6k
    ext_flags->ref_frame_flags ^= AOM_ALT_FLAG;
3011
21.6k
    ext_flags->ref_frame_flags ^= AOM_GOLD_FLAG;
3012
21.6k
    if (cpi->sf.rt_sf.ref_frame_comp_nonrd[1])
3013
0
      ext_flags->ref_frame_flags ^= AOM_LAST2_FLAG;
3014
21.6k
  }
3015
21.6k
  const int sh = 6;
3016
  // Moving index slot for last: 0 - (sh - 1).
3017
21.6k
  if (frame_number > 1) last_idx = ((frame_number - 1) % sh);
3018
  // Moving index for refresh of last: one ahead for next frame.
3019
21.6k
  last_idx_refresh = (frame_number % sh);
3020
21.6k
  gld_idx = 6;
3021
3022
  // Moving index for alt_ref, lag behind LAST by lag_alt frames.
3023
21.6k
  if (frame_number > lag_alt) alt_ref_idx = ((frame_number - lag_alt) % sh);
3024
21.6k
  if (cpi->sf.rt_sf.ref_frame_comp_nonrd[1]) {
3025
    // Moving index for LAST2, lag behind LAST by 2 frames.
3026
0
    if (frame_number > 2) last2_idx = ((frame_number - 2) % sh);
3027
0
  }
3028
21.6k
  rtc_ref->ref_idx[0] = last_idx;          // LAST
3029
21.6k
  rtc_ref->ref_idx[1] = last_idx_refresh;  // LAST2 (for refresh of last).
3030
21.6k
  if (cpi->sf.rt_sf.ref_frame_comp_nonrd[1]) {
3031
0
    rtc_ref->ref_idx[1] = last2_idx;         // LAST2
3032
0
    rtc_ref->ref_idx[2] = last_idx_refresh;  // LAST3 (for refresh of last).
3033
0
  }
3034
21.6k
  rtc_ref->ref_idx[3] = gld_idx;      // GOLDEN
3035
21.6k
  rtc_ref->ref_idx[6] = alt_ref_idx;  // ALT_REF
3036
  // Refresh this slot, which will become LAST on next frame.
3037
21.6k
  rtc_ref->refresh[last_idx_refresh] = 1;
3038
  // Update GOLDEN on period for fixed slot case.
3039
21.6k
  if (gf_update && cm->current_frame.frame_type != KEY_FRAME) {
3040
0
    ext_refresh_frame_flags->golden_frame = 1;
3041
0
    rtc_ref->refresh[gld_idx] = 1;
3042
0
  }
3043
21.6k
  rtc_ref->gld_idx_1layer = gld_idx;
3044
  // Set the flag to reduce the number of reference frame buffers used.
3045
  // This assumes that slot 7 is never used.
3046
21.6k
  cpi->rt_reduce_num_ref_buffers = 1;
3047
21.6k
  cpi->rt_reduce_num_ref_buffers &= (rtc_ref->ref_idx[0] < 7);
3048
21.6k
  cpi->rt_reduce_num_ref_buffers &= (rtc_ref->ref_idx[1] < 7);
3049
21.6k
  cpi->rt_reduce_num_ref_buffers &= (rtc_ref->ref_idx[3] < 7);
3050
21.6k
  cpi->rt_reduce_num_ref_buffers &= (rtc_ref->ref_idx[6] < 7);
3051
21.6k
  if (cpi->sf.rt_sf.ref_frame_comp_nonrd[1])
3052
0
    cpi->rt_reduce_num_ref_buffers &= (rtc_ref->ref_idx[2] < 7);
3053
21.6k
}
3054
3055
// Returns whether the 64x64 block is active or inactive: used
3056
// by the scene detection, which is over 64x64 blocks.
3057
static int set_block_is_active(unsigned char *const active_map_4x4, int mi_cols,
3058
0
                               int mi_rows, int sbi_col, int sbi_row) {
3059
0
  int num_4x4 = 16;
3060
0
  int r = sbi_row << 4;
3061
0
  int c = sbi_col << 4;
3062
0
  const int row_max = AOMMIN(num_4x4, mi_rows - r);
3063
0
  const int col_max = AOMMIN(num_4x4, mi_cols - c);
3064
  // Active map is set for 16x16 blocks, so only need to
3065
  // check over16x16,
3066
0
  for (int x = 0; x < row_max; x += 4) {
3067
0
    for (int y = 0; y < col_max; y += 4) {
3068
0
      if (active_map_4x4[(r + x) * mi_cols + (c + y)] == AM_SEGMENT_ID_ACTIVE)
3069
0
        return 1;
3070
0
    }
3071
0
  }
3072
0
  return 0;
3073
0
}
3074
3075
// Returns the best sad for column or row motion of the superblock.
3076
static unsigned int estimate_scroll_motion(
3077
    const AV1_COMP *cpi, uint8_t *src_buf, uint8_t *last_src_buf,
3078
    int src_stride, int ref_stride, BLOCK_SIZE bsize, int pos_col, int pos_row,
3079
0
    int *best_intmv_col, int *best_intmv_row, int sw_col, int sw_row) {
3080
0
  const AV1_COMMON *const cm = &cpi->common;
3081
0
  const int bw = block_size_wide[bsize];
3082
0
  const int bh = block_size_high[bsize];
3083
0
  const int full_search = 1;
3084
  // Keep border a multiple of 16.
3085
0
  const int border = (cpi->oxcf.border_in_pixels >> 4) << 4;
3086
0
  int search_size_width = sw_col;
3087
0
  int search_size_height = sw_row;
3088
  // Adjust based on boundary.
3089
0
  if ((pos_col - search_size_width < -border) ||
3090
0
      (pos_col + search_size_width > cm->width + border))
3091
0
    search_size_width = border;
3092
0
  if ((pos_row - search_size_height < -border) ||
3093
0
      (pos_row + search_size_height > cm->height + border))
3094
0
    search_size_height = border;
3095
0
  const uint8_t *ref_buf;
3096
0
  const int row_norm_factor = mi_size_high_log2[bsize] + 1;
3097
0
  const int col_norm_factor = 3 + (bw >> 5);
3098
0
  const int ref_buf_width = (search_size_width << 1) + bw;
3099
0
  const int ref_buf_height = (search_size_height << 1) + bh;
3100
0
  int16_t *hbuf = (int16_t *)aom_malloc(ref_buf_width * sizeof(*hbuf));
3101
0
  int16_t *vbuf = (int16_t *)aom_malloc(ref_buf_height * sizeof(*vbuf));
3102
0
  int16_t *src_hbuf = (int16_t *)aom_malloc(bw * sizeof(*src_hbuf));
3103
0
  int16_t *src_vbuf = (int16_t *)aom_malloc(bh * sizeof(*src_vbuf));
3104
0
  if (!hbuf || !vbuf || !src_hbuf || !src_vbuf) {
3105
0
    aom_free(hbuf);
3106
0
    aom_free(vbuf);
3107
0
    aom_free(src_hbuf);
3108
0
    aom_free(src_vbuf);
3109
0
    aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
3110
0
                       "Failed to allocate hbuf, vbuf, src_hbuf, or src_vbuf");
3111
0
  }
3112
  // Set up prediction 1-D reference set for rows.
3113
0
  ref_buf = last_src_buf - search_size_width;
3114
0
  aom_int_pro_row(hbuf, ref_buf, ref_stride, ref_buf_width, bh,
3115
0
                  row_norm_factor);
3116
  // Set up prediction 1-D reference set for cols
3117
0
  ref_buf = last_src_buf - search_size_height * ref_stride;
3118
0
  aom_int_pro_col(vbuf, ref_buf, ref_stride, bw, ref_buf_height,
3119
0
                  col_norm_factor);
3120
  // Set up src 1-D reference set
3121
0
  aom_int_pro_row(src_hbuf, src_buf, src_stride, bw, bh, row_norm_factor);
3122
0
  aom_int_pro_col(src_vbuf, src_buf, src_stride, bw, bh, col_norm_factor);
3123
0
  unsigned int best_sad;
3124
0
  int best_sad_col, best_sad_row;
3125
  // Find the best match per 1-D search
3126
0
  *best_intmv_col =
3127
0
      av1_vector_match(hbuf, src_hbuf, mi_size_wide_log2[bsize],
3128
0
                       search_size_width, full_search, &best_sad_col);
3129
0
  *best_intmv_row =
3130
0
      av1_vector_match(vbuf, src_vbuf, mi_size_high_log2[bsize],
3131
0
                       search_size_height, full_search, &best_sad_row);
3132
0
  if (best_sad_col < best_sad_row) {
3133
0
    *best_intmv_row = 0;
3134
0
    best_sad = best_sad_col;
3135
0
  } else {
3136
0
    *best_intmv_col = 0;
3137
0
    best_sad = best_sad_row;
3138
0
  }
3139
0
  aom_free(hbuf);
3140
0
  aom_free(vbuf);
3141
0
  aom_free(src_hbuf);
3142
0
  aom_free(src_vbuf);
3143
0
  return best_sad;
3144
0
}
3145
3146
/*!\brief Check for scene detection, for 1 pass real-time mode.
3147
 *
3148
 * Compute average source sad (temporal sad: between current source and
3149
 * previous source) over a subset of superblocks. Use this is detect big changes
3150
 * in content and set the \c cpi->rc.high_source_sad flag.
3151
 *
3152
 * \ingroup rate_control
3153
 * \param[in]       cpi          Top level encoder structure
3154
 * \param[in]       frame_input  Current and last input source frames
3155
 *
3156
 * \remark Nothing is returned. Instead the flag \c cpi->rc.high_source_sad
3157
 * is set if scene change is detected, and \c cpi->rc.avg_source_sad is updated.
3158
 */
3159
static void rc_scene_detection_onepass_rt(AV1_COMP *cpi,
3160
14.3k
                                          const EncodeFrameInput *frame_input) {
3161
14.3k
  AV1_COMMON *const cm = &cpi->common;
3162
14.3k
  RATE_CONTROL *const rc = &cpi->rc;
3163
14.3k
  YV12_BUFFER_CONFIG const *const unscaled_src = frame_input->source;
3164
14.3k
  YV12_BUFFER_CONFIG const *const unscaled_last_src = frame_input->last_source;
3165
14.3k
  uint8_t *src_y;
3166
14.3k
  int src_ystride;
3167
14.3k
  int src_width;
3168
14.3k
  int src_height;
3169
14.3k
  uint8_t *last_src_y;
3170
14.3k
  int last_src_ystride;
3171
14.3k
  int last_src_width;
3172
14.3k
  int last_src_height;
3173
14.3k
  int width = cm->width;
3174
14.3k
  int height = cm->height;
3175
14.3k
  if (cpi->svc.number_spatial_layers > 1) {
3176
0
    width = cpi->oxcf.frm_dim_cfg.width;
3177
0
    height = cpi->oxcf.frm_dim_cfg.height;
3178
0
  }
3179
14.3k
  if (width != cm->render_width || height != cm->render_height ||
3180
14.3k
      unscaled_src == NULL || unscaled_last_src == NULL) {
3181
0
    aom_free(cpi->src_sad_blk_64x64);
3182
0
    cpi->src_sad_blk_64x64 = NULL;
3183
0
  }
3184
14.3k
  if (unscaled_src == NULL || unscaled_last_src == NULL) return;
3185
14.3k
  src_y = unscaled_src->y_buffer;
3186
14.3k
  src_ystride = unscaled_src->y_stride;
3187
14.3k
  src_width = unscaled_src->y_width;
3188
14.3k
  src_height = unscaled_src->y_height;
3189
14.3k
  last_src_y = unscaled_last_src->y_buffer;
3190
14.3k
  last_src_ystride = unscaled_last_src->y_stride;
3191
14.3k
  last_src_width = unscaled_last_src->y_width;
3192
14.3k
  last_src_height = unscaled_last_src->y_height;
3193
14.3k
  if (src_width != last_src_width || src_height != last_src_height) {
3194
0
    aom_free(cpi->src_sad_blk_64x64);
3195
0
    cpi->src_sad_blk_64x64 = NULL;
3196
0
    return;
3197
0
  }
3198
14.3k
  rc->high_source_sad = 0;
3199
14.3k
  rc->percent_blocks_with_motion = 0;
3200
14.3k
  rc->max_block_source_sad = 0;
3201
14.3k
  rc->prev_avg_source_sad = rc->avg_source_sad;
3202
14.3k
  int num_mi_cols = cm->mi_params.mi_cols;
3203
14.3k
  int num_mi_rows = cm->mi_params.mi_rows;
3204
14.3k
  if (cpi->svc.number_spatial_layers > 1) {
3205
0
    num_mi_cols = cpi->svc.mi_cols_full_resoln;
3206
0
    num_mi_rows = cpi->svc.mi_rows_full_resoln;
3207
0
  }
3208
14.3k
  int num_zero_temp_sad = 0;
3209
14.3k
  uint32_t min_thresh =
3210
14.3k
      (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN) ? 8000 : 10000;
3211
14.3k
  if (cpi->sf.rt_sf.higher_thresh_scene_detection) {
3212
14.3k
    min_thresh = cm->width * cm->height <= 320 * 240 && cpi->framerate < 10.0
3213
14.3k
                     ? 50000
3214
14.3k
                     : 100000;
3215
14.3k
  }
3216
14.3k
  const BLOCK_SIZE bsize = BLOCK_64X64;
3217
  // Loop over sub-sample of frame, compute average sad over 64x64 blocks.
3218
14.3k
  uint64_t avg_sad = 0;
3219
14.3k
  uint64_t tmp_sad = 0;
3220
14.3k
  int num_samples = 0;
3221
14.3k
  const int thresh =
3222
14.3k
      ((cm->width * cm->height <= 320 * 240 && cpi->framerate < 10.0) ||
3223
14.3k
       (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN))
3224
14.3k
          ? 5
3225
14.3k
          : 6;
3226
  // SAD is computed on 64x64 blocks
3227
14.3k
  const int sb_size_by_mb = (cm->seq_params->sb_size == BLOCK_128X128)
3228
14.3k
                                ? (cm->seq_params->mib_size >> 1)
3229
14.3k
                                : cm->seq_params->mib_size;
3230
14.3k
  const int sb_cols = (num_mi_cols + sb_size_by_mb - 1) / sb_size_by_mb;
3231
14.3k
  const int sb_rows = (num_mi_rows + sb_size_by_mb - 1) / sb_size_by_mb;
3232
14.3k
  uint64_t sum_sq_thresh = 10000;  // sum = sqrt(thresh / 64*64)) ~1.5
3233
14.3k
  int num_low_var_high_sumdiff = 0;
3234
14.3k
  int light_change = 0;
3235
  // Flag to check light change or not.
3236
14.3k
  const int check_light_change = 0;
3237
  // TODO(marpan): There seems some difference along the bottom border when
3238
  // using the source_last_tl0 for last_source (used for temporal layers or
3239
  // when previous frame is dropped).
3240
  // Remove this border parameter when issue is resolved: difference is that
3241
  // non-zero sad exists along bottom border even though source is static.
3242
14.3k
  const int border =
3243
14.3k
      rc->prev_frame_is_dropped || cpi->svc.number_temporal_layers > 1;
3244
  // Store blkwise SAD for later use. Disable for spatial layers for now.
3245
14.3k
  if (width == cm->render_width && height == cm->render_height &&
3246
14.3k
      cpi->svc.number_spatial_layers == 1) {
3247
14.3k
    if (cpi->src_sad_blk_64x64 == NULL) {
3248
6.46k
      CHECK_MEM_ERROR(cm, cpi->src_sad_blk_64x64,
3249
6.46k
                      (uint64_t *)aom_calloc(sb_cols * sb_rows,
3250
6.46k
                                             sizeof(*cpi->src_sad_blk_64x64)));
3251
6.46k
    }
3252
14.3k
  }
3253
14.3k
  const CommonModeInfoParams *const mi_params = &cpi->common.mi_params;
3254
14.3k
  const int mi_cols = mi_params->mi_cols;
3255
14.3k
  const int mi_rows = mi_params->mi_rows;
3256
14.3k
  unsigned char *const active_map_4x4 = cpi->active_map.map;
3257
  // Avoid bottom and right border.
3258
37.0k
  for (int sbi_row = 0; sbi_row < sb_rows - border; ++sbi_row) {
3259
60.5k
    for (int sbi_col = 0; sbi_col < sb_cols; ++sbi_col) {
3260
37.9k
      int block_is_active = 1;
3261
37.9k
      if (cpi->active_map.enabled && rc->percent_blocks_inactive > 0) {
3262
        // Fix this to include skip feature via ROI.
3263
0
        block_is_active = set_block_is_active(active_map_4x4, mi_cols, mi_rows,
3264
0
                                              sbi_col, sbi_row);
3265
0
      }
3266
37.9k
      if (block_is_active) {
3267
37.9k
        tmp_sad = cpi->ppi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y,
3268
37.9k
                                              last_src_ystride);
3269
37.9k
      } else {
3270
0
        tmp_sad = 0;
3271
0
      }
3272
37.9k
      if (cpi->src_sad_blk_64x64 != NULL)
3273
37.9k
        cpi->src_sad_blk_64x64[sbi_col + sbi_row * sb_cols] = tmp_sad;
3274
37.9k
      if (check_light_change) {
3275
0
        unsigned int sse, variance;
3276
0
        variance = cpi->ppi->fn_ptr[bsize].vf(src_y, src_ystride, last_src_y,
3277
0
                                              last_src_ystride, &sse);
3278
        // Note: sse - variance = ((sum * sum) >> 12)
3279
        // Detect large lighting change.
3280
0
        if (variance < (sse >> 1) && (sse - variance) > sum_sq_thresh) {
3281
0
          num_low_var_high_sumdiff++;
3282
0
        }
3283
0
      }
3284
37.9k
      avg_sad += tmp_sad;
3285
37.9k
      num_samples++;
3286
37.9k
      if (tmp_sad == 0) num_zero_temp_sad++;
3287
37.9k
      if (tmp_sad > rc->max_block_source_sad)
3288
21.8k
        rc->max_block_source_sad = tmp_sad;
3289
3290
37.9k
      src_y += 64;
3291
37.9k
      last_src_y += 64;
3292
37.9k
    }
3293
22.6k
    src_y += (src_ystride << 6) - (sb_cols << 6);
3294
22.6k
    last_src_y += (last_src_ystride << 6) - (sb_cols << 6);
3295
22.6k
  }
3296
14.3k
  if (check_light_change && num_samples > 0 &&
3297
0
      num_low_var_high_sumdiff > (num_samples >> 1))
3298
0
    light_change = 1;
3299
14.3k
  if (num_samples > 0) avg_sad = avg_sad / num_samples;
3300
  // Set high_source_sad flag if we detect very high increase in avg_sad
3301
  // between current and previous frame value(s). Use minimum threshold
3302
  // for cases where there is small change from content that is completely
3303
  // static.
3304
14.3k
  if (!light_change &&
3305
14.3k
      avg_sad >
3306
14.3k
          AOMMAX(min_thresh, (unsigned int)(rc->avg_source_sad * thresh)) &&
3307
6.91k
      rc->frames_since_key > 1 + cpi->svc.number_spatial_layers &&
3308
79
      num_zero_temp_sad < 3 * (num_samples >> 2))
3309
0
    rc->high_source_sad = 1;
3310
14.3k
  else
3311
14.3k
    rc->high_source_sad = 0;
3312
14.3k
  rc->avg_source_sad = (3 * rc->avg_source_sad + avg_sad) >> 2;
3313
14.3k
  rc->frame_source_sad = avg_sad;
3314
14.3k
  if (num_samples > 0)
3315
14.3k
    rc->percent_blocks_with_motion =
3316
14.3k
        ((num_samples - num_zero_temp_sad) * 100) / num_samples;
3317
14.3k
  if (rc->frame_source_sad > 0) rc->static_since_last_scene_change = 0;
3318
14.3k
  if (rc->high_source_sad) {
3319
0
    cpi->rc.frames_since_scene_change = 0;
3320
0
    rc->static_since_last_scene_change = 1;
3321
0
  }
3322
  // Update the high_motion_content_screen_rtc flag on TL0. Avoid the update
3323
  // if too many consecutive frame drops occurred.
3324
14.3k
  const uint64_t thresh_high_motion = 9 * 64 * 64;
3325
14.3k
  if (cpi->svc.temporal_layer_id == 0 && rc->drop_count_consec < 3) {
3326
14.3k
    cpi->rc.high_motion_content_screen_rtc = 0;
3327
14.3k
    if (cpi->oxcf.speed >= 11 &&
3328
0
        cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN &&
3329
0
        rc->percent_blocks_with_motion > 40 &&
3330
0
        rc->prev_avg_source_sad > thresh_high_motion &&
3331
0
        rc->avg_source_sad > thresh_high_motion &&
3332
0
        rc->avg_frame_low_motion < 60 && unscaled_src->y_width >= 1280 &&
3333
0
        unscaled_src->y_height >= 720) {
3334
0
      cpi->rc.high_motion_content_screen_rtc = 1;
3335
      // Compute fast coarse/global motion for 128x128 superblock centered
3336
      // at middle of frame, and one to the upper left and one to lower right.
3337
      // to determine if motion is scroll. Only test 3 points (pts) for now.
3338
      // TODO(marpan): Only allow for 8 bit-depth for now.
3339
0
      if (cm->seq_params->bit_depth == 8) {
3340
0
        int sw_row = (cpi->rc.frame_source_sad > 20000) ? 512 : 192;
3341
0
        int sw_col = (cpi->rc.frame_source_sad > 20000) ? 512 : 160;
3342
0
        if (cm->width * cm->height >= 3840 * 2160 &&
3343
0
            cpi->svc.number_temporal_layers > 1) {
3344
0
          sw_row = sw_row << 1;
3345
0
          sw_col = sw_col << 1;
3346
0
        }
3347
0
        const int num_pts =
3348
0
            unscaled_src->y_width * unscaled_src->y_height >= 1920 * 1080 ? 3
3349
0
                                                                          : 1;
3350
0
        for (int pts = 0; pts < num_pts; pts++) {
3351
          // fac and shift are used to move the center block for the other
3352
          // two points (pts).
3353
0
          int fac = 1;
3354
0
          int shift = 1;
3355
0
          if (pts == 1) {
3356
0
            fac = 1;
3357
0
            shift = 2;
3358
0
          } else if (pts == 2) {
3359
0
            fac = 3;
3360
0
            shift = 2;
3361
0
          }
3362
0
          int pos_col = (fac * unscaled_src->y_width >> shift) - 64;
3363
0
          int pos_row = (fac * unscaled_src->y_height >> shift) - 64;
3364
0
          pos_col = AOMMAX(sw_col,
3365
0
                           AOMMIN(unscaled_src->y_width - sw_col - 1, pos_col));
3366
0
          pos_row = AOMMAX(
3367
0
              sw_row, AOMMIN(unscaled_src->y_height - sw_row - 1, pos_row));
3368
0
          if (pos_col >= 0 && pos_col < unscaled_src->y_width - 64 &&
3369
0
              pos_row >= 0 && pos_row < unscaled_src->y_height - 64) {
3370
0
            src_y = unscaled_src->y_buffer + pos_row * src_ystride + pos_col;
3371
0
            last_src_y = unscaled_last_src->y_buffer +
3372
0
                         pos_row * last_src_ystride + pos_col;
3373
0
            int best_intmv_col = 0;
3374
0
            int best_intmv_row = 0;
3375
0
            unsigned int y_sad = estimate_scroll_motion(
3376
0
                cpi, src_y, last_src_y, src_ystride, last_src_ystride,
3377
0
                BLOCK_128X128, pos_col, pos_row, &best_intmv_col,
3378
0
                &best_intmv_row, sw_col, sw_row);
3379
0
            unsigned int sad_thresh =
3380
0
                (abs(best_intmv_col) > 150 || abs(best_intmv_row) > 150) ? 300
3381
0
                                                                         : 150;
3382
0
            if (y_sad < sad_thresh &&
3383
0
                (abs(best_intmv_col) > 16 || abs(best_intmv_row) > 16)) {
3384
0
              cpi->rc.high_motion_content_screen_rtc = 0;
3385
0
              break;
3386
0
            }
3387
0
          }
3388
0
        }
3389
0
      }
3390
0
    }
3391
    // Pass the flag value to all layer frames.
3392
14.3k
    if (cpi->svc.number_spatial_layers > 1 ||
3393
14.3k
        cpi->svc.number_temporal_layers > 1) {
3394
0
      SVC *svc = &cpi->svc;
3395
0
      for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
3396
0
        for (int tl = 1; tl < svc->number_temporal_layers; ++tl) {
3397
0
          const int layer =
3398
0
              LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
3399
0
          LAYER_CONTEXT *lc = &svc->layer_context[layer];
3400
0
          RATE_CONTROL *lrc = &lc->rc;
3401
0
          lrc->high_motion_content_screen_rtc =
3402
0
              rc->high_motion_content_screen_rtc;
3403
0
        }
3404
0
      }
3405
0
    }
3406
14.3k
  }
3407
  // Scene detection is only on base SLO, and using full/original resolution.
3408
  // Pass the state to the upper spatial layers.
3409
14.3k
  if (cpi->svc.number_spatial_layers > 1) {
3410
0
    SVC *svc = &cpi->svc;
3411
0
    for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
3412
0
      int tl = svc->temporal_layer_id;
3413
0
      const int layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
3414
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
3415
0
      RATE_CONTROL *lrc = &lc->rc;
3416
0
      lrc->high_source_sad = rc->high_source_sad;
3417
0
      lrc->frame_source_sad = rc->frame_source_sad;
3418
0
      lrc->avg_source_sad = rc->avg_source_sad;
3419
0
      lrc->percent_blocks_with_motion = rc->percent_blocks_with_motion;
3420
0
      lrc->max_block_source_sad = rc->max_block_source_sad;
3421
0
    }
3422
0
  }
3423
14.3k
}
3424
3425
// This is used as a reference when computing the source variance.
3426
static const uint8_t AV1_VAR_OFFS[MAX_SB_SIZE] = {
3427
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3428
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3429
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3430
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3431
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3432
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3433
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3434
  128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128,
3435
  128, 128, 128, 128, 128, 128, 128, 128
3436
};
3437
3438
/*!\brief Compute spatial activity for frame,  1 pass real-time mode.
3439
 *
3440
 * Compute average spatial activity/variance for source frame over a
3441
 * subset of superblocks.
3442
 *
3443
 * \ingroup rate_control
3444
 * \param[in]       cpi          Top level encoder structure
3445
 * \param[in]       src_y        Input source buffer for y channel.
3446
 * \param[in]       src_ystride  Input source stride for y channel.
3447
 *
3448
 * \remark Nothing is returned. Instead the average spatial variance
3449
 * computed is stored in flag \c cpi->rc.frame_spatial_variance.
3450
 */
3451
static void rc_spatial_act_onepass_rt(AV1_COMP *cpi, uint8_t *src_y,
3452
0
                                      int src_ystride) {
3453
0
  AV1_COMMON *const cm = &cpi->common;
3454
0
  int num_mi_cols = cm->mi_params.mi_cols;
3455
0
  int num_mi_rows = cm->mi_params.mi_rows;
3456
0
  const BLOCK_SIZE bsize = BLOCK_64X64;
3457
  // Loop over sub-sample of frame, compute average over 64x64 blocks.
3458
0
  uint64_t avg_variance = 0;
3459
0
  int num_samples = 0;
3460
0
  int num_zero_var_blocks = 0;
3461
0
  cpi->rc.perc_spatial_flat_blocks = 0;
3462
0
  const int sb_size_by_mb = (cm->seq_params->sb_size == BLOCK_128X128)
3463
0
                                ? (cm->seq_params->mib_size >> 1)
3464
0
                                : cm->seq_params->mib_size;
3465
0
  const int sb_cols = (num_mi_cols + sb_size_by_mb - 1) / sb_size_by_mb;
3466
0
  const int sb_rows = (num_mi_rows + sb_size_by_mb - 1) / sb_size_by_mb;
3467
0
  for (int sbi_row = 0; sbi_row < sb_rows; ++sbi_row) {
3468
0
    for (int sbi_col = 0; sbi_col < sb_cols; ++sbi_col) {
3469
0
      unsigned int sse;
3470
0
      const unsigned int var =
3471
0
          cpi->ppi->fn_ptr[bsize].vf(src_y, src_ystride, AV1_VAR_OFFS, 0, &sse);
3472
0
      avg_variance += var;
3473
0
      num_samples++;
3474
0
      if (var == 0) num_zero_var_blocks++;
3475
0
      src_y += 64;
3476
0
    }
3477
0
    src_y += (src_ystride << 6) - (sb_cols << 6);
3478
0
  }
3479
0
  if (num_samples > 0) {
3480
0
    cpi->rc.perc_spatial_flat_blocks = 100 * num_zero_var_blocks / num_samples;
3481
0
    avg_variance = avg_variance / num_samples;
3482
0
  }
3483
0
  cpi->rc.frame_spatial_variance = avg_variance >> 12;
3484
0
}
3485
3486
/*!\brief Set the GF baseline interval for 1 pass real-time mode.
3487
 *
3488
 *
3489
 * \ingroup rate_control
3490
 * \param[in]       cpi          Top level encoder structure
3491
 * \param[in]       frame_type   frame type
3492
 *
3493
 * \return Return GF update flag, and update the \c cpi->rc with
3494
 * the next GF interval settings.
3495
 */
3496
static int set_gf_interval_update_onepass_rt(AV1_COMP *cpi,
3497
21.6k
                                             FRAME_TYPE frame_type) {
3498
21.6k
  RATE_CONTROL *const rc = &cpi->rc;
3499
21.6k
  int gf_update = 0;
3500
21.6k
  const int resize_pending = is_frame_resize_pending(cpi);
3501
  // GF update based on frames_till_gf_update_due, also
3502
  // force update on resize pending frame or for scene change.
3503
21.6k
  if ((resize_pending || rc->high_source_sad ||
3504
21.6k
       rc->frames_till_gf_update_due == 0) &&
3505
7.30k
      cpi->svc.temporal_layer_id == 0 && cpi->svc.spatial_layer_id == 0) {
3506
7.30k
    set_baseline_gf_interval(cpi, frame_type);
3507
7.30k
    gf_update = 1;
3508
7.30k
  }
3509
21.6k
  return gf_update;
3510
21.6k
}
3511
3512
static void resize_reset_rc(AV1_COMP *cpi, int resize_width, int resize_height,
3513
0
                            int prev_width, int prev_height) {
3514
0
  RATE_CONTROL *const rc = &cpi->rc;
3515
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3516
0
  SVC *const svc = &cpi->svc;
3517
0
  int target_bits_per_frame;
3518
0
  int active_worst_quality;
3519
0
  int qindex;
3520
0
  double tot_scale_change = (double)(resize_width * resize_height) /
3521
0
                            (double)(prev_width * prev_height);
3522
  // Disable the skip mv search for svc on resize frame.
3523
0
  svc->skip_mvsearch_last = 0;
3524
0
  svc->skip_mvsearch_gf = 0;
3525
0
  svc->skip_mvsearch_altref = 0;
3526
  // Reset buffer level to optimal, update target size.
3527
0
  p_rc->buffer_level = p_rc->optimal_buffer_level;
3528
0
  p_rc->bits_off_target = p_rc->optimal_buffer_level;
3529
0
  rc->this_frame_target =
3530
0
      av1_calc_pframe_target_size_one_pass_cbr(cpi, INTER_FRAME);
3531
0
  target_bits_per_frame = rc->this_frame_target;
3532
0
  if (tot_scale_change > 4.0)
3533
0
    p_rc->avg_frame_qindex[INTER_FRAME] = rc->worst_quality;
3534
0
  else if (tot_scale_change > 1.0)
3535
0
    p_rc->avg_frame_qindex[INTER_FRAME] =
3536
0
        (p_rc->avg_frame_qindex[INTER_FRAME] + rc->worst_quality) >> 1;
3537
0
  active_worst_quality = calc_active_worst_quality_no_stats_cbr(cpi);
3538
0
  qindex = av1_rc_regulate_q(cpi, target_bits_per_frame, rc->best_quality,
3539
0
                             active_worst_quality, resize_width, resize_height);
3540
  // If resize is down, check if projected q index is close to worst_quality,
3541
  // and if so, reduce the rate correction factor (since likely can afford
3542
  // lower q for resized frame).
3543
0
  if (tot_scale_change < 1.0 && qindex > 90 * rc->worst_quality / 100)
3544
0
    p_rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
3545
  // If resize is back up: check if projected q index is too much above the
3546
  // previous index, and if so, reduce the rate correction factor
3547
  // (since prefer to keep q for resized frame at least closet to previous q).
3548
  // Also check if projected qindex is close to previous qindex, if so
3549
  // increase correction factor (to push qindex higher and avoid overshoot).
3550
0
  if (tot_scale_change >= 1.0) {
3551
0
    if (tot_scale_change < 4.0 &&
3552
0
        qindex > 130 * p_rc->last_q[INTER_FRAME] / 100)
3553
0
      p_rc->rate_correction_factors[INTER_NORMAL] *= 0.8;
3554
0
    if (qindex <= 120 * p_rc->last_q[INTER_FRAME] / 100)
3555
0
      p_rc->rate_correction_factors[INTER_NORMAL] *= 1.5;
3556
0
  }
3557
0
  if (svc->number_temporal_layers > 1) {
3558
    // Apply the same rate control reset to all temporal layers.
3559
0
    for (int tl = 0; tl < svc->number_temporal_layers; tl++) {
3560
0
      LAYER_CONTEXT *lc = NULL;
3561
0
      lc = &svc->layer_context[svc->spatial_layer_id *
3562
0
                                   svc->number_temporal_layers +
3563
0
                               tl];
3564
0
      lc->rc.resize_state = rc->resize_state;
3565
0
      lc->p_rc.buffer_level = lc->p_rc.optimal_buffer_level;
3566
0
      lc->p_rc.bits_off_target = lc->p_rc.optimal_buffer_level;
3567
0
      lc->p_rc.rate_correction_factors[INTER_NORMAL] =
3568
0
          p_rc->rate_correction_factors[INTER_NORMAL];
3569
0
      lc->p_rc.avg_frame_qindex[INTER_FRAME] =
3570
0
          p_rc->avg_frame_qindex[INTER_FRAME];
3571
0
    }
3572
0
  }
3573
0
}
3574
3575
/*!\brief Check for resize based on Q, for 1 pass real-time mode.
3576
 *
3577
 * Check if we should resize, based on average QP and content/motion
3578
 * complexity from past x frames.
3579
 * Only allow for resize at most 1/2 scale down for now, Scaling factor
3580
 * for each step may be 3/4 or 1/2.
3581
 *
3582
 * \ingroup rate_control
3583
 * \param[in]       cpi            Top level encoder structure
3584
 * \param[in]       one_half_only  Only allow 1/2 scaling factor
3585
 *
3586
 * \remark Return resized width/height in \c cpi->resize_pending_params,
3587
 * and update some resize counters in \c rc.
3588
 */
3589
0
static void dynamic_resize_one_pass_cbr(AV1_COMP *cpi, int one_half_only) {
3590
0
  const AV1_COMMON *const cm = &cpi->common;
3591
0
  RATE_CONTROL *const rc = &cpi->rc;
3592
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3593
0
  RESIZE_ACTION resize_action = NO_RESIZE;
3594
0
  const int avg_qp_thr1 = 70;
3595
0
  const int avg_qp_thr2 = 50;
3596
  // Don't allow for resized frame to go below 160x90, resize in steps of 3/4.
3597
0
  const int min_width = (160 * 4) / 3;
3598
0
  const int min_height = (90 * 4) / 3;
3599
0
  int down_size_on = 1;
3600
  // Don't resize on key frame; reset the counters on key frame.
3601
0
  if (cm->current_frame.frame_type == KEY_FRAME) {
3602
0
    rc->resize_avg_qp = 0;
3603
0
    rc->resize_count = 0;
3604
0
    rc->resize_buffer_underflow = 0;
3605
0
    return;
3606
0
  }
3607
  // No resizing down if frame size is below some limit.
3608
0
  if ((cm->width * cm->height) < min_width * min_height) down_size_on = 0;
3609
3610
  // Resize based on average buffer underflow and QP over some window.
3611
  // Ignore samples close to key frame and scene change since QP is usually high
3612
  // after key and scene change.
3613
  // Need to incorpoate content/motion from scene detection analysis.
3614
0
  if (rc->frames_since_key > cpi->framerate && !rc->high_source_sad) {
3615
0
    const int window = AOMMAX(60, (int)(3 * cpi->framerate));
3616
0
    rc->resize_avg_qp += p_rc->last_q[INTER_FRAME];
3617
0
    if (cpi->ppi->p_rc.buffer_level <
3618
0
        (int)(30 * p_rc->optimal_buffer_level / 100))
3619
0
      ++rc->resize_buffer_underflow;
3620
0
    ++rc->resize_count;
3621
    // Check for resize action every "window" frames.
3622
0
    if (rc->resize_count >= window) {
3623
0
      int avg_qp = rc->resize_avg_qp / rc->resize_count;
3624
      // Resize down if buffer level has underflowed sufficient amount in past
3625
      // window, and we are at original or 3/4 of original resolution.
3626
      // Resize back up if average QP is low, and we are currently in a resized
3627
      // down state, i.e. 1/2 or 3/4 of original resolution.
3628
      // Currently, use a flag to turn 3/4 resizing feature on/off.
3629
0
      if (rc->resize_buffer_underflow > (rc->resize_count >> 2) &&
3630
0
          down_size_on) {
3631
0
        if (rc->resize_state == THREE_QUARTER) {
3632
0
          resize_action = DOWN_ONEHALF;
3633
0
          rc->resize_state = ONE_HALF;
3634
0
        } else if (rc->resize_state == ORIG) {
3635
0
          resize_action = one_half_only ? DOWN_ONEHALF : DOWN_THREEFOUR;
3636
0
          rc->resize_state = one_half_only ? ONE_HALF : THREE_QUARTER;
3637
0
        }
3638
0
      } else if (rc->resize_state != ORIG &&
3639
0
                 avg_qp < avg_qp_thr1 * cpi->rc.worst_quality / 100) {
3640
0
        if (rc->resize_state == THREE_QUARTER ||
3641
0
            avg_qp < avg_qp_thr2 * cpi->rc.worst_quality / 100 ||
3642
0
            one_half_only) {
3643
0
          resize_action = UP_ORIG;
3644
0
          rc->resize_state = ORIG;
3645
0
        } else if (rc->resize_state == ONE_HALF) {
3646
0
          resize_action = UP_THREEFOUR;
3647
0
          rc->resize_state = THREE_QUARTER;
3648
0
        }
3649
0
      }
3650
      // Reset for next window measurement.
3651
0
      rc->resize_avg_qp = 0;
3652
0
      rc->resize_count = 0;
3653
0
      rc->resize_buffer_underflow = 0;
3654
0
    }
3655
0
  }
3656
  // If decision is to resize, reset some quantities, and check is we should
3657
  // reduce rate correction factor,
3658
0
  if (resize_action != NO_RESIZE) {
3659
0
    int resize_width = cpi->oxcf.frm_dim_cfg.width;
3660
0
    int resize_height = cpi->oxcf.frm_dim_cfg.height;
3661
0
    int resize_scale_num = 1;
3662
0
    int resize_scale_den = 1;
3663
0
    if (resize_action == DOWN_THREEFOUR || resize_action == UP_THREEFOUR) {
3664
0
      resize_scale_num = 3;
3665
0
      resize_scale_den = 4;
3666
0
    } else if (resize_action == DOWN_ONEHALF) {
3667
0
      resize_scale_num = 1;
3668
0
      resize_scale_den = 2;
3669
0
    }
3670
0
    resize_width = resize_width * resize_scale_num / resize_scale_den;
3671
0
    resize_height = resize_height * resize_scale_num / resize_scale_den;
3672
0
    resize_reset_rc(cpi, resize_width, resize_height, cm->width, cm->height);
3673
0
  }
3674
0
  return;
3675
0
}
3676
3677
21.6k
static inline int set_key_frame(AV1_COMP *cpi, unsigned int frame_flags) {
3678
21.6k
  RATE_CONTROL *const rc = &cpi->rc;
3679
21.6k
  AV1_COMMON *const cm = &cpi->common;
3680
21.6k
  SVC *const svc = &cpi->svc;
3681
3682
  // Very first frame has to be key frame.
3683
21.6k
  if (cm->current_frame.frame_number == 0) return 1;
3684
  // Set key frame if forced by frame flags.
3685
14.3k
  if (frame_flags & FRAMEFLAGS_KEY) return 1;
3686
10.2k
  if (!cpi->ppi->use_svc) {
3687
    // Non-SVC
3688
10.2k
    if (cpi->oxcf.kf_cfg.auto_key && rc->frames_to_key == 0) return 1;
3689
10.2k
  } else {
3690
    // SVC
3691
0
    if (svc->spatial_layer_id == 0 &&
3692
0
        (cpi->oxcf.kf_cfg.auto_key &&
3693
0
         (cpi->oxcf.kf_cfg.key_freq_max == 0 ||
3694
0
          svc->current_superframe % cpi->oxcf.kf_cfg.key_freq_max == 0)))
3695
0
      return 1;
3696
0
  }
3697
3698
10.2k
  return 0;
3699
10.2k
}
3700
3701
// Set to true if this frame is a recovery frame, for 1 layer RPS,
3702
// and whether we should apply some boost (QP, adjust speed features, etc).
3703
// Recovery frame here means frame whose closest reference is x frames away,
3704
// where x = 4.
3705
// TODO(marpan): Consider adding on/off flag to SVC_REF_FRAME_CONFIG to
3706
// allow more control for applications.
3707
21.6k
static bool set_flag_rps_bias_recovery_frame(const AV1_COMP *const cpi) {
3708
21.6k
  if (cpi->ppi->rtc_ref.set_ref_frame_config &&
3709
0
      cpi->svc.number_temporal_layers == 1 &&
3710
0
      cpi->svc.number_spatial_layers == 1 &&
3711
0
      cpi->ppi->rtc_ref.reference_was_previous_frame) {
3712
0
    int min_dist = av1_svc_get_min_ref_dist(cpi);
3713
    // Only consider boost for this frame if its closest reference is further
3714
    // than or equal to x frames away, using x = 4 for now.
3715
0
    if (min_dist != INT_MAX && min_dist >= 4) return true;
3716
0
  }
3717
21.6k
  return false;
3718
21.6k
}
3719
3720
void av1_get_one_pass_rt_params(AV1_COMP *cpi, FRAME_TYPE *const frame_type,
3721
                                const EncodeFrameInput *frame_input,
3722
21.6k
                                unsigned int frame_flags) {
3723
21.6k
  RATE_CONTROL *const rc = &cpi->rc;
3724
21.6k
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3725
21.6k
  AV1_COMMON *const cm = &cpi->common;
3726
21.6k
  GF_GROUP *const gf_group = &cpi->ppi->gf_group;
3727
21.6k
  SVC *const svc = &cpi->svc;
3728
21.6k
  ResizePendingParams *const resize_pending_params =
3729
21.6k
      &cpi->resize_pending_params;
3730
21.6k
  int target;
3731
21.6k
  const int layer =
3732
21.6k
      LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
3733
21.6k
                       svc->number_temporal_layers);
3734
21.6k
  if (cpi->oxcf.rc_cfg.max_consec_drop_ms > 0) {
3735
0
    double framerate =
3736
0
        cpi->framerate > 1 ? round(cpi->framerate) : cpi->framerate;
3737
0
    rc->max_consec_drop = saturate_cast_double_to_int(
3738
0
        ceil(cpi->oxcf.rc_cfg.max_consec_drop_ms * framerate / 1000));
3739
0
  }
3740
21.6k
  if (cpi->ppi->use_svc) {
3741
0
    av1_update_temporal_layer_framerate(cpi);
3742
0
    av1_restore_layer_context(cpi);
3743
0
  }
3744
21.6k
  cpi->ppi->rtc_ref.bias_recovery_frame = set_flag_rps_bias_recovery_frame(cpi);
3745
  // Set frame type.
3746
21.6k
  if (set_key_frame(cpi, frame_flags)) {
3747
11.4k
    *frame_type = KEY_FRAME;
3748
11.4k
    p_rc->this_key_frame_forced =
3749
11.4k
        cm->current_frame.frame_number != 0 && rc->frames_to_key == 0;
3750
11.4k
    rc->frames_to_key = cpi->oxcf.kf_cfg.key_freq_max;
3751
11.4k
    p_rc->kf_boost = DEFAULT_KF_BOOST_RT;
3752
11.4k
    gf_group->update_type[cpi->gf_frame_index] = KF_UPDATE;
3753
11.4k
    gf_group->frame_type[cpi->gf_frame_index] = KEY_FRAME;
3754
11.4k
    gf_group->refbuf_state[cpi->gf_frame_index] = REFBUF_RESET;
3755
11.4k
    if (cpi->ppi->use_svc) {
3756
0
      if (cm->current_frame.frame_number > 0)
3757
0
        av1_svc_reset_temporal_layers(cpi, 1);
3758
0
      svc->layer_context[layer].is_key_frame = 1;
3759
0
    }
3760
11.4k
    rc->frame_number_encoded = 0;
3761
11.4k
    cpi->ppi->rtc_ref.non_reference_frame = 0;
3762
11.4k
    rc->static_since_last_scene_change = 0;
3763
11.4k
  } else {
3764
10.2k
    *frame_type = INTER_FRAME;
3765
10.2k
    gf_group->update_type[cpi->gf_frame_index] = LF_UPDATE;
3766
10.2k
    gf_group->frame_type[cpi->gf_frame_index] = INTER_FRAME;
3767
10.2k
    gf_group->refbuf_state[cpi->gf_frame_index] = REFBUF_UPDATE;
3768
10.2k
    if (cpi->ppi->use_svc) {
3769
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
3770
0
      lc->is_key_frame =
3771
0
          svc->spatial_layer_id == 0
3772
0
              ? 0
3773
0
              : svc->layer_context[svc->temporal_layer_id].is_key_frame;
3774
0
    }
3775
    // If the user is setting the reference structure with
3776
    // set_ref_frame_config and did not set any references, set the
3777
    // frame type to Intra-only.
3778
10.2k
    if (cpi->ppi->rtc_ref.set_ref_frame_config) {
3779
0
      int no_references_set = 1;
3780
0
      for (int i = 0; i < INTER_REFS_PER_FRAME; i++) {
3781
0
        if (cpi->ppi->rtc_ref.reference[i]) {
3782
0
          no_references_set = 0;
3783
0
          break;
3784
0
        }
3785
0
      }
3786
3787
      // Set to intra_only_frame if no references are set.
3788
      // The stream can start decoding on INTRA_ONLY_FRAME so long as the
3789
      // layer with the intra_only_frame doesn't signal a reference to a slot
3790
      // that hasn't been set yet.
3791
0
      if (no_references_set) *frame_type = INTRA_ONLY_FRAME;
3792
0
    }
3793
10.2k
  }
3794
21.6k
  if (cpi->active_map.enabled && cpi->rc.percent_blocks_inactive == 100) {
3795
0
    rc->frame_source_sad = 0;
3796
0
    rc->avg_source_sad = (3 * rc->avg_source_sad + rc->frame_source_sad) >> 2;
3797
0
    rc->percent_blocks_with_motion = 0;
3798
0
    rc->high_source_sad = 0;
3799
21.6k
  } else if (cpi->sf.rt_sf.check_scene_detection &&
3800
21.6k
             svc->spatial_layer_id == 0) {
3801
21.6k
    if (rc->prev_coded_width == cm->width &&
3802
14.3k
        rc->prev_coded_height == cm->height) {
3803
14.3k
      rc_scene_detection_onepass_rt(cpi, frame_input);
3804
14.3k
    } else {
3805
7.30k
      aom_free(cpi->src_sad_blk_64x64);
3806
7.30k
      cpi->src_sad_blk_64x64 = NULL;
3807
7.30k
    }
3808
21.6k
  }
3809
21.6k
  if (((*frame_type == KEY_FRAME && cpi->sf.rt_sf.rc_adjust_keyframe) ||
3810
21.6k
       (cpi->sf.rt_sf.rc_compute_spatial_var_sc && rc->high_source_sad)) &&
3811
0
      svc->spatial_layer_id == 0 && cm->seq_params->bit_depth == 8 &&
3812
0
      cpi->oxcf.rc_cfg.max_intra_bitrate_pct > 0)
3813
0
    rc_spatial_act_onepass_rt(cpi, frame_input->source->y_buffer,
3814
0
                              frame_input->source->y_stride);
3815
  // Check for dynamic resize, for single spatial layer for now.
3816
  // For temporal layers only check on base temporal layer.
3817
21.6k
  if (cpi->oxcf.resize_cfg.resize_mode == RESIZE_DYNAMIC) {
3818
0
    if (svc->number_spatial_layers == 1 && svc->temporal_layer_id == 0)
3819
0
      dynamic_resize_one_pass_cbr(cpi, /*one_half_only=*/1);
3820
0
    if (rc->resize_state == THREE_QUARTER) {
3821
0
      resize_pending_params->width = (3 + cpi->oxcf.frm_dim_cfg.width * 3) >> 2;
3822
0
      resize_pending_params->height =
3823
0
          (3 + cpi->oxcf.frm_dim_cfg.height * 3) >> 2;
3824
0
    } else if (rc->resize_state == ONE_HALF) {
3825
0
      resize_pending_params->width = (1 + cpi->oxcf.frm_dim_cfg.width) >> 1;
3826
0
      resize_pending_params->height = (1 + cpi->oxcf.frm_dim_cfg.height) >> 1;
3827
0
    } else {
3828
0
      resize_pending_params->width = cpi->oxcf.frm_dim_cfg.width;
3829
0
      resize_pending_params->height = cpi->oxcf.frm_dim_cfg.height;
3830
0
    }
3831
21.6k
  } else if (is_frame_resize_pending(cpi)) {
3832
0
    resize_reset_rc(cpi, resize_pending_params->width,
3833
0
                    resize_pending_params->height, cm->width, cm->height);
3834
0
  }
3835
21.6k
  if (svc->temporal_layer_id == 0) {
3836
21.6k
    rc->num_col_blscroll_last_tl0 = 0;
3837
21.6k
    rc->num_row_blscroll_last_tl0 = 0;
3838
21.6k
  }
3839
  // Set the GF interval and update flag.
3840
21.6k
  if (!rc->rtc_external_ratectrl)
3841
21.6k
    set_gf_interval_update_onepass_rt(cpi, *frame_type);
3842
  // Set target size.
3843
21.6k
  if (cpi->oxcf.rc_cfg.mode == AOM_CBR) {
3844
21.6k
    if (*frame_type == KEY_FRAME || *frame_type == INTRA_ONLY_FRAME) {
3845
11.4k
      target = av1_calc_iframe_target_size_one_pass_cbr(cpi);
3846
11.4k
    } else {
3847
10.2k
      target = av1_calc_pframe_target_size_one_pass_cbr(
3848
10.2k
          cpi, gf_group->update_type[cpi->gf_frame_index]);
3849
10.2k
    }
3850
21.6k
  } else {
3851
0
    if (*frame_type == KEY_FRAME || *frame_type == INTRA_ONLY_FRAME) {
3852
0
      target = av1_calc_iframe_target_size_one_pass_vbr(cpi);
3853
0
    } else {
3854
0
      target = av1_calc_pframe_target_size_one_pass_vbr(
3855
0
          cpi, gf_group->update_type[cpi->gf_frame_index]);
3856
0
    }
3857
0
  }
3858
21.6k
  if (cpi->oxcf.rc_cfg.mode == AOM_Q)
3859
0
    rc->active_worst_quality = cpi->oxcf.rc_cfg.cq_level;
3860
3861
21.6k
  av1_rc_set_frame_target(cpi, target, cm->width, cm->height);
3862
21.6k
  rc->base_frame_target = target;
3863
21.6k
  cm->current_frame.frame_type = *frame_type;
3864
  // For fixed mode SVC: if KSVC is enabled remove inter layer
3865
  // prediction on spatial enhancement layer frames for frames
3866
  // whose base is not KEY frame.
3867
21.6k
  if (cpi->ppi->use_svc && !svc->use_flexible_mode && svc->ksvc_fixed_mode &&
3868
0
      svc->number_spatial_layers > 1 &&
3869
0
      !svc->layer_context[layer].is_key_frame) {
3870
0
    ExternalFlags *const ext_flags = &cpi->ext_flags;
3871
0
    ext_flags->ref_frame_flags ^= AOM_GOLD_FLAG;
3872
0
  }
3873
21.6k
}
3874
3875
#define CHECK_INTER_LAYER_PRED(ref_frame)                         \
3876
0
  ((cpi->ref_frame_flags & av1_ref_frame_flag_list[ref_frame]) && \
3877
0
   (av1_check_ref_is_low_spatial_res_super_frame(cpi, ref_frame)))
3878
3879
0
int av1_encodedframe_overshoot_cbr(AV1_COMP *cpi, int *q) {
3880
0
  AV1_COMMON *const cm = &cpi->common;
3881
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3882
0
  double rate_correction_factor =
3883
0
      cpi->ppi->p_rc.rate_correction_factors[INTER_NORMAL];
3884
0
  const int target_size = cpi->rc.avg_frame_bandwidth;
3885
0
  double new_correction_factor;
3886
0
  int target_bits_per_mb;
3887
0
  double q2;
3888
0
  int enumerator;
3889
0
  int inter_layer_pred_on = 0;
3890
0
  int is_screen_content = (cpi->oxcf.tune_cfg.content == AOM_CONTENT_SCREEN);
3891
0
  cpi->cyclic_refresh->counter_encode_maxq_scene_change = 0;
3892
0
  if (cpi->svc.spatial_layer_id > 0) {
3893
    // For spatial layers: check if inter-layer (spatial) prediction is used
3894
    // (check if any reference is being used that is the lower spatial layer),
3895
0
    inter_layer_pred_on = CHECK_INTER_LAYER_PRED(LAST_FRAME) ||
3896
0
                          CHECK_INTER_LAYER_PRED(GOLDEN_FRAME) ||
3897
0
                          CHECK_INTER_LAYER_PRED(ALTREF_FRAME);
3898
0
  }
3899
  // If inter-layer prediction is on: we expect to pull up the quality from
3900
  // the lower spatial layer, so we can use a lower q.
3901
0
  if (cpi->svc.spatial_layer_id > 0 && inter_layer_pred_on) {
3902
0
    *q = (cpi->rc.worst_quality + *q) >> 1;
3903
0
  } else {
3904
    // For easy scene changes used lower QP, otherwise set max-q.
3905
    // If rt_sf->compute_spatial_var_sc is enabled relax the max-q
3906
    // condition based on frame spatial variance.
3907
0
    if (cpi->sf.rt_sf.rc_compute_spatial_var_sc) {
3908
0
      if (cpi->rc.frame_spatial_variance < 100) {
3909
0
        *q = (cpi->rc.worst_quality + *q) >> 1;
3910
0
      } else if (cpi->rc.frame_spatial_variance < 400 ||
3911
0
                 (cpi->rc.frame_source_sad < 80000 &&
3912
0
                  cpi->rc.frame_spatial_variance < 1000)) {
3913
0
        *q = (3 * cpi->rc.worst_quality + *q) >> 2;
3914
0
      } else {
3915
0
        *q = cpi->rc.worst_quality;
3916
0
      }
3917
0
    } else {
3918
      // Set a larger QP.
3919
0
      const uint64_t sad_thr = 64 * 64 * 32;
3920
0
      if (cm->width * cm->height >= 1280 * 720 &&
3921
0
          (p_rc->buffer_level > (p_rc->optimal_buffer_level) >> 1) &&
3922
0
          cpi->rc.avg_source_sad < sad_thr) {
3923
0
        *q = (*q + cpi->rc.worst_quality) >> 1;
3924
0
      } else {
3925
0
        *q = (3 * cpi->rc.worst_quality + *q) >> 2;
3926
0
      }
3927
      // If we arrive here for screen content: use the max-q set by the user.
3928
0
      if (is_screen_content) *q = cpi->rc.worst_quality;
3929
0
    }
3930
0
  }
3931
  // Adjust avg_frame_qindex, buffer_level, and rate correction factors, as
3932
  // these parameters will affect QP selection for subsequent frames. If they
3933
  // have settled down to a very different (low QP) state, then not adjusting
3934
  // them may cause next frame to select low QP and overshoot again.
3935
0
  p_rc->avg_frame_qindex[INTER_FRAME] = *q;
3936
0
  p_rc->buffer_level = p_rc->optimal_buffer_level;
3937
0
  p_rc->bits_off_target = p_rc->optimal_buffer_level;
3938
  // Reset rate under/over-shoot flags.
3939
0
  cpi->rc.rc_1_frame = 0;
3940
0
  cpi->rc.rc_2_frame = 0;
3941
  // Adjust rate correction factor.
3942
0
  target_bits_per_mb =
3943
0
      (int)(((uint64_t)target_size << BPER_MB_NORMBITS) / cm->mi_params.MBs);
3944
  // Reset rate correction factor: for now base it on target_bits_per_mb
3945
  // and qp (==max_QP). This comes from the inverse computation of
3946
  // av1_rc_bits_per_mb().
3947
0
  q2 = av1_convert_qindex_to_q(*q, cm->seq_params->bit_depth);
3948
0
  enumerator = get_bpmb_enumerator(INTER_NORMAL, is_screen_content);
3949
0
  new_correction_factor = (double)target_bits_per_mb * q2 / enumerator;
3950
0
  if (new_correction_factor > rate_correction_factor) {
3951
0
    rate_correction_factor =
3952
0
        (new_correction_factor + rate_correction_factor) / 2.0;
3953
0
    if (rate_correction_factor > MAX_BPB_FACTOR)
3954
0
      rate_correction_factor = MAX_BPB_FACTOR;
3955
0
    cpi->ppi->p_rc.rate_correction_factors[INTER_NORMAL] =
3956
0
        rate_correction_factor;
3957
0
  }
3958
  // For temporal layers: reset the rate control parameters across all
3959
  // temporal layers. Only do it for spatial enhancement layers when
3960
  // inter_layer_pred_on is not set (off).
3961
0
  if (cpi->svc.number_temporal_layers > 1 &&
3962
0
      (cpi->svc.spatial_layer_id == 0 || inter_layer_pred_on == 0)) {
3963
0
    SVC *svc = &cpi->svc;
3964
0
    for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
3965
0
      int sl = svc->spatial_layer_id;
3966
0
      const int layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
3967
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
3968
0
      RATE_CONTROL *lrc = &lc->rc;
3969
0
      PRIMARY_RATE_CONTROL *lp_rc = &lc->p_rc;
3970
0
      lp_rc->avg_frame_qindex[INTER_FRAME] = *q;
3971
0
      lp_rc->buffer_level = lp_rc->optimal_buffer_level;
3972
0
      lp_rc->bits_off_target = lp_rc->optimal_buffer_level;
3973
0
      lrc->rc_1_frame = 0;
3974
0
      lrc->rc_2_frame = 0;
3975
0
      lp_rc->rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
3976
0
    }
3977
0
  }
3978
0
  return 1;
3979
0
}
3980
3981
0
int av1_postencode_drop_cbr(AV1_COMP *cpi, size_t *size) {
3982
0
  PRIMARY_RATE_CONTROL *const p_rc = &cpi->ppi->p_rc;
3983
0
  size_t frame_size = *size << 3;
3984
0
  const int64_t new_buffer_level =
3985
0
      p_rc->buffer_level + cpi->rc.avg_frame_bandwidth - (int64_t)frame_size;
3986
  // Drop if new buffer level (given the encoded frame size) goes below a
3987
  // threshold and encoded frame size is much larger than per-frame-bandwidth.
3988
  // If the frame is already labelled as scene change (high_source_sad = 1)
3989
  // or the QP is close to max, then no need to drop.
3990
0
  const int qp_thresh = 3 * (cpi->rc.worst_quality >> 2);
3991
0
  const int64_t buffer_thresh = p_rc->optimal_buffer_level >> 2;
3992
0
  if (!cpi->rc.high_source_sad && new_buffer_level < buffer_thresh &&
3993
0
      frame_size > 8 * (unsigned int)cpi->rc.avg_frame_bandwidth &&
3994
0
      cpi->common.quant_params.base_qindex < qp_thresh) {
3995
0
    *size = 0;
3996
0
    cpi->is_dropped_frame = true;
3997
0
    restore_all_coding_context(cpi);
3998
0
    av1_rc_postencode_update_drop_frame(cpi);
3999
    // Force max_q on next fame. Reset some RC parameters.
4000
0
    cpi->rc.force_max_q = 1;
4001
0
    p_rc->avg_frame_qindex[INTER_FRAME] = cpi->rc.worst_quality;
4002
0
    p_rc->buffer_level = p_rc->optimal_buffer_level;
4003
0
    p_rc->bits_off_target = p_rc->optimal_buffer_level;
4004
0
    cpi->rc.rc_1_frame = 0;
4005
0
    cpi->rc.rc_2_frame = 0;
4006
0
    if (cpi->svc.number_spatial_layers > 1 ||
4007
0
        cpi->svc.number_temporal_layers > 1) {
4008
0
      SVC *svc = &cpi->svc;
4009
      // Postencode drop is only checked on base spatial layer,
4010
      // for now if max-q is set on base we force it on all layers.
4011
0
      for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
4012
0
        for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
4013
0
          const int layer =
4014
0
              LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
4015
0
          LAYER_CONTEXT *lc = &svc->layer_context[layer];
4016
0
          RATE_CONTROL *lrc = &lc->rc;
4017
0
          PRIMARY_RATE_CONTROL *lp_rc = &lc->p_rc;
4018
          // Force max_q on next fame. Reset some RC parameters.
4019
0
          lrc->force_max_q = 1;
4020
0
          lp_rc->avg_frame_qindex[INTER_FRAME] = cpi->rc.worst_quality;
4021
0
          lp_rc->buffer_level = lp_rc->optimal_buffer_level;
4022
0
          lp_rc->bits_off_target = lp_rc->optimal_buffer_level;
4023
0
          lrc->rc_1_frame = 0;
4024
0
          lrc->rc_2_frame = 0;
4025
0
        }
4026
0
      }
4027
0
    }
4028
0
    return 1;
4029
0
  }
4030
0
  return 0;
4031
0
}