Merge "Fix high bit depth in vp10 codebase"
[platform/upstream/libvpx.git] / vp10 / encoder / 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 "vp10/common/alloccommon.h"
22 #include "vp10/encoder/aq_cyclicrefresh.h"
23 #include "vp10/common/common.h"
24 #include "vp10/common/entropymode.h"
25 #include "vp10/common/quant_common.h"
26 #include "vp10/common/seg_common.h"
27 #include "vp10/common/systemdependent.h"
28
29 #include "vp10/encoder/encodemv.h"
30 #include "vp10/encoder/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 <= vp10_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 = vp10_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 vp10_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 vp10_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 vp10_ac_quant(qindex, 0, bit_depth) / 4.0;
163     case VPX_BITS_10:
164       return vp10_ac_quant(qindex, 0, bit_depth) / 16.0;
165     case VPX_BITS_12:
166       return vp10_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 vp10_ac_quant(qindex, 0, bit_depth) / 4.0;
173 #endif
174 }
175
176 int vp10_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 = vp10_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 vp10_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)(vp10_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 vp10_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 vp10_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 int vp10_rc_get_default_min_gf_interval(
280     int width, int height, double framerate) {
281   // Assume we do not need any constraint lower than 4K 20 fps
282   static const double factor_safe = 3840 * 2160 * 20.0;
283   const double factor = width * height * framerate;
284   const int default_interval =
285       clamp((int)(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
286
287   if (factor <= factor_safe)
288     return default_interval;
289   else
290     return MAX(default_interval,
291                (int)(MIN_GF_INTERVAL * factor / factor_safe + 0.5));
292   // Note this logic makes:
293   // 4K24: 5
294   // 4K30: 6
295   // 4K60: 12
296 }
297
298 int vp10_rc_get_default_max_gf_interval(double framerate, int min_gf_interval) {
299   int interval = MIN(MAX_GF_INTERVAL, (int)(framerate * 0.75));
300   interval += (interval & 0x01);  // Round to even value
301   return MAX(interval, min_gf_interval);
302 }
303
304 void vp10_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
305   int i;
306
307   if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
308     rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
309     rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
310   } else {
311     rc->avg_frame_qindex[KEY_FRAME] = (oxcf->worst_allowed_q +
312                                        oxcf->best_allowed_q) / 2;
313     rc->avg_frame_qindex[INTER_FRAME] = (oxcf->worst_allowed_q +
314                                          oxcf->best_allowed_q) / 2;
315   }
316
317   rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
318   rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
319
320   rc->buffer_level =    rc->starting_buffer_level;
321   rc->bits_off_target = rc->starting_buffer_level;
322
323   rc->rolling_target_bits      = rc->avg_frame_bandwidth;
324   rc->rolling_actual_bits      = rc->avg_frame_bandwidth;
325   rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
326   rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
327
328   rc->total_actual_bits = 0;
329   rc->total_target_bits = 0;
330   rc->total_target_vs_actual = 0;
331
332   rc->frames_since_key = 8;  // Sensible default for first frame.
333   rc->this_key_frame_forced = 0;
334   rc->next_key_frame_forced = 0;
335   rc->source_alt_ref_pending = 0;
336   rc->source_alt_ref_active = 0;
337
338   rc->frames_till_gf_update_due = 0;
339   rc->ni_av_qi = oxcf->worst_allowed_q;
340   rc->ni_tot_qi = 0;
341   rc->ni_frames = 0;
342
343   rc->tot_q = 0.0;
344   rc->avg_q = vp10_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
345
346   for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
347     rc->rate_correction_factors[i] = 1.0;
348   }
349
350   rc->min_gf_interval = oxcf->min_gf_interval;
351   rc->max_gf_interval = oxcf->max_gf_interval;
352   if (rc->min_gf_interval == 0)
353     rc->min_gf_interval = vp10_rc_get_default_min_gf_interval(
354         oxcf->width, oxcf->height, oxcf->init_framerate);
355   if (rc->max_gf_interval == 0)
356     rc->max_gf_interval = vp10_rc_get_default_max_gf_interval(
357         oxcf->init_framerate, rc->min_gf_interval);
358   rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
359 }
360
361 int vp10_rc_drop_frame(VP9_COMP *cpi) {
362   const VP9EncoderConfig *oxcf = &cpi->oxcf;
363   RATE_CONTROL *const rc = &cpi->rc;
364
365   if (!oxcf->drop_frames_water_mark) {
366     return 0;
367   } else {
368     if (rc->buffer_level < 0) {
369       // Always drop if buffer is below 0.
370       return 1;
371     } else {
372       // If buffer is below drop_mark, for now just drop every other frame
373       // (starting with the next frame) until it increases back over drop_mark.
374       int drop_mark = (int)(oxcf->drop_frames_water_mark *
375           rc->optimal_buffer_level / 100);
376       if ((rc->buffer_level > drop_mark) &&
377           (rc->decimation_factor > 0)) {
378         --rc->decimation_factor;
379       } else if (rc->buffer_level <= drop_mark &&
380           rc->decimation_factor == 0) {
381         rc->decimation_factor = 1;
382       }
383       if (rc->decimation_factor > 0) {
384         if (rc->decimation_count > 0) {
385           --rc->decimation_count;
386           return 1;
387         } else {
388           rc->decimation_count = rc->decimation_factor;
389           return 0;
390         }
391       } else {
392         rc->decimation_count = 0;
393         return 0;
394       }
395     }
396   }
397 }
398
399 static double get_rate_correction_factor(const VP9_COMP *cpi) {
400   const RATE_CONTROL *const rc = &cpi->rc;
401   double rcf;
402
403   if (cpi->common.frame_type == KEY_FRAME) {
404     rcf = rc->rate_correction_factors[KF_STD];
405   } else if (cpi->oxcf.pass == 2) {
406     RATE_FACTOR_LEVEL rf_lvl =
407       cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
408     rcf = rc->rate_correction_factors[rf_lvl];
409   } else {
410     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
411         !rc->is_src_frame_alt_ref && !cpi->use_svc &&
412         (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
413       rcf = rc->rate_correction_factors[GF_ARF_STD];
414     else
415       rcf = rc->rate_correction_factors[INTER_NORMAL];
416   }
417   rcf *= rcf_mult[rc->frame_size_selector];
418   return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
419 }
420
421 static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
422   RATE_CONTROL *const rc = &cpi->rc;
423
424   // Normalize RCF to account for the size-dependent scaling factor.
425   factor /= rcf_mult[cpi->rc.frame_size_selector];
426
427   factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
428
429   if (cpi->common.frame_type == KEY_FRAME) {
430     rc->rate_correction_factors[KF_STD] = factor;
431   } else if (cpi->oxcf.pass == 2) {
432     RATE_FACTOR_LEVEL rf_lvl =
433       cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
434     rc->rate_correction_factors[rf_lvl] = factor;
435   } else {
436     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
437         !rc->is_src_frame_alt_ref && !cpi->use_svc &&
438         (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
439       rc->rate_correction_factors[GF_ARF_STD] = factor;
440     else
441       rc->rate_correction_factors[INTER_NORMAL] = factor;
442   }
443 }
444
445 void vp10_rc_update_rate_correction_factors(VP9_COMP *cpi) {
446   const VP9_COMMON *const cm = &cpi->common;
447   int correction_factor = 100;
448   double rate_correction_factor = get_rate_correction_factor(cpi);
449   double adjustment_limit;
450
451   int projected_size_based_on_q = 0;
452
453   // Do not update the rate factors for arf overlay frames.
454   if (cpi->rc.is_src_frame_alt_ref)
455     return;
456
457   // Clear down mmx registers to allow floating point in what follows
458   vpx_clear_system_state();
459
460   // Work out how big we would have expected the frame to be at this Q given
461   // the current correction factor.
462   // Stay in double to avoid int overflow when values are large
463   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled) {
464     projected_size_based_on_q =
465         vp10_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
466   } else {
467     projected_size_based_on_q = vp10_estimate_bits_at_q(cpi->common.frame_type,
468                                                        cm->base_qindex,
469                                                        cm->MBs,
470                                                        rate_correction_factor,
471                                                        cm->bit_depth);
472   }
473   // Work out a size correction factor.
474   if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
475     correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
476                         projected_size_based_on_q);
477
478   // More heavily damped adjustment used if we have been oscillating either side
479   // of target.
480   adjustment_limit = 0.25 +
481       0.5 * MIN(1, fabs(log10(0.01 * correction_factor)));
482
483   cpi->rc.q_2_frame = cpi->rc.q_1_frame;
484   cpi->rc.q_1_frame = cm->base_qindex;
485   cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
486   if (correction_factor > 110)
487     cpi->rc.rc_1_frame = -1;
488   else if (correction_factor < 90)
489     cpi->rc.rc_1_frame = 1;
490   else
491     cpi->rc.rc_1_frame = 0;
492
493   if (correction_factor > 102) {
494     // We are not already at the worst allowable quality
495     correction_factor = (int)(100 + ((correction_factor - 100) *
496                                   adjustment_limit));
497     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
498     // Keep rate_correction_factor within limits
499     if (rate_correction_factor > MAX_BPB_FACTOR)
500       rate_correction_factor = MAX_BPB_FACTOR;
501   } else if (correction_factor < 99) {
502     // We are not already at the best allowable quality
503     correction_factor = (int)(100 - ((100 - correction_factor) *
504                                   adjustment_limit));
505     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
506
507     // Keep rate_correction_factor within limits
508     if (rate_correction_factor < MIN_BPB_FACTOR)
509       rate_correction_factor = MIN_BPB_FACTOR;
510   }
511
512   set_rate_correction_factor(cpi, rate_correction_factor);
513 }
514
515
516 int vp10_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
517                       int active_best_quality, int active_worst_quality) {
518   const VP9_COMMON *const cm = &cpi->common;
519   int q = active_worst_quality;
520   int last_error = INT_MAX;
521   int i, target_bits_per_mb, bits_per_mb_at_this_q;
522   const double correction_factor = get_rate_correction_factor(cpi);
523
524   // Calculate required scaling factor based on target frame size and size of
525   // frame produced using previous Q.
526   target_bits_per_mb =
527       ((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs;
528
529   i = active_best_quality;
530
531   do {
532     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
533         cm->seg.enabled &&
534         cpi->svc.temporal_layer_id == 0 &&
535         cpi->svc.spatial_layer_id == 0) {
536       bits_per_mb_at_this_q =
537           (int)vp10_cyclic_refresh_rc_bits_per_mb(cpi, i, correction_factor);
538     } else {
539       bits_per_mb_at_this_q = (int)vp10_rc_bits_per_mb(cm->frame_type, i,
540                                                       correction_factor,
541                                                       cm->bit_depth);
542     }
543
544     if (bits_per_mb_at_this_q <= target_bits_per_mb) {
545       if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
546         q = i;
547       else
548         q = i - 1;
549
550       break;
551     } else {
552       last_error = bits_per_mb_at_this_q - target_bits_per_mb;
553     }
554   } while (++i <= active_worst_quality);
555
556   // In CBR mode, this makes sure q is between oscillating Qs to prevent
557   // resonance.
558   if (cpi->oxcf.rc_mode == VPX_CBR &&
559       (cpi->rc.rc_1_frame * cpi->rc.rc_2_frame == -1) &&
560       cpi->rc.q_1_frame != cpi->rc.q_2_frame) {
561     q = clamp(q, MIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
562               MAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
563   }
564   return q;
565 }
566
567 static int get_active_quality(int q, int gfu_boost, int low, int high,
568                               int *low_motion_minq, int *high_motion_minq) {
569   if (gfu_boost > high) {
570     return low_motion_minq[q];
571   } else if (gfu_boost < low) {
572     return high_motion_minq[q];
573   } else {
574     const int gap = high - low;
575     const int offset = high - gfu_boost;
576     const int qdiff = high_motion_minq[q] - low_motion_minq[q];
577     const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
578     return low_motion_minq[q] + adjustment;
579   }
580 }
581
582 static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
583                                  vpx_bit_depth_t bit_depth) {
584   int *kf_low_motion_minq;
585   int *kf_high_motion_minq;
586   ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
587   ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
588   return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
589                             kf_low_motion_minq, kf_high_motion_minq);
590 }
591
592 static int get_gf_active_quality(const RATE_CONTROL *const rc, int q,
593                                  vpx_bit_depth_t bit_depth) {
594   int *arfgf_low_motion_minq;
595   int *arfgf_high_motion_minq;
596   ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
597   ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
598   return get_active_quality(q, rc->gfu_boost, gf_low, gf_high,
599                             arfgf_low_motion_minq, arfgf_high_motion_minq);
600 }
601
602 static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
603   const RATE_CONTROL *const rc = &cpi->rc;
604   const unsigned int curr_frame = cpi->common.current_video_frame;
605   int active_worst_quality;
606
607   if (cpi->common.frame_type == KEY_FRAME) {
608     active_worst_quality = curr_frame == 0 ? rc->worst_quality
609                                            : rc->last_q[KEY_FRAME] * 2;
610   } else {
611     if (!rc->is_src_frame_alt_ref &&
612         (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
613       active_worst_quality =  curr_frame == 1 ? rc->last_q[KEY_FRAME] * 5 / 4
614                                               : rc->last_q[INTER_FRAME];
615     } else {
616       active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 2
617                                              : rc->last_q[INTER_FRAME] * 2;
618     }
619   }
620   return MIN(active_worst_quality, rc->worst_quality);
621 }
622
623 // Adjust active_worst_quality level based on buffer level.
624 static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
625   // Adjust active_worst_quality: If buffer is above the optimal/target level,
626   // bring active_worst_quality down depending on fullness of buffer.
627   // If buffer is below the optimal level, let the active_worst_quality go from
628   // ambient Q (at buffer = optimal level) to worst_quality level
629   // (at buffer = critical level).
630   const VP9_COMMON *const cm = &cpi->common;
631   const RATE_CONTROL *rc = &cpi->rc;
632   // Buffer level below which we push active_worst to worst_quality.
633   int64_t critical_level = rc->optimal_buffer_level >> 3;
634   int64_t buff_lvl_step = 0;
635   int adjustment = 0;
636   int active_worst_quality;
637   int ambient_qp;
638   if (cm->frame_type == KEY_FRAME)
639     return rc->worst_quality;
640   // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
641   // for the first few frames following key frame. These are both initialized
642   // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
643   // So for first few frames following key, the qp of that key frame is weighted
644   // into the active_worst_quality setting.
645   ambient_qp = (cm->current_video_frame < 5) ?
646       MIN(rc->avg_frame_qindex[INTER_FRAME], rc->avg_frame_qindex[KEY_FRAME]) :
647       rc->avg_frame_qindex[INTER_FRAME];
648   active_worst_quality = MIN(rc->worst_quality,
649                              ambient_qp * 5 / 4);
650   if (rc->buffer_level > rc->optimal_buffer_level) {
651     // Adjust down.
652     // Maximum limit for down adjustment, ~30%.
653     int max_adjustment_down = active_worst_quality / 3;
654     if (max_adjustment_down) {
655       buff_lvl_step = ((rc->maximum_buffer_size -
656                         rc->optimal_buffer_level) / max_adjustment_down);
657       if (buff_lvl_step)
658         adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
659                             buff_lvl_step);
660       active_worst_quality -= adjustment;
661     }
662   } else if (rc->buffer_level > critical_level) {
663     // Adjust up from ambient Q.
664     if (critical_level) {
665       buff_lvl_step = (rc->optimal_buffer_level - critical_level);
666       if (buff_lvl_step) {
667         adjustment = (int)((rc->worst_quality - ambient_qp) *
668                            (rc->optimal_buffer_level - rc->buffer_level) /
669                            buff_lvl_step);
670       }
671       active_worst_quality = ambient_qp + adjustment;
672     }
673   } else {
674     // Set to worst_quality if buffer is below critical level.
675     active_worst_quality = rc->worst_quality;
676   }
677   return active_worst_quality;
678 }
679
680 static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
681                                              int *bottom_index,
682                                              int *top_index) {
683   const VP9_COMMON *const cm = &cpi->common;
684   const RATE_CONTROL *const rc = &cpi->rc;
685   int active_best_quality;
686   int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
687   int q;
688   int *rtc_minq;
689   ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
690
691   if (frame_is_intra_only(cm)) {
692     active_best_quality = rc->best_quality;
693     // Handle the special case for key frames forced when we have reached
694     // the maximum key frame interval. Here force the Q to a range
695     // based on the ambient Q to reduce the risk of popping.
696     if (rc->this_key_frame_forced) {
697       int qindex = rc->last_boosted_qindex;
698       double last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
699       int delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
700                                             (last_boosted_q * 0.75),
701                                             cm->bit_depth);
702       active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
703     } else if (cm->current_video_frame > 0) {
704       // not first frame of one pass and kf_boost is set
705       double q_adj_factor = 1.0;
706       double q_val;
707
708       active_best_quality =
709           get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
710                                 cm->bit_depth);
711
712       // Allow somewhat lower kf minq with small image formats.
713       if ((cm->width * cm->height) <= (352 * 288)) {
714         q_adj_factor -= 0.25;
715       }
716
717       // Convert the adjustment factor to a qindex delta
718       // on active_best_quality.
719       q_val = vp10_convert_qindex_to_q(active_best_quality, cm->bit_depth);
720       active_best_quality += vp10_compute_qdelta(rc, q_val,
721                                                 q_val * q_adj_factor,
722                                                 cm->bit_depth);
723     }
724   } else if (!rc->is_src_frame_alt_ref &&
725              !cpi->use_svc &&
726              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
727     // Use the lower of active_worst_quality and recent
728     // average Q as basis for GF/ARF best Q limit unless last frame was
729     // a key frame.
730     if (rc->frames_since_key > 1 &&
731         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
732       q = rc->avg_frame_qindex[INTER_FRAME];
733     } else {
734       q = active_worst_quality;
735     }
736     active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
737   } else {
738     // Use the lower of active_worst_quality and recent/average Q.
739     if (cm->current_video_frame > 1) {
740       if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
741         active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
742       else
743         active_best_quality = rtc_minq[active_worst_quality];
744     } else {
745       if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
746         active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
747       else
748         active_best_quality = rtc_minq[active_worst_quality];
749     }
750   }
751
752   // Clip the active best and worst quality values to limits
753   active_best_quality = clamp(active_best_quality,
754                               rc->best_quality, rc->worst_quality);
755   active_worst_quality = clamp(active_worst_quality,
756                                active_best_quality, rc->worst_quality);
757
758   *top_index = active_worst_quality;
759   *bottom_index = active_best_quality;
760
761 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
762   // Limit Q range for the adaptive loop.
763   if (cm->frame_type == KEY_FRAME &&
764       !rc->this_key_frame_forced  &&
765       !(cm->current_video_frame == 0)) {
766     int qdelta = 0;
767     vpx_clear_system_state();
768     qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
769                                         active_worst_quality, 2.0,
770                                         cm->bit_depth);
771     *top_index = active_worst_quality + qdelta;
772     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
773   }
774 #endif
775
776   // Special case code to try and match quality with forced key frames
777   if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
778     q = rc->last_boosted_qindex;
779   } else {
780     q = vp10_rc_regulate_q(cpi, rc->this_frame_target,
781                           active_best_quality, active_worst_quality);
782     if (q > *top_index) {
783       // Special case when we are targeting the max allowed rate
784       if (rc->this_frame_target >= rc->max_frame_bandwidth)
785         *top_index = q;
786       else
787         q = *top_index;
788     }
789   }
790   assert(*top_index <= rc->worst_quality &&
791          *top_index >= rc->best_quality);
792   assert(*bottom_index <= rc->worst_quality &&
793          *bottom_index >= rc->best_quality);
794   assert(q <= rc->worst_quality && q >= rc->best_quality);
795   return q;
796 }
797
798 static int get_active_cq_level(const RATE_CONTROL *rc,
799                                const VP9EncoderConfig *const oxcf) {
800   static const double cq_adjust_threshold = 0.1;
801   int active_cq_level = oxcf->cq_level;
802   if (oxcf->rc_mode == VPX_CQ &&
803       rc->total_target_bits > 0) {
804     const double x = (double)rc->total_actual_bits / rc->total_target_bits;
805     if (x < cq_adjust_threshold) {
806       active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
807     }
808   }
809   return active_cq_level;
810 }
811
812 static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
813                                              int *bottom_index,
814                                              int *top_index) {
815   const VP9_COMMON *const cm = &cpi->common;
816   const RATE_CONTROL *const rc = &cpi->rc;
817   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
818   const int cq_level = get_active_cq_level(rc, oxcf);
819   int active_best_quality;
820   int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
821   int q;
822   int *inter_minq;
823   ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
824
825   if (frame_is_intra_only(cm)) {
826
827     // Handle the special case for key frames forced when we have reached
828     // the maximum key frame interval. Here force the Q to a range
829     // based on the ambient Q to reduce the risk of popping.
830     if (rc->this_key_frame_forced) {
831       int qindex = rc->last_boosted_qindex;
832       double last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
833       int delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
834                                             last_boosted_q * 0.75,
835                                             cm->bit_depth);
836       active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
837     } else {
838       // not first frame of one pass and kf_boost is set
839       double q_adj_factor = 1.0;
840       double q_val;
841
842       active_best_quality =
843           get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
844                                 cm->bit_depth);
845
846       // Allow somewhat lower kf minq with small image formats.
847       if ((cm->width * cm->height) <= (352 * 288)) {
848         q_adj_factor -= 0.25;
849       }
850
851       // Convert the adjustment factor to a qindex delta
852       // on active_best_quality.
853       q_val = vp10_convert_qindex_to_q(active_best_quality, cm->bit_depth);
854       active_best_quality += vp10_compute_qdelta(rc, q_val,
855                                                 q_val * q_adj_factor,
856                                                 cm->bit_depth);
857     }
858   } else if (!rc->is_src_frame_alt_ref &&
859              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
860     // Use the lower of active_worst_quality and recent
861     // average Q as basis for GF/ARF best Q limit unless last frame was
862     // a key frame.
863     if (rc->frames_since_key > 1 &&
864         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
865       q = rc->avg_frame_qindex[INTER_FRAME];
866     } else {
867       q = rc->avg_frame_qindex[KEY_FRAME];
868     }
869     // For constrained quality dont allow Q less than the cq level
870     if (oxcf->rc_mode == VPX_CQ) {
871       if (q < cq_level)
872         q = cq_level;
873
874       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
875
876       // Constrained quality use slightly lower active best.
877       active_best_quality = active_best_quality * 15 / 16;
878
879     } else if (oxcf->rc_mode == VPX_Q) {
880       if (!cpi->refresh_alt_ref_frame) {
881         active_best_quality = cq_level;
882       } else {
883         active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
884       }
885     } else {
886       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
887     }
888   } else {
889     if (oxcf->rc_mode == VPX_Q) {
890       active_best_quality = cq_level;
891     } else {
892       // Use the lower of active_worst_quality and recent/average Q.
893       if (cm->current_video_frame > 1)
894         active_best_quality = inter_minq[rc->avg_frame_qindex[INTER_FRAME]];
895       else
896         active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
897       // For the constrained quality mode we don't want
898       // q to fall below the cq level.
899       if ((oxcf->rc_mode == VPX_CQ) &&
900           (active_best_quality < cq_level)) {
901         active_best_quality = cq_level;
902       }
903     }
904   }
905
906   // Clip the active best and worst quality values to limits
907   active_best_quality = clamp(active_best_quality,
908                               rc->best_quality, rc->worst_quality);
909   active_worst_quality = clamp(active_worst_quality,
910                                active_best_quality, rc->worst_quality);
911
912   *top_index = active_worst_quality;
913   *bottom_index = active_best_quality;
914
915 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
916   {
917     int qdelta = 0;
918     vpx_clear_system_state();
919
920     // Limit Q range for the adaptive loop.
921     if (cm->frame_type == KEY_FRAME &&
922         !rc->this_key_frame_forced &&
923         !(cm->current_video_frame == 0)) {
924       qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
925                                           active_worst_quality, 2.0,
926                                           cm->bit_depth);
927     } else if (!rc->is_src_frame_alt_ref &&
928                (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
929       qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
930                                           active_worst_quality, 1.75,
931                                           cm->bit_depth);
932     }
933     *top_index = active_worst_quality + qdelta;
934     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
935   }
936 #endif
937
938   if (oxcf->rc_mode == VPX_Q) {
939     q = active_best_quality;
940   // Special case code to try and match quality with forced key frames
941   } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
942     q = rc->last_boosted_qindex;
943   } else {
944     q = vp10_rc_regulate_q(cpi, rc->this_frame_target,
945                           active_best_quality, active_worst_quality);
946     if (q > *top_index) {
947       // Special case when we are targeting the max allowed rate
948       if (rc->this_frame_target >= rc->max_frame_bandwidth)
949         *top_index = q;
950       else
951         q = *top_index;
952     }
953   }
954
955   assert(*top_index <= rc->worst_quality &&
956          *top_index >= rc->best_quality);
957   assert(*bottom_index <= rc->worst_quality &&
958          *bottom_index >= rc->best_quality);
959   assert(q <= rc->worst_quality && q >= rc->best_quality);
960   return q;
961 }
962
963 int vp10_frame_type_qdelta(const VP9_COMP *cpi, int rf_level, int q) {
964   static const double rate_factor_deltas[RATE_FACTOR_LEVELS] = {
965     1.00,  // INTER_NORMAL
966     1.00,  // INTER_HIGH
967     1.50,  // GF_ARF_LOW
968     1.75,  // GF_ARF_STD
969     2.00,  // KF_STD
970   };
971   static const FRAME_TYPE frame_type[RATE_FACTOR_LEVELS] =
972       {INTER_FRAME, INTER_FRAME, INTER_FRAME, INTER_FRAME, KEY_FRAME};
973   const VP9_COMMON *const cm = &cpi->common;
974   int qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, frame_type[rf_level],
975                                           q, rate_factor_deltas[rf_level],
976                                           cm->bit_depth);
977   return qdelta;
978 }
979
980 #define STATIC_MOTION_THRESH 95
981 static int rc_pick_q_and_bounds_two_pass(const VP9_COMP *cpi,
982                                          int *bottom_index,
983                                          int *top_index) {
984   const VP9_COMMON *const cm = &cpi->common;
985   const RATE_CONTROL *const rc = &cpi->rc;
986   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
987   const GF_GROUP *gf_group = &cpi->twopass.gf_group;
988   const int cq_level = get_active_cq_level(rc, oxcf);
989   int active_best_quality;
990   int active_worst_quality = cpi->twopass.active_worst_quality;
991   int q;
992   int *inter_minq;
993   ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
994
995   if (frame_is_intra_only(cm) || vp10_is_upper_layer_key_frame(cpi)) {
996     // Handle the special case for key frames forced when we have reached
997     // the maximum key frame interval. Here force the Q to a range
998     // based on the ambient Q to reduce the risk of popping.
999     if (rc->this_key_frame_forced) {
1000       double last_boosted_q;
1001       int delta_qindex;
1002       int qindex;
1003
1004       if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1005         qindex = MIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1006         active_best_quality = qindex;
1007         last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
1008         delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
1009                                               last_boosted_q * 1.25,
1010                                               cm->bit_depth);
1011         active_worst_quality = MIN(qindex + delta_qindex, active_worst_quality);
1012
1013       } else {
1014         qindex = rc->last_boosted_qindex;
1015         last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
1016         delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
1017                                               last_boosted_q * 0.75,
1018                                               cm->bit_depth);
1019         active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
1020       }
1021     } else {
1022       // Not forced keyframe.
1023       double q_adj_factor = 1.0;
1024       double q_val;
1025       // Baseline value derived from cpi->active_worst_quality and kf boost.
1026       active_best_quality = get_kf_active_quality(rc, active_worst_quality,
1027                                                   cm->bit_depth);
1028
1029       // Allow somewhat lower kf minq with small image formats.
1030       if ((cm->width * cm->height) <= (352 * 288)) {
1031         q_adj_factor -= 0.25;
1032       }
1033
1034       // Make a further adjustment based on the kf zero motion measure.
1035       q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
1036
1037       // Convert the adjustment factor to a qindex delta
1038       // on active_best_quality.
1039       q_val = vp10_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1040       active_best_quality += vp10_compute_qdelta(rc, q_val,
1041                                                 q_val * q_adj_factor,
1042                                                 cm->bit_depth);
1043     }
1044   } else if (!rc->is_src_frame_alt_ref &&
1045              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1046     // Use the lower of active_worst_quality and recent
1047     // average Q as basis for GF/ARF best Q limit unless last frame was
1048     // a key frame.
1049     if (rc->frames_since_key > 1 &&
1050         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1051       q = rc->avg_frame_qindex[INTER_FRAME];
1052     } else {
1053       q = active_worst_quality;
1054     }
1055     // For constrained quality dont allow Q less than the cq level
1056     if (oxcf->rc_mode == VPX_CQ) {
1057       if (q < cq_level)
1058         q = cq_level;
1059
1060       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1061
1062       // Constrained quality use slightly lower active best.
1063       active_best_quality = active_best_quality * 15 / 16;
1064
1065     } else if (oxcf->rc_mode == VPX_Q) {
1066       if (!cpi->refresh_alt_ref_frame) {
1067         active_best_quality = cq_level;
1068       } else {
1069        active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1070
1071         // Modify best quality for second level arfs. For mode VPX_Q this
1072         // becomes the baseline frame q.
1073         if (gf_group->rf_level[gf_group->index] == GF_ARF_LOW)
1074           active_best_quality = (active_best_quality + cq_level + 1) / 2;
1075       }
1076     } else {
1077       active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1078     }
1079   } else {
1080     if (oxcf->rc_mode == VPX_Q) {
1081       active_best_quality = cq_level;
1082     } else {
1083       active_best_quality = inter_minq[active_worst_quality];
1084
1085       // For the constrained quality mode we don't want
1086       // q to fall below the cq level.
1087       if ((oxcf->rc_mode == VPX_CQ) &&
1088           (active_best_quality < cq_level)) {
1089         active_best_quality = cq_level;
1090       }
1091     }
1092   }
1093
1094   // Extension to max or min Q if undershoot or overshoot is outside
1095   // the permitted range.
1096   if ((cpi->oxcf.rc_mode != VPX_Q) &&
1097       (cpi->twopass.gf_zeromotion_pct < VLOW_MOTION_THRESHOLD)) {
1098     if (frame_is_intra_only(cm) ||
1099         (!rc->is_src_frame_alt_ref &&
1100          (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1101       active_best_quality -=
1102         (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast);
1103       active_worst_quality += (cpi->twopass.extend_maxq / 2);
1104     } else {
1105       active_best_quality -=
1106         (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast) / 2;
1107       active_worst_quality += cpi->twopass.extend_maxq;
1108     }
1109   }
1110
1111 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
1112   vpx_clear_system_state();
1113   // Static forced key frames Q restrictions dealt with elsewhere.
1114   if (!((frame_is_intra_only(cm) || vp10_is_upper_layer_key_frame(cpi))) ||
1115       !rc->this_key_frame_forced ||
1116       (cpi->twopass.last_kfgroup_zeromotion_pct < STATIC_MOTION_THRESH)) {
1117     int qdelta = vp10_frame_type_qdelta(cpi, gf_group->rf_level[gf_group->index],
1118                                        active_worst_quality);
1119     active_worst_quality = MAX(active_worst_quality + qdelta,
1120                                active_best_quality);
1121   }
1122 #endif
1123
1124   // Modify active_best_quality for downscaled normal frames.
1125   if (rc->frame_size_selector != UNSCALED && !frame_is_kf_gf_arf(cpi)) {
1126     int qdelta = vp10_compute_qdelta_by_rate(rc, cm->frame_type,
1127                                             active_best_quality, 2.0,
1128                                             cm->bit_depth);
1129     active_best_quality = MAX(active_best_quality + qdelta, rc->best_quality);
1130   }
1131
1132   active_best_quality = clamp(active_best_quality,
1133                               rc->best_quality, rc->worst_quality);
1134   active_worst_quality = clamp(active_worst_quality,
1135                                active_best_quality, rc->worst_quality);
1136
1137   if (oxcf->rc_mode == VPX_Q) {
1138     q = active_best_quality;
1139   // Special case code to try and match quality with forced key frames.
1140   } else if ((frame_is_intra_only(cm) || vp10_is_upper_layer_key_frame(cpi)) &&
1141              rc->this_key_frame_forced) {
1142     // If static since last kf use better of last boosted and last kf q.
1143     if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1144       q = MIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1145     } else {
1146       q = rc->last_boosted_qindex;
1147     }
1148   } else {
1149     q = vp10_rc_regulate_q(cpi, rc->this_frame_target,
1150                           active_best_quality, active_worst_quality);
1151     if (q > active_worst_quality) {
1152       // Special case when we are targeting the max allowed rate.
1153       if (rc->this_frame_target >= rc->max_frame_bandwidth)
1154         active_worst_quality = q;
1155       else
1156         q = active_worst_quality;
1157     }
1158   }
1159   clamp(q, active_best_quality, active_worst_quality);
1160
1161   *top_index = active_worst_quality;
1162   *bottom_index = active_best_quality;
1163
1164   assert(*top_index <= rc->worst_quality &&
1165          *top_index >= rc->best_quality);
1166   assert(*bottom_index <= rc->worst_quality &&
1167          *bottom_index >= rc->best_quality);
1168   assert(q <= rc->worst_quality && q >= rc->best_quality);
1169   return q;
1170 }
1171
1172 int vp10_rc_pick_q_and_bounds(const VP9_COMP *cpi,
1173                              int *bottom_index, int *top_index) {
1174   int q;
1175   if (cpi->oxcf.pass == 0) {
1176     if (cpi->oxcf.rc_mode == VPX_CBR)
1177       q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
1178     else
1179       q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
1180   } else {
1181     q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
1182   }
1183   if (cpi->sf.use_nonrd_pick_mode) {
1184     if (cpi->sf.force_frame_boost == 1)
1185       q -= cpi->sf.max_delta_qindex;
1186
1187     if (q < *bottom_index)
1188       *bottom_index = q;
1189     else if (q > *top_index)
1190       *top_index = q;
1191   }
1192   return q;
1193 }
1194
1195 void vp10_rc_compute_frame_size_bounds(const VP9_COMP *cpi,
1196                                       int frame_target,
1197                                       int *frame_under_shoot_limit,
1198                                       int *frame_over_shoot_limit) {
1199   if (cpi->oxcf.rc_mode == VPX_Q) {
1200     *frame_under_shoot_limit = 0;
1201     *frame_over_shoot_limit  = INT_MAX;
1202   } else {
1203     // For very small rate targets where the fractional adjustment
1204     // may be tiny make sure there is at least a minimum range.
1205     const int tolerance = (cpi->sf.recode_tolerance * frame_target) / 100;
1206     *frame_under_shoot_limit = MAX(frame_target - tolerance - 200, 0);
1207     *frame_over_shoot_limit = MIN(frame_target + tolerance + 200,
1208                                   cpi->rc.max_frame_bandwidth);
1209   }
1210 }
1211
1212 void vp10_rc_set_frame_target(VP9_COMP *cpi, int target) {
1213   const VP9_COMMON *const cm = &cpi->common;
1214   RATE_CONTROL *const rc = &cpi->rc;
1215
1216   rc->this_frame_target = target;
1217
1218   // Modify frame size target when down-scaling.
1219   if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC &&
1220       rc->frame_size_selector != UNSCALED)
1221     rc->this_frame_target = (int)(rc->this_frame_target
1222         * rate_thresh_mult[rc->frame_size_selector]);
1223
1224   // Target rate per SB64 (including partial SB64s.
1225   rc->sb64_target_rate = ((int64_t)rc->this_frame_target * 64 * 64) /
1226                              (cm->width * cm->height);
1227 }
1228
1229 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
1230   // this frame refreshes means next frames don't unless specified by user
1231   RATE_CONTROL *const rc = &cpi->rc;
1232   rc->frames_since_golden = 0;
1233
1234   // Mark the alt ref as done (setting to 0 means no further alt refs pending).
1235   rc->source_alt_ref_pending = 0;
1236
1237   // Set the alternate reference frame active flag
1238   rc->source_alt_ref_active = 1;
1239 }
1240
1241 static void update_golden_frame_stats(VP9_COMP *cpi) {
1242   RATE_CONTROL *const rc = &cpi->rc;
1243
1244   // Update the Golden frame usage counts.
1245   if (cpi->refresh_golden_frame) {
1246     // this frame refreshes means next frames don't unless specified by user
1247     rc->frames_since_golden = 0;
1248
1249     // If we are not using alt ref in the up and coming group clear the arf
1250     // active flag.
1251     if (!rc->source_alt_ref_pending) {
1252       rc->source_alt_ref_active = 0;
1253     }
1254
1255     // Decrement count down till next gf
1256     if (rc->frames_till_gf_update_due > 0)
1257       rc->frames_till_gf_update_due--;
1258
1259   } else if (!cpi->refresh_alt_ref_frame) {
1260     // Decrement count down till next gf
1261     if (rc->frames_till_gf_update_due > 0)
1262       rc->frames_till_gf_update_due--;
1263
1264     rc->frames_since_golden++;
1265   }
1266 }
1267
1268 void vp10_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
1269   const VP9_COMMON *const cm = &cpi->common;
1270   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1271   RATE_CONTROL *const rc = &cpi->rc;
1272   const int qindex = cm->base_qindex;
1273
1274   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
1275     vp10_cyclic_refresh_postencode(cpi);
1276   }
1277
1278   // Update rate control heuristics
1279   rc->projected_frame_size = (int)(bytes_used << 3);
1280
1281   // Post encode loop adjustment of Q prediction.
1282   vp10_rc_update_rate_correction_factors(cpi);
1283
1284   // Keep a record of last Q and ambient average Q.
1285   if (cm->frame_type == KEY_FRAME) {
1286     rc->last_q[KEY_FRAME] = qindex;
1287     rc->avg_frame_qindex[KEY_FRAME] =
1288         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1289   } else {
1290     if (rc->is_src_frame_alt_ref ||
1291         !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) ||
1292         (cpi->use_svc && oxcf->rc_mode == VPX_CBR)) {
1293       rc->last_q[INTER_FRAME] = qindex;
1294       rc->avg_frame_qindex[INTER_FRAME] =
1295         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1296       rc->ni_frames++;
1297       rc->tot_q += vp10_convert_qindex_to_q(qindex, cm->bit_depth);
1298       rc->avg_q = rc->tot_q / rc->ni_frames;
1299       // Calculate the average Q for normal inter frames (not key or GFU
1300       // frames).
1301       rc->ni_tot_qi += qindex;
1302       rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1303     }
1304   }
1305
1306   // Keep record of last boosted (KF/KF/ARF) Q value.
1307   // If the current frame is coded at a lower Q then we also update it.
1308   // If all mbs in this group are skipped only update if the Q value is
1309   // better than that already stored.
1310   // This is used to help set quality in forced key frames to reduce popping
1311   if ((qindex < rc->last_boosted_qindex) ||
1312       (cm->frame_type == KEY_FRAME) ||
1313       (!rc->constrained_gf_group &&
1314        (cpi->refresh_alt_ref_frame ||
1315         (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1316     rc->last_boosted_qindex = qindex;
1317   }
1318   if (cm->frame_type == KEY_FRAME)
1319     rc->last_kf_qindex = qindex;
1320
1321   update_buffer_level(cpi, rc->projected_frame_size);
1322
1323   // Rolling monitors of whether we are over or underspending used to help
1324   // regulate min and Max Q in two pass.
1325   if (cm->frame_type != KEY_FRAME) {
1326     rc->rolling_target_bits = ROUND_POWER_OF_TWO(
1327         rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1328     rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
1329         rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1330     rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
1331         rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1332     rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
1333         rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
1334   }
1335
1336   // Actual bits spent
1337   rc->total_actual_bits += rc->projected_frame_size;
1338   rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1339
1340   rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1341
1342   if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
1343       (cm->frame_type != KEY_FRAME))
1344     // Update the alternate reference frame stats as appropriate.
1345     update_alt_ref_frame_stats(cpi);
1346   else
1347     // Update the Golden frame stats as appropriate.
1348     update_golden_frame_stats(cpi);
1349
1350   if (cm->frame_type == KEY_FRAME)
1351     rc->frames_since_key = 0;
1352   if (cm->show_frame) {
1353     rc->frames_since_key++;
1354     rc->frames_to_key--;
1355   }
1356
1357   // Trigger the resizing of the next frame if it is scaled.
1358   if (oxcf->pass != 0) {
1359     cpi->resize_pending =
1360         rc->next_frame_size_selector != rc->frame_size_selector;
1361     rc->frame_size_selector = rc->next_frame_size_selector;
1362   }
1363 }
1364
1365 void vp10_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
1366   // Update buffer level with zero size, update frame counters, and return.
1367   update_buffer_level(cpi, 0);
1368   cpi->rc.frames_since_key++;
1369   cpi->rc.frames_to_key--;
1370   cpi->rc.rc_2_frame = 0;
1371   cpi->rc.rc_1_frame = 0;
1372 }
1373
1374 // Use this macro to turn on/off use of alt-refs in one-pass mode.
1375 #define USE_ALTREF_FOR_ONE_PASS   1
1376
1377 static int calc_pframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1378   static const int af_ratio = 10;
1379   const RATE_CONTROL *const rc = &cpi->rc;
1380   int target;
1381 #if USE_ALTREF_FOR_ONE_PASS
1382   target = (!rc->is_src_frame_alt_ref &&
1383             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) ?
1384       (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
1385       (rc->baseline_gf_interval + af_ratio - 1) :
1386       (rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
1387       (rc->baseline_gf_interval + af_ratio - 1);
1388 #else
1389   target = rc->avg_frame_bandwidth;
1390 #endif
1391   return vp10_rc_clamp_pframe_target_size(cpi, target);
1392 }
1393
1394 static int calc_iframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1395   static const int kf_ratio = 25;
1396   const RATE_CONTROL *rc = &cpi->rc;
1397   const int target = rc->avg_frame_bandwidth * kf_ratio;
1398   return vp10_rc_clamp_iframe_target_size(cpi, target);
1399 }
1400
1401 void vp10_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
1402   VP9_COMMON *const cm = &cpi->common;
1403   RATE_CONTROL *const rc = &cpi->rc;
1404   int target;
1405   // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1406   if (!cpi->refresh_alt_ref_frame &&
1407       (cm->current_video_frame == 0 ||
1408        (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1409        rc->frames_to_key == 0 ||
1410        (cpi->oxcf.auto_key && 0))) {
1411     cm->frame_type = KEY_FRAME;
1412     rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1413                                 rc->frames_to_key == 0;
1414     rc->frames_to_key = cpi->oxcf.key_freq;
1415     rc->kf_boost = DEFAULT_KF_BOOST;
1416     rc->source_alt_ref_active = 0;
1417   } else {
1418     cm->frame_type = INTER_FRAME;
1419   }
1420   if (rc->frames_till_gf_update_due == 0) {
1421     rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
1422     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1423     // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1424     if (rc->frames_till_gf_update_due > rc->frames_to_key) {
1425       rc->frames_till_gf_update_due = rc->frames_to_key;
1426       rc->constrained_gf_group = 1;
1427     } else {
1428       rc->constrained_gf_group = 0;
1429     }
1430     cpi->refresh_golden_frame = 1;
1431     rc->source_alt_ref_pending = USE_ALTREF_FOR_ONE_PASS;
1432     rc->gfu_boost = DEFAULT_GF_BOOST;
1433   }
1434   if (cm->frame_type == KEY_FRAME)
1435     target = calc_iframe_target_size_one_pass_vbr(cpi);
1436   else
1437     target = calc_pframe_target_size_one_pass_vbr(cpi);
1438   vp10_rc_set_frame_target(cpi, target);
1439 }
1440
1441 static int calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1442   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1443   const RATE_CONTROL *rc = &cpi->rc;
1444   const SVC *const svc = &cpi->svc;
1445   const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
1446   const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
1447   int min_frame_target = MAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
1448   int target;
1449
1450   if (oxcf->gf_cbr_boost_pct) {
1451     const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
1452     target =  cpi->refresh_golden_frame ?
1453       (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio_pct) /
1454       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100) :
1455       (rc->avg_frame_bandwidth * rc->baseline_gf_interval * 100) /
1456       (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
1457   } else {
1458     target = rc->avg_frame_bandwidth;
1459   }
1460   if (is_one_pass_cbr_svc(cpi)) {
1461     // Note that for layers, avg_frame_bandwidth is the cumulative
1462     // per-frame-bandwidth. For the target size of this frame, use the
1463     // layer average frame size (i.e., non-cumulative per-frame-bw).
1464     int layer =
1465         LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1466             svc->temporal_layer_id, svc->number_temporal_layers);
1467     const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1468     target = lc->avg_frame_size;
1469     min_frame_target = MAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
1470   }
1471   if (diff > 0) {
1472     // Lower the target bandwidth for this frame.
1473     const int pct_low = (int)MIN(diff / one_pct_bits, oxcf->under_shoot_pct);
1474     target -= (target * pct_low) / 200;
1475   } else if (diff < 0) {
1476     // Increase the target bandwidth for this frame.
1477     const int pct_high = (int)MIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
1478     target += (target * pct_high) / 200;
1479   }
1480   if (oxcf->rc_max_inter_bitrate_pct) {
1481     const int max_rate = rc->avg_frame_bandwidth *
1482                          oxcf->rc_max_inter_bitrate_pct / 100;
1483     target = MIN(target, max_rate);
1484   }
1485   return MAX(min_frame_target, target);
1486 }
1487
1488 static int calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1489   const RATE_CONTROL *rc = &cpi->rc;
1490   const VP9EncoderConfig *oxcf = &cpi->oxcf;
1491   const SVC *const svc = &cpi->svc;
1492   int target;
1493   if (cpi->common.current_video_frame == 0) {
1494     target = ((rc->starting_buffer_level / 2) > INT_MAX)
1495       ? INT_MAX : (int)(rc->starting_buffer_level / 2);
1496   } else {
1497     int kf_boost = 32;
1498     double framerate = cpi->framerate;
1499     if (svc->number_temporal_layers > 1 &&
1500         oxcf->rc_mode == VPX_CBR) {
1501       // Use the layer framerate for temporal layers CBR mode.
1502       const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1503           svc->temporal_layer_id, svc->number_temporal_layers);
1504       const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1505       framerate = lc->framerate;
1506     }
1507     kf_boost = MAX(kf_boost, (int)(2 * framerate - 16));
1508     if (rc->frames_since_key <  framerate / 2) {
1509       kf_boost = (int)(kf_boost * rc->frames_since_key /
1510                        (framerate / 2));
1511     }
1512     target = ((16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
1513   }
1514   return vp10_rc_clamp_iframe_target_size(cpi, target);
1515 }
1516
1517 // Reset information needed to set proper reference frames and buffer updates
1518 // for temporal layering. This is called when a key frame is encoded.
1519 static void reset_temporal_layer_to_zero(VP9_COMP *cpi) {
1520   int sl;
1521   LAYER_CONTEXT *lc = NULL;
1522   cpi->svc.temporal_layer_id = 0;
1523
1524   for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
1525     lc = &cpi->svc.layer_context[sl * cpi->svc.number_temporal_layers];
1526     lc->current_video_frame_in_layer = 0;
1527     lc->frames_from_key_frame = 0;
1528   }
1529 }
1530
1531 void vp10_rc_get_svc_params(VP9_COMP *cpi) {
1532   VP9_COMMON *const cm = &cpi->common;
1533   RATE_CONTROL *const rc = &cpi->rc;
1534   int target = rc->avg_frame_bandwidth;
1535   const int layer = LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id,
1536       cpi->svc.temporal_layer_id, cpi->svc.number_temporal_layers);
1537
1538   if ((cm->current_video_frame == 0) ||
1539       (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1540       (cpi->oxcf.auto_key && (rc->frames_since_key %
1541           cpi->oxcf.key_freq == 0))) {
1542     cm->frame_type = KEY_FRAME;
1543     rc->source_alt_ref_active = 0;
1544
1545     if (is_two_pass_svc(cpi)) {
1546       cpi->svc.layer_context[layer].is_key_frame = 1;
1547       cpi->ref_frame_flags &=
1548           (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1549     } else if (is_one_pass_cbr_svc(cpi)) {
1550       cpi->svc.layer_context[layer].is_key_frame = 1;
1551       reset_temporal_layer_to_zero(cpi);
1552       cpi->ref_frame_flags &=
1553                 (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1554       // Assumption here is that LAST_FRAME is being updated for a keyframe.
1555       // Thus no change in update flags.
1556       target = calc_iframe_target_size_one_pass_cbr(cpi);
1557     }
1558   } else {
1559     cm->frame_type = INTER_FRAME;
1560     if (is_two_pass_svc(cpi)) {
1561       LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1562       if (cpi->svc.spatial_layer_id == 0) {
1563         lc->is_key_frame = 0;
1564       } else {
1565         lc->is_key_frame =
1566             cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1567         if (lc->is_key_frame)
1568           cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
1569       }
1570       cpi->ref_frame_flags &= (~VP9_ALT_FLAG);
1571     } else if (is_one_pass_cbr_svc(cpi)) {
1572       LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1573       if (cpi->svc.spatial_layer_id == 0) {
1574         lc->is_key_frame = 0;
1575       } else {
1576         lc->is_key_frame =
1577             cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1578       }
1579       target = calc_pframe_target_size_one_pass_cbr(cpi);
1580     }
1581   }
1582
1583   // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1584   // should be done here, before the frame qp is selected.
1585   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1586     vp10_cyclic_refresh_update_parameters(cpi);
1587
1588   vp10_rc_set_frame_target(cpi, target);
1589   rc->frames_till_gf_update_due = INT_MAX;
1590   rc->baseline_gf_interval = INT_MAX;
1591 }
1592
1593 void vp10_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
1594   VP9_COMMON *const cm = &cpi->common;
1595   RATE_CONTROL *const rc = &cpi->rc;
1596   int target;
1597   // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1598   if ((cm->current_video_frame == 0 ||
1599       (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1600       rc->frames_to_key == 0 ||
1601       (cpi->oxcf.auto_key && 0))) {
1602     cm->frame_type = KEY_FRAME;
1603     rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1604                                 rc->frames_to_key == 0;
1605     rc->frames_to_key = cpi->oxcf.key_freq;
1606     rc->kf_boost = DEFAULT_KF_BOOST;
1607     rc->source_alt_ref_active = 0;
1608   } else {
1609     cm->frame_type = INTER_FRAME;
1610   }
1611   if (rc->frames_till_gf_update_due == 0) {
1612     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1613       vp10_cyclic_refresh_set_golden_update(cpi);
1614     else
1615       rc->baseline_gf_interval =
1616           (rc->min_gf_interval + rc->max_gf_interval) / 2;
1617     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1618     // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1619     if (rc->frames_till_gf_update_due > rc->frames_to_key)
1620       rc->frames_till_gf_update_due = rc->frames_to_key;
1621     cpi->refresh_golden_frame = 1;
1622     rc->gfu_boost = DEFAULT_GF_BOOST;
1623   }
1624
1625   // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1626   // should be done here, before the frame qp is selected.
1627   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1628     vp10_cyclic_refresh_update_parameters(cpi);
1629
1630   if (cm->frame_type == KEY_FRAME)
1631     target = calc_iframe_target_size_one_pass_cbr(cpi);
1632   else
1633     target = calc_pframe_target_size_one_pass_cbr(cpi);
1634
1635   vp10_rc_set_frame_target(cpi, target);
1636   if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC)
1637     cpi->resize_pending = vp10_resize_one_pass_cbr(cpi);
1638   else
1639     cpi->resize_pending = 0;
1640 }
1641
1642 int vp10_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
1643                        vpx_bit_depth_t bit_depth) {
1644   int start_index = rc->worst_quality;
1645   int target_index = rc->worst_quality;
1646   int i;
1647
1648   // Convert the average q value to an index.
1649   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1650     start_index = i;
1651     if (vp10_convert_qindex_to_q(i, bit_depth) >= qstart)
1652       break;
1653   }
1654
1655   // Convert the q target to an index
1656   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1657     target_index = i;
1658     if (vp10_convert_qindex_to_q(i, bit_depth) >= qtarget)
1659       break;
1660   }
1661
1662   return target_index - start_index;
1663 }
1664
1665 int vp10_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
1666                                int qindex, double rate_target_ratio,
1667                                vpx_bit_depth_t bit_depth) {
1668   int target_index = rc->worst_quality;
1669   int i;
1670
1671   // Look up the current projected bits per block for the base index
1672   const int base_bits_per_mb = vp10_rc_bits_per_mb(frame_type, qindex, 1.0,
1673                                                   bit_depth);
1674
1675   // Find the target bits per mb based on the base value and given ratio.
1676   const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
1677
1678   // Convert the q target to an index
1679   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1680     if (vp10_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
1681         target_bits_per_mb) {
1682       target_index = i;
1683       break;
1684     }
1685   }
1686   return target_index - qindex;
1687 }
1688
1689 void vp10_rc_set_gf_interval_range(const VP9_COMP *const cpi,
1690                                   RATE_CONTROL *const rc) {
1691   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1692
1693   // Set Maximum gf/arf interval
1694   rc->max_gf_interval = oxcf->max_gf_interval;
1695   rc->min_gf_interval = oxcf->min_gf_interval;
1696   if (rc->min_gf_interval == 0)
1697     rc->min_gf_interval = vp10_rc_get_default_min_gf_interval(
1698         oxcf->width, oxcf->height, cpi->framerate);
1699   if (rc->max_gf_interval == 0)
1700     rc->max_gf_interval = vp10_rc_get_default_max_gf_interval(
1701         cpi->framerate, rc->min_gf_interval);
1702
1703   // Extended interval for genuinely static scenes
1704   rc->static_scene_max_gf_interval = MAX_LAG_BUFFERS * 2;
1705
1706   if (is_altref_enabled(cpi)) {
1707     if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
1708       rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
1709   }
1710
1711   if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
1712     rc->max_gf_interval = rc->static_scene_max_gf_interval;
1713
1714   // Clamp min to max
1715   rc->min_gf_interval = MIN(rc->min_gf_interval, rc->max_gf_interval);
1716 }
1717
1718 void vp10_rc_update_framerate(VP9_COMP *cpi) {
1719   const VP9_COMMON *const cm = &cpi->common;
1720   const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1721   RATE_CONTROL *const rc = &cpi->rc;
1722   int vbr_max_bits;
1723
1724   rc->avg_frame_bandwidth = (int)(oxcf->target_bandwidth / cpi->framerate);
1725   rc->min_frame_bandwidth = (int)(rc->avg_frame_bandwidth *
1726                                 oxcf->two_pass_vbrmin_section / 100);
1727
1728   rc->min_frame_bandwidth = MAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1729
1730   // A maximum bitrate for a frame is defined.
1731   // The baseline for this aligns with HW implementations that
1732   // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
1733   // per 16x16 MB (averaged over a frame). However this limit is extended if
1734   // a very high rate is given on the command line or the the rate cannnot
1735   // be acheived because of a user specificed max q (e.g. when the user
1736   // specifies lossless encode.
1737   vbr_max_bits = (int)(((int64_t)rc->avg_frame_bandwidth *
1738                      oxcf->two_pass_vbrmax_section) / 100);
1739   rc->max_frame_bandwidth = MAX(MAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P),
1740                                     vbr_max_bits);
1741
1742   vp10_rc_set_gf_interval_range(cpi, rc);
1743 }
1744
1745 #define VBR_PCT_ADJUSTMENT_LIMIT 50
1746 // For VBR...adjustment to the frame target based on error from previous frames
1747 static void vbr_rate_correction(VP9_COMP *cpi, int *this_frame_target) {
1748   RATE_CONTROL *const rc = &cpi->rc;
1749   int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
1750   int max_delta;
1751   double position_factor = 1.0;
1752
1753   // How far through the clip are we.
1754   // This number is used to damp the per frame rate correction.
1755   // Range 0 - 1.0
1756   if (cpi->twopass.total_stats.count) {
1757     position_factor = sqrt((double)cpi->common.current_video_frame /
1758                            cpi->twopass.total_stats.count);
1759   }
1760   max_delta = (int)(position_factor *
1761                     ((*this_frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
1762
1763   // vbr_bits_off_target > 0 means we have extra bits to spend
1764   if (vbr_bits_off_target > 0) {
1765     *this_frame_target +=
1766       (vbr_bits_off_target > max_delta) ? max_delta
1767                                         : (int)vbr_bits_off_target;
1768   } else {
1769     *this_frame_target -=
1770       (vbr_bits_off_target < -max_delta) ? max_delta
1771                                          : (int)-vbr_bits_off_target;
1772   }
1773
1774   // Fast redistribution of bits arising from massive local undershoot.
1775   // Dont do it for kf,arf,gf or overlay frames.
1776   if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
1777       rc->vbr_bits_off_target_fast) {
1778     int one_frame_bits = MAX(rc->avg_frame_bandwidth, *this_frame_target);
1779     int fast_extra_bits;
1780     fast_extra_bits =
1781       (int)MIN(rc->vbr_bits_off_target_fast, one_frame_bits);
1782     fast_extra_bits = (int)MIN(fast_extra_bits,
1783       MAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
1784     *this_frame_target += (int)fast_extra_bits;
1785     rc->vbr_bits_off_target_fast -= fast_extra_bits;
1786   }
1787 }
1788
1789 void vp10_set_target_rate(VP9_COMP *cpi) {
1790   RATE_CONTROL *const rc = &cpi->rc;
1791   int target_rate = rc->base_frame_target;
1792
1793   // Correction to rate target based on prior over or under shoot.
1794   if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
1795     vbr_rate_correction(cpi, &target_rate);
1796   vp10_rc_set_frame_target(cpi, target_rate);
1797 }
1798
1799 // Check if we should resize, based on average QP from past x frames.
1800 // Only allow for resize at most one scale down for now, scaling factor is 2.
1801 int vp10_resize_one_pass_cbr(VP9_COMP *cpi) {
1802   const VP9_COMMON *const cm = &cpi->common;
1803   RATE_CONTROL *const rc = &cpi->rc;
1804   int resize_now = 0;
1805   cpi->resize_scale_num = 1;
1806   cpi->resize_scale_den = 1;
1807   // Don't resize on key frame; reset the counters on key frame.
1808   if (cm->frame_type == KEY_FRAME) {
1809     cpi->resize_avg_qp = 0;
1810     cpi->resize_count = 0;
1811     return 0;
1812   }
1813   // Resize based on average buffer underflow and QP over some window.
1814   // Ignore samples close to key frame, since QP is usually high after key.
1815   if (cpi->rc.frames_since_key > 2 * cpi->framerate) {
1816     const int window = (int)(5 * cpi->framerate);
1817     cpi->resize_avg_qp += cm->base_qindex;
1818     if (cpi->rc.buffer_level < (int)(30 * rc->optimal_buffer_level / 100))
1819       ++cpi->resize_buffer_underflow;
1820     ++cpi->resize_count;
1821     // Check for resize action every "window" frames.
1822     if (cpi->resize_count >= window) {
1823       int avg_qp = cpi->resize_avg_qp / cpi->resize_count;
1824       // Resize down if buffer level has underflowed sufficent amount in past
1825       // window, and we are at original resolution.
1826       // Resize back up if average QP is low, and we are currently in a resized
1827       // down state.
1828       if (cpi->resize_state == 0 &&
1829           cpi->resize_buffer_underflow > (cpi->resize_count >> 2)) {
1830         resize_now = 1;
1831         cpi->resize_state = 1;
1832       } else if (cpi->resize_state == 1 &&
1833                  avg_qp < 40 * cpi->rc.worst_quality / 100) {
1834         resize_now = -1;
1835         cpi->resize_state = 0;
1836       }
1837       // Reset for next window measurement.
1838       cpi->resize_avg_qp = 0;
1839       cpi->resize_count = 0;
1840       cpi->resize_buffer_underflow = 0;
1841     }
1842   }
1843   // If decision is to resize, reset some quantities, and check is we should
1844   // reduce rate correction factor,
1845   if (resize_now != 0) {
1846     int target_bits_per_frame;
1847     int active_worst_quality;
1848     int qindex;
1849     int tot_scale_change;
1850     // For now, resize is by 1/2 x 1/2.
1851     cpi->resize_scale_num = 1;
1852     cpi->resize_scale_den = 2;
1853     tot_scale_change = (cpi->resize_scale_den * cpi->resize_scale_den) /
1854         (cpi->resize_scale_num * cpi->resize_scale_num);
1855     // Reset buffer level to optimal, update target size.
1856     rc->buffer_level = rc->optimal_buffer_level;
1857     rc->bits_off_target = rc->optimal_buffer_level;
1858     rc->this_frame_target = calc_pframe_target_size_one_pass_cbr(cpi);
1859     // Reset cyclic refresh parameters.
1860     if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
1861       vp10_cyclic_refresh_reset_resize(cpi);
1862     // Get the projected qindex, based on the scaled target frame size (scaled
1863     // so target_bits_per_mb in vp10_rc_regulate_q will be correct target).
1864     target_bits_per_frame = (resize_now == 1) ?
1865         rc->this_frame_target * tot_scale_change :
1866         rc->this_frame_target / tot_scale_change;
1867     active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
1868     qindex = vp10_rc_regulate_q(cpi,
1869                                target_bits_per_frame,
1870                                rc->best_quality,
1871                                active_worst_quality);
1872     // If resize is down, check if projected q index is close to worst_quality,
1873     // and if so, reduce the rate correction factor (since likely can afford
1874     // lower q for resized frame).
1875     if (resize_now == 1 &&
1876         qindex > 90 * cpi->rc.worst_quality / 100) {
1877       rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
1878     }
1879     // If resize is back up, check if projected q index is too much above the
1880     // current base_qindex, and if so, reduce the rate correction factor
1881     // (since prefer to keep q for resized frame at least close to previous q).
1882     if (resize_now == -1 &&
1883        qindex > 130 * cm->base_qindex / 100) {
1884       rc->rate_correction_factors[INTER_NORMAL] *= 0.9;
1885     }
1886   }
1887   return resize_now;
1888 }