Upstream version 5.34.92.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   // interval before next GF
188   cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
189   /* All buffers are implicitly updated on key frames. */
190   cpi->refresh_golden_frame = 1;
191   cpi->refresh_alt_ref_frame = 1;
192 }
193
194 void vp9_setup_inter_frame(VP9_COMP *cpi) {
195   VP9_COMMON *cm = &cpi->common;
196   if (cm->error_resilient_mode || cm->intra_only)
197     vp9_setup_past_independence(cm);
198
199   assert(cm->frame_context_idx < FRAME_CONTEXTS);
200   cm->fc = cm->frame_contexts[cm->frame_context_idx];
201 }
202
203 static int estimate_bits_at_q(int frame_kind, int q, int mbs,
204                               double correction_factor) {
205   const int bpm = (int)(vp9_rc_bits_per_mb(frame_kind, q, correction_factor));
206
207   // Attempt to retain reasonable accuracy without overflow. The cutoff is
208   // chosen such that the maximum product of Bpm and MBs fits 31 bits. The
209   // largest Bpm takes 20 bits.
210   return (mbs > (1 << 11)) ? (bpm >> BPER_MB_NORMBITS) * mbs
211                            : (bpm * mbs) >> BPER_MB_NORMBITS;
212 }
213
214
215 static void calc_iframe_target_size(VP9_COMP *cpi) {
216   // boost defaults to half second
217   int target;
218
219   // Clear down mmx registers to allow floating point in what follows
220   vp9_clear_system_state();  // __asm emms;
221
222   // New Two pass RC
223   target = cpi->rc.per_frame_bandwidth;
224
225   // For 1-pass.
226   if (cpi->pass == 0) {
227     if (cpi->common.current_video_frame == 0) {
228       target = cpi->oxcf.starting_buffer_level / 2;
229     } else {
230       // TODO(marpan): Add in adjustment based on Q.
231       // If this keyframe was forced, use a more recent Q estimate.
232       // int Q = (cpi->common.frame_flags & FRAMEFLAGS_KEY) ?
233       //    cpi->rc.avg_frame_qindex : cpi->rc.ni_av_qi;
234       int initial_boost = 32;
235       // Boost depends somewhat on frame rate.
236       int kf_boost = MAX(initial_boost, (int)(2 * cpi->output_framerate - 16));
237       // Adjustment up based on q: need to fix.
238       // kf_boost = kf_boost * kfboost_qadjust(Q) / 100;
239       // Frame separation adjustment (down).
240       if (cpi->rc.frames_since_key  < cpi->output_framerate / 2) {
241         kf_boost = (int)(kf_boost * cpi->rc.frames_since_key /
242             (cpi->output_framerate / 2));
243       }
244       kf_boost = (kf_boost < 16) ? 16 : kf_boost;
245       target = ((16 + kf_boost) * cpi->rc.per_frame_bandwidth) >> 4;
246     }
247     cpi->rc.active_worst_quality = cpi->rc.worst_quality;
248   }
249
250   if (cpi->oxcf.rc_max_intra_bitrate_pct) {
251     int max_rate = cpi->rc.per_frame_bandwidth
252                  * cpi->oxcf.rc_max_intra_bitrate_pct / 100;
253
254     if (target > max_rate)
255       target = max_rate;
256   }
257   cpi->rc.this_frame_target = target;
258 }
259
260 //  Do the best we can to define the parameters for the next GF based
261 //  on what information we have available.
262 //
263 //  In this experimental code only two pass is supported
264 //  so we just use the interval determined in the two pass code.
265 static void calc_gf_params(VP9_COMP *cpi) {
266   // Set the gf interval
267   cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
268 }
269
270 // Update the buffer level: leaky bucket model.
271 void vp9_update_buffer_level(VP9_COMP *const cpi, int encoded_frame_size) {
272   VP9_COMMON *const cm = &cpi->common;
273   // Non-viewable frames are a special case and are treated as pure overhead.
274   if (!cm->show_frame) {
275     cpi->rc.bits_off_target -= encoded_frame_size;
276   } else {
277     cpi->rc.bits_off_target += cpi->rc.av_per_frame_bandwidth -
278         encoded_frame_size;
279   }
280   // Clip the buffer level to the maximum specified buffer size.
281   if (cpi->rc.bits_off_target > cpi->oxcf.maximum_buffer_size) {
282     cpi->rc.bits_off_target = cpi->oxcf.maximum_buffer_size;
283   }
284   cpi->rc.buffer_level = cpi->rc.bits_off_target;
285 }
286
287 int vp9_drop_frame(VP9_COMP *const cpi) {
288   if (!cpi->oxcf.drop_frames_water_mark) {
289     return 0;
290   } else {
291     if (cpi->rc.buffer_level < 0) {
292       // Always drop if buffer is below 0.
293       return 1;
294     } else {
295       // If buffer is below drop_mark, for now just drop every other frame
296       // (starting with the next frame) until it increases back over drop_mark.
297       int drop_mark = (int)(cpi->oxcf.drop_frames_water_mark *
298           cpi->oxcf.optimal_buffer_level / 100);
299       if ((cpi->rc.buffer_level > drop_mark) &&
300           (cpi->rc.decimation_factor > 0)) {
301         --cpi->rc.decimation_factor;
302       } else if (cpi->rc.buffer_level <= drop_mark &&
303           cpi->rc.decimation_factor == 0) {
304         cpi->rc.decimation_factor = 1;
305       }
306       if (cpi->rc.decimation_factor > 0) {
307         if (cpi->rc.decimation_count > 0) {
308           --cpi->rc.decimation_count;
309           return 1;
310         } else {
311           cpi->rc.decimation_count = cpi->rc.decimation_factor;
312           return 0;
313         }
314       } else {
315         cpi->rc.decimation_count = 0;
316         return 0;
317       }
318     }
319   }
320 }
321
322 // Adjust active_worst_quality level based on buffer level.
323 static int adjust_active_worst_quality_from_buffer_level(const VP9_COMP *cpi) {
324   // Adjust active_worst_quality: If buffer is above the optimal/target level,
325   // bring active_worst_quality down depending on fullness over buffer.
326   // If buffer is below the optimal level, let the active_worst_quality go from
327   // ambient Q (at buffer = optimal level) to worst_quality level
328   // (at buffer = critical level).
329   int active_worst_quality = cpi->rc.active_worst_quality;
330   // Maximum limit for down adjustment, ~20%.
331   int max_adjustment_down = active_worst_quality / 5;
332   // Buffer level below which we push active_worst to worst_quality.
333   int critical_level = cpi->oxcf.optimal_buffer_level >> 2;
334   int adjustment = 0;
335   int buff_lvl_step = 0;
336   if (cpi->rc.buffer_level > cpi->oxcf.optimal_buffer_level) {
337     // Adjust down.
338     if (max_adjustment_down) {
339       buff_lvl_step = (int)((cpi->oxcf.maximum_buffer_size -
340           cpi->oxcf.optimal_buffer_level) / max_adjustment_down);
341       if (buff_lvl_step) {
342         adjustment = (int)((cpi->rc.buffer_level -
343             cpi->oxcf.optimal_buffer_level) / buff_lvl_step);
344       }
345       active_worst_quality -= adjustment;
346     }
347   } else if (cpi->rc.buffer_level > critical_level) {
348     // Adjust up from ambient Q.
349     if (critical_level) {
350       buff_lvl_step = (cpi->oxcf.optimal_buffer_level - critical_level);
351       if (buff_lvl_step) {
352         adjustment =
353             (cpi->rc.worst_quality - cpi->rc.avg_frame_qindex[INTER_FRAME]) *
354             (cpi->oxcf.optimal_buffer_level - cpi->rc.buffer_level) /
355             buff_lvl_step;
356       }
357       active_worst_quality = cpi->rc.avg_frame_qindex[INTER_FRAME] + adjustment;
358     }
359   } else {
360     // Set to worst_quality if buffer is below critical level.
361     active_worst_quality = cpi->rc.worst_quality;
362   }
363   return active_worst_quality;
364 }
365
366 // Adjust target frame size with respect to the buffering constraints:
367 static int target_size_from_buffer_level(const VP9_COMP *cpi) {
368   int this_frame_target = cpi->rc.this_frame_target;
369   int percent_low = 0;
370   int percent_high = 0;
371   int one_percent_bits = (int)(1 + cpi->oxcf.optimal_buffer_level / 100);
372   if (cpi->rc.buffer_level < cpi->oxcf.optimal_buffer_level) {
373     percent_low = (int)((cpi->oxcf.optimal_buffer_level - cpi->rc.buffer_level)
374         / one_percent_bits);
375     if (percent_low > cpi->oxcf.under_shoot_pct) {
376       percent_low = cpi->oxcf.under_shoot_pct;
377     } else if (percent_low < 0) {
378       percent_low = 0;
379     }
380     // Lower the target bandwidth for this frame.
381     this_frame_target -= (this_frame_target * percent_low) / 200;
382   } else  if (cpi->rc.buffer_level > cpi->oxcf.optimal_buffer_level) {
383     percent_high = (int)((cpi->rc.buffer_level - cpi->oxcf.optimal_buffer_level)
384         / one_percent_bits);
385     if (percent_high > cpi->oxcf.over_shoot_pct) {
386       percent_high = cpi->oxcf.over_shoot_pct;
387     } else if (percent_high < 0) {
388       percent_high = 0;
389     }
390     // Increase the target bandwidth for this frame.
391     this_frame_target += (this_frame_target * percent_high) / 200;
392   }
393   return this_frame_target;
394 }
395
396 static void calc_pframe_target_size(VP9_COMP *const cpi) {
397   int min_frame_target = MAX(cpi->rc.min_frame_bandwidth,
398                              cpi->rc.av_per_frame_bandwidth >> 5);
399   if (cpi->refresh_alt_ref_frame) {
400     // Special alt reference frame case
401     // Per frame bit target for the alt ref frame
402     cpi->rc.per_frame_bandwidth = cpi->twopass.gf_bits;
403     cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
404   } else {
405     // Normal frames (gf and inter).
406     cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
407     // Set target frame size based on buffer level, for 1 pass CBR.
408     if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
409       // Need to decide how low min_frame_target should be for 1-pass CBR.
410       // For now, use: cpi->rc.av_per_frame_bandwidth / 16:
411       min_frame_target = MAX(cpi->rc.av_per_frame_bandwidth >> 4,
412                              FRAME_OVERHEAD_BITS);
413       cpi->rc.this_frame_target = target_size_from_buffer_level(cpi);
414       // Adjust qp-max based on buffer level.
415       cpi->rc.active_worst_quality =
416           adjust_active_worst_quality_from_buffer_level(cpi);
417     }
418   }
419
420   // Check that the total sum of adjustments is not above the maximum allowed.
421   // That is, having allowed for the KF and GF penalties, we have not pushed
422   // the current inter-frame target too low. If the adjustment we apply here is
423   // not capable of recovering all the extra bits we have spent in the KF or GF,
424   // then the remainder will have to be recovered over a longer time span via
425   // other buffer / rate control mechanisms.
426   if (cpi->rc.this_frame_target < min_frame_target) {
427     cpi->rc.this_frame_target = min_frame_target;
428   }
429
430   // Adjust target frame size for Golden Frames:
431   if (cpi->refresh_golden_frame) {
432     // If we are using alternate ref instead of gf then do not apply the boost
433     // It will instead be applied to the altref update
434     // Jims modified boost
435     if (!cpi->rc.source_alt_ref_active) {
436       // The spend on the GF is defined in the two pass code
437       // for two pass encodes
438       cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
439     } else {
440       // If there is an active ARF at this location use the minimum
441       // bits on this frame even if it is a constructed arf.
442       // The active maximum quantizer insures that an appropriate
443       // number of bits will be spent if needed for constructed ARFs.
444       cpi->rc.this_frame_target = 0;
445     }
446   }
447 }
448
449 void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi, int damp_var) {
450   const int q = cpi->common.base_qindex;
451   int correction_factor = 100;
452   double rate_correction_factor;
453   double adjustment_limit;
454
455   int projected_size_based_on_q = 0;
456
457   // Clear down mmx registers to allow floating point in what follows
458   vp9_clear_system_state();  // __asm emms;
459
460   if (cpi->common.frame_type == KEY_FRAME) {
461     rate_correction_factor = cpi->rc.key_frame_rate_correction_factor;
462   } else {
463     if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
464       rate_correction_factor = cpi->rc.gf_rate_correction_factor;
465     else
466       rate_correction_factor = cpi->rc.rate_correction_factor;
467   }
468
469   // Work out how big we would have expected the frame to be at this Q given
470   // the current correction factor.
471   // Stay in double to avoid int overflow when values are large
472   projected_size_based_on_q = estimate_bits_at_q(cpi->common.frame_type, q,
473                                                  cpi->common.MBs,
474                                                  rate_correction_factor);
475
476   // Work out a size correction factor.
477   if (projected_size_based_on_q > 0)
478     correction_factor =
479         (100 * cpi->rc.projected_frame_size) / projected_size_based_on_q;
480
481   // More heavily damped adjustment used if we have been oscillating either side
482   // of target.
483   switch (damp_var) {
484     case 0:
485       adjustment_limit = 0.75;
486       break;
487     case 1:
488       adjustment_limit = 0.375;
489       break;
490     case 2:
491     default:
492       adjustment_limit = 0.25;
493       break;
494   }
495
496   if (correction_factor > 102) {
497     // We are not already at the worst allowable quality
498     correction_factor =
499         (int)(100 + ((correction_factor - 100) * adjustment_limit));
500     rate_correction_factor =
501         ((rate_correction_factor * correction_factor) / 100);
502
503     // Keep rate_correction_factor within limits
504     if (rate_correction_factor > MAX_BPB_FACTOR)
505       rate_correction_factor = MAX_BPB_FACTOR;
506   } else if (correction_factor < 99) {
507     // We are not already at the best allowable quality
508     correction_factor =
509         (int)(100 - ((100 - correction_factor) * adjustment_limit));
510     rate_correction_factor =
511         ((rate_correction_factor * correction_factor) / 100);
512
513     // Keep rate_correction_factor within limits
514     if (rate_correction_factor < MIN_BPB_FACTOR)
515       rate_correction_factor = MIN_BPB_FACTOR;
516   }
517
518   if (cpi->common.frame_type == KEY_FRAME) {
519     cpi->rc.key_frame_rate_correction_factor = rate_correction_factor;
520   } else {
521     if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
522       cpi->rc.gf_rate_correction_factor = rate_correction_factor;
523     else
524       cpi->rc.rate_correction_factor = rate_correction_factor;
525   }
526 }
527
528
529 int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
530                       int active_best_quality, int active_worst_quality) {
531   int q = active_worst_quality;
532
533   int i;
534   int last_error = INT_MAX;
535   int target_bits_per_mb;
536   int bits_per_mb_at_this_q;
537   double correction_factor;
538
539   // Select the appropriate correction factor based upon type of frame.
540   if (cpi->common.frame_type == KEY_FRAME) {
541     correction_factor = cpi->rc.key_frame_rate_correction_factor;
542   } else {
543     if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
544       correction_factor = cpi->rc.gf_rate_correction_factor;
545     else
546       correction_factor = cpi->rc.rate_correction_factor;
547   }
548
549   // Calculate required scaling factor based on target frame size and size of
550   // frame produced using previous Q.
551   if (target_bits_per_frame >= (INT_MAX >> BPER_MB_NORMBITS))
552     target_bits_per_mb =
553         (target_bits_per_frame / cpi->common.MBs)
554         << BPER_MB_NORMBITS;  // Case where we would overflow int
555   else
556     target_bits_per_mb =
557         (target_bits_per_frame << BPER_MB_NORMBITS) / cpi->common.MBs;
558
559   i = active_best_quality;
560
561   do {
562     bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cpi->common.frame_type, i,
563                                                     correction_factor);
564
565     if (bits_per_mb_at_this_q <= target_bits_per_mb) {
566       if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
567         q = i;
568       else
569         q = i - 1;
570
571       break;
572     } else {
573       last_error = bits_per_mb_at_this_q - target_bits_per_mb;
574     }
575   } while (++i <= active_worst_quality);
576
577   return q;
578 }
579
580 static int get_active_quality(int q,
581                               int gfu_boost,
582                               int low,
583                               int high,
584                               int *low_motion_minq,
585                               int *high_motion_minq) {
586   int active_best_quality;
587   if (gfu_boost > high) {
588     active_best_quality = low_motion_minq[q];
589   } else if (gfu_boost < low) {
590     active_best_quality = high_motion_minq[q];
591   } else {
592     const int gap = high - low;
593     const int offset = high - gfu_boost;
594     const int qdiff = high_motion_minq[q] - low_motion_minq[q];
595     const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
596     active_best_quality = low_motion_minq[q] + adjustment;
597   }
598   return active_best_quality;
599 }
600
601 int vp9_rc_pick_q_and_adjust_q_bounds(const VP9_COMP *cpi,
602                                       int *bottom_index,
603                                       int *top_index) {
604   const VP9_COMMON *const cm = &cpi->common;
605   int active_best_quality;
606   int active_worst_quality = cpi->rc.active_worst_quality;
607   int q;
608
609   if (frame_is_intra_only(cm)) {
610     active_best_quality = cpi->rc.best_quality;
611 #if !CONFIG_MULTIPLE_ARF
612     // Handle the special case for key frames forced when we have75 reached
613     // the maximum key frame interval. Here force the Q to a range
614     // based on the ambient Q to reduce the risk of popping.
615     if (cpi->rc.this_key_frame_forced) {
616       int delta_qindex;
617       int qindex = cpi->rc.last_boosted_qindex;
618       double last_boosted_q = vp9_convert_qindex_to_q(qindex);
619
620       delta_qindex = vp9_compute_qdelta(cpi, last_boosted_q,
621                                         (last_boosted_q * 0.75));
622       active_best_quality = MAX(qindex + delta_qindex,
623                                 cpi->rc.best_quality);
624     } else if (!(cpi->pass == 0 && cpi->common.current_video_frame == 0)) {
625       // not first frame of one pass
626       double q_adj_factor = 1.0;
627       double q_val;
628
629       // Baseline value derived from cpi->active_worst_quality and kf boost
630       active_best_quality = get_active_quality(active_worst_quality,
631                                                cpi->rc.kf_boost,
632                                                kf_low, kf_high,
633                                                kf_low_motion_minq,
634                                                kf_high_motion_minq);
635
636       // Allow somewhat lower kf minq with small image formats.
637       if ((cm->width * cm->height) <= (352 * 288)) {
638         q_adj_factor -= 0.25;
639       }
640
641       // Make a further adjustment based on the kf zero motion measure.
642       q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
643
644       // Convert the adjustment factor to a qindex delta
645       // on active_best_quality.
646       q_val = vp9_convert_qindex_to_q(active_best_quality);
647       active_best_quality +=
648           vp9_compute_qdelta(cpi, q_val, (q_val * q_adj_factor));
649     }
650 #else
651     double current_q;
652     // Force the KF quantizer to be 30% of the active_worst_quality.
653     current_q = vp9_convert_qindex_to_q(active_worst_quality);
654     active_best_quality = active_worst_quality
655         + vp9_compute_qdelta(cpi, current_q, current_q * 0.3);
656 #endif
657   } else if (!cpi->rc.is_src_frame_alt_ref &&
658              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
659
660     // Use the lower of active_worst_quality and recent
661     // average Q as basis for GF/ARF best Q limit unless last frame was
662     // a key frame.
663     if (cpi->rc.frames_since_key > 1 &&
664         cpi->rc.avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
665       q = cpi->rc.avg_frame_qindex[INTER_FRAME];
666     } else {
667       q = active_worst_quality;
668     }
669     // For constrained quality dont allow Q less than the cq level
670     if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
671       if (q < cpi->cq_target_quality)
672         q = cpi->cq_target_quality;
673       if (cpi->rc.frames_since_key > 1) {
674         active_best_quality = get_active_quality(q, cpi->rc.gfu_boost,
675                                                  gf_low, gf_high,
676                                                  afq_low_motion_minq,
677                                                  afq_high_motion_minq);
678       } else {
679         active_best_quality = get_active_quality(q, cpi->rc.gfu_boost,
680                                                  gf_low, gf_high,
681                                                  gf_low_motion_minq,
682                                                  gf_high_motion_minq);
683       }
684       // Constrained quality use slightly lower active best.
685       active_best_quality = active_best_quality * 15 / 16;
686
687     } else if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
688       if (!cpi->refresh_alt_ref_frame) {
689         active_best_quality = cpi->cq_target_quality;
690       } else {
691         if (cpi->rc.frames_since_key > 1) {
692           active_best_quality = get_active_quality(
693               q, cpi->rc.gfu_boost, gf_low, gf_high,
694               afq_low_motion_minq, afq_high_motion_minq);
695         } else {
696           active_best_quality = get_active_quality(
697               q, cpi->rc.gfu_boost, gf_low, gf_high,
698               gf_low_motion_minq, gf_high_motion_minq);
699         }
700       }
701     } else {
702       active_best_quality = get_active_quality(
703           q, cpi->rc.gfu_boost, gf_low, gf_high,
704           gf_low_motion_minq, gf_high_motion_minq);
705     }
706   } else {
707     if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
708       active_best_quality = cpi->cq_target_quality;
709     } else {
710       if (cpi->pass == 0 &&
711           cpi->rc.avg_frame_qindex[INTER_FRAME] < active_worst_quality)
712         // 1-pass: for now, use the average Q for the active_best, if its lower
713         // than active_worst.
714         active_best_quality = inter_minq[cpi->rc.avg_frame_qindex[INTER_FRAME]];
715       else
716         active_best_quality = inter_minq[active_worst_quality];
717
718       // For the constrained quality mode we don't want
719       // q to fall below the cq level.
720       if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
721           (active_best_quality < cpi->cq_target_quality)) {
722         // If we are strongly undershooting the target rate in the last
723         // frames then use the user passed in cq value not the auto
724         // cq value.
725         if (cpi->rc.rolling_actual_bits < cpi->rc.min_frame_bandwidth)
726           active_best_quality = cpi->oxcf.cq_level;
727         else
728           active_best_quality = cpi->cq_target_quality;
729       }
730     }
731   }
732
733   // Clip the active best and worst quality values to limits
734   if (active_worst_quality > cpi->rc.worst_quality)
735     active_worst_quality = cpi->rc.worst_quality;
736
737   if (active_best_quality < cpi->rc.best_quality)
738     active_best_quality = cpi->rc.best_quality;
739
740   if (active_best_quality > cpi->rc.worst_quality)
741     active_best_quality = cpi->rc.worst_quality;
742
743   if (active_worst_quality < active_best_quality)
744     active_worst_quality = active_best_quality;
745
746   *top_index = active_worst_quality;
747   *bottom_index = active_best_quality;
748
749 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
750   // Limit Q range for the adaptive loop.
751   if (cm->frame_type == KEY_FRAME && !cpi->rc.this_key_frame_forced) {
752     if (!(cpi->pass == 0 && cpi->common.current_video_frame == 0)) {
753       *top_index = active_worst_quality;
754       *top_index =
755           (active_worst_quality + active_best_quality * 3) / 4;
756     }
757   } else if (!cpi->rc.is_src_frame_alt_ref &&
758              (cpi->oxcf.end_usage != USAGE_STREAM_FROM_SERVER) &&
759              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
760     *top_index =
761       (active_worst_quality + active_best_quality) / 2;
762   }
763 #endif
764
765   if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
766     q = active_best_quality;
767   // Special case code to try and match quality with forced key frames
768   } else if ((cm->frame_type == KEY_FRAME) && cpi->rc.this_key_frame_forced) {
769     q = cpi->rc.last_boosted_qindex;
770   } else {
771     q = vp9_rc_regulate_q(cpi, cpi->rc.this_frame_target,
772                           active_best_quality, active_worst_quality);
773     if (q > *top_index)
774       q = *top_index;
775   }
776 #if CONFIG_MULTIPLE_ARF
777   // Force the quantizer determined by the coding order pattern.
778   if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
779       cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
780     double new_q;
781     double current_q = vp9_convert_qindex_to_q(active_worst_quality);
782     int level = cpi->this_frame_weight;
783     assert(level >= 0);
784     new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
785     q = active_worst_quality +
786         vp9_compute_qdelta(cpi, current_q, new_q);
787
788     *bottom_index = q;
789     *top_index    = q;
790     printf("frame:%d q:%d\n", cm->current_video_frame, q);
791   }
792 #endif
793   return q;
794 }
795
796 void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi,
797                                       int this_frame_target,
798                                       int *frame_under_shoot_limit,
799                                       int *frame_over_shoot_limit) {
800   // Set-up bounds on acceptable frame size:
801   if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
802     *frame_under_shoot_limit = 0;
803     *frame_over_shoot_limit  = INT_MAX;
804   } else {
805     if (cpi->common.frame_type == KEY_FRAME) {
806       *frame_over_shoot_limit  = this_frame_target * 9 / 8;
807       *frame_under_shoot_limit = this_frame_target * 7 / 8;
808     } else {
809       if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) {
810         *frame_over_shoot_limit  = this_frame_target * 9 / 8;
811         *frame_under_shoot_limit = this_frame_target * 7 / 8;
812       } else {
813         // Stron overshoot limit for constrained quality
814         if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
815           *frame_over_shoot_limit  = this_frame_target * 11 / 8;
816           *frame_under_shoot_limit = this_frame_target * 2 / 8;
817         } else {
818           *frame_over_shoot_limit  = this_frame_target * 11 / 8;
819           *frame_under_shoot_limit = this_frame_target * 5 / 8;
820         }
821       }
822     }
823
824     // For very small rate targets where the fractional adjustment
825     // (eg * 7/8) may be tiny make sure there is at least a minimum
826     // range.
827     *frame_over_shoot_limit += 200;
828     *frame_under_shoot_limit -= 200;
829     if (*frame_under_shoot_limit < 0)
830       *frame_under_shoot_limit = 0;
831   }
832 }
833
834 // return of 0 means drop frame
835 int vp9_rc_pick_frame_size_target(VP9_COMP *cpi) {
836   VP9_COMMON *cm = &cpi->common;
837
838   if (cm->frame_type == KEY_FRAME)
839     calc_iframe_target_size(cpi);
840   else
841     calc_pframe_target_size(cpi);
842
843   // Target rate per SB64 (including partial SB64s.
844   cpi->rc.sb64_target_rate = ((int64_t)cpi->rc.this_frame_target * 64 * 64) /
845                              (cpi->common.width * cpi->common.height);
846   return 1;
847 }
848
849 void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
850   VP9_COMMON *const cm = &cpi->common;
851   // Update rate control heuristics
852   cpi->rc.projected_frame_size = (bytes_used << 3);
853
854   // Post encode loop adjustment of Q prediction.
855   vp9_rc_update_rate_correction_factors(
856       cpi, (cpi->sf.recode_loop ||
857             cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ? 2 : 0);
858
859   // Keep a record of last Q and ambient average Q.
860   if (cm->frame_type == KEY_FRAME) {
861     cpi->rc.last_q[KEY_FRAME] = cm->base_qindex;
862     cpi->rc.avg_frame_qindex[KEY_FRAME] =
863         (2 + 3 * cpi->rc.avg_frame_qindex[KEY_FRAME] + cm->base_qindex) >> 2;
864   } else if (!cpi->rc.is_src_frame_alt_ref &&
865              (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
866     cpi->rc.last_q[2] = cm->base_qindex;
867     cpi->rc.avg_frame_qindex[2] =
868         (2 + 3 * cpi->rc.avg_frame_qindex[2] + cm->base_qindex) >> 2;
869   } else {
870     cpi->rc.last_q[INTER_FRAME] = cm->base_qindex;
871     cpi->rc.avg_frame_qindex[INTER_FRAME] =
872         (2 + 3 * cpi->rc.avg_frame_qindex[INTER_FRAME] +
873          cm->base_qindex) >> 2;
874     cpi->rc.ni_frames++;
875     cpi->rc.tot_q += vp9_convert_qindex_to_q(cm->base_qindex);
876     cpi->rc.avg_q = cpi->rc.tot_q / (double)cpi->rc.ni_frames;
877
878     // Calculate the average Q for normal inter frames (not key or GFU frames).
879     cpi->rc.ni_tot_qi += cm->base_qindex;
880     cpi->rc.ni_av_qi = cpi->rc.ni_tot_qi / cpi->rc.ni_frames;
881   }
882
883   // Keep record of last boosted (KF/KF/ARF) Q value.
884   // If the current frame is coded at a lower Q then we also update it.
885   // If all mbs in this group are skipped only update if the Q value is
886   // better than that already stored.
887   // This is used to help set quality in forced key frames to reduce popping
888   if ((cm->base_qindex < cpi->rc.last_boosted_qindex) ||
889       ((cpi->static_mb_pct < 100) &&
890        ((cm->frame_type == KEY_FRAME) || cpi->refresh_alt_ref_frame ||
891         (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)))) {
892     cpi->rc.last_boosted_qindex = cm->base_qindex;
893   }
894
895   vp9_update_buffer_level(cpi, cpi->rc.projected_frame_size);
896
897   // Rolling monitors of whether we are over or underspending used to help
898   // regulate min and Max Q in two pass.
899   if (cm->frame_type != KEY_FRAME) {
900     cpi->rc.rolling_target_bits =
901         ((cpi->rc.rolling_target_bits * 3) +
902          cpi->rc.this_frame_target + 2) / 4;
903     cpi->rc.rolling_actual_bits =
904         ((cpi->rc.rolling_actual_bits * 3) +
905          cpi->rc.projected_frame_size + 2) / 4;
906     cpi->rc.long_rolling_target_bits =
907         ((cpi->rc.long_rolling_target_bits * 31) +
908          cpi->rc.this_frame_target + 16) / 32;
909     cpi->rc.long_rolling_actual_bits =
910         ((cpi->rc.long_rolling_actual_bits * 31) +
911          cpi->rc.projected_frame_size + 16) / 32;
912   }
913
914   // Actual bits spent
915   cpi->rc.total_actual_bits += cpi->rc.projected_frame_size;
916
917   // Debug stats
918   cpi->rc.total_target_vs_actual += (cpi->rc.this_frame_target -
919                                      cpi->rc.projected_frame_size);
920
921 #ifndef DISABLE_RC_LONG_TERM_MEM
922   // Update bits left to the kf and gf groups to account for overshoot or
923   // undershoot on these frames
924   if (cm->frame_type == KEY_FRAME) {
925     cpi->twopass.kf_group_bits += cpi->rc.this_frame_target -
926                                   cpi->rc.projected_frame_size;
927
928     cpi->twopass.kf_group_bits = MAX(cpi->twopass.kf_group_bits, 0);
929   } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
930     cpi->twopass.gf_group_bits += cpi->rc.this_frame_target -
931                                   cpi->rc.projected_frame_size;
932
933     cpi->twopass.gf_group_bits = MAX(cpi->twopass.gf_group_bits, 0);
934   }
935 #endif
936 }