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