Coverage Report

Created: 2026-12-01 07:01

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
2.02M
#define MIN_BPB_FACTOR 0.005
56
2.02M
#define MAX_BPB_FACTOR 50
57
58
#if CONFIG_VP9_HIGHBITDEPTH
59
#define ASSIGN_MINQ_TABLE(bit_depth, name)       \
60
807k
  do {                                           \
61
807k
    switch (bit_depth) {                         \
62
807k
      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
807k
    }                                            \
69
807k
  } 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
9.21k
                          vpx_bit_depth_t bit_depth) {
119
9.21k
  int i;
120
9.21k
  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
9.21k
  if (minqtarget <= 2.0) return 0;
125
126
742k
  for (i = 0; i < QINDEX_RANGE; i++) {
127
742k
    if (minqtarget <= vp9_convert_qindex_to_q(i, bit_depth)) return i;
128
742k
  }
129
130
0
  return QINDEX_RANGE - 1;
131
8.39k
}
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
6
                           vpx_bit_depth_t bit_depth) {
136
6
  int i;
137
1.54k
  for (i = 0; i < QINDEX_RANGE; i++) {
138
1.53k
    const double maxq = vp9_convert_qindex_to_q(i, bit_depth);
139
1.53k
    kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
140
1.53k
    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
1.53k
    arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
146
1.53k
    inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
147
1.53k
#endif
148
1.53k
    arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
149
1.53k
    rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
150
1.53k
  }
151
6
}
152
153
2
void vp9_rc_init_minq_luts(void) {
154
2
  init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
155
2
                 arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
156
2
                 inter_minq_8, rtc_minq_8, VPX_BITS_8);
157
2
#if CONFIG_VP9_HIGHBITDEPTH
158
2
  init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
159
2
                 arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
160
2
                 inter_minq_10, rtc_minq_10, VPX_BITS_10);
161
2
  init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
162
2
                 arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
163
2
                 inter_minq_12, rtc_minq_12, VPX_BITS_12);
164
2
#endif
165
2
}
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
28.0M
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
28.0M
#if CONFIG_VP9_HIGHBITDEPTH
173
28.0M
  switch (bit_depth) {
174
27.5M
    case VPX_BITS_8: return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
175
250k
    case VPX_BITS_10: return vp9_ac_quant(qindex, 0, bit_depth) / 16.0;
176
252k
    default:
177
252k
      assert(bit_depth == VPX_BITS_12);
178
252k
      return vp9_ac_quant(qindex, 0, bit_depth) / 64.0;
179
28.0M
  }
180
#else
181
  return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
182
#endif
183
28.0M
}
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
23.2M
                       double correction_factor, vpx_bit_depth_t bit_depth) {
198
23.2M
  const double q = vp9_convert_qindex_to_q(qindex, bit_depth);
199
23.2M
  int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
200
201
23.2M
  assert(correction_factor <= MAX_BPB_FACTOR &&
202
23.2M
         correction_factor >= MIN_BPB_FACTOR);
203
204
  // q based adjustment to baseline enumerator
205
23.2M
  enumerator += (int)(enumerator * q) >> 12;
206
23.2M
  return (int)(enumerator * correction_factor / q);
207
23.2M
}
208
209
int vp9_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
210
                           double correction_factor,
211
611k
                           vpx_bit_depth_t bit_depth) {
212
611k
  const int bpm =
213
611k
      (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor, bit_depth));
214
611k
  return VPXMAX(FRAME_OVERHEAD_BITS,
215
611k
                (int)(((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS));
216
611k
}
217
218
601k
int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
219
601k
  const RATE_CONTROL *rc = &cpi->rc;
220
601k
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
221
222
601k
  const int min_frame_target =
223
601k
      VPXMAX(rc->min_frame_bandwidth, rc->avg_frame_bandwidth >> 5);
224
601k
  if (target < min_frame_target) target = min_frame_target;
225
601k
  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
22.1k
    target = min_frame_target;
231
22.1k
  }
232
233
  // Clip the frame target to the maximum allowed value.
234
601k
  if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
235
236
601k
  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
601k
  return target;
243
601k
}
244
245
42.4k
int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
246
42.4k
  const RATE_CONTROL *rc = &cpi->rc;
247
42.4k
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
248
42.4k
  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
42.4k
  if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
254
42.4k
  return target;
255
42.4k
}
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
612k
void vp9_update_buffer_level_preencode(VP9_COMP *cpi) {
262
612k
  RATE_CONTROL *const rc = &cpi->rc;
263
612k
  rc->bits_off_target += rc->avg_frame_bandwidth;
264
  // Clip the buffer level to the maximum specified buffer size.
265
612k
  rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
266
612k
  rc->buffer_level = rc->bits_off_target;
267
612k
}
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
625k
                                           int encoded_frame_size) {
331
625k
  RATE_CONTROL *const rc = &cpi->rc;
332
625k
  rc->bits_off_target -= encoded_frame_size;
333
  // Clip the buffer level to the maximum specified buffer size.
334
625k
  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
625k
  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
625k
  rc->buffer_level = rc->bits_off_target;
342
343
625k
  if (is_one_pass_svc(cpi)) {
344
0
    update_layer_buffer_level_postencode(&cpi->svc, encoded_frame_size);
345
0
  }
346
625k
}
347
348
int vp9_rc_get_default_min_gf_interval(int width, int height,
349
665k
                                       double framerate) {
350
  // Assume we do not need any constraint lower than 4K 20 fps
351
665k
  static const double factor_safe = 3840 * 2160 * 20.0;
352
665k
  const double factor = width * height * framerate;
353
665k
  const int default_interval =
354
665k
      clamp((int)round(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
355
356
665k
  if (factor <= factor_safe)
357
665k
    return default_interval;
358
0
  else
359
0
    return VPXMAX(default_interval,
360
665k
                  (int)round(MIN_GF_INTERVAL * factor / factor_safe));
361
  // Note this logic makes:
362
  // 4K24: 5
363
  // 4K30: 6
364
  // 4K60: 12
365
665k
}
366
367
665k
int vp9_rc_get_default_max_gf_interval(double framerate, int min_gf_interval) {
368
665k
  int interval = VPXMIN(MAX_GF_INTERVAL, (int)round(framerate * 0.75));
369
665k
  interval += (interval & 0x01);  // Round to even value
370
665k
  return VPXMAX(interval, min_gf_interval);
371
665k
}
372
373
19.8k
void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
374
19.8k
  int i;
375
376
19.8k
  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
19.8k
  } else {
380
19.8k
    rc->avg_frame_qindex[KEY_FRAME] =
381
19.8k
        (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
382
19.8k
    rc->avg_frame_qindex[INTER_FRAME] =
383
19.8k
        (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
384
19.8k
  }
385
386
19.8k
  rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
387
19.8k
  rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
388
389
19.8k
  rc->buffer_level = rc->starting_buffer_level;
390
19.8k
  rc->bits_off_target = rc->starting_buffer_level;
391
392
19.8k
  rc->rolling_target_bits = rc->avg_frame_bandwidth;
393
19.8k
  rc->rolling_actual_bits = rc->avg_frame_bandwidth;
394
19.8k
  rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
395
19.8k
  rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
396
397
19.8k
  rc->total_actual_bits = 0;
398
19.8k
  rc->total_target_bits = 0;
399
19.8k
  rc->total_target_vs_actual = 0;
400
19.8k
  rc->avg_frame_low_motion = 0;
401
19.8k
  rc->count_last_scene_change = 0;
402
19.8k
  rc->af_ratio_onepass_vbr = 10;
403
19.8k
  rc->prev_avg_source_sad_lag = 0;
404
19.8k
  rc->high_source_sad = 0;
405
19.8k
  rc->reset_high_source_sad = 0;
406
19.8k
  rc->high_source_sad_lagindex = -1;
407
19.8k
  rc->high_num_blocks_with_motion = 0;
408
19.8k
  rc->hybrid_intra_scene_change = 0;
409
19.8k
  rc->re_encode_maxq_scene_change = 0;
410
19.8k
  rc->alt_ref_gf_group = 0;
411
19.8k
  rc->last_frame_is_src_altref = 0;
412
19.8k
  rc->fac_active_worst_inter = 150;
413
19.8k
  rc->fac_active_worst_gf = 100;
414
19.8k
  rc->force_qpmin = 0;
415
515k
  for (i = 0; i < MAX_LAG_BUFFERS; ++i) rc->avg_source_sad[i] = 0;
416
19.8k
  rc->frames_to_key = 0;
417
19.8k
  rc->frames_since_key = 8;  // Sensible default for first frame.
418
19.8k
  rc->this_key_frame_forced = 0;
419
19.8k
  rc->next_key_frame_forced = 0;
420
19.8k
  rc->source_alt_ref_pending = 0;
421
19.8k
  rc->source_alt_ref_active = 0;
422
423
19.8k
  rc->frames_till_gf_update_due = 0;
424
19.8k
  rc->constrain_gf_key_freq_onepass_vbr = 1;
425
19.8k
  rc->ni_av_qi = oxcf->worst_allowed_q;
426
19.8k
  rc->ni_tot_qi = 0;
427
19.8k
  rc->ni_frames = 0;
428
429
19.8k
  rc->tot_q = 0.0;
430
19.8k
  rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
431
432
118k
  for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
433
99.1k
    rc->rate_correction_factors[i] = 1.0;
434
99.1k
    rc->damped_adjustment[i] = 0;
435
99.1k
  }
436
437
19.8k
  rc->min_gf_interval = oxcf->min_gf_interval;
438
19.8k
  rc->max_gf_interval = oxcf->max_gf_interval;
439
19.8k
  if (rc->min_gf_interval == 0)
440
19.8k
    rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
441
19.8k
        oxcf->width, oxcf->height, oxcf->init_framerate);
442
19.8k
  if (rc->max_gf_interval == 0)
443
19.8k
    rc->max_gf_interval = vp9_rc_get_default_max_gf_interval(
444
19.8k
        oxcf->init_framerate, rc->min_gf_interval);
445
19.8k
  rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
446
19.8k
  if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
447
0
    rc->static_scene_max_gf_interval = FIXED_GF_INTERVAL;
448
19.8k
  } else {
449
19.8k
    rc->static_scene_max_gf_interval = MAX_STATIC_GF_GROUP_LENGTH;
450
19.8k
  }
451
452
19.8k
  rc->force_max_q = 0;
453
19.8k
  rc->last_post_encode_dropped_scene_change = 0;
454
19.8k
  rc->use_post_encode_drop = 0;
455
19.8k
  rc->ext_use_post_encode_drop = 0;
456
19.8k
  rc->disable_overshoot_maxq_cbr = 0;
457
19.8k
  rc->arf_active_best_quality_adjustment_factor = 1.0;
458
19.8k
  rc->arf_increase_active_best_quality = 0;
459
19.8k
  rc->preserve_arf_as_gld = 0;
460
19.8k
  rc->preserve_next_arf_as_gld = 0;
461
19.8k
  rc->show_arf_as_gld = 0;
462
19.8k
}
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
1.25M
static double get_rate_correction_factor(const VP9_COMP *cpi) {
703
1.25M
  const RATE_CONTROL *const rc = &cpi->rc;
704
1.25M
  const VP9_COMMON *const cm = &cpi->common;
705
1.25M
  double rcf;
706
707
1.25M
  if (frame_is_intra_only(cm)) {
708
83.7k
    rcf = rc->rate_correction_factors[KF_STD];
709
1.16M
  } 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
1.16M
  } else {
714
1.16M
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
715
126k
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
716
98.6k
        (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 100))
717
98.6k
      rcf = rc->rate_correction_factors[GF_ARF_STD];
718
1.06M
    else
719
1.06M
      rcf = rc->rate_correction_factors[INTER_NORMAL];
720
1.16M
  }
721
1.25M
  rcf *= rcf_mult[rc->frame_size_selector];
722
1.25M
  return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
723
1.25M
}
724
725
611k
static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
726
611k
  RATE_CONTROL *const rc = &cpi->rc;
727
611k
  const VP9_COMMON *const cm = &cpi->common;
728
729
  // Normalize RCF to account for the size-dependent scaling factor.
730
611k
  factor /= rcf_mult[cpi->rc.frame_size_selector];
731
732
611k
  factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
733
734
611k
  if (frame_is_intra_only(cm)) {
735
42.1k
    rc->rate_correction_factors[KF_STD] = factor;
736
569k
  } 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
569k
  } else {
741
569k
    if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
742
49.2k
        !rc->is_src_frame_alt_ref && !cpi->use_svc &&
743
49.2k
        (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 100))
744
49.2k
      rc->rate_correction_factors[GF_ARF_STD] = factor;
745
519k
    else
746
519k
      rc->rate_correction_factors[INTER_NORMAL] = factor;
747
569k
  }
748
611k
}
749
750
625k
void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi) {
751
625k
  const VP9_COMMON *const cm = &cpi->common;
752
625k
  int correction_factor = 100;
753
625k
  double rate_correction_factor = get_rate_correction_factor(cpi);
754
625k
  double adjustment_limit;
755
625k
  RATE_FACTOR_LEVEL rf_lvl =
756
625k
      cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
757
758
625k
  int projected_size_based_on_q = 0;
759
760
  // Do not update the rate factors for arf overlay frames.
761
625k
  if (cpi->rc.is_src_frame_alt_ref) return;
762
763
  // Clear down mmx registers to allow floating point in what follows
764
611k
  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
611k
  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
611k
  } else {
773
611k
    FRAME_TYPE frame_type = cm->intra_only ? KEY_FRAME : cm->frame_type;
774
611k
    projected_size_based_on_q =
775
611k
        vp9_estimate_bits_at_q(frame_type, cm->base_qindex, cm->MBs,
776
611k
                               rate_correction_factor, cm->bit_depth);
777
611k
  }
778
  // Work out a size correction factor.
779
611k
  if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
780
347k
    correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
781
347k
                              projected_size_based_on_q);
782
783
  // Do not use damped adjustment for the first frame of each frame type
784
611k
  if (!cpi->rc.damped_adjustment[rf_lvl]) {
785
19.8k
    adjustment_limit = 1.0;
786
19.8k
    cpi->rc.damped_adjustment[rf_lvl] = 1;
787
591k
  } else {
788
    // More heavily damped adjustment used if we have been oscillating either
789
    // side of target.
790
591k
    adjustment_limit =
791
591k
        0.25 + 0.5 * VPXMIN(1, fabs(log10(0.01 * correction_factor)));
792
591k
  }
793
794
611k
  cpi->rc.q_2_frame = cpi->rc.q_1_frame;
795
611k
  cpi->rc.q_1_frame = cm->base_qindex;
796
611k
  cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
797
611k
  if (correction_factor > 110)
798
133k
    cpi->rc.rc_1_frame = -1;
799
478k
  else if (correction_factor < 90)
800
131k
    cpi->rc.rc_1_frame = 1;
801
346k
  else
802
346k
    cpi->rc.rc_1_frame = 0;
803
804
  // Turn off oscilation detection in the case of massive overshoot.
805
611k
  if (cpi->rc.rc_1_frame == -1 && cpi->rc.rc_2_frame == 1 &&
806
30.6k
      correction_factor > 1000) {
807
1.14k
    cpi->rc.rc_2_frame = 0;
808
1.14k
  }
809
810
611k
  if (correction_factor > 102) {
811
    // We are not already at the worst allowable quality
812
167k
    correction_factor =
813
167k
        (int)(100 + ((correction_factor - 100) * adjustment_limit));
814
167k
    rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
815
    // Keep rate_correction_factor within limits
816
167k
    if (rate_correction_factor > MAX_BPB_FACTOR)
817
380
      rate_correction_factor = MAX_BPB_FACTOR;
818
444k
  } else if (correction_factor < 99) {
819
    // We are not already at the best allowable quality
820
162k
    correction_factor =
821
162k
        (int)(100 - ((100 - correction_factor) * adjustment_limit));
822
162k
    rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
823
824
    // Keep rate_correction_factor within limits
825
162k
    if (rate_correction_factor < MIN_BPB_FACTOR)
826
3.06k
      rate_correction_factor = MIN_BPB_FACTOR;
827
162k
  }
828
829
611k
  set_rate_correction_factor(cpi, rate_correction_factor);
830
611k
}
831
832
int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
833
625k
                      int active_best_quality, int active_worst_quality) {
834
625k
  const VP9_COMMON *const cm = &cpi->common;
835
625k
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
836
625k
  int q = active_worst_quality;
837
625k
  int last_error = INT_MAX;
838
625k
  int i, target_bits_per_mb, bits_per_mb_at_this_q;
839
625k
  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
625k
  target_bits_per_mb =
844
625k
      (int)(((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs);
845
846
625k
  i = active_best_quality;
847
848
12.8M
  do {
849
12.8M
    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
12.8M
    } else {
854
12.8M
      FRAME_TYPE frame_type = cm->intra_only ? KEY_FRAME : cm->frame_type;
855
12.8M
      bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(
856
12.8M
          frame_type, i, correction_factor, cm->bit_depth);
857
12.8M
    }
858
859
12.8M
    int diff_bits = (int)VPXMIN(
860
12.8M
        VPXMAX(((int64_t)target_bits_per_mb - (int64_t)bits_per_mb_at_this_q),
861
12.8M
               -INT_MAX),
862
12.8M
        INT_MAX);
863
12.8M
    if (bits_per_mb_at_this_q <= target_bits_per_mb) {
864
579k
      if (diff_bits <= last_error)
865
489k
        q = i;
866
90.2k
      else
867
90.2k
        q = i - 1;
868
869
579k
      break;
870
12.2M
    } else {
871
12.2M
      last_error = -diff_bits;
872
12.2M
    }
873
12.8M
  } while (++i <= active_worst_quality);
874
875
  // Adjustment to q for CBR mode.
876
625k
  if (cpi->oxcf.rc_mode == VPX_CBR) return adjust_q_cbr(cpi, q);
877
878
625k
  return q;
879
625k
}
880
881
static int get_active_quality(int q, int gfu_boost, int low, int high,
882
90.7k
                              int *low_motion_minq, int *high_motion_minq) {
883
90.7k
  if (gfu_boost > high) {
884
0
    return low_motion_minq[q];
885
90.7k
  } else if (gfu_boost < low) {
886
0
    return high_motion_minq[q];
887
90.7k
  } else {
888
90.7k
    const int gap = high - low;
889
90.7k
    const int offset = high - gfu_boost;
890
90.7k
    const int qdiff = high_motion_minq[q] - low_motion_minq[q];
891
90.7k
    const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
892
90.7k
    return low_motion_minq[q] + adjustment;
893
90.7k
  }
894
90.7k
}
895
896
static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
897
41.3k
                                 vpx_bit_depth_t bit_depth) {
898
41.3k
  int *kf_low_motion_minq;
899
41.3k
  int *kf_high_motion_minq;
900
41.3k
  ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
901
41.3k
  ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
902
41.3k
  return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
903
41.3k
                            kf_low_motion_minq, kf_high_motion_minq);
904
41.3k
}
905
906
static int get_gf_active_quality(const VP9_COMP *const cpi, int q,
907
49.3k
                                 vpx_bit_depth_t bit_depth) {
908
49.3k
  const GF_GROUP *const gf_group = &cpi->twopass.gf_group;
909
49.3k
  const RATE_CONTROL *const rc = &cpi->rc;
910
911
49.3k
  int *arfgf_low_motion_minq;
912
49.3k
  int *arfgf_high_motion_minq;
913
49.3k
  const int gfu_boost = cpi->multi_layer_arf
914
49.3k
                            ? gf_group->gfu_boost[gf_group->index]
915
49.3k
                            : rc->gfu_boost;
916
49.3k
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
917
49.3k
  ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
918
49.3k
  return get_active_quality(q, gfu_boost, gf_low, gf_high,
919
49.3k
                            arfgf_low_motion_minq, arfgf_high_motion_minq);
920
49.3k
}
921
922
626k
static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
923
626k
  const RATE_CONTROL *const rc = &cpi->rc;
924
626k
  const unsigned int curr_frame = cpi->common.current_video_frame;
925
626k
  int active_worst_quality;
926
927
626k
  if (cpi->common.frame_type == KEY_FRAME) {
928
42.4k
    active_worst_quality =
929
42.4k
        curr_frame == 0 ? rc->worst_quality : rc->last_q[KEY_FRAME] << 1;
930
583k
  } else {
931
583k
    if (!rc->is_src_frame_alt_ref && !cpi->use_svc &&
932
569k
        (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
933
49.3k
      active_worst_quality =
934
49.3k
          curr_frame == 1
935
49.3k
              ? rc->last_q[KEY_FRAME] * 5 >> 2
936
49.3k
              : rc->last_q[INTER_FRAME] * rc->fac_active_worst_gf / 100;
937
534k
    } else {
938
534k
      active_worst_quality = curr_frame == 1
939
534k
                                 ? rc->last_q[KEY_FRAME] << 1
940
534k
                                 : rc->avg_frame_qindex[INTER_FRAME] *
941
517k
                                       rc->fac_active_worst_inter / 100;
942
534k
    }
943
583k
  }
944
626k
  return VPXMIN(active_worst_quality, rc->worst_quality);
945
626k
}
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 = clamp(rc->last_boosted_qindex, rc->best_quality, rc->worst_quality);
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
626k
                                        const VP9EncoderConfig *const oxcf) {
1121
626k
  static const double cq_adjust_threshold = 0.1;
1122
626k
  int active_cq_level = oxcf->cq_level;
1123
626k
  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
626k
  return active_cq_level;
1130
626k
}
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
626k
                                             int *top_index) {
1158
626k
  const VP9_COMMON *const cm = &cpi->common;
1159
626k
  const RATE_CONTROL *const rc = &cpi->rc;
1160
626k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1161
626k
  const int cq_level = get_active_cq_level_one_pass(rc, oxcf);
1162
626k
  int active_best_quality;
1163
626k
  int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
1164
626k
  int q;
1165
626k
  int *inter_minq;
1166
626k
  ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
1167
1168
626k
  if (frame_is_intra_only(cm)) {
1169
42.4k
    if (oxcf->rc_mode == VPX_Q) {
1170
0
      int qindex = cq_level;
1171
0
      double qstart = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1172
0
      int delta_qindex =
1173
0
          vp9_compute_qdelta(rc, qstart, qstart * 0.25, cm->bit_depth);
1174
0
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1175
42.4k
    } 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
1.10k
      int qindex = rc->last_boosted_qindex;
1180
1.10k
      double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1181
1.10k
      int delta_qindex = vp9_compute_qdelta(
1182
1.10k
          rc, last_boosted_q, last_boosted_q * 0.75, cm->bit_depth);
1183
1.10k
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1184
41.3k
    } else {
1185
      // not first frame of one pass and kf_boost is set
1186
41.3k
      double q_adj_factor = 1.0;
1187
41.3k
      double q_val;
1188
1189
41.3k
      active_best_quality = get_kf_active_quality(
1190
41.3k
          rc, rc->avg_frame_qindex[KEY_FRAME], cm->bit_depth);
1191
1192
      // Allow somewhat lower kf minq with small image formats.
1193
41.3k
      if ((cm->width * cm->height) <= (352 * 288)) {
1194
41.3k
        q_adj_factor -= 0.25;
1195
41.3k
      }
1196
1197
      // Convert the adjustment factor to a qindex delta
1198
      // on active_best_quality.
1199
41.3k
      q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1200
41.3k
      active_best_quality +=
1201
41.3k
          vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
1202
41.3k
    }
1203
583k
  } else if (!rc->is_src_frame_alt_ref &&
1204
569k
             (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
49.3k
    if (rc->frames_since_key > 1) {
1209
43.0k
      if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1210
9.26k
        q = rc->avg_frame_qindex[INTER_FRAME];
1211
33.8k
      } else {
1212
33.8k
        q = active_worst_quality;
1213
33.8k
      }
1214
43.0k
    } else {
1215
6.27k
      q = rc->avg_frame_qindex[KEY_FRAME];
1216
6.27k
    }
1217
    // For constrained quality don't allow Q less than the cq level
1218
49.3k
    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
49.3k
    } else if (oxcf->rc_mode == VPX_Q) {
1227
0
      int qindex = cq_level;
1228
0
      double qstart = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1229
0
      int delta_qindex;
1230
0
      if (cpi->refresh_alt_ref_frame)
1231
0
        delta_qindex =
1232
0
            vp9_compute_qdelta(rc, qstart, qstart * 0.40, cm->bit_depth);
1233
0
      else
1234
0
        delta_qindex =
1235
0
            vp9_compute_qdelta(rc, qstart, qstart * 0.50, cm->bit_depth);
1236
0
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1237
49.3k
    } else {
1238
49.3k
      active_best_quality = get_gf_active_quality(cpi, q, cm->bit_depth);
1239
49.3k
    }
1240
534k
  } else {
1241
534k
    if (oxcf->rc_mode == VPX_Q) {
1242
0
      int qindex = cq_level;
1243
0
      double qstart = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1244
0
      double delta_rate[FIXED_GF_INTERVAL] = { 0.50, 1.0, 0.85, 1.0,
1245
0
                                               0.70, 1.0, 0.85, 1.0 };
1246
0
      int delta_qindex = vp9_compute_qdelta(
1247
0
          rc, qstart,
1248
0
          qstart * delta_rate[cm->current_video_frame % FIXED_GF_INTERVAL],
1249
0
          cm->bit_depth);
1250
0
      active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1251
534k
    } else {
1252
      // Use the min of the average Q and active_worst_quality as basis for
1253
      // active_best.
1254
534k
      if (cm->current_video_frame > 1) {
1255
517k
        q = VPXMIN(rc->avg_frame_qindex[INTER_FRAME], active_worst_quality);
1256
517k
        active_best_quality = inter_minq[q];
1257
517k
      } else {
1258
17.0k
        active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
1259
17.0k
      }
1260
      // For the constrained quality mode we don't want
1261
      // q to fall below the cq level.
1262
534k
      if ((oxcf->rc_mode == VPX_CQ) && (active_best_quality < cq_level)) {
1263
0
        active_best_quality = cq_level;
1264
0
      }
1265
534k
    }
1266
534k
  }
1267
1268
  // Clip the active best and worst quality values to limits
1269
626k
  active_best_quality =
1270
626k
      clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1271
626k
  active_worst_quality =
1272
626k
      clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1273
1274
626k
  *top_index = active_worst_quality;
1275
626k
  *bottom_index = active_best_quality;
1276
1277
626k
#if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
1278
626k
  {
1279
626k
    int qdelta = 0;
1280
626k
    vpx_clear_system_state();
1281
1282
    // Limit Q range for the adaptive loop.
1283
626k
    if (cm->frame_type == KEY_FRAME && !rc->this_key_frame_forced &&
1284
41.3k
        !(cm->current_video_frame == 0)) {
1285
21.5k
      qdelta = vp9_compute_qdelta_by_rate(
1286
21.5k
          &cpi->rc, cm->frame_type, active_worst_quality, 2.0, cm->bit_depth);
1287
604k
    } else if (!rc->is_src_frame_alt_ref &&
1288
590k
               (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1289
70.1k
      qdelta = vp9_compute_qdelta_by_rate(
1290
70.1k
          &cpi->rc, cm->frame_type, active_worst_quality, 1.75, cm->bit_depth);
1291
70.1k
    }
1292
626k
    if (rc->high_source_sad && cpi->sf.use_altref_onepass) qdelta = 0;
1293
626k
    *top_index = active_worst_quality + qdelta;
1294
626k
    *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
1295
626k
  }
1296
626k
#endif
1297
1298
626k
  if (oxcf->rc_mode == VPX_Q) {
1299
0
    q = active_best_quality;
1300
    // Special case code to try and match quality with forced key frames
1301
626k
  } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
1302
1.10k
    q = clamp(rc->last_boosted_qindex, rc->best_quality, rc->worst_quality);
1303
625k
  } else {
1304
625k
    q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1305
625k
                          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
625k
    const int qp_thresh = 32;
1317
625k
    const int64_t bitrate_err =
1318
625k
        (int64_t)(cpi->framerate *
1319
625k
                  (rc->buffer_level - rc->starting_buffer_level -
1320
625k
                   rc->avg_frame_bandwidth) /
1321
625k
                  (cm->current_video_frame + 1));
1322
    // Threshold may be tuned, but for now condition this on low QP.
1323
625k
    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
625k
    if (q > *top_index) {
1331
      // Special case when we are targeting the max allowed rate
1332
21.6k
      if (rc->this_frame_target >= rc->max_frame_bandwidth)
1333
0
        *top_index = q;
1334
21.6k
      else
1335
21.6k
        q = *top_index;
1336
21.6k
    }
1337
625k
  }
1338
1339
626k
  assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1340
626k
  assert(*bottom_index <= rc->worst_quality &&
1341
626k
         *bottom_index >= rc->best_quality);
1342
626k
  assert(q <= rc->worst_quality && q >= rc->best_quality);
1343
626k
  return q;
1344
626k
}
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
626k
                             int *top_index) {
1629
626k
  int q;
1630
626k
  const int gf_group_index = cpi->twopass.gf_group.index;
1631
626k
  if (cpi->oxcf.pass == 0) {
1632
626k
    if (cpi->oxcf.rc_mode == VPX_CBR)
1633
0
      q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
1634
626k
    else
1635
626k
      q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
1636
626k
  } 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
626k
  if (cpi->sf.use_nonrd_pick_mode) {
1641
343k
    if (cpi->sf.force_frame_boost == 1)
1642
101k
      q = VPXMAX(q - cpi->sf.max_delta_qindex, cpi->rc.best_quality);
1643
343k
    if (q < *bottom_index)
1644
0
      *bottom_index = q;
1645
343k
    else if (q > *top_index)
1646
120
      *top_index = q;
1647
343k
  }
1648
626k
  return q;
1649
626k
}
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
643k
void vp9_rc_set_frame_target(VP9_COMP *cpi, int target) {
1729
643k
  const VP9_COMMON *const cm = &cpi->common;
1730
643k
  RATE_CONTROL *const rc = &cpi->rc;
1731
1732
643k
  rc->this_frame_target = target;
1733
1734
  // Modify frame size target when down-scaling.
1735
643k
  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
643k
  const int64_t sb64_target_rate =
1743
643k
      ((int64_t)rc->this_frame_target * 64 * 64) / (cm->width * cm->height);
1744
643k
  rc->sb64_target_rate = (int)VPXMIN(sb64_target_rate, INT_MAX);
1745
643k
}
1746
1747
14.0k
static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
1748
  // this frame refreshes means next frames don't unless specified by user
1749
14.0k
  RATE_CONTROL *const rc = &cpi->rc;
1750
14.0k
  rc->frames_since_golden = 0;
1751
1752
  // Mark the alt ref as done (setting to 0 means no further alt refs pending).
1753
14.0k
  rc->source_alt_ref_pending = 0;
1754
1755
  // Set the alternate reference frame active flag
1756
14.0k
  rc->source_alt_ref_active = 1;
1757
14.0k
}
1758
1759
611k
static void update_golden_frame_stats(VP9_COMP *cpi) {
1760
611k
  RATE_CONTROL *const rc = &cpi->rc;
1761
1762
  // Update the Golden frame usage counts.
1763
611k
  if (cpi->refresh_golden_frame) {
1764
    // this frame refreshes means next frames don't unless specified by user
1765
91.3k
    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
91.3k
    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
91.3k
    } else if (!rc->source_alt_ref_pending) {
1774
65.6k
      rc->source_alt_ref_active = 0;
1775
65.6k
    }
1776
1777
    // Decrement count down till next gf
1778
91.3k
    if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1779
1780
519k
  } else if (!cpi->refresh_alt_ref_frame) {
1781
    // Decrement count down till next gf
1782
519k
    if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1783
1784
519k
    rc->frames_since_golden++;
1785
1786
519k
    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
519k
  }
1795
611k
}
1796
1797
317k
static void update_altref_usage(VP9_COMP *const cpi) {
1798
317k
  VP9_COMMON *const cm = &cpi->common;
1799
317k
  int sum_ref_frame_usage = 0;
1800
317k
  int arf_frame_usage = 0;
1801
317k
  int mi_row, mi_col;
1802
317k
  if (cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
1803
170k
      !cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame &&
1804
152k
      cpi->count_arf_frame_usage != NULL &&
1805
152k
      cpi->count_lastgolden_frame_usage != NULL)
1806
304k
    for (mi_row = 0; mi_row < cm->mi_rows; mi_row += 8) {
1807
304k
      for (mi_col = 0; mi_col < cm->mi_cols; mi_col += 8) {
1808
152k
        int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1809
152k
        sum_ref_frame_usage += cpi->count_arf_frame_usage[sboffset] +
1810
152k
                               cpi->count_lastgolden_frame_usage[sboffset];
1811
152k
        arf_frame_usage += cpi->count_arf_frame_usage[sboffset];
1812
152k
      }
1813
152k
    }
1814
317k
  if (sum_ref_frame_usage > 0) {
1815
119k
    double altref_count = 100.0 * arf_frame_usage / sum_ref_frame_usage;
1816
119k
    cpi->rc.perc_arf_usage =
1817
119k
        0.75 * cpi->rc.perc_arf_usage + 0.25 * altref_count;
1818
119k
  }
1819
317k
}
1820
1821
582k
void vp9_compute_frame_low_motion(VP9_COMP *const cpi) {
1822
582k
  VP9_COMMON *const cm = &cpi->common;
1823
582k
  SVC *const svc = &cpi->svc;
1824
582k
  int mi_row, mi_col;
1825
582k
  MODE_INFO **mi = cm->mi_grid_visible;
1826
582k
  RATE_CONTROL *const rc = &cpi->rc;
1827
582k
  const int rows = cm->mi_rows, cols = cm->mi_cols;
1828
582k
  int cnt_zeromv = 0;
1829
2.18M
  for (mi_row = 0; mi_row < rows; mi_row++) {
1830
8.73M
    for (mi_col = 0; mi_col < cols; mi_col++) {
1831
7.12M
      if (mi[0]->ref_frame[0] == LAST_FRAME &&
1832
2.96M
          abs(mi[0]->mv[0].as_mv.row) < 16 && abs(mi[0]->mv[0].as_mv.col) < 16)
1833
1.57M
        cnt_zeromv++;
1834
7.12M
      mi++;
1835
7.12M
    }
1836
1.60M
    mi += 8;
1837
1.60M
  }
1838
582k
  cnt_zeromv = 100 * cnt_zeromv / (rows * cols);
1839
582k
  rc->avg_frame_low_motion = (3 * rc->avg_frame_low_motion + cnt_zeromv) >> 2;
1840
1841
  // For SVC: set avg_frame_low_motion (only computed on top spatial layer)
1842
  // to all lower spatial layers.
1843
582k
  if (cpi->use_svc && svc->spatial_layer_id == svc->number_spatial_layers - 1) {
1844
0
    int i;
1845
0
    for (i = 0; i < svc->number_spatial_layers - 1; ++i) {
1846
0
      const int layer = LAYER_IDS_TO_IDX(i, svc->temporal_layer_id,
1847
0
                                         svc->number_temporal_layers);
1848
0
      LAYER_CONTEXT *const lc = &svc->layer_context[layer];
1849
0
      RATE_CONTROL *const lrc = &lc->rc;
1850
0
      lrc->avg_frame_low_motion = rc->avg_frame_low_motion;
1851
0
    }
1852
0
  }
1853
582k
}
1854
1855
625k
void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
1856
625k
  const VP9_COMMON *const cm = &cpi->common;
1857
625k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1858
625k
  RATE_CONTROL *const rc = &cpi->rc;
1859
625k
  SVC *const svc = &cpi->svc;
1860
625k
  const int qindex = cm->base_qindex;
1861
625k
  const GF_GROUP *gf_group = &cpi->twopass.gf_group;
1862
625k
  const int gf_group_index = cpi->twopass.gf_group.index;
1863
625k
  const int layer_depth = gf_group->layer_depth[gf_group_index];
1864
1865
  // Update rate control heuristics
1866
625k
  rc->projected_frame_size = (int)(bytes_used << 3);
1867
1868
  // Post encode loop adjustment of Q prediction.
1869
625k
  vp9_rc_update_rate_correction_factors(cpi);
1870
1871
  // Keep a record of last Q and ambient average Q.
1872
625k
  if (frame_is_intra_only(cm)) {
1873
42.3k
    rc->last_q[KEY_FRAME] = qindex;
1874
42.3k
    rc->avg_frame_qindex[KEY_FRAME] =
1875
42.3k
        ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1876
42.3k
    if (cpi->use_svc) {
1877
0
      int i;
1878
0
      for (i = 0; i < svc->number_temporal_layers; ++i) {
1879
0
        const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
1880
0
                                           svc->number_temporal_layers);
1881
0
        LAYER_CONTEXT *lc = &svc->layer_context[layer];
1882
0
        RATE_CONTROL *lrc = &lc->rc;
1883
0
        lrc->last_q[KEY_FRAME] = rc->last_q[KEY_FRAME];
1884
0
        lrc->avg_frame_qindex[KEY_FRAME] = rc->avg_frame_qindex[KEY_FRAME];
1885
0
      }
1886
0
    }
1887
582k
  } else {
1888
582k
    if ((cpi->use_svc) ||
1889
582k
        (!rc->is_src_frame_alt_ref &&
1890
569k
         !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1891
519k
      rc->last_q[INTER_FRAME] = qindex;
1892
519k
      rc->avg_frame_qindex[INTER_FRAME] =
1893
519k
          ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1894
519k
      rc->ni_frames++;
1895
519k
      rc->tot_q += vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1896
519k
      rc->avg_q = rc->tot_q / rc->ni_frames;
1897
      // Calculate the average Q for normal inter frames (not key or GFU
1898
      // frames).
1899
519k
      rc->ni_tot_qi += qindex;
1900
519k
      rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1901
519k
    }
1902
582k
  }
1903
1904
625k
  if (cpi->use_svc) vp9_svc_adjust_avg_frame_qindex(cpi);
1905
1906
  // Keep record of last boosted (KF/KF/ARF) Q value.
1907
  // If the current frame is coded at a lower Q then we also update it.
1908
  // If all mbs in this group are skipped only update if the Q value is
1909
  // better than that already stored.
1910
  // This is used to help set quality in forced key frames to reduce popping
1911
625k
  if ((qindex < rc->last_boosted_qindex) || (cm->frame_type == KEY_FRAME) ||
1912
533k
      (!rc->constrained_gf_group &&
1913
517k
       (cpi->refresh_alt_ref_frame ||
1914
508k
        (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1915
121k
    rc->last_boosted_qindex = qindex;
1916
121k
  }
1917
1918
625k
  if ((qindex < cpi->twopass.last_qindex_of_arf_layer[layer_depth]) ||
1919
569k
      (cm->frame_type == KEY_FRAME) ||
1920
533k
      (!rc->constrained_gf_group &&
1921
517k
       (cpi->refresh_alt_ref_frame ||
1922
508k
        (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1923
121k
    cpi->twopass.last_qindex_of_arf_layer[layer_depth] = qindex;
1924
121k
  }
1925
1926
625k
  if (frame_is_intra_only(cm)) rc->last_kf_qindex = qindex;
1927
1928
625k
  update_buffer_level_postencode(cpi, rc->projected_frame_size);
1929
1930
  // Rolling monitors of whether we are over or underspending used to help
1931
  // regulate min and Max Q in two pass.
1932
625k
  if (!frame_is_intra_only(cm)) {
1933
582k
    rc->rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
1934
582k
        (int64_t)rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1935
582k
    rc->rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
1936
582k
        (int64_t)rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1937
582k
    rc->long_rolling_target_bits = (int)ROUND64_POWER_OF_TWO(
1938
582k
        (int64_t)rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1939
582k
    rc->long_rolling_actual_bits = (int)ROUND64_POWER_OF_TWO(
1940
582k
        (int64_t)rc->long_rolling_actual_bits * 31 + rc->projected_frame_size,
1941
582k
        5);
1942
582k
  }
1943
1944
  // Actual bits spent
1945
625k
  rc->total_actual_bits += rc->projected_frame_size;
1946
625k
  rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1947
1948
625k
  rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1949
1950
625k
  if (!cpi->use_svc) {
1951
625k
    if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
1952
56.3k
        (!frame_is_intra_only(cm)))
1953
      // Update the alternate reference frame stats as appropriate.
1954
14.0k
      update_alt_ref_frame_stats(cpi);
1955
611k
    else
1956
      // Update the Golden frame stats as appropriate.
1957
611k
      update_golden_frame_stats(cpi);
1958
625k
  }
1959
1960
  // If second (long term) temporal reference is used for SVC,
1961
  // update the golden frame counter, only for base temporal layer.
1962
625k
  if (cpi->use_svc && svc->use_gf_temporal_ref_current_layer &&
1963
0
      svc->temporal_layer_id == 0) {
1964
0
    int i = 0;
1965
0
    if (cpi->refresh_golden_frame)
1966
0
      rc->frames_since_golden = 0;
1967
0
    else
1968
0
      rc->frames_since_golden++;
1969
    // Decrement count down till next gf
1970
0
    if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1971
    // Update the frames_since_golden for all upper temporal layers.
1972
0
    for (i = 1; i < svc->number_temporal_layers; ++i) {
1973
0
      const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
1974
0
                                         svc->number_temporal_layers);
1975
0
      LAYER_CONTEXT *const lc = &svc->layer_context[layer];
1976
0
      RATE_CONTROL *const lrc = &lc->rc;
1977
0
      lrc->frames_since_golden = rc->frames_since_golden;
1978
0
    }
1979
0
  }
1980
1981
625k
  if (frame_is_intra_only(cm)) rc->frames_since_key = 0;
1982
625k
  if (cm->show_frame) {
1983
611k
    rc->frames_since_key++;
1984
611k
    rc->frames_to_key--;
1985
611k
  }
1986
1987
  // Trigger the resizing of the next frame if it is scaled.
1988
625k
  if (oxcf->pass != 0) {
1989
0
    cpi->resize_pending =
1990
0
        rc->next_frame_size_selector != rc->frame_size_selector;
1991
0
    rc->frame_size_selector = rc->next_frame_size_selector;
1992
0
  }
1993
1994
625k
  if (oxcf->pass == 0) {
1995
625k
    if (!frame_is_intra_only(cm))
1996
582k
      if (cpi->sf.use_altref_onepass) update_altref_usage(cpi);
1997
625k
    cpi->rc.last_frame_is_src_altref = cpi->rc.is_src_frame_alt_ref;
1998
625k
  }
1999
2000
625k
  if (!frame_is_intra_only(cm)) rc->reset_high_source_sad = 0;
2001
2002
625k
  rc->last_avg_frame_bandwidth = rc->avg_frame_bandwidth;
2003
625k
  if (cpi->use_svc && svc->spatial_layer_id < svc->number_spatial_layers - 1)
2004
0
    svc->lower_layer_qindex = cm->base_qindex;
2005
625k
  cpi->deadline_mode_previous_frame = cpi->oxcf.mode;
2006
625k
}
2007
2008
0
void vp9_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
2009
0
  cpi->common.current_video_frame++;
2010
0
  cpi->rc.frames_since_key++;
2011
0
  cpi->rc.frames_to_key--;
2012
0
  cpi->rc.rc_2_frame = 0;
2013
0
  cpi->rc.rc_1_frame = 0;
2014
0
  cpi->rc.last_avg_frame_bandwidth = cpi->rc.avg_frame_bandwidth;
2015
0
  cpi->rc.last_q[INTER_FRAME] = cpi->common.base_qindex;
2016
  // For SVC on dropped frame when framedrop_mode != LAYER_DROP:
2017
  // in this mode the whole superframe may be dropped if only a single layer
2018
  // has buffer underflow (below threshold). Since this can then lead to
2019
  // increasing buffer levels/overflow for certain layers even though whole
2020
  // superframe is dropped, we cap buffer level if its already stable.
2021
0
  if (cpi->use_svc && cpi->svc.framedrop_mode != LAYER_DROP &&
2022
0
      cpi->rc.buffer_level > cpi->rc.optimal_buffer_level) {
2023
0
    cpi->rc.buffer_level = cpi->rc.optimal_buffer_level;
2024
0
    cpi->rc.bits_off_target = cpi->rc.optimal_buffer_level;
2025
0
  }
2026
0
  cpi->deadline_mode_previous_frame = cpi->oxcf.mode;
2027
0
}
2028
2029
601k
int vp9_calc_pframe_target_size_one_pass_vbr(const VP9_COMP *cpi) {
2030
601k
  const RATE_CONTROL *const rc = &cpi->rc;
2031
601k
  const int af_ratio = rc->af_ratio_onepass_vbr;
2032
601k
  int64_t target =
2033
601k
      (!rc->is_src_frame_alt_ref &&
2034
579k
       (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))
2035
601k
          ? ((int64_t)rc->avg_frame_bandwidth * rc->baseline_gf_interval *
2036
58.7k
             af_ratio) /
2037
58.7k
                (rc->baseline_gf_interval + af_ratio - 1)
2038
601k
          : ((int64_t)rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
2039
542k
                (rc->baseline_gf_interval + af_ratio - 1);
2040
  // For SVC: refresh flags are used to define the pattern, so we can't
2041
  // use that for boosting the target size here.
2042
  // TODO(marpan): Consider adding internal boost on TL0 for VBR-SVC.
2043
  // For now just use the CBR logic for setting target size.
2044
601k
  if (cpi->use_svc) target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2045
601k
  if (target > INT_MAX) target = INT_MAX;
2046
601k
  return vp9_rc_clamp_pframe_target_size(cpi, (int)target);
2047
601k
}
2048
2049
42.4k
int vp9_calc_iframe_target_size_one_pass_vbr(const VP9_COMP *cpi) {
2050
42.4k
  static const int kf_ratio = 25;
2051
42.4k
  const RATE_CONTROL *rc = &cpi->rc;
2052
42.4k
  int target = rc->avg_frame_bandwidth;
2053
42.4k
  if (target > INT_MAX / kf_ratio)
2054
0
    target = INT_MAX;
2055
42.4k
  else
2056
42.4k
    target = rc->avg_frame_bandwidth * kf_ratio;
2057
42.4k
  return vp9_rc_clamp_iframe_target_size(cpi, target);
2058
42.4k
}
2059
2060
90.5k
static void adjust_gfint_frame_constraint(VP9_COMP *cpi, int frame_constraint) {
2061
90.5k
  RATE_CONTROL *const rc = &cpi->rc;
2062
90.5k
  rc->constrained_gf_group = 0;
2063
  // Reset gf interval to make more equal spacing for frame_constraint.
2064
90.5k
  if ((frame_constraint <= 7 * rc->baseline_gf_interval >> 2) &&
2065
3.56k
      (frame_constraint > rc->baseline_gf_interval)) {
2066
1.83k
    rc->baseline_gf_interval = frame_constraint >> 1;
2067
1.83k
    if (rc->baseline_gf_interval < 5)
2068
183
      rc->baseline_gf_interval = frame_constraint;
2069
1.83k
    rc->constrained_gf_group = 1;
2070
88.6k
  } else {
2071
    // Reset to keep gf_interval <= frame_constraint.
2072
88.6k
    if (rc->baseline_gf_interval > frame_constraint) {
2073
1.43k
      rc->baseline_gf_interval = frame_constraint;
2074
1.43k
      rc->constrained_gf_group = 1;
2075
1.43k
    }
2076
88.6k
  }
2077
90.5k
}
2078
2079
626k
void vp9_set_gf_update_one_pass_vbr(VP9_COMP *const cpi) {
2080
626k
  RATE_CONTROL *const rc = &cpi->rc;
2081
626k
  VP9_COMMON *const cm = &cpi->common;
2082
626k
  if (rc->frames_till_gf_update_due == 0) {
2083
72.7k
    double rate_err = 1.0;
2084
72.7k
    rc->gfu_boost = DEFAULT_GF_BOOST;
2085
72.7k
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0) {
2086
0
      vp9_cyclic_refresh_set_golden_update(cpi);
2087
72.7k
    } else {
2088
72.7k
      rc->baseline_gf_interval = VPXMIN(
2089
72.7k
          20, VPXMAX(10, (rc->min_gf_interval + rc->max_gf_interval) / 2));
2090
72.7k
    }
2091
72.7k
    rc->af_ratio_onepass_vbr = 10;
2092
72.7k
    if (rc->rolling_target_bits > 0)
2093
69.8k
      rate_err =
2094
69.8k
          (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
2095
72.7k
    if (cm->current_video_frame > 30) {
2096
34.0k
      if (rc->avg_frame_qindex[INTER_FRAME] > (7 * rc->worst_quality) >> 3 &&
2097
2.73k
          rate_err > 3.5) {
2098
0
        rc->baseline_gf_interval =
2099
0
            VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
2100
34.0k
      } else if (rc->avg_frame_low_motion > 0 &&
2101
26.2k
                 rc->avg_frame_low_motion < 20) {
2102
        // Decrease gf interval for high motion case.
2103
11.7k
        rc->baseline_gf_interval = VPXMAX(6, rc->baseline_gf_interval >> 1);
2104
11.7k
      }
2105
      // Adjust boost and af_ratio based on avg_frame_low_motion, which
2106
      // varies between 0 and 100 (stationary, 100% zero/small motion).
2107
34.0k
      if (rc->avg_frame_low_motion > 0)
2108
26.2k
        rc->gfu_boost =
2109
26.2k
            VPXMAX(500, DEFAULT_GF_BOOST * (rc->avg_frame_low_motion << 1) /
2110
34.0k
                            (rc->avg_frame_low_motion + 100));
2111
7.80k
      else if (rc->avg_frame_low_motion == 0 && rate_err > 1.0)
2112
4.00k
        rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
2113
34.0k
      rc->af_ratio_onepass_vbr = VPXMIN(15, VPXMAX(5, 3 * rc->gfu_boost / 400));
2114
34.0k
    }
2115
72.7k
    if (rc->constrain_gf_key_freq_onepass_vbr)
2116
72.7k
      adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
2117
72.7k
    rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2118
72.7k
    cpi->refresh_golden_frame = 1;
2119
72.7k
    rc->source_alt_ref_pending = 0;
2120
72.7k
    rc->alt_ref_gf_group = 0;
2121
72.7k
    if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf) {
2122
27.0k
      rc->source_alt_ref_pending = 1;
2123
27.0k
      rc->alt_ref_gf_group = 1;
2124
27.0k
    }
2125
72.7k
  }
2126
626k
}
2127
2128
626k
void vp9_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
2129
626k
  VP9_COMMON *const cm = &cpi->common;
2130
626k
  RATE_CONTROL *const rc = &cpi->rc;
2131
626k
  int target;
2132
626k
  if (!cpi->refresh_alt_ref_frame &&
2133
612k
      (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
2134
570k
       rc->frames_to_key == 0 ||
2135
569k
       (cpi->oxcf.mode != cpi->deadline_mode_previous_frame))) {
2136
42.4k
    cm->frame_type = KEY_FRAME;
2137
42.4k
    rc->this_key_frame_forced =
2138
42.4k
        cm->current_video_frame != 0 && rc->frames_to_key == 0;
2139
42.4k
    rc->frames_to_key = cpi->oxcf.key_freq;
2140
42.4k
    rc->kf_boost = DEFAULT_KF_BOOST;
2141
42.4k
    rc->source_alt_ref_active = 0;
2142
583k
  } else {
2143
583k
    cm->frame_type = INTER_FRAME;
2144
583k
  }
2145
626k
  vp9_set_gf_update_one_pass_vbr(cpi);
2146
626k
  if (cm->frame_type == KEY_FRAME)
2147
42.4k
    target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2148
583k
  else
2149
583k
    target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
2150
626k
  vp9_rc_set_frame_target(cpi, target);
2151
626k
  if (cm->show_frame) vp9_update_buffer_level_preencode(cpi);
2152
626k
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0)
2153
0
    vp9_cyclic_refresh_update_parameters(cpi);
2154
626k
}
2155
2156
0
int vp9_calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
2157
0
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
2158
0
  const RATE_CONTROL *rc = &cpi->rc;
2159
0
  const SVC *const svc = &cpi->svc;
2160
0
  const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
2161
0
  const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
2162
0
  int min_frame_target =
2163
0
      VPXMAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
2164
0
  int64_t target;
2165
2166
0
  if (oxcf->gf_cbr_boost_pct && rc->baseline_gf_interval != INT_MAX) {
2167
0
    const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
2168
0
    target = cpi->refresh_golden_frame
2169
0
                 ? ((int64_t)rc->avg_frame_bandwidth *
2170
0
                    rc->baseline_gf_interval * af_ratio_pct) /
2171
0
                       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100)
2172
0
                 : ((int64_t)rc->avg_frame_bandwidth *
2173
0
                    rc->baseline_gf_interval * 100) /
2174
0
                       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
2175
0
  } else {
2176
0
    target = rc->avg_frame_bandwidth;
2177
0
  }
2178
0
  if (is_one_pass_svc(cpi)) {
2179
    // Note that for layers, avg_frame_bandwidth is the cumulative
2180
    // per-frame-bandwidth. For the target size of this frame, use the
2181
    // layer average frame size (i.e., non-cumulative per-frame-bw).
2182
0
    int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2183
0
                                 svc->number_temporal_layers);
2184
0
    const LAYER_CONTEXT *lc = &svc->layer_context[layer];
2185
0
    target = lc->avg_frame_size;
2186
0
    min_frame_target = VPXMAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
2187
0
  }
2188
0
  if (diff > 0) {
2189
    // Lower the target bandwidth for this frame.
2190
0
    const int pct_low = (int)VPXMIN(diff / one_pct_bits, oxcf->under_shoot_pct);
2191
0
    target -= (target * pct_low) / 200;
2192
0
  } else if (diff < 0) {
2193
    // Increase the target bandwidth for this frame.
2194
0
    const int pct_high =
2195
0
        (int)VPXMIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
2196
0
    target += (target * pct_high) / 200;
2197
0
  }
2198
0
  if (oxcf->rc_max_inter_bitrate_pct) {
2199
0
    const int64_t max_rate =
2200
0
        (int64_t)rc->avg_frame_bandwidth * oxcf->rc_max_inter_bitrate_pct / 100;
2201
0
    target = VPXMIN(target, max_rate);
2202
0
  }
2203
0
  if (target > INT_MAX) target = INT_MAX;
2204
0
  return VPXMAX(min_frame_target, (int)target);
2205
0
}
2206
2207
0
int vp9_calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
2208
0
  const RATE_CONTROL *rc = &cpi->rc;
2209
0
  const VP9EncoderConfig *oxcf = &cpi->oxcf;
2210
0
  const SVC *const svc = &cpi->svc;
2211
0
  int64_t target;
2212
0
  if (cpi->common.current_video_frame == 0) {
2213
0
    target = rc->starting_buffer_level / 2;
2214
0
  } else {
2215
0
    int kf_boost = 32;
2216
0
    double framerate = cpi->framerate;
2217
0
    if (svc->number_temporal_layers > 1 && oxcf->rc_mode == VPX_CBR) {
2218
      // Use the layer framerate for temporal layers CBR mode.
2219
0
      const int layer =
2220
0
          LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2221
0
                           svc->number_temporal_layers);
2222
0
      const LAYER_CONTEXT *lc = &svc->layer_context[layer];
2223
0
      framerate = lc->framerate;
2224
0
    }
2225
0
    kf_boost = VPXMAX(kf_boost, (int)round(2 * framerate - 16));
2226
0
    if (rc->frames_since_key < framerate / 2) {
2227
0
      kf_boost = (int)round(kf_boost * rc->frames_since_key / (framerate / 2));
2228
0
    }
2229
2230
0
    target = ((int64_t)(16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
2231
0
  }
2232
0
  target = VPXMIN(INT_MAX, target);
2233
0
  return vp9_rc_clamp_iframe_target_size(cpi, (int)target);
2234
0
}
2235
2236
0
static void set_intra_only_frame(VP9_COMP *cpi) {
2237
0
  VP9_COMMON *const cm = &cpi->common;
2238
0
  SVC *const svc = &cpi->svc;
2239
  // Don't allow intra_only frame for bypass/flexible SVC mode, or if number
2240
  // of spatial layers is 1 or if number of spatial or temporal layers > 3.
2241
  // Also if intra-only is inserted on very first frame, don't allow if
2242
  // if number of temporal layers > 1. This is because on intra-only frame
2243
  // only 3 reference buffers can be updated, but for temporal layers > 1
2244
  // we generally need to use buffer slots 4 and 5.
2245
0
  if ((cm->current_video_frame == 0 && svc->number_temporal_layers > 1) ||
2246
0
      svc->number_spatial_layers > 3 || svc->number_temporal_layers > 3 ||
2247
0
      svc->number_spatial_layers == 1)
2248
0
    return;
2249
0
  cm->show_frame = 0;
2250
0
  cm->intra_only = 1;
2251
0
  cm->frame_type = INTER_FRAME;
2252
0
  cpi->ext_refresh_frame_flags_pending = 1;
2253
0
  cpi->ext_refresh_last_frame = 1;
2254
0
  cpi->ext_refresh_golden_frame = 1;
2255
0
  cpi->ext_refresh_alt_ref_frame = 1;
2256
0
  if (cm->current_video_frame == 0) {
2257
0
    cpi->lst_fb_idx = 0;
2258
0
    cpi->gld_fb_idx = 1;
2259
0
    cpi->alt_fb_idx = 2;
2260
0
  } else {
2261
0
    int i;
2262
0
    int count = 0;
2263
0
    cpi->lst_fb_idx = -1;
2264
0
    cpi->gld_fb_idx = -1;
2265
0
    cpi->alt_fb_idx = -1;
2266
0
    svc->update_buffer_slot[0] = 0;
2267
    // For intra-only frame we need to refresh all slots that were
2268
    // being used for the base layer (fb_idx_base[i] == 1).
2269
    // Start with assigning last first, then golden and then alt.
2270
0
    for (i = 0; i < REF_FRAMES; ++i) {
2271
0
      if (svc->fb_idx_base[i] == 1) {
2272
0
        svc->update_buffer_slot[0] |= 1 << i;
2273
0
        count++;
2274
0
      }
2275
0
      if (count == 1 && cpi->lst_fb_idx == -1) cpi->lst_fb_idx = i;
2276
0
      if (count == 2 && cpi->gld_fb_idx == -1) cpi->gld_fb_idx = i;
2277
0
      if (count == 3 && cpi->alt_fb_idx == -1) cpi->alt_fb_idx = i;
2278
0
    }
2279
    // If golden or alt is not being used for base layer, then set them
2280
    // to the lst_fb_idx.
2281
0
    if (cpi->gld_fb_idx == -1) cpi->gld_fb_idx = cpi->lst_fb_idx;
2282
0
    if (cpi->alt_fb_idx == -1) cpi->alt_fb_idx = cpi->lst_fb_idx;
2283
0
    if (svc->temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
2284
0
      cpi->ext_refresh_last_frame = 0;
2285
0
      cpi->ext_refresh_golden_frame = 0;
2286
0
      cpi->ext_refresh_alt_ref_frame = 0;
2287
0
      cpi->ref_frame_flags = 0;
2288
0
    }
2289
0
  }
2290
0
}
2291
2292
0
void vp9_rc_get_svc_params(VP9_COMP *cpi) {
2293
0
  VP9_COMMON *const cm = &cpi->common;
2294
0
  RATE_CONTROL *const rc = &cpi->rc;
2295
0
  SVC *const svc = &cpi->svc;
2296
0
  int target = rc->avg_frame_bandwidth;
2297
0
  int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2298
0
                               svc->number_temporal_layers);
2299
  // Clear is_key_frame on skipped lower spatial layers so stale keyframe state
2300
  // is not retained when first_spatial_layer_to_encode > 0.
2301
0
  if (svc->first_spatial_layer_to_encode > 0) {
2302
0
    int sl, tl;
2303
0
    for (sl = 0; sl < svc->first_spatial_layer_to_encode; ++sl) {
2304
0
      for (tl = 0; tl < svc->number_temporal_layers; ++tl) {
2305
0
        const int sl_layer =
2306
0
            LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
2307
0
        svc->layer_context[sl_layer].is_key_frame = 0;
2308
0
      }
2309
0
    }
2310
0
  }
2311
  // Periodic key frames is based on the super-frame counter
2312
  // (svc.current_superframe), also only base spatial layer is key frame.
2313
  // Key frame is set for any of the following: very first frame, frame flags
2314
  // indicates key, superframe counter hits key frequency,(non-intra) sync
2315
  // flag is set for spatial layer 0, or deadline mode changes.
2316
0
  if ((cm->current_video_frame == 0 && !svc->previous_frame_is_intra_only) ||
2317
0
      (cpi->frame_flags & FRAMEFLAGS_KEY) ||
2318
0
      (cpi->oxcf.auto_key &&
2319
0
       (svc->current_superframe % cpi->oxcf.key_freq == 0) &&
2320
0
       !svc->previous_frame_is_intra_only && svc->spatial_layer_id == 0) ||
2321
0
      (svc->spatial_layer_sync[0] == 1 && svc->spatial_layer_id == 0) ||
2322
0
      (cpi->oxcf.mode != cpi->deadline_mode_previous_frame)) {
2323
0
    cm->frame_type = KEY_FRAME;
2324
0
    rc->source_alt_ref_active = 0;
2325
0
    if (is_one_pass_svc(cpi)) {
2326
0
      if (cm->current_video_frame > 0) vp9_svc_reset_temporal_layers(cpi, 1);
2327
0
      layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
2328
0
                               svc->number_temporal_layers);
2329
0
      svc->layer_context[layer].is_key_frame = 1;
2330
0
      cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
2331
      // Assumption here is that LAST_FRAME is being updated for a keyframe.
2332
      // Thus no change in update flags.
2333
0
      if (cpi->oxcf.rc_mode == VPX_CBR)
2334
0
        target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2335
0
      else
2336
0
        target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2337
0
    }
2338
0
  } else {
2339
0
    cm->frame_type = INTER_FRAME;
2340
0
    if (is_one_pass_svc(cpi)) {
2341
      // Propagate is_key_frame from first_spatial_layer_to_encode (rather than
2342
      // spatial layer 0) so upper spatial layers inherit forced keyframes when
2343
      // lower spatial layers are disabled/skipped.
2344
0
      const int base_layer =
2345
0
          LAYER_IDS_TO_IDX(svc->first_spatial_layer_to_encode,
2346
0
                           svc->temporal_layer_id, svc->number_temporal_layers);
2347
0
      LAYER_CONTEXT *lc = &svc->layer_context[layer];
2348
      // Add condition current_video_frame > 0 for the case where first frame
2349
      // is intra only followed by overlay/copy frame. In this case we don't
2350
      // want to reset is_key_frame to 0 on overlay/copy frame.
2351
0
      lc->is_key_frame =
2352
0
          (svc->spatial_layer_id == svc->first_spatial_layer_to_encode &&
2353
0
           cm->current_video_frame > 0)
2354
0
              ? 0
2355
0
              : svc->layer_context[base_layer].is_key_frame;
2356
0
      if (cpi->oxcf.rc_mode == VPX_CBR) {
2357
0
        target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2358
0
      } else {
2359
0
        double rate_err = 0.0;
2360
0
        rc->fac_active_worst_inter = 140;
2361
0
        rc->fac_active_worst_gf = 100;
2362
0
        if (rc->rolling_target_bits > 0) {
2363
0
          rate_err =
2364
0
              (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
2365
0
          if (rate_err < 1.0)
2366
0
            rc->fac_active_worst_inter = 120;
2367
0
          else if (rate_err > 2.0)
2368
            // Increase active_worst faster if rate fluctuation is high.
2369
0
            rc->fac_active_worst_inter = 160;
2370
0
        }
2371
0
        target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
2372
0
      }
2373
0
    }
2374
0
  }
2375
2376
0
  if (svc->simulcast_mode) {
2377
0
    if (svc->spatial_layer_id > 0 &&
2378
0
        svc->layer_context[layer].is_key_frame == 1) {
2379
0
      cm->frame_type = KEY_FRAME;
2380
0
      cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
2381
0
      if (cpi->oxcf.rc_mode == VPX_CBR)
2382
0
        target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2383
0
      else
2384
0
        target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2385
0
    }
2386
    // Set the buffer idx and refresh flags for key frames in simulcast mode.
2387
    // Note the buffer slot for long-term reference is set below (line 2255),
2388
    // and alt_ref is used for that on key frame. So use last and golden for
2389
    // the other two normal slots.
2390
0
    if (cm->frame_type == KEY_FRAME) {
2391
0
      if (svc->number_spatial_layers == 2) {
2392
0
        if (svc->spatial_layer_id == 0) {
2393
0
          cpi->lst_fb_idx = 0;
2394
0
          cpi->gld_fb_idx = 2;
2395
0
          cpi->alt_fb_idx = 6;
2396
0
        } else if (svc->spatial_layer_id == 1) {
2397
0
          cpi->lst_fb_idx = 1;
2398
0
          cpi->gld_fb_idx = 3;
2399
0
          cpi->alt_fb_idx = 6;
2400
0
        }
2401
0
      } else if (svc->number_spatial_layers == 3) {
2402
0
        if (svc->spatial_layer_id == 0) {
2403
0
          cpi->lst_fb_idx = 0;
2404
0
          cpi->gld_fb_idx = 3;
2405
0
          cpi->alt_fb_idx = 6;
2406
0
        } else if (svc->spatial_layer_id == 1) {
2407
0
          cpi->lst_fb_idx = 1;
2408
0
          cpi->gld_fb_idx = 4;
2409
0
          cpi->alt_fb_idx = 6;
2410
0
        } else if (svc->spatial_layer_id == 2) {
2411
0
          cpi->lst_fb_idx = 2;
2412
0
          cpi->gld_fb_idx = 5;
2413
0
          cpi->alt_fb_idx = 7;
2414
0
        }
2415
0
      }
2416
0
      cpi->ext_refresh_last_frame = 1;
2417
0
      cpi->ext_refresh_golden_frame = 1;
2418
0
      cpi->ext_refresh_alt_ref_frame = 1;
2419
0
    }
2420
0
  }
2421
2422
  // Check if superframe contains a sync layer request.
2423
0
  vp9_svc_check_spatial_layer_sync(cpi);
2424
2425
  // If long term termporal feature is enabled, set the period of the update.
2426
  // The update/refresh of this reference frame is always on base temporal
2427
  // layer frame.
2428
0
  if (svc->use_gf_temporal_ref_current_layer) {
2429
    // Only use gf long-term prediction on non-key superframes.
2430
0
    if (!svc->layer_context[svc->temporal_layer_id].is_key_frame) {
2431
      // Use golden for this reference, which will be used for prediction.
2432
0
      int index = svc->spatial_layer_id;
2433
0
      if (svc->number_spatial_layers == 3) index = svc->spatial_layer_id - 1;
2434
0
      assert(index >= 0);
2435
0
      cpi->gld_fb_idx = svc->buffer_gf_temporal_ref[index].idx;
2436
      // Enable prediction off LAST (last reference) and golden (which will
2437
      // generally be further behind/long-term reference).
2438
0
      cpi->ref_frame_flags = VP9_LAST_FLAG | VP9_GOLD_FLAG;
2439
0
    }
2440
    // Check for update/refresh of reference: only refresh on base temporal
2441
    // layer.
2442
0
    if (svc->temporal_layer_id == 0) {
2443
0
      if (svc->layer_context[svc->temporal_layer_id].is_key_frame) {
2444
        // On key frame we update the buffer index used for long term reference.
2445
        // Use the alt_ref since it is not used or updated on key frames.
2446
0
        int index = svc->spatial_layer_id;
2447
0
        if (svc->number_spatial_layers == 3) index = svc->spatial_layer_id - 1;
2448
0
        assert(index >= 0);
2449
0
        cpi->alt_fb_idx = svc->buffer_gf_temporal_ref[index].idx;
2450
0
        cpi->ext_refresh_alt_ref_frame = 1;
2451
0
      } else if (rc->frames_till_gf_update_due == 0) {
2452
        // Set perdiod of next update. Make it a multiple of 10, as the cyclic
2453
        // refresh is typically ~10%, and we'd like the update to happen after
2454
        // a few cylces of the refresh (so it better quality frame). Note the
2455
        // cyclic refresh for SVC only operates on base temporal layer frames.
2456
        // Choose 20 as perdiod for now (2 cycles).
2457
0
        rc->baseline_gf_interval = 20;
2458
0
        rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2459
0
        cpi->ext_refresh_golden_frame = 1;
2460
0
        rc->gfu_boost = DEFAULT_GF_BOOST;
2461
0
      }
2462
0
    }
2463
0
  } else if (!svc->use_gf_temporal_ref) {
2464
0
    rc->frames_till_gf_update_due = INT_MAX;
2465
0
    rc->baseline_gf_interval = INT_MAX;
2466
0
  }
2467
0
  if (svc->set_intra_only_frame) {
2468
0
    set_intra_only_frame(cpi);
2469
0
    if (cpi->oxcf.rc_mode == VPX_CBR)
2470
0
      target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2471
0
    else
2472
0
      target = vp9_calc_iframe_target_size_one_pass_vbr(cpi);
2473
0
  }
2474
  // Overlay frame predicts from LAST (intra-only)
2475
0
  if (svc->previous_frame_is_intra_only) cpi->ref_frame_flags |= VP9_LAST_FLAG;
2476
2477
  // Any update/change of global cyclic refresh parameters (amount/delta-qp)
2478
  // should be done here, before the frame qp is selected.
2479
0
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
2480
0
    vp9_cyclic_refresh_update_parameters(cpi);
2481
2482
0
  vp9_rc_set_frame_target(cpi, target);
2483
0
  if (cm->show_frame) vp9_update_buffer_level_svc_preencode(cpi);
2484
2485
0
  if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC && svc->single_layer_svc == 1 &&
2486
0
      svc->spatial_layer_id == svc->first_spatial_layer_to_encode &&
2487
0
      svc->temporal_layer_id == 0) {
2488
0
    LAYER_CONTEXT *lc = NULL;
2489
0
    cpi->resize_pending = vp9_resize_one_pass_cbr(cpi);
2490
0
    if (cpi->resize_pending) {
2491
0
      int tl, width, height;
2492
      // Apply the same scale to all temporal layers.
2493
0
      for (tl = 0; tl < svc->number_temporal_layers; tl++) {
2494
0
        lc = &svc->layer_context[svc->spatial_layer_id *
2495
0
                                     svc->number_temporal_layers +
2496
0
                                 tl];
2497
0
        lc->scaling_factor_num_resize =
2498
0
            cpi->resize_scale_num * lc->scaling_factor_num;
2499
0
        lc->scaling_factor_den_resize =
2500
0
            cpi->resize_scale_den * lc->scaling_factor_den;
2501
        // Reset rate control for all temporal layers.
2502
0
        lc->rc.buffer_level = lc->rc.optimal_buffer_level;
2503
0
        lc->rc.bits_off_target = lc->rc.optimal_buffer_level;
2504
0
        lc->rc.rate_correction_factors[INTER_FRAME] =
2505
0
            rc->rate_correction_factors[INTER_FRAME];
2506
0
      }
2507
      // Set the size for this current temporal layer.
2508
0
      lc = &svc->layer_context[svc->spatial_layer_id *
2509
0
                                   svc->number_temporal_layers +
2510
0
                               svc->temporal_layer_id];
2511
0
      get_layer_resolution(cpi->oxcf.width, cpi->oxcf.height,
2512
0
                           lc->scaling_factor_num_resize,
2513
0
                           lc->scaling_factor_den_resize, &width, &height);
2514
0
      vp9_set_size_literal(cpi, width, height);
2515
0
      svc->resize_set = 1;
2516
0
    }
2517
0
  } else {
2518
0
    cpi->resize_pending = 0;
2519
0
    svc->resize_set = 0;
2520
0
  }
2521
0
}
2522
2523
0
void vp9_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
2524
0
  VP9_COMMON *const cm = &cpi->common;
2525
0
  RATE_CONTROL *const rc = &cpi->rc;
2526
0
  int target;
2527
0
  if ((cm->current_video_frame == 0) || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
2528
0
      (cpi->oxcf.auto_key && rc->frames_to_key == 0) ||
2529
0
      (cpi->oxcf.mode != cpi->deadline_mode_previous_frame)) {
2530
0
    cm->frame_type = KEY_FRAME;
2531
0
    rc->frames_to_key = cpi->oxcf.key_freq;
2532
0
    rc->kf_boost = DEFAULT_KF_BOOST;
2533
0
    rc->source_alt_ref_active = 0;
2534
0
  } else {
2535
0
    cm->frame_type = INTER_FRAME;
2536
0
  }
2537
0
  if (rc->frames_till_gf_update_due == 0) {
2538
0
    if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
2539
0
      vp9_cyclic_refresh_set_golden_update(cpi);
2540
0
    else
2541
0
      rc->baseline_gf_interval =
2542
0
          (rc->min_gf_interval + rc->max_gf_interval) / 2;
2543
0
    rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2544
    // NOTE: frames_till_gf_update_due must be <= frames_to_key.
2545
0
    if (rc->frames_till_gf_update_due > rc->frames_to_key)
2546
0
      rc->frames_till_gf_update_due = rc->frames_to_key;
2547
0
    cpi->refresh_golden_frame = 1;
2548
0
    rc->gfu_boost = DEFAULT_GF_BOOST;
2549
0
  }
2550
2551
  // Any update/change of global cyclic refresh parameters (amount/delta-qp)
2552
  // should be done here, before the frame qp is selected.
2553
0
  if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
2554
0
    vp9_cyclic_refresh_update_parameters(cpi);
2555
2556
0
  if (frame_is_intra_only(cm))
2557
0
    target = vp9_calc_iframe_target_size_one_pass_cbr(cpi);
2558
0
  else
2559
0
    target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2560
2561
0
  vp9_rc_set_frame_target(cpi, target);
2562
2563
0
  if (cm->show_frame) vp9_update_buffer_level_preencode(cpi);
2564
2565
0
  if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC)
2566
0
    cpi->resize_pending = vp9_resize_one_pass_cbr(cpi);
2567
0
  else
2568
0
    cpi->resize_pending = 0;
2569
0
}
2570
2571
int vp9_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
2572
42.4k
                       vpx_bit_depth_t bit_depth) {
2573
42.4k
  int start_index = rc->worst_quality;
2574
42.4k
  int target_index = rc->worst_quality;
2575
42.4k
  int i;
2576
2577
  // Convert the average q value to an index.
2578
2.01M
  for (i = rc->best_quality; i < rc->worst_quality; ++i) {
2579
2.01M
    start_index = i;
2580
2.01M
    if (vp9_convert_qindex_to_q(i, bit_depth) >= qstart) break;
2581
2.01M
  }
2582
2583
  // Convert the q target to an index
2584
1.51M
  for (i = rc->best_quality; i < rc->worst_quality; ++i) {
2585
1.51M
    target_index = i;
2586
1.51M
    if (vp9_convert_qindex_to_q(i, bit_depth) >= qtarget) break;
2587
1.51M
  }
2588
2589
42.4k
  return target_index - start_index;
2590
42.4k
}
2591
2592
int vp9_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
2593
                               int qindex, double rate_target_ratio,
2594
91.6k
                               vpx_bit_depth_t bit_depth) {
2595
91.6k
  int target_index = rc->worst_quality;
2596
91.6k
  int i;
2597
2598
  // Look up the current projected bits per block for the base index
2599
91.6k
  const int base_bits_per_mb =
2600
91.6k
      vp9_rc_bits_per_mb(frame_type, qindex, 1.0, bit_depth);
2601
2602
  // Find the target bits per mb based on the base value and given ratio.
2603
91.6k
  const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
2604
2605
  // Convert the q target to an index
2606
9.71M
  for (i = rc->best_quality; i < rc->worst_quality; ++i) {
2607
9.71M
    if (vp9_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
2608
9.71M
        target_bits_per_mb) {
2609
91.6k
      target_index = i;
2610
91.6k
      break;
2611
91.6k
    }
2612
9.71M
  }
2613
91.6k
  return target_index - qindex;
2614
91.6k
}
2615
2616
void vp9_rc_set_gf_interval_range(const VP9_COMP *const cpi,
2617
645k
                                  RATE_CONTROL *const rc) {
2618
645k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2619
2620
  // Special case code for 1 pass fixed Q mode tests
2621
645k
  if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
2622
0
    rc->max_gf_interval = FIXED_GF_INTERVAL;
2623
0
    rc->min_gf_interval = FIXED_GF_INTERVAL;
2624
0
    rc->static_scene_max_gf_interval = FIXED_GF_INTERVAL;
2625
645k
  } else {
2626
645k
    double framerate = cpi->framerate;
2627
    // Set Maximum gf/arf interval
2628
645k
    rc->max_gf_interval = oxcf->max_gf_interval;
2629
645k
    rc->min_gf_interval = oxcf->min_gf_interval;
2630
645k
    if (rc->min_gf_interval == 0) {
2631
645k
      rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
2632
645k
          oxcf->width, oxcf->height, framerate);
2633
645k
    }
2634
645k
    if (rc->max_gf_interval == 0) {
2635
645k
      rc->max_gf_interval =
2636
645k
          vp9_rc_get_default_max_gf_interval(framerate, rc->min_gf_interval);
2637
645k
    }
2638
2639
    // Extended max interval for genuinely static scenes like slide shows.
2640
645k
    rc->static_scene_max_gf_interval = MAX_STATIC_GF_GROUP_LENGTH;
2641
2642
645k
    if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
2643
0
      rc->max_gf_interval = rc->static_scene_max_gf_interval;
2644
2645
    // Clamp min to max
2646
645k
    rc->min_gf_interval = VPXMIN(rc->min_gf_interval, rc->max_gf_interval);
2647
2648
645k
    if (oxcf->target_level == LEVEL_AUTO) {
2649
0
      const uint32_t pic_size = cpi->common.width * cpi->common.height;
2650
0
      const uint32_t pic_breadth =
2651
0
          VPXMAX(cpi->common.width, cpi->common.height);
2652
0
      int i;
2653
0
      for (i = 0; i < VP9_LEVELS; ++i) {
2654
0
        if (vp9_level_defs[i].max_luma_picture_size >= pic_size &&
2655
0
            vp9_level_defs[i].max_luma_picture_breadth >= pic_breadth) {
2656
0
          if (rc->min_gf_interval <=
2657
0
              (int)vp9_level_defs[i].min_altref_distance) {
2658
0
            rc->min_gf_interval = (int)vp9_level_defs[i].min_altref_distance;
2659
0
            rc->max_gf_interval =
2660
0
                VPXMAX(rc->max_gf_interval, rc->min_gf_interval);
2661
0
          }
2662
0
          break;
2663
0
        }
2664
0
      }
2665
0
    }
2666
645k
  }
2667
645k
}
2668
2669
645k
void vp9_rc_update_framerate(VP9_COMP *cpi) {
2670
645k
  const VP9_COMMON *const cm = &cpi->common;
2671
645k
  const VP9EncoderConfig *const oxcf = &cpi->oxcf;
2672
645k
  RATE_CONTROL *const rc = &cpi->rc;
2673
2674
645k
  rc->avg_frame_bandwidth = saturate_cast_double_to_int(
2675
645k
      round(oxcf->target_bandwidth / cpi->framerate));
2676
2677
645k
  int64_t vbr_min_bits =
2678
645k
      (int64_t)rc->avg_frame_bandwidth * oxcf->two_pass_vbrmin_section / 100;
2679
645k
  vbr_min_bits = VPXMIN(vbr_min_bits, INT_MAX);
2680
2681
645k
  rc->min_frame_bandwidth = VPXMAX((int)vbr_min_bits, FRAME_OVERHEAD_BITS);
2682
2683
  // A maximum bitrate for a frame is defined.
2684
  // However this limit is extended if a very high rate is given on the command
2685
  // line or the rate can not be achieved because of a user specified max q
2686
  // (e.g. when the user specifies lossless encode).
2687
  //
2688
  // If a level is specified that requires a lower maximum rate then the level
2689
  // value take precedence.
2690
645k
  int64_t vbr_max_bits =
2691
645k
      (int64_t)rc->avg_frame_bandwidth * oxcf->two_pass_vbrmax_section / 100;
2692
645k
  vbr_max_bits = VPXMIN(vbr_max_bits, INT_MAX);
2693
2694
645k
  rc->max_frame_bandwidth =
2695
645k
      VPXMAX(VPXMAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P), (int)vbr_max_bits);
2696
2697
645k
  vp9_rc_set_gf_interval_range(cpi, rc);
2698
645k
}
2699
2700
#define VBR_PCT_ADJUSTMENT_LIMIT 50
2701
// For VBR...adjustment to the frame target based on error from previous frames
2702
0
static void vbr_rate_correction(VP9_COMP *cpi, int *this_frame_target) {
2703
0
  RATE_CONTROL *const rc = &cpi->rc;
2704
0
  int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
2705
0
  int64_t frame_target = *this_frame_target;
2706
0
  int frame_window = (int)VPXMIN(
2707
0
      16, cpi->twopass.total_stats.count - cpi->common.current_video_frame);
2708
2709
  // Calcluate the adjustment to rate for this frame.
2710
0
  if (frame_window > 0) {
2711
0
    int64_t max_delta = (vbr_bits_off_target > 0)
2712
0
                            ? (vbr_bits_off_target / frame_window)
2713
0
                            : (-vbr_bits_off_target / frame_window);
2714
2715
0
    max_delta =
2716
0
        VPXMIN(max_delta, ((frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
2717
2718
    // vbr_bits_off_target > 0 means we have extra bits to spend
2719
0
    if (vbr_bits_off_target > 0) {
2720
0
      frame_target += VPXMIN(vbr_bits_off_target, max_delta);
2721
0
    } else {
2722
0
      frame_target -= VPXMIN(-vbr_bits_off_target, max_delta);
2723
0
    }
2724
0
  }
2725
2726
  // Fast redistribution of bits arising from massive local undershoot.
2727
  // Don't do it for kf,arf,gf or overlay frames.
2728
0
  if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
2729
0
      rc->vbr_bits_off_target_fast) {
2730
0
    int64_t one_frame_bits = VPXMAX(rc->avg_frame_bandwidth, frame_target);
2731
0
    int64_t fast_extra_bits =
2732
0
        VPXMIN(rc->vbr_bits_off_target_fast, one_frame_bits);
2733
0
    fast_extra_bits =
2734
0
        VPXMIN(fast_extra_bits,
2735
0
               VPXMAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
2736
0
    frame_target += fast_extra_bits;
2737
0
    rc->vbr_bits_off_target_fast -= fast_extra_bits;
2738
0
  }
2739
2740
  // Clamp the target for the frame to the maximum allowed for one frame.
2741
0
  *this_frame_target = (int)VPXMIN(frame_target, INT_MAX);
2742
0
}
2743
2744
0
void vp9_set_target_rate(VP9_COMP *cpi) {
2745
0
  RATE_CONTROL *const rc = &cpi->rc;
2746
0
  int target_rate = rc->base_frame_target;
2747
2748
0
  if (cpi->common.frame_type == KEY_FRAME)
2749
0
    target_rate = vp9_rc_clamp_iframe_target_size(cpi, target_rate);
2750
0
  else
2751
0
    target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
2752
2753
0
  if (!cpi->oxcf.vbr_corpus_complexity) {
2754
    // Correction to rate target based on prior over or under shoot.
2755
0
    if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
2756
0
      vbr_rate_correction(cpi, &target_rate);
2757
0
  }
2758
0
  vp9_rc_set_frame_target(cpi, target_rate);
2759
0
}
2760
2761
// Check if we should resize, based on average QP from past x frames.
2762
// Only allow for resize at most one scale down for now, scaling factor is 2.
2763
0
int vp9_resize_one_pass_cbr(VP9_COMP *cpi) {
2764
0
  const VP9_COMMON *const cm = &cpi->common;
2765
0
  RATE_CONTROL *const rc = &cpi->rc;
2766
0
  RESIZE_ACTION resize_action = NO_RESIZE;
2767
0
  int avg_qp_thr1 = 70;
2768
0
  int avg_qp_thr2 = 50;
2769
  // Don't allow for resized frame to go below 320x180, resize in steps of 3/4.
2770
0
  int min_width = (320 * 4) / 3;
2771
0
  int min_height = (180 * 4) / 3;
2772
0
  int down_size_on = 1;
2773
0
  int force_downsize_rate = 0;
2774
0
  cpi->resize_scale_num = 1;
2775
0
  cpi->resize_scale_den = 1;
2776
  // Don't resize on key frame; reset the counters on key frame.
2777
0
  if (cm->frame_type == KEY_FRAME) {
2778
0
    cpi->resize_avg_qp = 0;
2779
0
    cpi->resize_count = 0;
2780
0
    return 0;
2781
0
  }
2782
2783
  // No resizing down if frame size is below some limit.
2784
0
  if ((cm->width * cm->height) < min_width * min_height) down_size_on = 0;
2785
2786
#if CONFIG_VP9_TEMPORAL_DENOISING
2787
  // If denoiser is on, apply a smaller qp threshold.
2788
  if (cpi->oxcf.noise_sensitivity > 0) {
2789
    avg_qp_thr1 = 60;
2790
    avg_qp_thr2 = 40;
2791
  }
2792
#endif
2793
2794
  // Force downsize based on per-frame-bandwidth, for extreme case,
2795
  // for HD input.
2796
0
  if (cpi->resize_state == ORIG && cm->width * cm->height >= 1280 * 720) {
2797
0
    if (rc->avg_frame_bandwidth < 300000 / 30) {
2798
0
      resize_action = DOWN_ONEHALF;
2799
0
      cpi->resize_state = ONE_HALF;
2800
0
      force_downsize_rate = 1;
2801
0
    } else if (rc->avg_frame_bandwidth < 400000 / 30) {
2802
0
      resize_action = ONEHALFONLY_RESIZE ? DOWN_ONEHALF : DOWN_THREEFOUR;
2803
0
      cpi->resize_state = ONEHALFONLY_RESIZE ? ONE_HALF : THREE_QUARTER;
2804
0
      force_downsize_rate = 1;
2805
0
    }
2806
0
  } else if (cpi->resize_state == THREE_QUARTER &&
2807
0
             cm->width * cm->height >= 960 * 540) {
2808
0
    if (rc->avg_frame_bandwidth < 300000 / 30) {
2809
0
      resize_action = DOWN_ONEHALF;
2810
0
      cpi->resize_state = ONE_HALF;
2811
0
      force_downsize_rate = 1;
2812
0
    }
2813
0
  }
2814
2815
  // Resize based on average buffer underflow and QP over some window.
2816
  // Ignore samples close to key frame, since QP is usually high after key.
2817
0
  if (!force_downsize_rate && cpi->rc.frames_since_key > cpi->framerate) {
2818
0
    const int window = VPXMIN(30, (int)round(2 * cpi->framerate));
2819
0
    cpi->resize_avg_qp += rc->last_q[INTER_FRAME];
2820
0
    if (cpi->rc.buffer_level < (int)(30 * rc->optimal_buffer_level / 100))
2821
0
      ++cpi->resize_buffer_underflow;
2822
0
    ++cpi->resize_count;
2823
    // Check for resize action every "window" frames.
2824
0
    if (cpi->resize_count >= window) {
2825
0
      int avg_qp = cpi->resize_avg_qp / cpi->resize_count;
2826
      // Resize down if buffer level has underflowed sufficient amount in past
2827
      // window, and we are at original or 3/4 of original resolution.
2828
      // Resize back up if average QP is low, and we are currently in a resized
2829
      // down state, i.e. 1/2 or 3/4 of original resolution.
2830
      // Currently, use a flag to turn 3/4 resizing feature on/off.
2831
0
      if (cpi->resize_buffer_underflow > (cpi->resize_count >> 2) &&
2832
0
          down_size_on) {
2833
0
        if (cpi->resize_state == THREE_QUARTER) {
2834
0
          resize_action = DOWN_ONEHALF;
2835
0
          cpi->resize_state = ONE_HALF;
2836
0
        } else if (cpi->resize_state == ORIG) {
2837
0
          resize_action = ONEHALFONLY_RESIZE ? DOWN_ONEHALF : DOWN_THREEFOUR;
2838
0
          cpi->resize_state = ONEHALFONLY_RESIZE ? ONE_HALF : THREE_QUARTER;
2839
0
        }
2840
0
      } else if (cpi->resize_state != ORIG &&
2841
0
                 avg_qp < avg_qp_thr1 * cpi->rc.worst_quality / 100) {
2842
0
        if (cpi->resize_state == THREE_QUARTER ||
2843
0
            avg_qp < avg_qp_thr2 * cpi->rc.worst_quality / 100 ||
2844
0
            ONEHALFONLY_RESIZE) {
2845
0
          resize_action = UP_ORIG;
2846
0
          cpi->resize_state = ORIG;
2847
0
        } else if (cpi->resize_state == ONE_HALF) {
2848
0
          resize_action = UP_THREEFOUR;
2849
0
          cpi->resize_state = THREE_QUARTER;
2850
0
        }
2851
0
      }
2852
      // Reset for next window measurement.
2853
0
      cpi->resize_avg_qp = 0;
2854
0
      cpi->resize_count = 0;
2855
0
      cpi->resize_buffer_underflow = 0;
2856
0
    }
2857
0
  }
2858
  // If decision is to resize, reset some quantities, and check is we should
2859
  // reduce rate correction factor,
2860
0
  if (resize_action != NO_RESIZE) {
2861
0
    int target_bits_per_frame;
2862
0
    int active_worst_quality;
2863
0
    int qindex;
2864
0
    int tot_scale_change;
2865
0
    if (resize_action == DOWN_THREEFOUR || resize_action == UP_THREEFOUR) {
2866
0
      cpi->resize_scale_num = 3;
2867
0
      cpi->resize_scale_den = 4;
2868
0
    } else if (resize_action == DOWN_ONEHALF) {
2869
0
      cpi->resize_scale_num = 1;
2870
0
      cpi->resize_scale_den = 2;
2871
0
    } else {  // UP_ORIG or anything else
2872
0
      cpi->resize_scale_num = 1;
2873
0
      cpi->resize_scale_den = 1;
2874
0
    }
2875
0
    tot_scale_change = (cpi->resize_scale_den * cpi->resize_scale_den) /
2876
0
                       (cpi->resize_scale_num * cpi->resize_scale_num);
2877
    // Reset buffer level to optimal, update target size.
2878
0
    rc->buffer_level = rc->optimal_buffer_level;
2879
0
    rc->bits_off_target = rc->optimal_buffer_level;
2880
0
    rc->this_frame_target = vp9_calc_pframe_target_size_one_pass_cbr(cpi);
2881
    // Get the projected qindex, based on the scaled target frame size (scaled
2882
    // so target_bits_per_mb in vp9_rc_regulate_q will be correct target).
2883
0
    target_bits_per_frame = (resize_action >= 0)
2884
0
                                ? rc->this_frame_target * tot_scale_change
2885
0
                                : rc->this_frame_target / tot_scale_change;
2886
0
    active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
2887
0
    qindex = vp9_rc_regulate_q(cpi, target_bits_per_frame, rc->best_quality,
2888
0
                               active_worst_quality);
2889
    // If resize is down, check if projected q index is close to worst_quality,
2890
    // and if so, reduce the rate correction factor (since likely can afford
2891
    // lower q for resized frame).
2892
0
    if (resize_action > 0 && qindex > 90 * cpi->rc.worst_quality / 100) {
2893
0
      rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
2894
0
    }
2895
    // If resize is back up, check if projected q index is too much above the
2896
    // current base_qindex, and if so, reduce the rate correction factor
2897
    // (since prefer to keep q for resized frame at least close to previous q).
2898
0
    if (resize_action < 0 && qindex > 130 * cm->base_qindex / 100) {
2899
0
      rc->rate_correction_factors[INTER_NORMAL] *= 0.9;
2900
0
    }
2901
0
  }
2902
0
  return resize_action;
2903
0
}
2904
2905
static void adjust_gf_boost_lag_one_pass_vbr(VP9_COMP *cpi,
2906
321k
                                             uint64_t avg_sad_current) {
2907
321k
  VP9_COMMON *const cm = &cpi->common;
2908
321k
  RATE_CONTROL *const rc = &cpi->rc;
2909
321k
  int target;
2910
321k
  int found = 0;
2911
321k
  int found2 = 0;
2912
321k
  int frame;
2913
321k
  int i;
2914
321k
  uint64_t avg_source_sad_lag = avg_sad_current;
2915
321k
  int high_source_sad_lagindex = -1;
2916
321k
  int steady_sad_lagindex = -1;
2917
321k
  uint32_t sad_thresh1 = 70000;
2918
321k
  uint32_t sad_thresh2 = 120000;
2919
321k
  int low_content = 0;
2920
321k
  int high_content = 0;
2921
321k
  double rate_err = 1.0;
2922
  // Get measure of complexity over the future frames, and get the first
2923
  // future frame with high_source_sad/scene-change.
2924
321k
  int tot_frames = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
2925
6.32M
  for (frame = tot_frames; frame >= 1; --frame) {
2926
6.00M
    const int lagframe_idx = tot_frames - frame + 1;
2927
6.00M
    uint64_t reference_sad = rc->avg_source_sad[0];
2928
67.1M
    for (i = 1; i < lagframe_idx; ++i) {
2929
61.1M
      if (rc->avg_source_sad[i] > 0)
2930
0
        reference_sad = (3 * reference_sad + rc->avg_source_sad[i]) >> 2;
2931
61.1M
    }
2932
    // Detect up-coming scene change.
2933
6.00M
    if (!found &&
2934
6.00M
        (rc->avg_source_sad[lagframe_idx] >
2935
6.00M
             VPXMAX(sad_thresh1, (unsigned int)(reference_sad << 1)) ||
2936
6.00M
         rc->avg_source_sad[lagframe_idx] >
2937
6.00M
             VPXMAX(3 * sad_thresh1 >> 2,
2938
6.00M
                    (unsigned int)(reference_sad << 2)))) {
2939
0
      high_source_sad_lagindex = lagframe_idx;
2940
0
      found = 1;
2941
0
    }
2942
    // Detect change from motion to steady.
2943
6.00M
    if (!found2 && lagframe_idx > 1 && lagframe_idx < tot_frames &&
2944
5.38M
        rc->avg_source_sad[lagframe_idx - 1] > (sad_thresh1 >> 2)) {
2945
0
      found2 = 1;
2946
0
      for (i = lagframe_idx; i < tot_frames; ++i) {
2947
0
        if (!(rc->avg_source_sad[i] > 0 &&
2948
0
              rc->avg_source_sad[i] < (sad_thresh1 >> 2) &&
2949
0
              rc->avg_source_sad[i] <
2950
0
                  (rc->avg_source_sad[lagframe_idx - 1] >> 1))) {
2951
0
          found2 = 0;
2952
0
          i = tot_frames;
2953
0
        }
2954
0
      }
2955
0
      if (found2) steady_sad_lagindex = lagframe_idx;
2956
0
    }
2957
6.00M
    avg_source_sad_lag += rc->avg_source_sad[lagframe_idx];
2958
6.00M
  }
2959
321k
  if (tot_frames > 0) avg_source_sad_lag = avg_source_sad_lag / tot_frames;
2960
  // Constrain distance between detected scene cuts.
2961
321k
  if (high_source_sad_lagindex != -1 &&
2962
0
      high_source_sad_lagindex != rc->high_source_sad_lagindex - 1 &&
2963
0
      abs(high_source_sad_lagindex - rc->high_source_sad_lagindex) < 4)
2964
0
    rc->high_source_sad_lagindex = -1;
2965
321k
  else
2966
321k
    rc->high_source_sad_lagindex = high_source_sad_lagindex;
2967
  // Adjust some factors for the next GF group, ignore initial key frame,
2968
  // and only for lag_in_frames not too small.
2969
321k
  if (cpi->refresh_golden_frame == 1 && cm->current_video_frame > 30 &&
2970
17.7k
      cpi->oxcf.lag_in_frames > 8) {
2971
17.7k
    int frame_constraint;
2972
17.7k
    if (rc->rolling_target_bits > 0)
2973
17.7k
      rate_err =
2974
17.7k
          (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
2975
17.7k
    high_content = high_source_sad_lagindex != -1 ||
2976
17.7k
                   avg_source_sad_lag > (rc->prev_avg_source_sad_lag << 1) ||
2977
17.7k
                   avg_source_sad_lag > sad_thresh2;
2978
17.7k
    low_content = high_source_sad_lagindex == -1 &&
2979
17.7k
                  ((avg_source_sad_lag < (rc->prev_avg_source_sad_lag >> 1)) ||
2980
17.7k
                   (avg_source_sad_lag < sad_thresh1));
2981
17.7k
    if (low_content) {
2982
17.7k
      rc->gfu_boost = DEFAULT_GF_BOOST;
2983
17.7k
      rc->baseline_gf_interval =
2984
17.7k
          VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
2985
17.7k
    } else if (high_content) {
2986
0
      rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
2987
0
      rc->baseline_gf_interval = (rate_err > 3.0)
2988
0
                                     ? VPXMAX(10, rc->baseline_gf_interval >> 1)
2989
0
                                     : VPXMAX(6, rc->baseline_gf_interval >> 1);
2990
0
    }
2991
17.7k
    if (rc->baseline_gf_interval > cpi->oxcf.lag_in_frames - 1)
2992
0
      rc->baseline_gf_interval = cpi->oxcf.lag_in_frames - 1;
2993
    // Check for constraining gf_interval for up-coming scene/content changes,
2994
    // or for up-coming key frame, whichever is closer.
2995
17.7k
    frame_constraint = rc->frames_to_key;
2996
17.7k
    if (rc->high_source_sad_lagindex > 0 &&
2997
0
        frame_constraint > rc->high_source_sad_lagindex)
2998
0
      frame_constraint = rc->high_source_sad_lagindex;
2999
17.7k
    if (steady_sad_lagindex > 3 && frame_constraint > steady_sad_lagindex)
3000
0
      frame_constraint = steady_sad_lagindex;
3001
17.7k
    adjust_gfint_frame_constraint(cpi, frame_constraint);
3002
17.7k
    rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3003
    // Adjust factors for active_worst setting & af_ratio for next gf interval.
3004
17.7k
    rc->fac_active_worst_inter = 150;  // corresponds to 3/2 (= 150 /100).
3005
17.7k
    rc->fac_active_worst_gf = 100;
3006
17.7k
    if (rate_err < 2.0 && !high_content) {
3007
16.6k
      rc->fac_active_worst_inter = 120;
3008
16.6k
      rc->fac_active_worst_gf = 90;
3009
16.6k
    } else if (rate_err > 8.0 && rc->avg_frame_qindex[INTER_FRAME] < 16) {
3010
      // Increase active_worst faster at low Q if rate fluctuation is high.
3011
66
      rc->fac_active_worst_inter = 200;
3012
66
      if (rc->avg_frame_qindex[INTER_FRAME] < 8)
3013
64
        rc->fac_active_worst_inter = 400;
3014
66
    }
3015
17.7k
    if (low_content && rc->avg_frame_low_motion > 80) {
3016
2.46k
      rc->af_ratio_onepass_vbr = 15;
3017
15.2k
    } else if (high_content || rc->avg_frame_low_motion < 30) {
3018
10.5k
      rc->af_ratio_onepass_vbr = 5;
3019
10.5k
      rc->gfu_boost = DEFAULT_GF_BOOST >> 2;
3020
10.5k
    }
3021
17.7k
    if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf) {
3022
      // Flag to disable usage of ARF based on past usage, only allow this
3023
      // disabling if current frame/group does not start with key frame or
3024
      // scene cut. Note perc_arf_usage is only computed for speed >= 5.
3025
17.7k
      int arf_usage_low =
3026
17.7k
          (cm->frame_type != KEY_FRAME && !rc->high_source_sad &&
3027
15.0k
           cpi->rc.perc_arf_usage < 15 && cpi->oxcf.speed >= 5);
3028
      // Don't use alt-ref for this group under certain conditions.
3029
17.7k
      if (arf_usage_low ||
3030
9.12k
          (rc->high_source_sad_lagindex > 0 &&
3031
0
           rc->high_source_sad_lagindex <= rc->frames_till_gf_update_due) ||
3032
9.12k
          (avg_source_sad_lag > 3 * sad_thresh1 >> 3)) {
3033
8.63k
        rc->source_alt_ref_pending = 0;
3034
8.63k
        rc->alt_ref_gf_group = 0;
3035
9.12k
      } else {
3036
9.12k
        rc->source_alt_ref_pending = 1;
3037
9.12k
        rc->alt_ref_gf_group = 1;
3038
        // If alt-ref is used for this gf group, limit the interval.
3039
9.12k
        if (rc->baseline_gf_interval > 12) {
3040
5.55k
          rc->baseline_gf_interval = 12;
3041
5.55k
          rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3042
5.55k
        }
3043
9.12k
      }
3044
17.7k
    }
3045
17.7k
    target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
3046
17.7k
    vp9_rc_set_frame_target(cpi, target);
3047
17.7k
  }
3048
321k
  rc->prev_avg_source_sad_lag = avg_source_sad_lag;
3049
321k
}
3050
3051
// Compute average source sad (temporal sad: between current source and
3052
// previous source) over a subset of superblocks. Use this is detect big changes
3053
// in content and allow rate control to react.
3054
// This function also handles special case of lag_in_frames, to measure content
3055
// level in #future frames set by the lag_in_frames.
3056
329k
void vp9_scene_detection_onepass(VP9_COMP *cpi) {
3057
329k
  VP9_COMMON *const cm = &cpi->common;
3058
329k
  RATE_CONTROL *const rc = &cpi->rc;
3059
329k
  YV12_BUFFER_CONFIG const *unscaled_src = cpi->un_scaled_source;
3060
329k
  YV12_BUFFER_CONFIG const *unscaled_last_src = cpi->unscaled_last_source;
3061
329k
  uint8_t *src_y;
3062
329k
  int src_ystride;
3063
329k
  int src_width;
3064
329k
  int src_height;
3065
329k
  uint8_t *last_src_y;
3066
329k
  int last_src_ystride;
3067
329k
  int last_src_width;
3068
329k
  int last_src_height;
3069
329k
  if (cpi->un_scaled_source == NULL || cpi->unscaled_last_source == NULL ||
3070
321k
      (cpi->use_svc && cpi->svc.current_superframe == 0))
3071
7.48k
    return;
3072
321k
  src_y = unscaled_src->y_buffer;
3073
321k
  src_ystride = unscaled_src->y_stride;
3074
321k
  src_width = unscaled_src->y_width;
3075
321k
  src_height = unscaled_src->y_height;
3076
321k
  last_src_y = unscaled_last_src->y_buffer;
3077
321k
  last_src_ystride = unscaled_last_src->y_stride;
3078
321k
  last_src_width = unscaled_last_src->y_width;
3079
321k
  last_src_height = unscaled_last_src->y_height;
3080
321k
#if CONFIG_VP9_HIGHBITDEPTH
3081
321k
  if (cm->use_highbitdepth) return;
3082
321k
#endif
3083
321k
  rc->high_source_sad = 0;
3084
321k
  rc->high_num_blocks_with_motion = 0;
3085
  // For SVC: scene detection is only checked on first spatial layer of
3086
  // the superframe using the original/unscaled resolutions.
3087
321k
  if (cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode &&
3088
321k
      src_width == last_src_width && src_height == last_src_height) {
3089
321k
    YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS] = { NULL };
3090
321k
    int num_mi_cols = cm->mi_cols;
3091
321k
    int num_mi_rows = cm->mi_rows;
3092
321k
    int start_frame = 0;
3093
321k
    int frames_to_buffer = 1;
3094
321k
    int frame = 0;
3095
321k
    int scene_cut_force_key_frame = 0;
3096
321k
    int num_zero_temp_sad = 0;
3097
321k
    uint64_t avg_sad_current = 0;
3098
321k
    uint32_t min_thresh = 20000;  // ~5 * 64 * 64
3099
321k
    float thresh = 8.0f;
3100
321k
    uint32_t thresh_key = 140000;
3101
321k
    if (cpi->oxcf.speed <= 5) thresh_key = 240000;
3102
321k
    if (cpi->oxcf.content != VP9E_CONTENT_SCREEN) min_thresh = 65000;
3103
321k
    if (cpi->oxcf.rc_mode == VPX_VBR) thresh = 2.1f;
3104
321k
    if (cpi->use_svc && cpi->svc.number_spatial_layers > 1) {
3105
0
      const int aligned_width = ALIGN_POWER_OF_TWO(src_width, MI_SIZE_LOG2);
3106
0
      const int aligned_height = ALIGN_POWER_OF_TWO(src_height, MI_SIZE_LOG2);
3107
0
      num_mi_cols = aligned_width >> MI_SIZE_LOG2;
3108
0
      num_mi_rows = aligned_height >> MI_SIZE_LOG2;
3109
0
    }
3110
321k
    if (cpi->oxcf.lag_in_frames > 0) {
3111
321k
      frames_to_buffer = (cm->current_video_frame == 1)
3112
321k
                             ? (int)vp9_lookahead_depth(cpi->lookahead) - 1
3113
321k
                             : 2;
3114
321k
      start_frame = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
3115
1.03M
      for (frame = 0; frame < frames_to_buffer; ++frame) {
3116
711k
        const int lagframe_idx = start_frame - frame;
3117
711k
        if (lagframe_idx >= 0) {
3118
696k
          struct lookahead_entry *buf =
3119
696k
              vp9_lookahead_peek(cpi->lookahead, lagframe_idx);
3120
696k
          frames[frame] = &buf->img;
3121
696k
        }
3122
711k
      }
3123
      // The avg_sad for this current frame is the value of frame#1
3124
      // (first future frame) from previous frame.
3125
321k
      avg_sad_current = rc->avg_source_sad[1];
3126
321k
      if (avg_sad_current >
3127
321k
              VPXMAX(min_thresh,
3128
321k
                     (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
3129
0
          cm->current_video_frame > (unsigned int)cpi->oxcf.lag_in_frames)
3130
0
        rc->high_source_sad = 1;
3131
321k
      else
3132
321k
        rc->high_source_sad = 0;
3133
321k
      if (rc->high_source_sad && avg_sad_current > thresh_key)
3134
0
        scene_cut_force_key_frame = 1;
3135
      // Update recursive average for current frame.
3136
321k
      if (avg_sad_current > 0)
3137
0
        rc->avg_source_sad[0] =
3138
0
            (3 * rc->avg_source_sad[0] + avg_sad_current) >> 2;
3139
      // Shift back data, starting at frame#1.
3140
7.71M
      for (frame = 1; frame < cpi->oxcf.lag_in_frames - 1; ++frame)
3141
7.39M
        rc->avg_source_sad[frame] = rc->avg_source_sad[frame + 1];
3142
321k
    }
3143
1.03M
    for (frame = 0; frame < frames_to_buffer; ++frame) {
3144
711k
      if (cpi->oxcf.lag_in_frames == 0 ||
3145
711k
          (frames[frame] != NULL && frames[frame + 1] != NULL &&
3146
381k
           frames[frame]->y_width == frames[frame + 1]->y_width &&
3147
381k
           frames[frame]->y_height == frames[frame + 1]->y_height)) {
3148
381k
        int sbi_row, sbi_col;
3149
381k
        const int lagframe_idx =
3150
381k
            (cpi->oxcf.lag_in_frames == 0) ? 0 : start_frame - frame + 1;
3151
381k
        const BLOCK_SIZE bsize = BLOCK_64X64;
3152
        // Loop over sub-sample of frame, compute average sad over 64x64 blocks.
3153
381k
        uint64_t avg_sad = 0;
3154
381k
        uint64_t tmp_sad = 0;
3155
381k
        int num_samples = 0;
3156
381k
        int sb_cols = (num_mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
3157
381k
        int sb_rows = (num_mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
3158
381k
        if (cpi->oxcf.lag_in_frames > 0) {
3159
381k
          src_y = frames[frame]->y_buffer;
3160
381k
          src_ystride = frames[frame]->y_stride;
3161
381k
          last_src_y = frames[frame + 1]->y_buffer;
3162
381k
          last_src_ystride = frames[frame + 1]->y_stride;
3163
381k
        }
3164
381k
        num_zero_temp_sad = 0;
3165
762k
        for (sbi_row = 0; sbi_row < sb_rows; ++sbi_row) {
3166
762k
          for (sbi_col = 0; sbi_col < sb_cols; ++sbi_col) {
3167
            // Checker-board pattern, ignore boundary.
3168
381k
            if (((sbi_row > 0 && sbi_col > 0) &&
3169
0
                 (sbi_row < sb_rows - 1 && sbi_col < sb_cols - 1) &&
3170
0
                 ((sbi_row % 2 == 0 && sbi_col % 2 == 0) ||
3171
0
                  (sbi_row % 2 != 0 && sbi_col % 2 != 0)))) {
3172
0
              tmp_sad = cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y,
3173
0
                                               last_src_ystride);
3174
0
              avg_sad += tmp_sad;
3175
0
              num_samples++;
3176
0
              if (tmp_sad == 0) num_zero_temp_sad++;
3177
0
            }
3178
381k
            src_y += 64;
3179
381k
            last_src_y += 64;
3180
381k
          }
3181
381k
          src_y += (src_ystride << 6) - (sb_cols << 6);
3182
381k
          last_src_y += (last_src_ystride << 6) - (sb_cols << 6);
3183
381k
        }
3184
381k
        if (num_samples > 0) avg_sad = avg_sad / num_samples;
3185
        // Set high_source_sad flag if we detect very high increase in avg_sad
3186
        // between current and previous frame value(s). Use minimum threshold
3187
        // for cases where there is small change from content that is completely
3188
        // static.
3189
381k
        if (lagframe_idx == 0) {
3190
0
          if (avg_sad >
3191
0
                  VPXMAX(min_thresh,
3192
0
                         (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
3193
0
              rc->frames_since_key > 1 + cpi->svc.number_spatial_layers &&
3194
0
              num_zero_temp_sad < 3 * (num_samples >> 2))
3195
0
            rc->high_source_sad = 1;
3196
0
          else
3197
0
            rc->high_source_sad = 0;
3198
0
          if (rc->high_source_sad && avg_sad > thresh_key)
3199
0
            scene_cut_force_key_frame = 1;
3200
0
          if (avg_sad > 0 || cpi->oxcf.rc_mode == VPX_CBR)
3201
0
            rc->avg_source_sad[0] = (3 * rc->avg_source_sad[0] + avg_sad) >> 2;
3202
381k
        } else {
3203
381k
          rc->avg_source_sad[lagframe_idx] = avg_sad;
3204
381k
        }
3205
381k
        if (num_zero_temp_sad < (3 * num_samples >> 2))
3206
0
          rc->high_num_blocks_with_motion = 1;
3207
381k
      }
3208
711k
    }
3209
    // For CBR non-screen content mode, check if we should reset the rate
3210
    // control. Reset is done if high_source_sad is detected and the rate
3211
    // control is at very low QP with rate correction factor at min level.
3212
321k
    if (cpi->oxcf.rc_mode == VPX_CBR &&
3213
0
        cpi->oxcf.content != VP9E_CONTENT_SCREEN && !cpi->use_svc) {
3214
0
      if (rc->high_source_sad && rc->last_q[INTER_FRAME] == rc->best_quality &&
3215
0
          rc->avg_frame_qindex[INTER_FRAME] < (rc->best_quality << 1) &&
3216
0
          rc->rate_correction_factors[INTER_NORMAL] == MIN_BPB_FACTOR) {
3217
0
        rc->rate_correction_factors[INTER_NORMAL] = 0.5;
3218
0
        rc->avg_frame_qindex[INTER_FRAME] = rc->worst_quality;
3219
0
        rc->buffer_level = rc->optimal_buffer_level;
3220
0
        rc->bits_off_target = rc->optimal_buffer_level;
3221
0
        rc->reset_high_source_sad = 1;
3222
0
      }
3223
0
      if (cm->frame_type != KEY_FRAME && rc->reset_high_source_sad)
3224
0
        rc->this_frame_target = rc->avg_frame_bandwidth;
3225
0
    }
3226
    // For SVC the new (updated) avg_source_sad[0] for the current superframe
3227
    // updates the setting for all layers.
3228
321k
    if (cpi->use_svc) {
3229
0
      int sl, tl;
3230
0
      SVC *const svc = &cpi->svc;
3231
0
      for (sl = 0; sl < svc->number_spatial_layers; ++sl)
3232
0
        for (tl = 0; tl < svc->number_temporal_layers; ++tl) {
3233
0
          int layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
3234
0
          LAYER_CONTEXT *const lc = &svc->layer_context[layer];
3235
0
          RATE_CONTROL *const lrc = &lc->rc;
3236
0
          lrc->avg_source_sad[0] = rc->avg_source_sad[0];
3237
0
        }
3238
0
    }
3239
    // For VBR, under scene change/high content change, force golden refresh.
3240
321k
    if (cpi->oxcf.rc_mode == VPX_VBR && cm->frame_type != KEY_FRAME &&
3241
303k
        rc->high_source_sad && rc->frames_to_key > 3 &&
3242
0
        rc->count_last_scene_change > 4 &&
3243
0
        cpi->ext_refresh_frame_flags_pending == 0) {
3244
0
      int target;
3245
0
      cpi->refresh_golden_frame = 1;
3246
0
      if (scene_cut_force_key_frame) cm->frame_type = KEY_FRAME;
3247
0
      rc->source_alt_ref_pending = 0;
3248
0
      if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf)
3249
0
        rc->source_alt_ref_pending = 1;
3250
0
      rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
3251
0
      rc->baseline_gf_interval =
3252
0
          VPXMIN(20, VPXMAX(10, rc->baseline_gf_interval));
3253
0
      adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
3254
0
      rc->frames_till_gf_update_due = rc->baseline_gf_interval;
3255
0
      target = vp9_calc_pframe_target_size_one_pass_vbr(cpi);
3256
0
      vp9_rc_set_frame_target(cpi, target);
3257
0
      rc->count_last_scene_change = 0;
3258
321k
    } else {
3259
321k
      rc->count_last_scene_change++;
3260
321k
    }
3261
    // If lag_in_frame is used, set the gf boost and interval.
3262
321k
    if (cpi->oxcf.lag_in_frames > 0)
3263
321k
      adjust_gf_boost_lag_one_pass_vbr(cpi, avg_sad_current);
3264
321k
  }
3265
321k
}
3266
3267
// Test if encoded frame will significantly overshoot the target bitrate, and
3268
// if so, set the QP, reset/adjust some rate control parameters, and return 1.
3269
// frame_size = -1 means frame has not been encoded.
3270
0
int vp9_encodedframe_overshoot(VP9_COMP *cpi, int frame_size, int *q) {
3271
0
  VP9_COMMON *const cm = &cpi->common;
3272
0
  RATE_CONTROL *const rc = &cpi->rc;
3273
0
  SPEED_FEATURES *const sf = &cpi->sf;
3274
0
  int thresh_qp = 7 * (rc->worst_quality >> 3);
3275
0
  int thresh_rate = rc->avg_frame_bandwidth << 3;
3276
  // Lower thresh_qp for video (more overshoot at lower Q) to be
3277
  // more conservative for video.
3278
0
  if (cpi->oxcf.content != VP9E_CONTENT_SCREEN)
3279
0
    thresh_qp = 3 * (rc->worst_quality >> 2);
3280
  // If this decision is not based on an encoded frame size but just on
3281
  // scene/slide change detection (i.e., re_encode_overshoot_cbr_rt ==
3282
  // FAST_DETECTION_MAXQ), for now skip the (frame_size > thresh_rate)
3283
  // condition in this case.
3284
  // TODO(marpan): Use a better size/rate condition for this case and
3285
  // adjust thresholds.
3286
0
  if ((sf->overshoot_detection_cbr_rt == FAST_DETECTION_MAXQ ||
3287
0
       frame_size > thresh_rate) &&
3288
0
      cm->base_qindex < thresh_qp) {
3289
0
    double rate_correction_factor =
3290
0
        cpi->rc.rate_correction_factors[INTER_NORMAL];
3291
0
    const int target_size = cpi->rc.avg_frame_bandwidth;
3292
0
    const uint64_t sad_thr = 64 * 64 * 32;
3293
0
    int force_maxqp = 1;
3294
0
    double new_correction_factor;
3295
0
    int target_bits_per_mb;
3296
0
    double q2;
3297
0
    int enumerator;
3298
    // Set a larger QP.
3299
0
    if (cpi->oxcf.content != VP9E_CONTENT_SCREEN &&
3300
0
        (rc->buffer_level > (3 * rc->optimal_buffer_level) >> 2) &&
3301
0
        (cpi->rc.avg_source_sad[0] < sad_thr)) {
3302
0
      *q = (*q + cpi->rc.worst_quality) >> 1;
3303
0
      force_maxqp = 0;
3304
0
    } else {
3305
0
      *q = cpi->rc.worst_quality;
3306
0
    }
3307
0
    cpi->cyclic_refresh->counter_encode_maxq_scene_change = 0;
3308
0
    cpi->rc.re_encode_maxq_scene_change = 1;
3309
    // If the frame_size is much larger than the threshold (big content change)
3310
    // and the encoded frame used alot of Intra modes, then force hybrid_intra
3311
    // encoding for the re-encode on this scene change. hybrid_intra will
3312
    // use rd-based intra mode selection for small blocks.
3313
0
    if (sf->overshoot_detection_cbr_rt == RE_ENCODE_MAXQ &&
3314
0
        frame_size > (thresh_rate << 1) && cpi->svc.spatial_layer_id == 0) {
3315
0
      MODE_INFO **mi = cm->mi_grid_visible;
3316
0
      int sum_intra_usage = 0;
3317
0
      int mi_row, mi_col;
3318
0
      for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) {
3319
0
        for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
3320
0
          if (mi[0]->ref_frame[0] == INTRA_FRAME) sum_intra_usage++;
3321
0
          mi++;
3322
0
        }
3323
0
        mi += 8;
3324
0
      }
3325
0
      sum_intra_usage = 100 * sum_intra_usage / (cm->mi_rows * cm->mi_cols);
3326
0
      if (sum_intra_usage > 60) cpi->rc.hybrid_intra_scene_change = 1;
3327
0
    }
3328
    // Adjust avg_frame_qindex, buffer_level, and rate correction factors, as
3329
    // these parameters will affect QP selection for subsequent frames. If they
3330
    // have settled down to a very different (low QP) state, then not adjusting
3331
    // them may cause next frame to select low QP and overshoot again.
3332
0
    cpi->rc.avg_frame_qindex[INTER_FRAME] = *q;
3333
0
    rc->buffer_level = rc->optimal_buffer_level;
3334
0
    rc->bits_off_target = rc->optimal_buffer_level;
3335
    // Reset rate under/over-shoot flags.
3336
0
    cpi->rc.rc_1_frame = 0;
3337
0
    cpi->rc.rc_2_frame = 0;
3338
    // Adjust rate correction factor.
3339
0
    target_bits_per_mb =
3340
0
        (int)(((uint64_t)target_size << BPER_MB_NORMBITS) / cm->MBs);
3341
    // Rate correction factor based on target_bits_per_mb and qp (==max_QP).
3342
    // This comes from the inverse computation of vp9_rc_bits_per_mb().
3343
0
    q2 = vp9_convert_qindex_to_q(*q, cm->bit_depth);
3344
0
    enumerator = 1800000;  // Factor for inter frame.
3345
0
    enumerator += (int)(enumerator * q2) >> 12;
3346
0
    new_correction_factor = (double)target_bits_per_mb * q2 / enumerator;
3347
0
    if (new_correction_factor > rate_correction_factor) {
3348
0
      rate_correction_factor =
3349
0
          VPXMIN(2.0 * rate_correction_factor, new_correction_factor);
3350
0
      if (rate_correction_factor > MAX_BPB_FACTOR)
3351
0
        rate_correction_factor = MAX_BPB_FACTOR;
3352
0
      cpi->rc.rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
3353
0
    }
3354
    // For temporal layers, reset the rate control parametes across all
3355
    // temporal layers.
3356
    // If the first_spatial_layer_to_encode > 0, then this superframe has
3357
    // skipped lower base layers. So in this case we should also reset and
3358
    // force max-q for spatial layers < first_spatial_layer_to_encode.
3359
    // For the case of no inter-layer prediction on delta frames: reset and
3360
    // force max-q for all spatial layers, to avoid excessive frame drops.
3361
0
    if (cpi->use_svc) {
3362
0
      int tl = 0;
3363
0
      int sl = 0;
3364
0
      SVC *svc = &cpi->svc;
3365
0
      int num_spatial_layers = VPXMAX(1, svc->first_spatial_layer_to_encode);
3366
0
      if (svc->disable_inter_layer_pred != INTER_LAYER_PRED_ON)
3367
0
        num_spatial_layers = svc->number_spatial_layers;
3368
0
      for (sl = 0; sl < num_spatial_layers; ++sl) {
3369
0
        for (tl = 0; tl < svc->number_temporal_layers; ++tl) {
3370
0
          const int layer =
3371
0
              LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
3372
0
          LAYER_CONTEXT *lc = &svc->layer_context[layer];
3373
0
          RATE_CONTROL *lrc = &lc->rc;
3374
0
          lrc->avg_frame_qindex[INTER_FRAME] = *q;
3375
0
          lrc->buffer_level = lrc->optimal_buffer_level;
3376
0
          lrc->bits_off_target = lrc->optimal_buffer_level;
3377
0
          lrc->rc_1_frame = 0;
3378
0
          lrc->rc_2_frame = 0;
3379
0
          lrc->rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
3380
0
          lrc->force_max_q = force_maxqp;
3381
0
        }
3382
0
      }
3383
0
    }
3384
0
    return 1;
3385
0
  } else {
3386
0
    return 0;
3387
0
  }
3388
0
}