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