Coverage Report

Created: 2025-11-16 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libvpx/vp9/encoder/vp9_ratectrl.c
Line
Count
Source
1
/*
2
 *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
 *  that can be found in the LICENSE file in the root of the source
6
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS.  All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
9
 */
10
11
#include <assert.h>
12
#include <limits.h>
13
#include <math.h>
14
#include <stdint.h>
15
#include <stdio.h>
16
#include <stdlib.h>
17
#include <string.h>
18
19
#include "./vpx_dsp_rtcd.h"
20
#include "vpx_dsp/vpx_dsp_common.h"
21
#include "vpx_mem/vpx_mem.h"
22
#include "vpx_ports/mem.h"
23
#include "vpx_ports/system_state.h"
24
25
#include "vp9/common/vp9_alloccommon.h"
26
#include "vp9/common/vp9_blockd.h"
27
#include "vp9/common/vp9_common.h"
28
#include "vp9/common/vp9_entropymode.h"
29
#include "vp9/common/vp9_onyxc_int.h"
30
#include "vp9/common/vp9_quant_common.h"
31
#include "vp9/common/vp9_seg_common.h"
32
33
#include "vp9/encoder/vp9_aq_cyclicrefresh.h"
34
#include "vp9/encoder/vp9_encodemv.h"
35
#include "vp9/encoder/vp9_encoder.h"
36
#include "vp9/encoder/vp9_ext_ratectrl.h"
37
#include "vp9/encoder/vp9_firstpass.h"
38
#include "vp9/encoder/vp9_ratectrl.h"
39
#include "vp9/encoder/vp9_svc_layercontext.h"
40
41
#include "vpx/vpx_codec.h"
42
#include "vpx/vpx_ext_ratectrl.h"
43
#include "vpx/internal/vpx_codec_internal.h"
44
45
// Max rate per frame for 1080P and below encodes if no level requirement given.
46
// For larger formats limit to MAX_MB_RATE bits per MB
47
// 4Mbits is derived from the level requirement for level 4 (1080P 30) which
48
// requires that HW can sustain a rate of 16Mbits over a 4 frame group.
49
// If a lower level requirement is specified then this may over ride this value.
50
#define MAX_MB_RATE 250
51
#define MAXRATE_1080P 4000000
52
53
#define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
54
55
179k
#define MIN_BPB_FACTOR 0.005
56
174k
#define MAX_BPB_FACTOR 50
57
58
#if CONFIG_VP9_HIGHBITDEPTH
59
#define ASSIGN_MINQ_TABLE(bit_depth, name)       \
60
76.2k
  do {                                           \
61
76.2k
    switch (bit_depth) {                         \
62
76.2k
      case VPX_BITS_8: name = name##_8; break;   \
63
0
      case VPX_BITS_10: name = name##_10; break; \
64
0
      default:                                   \
65
0
        assert(bit_depth == VPX_BITS_12);        \
66
0
        name = name##_12;                        \
67
0
        break;                                   \
68
76.2k
    }                                            \
69
76.2k
  } while (0)
70
#else
71
#define ASSIGN_MINQ_TABLE(bit_depth, name) \
72
  do {                                     \
73
    (void)bit_depth;                       \
74
    name = name##_8;                       \
75
  } while (0)
76
#endif
77
78
// Tables relating active max Q to active min Q
79
static int kf_low_motion_minq_8[QINDEX_RANGE];
80
static int kf_high_motion_minq_8[QINDEX_RANGE];
81
static int arfgf_low_motion_minq_8[QINDEX_RANGE];
82
static int arfgf_high_motion_minq_8[QINDEX_RANGE];
83
static int inter_minq_8[QINDEX_RANGE];
84
static int rtc_minq_8[QINDEX_RANGE];
85
86
#if CONFIG_VP9_HIGHBITDEPTH
87
static int kf_low_motion_minq_10[QINDEX_RANGE];
88
static int kf_high_motion_minq_10[QINDEX_RANGE];
89
static int arfgf_low_motion_minq_10[QINDEX_RANGE];
90
static int arfgf_high_motion_minq_10[QINDEX_RANGE];
91
static int inter_minq_10[QINDEX_RANGE];
92
static int rtc_minq_10[QINDEX_RANGE];
93
static int kf_low_motion_minq_12[QINDEX_RANGE];
94
static int kf_high_motion_minq_12[QINDEX_RANGE];
95
static int arfgf_low_motion_minq_12[QINDEX_RANGE];
96
static int arfgf_high_motion_minq_12[QINDEX_RANGE];
97
static int inter_minq_12[QINDEX_RANGE];
98
static int rtc_minq_12[QINDEX_RANGE];
99
#endif
100
101
#ifdef AGGRESSIVE_VBR
102
static int gf_high = 2400;
103
static int gf_low = 400;
104
static int kf_high = 4000;
105
static int kf_low = 400;
106
#else
107
static int gf_high = 2000;
108
static int gf_low = 400;
109
static int kf_high = 4800;
110
static int kf_low = 300;
111
#endif
112
113
// Functions to compute the active minq lookup table entries based on a
114
// formulaic approach to facilitate easier adjustment of the Q tables.
115
// The formulae were derived from computing a 3rd order polynomial best
116
// fit to the original data (after plotting real maxq vs minq (not q index))
117
static int get_minq_index(double maxq, double x3, double x2, double x1,
118
4.60k
                          vpx_bit_depth_t bit_depth) {
119
4.60k
  int i;
120
4.60k
  const double minqtarget = VPXMIN(((x3 * maxq + x2) * maxq + x1) * maxq, maxq);
121
122
  // Special case handling to deal with the step from q2.0
123
  // down to lossless mode represented by q 1.0.
124
4.60k
  if (minqtarget <= 2.0) return 0;
125
126
371k
  for (i = 0; i < QINDEX_RANGE; i++) {
127
371k
    if (minqtarget <= vp9_convert_qindex_to_q(i, bit_depth)) return i;
128
371k
  }
129
130
0
  return QINDEX_RANGE - 1;
131
4.19k
}
132
133
static void init_minq_luts(int *kf_low_m, int *kf_high_m, int *arfgf_low,
134
                           int *arfgf_high, int *inter, int *rtc,
135
3
                           vpx_bit_depth_t bit_depth) {
136
3
  int i;
137
771
  for (i = 0; i < QINDEX_RANGE; i++) {
138
768
    const double maxq = vp9_convert_qindex_to_q(i, bit_depth);
139
768
    kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
140
768
    kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.45, bit_depth);
141
#ifdef AGGRESSIVE_VBR
142
    arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.275, bit_depth);
143
    inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.80, bit_depth);
144
#else
145
768
    arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
146
768
    inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
147
768
#endif
148
768
    arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
149
768
    rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
150
768
  }
151
3
}
152
153
1
void vp9_rc_init_minq_luts(void) {
154
1
  init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
155
1
                 arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
156
1
                 inter_minq_8, rtc_minq_8, VPX_BITS_8);
157
1
#if CONFIG_VP9_HIGHBITDEPTH
158
1
  init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
159
1
                 arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
160
1
                 inter_minq_10, rtc_minq_10, VPX_BITS_10);
161
1
  init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
162
1
                 arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
163
1
                 inter_minq_12, rtc_minq_12, VPX_BITS_12);
164
1
#endif
165
1
}
166
167
// These functions use formulaic calculations to make playing with the
168
// quantizer tables easier. If necessary they can be replaced by lookup
169
// tables if and when things settle down in the experimental bitstream
170
5.46M
double vp9_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
171
// Convert the index to a real Q value (scaled down to match old Q values)
172
5.46M
#if CONFIG_VP9_HIGHBITDEPTH
173
5.46M
  switch (bit_depth) {
174
5.21M
    case VPX_BITS_8: return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
175
125k
    case VPX_BITS_10: return vp9_ac_quant(qindex, 0, bit_depth) / 16.0;
176
126k
    default:
177
126k
      assert(bit_depth == VPX_BITS_12);
178
126k
      return vp9_ac_quant(qindex, 0, bit_depth) / 64.0;
179
5.46M
  }
180
#else
181
  return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
182
#endif
183
5.46M
}
184
185
0
int vp9_convert_q_to_qindex(double q_val, vpx_bit_depth_t bit_depth) {
186
0
  int i;
187
188
0
  for (i = 0; i < QINDEX_RANGE; ++i)
189
0
    if (vp9_convert_qindex_to_q(i, bit_depth) >= q_val) break;
190
191
0
  if (i == QINDEX_RANGE) i--;
192
193
0
  return i;
194
0
}
195
196
int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
197
3.19M
                       double correction_factor, vpx_bit_depth_t bit_depth) {
198
3.19M
  const double q = vp9_convert_qindex_to_q(qindex, bit_depth);
199
3.19M
  int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
200
201
3.19M
  assert(correction_factor <= MAX_BPB_FACTOR &&
202
3.19M
         correction_factor >= MIN_BPB_FACTOR);
203
204
  // q based adjustment to baseline enumerator
205
3.19M
  enumerator += (int)(enumerator * q) >> 12;
206
3.19M
  return (int)(enumerator * correction_factor / q);
207
3.19M
}
208
209
int vp9_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
210
                           double correction_factor,
211
54.0k
                           vpx_bit_depth_t bit_depth) {
212
54.0k
  const int bpm =
213
54.0k
      (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor, bit_depth));
214
54.0k
  return VPXMAX(FRAME_OVERHEAD_BITS,
215
54.0k
                (int)(((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS));
216
54.0k
}
217
218
44.4k
int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
219
44.4k
  const RATE_CONTROL *rc = &cpi->rc;
220
44.4k
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
221
222
44.4k
  const int min_frame_target =
223
44.4k
      VPXMAX(rc->min_frame_bandwidth, rc->avg_frame_bandwidth >> 5);
224
44.4k
  if (target < min_frame_target) target = min_frame_target;
225
44.4k
  if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
226
    // If there is an active ARF at this location use the minimum
227
    // bits on this frame even if it is a constructed arf.
228
    // The active maximum quantizer insures that an appropriate
229
    // number of bits will be spent if needed for constructed ARFs.
230
0
    target = min_frame_target;
231
0
  }
232
233
  // Clip the frame target to the maximum allowed value.
234
44.4k
  if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
235
236
44.4k
  if (oxcf->rc_max_inter_bitrate_pct) {
237
0
    const int64_t max_rate =
238
0
        (int64_t)rc->avg_frame_bandwidth * oxcf->rc_max_inter_bitrate_pct / 100;
239
    // target is of type int and VPXMIN cannot evaluate to larger than target
240
0
    target = (int)VPXMIN(target, max_rate);
241
0
  }
242
44.4k
  return target;
243
44.4k
}
244
245
12.8k
int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
246
12.8k
  const RATE_CONTROL *rc = &cpi->rc;
247
12.8k
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
248
12.8k
  if (oxcf->rc_max_intra_bitrate_pct) {
249
0
    const int64_t max_rate =
250
0
        (int64_t)rc->avg_frame_bandwidth * oxcf->rc_max_intra_bitrate_pct / 100;
251
0
    target = (int)VPXMIN(target, max_rate);
252
0
  }
253
12.8k
  if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
254
12.8k
  return target;
255
12.8k
}
256
257
// TODO(marpan/jianj): bits_off_target and buffer_level are used in the same
258
// way for CBR mode, for the buffering updates below. Look into removing one
259
// of these (i.e., bits_off_target).
260
// Update the buffer level before encoding with the per-frame-bandwidth,
261
54.1k
void vp9_update_buffer_level_preencode(VP9_COMP *cpi) {
262
54.1k
  RATE_CONTROL *const rc = &cpi->rc;
263
54.1k
  rc->bits_off_target += rc->avg_frame_bandwidth;
264
  // Clip the buffer level to the maximum specified buffer size.
265
54.1k
  rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
266
54.1k
  rc->buffer_level = rc->bits_off_target;
267
54.1k
}
268
269
// Update the buffer level before encoding with the per-frame-bandwidth
270
// for SVC. The current and all upper temporal layers are updated, needed
271
// for the layered rate control which involves cumulative buffer levels for
272
// the temporal layers. Allow for using the timestamp(pts) delta for the
273
// framerate when the set_ref_frame_config is used.
274
0
void vp9_update_buffer_level_svc_preencode(VP9_COMP *cpi) {
275
0
  SVC *const svc = &cpi->svc;
276
0
  int i;
277
  // Set this to 1 to use timestamp delta for "framerate" under
278
  // ref_frame_config usage.
279
0
  int use_timestamp = 1;
280
0
  const int64_t ts_delta =
281
0
      svc->time_stamp_superframe - svc->time_stamp_prev[svc->spatial_layer_id];
282
0
  for (i = svc->temporal_layer_id; i < svc->number_temporal_layers; ++i) {
283
0
    const int layer =
284
0
        LAYER_IDS_TO_IDX(svc->spatial_layer_id, i, svc->number_temporal_layers);
285
0
    LAYER_CONTEXT *const lc = &svc->layer_context[layer];
286
0
    RATE_CONTROL *const lrc = &lc->rc;
287
0
    if (use_timestamp && cpi->svc.use_set_ref_frame_config &&
288
0
        svc->number_temporal_layers == 1 && ts_delta > 0 &&
289
0
        svc->current_superframe > 0) {
290
      // TODO(marpan): This may need to be modified for temporal layers.
291
0
      const double framerate_pts = 10000000.0 / ts_delta;
292
0
      lrc->bits_off_target += saturate_cast_double_to_int(
293
0
          round(lc->target_bandwidth / framerate_pts));
294
0
    } else {
295
0
      lrc->bits_off_target += saturate_cast_double_to_int(
296
0
          round(lc->target_bandwidth / lc->framerate));
297
0
    }
298
    // Clip buffer level to maximum buffer size for the layer.
299
0
    lrc->bits_off_target =
300
0
        VPXMIN(lrc->bits_off_target, lrc->maximum_buffer_size);
301
0
    lrc->buffer_level = lrc->bits_off_target;
302
0
    if (i == svc->temporal_layer_id) {
303
0
      cpi->rc.bits_off_target = lrc->bits_off_target;
304
0
      cpi->rc.buffer_level = lrc->buffer_level;
305
0
    }
306
0
  }
307
0
}
308
309
// Update the buffer level for higher temporal layers, given the encoded current
310
// temporal layer.
311
static void update_layer_buffer_level_postencode(SVC *svc,
312
0
                                                 int encoded_frame_size) {
313
0
  int i = 0;
314
0
  const int current_temporal_layer = svc->temporal_layer_id;
315
0
  for (i = current_temporal_layer + 1; i < svc->number_temporal_layers; ++i) {
316
0
    const int layer =
317
0
        LAYER_IDS_TO_IDX(svc->spatial_layer_id, i, svc->number_temporal_layers);
318
0
    LAYER_CONTEXT *lc = &svc->layer_context[layer];
319
0
    RATE_CONTROL *lrc = &lc->rc;
320
0
    lrc->bits_off_target -= encoded_frame_size;
321
    // Clip buffer level to maximum buffer size for the layer.
322
0
    lrc->bits_off_target =
323
0
        VPXMIN(lrc->bits_off_target, lrc->maximum_buffer_size);
324
0
    lrc->buffer_level = lrc->bits_off_target;
325
0
  }
326
0
}
327
328
// Update the buffer level after encoding with encoded frame size.
329
static void update_buffer_level_postencode(VP9_COMP *cpi,
330
54.0k
                                           int encoded_frame_size) {
331
54.0k
  RATE_CONTROL *const rc = &cpi->rc;
332
54.0k
  rc->bits_off_target -= encoded_frame_size;
333
  // Clip the buffer level to the maximum specified buffer size.
334
54.0k
  rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
335
  // For screen-content mode, and if frame-dropper is off, don't let buffer
336
  // level go below threshold, given here as -rc->maximum_ buffer_size.
337
54.0k
  if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
338
0
      cpi->oxcf.drop_frames_water_mark == 0)
339
0
    rc->bits_off_target = VPXMAX(rc->bits_off_target, -rc->maximum_buffer_size);
340
341
54.0k
  rc->buffer_level = rc->bits_off_target;
342
343
54.0k
  if (is_one_pass_svc(cpi)) {
344
0
    update_layer_buffer_level_postencode(&cpi->svc, encoded_frame_size);
345
0
  }
346
54.0k
}
347
348
int vp9_rc_get_default_min_gf_interval(int width, int height,
349
87.6k
                                       double framerate) {
350
  // Assume we do not need any constraint lower than 4K 20 fps
351
87.6k
  static const double factor_safe = 3840 * 2160 * 20.0;
352
87.6k
  const double factor = width * height * framerate;
353
87.6k
  const int default_interval =
354
87.6k
      clamp((int)round(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
355
356
87.6k
  if (factor <= factor_safe)
357
85.5k
    return default_interval;
358
2.11k
  else
359
2.11k
    return VPXMAX(default_interval,
360
87.6k
                  (int)round(MIN_GF_INTERVAL * factor / factor_safe));
361
  // Note this logic makes:
362
  // 4K24: 5
363
  // 4K30: 6
364
  // 4K60: 12
365
87.6k
}
366
367
87.6k
int vp9_rc_get_default_max_gf_interval(double framerate, int min_gf_interval) {
368
87.6k
  int interval = VPXMIN(MAX_GF_INTERVAL, (int)round(framerate * 0.75));
369
87.6k
  interval += (interval & 0x01);  // Round to even value
370
87.6k
  return VPXMAX(interval, min_gf_interval);
371
87.6k
}
372
373
4.01k
void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
374
4.01k
  int i;
375
376
4.01k
  if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
377
0
    rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
378
0
    rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
379
4.01k
  } else {
380
4.01k
    rc->avg_frame_qindex[KEY_FRAME] =
381
4.01k
        (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
382
4.01k
    rc->avg_frame_qindex[INTER_FRAME] =
383
4.01k
        (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
384
4.01k
  }
385
386
4.01k
  rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
387
4.01k
  rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
388
389
4.01k
  rc->buffer_level = rc->starting_buffer_level;
390
4.01k
  rc->bits_off_target = rc->starting_buffer_level;
391
392
4.01k
  rc->rolling_target_bits = rc->avg_frame_bandwidth;
393
4.01k
  rc->rolling_actual_bits = rc->avg_frame_bandwidth;
394
4.01k
  rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
395
4.01k
  rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
396
397
4.01k
  rc->total_actual_bits = 0;
398
4.01k
  rc->total_target_bits = 0;
399
4.01k
  rc->total_target_vs_actual = 0;
400
4.01k
  rc->avg_frame_low_motion = 0;
401
4.01k
  rc->count_last_scene_change = 0;
402
4.01k
  rc->af_ratio_onepass_vbr = 10;
403
4.01k
  rc->prev_avg_source_sad_lag = 0;
404
4.01k
  rc->high_source_sad = 0;
405
4.01k
  rc->reset_high_source_sad = 0;
406
4.01k
  rc->high_source_sad_lagindex = -1;
407
4.01k
  rc->high_num_blocks_with_motion = 0;
408
4.01k
  rc->hybrid_intra_scene_change = 0;
409
4.01k
  rc->re_encode_maxq_scene_change = 0;
410
4.01k
  rc->alt_ref_gf_group = 0;
411
4.01k
  rc->last_frame_is_src_altref = 0;
412
4.01k
  rc->fac_active_worst_inter = 150;
413
4.01k
  rc->fac_active_worst_gf = 100;
414
4.01k
  rc->force_qpmin = 0;
415
104k
  for (i = 0; i < MAX_LAG_BUFFERS; ++i) rc->avg_source_sad[i] = 0;
416
4.01k
  rc->frames_to_key = 0;
417
4.01k
  rc->frames_since_key = 8;  // Sensible default for first frame.
418
4.01k
  rc->this_key_frame_forced = 0;
419
4.01k
  rc->next_key_frame_forced = 0;
420
4.01k
  rc->source_alt_ref_pending = 0;
421
4.01k
  rc->source_alt_ref_active = 0;
422
423
4.01k
  rc->frames_till_gf_update_due = 0;
424
4.01k
  rc->constrain_gf_key_freq_onepass_vbr = 1;
425
4.01k
  rc->ni_av_qi = oxcf->worst_allowed_q;
426
4.01k
  rc->ni_tot_qi = 0;
427
4.01k
  rc->ni_frames = 0;
428
429
4.01k
  rc->tot_q = 0.0;
430
4.01k
  rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
431
432
24.0k
  for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
433
20.0k
    rc->rate_correction_factors[i] = 1.0;
434
20.0k
    rc->damped_adjustment[i] = 0;
435
20.0k
  }
436
437
4.01k
  rc->min_gf_interval = oxcf->min_gf_interval;
438
4.01k
  rc->max_gf_interval = oxcf->max_gf_interval;
439
4.01k
  if (rc->min_gf_interval == 0)
440
4.01k
    rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
441
4.01k
        oxcf->width, oxcf->height, oxcf->init_framerate);
442
4.01k
  if (rc->max_gf_interval == 0)
443
4.01k
    rc->max_gf_interval = vp9_rc_get_default_max_gf_interval(
444
4.01k
        oxcf->init_framerate, rc->min_gf_interval);
445
4.01k
  rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
446
4.01k
  if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
447
186
    rc->static_scene_max_gf_interval = FIXED_GF_INTERVAL;
448
3.83k
  } else {
449
3.83k
    rc->static_scene_max_gf_interval = MAX_STATIC_GF_GROUP_LENGTH;
450
3.83k
  }
451
452
4.01k
  rc->force_max_q = 0;
453
4.01k
  rc->last_post_encode_dropped_scene_change = 0;
454
4.01k
  rc->use_post_encode_drop = 0;
455
4.01k
  rc->ext_use_post_encode_drop = 0;
456
4.01k
  rc->disable_overshoot_maxq_cbr = 0;
457
4.01k
  rc->arf_active_best_quality_adjustment_factor = 1.0;
458
4.01k
  rc->arf_increase_active_best_quality = 0;
459
4.01k
  rc->preserve_arf_as_gld = 0;
460
4.01k
  rc->preserve_next_arf_as_gld = 0;
461
4.01k
  rc->show_arf_as_gld = 0;
462
4.01k
}
463
464
0
static int check_buffer_above_thresh(VP9_COMP *cpi, int drop_mark) {
465
0
  SVC *svc = &cpi->svc;
466
0
  if (!cpi->use_svc || cpi->svc.framedrop_mode != FULL_SUPERFRAME_DROP) {
467
0
    RATE_CONTROL *const rc = &cpi->rc;
468
0
    return (rc->buffer_level > drop_mark);
469
0
  } else {
470
0
    int i;
471
    // For SVC in the FULL_SUPERFRAME_DROP): the condition on
472
    // buffer (if its above threshold, so no drop) is checked on current and
473
    // upper spatial layers. If any spatial layer is not above threshold then
474
    // we return 0.
475
0
    for (i = svc->spatial_layer_id; i < svc->number_spatial_layers; ++i) {
476
0
      const int layer = LAYER_IDS_TO_IDX(i, svc->temporal_layer_id,
477
0
                                         svc->number_temporal_layers);
478
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
479
0
      RATE_CONTROL *lrc = &lc->rc;
480
      // Exclude check for layer whose bitrate is 0.
481
0
      if (lc->target_bandwidth > 0) {
482
0
        const int drop_mark_layer = (int)(cpi->svc.framedrop_thresh[i] *
483
0
                                          lrc->optimal_buffer_level / 100);
484
0
        if (!(lrc->buffer_level > drop_mark_layer)) return 0;
485
0
      }
486
0
    }
487
0
    return 1;
488
0
  }
489
0
}
490
491
0
static int check_buffer_below_thresh(VP9_COMP *cpi, int drop_mark) {
492
0
  SVC *svc = &cpi->svc;
493
0
  if (!cpi->use_svc || cpi->svc.framedrop_mode == LAYER_DROP) {
494
0
    RATE_CONTROL *const rc = &cpi->rc;
495
0
    return (rc->buffer_level <= drop_mark);
496
0
  } else {
497
0
    int i;
498
    // For SVC in the constrained framedrop mode (svc->framedrop_mode =
499
    // CONSTRAINED_LAYER_DROP or FULL_SUPERFRAME_DROP): the condition on
500
    // buffer (if its below threshold, so drop frame) is checked on current
501
    // and upper spatial layers. For FULL_SUPERFRAME_DROP mode if any
502
    // spatial layer is <= threshold, then we return 1 (drop).
503
0
    for (i = svc->spatial_layer_id; i < svc->number_spatial_layers; ++i) {
504
0
      const int layer = LAYER_IDS_TO_IDX(i, svc->temporal_layer_id,
505
0
                                         svc->number_temporal_layers);
506
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
507
0
      RATE_CONTROL *lrc = &lc->rc;
508
      // Exclude check for layer whose bitrate is 0.
509
0
      if (lc->target_bandwidth > 0) {
510
0
        const int drop_mark_layer = (int)(cpi->svc.framedrop_thresh[i] *
511
0
                                          lrc->optimal_buffer_level / 100);
512
0
        if (cpi->svc.framedrop_mode == FULL_SUPERFRAME_DROP) {
513
0
          if (lrc->buffer_level <= drop_mark_layer) return 1;
514
0
        } else {
515
0
          if (!(lrc->buffer_level <= drop_mark_layer)) return 0;
516
0
        }
517
0
      }
518
0
    }
519
0
    if (cpi->svc.framedrop_mode == FULL_SUPERFRAME_DROP)
520
0
      return 0;
521
0
    else
522
0
      return 1;
523
0
  }
524
0
}
525
526
0
int vp9_test_drop(VP9_COMP *cpi) {
527
0
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
528
0
  RATE_CONTROL *const rc = &cpi->rc;
529
0
  SVC *svc = &cpi->svc;
530
0
  int drop_frames_water_mark = oxcf->drop_frames_water_mark;
531
0
  if (cpi->use_svc) {
532
    // If we have dropped max_consec_drop frames, then we don't
533
    // drop this spatial layer, and reset counter to 0.
534
0
    if (svc->drop_count[svc->spatial_layer_id] == svc->max_consec_drop) {
535
0
      svc->drop_count[svc->spatial_layer_id] = 0;
536
0
      return 0;
537
0
    } else {
538
0
      drop_frames_water_mark = svc->framedrop_thresh[svc->spatial_layer_id];
539
0
    }
540
0
  }
541
0
  if (!drop_frames_water_mark ||
542
0
      (svc->spatial_layer_id > 0 &&
543
0
       svc->framedrop_mode == FULL_SUPERFRAME_DROP)) {
544
0
    return 0;
545
0
  } else {
546
0
    if ((rc->buffer_level < 0 && svc->framedrop_mode != FULL_SUPERFRAME_DROP) ||
547
0
        (check_buffer_below_thresh(cpi, -1) &&
548
0
         svc->framedrop_mode == FULL_SUPERFRAME_DROP)) {
549
      // Always drop if buffer is below 0.
550
0
      return 1;
551
0
    } else {
552
      // If buffer is below drop_mark, for now just drop every other frame
553
      // (starting with the next frame) until it increases back over drop_mark.
554
0
      int drop_mark =
555
0
          (int)(drop_frames_water_mark * rc->optimal_buffer_level / 100);
556
0
      if (check_buffer_above_thresh(cpi, drop_mark) &&
557
0
          (rc->decimation_factor > 0)) {
558
0
        --rc->decimation_factor;
559
0
      } else if (check_buffer_below_thresh(cpi, drop_mark) &&
560
0
                 rc->decimation_factor == 0) {
561
0
        rc->decimation_factor = 1;
562
0
      }
563
0
      if (rc->decimation_factor > 0) {
564
0
        if (rc->decimation_count > 0) {
565
0
          --rc->decimation_count;
566
0
          return 1;
567
0
        } else {
568
0
          rc->decimation_count = rc->decimation_factor;
569
0
          return 0;
570
0
        }
571
0
      } else {
572
0
        rc->decimation_count = 0;
573
0
        return 0;
574
0
      }
575
0
    }
576
0
  }
577
0
}
578
579
0
int post_encode_drop_cbr(VP9_COMP *cpi, size_t *size) {
580
0
  size_t frame_size = *size << 3;
581
0
  int64_t new_buffer_level =
582
0
      cpi->rc.buffer_level + cpi->rc.avg_frame_bandwidth - (int64_t)frame_size;
583
584
  // For now we drop if new buffer level (given the encoded frame size) goes
585
  // below 0.
586
0
  if (new_buffer_level < 0) {
587
0
    *size = 0;
588
0
    vp9_rc_postencode_update_drop_frame(cpi);
589
    // Update flag to use for next frame.
590
0
    if (cpi->rc.high_source_sad ||
591
0
        (cpi->use_svc && cpi->svc.high_source_sad_superframe))
592
0
      cpi->rc.last_post_encode_dropped_scene_change = 1;
593
    // Force max_q on next fame.
594
0
    cpi->rc.force_max_q = 1;
595
0
    cpi->rc.avg_frame_qindex[INTER_FRAME] = cpi->rc.worst_quality;
596
0
    cpi->last_frame_dropped = 1;
597
0
    cpi->ext_refresh_frame_flags_pending = 0;
598
0
    if (cpi->use_svc) {
599
0
      SVC *svc = &cpi->svc;
600
0
      int sl = 0;
601
0
      int tl = 0;
602
0
      svc->last_layer_dropped[svc->spatial_layer_id] = 1;
603
0
      svc->drop_spatial_layer[svc->spatial_layer_id] = 1;
604
0
      svc->drop_count[svc->spatial_layer_id]++;
605
0
      svc->skip_enhancement_layer = 1;
606
      // Postencode drop is only checked on base spatial layer,
607
      // for now if max-q is set on base we force it on all layers.
608
0
      for (sl = 0; sl < svc->number_spatial_layers; ++sl) {
609
0
        for (tl = 0; tl < svc->number_temporal_layers; ++tl) {
610
0
          const int layer =
611
0
              LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
612
0
          LAYER_CONTEXT *lc = &svc->layer_context[layer];
613
0
          RATE_CONTROL *lrc = &lc->rc;
614
0
          lrc->force_max_q = 1;
615
0
          lrc->avg_frame_qindex[INTER_FRAME] = cpi->rc.worst_quality;
616
0
        }
617
0
      }
618
0
    }
619
0
    return 1;
620
0
  }
621
622
0
  cpi->rc.force_max_q = 0;
623
0
  cpi->rc.last_post_encode_dropped_scene_change = 0;
624
0
  return 0;
625
0
}
626
627
0
int vp9_rc_drop_frame(VP9_COMP *cpi) {
628
0
  SVC *svc = &cpi->svc;
629
0
  int svc_prev_layer_dropped = 0;
630
  // In the constrained or full_superframe framedrop mode for svc
631
  // (framedrop_mode != (LAYER_DROP && CONSTRAINED_FROM_ABOVE)),
632
  // if the previous spatial layer was dropped, drop the current spatial layer.
633
0
  if (cpi->use_svc && svc->spatial_layer_id > 0 &&
634
0
      svc->drop_spatial_layer[svc->spatial_layer_id - 1])
635
0
    svc_prev_layer_dropped = 1;
636
0
  if ((svc_prev_layer_dropped && svc->framedrop_mode != LAYER_DROP &&
637
0
       svc->framedrop_mode != CONSTRAINED_FROM_ABOVE_DROP) ||
638
0
      svc->force_drop_constrained_from_above[svc->spatial_layer_id] ||
639
0
      vp9_test_drop(cpi)) {
640
0
    vp9_rc_postencode_update_drop_frame(cpi);
641
0
    cpi->ext_refresh_frame_flags_pending = 0;
642
0
    cpi->last_frame_dropped = 1;
643
0
    if (cpi->use_svc) {
644
0
      svc->last_layer_dropped[svc->spatial_layer_id] = 1;
645
0
      svc->drop_spatial_layer[svc->spatial_layer_id] = 1;
646
0
      svc->drop_count[svc->spatial_layer_id]++;
647
0
      svc->skip_enhancement_layer = 1;
648
0
      if (svc->framedrop_mode == LAYER_DROP ||
649
0
          (svc->framedrop_mode == CONSTRAINED_FROM_ABOVE_DROP &&
650
0
           svc->force_drop_constrained_from_above[svc->number_spatial_layers -
651
0
                                                  1] == 0) ||
652
0
          svc->drop_spatial_layer[0] == 0) {
653
        // For the case of constrained drop mode where full superframe is
654
        // dropped, we don't increment the svc frame counters.
655
        // In particular temporal layer counter (which is incremented in
656
        // vp9_inc_frame_in_layer()) won't be incremented, so on a dropped
657
        // frame we try the same temporal_layer_id on next incoming frame.
658
        // This is to avoid an issue with temporal alignment with full
659
        // superframe dropping.
660
0
        vp9_inc_frame_in_layer(cpi);
661
0
      }
662
0
      if (svc->spatial_layer_id == svc->number_spatial_layers - 1) {
663
0
        int i;
664
0
        int all_layers_drop = 1;
665
0
        for (i = 0; i < svc->spatial_layer_id; i++) {
666
0
          if (svc->drop_spatial_layer[i] == 0) {
667
0
            all_layers_drop = 0;
668
0
            break;
669
0
          }
670
0
        }
671
0
        if (all_layers_drop == 1) svc->skip_enhancement_layer = 0;
672
0
      }
673
0
    }
674
0
    return 1;
675
0
  }
676
0
  return 0;
677
0
}
678
679
0
static int adjust_q_cbr(const VP9_COMP *cpi, int q) {
680
  // This makes sure q is between oscillating Qs to prevent resonance.
681
0
  if (!cpi->rc.reset_high_source_sad &&
682
0
      (!cpi->oxcf.gf_cbr_boost_pct ||
683
0
       !(cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)) &&
684
0
      (cpi->rc.rc_1_frame * cpi->rc.rc_2_frame == -1) &&
685
0
      cpi->rc.q_1_frame != cpi->rc.q_2_frame) {
686
0
    int qclamp = clamp(q, VPXMIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
687
0
                       VPXMAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
688
    // If the previous frame had overshoot and the current q needs to increase
689
    // above the clamped value, reduce the clamp for faster reaction to
690
    // overshoot.
691
0
    if (cpi->rc.rc_1_frame == -1 && q > qclamp)
692
0
      q = (q + qclamp) >> 1;
693
0
    else
694
0
      q = qclamp;
695
0
  }
696
0
  if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
697
0
      cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
698
0
    vp9_cyclic_refresh_limit_q(cpi, &q);
699
0
  return VPXMAX(VPXMIN(q, cpi->rc.worst_quality), cpi->rc.best_quality);
700
0
}
701
702
102k
static double get_rate_correction_factor(const VP9_COMP *cpi) {
703
102k
  const RATE_CONTROL *const rc = &cpi->rc;
704
102k
  const VP9_COMMON *const cm = &cpi->common;
705
102k
  double rcf;
706
707
102k
  if (frame_is_intra_only(cm)) {
708
21.0k
    rcf = rc->rate_correction_factors[KF_STD];
709
81.6k
  } else if (cpi->oxcf.pass == 2) {
710
0
    RATE_FACTOR_LEVEL rf_lvl =
711
0
        cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
712
0
    rcf = rc->rate_correction_factors[rf_lvl];
713
81.6k
  } else {
714
81.6k
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
715
5.57k
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
716
5.57k
        (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 100))
717
5.57k
      rcf = rc->rate_correction_factors[GF_ARF_STD];
718
76.0k
    else
719
76.0k
      rcf = rc->rate_correction_factors[INTER_NORMAL];
720
81.6k
  }
721
102k
  rcf *= rcf_mult[rc->frame_size_selector];
722
102k
  return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
723
102k
}
724
725
54.0k
static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
726
54.0k
  RATE_CONTROL *const rc = &cpi->rc;
727
54.0k
  const VP9_COMMON *const cm = &cpi->common;
728
729
  // Normalize RCF to account for the size-dependent scaling factor.
730
54.0k
  factor /= rcf_mult[cpi->rc.frame_size_selector];
731
732
54.0k
  factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
733
734
54.0k
  if (frame_is_intra_only(cm)) {
735
12.7k
    rc->rate_correction_factors[KF_STD] = factor;
736
41.3k
  } else if (cpi->oxcf.pass == 2) {
737
0
    RATE_FACTOR_LEVEL rf_lvl =
738
0
        cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
739
0
    rc->rate_correction_factors[rf_lvl] = factor;
740
41.3k
  } else {
741
41.3k
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
742
2.81k
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
743
2.81k
        (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 100))
744
2.81k
      rc->rate_correction_factors[GF_ARF_STD] = factor;
745
38.5k
    else
746
38.5k
      rc->rate_correction_factors[INTER_NORMAL] = factor;
747
41.3k
  }
748
54.0k
}
749
750
54.0k
void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi) {
751
54.0k
  const VP9_COMMON *const cm = &cpi->common;
752
54.0k
  int correction_factor = 100;
753
54.0k
  double rate_correction_factor = get_rate_correction_factor(cpi);
754
54.0k
  double adjustment_limit;
755
54.0k
  RATE_FACTOR_LEVEL rf_lvl =
756
54.0k
      cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
757
758
54.0k
  int projected_size_based_on_q = 0;
759
760
  // Do not update the rate factors for arf overlay frames.
761
54.0k
  if (cpi->rc.is_src_frame_alt_ref) return;
762
763
  // Clear down mmx registers to allow floating point in what follows
764
54.0k
  vpx_clear_system_state();
765
766
  // Work out how big we would have expected the frame to be at this Q given
767
  // the current correction factor.
768
  // Stay in double to avoid int overflow when values are large
769
54.0k
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled) {
770
0
    projected_size_based_on_q =
771
0
        vp9_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
772
54.0k
  } else {
773
54.0k
    FRAME_TYPE frame_type = cm->intra_only ? KEY_FRAME : cm->frame_type;
774
54.0k
    projected_size_based_on_q =
775
54.0k
        vp9_estimate_bits_at_q(frame_type, cm->base_qindex, cm->MBs,
776
54.0k
                               rate_correction_factor, cm->bit_depth);
777
54.0k
  }
778
  // Work out a size correction factor.
779
54.0k
  if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
780
43.2k
    correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
781
43.2k
                              projected_size_based_on_q);
782
783
  // Do not use damped adjustment for the first frame of each frame type
784
54.0k
  if (!cpi->rc.damped_adjustment[rf_lvl]) {
785
3.88k
    adjustment_limit = 1.0;
786
3.88k
    cpi->rc.damped_adjustment[rf_lvl] = 1;
787
50.2k
  } else {
788
    // More heavily damped adjustment used if we have been oscillating either
789
    // side of target.
790
50.2k
    adjustment_limit =
791
50.2k
        0.25 + 0.5 * VPXMIN(1, fabs(log10(0.01 * correction_factor)));
792
50.2k
  }
793
794
54.0k
  cpi->rc.q_2_frame = cpi->rc.q_1_frame;
795
54.0k
  cpi->rc.q_1_frame = cm->base_qindex;
796
54.0k
  cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
797
54.0k
  if (correction_factor > 110)
798
14.2k
    cpi->rc.rc_1_frame = -1;
799
39.8k
  else if (correction_factor < 90)
800
17.8k
    cpi->rc.rc_1_frame = 1;
801
21.9k
  else
802
21.9k
    cpi->rc.rc_1_frame = 0;
803
804
  // Turn off oscilation detection in the case of massive overshoot.
805
54.0k
  if (cpi->rc.rc_1_frame == -1 && cpi->rc.rc_2_frame == 1 &&
806
3.25k
      correction_factor > 1000) {
807
196
    cpi->rc.rc_2_frame = 0;
808
196
  }
809
810
54.0k
  if (correction_factor > 102) {
811
    // We are not already at the worst allowable quality
812
17.8k
    correction_factor =
813
17.8k
        (int)(100 + ((correction_factor - 100) * adjustment_limit));
814
17.8k
    rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
815
    // Keep rate_correction_factor within limits
816
17.8k
    if (rate_correction_factor > MAX_BPB_FACTOR)
817
0
      rate_correction_factor = MAX_BPB_FACTOR;
818
36.2k
  } else if (correction_factor < 99) {
819
    // We are not already at the best allowable quality
820
22.6k
    correction_factor =
821
22.6k
        (int)(100 - ((100 - correction_factor) * adjustment_limit));
822
22.6k
    rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
823
824
    // Keep rate_correction_factor within limits
825
22.6k
    if (rate_correction_factor < MIN_BPB_FACTOR)
826
215
      rate_correction_factor = MIN_BPB_FACTOR;
827
22.6k
  }
828
829
54.0k
  set_rate_correction_factor(cpi, rate_correction_factor);
830
54.0k
}
831
832
int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
833
48.6k
                      int active_best_quality, int active_worst_quality) {
834
48.6k
  const VP9_COMMON *const cm = &cpi->common;
835
48.6k
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
836
48.6k
  int q = active_worst_quality;
837
48.6k
  int last_error = INT_MAX;
838
48.6k
  int i, target_bits_per_mb, bits_per_mb_at_this_q;
839
48.6k
  const double correction_factor = get_rate_correction_factor(cpi);
840
841
  // Calculate required scaling factor based on target frame size and size of
842
  // frame produced using previous Q.
843
48.6k
  target_bits_per_mb =
844
48.6k
      (int)(((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs);
845
846
48.6k
  i = active_best_quality;
847
848
1.21M
  do {
849
1.21M
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cr->apply_cyclic_refresh &&
850
0
        (!cpi->oxcf.gf_cbr_boost_pct || !cpi->refresh_golden_frame)) {
851
0
      bits_per_mb_at_this_q =
852
0
          (int)vp9_cyclic_refresh_rc_bits_per_mb(cpi, i, correction_factor);
853
1.21M
    } else {
854
1.21M
      FRAME_TYPE frame_type = cm->intra_only ? KEY_FRAME : cm->frame_type;
855
1.21M
      bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(
856
1.21M
          frame_type, i, correction_factor, cm->bit_depth);
857
1.21M
    }
858
859
1.21M
    int diff_bits = (int)VPXMIN(
860
1.21M
        VPXMAX(((int64_t)target_bits_per_mb - (int64_t)bits_per_mb_at_this_q),
861
1.21M
               -INT_MAX),
862
1.21M
        INT_MAX);
863
1.21M
    if (bits_per_mb_at_this_q <= target_bits_per_mb) {
864
37.3k
      if (diff_bits <= last_error)
865
33.8k
        q = i;
866
3.58k
      else
867
3.58k
        q = i - 1;
868
869
37.3k
      break;
870
1.17M
    } else {
871
1.17M
      last_error = -diff_bits;
872
1.17M
    }
873
1.21M
  } while (++i <= active_worst_quality);
874
875
  // Adjustment to q for CBR mode.
876
48.6k
  if (cpi->oxcf.rc_mode == VPX_CBR) return adjust_q_cbr(cpi, q);
877
878
48.6k
  return q;
879
48.6k
}
880
881
static int get_active_quality(int q, int gfu_boost, int low, int high,
882
11.0k
                              int *low_motion_minq, int *high_motion_minq) {
883
11.0k
  if (gfu_boost > high) {
884
0
    return low_motion_minq[q];
885
11.0k
  } else if (gfu_boost < low) {
886
0
    return high_motion_minq[q];
887
11.0k
  } else {
888
11.0k
    const int gap = high - low;
889
11.0k
    const int offset = high - gfu_boost;
890
11.0k
    const int qdiff = high_motion_minq[q] - low_motion_minq[q];
891
11.0k
    const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
892
11.0k
    return low_motion_minq[q] + adjustment;
893
11.0k
  }
894
11.0k
}
895
896
static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
897
8.29k
                                 vpx_bit_depth_t bit_depth) {
898
8.29k
  int *kf_low_motion_minq;
899
8.29k
  int *kf_high_motion_minq;
900
8.29k
  ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
901
8.29k
  ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
902
8.29k
  return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
903
8.29k
                            kf_low_motion_minq, kf_high_motion_minq);
904
8.29k
}
905
906
static int get_gf_active_quality(const VP9_COMP *const cpi, int q,
907
2.75k
                                 vpx_bit_depth_t bit_depth) {
908
2.75k
  const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
909
2.75k
  const RATE_CONTROL *const rc = &cpi->rc;
910
911
2.75k
  int *arfgf_low_motion_minq;
912
2.75k
  int *arfgf_high_motion_minq;
913
2.75k
  const int gfu_boost = cpi->multi_layer_arf
914
2.75k
                            ? gf_group->gfu_boost[gf_group->index]
915
2.75k
                            : rc->gfu_boost;
916
2.75k
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
917
2.75k
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
918
2.75k
  return get_active_quality(q, gfu_boost, gf_low, gf_high,
919
2.75k
                            arfgf_low_motion_minq, arfgf_high_motion_minq);
920
2.75k
}
921
922
54.1k
static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
923
54.1k
  const RATE_CONTROL *const rc = &cpi->rc;
924
54.1k
  const unsigned int curr_frame = cpi->common.current_video_frame;
925
54.1k
  int active_worst_quality;
926
927
54.1k
  if (cpi->common.frame_type == KEY_FRAME) {
928
12.8k
    active_worst_quality =
929
12.8k
        curr_frame == 0 ? rc->worst_quality : rc->last_q[KEY_FRAME] << 1;
930
41.3k
  } else {
931
41.3k
    if (!rc->is_src_frame_alt_ref && !cpi->use_svc &&
932
41.3k
        (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
933
2.83k
      active_worst_quality =
934
2.83k
          curr_frame == 1
935
2.83k
              ? rc->last_q[KEY_FRAME] * 5 >> 2
936
2.83k
              : rc->last_q[INTER_FRAME] * rc->fac_active_worst_gf / 100;
937
38.5k
    } else {
938
38.5k
      active_worst_quality = curr_frame == 1
939
38.5k
                                 ? rc->last_q[KEY_FRAME] << 1
940
38.5k
                                 : rc->avg_frame_qindex[INTER_FRAME] *
941
36.2k
                                       rc->fac_active_worst_inter / 100;
942
38.5k
    }
943
41.3k
  }
944
54.1k
  return VPXMIN(active_worst_quality, rc->worst_quality);
945
54.1k
}
946
947
// Adjust active_worst_quality level based on buffer level.
948
0
static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
949
  // Adjust active_worst_quality: If buffer is above the optimal/target level,
950
  // bring active_worst_quality down depending on fullness of buffer.
951
  // If buffer is below the optimal level, let the active_worst_quality go from
952
  // ambient Q (at buffer = optimal level) to worst_quality level
953
  // (at buffer = critical level).
954
0
  const VP9_COMMON *const cm = &cpi->common;
955
0
  const RATE_CONTROL *rc = &cpi->rc;
956
  // Buffer level below which we push active_worst to worst_quality.
957
0
  int64_t critical_level = rc->optimal_buffer_level >> 3;
958
0
  int64_t buff_lvl_step = 0;
959
0
  int adjustment = 0;
960
0
  int active_worst_quality;
961
0
  int ambient_qp;
962
0
  unsigned int num_frames_weight_key = 5 * cpi->svc.number_temporal_layers;
963
0
  if (frame_is_intra_only(cm) || rc->reset_high_source_sad || rc->force_max_q)
964
0
    return rc->worst_quality;
965
  // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
966
  // for the first few frames following key frame. These are both initialized
967
  // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
968
  // So for first few frames following key, the qp of that key frame is weighted
969
  // into the active_worst_quality setting.
970
0
  ambient_qp = (cm->current_video_frame < num_frames_weight_key)
971
0
                   ? VPXMIN(rc->avg_frame_qindex[INTER_FRAME],
972
0
                            rc->avg_frame_qindex[KEY_FRAME])
973
0
                   : rc->avg_frame_qindex[INTER_FRAME];
974
0
  active_worst_quality = VPXMIN(rc->worst_quality, (ambient_qp * 5) >> 2);
975
  // For SVC if the current base spatial layer was key frame, use the QP from
976
  // that base layer for ambient_qp.
977
0
  if (cpi->use_svc && cpi->svc.spatial_layer_id > 0) {
978
0
    int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
979
0
                                 cpi->svc.number_temporal_layers);
980
0
    const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
981
0
    if (lc->is_key_frame) {
982
0
      const RATE_CONTROL *lrc = &lc->rc;
983
0
      ambient_qp = VPXMIN(ambient_qp, lrc->last_q[KEY_FRAME]);
984
0
      active_worst_quality = VPXMIN(rc->worst_quality, (ambient_qp * 9) >> 3);
985
0
    }
986
0
  }
987
0
  if (rc->buffer_level > rc->optimal_buffer_level) {
988
    // Adjust down.
989
    // Maximum limit for down adjustment ~30%; make it lower for screen content.
990
0
    int max_adjustment_down = active_worst_quality / 3;
991
0
    if (cpi->oxcf.content == VP9E_CONTENT_SCREEN)
992
0
      max_adjustment_down = active_worst_quality >> 3;
993
0
    if (max_adjustment_down) {
994
0
      buff_lvl_step = ((rc->maximum_buffer_size - rc->optimal_buffer_level) /
995
0
                       max_adjustment_down);
996
0
      if (buff_lvl_step)
997
0
        adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
998
0
                           buff_lvl_step);
999
0
      active_worst_quality -= adjustment;
1000
0
    }
1001
0
  } else if (rc->buffer_level > critical_level) {
1002
    // Adjust up from ambient Q.
1003
0
    if (critical_level) {
1004
0
      buff_lvl_step = (rc->optimal_buffer_level - critical_level);
1005
0
      if (buff_lvl_step) {
1006
0
        adjustment = (int)((rc->worst_quality - ambient_qp) *
1007
0
                           (rc->optimal_buffer_level - rc->buffer_level) /
1008
0
                           buff_lvl_step);
1009
0
      }
1010
0
      active_worst_quality = ambient_qp + adjustment;
1011
0
    }
1012
0
  } else {
1013
    // Set to worst_quality if buffer is below critical level.
1014
0
    active_worst_quality = rc->worst_quality;
1015
0
  }
1016
0
  return active_worst_quality;
1017
0
}
1018
1019
static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
1020
                                             int *bottom_index,
1021
0
                                             int *top_index) {
1022
0
  const VP9_COMMON *const cm = &cpi->common;
1023
0
  const RATE_CONTROL *const rc = &cpi->rc;
1024
0
  int active_best_quality;
1025
0
  int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
1026
0
  int q;
1027
0
  int *rtc_minq;
1028
0
  ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
1029
1030
0
  if (frame_is_intra_only(cm)) {
1031
0
    active_best_quality = rc->best_quality;
1032
    // Handle the special case for key frames forced when we have reached
1033
    // the maximum key frame interval. Here force the Q to a range
1034
    // based on the ambient Q to reduce the risk of popping.
1035
0
    if (rc->this_key_frame_forced) {
1036
0
      int qindex = rc->last_boosted_qindex;
1037
0
      double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1038
0
      int delta_qindex = vp9_compute_qdelta(
1039
0
          rc, last_boosted_q, (last_boosted_q * 0.75), cm->bit_depth);
1040
0
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1041
0
    } else if (cm->current_video_frame > 0) {
1042
      // not first frame of one pass and kf_boost is set
1043
0
      double q_adj_factor = 1.0;
1044
0
      double q_val;
1045
1046
0
      active_best_quality = get_kf_active_quality(
1047
0
          rc, rc->avg_frame_qindex[KEY_FRAME], cm->bit_depth);
1048
1049
      // Allow somewhat lower kf minq with small image formats.
1050
0
      if ((cm->width * cm->height) <= (352 * 288)) {
1051
0
        q_adj_factor -= 0.25;
1052
0
      }
1053
1054
      // Convert the adjustment factor to a qindex delta
1055
      // on active_best_quality.
1056
0
      q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1057
0
      active_best_quality +=
1058
0
          vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
1059
0
    }
1060
0
  } else if (!rc->is_src_frame_alt_ref && !cpi->use_svc &&
1061
0
             cpi->oxcf.gf_cbr_boost_pct &&
1062
0
             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1063
    // Use the lower of active_worst_quality and recent
1064
    // average Q as basis for GF/ARF best Q limit unless last frame was
1065
    // a key frame.
1066
0
    if (rc->frames_since_key > 1 &&
1067
0
        rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1068
0
      q = rc->avg_frame_qindex[INTER_FRAME];
1069
0
    } else {
1070
0
      q = active_worst_quality;
1071
0
    }
1072
0
    active_best_quality = get_gf_active_quality(cpi, q, cm->bit_depth);
1073
0
  } else {
1074
    // Use the lower of active_worst_quality and recent/average Q.
1075
0
    if (cm->current_video_frame > 1) {
1076
0
      if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
1077
0
        active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
1078
0
      else
1079
0
        active_best_quality = rtc_minq[active_worst_quality];
1080
0
    } else {
1081
0
      if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
1082
0
        active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
1083
0
      else
1084
0
        active_best_quality = rtc_minq[active_worst_quality];
1085
0
    }
1086
0
  }
1087
1088
  // Clip the active best and worst quality values to limits
1089
0
  active_best_quality =
1090
0
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1091
0
  active_worst_quality =
1092
0
      clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1093
1094
0
  *top_index = active_worst_quality;
1095
0
  *bottom_index = active_best_quality;
1096
1097
  // Special case code to try and match quality with forced key frames
1098
0
  if (frame_is_intra_only(cm) && rc->this_key_frame_forced) {
1099
0
    q = rc->last_boosted_qindex;
1100
0
  } else {
1101
0
    q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1102
0
                          active_worst_quality);
1103
0
    if (q > *top_index) {
1104
      // Special case when we are targeting the max allowed rate
1105
0
      if (rc->this_frame_target >= rc->max_frame_bandwidth)
1106
0
        *top_index = q;
1107
0
      else
1108
0
        q = *top_index;
1109
0
    }
1110
0
  }
1111
1112
0
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1113
0
  assert(*bottom_index <= rc->worst_quality &&
1114
0
         *bottom_index >= rc->best_quality);
1115
0
  assert(q <= rc->worst_quality && q >= rc->best_quality);
1116
0
  return q;
1117
0
}
1118
1119
static int get_active_cq_level_one_pass(const RATE_CONTROL *rc,
1120
54.1k
                                        const VP9EncoderConfig *const oxcf) {
1121
54.1k
  static const double cq_adjust_threshold = 0.1;
1122
54.1k
  int active_cq_level = oxcf->cq_level;
1123
54.1k
  if (oxcf->rc_mode == VPX_CQ && rc->total_target_bits > 0) {
1124
0
    const double x = (double)rc->total_actual_bits / rc->total_target_bits;
1125
0
    if (x < cq_adjust_threshold) {
1126
0
      active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
1127
0
    }
1128
0
  }
1129
54.1k
  return active_cq_level;
1130
54.1k
}
1131
1132
0
#define SMOOTH_PCT_MIN 0.1
1133
0
#define SMOOTH_PCT_DIV 0.05
1134
static int get_active_cq_level_two_pass(const TWO_PASS *twopass,
1135
                                        const RATE_CONTROL *rc,
1136
0
                                        const VP9EncoderConfig *const oxcf) {
1137
0
  static const double cq_adjust_threshold = 0.1;
1138
0
  int active_cq_level = oxcf->cq_level;
1139
0
  if (oxcf->rc_mode == VPX_CQ) {
1140
0
    if (twopass->mb_smooth_pct > SMOOTH_PCT_MIN) {
1141
0
      active_cq_level -=
1142
0
          (int)((twopass->mb_smooth_pct - SMOOTH_PCT_MIN) / SMOOTH_PCT_DIV);
1143
0
      active_cq_level = VPXMAX(active_cq_level, 0);
1144
0
    }
1145
0
    if (rc->total_target_bits > 0) {
1146
0
      const double x = (double)rc->total_actual_bits / rc->total_target_bits;
1147
0
      if (x < cq_adjust_threshold) {
1148
0
        active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
1149
0
      }
1150
0
    }
1151
0
  }
1152
0
  return active_cq_level;
1153
0
}
1154
1155
static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
1156
                                             int *bottom_index,
1157
54.1k
                                             int *top_index) {
1158
54.1k
  const VP9_COMMON *const cm = &cpi->common;
1159
54.1k
  const RATE_CONTROL *const rc = &cpi->rc;
1160
54.1k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1161
54.1k
  const int cq_level = get_active_cq_level_one_pass(rc, oxcf);
1162
54.1k
  int active_best_quality;
1163
54.1k
  int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
1164
54.1k
  int q;
1165
54.1k
  int *inter_minq;
1166
54.1k
  ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
1167
1168
54.1k
  if (frame_is_intra_only(cm)) {
1169
12.8k
    if (oxcf->rc_mode == VPX_Q) {
1170
2.00k
      int qindex = cq_level;
1171
2.00k
      double qstart = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1172
2.00k
      int delta_qindex =
1173
2.00k
          vp9_compute_qdelta(rc, qstart, qstart * 0.25, cm->bit_depth);
1174
2.00k
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1175
10.8k
    } else if (rc->this_key_frame_forced) {
1176
      // Handle the special case for key frames forced when we have reached
1177
      // the maximum key frame interval. Here force the Q to a range
1178
      // based on the ambient Q to reduce the risk of popping.
1179
2.52k
      int qindex = rc->last_boosted_qindex;
1180
2.52k
      double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1181
2.52k
      int delta_qindex = vp9_compute_qdelta(
1182
2.52k
          rc, last_boosted_q, last_boosted_q * 0.75, cm->bit_depth);
1183
2.52k
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1184
8.29k
    } else {
1185
      // not first frame of one pass and kf_boost is set
1186
8.29k
      double q_adj_factor = 1.0;
1187
8.29k
      double q_val;
1188
1189
8.29k
      active_best_quality = get_kf_active_quality(
1190
8.29k
          rc, rc->avg_frame_qindex[KEY_FRAME], cm->bit_depth);
1191
1192
      // Allow somewhat lower kf minq with small image formats.
1193
8.29k
      if ((cm->width * cm->height) <= (352 * 288)) {
1194
7.99k
        q_adj_factor -= 0.25;
1195
7.99k
      }
1196
1197
      // Convert the adjustment factor to a qindex delta
1198
      // on active_best_quality.
1199
8.29k
      q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1200
8.29k
      active_best_quality +=
1201
8.29k
          vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
1202
8.29k
    }
1203
41.3k
  } else if (!rc->is_src_frame_alt_ref &&
1204
41.3k
             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1205
    // Use the lower of active_worst_quality and recent
1206
    // average Q as basis for GF/ARF best Q limit unless last frame was
1207
    // a key frame.
1208
2.83k
    if (rc->frames_since_key > 1) {
1209
2.83k
      if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1210
676
        q = rc->avg_frame_qindex[INTER_FRAME];
1211
2.16k
      } else {
1212
2.16k
        q = active_worst_quality;
1213
2.16k
      }
1214
2.83k
    } else {
1215
0
      q = rc->avg_frame_qindex[KEY_FRAME];
1216
0
    }
1217
    // For constrained quality don't allow Q less than the cq level
1218
2.83k
    if (oxcf->rc_mode == VPX_CQ) {
1219
0
      if (q < cq_level) q = cq_level;
1220
1221
0
      active_best_quality = get_gf_active_quality(cpi, q, cm->bit_depth);
1222
1223
      // Constrained quality use slightly lower active best.
1224
0
      active_best_quality = active_best_quality * 15 / 16;
1225
1226
2.83k
    } else if (oxcf->rc_mode == VPX_Q) {
1227
79
      int qindex = cq_level;
1228
79
      double qstart = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1229
79
      int delta_qindex;
1230
79
      if (cpi->refresh_alt_ref_frame)
1231
0
        delta_qindex =
1232
0
            vp9_compute_qdelta(rc, qstart, qstart * 0.40, cm->bit_depth);
1233
79
      else
1234
79
        delta_qindex =
1235
79
            vp9_compute_qdelta(rc, qstart, qstart * 0.50, cm->bit_depth);
1236
79
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1237
2.75k
    } else {
1238
2.75k
      active_best_quality = get_gf_active_quality(cpi, q, cm->bit_depth);
1239
2.75k
    }
1240
38.5k
  } else {
1241
38.5k
    if (oxcf->rc_mode == VPX_Q) {
1242
945
      int qindex = cq_level;
1243
945
      double qstart = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1244
945
      double delta_rate[FIXED_GF_INTERVAL] = { 0.50, 1.0, 0.85, 1.0,
1245
945
                                               0.70, 1.0, 0.85, 1.0 };
1246
945
      int delta_qindex = vp9_compute_qdelta(
1247
945
          rc, qstart,
1248
945
          qstart * delta_rate[cm->current_video_frame % FIXED_GF_INTERVAL],
1249
945
          cm->bit_depth);
1250
945
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1251
37.5k
    } else {
1252
      // Use the min of the average Q and active_worst_quality as basis for
1253
      // active_best.
1254
37.5k
      if (cm->current_video_frame > 1) {
1255
35.3k
        q = VPXMIN(rc->avg_frame_qindex[INTER_FRAME], active_worst_quality);
1256
35.3k
        active_best_quality = inter_minq[q];
1257
35.3k
      } else {
1258
2.21k
        active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
1259
2.21k
      }
1260
      // For the constrained quality mode we don't want
1261
      // q to fall below the cq level.
1262
37.5k
      if ((oxcf->rc_mode == VPX_CQ) && (active_best_quality < cq_level)) {
1263
0
        active_best_quality = cq_level;
1264
0
      }
1265
37.5k
    }
1266
38.5k
  }
1267
1268
  // Clip the active best and worst quality values to limits
1269
54.1k
  active_best_quality =
1270
54.1k
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1271
54.1k
  active_worst_quality =
1272
54.1k
      clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1273
1274
54.1k
  *top_index = active_worst_quality;
1275
54.1k
  *bottom_index = active_best_quality;
1276
1277
54.1k
#if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
1278
54.1k
  {
1279
54.1k
    int qdelta = 0;
1280
54.1k
    vpx_clear_system_state();
1281
1282
    // Limit Q range for the adaptive loop.
1283
54.1k
    if (cm->frame_type == KEY_FRAME && !rc->this_key_frame_forced &&
1284
10.2k
        !(cm->current_video_frame == 0)) {
1285
6.36k
      qdelta = vp9_compute_qdelta_by_rate(
1286
6.36k
          &cpi->rc, cm->frame_type, active_worst_quality, 2.0, cm->bit_depth);
1287
47.8k
    } else if (!rc->is_src_frame_alt_ref &&
1288
47.8k
               (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1289
9.29k
      qdelta = vp9_compute_qdelta_by_rate(
1290
9.29k
          &cpi->rc, cm->frame_type, active_worst_quality, 1.75, cm->bit_depth);
1291
9.29k
    }
1292
54.1k
    if (rc->high_source_sad && cpi->sf.use_altref_onepass) qdelta = 0;
1293
54.1k
    *top_index = active_worst_quality + qdelta;
1294
54.1k
    *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
1295
54.1k
  }
1296
54.1k
#endif
1297
1298
54.1k
  if (oxcf->rc_mode == VPX_Q) {
1299
3.03k
    q = active_best_quality;
1300
    // Special case code to try and match quality with forced key frames
1301
51.1k
  } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
1302
2.52k
    q = rc->last_boosted_qindex;
1303
48.6k
  } else {
1304
48.6k
    q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1305
48.6k
                          active_worst_quality);
1306
1307
    // For no lookahead: if buffer_level indicates overshoot, then avoid going
1308
    // to very low QP. This reduces overshoot observed in Issue: 376707227.
1309
    // Note the buffer_level is updated for every encoded frame as:
1310
    // buffer_level - starting_buffer_level += (avg_frame_bandwidth -
1311
    // encoded_frame_size). So normalizing this with framerate and #encoded
1312
    // frames (current_video_frame) gives the difference/error between target
1313
    // and encoding bitrate. The additional avg_frame_bandwidth term is to
1314
    // compensate for the pre-encoded buffer update (in
1315
    // vp9_rc_get_one_pass_vbr_params).
1316
48.6k
    const int qp_thresh = 32;
1317
48.6k
    const int64_t bitrate_err =
1318
48.6k
        (int64_t)(cpi->framerate *
1319
48.6k
                  (rc->buffer_level - rc->starting_buffer_level -
1320
48.6k
                   rc->avg_frame_bandwidth) /
1321
48.6k
                  (cm->current_video_frame + 1));
1322
    // Threshold may be tuned, but for now condition this on low QP.
1323
48.6k
    if (cpi->oxcf.lag_in_frames == 0 && bitrate_err / 1000 < -10 &&
1324
0
        qp_thresh < rc->worst_quality &&
1325
0
        (q < qp_thresh || *top_index < qp_thresh)) {
1326
0
      q = qp_thresh;
1327
0
      *top_index = VPXMAX(*top_index, q);
1328
0
    }
1329
1330
48.6k
    if (q > *top_index) {
1331
      // Special case when we are targeting the max allowed rate
1332
3.47k
      if (rc->this_frame_target >= rc->max_frame_bandwidth)
1333
362
        *top_index = q;
1334
3.11k
      else
1335
3.11k
        q = *top_index;
1336
3.47k
    }
1337
48.6k
  }
1338
1339
54.1k
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1340
54.1k
  assert(*bottom_index <= rc->worst_quality &&
1341
54.1k
         *bottom_index >= rc->best_quality);
1342
54.1k
  assert(q <= rc->worst_quality && q >= rc->best_quality);
1343
54.1k
  return q;
1344
54.1k
}
1345
1346
0
int vp9_frame_type_qdelta(const VP9_COMP *cpi, int rf_level, int q) {
1347
0
  static const double rate_factor_deltas[RATE_FACTOR_LEVELS] = {
1348
0
    1.00,  // INTER_NORMAL
1349
0
    1.00,  // INTER_HIGH
1350
0
    1.50,  // GF_ARF_LOW
1351
0
    1.75,  // GF_ARF_STD
1352
0
    2.00,  // KF_STD
1353
0
  };
1354
0
  const VP9_COMMON *const cm = &cpi->common;
1355
1356
0
  int qdelta = vp9_compute_qdelta_by_rate(
1357
0
      &cpi->rc, cm->frame_type, q, rate_factor_deltas[rf_level], cm->bit_depth);
1358
0
  return qdelta;
1359
0
}
1360
1361
0
#define STATIC_MOTION_THRESH 95
1362
1363
static void pick_kf_q_bound_two_pass(const VP9_COMP *cpi, int *bottom_index,
1364
0
                                     int *top_index) {
1365
0
  const VP9_COMMON *const cm = &cpi->common;
1366
0
  const RATE_CONTROL *const rc = &cpi->rc;
1367
0
  int active_best_quality;
1368
0
  int active_worst_quality = cpi->twopass.active_worst_quality;
1369
1370
0
  if (rc->this_key_frame_forced) {
1371
    // Handle the special case for key frames forced when we have reached
1372
    // the maximum key frame interval. Here force the Q to a range
1373
    // based on the ambient Q to reduce the risk of popping.
1374
0
    double last_boosted_q;
1375
0
    int delta_qindex;
1376
0
    int qindex;
1377
1378
0
    if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1379
0
      qindex = VPXMIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1380
0
      active_best_quality = qindex;
1381
0
      last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1382
0
      delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
1383
0
                                        last_boosted_q * 1.25, cm->bit_depth);
1384
0
      active_worst_quality =
1385
0
          VPXMIN(qindex + delta_qindex, active_worst_quality);
1386
0
    } else {
1387
0
      qindex = rc->last_boosted_qindex;
1388
0
      last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1389
0
      delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
1390
0
                                        last_boosted_q * 0.75, cm->bit_depth);
1391
0
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1392
0
    }
1393
0
  } else {
1394
    // Not forced keyframe.
1395
0
    double q_adj_factor = 1.0;
1396
0
    double q_val;
1397
    // Baseline value derived from cpi->active_worst_quality and kf boost.
1398
0
    active_best_quality =
1399
0
        get_kf_active_quality(rc, active_worst_quality, cm->bit_depth);
1400
0
    if (cpi->twopass.kf_zeromotion_pct >= STATIC_KF_GROUP_THRESH) {
1401
0
      active_best_quality /= 4;
1402
0
    }
1403
1404
    // Don't allow the active min to be lossless (q0) unlesss the max q
1405
    // already indicates lossless.
1406
0
    active_best_quality =
1407
0
        VPXMIN(active_worst_quality, VPXMAX(1, active_best_quality));
1408
1409
    // Allow somewhat lower kf minq with small image formats.
1410
0
    if ((cm->width * cm->height) <= (352 * 288)) {
1411
0
      q_adj_factor -= 0.25;
1412
0
    }
1413
1414
    // Make a further adjustment based on the kf zero motion measure.
1415
0
    q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
1416
1417
    // Convert the adjustment factor to a qindex delta
1418
    // on active_best_quality.
1419
0
    q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1420
0
    active_best_quality +=
1421
0
        vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
1422
0
  }
1423
0
  *top_index = active_worst_quality;
1424
0
  *bottom_index = active_best_quality;
1425
0
}
1426
1427
static int rc_constant_q(const VP9_COMP *cpi, int *bottom_index, int *top_index,
1428
0
                         int gf_group_index) {
1429
0
  const VP9_COMMON *const cm = &cpi->common;
1430
0
  const RATE_CONTROL *const rc = &cpi->rc;
1431
0
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1432
0
  const GF_GROUP *gf_group = &cpi->twopass.gf_group;
1433
0
  const int is_intra_frame = frame_is_intra_only(cm);
1434
1435
0
  const int cq_level = get_active_cq_level_two_pass(&cpi->twopass, rc, oxcf);
1436
1437
0
  int q = cq_level;
1438
0
  int active_best_quality = cq_level;
1439
0
  int active_worst_quality = cq_level;
1440
1441
  // Key frame qp decision
1442
0
  if (is_intra_frame && rc->frames_to_key > 1)
1443
0
    pick_kf_q_bound_two_pass(cpi, &active_best_quality, &active_worst_quality);
1444
1445
  // ARF / GF qp decision
1446
0
  if (!is_intra_frame && !rc->is_src_frame_alt_ref &&
1447
0
      cpi->refresh_alt_ref_frame) {
1448
0
    active_best_quality = get_gf_active_quality(cpi, q, cm->bit_depth);
1449
1450
    // Modify best quality for second level arfs. For mode VPX_Q this
1451
    // becomes the baseline frame q.
1452
0
    if (gf_group->rf_level[gf_group_index] == GF_ARF_LOW) {
1453
0
      const int layer_depth = gf_group->layer_depth[gf_group_index];
1454
      // linearly fit the frame q depending on the layer depth index from
1455
      // the base layer ARF.
1456
0
      active_best_quality = ((layer_depth - 1) * cq_level +
1457
0
                             active_best_quality + layer_depth / 2) /
1458
0
                            layer_depth;
1459
0
    }
1460
0
  }
1461
1462
0
  q = active_best_quality;
1463
0
  *top_index = active_worst_quality;
1464
0
  *bottom_index = active_best_quality;
1465
0
  return q;
1466
0
}
1467
1468
int vp9_rc_pick_q_and_bounds_two_pass(const VP9_COMP *cpi, int *bottom_index,
1469
0
                                      int *top_index, int gf_group_index) {
1470
0
  const VP9_COMMON *const cm = &cpi->common;
1471
0
  const RATE_CONTROL *const rc = &cpi->rc;
1472
0
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1473
0
  const GF_GROUP *gf_group = &cpi->twopass.gf_group;
1474
0
  const int cq_level = get_active_cq_level_two_pass(&cpi->twopass, rc, oxcf);
1475
0
  int active_best_quality;
1476
0
  int active_worst_quality = cpi->twopass.active_worst_quality;
1477
0
  int q;
1478
0
  int *inter_minq;
1479
0
  int arf_active_best_quality_hl;
1480
0
  int *arfgf_high_motion_minq, *arfgf_low_motion_minq;
1481
0
  const int boost_frame =
1482
0
      !rc->is_src_frame_alt_ref &&
1483
0
      (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame);
1484
1485
0
  ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
1486
1487
0
  if (oxcf->rc_mode == VPX_Q)
1488
0
    return rc_constant_q(cpi, bottom_index, top_index, gf_group_index);
1489
1490
0
  if (frame_is_intra_only(cm)) {
1491
0
    pick_kf_q_bound_two_pass(cpi, &active_best_quality, &active_worst_quality);
1492
0
  } else if (boost_frame) {
1493
    // Use the lower of active_worst_quality and recent
1494
    // average Q as basis for GF/ARF best Q limit unless last frame was
1495
    // a key frame.
1496
0
    if (rc->frames_since_key > 1 &&
1497
0
        rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1498
0
      q = rc->avg_frame_qindex[INTER_FRAME];
1499
0
    } else {
1500
0
      q = active_worst_quality;
1501
0
    }
1502
    // For constrained quality don't allow Q less than the cq level
1503
0
    if (oxcf->rc_mode == VPX_CQ) {
1504
0
      if (q < cq_level) q = cq_level;
1505
0
    }
1506
0
    active_best_quality = get_gf_active_quality(cpi, q, cm->bit_depth);
1507
0
    arf_active_best_quality_hl = active_best_quality;
1508
1509
0
    if (rc->arf_increase_active_best_quality == 1) {
1510
0
      ASSIGN_MINQ_TABLE(cm->bit_depth, arfgf_high_motion_minq);
1511
0
      arf_active_best_quality_hl = arfgf_high_motion_minq[q];
1512
0
    } else if (rc->arf_increase_active_best_quality == -1) {
1513
0
      ASSIGN_MINQ_TABLE(cm->bit_depth, arfgf_low_motion_minq);
1514
0
      arf_active_best_quality_hl = arfgf_low_motion_minq[q];
1515
0
    }
1516
0
    active_best_quality =
1517
0
        (int)((double)active_best_quality *
1518
0
                  rc->arf_active_best_quality_adjustment_factor +
1519
0
              (double)arf_active_best_quality_hl *
1520
0
                  (1.0 - rc->arf_active_best_quality_adjustment_factor));
1521
1522
    // Modify best quality for second level arfs. For mode VPX_Q this
1523
    // becomes the baseline frame q.
1524
0
    if (gf_group->rf_level[gf_group_index] == GF_ARF_LOW) {
1525
0
      const int layer_depth = gf_group->layer_depth[gf_group_index];
1526
      // linearly fit the frame q depending on the layer depth index from
1527
      // the base layer ARF.
1528
0
      active_best_quality =
1529
0
          ((layer_depth - 1) * q + active_best_quality + layer_depth / 2) /
1530
0
          layer_depth;
1531
0
    }
1532
0
  } else {
1533
0
    active_best_quality = inter_minq[active_worst_quality];
1534
1535
    // For the constrained quality mode we don't want
1536
    // q to fall below the cq level.
1537
0
    if ((oxcf->rc_mode == VPX_CQ) && (active_best_quality < cq_level)) {
1538
0
      active_best_quality = cq_level;
1539
0
    }
1540
0
  }
1541
1542
  // Extension to max or min Q if undershoot or overshoot is outside
1543
  // the permitted range.
1544
0
  if (frame_is_intra_only(cm) || boost_frame) {
1545
0
    const int layer_depth = gf_group->layer_depth[gf_group_index];
1546
0
    active_best_quality -=
1547
0
        (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast);
1548
0
    active_worst_quality += (cpi->twopass.extend_maxq / 2);
1549
1550
0
    if (gf_group->rf_level[gf_group_index] == GF_ARF_LOW) {
1551
0
      assert(layer_depth > 1);
1552
0
      active_best_quality =
1553
0
          VPXMAX(active_best_quality,
1554
0
                 cpi->twopass.last_qindex_of_arf_layer[layer_depth - 1]);
1555
0
    }
1556
0
  } else {
1557
0
    const int max_layer_depth = gf_group->max_layer_depth;
1558
0
    assert(max_layer_depth > 0);
1559
1560
0
    active_best_quality -=
1561
0
        (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast) / 2;
1562
0
    active_worst_quality += cpi->twopass.extend_maxq;
1563
1564
    // For normal frames do not allow an active minq lower than the q used for
1565
    // the last boosted frame.
1566
0
    active_best_quality =
1567
0
        VPXMAX(active_best_quality,
1568
0
               cpi->twopass.last_qindex_of_arf_layer[max_layer_depth - 1]);
1569
0
  }
1570
1571
0
#if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
1572
0
  vpx_clear_system_state();
1573
  // Static forced key frames Q restrictions dealt with elsewhere.
1574
0
  if (!frame_is_intra_only(cm) || !rc->this_key_frame_forced ||
1575
0
      cpi->twopass.last_kfgroup_zeromotion_pct < STATIC_MOTION_THRESH) {
1576
0
    int qdelta = vp9_frame_type_qdelta(cpi, gf_group->rf_level[gf_group_index],
1577
0
                                       active_worst_quality);
1578
0
    active_worst_quality =
1579
0
        VPXMAX(active_worst_quality + qdelta, active_best_quality);
1580
0
  }
1581
0
#endif
1582
1583
  // Modify active_best_quality for downscaled normal frames.
1584
0
  if (rc->frame_size_selector != UNSCALED && !frame_is_kf_gf_arf(cpi)) {
1585
0
    int qdelta = vp9_compute_qdelta_by_rate(
1586
0
        rc, cm->frame_type, active_best_quality, 2.0, cm->bit_depth);
1587
0
    active_best_quality =
1588
0
        VPXMAX(active_best_quality + qdelta, rc->best_quality);
1589
0
  }
1590
1591
0
  active_best_quality =
1592
0
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1593
0
  active_worst_quality =
1594
0
      clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1595
1596
0
  if (frame_is_intra_only(cm) && rc->this_key_frame_forced) {
1597
    // If static since last kf use better of last boosted and last kf q.
1598
0
    if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1599
0
      q = VPXMIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1600
0
    } else {
1601
0
      q = rc->last_boosted_qindex;
1602
0
    }
1603
0
  } else if (frame_is_intra_only(cm) && !rc->this_key_frame_forced) {
1604
0
    q = active_best_quality;
1605
0
  } else {
1606
0
    q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1607
0
                          active_worst_quality);
1608
0
    if (q > active_worst_quality) {
1609
      // Special case when we are targeting the max allowed rate.
1610
0
      if (rc->this_frame_target >= rc->max_frame_bandwidth)
1611
0
        active_worst_quality = q;
1612
0
      else
1613
0
        q = active_worst_quality;
1614
0
    }
1615
0
  }
1616
1617
0
  *top_index = active_worst_quality;
1618
0
  *bottom_index = active_best_quality;
1619
1620
0
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1621
0
  assert(*bottom_index <= rc->worst_quality &&
1622
0
         *bottom_index >= rc->best_quality);
1623
0
  assert(q <= rc->worst_quality && q >= rc->best_quality);
1624
0
  return q;
1625
0
}
1626
1627
int vp9_rc_pick_q_and_bounds(const VP9_COMP *cpi, int *bottom_index,
1628
54.1k
                             int *top_index) {
1629
54.1k
  int q;
1630
54.1k
  const int gf_group_index = cpi->twopass.gf_group.index;
1631
54.1k
  if (cpi->oxcf.pass == 0) {
1632
54.1k
    if (cpi->oxcf.rc_mode == VPX_CBR)
1633
0
      q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
1634
54.1k
    else
1635
54.1k
      q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
1636
54.1k
  } else {
1637
0
    q = vp9_rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index,
1638
0
                                          gf_group_index);
1639
0
  }
1640
54.1k
  if (cpi->sf.use_nonrd_pick_mode) {
1641
0
    if (cpi->sf.force_frame_boost == 1) q -= cpi->sf.max_delta_qindex;
1642
1643
0
    if (q < *bottom_index)
1644
0
      *bottom_index = q;
1645
0
    else if (q > *top_index)
1646
0
      *top_index = q;
1647
0
  }
1648
54.1k
  return q;
1649
54.1k
}
1650
1651
0
void vp9_configure_buffer_updates(VP9_COMP *cpi, int gf_group_index) {
1652
0
  VP9_COMMON *cm = &cpi->common;
1653
0
  TWO_PASS *const twopass = &cpi->twopass;
1654
1655
0
  cpi->rc.is_src_frame_alt_ref = 0;
1656
0
  cm->show_existing_frame = 0;
1657
0
  cpi->rc.show_arf_as_gld = 0;
1658
0
  switch (twopass->gf_group.update_type[gf_group_index]) {
1659
0
    case KF_UPDATE:
1660
0
      cpi->refresh_last_frame = 1;
1661
0
      cpi->refresh_golden_frame = 1;
1662
0
      cpi->refresh_alt_ref_frame = 1;
1663
0
      break;
1664
0
    case LF_UPDATE:
1665
0
      cpi->refresh_last_frame = 1;
1666
0
      cpi->refresh_golden_frame = 0;
1667
0
      cpi->refresh_alt_ref_frame = 0;
1668
0
      break;
1669
0
    case GF_UPDATE:
1670
0
      cpi->refresh_last_frame = 1;
1671
0
      cpi->refresh_golden_frame = 1;
1672
0
      cpi->refresh_alt_ref_frame = 0;
1673
0
      break;
1674
0
    case OVERLAY_UPDATE:
1675
0
      cpi->refresh_last_frame = 0;
1676
0
      cpi->refresh_golden_frame = 1;
1677
0
      cpi->refresh_alt_ref_frame = 0;
1678
0
      cpi->rc.is_src_frame_alt_ref = 1;
1679
0
      if (cpi->rc.preserve_arf_as_gld) {
1680
0
        cpi->rc.show_arf_as_gld = 1;
1681
0
        cpi->refresh_golden_frame = 0;
1682
0
        cm->show_existing_frame = 1;
1683
0
        cm->refresh_frame_context = 0;
1684
0
      }
1685
0
      break;
1686
0
    case MID_OVERLAY_UPDATE:
1687
0
      cpi->refresh_last_frame = 1;
1688
0
      cpi->refresh_golden_frame = 0;
1689
0
      cpi->refresh_alt_ref_frame = 0;
1690
0
      cpi->rc.is_src_frame_alt_ref = 1;
1691
0
      break;
1692
0
    case USE_BUF_FRAME:
1693
0
      cpi->refresh_last_frame = 0;
1694
0
      cpi->refresh_golden_frame = 0;
1695
0
      cpi->refresh_alt_ref_frame = 0;
1696
0
      cpi->rc.is_src_frame_alt_ref = 1;
1697
0
      cm->show_existing_frame = 1;
1698
0
      cm->refresh_frame_context = 0;
1699
0
      break;
1700
0
    default:
1701
0
      assert(twopass->gf_group.update_type[gf_group_index] == ARF_UPDATE);
1702
0
      cpi->refresh_last_frame = 0;
1703
0
      cpi->refresh_golden_frame = 0;
1704
0
      cpi->refresh_alt_ref_frame = 1;
1705
0
      break;
1706
0
  }
1707
0
}
1708
1709
void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi, int frame_target,
1710
                                      int *frame_under_shoot_limit,
1711
0
                                      int *frame_over_shoot_limit) {
1712
0
  if (cpi->oxcf.rc_mode == VPX_Q) {
1713
0
    *frame_under_shoot_limit = 0;
1714
0
    *frame_over_shoot_limit = INT_MAX;
1715
0
  } else {
1716
    // For very small rate targets where the fractional adjustment
1717
    // may be tiny make sure there is at least a minimum range.
1718
0
    const int tol_low =
1719
0
        (int)(((int64_t)cpi->sf.recode_tolerance_low * frame_target) / 100);
1720
0
    const int tol_high =
1721
0
        (int)(((int64_t)cpi->sf.recode_tolerance_high * frame_target) / 100);
1722
0
    *frame_under_shoot_limit = VPXMAX(frame_target - tol_low - 100, 0);
1723
0
    *frame_over_shoot_limit =
1724
0
        VPXMIN(frame_target + tol_high + 100, cpi->rc.max_frame_bandwidth);
1725
0
  }
1726
0
}
1727
1728
57.3k
void vp9_rc_set_frame_target(VP9_COMP *cpi, int target) {
1729
57.3k
  const VP9_COMMON *const cm = &cpi->common;
1730
57.3k
  RATE_CONTROL *const rc = &cpi->rc;
1731
1732
57.3k
  rc->this_frame_target = target;
1733
1734
  // Modify frame size target when down-scaling.
1735
57.3k
  if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC &&
1736
0
      rc->frame_size_selector != UNSCALED) {
1737
0
    rc->this_frame_target = (int)(rc->this_frame_target *
1738
0
                                  rate_thresh_mult[rc->frame_size_selector]);
1739
0
  }
1740
1741
  // Target rate per SB64 (including partial SB64s.
1742
57.3k
  const int64_t sb64_target_rate =
1743
57.3k
      ((int64_t)rc->this_frame_target * 64 * 64) / (cm->width * cm->height);
1744
57.3k
  rc->sb64_target_rate = (int)VPXMIN(sb64_target_rate, INT_MAX);
1745
57.3k
}
1746
1747
0
static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
1748
  // this frame refreshes means next frames don't unless specified by user
1749
0
  RATE_CONTROL *const rc = &cpi->rc;
1750
0
  rc->frames_since_golden = 0;
1751
1752
  // Mark the alt ref as done (setting to 0 means no further alt refs pending).
1753
0
  rc->source_alt_ref_pending = 0;
1754
1755
  // Set the alternate reference frame active flag
1756
0
  rc->source_alt_ref_active = 1;
1757
0
}
1758
1759
54.0k
static void update_golden_frame_stats(VP9_COMP *cpi) {
1760
54.0k
  RATE_CONTROL *const rc = &cpi->rc;
1761
1762
  // Update the Golden frame usage counts.
1763
54.0k
  if (cpi->refresh_golden_frame) {
1764
    // this frame refreshes means next frames don't unless specified by user
1765
15.5k
    rc->frames_since_golden = 0;
1766
1767
    // If we are not using alt ref in the up and coming group clear the arf
1768
    // active flag. In multi arf group case, if the index is not 0 then
1769
    // we are overlaying a mid group arf so should not reset the flag.
1770
15.5k
    if (cpi->oxcf.pass == 2) {
1771
0
      if (!rc->source_alt_ref_pending && (cpi->twopass.gf_group.index == 0))
1772
0
        rc->source_alt_ref_active = 0;
1773
15.5k
    } else if (!rc->source_alt_ref_pending) {
1774
15.5k
      rc->source_alt_ref_active = 0;
1775
15.5k
    }
1776
1777
    // Decrement count down till next gf
1778
15.5k
    if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1779
1780
38.5k
  } else if (!cpi->refresh_alt_ref_frame) {
1781
    // Decrement count down till next gf
1782
38.5k
    if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1783
1784
38.5k
    rc->frames_since_golden++;
1785
1786
38.5k
    if (rc->show_arf_as_gld) {
1787
0
      rc->frames_since_golden = 0;
1788
      // If we are not using alt ref in the up and coming group clear the arf
1789
      // active flag. In multi arf group case, if the index is not 0 then
1790
      // we are overlaying a mid group arf so should not reset the flag.
1791
0
      if (!rc->source_alt_ref_pending && (cpi->twopass.gf_group.index == 0))
1792
0
        rc->source_alt_ref_active = 0;
1793
0
    }
1794
38.5k
  }
1795
54.0k
}
1796
1797
0
static void update_altref_usage(VP9_COMP *const cpi) {
1798
0
  VP9_COMMON *const cm = &cpi->common;
1799
0
  int sum_ref_frame_usage = 0;
1800
0
  int arf_frame_usage = 0;
1801
0
  int mi_row, mi_col;
1802
0
  if (cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
1803
0
      !cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame)
1804
0
    for (mi_row = 0; mi_row < cm->mi_rows; mi_row += 8) {
1805
0
      for (mi_col = 0; mi_col < cm->mi_cols; mi_col += 8) {
1806
0
        int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1807
0
        sum_ref_frame_usage += cpi->count_arf_frame_usage[sboffset] +
1808
0
                               cpi->count_lastgolden_frame_usage[sboffset];
1809
0
        arf_frame_usage += cpi->count_arf_frame_usage[sboffset];
1810
0
      }
1811
0
    }
1812
0
  if (sum_ref_frame_usage > 0) {
1813
0
    double altref_count = 100.0 * arf_frame_usage / sum_ref_frame_usage;
1814
0
    cpi->rc.perc_arf_usage =
1815
0
        0.75 * cpi->rc.perc_arf_usage + 0.25 * altref_count;
1816
0
  }
1817
0
}
1818
1819
41.3k
void vp9_compute_frame_low_motion(VP9_COMP *const cpi) {
1820
41.3k
  VP9_COMMON *const cm = &cpi->common;
1821
41.3k
  SVC *const svc = &cpi->svc;
1822
41.3k
  int mi_row, mi_col;
1823
41.3k
  MODE_INFO **mi = cm->mi_grid_visible;
1824
41.3k
  RATE_CONTROL *const rc = &cpi->rc;
1825
41.3k
  const int rows = cm->mi_rows, cols = cm->mi_cols;
1826
41.3k
  int cnt_zeromv = 0;
1827
295k
  for (mi_row = 0; mi_row < rows; mi_row++) {
1828
2.46M
    for (mi_col = 0; mi_col < cols; mi_col++) {
1829
2.20M
      if (mi[0]->ref_frame[0] == LAST_FRAME &&
1830
667k
          abs(mi[0]->mv[0].as_mv.row) < 16 && abs(mi[0]->mv[0].as_mv.col) < 16)
1831
176k
        cnt_zeromv++;
1832
2.20M
      mi++;
1833
2.20M
    }
1834
253k
    mi += 8;
1835
253k
  }
1836
41.3k
  cnt_zeromv = 100 * cnt_zeromv / (rows * cols);
1837
41.3k
  rc->avg_frame_low_motion = (3 * rc->avg_frame_low_motion + cnt_zeromv) >> 2;
1838
1839
  // For SVC: set avg_frame_low_motion (only computed on top spatial layer)
1840
  // to all lower spatial layers.
1841
41.3k
  if (cpi->use_svc && svc->spatial_layer_id == svc->number_spatial_layers - 1) {
1842
0
    int i;
1843
0
    for (i = 0; i < svc->number_spatial_layers - 1; ++i) {
1844
0
      const int layer = LAYER_IDS_TO_IDX(i, svc->temporal_layer_id,
1845
0
                                         svc->number_temporal_layers);
1846
0
      LAYER_CONTEXT *const lc = &svc->layer_context[layer];
1847
0
      RATE_CONTROL *const lrc = &lc->rc;
1848
0
      lrc->avg_frame_low_motion = rc->avg_frame_low_motion;
1849
0
    }
1850
0
  }
1851
41.3k
}
1852
1853
54.0k
void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
1854
54.0k
  const VP9_COMMON *const cm = &cpi->common;
1855
54.0k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1856
54.0k
  RATE_CONTROL *const rc = &cpi->rc;
1857
54.0k
  SVC *const svc = &cpi->svc;
1858
54.0k
  const int qindex = cm->base_qindex;
1859
54.0k
  const GF_GROUP *gf_group = &cpi->twopass.gf_group;
1860
54.0k
  const int gf_group_index = cpi->twopass.gf_group.index;
1861
54.0k
  const int layer_depth = gf_group->layer_depth[gf_group_index];
1862
1863
  // Update rate control heuristics
1864
54.0k
  rc->projected_frame_size = (int)(bytes_used << 3);
1865
1866
  // Post encode loop adjustment of Q prediction.
1867
54.0k
  vp9_rc_update_rate_correction_factors(cpi);
1868
1869
  // Keep a record of last Q and ambient average Q.
1870
54.0k
  if (frame_is_intra_only(cm)) {
1871
12.7k
    rc->last_q[KEY_FRAME] = qindex;
1872
12.7k
    rc->avg_frame_qindex[KEY_FRAME] =
1873
12.7k
        ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1874
12.7k
    if (cpi->use_svc) {
1875
0
      int i;
1876
0
      for (i = 0; i < svc->number_temporal_layers; ++i) {
1877
0
        const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
1878
0
                                           svc->number_temporal_layers);
1879
0
        LAYER_CONTEXT *lc = &svc->layer_context[layer];
1880
0
        RATE_CONTROL *lrc = &lc->rc;
1881
0
        lrc->last_q[KEY_FRAME] = rc->last_q[KEY_FRAME];
1882
0
        lrc->avg_frame_qindex[KEY_FRAME] = rc->avg_frame_qindex[KEY_FRAME];
1883
0
      }
1884
0
    }
1885
41.3k
  } else {
1886
41.3k
    if ((cpi->use_svc) ||
1887
41.3k
        (!rc->is_src_frame_alt_ref &&
1888
41.3k
         !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1889
38.5k
      rc->last_q[INTER_FRAME] = qindex;
1890
38.5k
      rc->avg_frame_qindex[INTER_FRAME] =
1891
38.5k
          ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1892
38.5k
      rc->ni_frames++;
1893
38.5k
      rc->tot_q += vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1894
38.5k
      rc->avg_q = rc->tot_q / rc->ni_frames;
1895
      // Calculate the average Q for normal inter frames (not key or GFU
1896
      // frames).
1897
38.5k
      rc->ni_tot_qi += qindex;
1898
38.5k
      rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1899
38.5k
    }
1900
41.3k
  }
1901
1902
54.0k
  if (cpi->use_svc) vp9_svc_adjust_avg_frame_qindex(cpi);
1903
1904
  // Keep record of last boosted (KF/KF/ARF) Q value.
1905
  // If the current frame is coded at a lower Q then we also update it.
1906
  // If all mbs in this group are skipped only update if the Q value is
1907
  // better than that already stored.
1908
  // This is used to help set quality in forced key frames to reduce popping
1909
54.0k
  if ((qindex < rc->last_boosted_qindex) || (cm->frame_type == KEY_FRAME) ||
1910
39.4k
      (!rc->constrained_gf_group &&
1911
35.1k
       (cpi->refresh_alt_ref_frame ||
1912
35.1k
        (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1913
16.3k
    rc->last_boosted_qindex = qindex;
1914
16.3k
  }
1915
1916
54.0k
  if ((qindex < cpi->twopass.last_qindex_of_arf_layer[layer_depth]) ||
1917
51.2k
      (cm->frame_type == KEY_FRAME) ||
1918
39.4k
      (!rc->constrained_gf_group &&
1919
35.1k
       (cpi->refresh_alt_ref_frame ||
1920
35.1k
        (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1921
16.3k
    cpi->twopass.last_qindex_of_arf_layer[layer_depth] = qindex;
1922
16.3k
  }
1923
1924
54.0k
  if (frame_is_intra_only(cm)) rc->last_kf_qindex = qindex;
1925
1926
54.0k
  update_buffer_level_postencode(cpi, rc->projected_frame_size);
1927
1928
  // Rolling monitors of whether we are over or underspending used to help
1929
  // regulate min and Max Q in two pass.
1930
54.0k
  if (!frame_is_intra_only(cm)) {
1931
41.3k
    rc->rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
1932
41.3k
        (int64_t)rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1933
41.3k
    rc->rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
1934
41.3k
        (int64_t)rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1935
41.3k
    rc->long_rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
1936
41.3k
        (int64_t)rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1937
41.3k
    rc->long_rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
1938
41.3k
        (int64_t)rc->long_rolling_actual_bits * 31 + rc->projected_frame_size,
1939
41.3k
        5);
1940
41.3k
  }
1941
1942
  // Actual bits spent
1943
54.0k
  rc->total_actual_bits += rc->projected_frame_size;
1944
54.0k
  rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1945
1946
54.0k
  rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1947
1948
54.0k
  if (!cpi->use_svc) {
1949
54.0k
    if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
1950
12.7k
        (!frame_is_intra_only(cm)))
1951
      // Update the alternate reference frame stats as appropriate.
1952
0
      update_alt_ref_frame_stats(cpi);
1953
54.0k
    else
1954
      // Update the Golden frame stats as appropriate.
1955
54.0k
      update_golden_frame_stats(cpi);
1956
54.0k
  }
1957
1958
  // If second (long term) temporal reference is used for SVC,
1959
  // update the golden frame counter, only for base temporal layer.
1960
54.0k
  if (cpi->use_svc && svc->use_gf_temporal_ref_current_layer &&
1961
0
      svc->temporal_layer_id == 0) {
1962
0
    int i = 0;
1963
0
    if (cpi->refresh_golden_frame)
1964
0
      rc->frames_since_golden = 0;
1965
0
    else
1966
0
      rc->frames_since_golden++;
1967
    // Decrement count down till next gf
1968
0
    if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1969
    // Update the frames_since_golden for all upper temporal layers.
1970
0
    for (i = 1; i < svc->number_temporal_layers; ++i) {
1971
0
      const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
1972
0
                                         svc->number_temporal_layers);
1973
0
      LAYER_CONTEXT *const lc = &svc->layer_context[layer];
1974
0
      RATE_CONTROL *const lrc = &lc->rc;
1975
0
      lrc->frames_since_golden = rc->frames_since_golden;
1976
0
    }
1977
0
  }
1978
1979
54.0k
  if (frame_is_intra_only(cm)) rc->frames_since_key = 0;
1980
54.0k
  if (cm->show_frame) {
1981
54.0k
    rc->frames_since_key++;
1982
54.0k
    rc->frames_to_key--;
1983
54.0k
  }
1984
1985
  // Trigger the resizing of the next frame if it is scaled.
1986
54.0k
  if (oxcf->pass != 0) {
1987
0
    cpi->resize_pending =
1988
0
        rc->next_frame_size_selector != rc->frame_size_selector;
1989
0
    rc->frame_size_selector = rc->next_frame_size_selector;
1990
0
  }
1991
1992
54.0k
  if (oxcf->pass == 0) {
1993
54.0k
    if (!frame_is_intra_only(cm))
1994
41.3k
      if (cpi->sf.use_altref_onepass) update_altref_usage(cpi);
1995
54.0k
    cpi->rc.last_frame_is_src_altref = cpi->rc.is_src_frame_alt_ref;
1996
54.0k
  }
1997
1998
54.0k
  if (!frame_is_intra_only(cm)) rc->reset_high_source_sad = 0;
1999
2000
54.0k
  rc->last_avg_frame_bandwidth = rc->avg_frame_bandwidth;
2001
54.0k
  if (cpi->use_svc && svc->spatial_layer_id < svc->number_spatial_layers - 1)
2002
0
    svc->lower_layer_qindex = cm->base_qindex;
2003
54.0k
  cpi->deadline_mode_previous_frame = cpi->oxcf.mode;
2004
54.0k
}
2005
2006
0
void vp9_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
2007
0
  cpi->common.current_video_frame++;
2008
0
  cpi->rc.frames_since_key++;
2009
0
  cpi->rc.frames_to_key--;
2010
0
  cpi->rc.rc_2_frame = 0;
2011
0
  cpi->rc.rc_1_frame = 0;
2012
0
  cpi->rc.last_avg_frame_bandwidth = cpi->rc.avg_frame_bandwidth;
2013
0
  cpi->rc.last_q[INTER_FRAME] = cpi->common.base_qindex;
2014
  // For SVC on dropped frame when framedrop_mode != LAYER_DROP:
2015
  // in this mode the whole superframe may be dropped if only a single layer
2016
  // has buffer underflow (below threshold). Since this can then lead to
2017
  // increasing buffer levels/overflow for certain layers even though whole
2018
  // superframe is dropped, we cap buffer level if its already stable.
2019
0
  if (cpi->use_svc && cpi->svc.framedrop_mode != LAYER_DROP &&
2020
0
      cpi->rc.buffer_level > cpi->rc.optimal_buffer_level) {
2021
0
    cpi->rc.buffer_level = cpi->rc.optimal_buffer_level;
2022
0
    cpi->rc.bits_off_target = cpi->rc.optimal_buffer_level;
2023
0
  }
2024
0
  cpi->deadline_mode_previous_frame = cpi->oxcf.mode;
2025
0
}
2026
2027
44.4k
int vp9_calc_pframe_target_size_one_pass_vbr(const VP9_COMP *cpi) {
2028
44.4k
  const RATE_CONTROL *const rc = &cpi->rc;
2029
44.4k
  const int af_ratio = rc->af_ratio_onepass_vbr;
2030
44.4k
  int64_t target =
2031
44.4k
      (!rc->is_src_frame_alt_ref &&
2032
44.4k
       (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))
2033
44.4k
          ? ((int64_t)rc->avg_frame_bandwidth * rc->baseline_gf_interval *
2034
5.96k
             af_ratio) /
2035
5.96k
                (rc->baseline_gf_interval + af_ratio - 1)
2036
44.4k
          : ((int64_t)rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
2037
38.5k
                (rc->baseline_gf_interval + af_ratio - 1);
2038
  // For SVC: refresh flags are used to define the pattern, so we can't
2039
  // use that for boosting the target size here.
2040
  // TODO(marpan): Consider adding internal boost on TL0 for VBR-SVC.
2041
  // For now just use the CBR logic for setting target size.
2042
44.4k
  if (cpi->use_svc) target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2043
44.4k
  if (target > INT_MAX) target = INT_MAX;
2044
44.4k
  return vp9_rc_clamp_pframe_target_size(cpi, (int)target);
2045
44.4k
}
2046
2047
12.8k
int vp9_calc_iframe_target_size_one_pass_vbr(const VP9_COMP *cpi) {
2048
12.8k
  static const int kf_ratio = 25;
2049
12.8k
  const RATE_CONTROL *rc = &cpi->rc;
2050
12.8k
  int target = rc->avg_frame_bandwidth;
2051
12.8k
  if (target > INT_MAX / kf_ratio)
2052
50
    target = INT_MAX;
2053
12.7k
  else
2054
12.7k
    target = rc->avg_frame_bandwidth * kf_ratio;
2055
12.8k
  return vp9_rc_clamp_iframe_target_size(cpi, target);
2056
12.8k
}
2057
2058
18.7k
static void adjust_gfint_frame_constraint(VP9_COMP *cpi, int frame_constraint) {
2059
18.7k
  RATE_CONTROL *const rc = &cpi->rc;
2060
18.7k
  rc->constrained_gf_group = 0;
2061
  // Reset gf interval to make more equal spacing for frame_constraint.
2062
18.7k
  if ((frame_constraint <= 7 * rc->baseline_gf_interval >> 2) &&
2063
12.4k
      (frame_constraint > rc->baseline_gf_interval)) {
2064
201
    rc->baseline_gf_interval = frame_constraint >> 1;
2065
201
    if (rc->baseline_gf_interval < 5)
2066
51
      rc->baseline_gf_interval = frame_constraint;
2067
201
    rc->constrained_gf_group = 1;
2068
18.5k
  } else {
2069
    // Reset to keep gf_interval <= frame_constraint.
2070
18.5k
    if (rc->baseline_gf_interval > frame_constraint) {
2071
10.3k
      rc->baseline_gf_interval = frame_constraint;
2072
10.3k
      rc->constrained_gf_group = 1;
2073
10.3k
    }
2074
18.5k
  }
2075
18.7k
}
2076
2077
54.1k
void vp9_set_gf_update_one_pass_vbr(VP9_COMP *const cpi) {
2078
54.1k
  RATE_CONTROL *const rc = &cpi->rc;
2079
54.1k
  VP9_COMMON *const cm = &cpi->common;
2080
54.1k
  if (rc->frames_till_gf_update_due == 0) {
2081
15.6k
    double rate_err = 1.0;
2082
15.6k
    rc->gfu_boost = DEFAULT_GF_BOOST;
2083
15.6k
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0) {
2084
0
      vp9_cyclic_refresh_set_golden_update(cpi);
2085
15.6k
    } else {
2086
15.6k
      rc->baseline_gf_interval = VPXMIN(
2087
15.6k
          20, VPXMAX(10, (rc->min_gf_interval + rc->max_gf_interval) / 2));
2088
15.6k
    }
2089
15.6k
    rc->af_ratio_onepass_vbr = 10;
2090
15.6k
    if (rc->rolling_target_bits > 0)
2091
11.9k
      rate_err =
2092
11.9k
          (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
2093
15.6k
    if (cm->current_video_frame > 30) {
2094
5.79k
      if (rc->avg_frame_qindex[INTER_FRAME] > (7 * rc->worst_quality) >> 3 &&
2095
320
          rate_err > 3.5) {
2096
120
        rc->baseline_gf_interval =
2097
120
            VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
2098
5.67k
      } else if (rc->avg_frame_low_motion > 0 &&
2099
1.33k
                 rc->avg_frame_low_motion < 20) {
2100
        // Decrease gf interval for high motion case.
2101
824
        rc->baseline_gf_interval = VPXMAX(6, rc->baseline_gf_interval >> 1);
2102
824
      }
2103
      // Adjust boost and af_ratio based on avg_frame_low_motion, which
2104
      // varies between 0 and 100 (stationary, 100% zero/small motion).
2105
5.79k
      if (rc->avg_frame_low_motion > 0)
2106
1.38k
        rc->gfu_boost =
2107
1.38k
            VPXMAX(500, DEFAULT_GF_BOOST * (rc->avg_frame_low_motion << 1) /
2108
5.79k
                            (rc->avg_frame_low_motion + 100));
2109
4.41k
      else if (rc->avg_frame_low_motion == 0 && rate_err > 1.0)
2110
377
        rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
2111
5.79k
      rc->af_ratio_onepass_vbr = VPXMIN(15, VPXMAX(5, 3 * rc->gfu_boost / 400));
2112
5.79k
    }
2113
15.6k
    if (rc->constrain_gf_key_freq_onepass_vbr)
2114
15.6k
      adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
2115
15.6k
    rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2116
15.6k
    cpi->refresh_golden_frame = 1;
2117
15.6k
    rc->source_alt_ref_pending = 0;
2118
15.6k
    rc->alt_ref_gf_group = 0;
2119
15.6k
    if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf) {
2120
0
      rc->source_alt_ref_pending = 1;
2121
0
      rc->alt_ref_gf_group = 1;
2122
0
    }
2123
15.6k
  }
2124
54.1k
}
2125
2126
54.1k
void vp9_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
2127
54.1k
  VP9_COMMON *const cm = &cpi->common;
2128
54.1k
  RATE_CONTROL *const rc = &cpi->rc;
2129
54.1k
  int target;
2130
54.1k
  if (!cpi->refresh_alt_ref_frame &&
2131
54.1k
      (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
2132
43.9k
       rc->frames_to_key == 0 ||
2133
41.3k
       (cpi->oxcf.mode != cpi->deadline_mode_previous_frame))) {
2134
12.8k
    cm->frame_type = KEY_FRAME;
2135
12.8k
    rc->this_key_frame_forced =
2136
12.8k
        cm->current_video_frame != 0 && rc->frames_to_key == 0;
2137
12.8k
    rc->frames_to_key = cpi->oxcf.key_freq;
2138
12.8k
    rc->kf_boost = DEFAULT_KF_BOOST;
2139
12.8k
    rc->source_alt_ref_active = 0;
2140
41.3k
  } else {
2141
41.3k
    cm->frame_type = INTER_FRAME;
2142
41.3k
  }
2143
54.1k
  vp9_set_gf_update_one_pass_vbr(cpi);
2144
54.1k
  if (cm->frame_type == KEY_FRAME)
2145
12.8k
    target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2146
41.3k
  else
2147
41.3k
    target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
2148
54.1k
  vp9_rc_set_frame_target(cpi, target);
2149
54.1k
  if (cm->show_frame) vp9_update_buffer_level_preencode(cpi);
2150
54.1k
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0)
2151
0
    vp9_cyclic_refresh_update_parameters(cpi);
2152
54.1k
}
2153
2154
0
int vp9_calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
2155
0
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
2156
0
  const RATE_CONTROL *rc = &cpi->rc;
2157
0
  const SVC *const svc = &cpi->svc;
2158
0
  const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
2159
0
  const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
2160
0
  int min_frame_target =
2161
0
      VPXMAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
2162
0
  int64_t target;
2163
2164
0
  if (oxcf->gf_cbr_boost_pct) {
2165
0
    const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
2166
0
    target = cpi->refresh_golden_frame
2167
0
                 ? ((int64_t)rc->avg_frame_bandwidth *
2168
0
                    rc->baseline_gf_interval * af_ratio_pct) /
2169
0
                       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100)
2170
0
                 : ((int64_t)rc->avg_frame_bandwidth *
2171
0
                    rc->baseline_gf_interval * 100) /
2172
0
                       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
2173
0
  } else {
2174
0
    target = rc->avg_frame_bandwidth;
2175
0
  }
2176
0
  if (is_one_pass_svc(cpi)) {
2177
    // Note that for layers, avg_frame_bandwidth is the cumulative
2178
    // per-frame-bandwidth. For the target size of this frame, use the
2179
    // layer average frame size (i.e., non-cumulative per-frame-bw).
2180
0
    int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2181
0
                                 svc->number_temporal_layers);
2182
0
    const LAYER_CONTEXT *lc = &svc->layer_context[layer];
2183
0
    target = lc->avg_frame_size;
2184
0
    min_frame_target = VPXMAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
2185
0
  }
2186
0
  if (diff > 0) {
2187
    // Lower the target bandwidth for this frame.
2188
0
    const int pct_low = (int)VPXMIN(diff / one_pct_bits, oxcf->under_shoot_pct);
2189
0
    target -= (target * pct_low) / 200;
2190
0
  } else if (diff < 0) {
2191
    // Increase the target bandwidth for this frame.
2192
0
    const int pct_high =
2193
0
        (int)VPXMIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
2194
0
    target += (target * pct_high) / 200;
2195
0
  }
2196
0
  if (oxcf->rc_max_inter_bitrate_pct) {
2197
0
    const int64_t max_rate =
2198
0
        (int64_t)rc->avg_frame_bandwidth * oxcf->rc_max_inter_bitrate_pct / 100;
2199
0
    target = VPXMIN(target, max_rate);
2200
0
  }
2201
0
  if (target > INT_MAX) target = INT_MAX;
2202
0
  return VPXMAX(min_frame_target, (int)target);
2203
0
}
2204
2205
0
int vp9_calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
2206
0
  const RATE_CONTROL *rc = &cpi->rc;
2207
0
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
2208
0
  const SVC *const svc = &cpi->svc;
2209
0
  int64_t target;
2210
0
  if (cpi->common.current_video_frame == 0) {
2211
0
    target = rc->starting_buffer_level / 2;
2212
0
  } else {
2213
0
    int kf_boost = 32;
2214
0
    double framerate = cpi->framerate;
2215
0
    if (svc->number_temporal_layers > 1 && oxcf->rc_mode == VPX_CBR) {
2216
      // Use the layer framerate for temporal layers CBR mode.
2217
0
      const int layer =
2218
0
          LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2219
0
                           svc->number_temporal_layers);
2220
0
      const LAYER_CONTEXT *lc = &svc->layer_context[layer];
2221
0
      framerate = lc->framerate;
2222
0
    }
2223
0
    kf_boost = VPXMAX(kf_boost, (int)round(2 * framerate - 16));
2224
0
    if (rc->frames_since_key < framerate / 2) {
2225
0
      kf_boost = (int)round(kf_boost * rc->frames_since_key / (framerate / 2));
2226
0
    }
2227
2228
0
    target = ((int64_t)(16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
2229
0
  }
2230
0
  target = VPXMIN(INT_MAX, target);
2231
0
  return vp9_rc_clamp_iframe_target_size(cpi, (int)target);
2232
0
}
2233
2234
0
static void set_intra_only_frame(VP9_COMP *cpi) {
2235
0
  VP9_COMMON *const cm = &cpi->common;
2236
0
  SVC *const svc = &cpi->svc;
2237
  // Don't allow intra_only frame for bypass/flexible SVC mode, or if number
2238
  // of spatial layers is 1 or if number of spatial or temporal layers > 3.
2239
  // Also if intra-only is inserted on very first frame, don't allow if
2240
  // if number of temporal layers > 1. This is because on intra-only frame
2241
  // only 3 reference buffers can be updated, but for temporal layers > 1
2242
  // we generally need to use buffer slots 4 and 5.
2243
0
  if ((cm->current_video_frame == 0 && svc->number_temporal_layers > 1) ||
2244
0
      svc->number_spatial_layers > 3 || svc->number_temporal_layers > 3 ||
2245
0
      svc->number_spatial_layers == 1)
2246
0
    return;
2247
0
  cm->show_frame = 0;
2248
0
  cm->intra_only = 1;
2249
0
  cm->frame_type = INTER_FRAME;
2250
0
  cpi->ext_refresh_frame_flags_pending = 1;
2251
0
  cpi->ext_refresh_last_frame = 1;
2252
0
  cpi->ext_refresh_golden_frame = 1;
2253
0
  cpi->ext_refresh_alt_ref_frame = 1;
2254
0
  if (cm->current_video_frame == 0) {
2255
0
    cpi->lst_fb_idx = 0;
2256
0
    cpi->gld_fb_idx = 1;
2257
0
    cpi->alt_fb_idx = 2;
2258
0
  } else {
2259
0
    int i;
2260
0
    int count = 0;
2261
0
    cpi->lst_fb_idx = -1;
2262
0
    cpi->gld_fb_idx = -1;
2263
0
    cpi->alt_fb_idx = -1;
2264
0
    svc->update_buffer_slot[0] = 0;
2265
    // For intra-only frame we need to refresh all slots that were
2266
    // being used for the base layer (fb_idx_base[i] == 1).
2267
    // Start with assigning last first, then golden and then alt.
2268
0
    for (i = 0; i < REF_FRAMES; ++i) {
2269
0
      if (svc->fb_idx_base[i] == 1) {
2270
0
        svc->update_buffer_slot[0] |= 1 << i;
2271
0
        count++;
2272
0
      }
2273
0
      if (count == 1 && cpi->lst_fb_idx == -1) cpi->lst_fb_idx = i;
2274
0
      if (count == 2 && cpi->gld_fb_idx == -1) cpi->gld_fb_idx = i;
2275
0
      if (count == 3 && cpi->alt_fb_idx == -1) cpi->alt_fb_idx = i;
2276
0
    }
2277
    // If golden or alt is not being used for base layer, then set them
2278
    // to the lst_fb_idx.
2279
0
    if (cpi->gld_fb_idx == -1) cpi->gld_fb_idx = cpi->lst_fb_idx;
2280
0
    if (cpi->alt_fb_idx == -1) cpi->alt_fb_idx = cpi->lst_fb_idx;
2281
0
    if (svc->temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
2282
0
      cpi->ext_refresh_last_frame = 0;
2283
0
      cpi->ext_refresh_golden_frame = 0;
2284
0
      cpi->ext_refresh_alt_ref_frame = 0;
2285
0
      cpi->ref_frame_flags = 0;
2286
0
    }
2287
0
  }
2288
0
}
2289
2290
0
void vp9_rc_get_svc_params(VP9_COMP *cpi) {
2291
0
  VP9_COMMON *const cm = &cpi->common;
2292
0
  RATE_CONTROL *const rc = &cpi->rc;
2293
0
  SVC *const svc = &cpi->svc;
2294
0
  int target = rc->avg_frame_bandwidth;
2295
0
  int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2296
0
                               svc->number_temporal_layers);
2297
0
  if (svc->first_spatial_layer_to_encode)
2298
0
    svc->layer_context[svc->temporal_layer_id].is_key_frame = 0;
2299
  // Periodic key frames is based on the super-frame counter
2300
  // (svc.current_superframe), also only base spatial layer is key frame.
2301
  // Key frame is set for any of the following: very first frame, frame flags
2302
  // indicates key, superframe counter hits key frequency,(non-intra) sync
2303
  // flag is set for spatial layer 0, or deadline mode changes.
2304
0
  if ((cm->current_video_frame == 0 && !svc->previous_frame_is_intra_only) ||
2305
0
      (cpi->frame_flags & FRAMEFLAGS_KEY) ||
2306
0
      (cpi->oxcf.auto_key &&
2307
0
       (svc->current_superframe % cpi->oxcf.key_freq == 0) &&
2308
0
       !svc->previous_frame_is_intra_only && svc->spatial_layer_id == 0) ||
2309
0
      (svc->spatial_layer_sync[0] == 1 && svc->spatial_layer_id == 0) ||
2310
0
      (cpi->oxcf.mode != cpi->deadline_mode_previous_frame)) {
2311
0
    cm->frame_type = KEY_FRAME;
2312
0
    rc->source_alt_ref_active = 0;
2313
0
    if (is_one_pass_svc(cpi)) {
2314
0
      if (cm->current_video_frame > 0) vp9_svc_reset_temporal_layers(cpi, 1);
2315
0
      layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2316
0
                               svc->number_temporal_layers);
2317
0
      svc->layer_context[layer].is_key_frame = 1;
2318
0
      cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
2319
      // Assumption here is that LAST_FRAME is being updated for a keyframe.
2320
      // Thus no change in update flags.
2321
0
      if (cpi->oxcf.rc_mode == VPX_CBR)
2322
0
        target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2323
0
      else
2324
0
        target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2325
0
    }
2326
0
  } else {
2327
0
    cm->frame_type = INTER_FRAME;
2328
0
    if (is_one_pass_svc(cpi)) {
2329
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
2330
      // Add condition current_video_frame > 0 for the case where first frame
2331
      // is intra only followed by overlay/copy frame. In this case we don't
2332
      // want to reset is_key_frame to 0 on overlay/copy frame.
2333
0
      lc->is_key_frame =
2334
0
          (svc->spatial_layer_id == 0 && cm->current_video_frame > 0)
2335
0
              ? 0
2336
0
              : svc->layer_context[svc->temporal_layer_id].is_key_frame;
2337
0
      if (cpi->oxcf.rc_mode == VPX_CBR) {
2338
0
        target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2339
0
      } else {
2340
0
        double rate_err = 0.0;
2341
0
        rc->fac_active_worst_inter = 140;
2342
0
        rc->fac_active_worst_gf = 100;
2343
0
        if (rc->rolling_target_bits > 0) {
2344
0
          rate_err =
2345
0
              (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
2346
0
          if (rate_err < 1.0)
2347
0
            rc->fac_active_worst_inter = 120;
2348
0
          else if (rate_err > 2.0)
2349
            // Increase active_worst faster if rate fluctuation is high.
2350
0
            rc->fac_active_worst_inter = 160;
2351
0
        }
2352
0
        target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
2353
0
      }
2354
0
    }
2355
0
  }
2356
2357
0
  if (svc->simulcast_mode) {
2358
0
    if (svc->spatial_layer_id > 0 &&
2359
0
        svc->layer_context[layer].is_key_frame == 1) {
2360
0
      cm->frame_type = KEY_FRAME;
2361
0
      cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
2362
0
      if (cpi->oxcf.rc_mode == VPX_CBR)
2363
0
        target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2364
0
      else
2365
0
        target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2366
0
    }
2367
    // Set the buffer idx and refresh flags for key frames in simulcast mode.
2368
    // Note the buffer slot for long-term reference is set below (line 2255),
2369
    // and alt_ref is used for that on key frame. So use last and golden for
2370
    // the other two normal slots.
2371
0
    if (cm->frame_type == KEY_FRAME) {
2372
0
      if (svc->number_spatial_layers == 2) {
2373
0
        if (svc->spatial_layer_id == 0) {
2374
0
          cpi->lst_fb_idx = 0;
2375
0
          cpi->gld_fb_idx = 2;
2376
0
          cpi->alt_fb_idx = 6;
2377
0
        } else if (svc->spatial_layer_id == 1) {
2378
0
          cpi->lst_fb_idx = 1;
2379
0
          cpi->gld_fb_idx = 3;
2380
0
          cpi->alt_fb_idx = 6;
2381
0
        }
2382
0
      } else if (svc->number_spatial_layers == 3) {
2383
0
        if (svc->spatial_layer_id == 0) {
2384
0
          cpi->lst_fb_idx = 0;
2385
0
          cpi->gld_fb_idx = 3;
2386
0
          cpi->alt_fb_idx = 6;
2387
0
        } else if (svc->spatial_layer_id == 1) {
2388
0
          cpi->lst_fb_idx = 1;
2389
0
          cpi->gld_fb_idx = 4;
2390
0
          cpi->alt_fb_idx = 6;
2391
0
        } else if (svc->spatial_layer_id == 2) {
2392
0
          cpi->lst_fb_idx = 2;
2393
0
          cpi->gld_fb_idx = 5;
2394
0
          cpi->alt_fb_idx = 7;
2395
0
        }
2396
0
      }
2397
0
      cpi->ext_refresh_last_frame = 1;
2398
0
      cpi->ext_refresh_golden_frame = 1;
2399
0
      cpi->ext_refresh_alt_ref_frame = 1;
2400
0
    }
2401
0
  }
2402
2403
  // Check if superframe contains a sync layer request.
2404
0
  vp9_svc_check_spatial_layer_sync(cpi);
2405
2406
  // If long term termporal feature is enabled, set the period of the update.
2407
  // The update/refresh of this reference frame is always on base temporal
2408
  // layer frame.
2409
0
  if (svc->use_gf_temporal_ref_current_layer) {
2410
    // Only use gf long-term prediction on non-key superframes.
2411
0
    if (!svc->layer_context[svc->temporal_layer_id].is_key_frame) {
2412
      // Use golden for this reference, which will be used for prediction.
2413
0
      int index = svc->spatial_layer_id;
2414
0
      if (svc->number_spatial_layers == 3) index = svc->spatial_layer_id - 1;
2415
0
      assert(index >= 0);
2416
0
      cpi->gld_fb_idx = svc->buffer_gf_temporal_ref[index].idx;
2417
      // Enable prediction off LAST (last reference) and golden (which will
2418
      // generally be further behind/long-term reference).
2419
0
      cpi->ref_frame_flags = VP9_LAST_FLAG | VP9_GOLD_FLAG;
2420
0
    }
2421
    // Check for update/refresh of reference: only refresh on base temporal
2422
    // layer.
2423
0
    if (svc->temporal_layer_id == 0) {
2424
0
      if (svc->layer_context[svc->temporal_layer_id].is_key_frame) {
2425
        // On key frame we update the buffer index used for long term reference.
2426
        // Use the alt_ref since it is not used or updated on key frames.
2427
0
        int index = svc->spatial_layer_id;
2428
0
        if (svc->number_spatial_layers == 3) index = svc->spatial_layer_id - 1;
2429
0
        assert(index >= 0);
2430
0
        cpi->alt_fb_idx = svc->buffer_gf_temporal_ref[index].idx;
2431
0
        cpi->ext_refresh_alt_ref_frame = 1;
2432
0
      } else if (rc->frames_till_gf_update_due == 0) {
2433
        // Set perdiod of next update. Make it a multiple of 10, as the cyclic
2434
        // refresh is typically ~10%, and we'd like the update to happen after
2435
        // a few cylces of the refresh (so it better quality frame). Note the
2436
        // cyclic refresh for SVC only operates on base temporal layer frames.
2437
        // Choose 20 as perdiod for now (2 cycles).
2438
0
        rc->baseline_gf_interval = 20;
2439
0
        rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2440
0
        cpi->ext_refresh_golden_frame = 1;
2441
0
        rc->gfu_boost = DEFAULT_GF_BOOST;
2442
0
      }
2443
0
    }
2444
0
  } else if (!svc->use_gf_temporal_ref) {
2445
0
    rc->frames_till_gf_update_due = INT_MAX;
2446
0
    rc->baseline_gf_interval = INT_MAX;
2447
0
  }
2448
0
  if (svc->set_intra_only_frame) {
2449
0
    set_intra_only_frame(cpi);
2450
0
    if (cpi->oxcf.rc_mode == VPX_CBR)
2451
0
      target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2452
0
    else
2453
0
      target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2454
0
  }
2455
  // Overlay frame predicts from LAST (intra-only)
2456
0
  if (svc->previous_frame_is_intra_only) cpi->ref_frame_flags |= VP9_LAST_FLAG;
2457
2458
  // Any update/change of global cyclic refresh parameters (amount/delta-qp)
2459
  // should be done here, before the frame qp is selected.
2460
0
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
2461
0
    vp9_cyclic_refresh_update_parameters(cpi);
2462
2463
0
  vp9_rc_set_frame_target(cpi, target);
2464
0
  if (cm->show_frame) vp9_update_buffer_level_svc_preencode(cpi);
2465
2466
0
  if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC && svc->single_layer_svc == 1 &&
2467
0
      svc->spatial_layer_id == svc->first_spatial_layer_to_encode &&
2468
0
      svc->temporal_layer_id == 0) {
2469
0
    LAYER_CONTEXT *lc = NULL;
2470
0
    cpi->resize_pending = vp9_resize_one_pass_cbr(cpi);
2471
0
    if (cpi->resize_pending) {
2472
0
      int tl, width, height;
2473
      // Apply the same scale to all temporal layers.
2474
0
      for (tl = 0; tl < svc->number_temporal_layers; tl++) {
2475
0
        lc = &svc->layer_context[svc->spatial_layer_id *
2476
0
                                     svc->number_temporal_layers +
2477
0
                                 tl];
2478
0
        lc->scaling_factor_num_resize =
2479
0
            cpi->resize_scale_num * lc->scaling_factor_num;
2480
0
        lc->scaling_factor_den_resize =
2481
0
            cpi->resize_scale_den * lc->scaling_factor_den;
2482
        // Reset rate control for all temporal layers.
2483
0
        lc->rc.buffer_level = lc->rc.optimal_buffer_level;
2484
0
        lc->rc.bits_off_target = lc->rc.optimal_buffer_level;
2485
0
        lc->rc.rate_correction_factors[INTER_FRAME] =
2486
0
            rc->rate_correction_factors[INTER_FRAME];
2487
0
      }
2488
      // Set the size for this current temporal layer.
2489
0
      lc = &svc->layer_context[svc->spatial_layer_id *
2490
0
                                   svc->number_temporal_layers +
2491
0
                               svc->temporal_layer_id];
2492
0
      get_layer_resolution(cpi->oxcf.width, cpi->oxcf.height,
2493
0
                           lc->scaling_factor_num_resize,
2494
0
                           lc->scaling_factor_den_resize, &width, &height);
2495
0
      vp9_set_size_literal(cpi, width, height);
2496
0
      svc->resize_set = 1;
2497
0
    }
2498
0
  } else {
2499
0
    cpi->resize_pending = 0;
2500
0
    svc->resize_set = 0;
2501
0
  }
2502
0
}
2503
2504
0
void vp9_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
2505
0
  VP9_COMMON *const cm = &cpi->common;
2506
0
  RATE_CONTROL *const rc = &cpi->rc;
2507
0
  int target;
2508
0
  if ((cm->current_video_frame == 0) || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
2509
0
      (cpi->oxcf.auto_key && rc->frames_to_key == 0) ||
2510
0
      (cpi->oxcf.mode != cpi->deadline_mode_previous_frame)) {
2511
0
    cm->frame_type = KEY_FRAME;
2512
0
    rc->frames_to_key = cpi->oxcf.key_freq;
2513
0
    rc->kf_boost = DEFAULT_KF_BOOST;
2514
0
    rc->source_alt_ref_active = 0;
2515
0
  } else {
2516
0
    cm->frame_type = INTER_FRAME;
2517
0
  }
2518
0
  if (rc->frames_till_gf_update_due == 0) {
2519
0
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
2520
0
      vp9_cyclic_refresh_set_golden_update(cpi);
2521
0
    else
2522
0
      rc->baseline_gf_interval =
2523
0
          (rc->min_gf_interval + rc->max_gf_interval) / 2;
2524
0
    rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2525
    // NOTE: frames_till_gf_update_due must be <= frames_to_key.
2526
0
    if (rc->frames_till_gf_update_due > rc->frames_to_key)
2527
0
      rc->frames_till_gf_update_due = rc->frames_to_key;
2528
0
    cpi->refresh_golden_frame = 1;
2529
0
    rc->gfu_boost = DEFAULT_GF_BOOST;
2530
0
  }
2531
2532
  // Any update/change of global cyclic refresh parameters (amount/delta-qp)
2533
  // should be done here, before the frame qp is selected.
2534
0
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
2535
0
    vp9_cyclic_refresh_update_parameters(cpi);
2536
2537
0
  if (frame_is_intra_only(cm))
2538
0
    target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2539
0
  else
2540
0
    target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2541
2542
0
  vp9_rc_set_frame_target(cpi, target);
2543
2544
0
  if (cm->show_frame) vp9_update_buffer_level_preencode(cpi);
2545
2546
0
  if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC)
2547
0
    cpi->resize_pending = vp9_resize_one_pass_cbr(cpi);
2548
0
  else
2549
0
    cpi->resize_pending = 0;
2550
0
}
2551
2552
int vp9_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
2553
13.8k
                       vpx_bit_depth_t bit_depth) {
2554
13.8k
  int start_index = rc->worst_quality;
2555
13.8k
  int target_index = rc->worst_quality;
2556
13.8k
  int i;
2557
2558
  // Convert the average q value to an index.
2559
1.07M
  for (i = rc->best_quality; i < rc->worst_quality; ++i) {
2560
1.07M
    start_index = i;
2561
1.07M
    if (vp9_convert_qindex_to_q(i, bit_depth) >= qstart) break;
2562
1.07M
  }
2563
2564
  // Convert the q target to an index
2565
761k
  for (i = rc->best_quality; i < rc->worst_quality; ++i) {
2566
761k
    target_index = i;
2567
761k
    if (vp9_convert_qindex_to_q(i, bit_depth) >= qtarget) break;
2568
761k
  }
2569
2570
13.8k
  return target_index - start_index;
2571
13.8k
}
2572
2573
int vp9_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
2574
                               int qindex, double rate_target_ratio,
2575
15.6k
                               vpx_bit_depth_t bit_depth) {
2576
15.6k
  int target_index = rc->worst_quality;
2577
15.6k
  int i;
2578
2579
  // Look up the current projected bits per block for the base index
2580
15.6k
  const int base_bits_per_mb =
2581
15.6k
      vp9_rc_bits_per_mb(frame_type, qindex, 1.0, bit_depth);
2582
2583
  // Find the target bits per mb based on the base value and given ratio.
2584
15.6k
  const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
2585
2586
  // Convert the q target to an index
2587
1.90M
  for (i = rc->best_quality; i < rc->worst_quality; ++i) {
2588
1.90M
    if (vp9_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
2589
1.90M
        target_bits_per_mb) {
2590
15.6k
      target_index = i;
2591
15.6k
      break;
2592
15.6k
    }
2593
1.90M
  }
2594
15.6k
  return target_index - qindex;
2595
15.6k
}
2596
2597
void vp9_rc_set_gf_interval_range(const VP9_COMP *const cpi,
2598
88.4k
                                  RATE_CONTROL *const rc) {
2599
88.4k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2600
2601
  // Special case code for 1 pass fixed Q mode tests
2602
88.4k
  if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
2603
4.81k
    rc->max_gf_interval = FIXED_GF_INTERVAL;
2604
4.81k
    rc->min_gf_interval = FIXED_GF_INTERVAL;
2605
4.81k
    rc->static_scene_max_gf_interval = FIXED_GF_INTERVAL;
2606
83.6k
  } else {
2607
83.6k
    double framerate = cpi->framerate;
2608
    // Set Maximum gf/arf interval
2609
83.6k
    rc->max_gf_interval = oxcf->max_gf_interval;
2610
83.6k
    rc->min_gf_interval = oxcf->min_gf_interval;
2611
83.6k
    if (rc->min_gf_interval == 0) {
2612
83.6k
      rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
2613
83.6k
          oxcf->width, oxcf->height, framerate);
2614
83.6k
    }
2615
83.6k
    if (rc->max_gf_interval == 0) {
2616
83.6k
      rc->max_gf_interval =
2617
83.6k
          vp9_rc_get_default_max_gf_interval(framerate, rc->min_gf_interval);
2618
83.6k
    }
2619
2620
    // Extended max interval for genuinely static scenes like slide shows.
2621
83.6k
    rc->static_scene_max_gf_interval = MAX_STATIC_GF_GROUP_LENGTH;
2622
2623
83.6k
    if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
2624
182
      rc->max_gf_interval = rc->static_scene_max_gf_interval;
2625
2626
    // Clamp min to max
2627
83.6k
    rc->min_gf_interval = VPXMIN(rc->min_gf_interval, rc->max_gf_interval);
2628
2629
83.6k
    if (oxcf->target_level == LEVEL_AUTO) {
2630
0
      const uint32_t pic_size = cpi->common.width * cpi->common.height;
2631
0
      const uint32_t pic_breadth =
2632
0
          VPXMAX(cpi->common.width, cpi->common.height);
2633
0
      int i;
2634
0
      for (i = 0; i < VP9_LEVELS; ++i) {
2635
0
        if (vp9_level_defs[i].max_luma_picture_size >= pic_size &&
2636
0
            vp9_level_defs[i].max_luma_picture_breadth >= pic_breadth) {
2637
0
          if (rc->min_gf_interval <=
2638
0
              (int)vp9_level_defs[i].min_altref_distance) {
2639
0
            rc->min_gf_interval = (int)vp9_level_defs[i].min_altref_distance;
2640
0
            rc->max_gf_interval =
2641
0
                VPXMAX(rc->max_gf_interval, rc->min_gf_interval);
2642
0
          }
2643
0
          break;
2644
0
        }
2645
0
      }
2646
0
    }
2647
83.6k
  }
2648
88.4k
}
2649
2650
88.4k
void vp9_rc_update_framerate(VP9_COMP *cpi) {
2651
88.4k
  const VP9_COMMON *const cm = &cpi->common;
2652
88.4k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2653
88.4k
  RATE_CONTROL *const rc = &cpi->rc;
2654
2655
88.4k
  rc->avg_frame_bandwidth = saturate_cast_double_to_int(
2656
88.4k
      round(oxcf->target_bandwidth / cpi->framerate));
2657
2658
88.4k
  int64_t vbr_min_bits =
2659
88.4k
      (int64_t)rc->avg_frame_bandwidth * oxcf->two_pass_vbrmin_section / 100;
2660
88.4k
  vbr_min_bits = VPXMIN(vbr_min_bits, INT_MAX);
2661
2662
88.4k
  rc->min_frame_bandwidth = VPXMAX((int)vbr_min_bits, FRAME_OVERHEAD_BITS);
2663
2664
  // A maximum bitrate for a frame is defined.
2665
  // However this limit is extended if a very high rate is given on the command
2666
  // line or the rate can not be achieved because of a user specified max q
2667
  // (e.g. when the user specifies lossless encode).
2668
  //
2669
  // If a level is specified that requires a lower maximum rate then the level
2670
  // value take precedence.
2671
88.4k
  int64_t vbr_max_bits =
2672
88.4k
      (int64_t)rc->avg_frame_bandwidth * oxcf->two_pass_vbrmax_section / 100;
2673
88.4k
  vbr_max_bits = VPXMIN(vbr_max_bits, INT_MAX);
2674
2675
88.4k
  rc->max_frame_bandwidth =
2676
88.4k
      VPXMAX(VPXMAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P), (int)vbr_max_bits);
2677
2678
88.4k
  vp9_rc_set_gf_interval_range(cpi, rc);
2679
88.4k
}
2680
2681
#define VBR_PCT_ADJUSTMENT_LIMIT 50
2682
// For VBR...adjustment to the frame target based on error from previous frames
2683
0
static void vbr_rate_correction(VP9_COMP *cpi, int *this_frame_target) {
2684
0
  RATE_CONTROL *const rc = &cpi->rc;
2685
0
  int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
2686
0
  int64_t frame_target = *this_frame_target;
2687
0
  int frame_window = (int)VPXMIN(
2688
0
      16, cpi->twopass.total_stats.count - cpi->common.current_video_frame);
2689
2690
  // Calcluate the adjustment to rate for this frame.
2691
0
  if (frame_window > 0) {
2692
0
    int64_t max_delta = (vbr_bits_off_target > 0)
2693
0
                            ? (vbr_bits_off_target / frame_window)
2694
0
                            : (-vbr_bits_off_target / frame_window);
2695
2696
0
    max_delta =
2697
0
        VPXMIN(max_delta, ((frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
2698
2699
    // vbr_bits_off_target > 0 means we have extra bits to spend
2700
0
    if (vbr_bits_off_target > 0) {
2701
0
      frame_target += VPXMIN(vbr_bits_off_target, max_delta);
2702
0
    } else {
2703
0
      frame_target -= VPXMIN(-vbr_bits_off_target, max_delta);
2704
0
    }
2705
0
  }
2706
2707
  // Fast redistribution of bits arising from massive local undershoot.
2708
  // Don't do it for kf,arf,gf or overlay frames.
2709
0
  if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
2710
0
      rc->vbr_bits_off_target_fast) {
2711
0
    int64_t one_frame_bits = VPXMAX(rc->avg_frame_bandwidth, frame_target);
2712
0
    int64_t fast_extra_bits =
2713
0
        VPXMIN(rc->vbr_bits_off_target_fast, one_frame_bits);
2714
0
    fast_extra_bits =
2715
0
        VPXMIN(fast_extra_bits,
2716
0
               VPXMAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
2717
0
    frame_target += fast_extra_bits;
2718
0
    rc->vbr_bits_off_target_fast -= fast_extra_bits;
2719
0
  }
2720
2721
  // Clamp the target for the frame to the maximum allowed for one frame.
2722
0
  *this_frame_target = (int)VPXMIN(frame_target, INT_MAX);
2723
0
}
2724
2725
0
void vp9_set_target_rate(VP9_COMP *cpi) {
2726
0
  RATE_CONTROL *const rc = &cpi->rc;
2727
0
  int target_rate = rc->base_frame_target;
2728
2729
0
  if (cpi->common.frame_type == KEY_FRAME)
2730
0
    target_rate = vp9_rc_clamp_iframe_target_size(cpi, target_rate);
2731
0
  else
2732
0
    target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2733
2734
0
  if (!cpi->oxcf.vbr_corpus_complexity) {
2735
    // Correction to rate target based on prior over or under shoot.
2736
0
    if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
2737
0
      vbr_rate_correction(cpi, &target_rate);
2738
0
  }
2739
0
  vp9_rc_set_frame_target(cpi, target_rate);
2740
0
}
2741
2742
// Check if we should resize, based on average QP from past x frames.
2743
// Only allow for resize at most one scale down for now, scaling factor is 2.
2744
0
int vp9_resize_one_pass_cbr(VP9_COMP *cpi) {
2745
0
  const VP9_COMMON *const cm = &cpi->common;
2746
0
  RATE_CONTROL *const rc = &cpi->rc;
2747
0
  RESIZE_ACTION resize_action = NO_RESIZE;
2748
0
  int avg_qp_thr1 = 70;
2749
0
  int avg_qp_thr2 = 50;
2750
  // Don't allow for resized frame to go below 320x180, resize in steps of 3/4.
2751
0
  int min_width = (320 * 4) / 3;
2752
0
  int min_height = (180 * 4) / 3;
2753
0
  int down_size_on = 1;
2754
0
  int force_downsize_rate = 0;
2755
0
  cpi->resize_scale_num = 1;
2756
0
  cpi->resize_scale_den = 1;
2757
  // Don't resize on key frame; reset the counters on key frame.
2758
0
  if (cm->frame_type == KEY_FRAME) {
2759
0
    cpi->resize_avg_qp = 0;
2760
0
    cpi->resize_count = 0;
2761
0
    return 0;
2762
0
  }
2763
2764
  // No resizing down if frame size is below some limit.
2765
0
  if ((cm->width * cm->height) < min_width * min_height) down_size_on = 0;
2766
2767
#if CONFIG_VP9_TEMPORAL_DENOISING
2768
  // If denoiser is on, apply a smaller qp threshold.
2769
  if (cpi->oxcf.noise_sensitivity > 0) {
2770
    avg_qp_thr1 = 60;
2771
    avg_qp_thr2 = 40;
2772
  }
2773
#endif
2774
2775
  // Force downsize based on per-frame-bandwidth, for extreme case,
2776
  // for HD input.
2777
0
  if (cpi->resize_state == ORIG && cm->width * cm->height >= 1280 * 720) {
2778
0
    if (rc->avg_frame_bandwidth < 300000 / 30) {
2779
0
      resize_action = DOWN_ONEHALF;
2780
0
      cpi->resize_state = ONE_HALF;
2781
0
      force_downsize_rate = 1;
2782
0
    } else if (rc->avg_frame_bandwidth < 400000 / 30) {
2783
0
      resize_action = ONEHALFONLY_RESIZE ? DOWN_ONEHALF : DOWN_THREEFOUR;
2784
0
      cpi->resize_state = ONEHALFONLY_RESIZE ? ONE_HALF : THREE_QUARTER;
2785
0
      force_downsize_rate = 1;
2786
0
    }
2787
0
  } else if (cpi->resize_state == THREE_QUARTER &&
2788
0
             cm->width * cm->height >= 960 * 540) {
2789
0
    if (rc->avg_frame_bandwidth < 300000 / 30) {
2790
0
      resize_action = DOWN_ONEHALF;
2791
0
      cpi->resize_state = ONE_HALF;
2792
0
      force_downsize_rate = 1;
2793
0
    }
2794
0
  }
2795
2796
  // Resize based on average buffer underflow and QP over some window.
2797
  // Ignore samples close to key frame, since QP is usually high after key.
2798
0
  if (!force_downsize_rate && cpi->rc.frames_since_key > cpi->framerate) {
2799
0
    const int window = VPXMIN(30, (int)round(2 * cpi->framerate));
2800
0
    cpi->resize_avg_qp += rc->last_q[INTER_FRAME];
2801
0
    if (cpi->rc.buffer_level < (int)(30 * rc->optimal_buffer_level / 100))
2802
0
      ++cpi->resize_buffer_underflow;
2803
0
    ++cpi->resize_count;
2804
    // Check for resize action every "window" frames.
2805
0
    if (cpi->resize_count >= window) {
2806
0
      int avg_qp = cpi->resize_avg_qp / cpi->resize_count;
2807
      // Resize down if buffer level has underflowed sufficient amount in past
2808
      // window, and we are at original or 3/4 of original resolution.
2809
      // Resize back up if average QP is low, and we are currently in a resized
2810
      // down state, i.e. 1/2 or 3/4 of original resolution.
2811
      // Currently, use a flag to turn 3/4 resizing feature on/off.
2812
0
      if (cpi->resize_buffer_underflow > (cpi->resize_count >> 2) &&
2813
0
          down_size_on) {
2814
0
        if (cpi->resize_state == THREE_QUARTER) {
2815
0
          resize_action = DOWN_ONEHALF;
2816
0
          cpi->resize_state = ONE_HALF;
2817
0
        } else if (cpi->resize_state == ORIG) {
2818
0
          resize_action = ONEHALFONLY_RESIZE ? DOWN_ONEHALF : DOWN_THREEFOUR;
2819
0
          cpi->resize_state = ONEHALFONLY_RESIZE ? ONE_HALF : THREE_QUARTER;
2820
0
        }
2821
0
      } else if (cpi->resize_state != ORIG &&
2822
0
                 avg_qp < avg_qp_thr1 * cpi->rc.worst_quality / 100) {
2823
0
        if (cpi->resize_state == THREE_QUARTER ||
2824
0
            avg_qp < avg_qp_thr2 * cpi->rc.worst_quality / 100 ||
2825
0
            ONEHALFONLY_RESIZE) {
2826
0
          resize_action = UP_ORIG;
2827
0
          cpi->resize_state = ORIG;
2828
0
        } else if (cpi->resize_state == ONE_HALF) {
2829
0
          resize_action = UP_THREEFOUR;
2830
0
          cpi->resize_state = THREE_QUARTER;
2831
0
        }
2832
0
      }
2833
      // Reset for next window measurement.
2834
0
      cpi->resize_avg_qp = 0;
2835
0
      cpi->resize_count = 0;
2836
0
      cpi->resize_buffer_underflow = 0;
2837
0
    }
2838
0
  }
2839
  // If decision is to resize, reset some quantities, and check is we should
2840
  // reduce rate correction factor,
2841
0
  if (resize_action != NO_RESIZE) {
2842
0
    int target_bits_per_frame;
2843
0
    int active_worst_quality;
2844
0
    int qindex;
2845
0
    int tot_scale_change;
2846
0
    if (resize_action == DOWN_THREEFOUR || resize_action == UP_THREEFOUR) {
2847
0
      cpi->resize_scale_num = 3;
2848
0
      cpi->resize_scale_den = 4;
2849
0
    } else if (resize_action == DOWN_ONEHALF) {
2850
0
      cpi->resize_scale_num = 1;
2851
0
      cpi->resize_scale_den = 2;
2852
0
    } else {  // UP_ORIG or anything else
2853
0
      cpi->resize_scale_num = 1;
2854
0
      cpi->resize_scale_den = 1;
2855
0
    }
2856
0
    tot_scale_change = (cpi->resize_scale_den * cpi->resize_scale_den) /
2857
0
                       (cpi->resize_scale_num * cpi->resize_scale_num);
2858
    // Reset buffer level to optimal, update target size.
2859
0
    rc->buffer_level = rc->optimal_buffer_level;
2860
0
    rc->bits_off_target = rc->optimal_buffer_level;
2861
0
    rc->this_frame_target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2862
    // Get the projected qindex, based on the scaled target frame size (scaled
2863
    // so target_bits_per_mb in vp9_rc_regulate_q will be correct target).
2864
0
    target_bits_per_frame = (resize_action >= 0)
2865
0
                                ? rc->this_frame_target * tot_scale_change
2866
0
                                : rc->this_frame_target / tot_scale_change;
2867
0
    active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
2868
0
    qindex = vp9_rc_regulate_q(cpi, target_bits_per_frame, rc->best_quality,
2869
0
                               active_worst_quality);
2870
    // If resize is down, check if projected q index is close to worst_quality,
2871
    // and if so, reduce the rate correction factor (since likely can afford
2872
    // lower q for resized frame).
2873
0
    if (resize_action > 0 && qindex > 90 * cpi->rc.worst_quality / 100) {
2874
0
      rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
2875
0
    }
2876
    // If resize is back up, check if projected q index is too much above the
2877
    // current base_qindex, and if so, reduce the rate correction factor
2878
    // (since prefer to keep q for resized frame at least close to previous q).
2879
0
    if (resize_action < 0 && qindex > 130 * cm->base_qindex / 100) {
2880
0
      rc->rate_correction_factors[INTER_NORMAL] *= 0.9;
2881
0
    }
2882
0
  }
2883
0
  return resize_action;
2884
0
}
2885
2886
static void adjust_gf_boost_lag_one_pass_vbr(VP9_COMP *cpi,
2887
27.8k
                                             uint64_t avg_sad_current) {
2888
27.8k
  VP9_COMMON *const cm = &cpi->common;
2889
27.8k
  RATE_CONTROL *const rc = &cpi->rc;
2890
27.8k
  int target;
2891
27.8k
  int found = 0;
2892
27.8k
  int found2 = 0;
2893
27.8k
  int frame;
2894
27.8k
  int i;
2895
27.8k
  uint64_t avg_source_sad_lag = avg_sad_current;
2896
27.8k
  int high_source_sad_lagindex = -1;
2897
27.8k
  int steady_sad_lagindex = -1;
2898
27.8k
  uint32_t sad_thresh1 = 70000;
2899
27.8k
  uint32_t sad_thresh2 = 120000;
2900
27.8k
  int low_content = 0;
2901
27.8k
  int high_content = 0;
2902
27.8k
  double rate_err = 1.0;
2903
  // Get measure of complexity over the future frames, and get the first
2904
  // future frame with high_source_sad/scene-change.
2905
27.8k
  int tot_frames = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
2906
457k
  for (frame = tot_frames; frame >= 1; --frame) {
2907
429k
    const int lagframe_idx = tot_frames - frame + 1;
2908
429k
    uint64_t reference_sad = rc->avg_source_sad[0];
2909
4.65M
    for (i = 1; i < lagframe_idx; ++i) {
2910
4.22M
      if (rc->avg_source_sad[i] > 0)
2911
1.55k
        reference_sad = (3 * reference_sad + rc->avg_source_sad[i]) >> 2;
2912
4.22M
    }
2913
    // Detect up-coming scene change.
2914
429k
    if (!found &&
2915
429k
        (rc->avg_source_sad[lagframe_idx] >
2916
429k
             VPXMAX(sad_thresh1, (unsigned int)(reference_sad << 1)) ||
2917
429k
         rc->avg_source_sad[lagframe_idx] >
2918
429k
             VPXMAX(3 * sad_thresh1 >> 2,
2919
429k
                    (unsigned int)(reference_sad << 2)))) {
2920
174
      high_source_sad_lagindex = lagframe_idx;
2921
174
      found = 1;
2922
174
    }
2923
    // Detect change from motion to steady.
2924
429k
    if (!found2 && lagframe_idx > 1 && lagframe_idx < tot_frames &&
2925
380k
        rc->avg_source_sad[lagframe_idx - 1] > (sad_thresh1 >> 2)) {
2926
300
      found2 = 1;
2927
609
      for (i = lagframe_idx; i < tot_frames; ++i) {
2928
309
        if (!(rc->avg_source_sad[i] > 0 &&
2929
263
              rc->avg_source_sad[i] < (sad_thresh1 >> 2) &&
2930
23
              rc->avg_source_sad[i] <
2931
286
                  (rc->avg_source_sad[lagframe_idx - 1] >> 1))) {
2932
286
          found2 = 0;
2933
286
          i = tot_frames;
2934
286
        }
2935
309
      }
2936
300
      if (found2) steady_sad_lagindex = lagframe_idx;
2937
300
    }
2938
429k
    avg_source_sad_lag += rc->avg_source_sad[lagframe_idx];
2939
429k
  }
2940
27.8k
  if (tot_frames > 0) avg_source_sad_lag = avg_source_sad_lag / tot_frames;
2941
  // Constrain distance between detected scene cuts.
2942
27.8k
  if (high_source_sad_lagindex != -1 &&
2943
174
      high_source_sad_lagindex != rc->high_source_sad_lagindex - 1 &&
2944
85
      abs(high_source_sad_lagindex - rc->high_source_sad_lagindex) < 4)
2945
48
    rc->high_source_sad_lagindex = -1;
2946
27.8k
  else
2947
27.8k
    rc->high_source_sad_lagindex = high_source_sad_lagindex;
2948
  // Adjust some factors for the next GF group, ignore initial key frame,
2949
  // and only for lag_in_frames not too small.
2950
27.8k
  if (cpi->refresh_golden_frame == 1 && cm->current_video_frame > 30 &&
2951
3.13k
      cpi->oxcf.lag_in_frames > 8) {
2952
3.13k
    int frame_constraint;
2953
3.13k
    if (rc->rolling_target_bits > 0)
2954
1.76k
      rate_err =
2955
1.76k
          (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
2956
3.13k
    high_content = high_source_sad_lagindex != -1 ||
2957
3.13k
                   avg_source_sad_lag > (rc->prev_avg_source_sad_lag << 1) ||
2958
3.13k
                   avg_source_sad_lag > sad_thresh2;
2959
3.13k
    low_content = high_source_sad_lagindex == -1 &&
2960
3.13k
                  ((avg_source_sad_lag < (rc->prev_avg_source_sad_lag >> 1)) ||
2961
3.13k
                   (avg_source_sad_lag < sad_thresh1));
2962
3.13k
    if (low_content) {
2963
3.13k
      rc->gfu_boost = DEFAULT_GF_BOOST;
2964
3.13k
      rc->baseline_gf_interval =
2965
3.13k
          VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
2966
3.13k
    } else if (high_content) {
2967
0
      rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
2968
0
      rc->baseline_gf_interval = (rate_err > 3.0)
2969
0
                                     ? VPXMAX(10, rc->baseline_gf_interval >> 1)
2970
0
                                     : VPXMAX(6, rc->baseline_gf_interval >> 1);
2971
0
    }
2972
3.13k
    if (rc->baseline_gf_interval > cpi->oxcf.lag_in_frames - 1)
2973
0
      rc->baseline_gf_interval = cpi->oxcf.lag_in_frames - 1;
2974
    // Check for constraining gf_interval for up-coming scene/content changes,
2975
    // or for up-coming key frame, whichever is closer.
2976
3.13k
    frame_constraint = rc->frames_to_key;
2977
3.13k
    if (rc->high_source_sad_lagindex > 0 &&
2978
0
        frame_constraint > rc->high_source_sad_lagindex)
2979
0
      frame_constraint = rc->high_source_sad_lagindex;
2980
3.13k
    if (steady_sad_lagindex > 3 && frame_constraint > steady_sad_lagindex)
2981
0
      frame_constraint = steady_sad_lagindex;
2982
3.13k
    adjust_gfint_frame_constraint(cpi, frame_constraint);
2983
3.13k
    rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2984
    // Adjust factors for active_worst setting & af_ratio for next gf interval.
2985
3.13k
    rc->fac_active_worst_inter = 150;  // corresponds to 3/2 (= 150 /100).
2986
3.13k
    rc->fac_active_worst_gf = 100;
2987
3.13k
    if (rate_err < 2.0 && !high_content) {
2988
2.86k
      rc->fac_active_worst_inter = 120;
2989
2.86k
      rc->fac_active_worst_gf = 90;
2990
2.86k
    } else if (rate_err > 8.0 && rc->avg_frame_qindex[INTER_FRAME] < 16) {
2991
      // Increase active_worst faster at low Q if rate fluctuation is high.
2992
0
      rc->fac_active_worst_inter = 200;
2993
0
      if (rc->avg_frame_qindex[INTER_FRAME] < 8)
2994
0
        rc->fac_active_worst_inter = 400;
2995
0
    }
2996
3.13k
    if (low_content && rc->avg_frame_low_motion > 80) {
2997
99
      rc->af_ratio_onepass_vbr = 15;
2998
3.03k
    } else if (high_content || rc->avg_frame_low_motion < 30) {
2999
2.85k
      rc->af_ratio_onepass_vbr = 5;
3000
2.85k
      rc->gfu_boost = DEFAULT_GF_BOOST >> 2;
3001
2.85k
    }
3002
3.13k
    if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf) {
3003
      // Flag to disable usage of ARF based on past usage, only allow this
3004
      // disabling if current frame/group does not start with key frame or
3005
      // scene cut. Note perc_arf_usage is only computed for speed >= 5.
3006
0
      int arf_usage_low =
3007
0
          (cm->frame_type != KEY_FRAME && !rc->high_source_sad &&
3008
0
           cpi->rc.perc_arf_usage < 15 && cpi->oxcf.speed >= 5);
3009
      // Don't use alt-ref for this group under certain conditions.
3010
0
      if (arf_usage_low ||
3011
0
          (rc->high_source_sad_lagindex > 0 &&
3012
0
           rc->high_source_sad_lagindex <= rc->frames_till_gf_update_due) ||
3013
0
          (avg_source_sad_lag > 3 * sad_thresh1 >> 3)) {
3014
0
        rc->source_alt_ref_pending = 0;
3015
0
        rc->alt_ref_gf_group = 0;
3016
0
      } else {
3017
0
        rc->source_alt_ref_pending = 1;
3018
0
        rc->alt_ref_gf_group = 1;
3019
        // If alt-ref is used for this gf group, limit the interval.
3020
0
        if (rc->baseline_gf_interval > 12) {
3021
0
          rc->baseline_gf_interval = 12;
3022
0
          rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3023
0
        }
3024
0
      }
3025
0
    }
3026
3.13k
    target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
3027
3.13k
    vp9_rc_set_frame_target(cpi, target);
3028
3.13k
  }
3029
27.8k
  rc->prev_avg_source_sad_lag = avg_source_sad_lag;
3030
27.8k
}
3031
3032
// Compute average source sad (temporal sad: between current source and
3033
// previous source) over a subset of superblocks. Use this is detect big changes
3034
// in content and allow rate control to react.
3035
// This function also handles special case of lag_in_frames, to measure content
3036
// level in #future frames set by the lag_in_frames.
3037
30.1k
void vp9_scene_detection_onepass(VP9_COMP *cpi) {
3038
30.1k
  VP9_COMMON *const cm = &cpi->common;
3039
30.1k
  RATE_CONTROL *const rc = &cpi->rc;
3040
30.1k
  YV12_BUFFER_CONFIG const *unscaled_src = cpi->un_scaled_source;
3041
30.1k
  YV12_BUFFER_CONFIG const *unscaled_last_src = cpi->unscaled_last_source;
3042
30.1k
  uint8_t *src_y;
3043
30.1k
  int src_ystride;
3044
30.1k
  int src_width;
3045
30.1k
  int src_height;
3046
30.1k
  uint8_t *last_src_y;
3047
30.1k
  int last_src_ystride;
3048
30.1k
  int last_src_width;
3049
30.1k
  int last_src_height;
3050
30.1k
  if (cpi->un_scaled_source == NULL || cpi->unscaled_last_source == NULL ||
3051
27.8k
      (cpi->use_svc && cpi->svc.current_superframe == 0))
3052
2.25k
    return;
3053
27.8k
  src_y = unscaled_src->y_buffer;
3054
27.8k
  src_ystride = unscaled_src->y_stride;
3055
27.8k
  src_width = unscaled_src->y_width;
3056
27.8k
  src_height = unscaled_src->y_height;
3057
27.8k
  last_src_y = unscaled_last_src->y_buffer;
3058
27.8k
  last_src_ystride = unscaled_last_src->y_stride;
3059
27.8k
  last_src_width = unscaled_last_src->y_width;
3060
27.8k
  last_src_height = unscaled_last_src->y_height;
3061
27.8k
#if CONFIG_VP9_HIGHBITDEPTH
3062
27.8k
  if (cm->use_highbitdepth) return;
3063
27.8k
#endif
3064
27.8k
  rc->high_source_sad = 0;
3065
27.8k
  rc->high_num_blocks_with_motion = 0;
3066
  // For SVC: scene detection is only checked on first spatial layer of
3067
  // the superframe using the original/unscaled resolutions.
3068
27.8k
  if (cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
3069
27.8k
      src_width == last_src_width && src_height == last_src_height) {
3070
27.8k
    YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS] = { NULL };
3071
27.8k
    int num_mi_cols = cm->mi_cols;
3072
27.8k
    int num_mi_rows = cm->mi_rows;
3073
27.8k
    int start_frame = 0;
3074
27.8k
    int frames_to_buffer = 1;
3075
27.8k
    int frame = 0;
3076
27.8k
    int scene_cut_force_key_frame = 0;
3077
27.8k
    int num_zero_temp_sad = 0;
3078
27.8k
    uint64_t avg_sad_current = 0;
3079
27.8k
    uint32_t min_thresh = 20000;  // ~5 * 64 * 64
3080
27.8k
    float thresh = 8.0f;
3081
27.8k
    uint32_t thresh_key = 140000;
3082
27.8k
    if (cpi->oxcf.speed <= 5) thresh_key = 240000;
3083
27.8k
    if (cpi->oxcf.content != VP9E_CONTENT_SCREEN) min_thresh = 65000;
3084
27.8k
    if (cpi->oxcf.rc_mode == VPX_VBR) thresh = 2.1f;
3085
27.8k
    if (cpi->use_svc && cpi->svc.number_spatial_layers > 1) {
3086
0
      const int aligned_width = ALIGN_POWER_OF_TWO(src_width, MI_SIZE_LOG2);
3087
0
      const int aligned_height = ALIGN_POWER_OF_TWO(src_height, MI_SIZE_LOG2);
3088
0
      num_mi_cols = aligned_width >> MI_SIZE_LOG2;
3089
0
      num_mi_rows = aligned_height >> MI_SIZE_LOG2;
3090
0
    }
3091
27.8k
    if (cpi->oxcf.lag_in_frames > 0) {
3092
27.8k
      frames_to_buffer = (cm->current_video_frame == 1)
3093
27.8k
                             ? (int)vp9_lookahead_depth(cpi->lookahead) - 1
3094
27.8k
                             : 2;
3095
27.8k
      start_frame = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
3096
92.7k
      for (frame = 0; frame < frames_to_buffer; ++frame) {
3097
64.8k
        const int lagframe_idx = start_frame - frame;
3098
64.8k
        if (lagframe_idx >= 0) {
3099
61.7k
          struct lookahead_entry *buf =
3100
61.7k
              vp9_lookahead_peek(cpi->lookahead, lagframe_idx);
3101
61.7k
          frames[frame] = &buf->img;
3102
61.7k
        }
3103
64.8k
      }
3104
      // The avg_sad for this current frame is the value of frame#1
3105
      // (first future frame) from previous frame.
3106
27.8k
      avg_sad_current = rc->avg_source_sad[1];
3107
27.8k
      if (avg_sad_current >
3108
27.8k
              VPXMAX(min_thresh,
3109
27.8k
                     (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
3110
99
          cm->current_video_frame > (unsigned int)cpi->oxcf.lag_in_frames)
3111
0
        rc->high_source_sad = 1;
3112
27.8k
      else
3113
27.8k
        rc->high_source_sad = 0;
3114
27.8k
      if (rc->high_source_sad && avg_sad_current > thresh_key)
3115
0
        scene_cut_force_key_frame = 1;
3116
      // Update recursive average for current frame.
3117
27.8k
      if (avg_sad_current > 0)
3118
175
        rc->avg_source_sad[0] =
3119
175
            (3 * rc->avg_source_sad[0] + avg_sad_current) >> 2;
3120
      // Shift back data, starting at frame#1.
3121
669k
      for (frame = 1; frame < cpi->oxcf.lag_in_frames - 1; ++frame)
3122
641k
        rc->avg_source_sad[frame] = rc->avg_source_sad[frame + 1];
3123
27.8k
    }
3124
92.7k
    for (frame = 0; frame < frames_to_buffer; ++frame) {
3125
64.8k
      if (cpi->oxcf.lag_in_frames == 0 ||
3126
64.8k
          (frames[frame] != NULL && frames[frame + 1] != NULL &&
3127
35.4k
           frames[frame]->y_width == frames[frame + 1]->y_width &&
3128
35.4k
           frames[frame]->y_height == frames[frame + 1]->y_height)) {
3129
35.4k
        int sbi_row, sbi_col;
3130
35.4k
        const int lagframe_idx =
3131
35.4k
            (cpi->oxcf.lag_in_frames == 0) ? 0 : start_frame - frame + 1;
3132
35.4k
        const BLOCK_SIZE bsize = BLOCK_64X64;
3133
        // Loop over sub-sample of frame, compute average sad over 64x64 blocks.
3134
35.4k
        uint64_t avg_sad = 0;
3135
35.4k
        uint64_t tmp_sad = 0;
3136
35.4k
        int num_samples = 0;
3137
35.4k
        int sb_cols = (num_mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
3138
35.4k
        int sb_rows = (num_mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
3139
35.4k
        if (cpi->oxcf.lag_in_frames > 0) {
3140
35.4k
          src_y = frames[frame]->y_buffer;
3141
35.4k
          src_ystride = frames[frame]->y_stride;
3142
35.4k
          last_src_y = frames[frame + 1]->y_buffer;
3143
35.4k
          last_src_ystride = frames[frame + 1]->y_stride;
3144
35.4k
        }
3145
35.4k
        num_zero_temp_sad = 0;
3146
73.1k
        for (sbi_row = 0; sbi_row < sb_rows; ++sbi_row) {
3147
83.1k
          for (sbi_col = 0; sbi_col < sb_cols; ++sbi_col) {
3148
            // Checker-board pattern, ignore boundary.
3149
45.4k
            if (((sbi_row > 0 && sbi_col > 0) &&
3150
3.63k
                 (sbi_row < sb_rows - 1 && sbi_col < sb_cols - 1) &&
3151
1.27k
                 ((sbi_row % 2 == 0 && sbi_col % 2 == 0) ||
3152
1.08k
                  (sbi_row % 2 != 0 && sbi_col % 2 != 0)))) {
3153
750
              tmp_sad = cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y,
3154
750
                                               last_src_ystride);
3155
750
              avg_sad += tmp_sad;
3156
750
              num_samples++;
3157
750
              if (tmp_sad == 0) num_zero_temp_sad++;
3158
750
            }
3159
45.4k
            src_y += 64;
3160
45.4k
            last_src_y += 64;
3161
45.4k
          }
3162
37.7k
          src_y += (src_ystride << 6) - (sb_cols << 6);
3163
37.7k
          last_src_y += (last_src_ystride << 6) - (sb_cols << 6);
3164
37.7k
        }
3165
35.4k
        if (num_samples > 0) avg_sad = avg_sad / num_samples;
3166
        // Set high_source_sad flag if we detect very high increase in avg_sad
3167
        // between current and previous frame value(s). Use minimum threshold
3168
        // for cases where there is small change from content that is completely
3169
        // static.
3170
35.4k
        if (lagframe_idx == 0) {
3171
0
          if (avg_sad >
3172
0
                  VPXMAX(min_thresh,
3173
0
                         (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
3174
0
              rc->frames_since_key > 1 + cpi->svc.number_spatial_layers &&
3175
0
              num_zero_temp_sad < 3 * (num_samples >> 2))
3176
0
            rc->high_source_sad = 1;
3177
0
          else
3178
0
            rc->high_source_sad = 0;
3179
0
          if (rc->high_source_sad && avg_sad > thresh_key)
3180
0
            scene_cut_force_key_frame = 1;
3181
0
          if (avg_sad > 0 || cpi->oxcf.rc_mode == VPX_CBR)
3182
0
            rc->avg_source_sad[0] = (3 * rc->avg_source_sad[0] + avg_sad) >> 2;
3183
35.4k
        } else {
3184
35.4k
          rc->avg_source_sad[lagframe_idx] = avg_sad;
3185
35.4k
        }
3186
35.4k
        if (num_zero_temp_sad < (3 * num_samples >> 2))
3187
105
          rc->high_num_blocks_with_motion = 1;
3188
35.4k
      }
3189
64.8k
    }
3190
    // For CBR non-screen content mode, check if we should reset the rate
3191
    // control. Reset is done if high_source_sad is detected and the rate
3192
    // control is at very low QP with rate correction factor at min level.
3193
27.8k
    if (cpi->oxcf.rc_mode == VPX_CBR &&
3194
0
        cpi->oxcf.content != VP9E_CONTENT_SCREEN && !cpi->use_svc) {
3195
0
      if (rc->high_source_sad && rc->last_q[INTER_FRAME] == rc->best_quality &&
3196
0
          rc->avg_frame_qindex[INTER_FRAME] < (rc->best_quality << 1) &&
3197
0
          rc->rate_correction_factors[INTER_NORMAL] == MIN_BPB_FACTOR) {
3198
0
        rc->rate_correction_factors[INTER_NORMAL] = 0.5;
3199
0
        rc->avg_frame_qindex[INTER_FRAME] = rc->worst_quality;
3200
0
        rc->buffer_level = rc->optimal_buffer_level;
3201
0
        rc->bits_off_target = rc->optimal_buffer_level;
3202
0
        rc->reset_high_source_sad = 1;
3203
0
      }
3204
0
      if (cm->frame_type != KEY_FRAME && rc->reset_high_source_sad)
3205
0
        rc->this_frame_target = rc->avg_frame_bandwidth;
3206
0
    }
3207
    // For SVC the new (updated) avg_source_sad[0] for the current superframe
3208
    // updates the setting for all layers.
3209
27.8k
    if (cpi->use_svc) {
3210
0
      int sl, tl;
3211
0
      SVC *const svc = &cpi->svc;
3212
0
      for (sl = 0; sl < svc->number_spatial_layers; ++sl)
3213
0
        for (tl = 0; tl < svc->number_temporal_layers; ++tl) {
3214
0
          int layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
3215
0
          LAYER_CONTEXT *const lc = &svc->layer_context[layer];
3216
0
          RATE_CONTROL *const lrc = &lc->rc;
3217
0
          lrc->avg_source_sad[0] = rc->avg_source_sad[0];
3218
0
        }
3219
0
    }
3220
    // For VBR, under scene change/high content change, force golden refresh.
3221
27.8k
    if (cpi->oxcf.rc_mode == VPX_VBR && cm->frame_type != KEY_FRAME &&
3222
22.7k
        rc->high_source_sad && rc->frames_to_key > 3 &&
3223
0
        rc->count_last_scene_change > 4 &&
3224
0
        cpi->ext_refresh_frame_flags_pending == 0) {
3225
0
      int target;
3226
0
      cpi->refresh_golden_frame = 1;
3227
0
      if (scene_cut_force_key_frame) cm->frame_type = KEY_FRAME;
3228
0
      rc->source_alt_ref_pending = 0;
3229
0
      if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf)
3230
0
        rc->source_alt_ref_pending = 1;
3231
0
      rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
3232
0
      rc->baseline_gf_interval =
3233
0
          VPXMIN(20, VPXMAX(10, rc->baseline_gf_interval));
3234
0
      adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
3235
0
      rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3236
0
      target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
3237
0
      vp9_rc_set_frame_target(cpi, target);
3238
0
      rc->count_last_scene_change = 0;
3239
27.8k
    } else {
3240
27.8k
      rc->count_last_scene_change++;
3241
27.8k
    }
3242
    // If lag_in_frame is used, set the gf boost and interval.
3243
27.8k
    if (cpi->oxcf.lag_in_frames > 0)
3244
27.8k
      adjust_gf_boost_lag_one_pass_vbr(cpi, avg_sad_current);
3245
27.8k
  }
3246
27.8k
}
3247
3248
// Test if encoded frame will significantly overshoot the target bitrate, and
3249
// if so, set the QP, reset/adjust some rate control parameters, and return 1.
3250
// frame_size = -1 means frame has not been encoded.
3251
0
int vp9_encodedframe_overshoot(VP9_COMP *cpi, int frame_size, int *q) {
3252
0
  VP9_COMMON *const cm = &cpi->common;
3253
0
  RATE_CONTROL *const rc = &cpi->rc;
3254
0
  SPEED_FEATURES *const sf = &cpi->sf;
3255
0
  int thresh_qp = 7 * (rc->worst_quality >> 3);
3256
0
  int thresh_rate = rc->avg_frame_bandwidth << 3;
3257
  // Lower thresh_qp for video (more overshoot at lower Q) to be
3258
  // more conservative for video.
3259
0
  if (cpi->oxcf.content != VP9E_CONTENT_SCREEN)
3260
0
    thresh_qp = 3 * (rc->worst_quality >> 2);
3261
  // If this decision is not based on an encoded frame size but just on
3262
  // scene/slide change detection (i.e., re_encode_overshoot_cbr_rt ==
3263
  // FAST_DETECTION_MAXQ), for now skip the (frame_size > thresh_rate)
3264
  // condition in this case.
3265
  // TODO(marpan): Use a better size/rate condition for this case and
3266
  // adjust thresholds.
3267
0
  if ((sf->overshoot_detection_cbr_rt == FAST_DETECTION_MAXQ ||
3268
0
       frame_size > thresh_rate) &&
3269
0
      cm->base_qindex < thresh_qp) {
3270
0
    double rate_correction_factor =
3271
0
        cpi->rc.rate_correction_factors[INTER_NORMAL];
3272
0
    const int target_size = cpi->rc.avg_frame_bandwidth;
3273
0
    const uint64_t sad_thr = 64 * 64 * 32;
3274
0
    int force_maxqp = 1;
3275
0
    double new_correction_factor;
3276
0
    int target_bits_per_mb;
3277
0
    double q2;
3278
0
    int enumerator;
3279
    // Set a larger QP.
3280
0
    if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
3281
0
        (rc->buffer_level > (3 * rc->optimal_buffer_level) >> 2) &&
3282
0
        (cpi->rc.avg_source_sad[0] < sad_thr)) {
3283
0
      *q = (*q + cpi->rc.worst_quality) >> 1;
3284
0
      force_maxqp = 0;
3285
0
    } else {
3286
0
      *q = cpi->rc.worst_quality;
3287
0
    }
3288
0
    cpi->cyclic_refresh->counter_encode_maxq_scene_change = 0;
3289
0
    cpi->rc.re_encode_maxq_scene_change = 1;
3290
    // If the frame_size is much larger than the threshold (big content change)
3291
    // and the encoded frame used alot of Intra modes, then force hybrid_intra
3292
    // encoding for the re-encode on this scene change. hybrid_intra will
3293
    // use rd-based intra mode selection for small blocks.
3294
0
    if (sf->overshoot_detection_cbr_rt == RE_ENCODE_MAXQ &&
3295
0
        frame_size > (thresh_rate << 1) && cpi->svc.spatial_layer_id == 0) {
3296
0
      MODE_INFO **mi = cm->mi_grid_visible;
3297
0
      int sum_intra_usage = 0;
3298
0
      int mi_row, mi_col;
3299
0
      for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
3300
0
        for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
3301
0
          if (mi[0]->ref_frame[0] == INTRA_FRAME) sum_intra_usage++;
3302
0
          mi++;
3303
0
        }
3304
0
        mi += 8;
3305
0
      }
3306
0
      sum_intra_usage = 100 * sum_intra_usage / (cm->mi_rows * cm->mi_cols);
3307
0
      if (sum_intra_usage > 60) cpi->rc.hybrid_intra_scene_change = 1;
3308
0
    }
3309
    // Adjust avg_frame_qindex, buffer_level, and rate correction factors, as
3310
    // these parameters will affect QP selection for subsequent frames. If they
3311
    // have settled down to a very different (low QP) state, then not adjusting
3312
    // them may cause next frame to select low QP and overshoot again.
3313
0
    cpi->rc.avg_frame_qindex[INTER_FRAME] = *q;
3314
0
    rc->buffer_level = rc->optimal_buffer_level;
3315
0
    rc->bits_off_target = rc->optimal_buffer_level;
3316
    // Reset rate under/over-shoot flags.
3317
0
    cpi->rc.rc_1_frame = 0;
3318
0
    cpi->rc.rc_2_frame = 0;
3319
    // Adjust rate correction factor.
3320
0
    target_bits_per_mb =
3321
0
        (int)(((uint64_t)target_size << BPER_MB_NORMBITS) / cm->MBs);
3322
    // Rate correction factor based on target_bits_per_mb and qp (==max_QP).
3323
    // This comes from the inverse computation of vp9_rc_bits_per_mb().
3324
0
    q2 = vp9_convert_qindex_to_q(*q, cm->bit_depth);
3325
0
    enumerator = 1800000;  // Factor for inter frame.
3326
0
    enumerator += (int)(enumerator * q2) >> 12;
3327
0
    new_correction_factor = (double)target_bits_per_mb * q2 / enumerator;
3328
0
    if (new_correction_factor > rate_correction_factor) {
3329
0
      rate_correction_factor =
3330
0
          VPXMIN(2.0 * rate_correction_factor, new_correction_factor);
3331
0
      if (rate_correction_factor > MAX_BPB_FACTOR)
3332
0
        rate_correction_factor = MAX_BPB_FACTOR;
3333
0
      cpi->rc.rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
3334
0
    }
3335
    // For temporal layers, reset the rate control parametes across all
3336
    // temporal layers.
3337
    // If the first_spatial_layer_to_encode > 0, then this superframe has
3338
    // skipped lower base layers. So in this case we should also reset and
3339
    // force max-q for spatial layers < first_spatial_layer_to_encode.
3340
    // For the case of no inter-layer prediction on delta frames: reset and
3341
    // force max-q for all spatial layers, to avoid excessive frame drops.
3342
0
    if (cpi->use_svc) {
3343
0
      int tl = 0;
3344
0
      int sl = 0;
3345
0
      SVC *svc = &cpi->svc;
3346
0
      int num_spatial_layers = VPXMAX(1, svc->first_spatial_layer_to_encode);
3347
0
      if (svc->disable_inter_layer_pred != INTER_LAYER_PRED_ON)
3348
0
        num_spatial_layers = svc->number_spatial_layers;
3349
0
      for (sl = 0; sl < num_spatial_layers; ++sl) {
3350
0
        for (tl = 0; tl < svc->number_temporal_layers; ++tl) {
3351
0
          const int layer =
3352
0
              LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
3353
0
          LAYER_CONTEXT *lc = &svc->layer_context[layer];
3354
0
          RATE_CONTROL *lrc = &lc->rc;
3355
0
          lrc->avg_frame_qindex[INTER_FRAME] = *q;
3356
0
          lrc->buffer_level = lrc->optimal_buffer_level;
3357
0
          lrc->bits_off_target = lrc->optimal_buffer_level;
3358
0
          lrc->rc_1_frame = 0;
3359
0
          lrc->rc_2_frame = 0;
3360
0
          lrc->rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
3361
0
          lrc->force_max_q = force_maxqp;
3362
0
        }
3363
0
      }
3364
0
    }
3365
0
    return 1;
3366
0
  } else {
3367
0
    return 0;
3368
0
  }
3369
0
}