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