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 = VPXMIN(((x3 * maxq + x2) * maxq + x1) * maxq, maxq);
111 // Special case handling to deal with the step from q2.0
112 // down to lossless mode represented by q 1.0.
113 if (minqtarget <= 2.0)
116 for (i = 0; i < QINDEX_RANGE; i++) {
117 if (minqtarget <= vp10_convert_qindex_to_q(i, bit_depth))
121 return QINDEX_RANGE - 1;
124 static void init_minq_luts(int *kf_low_m, int *kf_high_m,
125 int *arfgf_low, int *arfgf_high,
126 int *inter, int *rtc, vpx_bit_depth_t bit_depth) {
128 for (i = 0; i < QINDEX_RANGE; i++) {
129 const double maxq = vp10_convert_qindex_to_q(i, bit_depth);
130 kf_low_m[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.150, bit_depth);
131 kf_high_m[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
132 arfgf_low[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30, bit_depth);
133 arfgf_high[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.55, bit_depth);
134 inter[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.90, bit_depth);
135 rtc[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.70, bit_depth);
139 void vp10_rc_init_minq_luts(void) {
140 init_minq_luts(kf_low_motion_minq_8, kf_high_motion_minq_8,
141 arfgf_low_motion_minq_8, arfgf_high_motion_minq_8,
142 inter_minq_8, rtc_minq_8, VPX_BITS_8);
143 #if CONFIG_VP9_HIGHBITDEPTH
144 init_minq_luts(kf_low_motion_minq_10, kf_high_motion_minq_10,
145 arfgf_low_motion_minq_10, arfgf_high_motion_minq_10,
146 inter_minq_10, rtc_minq_10, VPX_BITS_10);
147 init_minq_luts(kf_low_motion_minq_12, kf_high_motion_minq_12,
148 arfgf_low_motion_minq_12, arfgf_high_motion_minq_12,
149 inter_minq_12, rtc_minq_12, VPX_BITS_12);
153 // These functions use formulaic calculations to make playing with the
154 // quantizer tables easier. If necessary they can be replaced by lookup
155 // tables if and when things settle down in the experimental bitstream
156 double vp10_convert_qindex_to_q(int qindex, vpx_bit_depth_t bit_depth) {
157 // Convert the index to a real Q value (scaled down to match old Q values)
158 #if CONFIG_VP9_HIGHBITDEPTH
161 return vp10_ac_quant(qindex, 0, bit_depth) / 4.0;
163 return vp10_ac_quant(qindex, 0, bit_depth) / 16.0;
165 return vp10_ac_quant(qindex, 0, bit_depth) / 64.0;
167 assert(0 && "bit_depth should be VPX_BITS_8, VPX_BITS_10 or VPX_BITS_12");
171 return vp10_ac_quant(qindex, 0, bit_depth) / 4.0;
175 int vp10_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
176 double correction_factor,
177 vpx_bit_depth_t bit_depth) {
178 const double q = vp10_convert_qindex_to_q(qindex, bit_depth);
179 int enumerator = frame_type == KEY_FRAME ? 2700000 : 1800000;
181 assert(correction_factor <= MAX_BPB_FACTOR &&
182 correction_factor >= MIN_BPB_FACTOR);
184 // q based adjustment to baseline enumerator
185 enumerator += (int)(enumerator * q) >> 12;
186 return (int)(enumerator * correction_factor / q);
189 int vp10_estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
190 double correction_factor,
191 vpx_bit_depth_t bit_depth) {
192 const int bpm = (int)(vp10_rc_bits_per_mb(frame_type, q, correction_factor,
194 return VPXMAX(FRAME_OVERHEAD_BITS,
195 (int)((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS);
198 int vp10_rc_clamp_pframe_target_size(const VP10_COMP *const cpi, int target) {
199 const RATE_CONTROL *rc = &cpi->rc;
200 const VP10EncoderConfig *oxcf = &cpi->oxcf;
201 const int min_frame_target = VPXMAX(rc->min_frame_bandwidth,
202 rc->avg_frame_bandwidth >> 5);
203 if (target < min_frame_target)
204 target = min_frame_target;
205 if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
206 // If there is an active ARF at this location use the minimum
207 // bits on this frame even if it is a constructed arf.
208 // The active maximum quantizer insures that an appropriate
209 // number of bits will be spent if needed for constructed ARFs.
210 target = min_frame_target;
212 // Clip the frame target to the maximum allowed value.
213 if (target > rc->max_frame_bandwidth)
214 target = rc->max_frame_bandwidth;
215 if (oxcf->rc_max_inter_bitrate_pct) {
216 const int max_rate = rc->avg_frame_bandwidth *
217 oxcf->rc_max_inter_bitrate_pct / 100;
218 target = VPXMIN(target, max_rate);
223 int vp10_rc_clamp_iframe_target_size(const VP10_COMP *const cpi, int target) {
224 const RATE_CONTROL *rc = &cpi->rc;
225 const VP10EncoderConfig *oxcf = &cpi->oxcf;
226 if (oxcf->rc_max_intra_bitrate_pct) {
227 const int max_rate = rc->avg_frame_bandwidth *
228 oxcf->rc_max_intra_bitrate_pct / 100;
229 target = VPXMIN(target, max_rate);
231 if (target > rc->max_frame_bandwidth)
232 target = rc->max_frame_bandwidth;
236 // Update the buffer level for higher temporal layers, given the encoded current
238 static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
240 int current_temporal_layer = svc->temporal_layer_id;
241 for (i = current_temporal_layer + 1;
242 i < svc->number_temporal_layers; ++i) {
243 const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id, i,
244 svc->number_temporal_layers);
245 LAYER_CONTEXT *lc = &svc->layer_context[layer];
246 RATE_CONTROL *lrc = &lc->rc;
247 int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
249 lrc->bits_off_target += bits_off_for_this_layer;
251 // Clip buffer level to maximum buffer size for the layer.
252 lrc->bits_off_target =
253 VPXMIN(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 = VPXMIN(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 VPXMAX(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 = VPXMIN(MAX_GF_INTERVAL, (int)(framerate * 0.75));
300 interval += (interval & 0x01); // Round to even value
301 return VPXMAX(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 * VPXMIN(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, VPXMIN(cpi->rc.q_1_frame, cpi->rc.q_2_frame),
562 VPXMAX(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 VPXMIN(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 VPXMIN(rc->avg_frame_qindex[INTER_FRAME],
647 rc->avg_frame_qindex[KEY_FRAME]) :
648 rc->avg_frame_qindex[INTER_FRAME];
649 active_worst_quality = VPXMIN(rc->worst_quality, ambient_qp * 5 / 4);
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 = VPXMAX(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 = VPXMAX(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 = VPXMIN(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 =
1012 VPXMIN(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 = VPXMAX(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 = VPXMAX(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 =
1130 VPXMAX(active_best_quality + qdelta, rc->best_quality);
1133 active_best_quality = clamp(active_best_quality,
1134 rc->best_quality, rc->worst_quality);
1135 active_worst_quality = clamp(active_worst_quality,
1136 active_best_quality, rc->worst_quality);
1138 if (oxcf->rc_mode == VPX_Q) {
1139 q = active_best_quality;
1140 // Special case code to try and match quality with forced key frames.
1141 } else if ((frame_is_intra_only(cm) || vp10_is_upper_layer_key_frame(cpi)) &&
1142 rc->this_key_frame_forced) {
1143 // If static since last kf use better of last boosted and last kf q.
1144 if (cpi->twopass.last_kfgroup_zeromotion_pct >= STATIC_MOTION_THRESH) {
1145 q = VPXMIN(rc->last_kf_qindex, rc->last_boosted_qindex);
1147 q = rc->last_boosted_qindex;
1150 q = vp10_rc_regulate_q(cpi, rc->this_frame_target,
1151 active_best_quality, active_worst_quality);
1152 if (q > active_worst_quality) {
1153 // Special case when we are targeting the max allowed rate.
1154 if (rc->this_frame_target >= rc->max_frame_bandwidth)
1155 active_worst_quality = q;
1157 q = active_worst_quality;
1160 clamp(q, active_best_quality, active_worst_quality);
1162 *top_index = active_worst_quality;
1163 *bottom_index = active_best_quality;
1165 assert(*top_index <= rc->worst_quality &&
1166 *top_index >= rc->best_quality);
1167 assert(*bottom_index <= rc->worst_quality &&
1168 *bottom_index >= rc->best_quality);
1169 assert(q <= rc->worst_quality && q >= rc->best_quality);
1173 int vp10_rc_pick_q_and_bounds(const VP10_COMP *cpi,
1174 int *bottom_index, int *top_index) {
1176 if (cpi->oxcf.pass == 0) {
1177 if (cpi->oxcf.rc_mode == VPX_CBR)
1178 q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
1180 q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
1182 q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
1188 void vp10_rc_compute_frame_size_bounds(const VP10_COMP *cpi,
1190 int *frame_under_shoot_limit,
1191 int *frame_over_shoot_limit) {
1192 if (cpi->oxcf.rc_mode == VPX_Q) {
1193 *frame_under_shoot_limit = 0;
1194 *frame_over_shoot_limit = INT_MAX;
1196 // For very small rate targets where the fractional adjustment
1197 // may be tiny make sure there is at least a minimum range.
1198 const int tolerance = (cpi->sf.recode_tolerance * frame_target) / 100;
1199 *frame_under_shoot_limit = VPXMAX(frame_target - tolerance - 200, 0);
1200 *frame_over_shoot_limit = VPXMIN(frame_target + tolerance + 200,
1201 cpi->rc.max_frame_bandwidth);
1205 void vp10_rc_set_frame_target(VP10_COMP *cpi, int target) {
1206 const VP10_COMMON *const cm = &cpi->common;
1207 RATE_CONTROL *const rc = &cpi->rc;
1209 rc->this_frame_target = target;
1211 // Modify frame size target when down-scaling.
1212 if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC &&
1213 rc->frame_size_selector != UNSCALED)
1214 rc->this_frame_target = (int)(rc->this_frame_target
1215 * rate_thresh_mult[rc->frame_size_selector]);
1217 // Target rate per SB64 (including partial SB64s.
1218 rc->sb64_target_rate = ((int64_t)rc->this_frame_target * 64 * 64) /
1219 (cm->width * cm->height);
1222 static void update_alt_ref_frame_stats(VP10_COMP *cpi) {
1223 // this frame refreshes means next frames don't unless specified by user
1224 RATE_CONTROL *const rc = &cpi->rc;
1225 rc->frames_since_golden = 0;
1227 // Mark the alt ref as done (setting to 0 means no further alt refs pending).
1228 rc->source_alt_ref_pending = 0;
1230 // Set the alternate reference frame active flag
1231 rc->source_alt_ref_active = 1;
1234 static void update_golden_frame_stats(VP10_COMP *cpi) {
1235 RATE_CONTROL *const rc = &cpi->rc;
1237 // Update the Golden frame usage counts.
1238 if (cpi->refresh_golden_frame) {
1239 // this frame refreshes means next frames don't unless specified by user
1240 rc->frames_since_golden = 0;
1242 // If we are not using alt ref in the up and coming group clear the arf
1244 if (!rc->source_alt_ref_pending) {
1245 rc->source_alt_ref_active = 0;
1248 // Decrement count down till next gf
1249 if (rc->frames_till_gf_update_due > 0)
1250 rc->frames_till_gf_update_due--;
1252 } else if (!cpi->refresh_alt_ref_frame) {
1253 // Decrement count down till next gf
1254 if (rc->frames_till_gf_update_due > 0)
1255 rc->frames_till_gf_update_due--;
1257 rc->frames_since_golden++;
1261 void vp10_rc_postencode_update(VP10_COMP *cpi, uint64_t bytes_used) {
1262 const VP10_COMMON *const cm = &cpi->common;
1263 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
1264 RATE_CONTROL *const rc = &cpi->rc;
1265 const int qindex = cm->base_qindex;
1267 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled) {
1268 vp10_cyclic_refresh_postencode(cpi);
1271 // Update rate control heuristics
1272 rc->projected_frame_size = (int)(bytes_used << 3);
1274 // Post encode loop adjustment of Q prediction.
1275 vp10_rc_update_rate_correction_factors(cpi);
1277 // Keep a record of last Q and ambient average Q.
1278 if (cm->frame_type == KEY_FRAME) {
1279 rc->last_q[KEY_FRAME] = qindex;
1280 rc->avg_frame_qindex[KEY_FRAME] =
1281 ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1283 if (rc->is_src_frame_alt_ref ||
1284 !(cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) ||
1285 (cpi->use_svc && oxcf->rc_mode == VPX_CBR)) {
1286 rc->last_q[INTER_FRAME] = qindex;
1287 rc->avg_frame_qindex[INTER_FRAME] =
1288 ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1290 rc->tot_q += vp10_convert_qindex_to_q(qindex, cm->bit_depth);
1291 rc->avg_q = rc->tot_q / rc->ni_frames;
1292 // Calculate the average Q for normal inter frames (not key or GFU
1294 rc->ni_tot_qi += qindex;
1295 rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1299 // Keep record of last boosted (KF/KF/ARF) Q value.
1300 // If the current frame is coded at a lower Q then we also update it.
1301 // If all mbs in this group are skipped only update if the Q value is
1302 // better than that already stored.
1303 // This is used to help set quality in forced key frames to reduce popping
1304 if ((qindex < rc->last_boosted_qindex) ||
1305 (cm->frame_type == KEY_FRAME) ||
1306 (!rc->constrained_gf_group &&
1307 (cpi->refresh_alt_ref_frame ||
1308 (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1309 rc->last_boosted_qindex = qindex;
1311 if (cm->frame_type == KEY_FRAME)
1312 rc->last_kf_qindex = qindex;
1314 update_buffer_level(cpi, rc->projected_frame_size);
1316 // Rolling monitors of whether we are over or underspending used to help
1317 // regulate min and Max Q in two pass.
1318 if (cm->frame_type != KEY_FRAME) {
1319 rc->rolling_target_bits = ROUND_POWER_OF_TWO(
1320 rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1321 rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
1322 rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1323 rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
1324 rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1325 rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
1326 rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
1329 // Actual bits spent
1330 rc->total_actual_bits += rc->projected_frame_size;
1331 rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1333 rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1335 if (is_altref_enabled(cpi) && cpi->refresh_alt_ref_frame &&
1336 (cm->frame_type != KEY_FRAME))
1337 // Update the alternate reference frame stats as appropriate.
1338 update_alt_ref_frame_stats(cpi);
1340 // Update the Golden frame stats as appropriate.
1341 update_golden_frame_stats(cpi);
1343 if (cm->frame_type == KEY_FRAME)
1344 rc->frames_since_key = 0;
1345 if (cm->show_frame) {
1346 rc->frames_since_key++;
1347 rc->frames_to_key--;
1350 // Trigger the resizing of the next frame if it is scaled.
1351 if (oxcf->pass != 0) {
1352 cpi->resize_pending =
1353 rc->next_frame_size_selector != rc->frame_size_selector;
1354 rc->frame_size_selector = rc->next_frame_size_selector;
1358 void vp10_rc_postencode_update_drop_frame(VP10_COMP *cpi) {
1359 // Update buffer level with zero size, update frame counters, and return.
1360 update_buffer_level(cpi, 0);
1361 cpi->rc.frames_since_key++;
1362 cpi->rc.frames_to_key--;
1363 cpi->rc.rc_2_frame = 0;
1364 cpi->rc.rc_1_frame = 0;
1367 // Use this macro to turn on/off use of alt-refs in one-pass mode.
1368 #define USE_ALTREF_FOR_ONE_PASS 1
1370 static int calc_pframe_target_size_one_pass_vbr(const VP10_COMP *const cpi) {
1371 static const int af_ratio = 10;
1372 const RATE_CONTROL *const rc = &cpi->rc;
1374 #if USE_ALTREF_FOR_ONE_PASS
1375 target = (!rc->is_src_frame_alt_ref &&
1376 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) ?
1377 (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
1378 (rc->baseline_gf_interval + af_ratio - 1) :
1379 (rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
1380 (rc->baseline_gf_interval + af_ratio - 1);
1382 target = rc->avg_frame_bandwidth;
1384 return vp10_rc_clamp_pframe_target_size(cpi, target);
1387 static int calc_iframe_target_size_one_pass_vbr(const VP10_COMP *const cpi) {
1388 static const int kf_ratio = 25;
1389 const RATE_CONTROL *rc = &cpi->rc;
1390 const int target = rc->avg_frame_bandwidth * kf_ratio;
1391 return vp10_rc_clamp_iframe_target_size(cpi, target);
1394 void vp10_rc_get_one_pass_vbr_params(VP10_COMP *cpi) {
1395 VP10_COMMON *const cm = &cpi->common;
1396 RATE_CONTROL *const rc = &cpi->rc;
1398 // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1399 if (!cpi->refresh_alt_ref_frame &&
1400 (cm->current_video_frame == 0 ||
1401 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1402 rc->frames_to_key == 0 ||
1403 (cpi->oxcf.auto_key && 0))) {
1404 cm->frame_type = KEY_FRAME;
1405 rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1406 rc->frames_to_key == 0;
1407 rc->frames_to_key = cpi->oxcf.key_freq;
1408 rc->kf_boost = DEFAULT_KF_BOOST;
1409 rc->source_alt_ref_active = 0;
1411 cm->frame_type = INTER_FRAME;
1413 if (rc->frames_till_gf_update_due == 0) {
1414 rc->baseline_gf_interval = (rc->min_gf_interval + rc->max_gf_interval) / 2;
1415 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1416 // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1417 if (rc->frames_till_gf_update_due > rc->frames_to_key) {
1418 rc->frames_till_gf_update_due = rc->frames_to_key;
1419 rc->constrained_gf_group = 1;
1421 rc->constrained_gf_group = 0;
1423 cpi->refresh_golden_frame = 1;
1424 rc->source_alt_ref_pending = USE_ALTREF_FOR_ONE_PASS;
1425 rc->gfu_boost = DEFAULT_GF_BOOST;
1427 if (cm->frame_type == KEY_FRAME)
1428 target = calc_iframe_target_size_one_pass_vbr(cpi);
1430 target = calc_pframe_target_size_one_pass_vbr(cpi);
1431 vp10_rc_set_frame_target(cpi, target);
1434 static int calc_pframe_target_size_one_pass_cbr(const VP10_COMP *cpi) {
1435 const VP10EncoderConfig *oxcf = &cpi->oxcf;
1436 const RATE_CONTROL *rc = &cpi->rc;
1437 const SVC *const svc = &cpi->svc;
1438 const int64_t diff = rc->optimal_buffer_level - rc->buffer_level;
1439 const int64_t one_pct_bits = 1 + rc->optimal_buffer_level / 100;
1440 int min_frame_target =
1441 VPXMAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
1444 if (oxcf->gf_cbr_boost_pct) {
1445 const int af_ratio_pct = oxcf->gf_cbr_boost_pct + 100;
1446 target = cpi->refresh_golden_frame ?
1447 (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio_pct) /
1448 (rc->baseline_gf_interval * 100 + af_ratio_pct - 100) :
1449 (rc->avg_frame_bandwidth * rc->baseline_gf_interval * 100) /
1450 (rc->baseline_gf_interval * 100 + af_ratio_pct - 100);
1452 target = rc->avg_frame_bandwidth;
1454 if (is_one_pass_cbr_svc(cpi)) {
1455 // Note that for layers, avg_frame_bandwidth is the cumulative
1456 // per-frame-bandwidth. For the target size of this frame, use the
1457 // layer average frame size (i.e., non-cumulative per-frame-bw).
1459 LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1460 svc->temporal_layer_id, svc->number_temporal_layers);
1461 const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1462 target = lc->avg_frame_size;
1463 min_frame_target = VPXMAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
1466 // Lower the target bandwidth for this frame.
1467 const int pct_low = (int)VPXMIN(diff / one_pct_bits, oxcf->under_shoot_pct);
1468 target -= (target * pct_low) / 200;
1469 } else if (diff < 0) {
1470 // Increase the target bandwidth for this frame.
1471 const int pct_high =
1472 (int)VPXMIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
1473 target += (target * pct_high) / 200;
1475 if (oxcf->rc_max_inter_bitrate_pct) {
1476 const int max_rate = rc->avg_frame_bandwidth *
1477 oxcf->rc_max_inter_bitrate_pct / 100;
1478 target = VPXMIN(target, max_rate);
1480 return VPXMAX(min_frame_target, target);
1483 static int calc_iframe_target_size_one_pass_cbr(const VP10_COMP *cpi) {
1484 const RATE_CONTROL *rc = &cpi->rc;
1485 const VP10EncoderConfig *oxcf = &cpi->oxcf;
1486 const SVC *const svc = &cpi->svc;
1488 if (cpi->common.current_video_frame == 0) {
1489 target = ((rc->starting_buffer_level / 2) > INT_MAX)
1490 ? INT_MAX : (int)(rc->starting_buffer_level / 2);
1493 double framerate = cpi->framerate;
1494 if (svc->number_temporal_layers > 1 &&
1495 oxcf->rc_mode == VPX_CBR) {
1496 // Use the layer framerate for temporal layers CBR mode.
1497 const int layer = LAYER_IDS_TO_IDX(svc->spatial_layer_id,
1498 svc->temporal_layer_id, svc->number_temporal_layers);
1499 const LAYER_CONTEXT *lc = &svc->layer_context[layer];
1500 framerate = lc->framerate;
1502 kf_boost = VPXMAX(kf_boost, (int)(2 * framerate - 16));
1503 if (rc->frames_since_key < framerate / 2) {
1504 kf_boost = (int)(kf_boost * rc->frames_since_key /
1507 target = ((16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
1509 return vp10_rc_clamp_iframe_target_size(cpi, target);
1512 // Reset information needed to set proper reference frames and buffer updates
1513 // for temporal layering. This is called when a key frame is encoded.
1514 static void reset_temporal_layer_to_zero(VP10_COMP *cpi) {
1516 LAYER_CONTEXT *lc = NULL;
1517 cpi->svc.temporal_layer_id = 0;
1519 for (sl = 0; sl < cpi->svc.number_spatial_layers; ++sl) {
1520 lc = &cpi->svc.layer_context[sl * cpi->svc.number_temporal_layers];
1521 lc->current_video_frame_in_layer = 0;
1522 lc->frames_from_key_frame = 0;
1526 void vp10_rc_get_svc_params(VP10_COMP *cpi) {
1527 VP10_COMMON *const cm = &cpi->common;
1528 RATE_CONTROL *const rc = &cpi->rc;
1529 int target = rc->avg_frame_bandwidth;
1530 const int layer = LAYER_IDS_TO_IDX(cpi->svc.spatial_layer_id,
1531 cpi->svc.temporal_layer_id, cpi->svc.number_temporal_layers);
1533 if ((cm->current_video_frame == 0) ||
1534 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1535 (cpi->oxcf.auto_key && (rc->frames_since_key %
1536 cpi->oxcf.key_freq == 0))) {
1537 cm->frame_type = KEY_FRAME;
1538 rc->source_alt_ref_active = 0;
1540 if (is_two_pass_svc(cpi)) {
1541 cpi->svc.layer_context[layer].is_key_frame = 1;
1542 cpi->ref_frame_flags &=
1543 (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1544 } else if (is_one_pass_cbr_svc(cpi)) {
1545 cpi->svc.layer_context[layer].is_key_frame = 1;
1546 reset_temporal_layer_to_zero(cpi);
1547 cpi->ref_frame_flags &=
1548 (~VP9_LAST_FLAG & ~VP9_GOLD_FLAG & ~VP9_ALT_FLAG);
1549 // Assumption here is that LAST_FRAME is being updated for a keyframe.
1550 // Thus no change in update flags.
1551 target = calc_iframe_target_size_one_pass_cbr(cpi);
1554 cm->frame_type = INTER_FRAME;
1555 if (is_two_pass_svc(cpi)) {
1556 LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1557 if (cpi->svc.spatial_layer_id == 0) {
1558 lc->is_key_frame = 0;
1561 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1562 if (lc->is_key_frame)
1563 cpi->ref_frame_flags &= (~VP9_LAST_FLAG);
1565 cpi->ref_frame_flags &= (~VP9_ALT_FLAG);
1566 } else if (is_one_pass_cbr_svc(cpi)) {
1567 LAYER_CONTEXT *lc = &cpi->svc.layer_context[layer];
1568 if (cpi->svc.spatial_layer_id == 0) {
1569 lc->is_key_frame = 0;
1572 cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame;
1574 target = calc_pframe_target_size_one_pass_cbr(cpi);
1578 // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1579 // should be done here, before the frame qp is selected.
1580 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1581 vp10_cyclic_refresh_update_parameters(cpi);
1583 vp10_rc_set_frame_target(cpi, target);
1584 rc->frames_till_gf_update_due = INT_MAX;
1585 rc->baseline_gf_interval = INT_MAX;
1588 void vp10_rc_get_one_pass_cbr_params(VP10_COMP *cpi) {
1589 VP10_COMMON *const cm = &cpi->common;
1590 RATE_CONTROL *const rc = &cpi->rc;
1592 // TODO(yaowu): replace the "auto_key && 0" below with proper decision logic.
1593 if ((cm->current_video_frame == 0 ||
1594 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1595 rc->frames_to_key == 0 ||
1596 (cpi->oxcf.auto_key && 0))) {
1597 cm->frame_type = KEY_FRAME;
1598 rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1599 rc->frames_to_key == 0;
1600 rc->frames_to_key = cpi->oxcf.key_freq;
1601 rc->kf_boost = DEFAULT_KF_BOOST;
1602 rc->source_alt_ref_active = 0;
1604 cm->frame_type = INTER_FRAME;
1606 if (rc->frames_till_gf_update_due == 0) {
1607 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1608 vp10_cyclic_refresh_set_golden_update(cpi);
1610 rc->baseline_gf_interval =
1611 (rc->min_gf_interval + rc->max_gf_interval) / 2;
1612 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1613 // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1614 if (rc->frames_till_gf_update_due > rc->frames_to_key)
1615 rc->frames_till_gf_update_due = rc->frames_to_key;
1616 cpi->refresh_golden_frame = 1;
1617 rc->gfu_boost = DEFAULT_GF_BOOST;
1620 // Any update/change of global cyclic refresh parameters (amount/delta-qp)
1621 // should be done here, before the frame qp is selected.
1622 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ)
1623 vp10_cyclic_refresh_update_parameters(cpi);
1625 if (cm->frame_type == KEY_FRAME)
1626 target = calc_iframe_target_size_one_pass_cbr(cpi);
1628 target = calc_pframe_target_size_one_pass_cbr(cpi);
1630 vp10_rc_set_frame_target(cpi, target);
1631 if (cpi->oxcf.resize_mode == RESIZE_DYNAMIC)
1632 cpi->resize_pending = vp10_resize_one_pass_cbr(cpi);
1634 cpi->resize_pending = 0;
1637 int vp10_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget,
1638 vpx_bit_depth_t bit_depth) {
1639 int start_index = rc->worst_quality;
1640 int target_index = rc->worst_quality;
1643 // Convert the average q value to an index.
1644 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1646 if (vp10_convert_qindex_to_q(i, bit_depth) >= qstart)
1650 // Convert the q target to an index
1651 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1653 if (vp10_convert_qindex_to_q(i, bit_depth) >= qtarget)
1657 return target_index - start_index;
1660 int vp10_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
1661 int qindex, double rate_target_ratio,
1662 vpx_bit_depth_t bit_depth) {
1663 int target_index = rc->worst_quality;
1666 // Look up the current projected bits per block for the base index
1667 const int base_bits_per_mb = vp10_rc_bits_per_mb(frame_type, qindex, 1.0,
1670 // Find the target bits per mb based on the base value and given ratio.
1671 const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
1673 // Convert the q target to an index
1674 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1675 if (vp10_rc_bits_per_mb(frame_type, i, 1.0, bit_depth) <=
1676 target_bits_per_mb) {
1681 return target_index - qindex;
1684 void vp10_rc_set_gf_interval_range(const VP10_COMP *const cpi,
1685 RATE_CONTROL *const rc) {
1686 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
1688 // Set Maximum gf/arf interval
1689 rc->max_gf_interval = oxcf->max_gf_interval;
1690 rc->min_gf_interval = oxcf->min_gf_interval;
1691 if (rc->min_gf_interval == 0)
1692 rc->min_gf_interval = vp10_rc_get_default_min_gf_interval(
1693 oxcf->width, oxcf->height, cpi->framerate);
1694 if (rc->max_gf_interval == 0)
1695 rc->max_gf_interval = vp10_rc_get_default_max_gf_interval(
1696 cpi->framerate, rc->min_gf_interval);
1698 // Extended interval for genuinely static scenes
1699 rc->static_scene_max_gf_interval = MAX_LAG_BUFFERS * 2;
1701 if (is_altref_enabled(cpi)) {
1702 if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
1703 rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
1706 if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
1707 rc->max_gf_interval = rc->static_scene_max_gf_interval;
1710 rc->min_gf_interval = VPXMIN(rc->min_gf_interval, rc->max_gf_interval);
1713 void vp10_rc_update_framerate(VP10_COMP *cpi) {
1714 const VP10_COMMON *const cm = &cpi->common;
1715 const VP10EncoderConfig *const oxcf = &cpi->oxcf;
1716 RATE_CONTROL *const rc = &cpi->rc;
1719 rc->avg_frame_bandwidth = (int)(oxcf->target_bandwidth / cpi->framerate);
1720 rc->min_frame_bandwidth = (int)(rc->avg_frame_bandwidth *
1721 oxcf->two_pass_vbrmin_section / 100);
1723 rc->min_frame_bandwidth =
1724 VPXMAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1726 // A maximum bitrate for a frame is defined.
1727 // The baseline for this aligns with HW implementations that
1728 // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
1729 // per 16x16 MB (averaged over a frame). However this limit is extended if
1730 // a very high rate is given on the command line or the the rate cannnot
1731 // be acheived because of a user specificed max q (e.g. when the user
1732 // specifies lossless encode.
1733 vbr_max_bits = (int)(((int64_t)rc->avg_frame_bandwidth *
1734 oxcf->two_pass_vbrmax_section) / 100);
1735 rc->max_frame_bandwidth =
1736 VPXMAX(VPXMAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P), vbr_max_bits);
1738 vp10_rc_set_gf_interval_range(cpi, rc);
1741 #define VBR_PCT_ADJUSTMENT_LIMIT 50
1742 // For VBR...adjustment to the frame target based on error from previous frames
1743 static void vbr_rate_correction(VP10_COMP *cpi, int *this_frame_target) {
1744 RATE_CONTROL *const rc = &cpi->rc;
1745 int64_t vbr_bits_off_target = rc->vbr_bits_off_target;
1747 double position_factor = 1.0;
1749 // How far through the clip are we.
1750 // This number is used to damp the per frame rate correction.
1752 if (cpi->twopass.total_stats.count) {
1753 position_factor = sqrt((double)cpi->common.current_video_frame /
1754 cpi->twopass.total_stats.count);
1756 max_delta = (int)(position_factor *
1757 ((*this_frame_target * VBR_PCT_ADJUSTMENT_LIMIT) / 100));
1759 // vbr_bits_off_target > 0 means we have extra bits to spend
1760 if (vbr_bits_off_target > 0) {
1761 *this_frame_target +=
1762 (vbr_bits_off_target > max_delta) ? max_delta
1763 : (int)vbr_bits_off_target;
1765 *this_frame_target -=
1766 (vbr_bits_off_target < -max_delta) ? max_delta
1767 : (int)-vbr_bits_off_target;
1770 // Fast redistribution of bits arising from massive local undershoot.
1771 // Dont do it for kf,arf,gf or overlay frames.
1772 if (!frame_is_kf_gf_arf(cpi) && !rc->is_src_frame_alt_ref &&
1773 rc->vbr_bits_off_target_fast) {
1774 int one_frame_bits = VPXMAX(rc->avg_frame_bandwidth, *this_frame_target);
1775 int fast_extra_bits;
1776 fast_extra_bits = (int)VPXMIN(rc->vbr_bits_off_target_fast, one_frame_bits);
1777 fast_extra_bits = (int)VPXMIN(
1779 VPXMAX(one_frame_bits / 8, rc->vbr_bits_off_target_fast / 8));
1780 *this_frame_target += (int)fast_extra_bits;
1781 rc->vbr_bits_off_target_fast -= fast_extra_bits;
1785 void vp10_set_target_rate(VP10_COMP *cpi) {
1786 RATE_CONTROL *const rc = &cpi->rc;
1787 int target_rate = rc->base_frame_target;
1789 // Correction to rate target based on prior over or under shoot.
1790 if (cpi->oxcf.rc_mode == VPX_VBR || cpi->oxcf.rc_mode == VPX_CQ)
1791 vbr_rate_correction(cpi, &target_rate);
1792 vp10_rc_set_frame_target(cpi, target_rate);
1795 // Check if we should resize, based on average QP from past x frames.
1796 // Only allow for resize at most one scale down for now, scaling factor is 2.
1797 int vp10_resize_one_pass_cbr(VP10_COMP *cpi) {
1798 const VP10_COMMON *const cm = &cpi->common;
1799 RATE_CONTROL *const rc = &cpi->rc;
1801 cpi->resize_scale_num = 1;
1802 cpi->resize_scale_den = 1;
1803 // Don't resize on key frame; reset the counters on key frame.
1804 if (cm->frame_type == KEY_FRAME) {
1805 cpi->resize_avg_qp = 0;
1806 cpi->resize_count = 0;
1809 // Resize based on average buffer underflow and QP over some window.
1810 // Ignore samples close to key frame, since QP is usually high after key.
1811 if (cpi->rc.frames_since_key > 2 * cpi->framerate) {
1812 const int window = (int)(5 * cpi->framerate);
1813 cpi->resize_avg_qp += cm->base_qindex;
1814 if (cpi->rc.buffer_level < (int)(30 * rc->optimal_buffer_level / 100))
1815 ++cpi->resize_buffer_underflow;
1816 ++cpi->resize_count;
1817 // Check for resize action every "window" frames.
1818 if (cpi->resize_count >= window) {
1819 int avg_qp = cpi->resize_avg_qp / cpi->resize_count;
1820 // Resize down if buffer level has underflowed sufficent amount in past
1821 // window, and we are at original resolution.
1822 // Resize back up if average QP is low, and we are currently in a resized
1824 if (cpi->resize_state == 0 &&
1825 cpi->resize_buffer_underflow > (cpi->resize_count >> 2)) {
1827 cpi->resize_state = 1;
1828 } else if (cpi->resize_state == 1 &&
1829 avg_qp < 40 * cpi->rc.worst_quality / 100) {
1831 cpi->resize_state = 0;
1833 // Reset for next window measurement.
1834 cpi->resize_avg_qp = 0;
1835 cpi->resize_count = 0;
1836 cpi->resize_buffer_underflow = 0;
1839 // If decision is to resize, reset some quantities, and check is we should
1840 // reduce rate correction factor,
1841 if (resize_now != 0) {
1842 int target_bits_per_frame;
1843 int active_worst_quality;
1845 int tot_scale_change;
1846 // For now, resize is by 1/2 x 1/2.
1847 cpi->resize_scale_num = 1;
1848 cpi->resize_scale_den = 2;
1849 tot_scale_change = (cpi->resize_scale_den * cpi->resize_scale_den) /
1850 (cpi->resize_scale_num * cpi->resize_scale_num);
1851 // Reset buffer level to optimal, update target size.
1852 rc->buffer_level = rc->optimal_buffer_level;
1853 rc->bits_off_target = rc->optimal_buffer_level;
1854 rc->this_frame_target = calc_pframe_target_size_one_pass_cbr(cpi);
1855 // Reset cyclic refresh parameters.
1856 if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ && cm->seg.enabled)
1857 vp10_cyclic_refresh_reset_resize(cpi);
1858 // Get the projected qindex, based on the scaled target frame size (scaled
1859 // so target_bits_per_mb in vp10_rc_regulate_q will be correct target).
1860 target_bits_per_frame = (resize_now == 1) ?
1861 rc->this_frame_target * tot_scale_change :
1862 rc->this_frame_target / tot_scale_change;
1863 active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
1864 qindex = vp10_rc_regulate_q(cpi,
1865 target_bits_per_frame,
1867 active_worst_quality);
1868 // If resize is down, check if projected q index is close to worst_quality,
1869 // and if so, reduce the rate correction factor (since likely can afford
1870 // lower q for resized frame).
1871 if (resize_now == 1 &&
1872 qindex > 90 * cpi->rc.worst_quality / 100) {
1873 rc->rate_correction_factors[INTER_NORMAL] *= 0.85;
1875 // If resize is back up, check if projected q index is too much above the
1876 // current base_qindex, and if so, reduce the rate correction factor
1877 // (since prefer to keep q for resized frame at least close to previous q).
1878 if (resize_now == -1 &&
1879 qindex > 130 * cm->base_qindex / 100) {
1880 rc->rate_correction_factors[INTER_NORMAL] *= 0.9;