Coverage Report

Created: 2026-10-28 07:26

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