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