2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
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.
18 #include "vpx_mem/vpx_mem.h"
19 #include "vpx_ports/mem.h"
20 #include "vpx_ports/system_state.h"
22 #include "vp10/common/alloccommon.h"
23 #include "vp10/encoder/aq_cyclicrefresh.h"
24 #include "vp10/common/common.h"
25 #include "vp10/common/entropymode.h"
26 #include "vp10/common/quant_common.h"
27 #include "vp10/common/seg_common.h"
29 #include "vp10/encoder/encodemv.h"
30 #include "vp10/encoder/ratectrl.h"
32 // Max rate target for 1080P and below encodes under normal circumstances
33 // (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
34 #define MAX_MB_RATE 250
35 #define MAXRATE_1080P 2025000
37 #define DEFAULT_KF_BOOST 2000
38 #define DEFAULT_GF_BOOST 2000
40 #define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
42 #define MIN_BPB_FACTOR 0.005
43 #define MAX_BPB_FACTOR 50
45 #define FRAME_OVERHEAD_BITS 200
47 #if CONFIG_VP9_HIGHBITDEPTH
48 #define ASSIGN_MINQ_TABLE(bit_depth, name) \
50 switch (bit_depth) { \
61 assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10" \
67 #define ASSIGN_MINQ_TABLE(bit_depth, name) \
74 // Tables relating active max Q to active min Q
75 static int kf_low_motion_minq_8[QINDEX_RANGE];
76 static int kf_high_motion_minq_8[QINDEX_RANGE];
77 static int arfgf_low_motion_minq_8[QINDEX_RANGE];
78 static int arfgf_high_motion_minq_8[QINDEX_RANGE];
79 static int inter_minq_8[QINDEX_RANGE];
80 static int rtc_minq_8[QINDEX_RANGE];
82 #if CONFIG_VP9_HIGHBITDEPTH
83 static int kf_low_motion_minq_10[QINDEX_RANGE];
84 static int kf_high_motion_minq_10[QINDEX_RANGE];
85 static int arfgf_low_motion_minq_10[QINDEX_RANGE];
86 static int arfgf_high_motion_minq_10[QINDEX_RANGE];
87 static int inter_minq_10[QINDEX_RANGE];
88 static int rtc_minq_10[QINDEX_RANGE];
89 static int kf_low_motion_minq_12[QINDEX_RANGE];
90 static int kf_high_motion_minq_12[QINDEX_RANGE];
91 static int arfgf_low_motion_minq_12[QINDEX_RANGE];
92 static int arfgf_high_motion_minq_12[QINDEX_RANGE];
93 static int inter_minq_12[QINDEX_RANGE];
94 static int rtc_minq_12[QINDEX_RANGE];
97 static int gf_high = 2000;
98 static int gf_low = 400;
99 static int kf_high = 5000;
100 static int kf_low = 400;
102 // Functions to compute the active minq lookup table entries based on a
103 // formulaic approach to facilitate easier adjustment of the Q tables.
104 // The formulae were derived from computing a 3rd order polynomial best
105 // fit to the original data (after plotting real maxq vs minq (not q index))
106 static int get_minq_index(double maxq, double x3, double x2, double x1,
107 vpx_bit_depth_t bit_depth) {
109 const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq,
112 // Special case handling to deal with the step from q2.0
113 // down to lossless mode represented by q 1.0.
114 if (minqtarget <= 2.0)
117 for (i = 0; i < QINDEX_RANGE; i++) {
118 if (minqtarget <= vp10_convert_qindex_to_q(i, bit_depth))
122 return QINDEX_RANGE - 1;
125 static void init_minq_luts(int *kf_low_m, int *kf_high_m,
126 int *arfgf_low, int *arfgf_high,
127 int *inter, int *rtc, vpx_bit_depth_t bit_depth) {
129 for (i = 0; i < QINDEX_RANGE; i++) {
130 const double maxq = vp10_convert_qindex_to_q(i, bit_depth);
131 kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
132 kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
133 arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
134 arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
135 inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.90, bit_depth);
136 rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
140 void vp10_rc_init_minq_luts(void) {
141 init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
142 arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
143 inter_minq_8, rtc_minq_8, VPX_BITS_8);
144 #if CONFIG_VP9_HIGHBITDEPTH
145 init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
146 arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
147 inter_minq_10, rtc_minq_10, VPX_BITS_10);
148 init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
149 arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
150 inter_minq_12, rtc_minq_12, VPX_BITS_12);
154 // These functions use formulaic calculations to make playing with the
155 // quantizer tables easier. If necessary they can be replaced by lookup
156 // tables if and when things settle down in the experimental bitstream
157 double vp10_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
158 // Convert the index to a real Q value (scaled down to match old Q values)
159 #if CONFIG_VP9_HIGHBITDEPTH
162 return vp10_ac_quant(qindex, 0, bit_depth) / 4.0;
164 return vp10_ac_quant(qindex, 0, bit_depth) / 16.0;
166 return vp10_ac_quant(qindex, 0, bit_depth) / 64.0;
168 assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
172 return vp10_ac_quant(qindex, 0, bit_depth) / 4.0;
176 int vp10_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
177 double correction_factor,
178 vpx_bit_depth_t bit_depth) {
179 const double q = vp10_convert_qindex_to_q(qindex, bit_depth);
180 int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
182 assert(correction_factor <= MAX_BPB_FACTOR &&
183 correction_factor >= MIN_BPB_FACTOR);
185 // q based adjustment to baseline enumerator
186 enumerator += (int)(enumerator * q) >> 12;
187 return (int)(enumerator * correction_factor / q);
190 int vp10_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
191 double correction_factor,
192 vpx_bit_depth_t bit_depth) {
193 const int bpm = (int)(vp10_rc_bits_per_mb(frame_type, q, correction_factor,
195 return MAX(FRAME_OVERHEAD_BITS,
196 (int)((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS);
199 int vp10_rc_clamp_pframe_target_size(const VP10_COMP *const cpi, int target) {
200 const RATE_CONTROL *rc = &cpi->rc;
201 const VP10EncoderConfig *oxcf = &cpi->oxcf;
202 const int min_frame_target = MAX(rc->min_frame_bandwidth,
203 rc->avg_frame_bandwidth >> 5);
204 if (target < min_frame_target)
205 target = min_frame_target;
206 if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
207 // If there is an active ARF at this location use the minimum
208 // bits on this frame even if it is a constructed arf.
209 // The active maximum quantizer insures that an appropriate
210 // number of bits will be spent if needed for constructed ARFs.
211 target = min_frame_target;
213 // Clip the frame target to the maximum allowed value.
214 if (target > rc->max_frame_bandwidth)
215 target = rc->max_frame_bandwidth;
216 if (oxcf->rc_max_inter_bitrate_pct) {
217 const int max_rate = rc->avg_frame_bandwidth *
218 oxcf->rc_max_inter_bitrate_pct / 100;
219 target = MIN(target, max_rate);
224 int vp10_rc_clamp_iframe_target_size(const VP10_COMP *const cpi, int target) {
225 const RATE_CONTROL *rc = &cpi->rc;
226 const VP10EncoderConfig *oxcf = &cpi->oxcf;
227 if (oxcf->rc_max_intra_bitrate_pct) {
228 const int max_rate = rc->avg_frame_bandwidth *
229 oxcf->rc_max_intra_bitrate_pct / 100;
230 target = MIN(target, max_rate);
232 if (target > rc->max_frame_bandwidth)
233 target = rc->max_frame_bandwidth;
237 // Update the buffer level for higher temporal layers, given the encoded current
239 static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
241 int current_temporal_layer = svc->temporal_layer_id;
242 for (i = current_temporal_layer + 1;
243 i < svc->number_temporal_layers; ++i) {
244 const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
245 svc->number_temporal_layers);
246 LAYER_CONTEXT *lc = &svc->layer_context[layer];
247 RATE_CONTROL *lrc = &lc->rc;
248 int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
250 lrc->bits_off_target += bits_off_for_this_layer;
252 // Clip buffer level to maximum buffer size for the layer.
253 lrc->bits_off_target = MIN(lrc->bits_off_target, lrc->maximum_buffer_size);
254 lrc->buffer_level = lrc->bits_off_target;
258 // Update the buffer level: leaky bucket model.
259 static void update_buffer_level(VP10_COMP *cpi, int encoded_frame_size) {
260 const VP10_COMMON *const cm = &cpi->common;
261 RATE_CONTROL *const rc = &cpi->rc;
263 // Non-viewable frames are a special case and are treated as pure overhead.
264 if (!cm->show_frame) {
265 rc->bits_off_target -= encoded_frame_size;
267 rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
270 // Clip the buffer level to the maximum specified buffer size.
271 rc->bits_off_target = MIN(rc->bits_off_target, rc->maximum_buffer_size);
272 rc->buffer_level = rc->bits_off_target;
274 if (is_one_pass_cbr_svc(cpi)) {
275 update_layer_buffer_level(&cpi->svc, encoded_frame_size);
279 int vp10_rc_get_default_min_gf_interval(
280 int width, int height, double framerate) {
281 // Assume we do not need any constraint lower than 4K 20 fps
282 static const double factor_safe = 3840 * 2160 * 20.0;
283 const double factor = width * height * framerate;
284 const int default_interval =
285 clamp((int)(framerate * 0.125), MIN_GF_INTERVAL, MAX_GF_INTERVAL);
287 if (factor <= factor_safe)
288 return default_interval;
290 return MAX(default_interval,
291 (int)(MIN_GF_INTERVAL * factor / factor_safe + 0.5));
292 // Note this logic makes:
298 int vp10_rc_get_default_max_gf_interval(double framerate, int min_gf_interval) {
299 int interval = MIN(MAX_GF_INTERVAL, (int)(framerate * 0.75));
300 interval += (interval & 0x01); // Round to even value
301 return MAX(interval, min_gf_interval);
304 void vp10_rc_init(const VP10EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
307 if (pass == 0 && oxcf->rc_mode == VPX_CBR) {
308 rc->avg_frame_qindex[KEY_FRAME] = oxcf->worst_allowed_q;
309 rc->avg_frame_qindex[INTER_FRAME] = oxcf->worst_allowed_q;
311 rc->avg_frame_qindex[KEY_FRAME] = (oxcf->worst_allowed_q +
312 oxcf->best_allowed_q) / 2;
313 rc->avg_frame_qindex[INTER_FRAME] = (oxcf->worst_allowed_q +
314 oxcf->best_allowed_q) / 2;
317 rc->last_q[KEY_FRAME] = oxcf->best_allowed_q;
318 rc->last_q[INTER_FRAME] = oxcf->worst_allowed_q;
320 rc->buffer_level = rc->starting_buffer_level;
321 rc->bits_off_target = rc->starting_buffer_level;
323 rc->rolling_target_bits = rc->avg_frame_bandwidth;
324 rc->rolling_actual_bits = rc->avg_frame_bandwidth;
325 rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
326 rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
328 rc->total_actual_bits = 0;
329 rc->total_target_bits = 0;
330 rc->total_target_vs_actual = 0;
332 rc->frames_since_key = 8; // Sensible default for first frame.
333 rc->this_key_frame_forced = 0;
334 rc->next_key_frame_forced = 0;
335 rc->source_alt_ref_pending = 0;
336 rc->source_alt_ref_active = 0;
338 rc->frames_till_gf_update_due = 0;
339 rc->ni_av_qi = oxcf->worst_allowed_q;
344 rc->avg_q = vp10_convert_qindex_to_q(oxcf->worst_allowed_q, oxcf->bit_depth);
346 for (i = 0; i < RATE_FACTOR_LEVELS; ++i) {
347 rc->rate_correction_factors[i] = 1.0;
350 rc->min_gf_interval = oxcf->min_gf_interval;
351 rc->max_gf_interval = oxcf->max_gf_interval;
352 if (rc->min_gf_interval == 0)
353 rc->min_gf_interval = vp10_rc_get_default_min_gf_interval(
354 oxcf->width, oxcf->height, oxcf->init_framerate);
355 if (rc->max_gf_interval == 0)
356 rc->max_gf_interval = vp10_rc_get_default_max_gf_interval(
357 oxcf->init_framerate, rc->min_gf_interval);
358 rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
361 int vp10_rc_drop_frame(VP10_COMP *cpi) {
362 const VP10EncoderConfig *oxcf = &cpi->oxcf;
363 RATE_CONTROL *const rc = &cpi->rc;
365 if (!oxcf->drop_frames_water_mark) {
368 if (rc->buffer_level < 0) {
369 // Always drop if buffer is below 0.
372 // If buffer is below drop_mark, for now just drop every other frame
373 // (starting with the next frame) until it increases back over drop_mark.
374 int drop_mark = (int)(oxcf->drop_frames_water_mark *
375 rc->optimal_buffer_level / 100);
376 if ((rc->buffer_level > drop_mark) &&
377 (rc->decimation_factor > 0)) {
378 --rc->decimation_factor;
379 } else if (rc->buffer_level <= drop_mark &&
380 rc->decimation_factor == 0) {
381 rc->decimation_factor = 1;
383 if (rc->decimation_factor > 0) {
384 if (rc->decimation_count > 0) {
385 --rc->decimation_count;
388 rc->decimation_count = rc->decimation_factor;
392 rc->decimation_count = 0;
399 static double get_rate_correction_factor(const VP10_COMP *cpi) {
400 const RATE_CONTROL *const rc = &cpi->rc;
403 if (cpi->common.frame_type == KEY_FRAME) {
404 rcf = rc->rate_correction_factors[KF_STD];
405 } else if (cpi->oxcf.pass == 2) {
406 RATE_FACTOR_LEVEL rf_lvl =
407 cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
408 rcf = rc->rate_correction_factors[rf_lvl];
410 if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
411 !rc->is_src_frame_alt_ref && !cpi->use_svc &&
412 (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
413 rcf = rc->rate_correction_factors[GF_ARF_STD];
415 rcf = rc->rate_correction_factors[INTER_NORMAL];
417 rcf *= rcf_mult[rc->frame_size_selector];
418 return fclamp(rcf, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
421 static void set_rate_correction_factor(VP10_COMP *cpi, double factor) {
422 RATE_CONTROL *const rc = &cpi->rc;
424 // Normalize RCF to account for the size-dependent scaling factor.
425 factor /= rcf_mult[cpi->rc.frame_size_selector];
427 factor = fclamp(factor, MIN_BPB_FACTOR, MAX_BPB_FACTOR);
429 if (cpi->common.frame_type == KEY_FRAME) {
430 rc->rate_correction_factors[KF_STD] = factor;
431 } else if (cpi->oxcf.pass == 2) {
432 RATE_FACTOR_LEVEL rf_lvl =
433 cpi->twopass.gf_group.rf_level[cpi->twopass.gf_group.index];
434 rc->rate_correction_factors[rf_lvl] = factor;
436 if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
437 !rc->is_src_frame_alt_ref && !cpi->use_svc &&
438 (cpi->oxcf.rc_mode != VPX_CBR || cpi->oxcf.gf_cbr_boost_pct > 20))
439 rc->rate_correction_factors[GF_ARF_STD] = factor;
441 rc->rate_correction_factors[INTER_NORMAL] = factor;
445 void vp10_rc_update_rate_correction_factors(VP10_COMP *cpi) {
446 const VP10_COMMON *const cm = &cpi->common;
447 int correction_factor = 100;
448 double rate_correction_factor = get_rate_correction_factor(cpi);
449 double adjustment_limit;
451 int projected_size_based_on_q = 0;
453 // Do not update the rate factors for arf overlay frames.
454 if (cpi->rc.is_src_frame_alt_ref)
457 // Clear down mmx registers to allow floating point in what follows
458 vpx_clear_system_state();
460 // Work out how big we would have expected the frame to be at this Q given
461 // the current correction factor.
462 // Stay in double to avoid int overflow when values are large
463 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cpi->common.seg.enabled) {
464 projected_size_based_on_q =
465 vp10_cyclic_refresh_estimate_bits_at_q(cpi, rate_correction_factor);
467 projected_size_based_on_q = vp10_estimate_bits_at_q(cpi->common.frame_type,
470 rate_correction_factor,
473 // Work out a size correction factor.
474 if (projected_size_based_on_q > FRAME_OVERHEAD_BITS)
475 correction_factor = (int)((100 * (int64_t)cpi->rc.projected_frame_size) /
476 projected_size_based_on_q);
478 // More heavily damped adjustment used if we have been oscillating either side
480 adjustment_limit = 0.25 +
481 0.5 * MIN(1, fabs(log10(0.01 * correction_factor)));
483 cpi->rc.q_2_frame = cpi->rc.q_1_frame;
484 cpi->rc.q_1_frame = cm->base_qindex;
485 cpi->rc.rc_2_frame = cpi->rc.rc_1_frame;
486 if (correction_factor > 110)
487 cpi->rc.rc_1_frame = -1;
488 else if (correction_factor < 90)
489 cpi->rc.rc_1_frame = 1;
491 cpi->rc.rc_1_frame = 0;
493 if (correction_factor > 102) {
494 // We are not already at the worst allowable quality
495 correction_factor = (int)(100 + ((correction_factor - 100) *
497 rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
498 // Keep rate_correction_factor within limits
499 if (rate_correction_factor > MAX_BPB_FACTOR)
500 rate_correction_factor = MAX_BPB_FACTOR;
501 } else if (correction_factor < 99) {
502 // We are not already at the best allowable quality
503 correction_factor = (int)(100 - ((100 - correction_factor) *
505 rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
507 // Keep rate_correction_factor within limits
508 if (rate_correction_factor < MIN_BPB_FACTOR)
509 rate_correction_factor = MIN_BPB_FACTOR;
512 set_rate_correction_factor(cpi, rate_correction_factor);
516 int vp10_rc_regulate_q(const VP10_COMP *cpi, int target_bits_per_frame,
517 int active_best_quality, int active_worst_quality) {
518 const VP10_COMMON *const cm = &cpi->common;
519 int q = active_worst_quality;
520 int last_error = INT_MAX;
521 int i, target_bits_per_mb, bits_per_mb_at_this_q;
522 const double correction_factor = get_rate_correction_factor(cpi);
524 // Calculate required scaling factor based on target frame size and size of
525 // frame produced using previous Q.
527 ((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs;
529 i = active_best_quality;
532 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
534 cpi->svc.temporal_layer_id == 0 &&
535 cpi->svc.spatial_layer_id == 0) {
536 bits_per_mb_at_this_q =
537 (int)vp10_cyclic_refresh_rc_bits_per_mb(cpi, i, correction_factor);
539 bits_per_mb_at_this_q = (int)vp10_rc_bits_per_mb(cm->frame_type, i,
544 if (bits_per_mb_at_this_q <= target_bits_per_mb) {
545 if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
552 last_error = bits_per_mb_at_this_q - target_bits_per_mb;
554 } while (++i <= active_worst_quality);
556 // In CBR mode, this makes sure q is between oscillating Qs to prevent
558 if (cpi->oxcf.rc_mode == VPX_CBR &&
559 (cpi->rc.rc_1_frame * cpi->rc.rc_2_frame == -1) &&
560 cpi->rc.q_1_frame != cpi->rc.q_2_frame) {
561 q = clamp(q, MIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
562 MAX(cpi->rc.q_1_frame, cpi->rc.q_2_frame));
567 static int get_active_quality(int q, int gfu_boost, int low, int high,
568 int *low_motion_minq, int *high_motion_minq) {
569 if (gfu_boost > high) {
570 return low_motion_minq[q];
571 } else if (gfu_boost < low) {
572 return high_motion_minq[q];
574 const int gap = high - low;
575 const int offset = high - gfu_boost;
576 const int qdiff = high_motion_minq[q] - low_motion_minq[q];
577 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
578 return low_motion_minq[q] + adjustment;
582 static int get_kf_active_quality(const RATE_CONTROL *const rc, int q,
583 vpx_bit_depth_t bit_depth) {
584 int *kf_low_motion_minq;
585 int *kf_high_motion_minq;
586 ASSIGN_MINQ_TABLE(bit_depth, kf_low_motion_minq);
587 ASSIGN_MINQ_TABLE(bit_depth, kf_high_motion_minq);
588 return get_active_quality(q, rc->kf_boost, kf_low, kf_high,
589 kf_low_motion_minq, kf_high_motion_minq);
592 static int get_gf_active_quality(const RATE_CONTROL *const rc, int q,
593 vpx_bit_depth_t bit_depth) {
594 int *arfgf_low_motion_minq;
595 int *arfgf_high_motion_minq;
596 ASSIGN_MINQ_TABLE(bit_depth, arfgf_low_motion_minq);
597 ASSIGN_MINQ_TABLE(bit_depth, arfgf_high_motion_minq);
598 return get_active_quality(q, rc->gfu_boost, gf_low, gf_high,
599 arfgf_low_motion_minq, arfgf_high_motion_minq);
602 static int calc_active_worst_quality_one_pass_vbr(const VP10_COMP *cpi) {
603 const RATE_CONTROL *const rc = &cpi->rc;
604 const unsigned int curr_frame = cpi->common.current_video_frame;
605 int active_worst_quality;
607 if (cpi->common.frame_type == KEY_FRAME) {
608 active_worst_quality = curr_frame == 0 ? rc->worst_quality
609 : rc->last_q[KEY_FRAME] * 2;
611 if (!rc->is_src_frame_alt_ref &&
612 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
613 active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 5 / 4
614 : rc->last_q[INTER_FRAME];
616 active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 2
617 : rc->last_q[INTER_FRAME] * 2;
620 return MIN(active_worst_quality, rc->worst_quality);
623 // Adjust active_worst_quality level based on buffer level.
624 static int calc_active_worst_quality_one_pass_cbr(const VP10_COMP *cpi) {
625 // Adjust active_worst_quality: If buffer is above the optimal/target level,
626 // bring active_worst_quality down depending on fullness of buffer.
627 // If buffer is below the optimal level, let the active_worst_quality go from
628 // ambient Q (at buffer = optimal level) to worst_quality level
629 // (at buffer = critical level).
630 const VP10_COMMON *const cm = &cpi->common;
631 const RATE_CONTROL *rc = &cpi->rc;
632 // Buffer level below which we push active_worst to worst_quality.
633 int64_t critical_level = rc->optimal_buffer_level >> 3;
634 int64_t buff_lvl_step = 0;
636 int active_worst_quality;
638 if (cm->frame_type == KEY_FRAME)
639 return rc->worst_quality;
640 // For ambient_qp we use minimum of avg_frame_qindex[KEY_FRAME/INTER_FRAME]
641 // for the first few frames following key frame. These are both initialized
642 // to worst_quality and updated with (3/4, 1/4) average in postencode_update.
643 // So for first few frames following key, the qp of that key frame is weighted
644 // into the active_worst_quality setting.
645 ambient_qp = (cm->current_video_frame < 5) ?
646 MIN(rc->avg_frame_qindex[INTER_FRAME], rc->avg_frame_qindex[KEY_FRAME]) :
647 rc->avg_frame_qindex[INTER_FRAME];
648 active_worst_quality = MIN(rc->worst_quality,
650 if (rc->buffer_level > rc->optimal_buffer_level) {
652 // Maximum limit for down adjustment, ~30%.
653 int max_adjustment_down = active_worst_quality / 3;
654 if (max_adjustment_down) {
655 buff_lvl_step = ((rc->maximum_buffer_size -
656 rc->optimal_buffer_level) / max_adjustment_down);
658 adjustment = (int)((rc->buffer_level - rc->optimal_buffer_level) /
660 active_worst_quality -= adjustment;
662 } else if (rc->buffer_level > critical_level) {
663 // Adjust up from ambient Q.
664 if (critical_level) {
665 buff_lvl_step = (rc->optimal_buffer_level - critical_level);
667 adjustment = (int)((rc->worst_quality - ambient_qp) *
668 (rc->optimal_buffer_level - rc->buffer_level) /
671 active_worst_quality = ambient_qp + adjustment;
674 // Set to worst_quality if buffer is below critical level.
675 active_worst_quality = rc->worst_quality;
677 return active_worst_quality;
680 static int rc_pick_q_and_bounds_one_pass_cbr(const VP10_COMP *cpi,
683 const VP10_COMMON *const cm = &cpi->common;
684 const RATE_CONTROL *const rc = &cpi->rc;
685 int active_best_quality;
686 int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
689 ASSIGN_MINQ_TABLE(cm->bit_depth, rtc_minq);
691 if (frame_is_intra_only(cm)) {
692 active_best_quality = rc->best_quality;
693 // Handle the special case for key frames forced when we have reached
694 // the maximum key frame interval. Here force the Q to a range
695 // based on the ambient Q to reduce the risk of popping.
696 if (rc->this_key_frame_forced) {
697 int qindex = rc->last_boosted_qindex;
698 double last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
699 int delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
700 (last_boosted_q * 0.75),
702 active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
703 } else if (cm->current_video_frame > 0) {
704 // not first frame of one pass and kf_boost is set
705 double q_adj_factor = 1.0;
708 active_best_quality =
709 get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
712 // Allow somewhat lower kf minq with small image formats.
713 if ((cm->width * cm->height) <= (352 * 288)) {
714 q_adj_factor -= 0.25;
717 // Convert the adjustment factor to a qindex delta
718 // on active_best_quality.
719 q_val = vp10_convert_qindex_to_q(active_best_quality, cm->bit_depth);
720 active_best_quality += vp10_compute_qdelta(rc, q_val,
721 q_val * q_adj_factor,
724 } else if (!rc->is_src_frame_alt_ref &&
726 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
727 // Use the lower of active_worst_quality and recent
728 // average Q as basis for GF/ARF best Q limit unless last frame was
730 if (rc->frames_since_key > 1 &&
731 rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
732 q = rc->avg_frame_qindex[INTER_FRAME];
734 q = active_worst_quality;
736 active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
738 // Use the lower of active_worst_quality and recent/average Q.
739 if (cm->current_video_frame > 1) {
740 if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
741 active_best_quality = rtc_minq[rc->avg_frame_qindex[INTER_FRAME]];
743 active_best_quality = rtc_minq[active_worst_quality];
745 if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
746 active_best_quality = rtc_minq[rc->avg_frame_qindex[KEY_FRAME]];
748 active_best_quality = rtc_minq[active_worst_quality];
752 // Clip the active best and worst quality values to limits
753 active_best_quality = clamp(active_best_quality,
754 rc->best_quality, rc->worst_quality);
755 active_worst_quality = clamp(active_worst_quality,
756 active_best_quality, rc->worst_quality);
758 *top_index = active_worst_quality;
759 *bottom_index = active_best_quality;
761 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
762 // Limit Q range for the adaptive loop.
763 if (cm->frame_type == KEY_FRAME &&
764 !rc->this_key_frame_forced &&
765 !(cm->current_video_frame == 0)) {
767 vpx_clear_system_state();
768 qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
769 active_worst_quality, 2.0,
771 *top_index = active_worst_quality + qdelta;
772 *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
776 // Special case code to try and match quality with forced key frames
777 if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
778 q = rc->last_boosted_qindex;
780 q = vp10_rc_regulate_q(cpi, rc->this_frame_target,
781 active_best_quality, active_worst_quality);
782 if (q > *top_index) {
783 // Special case when we are targeting the max allowed rate
784 if (rc->this_frame_target >= rc->max_frame_bandwidth)
790 assert(*top_index <= rc->worst_quality &&
791 *top_index >= rc->best_quality);
792 assert(*bottom_index <= rc->worst_quality &&
793 *bottom_index >= rc->best_quality);
794 assert(q <= rc->worst_quality && q >= rc->best_quality);
798 static int get_active_cq_level(const RATE_CONTROL *rc,
799 const VP10EncoderConfig *const oxcf) {
800 static const double cq_adjust_threshold = 0.1;
801 int active_cq_level = oxcf->cq_level;
802 if (oxcf->rc_mode == VPX_CQ &&
803 rc->total_target_bits > 0) {
804 const double x = (double)rc->total_actual_bits / rc->total_target_bits;
805 if (x < cq_adjust_threshold) {
806 active_cq_level = (int)(active_cq_level * x / cq_adjust_threshold);
809 return active_cq_level;
812 static int rc_pick_q_and_bounds_one_pass_vbr(const VP10_COMP *cpi,
815 const VP10_COMMON *const cm = &cpi->common;
816 const RATE_CONTROL *const rc = &cpi->rc;
817 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
818 const int cq_level = get_active_cq_level(rc, oxcf);
819 int active_best_quality;
820 int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
823 ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
825 if (frame_is_intra_only(cm)) {
827 // Handle the special case for key frames forced when we have reached
828 // the maximum key frame interval. Here force the Q to a range
829 // based on the ambient Q to reduce the risk of popping.
830 if (rc->this_key_frame_forced) {
831 int qindex = rc->last_boosted_qindex;
832 double last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
833 int delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
834 last_boosted_q * 0.75,
836 active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
838 // not first frame of one pass and kf_boost is set
839 double q_adj_factor = 1.0;
842 active_best_quality =
843 get_kf_active_quality(rc, rc->avg_frame_qindex[KEY_FRAME],
846 // Allow somewhat lower kf minq with small image formats.
847 if ((cm->width * cm->height) <= (352 * 288)) {
848 q_adj_factor -= 0.25;
851 // Convert the adjustment factor to a qindex delta
852 // on active_best_quality.
853 q_val = vp10_convert_qindex_to_q(active_best_quality, cm->bit_depth);
854 active_best_quality += vp10_compute_qdelta(rc, q_val,
855 q_val * q_adj_factor,
858 } else if (!rc->is_src_frame_alt_ref &&
859 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
860 // Use the lower of active_worst_quality and recent
861 // average Q as basis for GF/ARF best Q limit unless last frame was
863 if (rc->frames_since_key > 1 &&
864 rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
865 q = rc->avg_frame_qindex[INTER_FRAME];
867 q = rc->avg_frame_qindex[KEY_FRAME];
869 // For constrained quality dont allow Q less than the cq level
870 if (oxcf->rc_mode == VPX_CQ) {
874 active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
876 // Constrained quality use slightly lower active best.
877 active_best_quality = active_best_quality * 15 / 16;
879 } else if (oxcf->rc_mode == VPX_Q) {
880 if (!cpi->refresh_alt_ref_frame) {
881 active_best_quality = cq_level;
883 active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
886 active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
889 if (oxcf->rc_mode == VPX_Q) {
890 active_best_quality = cq_level;
892 // Use the lower of active_worst_quality and recent/average Q.
893 if (cm->current_video_frame > 1)
894 active_best_quality = inter_minq[rc->avg_frame_qindex[INTER_FRAME]];
896 active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
897 // For the constrained quality mode we don't want
898 // q to fall below the cq level.
899 if ((oxcf->rc_mode == VPX_CQ) &&
900 (active_best_quality < cq_level)) {
901 active_best_quality = cq_level;
906 // Clip the active best and worst quality values to limits
907 active_best_quality = clamp(active_best_quality,
908 rc->best_quality, rc->worst_quality);
909 active_worst_quality = clamp(active_worst_quality,
910 active_best_quality, rc->worst_quality);
912 *top_index = active_worst_quality;
913 *bottom_index = active_best_quality;
915 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
918 vpx_clear_system_state();
920 // Limit Q range for the adaptive loop.
921 if (cm->frame_type == KEY_FRAME &&
922 !rc->this_key_frame_forced &&
923 !(cm->current_video_frame == 0)) {
924 qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
925 active_worst_quality, 2.0,
927 } else if (!rc->is_src_frame_alt_ref &&
928 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
929 qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
930 active_worst_quality, 1.75,
933 *top_index = active_worst_quality + qdelta;
934 *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
938 if (oxcf->rc_mode == VPX_Q) {
939 q = active_best_quality;
940 // Special case code to try and match quality with forced key frames
941 } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
942 q = rc->last_boosted_qindex;
944 q = vp10_rc_regulate_q(cpi, rc->this_frame_target,
945 active_best_quality, active_worst_quality);
946 if (q > *top_index) {
947 // Special case when we are targeting the max allowed rate
948 if (rc->this_frame_target >= rc->max_frame_bandwidth)
955 assert(*top_index <= rc->worst_quality &&
956 *top_index >= rc->best_quality);
957 assert(*bottom_index <= rc->worst_quality &&
958 *bottom_index >= rc->best_quality);
959 assert(q <= rc->worst_quality && q >= rc->best_quality);
963 int vp10_frame_type_qdelta(const VP10_COMP *cpi, int rf_level, int q) {
964 static const double rate_factor_deltas[RATE_FACTOR_LEVELS] = {
965 1.00, // INTER_NORMAL
971 static const FRAME_TYPE frame_type[RATE_FACTOR_LEVELS] =
972 {INTER_FRAME, INTER_FRAME, INTER_FRAME, INTER_FRAME, KEY_FRAME};
973 const VP10_COMMON *const cm = &cpi->common;
974 int qdelta = vp10_compute_qdelta_by_rate(&cpi->rc, frame_type[rf_level],
975 q, rate_factor_deltas[rf_level],
980 #define STATIC_MOTION_THRESH 95
981 static int rc_pick_q_and_bounds_two_pass(const VP10_COMP *cpi,
984 const VP10_COMMON *const cm = &cpi->common;
985 const RATE_CONTROL *const rc = &cpi->rc;
986 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
987 const GF_GROUP *gf_group = &cpi->twopass.gf_group;
988 const int cq_level = get_active_cq_level(rc, oxcf);
989 int active_best_quality;
990 int active_worst_quality = cpi->twopass.active_worst_quality;
993 ASSIGN_MINQ_TABLE(cm->bit_depth, inter_minq);
995 if (frame_is_intra_only(cm) || vp10_is_upper_layer_key_frame(cpi)) {
996 // Handle the special case for key frames forced when we have reached
997 // the maximum key frame interval. Here force the Q to a range
998 // based on the ambient Q to reduce the risk of popping.
999 if (rc->this_key_frame_forced) {
1000 double last_boosted_q;
1004 if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1005 qindex = MIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1006 active_best_quality = qindex;
1007 last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
1008 delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
1009 last_boosted_q * 1.25,
1011 active_worst_quality = MIN(qindex + delta_qindex, active_worst_quality);
1014 qindex = rc->last_boosted_qindex;
1015 last_boosted_q = vp10_convert_qindex_to_q(qindex, cm->bit_depth);
1016 delta_qindex = vp10_compute_qdelta(rc, last_boosted_q,
1017 last_boosted_q * 0.75,
1019 active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
1022 // Not forced keyframe.
1023 double q_adj_factor = 1.0;
1025 // Baseline value derived from cpi->active_worst_quality and kf boost.
1026 active_best_quality = get_kf_active_quality(rc, active_worst_quality,
1029 // Allow somewhat lower kf minq with small image formats.
1030 if ((cm->width * cm->height) <= (352 * 288)) {
1031 q_adj_factor -= 0.25;
1034 // Make a further adjustment based on the kf zero motion measure.
1035 q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
1037 // Convert the adjustment factor to a qindex delta
1038 // on active_best_quality.
1039 q_val = vp10_convert_qindex_to_q(active_best_quality, cm->bit_depth);
1040 active_best_quality += vp10_compute_qdelta(rc, q_val,
1041 q_val * q_adj_factor,
1044 } else if (!rc->is_src_frame_alt_ref &&
1045 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
1046 // Use the lower of active_worst_quality and recent
1047 // average Q as basis for GF/ARF best Q limit unless last frame was
1049 if (rc->frames_since_key > 1 &&
1050 rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
1051 q = rc->avg_frame_qindex[INTER_FRAME];
1053 q = active_worst_quality;
1055 // For constrained quality dont allow Q less than the cq level
1056 if (oxcf->rc_mode == VPX_CQ) {
1060 active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1062 // Constrained quality use slightly lower active best.
1063 active_best_quality = active_best_quality * 15 / 16;
1065 } else if (oxcf->rc_mode == VPX_Q) {
1066 if (!cpi->refresh_alt_ref_frame) {
1067 active_best_quality = cq_level;
1069 active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1071 // Modify best quality for second level arfs. For mode VPX_Q this
1072 // becomes the baseline frame q.
1073 if (gf_group->rf_level[gf_group->index] == GF_ARF_LOW)
1074 active_best_quality = (active_best_quality + cq_level + 1) / 2;
1077 active_best_quality = get_gf_active_quality(rc, q, cm->bit_depth);
1080 if (oxcf->rc_mode == VPX_Q) {
1081 active_best_quality = cq_level;
1083 active_best_quality = inter_minq[active_worst_quality];
1085 // For the constrained quality mode we don't want
1086 // q to fall below the cq level.
1087 if ((oxcf->rc_mode == VPX_CQ) &&
1088 (active_best_quality < cq_level)) {
1089 active_best_quality = cq_level;
1094 // Extension to max or min Q if undershoot or overshoot is outside
1095 // the permitted range.
1096 if ((cpi->oxcf.rc_mode != VPX_Q) &&
1097 (cpi->twopass.gf_zeromotion_pct < VLOW_MOTION_THRESHOLD)) {
1098 if (frame_is_intra_only(cm) ||
1099 (!rc->is_src_frame_alt_ref &&
1100 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame))) {
1101 active_best_quality -=
1102 (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast);
1103 active_worst_quality += (cpi->twopass.extend_maxq / 2);
1105 active_best_quality -=
1106 (cpi->twopass.extend_minq + cpi->twopass.extend_minq_fast) / 2;
1107 active_worst_quality += cpi->twopass.extend_maxq;
1111 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
1112 vpx_clear_system_state();
1113 // Static forced key frames Q restrictions dealt with elsewhere.
1114 if (!((frame_is_intra_only(cm) || vp10_is_upper_layer_key_frame(cpi))) ||
1115 !rc->this_key_frame_forced ||
1116 (cpi->twopass.last_kfgroup_zeromotion_pct < STATIC_MOTION_THRESH)) {
1117 int qdelta = vp10_frame_type_qdelta(cpi, gf_group->rf_level[gf_group->index],
1118 active_worst_quality);
1119 active_worst_quality = MAX(active_worst_quality + qdelta,
1120 active_best_quality);
1124 // Modify active_best_quality for downscaled normal frames.
1125 if (rc->frame_size_selector != UNSCALED && !frame_is_kf_gf_arf(cpi)) {
1126 int qdelta = vp10_compute_qdelta_by_rate(rc, cm->frame_type,
1127 active_best_quality, 2.0,
1129 active_best_quality = MAX(active_best_quality + qdelta, rc->best_quality);
1132 active_best_quality = clamp(active_best_quality,
1133 rc->best_quality, rc->worst_quality);
1134 active_worst_quality = clamp(active_worst_quality,
1135 active_best_quality, rc->worst_quality);
1137 if (oxcf->rc_mode == VPX_Q) {
1138 q = active_best_quality;
1139 // Special case code to try and match quality with forced key frames.
1140 } else if ((frame_is_intra_only(cm) || vp10_is_upper_layer_key_frame(cpi)) &&
1141 rc->this_key_frame_forced) {
1142 // If static since last kf use better of last boosted and last kf q.
1143 if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1144 q = MIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1146 q = rc->last_boosted_qindex;
1149 q = vp10_rc_regulate_q(cpi, rc->this_frame_target,
1150 active_best_quality, active_worst_quality);
1151 if (q > active_worst_quality) {
1152 // Special case when we are targeting the max allowed rate.
1153 if (rc->this_frame_target >= rc->max_frame_bandwidth)
1154 active_worst_quality = q;
1156 q = active_worst_quality;
1159 clamp(q, active_best_quality, active_worst_quality);
1161 *top_index = active_worst_quality;
1162 *bottom_index = active_best_quality;
1164 assert(*top_index <= rc->worst_quality &&
1165 *top_index >= rc->best_quality);
1166 assert(*bottom_index <= rc->worst_quality &&
1167 *bottom_index >= rc->best_quality);
1168 assert(q <= rc->worst_quality && q >= rc->best_quality);
1172 int vp10_rc_pick_q_and_bounds(const VP10_COMP *cpi,
1173 int *bottom_index, int *top_index) {
1175 if (cpi->oxcf.pass == 0) {
1176 if (cpi->oxcf.rc_mode == VPX_CBR)
1177 q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
1179 q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
1181 q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
1187 void vp10_rc_compute_frame_size_bounds(const VP10_COMP *cpi,
1189 int *frame_under_shoot_limit,
1190 int *frame_over_shoot_limit) {
1191 if (cpi->oxcf.rc_mode == VPX_Q) {
1192 *frame_under_shoot_limit = 0;
1193 *frame_over_shoot_limit = INT_MAX;
1195 // For very small rate targets where the fractional adjustment
1196 // may be tiny make sure there is at least a minimum range.
1197 const int tolerance = (cpi->sf.recode_tolerance * frame_target) / 100;
1198 *frame_under_shoot_limit = MAX(frame_target - tolerance - 200, 0);
1199 *frame_over_shoot_limit = MIN(frame_target + tolerance + 200,
1200 cpi->rc.max_frame_bandwidth);
1204 void vp10_rc_set_frame_target(VP10_COMP *cpi, int target) {
1205 const VP10_COMMON *const cm = &cpi->common;
1206 RATE_CONTROL *const rc = &cpi->rc;
1208 rc->this_frame_target = target;
1210 // Modify frame size target when down-scaling.
1211 if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC &&
1212 rc->frame_size_selector != UNSCALED)
1213 rc->this_frame_target = (int)(rc->this_frame_target
1214 * rate_thresh_mult[rc->frame_size_selector]);
1216 // Target rate per SB64 (including partial SB64s.
1217 rc->sb64_target_rate = ((int64_t)rc->this_frame_target * 64 * 64) /
1218 (cm->width * cm->height);
1221 static void update_alt_ref_frame_stats(VP10_COMP *cpi) {
1222 // this frame refreshes means next frames don't unless specified by user
1223 RATE_CONTROL *const rc = &cpi->rc;
1224 rc->frames_since_golden = 0;
1226 // Mark the alt ref as done (setting to 0 means no further alt refs pending).
1227 rc->source_alt_ref_pending = 0;
1229 // Set the alternate reference frame active flag
1230 rc->source_alt_ref_active = 1;
1233 static void update_golden_frame_stats(VP10_COMP *cpi) {
1234 RATE_CONTROL *const rc = &cpi->rc;
1236 // Update the Golden frame usage counts.
1237 if (cpi->refresh_golden_frame) {
1238 // this frame refreshes means next frames don't unless specified by user
1239 rc->frames_since_golden = 0;
1241 // If we are not using alt ref in the up and coming group clear the arf
1243 if (!rc->source_alt_ref_pending) {
1244 rc->source_alt_ref_active = 0;
1247 // Decrement count down till next gf
1248 if (rc->frames_till_gf_update_due > 0)
1249 rc->frames_till_gf_update_due--;
1251 } else if (!cpi->refresh_alt_ref_frame) {
1252 // Decrement count down till next gf
1253 if (rc->frames_till_gf_update_due > 0)
1254 rc->frames_till_gf_update_due--;
1256 rc->frames_since_golden++;
1260 void vp10_rc_postencode_update(VP10_COMP *cpi, uint64_t bytes_used) {
1261 const VP10_COMMON *const cm = &cpi->common;
1262 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
1263 RATE_CONTROL *const rc = &cpi->rc;
1264 const int qindex = cm->base_qindex;
1266 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
1267 vp10_cyclic_refresh_postencode(cpi);
1270 // Update rate control heuristics
1271 rc->projected_frame_size = (int)(bytes_used << 3);
1273 // Post encode loop adjustment of Q prediction.
1274 vp10_rc_update_rate_correction_factors(cpi);
1276 // Keep a record of last Q and ambient average Q.
1277 if (cm->frame_type == KEY_FRAME) {
1278 rc->last_q[KEY_FRAME] = qindex;
1279 rc->avg_frame_qindex[KEY_FRAME] =
1280 ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1282 if (rc->is_src_frame_alt_ref ||
1283 !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) ||
1284 (cpi->use_svc && oxcf->rc_mode == VPX_CBR)) {
1285 rc->last_q[INTER_FRAME] = qindex;
1286 rc->avg_frame_qindex[INTER_FRAME] =
1287 ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1289 rc->tot_q += vp10_convert_qindex_to_q(qindex, cm->bit_depth);
1290 rc->avg_q = rc->tot_q / rc->ni_frames;
1291 // Calculate the average Q for normal inter frames (not key or GFU
1293 rc->ni_tot_qi += qindex;
1294 rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1298 // Keep record of last boosted (KF/KF/ARF) Q value.
1299 // If the current frame is coded at a lower Q then we also update it.
1300 // If all mbs in this group are skipped only update if the Q value is
1301 // better than that already stored.
1302 // This is used to help set quality in forced key frames to reduce popping
1303 if ((qindex < rc->last_boosted_qindex) ||
1304 (cm->frame_type == KEY_FRAME) ||
1305 (!rc->constrained_gf_group &&
1306 (cpi->refresh_alt_ref_frame ||
1307 (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1308 rc->last_boosted_qindex = qindex;
1310 if (cm->frame_type == KEY_FRAME)
1311 rc->last_kf_qindex = qindex;
1313 update_buffer_level(cpi, rc->projected_frame_size);
1315 // Rolling monitors of whether we are over or underspending used to help
1316 // regulate min and Max Q in two pass.
1317 if (cm->frame_type != KEY_FRAME) {
1318 rc->rolling_target_bits = ROUND_POWER_OF_TWO(
1319 rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1320 rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
1321 rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1322 rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
1323 rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1324 rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
1325 rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
1328 // Actual bits spent
1329 rc->total_actual_bits += rc->projected_frame_size;
1330 rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1332 rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1334 if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
1335 (cm->frame_type != KEY_FRAME))
1336 // Update the alternate reference frame stats as appropriate.
1337 update_alt_ref_frame_stats(cpi);
1339 // Update the Golden frame stats as appropriate.
1340 update_golden_frame_stats(cpi);
1342 if (cm->frame_type == KEY_FRAME)
1343 rc->frames_since_key = 0;
1344 if (cm->show_frame) {
1345 rc->frames_since_key++;
1346 rc->frames_to_key--;
1349 // Trigger the resizing of the next frame if it is scaled.
1350 if (oxcf->pass != 0) {
1351 cpi->resize_pending =
1352 rc->next_frame_size_selector != rc->frame_size_selector;
1353 rc->frame_size_selector = rc->next_frame_size_selector;
1357 void vp10_rc_postencode_update_drop_frame(VP10_COMP *cpi) {
1358 // Update buffer level with zero size, update frame counters, and return.
1359 update_buffer_level(cpi, 0);
1360 cpi->rc.frames_since_key++;
1361 cpi->rc.frames_to_key--;
1362 cpi->rc.rc_2_frame = 0;
1363 cpi->rc.rc_1_frame = 0;
1366 // Use this macro to turn on/off use of alt-refs in one-pass mode.
1367 #define USE_ALTREF_FOR_ONE_PASS 1
1369 static int calc_pframe_target_size_one_pass_vbr(const VP10_COMP *const cpi) {
1370 static const int af_ratio = 10;
1371 const RATE_CONTROL *const rc = &cpi->rc;
1373 #if USE_ALTREF_FOR_ONE_PASS
1374 target = (!rc->is_src_frame_alt_ref &&
1375 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) ?
1376 (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
1377 (rc->baseline_gf_interval + af_ratio - 1) :
1378 (rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
1379 (rc->baseline_gf_interval + af_ratio - 1);
1381 target = rc->avg_frame_bandwidth;
1383 return vp10_rc_clamp_pframe_target_size(cpi, target);
1386 static int calc_iframe_target_size_one_pass_vbr(const VP10_COMP *const cpi) {
1387 static const int kf_ratio = 25;
1388 const RATE_CONTROL *rc = &cpi->rc;
1389 const int target = rc->avg_frame_bandwidth * kf_ratio;
1390 return vp10_rc_clamp_iframe_target_size(cpi, target);
1393 void vp10_rc_get_one_pass_vbr_params(VP10_COMP *cpi) {
1394 VP10_COMMON *const cm = &cpi->common;
1395 RATE_CONTROL *const rc = &cpi->rc;
1397 // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1398 if (!cpi->refresh_alt_ref_frame &&
1399 (cm->current_video_frame == 0 ||
1400 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1401 rc->frames_to_key == 0 ||
1402 (cpi->oxcf.auto_key && 0))) {
1403 cm->frame_type = KEY_FRAME;
1404 rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1405 rc->frames_to_key == 0;
1406 rc->frames_to_key = cpi->oxcf.key_freq;
1407 rc->kf_boost = DEFAULT_KF_BOOST;
1408 rc->source_alt_ref_active = 0;
1410 cm->frame_type = INTER_FRAME;
1412 if (rc->frames_till_gf_update_due == 0) {
1413 rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
1414 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1415 // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1416 if (rc->frames_till_gf_update_due > rc->frames_to_key) {
1417 rc->frames_till_gf_update_due = rc->frames_to_key;
1418 rc->constrained_gf_group = 1;
1420 rc->constrained_gf_group = 0;
1422 cpi->refresh_golden_frame = 1;
1423 rc->source_alt_ref_pending = USE_ALTREF_FOR_ONE_PASS;
1424 rc->gfu_boost = DEFAULT_GF_BOOST;
1426 if (cm->frame_type == KEY_FRAME)
1427 target = calc_iframe_target_size_one_pass_vbr(cpi);
1429 target = calc_pframe_target_size_one_pass_vbr(cpi);
1430 vp10_rc_set_frame_target(cpi, target);
1433 static int calc_pframe_target_size_one_pass_cbr(const VP10_COMP *cpi) {
1434 const VP10EncoderConfig *oxcf = &cpi->oxcf;
1435 const RATE_CONTROL *rc = &cpi->rc;
1436 const SVC *const svc = &cpi->svc;
1437 const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
1438 const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
1439 int min_frame_target = MAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
1442 if (oxcf->gf_cbr_boost_pct) {
1443 const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
1444 target = cpi->refresh_golden_frame ?
1445 (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio_pct) /
1446 (rc->baseline_gf_interval * 100 + af_ratio_pct - 100) :
1447 (rc->avg_frame_bandwidth * rc->baseline_gf_interval * 100) /
1448 (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
1450 target = rc->avg_frame_bandwidth;
1452 if (is_one_pass_cbr_svc(cpi)) {
1453 // Note that for layers, avg_frame_bandwidth is the cumulative
1454 // per-frame-bandwidth. For the target size of this frame, use the
1455 // layer average frame size (i.e., non-cumulative per-frame-bw).
1457 LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1458 svc->temporal_layer_id, svc->number_temporal_layers);
1459 const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1460 target = lc->avg_frame_size;
1461 min_frame_target = MAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
1464 // Lower the target bandwidth for this frame.
1465 const int pct_low = (int)MIN(diff / one_pct_bits, oxcf->under_shoot_pct);
1466 target -= (target * pct_low) / 200;
1467 } else if (diff < 0) {
1468 // Increase the target bandwidth for this frame.
1469 const int pct_high = (int)MIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
1470 target += (target * pct_high) / 200;
1472 if (oxcf->rc_max_inter_bitrate_pct) {
1473 const int max_rate = rc->avg_frame_bandwidth *
1474 oxcf->rc_max_inter_bitrate_pct / 100;
1475 target = MIN(target, max_rate);
1477 return MAX(min_frame_target, target);
1480 static int calc_iframe_target_size_one_pass_cbr(const VP10_COMP *cpi) {
1481 const RATE_CONTROL *rc = &cpi->rc;
1482 const VP10EncoderConfig *oxcf = &cpi->oxcf;
1483 const SVC *const svc = &cpi->svc;
1485 if (cpi->common.current_video_frame == 0) {
1486 target = ((rc->starting_buffer_level / 2) > INT_MAX)
1487 ? INT_MAX : (int)(rc->starting_buffer_level / 2);
1490 double framerate = cpi->framerate;
1491 if (svc->number_temporal_layers > 1 &&
1492 oxcf->rc_mode == VPX_CBR) {
1493 // Use the layer framerate for temporal layers CBR mode.
1494 const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1495 svc->temporal_layer_id, svc->number_temporal_layers);
1496 const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1497 framerate = lc->framerate;
1499 kf_boost = MAX(kf_boost, (int)(2 * framerate - 16));
1500 if (rc->frames_since_key < framerate / 2) {
1501 kf_boost = (int)(kf_boost * rc->frames_since_key /
1504 target = ((16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
1506 return vp10_rc_clamp_iframe_target_size(cpi, target);
1509 // Reset information needed to set proper reference frames and buffer updates
1510 // for temporal layering. This is called when a key frame is encoded.
1511 static void reset_temporal_layer_to_zero(VP10_COMP *cpi) {
1513 LAYER_CONTEXT *lc = NULL;
1514 cpi->svc.temporal_layer_id = 0;
1516 for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
1517 lc = &cpi->svc.layer_context[sl * cpi->svc.number_temporal_layers];
1518 lc->current_video_frame_in_layer = 0;
1519 lc->frames_from_key_frame = 0;
1523 void vp10_rc_get_svc_params(VP10_COMP *cpi) {
1524 VP10_COMMON *const cm = &cpi->common;
1525 RATE_CONTROL *const rc = &cpi->rc;
1526 int target = rc->avg_frame_bandwidth;
1527 const int layer = LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id,
1528 cpi->svc.temporal_layer_id, cpi->svc.number_temporal_layers);
1530 if ((cm->current_video_frame == 0) ||
1531 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1532 (cpi->oxcf.auto_key && (rc->frames_since_key %
1533 cpi->oxcf.key_freq == 0))) {
1534 cm->frame_type = KEY_FRAME;
1535 rc->source_alt_ref_active = 0;
1537 if (is_two_pass_svc(cpi)) {
1538 cpi->svc.layer_context[layer].is_key_frame = 1;
1539 cpi->ref_frame_flags &=
1540 (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1541 } else if (is_one_pass_cbr_svc(cpi)) {
1542 cpi->svc.layer_context[layer].is_key_frame = 1;
1543 reset_temporal_layer_to_zero(cpi);
1544 cpi->ref_frame_flags &=
1545 (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1546 // Assumption here is that LAST_FRAME is being updated for a keyframe.
1547 // Thus no change in update flags.
1548 target = calc_iframe_target_size_one_pass_cbr(cpi);
1551 cm->frame_type = INTER_FRAME;
1552 if (is_two_pass_svc(cpi)) {
1553 LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1554 if (cpi->svc.spatial_layer_id == 0) {
1555 lc->is_key_frame = 0;
1558 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1559 if (lc->is_key_frame)
1560 cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
1562 cpi->ref_frame_flags &= (~VP9_ALT_FLAG);
1563 } else if (is_one_pass_cbr_svc(cpi)) {
1564 LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1565 if (cpi->svc.spatial_layer_id == 0) {
1566 lc->is_key_frame = 0;
1569 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1571 target = calc_pframe_target_size_one_pass_cbr(cpi);
1575 // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1576 // should be done here, before the frame qp is selected.
1577 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1578 vp10_cyclic_refresh_update_parameters(cpi);
1580 vp10_rc_set_frame_target(cpi, target);
1581 rc->frames_till_gf_update_due = INT_MAX;
1582 rc->baseline_gf_interval = INT_MAX;
1585 void vp10_rc_get_one_pass_cbr_params(VP10_COMP *cpi) {
1586 VP10_COMMON *const cm = &cpi->common;
1587 RATE_CONTROL *const rc = &cpi->rc;
1589 // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1590 if ((cm->current_video_frame == 0 ||
1591 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1592 rc->frames_to_key == 0 ||
1593 (cpi->oxcf.auto_key && 0))) {
1594 cm->frame_type = KEY_FRAME;
1595 rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1596 rc->frames_to_key == 0;
1597 rc->frames_to_key = cpi->oxcf.key_freq;
1598 rc->kf_boost = DEFAULT_KF_BOOST;
1599 rc->source_alt_ref_active = 0;
1601 cm->frame_type = INTER_FRAME;
1603 if (rc->frames_till_gf_update_due == 0) {
1604 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1605 vp10_cyclic_refresh_set_golden_update(cpi);
1607 rc->baseline_gf_interval =
1608 (rc->min_gf_interval + rc->max_gf_interval) / 2;
1609 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1610 // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1611 if (rc->frames_till_gf_update_due > rc->frames_to_key)
1612 rc->frames_till_gf_update_due = rc->frames_to_key;
1613 cpi->refresh_golden_frame = 1;
1614 rc->gfu_boost = DEFAULT_GF_BOOST;
1617 // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1618 // should be done here, before the frame qp is selected.
1619 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1620 vp10_cyclic_refresh_update_parameters(cpi);
1622 if (cm->frame_type == KEY_FRAME)
1623 target = calc_iframe_target_size_one_pass_cbr(cpi);
1625 target = calc_pframe_target_size_one_pass_cbr(cpi);
1627 vp10_rc_set_frame_target(cpi, target);
1628 if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC)
1629 cpi->resize_pending = vp10_resize_one_pass_cbr(cpi);
1631 cpi->resize_pending = 0;
1634 int vp10_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
1635 vpx_bit_depth_t bit_depth) {
1636 int start_index = rc->worst_quality;
1637 int target_index = rc->worst_quality;
1640 // Convert the average q value to an index.
1641 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1643 if (vp10_convert_qindex_to_q(i, bit_depth) >= qstart)
1647 // Convert the q target to an index
1648 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1650 if (vp10_convert_qindex_to_q(i, bit_depth) >= qtarget)
1654 return target_index - start_index;
1657 int vp10_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
1658 int qindex, double rate_target_ratio,
1659 vpx_bit_depth_t bit_depth) {
1660 int target_index = rc->worst_quality;
1663 // Look up the current projected bits per block for the base index
1664 const int base_bits_per_mb = vp10_rc_bits_per_mb(frame_type, qindex, 1.0,
1667 // Find the target bits per mb based on the base value and given ratio.
1668 const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
1670 // Convert the q target to an index
1671 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1672 if (vp10_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
1673 target_bits_per_mb) {
1678 return target_index - qindex;
1681 void vp10_rc_set_gf_interval_range(const VP10_COMP *const cpi,
1682 RATE_CONTROL *const rc) {
1683 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
1685 // Set Maximum gf/arf interval
1686 rc->max_gf_interval = oxcf->max_gf_interval;
1687 rc->min_gf_interval = oxcf->min_gf_interval;
1688 if (rc->min_gf_interval == 0)
1689 rc->min_gf_interval = vp10_rc_get_default_min_gf_interval(
1690 oxcf->width, oxcf->height, cpi->framerate);
1691 if (rc->max_gf_interval == 0)
1692 rc->max_gf_interval = vp10_rc_get_default_max_gf_interval(
1693 cpi->framerate, rc->min_gf_interval);
1695 // Extended interval for genuinely static scenes
1696 rc->static_scene_max_gf_interval = MAX_LAG_BUFFERS * 2;
1698 if (is_altref_enabled(cpi)) {
1699 if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
1700 rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
1703 if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
1704 rc->max_gf_interval = rc->static_scene_max_gf_interval;
1707 rc->min_gf_interval = MIN(rc->min_gf_interval, rc->max_gf_interval);
1710 void vp10_rc_update_framerate(VP10_COMP *cpi) {
1711 const VP10_COMMON *const cm = &cpi->common;
1712 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
1713 RATE_CONTROL *const rc = &cpi->rc;
1716 rc->avg_frame_bandwidth = (int)(oxcf->target_bandwidth / cpi->framerate);
1717 rc->min_frame_bandwidth = (int)(rc->avg_frame_bandwidth *
1718 oxcf->two_pass_vbrmin_section / 100);
1720 rc->min_frame_bandwidth = MAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1722 // A maximum bitrate for a frame is defined.
1723 // The baseline for this aligns with HW implementations that
1724 // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
1725 // per 16x16 MB (averaged over a frame). However this limit is extended if
1726 // a very high rate is given on the command line or the the rate cannnot
1727 // be acheived because of a user specificed max q (e.g. when the user
1728 // specifies lossless encode.
1729 vbr_max_bits = (int)(((int64_t)rc->avg_frame_bandwidth *
1730 oxcf->two_pass_vbrmax_section) / 100);
1731 rc->max_frame_bandwidth = MAX(MAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P),
1734 vp10_rc_set_gf_interval_range(cpi, rc);
1737 #define VBR_PCT_ADJUSTMENT_LIMIT 50
1738 // For VBR...adjustment to the frame target based on error from previous frames
1739 static void vbr_rate_correction(VP10_COMP *cpi, int *this_frame_target) {
1740 RATE_CONTROL *const rc = &cpi->rc;
1741 int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
1743 double position_factor = 1.0;
1745 // How far through the clip are we.
1746 // This number is used to damp the per frame rate correction.
1748 if (cpi->twopass.total_stats.count) {
1749 position_factor = sqrt((double)cpi->common.current_video_frame /
1750 cpi->twopass.total_stats.count);
1752 max_delta = (int)(position_factor *
1753 ((*this_frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
1755 // vbr_bits_off_target > 0 means we have extra bits to spend
1756 if (vbr_bits_off_target > 0) {
1757 *this_frame_target +=
1758 (vbr_bits_off_target > max_delta) ? max_delta
1759 : (int)vbr_bits_off_target;
1761 *this_frame_target -=
1762 (vbr_bits_off_target < -max_delta) ? max_delta
1763 : (int)-vbr_bits_off_target;
1766 // Fast redistribution of bits arising from massive local undershoot.
1767 // Dont do it for kf,arf,gf or overlay frames.
1768 if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
1769 rc->vbr_bits_off_target_fast) {
1770 int one_frame_bits = MAX(rc->avg_frame_bandwidth, *this_frame_target);
1771 int fast_extra_bits;
1773 (int)MIN(rc->vbr_bits_off_target_fast, one_frame_bits);
1774 fast_extra_bits = (int)MIN(fast_extra_bits,
1775 MAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
1776 *this_frame_target += (int)fast_extra_bits;
1777 rc->vbr_bits_off_target_fast -= fast_extra_bits;
1781 void vp10_set_target_rate(VP10_COMP *cpi) {
1782 RATE_CONTROL *const rc = &cpi->rc;
1783 int target_rate = rc->base_frame_target;
1785 // Correction to rate target based on prior over or under shoot.
1786 if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
1787 vbr_rate_correction(cpi, &target_rate);
1788 vp10_rc_set_frame_target(cpi, target_rate);
1791 // Check if we should resize, based on average QP from past x frames.
1792 // Only allow for resize at most one scale down for now, scaling factor is 2.
1793 int vp10_resize_one_pass_cbr(VP10_COMP *cpi) {
1794 const VP10_COMMON *const cm = &cpi->common;
1795 RATE_CONTROL *const rc = &cpi->rc;
1797 cpi->resize_scale_num = 1;
1798 cpi->resize_scale_den = 1;
1799 // Don't resize on key frame; reset the counters on key frame.
1800 if (cm->frame_type == KEY_FRAME) {
1801 cpi->resize_avg_qp = 0;
1802 cpi->resize_count = 0;
1805 // Resize based on average buffer underflow and QP over some window.
1806 // Ignore samples close to key frame, since QP is usually high after key.
1807 if (cpi->rc.frames_since_key > 2 * cpi->framerate) {
1808 const int window = (int)(5 * cpi->framerate);
1809 cpi->resize_avg_qp += cm->base_qindex;
1810 if (cpi->rc.buffer_level < (int)(30 * rc->optimal_buffer_level / 100))
1811 ++cpi->resize_buffer_underflow;
1812 ++cpi->resize_count;
1813 // Check for resize action every "window" frames.
1814 if (cpi->resize_count >= window) {
1815 int avg_qp = cpi->resize_avg_qp / cpi->resize_count;
1816 // Resize down if buffer level has underflowed sufficent amount in past
1817 // window, and we are at original resolution.
1818 // Resize back up if average QP is low, and we are currently in a resized
1820 if (cpi->resize_state == 0 &&
1821 cpi->resize_buffer_underflow > (cpi->resize_count >> 2)) {
1823 cpi->resize_state = 1;
1824 } else if (cpi->resize_state == 1 &&
1825 avg_qp < 40 * cpi->rc.worst_quality / 100) {
1827 cpi->resize_state = 0;
1829 // Reset for next window measurement.
1830 cpi->resize_avg_qp = 0;
1831 cpi->resize_count = 0;
1832 cpi->resize_buffer_underflow = 0;
1835 // If decision is to resize, reset some quantities, and check is we should
1836 // reduce rate correction factor,
1837 if (resize_now != 0) {
1838 int target_bits_per_frame;
1839 int active_worst_quality;
1841 int tot_scale_change;
1842 // For now, resize is by 1/2 x 1/2.
1843 cpi->resize_scale_num = 1;
1844 cpi->resize_scale_den = 2;
1845 tot_scale_change = (cpi->resize_scale_den * cpi->resize_scale_den) /
1846 (cpi->resize_scale_num * cpi->resize_scale_num);
1847 // Reset buffer level to optimal, update target size.
1848 rc->buffer_level = rc->optimal_buffer_level;
1849 rc->bits_off_target = rc->optimal_buffer_level;
1850 rc->this_frame_target = calc_pframe_target_size_one_pass_cbr(cpi);
1851 // Reset cyclic refresh parameters.
1852 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
1853 vp10_cyclic_refresh_reset_resize(cpi);
1854 // Get the projected qindex, based on the scaled target frame size (scaled
1855 // so target_bits_per_mb in vp10_rc_regulate_q will be correct target).
1856 target_bits_per_frame = (resize_now == 1) ?
1857 rc->this_frame_target * tot_scale_change :
1858 rc->this_frame_target / tot_scale_change;
1859 active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
1860 qindex = vp10_rc_regulate_q(cpi,
1861 target_bits_per_frame,
1863 active_worst_quality);
1864 // If resize is down, check if projected q index is close to worst_quality,
1865 // and if so, reduce the rate correction factor (since likely can afford
1866 // lower q for resized frame).
1867 if (resize_now == 1 &&
1868 qindex > 90 * cpi->rc.worst_quality / 100) {
1869 rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
1871 // If resize is back up, check if projected q index is too much above the
1872 // current base_qindex, and if so, reduce the rate correction factor
1873 // (since prefer to keep q for resized frame at least close to previous q).
1874 if (resize_now == -1 &&
1875 qindex > 130 * cm->base_qindex / 100) {
1876 rc->rate_correction_factors[INTER_NORMAL] *= 0.9;