]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_ratectrl.c
32682fe7480c23448e8a80ac9d12984f56ffa3be
[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_mem/vpx_mem.h"
19 #include "vpx_ports/mem.h"
20
21 #include "vp9/common/vp9_alloccommon.h"
22 #include "vp9/encoder/vp9_aq_cyclicrefresh.h"
23 #include "vp9/common/vp9_common.h"
24 #include "vp9/common/vp9_entropymode.h"
25 #include "vp9/common/vp9_quant_common.h"
26 #include "vp9/common/vp9_seg_common.h"
27 #include "vp9/common/vp9_systemdependent.h"
28
29 #include "vp9/encoder/vp9_encodemv.h"
30 #include "vp9/encoder/vp9_ratectrl.h"
31
32 // Max rate target for 1080P and below encodes under normal circumstances
33 // (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
34 #define MAX_MB_RATE 250
35 #define MAXRATE_1080P 2025000
36
37 #define DEFAULT_KF_BOOST 2000
38 #define DEFAULT_GF_BOOST 2000
39
40 #define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
41
42 #define MIN_BPB_FACTOR 0.005
43 #define MAX_BPB_FACTOR 50
44
45 #define FRAME_OVERHEAD_BITS 200
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: \
52         name = name##_8; \
53         break; \
54       case VPX_BITS_10: \
55         name = name##_10; \
56         break; \
57       case VPX_BITS_12: \
58         name = name##_12; \
59         break; \
60       default: \
61         assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10" \
62                     " or VPX_BITS_12"); \
63         name = NULL; \
64     } \
65   } while (0)
66 #else
67 #define ASSIGN_MINQ_TABLE(bit_depth, name) \
68   do { \
69     (void) bit_depth; \
70     name = name##_8; \
71   } while (0)
72 #endif
73
74 // Tables relating active max Q to active min Q
75 static int kf_low_motion_minq_8[QINDEX_RANGE];
76 static int kf_high_motion_minq_8[QINDEX_RANGE];
77 static int arfgf_low_motion_minq_8[QINDEX_RANGE];
78 static int arfgf_high_motion_minq_8[QINDEX_RANGE];
79 static int inter_minq_8[QINDEX_RANGE];
80 static int rtc_minq_8[QINDEX_RANGE];
81
82 #if CONFIG_VP9_HIGHBITDEPTH
83 static int kf_low_motion_minq_10[QINDEX_RANGE];
84 static int kf_high_motion_minq_10[QINDEX_RANGE];
85 static int arfgf_low_motion_minq_10[QINDEX_RANGE];
86 static int arfgf_high_motion_minq_10[QINDEX_RANGE];
87 static int inter_minq_10[QINDEX_RANGE];
88 static int rtc_minq_10[QINDEX_RANGE];
89 static int kf_low_motion_minq_12[QINDEX_RANGE];
90 static int kf_high_motion_minq_12[QINDEX_RANGE];
91 static int arfgf_low_motion_minq_12[QINDEX_RANGE];
92 static int arfgf_high_motion_minq_12[QINDEX_RANGE];
93 static int inter_minq_12[QINDEX_RANGE];
94 static int rtc_minq_12[QINDEX_RANGE];
95 #endif
96
97 static int gf_high = 2000;
98 static int gf_low = 400;
99 static int kf_high = 5000;
100 static int kf_low = 400;
101
102 // Functions to compute the active minq lookup table entries based on a
103 // formulaic approach to facilitate easier adjustment of the Q tables.
104 // The formulae were derived from computing a 3rd order polynomial best
105 // fit to the original data (after plotting real maxq vs minq (not q index))
106 static int get_minq_index(double maxq, double x3, double x2, double x1,
107                           vpx_bit_depth_t bit_depth) {
108   int i;
109   const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq,
110                                 maxq);
111
112   // Special case handling to deal with the step from q2.0
113   // down to lossless mode represented by q 1.0.
114   if (minqtarget <= 2.0)
115     return 0;
116
117   for (i = 0; i < QINDEX_RANGE; i++) {
118     if (minqtarget <= vp9_convert_qindex_to_q(i, bit_depth))
119       return i;
120   }
121
122   return QINDEX_RANGE - 1;
123 }
124
125 static void init_minq_luts(int *kf_low_m, int *kf_high_m,
126                            int *arfgf_low, int *arfgf_high,
127                            int *inter, int *rtc, vpx_bit_depth_t bit_depth) {
128   int i;
129   for (i = 0; i < QINDEX_RANGE; i++) {
130     const double maxq = vp9_convert_qindex_to_q(i, bit_depth);
131     kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
132     kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
133     arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
134     arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
135     inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.90, bit_depth);
136     rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
137   }
138 }
139
140 void vp9_rc_init_minq_luts(void) {
141   init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
142                  arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
143                  inter_minq_8, rtc_minq_8, VPX_BITS_8);
144 #if CONFIG_VP9_HIGHBITDEPTH
145   init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
146                  arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
147                  inter_minq_10, rtc_minq_10, VPX_BITS_10);
148   init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
149                  arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
150                  inter_minq_12, rtc_minq_12, VPX_BITS_12);
151 #endif
152 }
153
154 // These functions use formulaic calculations to make playing with the
155 // quantizer tables easier. If necessary they can be replaced by lookup
156 // tables if and when things settle down in the experimental bitstream
157 double vp9_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
158   // Convert the index to a real Q value (scaled down to match old Q values)
159 #if CONFIG_VP9_HIGHBITDEPTH
160   switch (bit_depth) {
161     case VPX_BITS_8:
162       return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
163     case VPX_BITS_10:
164       return vp9_ac_quant(qindex, 0, bit_depth) / 16.0;
165     case VPX_BITS_12:
166       return vp9_ac_quant(qindex, 0, bit_depth) / 64.0;
167     default:
168       assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
169       return -1.0;
170   }
171 #else
172   return vp9_ac_quant(qindex, 0, bit_depth) / 4.0;
173 #endif
174 }
175
176 int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
177                        double correction_factor,
178                        vpx_bit_depth_t bit_depth) {
179   const double q = vp9_convert_qindex_to_q(qindex, bit_depth);
180   int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
181
182   assert(correction_factor <= MAX_BPB_FACTOR &&
183          correction_factor >= MIN_BPB_FACTOR);
184
185   // q based adjustment to baseline enumerator
186   enumerator += (int)(enumerator * q) >> 12;
187   return (int)(enumerator * correction_factor / q);
188 }
189
190 int vp9_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
191                            double correction_factor,
192                            vpx_bit_depth_t bit_depth) {
193   const int bpm = (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor,
194                                            bit_depth));
195   return MAX(FRAME_OVERHEAD_BITS,
196              (int)((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS);
197 }
198
199 int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
200   const RATE_CONTROL *rc = &cpi->rc;
201   const VP9EncoderConfig *oxcf = &cpi->oxcf;
202   const int min_frame_target = MAX(rc->min_frame_bandwidth,
203                                    rc->avg_frame_bandwidth >> 5);
204   if (target < min_frame_target)
205     target = min_frame_target;
206   if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
207     // If there is an active ARF at this location use the minimum
208     // bits on this frame even if it is a constructed arf.
209     // The active maximum quantizer insures that an appropriate
210     // number of bits will be spent if needed for constructed ARFs.
211     target = min_frame_target;
212   }
213   // Clip the frame target to the maximum allowed value.
214   if (target > rc->max_frame_bandwidth)
215     target = rc->max_frame_bandwidth;
216   if (oxcf->rc_max_inter_bitrate_pct) {
217     const int max_rate = rc->avg_frame_bandwidth *
218                          oxcf->rc_max_inter_bitrate_pct / 100;
219     target = MIN(target, max_rate);
220   }
221   return target;
222 }
223
224 int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
225   const RATE_CONTROL *rc = &cpi->rc;
226   const VP9EncoderConfig *oxcf = &cpi->oxcf;
227   if (oxcf->rc_max_intra_bitrate_pct) {
228     const int max_rate = rc->avg_frame_bandwidth *
229                              oxcf->rc_max_intra_bitrate_pct / 100;
230     target = MIN(target, max_rate);
231   }
232   if (target > rc->max_frame_bandwidth)
233     target = rc->max_frame_bandwidth;
234   return target;
235 }
236
237 // Update the buffer level for higher temporal layers, given the encoded current
238 // temporal layer.
239 static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
240   int i = 0;
241   int current_temporal_layer = svc->temporal_layer_id;
242   for (i = current_temporal_layer + 1;
243       i < svc->number_temporal_layers; ++i) {
244     const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
245                                        svc->number_temporal_layers);
246     LAYER_CONTEXT *lc = &svc->layer_context[layer];
247     RATE_CONTROL *lrc = &lc->rc;
248     int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
249         encoded_frame_size);
250     lrc->bits_off_target += bits_off_for_this_layer;
251
252     // Clip buffer level to maximum buffer size for the layer.
253     lrc->bits_off_target = MIN(lrc->bits_off_target, lrc->maximum_buffer_size);
254     lrc->buffer_level = lrc->bits_off_target;
255   }
256 }
257
258 // Update the buffer level: leaky bucket model.
259 static void update_buffer_level(VP9_COMP *cpi, int encoded_frame_size) {
260   const VP9_COMMON *const cm = &cpi->common;
261   RATE_CONTROL *const rc = &cpi->rc;
262
263   // Non-viewable frames are a special case and are treated as pure overhead.
264   if (!cm->show_frame) {
265     rc->bits_off_target -= encoded_frame_size;
266   } else {
267     rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
268   }
269
270   // Clip the buffer level to the maximum specified buffer size.
271   rc->bits_off_target = MIN(rc->bits_off_target, rc->maximum_buffer_size);
272   rc->buffer_level = rc->bits_off_target;
273
274   if (is_one_pass_cbr_svc(cpi)) {
275     update_layer_buffer_level(&cpi->svc, encoded_frame_size);
276   }
277 }
278
279 void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
280   int i;
281
282   if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
283     rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
284     rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
285   } else {
286     rc->avg_frame_qindex[KEY_FRAME] = (oxcf->worst_allowed_q +
287                                            oxcf->best_allowed_q) / 2;
288     rc->avg_frame_qindex[INTER_FRAME] = (oxcf->worst_allowed_q +
289                                            oxcf->best_allowed_q) / 2;
290   }
291
292   rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
293   rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
294
295   rc->buffer_level =    rc->starting_buffer_level;
296   rc->bits_off_target = rc->starting_buffer_level;
297
298   rc->rolling_target_bits      = rc->avg_frame_bandwidth;
299   rc->rolling_actual_bits      = rc->avg_frame_bandwidth;
300   rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
301   rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
302
303   rc->total_actual_bits = 0;
304   rc->total_target_bits = 0;
305   rc->total_target_vs_actual = 0;
306
307   rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
308   rc->frames_since_key = 8;  // Sensible default for first frame.
309   rc->this_key_frame_forced = 0;
310   rc->next_key_frame_forced = 0;
311   rc->source_alt_ref_pending = 0;
312   rc->source_alt_ref_active = 0;
313
314   rc->frames_till_gf_update_due = 0;
315   rc->ni_av_qi = oxcf->worst_allowed_q;
316   rc->ni_tot_qi = 0;
317   rc->ni_frames = 0;
318
319   rc->tot_q = 0.0;
320   rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
321
322   for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
323     rc->rate_correction_factors[i] = 1.0;
324   }
325 }
326
327 int vp9_rc_drop_frame(VP9_COMP *cpi) {
328   const VP9EncoderConfig *oxcf = &cpi->oxcf;
329   RATE_CONTROL *const rc = &cpi->rc;
330
331   if (!oxcf->drop_frames_water_mark) {
332     return 0;
333   } else {
334     if (rc->buffer_level < 0) {
335       // Always drop if buffer is below 0.
336       return 1;
337     } else {
338       // If buffer is below drop_mark, for now just drop every other frame
339       // (starting with the next frame) until it increases back over drop_mark.
340       int drop_mark = (int)(oxcf->drop_frames_water_mark *
341           rc->optimal_buffer_level / 100);
342       if ((rc->buffer_level > drop_mark) &&
343           (rc->decimation_factor > 0)) {
344         --rc->decimation_factor;
345       } else if (rc->buffer_level <= drop_mark &&
346           rc->decimation_factor == 0) {
347         rc->decimation_factor = 1;
348       }
349       if (rc->decimation_factor > 0) {
350         if (rc->decimation_count > 0) {
351           --rc->decimation_count;
352           return 1;
353         } else {
354           rc->decimation_count = rc->decimation_factor;
355           return 0;
356         }
357       } else {
358         rc->decimation_count = 0;
359         return 0;
360       }
361     }
362   }
363 }
364
365 static double get_rate_correction_factor(const VP9_COMP *cpi) {
366   const RATE_CONTROL *const rc = &cpi->rc;
367   double rcf;
368
369   if (cpi->common.frame_type == KEY_FRAME) {
370     rcf = rc->rate_correction_factors[KF_STD];
371   } else if (cpi->oxcf.pass == 2) {
372     RATE_FACTOR_LEVEL rf_lvl =
373       cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
374     rcf = rc->rate_correction_factors[rf_lvl];
375   } else {
376     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
377         !rc->is_src_frame_alt_ref && !cpi->use_svc &&
378         (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
379       rcf = rc->rate_correction_factors[GF_ARF_STD];
380     else
381       rcf = rc->rate_correction_factors[INTER_NORMAL];
382   }
383   rcf *= rcf_mult[rc->frame_size_selector];
384   return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
385 }
386
387 static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
388   RATE_CONTROL *const rc = &cpi->rc;
389
390   // Normalize RCF to account for the size-dependent scaling factor.
391   factor /= rcf_mult[cpi->rc.frame_size_selector];
392
393   factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
394
395   if (cpi->common.frame_type == KEY_FRAME) {
396     rc->rate_correction_factors[KF_STD] = factor;
397   } else if (cpi->oxcf.pass == 2) {
398     RATE_FACTOR_LEVEL rf_lvl =
399       cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
400     rc->rate_correction_factors[rf_lvl] = factor;
401   } else {
402     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
403         !rc->is_src_frame_alt_ref && !cpi->use_svc &&
404         (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
405       rc->rate_correction_factors[GF_ARF_STD] = factor;
406     else
407       rc->rate_correction_factors[INTER_NORMAL] = factor;
408   }
409 }
410
411 void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi) {
412   const VP9_COMMON *const cm = &cpi->common;
413   int correction_factor = 100;
414   double rate_correction_factor = get_rate_correction_factor(cpi);
415   double adjustment_limit;
416
417   int projected_size_based_on_q = 0;
418
419   // Do not update the rate factors for arf overlay frames.
420   if (cpi->rc.is_src_frame_alt_ref)
421     return;
422
423   // Clear down mmx registers to allow floating point in what follows
424   vp9_clear_system_state();
425
426   // Work out how big we would have expected the frame to be at this Q given
427   // the current correction factor.
428   // Stay in double to avoid int overflow when values are large
429   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled) {
430     projected_size_based_on_q =
431         vp9_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
432   } else {
433     projected_size_based_on_q = vp9_estimate_bits_at_q(cpi->common.frame_type,
434                                                        cm->base_qindex,
435                                                        cm->MBs,
436                                                        rate_correction_factor,
437                                                        cm->bit_depth);
438   }
439   // Work out a size correction factor.
440   if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
441     correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
442                         projected_size_based_on_q);
443
444   // More heavily damped adjustment used if we have been oscillating either side
445   // of target.
446   adjustment_limit = 0.25 +
447       0.5 * MIN(1, fabs(log10(0.01 * correction_factor)));
448
449   cpi->rc.q_2_frame = cpi->rc.q_1_frame;
450   cpi->rc.q_1_frame = cm->base_qindex;
451   cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
452   if (correction_factor > 110)
453     cpi->rc.rc_1_frame = -1;
454   else if (correction_factor < 90)
455     cpi->rc.rc_1_frame = 1;
456   else
457     cpi->rc.rc_1_frame = 0;
458
459   if (correction_factor > 102) {
460     // We are not already at the worst allowable quality
461     correction_factor = (int)(100 + ((correction_factor - 100) *
462                                   adjustment_limit));
463     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
464     // Keep rate_correction_factor within limits
465     if (rate_correction_factor > MAX_BPB_FACTOR)
466       rate_correction_factor = MAX_BPB_FACTOR;
467   } else if (correction_factor < 99) {
468     // We are not already at the best allowable quality
469     correction_factor = (int)(100 - ((100 - correction_factor) *
470                                   adjustment_limit));
471     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
472
473     // Keep rate_correction_factor within limits
474     if (rate_correction_factor < MIN_BPB_FACTOR)
475       rate_correction_factor = MIN_BPB_FACTOR;
476   }
477
478   set_rate_correction_factor(cpi, rate_correction_factor);
479 }
480
481
482 int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
483                       int active_best_quality, int active_worst_quality) {
484   const VP9_COMMON *const cm = &cpi->common;
485   int q = active_worst_quality;
486   int last_error = INT_MAX;
487   int i, target_bits_per_mb, bits_per_mb_at_this_q;
488   const double correction_factor = get_rate_correction_factor(cpi);
489
490   // Calculate required scaling factor based on target frame size and size of
491   // frame produced using previous Q.
492   target_bits_per_mb =
493       ((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs;
494
495   i = active_best_quality;
496
497   do {
498     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
499         cm->seg.enabled &&
500         cpi->svc.temporal_layer_id == 0 &&
501         cpi->svc.spatial_layer_id == 0) {
502       bits_per_mb_at_this_q =
503           (int)vp9_cyclic_refresh_rc_bits_per_mb(cpi, i, correction_factor);
504     } else {
505       bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cm->frame_type, i,
506                                                       correction_factor,
507                                                       cm->bit_depth);
508     }
509
510     if (bits_per_mb_at_this_q <= target_bits_per_mb) {
511       if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
512         q = i;
513       else
514         q = i - 1;
515
516       break;
517     } else {
518       last_error = bits_per_mb_at_this_q - target_bits_per_mb;
519     }
520   } while (++i <= active_worst_quality);
521
522   // In CBR mode, this makes sure q is between oscillating Qs to prevent
523   // resonance.
524   if (cpi->oxcf.rc_mode == VPX_CBR &&
525       (cpi->rc.rc_1_frame * cpi->rc.rc_2_frame == -1) &&
526       cpi->rc.q_1_frame != cpi->rc.q_2_frame) {
527     q = clamp(q, MIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
528               MAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
529   }
530   return q;
531 }
532
533 static int get_active_quality(int q, int gfu_boost, int low, int high,
534                               int *low_motion_minq, int *high_motion_minq) {
535   if (gfu_boost > high) {
536     return low_motion_minq[q];
537   } else if (gfu_boost < low) {
538     return high_motion_minq[q];
539   } else {
540     const int gap = high - low;
541     const int offset = high - gfu_boost;
542     const int qdiff = high_motion_minq[q] - low_motion_minq[q];
543     const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
544     return low_motion_minq[q] + adjustment;
545   }
546 }
547
548 static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
549                                  vpx_bit_depth_t bit_depth) {
550   int *kf_low_motion_minq;
551   int *kf_high_motion_minq;
552   ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
553   ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
554   return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
555                             kf_low_motion_minq, kf_high_motion_minq);
556 }
557
558 static int get_gf_active_quality(const RATE_CONTROL *const rc, int q,
559                                  vpx_bit_depth_t bit_depth) {
560   int *arfgf_low_motion_minq;
561   int *arfgf_high_motion_minq;
562   ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
563   ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
564   return get_active_quality(q, rc->gfu_boost, gf_low, gf_high,
565                             arfgf_low_motion_minq, arfgf_high_motion_minq);
566 }
567
568 static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
569   const RATE_CONTROL *const rc = &cpi->rc;
570   const unsigned int curr_frame = cpi->common.current_video_frame;
571   int active_worst_quality;
572
573   if (cpi->common.frame_type == KEY_FRAME) {
574     active_worst_quality = curr_frame == 0 ? rc->worst_quality
575                                            : rc->last_q[KEY_FRAME] * 2;
576   } else {
577     if (!rc->is_src_frame_alt_ref &&
578         (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
579       active_worst_quality =  curr_frame == 1 ? rc->last_q[KEY_FRAME] * 5 / 4
580                                               : rc->last_q[INTER_FRAME];
581     } else {
582       active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 2
583                                              : rc->last_q[INTER_FRAME] * 2;
584     }
585   }
586   return MIN(active_worst_quality, rc->worst_quality);
587 }
588
589 // Adjust active_worst_quality level based on buffer level.
590 static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
591   // Adjust active_worst_quality: If buffer is above the optimal/target level,
592   // bring active_worst_quality down depending on fullness of buffer.
593   // If buffer is below the optimal level, let the active_worst_quality go from
594   // ambient Q (at buffer = optimal level) to worst_quality level
595   // (at buffer = critical level).
596   const VP9_COMMON *const cm = &cpi->common;
597   const RATE_CONTROL *rc = &cpi->rc;
598   // Buffer level below which we push active_worst to worst_quality.
599   int64_t critical_level = rc->optimal_buffer_level >> 3;
600   int64_t buff_lvl_step = 0;
601   int adjustment = 0;
602   int active_worst_quality;
603   int ambient_qp;
604   if (cm->frame_type == KEY_FRAME)
605     return rc->worst_quality;
606   // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
607   // for the first few frames following key frame. These are both initialized
608   // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
609   // So for first few frames following key, the qp of that key frame is weighted
610   // into the active_worst_quality setting.
611   ambient_qp = (cm->current_video_frame < 5) ?
612       MIN(rc->avg_frame_qindex[INTER_FRAME], rc->avg_frame_qindex[KEY_FRAME]) :
613       rc->avg_frame_qindex[INTER_FRAME];
614   active_worst_quality = MIN(rc->worst_quality,
615                              ambient_qp * 5 / 4);
616   if (rc->buffer_level > rc->optimal_buffer_level) {
617     // Adjust down.
618     // Maximum limit for down adjustment, ~30%.
619     int max_adjustment_down = active_worst_quality / 3;
620     if (max_adjustment_down) {
621       buff_lvl_step = ((rc->maximum_buffer_size -
622                         rc->optimal_buffer_level) / max_adjustment_down);
623       if (buff_lvl_step)
624         adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
625                             buff_lvl_step);
626       active_worst_quality -= adjustment;
627     }
628   } else if (rc->buffer_level > critical_level) {
629     // Adjust up from ambient Q.
630     if (critical_level) {
631       buff_lvl_step = (rc->optimal_buffer_level - critical_level);
632       if (buff_lvl_step) {
633         adjustment = (int)((rc->worst_quality - ambient_qp) *
634                            (rc->optimal_buffer_level - rc->buffer_level) /
635                            buff_lvl_step);
636       }
637       active_worst_quality = ambient_qp + adjustment;
638     }
639   } else {
640     // Set to worst_quality if buffer is below critical level.
641     active_worst_quality = rc->worst_quality;
642   }
643   return active_worst_quality;
644 }
645
646 static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
647                                              int *bottom_index,
648                                              int *top_index) {
649   const VP9_COMMON *const cm = &cpi->common;
650   const RATE_CONTROL *const rc = &cpi->rc;
651   int active_best_quality;
652   int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
653   int q;
654   int *rtc_minq;
655   ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
656
657   if (frame_is_intra_only(cm)) {
658     active_best_quality = rc->best_quality;
659     // Handle the special case for key frames forced when we have reached
660     // the maximum key frame interval. Here force the Q to a range
661     // based on the ambient Q to reduce the risk of popping.
662     if (rc->this_key_frame_forced) {
663       int qindex = rc->last_boosted_qindex;
664       double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
665       int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
666                                             (last_boosted_q * 0.75),
667                                             cm->bit_depth);
668       active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
669     } else if (cm->current_video_frame > 0) {
670       // not first frame of one pass and kf_boost is set
671       double q_adj_factor = 1.0;
672       double q_val;
673
674       active_best_quality =
675           get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
676                                 cm->bit_depth);
677
678       // Allow somewhat lower kf minq with small image formats.
679       if ((cm->width * cm->height) <= (352 * 288)) {
680         q_adj_factor -= 0.25;
681       }
682
683       // Convert the adjustment factor to a qindex delta
684       // on active_best_quality.
685       q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
686       active_best_quality += vp9_compute_qdelta(rc, q_val,
687                                                 q_val * q_adj_factor,
688                                                 cm->bit_depth);
689     }
690   } else if (!rc->is_src_frame_alt_ref &&
691              !cpi->use_svc &&
692              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
693     // Use the lower of active_worst_quality and recent
694     // average Q as basis for GF/ARF best Q limit unless last frame was
695     // a key frame.
696     if (rc->frames_since_key > 1 &&
697         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
698       q = rc->avg_frame_qindex[INTER_FRAME];
699     } else {
700       q = active_worst_quality;
701     }
702     active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
703   } else {
704     // Use the lower of active_worst_quality and recent/average Q.
705     if (cm->current_video_frame > 1) {
706       if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
707         active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
708       else
709         active_best_quality = rtc_minq[active_worst_quality];
710     } else {
711       if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
712         active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
713       else
714         active_best_quality = rtc_minq[active_worst_quality];
715     }
716   }
717
718   // Clip the active best and worst quality values to limits
719   active_best_quality = clamp(active_best_quality,
720                               rc->best_quality, rc->worst_quality);
721   active_worst_quality = clamp(active_worst_quality,
722                                active_best_quality, rc->worst_quality);
723
724   *top_index = active_worst_quality;
725   *bottom_index = active_best_quality;
726
727 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
728   // Limit Q range for the adaptive loop.
729   if (cm->frame_type == KEY_FRAME &&
730       !rc->this_key_frame_forced  &&
731       !(cm->current_video_frame == 0)) {
732     int qdelta = 0;
733     vp9_clear_system_state();
734     qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
735                                         active_worst_quality, 2.0,
736                                         cm->bit_depth);
737     *top_index = active_worst_quality + qdelta;
738     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
739   }
740 #endif
741
742   // Special case code to try and match quality with forced key frames
743   if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
744     q = rc->last_boosted_qindex;
745   } else {
746     q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
747                           active_best_quality, active_worst_quality);
748     if (q > *top_index) {
749       // Special case when we are targeting the max allowed rate
750       if (rc->this_frame_target >= rc->max_frame_bandwidth)
751         *top_index = q;
752       else
753         q = *top_index;
754     }
755   }
756   assert(*top_index <= rc->worst_quality &&
757          *top_index >= rc->best_quality);
758   assert(*bottom_index <= rc->worst_quality &&
759          *bottom_index >= rc->best_quality);
760   assert(q <= rc->worst_quality && q >= rc->best_quality);
761   return q;
762 }
763
764 static int get_active_cq_level(const RATE_CONTROL *rc,
765                                const VP9EncoderConfig *const oxcf) {
766   static const double cq_adjust_threshold = 0.1;
767   int active_cq_level = oxcf->cq_level;
768   if (oxcf->rc_mode == VPX_CQ &&
769       rc->total_target_bits > 0) {
770     const double x = (double)rc->total_actual_bits / rc->total_target_bits;
771     if (x < cq_adjust_threshold) {
772       active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
773     }
774   }
775   return active_cq_level;
776 }
777
778 static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
779                                              int *bottom_index,
780                                              int *top_index) {
781   const VP9_COMMON *const cm = &cpi->common;
782   const RATE_CONTROL *const rc = &cpi->rc;
783   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
784   const int cq_level = get_active_cq_level(rc, oxcf);
785   int active_best_quality;
786   int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
787   int q;
788   int *inter_minq;
789   ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
790
791   if (frame_is_intra_only(cm)) {
792
793     // Handle the special case for key frames forced when we have reached
794     // the maximum key frame interval. Here force the Q to a range
795     // based on the ambient Q to reduce the risk of popping.
796     if (rc->this_key_frame_forced) {
797       int qindex = rc->last_boosted_qindex;
798       double last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
799       int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
800                                             last_boosted_q * 0.75,
801                                             cm->bit_depth);
802       active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
803     } else {
804       // not first frame of one pass and kf_boost is set
805       double q_adj_factor = 1.0;
806       double q_val;
807
808       active_best_quality =
809           get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
810                                 cm->bit_depth);
811
812       // Allow somewhat lower kf minq with small image formats.
813       if ((cm->width * cm->height) <= (352 * 288)) {
814         q_adj_factor -= 0.25;
815       }
816
817       // Convert the adjustment factor to a qindex delta
818       // on active_best_quality.
819       q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
820       active_best_quality += vp9_compute_qdelta(rc, q_val,
821                                                 q_val * q_adj_factor,
822                                                 cm->bit_depth);
823     }
824   } else if (!rc->is_src_frame_alt_ref &&
825              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
826     // Use the lower of active_worst_quality and recent
827     // average Q as basis for GF/ARF best Q limit unless last frame was
828     // a key frame.
829     if (rc->frames_since_key > 1 &&
830         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
831       q = rc->avg_frame_qindex[INTER_FRAME];
832     } else {
833       q = rc->avg_frame_qindex[KEY_FRAME];
834     }
835     // For constrained quality dont allow Q less than the cq level
836     if (oxcf->rc_mode == VPX_CQ) {
837       if (q < cq_level)
838         q = cq_level;
839
840       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
841
842       // Constrained quality use slightly lower active best.
843       active_best_quality = active_best_quality * 15 / 16;
844
845     } else if (oxcf->rc_mode == VPX_Q) {
846       if (!cpi->refresh_alt_ref_frame) {
847         active_best_quality = cq_level;
848       } else {
849         active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
850       }
851     } else {
852       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
853     }
854   } else {
855     if (oxcf->rc_mode == VPX_Q) {
856       active_best_quality = cq_level;
857     } else {
858       // Use the lower of active_worst_quality and recent/average Q.
859       if (cm->current_video_frame > 1)
860         active_best_quality = inter_minq[rc->avg_frame_qindex[INTER_FRAME]];
861       else
862         active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
863       // For the constrained quality mode we don't want
864       // q to fall below the cq level.
865       if ((oxcf->rc_mode == VPX_CQ) &&
866           (active_best_quality < cq_level)) {
867         active_best_quality = cq_level;
868       }
869     }
870   }
871
872   // Clip the active best and worst quality values to limits
873   active_best_quality = clamp(active_best_quality,
874                               rc->best_quality, rc->worst_quality);
875   active_worst_quality = clamp(active_worst_quality,
876                                active_best_quality, rc->worst_quality);
877
878   *top_index = active_worst_quality;
879   *bottom_index = active_best_quality;
880
881 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
882   {
883     int qdelta = 0;
884     vp9_clear_system_state();
885
886     // Limit Q range for the adaptive loop.
887     if (cm->frame_type == KEY_FRAME &&
888         !rc->this_key_frame_forced &&
889         !(cm->current_video_frame == 0)) {
890       qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
891                                           active_worst_quality, 2.0,
892                                           cm->bit_depth);
893     } else if (!rc->is_src_frame_alt_ref &&
894                (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
895       qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
896                                           active_worst_quality, 1.75,
897                                           cm->bit_depth);
898     }
899     *top_index = active_worst_quality + qdelta;
900     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
901   }
902 #endif
903
904   if (oxcf->rc_mode == VPX_Q) {
905     q = active_best_quality;
906   // Special case code to try and match quality with forced key frames
907   } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
908     q = rc->last_boosted_qindex;
909   } else {
910     q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
911                           active_best_quality, active_worst_quality);
912     if (q > *top_index) {
913       // Special case when we are targeting the max allowed rate
914       if (rc->this_frame_target >= rc->max_frame_bandwidth)
915         *top_index = q;
916       else
917         q = *top_index;
918     }
919   }
920
921   assert(*top_index <= rc->worst_quality &&
922          *top_index >= rc->best_quality);
923   assert(*bottom_index <= rc->worst_quality &&
924          *bottom_index >= rc->best_quality);
925   assert(q <= rc->worst_quality && q >= rc->best_quality);
926   return q;
927 }
928
929 int vp9_frame_type_qdelta(const VP9_COMP *cpi, int rf_level, int q) {
930   static const double rate_factor_deltas[RATE_FACTOR_LEVELS] = {
931     1.00,  // INTER_NORMAL
932     1.00,  // INTER_HIGH
933     1.50,  // GF_ARF_LOW
934     1.75,  // GF_ARF_STD
935     2.00,  // KF_STD
936   };
937   static const FRAME_TYPE frame_type[RATE_FACTOR_LEVELS] =
938       {INTER_FRAME, INTER_FRAME, INTER_FRAME, INTER_FRAME, KEY_FRAME};
939   const VP9_COMMON *const cm = &cpi->common;
940   int qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, frame_type[rf_level],
941                                           q, rate_factor_deltas[rf_level],
942                                           cm->bit_depth);
943   return qdelta;
944 }
945
946 #define STATIC_MOTION_THRESH 95
947 static int rc_pick_q_and_bounds_two_pass(const VP9_COMP *cpi,
948                                          int *bottom_index,
949                                          int *top_index) {
950   const VP9_COMMON *const cm = &cpi->common;
951   const RATE_CONTROL *const rc = &cpi->rc;
952   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
953   const GF_GROUP *gf_group = &cpi->twopass.gf_group;
954   const int cq_level = get_active_cq_level(rc, oxcf);
955   int active_best_quality;
956   int active_worst_quality = cpi->twopass.active_worst_quality;
957   int q;
958   int *inter_minq;
959   ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
960
961   if (frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi)) {
962     // Handle the special case for key frames forced when we have reached
963     // the maximum key frame interval. Here force the Q to a range
964     // based on the ambient Q to reduce the risk of popping.
965     if (rc->this_key_frame_forced) {
966       double last_boosted_q;
967       int delta_qindex;
968       int qindex;
969
970       if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
971         qindex = MIN(rc->last_kf_qindex, rc->last_boosted_qindex);
972         active_best_quality = qindex;
973         last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
974         delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
975                                               last_boosted_q * 1.25,
976                                               cm->bit_depth);
977         active_worst_quality = MIN(qindex + delta_qindex, active_worst_quality);
978
979       } else {
980         qindex = rc->last_boosted_qindex;
981         last_boosted_q = vp9_convert_qindex_to_q(qindex, cm->bit_depth);
982         delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
983                                               last_boosted_q * 0.75,
984                                               cm->bit_depth);
985         active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
986       }
987     } else {
988       // Not forced keyframe.
989       double q_adj_factor = 1.0;
990       double q_val;
991       // Baseline value derived from cpi->active_worst_quality and kf boost.
992       active_best_quality = get_kf_active_quality(rc, active_worst_quality,
993                                                   cm->bit_depth);
994
995       // Allow somewhat lower kf minq with small image formats.
996       if ((cm->width * cm->height) <= (352 * 288)) {
997         q_adj_factor -= 0.25;
998       }
999
1000       // Make a further adjustment based on the kf zero motion measure.
1001       q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
1002
1003       // Convert the adjustment factor to a qindex delta
1004       // on active_best_quality.
1005       q_val = vp9_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1006       active_best_quality += vp9_compute_qdelta(rc, q_val,
1007                                                 q_val * q_adj_factor,
1008                                                 cm->bit_depth);
1009     }
1010   } else if (!rc->is_src_frame_alt_ref &&
1011              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1012     // Use the lower of active_worst_quality and recent
1013     // average Q as basis for GF/ARF best Q limit unless last frame was
1014     // a key frame.
1015     if (rc->frames_since_key > 1 &&
1016         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1017       q = rc->avg_frame_qindex[INTER_FRAME];
1018     } else {
1019       q = active_worst_quality;
1020     }
1021     // For constrained quality dont allow Q less than the cq level
1022     if (oxcf->rc_mode == VPX_CQ) {
1023       if (q < cq_level)
1024         q = cq_level;
1025
1026       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1027
1028       // Constrained quality use slightly lower active best.
1029       active_best_quality = active_best_quality * 15 / 16;
1030
1031     } else if (oxcf->rc_mode == VPX_Q) {
1032       if (!cpi->refresh_alt_ref_frame) {
1033         active_best_quality = cq_level;
1034       } else {
1035        active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1036
1037         // Modify best quality for second level arfs. For mode VPX_Q this
1038         // becomes the baseline frame q.
1039         if (gf_group->rf_level[gf_group->index] == GF_ARF_LOW)
1040           active_best_quality = (active_best_quality + cq_level + 1) / 2;
1041       }
1042     } else {
1043       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1044     }
1045   } else {
1046     if (oxcf->rc_mode == VPX_Q) {
1047       active_best_quality = cq_level;
1048     } else {
1049       active_best_quality = inter_minq[active_worst_quality];
1050
1051       // For the constrained quality mode we don't want
1052       // q to fall below the cq level.
1053       if ((oxcf->rc_mode == VPX_CQ) &&
1054           (active_best_quality < cq_level)) {
1055         active_best_quality = cq_level;
1056       }
1057     }
1058   }
1059
1060   // Extension to max or min Q if undershoot or overshoot is outside
1061   // the permitted range.
1062   if ((cpi->oxcf.rc_mode != VPX_Q) &&
1063       (cpi->twopass.gf_zeromotion_pct < VLOW_MOTION_THRESHOLD)) {
1064     if (frame_is_intra_only(cm) ||
1065         (!rc->is_src_frame_alt_ref &&
1066          (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1067       active_best_quality -=
1068         (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast);
1069       active_worst_quality += (cpi->twopass.extend_maxq / 2);
1070     } else {
1071       active_best_quality -=
1072         (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast) / 2;
1073       active_worst_quality += cpi->twopass.extend_maxq;
1074     }
1075   }
1076
1077 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
1078   vp9_clear_system_state();
1079   // Static forced key frames Q restrictions dealt with elsewhere.
1080   if (!((frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi))) ||
1081       !rc->this_key_frame_forced ||
1082       (cpi->twopass.last_kfgroup_zeromotion_pct < STATIC_MOTION_THRESH)) {
1083     int qdelta = vp9_frame_type_qdelta(cpi, gf_group->rf_level[gf_group->index],
1084                                        active_worst_quality);
1085     active_worst_quality = MAX(active_worst_quality + qdelta,
1086                                active_best_quality);
1087   }
1088 #endif
1089
1090   // Modify active_best_quality for downscaled normal frames.
1091   if (rc->frame_size_selector != UNSCALED && !frame_is_kf_gf_arf(cpi)) {
1092     int qdelta = vp9_compute_qdelta_by_rate(rc, cm->frame_type,
1093                                             active_best_quality, 2.0,
1094                                             cm->bit_depth);
1095     active_best_quality = MAX(active_best_quality + qdelta, rc->best_quality);
1096   }
1097
1098   active_best_quality = clamp(active_best_quality,
1099                               rc->best_quality, rc->worst_quality);
1100   active_worst_quality = clamp(active_worst_quality,
1101                                active_best_quality, rc->worst_quality);
1102
1103   if (oxcf->rc_mode == VPX_Q) {
1104     q = active_best_quality;
1105   // Special case code to try and match quality with forced key frames.
1106   } else if ((frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi)) &&
1107              rc->this_key_frame_forced) {
1108     // If static since last kf use better of last boosted and last kf q.
1109     if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1110       q = MIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1111     } else {
1112       q = rc->last_boosted_qindex;
1113     }
1114   } else {
1115     q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
1116                           active_best_quality, active_worst_quality);
1117     if (q > active_worst_quality) {
1118       // Special case when we are targeting the max allowed rate.
1119       if (rc->this_frame_target >= rc->max_frame_bandwidth)
1120         active_worst_quality = q;
1121       else
1122         q = active_worst_quality;
1123     }
1124   }
1125   clamp(q, active_best_quality, active_worst_quality);
1126
1127   *top_index = active_worst_quality;
1128   *bottom_index = active_best_quality;
1129
1130   assert(*top_index <= rc->worst_quality &&
1131          *top_index >= rc->best_quality);
1132   assert(*bottom_index <= rc->worst_quality &&
1133          *bottom_index >= rc->best_quality);
1134   assert(q <= rc->worst_quality && q >= rc->best_quality);
1135   return q;
1136 }
1137
1138 int vp9_rc_pick_q_and_bounds(const VP9_COMP *cpi,
1139                              int *bottom_index, int *top_index) {
1140   int q;
1141   if (cpi->oxcf.pass == 0) {
1142     if (cpi->oxcf.rc_mode == VPX_CBR)
1143       q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
1144     else
1145       q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
1146   } else {
1147     q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
1148   }
1149   if (cpi->sf.use_nonrd_pick_mode) {
1150     if (cpi->sf.force_frame_boost == 1)
1151       q -= cpi->sf.max_delta_qindex;
1152
1153     if (q < *bottom_index)
1154       *bottom_index = q;
1155     else if (q > *top_index)
1156       *top_index = q;
1157   }
1158   return q;
1159 }
1160
1161 void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi,
1162                                       int frame_target,
1163                                       int *frame_under_shoot_limit,
1164                                       int *frame_over_shoot_limit) {
1165   if (cpi->oxcf.rc_mode == VPX_Q) {
1166     *frame_under_shoot_limit = 0;
1167     *frame_over_shoot_limit  = INT_MAX;
1168   } else {
1169     // For very small rate targets where the fractional adjustment
1170     // may be tiny make sure there is at least a minimum range.
1171     const int tolerance = (cpi->sf.recode_tolerance * frame_target) / 100;
1172     *frame_under_shoot_limit = MAX(frame_target - tolerance - 200, 0);
1173     *frame_over_shoot_limit = MIN(frame_target + tolerance + 200,
1174                                   cpi->rc.max_frame_bandwidth);
1175   }
1176 }
1177
1178 void vp9_rc_set_frame_target(VP9_COMP *cpi, int target) {
1179   const VP9_COMMON *const cm = &cpi->common;
1180   RATE_CONTROL *const rc = &cpi->rc;
1181
1182   rc->this_frame_target = target;
1183
1184   // Modify frame size target when down-scaling.
1185   if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC &&
1186       rc->frame_size_selector != UNSCALED)
1187     rc->this_frame_target = (int)(rc->this_frame_target
1188         * rate_thresh_mult[rc->frame_size_selector]);
1189
1190   // Target rate per SB64 (including partial SB64s.
1191   rc->sb64_target_rate = ((int64_t)rc->this_frame_target * 64 * 64) /
1192                              (cm->width * cm->height);
1193 }
1194
1195 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
1196   // this frame refreshes means next frames don't unless specified by user
1197   RATE_CONTROL *const rc = &cpi->rc;
1198   rc->frames_since_golden = 0;
1199
1200   // Mark the alt ref as done (setting to 0 means no further alt refs pending).
1201   rc->source_alt_ref_pending = 0;
1202
1203   // Set the alternate reference frame active flag
1204   rc->source_alt_ref_active = 1;
1205 }
1206
1207 static void update_golden_frame_stats(VP9_COMP *cpi) {
1208   RATE_CONTROL *const rc = &cpi->rc;
1209
1210   // Update the Golden frame usage counts.
1211   if (cpi->refresh_golden_frame) {
1212     // this frame refreshes means next frames don't unless specified by user
1213     rc->frames_since_golden = 0;
1214
1215     // If we are not using alt ref in the up and coming group clear the arf
1216     // active flag.
1217     if (!rc->source_alt_ref_pending) {
1218       rc->source_alt_ref_active = 0;
1219     }
1220
1221     // Decrement count down till next gf
1222     if (rc->frames_till_gf_update_due > 0)
1223       rc->frames_till_gf_update_due--;
1224
1225   } else if (!cpi->refresh_alt_ref_frame) {
1226     // Decrement count down till next gf
1227     if (rc->frames_till_gf_update_due > 0)
1228       rc->frames_till_gf_update_due--;
1229
1230     rc->frames_since_golden++;
1231   }
1232 }
1233
1234 void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
1235   const VP9_COMMON *const cm = &cpi->common;
1236   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1237   RATE_CONTROL *const rc = &cpi->rc;
1238   const int qindex = cm->base_qindex;
1239
1240   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
1241     vp9_cyclic_refresh_postencode(cpi);
1242   }
1243
1244   // Update rate control heuristics
1245   rc->projected_frame_size = (int)(bytes_used << 3);
1246
1247   // Post encode loop adjustment of Q prediction.
1248   vp9_rc_update_rate_correction_factors(cpi);
1249
1250   // Keep a record of last Q and ambient average Q.
1251   if (cm->frame_type == KEY_FRAME) {
1252     rc->last_q[KEY_FRAME] = qindex;
1253     rc->avg_frame_qindex[KEY_FRAME] =
1254         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1255   } else {
1256     if (rc->is_src_frame_alt_ref ||
1257         !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) ||
1258         (cpi->use_svc && oxcf->rc_mode == VPX_CBR)) {
1259       rc->last_q[INTER_FRAME] = qindex;
1260       rc->avg_frame_qindex[INTER_FRAME] =
1261         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1262       rc->ni_frames++;
1263       rc->tot_q += vp9_convert_qindex_to_q(qindex, cm->bit_depth);
1264       rc->avg_q = rc->tot_q / rc->ni_frames;
1265       // Calculate the average Q for normal inter frames (not key or GFU
1266       // frames).
1267       rc->ni_tot_qi += qindex;
1268       rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1269     }
1270   }
1271
1272   // Keep record of last boosted (KF/KF/ARF) Q value.
1273   // If the current frame is coded at a lower Q then we also update it.
1274   // If all mbs in this group are skipped only update if the Q value is
1275   // better than that already stored.
1276   // This is used to help set quality in forced key frames to reduce popping
1277   if ((qindex < rc->last_boosted_qindex) ||
1278       (cm->frame_type == KEY_FRAME) ||
1279       (!rc->constrained_gf_group &&
1280        (cpi->refresh_alt_ref_frame ||
1281         (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1282     rc->last_boosted_qindex = qindex;
1283   }
1284   if (cm->frame_type == KEY_FRAME)
1285     rc->last_kf_qindex = qindex;
1286
1287   update_buffer_level(cpi, rc->projected_frame_size);
1288
1289   // Rolling monitors of whether we are over or underspending used to help
1290   // regulate min and Max Q in two pass.
1291   if (cm->frame_type != KEY_FRAME) {
1292     rc->rolling_target_bits = ROUND_POWER_OF_TWO(
1293         rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1294     rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
1295         rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1296     rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
1297         rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1298     rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
1299         rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
1300   }
1301
1302   // Actual bits spent
1303   rc->total_actual_bits += rc->projected_frame_size;
1304   rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1305
1306   rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1307
1308   if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
1309       (cm->frame_type != KEY_FRAME))
1310     // Update the alternate reference frame stats as appropriate.
1311     update_alt_ref_frame_stats(cpi);
1312   else
1313     // Update the Golden frame stats as appropriate.
1314     update_golden_frame_stats(cpi);
1315
1316   if (cm->frame_type == KEY_FRAME)
1317     rc->frames_since_key = 0;
1318   if (cm->show_frame) {
1319     rc->frames_since_key++;
1320     rc->frames_to_key--;
1321   }
1322
1323   // Trigger the resizing of the next frame if it is scaled.
1324   cpi->resize_pending =
1325       rc->next_frame_size_selector != rc->frame_size_selector;
1326   rc->frame_size_selector = rc->next_frame_size_selector;
1327 }
1328
1329 void vp9_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
1330   // Update buffer level with zero size, update frame counters, and return.
1331   update_buffer_level(cpi, 0);
1332   cpi->rc.frames_since_key++;
1333   cpi->rc.frames_to_key--;
1334   cpi->rc.rc_2_frame = 0;
1335   cpi->rc.rc_1_frame = 0;
1336 }
1337
1338 // Use this macro to turn on/off use of alt-refs in one-pass mode.
1339 #define USE_ALTREF_FOR_ONE_PASS   1
1340
1341 static int calc_pframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1342   static const int af_ratio = 10;
1343   const RATE_CONTROL *const rc = &cpi->rc;
1344   int target;
1345 #if USE_ALTREF_FOR_ONE_PASS
1346   target = (!rc->is_src_frame_alt_ref &&
1347             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) ?
1348       (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
1349       (rc->baseline_gf_interval + af_ratio - 1) :
1350       (rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
1351       (rc->baseline_gf_interval + af_ratio - 1);
1352 #else
1353   target = rc->avg_frame_bandwidth;
1354 #endif
1355   return vp9_rc_clamp_pframe_target_size(cpi, target);
1356 }
1357
1358 static int calc_iframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1359   static const int kf_ratio = 25;
1360   const RATE_CONTROL *rc = &cpi->rc;
1361   const int target = rc->avg_frame_bandwidth * kf_ratio;
1362   return vp9_rc_clamp_iframe_target_size(cpi, target);
1363 }
1364
1365 void vp9_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
1366   VP9_COMMON *const cm = &cpi->common;
1367   RATE_CONTROL *const rc = &cpi->rc;
1368   int target;
1369   // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1370   if (!cpi->refresh_alt_ref_frame &&
1371       (cm->current_video_frame == 0 ||
1372        (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1373        rc->frames_to_key == 0 ||
1374        (cpi->oxcf.auto_key && 0))) {
1375     cm->frame_type = KEY_FRAME;
1376     rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1377                                 rc->frames_to_key == 0;
1378     rc->frames_to_key = cpi->oxcf.key_freq;
1379     rc->kf_boost = DEFAULT_KF_BOOST;
1380     rc->source_alt_ref_active = 0;
1381   } else {
1382     cm->frame_type = INTER_FRAME;
1383   }
1384   if (rc->frames_till_gf_update_due == 0) {
1385     rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1386     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1387     // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1388     if (rc->frames_till_gf_update_due > rc->frames_to_key) {
1389       rc->frames_till_gf_update_due = rc->frames_to_key;
1390       rc->constrained_gf_group = 1;
1391     } else {
1392       rc->constrained_gf_group = 0;
1393     }
1394     cpi->refresh_golden_frame = 1;
1395     rc->source_alt_ref_pending = USE_ALTREF_FOR_ONE_PASS;
1396     rc->gfu_boost = DEFAULT_GF_BOOST;
1397   }
1398   if (cm->frame_type == KEY_FRAME)
1399     target = calc_iframe_target_size_one_pass_vbr(cpi);
1400   else
1401     target = calc_pframe_target_size_one_pass_vbr(cpi);
1402   vp9_rc_set_frame_target(cpi, target);
1403 }
1404
1405 static int calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1406   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1407   const RATE_CONTROL *rc = &cpi->rc;
1408   const SVC *const svc = &cpi->svc;
1409   const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
1410   const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
1411   int min_frame_target = MAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
1412   int target;
1413
1414   if (oxcf->gf_cbr_boost_pct) {
1415     const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
1416     target =  cpi->refresh_golden_frame ?
1417       (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio_pct) /
1418       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100) :
1419       (rc->avg_frame_bandwidth * rc->baseline_gf_interval * 100) /
1420       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
1421   } else {
1422     target = rc->avg_frame_bandwidth;
1423   }
1424   if (is_one_pass_cbr_svc(cpi)) {
1425     // Note that for layers, avg_frame_bandwidth is the cumulative
1426     // per-frame-bandwidth. For the target size of this frame, use the
1427     // layer average frame size (i.e., non-cumulative per-frame-bw).
1428     int layer =
1429         LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1430             svc->temporal_layer_id, svc->number_temporal_layers);
1431     const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1432     target = lc->avg_frame_size;
1433     min_frame_target = MAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
1434   }
1435   if (diff > 0) {
1436     // Lower the target bandwidth for this frame.
1437     const int pct_low = (int)MIN(diff / one_pct_bits, oxcf->under_shoot_pct);
1438     target -= (target * pct_low) / 200;
1439   } else if (diff < 0) {
1440     // Increase the target bandwidth for this frame.
1441     const int pct_high = (int)MIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
1442     target += (target * pct_high) / 200;
1443   }
1444   if (oxcf->rc_max_inter_bitrate_pct) {
1445     const int max_rate = rc->avg_frame_bandwidth *
1446                          oxcf->rc_max_inter_bitrate_pct / 100;
1447     target = MIN(target, max_rate);
1448   }
1449   return MAX(min_frame_target, target);
1450 }
1451
1452 static int calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1453   const RATE_CONTROL *rc = &cpi->rc;
1454   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1455   const SVC *const svc = &cpi->svc;
1456   int target;
1457   if (cpi->common.current_video_frame == 0) {
1458     target = ((rc->starting_buffer_level / 2) > INT_MAX)
1459       ? INT_MAX : (int)(rc->starting_buffer_level / 2);
1460   } else {
1461     int kf_boost = 32;
1462     double framerate = cpi->framerate;
1463     if (svc->number_temporal_layers > 1 &&
1464         oxcf->rc_mode == VPX_CBR) {
1465       // Use the layer framerate for temporal layers CBR mode.
1466       const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1467           svc->temporal_layer_id, svc->number_temporal_layers);
1468       const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1469       framerate = lc->framerate;
1470     }
1471     kf_boost = MAX(kf_boost, (int)(2 * framerate - 16));
1472     if (rc->frames_since_key <  framerate / 2) {
1473       kf_boost = (int)(kf_boost * rc->frames_since_key /
1474                        (framerate / 2));
1475     }
1476     target = ((16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
1477   }
1478   return vp9_rc_clamp_iframe_target_size(cpi, target);
1479 }
1480
1481 // Reset information needed to set proper reference frames and buffer updates
1482 // for temporal layering. This is called when a key frame is encoded.
1483 static void reset_temporal_layer_to_zero(VP9_COMP *cpi) {
1484   int sl;
1485   LAYER_CONTEXT *lc = NULL;
1486   cpi->svc.temporal_layer_id = 0;
1487
1488   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
1489     lc = &cpi->svc.layer_context[sl * cpi->svc.number_temporal_layers];
1490     lc->current_video_frame_in_layer = 0;
1491     lc->frames_from_key_frame = 0;
1492   }
1493 }
1494
1495 void vp9_rc_get_svc_params(VP9_COMP *cpi) {
1496   VP9_COMMON *const cm = &cpi->common;
1497   RATE_CONTROL *const rc = &cpi->rc;
1498   int target = rc->avg_frame_bandwidth;
1499   const int layer = LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id,
1500       cpi->svc.temporal_layer_id, cpi->svc.number_temporal_layers);
1501
1502   if ((cm->current_video_frame == 0) ||
1503       (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1504       (cpi->oxcf.auto_key && (rc->frames_since_key %
1505           cpi->oxcf.key_freq == 0))) {
1506     cm->frame_type = KEY_FRAME;
1507     rc->source_alt_ref_active = 0;
1508
1509     if (is_two_pass_svc(cpi)) {
1510       cpi->svc.layer_context[layer].is_key_frame = 1;
1511       cpi->ref_frame_flags &=
1512           (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1513     } else if (is_one_pass_cbr_svc(cpi)) {
1514       cpi->svc.layer_context[layer].is_key_frame = 1;
1515       reset_temporal_layer_to_zero(cpi);
1516       cpi->ref_frame_flags &=
1517                 (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1518       // Assumption here is that LAST_FRAME is being updated for a keyframe.
1519       // Thus no change in update flags.
1520       target = calc_iframe_target_size_one_pass_cbr(cpi);
1521     }
1522   } else {
1523     cm->frame_type = INTER_FRAME;
1524     if (is_two_pass_svc(cpi)) {
1525       LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1526       if (cpi->svc.spatial_layer_id == 0) {
1527         lc->is_key_frame = 0;
1528       } else {
1529         lc->is_key_frame =
1530             cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1531         if (lc->is_key_frame)
1532           cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
1533       }
1534       cpi->ref_frame_flags &= (~VP9_ALT_FLAG);
1535     } else if (is_one_pass_cbr_svc(cpi)) {
1536       LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1537       if (cpi->svc.spatial_layer_id == 0) {
1538         lc->is_key_frame = 0;
1539       } else {
1540         lc->is_key_frame =
1541             cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1542       }
1543       target = calc_pframe_target_size_one_pass_cbr(cpi);
1544     }
1545   }
1546
1547   // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1548   // should be done here, before the frame qp is selected.
1549   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1550     vp9_cyclic_refresh_update_parameters(cpi);
1551
1552   vp9_rc_set_frame_target(cpi, target);
1553   rc->frames_till_gf_update_due = INT_MAX;
1554   rc->baseline_gf_interval = INT_MAX;
1555 }
1556
1557 void vp9_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
1558   VP9_COMMON *const cm = &cpi->common;
1559   RATE_CONTROL *const rc = &cpi->rc;
1560   int target;
1561   // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1562   if ((cm->current_video_frame == 0 ||
1563       (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1564       rc->frames_to_key == 0 ||
1565       (cpi->oxcf.auto_key && 0))) {
1566     cm->frame_type = KEY_FRAME;
1567     rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1568                                 rc->frames_to_key == 0;
1569     rc->frames_to_key = cpi->oxcf.key_freq;
1570     rc->kf_boost = DEFAULT_KF_BOOST;
1571     rc->source_alt_ref_active = 0;
1572   } else {
1573     cm->frame_type = INTER_FRAME;
1574   }
1575   if (rc->frames_till_gf_update_due == 0) {
1576     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1577       vp9_cyclic_refresh_set_golden_update(cpi);
1578     else
1579       rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1580     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1581     // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1582     if (rc->frames_till_gf_update_due > rc->frames_to_key)
1583       rc->frames_till_gf_update_due = rc->frames_to_key;
1584     cpi->refresh_golden_frame = 1;
1585     rc->gfu_boost = DEFAULT_GF_BOOST;
1586   }
1587
1588   // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1589   // should be done here, before the frame qp is selected.
1590   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1591     vp9_cyclic_refresh_update_parameters(cpi);
1592
1593   if (cm->frame_type == KEY_FRAME)
1594     target = calc_iframe_target_size_one_pass_cbr(cpi);
1595   else
1596     target = calc_pframe_target_size_one_pass_cbr(cpi);
1597
1598   vp9_rc_set_frame_target(cpi, target);
1599 }
1600
1601 int vp9_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
1602                        vpx_bit_depth_t bit_depth) {
1603   int start_index = rc->worst_quality;
1604   int target_index = rc->worst_quality;
1605   int i;
1606
1607   // Convert the average q value to an index.
1608   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1609     start_index = i;
1610     if (vp9_convert_qindex_to_q(i, bit_depth) >= qstart)
1611       break;
1612   }
1613
1614   // Convert the q target to an index
1615   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1616     target_index = i;
1617     if (vp9_convert_qindex_to_q(i, bit_depth) >= qtarget)
1618       break;
1619   }
1620
1621   return target_index - start_index;
1622 }
1623
1624 int vp9_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
1625                                int qindex, double rate_target_ratio,
1626                                vpx_bit_depth_t bit_depth) {
1627   int target_index = rc->worst_quality;
1628   int i;
1629
1630   // Look up the current projected bits per block for the base index
1631   const int base_bits_per_mb = vp9_rc_bits_per_mb(frame_type, qindex, 1.0,
1632                                                   bit_depth);
1633
1634   // Find the target bits per mb based on the base value and given ratio.
1635   const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
1636
1637   // Convert the q target to an index
1638   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1639     if (vp9_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
1640         target_bits_per_mb) {
1641       target_index = i;
1642       break;
1643     }
1644   }
1645   return target_index - qindex;
1646 }
1647
1648 #define MIN_GF_INTERVAL     4
1649 #define MAX_GF_INTERVAL     16
1650 void vp9_rc_set_gf_interval_range(const VP9_COMP *const cpi,
1651                                   RATE_CONTROL *const rc) {
1652   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1653
1654   // Set a minimum interval.
1655   rc->min_gf_interval =
1656     MIN(MAX_GF_INTERVAL, MAX(MIN_GF_INTERVAL, (int)(cpi->framerate * 0.125)));
1657
1658   // Set Maximum gf/arf interval.
1659   rc->max_gf_interval =
1660     MIN(MAX_GF_INTERVAL, (int)(cpi->framerate * 0.75));
1661   // Round up to next even number if odd.
1662   rc->max_gf_interval += (rc->max_gf_interval & 0x01);
1663
1664   // Extended interval for genuinely static scenes
1665   rc->static_scene_max_gf_interval = MAX_LAG_BUFFERS * 2;
1666
1667   if (is_altref_enabled(cpi)) {
1668     if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
1669       rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
1670   }
1671
1672   if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
1673     rc->max_gf_interval = rc->static_scene_max_gf_interval;
1674
1675   // Clamp min to max
1676   rc->min_gf_interval = MIN(rc->min_gf_interval, rc->max_gf_interval);
1677 }
1678
1679 void vp9_rc_update_framerate(VP9_COMP *cpi) {
1680   const VP9_COMMON *const cm = &cpi->common;
1681   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1682   RATE_CONTROL *const rc = &cpi->rc;
1683   int vbr_max_bits;
1684
1685   rc->avg_frame_bandwidth = (int)(oxcf->target_bandwidth / cpi->framerate);
1686   rc->min_frame_bandwidth = (int)(rc->avg_frame_bandwidth *
1687                                 oxcf->two_pass_vbrmin_section / 100);
1688
1689   rc->min_frame_bandwidth = MAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1690
1691   // A maximum bitrate for a frame is defined.
1692   // The baseline for this aligns with HW implementations that
1693   // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
1694   // per 16x16 MB (averaged over a frame). However this limit is extended if
1695   // a very high rate is given on the command line or the the rate cannnot
1696   // be acheived because of a user specificed max q (e.g. when the user
1697   // specifies lossless encode.
1698   vbr_max_bits = (int)(((int64_t)rc->avg_frame_bandwidth *
1699                      oxcf->two_pass_vbrmax_section) / 100);
1700   rc->max_frame_bandwidth = MAX(MAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P),
1701                                     vbr_max_bits);
1702
1703   vp9_rc_set_gf_interval_range(cpi, rc);
1704 }
1705
1706 #define VBR_PCT_ADJUSTMENT_LIMIT 50
1707 // For VBR...adjustment to the frame target based on error from previous frames
1708 static void vbr_rate_correction(VP9_COMP *cpi, int *this_frame_target) {
1709   RATE_CONTROL *const rc = &cpi->rc;
1710   int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
1711   int max_delta;
1712   double position_factor = 1.0;
1713
1714   // How far through the clip are we.
1715   // This number is used to damp the per frame rate correction.
1716   // Range 0 - 1.0
1717   if (cpi->twopass.total_stats.count) {
1718     position_factor = sqrt((double)cpi->common.current_video_frame /
1719                            cpi->twopass.total_stats.count);
1720   }
1721   max_delta = (int)(position_factor *
1722                     ((*this_frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
1723
1724   // vbr_bits_off_target > 0 means we have extra bits to spend
1725   if (vbr_bits_off_target > 0) {
1726     *this_frame_target +=
1727       (vbr_bits_off_target > max_delta) ? max_delta
1728                                         : (int)vbr_bits_off_target;
1729   } else {
1730     *this_frame_target -=
1731       (vbr_bits_off_target < -max_delta) ? max_delta
1732                                          : (int)-vbr_bits_off_target;
1733   }
1734
1735   // Fast redistribution of bits arising from massive local undershoot.
1736   // Dont do it for kf,arf,gf or overlay frames.
1737   if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
1738       rc->vbr_bits_off_target_fast) {
1739     int one_frame_bits = MAX(rc->avg_frame_bandwidth, *this_frame_target);
1740     int fast_extra_bits;
1741     fast_extra_bits =
1742       (int)MIN(rc->vbr_bits_off_target_fast, one_frame_bits);
1743     fast_extra_bits = (int)MIN(fast_extra_bits,
1744       MAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
1745     *this_frame_target += (int)fast_extra_bits;
1746     rc->vbr_bits_off_target_fast -= fast_extra_bits;
1747   }
1748 }
1749
1750 void vp9_set_target_rate(VP9_COMP *cpi) {
1751   RATE_CONTROL *const rc = &cpi->rc;
1752   int target_rate = rc->base_frame_target;
1753
1754   // Correction to rate target based on prior over or under shoot.
1755   if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
1756     vbr_rate_correction(cpi, &target_rate);
1757   vp9_rc_set_frame_target(cpi, target_rate);
1758 }