]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_ratectrl.c
Merge changes from topic "clang-format"
[libvpx] / vp9 / encoder / vp9_ratectrl.c
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 <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17
18 #include "./vpx_dsp_rtcd.h"
19 #include "vpx_dsp/vpx_dsp_common.h"
20 #include "vpx_mem/vpx_mem.h"
21 #include "vpx_ports/mem.h"
22 #include "vpx_ports/system_state.h"
23
24 #include "vp9/common/vp9_alloccommon.h"
25 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
26 #include "vp9/common/vp9_common.h"
27 #include "vp9/common/vp9_entropymode.h"
28 #include "vp9/common/vp9_quant_common.h"
29 #include "vp9/common/vp9_seg_common.h"
30
31 #include "vp9/encoder/vp9_encodemv.h"
32 #include "vp9/encoder/vp9_ratectrl.h"
33
34 // Max rate target for 1080P and below encodes under normal circumstances
35 // (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
36 #define MAX_MB_RATE 250
37 #define MAXRATE_1080P 2025000
38
39 #define DEFAULT_KF_BOOST 2000
40 #define DEFAULT_GF_BOOST 2000
41
42 #define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
43
44 #define MIN_BPB_FACTOR 0.005
45 #define MAX_BPB_FACTOR 50
46
47 #if CONFIG_VP9_HIGHBITDEPTH
48 #define ASSIGN_MINQ_TABLE(bit_depth, name)                   \
49   do {                                                       \
50     switch (bit_depth) {                                     \
51       case VPX_BITS_8: name = name##_8; break;               \
52       case VPX_BITS_10: name = name##_10; break;             \
53       case VPX_BITS_12: name = name##_12; break;             \
54       default:                                               \
55         assert(0 &&                                          \
56                "bit_depth should be VPX_BITS_8, VPX_BITS_10" \
57                " or VPX_BITS_12");                           \
58         name = NULL;                                         \
59     }                                                        \
60   } while (0)
61 #else
62 #define ASSIGN_MINQ_TABLE(bit_depth, name) \
63   do {                                     \
64     (void)bit_depth;                       \
65     name = name##_8;                       \
66   } while (0)
67 #endif
68
69 // Tables relating active max Q to active min Q
70 static int kf_low_motion_minq_8[QINDEX_RANGE];
71 static int kf_high_motion_minq_8[QINDEX_RANGE];
72 static int arfgf_low_motion_minq_8[QINDEX_RANGE];
73 static int arfgf_high_motion_minq_8[QINDEX_RANGE];
74 static int inter_minq_8[QINDEX_RANGE];
75 static int rtc_minq_8[QINDEX_RANGE];
76
77 #if CONFIG_VP9_HIGHBITDEPTH
78 static int kf_low_motion_minq_10[QINDEX_RANGE];
79 static int kf_high_motion_minq_10[QINDEX_RANGE];
80 static int arfgf_low_motion_minq_10[QINDEX_RANGE];
81 static int arfgf_high_motion_minq_10[QINDEX_RANGE];
82 static int inter_minq_10[QINDEX_RANGE];
83 static int rtc_minq_10[QINDEX_RANGE];
84 static int kf_low_motion_minq_12[QINDEX_RANGE];
85 static int kf_high_motion_minq_12[QINDEX_RANGE];
86 static int arfgf_low_motion_minq_12[QINDEX_RANGE];
87 static int arfgf_high_motion_minq_12[QINDEX_RANGE];
88 static int inter_minq_12[QINDEX_RANGE];
89 static int rtc_minq_12[QINDEX_RANGE];
90 #endif
91
92 #ifdef AGGRESSIVE_VBR
93 static int gf_high = 2400;
94 static int gf_low = 400;
95 static int kf_high = 4000;
96 static int kf_low = 400;
97 #else
98 static int gf_high = 2000;
99 static int gf_low = 400;
100 static int kf_high = 5000;
101 static int kf_low = 400;
102 #endif
103
104 // Functions to compute the active minq lookup table entries based on a
105 // formulaic approach to facilitate easier adjustment of the Q tables.
106 // The formulae were derived from computing a 3rd order polynomial best
107 // fit to the original data (after plotting real maxq vs minq (not q index))
108 static int get_minq_index(double maxq, double x3, double x2, double x1,
109                           vpx_bit_depth_t bit_depth) {
110   int i;
111   const double minqtarget = VPXMIN(((x3 * maxq + x2) * maxq + x1) * maxq, maxq);
112
113   // Special case handling to deal with the step from q2.0
114   // down to lossless mode represented by q 1.0.
115   if (minqtarget <= 2.0) return 0;
116
117   for (i = 0; i < QINDEX_RANGE; i++) {
118     if (minqtarget <= vp9_convert_qindex_to_q(i, bit_depth)) return i;
119   }
120
121   return QINDEX_RANGE - 1;
122 }
123
124 static void init_minq_luts(int *kf_low_m, int *kf_high_m, int *arfgf_low,
125                            int *arfgf_high, int *inter, int *rtc,
126                            vpx_bit_depth_t bit_depth) {
127   int i;
128   for (i = 0; i < QINDEX_RANGE; i++) {
129     const double maxq = vp9_convert_qindex_to_q(i, bit_depth);
130     kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
131     kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
132 #ifdef AGGRESSIVE_VBR
133     arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.275, bit_depth);
134     inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.80, bit_depth);
135 #else
136     arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
137     inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
138 #endif
139     arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
140     rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
141   }
142 }
143
144 void vp9_rc_init_minq_luts(void) {
145   init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
146                  arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
147                  inter_minq_8, rtc_minq_8, VPX_BITS_8);
148 #if CONFIG_VP9_HIGHBITDEPTH
149   init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
150                  arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
151                  inter_minq_10, rtc_minq_10, VPX_BITS_10);
152   init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
153                  arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
154                  inter_minq_12, rtc_minq_12, VPX_BITS_12);
155 #endif
156 }
157
158 // These functions use formulaic calculations to make playing with the
159 // quantizer tables easier. If necessary they can be replaced by lookup
160 // tables if and when things settle down in the experimental bitstream
161 double vp9_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
162 // Convert the index to a real Q value (scaled down to match old Q values)
163 #if CONFIG_VP9_HIGHBITDEPTH
164   switch (bit_depth) {
165     case VPX_BITS_8: return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
166     case VPX_BITS_10: return vp9_ac_quant(qindex, 0, bit_depth) / 16.0;
167     case VPX_BITS_12: return vp9_ac_quant(qindex, 0, bit_depth) / 64.0;
168     default:
169       assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
170       return -1.0;
171   }
172 #else
173   return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
174 #endif
175 }
176
177 int vp9_convert_q_to_qindex(double q_val, vpx_bit_depth_t bit_depth) {
178   int i;
179
180   for (i = 0; i < QINDEX_RANGE; ++i)
181     if (vp9_convert_qindex_to_q(i, bit_depth) >= q_val) break;
182
183   if (i == QINDEX_RANGE) i--;
184
185   return i;
186 }
187
188 int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
189                        double correction_factor, vpx_bit_depth_t bit_depth) {
190   const double q = vp9_convert_qindex_to_q(qindex, bit_depth);
191   int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
192
193   assert(correction_factor <= MAX_BPB_FACTOR &&
194          correction_factor >= MIN_BPB_FACTOR);
195
196   // q based adjustment to baseline enumerator
197   enumerator += (int)(enumerator * q) >> 12;
198   return (int)(enumerator * correction_factor / q);
199 }
200
201 int vp9_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
202                            double correction_factor,
203                            vpx_bit_depth_t bit_depth) {
204   const int bpm =
205       (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor, bit_depth));
206   return VPXMAX(FRAME_OVERHEAD_BITS,
207                 (int)(((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS));
208 }
209
210 int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
211   const RATE_CONTROL *rc = &cpi->rc;
212   const VP9EncoderConfig *oxcf = &cpi->oxcf;
213
214   if (cpi->oxcf.pass != 2) {
215     const int min_frame_target =
216         VPXMAX(rc->min_frame_bandwidth, rc->avg_frame_bandwidth >> 5);
217     if (target < min_frame_target) target = min_frame_target;
218     if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
219       // If there is an active ARF at this location use the minimum
220       // bits on this frame even if it is a constructed arf.
221       // The active maximum quantizer insures that an appropriate
222       // number of bits will be spent if needed for constructed ARFs.
223       target = min_frame_target;
224     }
225   }
226
227   // Clip the frame target to the maximum allowed value.
228   if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
229
230   if (oxcf->rc_max_inter_bitrate_pct) {
231     const int max_rate =
232         rc->avg_frame_bandwidth * oxcf->rc_max_inter_bitrate_pct / 100;
233     target = VPXMIN(target, max_rate);
234   }
235   return target;
236 }
237
238 int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
239   const RATE_CONTROL *rc = &cpi->rc;
240   const VP9EncoderConfig *oxcf = &cpi->oxcf;
241   if (oxcf->rc_max_intra_bitrate_pct) {
242     const int max_rate =
243         rc->avg_frame_bandwidth * oxcf->rc_max_intra_bitrate_pct / 100;
244     target = VPXMIN(target, max_rate);
245   }
246   if (target > rc->max_frame_bandwidth) target = rc->max_frame_bandwidth;
247   return target;
248 }
249
250 // Update the buffer level for higher temporal layers, given the encoded current
251 // temporal layer.
252 static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
253   int i = 0;
254   int current_temporal_layer = svc->temporal_layer_id;
255   for (i = current_temporal_layer + 1; i < svc->number_temporal_layers; ++i) {
256     const int layer =
257         LAYER_IDS_TO_IDX(svc->spatial_layer_id, i, svc->number_temporal_layers);
258     LAYER_CONTEXT *lc = &svc->layer_context[layer];
259     RATE_CONTROL *lrc = &lc->rc;
260     int bits_off_for_this_layer =
261         (int)(lc->target_bandwidth / lc->framerate - encoded_frame_size);
262     lrc->bits_off_target += bits_off_for_this_layer;
263
264     // Clip buffer level to maximum buffer size for the layer.
265     lrc->bits_off_target =
266         VPXMIN(lrc->bits_off_target, lrc->maximum_buffer_size);
267     lrc->buffer_level = lrc->bits_off_target;
268   }
269 }
270
271 // Update the buffer level: leaky bucket model.
272 static void update_buffer_level(VP9_COMP *cpi, int encoded_frame_size) {
273   const VP9_COMMON *const cm = &cpi->common;
274   RATE_CONTROL *const rc = &cpi->rc;
275
276   // Non-viewable frames are a special case and are treated as pure overhead.
277   if (!cm->show_frame) {
278     rc->bits_off_target -= encoded_frame_size;
279   } else {
280     rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
281   }
282
283   // Clip the buffer level to the maximum specified buffer size.
284   rc->bits_off_target = VPXMIN(rc->bits_off_target, rc->maximum_buffer_size);
285
286   // For screen-content mode, and if frame-dropper is off, don't let buffer
287   // level go below threshold, given here as -rc->maximum_ buffer_size.
288   if (cpi->oxcf.content == VP9E_CONTENT_SCREEN &&
289       cpi->oxcf.drop_frames_water_mark == 0)
290     rc->bits_off_target = VPXMAX(rc->bits_off_target, -rc->maximum_buffer_size);
291
292   rc->buffer_level = rc->bits_off_target;
293
294   if (is_one_pass_cbr_svc(cpi)) {
295     update_layer_buffer_level(&cpi->svc, encoded_frame_size);
296   }
297 }
298
299 int vp9_rc_get_default_min_gf_interval(int width, int height,
300                                        double framerate) {
301   // Assume we do not need any constraint lower than 4K 20 fps
302   static const double factor_safe = 3840 * 2160 * 20.0;
303   const double factor = width * height * framerate;
304   const int default_interval =
305       clamp((int)(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
306
307   if (factor <= factor_safe)
308     return default_interval;
309   else
310     return VPXMAX(default_interval,
311                   (int)(MIN_GF_INTERVAL * factor / factor_safe + 0.5));
312   // Note this logic makes:
313   // 4K24: 5
314   // 4K30: 6
315   // 4K60: 12
316 }
317
318 int vp9_rc_get_default_max_gf_interval(double framerate, int min_gf_interval) {
319   int interval = VPXMIN(MAX_GF_INTERVAL, (int)(framerate * 0.75));
320   interval += (interval & 0x01);  // Round to even value
321   return VPXMAX(interval, min_gf_interval);
322 }
323
324 void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
325   int i;
326
327   if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
328     rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
329     rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
330   } else {
331     rc->avg_frame_qindex[KEY_FRAME] =
332         (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
333     rc->avg_frame_qindex[INTER_FRAME] =
334         (oxcf->worst_allowed_q + oxcf->best_allowed_q) / 2;
335   }
336
337   rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
338   rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
339
340   rc->buffer_level = rc->starting_buffer_level;
341   rc->bits_off_target = rc->starting_buffer_level;
342
343   rc->rolling_target_bits = rc->avg_frame_bandwidth;
344   rc->rolling_actual_bits = rc->avg_frame_bandwidth;
345   rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
346   rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
347
348   rc->total_actual_bits = 0;
349   rc->total_target_bits = 0;
350   rc->total_target_vs_actual = 0;
351   rc->avg_frame_low_motion = 0;
352   rc->count_last_scene_change = 0;
353   rc->af_ratio_onepass_vbr = 10;
354   rc->prev_avg_source_sad_lag = 0;
355   rc->high_source_sad = 0;
356   rc->reset_high_source_sad = 0;
357   rc->high_source_sad_lagindex = -1;
358   rc->alt_ref_gf_group = 0;
359   rc->last_frame_is_src_altref = 0;
360   rc->fac_active_worst_inter = 150;
361   rc->fac_active_worst_gf = 100;
362   rc->force_qpmin = 0;
363   for (i = 0; i < MAX_LAG_BUFFERS; ++i) rc->avg_source_sad[i] = 0;
364   rc->frames_since_key = 8;  // Sensible default for first frame.
365   rc->this_key_frame_forced = 0;
366   rc->next_key_frame_forced = 0;
367   rc->source_alt_ref_pending = 0;
368   rc->source_alt_ref_active = 0;
369
370   rc->frames_till_gf_update_due = 0;
371   rc->ni_av_qi = oxcf->worst_allowed_q;
372   rc->ni_tot_qi = 0;
373   rc->ni_frames = 0;
374
375   rc->tot_q = 0.0;
376   rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
377
378   for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
379     rc->rate_correction_factors[i] = 1.0;
380   }
381
382   rc->min_gf_interval = oxcf->min_gf_interval;
383   rc->max_gf_interval = oxcf->max_gf_interval;
384   if (rc->min_gf_interval == 0)
385     rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
386         oxcf->width, oxcf->height, oxcf->init_framerate);
387   if (rc->max_gf_interval == 0)
388     rc->max_gf_interval = vp9_rc_get_default_max_gf_interval(
389         oxcf->init_framerate, rc->min_gf_interval);
390   rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
391 }
392
393 int vp9_rc_drop_frame(VP9_COMP *cpi) {
394   const VP9EncoderConfig *oxcf = &cpi->oxcf;
395   RATE_CONTROL *const rc = &cpi->rc;
396   if (!oxcf->drop_frames_water_mark ||
397       (is_one_pass_cbr_svc(cpi) &&
398        cpi->svc.spatial_layer_id > cpi->svc.first_spatial_layer_to_encode)) {
399     return 0;
400   } else {
401     if (rc->buffer_level < 0) {
402       // Always drop if buffer is below 0.
403       return 1;
404     } else {
405       // If buffer is below drop_mark, for now just drop every other frame
406       // (starting with the next frame) until it increases back over drop_mark.
407       int drop_mark =
408           (int)(oxcf->drop_frames_water_mark * rc->optimal_buffer_level / 100);
409       if ((rc->buffer_level > drop_mark) && (rc->decimation_factor > 0)) {
410         --rc->decimation_factor;
411       } else if (rc->buffer_level <= drop_mark && rc->decimation_factor == 0) {
412         rc->decimation_factor = 1;
413       }
414       if (rc->decimation_factor > 0) {
415         if (rc->decimation_count > 0) {
416           --rc->decimation_count;
417           return 1;
418         } else {
419           rc->decimation_count = rc->decimation_factor;
420           return 0;
421         }
422       } else {
423         rc->decimation_count = 0;
424         return 0;
425       }
426     }
427   }
428 }
429
430 static double get_rate_correction_factor(const VP9_COMP *cpi) {
431   const RATE_CONTROL *const rc = &cpi->rc;
432   double rcf;
433
434   if (cpi->common.frame_type == KEY_FRAME) {
435     rcf = rc->rate_correction_factors[KF_STD];
436   } else if (cpi->oxcf.pass == 2) {
437     RATE_FACTOR_LEVEL rf_lvl =
438         cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
439     rcf = rc->rate_correction_factors[rf_lvl];
440   } else {
441     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
442         !rc->is_src_frame_alt_ref && !cpi->use_svc &&
443         (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 100))
444       rcf = rc->rate_correction_factors[GF_ARF_STD];
445     else
446       rcf = rc->rate_correction_factors[INTER_NORMAL];
447   }
448   rcf *= rcf_mult[rc->frame_size_selector];
449   return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
450 }
451
452 static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
453   RATE_CONTROL *const rc = &cpi->rc;
454
455   // Normalize RCF to account for the size-dependent scaling factor.
456   factor /= rcf_mult[cpi->rc.frame_size_selector];
457
458   factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
459
460   if (cpi->common.frame_type == KEY_FRAME) {
461     rc->rate_correction_factors[KF_STD] = factor;
462   } else if (cpi->oxcf.pass == 2) {
463     RATE_FACTOR_LEVEL rf_lvl =
464         cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
465     rc->rate_correction_factors[rf_lvl] = factor;
466   } else {
467     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
468         !rc->is_src_frame_alt_ref && !cpi->use_svc &&
469         (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 100))
470       rc->rate_correction_factors[GF_ARF_STD] = factor;
471     else
472       rc->rate_correction_factors[INTER_NORMAL] = factor;
473   }
474 }
475
476 void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi) {
477   const VP9_COMMON *const cm = &cpi->common;
478   int correction_factor = 100;
479   double rate_correction_factor = get_rate_correction_factor(cpi);
480   double adjustment_limit;
481
482   int projected_size_based_on_q = 0;
483
484   // Do not update the rate factors for arf overlay frames.
485   if (cpi->rc.is_src_frame_alt_ref) return;
486
487   // Clear down mmx registers to allow floating point in what follows
488   vpx_clear_system_state();
489
490   // Work out how big we would have expected the frame to be at this Q given
491   // the current correction factor.
492   // Stay in double to avoid int overflow when values are large
493   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled) {
494     projected_size_based_on_q =
495         vp9_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
496   } else {
497     projected_size_based_on_q =
498         vp9_estimate_bits_at_q(cpi->common.frame_type, cm->base_qindex, cm->MBs,
499                                rate_correction_factor, cm->bit_depth);
500   }
501   // Work out a size correction factor.
502   if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
503     correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
504                               projected_size_based_on_q);
505
506   // More heavily damped adjustment used if we have been oscillating either side
507   // of target.
508   adjustment_limit =
509       0.25 + 0.5 * VPXMIN(1, fabs(log10(0.01 * correction_factor)));
510
511   cpi->rc.q_2_frame = cpi->rc.q_1_frame;
512   cpi->rc.q_1_frame = cm->base_qindex;
513   cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
514   if (correction_factor > 110)
515     cpi->rc.rc_1_frame = -1;
516   else if (correction_factor < 90)
517     cpi->rc.rc_1_frame = 1;
518   else
519     cpi->rc.rc_1_frame = 0;
520
521   // Turn off oscilation detection in the case of massive overshoot.
522   if (cpi->rc.rc_1_frame == -1 && cpi->rc.rc_2_frame == 1 &&
523       correction_factor > 1000) {
524     cpi->rc.rc_2_frame = 0;
525   }
526
527   if (correction_factor > 102) {
528     // We are not already at the worst allowable quality
529     correction_factor =
530         (int)(100 + ((correction_factor - 100) * adjustment_limit));
531     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
532     // Keep rate_correction_factor within limits
533     if (rate_correction_factor > MAX_BPB_FACTOR)
534       rate_correction_factor = MAX_BPB_FACTOR;
535   } else if (correction_factor < 99) {
536     // We are not already at the best allowable quality
537     correction_factor =
538         (int)(100 - ((100 - correction_factor) * adjustment_limit));
539     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
540
541     // Keep rate_correction_factor within limits
542     if (rate_correction_factor < MIN_BPB_FACTOR)
543       rate_correction_factor = MIN_BPB_FACTOR;
544   }
545
546   set_rate_correction_factor(cpi, rate_correction_factor);
547 }
548
549 int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
550                       int active_best_quality, int active_worst_quality) {
551   const VP9_COMMON *const cm = &cpi->common;
552   CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
553   int q = active_worst_quality;
554   int last_error = INT_MAX;
555   int i, target_bits_per_mb, bits_per_mb_at_this_q;
556   const double correction_factor = get_rate_correction_factor(cpi);
557
558   // Calculate required scaling factor based on target frame size and size of
559   // frame produced using previous Q.
560   target_bits_per_mb =
561       (int)(((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs);
562
563   i = active_best_quality;
564
565   do {
566     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled &&
567         cr->apply_cyclic_refresh &&
568         (!cpi->oxcf.gf_cbr_boost_pct || !cpi->refresh_golden_frame)) {
569       bits_per_mb_at_this_q =
570           (int)vp9_cyclic_refresh_rc_bits_per_mb(cpi, i, correction_factor);
571     } else {
572       bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(
573           cm->frame_type, i, correction_factor, cm->bit_depth);
574     }
575
576     if (bits_per_mb_at_this_q <= target_bits_per_mb) {
577       if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
578         q = i;
579       else
580         q = i - 1;
581
582       break;
583     } else {
584       last_error = bits_per_mb_at_this_q - target_bits_per_mb;
585     }
586   } while (++i <= active_worst_quality);
587
588   // In CBR mode, this makes sure q is between oscillating Qs to prevent
589   // resonance.
590   if (cpi->oxcf.rc_mode == VPX_CBR && !cpi->rc.reset_high_source_sad &&
591       (!cpi->oxcf.gf_cbr_boost_pct ||
592        !(cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)) &&
593       (cpi->rc.rc_1_frame * cpi->rc.rc_2_frame == -1) &&
594       cpi->rc.q_1_frame != cpi->rc.q_2_frame) {
595     q = clamp(q, VPXMIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
596               VPXMAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
597   }
598   return q;
599 }
600
601 static int get_active_quality(int q, int gfu_boost, int low, int high,
602                               int *low_motion_minq, int *high_motion_minq) {
603   if (gfu_boost > high) {
604     return low_motion_minq[q];
605   } else if (gfu_boost < low) {
606     return high_motion_minq[q];
607   } else {
608     const int gap = high - low;
609     const int offset = high - gfu_boost;
610     const int qdiff = high_motion_minq[q] - low_motion_minq[q];
611     const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
612     return low_motion_minq[q] + adjustment;
613   }
614 }
615
616 static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
617                                  vpx_bit_depth_t bit_depth) {
618   int *kf_low_motion_minq;
619   int *kf_high_motion_minq;
620   ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
621   ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
622   return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
623                             kf_low_motion_minq, kf_high_motion_minq);
624 }
625
626 static int get_gf_active_quality(const RATE_CONTROL *const rc, int q,
627                                  vpx_bit_depth_t bit_depth) {
628   int *arfgf_low_motion_minq;
629   int *arfgf_high_motion_minq;
630   ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
631   ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
632   return get_active_quality(q, rc->gfu_boost, gf_low, gf_high,
633                             arfgf_low_motion_minq, arfgf_high_motion_minq);
634 }
635
636 static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
637   const RATE_CONTROL *const rc = &cpi->rc;
638   const unsigned int curr_frame = cpi->common.current_video_frame;
639   int active_worst_quality;
640
641   if (cpi->common.frame_type == KEY_FRAME) {
642     active_worst_quality =
643         curr_frame == 0 ? rc->worst_quality : rc->last_q[KEY_FRAME] << 1;
644   } else {
645     if (!rc->is_src_frame_alt_ref &&
646         (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
647       active_worst_quality =
648           curr_frame == 1
649               ? rc->last_q[KEY_FRAME] * 5 >> 2
650               : rc->last_q[INTER_FRAME] * rc->fac_active_worst_gf / 100;
651     } else {
652       active_worst_quality = curr_frame == 1
653                                  ? rc->last_q[KEY_FRAME] << 1
654                                  : rc->avg_frame_qindex[INTER_FRAME] *
655                                        rc->fac_active_worst_inter / 100;
656     }
657   }
658   return VPXMIN(active_worst_quality, rc->worst_quality);
659 }
660
661 // Adjust active_worst_quality level based on buffer level.
662 static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
663   // Adjust active_worst_quality: If buffer is above the optimal/target level,
664   // bring active_worst_quality down depending on fullness of buffer.
665   // If buffer is below the optimal level, let the active_worst_quality go from
666   // ambient Q (at buffer = optimal level) to worst_quality level
667   // (at buffer = critical level).
668   const VP9_COMMON *const cm = &cpi->common;
669   const RATE_CONTROL *rc = &cpi->rc;
670   // Buffer level below which we push active_worst to worst_quality.
671   int64_t critical_level = rc->optimal_buffer_level >> 3;
672   int64_t buff_lvl_step = 0;
673   int adjustment = 0;
674   int active_worst_quality;
675   int ambient_qp;
676   unsigned int num_frames_weight_key = 5 * cpi->svc.number_temporal_layers;
677   if (cm->frame_type == KEY_FRAME || rc->reset_high_source_sad)
678     return rc->worst_quality;
679   // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
680   // for the first few frames following key frame. These are both initialized
681   // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
682   // So for first few frames following key, the qp of that key frame is weighted
683   // into the active_worst_quality setting.
684   ambient_qp = (cm->current_video_frame < num_frames_weight_key)
685                    ? VPXMIN(rc->avg_frame_qindex[INTER_FRAME],
686                             rc->avg_frame_qindex[KEY_FRAME])
687                    : rc->avg_frame_qindex[INTER_FRAME];
688   // For SVC if the current base spatial layer was key frame, use the QP from
689   // that base layer for ambient_qp.
690   if (cpi->use_svc && cpi->svc.spatial_layer_id > 0) {
691     int layer = LAYER_IDS_TO_IDX(0, cpi->svc.temporal_layer_id,
692                                  cpi->svc.number_temporal_layers);
693     const LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
694     if (lc->is_key_frame) {
695       const RATE_CONTROL *lrc = &lc->rc;
696       ambient_qp = VPXMIN(ambient_qp, lrc->last_q[KEY_FRAME]);
697     }
698   }
699   active_worst_quality = VPXMIN(rc->worst_quality, ambient_qp * 5 >> 2);
700   if (rc->buffer_level > rc->optimal_buffer_level) {
701     // Adjust down.
702     // Maximum limit for down adjustment, ~30%.
703     int max_adjustment_down = active_worst_quality / 3;
704     if (max_adjustment_down) {
705       buff_lvl_step = ((rc->maximum_buffer_size - rc->optimal_buffer_level) /
706                        max_adjustment_down);
707       if (buff_lvl_step)
708         adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
709                            buff_lvl_step);
710       active_worst_quality -= adjustment;
711     }
712   } else if (rc->buffer_level > critical_level) {
713     // Adjust up from ambient Q.
714     if (critical_level) {
715       buff_lvl_step = (rc->optimal_buffer_level - critical_level);
716       if (buff_lvl_step) {
717         adjustment = (int)((rc->worst_quality - ambient_qp) *
718                            (rc->optimal_buffer_level - rc->buffer_level) /
719                            buff_lvl_step);
720       }
721       active_worst_quality = ambient_qp + adjustment;
722     }
723   } else {
724     // Set to worst_quality if buffer is below critical level.
725     active_worst_quality = rc->worst_quality;
726   }
727   return active_worst_quality;
728 }
729
730 static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
731                                              int *bottom_index,
732                                              int *top_index) {
733   const VP9_COMMON *const cm = &cpi->common;
734   const RATE_CONTROL *const rc = &cpi->rc;
735   int active_best_quality;
736   int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
737   int q;
738   int *rtc_minq;
739   ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
740
741   if (frame_is_intra_only(cm)) {
742     active_best_quality = rc->best_quality;
743     // Handle the special case for key frames forced when we have reached
744     // the maximum key frame interval. Here force the Q to a range
745     // based on the ambient Q to reduce the risk of popping.
746     if (rc->this_key_frame_forced) {
747       int qindex = rc->last_boosted_qindex;
748       double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
749       int delta_qindex = vp9_compute_qdelta(
750           rc, last_boosted_q, (last_boosted_q * 0.75), cm->bit_depth);
751       active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
752     } else if (cm->current_video_frame > 0) {
753       // not first frame of one pass and kf_boost is set
754       double q_adj_factor = 1.0;
755       double q_val;
756
757       active_best_quality = get_kf_active_quality(
758           rc, rc->avg_frame_qindex[KEY_FRAME], cm->bit_depth);
759
760       // Allow somewhat lower kf minq with small image formats.
761       if ((cm->width * cm->height) <= (352 * 288)) {
762         q_adj_factor -= 0.25;
763       }
764
765       // Convert the adjustment factor to a qindex delta
766       // on active_best_quality.
767       q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
768       active_best_quality +=
769           vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
770     }
771   } else if (!rc->is_src_frame_alt_ref && !cpi->use_svc &&
772              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
773     // Use the lower of active_worst_quality and recent
774     // average Q as basis for GF/ARF best Q limit unless last frame was
775     // a key frame.
776     if (rc->frames_since_key > 1 &&
777         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
778       q = rc->avg_frame_qindex[INTER_FRAME];
779     } else {
780       q = active_worst_quality;
781     }
782     active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
783   } else {
784     // Use the lower of active_worst_quality and recent/average Q.
785     if (cm->current_video_frame > 1) {
786       if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
787         active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
788       else
789         active_best_quality = rtc_minq[active_worst_quality];
790     } else {
791       if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
792         active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
793       else
794         active_best_quality = rtc_minq[active_worst_quality];
795     }
796   }
797
798   // Clip the active best and worst quality values to limits
799   active_best_quality =
800       clamp(active_best_quality, rc->best_quality, rc->worst_quality);
801   active_worst_quality =
802       clamp(active_worst_quality, active_best_quality, rc->worst_quality);
803
804   *top_index = active_worst_quality;
805   *bottom_index = active_best_quality;
806
807 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
808   // Limit Q range for the adaptive loop.
809   if (cm->frame_type == KEY_FRAME && !rc->this_key_frame_forced &&
810       !(cm->current_video_frame == 0)) {
811     int qdelta = 0;
812     vpx_clear_system_state();
813     qdelta = vp9_compute_qdelta_by_rate(
814         &cpi->rc, cm->frame_type, active_worst_quality, 2.0, cm->bit_depth);
815     *top_index = active_worst_quality + qdelta;
816     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
817   }
818 #endif
819
820   // Special case code to try and match quality with forced key frames
821   if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
822     q = rc->last_boosted_qindex;
823   } else {
824     q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
825                           active_worst_quality);
826     if (q > *top_index) {
827       // Special case when we are targeting the max allowed rate
828       if (rc->this_frame_target >= rc->max_frame_bandwidth)
829         *top_index = q;
830       else
831         q = *top_index;
832     }
833   }
834   assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
835   assert(*bottom_index <= rc->worst_quality &&
836          *bottom_index >= rc->best_quality);
837   assert(q <= rc->worst_quality && q >= rc->best_quality);
838   return q;
839 }
840
841 static int get_active_cq_level_one_pass(const RATE_CONTROL *rc,
842                                         const VP9EncoderConfig *const oxcf) {
843   static const double cq_adjust_threshold = 0.1;
844   int active_cq_level = oxcf->cq_level;
845   if (oxcf->rc_mode == VPX_CQ && rc->total_target_bits > 0) {
846     const double x = (double)rc->total_actual_bits / rc->total_target_bits;
847     if (x < cq_adjust_threshold) {
848       active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
849     }
850   }
851   return active_cq_level;
852 }
853
854 #define SMOOTH_PCT_MIN 0.1
855 #define SMOOTH_PCT_DIV 0.05
856 static int get_active_cq_level_two_pass(const TWO_PASS *twopass,
857                                         const RATE_CONTROL *rc,
858                                         const VP9EncoderConfig *const oxcf) {
859   static const double cq_adjust_threshold = 0.1;
860   int active_cq_level = oxcf->cq_level;
861   if (oxcf->rc_mode == VPX_CQ) {
862     if (twopass->mb_smooth_pct > SMOOTH_PCT_MIN) {
863       active_cq_level -=
864           (int)((twopass->mb_smooth_pct - SMOOTH_PCT_MIN) / SMOOTH_PCT_DIV);
865       active_cq_level = VPXMAX(active_cq_level, 0);
866     }
867     if (rc->total_target_bits > 0) {
868       const double x = (double)rc->total_actual_bits / rc->total_target_bits;
869       if (x < cq_adjust_threshold) {
870         active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
871       }
872     }
873   }
874   return active_cq_level;
875 }
876
877 static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
878                                              int *bottom_index,
879                                              int *top_index) {
880   const VP9_COMMON *const cm = &cpi->common;
881   const RATE_CONTROL *const rc = &cpi->rc;
882   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
883   const int cq_level = get_active_cq_level_one_pass(rc, oxcf);
884   int active_best_quality;
885   int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
886   int q;
887   int *inter_minq;
888   ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
889
890   if (frame_is_intra_only(cm)) {
891     if (oxcf->rc_mode == VPX_Q) {
892       int qindex = cq_level;
893       double q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
894       int delta_qindex = vp9_compute_qdelta(rc, q, q * 0.25, cm->bit_depth);
895       active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
896     } else if (rc->this_key_frame_forced) {
897       // Handle the special case for key frames forced when we have reached
898       // the maximum key frame interval. Here force the Q to a range
899       // based on the ambient Q to reduce the risk of popping.
900       int qindex = rc->last_boosted_qindex;
901       double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
902       int delta_qindex = vp9_compute_qdelta(
903           rc, last_boosted_q, last_boosted_q * 0.75, cm->bit_depth);
904       active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
905     } else {
906       // not first frame of one pass and kf_boost is set
907       double q_adj_factor = 1.0;
908       double q_val;
909
910       active_best_quality = get_kf_active_quality(
911           rc, rc->avg_frame_qindex[KEY_FRAME], cm->bit_depth);
912
913       // Allow somewhat lower kf minq with small image formats.
914       if ((cm->width * cm->height) <= (352 * 288)) {
915         q_adj_factor -= 0.25;
916       }
917
918       // Convert the adjustment factor to a qindex delta
919       // on active_best_quality.
920       q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
921       active_best_quality +=
922           vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
923     }
924   } else if (!rc->is_src_frame_alt_ref &&
925              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
926     // Use the lower of active_worst_quality and recent
927     // average Q as basis for GF/ARF best Q limit unless last frame was
928     // a key frame.
929     if (rc->frames_since_key > 1) {
930       if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
931         q = rc->avg_frame_qindex[INTER_FRAME];
932       } else {
933         q = active_worst_quality;
934       }
935     } else {
936       q = rc->avg_frame_qindex[KEY_FRAME];
937     }
938     // For constrained quality dont allow Q less than the cq level
939     if (oxcf->rc_mode == VPX_CQ) {
940       if (q < cq_level) q = cq_level;
941
942       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
943
944       // Constrained quality use slightly lower active best.
945       active_best_quality = active_best_quality * 15 / 16;
946
947     } else if (oxcf->rc_mode == VPX_Q) {
948       int qindex = cq_level;
949       double q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
950       int delta_qindex;
951       if (cpi->refresh_alt_ref_frame)
952         delta_qindex = vp9_compute_qdelta(rc, q, q * 0.40, cm->bit_depth);
953       else
954         delta_qindex = vp9_compute_qdelta(rc, q, q * 0.50, cm->bit_depth);
955       active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
956     } else {
957       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
958     }
959   } else {
960     if (oxcf->rc_mode == VPX_Q) {
961       int qindex = cq_level;
962       double q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
963       double delta_rate[FIXED_GF_INTERVAL] = { 0.50, 1.0, 0.85, 1.0,
964                                                0.70, 1.0, 0.85, 1.0 };
965       int delta_qindex = vp9_compute_qdelta(
966           rc, q, q * delta_rate[cm->current_video_frame % FIXED_GF_INTERVAL],
967           cm->bit_depth);
968       active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
969     } else {
970       // Use the min of the average Q and active_worst_quality as basis for
971       // active_best.
972       if (cm->current_video_frame > 1) {
973         q = VPXMIN(rc->avg_frame_qindex[INTER_FRAME], active_worst_quality);
974         active_best_quality = inter_minq[q];
975       } else {
976         active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
977       }
978       // For the constrained quality mode we don't want
979       // q to fall below the cq level.
980       if ((oxcf->rc_mode == VPX_CQ) && (active_best_quality < cq_level)) {
981         active_best_quality = cq_level;
982       }
983     }
984   }
985
986   // Clip the active best and worst quality values to limits
987   active_best_quality =
988       clamp(active_best_quality, rc->best_quality, rc->worst_quality);
989   active_worst_quality =
990       clamp(active_worst_quality, active_best_quality, rc->worst_quality);
991
992   *top_index = active_worst_quality;
993   *bottom_index = active_best_quality;
994
995 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
996   {
997     int qdelta = 0;
998     vpx_clear_system_state();
999
1000     // Limit Q range for the adaptive loop.
1001     if (cm->frame_type == KEY_FRAME && !rc->this_key_frame_forced &&
1002         !(cm->current_video_frame == 0)) {
1003       qdelta = vp9_compute_qdelta_by_rate(
1004           &cpi->rc, cm->frame_type, active_worst_quality, 2.0, cm->bit_depth);
1005     } else if (!rc->is_src_frame_alt_ref &&
1006                (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1007       qdelta = vp9_compute_qdelta_by_rate(
1008           &cpi->rc, cm->frame_type, active_worst_quality, 1.75, cm->bit_depth);
1009     }
1010     if (rc->high_source_sad && cpi->sf.use_altref_onepass) qdelta = 0;
1011     *top_index = active_worst_quality + qdelta;
1012     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
1013   }
1014 #endif
1015
1016   if (oxcf->rc_mode == VPX_Q) {
1017     q = active_best_quality;
1018     // Special case code to try and match quality with forced key frames
1019   } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
1020     q = rc->last_boosted_qindex;
1021   } else {
1022     q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1023                           active_worst_quality);
1024     if (q > *top_index) {
1025       // Special case when we are targeting the max allowed rate
1026       if (rc->this_frame_target >= rc->max_frame_bandwidth)
1027         *top_index = q;
1028       else
1029         q = *top_index;
1030     }
1031   }
1032
1033   assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1034   assert(*bottom_index <= rc->worst_quality &&
1035          *bottom_index >= rc->best_quality);
1036   assert(q <= rc->worst_quality && q >= rc->best_quality);
1037   return q;
1038 }
1039
1040 int vp9_frame_type_qdelta(const VP9_COMP *cpi, int rf_level, int q) {
1041   static const double rate_factor_deltas[RATE_FACTOR_LEVELS] = {
1042     1.00,  // INTER_NORMAL
1043     1.00,  // INTER_HIGH
1044     1.50,  // GF_ARF_LOW
1045     1.75,  // GF_ARF_STD
1046     2.00,  // KF_STD
1047   };
1048   static const FRAME_TYPE frame_type[RATE_FACTOR_LEVELS] = {
1049     INTER_FRAME, INTER_FRAME, INTER_FRAME, INTER_FRAME, KEY_FRAME
1050   };
1051   const VP9_COMMON *const cm = &cpi->common;
1052   int qdelta =
1053       vp9_compute_qdelta_by_rate(&cpi->rc, frame_type[rf_level], q,
1054                                  rate_factor_deltas[rf_level], cm->bit_depth);
1055   return qdelta;
1056 }
1057
1058 #define STATIC_MOTION_THRESH 95
1059 static int rc_pick_q_and_bounds_two_pass(const VP9_COMP *cpi, int *bottom_index,
1060                                          int *top_index) {
1061   const VP9_COMMON *const cm = &cpi->common;
1062   const RATE_CONTROL *const rc = &cpi->rc;
1063   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1064   const GF_GROUP *gf_group = &cpi->twopass.gf_group;
1065   const int cq_level = get_active_cq_level_two_pass(&cpi->twopass, rc, oxcf);
1066   int active_best_quality;
1067   int active_worst_quality = cpi->twopass.active_worst_quality;
1068   int q;
1069   int *inter_minq;
1070   ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
1071
1072   if (frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi)) {
1073     // Handle the special case for key frames forced when we have reached
1074     // the maximum key frame interval. Here force the Q to a range
1075     // based on the ambient Q to reduce the risk of popping.
1076     if (rc->this_key_frame_forced) {
1077       double last_boosted_q;
1078       int delta_qindex;
1079       int qindex;
1080
1081       if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1082         qindex = VPXMIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1083         active_best_quality = qindex;
1084         last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1085         delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
1086                                           last_boosted_q * 1.25, cm->bit_depth);
1087         active_worst_quality =
1088             VPXMIN(qindex + delta_qindex, active_worst_quality);
1089       } else {
1090         qindex = rc->last_boosted_qindex;
1091         last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1092         delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
1093                                           last_boosted_q * 0.75, cm->bit_depth);
1094         active_best_quality = VPXMAX(qindex + delta_qindex, rc->best_quality);
1095       }
1096     } else {
1097       // Not forced keyframe.
1098       double q_adj_factor = 1.0;
1099       double q_val;
1100       // Baseline value derived from cpi->active_worst_quality and kf boost.
1101       active_best_quality =
1102           get_kf_active_quality(rc, active_worst_quality, cm->bit_depth);
1103
1104       // Allow somewhat lower kf minq with small image formats.
1105       if ((cm->width * cm->height) <= (352 * 288)) {
1106         q_adj_factor -= 0.25;
1107       }
1108
1109       // Make a further adjustment based on the kf zero motion measure.
1110       q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
1111
1112       // Convert the adjustment factor to a qindex delta
1113       // on active_best_quality.
1114       q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1115       active_best_quality +=
1116           vp9_compute_qdelta(rc, q_val, q_val * q_adj_factor, cm->bit_depth);
1117     }
1118   } else if (!rc->is_src_frame_alt_ref &&
1119              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1120     // Use the lower of active_worst_quality and recent
1121     // average Q as basis for GF/ARF best Q limit unless last frame was
1122     // a key frame.
1123     if (rc->frames_since_key > 1 &&
1124         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1125       q = rc->avg_frame_qindex[INTER_FRAME];
1126     } else {
1127       q = active_worst_quality;
1128     }
1129     // For constrained quality dont allow Q less than the cq level
1130     if (oxcf->rc_mode == VPX_CQ) {
1131       if (q < cq_level) q = cq_level;
1132
1133       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1134
1135       // Constrained quality use slightly lower active best.
1136       active_best_quality = active_best_quality * 15 / 16;
1137
1138     } else if (oxcf->rc_mode == VPX_Q) {
1139       if (!cpi->refresh_alt_ref_frame) {
1140         active_best_quality = cq_level;
1141       } else {
1142         active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1143
1144         // Modify best quality for second level arfs. For mode VPX_Q this
1145         // becomes the baseline frame q.
1146         if (gf_group->rf_level[gf_group->index] == GF_ARF_LOW)
1147           active_best_quality = (active_best_quality + cq_level + 1) / 2;
1148       }
1149     } else {
1150       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1151     }
1152   } else {
1153     if (oxcf->rc_mode == VPX_Q) {
1154       active_best_quality = cq_level;
1155     } else {
1156       active_best_quality = inter_minq[active_worst_quality];
1157
1158       // For the constrained quality mode we don't want
1159       // q to fall below the cq level.
1160       if ((oxcf->rc_mode == VPX_CQ) && (active_best_quality < cq_level)) {
1161         active_best_quality = cq_level;
1162       }
1163     }
1164   }
1165
1166   // Extension to max or min Q if undershoot or overshoot is outside
1167   // the permitted range.
1168   if (cpi->oxcf.rc_mode != VPX_Q) {
1169     if (frame_is_intra_only(cm) ||
1170         (!rc->is_src_frame_alt_ref &&
1171          (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1172       active_best_quality -=
1173           (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast);
1174       active_worst_quality += (cpi->twopass.extend_maxq / 2);
1175     } else {
1176       active_best_quality -=
1177           (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast) / 2;
1178       active_worst_quality += cpi->twopass.extend_maxq;
1179     }
1180   }
1181
1182 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
1183   vpx_clear_system_state();
1184   // Static forced key frames Q restrictions dealt with elsewhere.
1185   if (!((frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi))) ||
1186       !rc->this_key_frame_forced ||
1187       (cpi->twopass.last_kfgroup_zeromotion_pct < STATIC_MOTION_THRESH)) {
1188     int qdelta = vp9_frame_type_qdelta(cpi, gf_group->rf_level[gf_group->index],
1189                                        active_worst_quality);
1190     active_worst_quality =
1191         VPXMAX(active_worst_quality + qdelta, active_best_quality);
1192   }
1193 #endif
1194
1195   // Modify active_best_quality for downscaled normal frames.
1196   if (rc->frame_size_selector != UNSCALED && !frame_is_kf_gf_arf(cpi)) {
1197     int qdelta = vp9_compute_qdelta_by_rate(
1198         rc, cm->frame_type, active_best_quality, 2.0, cm->bit_depth);
1199     active_best_quality =
1200         VPXMAX(active_best_quality + qdelta, rc->best_quality);
1201   }
1202
1203   active_best_quality =
1204       clamp(active_best_quality, rc->best_quality, rc->worst_quality);
1205   active_worst_quality =
1206       clamp(active_worst_quality, active_best_quality, rc->worst_quality);
1207
1208   if (oxcf->rc_mode == VPX_Q) {
1209     q = active_best_quality;
1210     // Special case code to try and match quality with forced key frames.
1211   } else if ((frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi)) &&
1212              rc->this_key_frame_forced) {
1213     // If static since last kf use better of last boosted and last kf q.
1214     if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1215       q = VPXMIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1216     } else {
1217       q = rc->last_boosted_qindex;
1218     }
1219   } else {
1220     q = vp9_rc_regulate_q(cpi, rc->this_frame_target, active_best_quality,
1221                           active_worst_quality);
1222     if (q > active_worst_quality) {
1223       // Special case when we are targeting the max allowed rate.
1224       if (rc->this_frame_target >= rc->max_frame_bandwidth)
1225         active_worst_quality = q;
1226       else
1227         q = active_worst_quality;
1228     }
1229   }
1230   clamp(q, active_best_quality, active_worst_quality);
1231
1232   *top_index = active_worst_quality;
1233   *bottom_index = active_best_quality;
1234
1235   assert(*top_index <= rc->worst_quality && *top_index >= rc->best_quality);
1236   assert(*bottom_index <= rc->worst_quality &&
1237          *bottom_index >= rc->best_quality);
1238   assert(q <= rc->worst_quality && q >= rc->best_quality);
1239   return q;
1240 }
1241
1242 int vp9_rc_pick_q_and_bounds(const VP9_COMP *cpi, int *bottom_index,
1243                              int *top_index) {
1244   int q;
1245   if (cpi->oxcf.pass == 0) {
1246     if (cpi->oxcf.rc_mode == VPX_CBR)
1247       q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
1248     else
1249       q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
1250   } else {
1251     q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
1252   }
1253   if (cpi->sf.use_nonrd_pick_mode) {
1254     if (cpi->sf.force_frame_boost == 1) q -= cpi->sf.max_delta_qindex;
1255
1256     if (q < *bottom_index)
1257       *bottom_index = q;
1258     else if (q > *top_index)
1259       *top_index = q;
1260   }
1261   return q;
1262 }
1263
1264 void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi, int frame_target,
1265                                       int *frame_under_shoot_limit,
1266                                       int *frame_over_shoot_limit) {
1267   if (cpi->oxcf.rc_mode == VPX_Q) {
1268     *frame_under_shoot_limit = 0;
1269     *frame_over_shoot_limit = INT_MAX;
1270   } else {
1271     // For very small rate targets where the fractional adjustment
1272     // may be tiny make sure there is at least a minimum range.
1273     const int tol_low = (cpi->sf.recode_tolerance_low * frame_target) / 100;
1274     const int tol_high = (cpi->sf.recode_tolerance_high * frame_target) / 100;
1275     *frame_under_shoot_limit = VPXMAX(frame_target - tol_low - 100, 0);
1276     *frame_over_shoot_limit =
1277         VPXMIN(frame_target + tol_high + 100, cpi->rc.max_frame_bandwidth);
1278   }
1279 }
1280
1281 void vp9_rc_set_frame_target(VP9_COMP *cpi, int target) {
1282   const VP9_COMMON *const cm = &cpi->common;
1283   RATE_CONTROL *const rc = &cpi->rc;
1284
1285   rc->this_frame_target = target;
1286
1287   // Modify frame size target when down-scaling.
1288   if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC &&
1289       rc->frame_size_selector != UNSCALED)
1290     rc->this_frame_target = (int)(rc->this_frame_target *
1291                                   rate_thresh_mult[rc->frame_size_selector]);
1292
1293   // Target rate per SB64 (including partial SB64s.
1294   rc->sb64_target_rate = (int)(((int64_t)rc->this_frame_target * 64 * 64) /
1295                                (cm->width * cm->height));
1296 }
1297
1298 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
1299   // this frame refreshes means next frames don't unless specified by user
1300   RATE_CONTROL *const rc = &cpi->rc;
1301   rc->frames_since_golden = 0;
1302
1303   // Mark the alt ref as done (setting to 0 means no further alt refs pending).
1304   rc->source_alt_ref_pending = 0;
1305
1306   // Set the alternate reference frame active flag
1307   rc->source_alt_ref_active = 1;
1308 }
1309
1310 static void update_golden_frame_stats(VP9_COMP *cpi) {
1311   RATE_CONTROL *const rc = &cpi->rc;
1312
1313   // Update the Golden frame usage counts.
1314   if (cpi->refresh_golden_frame) {
1315     // this frame refreshes means next frames don't unless specified by user
1316     rc->frames_since_golden = 0;
1317
1318     // If we are not using alt ref in the up and coming group clear the arf
1319     // active flag. In multi arf group case, if the index is not 0 then
1320     // we are overlaying a mid group arf so should not reset the flag.
1321     if (cpi->oxcf.pass == 2) {
1322       if (!rc->source_alt_ref_pending && (cpi->twopass.gf_group.index == 0))
1323         rc->source_alt_ref_active = 0;
1324     } else if (!rc->source_alt_ref_pending) {
1325       rc->source_alt_ref_active = 0;
1326     }
1327
1328     // Decrement count down till next gf
1329     if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1330
1331   } else if (!cpi->refresh_alt_ref_frame) {
1332     // Decrement count down till next gf
1333     if (rc->frames_till_gf_update_due > 0) rc->frames_till_gf_update_due--;
1334
1335     rc->frames_since_golden++;
1336   }
1337 }
1338
1339 static void update_altref_usage(VP9_COMP *const cpi) {
1340   VP9_COMMON *const cm = &cpi->common;
1341   int sum_ref_frame_usage = 0;
1342   int arf_frame_usage = 0;
1343   int mi_row, mi_col;
1344   if (cpi->rc.alt_ref_gf_group && !cpi->rc.is_src_frame_alt_ref &&
1345       !cpi->refresh_golden_frame && !cpi->refresh_alt_ref_frame)
1346     for (mi_row = 0; mi_row < cm->mi_rows; mi_row += 8) {
1347       for (mi_col = 0; mi_col < cm->mi_cols; mi_col += 8) {
1348         int sboffset = ((cm->mi_cols + 7) >> 3) * (mi_row >> 3) + (mi_col >> 3);
1349         sum_ref_frame_usage += cpi->count_arf_frame_usage[sboffset] +
1350                                cpi->count_lastgolden_frame_usage[sboffset];
1351         arf_frame_usage += cpi->count_arf_frame_usage[sboffset];
1352       }
1353     }
1354   if (sum_ref_frame_usage > 0) {
1355     double altref_count = 100.0 * arf_frame_usage / sum_ref_frame_usage;
1356     cpi->rc.perc_arf_usage =
1357         0.75 * cpi->rc.perc_arf_usage + 0.25 * altref_count;
1358   }
1359 }
1360
1361 static void compute_frame_low_motion(VP9_COMP *const cpi) {
1362   VP9_COMMON *const cm = &cpi->common;
1363   int mi_row, mi_col;
1364   MODE_INFO **mi = cm->mi_grid_visible;
1365   RATE_CONTROL *const rc = &cpi->rc;
1366   const int rows = cm->mi_rows, cols = cm->mi_cols;
1367   int cnt_zeromv = 0;
1368   for (mi_row = 0; mi_row < rows; mi_row++) {
1369     for (mi_col = 0; mi_col < cols; mi_col++) {
1370       if (abs(mi[0]->mv[0].as_mv.row) < 16 && abs(mi[0]->mv[0].as_mv.col) < 16)
1371         cnt_zeromv++;
1372       mi++;
1373     }
1374     mi += 8;
1375   }
1376   cnt_zeromv = 100 * cnt_zeromv / (rows * cols);
1377   rc->avg_frame_low_motion = (3 * rc->avg_frame_low_motion + cnt_zeromv) >> 2;
1378 }
1379
1380 void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
1381   const VP9_COMMON *const cm = &cpi->common;
1382   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1383   RATE_CONTROL *const rc = &cpi->rc;
1384   const int qindex = cm->base_qindex;
1385
1386   // Update rate control heuristics
1387   rc->projected_frame_size = (int)(bytes_used << 3);
1388
1389   // Post encode loop adjustment of Q prediction.
1390   vp9_rc_update_rate_correction_factors(cpi);
1391
1392   // Keep a record of last Q and ambient average Q.
1393   if (cm->frame_type == KEY_FRAME) {
1394     rc->last_q[KEY_FRAME] = qindex;
1395     rc->avg_frame_qindex[KEY_FRAME] =
1396         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1397     if (cpi->use_svc) {
1398       int i = 0;
1399       SVC *svc = &cpi->svc;
1400       for (i = 0; i < svc->number_temporal_layers; ++i) {
1401         const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
1402                                            svc->number_temporal_layers);
1403         LAYER_CONTEXT *lc = &svc->layer_context[layer];
1404         RATE_CONTROL *lrc = &lc->rc;
1405         lrc->last_q[KEY_FRAME] = rc->last_q[KEY_FRAME];
1406         lrc->avg_frame_qindex[KEY_FRAME] = rc->avg_frame_qindex[KEY_FRAME];
1407       }
1408     }
1409   } else {
1410     if ((cpi->use_svc && oxcf->rc_mode == VPX_CBR) ||
1411         (!rc->is_src_frame_alt_ref &&
1412          !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1413       rc->last_q[INTER_FRAME] = qindex;
1414       rc->avg_frame_qindex[INTER_FRAME] =
1415           ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1416       rc->ni_frames++;
1417       rc->tot_q += vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1418       rc->avg_q = rc->tot_q / rc->ni_frames;
1419       // Calculate the average Q for normal inter frames (not key or GFU
1420       // frames).
1421       rc->ni_tot_qi += qindex;
1422       rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1423     }
1424   }
1425
1426   // Keep record of last boosted (KF/KF/ARF) Q value.
1427   // If the current frame is coded at a lower Q then we also update it.
1428   // If all mbs in this group are skipped only update if the Q value is
1429   // better than that already stored.
1430   // This is used to help set quality in forced key frames to reduce popping
1431   if ((qindex < rc->last_boosted_qindex) || (cm->frame_type == KEY_FRAME) ||
1432       (!rc->constrained_gf_group &&
1433        (cpi->refresh_alt_ref_frame ||
1434         (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1435     rc->last_boosted_qindex = qindex;
1436   }
1437   if (cm->frame_type == KEY_FRAME) rc->last_kf_qindex = qindex;
1438
1439   update_buffer_level(cpi, rc->projected_frame_size);
1440
1441   // Rolling monitors of whether we are over or underspending used to help
1442   // regulate min and Max Q in two pass.
1443   if (cm->frame_type != KEY_FRAME) {
1444     rc->rolling_target_bits = ROUND_POWER_OF_TWO(
1445         rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1446     rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
1447         rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1448     rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
1449         rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1450     rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
1451         rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
1452   }
1453
1454   // Actual bits spent
1455   rc->total_actual_bits += rc->projected_frame_size;
1456   rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1457
1458   rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1459
1460   if (!cpi->use_svc || is_two_pass_svc(cpi)) {
1461     if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
1462         (cm->frame_type != KEY_FRAME))
1463       // Update the alternate reference frame stats as appropriate.
1464       update_alt_ref_frame_stats(cpi);
1465     else
1466       // Update the Golden frame stats as appropriate.
1467       update_golden_frame_stats(cpi);
1468   }
1469
1470   if (cm->frame_type == KEY_FRAME) rc->frames_since_key = 0;
1471   if (cm->show_frame) {
1472     rc->frames_since_key++;
1473     rc->frames_to_key--;
1474   }
1475
1476   // Trigger the resizing of the next frame if it is scaled.
1477   if (oxcf->pass != 0) {
1478     cpi->resize_pending =
1479         rc->next_frame_size_selector != rc->frame_size_selector;
1480     rc->frame_size_selector = rc->next_frame_size_selector;
1481   }
1482
1483   if (oxcf->pass == 0) {
1484     if (cm->frame_type != KEY_FRAME) {
1485       compute_frame_low_motion(cpi);
1486       if (cpi->sf.use_altref_onepass) update_altref_usage(cpi);
1487     }
1488     cpi->rc.last_frame_is_src_altref = cpi->rc.is_src_frame_alt_ref;
1489   }
1490   if (cm->frame_type != KEY_FRAME) rc->reset_high_source_sad = 0;
1491
1492   rc->last_avg_frame_bandwidth = rc->avg_frame_bandwidth;
1493 }
1494
1495 void vp9_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
1496   // Update buffer level with zero size, update frame counters, and return.
1497   update_buffer_level(cpi, 0);
1498   cpi->common.current_video_frame++;
1499   cpi->rc.frames_since_key++;
1500   cpi->rc.frames_to_key--;
1501   cpi->rc.rc_2_frame = 0;
1502   cpi->rc.rc_1_frame = 0;
1503   cpi->rc.last_avg_frame_bandwidth = cpi->rc.avg_frame_bandwidth;
1504 }
1505
1506 static int calc_pframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1507   const RATE_CONTROL *const rc = &cpi->rc;
1508   const int af_ratio = rc->af_ratio_onepass_vbr;
1509   int target =
1510       (!rc->is_src_frame_alt_ref &&
1511        (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))
1512           ? (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
1513                 (rc->baseline_gf_interval + af_ratio - 1)
1514           : (rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
1515                 (rc->baseline_gf_interval + af_ratio - 1);
1516   return vp9_rc_clamp_pframe_target_size(cpi, target);
1517 }
1518
1519 static int calc_iframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1520   static const int kf_ratio = 25;
1521   const RATE_CONTROL *rc = &cpi->rc;
1522   const int target = rc->avg_frame_bandwidth * kf_ratio;
1523   return vp9_rc_clamp_iframe_target_size(cpi, target);
1524 }
1525
1526 static void adjust_gfint_frame_constraint(VP9_COMP *cpi, int frame_constraint) {
1527   RATE_CONTROL *const rc = &cpi->rc;
1528   rc->constrained_gf_group = 0;
1529   // Reset gf interval to make more equal spacing for frame_constraint.
1530   if ((frame_constraint <= 7 * rc->baseline_gf_interval >> 2) &&
1531       (frame_constraint > rc->baseline_gf_interval)) {
1532     rc->baseline_gf_interval = frame_constraint >> 1;
1533     if (rc->baseline_gf_interval < 5)
1534       rc->baseline_gf_interval = frame_constraint;
1535     rc->constrained_gf_group = 1;
1536   } else {
1537     // Reset to keep gf_interval <= frame_constraint.
1538     if (rc->baseline_gf_interval > frame_constraint) {
1539       rc->baseline_gf_interval = frame_constraint;
1540       rc->constrained_gf_group = 1;
1541     }
1542   }
1543 }
1544
1545 void vp9_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
1546   VP9_COMMON *const cm = &cpi->common;
1547   RATE_CONTROL *const rc = &cpi->rc;
1548   int target;
1549   // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1550   if (!cpi->refresh_alt_ref_frame &&
1551       (cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1552        rc->frames_to_key == 0 || (cpi->oxcf.auto_key && 0))) {
1553     cm->frame_type = KEY_FRAME;
1554     rc->this_key_frame_forced =
1555         cm->current_video_frame != 0 && rc->frames_to_key == 0;
1556     rc->frames_to_key = cpi->oxcf.key_freq;
1557     rc->kf_boost = DEFAULT_KF_BOOST;
1558     rc->source_alt_ref_active = 0;
1559   } else {
1560     cm->frame_type = INTER_FRAME;
1561   }
1562   if (rc->frames_till_gf_update_due == 0) {
1563     double rate_err = 1.0;
1564     rc->gfu_boost = DEFAULT_GF_BOOST;
1565     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0) {
1566       vp9_cyclic_refresh_set_golden_update(cpi);
1567     } else {
1568       rc->baseline_gf_interval = VPXMIN(
1569           20, VPXMAX(10, (rc->min_gf_interval + rc->max_gf_interval) / 2));
1570     }
1571     rc->af_ratio_onepass_vbr = 10;
1572     if (rc->rolling_target_bits > 0)
1573       rate_err =
1574           (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
1575     if (cm->current_video_frame > 30) {
1576       if (rc->avg_frame_qindex[INTER_FRAME] > (7 * rc->worst_quality) >> 3 &&
1577           rate_err > 3.5) {
1578         rc->baseline_gf_interval =
1579             VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
1580       } else if (rc->avg_frame_low_motion < 20) {
1581         // Decrease gf interval for high motion case.
1582         rc->baseline_gf_interval = VPXMAX(6, rc->baseline_gf_interval >> 1);
1583       }
1584       // Adjust boost and af_ratio based on avg_frame_low_motion, which varies
1585       // between 0 and 100 (stationary, 100% zero/small motion).
1586       rc->gfu_boost =
1587           VPXMAX(500, DEFAULT_GF_BOOST * (rc->avg_frame_low_motion << 1) /
1588                           (rc->avg_frame_low_motion + 100));
1589       rc->af_ratio_onepass_vbr = VPXMIN(15, VPXMAX(5, 3 * rc->gfu_boost / 400));
1590     }
1591     adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
1592     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1593     cpi->refresh_golden_frame = 1;
1594     rc->source_alt_ref_pending = 0;
1595     rc->alt_ref_gf_group = 0;
1596     if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf) {
1597       rc->source_alt_ref_pending = 1;
1598       rc->alt_ref_gf_group = 1;
1599     }
1600   }
1601   if (cm->frame_type == KEY_FRAME)
1602     target = calc_iframe_target_size_one_pass_vbr(cpi);
1603   else
1604     target = calc_pframe_target_size_one_pass_vbr(cpi);
1605   vp9_rc_set_frame_target(cpi, target);
1606   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->oxcf.pass == 0)
1607     vp9_cyclic_refresh_update_parameters(cpi);
1608 }
1609
1610 static int calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1611   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1612   const RATE_CONTROL *rc = &cpi->rc;
1613   const SVC *const svc = &cpi->svc;
1614   const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
1615   const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
1616   int min_frame_target =
1617       VPXMAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
1618   int target;
1619
1620   if (oxcf->gf_cbr_boost_pct) {
1621     const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
1622     target = cpi->refresh_golden_frame
1623                  ? (rc->avg_frame_bandwidth * rc->baseline_gf_interval *
1624                     af_ratio_pct) /
1625                        (rc->baseline_gf_interval * 100 + af_ratio_pct - 100)
1626                  : (rc->avg_frame_bandwidth * rc->baseline_gf_interval * 100) /
1627                        (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
1628   } else {
1629     target = rc->avg_frame_bandwidth;
1630   }
1631   if (is_one_pass_cbr_svc(cpi)) {
1632     // Note that for layers, avg_frame_bandwidth is the cumulative
1633     // per-frame-bandwidth. For the target size of this frame, use the
1634     // layer average frame size (i.e., non-cumulative per-frame-bw).
1635     int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
1636                                  svc->number_temporal_layers);
1637     const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1638     target = lc->avg_frame_size;
1639     min_frame_target = VPXMAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
1640   }
1641   if (diff > 0) {
1642     // Lower the target bandwidth for this frame.
1643     const int pct_low = (int)VPXMIN(diff / one_pct_bits, oxcf->under_shoot_pct);
1644     target -= (target * pct_low) / 200;
1645   } else if (diff < 0) {
1646     // Increase the target bandwidth for this frame.
1647     const int pct_high =
1648         (int)VPXMIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
1649     target += (target * pct_high) / 200;
1650   }
1651   if (oxcf->rc_max_inter_bitrate_pct) {
1652     const int max_rate =
1653         rc->avg_frame_bandwidth * oxcf->rc_max_inter_bitrate_pct / 100;
1654     target = VPXMIN(target, max_rate);
1655   }
1656   return VPXMAX(min_frame_target, target);
1657 }
1658
1659 static int calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1660   const RATE_CONTROL *rc = &cpi->rc;
1661   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1662   const SVC *const svc = &cpi->svc;
1663   int target;
1664   if (cpi->common.current_video_frame == 0) {
1665     target = ((rc->starting_buffer_level / 2) > INT_MAX)
1666                  ? INT_MAX
1667                  : (int)(rc->starting_buffer_level / 2);
1668   } else {
1669     int kf_boost = 32;
1670     double framerate = cpi->framerate;
1671     if (svc->number_temporal_layers > 1 && oxcf->rc_mode == VPX_CBR) {
1672       // Use the layer framerate for temporal layers CBR mode.
1673       const int layer =
1674           LAYER_IDS_TO_IDX(svc->spatial_layer_id, svc->temporal_layer_id,
1675                            svc->number_temporal_layers);
1676       const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1677       framerate = lc->framerate;
1678     }
1679     kf_boost = VPXMAX(kf_boost, (int)(2 * framerate - 16));
1680     if (rc->frames_since_key < framerate / 2) {
1681       kf_boost = (int)(kf_boost * rc->frames_since_key / (framerate / 2));
1682     }
1683     target = ((16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
1684   }
1685   return vp9_rc_clamp_iframe_target_size(cpi, target);
1686 }
1687
1688 void vp9_rc_get_svc_params(VP9_COMP *cpi) {
1689   VP9_COMMON *const cm = &cpi->common;
1690   RATE_CONTROL *const rc = &cpi->rc;
1691   int target = rc->avg_frame_bandwidth;
1692   int layer =
1693       LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id, cpi->svc.temporal_layer_id,
1694                        cpi->svc.number_temporal_layers);
1695   // Periodic key frames is based on the super-frame counter
1696   // (svc.current_superframe), also only base spatial layer is key frame.
1697   if ((cm->current_video_frame == 0) || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1698       (cpi->oxcf.auto_key &&
1699        (cpi->svc.current_superframe % cpi->oxcf.key_freq == 0) &&
1700        cpi->svc.spatial_layer_id == 0)) {
1701     cm->frame_type = KEY_FRAME;
1702     rc->source_alt_ref_active = 0;
1703     if (is_two_pass_svc(cpi)) {
1704       cpi->svc.layer_context[layer].is_key_frame = 1;
1705       cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1706     } else if (is_one_pass_cbr_svc(cpi)) {
1707       if (cm->current_video_frame > 0) vp9_svc_reset_key_frame(cpi);
1708       layer = LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id,
1709                                cpi->svc.temporal_layer_id,
1710                                cpi->svc.number_temporal_layers);
1711       cpi->svc.layer_context[layer].is_key_frame = 1;
1712       cpi->ref_frame_flags &= (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1713       // Assumption here is that LAST_FRAME is being updated for a keyframe.
1714       // Thus no change in update flags.
1715       target = calc_iframe_target_size_one_pass_cbr(cpi);
1716     }
1717   } else {
1718     cm->frame_type = INTER_FRAME;
1719     if (is_two_pass_svc(cpi)) {
1720       LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1721       if (cpi->svc.spatial_layer_id == 0) {
1722         lc->is_key_frame = 0;
1723       } else {
1724         lc->is_key_frame =
1725             cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1726         if (lc->is_key_frame) cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
1727       }
1728       cpi->ref_frame_flags &= (~VP9_ALT_FLAG);
1729     } else if (is_one_pass_cbr_svc(cpi)) {
1730       LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1731       if (cpi->svc.spatial_layer_id == cpi->svc.first_spatial_layer_to_encode) {
1732         lc->is_key_frame = 0;
1733       } else {
1734         lc->is_key_frame =
1735             cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1736       }
1737       target = calc_pframe_target_size_one_pass_cbr(cpi);
1738     }
1739   }
1740
1741   // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1742   // should be done here, before the frame qp is selected.
1743   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1744     vp9_cyclic_refresh_update_parameters(cpi);
1745
1746   vp9_rc_set_frame_target(cpi, target);
1747   rc->frames_till_gf_update_due = INT_MAX;
1748   rc->baseline_gf_interval = INT_MAX;
1749 }
1750
1751 void vp9_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
1752   VP9_COMMON *const cm = &cpi->common;
1753   RATE_CONTROL *const rc = &cpi->rc;
1754   int target;
1755   // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1756   if ((cm->current_video_frame == 0 || (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1757        rc->frames_to_key == 0 || (cpi->oxcf.auto_key && 0))) {
1758     cm->frame_type = KEY_FRAME;
1759     rc->this_key_frame_forced =
1760         cm->current_video_frame != 0 && rc->frames_to_key == 0;
1761     rc->frames_to_key = cpi->oxcf.key_freq;
1762     rc->kf_boost = DEFAULT_KF_BOOST;
1763     rc->source_alt_ref_active = 0;
1764   } else {
1765     cm->frame_type = INTER_FRAME;
1766   }
1767   if (rc->frames_till_gf_update_due == 0) {
1768     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1769       vp9_cyclic_refresh_set_golden_update(cpi);
1770     else
1771       rc->baseline_gf_interval =
1772           (rc->min_gf_interval + rc->max_gf_interval) / 2;
1773     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1774     // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1775     if (rc->frames_till_gf_update_due > rc->frames_to_key)
1776       rc->frames_till_gf_update_due = rc->frames_to_key;
1777     cpi->refresh_golden_frame = 1;
1778     rc->gfu_boost = DEFAULT_GF_BOOST;
1779   }
1780
1781   // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1782   // should be done here, before the frame qp is selected.
1783   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1784     vp9_cyclic_refresh_update_parameters(cpi);
1785
1786   if (cm->frame_type == KEY_FRAME)
1787     target = calc_iframe_target_size_one_pass_cbr(cpi);
1788   else
1789     target = calc_pframe_target_size_one_pass_cbr(cpi);
1790
1791   vp9_rc_set_frame_target(cpi, target);
1792   if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC)
1793     cpi->resize_pending = vp9_resize_one_pass_cbr(cpi);
1794   else
1795     cpi->resize_pending = 0;
1796 }
1797
1798 int vp9_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
1799                        vpx_bit_depth_t bit_depth) {
1800   int start_index = rc->worst_quality;
1801   int target_index = rc->worst_quality;
1802   int i;
1803
1804   // Convert the average q value to an index.
1805   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1806     start_index = i;
1807     if (vp9_convert_qindex_to_q(i, bit_depth) >= qstart) break;
1808   }
1809
1810   // Convert the q target to an index
1811   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1812     target_index = i;
1813     if (vp9_convert_qindex_to_q(i, bit_depth) >= qtarget) break;
1814   }
1815
1816   return target_index - start_index;
1817 }
1818
1819 int vp9_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
1820                                int qindex, double rate_target_ratio,
1821                                vpx_bit_depth_t bit_depth) {
1822   int target_index = rc->worst_quality;
1823   int i;
1824
1825   // Look up the current projected bits per block for the base index
1826   const int base_bits_per_mb =
1827       vp9_rc_bits_per_mb(frame_type, qindex, 1.0, bit_depth);
1828
1829   // Find the target bits per mb based on the base value and given ratio.
1830   const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
1831
1832   // Convert the q target to an index
1833   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1834     if (vp9_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
1835         target_bits_per_mb) {
1836       target_index = i;
1837       break;
1838     }
1839   }
1840   return target_index - qindex;
1841 }
1842
1843 void vp9_rc_set_gf_interval_range(const VP9_COMP *const cpi,
1844                                   RATE_CONTROL *const rc) {
1845   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1846
1847   // Special case code for 1 pass fixed Q mode tests
1848   if ((oxcf->pass == 0) && (oxcf->rc_mode == VPX_Q)) {
1849     rc->max_gf_interval = FIXED_GF_INTERVAL;
1850     rc->min_gf_interval = FIXED_GF_INTERVAL;
1851     rc->static_scene_max_gf_interval = FIXED_GF_INTERVAL;
1852   } else {
1853     // Set Maximum gf/arf interval
1854     rc->max_gf_interval = oxcf->max_gf_interval;
1855     rc->min_gf_interval = oxcf->min_gf_interval;
1856     if (rc->min_gf_interval == 0)
1857       rc->min_gf_interval = vp9_rc_get_default_min_gf_interval(
1858           oxcf->width, oxcf->height, cpi->framerate);
1859     if (rc->max_gf_interval == 0)
1860       rc->max_gf_interval = vp9_rc_get_default_max_gf_interval(
1861           cpi->framerate, rc->min_gf_interval);
1862
1863     // Extended interval for genuinely static scenes
1864     rc->static_scene_max_gf_interval = MAX_LAG_BUFFERS * 2;
1865
1866     if (is_altref_enabled(cpi)) {
1867       if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
1868         rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
1869     }
1870
1871     if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
1872       rc->max_gf_interval = rc->static_scene_max_gf_interval;
1873
1874     // Clamp min to max
1875     rc->min_gf_interval = VPXMIN(rc->min_gf_interval, rc->max_gf_interval);
1876
1877     if (oxcf->target_level == LEVEL_AUTO) {
1878       const uint32_t pic_size = cpi->common.width * cpi->common.height;
1879       const uint32_t pic_breadth =
1880           VPXMAX(cpi->common.width, cpi->common.height);
1881       int i;
1882       for (i = LEVEL_1; i < LEVEL_MAX; ++i) {
1883         if (vp9_level_defs[i].max_luma_picture_size >= pic_size &&
1884             vp9_level_defs[i].max_luma_picture_breadth >= pic_breadth) {
1885           if (rc->min_gf_interval <=
1886               (int)vp9_level_defs[i].min_altref_distance) {
1887             rc->min_gf_interval =
1888                 (int)vp9_level_defs[i].min_altref_distance + 1;
1889             rc->max_gf_interval =
1890                 VPXMAX(rc->max_gf_interval, rc->min_gf_interval);
1891           }
1892           break;
1893         }
1894       }
1895     }
1896   }
1897 }
1898
1899 void vp9_rc_update_framerate(VP9_COMP *cpi) {
1900   const VP9_COMMON *const cm = &cpi->common;
1901   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1902   RATE_CONTROL *const rc = &cpi->rc;
1903   int vbr_max_bits;
1904
1905   rc->avg_frame_bandwidth = (int)(oxcf->target_bandwidth / cpi->framerate);
1906   rc->min_frame_bandwidth =
1907       (int)(rc->avg_frame_bandwidth * oxcf->two_pass_vbrmin_section / 100);
1908
1909   rc->min_frame_bandwidth =
1910       VPXMAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1911
1912   // A maximum bitrate for a frame is defined.
1913   // The baseline for this aligns with HW implementations that
1914   // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
1915   // per 16x16 MB (averaged over a frame). However this limit is extended if
1916   // a very high rate is given on the command line or the the rate cannnot
1917   // be acheived because of a user specificed max q (e.g. when the user
1918   // specifies lossless encode.
1919   vbr_max_bits =
1920       (int)(((int64_t)rc->avg_frame_bandwidth * oxcf->two_pass_vbrmax_section) /
1921             100);
1922   rc->max_frame_bandwidth =
1923       VPXMAX(VPXMAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P), vbr_max_bits);
1924
1925   vp9_rc_set_gf_interval_range(cpi, rc);
1926 }
1927
1928 #define VBR_PCT_ADJUSTMENT_LIMIT 50
1929 // For VBR...adjustment to the frame target based on error from previous frames
1930 static void vbr_rate_correction(VP9_COMP *cpi, int *this_frame_target) {
1931   RATE_CONTROL *const rc = &cpi->rc;
1932   int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
1933   int max_delta;
1934   int frame_window = VPXMIN(16, ((int)cpi->twopass.total_stats.count -
1935                                  cpi->common.current_video_frame));
1936
1937   // Calcluate the adjustment to rate for this frame.
1938   if (frame_window > 0) {
1939     max_delta = (vbr_bits_off_target > 0)
1940                     ? (int)(vbr_bits_off_target / frame_window)
1941                     : (int)(-vbr_bits_off_target / frame_window);
1942
1943     max_delta = VPXMIN(max_delta,
1944                        ((*this_frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
1945
1946     // vbr_bits_off_target > 0 means we have extra bits to spend
1947     if (vbr_bits_off_target > 0) {
1948       *this_frame_target += (vbr_bits_off_target > max_delta)
1949                                 ? max_delta
1950                                 : (int)vbr_bits_off_target;
1951     } else {
1952       *this_frame_target -= (vbr_bits_off_target < -max_delta)
1953                                 ? max_delta
1954                                 : (int)-vbr_bits_off_target;
1955     }
1956   }
1957
1958   // Fast redistribution of bits arising from massive local undershoot.
1959   // Dont do it for kf,arf,gf or overlay frames.
1960   if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
1961       rc->vbr_bits_off_target_fast) {
1962     int one_frame_bits = VPXMAX(rc->avg_frame_bandwidth, *this_frame_target);
1963     int fast_extra_bits;
1964     fast_extra_bits = (int)VPXMIN(rc->vbr_bits_off_target_fast, one_frame_bits);
1965     fast_extra_bits = (int)VPXMIN(
1966         fast_extra_bits,
1967         VPXMAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
1968     *this_frame_target += (int)fast_extra_bits;
1969     rc->vbr_bits_off_target_fast -= fast_extra_bits;
1970   }
1971 }
1972
1973 void vp9_set_target_rate(VP9_COMP *cpi) {
1974   RATE_CONTROL *const rc = &cpi->rc;
1975   int target_rate = rc->base_frame_target;
1976
1977   if (cpi->common.frame_type == KEY_FRAME)
1978     target_rate = vp9_rc_clamp_iframe_target_size(cpi, target_rate);
1979   else
1980     target_rate = vp9_rc_clamp_pframe_target_size(cpi, target_rate);
1981
1982   if (!cpi->oxcf.vbr_corpus_complexity) {
1983     // Correction to rate target based on prior over or under shoot.
1984     if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
1985       vbr_rate_correction(cpi, &target_rate);
1986   }
1987   vp9_rc_set_frame_target(cpi, target_rate);
1988 }
1989
1990 // Check if we should resize, based on average QP from past x frames.
1991 // Only allow for resize at most one scale down for now, scaling factor is 2.
1992 int vp9_resize_one_pass_cbr(VP9_COMP *cpi) {
1993   const VP9_COMMON *const cm = &cpi->common;
1994   RATE_CONTROL *const rc = &cpi->rc;
1995   RESIZE_ACTION resize_action = NO_RESIZE;
1996   int avg_qp_thr1 = 70;
1997   int avg_qp_thr2 = 50;
1998   int min_width = 180;
1999   int min_height = 180;
2000   int down_size_on = 1;
2001   cpi->resize_scale_num = 1;
2002   cpi->resize_scale_den = 1;
2003   // Don't resize on key frame; reset the counters on key frame.
2004   if (cm->frame_type == KEY_FRAME) {
2005     cpi->resize_avg_qp = 0;
2006     cpi->resize_count = 0;
2007     return 0;
2008   }
2009   // Check current frame reslution to avoid generating frames smaller than
2010   // the minimum resolution.
2011   if (ONEHALFONLY_RESIZE) {
2012     if ((cm->width >> 1) < min_width || (cm->height >> 1) < min_height)
2013       down_size_on = 0;
2014   } else {
2015     if (cpi->resize_state == ORIG &&
2016         (cm->width * 3 / 4 < min_width || cm->height * 3 / 4 < min_height))
2017       return 0;
2018     else if (cpi->resize_state == THREE_QUARTER &&
2019              ((cpi->oxcf.width >> 1) < min_width ||
2020               (cpi->oxcf.height >> 1) < min_height))
2021       down_size_on = 0;
2022   }
2023
2024 #if CONFIG_VP9_TEMPORAL_DENOISING
2025   // If denoiser is on, apply a smaller qp threshold.
2026   if (cpi->oxcf.noise_sensitivity > 0) {
2027     avg_qp_thr1 = 60;
2028     avg_qp_thr2 = 40;
2029   }
2030 #endif
2031
2032   // Resize based on average buffer underflow and QP over some window.
2033   // Ignore samples close to key frame, since QP is usually high after key.
2034   if (cpi->rc.frames_since_key > 2 * cpi->framerate) {
2035     const int window = (int)(4 * cpi->framerate);
2036     cpi->resize_avg_qp += cm->base_qindex;
2037     if (cpi->rc.buffer_level < (int)(30 * rc->optimal_buffer_level / 100))
2038       ++cpi->resize_buffer_underflow;
2039     ++cpi->resize_count;
2040     // Check for resize action every "window" frames.
2041     if (cpi->resize_count >= window) {
2042       int avg_qp = cpi->resize_avg_qp / cpi->resize_count;
2043       // Resize down if buffer level has underflowed sufficient amount in past
2044       // window, and we are at original or 3/4 of original resolution.
2045       // Resize back up if average QP is low, and we are currently in a resized
2046       // down state, i.e. 1/2 or 3/4 of original resolution.
2047       // Currently, use a flag to turn 3/4 resizing feature on/off.
2048       if (cpi->resize_buffer_underflow > (cpi->resize_count >> 2)) {
2049         if (cpi->resize_state == THREE_QUARTER && down_size_on) {
2050           resize_action = DOWN_ONEHALF;
2051           cpi->resize_state = ONE_HALF;
2052         } else if (cpi->resize_state == ORIG) {
2053           resize_action = ONEHALFONLY_RESIZE ? DOWN_ONEHALF : DOWN_THREEFOUR;
2054           cpi->resize_state = ONEHALFONLY_RESIZE ? ONE_HALF : THREE_QUARTER;
2055         }
2056       } else if (cpi->resize_state != ORIG &&
2057                  avg_qp < avg_qp_thr1 * cpi->rc.worst_quality / 100) {
2058         if (cpi->resize_state == THREE_QUARTER ||
2059             avg_qp < avg_qp_thr2 * cpi->rc.worst_quality / 100 ||
2060             ONEHALFONLY_RESIZE) {
2061           resize_action = UP_ORIG;
2062           cpi->resize_state = ORIG;
2063         } else if (cpi->resize_state == ONE_HALF) {
2064           resize_action = UP_THREEFOUR;
2065           cpi->resize_state = THREE_QUARTER;
2066         }
2067       }
2068       // Reset for next window measurement.
2069       cpi->resize_avg_qp = 0;
2070       cpi->resize_count = 0;
2071       cpi->resize_buffer_underflow = 0;
2072     }
2073   }
2074   // If decision is to resize, reset some quantities, and check is we should
2075   // reduce rate correction factor,
2076   if (resize_action != NO_RESIZE) {
2077     int target_bits_per_frame;
2078     int active_worst_quality;
2079     int qindex;
2080     int tot_scale_change;
2081     if (resize_action == DOWN_THREEFOUR || resize_action == UP_THREEFOUR) {
2082       cpi->resize_scale_num = 3;
2083       cpi->resize_scale_den = 4;
2084     } else if (resize_action == DOWN_ONEHALF) {
2085       cpi->resize_scale_num = 1;
2086       cpi->resize_scale_den = 2;
2087     } else {  // UP_ORIG or anything else
2088       cpi->resize_scale_num = 1;
2089       cpi->resize_scale_den = 1;
2090     }
2091     tot_scale_change = (cpi->resize_scale_den * cpi->resize_scale_den) /
2092                        (cpi->resize_scale_num * cpi->resize_scale_num);
2093     // Reset buffer level to optimal, update target size.
2094     rc->buffer_level = rc->optimal_buffer_level;
2095     rc->bits_off_target = rc->optimal_buffer_level;
2096     rc->this_frame_target = calc_pframe_target_size_one_pass_cbr(cpi);
2097     // Get the projected qindex, based on the scaled target frame size (scaled
2098     // so target_bits_per_mb in vp9_rc_regulate_q will be correct target).
2099     target_bits_per_frame = (resize_action >= 0)
2100                                 ? rc->this_frame_target * tot_scale_change
2101                                 : rc->this_frame_target / tot_scale_change;
2102     active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
2103     qindex = vp9_rc_regulate_q(cpi, target_bits_per_frame, rc->best_quality,
2104                                active_worst_quality);
2105     // If resize is down, check if projected q index is close to worst_quality,
2106     // and if so, reduce the rate correction factor (since likely can afford
2107     // lower q for resized frame).
2108     if (resize_action > 0 && qindex > 90 * cpi->rc.worst_quality / 100) {
2109       rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
2110     }
2111     // If resize is back up, check if projected q index is too much above the
2112     // current base_qindex, and if so, reduce the rate correction factor
2113     // (since prefer to keep q for resized frame at least close to previous q).
2114     if (resize_action < 0 && qindex > 130 * cm->base_qindex / 100) {
2115       rc->rate_correction_factors[INTER_NORMAL] *= 0.9;
2116     }
2117   }
2118   return resize_action;
2119 }
2120
2121 static void adjust_gf_boost_lag_one_pass_vbr(VP9_COMP *cpi,
2122                                              uint64_t avg_sad_current) {
2123   VP9_COMMON *const cm = &cpi->common;
2124   RATE_CONTROL *const rc = &cpi->rc;
2125   int target;
2126   int found = 0;
2127   int found2 = 0;
2128   int frame;
2129   int i;
2130   uint64_t avg_source_sad_lag = avg_sad_current;
2131   int high_source_sad_lagindex = -1;
2132   int steady_sad_lagindex = -1;
2133   uint32_t sad_thresh1 = 70000;
2134   uint32_t sad_thresh2 = 120000;
2135   int low_content = 0;
2136   int high_content = 0;
2137   double rate_err = 1.0;
2138   // Get measure of complexity over the future frames, and get the first
2139   // future frame with high_source_sad/scene-change.
2140   int tot_frames = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
2141   for (frame = tot_frames; frame >= 1; --frame) {
2142     const int lagframe_idx = tot_frames - frame + 1;
2143     uint64_t reference_sad = rc->avg_source_sad[0];
2144     for (i = 1; i < lagframe_idx; ++i) {
2145       if (rc->avg_source_sad[i] > 0)
2146         reference_sad = (3 * reference_sad + rc->avg_source_sad[i]) >> 2;
2147     }
2148     // Detect up-coming scene change.
2149     if (!found &&
2150         (rc->avg_source_sad[lagframe_idx] >
2151              VPXMAX(sad_thresh1, (unsigned int)(reference_sad << 1)) ||
2152          rc->avg_source_sad[lagframe_idx] >
2153              VPXMAX(3 * sad_thresh1 >> 2,
2154                     (unsigned int)(reference_sad << 2)))) {
2155       high_source_sad_lagindex = lagframe_idx;
2156       found = 1;
2157     }
2158     // Detect change from motion to steady.
2159     if (!found2 && lagframe_idx > 1 && lagframe_idx < tot_frames &&
2160         rc->avg_source_sad[lagframe_idx - 1] > (sad_thresh1 >> 2)) {
2161       found2 = 1;
2162       for (i = lagframe_idx; i < tot_frames; ++i) {
2163         if (!(rc->avg_source_sad[i] > 0 &&
2164               rc->avg_source_sad[i] < (sad_thresh1 >> 2) &&
2165               rc->avg_source_sad[i] <
2166                   (rc->avg_source_sad[lagframe_idx - 1] >> 1))) {
2167           found2 = 0;
2168           i = tot_frames;
2169         }
2170       }
2171       if (found2) steady_sad_lagindex = lagframe_idx;
2172     }
2173     avg_source_sad_lag += rc->avg_source_sad[lagframe_idx];
2174   }
2175   if (tot_frames > 0) avg_source_sad_lag = avg_source_sad_lag / tot_frames;
2176   // Constrain distance between detected scene cuts.
2177   if (high_source_sad_lagindex != -1 &&
2178       high_source_sad_lagindex != rc->high_source_sad_lagindex - 1 &&
2179       abs(high_source_sad_lagindex - rc->high_source_sad_lagindex) < 4)
2180     rc->high_source_sad_lagindex = -1;
2181   else
2182     rc->high_source_sad_lagindex = high_source_sad_lagindex;
2183   // Adjust some factors for the next GF group, ignore initial key frame,
2184   // and only for lag_in_frames not too small.
2185   if (cpi->refresh_golden_frame == 1 && cm->current_video_frame > 30 &&
2186       cpi->oxcf.lag_in_frames > 8) {
2187     int frame_constraint;
2188     if (rc->rolling_target_bits > 0)
2189       rate_err =
2190           (double)rc->rolling_actual_bits / (double)rc->rolling_target_bits;
2191     high_content = high_source_sad_lagindex != -1 ||
2192                    avg_source_sad_lag > (rc->prev_avg_source_sad_lag << 1) ||
2193                    avg_source_sad_lag > sad_thresh2;
2194     low_content = high_source_sad_lagindex == -1 &&
2195                   ((avg_source_sad_lag < (rc->prev_avg_source_sad_lag >> 1)) ||
2196                    (avg_source_sad_lag < sad_thresh1));
2197     if (low_content) {
2198       rc->gfu_boost = DEFAULT_GF_BOOST;
2199       rc->baseline_gf_interval =
2200           VPXMIN(15, (3 * rc->baseline_gf_interval) >> 1);
2201     } else if (high_content) {
2202       rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
2203       rc->baseline_gf_interval = (rate_err > 3.0)
2204                                      ? VPXMAX(10, rc->baseline_gf_interval >> 1)
2205                                      : VPXMAX(6, rc->baseline_gf_interval >> 1);
2206     }
2207     if (rc->baseline_gf_interval > cpi->oxcf.lag_in_frames - 1)
2208       rc->baseline_gf_interval = cpi->oxcf.lag_in_frames - 1;
2209     // Check for constraining gf_interval for up-coming scene/content changes,
2210     // or for up-coming key frame, whichever is closer.
2211     frame_constraint = rc->frames_to_key;
2212     if (rc->high_source_sad_lagindex > 0 &&
2213         frame_constraint > rc->high_source_sad_lagindex)
2214       frame_constraint = rc->high_source_sad_lagindex;
2215     if (steady_sad_lagindex > 3 && frame_constraint > steady_sad_lagindex)
2216       frame_constraint = steady_sad_lagindex;
2217     adjust_gfint_frame_constraint(cpi, frame_constraint);
2218     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2219     // Adjust factors for active_worst setting & af_ratio for next gf interval.
2220     rc->fac_active_worst_inter = 150;  // corresponds to 3/2 (= 150 /100).
2221     rc->fac_active_worst_gf = 100;
2222     if (rate_err < 2.0 && !high_content) {
2223       rc->fac_active_worst_inter = 120;
2224       rc->fac_active_worst_gf = 90;
2225     } else if (rate_err > 8.0 && rc->avg_frame_qindex[INTER_FRAME] < 16) {
2226       // Increase active_worst faster at low Q if rate fluctuation is high.
2227       rc->fac_active_worst_inter = 200;
2228       if (rc->avg_frame_qindex[INTER_FRAME] < 8)
2229         rc->fac_active_worst_inter = 400;
2230     }
2231     if (low_content && rc->avg_frame_low_motion > 80) {
2232       rc->af_ratio_onepass_vbr = 15;
2233     } else if (high_content || rc->avg_frame_low_motion < 30) {
2234       rc->af_ratio_onepass_vbr = 5;
2235       rc->gfu_boost = DEFAULT_GF_BOOST >> 2;
2236     }
2237     if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf) {
2238       // Flag to disable usage of ARF based on past usage, only allow this
2239       // disabling if current frame/group does not start with key frame or
2240       // scene cut. Note perc_arf_usage is only computed for speed >= 5.
2241       int arf_usage_low =
2242           (cm->frame_type != KEY_FRAME && !rc->high_source_sad &&
2243            cpi->rc.perc_arf_usage < 15 && cpi->oxcf.speed >= 5);
2244       // Don't use alt-ref for this group under certain conditions.
2245       if (arf_usage_low ||
2246           (rc->high_source_sad_lagindex > 0 &&
2247            rc->high_source_sad_lagindex <= rc->frames_till_gf_update_due) ||
2248           (avg_source_sad_lag > 3 * sad_thresh1 >> 3)) {
2249         rc->source_alt_ref_pending = 0;
2250         rc->alt_ref_gf_group = 0;
2251       } else {
2252         rc->source_alt_ref_pending = 1;
2253         rc->alt_ref_gf_group = 1;
2254         // If alt-ref is used for this gf group, limit the interval.
2255         if (rc->baseline_gf_interval > 12) {
2256           rc->baseline_gf_interval = 12;
2257           rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2258         }
2259       }
2260     }
2261     target = calc_pframe_target_size_one_pass_vbr(cpi);
2262     vp9_rc_set_frame_target(cpi, target);
2263   }
2264   rc->prev_avg_source_sad_lag = avg_source_sad_lag;
2265 }
2266
2267 // Compute average source sad (temporal sad: between current source and
2268 // previous source) over a subset of superblocks. Use this is detect big changes
2269 // in content and allow rate control to react.
2270 // This function also handles special case of lag_in_frames, to measure content
2271 // level in #future frames set by the lag_in_frames.
2272 void vp9_scene_detection_onepass(VP9_COMP *cpi) {
2273   VP9_COMMON *const cm = &cpi->common;
2274   RATE_CONTROL *const rc = &cpi->rc;
2275 #if CONFIG_VP9_HIGHBITDEPTH
2276   if (cm->use_highbitdepth) return;
2277 #endif
2278   rc->high_source_sad = 0;
2279   if (cpi->Last_Source != NULL &&
2280       cpi->Last_Source->y_width == cpi->Source->y_width &&
2281       cpi->Last_Source->y_height == cpi->Source->y_height) {
2282     YV12_BUFFER_CONFIG *frames[MAX_LAG_BUFFERS] = { NULL };
2283     uint8_t *src_y = cpi->Source->y_buffer;
2284     int src_ystride = cpi->Source->y_stride;
2285     uint8_t *last_src_y = cpi->Last_Source->y_buffer;
2286     int last_src_ystride = cpi->Last_Source->y_stride;
2287     int start_frame = 0;
2288     int frames_to_buffer = 1;
2289     int frame = 0;
2290     int scene_cut_force_key_frame = 0;
2291     uint64_t avg_sad_current = 0;
2292     uint32_t min_thresh = 4000;
2293     float thresh = 8.0f;
2294     uint32_t thresh_key = 140000;
2295     if (cpi->oxcf.speed <= 5) thresh_key = 240000;
2296     if (cpi->oxcf.rc_mode == VPX_VBR) {
2297       min_thresh = 65000;
2298       thresh = 2.1f;
2299     }
2300     if (cpi->oxcf.lag_in_frames > 0) {
2301       frames_to_buffer = (cm->current_video_frame == 1)
2302                              ? (int)vp9_lookahead_depth(cpi->lookahead) - 1
2303                              : 2;
2304       start_frame = (int)vp9_lookahead_depth(cpi->lookahead) - 1;
2305       for (frame = 0; frame < frames_to_buffer; ++frame) {
2306         const int lagframe_idx = start_frame - frame;
2307         if (lagframe_idx >= 0) {
2308           struct lookahead_entry *buf =
2309               vp9_lookahead_peek(cpi->lookahead, lagframe_idx);
2310           frames[frame] = &buf->img;
2311         }
2312       }
2313       // The avg_sad for this current frame is the value of frame#1
2314       // (first future frame) from previous frame.
2315       avg_sad_current = rc->avg_source_sad[1];
2316       if (avg_sad_current >
2317               VPXMAX(min_thresh,
2318                      (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
2319           cm->current_video_frame > (unsigned int)cpi->oxcf.lag_in_frames)
2320         rc->high_source_sad = 1;
2321       else
2322         rc->high_source_sad = 0;
2323       if (rc->high_source_sad && avg_sad_current > thresh_key)
2324         scene_cut_force_key_frame = 1;
2325       // Update recursive average for current frame.
2326       if (avg_sad_current > 0)
2327         rc->avg_source_sad[0] =
2328             (3 * rc->avg_source_sad[0] + avg_sad_current) >> 2;
2329       // Shift back data, starting at frame#1.
2330       for (frame = 1; frame < cpi->oxcf.lag_in_frames - 1; ++frame)
2331         rc->avg_source_sad[frame] = rc->avg_source_sad[frame + 1];
2332     }
2333     for (frame = 0; frame < frames_to_buffer; ++frame) {
2334       if (cpi->oxcf.lag_in_frames == 0 ||
2335           (frames[frame] != NULL && frames[frame + 1] != NULL &&
2336            frames[frame]->y_width == frames[frame + 1]->y_width &&
2337            frames[frame]->y_height == frames[frame + 1]->y_height)) {
2338         int sbi_row, sbi_col;
2339         const int lagframe_idx =
2340             (cpi->oxcf.lag_in_frames == 0) ? 0 : start_frame - frame + 1;
2341         const BLOCK_SIZE bsize = BLOCK_64X64;
2342         // Loop over sub-sample of frame, compute average sad over 64x64 blocks.
2343         uint64_t avg_sad = 0;
2344         uint64_t tmp_sad = 0;
2345         int num_samples = 0;
2346         int sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
2347         int sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
2348         if (cpi->oxcf.lag_in_frames > 0) {
2349           src_y = frames[frame]->y_buffer;
2350           src_ystride = frames[frame]->y_stride;
2351           last_src_y = frames[frame + 1]->y_buffer;
2352           last_src_ystride = frames[frame + 1]->y_stride;
2353         }
2354         for (sbi_row = 0; sbi_row < sb_rows; ++sbi_row) {
2355           for (sbi_col = 0; sbi_col < sb_cols; ++sbi_col) {
2356             // Checker-board pattern, ignore boundary.
2357             if (((sbi_row > 0 && sbi_col > 0) &&
2358                  (sbi_row < sb_rows - 1 && sbi_col < sb_cols - 1) &&
2359                  ((sbi_row % 2 == 0 && sbi_col % 2 == 0) ||
2360                   (sbi_row % 2 != 0 && sbi_col % 2 != 0)))) {
2361               tmp_sad = cpi->fn_ptr[bsize].sdf(src_y, src_ystride, last_src_y,
2362                                                last_src_ystride);
2363               avg_sad += tmp_sad;
2364               num_samples++;
2365             }
2366             src_y += 64;
2367             last_src_y += 64;
2368           }
2369           src_y += (src_ystride << 6) - (sb_cols << 6);
2370           last_src_y += (last_src_ystride << 6) - (sb_cols << 6);
2371         }
2372         if (num_samples > 0) avg_sad = avg_sad / num_samples;
2373         // Set high_source_sad flag if we detect very high increase in avg_sad
2374         // between current and previous frame value(s). Use minimum threshold
2375         // for cases where there is small change from content that is completely
2376         // static.
2377         if (lagframe_idx == 0) {
2378           if (avg_sad >
2379                   VPXMAX(min_thresh,
2380                          (unsigned int)(rc->avg_source_sad[0] * thresh)) &&
2381               rc->frames_since_key > 1)
2382             rc->high_source_sad = 1;
2383           else
2384             rc->high_source_sad = 0;
2385           if (rc->high_source_sad && avg_sad > thresh_key)
2386             scene_cut_force_key_frame = 1;
2387           if (avg_sad > 0 || cpi->oxcf.rc_mode == VPX_CBR)
2388             rc->avg_source_sad[0] = (3 * rc->avg_source_sad[0] + avg_sad) >> 2;
2389         } else {
2390           rc->avg_source_sad[lagframe_idx] = avg_sad;
2391         }
2392       }
2393     }
2394     // For CBR non-screen content mode, check if we should reset the rate
2395     // control. Reset is done if high_source_sad is detected and the rate
2396     // control is at very low QP with rate correction factor at min level.
2397     if (cpi->oxcf.rc_mode == VPX_CBR &&
2398         cpi->oxcf.content != VP9E_CONTENT_SCREEN && !cpi->use_svc) {
2399       if (rc->high_source_sad && rc->last_q[INTER_FRAME] == rc->best_quality &&
2400           rc->avg_frame_qindex[INTER_FRAME] < (rc->best_quality << 1) &&
2401           rc->rate_correction_factors[INTER_NORMAL] == MIN_BPB_FACTOR) {
2402         rc->rate_correction_factors[INTER_NORMAL] = 0.5;
2403         rc->avg_frame_qindex[INTER_FRAME] = rc->worst_quality;
2404         rc->buffer_level = rc->optimal_buffer_level;
2405         rc->bits_off_target = rc->optimal_buffer_level;
2406         rc->reset_high_source_sad = 1;
2407       }
2408       if (cm->frame_type != KEY_FRAME && rc->reset_high_source_sad)
2409         rc->this_frame_target = rc->avg_frame_bandwidth;
2410     }
2411     // For VBR, under scene change/high content change, force golden refresh.
2412     if (cpi->oxcf.rc_mode == VPX_VBR && cm->frame_type != KEY_FRAME &&
2413         rc->high_source_sad && rc->frames_to_key > 3 &&
2414         rc->count_last_scene_change > 4 &&
2415         cpi->ext_refresh_frame_flags_pending == 0) {
2416       int target;
2417       cpi->refresh_golden_frame = 1;
2418       if (scene_cut_force_key_frame) cm->frame_type = KEY_FRAME;
2419       rc->source_alt_ref_pending = 0;
2420       if (cpi->sf.use_altref_onepass && cpi->oxcf.enable_auto_arf)
2421         rc->source_alt_ref_pending = 1;
2422       rc->gfu_boost = DEFAULT_GF_BOOST >> 1;
2423       rc->baseline_gf_interval =
2424           VPXMIN(20, VPXMAX(10, rc->baseline_gf_interval));
2425       adjust_gfint_frame_constraint(cpi, rc->frames_to_key);
2426       rc->frames_till_gf_update_due = rc->baseline_gf_interval;
2427       target = calc_pframe_target_size_one_pass_vbr(cpi);
2428       vp9_rc_set_frame_target(cpi, target);
2429       rc->count_last_scene_change = 0;
2430     } else {
2431       rc->count_last_scene_change++;
2432     }
2433     // If lag_in_frame is used, set the gf boost and interval.
2434     if (cpi->oxcf.lag_in_frames > 0)
2435       adjust_gf_boost_lag_one_pass_vbr(cpi, avg_sad_current);
2436   }
2437 }
2438
2439 // Test if encoded frame will significantly overshoot the target bitrate, and
2440 // if so, set the QP, reset/adjust some rate control parameters, and return 1.
2441 int vp9_encodedframe_overshoot(VP9_COMP *cpi, int frame_size, int *q) {
2442   VP9_COMMON *const cm = &cpi->common;
2443   RATE_CONTROL *const rc = &cpi->rc;
2444   int thresh_qp = 3 * (rc->worst_quality >> 2);
2445   int thresh_rate = rc->avg_frame_bandwidth * 10;
2446   if (cm->base_qindex < thresh_qp && frame_size > thresh_rate) {
2447     double rate_correction_factor =
2448         cpi->rc.rate_correction_factors[INTER_NORMAL];
2449     const int target_size = cpi->rc.avg_frame_bandwidth;
2450     double new_correction_factor;
2451     int target_bits_per_mb;
2452     double q2;
2453     int enumerator;
2454     // Force a re-encode, and for now use max-QP.
2455     *q = cpi->rc.worst_quality;
2456     // Adjust avg_frame_qindex, buffer_level, and rate correction factors, as
2457     // these parameters will affect QP selection for subsequent frames. If they
2458     // have settled down to a very different (low QP) state, then not adjusting
2459     // them may cause next frame to select low QP and overshoot again.
2460     cpi->rc.avg_frame_qindex[INTER_FRAME] = *q;
2461     rc->buffer_level = rc->optimal_buffer_level;
2462     rc->bits_off_target = rc->optimal_buffer_level;
2463     // Reset rate under/over-shoot flags.
2464     cpi->rc.rc_1_frame = 0;
2465     cpi->rc.rc_2_frame = 0;
2466     // Adjust rate correction factor.
2467     target_bits_per_mb =
2468         (int)(((uint64_t)target_size << BPER_MB_NORMBITS) / cm->MBs);
2469     // Rate correction factor based on target_bits_per_mb and qp (==max_QP).
2470     // This comes from the inverse computation of vp9_rc_bits_per_mb().
2471     q2 = vp9_convert_qindex_to_q(*q, cm->bit_depth);
2472     enumerator = 1800000;  // Factor for inter frame.
2473     enumerator += (int)(enumerator * q2) >> 12;
2474     new_correction_factor = (double)target_bits_per_mb * q2 / enumerator;
2475     if (new_correction_factor > rate_correction_factor) {
2476       rate_correction_factor =
2477           VPXMIN(2.0 * rate_correction_factor, new_correction_factor);
2478       if (rate_correction_factor > MAX_BPB_FACTOR)
2479         rate_correction_factor = MAX_BPB_FACTOR;
2480       cpi->rc.rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
2481     }
2482     // For temporal layers, reset the rate control parametes across all
2483     // temporal layers.
2484     if (cpi->use_svc) {
2485       int i = 0;
2486       SVC *svc = &cpi->svc;
2487       for (i = 0; i < svc->number_temporal_layers; ++i) {
2488         const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
2489                                            svc->number_temporal_layers);
2490         LAYER_CONTEXT *lc = &svc->layer_context[layer];
2491         RATE_CONTROL *lrc = &lc->rc;
2492         lrc->avg_frame_qindex[INTER_FRAME] = *q;
2493         lrc->buffer_level = rc->optimal_buffer_level;
2494         lrc->bits_off_target = rc->optimal_buffer_level;
2495         lrc->rc_1_frame = 0;
2496         lrc->rc_2_frame = 0;
2497         lrc->rate_correction_factors[INTER_NORMAL] = rate_correction_factor;
2498       }
2499     }
2500     return 1;
2501   } else {
2502     return 0;
2503   }
2504 }