]> granicus.if.org Git - libvpx/blob - vp9/encoder/vp9_ratectrl.c
b1ef08291c66e619065a76b416ca6a7af75a9043
[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_mem/vpx_mem.h"
19
20 #include "vp9/common/vp9_alloccommon.h"
21 #include "vp9/common/vp9_common.h"
22 #include "vp9/common/vp9_entropymode.h"
23 #include "vp9/common/vp9_quant_common.h"
24 #include "vp9/common/vp9_seg_common.h"
25 #include "vp9/common/vp9_systemdependent.h"
26
27 #include "vp9/encoder/vp9_encodemv.h"
28 #include "vp9/encoder/vp9_ratectrl.h"
29
30 #define DEFAULT_KF_BOOST 2000
31 #define DEFAULT_GF_BOOST 2000
32
33 #define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
34
35 #define MIN_BPB_FACTOR 0.005
36 #define MAX_BPB_FACTOR 50
37
38 // Tables relating active max Q to active min Q
39 static int kf_low_motion_minq[QINDEX_RANGE];
40 static int kf_high_motion_minq[QINDEX_RANGE];
41 static int gf_low_motion_minq[QINDEX_RANGE];
42 static int gf_high_motion_minq[QINDEX_RANGE];
43 static int inter_minq[QINDEX_RANGE];
44 static int afq_low_motion_minq[QINDEX_RANGE];
45 static int afq_high_motion_minq[QINDEX_RANGE];
46 static int gf_high = 2000;
47 static int gf_low = 400;
48 static int kf_high = 5000;
49 static int kf_low = 400;
50
51 // Functions to compute the active minq lookup table entries based on a
52 // formulaic approach to facilitate easier adjustment of the Q tables.
53 // The formulae were derived from computing a 3rd order polynomial best
54 // fit to the original data (after plotting real maxq vs minq (not q index))
55 static int get_minq_index(double maxq, double x3, double x2, double x1) {
56   int i;
57   const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq,
58                                 maxq);
59
60   // Special case handling to deal with the step from q2.0
61   // down to lossless mode represented by q 1.0.
62   if (minqtarget <= 2.0)
63     return 0;
64
65   for (i = 0; i < QINDEX_RANGE; i++)
66     if (minqtarget <= vp9_convert_qindex_to_q(i))
67       return i;
68
69   return QINDEX_RANGE - 1;
70 }
71
72 void vp9_rc_init_minq_luts() {
73   int i;
74
75   for (i = 0; i < QINDEX_RANGE; i++) {
76     const double maxq = vp9_convert_qindex_to_q(i);
77     kf_low_motion_minq[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.15);
78     kf_high_motion_minq[i] = get_minq_index(maxq, 0.000002, -0.0012, 0.50);
79     gf_low_motion_minq[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.32);
80     gf_high_motion_minq[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.50);
81     afq_low_motion_minq[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.33);
82     afq_high_motion_minq[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55);
83     inter_minq[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.55);
84   }
85 }
86
87 // These functions use formulaic calculations to make playing with the
88 // quantizer tables easier. If necessary they can be replaced by lookup
89 // tables if and when things settle down in the experimental bitstream
90 double vp9_convert_qindex_to_q(int qindex) {
91   // Convert the index to a real Q value (scaled down to match old Q values)
92   return vp9_ac_quant(qindex, 0) / 4.0;
93 }
94
95 int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
96                        double correction_factor) {
97   const double q = vp9_convert_qindex_to_q(qindex);
98   int enumerator = frame_type == KEY_FRAME ? 3300000 : 2250000;
99
100   // q based adjustment to baseline enumerator
101   enumerator += (int)(enumerator * q) >> 12;
102   return (int)(0.5 + (enumerator * correction_factor / q));
103 }
104
105 static int estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
106                               double correction_factor) {
107   const int bpm = (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor));
108   return ((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS;
109 }
110
111 int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
112   const RATE_CONTROL *rc = &cpi->rc;
113   const int min_frame_target = MAX(rc->min_frame_bandwidth,
114                                    rc->av_per_frame_bandwidth >> 5);
115   if (target < min_frame_target)
116     target = min_frame_target;
117   if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
118     // If there is an active ARF at this location use the minimum
119     // bits on this frame even if it is a constructed arf.
120     // The active maximum quantizer insures that an appropriate
121     // number of bits will be spent if needed for constructed ARFs.
122     target = min_frame_target;
123   }
124   // Clip the frame target to the maximum allowed value.
125   if (target > rc->max_frame_bandwidth)
126     target = rc->max_frame_bandwidth;
127   return target;
128 }
129
130 int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
131   const RATE_CONTROL *rc = &cpi->rc;
132   const VP9_CONFIG *oxcf = &cpi->oxcf;
133   if (oxcf->rc_max_intra_bitrate_pct) {
134     const int max_rate = rc->av_per_frame_bandwidth *
135         oxcf->rc_max_intra_bitrate_pct / 100;
136     target = MIN(target, max_rate);
137   }
138   if (target > rc->max_frame_bandwidth)
139     target = rc->max_frame_bandwidth;
140   return target;
141 }
142
143
144 // Update the buffer level for higher layers, given the encoded current layer.
145 static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
146   int temporal_layer = 0;
147   int current_temporal_layer = svc->temporal_layer_id;
148   for (temporal_layer = current_temporal_layer + 1;
149       temporal_layer < svc->number_temporal_layers; ++temporal_layer) {
150     LAYER_CONTEXT *lc = &svc->layer_context[temporal_layer];
151     RATE_CONTROL *lrc = &lc->rc;
152     int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
153         encoded_frame_size);
154     lrc->bits_off_target += bits_off_for_this_layer;
155
156     // Clip buffer level to maximum buffer size for the layer.
157     lrc->bits_off_target = MIN(lrc->bits_off_target, lc->maximum_buffer_size);
158     lrc->buffer_level = lrc->bits_off_target;
159   }
160 }
161
162 // Update the buffer level: leaky bucket model.
163 static void update_buffer_level(VP9_COMP *cpi, int encoded_frame_size) {
164   const VP9_COMMON *const cm = &cpi->common;
165   const VP9_CONFIG *oxcf = &cpi->oxcf;
166   RATE_CONTROL *const rc = &cpi->rc;
167
168   // Non-viewable frames are a special case and are treated as pure overhead.
169   if (!cm->show_frame) {
170     rc->bits_off_target -= encoded_frame_size;
171   } else {
172     rc->bits_off_target += rc->av_per_frame_bandwidth - encoded_frame_size;
173   }
174
175   // Clip the buffer level to the maximum specified buffer size.
176   rc->bits_off_target = MIN(rc->bits_off_target, oxcf->maximum_buffer_size);
177   rc->buffer_level = rc->bits_off_target;
178
179   if (cpi->use_svc && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
180     update_layer_buffer_level(&cpi->svc, encoded_frame_size);
181   }
182 }
183
184 void vp9_rc_init(const VP9_CONFIG *oxcf, int pass, RATE_CONTROL *rc) {
185   if (pass == 0 && oxcf->end_usage == USAGE_STREAM_FROM_SERVER) {
186     rc->avg_frame_qindex[0] = oxcf->worst_allowed_q;
187     rc->avg_frame_qindex[1] = oxcf->worst_allowed_q;
188     rc->avg_frame_qindex[2] = oxcf->worst_allowed_q;
189   } else {
190     rc->avg_frame_qindex[0] = (oxcf->worst_allowed_q +
191                                    oxcf->best_allowed_q) / 2;
192     rc->avg_frame_qindex[1] = (oxcf->worst_allowed_q +
193                                    oxcf->best_allowed_q) / 2;
194     rc->avg_frame_qindex[2] = (oxcf->worst_allowed_q +
195                                    oxcf->best_allowed_q) / 2;
196   }
197
198   rc->last_q[0] = oxcf->best_allowed_q;
199   rc->last_q[1] = oxcf->best_allowed_q;
200   rc->last_q[2] = oxcf->best_allowed_q;
201
202   rc->buffer_level =    oxcf->starting_buffer_level;
203   rc->bits_off_target = oxcf->starting_buffer_level;
204
205   rc->rolling_target_bits      = rc->av_per_frame_bandwidth;
206   rc->rolling_actual_bits      = rc->av_per_frame_bandwidth;
207   rc->long_rolling_target_bits = rc->av_per_frame_bandwidth;
208   rc->long_rolling_actual_bits = rc->av_per_frame_bandwidth;
209
210   rc->total_actual_bits = 0;
211   rc->total_target_vs_actual = 0;
212
213   rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
214   rc->frames_since_key = 8;  // Sensible default for first frame.
215   rc->this_key_frame_forced = 0;
216   rc->next_key_frame_forced = 0;
217   rc->source_alt_ref_pending = 0;
218   rc->source_alt_ref_active = 0;
219
220   rc->frames_till_gf_update_due = 0;
221
222   rc->ni_av_qi = oxcf->worst_allowed_q;
223   rc->ni_tot_qi = 0;
224   rc->ni_frames = 0;
225
226   rc->tot_q = 0.0;
227   rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q);
228
229   rc->rate_correction_factor = 1.0;
230   rc->key_frame_rate_correction_factor = 1.0;
231   rc->gf_rate_correction_factor = 1.0;
232 }
233
234 int vp9_rc_drop_frame(VP9_COMP *cpi) {
235   const VP9_CONFIG *oxcf = &cpi->oxcf;
236   RATE_CONTROL *const rc = &cpi->rc;
237
238   if (!oxcf->drop_frames_water_mark) {
239     return 0;
240   } else {
241     if (rc->buffer_level < 0) {
242       // Always drop if buffer is below 0.
243       return 1;
244     } else {
245       // If buffer is below drop_mark, for now just drop every other frame
246       // (starting with the next frame) until it increases back over drop_mark.
247       int drop_mark = (int)(oxcf->drop_frames_water_mark *
248           oxcf->optimal_buffer_level / 100);
249       if ((rc->buffer_level > drop_mark) &&
250           (rc->decimation_factor > 0)) {
251         --rc->decimation_factor;
252       } else if (rc->buffer_level <= drop_mark &&
253           rc->decimation_factor == 0) {
254         rc->decimation_factor = 1;
255       }
256       if (rc->decimation_factor > 0) {
257         if (rc->decimation_count > 0) {
258           --rc->decimation_count;
259           return 1;
260         } else {
261           rc->decimation_count = rc->decimation_factor;
262           return 0;
263         }
264       } else {
265         rc->decimation_count = 0;
266         return 0;
267       }
268     }
269   }
270 }
271
272 static double get_rate_correction_factor(const VP9_COMP *cpi) {
273   if (cpi->common.frame_type == KEY_FRAME) {
274     return cpi->rc.key_frame_rate_correction_factor;
275   } else {
276     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
277         !cpi->rc.is_src_frame_alt_ref &&
278         !(cpi->use_svc && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
279       return cpi->rc.gf_rate_correction_factor;
280     else
281       return cpi->rc.rate_correction_factor;
282   }
283 }
284
285 static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
286   if (cpi->common.frame_type == KEY_FRAME) {
287     cpi->rc.key_frame_rate_correction_factor = factor;
288   } else {
289     if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
290         !cpi->rc.is_src_frame_alt_ref &&
291         !(cpi->use_svc && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER))
292       cpi->rc.gf_rate_correction_factor = factor;
293     else
294       cpi->rc.rate_correction_factor = factor;
295   }
296 }
297
298 void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi, int damp_var) {
299   const VP9_COMMON *const cm = &cpi->common;
300   int correction_factor = 100;
301   double rate_correction_factor = get_rate_correction_factor(cpi);
302   double adjustment_limit;
303
304   int projected_size_based_on_q = 0;
305
306   // Clear down mmx registers to allow floating point in what follows
307   vp9_clear_system_state();
308
309   // Work out how big we would have expected the frame to be at this Q given
310   // the current correction factor.
311   // Stay in double to avoid int overflow when values are large
312   projected_size_based_on_q = estimate_bits_at_q(cm->frame_type,
313                                                  cm->base_qindex, cm->MBs,
314                                                  rate_correction_factor);
315   // Work out a size correction factor.
316   if (projected_size_based_on_q > 0)
317     correction_factor = (100 * cpi->rc.projected_frame_size) /
318                             projected_size_based_on_q;
319
320   // More heavily damped adjustment used if we have been oscillating either side
321   // of target.
322   switch (damp_var) {
323     case 0:
324       adjustment_limit = 0.75;
325       break;
326     case 1:
327       adjustment_limit = 0.375;
328       break;
329     case 2:
330     default:
331       adjustment_limit = 0.25;
332       break;
333   }
334
335   if (correction_factor > 102) {
336     // We are not already at the worst allowable quality
337     correction_factor = (int)(100 + ((correction_factor - 100) *
338                                   adjustment_limit));
339     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
340
341     // Keep rate_correction_factor within limits
342     if (rate_correction_factor > MAX_BPB_FACTOR)
343       rate_correction_factor = MAX_BPB_FACTOR;
344   } else if (correction_factor < 99) {
345     // We are not already at the best allowable quality
346     correction_factor = (int)(100 - ((100 - correction_factor) *
347                                   adjustment_limit));
348     rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
349
350     // Keep rate_correction_factor within limits
351     if (rate_correction_factor < MIN_BPB_FACTOR)
352       rate_correction_factor = MIN_BPB_FACTOR;
353   }
354
355   set_rate_correction_factor(cpi, rate_correction_factor);
356 }
357
358
359 int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
360                       int active_best_quality, int active_worst_quality) {
361   const VP9_COMMON *const cm = &cpi->common;
362   int q = active_worst_quality;
363   int last_error = INT_MAX;
364   int i, target_bits_per_mb;
365   const double correction_factor = get_rate_correction_factor(cpi);
366
367   // Calculate required scaling factor based on target frame size and size of
368   // frame produced using previous Q.
369   target_bits_per_mb =
370       ((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs;
371
372   i = active_best_quality;
373
374   do {
375     const int bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cm->frame_type, i,
376                                                              correction_factor);
377
378     if (bits_per_mb_at_this_q <= target_bits_per_mb) {
379       if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
380         q = i;
381       else
382         q = i - 1;
383
384       break;
385     } else {
386       last_error = bits_per_mb_at_this_q - target_bits_per_mb;
387     }
388   } while (++i <= active_worst_quality);
389
390   return q;
391 }
392
393 static int get_active_quality(int q, int gfu_boost, int low, int high,
394                               int *low_motion_minq, int *high_motion_minq) {
395   if (gfu_boost > high) {
396     return low_motion_minq[q];
397   } else if (gfu_boost < low) {
398     return high_motion_minq[q];
399   } else {
400     const int gap = high - low;
401     const int offset = high - gfu_boost;
402     const int qdiff = high_motion_minq[q] - low_motion_minq[q];
403     const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
404     return low_motion_minq[q] + adjustment;
405   }
406 }
407
408 static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
409   const RATE_CONTROL *const rc = &cpi->rc;
410   const unsigned int curr_frame = cpi->common.current_video_frame;
411   int active_worst_quality;
412
413   if (cpi->common.frame_type == KEY_FRAME) {
414     active_worst_quality = curr_frame == 0 ? rc->worst_quality
415                                            : rc->last_q[KEY_FRAME] * 2;
416   } else {
417     if (!rc->is_src_frame_alt_ref &&
418         (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
419       active_worst_quality =  curr_frame == 1 ? rc->last_q[KEY_FRAME] * 5 / 4
420                                               : rc->last_q[INTER_FRAME];
421     } else {
422       active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 2
423                                              : rc->last_q[INTER_FRAME] * 2;
424     }
425   }
426
427   return MIN(active_worst_quality, rc->worst_quality);
428 }
429
430 // Adjust active_worst_quality level based on buffer level.
431 static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
432   // Adjust active_worst_quality: If buffer is above the optimal/target level,
433   // bring active_worst_quality down depending on fullness of buffer.
434   // If buffer is below the optimal level, let the active_worst_quality go from
435   // ambient Q (at buffer = optimal level) to worst_quality level
436   // (at buffer = critical level).
437   const VP9_COMMON *const cm = &cpi->common;
438   const VP9_CONFIG *oxcf = &cpi->oxcf;
439   const RATE_CONTROL *rc = &cpi->rc;
440   // Buffer level below which we push active_worst to worst_quality.
441   int64_t critical_level = oxcf->optimal_buffer_level >> 2;
442   int64_t buff_lvl_step = 0;
443   int adjustment = 0;
444   int active_worst_quality;
445   if (cm->frame_type == KEY_FRAME)
446     return rc->worst_quality;
447   if (cm->current_video_frame > 1)
448     active_worst_quality = MIN(rc->worst_quality,
449                                rc->avg_frame_qindex[INTER_FRAME] * 5 / 4);
450   else
451     active_worst_quality = MIN(rc->worst_quality,
452                                rc->avg_frame_qindex[KEY_FRAME] * 3 / 2);
453   if (rc->buffer_level > oxcf->optimal_buffer_level) {
454     // Adjust down.
455     // Maximum limit for down adjustment, ~30%.
456     int max_adjustment_down = active_worst_quality / 3;
457     if (max_adjustment_down) {
458       buff_lvl_step = ((oxcf->maximum_buffer_size -
459                         oxcf->optimal_buffer_level) / max_adjustment_down);
460       if (buff_lvl_step)
461         adjustment = (int)((rc->buffer_level - oxcf->optimal_buffer_level) /
462                             buff_lvl_step);
463       active_worst_quality -= adjustment;
464     }
465   } else if (rc->buffer_level > critical_level) {
466     // Adjust up from ambient Q.
467     if (critical_level) {
468       buff_lvl_step = (oxcf->optimal_buffer_level - critical_level);
469       if (buff_lvl_step) {
470         adjustment =
471             (int)((rc->worst_quality - rc->avg_frame_qindex[INTER_FRAME]) *
472                   (oxcf->optimal_buffer_level - rc->buffer_level) /
473                   buff_lvl_step);
474       }
475       active_worst_quality = rc->avg_frame_qindex[INTER_FRAME] + adjustment;
476     }
477   } else {
478     // Set to worst_quality if buffer is below critical level.
479     active_worst_quality = rc->worst_quality;
480   }
481   return active_worst_quality;
482 }
483
484 static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
485                                              int *bottom_index,
486                                              int *top_index) {
487   const VP9_COMMON *const cm = &cpi->common;
488   const RATE_CONTROL *const rc = &cpi->rc;
489   int active_best_quality;
490   int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
491   int q;
492
493   if (frame_is_intra_only(cm)) {
494     active_best_quality = rc->best_quality;
495     // Handle the special case for key frames forced when we have75 reached
496     // the maximum key frame interval. Here force the Q to a range
497     // based on the ambient Q to reduce the risk of popping.
498     if (rc->this_key_frame_forced) {
499       int qindex = rc->last_boosted_qindex;
500       double last_boosted_q = vp9_convert_qindex_to_q(qindex);
501       int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
502                                             (last_boosted_q * 0.75));
503       active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
504     } else if (cm->current_video_frame > 0) {
505       // not first frame of one pass and kf_boost is set
506       double q_adj_factor = 1.0;
507       double q_val;
508
509       active_best_quality = get_active_quality(rc->avg_frame_qindex[KEY_FRAME],
510                                                rc->kf_boost,
511                                                kf_low, kf_high,
512                                                kf_low_motion_minq,
513                                                kf_high_motion_minq);
514
515       // Allow somewhat lower kf minq with small image formats.
516       if ((cm->width * cm->height) <= (352 * 288)) {
517         q_adj_factor -= 0.25;
518       }
519
520       // Convert the adjustment factor to a qindex delta
521       // on active_best_quality.
522       q_val = vp9_convert_qindex_to_q(active_best_quality);
523       active_best_quality += vp9_compute_qdelta(rc, q_val,
524                                                 q_val * q_adj_factor);
525     }
526   } else if (!rc->is_src_frame_alt_ref &&
527              !cpi->use_svc &&
528              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
529     // Use the lower of active_worst_quality and recent
530     // average Q as basis for GF/ARF best Q limit unless last frame was
531     // a key frame.
532     if (rc->frames_since_key > 1 &&
533         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
534       q = rc->avg_frame_qindex[INTER_FRAME];
535     } else {
536       q = active_worst_quality;
537     }
538     active_best_quality = get_active_quality(
539         q, rc->gfu_boost, gf_low, gf_high,
540         gf_low_motion_minq, gf_high_motion_minq);
541   } else {
542     // Use the lower of active_worst_quality and recent/average Q.
543     if (cm->current_video_frame > 1) {
544       if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
545         active_best_quality = inter_minq[rc->avg_frame_qindex[INTER_FRAME]];
546       else
547         active_best_quality = inter_minq[active_worst_quality];
548     } else {
549       if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
550         active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
551       else
552         active_best_quality = inter_minq[active_worst_quality];
553     }
554   }
555
556   // Clip the active best and worst quality values to limits
557   active_best_quality = clamp(active_best_quality,
558                               rc->best_quality, rc->worst_quality);
559   active_worst_quality = clamp(active_worst_quality,
560                                active_best_quality, rc->worst_quality);
561
562   *top_index = active_worst_quality;
563   *bottom_index = active_best_quality;
564
565 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
566   // Limit Q range for the adaptive loop.
567   if (cm->frame_type == KEY_FRAME &&
568       !rc->this_key_frame_forced  &&
569       !(cm->current_video_frame == 0)) {
570     int qdelta = 0;
571     vp9_clear_system_state();
572     qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
573                                         active_worst_quality, 2.0);
574     *top_index = active_worst_quality + qdelta;
575     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
576   }
577 #endif
578
579   // Special case code to try and match quality with forced key frames
580   if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
581     q = rc->last_boosted_qindex;
582   } else {
583     q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
584                           active_best_quality, active_worst_quality);
585     if (q > *top_index) {
586       // Special case when we are targeting the max allowed rate
587       if (rc->this_frame_target >= rc->max_frame_bandwidth)
588         *top_index = q;
589       else
590         q = *top_index;
591     }
592   }
593   assert(*top_index <= rc->worst_quality &&
594          *top_index >= rc->best_quality);
595   assert(*bottom_index <= rc->worst_quality &&
596          *bottom_index >= rc->best_quality);
597   assert(q <= rc->worst_quality && q >= rc->best_quality);
598   return q;
599 }
600
601 static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
602                                              int *bottom_index,
603                                              int *top_index) {
604   const VP9_COMMON *const cm = &cpi->common;
605   const RATE_CONTROL *const rc = &cpi->rc;
606   const VP9_CONFIG *const oxcf = &cpi->oxcf;
607   int active_best_quality;
608   int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
609   int q;
610
611   if (frame_is_intra_only(cm)) {
612     active_best_quality = rc->best_quality;
613 #if !CONFIG_MULTIPLE_ARF
614     // Handle the special case for key frames forced when we have75 reached
615     // the maximum key frame interval. Here force the Q to a range
616     // based on the ambient Q to reduce the risk of popping.
617     if (rc->this_key_frame_forced) {
618       int qindex = rc->last_boosted_qindex;
619       double last_boosted_q = vp9_convert_qindex_to_q(qindex);
620       int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
621                                             last_boosted_q * 0.75);
622       active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
623     } else if (cm->current_video_frame > 0) {
624       // not first frame of one pass and kf_boost is set
625       double q_adj_factor = 1.0;
626       double q_val;
627
628       active_best_quality = get_active_quality(rc->avg_frame_qindex[KEY_FRAME],
629                                                rc->kf_boost,
630                                                kf_low, kf_high,
631                                                kf_low_motion_minq,
632                                                kf_high_motion_minq);
633
634       // Allow somewhat lower kf minq with small image formats.
635       if ((cm->width * cm->height) <= (352 * 288)) {
636         q_adj_factor -= 0.25;
637       }
638
639       // Convert the adjustment factor to a qindex delta
640       // on active_best_quality.
641       q_val = vp9_convert_qindex_to_q(active_best_quality);
642       active_best_quality += vp9_compute_qdelta(rc, q_val,
643                                                 q_val * q_adj_factor);
644     }
645 #else
646     double current_q;
647     // Force the KF quantizer to be 30% of the active_worst_quality.
648     current_q = vp9_convert_qindex_to_q(active_worst_quality);
649     active_best_quality = active_worst_quality
650         + vp9_compute_qdelta(rc, current_q, current_q * 0.3);
651 #endif
652   } else if (!rc->is_src_frame_alt_ref &&
653              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
654     // Use the lower of active_worst_quality and recent
655     // average Q as basis for GF/ARF best Q limit unless last frame was
656     // a key frame.
657     if (rc->frames_since_key > 1 &&
658         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
659       q = rc->avg_frame_qindex[INTER_FRAME];
660     } else {
661       q = rc->avg_frame_qindex[KEY_FRAME];
662     }
663     // For constrained quality dont allow Q less than the cq level
664     if (oxcf->end_usage == USAGE_CONSTRAINED_QUALITY) {
665       if (q < cpi->cq_target_quality)
666         q = cpi->cq_target_quality;
667       if (rc->frames_since_key > 1) {
668         active_best_quality = get_active_quality(q, rc->gfu_boost,
669                                                  gf_low, gf_high,
670                                                  afq_low_motion_minq,
671                                                  afq_high_motion_minq);
672       } else {
673         active_best_quality = get_active_quality(q, rc->gfu_boost,
674                                                  gf_low, gf_high,
675                                                  gf_low_motion_minq,
676                                                  gf_high_motion_minq);
677       }
678       // Constrained quality use slightly lower active best.
679       active_best_quality = active_best_quality * 15 / 16;
680
681     } else if (oxcf->end_usage == USAGE_CONSTANT_QUALITY) {
682       if (!cpi->refresh_alt_ref_frame) {
683         active_best_quality = cpi->cq_target_quality;
684       } else {
685         if (rc->frames_since_key > 1) {
686           active_best_quality = get_active_quality(
687               q, rc->gfu_boost, gf_low, gf_high,
688               afq_low_motion_minq, afq_high_motion_minq);
689         } else {
690           active_best_quality = get_active_quality(
691               q, rc->gfu_boost, gf_low, gf_high,
692               gf_low_motion_minq, gf_high_motion_minq);
693         }
694       }
695     } else {
696       active_best_quality = get_active_quality(
697           q, rc->gfu_boost, gf_low, gf_high,
698           gf_low_motion_minq, gf_high_motion_minq);
699     }
700   } else {
701     if (oxcf->end_usage == USAGE_CONSTANT_QUALITY) {
702       active_best_quality = cpi->cq_target_quality;
703     } else {
704       // Use the lower of active_worst_quality and recent/average Q.
705       if (cm->current_video_frame > 1)
706         active_best_quality = inter_minq[rc->avg_frame_qindex[INTER_FRAME]];
707       else
708         active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
709       // For the constrained quality mode we don't want
710       // q to fall below the cq level.
711       if ((oxcf->end_usage == USAGE_CONSTRAINED_QUALITY) &&
712           (active_best_quality < cpi->cq_target_quality)) {
713         // If we are strongly undershooting the target rate in the last
714         // frames then use the user passed in cq value not the auto
715         // cq value.
716         if (rc->rolling_actual_bits < rc->min_frame_bandwidth)
717           active_best_quality = oxcf->cq_level;
718         else
719           active_best_quality = cpi->cq_target_quality;
720       }
721     }
722   }
723
724   // Clip the active best and worst quality values to limits
725   active_best_quality = clamp(active_best_quality,
726                               rc->best_quality, rc->worst_quality);
727   active_worst_quality = clamp(active_worst_quality,
728                                active_best_quality, rc->worst_quality);
729
730   *top_index = active_worst_quality;
731   *bottom_index = active_best_quality;
732
733 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
734   {
735     int qdelta = 0;
736     vp9_clear_system_state();
737
738     // Limit Q range for the adaptive loop.
739     if (cm->frame_type == KEY_FRAME &&
740         !rc->this_key_frame_forced &&
741         !(cm->current_video_frame == 0)) {
742       qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
743                                           active_worst_quality, 2.0);
744     } else if (!rc->is_src_frame_alt_ref &&
745                (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
746       qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
747                                           active_worst_quality, 1.75);
748     }
749     *top_index = active_worst_quality + qdelta;
750     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
751   }
752 #endif
753
754   if (oxcf->end_usage == USAGE_CONSTANT_QUALITY) {
755     q = active_best_quality;
756   // Special case code to try and match quality with forced key frames
757   } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
758     q = rc->last_boosted_qindex;
759   } else {
760     q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
761                           active_best_quality, active_worst_quality);
762     if (q > *top_index) {
763       // Special case when we are targeting the max allowed rate
764       if (rc->this_frame_target >= rc->max_frame_bandwidth)
765         *top_index = q;
766       else
767         q = *top_index;
768     }
769   }
770 #if CONFIG_MULTIPLE_ARF
771   // Force the quantizer determined by the coding order pattern.
772   if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
773       cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
774     double new_q;
775     double current_q = vp9_convert_qindex_to_q(active_worst_quality);
776     int level = cpi->this_frame_weight;
777     assert(level >= 0);
778     new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
779     q = active_worst_quality +
780         vp9_compute_qdelta(rc, current_q, new_q);
781
782     *bottom_index = q;
783     *top_index    = q;
784     printf("frame:%d q:%d\n", cm->current_video_frame, q);
785   }
786 #endif
787   assert(*top_index <= rc->worst_quality &&
788          *top_index >= rc->best_quality);
789   assert(*bottom_index <= rc->worst_quality &&
790          *bottom_index >= rc->best_quality);
791   assert(q <= rc->worst_quality && q >= rc->best_quality);
792   return q;
793 }
794
795 static int rc_pick_q_and_bounds_two_pass(const VP9_COMP *cpi,
796                                          int *bottom_index,
797                                          int *top_index) {
798   const VP9_COMMON *const cm = &cpi->common;
799   const RATE_CONTROL *const rc = &cpi->rc;
800   const VP9_CONFIG *const oxcf = &cpi->oxcf;
801   int active_best_quality;
802   int active_worst_quality = cpi->twopass.active_worst_quality;
803   int q;
804
805   if (frame_is_intra_only(cm)) {
806 #if !CONFIG_MULTIPLE_ARF
807     // Handle the special case for key frames forced when we have75 reached
808     // the maximum key frame interval. Here force the Q to a range
809     // based on the ambient Q to reduce the risk of popping.
810     if (rc->this_key_frame_forced) {
811       int qindex = rc->last_boosted_qindex;
812       double last_boosted_q = vp9_convert_qindex_to_q(qindex);
813       int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
814                                             last_boosted_q * 0.75);
815       active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
816     } else {
817       // Not forced keyframe.
818       double q_adj_factor = 1.0;
819       double q_val;
820       // Baseline value derived from cpi->active_worst_quality and kf boost.
821       active_best_quality = get_active_quality(active_worst_quality,
822                                                rc->kf_boost,
823                                                kf_low, kf_high,
824                                                kf_low_motion_minq,
825                                                kf_high_motion_minq);
826
827       // Allow somewhat lower kf minq with small image formats.
828       if ((cm->width * cm->height) <= (352 * 288)) {
829         q_adj_factor -= 0.25;
830       }
831
832       // Make a further adjustment based on the kf zero motion measure.
833       q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
834
835       // Convert the adjustment factor to a qindex delta
836       // on active_best_quality.
837       q_val = vp9_convert_qindex_to_q(active_best_quality);
838       active_best_quality += vp9_compute_qdelta(rc, q_val,
839                                                 q_val * q_adj_factor);
840     }
841 #else
842     double current_q;
843     // Force the KF quantizer to be 30% of the active_worst_quality.
844     current_q = vp9_convert_qindex_to_q(active_worst_quality);
845     active_best_quality = active_worst_quality
846         + vp9_compute_qdelta(rc, current_q, current_q * 0.3);
847 #endif
848   } else if (!rc->is_src_frame_alt_ref &&
849              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
850     // Use the lower of active_worst_quality and recent
851     // average Q as basis for GF/ARF best Q limit unless last frame was
852     // a key frame.
853     if (rc->frames_since_key > 1 &&
854         rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
855       q = rc->avg_frame_qindex[INTER_FRAME];
856     } else {
857       q = active_worst_quality;
858     }
859     // For constrained quality dont allow Q less than the cq level
860     if (oxcf->end_usage == USAGE_CONSTRAINED_QUALITY) {
861       if (q < cpi->cq_target_quality)
862         q = cpi->cq_target_quality;
863       if (rc->frames_since_key > 1) {
864         active_best_quality = get_active_quality(q, rc->gfu_boost,
865                                                  gf_low, gf_high,
866                                                  afq_low_motion_minq,
867                                                  afq_high_motion_minq);
868       } else {
869         active_best_quality = get_active_quality(q, rc->gfu_boost,
870                                                  gf_low, gf_high,
871                                                  gf_low_motion_minq,
872                                                  gf_high_motion_minq);
873       }
874       // Constrained quality use slightly lower active best.
875       active_best_quality = active_best_quality * 15 / 16;
876
877     } else if (oxcf->end_usage == USAGE_CONSTANT_QUALITY) {
878       if (!cpi->refresh_alt_ref_frame) {
879         active_best_quality = cpi->cq_target_quality;
880       } else {
881         if (rc->frames_since_key > 1) {
882           active_best_quality = get_active_quality(
883               q, rc->gfu_boost, gf_low, gf_high,
884               afq_low_motion_minq, afq_high_motion_minq);
885         } else {
886           active_best_quality = get_active_quality(
887               q, rc->gfu_boost, gf_low, gf_high,
888               gf_low_motion_minq, gf_high_motion_minq);
889         }
890       }
891     } else {
892       active_best_quality = get_active_quality(
893           q, rc->gfu_boost, gf_low, gf_high,
894           gf_low_motion_minq, gf_high_motion_minq);
895     }
896   } else {
897     if (oxcf->end_usage == USAGE_CONSTANT_QUALITY) {
898       active_best_quality = cpi->cq_target_quality;
899     } else {
900       active_best_quality = inter_minq[active_worst_quality];
901
902       // For the constrained quality mode we don't want
903       // q to fall below the cq level.
904       if ((oxcf->end_usage == USAGE_CONSTRAINED_QUALITY) &&
905           (active_best_quality < cpi->cq_target_quality)) {
906         // If we are strongly undershooting the target rate in the last
907         // frames then use the user passed in cq value not the auto
908         // cq value.
909         if (rc->rolling_actual_bits < rc->min_frame_bandwidth)
910           active_best_quality = oxcf->cq_level;
911         else
912           active_best_quality = cpi->cq_target_quality;
913       }
914     }
915   }
916
917   // Clip the active best and worst quality values to limits.
918   active_best_quality = clamp(active_best_quality,
919                               rc->best_quality, rc->worst_quality);
920   active_worst_quality = clamp(active_worst_quality,
921                                active_best_quality, rc->worst_quality);
922
923   *top_index = active_worst_quality;
924   *bottom_index = active_best_quality;
925
926 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
927   {
928     int qdelta = 0;
929     vp9_clear_system_state();
930
931     // Limit Q range for the adaptive loop.
932     if (cm->frame_type == KEY_FRAME && !rc->this_key_frame_forced) {
933       qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
934                                           active_worst_quality, 2.0);
935     } else if (!rc->is_src_frame_alt_ref &&
936                (oxcf->end_usage != USAGE_STREAM_FROM_SERVER) &&
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     }
941     *top_index = active_worst_quality + qdelta;
942     *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
943   }
944 #endif
945
946   if (oxcf->end_usage == USAGE_CONSTANT_QUALITY) {
947     q = active_best_quality;
948   // Special case code to try and match quality with forced key frames.
949   } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
950     q = rc->last_boosted_qindex;
951   } else {
952     q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
953                           active_best_quality, active_worst_quality);
954     if (q > *top_index) {
955       // Special case when we are targeting the max allowed rate.
956       if (rc->this_frame_target >= rc->max_frame_bandwidth)
957         *top_index = q;
958       else
959         q = *top_index;
960     }
961   }
962 #if CONFIG_MULTIPLE_ARF
963   // Force the quantizer determined by the coding order pattern.
964   if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
965       cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
966     double new_q;
967     double current_q = vp9_convert_qindex_to_q(active_worst_quality);
968     int level = cpi->this_frame_weight;
969     assert(level >= 0);
970     new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
971     q = active_worst_quality +
972         vp9_compute_qdelta(rc, current_q, new_q);
973
974     *bottom_index = q;
975     *top_index    = q;
976     printf("frame:%d q:%d\n", cm->current_video_frame, q);
977   }
978 #endif
979   assert(*top_index <= rc->worst_quality &&
980          *top_index >= rc->best_quality);
981   assert(*bottom_index <= rc->worst_quality &&
982          *bottom_index >= rc->best_quality);
983   assert(q <= rc->worst_quality && q >= rc->best_quality);
984   return q;
985 }
986
987 int vp9_rc_pick_q_and_bounds(const VP9_COMP *cpi,
988                              int *bottom_index, int *top_index) {
989   int q;
990   if (cpi->pass == 0) {
991     if (cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER)
992       q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
993     else
994       q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
995   } else {
996     q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
997   }
998
999   // Q of 0 is disabled because we force tx size to be
1000   // 16x16...
1001   if (cpi->sf.use_nonrd_pick_mode) {
1002     if (q == 0)
1003       q++;
1004     if (cpi->sf.force_frame_boost == 1)
1005       q -= cpi->sf.max_delta_qindex;
1006
1007     if (q < *bottom_index)
1008       *bottom_index = q;
1009     else if (q > *top_index)
1010       *top_index = q;
1011   }
1012   return q;
1013 }
1014
1015 void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi,
1016                                       int this_frame_target,
1017                                       int *frame_under_shoot_limit,
1018                                       int *frame_over_shoot_limit) {
1019   // Set-up bounds on acceptable frame size:
1020   if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
1021     *frame_under_shoot_limit = 0;
1022     *frame_over_shoot_limit  = INT_MAX;
1023   } else {
1024     int recode_tolerance =
1025       (cpi->sf.recode_tolerance * this_frame_target) / 100;
1026
1027     *frame_over_shoot_limit = this_frame_target + recode_tolerance;
1028     *frame_under_shoot_limit = this_frame_target - recode_tolerance;
1029
1030     // For very small rate targets where the fractional adjustment
1031     // may be tiny make sure there is at least a minimum range.
1032     *frame_over_shoot_limit += 200;
1033     *frame_under_shoot_limit -= 200;
1034     if (*frame_under_shoot_limit < 0)
1035       *frame_under_shoot_limit = 0;
1036
1037     // Clip to maximum allowed rate for a frame.
1038     if (*frame_over_shoot_limit > cpi->rc.max_frame_bandwidth) {
1039       *frame_over_shoot_limit = cpi->rc.max_frame_bandwidth;
1040     }
1041   }
1042 }
1043
1044 void vp9_rc_set_frame_target(VP9_COMP *cpi, int target) {
1045   const VP9_COMMON *const cm = &cpi->common;
1046   RATE_CONTROL *const rc = &cpi->rc;
1047
1048   rc->this_frame_target = target;
1049   // Target rate per SB64 (including partial SB64s.
1050   rc->sb64_target_rate = ((int64_t)rc->this_frame_target * 64 * 64) /
1051                              (cm->width * cm->height);
1052 }
1053
1054 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
1055   // this frame refreshes means next frames don't unless specified by user
1056   RATE_CONTROL *const rc = &cpi->rc;
1057   rc->frames_since_golden = 0;
1058
1059 #if CONFIG_MULTIPLE_ARF
1060   if (!cpi->multi_arf_enabled)
1061 #endif
1062     // Clear the alternate reference update pending flag.
1063     rc->source_alt_ref_pending = 0;
1064
1065   // Set the alternate reference frame active flag
1066   rc->source_alt_ref_active = 1;
1067 }
1068
1069 static void update_golden_frame_stats(VP9_COMP *cpi) {
1070   RATE_CONTROL *const rc = &cpi->rc;
1071
1072   // Update the Golden frame usage counts.
1073   if (cpi->refresh_golden_frame) {
1074     // this frame refreshes means next frames don't unless specified by user
1075     rc->frames_since_golden = 0;
1076
1077     if (!rc->source_alt_ref_pending)
1078       rc->source_alt_ref_active = 0;
1079
1080     // Decrement count down till next gf
1081     if (rc->frames_till_gf_update_due > 0)
1082       rc->frames_till_gf_update_due--;
1083
1084   } else if (!cpi->refresh_alt_ref_frame) {
1085     // Decrement count down till next gf
1086     if (rc->frames_till_gf_update_due > 0)
1087       rc->frames_till_gf_update_due--;
1088
1089     rc->frames_since_golden++;
1090   }
1091 }
1092
1093 void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
1094   const VP9_COMMON *const cm = &cpi->common;
1095   const VP9_CONFIG *const oxcf = &cpi->oxcf;
1096   RATE_CONTROL *const rc = &cpi->rc;
1097   const int qindex = cm->base_qindex;
1098
1099   // Update rate control heuristics
1100   rc->projected_frame_size = (int)(bytes_used << 3);
1101
1102   // Post encode loop adjustment of Q prediction.
1103   vp9_rc_update_rate_correction_factors(
1104       cpi, (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF ||
1105             oxcf->end_usage == USAGE_STREAM_FROM_SERVER) ? 2 : 0);
1106
1107   // Keep a record of last Q and ambient average Q.
1108   if (cm->frame_type == KEY_FRAME) {
1109     rc->last_q[KEY_FRAME] = qindex;
1110     rc->avg_frame_qindex[KEY_FRAME] =
1111         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1112   } else if (!rc->is_src_frame_alt_ref &&
1113              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) &&
1114              !(cpi->use_svc && oxcf->end_usage == USAGE_STREAM_FROM_SERVER)) {
1115     rc->last_q[2] = qindex;
1116     rc->avg_frame_qindex[2] =
1117         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[2] + qindex, 2);
1118   } else {
1119     rc->last_q[INTER_FRAME] = qindex;
1120     rc->avg_frame_qindex[INTER_FRAME] =
1121         ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1122     rc->ni_frames++;
1123     rc->tot_q += vp9_convert_qindex_to_q(qindex);
1124     rc->avg_q = rc->tot_q / rc->ni_frames;
1125     // Calculate the average Q for normal inter frames (not key or GFU frames).
1126     rc->ni_tot_qi += qindex;
1127     rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1128   }
1129
1130   // Keep record of last boosted (KF/KF/ARF) Q value.
1131   // If the current frame is coded at a lower Q then we also update it.
1132   // If all mbs in this group are skipped only update if the Q value is
1133   // better than that already stored.
1134   // This is used to help set quality in forced key frames to reduce popping
1135   if ((qindex < rc->last_boosted_qindex) ||
1136       ((cpi->static_mb_pct < 100) &&
1137        ((cm->frame_type == KEY_FRAME) || cpi->refresh_alt_ref_frame ||
1138         (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1139     rc->last_boosted_qindex = qindex;
1140   }
1141
1142   update_buffer_level(cpi, rc->projected_frame_size);
1143
1144   // Rolling monitors of whether we are over or underspending used to help
1145   // regulate min and Max Q in two pass.
1146   if (cm->frame_type != KEY_FRAME) {
1147     rc->rolling_target_bits = ROUND_POWER_OF_TWO(
1148         rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1149     rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
1150         rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1151     rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
1152         rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1153     rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
1154         rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
1155   }
1156
1157   // Actual bits spent
1158   rc->total_actual_bits += rc->projected_frame_size;
1159   rc->total_target_bits += (cm->show_frame ? rc->av_per_frame_bandwidth : 0);
1160
1161   rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1162
1163   if (oxcf->play_alternate && cpi->refresh_alt_ref_frame &&
1164       (cm->frame_type != KEY_FRAME))
1165     // Update the alternate reference frame stats as appropriate.
1166     update_alt_ref_frame_stats(cpi);
1167   else
1168     // Update the Golden frame stats as appropriate.
1169     update_golden_frame_stats(cpi);
1170
1171   if (cm->frame_type == KEY_FRAME)
1172     rc->frames_since_key = 0;
1173   if (cm->show_frame) {
1174     rc->frames_since_key++;
1175     rc->frames_to_key--;
1176   }
1177 }
1178
1179 void vp9_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
1180   // Update buffer level with zero size, update frame counters, and return.
1181   update_buffer_level(cpi, 0);
1182   cpi->common.last_frame_type = cpi->common.frame_type;
1183   cpi->rc.frames_since_key++;
1184   cpi->rc.frames_to_key--;
1185 }
1186
1187 static int test_for_kf_one_pass(VP9_COMP *cpi) {
1188   // Placeholder function for auto key frame
1189   return 0;
1190 }
1191 // Use this macro to turn on/off use of alt-refs in one-pass mode.
1192 #define USE_ALTREF_FOR_ONE_PASS   1
1193
1194 static int calc_pframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1195   static const int af_ratio = 10;
1196   const RATE_CONTROL *const rc = &cpi->rc;
1197   int target;
1198 #if USE_ALTREF_FOR_ONE_PASS
1199   target = (!rc->is_src_frame_alt_ref &&
1200             (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) ?
1201       (rc->av_per_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
1202       (rc->baseline_gf_interval + af_ratio - 1) :
1203       (rc->av_per_frame_bandwidth * rc->baseline_gf_interval) /
1204       (rc->baseline_gf_interval + af_ratio - 1);
1205 #else
1206   target = rc->av_per_frame_bandwidth;
1207 #endif
1208   return vp9_rc_clamp_pframe_target_size(cpi, target);
1209 }
1210
1211 static int calc_iframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1212   static const int kf_ratio = 25;
1213   const RATE_CONTROL *rc = &cpi->rc;
1214   int target = rc->av_per_frame_bandwidth * kf_ratio;
1215   return vp9_rc_clamp_iframe_target_size(cpi, target);
1216 }
1217
1218 void vp9_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
1219   VP9_COMMON *const cm = &cpi->common;
1220   RATE_CONTROL *const rc = &cpi->rc;
1221   int target;
1222   if (!cpi->refresh_alt_ref_frame &&
1223       (cm->current_video_frame == 0 ||
1224        (cm->frame_flags & FRAMEFLAGS_KEY) ||
1225        rc->frames_to_key == 0 ||
1226        (cpi->oxcf.auto_key && test_for_kf_one_pass(cpi)))) {
1227     cm->frame_type = KEY_FRAME;
1228     rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1229                                 rc->frames_to_key == 0;
1230     rc->frames_to_key = cpi->key_frame_frequency;
1231     rc->kf_boost = DEFAULT_KF_BOOST;
1232     rc->source_alt_ref_active = 0;
1233   } else {
1234     cm->frame_type = INTER_FRAME;
1235   }
1236   if (rc->frames_till_gf_update_due == 0) {
1237     rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1238     rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1239     // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1240     if (rc->frames_till_gf_update_due > rc->frames_to_key)
1241       rc->frames_till_gf_update_due = rc->frames_to_key;
1242     cpi->refresh_golden_frame = 1;
1243     rc->source_alt_ref_pending = USE_ALTREF_FOR_ONE_PASS;
1244     rc->gfu_boost = DEFAULT_GF_BOOST;
1245   }
1246   if (cm->frame_type == KEY_FRAME)
1247     target = calc_iframe_target_size_one_pass_vbr(cpi);
1248   else
1249     target = calc_pframe_target_size_one_pass_vbr(cpi);
1250   vp9_rc_set_frame_target(cpi, target);
1251 }
1252
1253 static int calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1254   const VP9_CONFIG *oxcf = &cpi->oxcf;
1255   const RATE_CONTROL *rc = &cpi->rc;
1256   const SVC *const svc = &cpi->svc;
1257   const int64_t diff = oxcf->optimal_buffer_level - rc->buffer_level;
1258   const int64_t one_pct_bits = 1 + oxcf->optimal_buffer_level / 100;
1259   int min_frame_target = MAX(rc->av_per_frame_bandwidth >> 4,
1260                              FRAME_OVERHEAD_BITS);
1261   int target = rc->av_per_frame_bandwidth;
1262   if (svc->number_temporal_layers > 1 &&
1263       oxcf->end_usage == USAGE_STREAM_FROM_SERVER) {
1264     // Note that for layers, av_per_frame_bandwidth is the cumulative
1265     // per-frame-bandwidth. For the target size of this frame, use the
1266     // layer average frame size (i.e., non-cumulative per-frame-bw).
1267     int current_temporal_layer = svc->temporal_layer_id;
1268     const LAYER_CONTEXT *lc = &svc->layer_context[current_temporal_layer];
1269     target = lc->avg_frame_size;
1270     min_frame_target = MAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
1271   }
1272   if (diff > 0) {
1273     // Lower the target bandwidth for this frame.
1274     const int pct_low = (int)MIN(diff / one_pct_bits, oxcf->under_shoot_pct);
1275     target -= (target * pct_low) / 200;
1276   } else if (diff < 0) {
1277     // Increase the target bandwidth for this frame.
1278     const int pct_high = (int)MIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
1279     target += (target * pct_high) / 200;
1280   }
1281   return MAX(min_frame_target, target);
1282 }
1283
1284 static int calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1285   const RATE_CONTROL *rc = &cpi->rc;
1286   const VP9_CONFIG *oxcf = &cpi->oxcf;
1287   const SVC *const svc = &cpi->svc;
1288   int target;
1289   if (cpi->common.current_video_frame == 0) {
1290     target = ((cpi->oxcf.starting_buffer_level / 2) > INT_MAX)
1291       ? INT_MAX : (int)(cpi->oxcf.starting_buffer_level / 2);
1292   } else {
1293     int kf_boost = 32;
1294     double framerate = oxcf->framerate;
1295     if (svc->number_temporal_layers > 1 &&
1296         oxcf->end_usage == USAGE_STREAM_FROM_SERVER) {
1297       // Use the layer framerate for temporal layers CBR mode.
1298       const LAYER_CONTEXT *lc = &svc->layer_context[svc->temporal_layer_id];
1299       framerate = lc->framerate;
1300     }
1301     kf_boost = MAX(kf_boost, (int)(2 * framerate - 16));
1302     if (rc->frames_since_key <  framerate / 2) {
1303       kf_boost = (int)(kf_boost * rc->frames_since_key /
1304                        (framerate / 2));
1305     }
1306     target = ((16 + kf_boost) * rc->av_per_frame_bandwidth) >> 4;
1307   }
1308   return vp9_rc_clamp_iframe_target_size(cpi, target);
1309 }
1310
1311 void vp9_rc_get_svc_params(VP9_COMP *cpi) {
1312   VP9_COMMON *const cm = &cpi->common;
1313   RATE_CONTROL *const rc = &cpi->rc;
1314   int target = rc->av_per_frame_bandwidth;
1315   if ((cm->current_video_frame == 0) ||
1316       (cm->frame_flags & FRAMEFLAGS_KEY) ||
1317       (cpi->oxcf.auto_key && (rc->frames_since_key %
1318                               cpi->key_frame_frequency == 0))) {
1319     cm->frame_type = KEY_FRAME;
1320     rc->source_alt_ref_active = 0;
1321     if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
1322       target = calc_iframe_target_size_one_pass_cbr(cpi);
1323     }
1324   } else {
1325     cm->frame_type = INTER_FRAME;
1326     if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
1327       target = calc_pframe_target_size_one_pass_cbr(cpi);
1328     }
1329   }
1330   vp9_rc_set_frame_target(cpi, target);
1331   rc->frames_till_gf_update_due = INT_MAX;
1332   rc->baseline_gf_interval = INT_MAX;
1333 }
1334
1335 void vp9_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
1336   VP9_COMMON *const cm = &cpi->common;
1337   RATE_CONTROL *const rc = &cpi->rc;
1338   int target;
1339   if ((cm->current_video_frame == 0 ||
1340       (cm->frame_flags & FRAMEFLAGS_KEY) ||
1341       rc->frames_to_key == 0 ||
1342       (cpi->oxcf.auto_key && test_for_kf_one_pass(cpi)))) {
1343     cm->frame_type = KEY_FRAME;
1344     rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1345                                 rc->frames_to_key == 0;
1346     rc->frames_to_key = cpi->key_frame_frequency;
1347     rc->kf_boost = DEFAULT_KF_BOOST;
1348     rc->source_alt_ref_active = 0;
1349     target = calc_iframe_target_size_one_pass_cbr(cpi);
1350   } else {
1351     cm->frame_type = INTER_FRAME;
1352     target = calc_pframe_target_size_one_pass_cbr(cpi);
1353   }
1354   vp9_rc_set_frame_target(cpi, target);
1355   // Don't use gf_update by default in CBR mode.
1356   rc->frames_till_gf_update_due = INT_MAX;
1357   rc->baseline_gf_interval = INT_MAX;
1358 }
1359
1360 int vp9_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget) {
1361   int start_index = rc->worst_quality;
1362   int target_index = rc->worst_quality;
1363   int i;
1364
1365   // Convert the average q value to an index.
1366   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1367     start_index = i;
1368     if (vp9_convert_qindex_to_q(i) >= qstart)
1369       break;
1370   }
1371
1372   // Convert the q target to an index
1373   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1374     target_index = i;
1375     if (vp9_convert_qindex_to_q(i) >= qtarget)
1376       break;
1377   }
1378
1379   return target_index - start_index;
1380 }
1381
1382 int vp9_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
1383                                int qindex, double rate_target_ratio) {
1384   int target_index = rc->worst_quality;
1385   int i;
1386
1387   // Look up the current projected bits per block for the base index
1388   const int base_bits_per_mb = vp9_rc_bits_per_mb(frame_type, qindex, 1.0);
1389
1390   // Find the target bits per mb based on the base value and given ratio.
1391   const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
1392
1393   // Convert the q target to an index
1394   for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1395     target_index = i;
1396     if (vp9_rc_bits_per_mb(frame_type, i, 1.0) <= target_bits_per_mb )
1397       break;
1398   }
1399
1400   return target_index - qindex;
1401 }