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