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