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