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"
20 #include "vp9/common/vp9_alloccommon.h"
21 #include "vp9/common/vp9_common.h"
22 #include "vp9/common/vp9_entropymode.h"
23 #include "vp9/common/vp9_quant_common.h"
24 #include "vp9/common/vp9_seg_common.h"
25 #include "vp9/common/vp9_systemdependent.h"
27 #include "vp9/encoder/vp9_encodemv.h"
28 #include "vp9/encoder/vp9_ratectrl.h"
30 // Max rate target for 1080P and below encodes under normal circumstances
31 // (1920 * 1080 / (16 * 16)) * MAX_MB_RATE bits per MB
32 #define MAX_MB_RATE 250
33 #define MAXRATE_1080P 2025000
35 #define DEFAULT_KF_BOOST 2000
36 #define DEFAULT_GF_BOOST 2000
38 #define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
40 #define MIN_BPB_FACTOR 0.005
41 #define MAX_BPB_FACTOR 50
43 #define FRAME_OVERHEAD_BITS 200
45 // Tables relating active max Q to active min Q
46 static int kf_low_motion_minq[QINDEX_RANGE];
47 static int kf_high_motion_minq[QINDEX_RANGE];
48 static int arfgf_low_motion_minq[QINDEX_RANGE];
49 static int arfgf_high_motion_minq[QINDEX_RANGE];
50 static int inter_minq[QINDEX_RANGE];
51 static int gf_high = 2000;
52 static int gf_low = 400;
53 static int kf_high = 5000;
54 static int kf_low = 400;
56 // Functions to compute the active minq lookup table entries based on a
57 // formulaic approach to facilitate easier adjustment of the Q tables.
58 // The formulae were derived from computing a 3rd order polynomial best
59 // fit to the original data (after plotting real maxq vs minq (not q index))
60 static int get_minq_index(double maxq, double x3, double x2, double x1) {
62 const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq,
65 // Special case handling to deal with the step from q2.0
66 // down to lossless mode represented by q 1.0.
67 if (minqtarget <= 2.0)
70 for (i = 0; i < QINDEX_RANGE; i++)
71 if (minqtarget <= vp9_convert_qindex_to_q(i))
74 return QINDEX_RANGE - 1;
77 void vp9_rc_init_minq_luts() {
80 for (i = 0; i < QINDEX_RANGE; i++) {
81 const double maxq = vp9_convert_qindex_to_q(i);
82 kf_low_motion_minq[i] = get_minq_index(maxq, 0.000001, -0.0004, 0.125);
83 kf_high_motion_minq[i] = get_minq_index(maxq, 0.000002, -0.0012, 0.50);
84 arfgf_low_motion_minq[i] = get_minq_index(maxq, 0.0000015, -0.0009, 0.30);
85 arfgf_high_motion_minq[i] = get_minq_index(maxq, 0.0000021, -0.00125, 0.50);
86 inter_minq[i] = get_minq_index(maxq, 0.00000271, -0.00113, 0.90);
90 // These functions use formulaic calculations to make playing with the
91 // quantizer tables easier. If necessary they can be replaced by lookup
92 // tables if and when things settle down in the experimental bitstream
93 double vp9_convert_qindex_to_q(int qindex) {
94 // Convert the index to a real Q value (scaled down to match old Q values)
95 return vp9_ac_quant(qindex, 0) / 4.0;
98 int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
99 double correction_factor) {
100 const double q = vp9_convert_qindex_to_q(qindex);
101 int enumerator = frame_type == KEY_FRAME ? 3300000 : 2250000;
103 // q based adjustment to baseline enumerator
104 enumerator += (int)(enumerator * q) >> 12;
105 return (int)(0.5 + (enumerator * correction_factor / q));
108 static int estimate_bits_at_q(FRAME_TYPE frame_type, int q, int mbs,
109 double correction_factor) {
110 const int bpm = (int)(vp9_rc_bits_per_mb(frame_type, q, correction_factor));
111 return ((uint64_t)bpm * mbs) >> BPER_MB_NORMBITS;
114 int vp9_rc_clamp_pframe_target_size(const VP9_COMP *const cpi, int target) {
115 const RATE_CONTROL *rc = &cpi->rc;
116 const int min_frame_target = MAX(rc->min_frame_bandwidth,
117 rc->avg_frame_bandwidth >> 5);
118 if (target < min_frame_target)
119 target = min_frame_target;
120 if (cpi->refresh_golden_frame && rc->is_src_frame_alt_ref) {
121 // If there is an active ARF at this location use the minimum
122 // bits on this frame even if it is a constructed arf.
123 // The active maximum quantizer insures that an appropriate
124 // number of bits will be spent if needed for constructed ARFs.
125 target = min_frame_target;
127 // Clip the frame target to the maximum allowed value.
128 if (target > rc->max_frame_bandwidth)
129 target = rc->max_frame_bandwidth;
133 int vp9_rc_clamp_iframe_target_size(const VP9_COMP *const cpi, int target) {
134 const RATE_CONTROL *rc = &cpi->rc;
135 const VP9EncoderConfig *oxcf = &cpi->oxcf;
136 if (oxcf->rc_max_intra_bitrate_pct) {
137 const int max_rate = rc->avg_frame_bandwidth *
138 oxcf->rc_max_intra_bitrate_pct / 100;
139 target = MIN(target, max_rate);
141 if (target > rc->max_frame_bandwidth)
142 target = rc->max_frame_bandwidth;
147 // Update the buffer level for higher layers, given the encoded current layer.
148 static void update_layer_buffer_level(SVC *svc, int encoded_frame_size) {
149 int temporal_layer = 0;
150 int current_temporal_layer = svc->temporal_layer_id;
151 for (temporal_layer = current_temporal_layer + 1;
152 temporal_layer < svc->number_temporal_layers; ++temporal_layer) {
153 LAYER_CONTEXT *lc = &svc->layer_context[temporal_layer];
154 RATE_CONTROL *lrc = &lc->rc;
155 int bits_off_for_this_layer = (int)(lc->target_bandwidth / lc->framerate -
157 lrc->bits_off_target += bits_off_for_this_layer;
159 // Clip buffer level to maximum buffer size for the layer.
160 lrc->bits_off_target = MIN(lrc->bits_off_target, lc->maximum_buffer_size);
161 lrc->buffer_level = lrc->bits_off_target;
165 // Update the buffer level: leaky bucket model.
166 static void update_buffer_level(VP9_COMP *cpi, int encoded_frame_size) {
167 const VP9_COMMON *const cm = &cpi->common;
168 const VP9EncoderConfig *oxcf = &cpi->oxcf;
169 RATE_CONTROL *const rc = &cpi->rc;
171 // Non-viewable frames are a special case and are treated as pure overhead.
172 if (!cm->show_frame) {
173 rc->bits_off_target -= encoded_frame_size;
175 rc->bits_off_target += rc->avg_frame_bandwidth - encoded_frame_size;
178 // Clip the buffer level to the maximum specified buffer size.
179 rc->bits_off_target = MIN(rc->bits_off_target, oxcf->maximum_buffer_size);
180 rc->buffer_level = rc->bits_off_target;
182 if (cpi->use_svc && cpi->oxcf.rc_mode == RC_MODE_CBR) {
183 update_layer_buffer_level(&cpi->svc, encoded_frame_size);
187 void vp9_rc_init(const VP9EncoderConfig *oxcf, int pass, RATE_CONTROL *rc) {
188 if (pass == 0 && oxcf->rc_mode == RC_MODE_CBR) {
189 rc->avg_frame_qindex[0] = oxcf->worst_allowed_q;
190 rc->avg_frame_qindex[1] = oxcf->worst_allowed_q;
191 rc->avg_frame_qindex[2] = oxcf->worst_allowed_q;
193 rc->avg_frame_qindex[0] = (oxcf->worst_allowed_q +
194 oxcf->best_allowed_q) / 2;
195 rc->avg_frame_qindex[1] = (oxcf->worst_allowed_q +
196 oxcf->best_allowed_q) / 2;
197 rc->avg_frame_qindex[2] = (oxcf->worst_allowed_q +
198 oxcf->best_allowed_q) / 2;
201 rc->last_q[0] = oxcf->best_allowed_q;
202 rc->last_q[1] = oxcf->best_allowed_q;
203 rc->last_q[2] = oxcf->best_allowed_q;
205 rc->buffer_level = oxcf->starting_buffer_level;
206 rc->bits_off_target = oxcf->starting_buffer_level;
208 rc->rolling_target_bits = rc->avg_frame_bandwidth;
209 rc->rolling_actual_bits = rc->avg_frame_bandwidth;
210 rc->long_rolling_target_bits = rc->avg_frame_bandwidth;
211 rc->long_rolling_actual_bits = rc->avg_frame_bandwidth;
213 rc->total_actual_bits = 0;
214 rc->total_target_vs_actual = 0;
216 rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
217 rc->frames_since_key = 8; // Sensible default for first frame.
218 rc->this_key_frame_forced = 0;
219 rc->next_key_frame_forced = 0;
220 rc->source_alt_ref_pending = 0;
221 rc->source_alt_ref_active = 0;
223 rc->frames_till_gf_update_due = 0;
225 rc->ni_av_qi = oxcf->worst_allowed_q;
230 rc->avg_q = vp9_convert_qindex_to_q(oxcf->worst_allowed_q);
232 rc->rate_correction_factor = 1.0;
233 rc->key_frame_rate_correction_factor = 1.0;
234 rc->gf_rate_correction_factor = 1.0;
237 int vp9_rc_drop_frame(VP9_COMP *cpi) {
238 const VP9EncoderConfig *oxcf = &cpi->oxcf;
239 RATE_CONTROL *const rc = &cpi->rc;
241 if (!oxcf->drop_frames_water_mark) {
244 if (rc->buffer_level < 0) {
245 // Always drop if buffer is below 0.
248 // If buffer is below drop_mark, for now just drop every other frame
249 // (starting with the next frame) until it increases back over drop_mark.
250 int drop_mark = (int)(oxcf->drop_frames_water_mark *
251 oxcf->optimal_buffer_level / 100);
252 if ((rc->buffer_level > drop_mark) &&
253 (rc->decimation_factor > 0)) {
254 --rc->decimation_factor;
255 } else if (rc->buffer_level <= drop_mark &&
256 rc->decimation_factor == 0) {
257 rc->decimation_factor = 1;
259 if (rc->decimation_factor > 0) {
260 if (rc->decimation_count > 0) {
261 --rc->decimation_count;
264 rc->decimation_count = rc->decimation_factor;
268 rc->decimation_count = 0;
275 static double get_rate_correction_factor(const VP9_COMP *cpi) {
276 if (cpi->common.frame_type == KEY_FRAME) {
277 return cpi->rc.key_frame_rate_correction_factor;
279 if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
280 !cpi->rc.is_src_frame_alt_ref &&
281 !(cpi->use_svc && cpi->oxcf.rc_mode == RC_MODE_CBR))
282 return cpi->rc.gf_rate_correction_factor;
284 return cpi->rc.rate_correction_factor;
288 static void set_rate_correction_factor(VP9_COMP *cpi, double factor) {
289 if (cpi->common.frame_type == KEY_FRAME) {
290 cpi->rc.key_frame_rate_correction_factor = factor;
292 if ((cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) &&
293 !cpi->rc.is_src_frame_alt_ref &&
294 !(cpi->use_svc && cpi->oxcf.rc_mode == RC_MODE_CBR))
295 cpi->rc.gf_rate_correction_factor = factor;
297 cpi->rc.rate_correction_factor = factor;
301 void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi, int damp_var) {
302 const VP9_COMMON *const cm = &cpi->common;
303 int correction_factor = 100;
304 double rate_correction_factor = get_rate_correction_factor(cpi);
305 double adjustment_limit;
307 int projected_size_based_on_q = 0;
309 // Do not update the rate factors for arf overlay frames.
310 if (cpi->rc.is_src_frame_alt_ref)
313 // Clear down mmx registers to allow floating point in what follows
314 vp9_clear_system_state();
316 // Work out how big we would have expected the frame to be at this Q given
317 // the current correction factor.
318 // Stay in double to avoid int overflow when values are large
319 projected_size_based_on_q = estimate_bits_at_q(cm->frame_type,
320 cm->base_qindex, cm->MBs,
321 rate_correction_factor);
322 // Work out a size correction factor.
323 if (projected_size_based_on_q > 0)
324 correction_factor = (100 * cpi->rc.projected_frame_size) /
325 projected_size_based_on_q;
327 // More heavily damped adjustment used if we have been oscillating either side
331 adjustment_limit = 0.75;
334 adjustment_limit = 0.375;
338 adjustment_limit = 0.25;
342 if (correction_factor > 102) {
343 // We are not already at the worst allowable quality
344 correction_factor = (int)(100 + ((correction_factor - 100) *
346 rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
348 // Keep rate_correction_factor within limits
349 if (rate_correction_factor > MAX_BPB_FACTOR)
350 rate_correction_factor = MAX_BPB_FACTOR;
351 } else if (correction_factor < 99) {
352 // We are not already at the best allowable quality
353 correction_factor = (int)(100 - ((100 - correction_factor) *
355 rate_correction_factor = (rate_correction_factor * correction_factor) / 100;
357 // Keep rate_correction_factor within limits
358 if (rate_correction_factor < MIN_BPB_FACTOR)
359 rate_correction_factor = MIN_BPB_FACTOR;
362 set_rate_correction_factor(cpi, rate_correction_factor);
366 int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
367 int active_best_quality, int active_worst_quality) {
368 const VP9_COMMON *const cm = &cpi->common;
369 int q = active_worst_quality;
370 int last_error = INT_MAX;
371 int i, target_bits_per_mb;
372 const double correction_factor = get_rate_correction_factor(cpi);
374 // Calculate required scaling factor based on target frame size and size of
375 // frame produced using previous Q.
377 ((uint64_t)target_bits_per_frame << BPER_MB_NORMBITS) / cm->MBs;
379 i = active_best_quality;
382 const int bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cm->frame_type, i,
385 if (bits_per_mb_at_this_q <= target_bits_per_mb) {
386 if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
393 last_error = bits_per_mb_at_this_q - target_bits_per_mb;
395 } while (++i <= active_worst_quality);
400 static int get_active_quality(int q, int gfu_boost, int low, int high,
401 int *low_motion_minq, int *high_motion_minq) {
402 if (gfu_boost > high) {
403 return low_motion_minq[q];
404 } else if (gfu_boost < low) {
405 return high_motion_minq[q];
407 const int gap = high - low;
408 const int offset = high - gfu_boost;
409 const int qdiff = high_motion_minq[q] - low_motion_minq[q];
410 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
411 return low_motion_minq[q] + adjustment;
415 static int calc_active_worst_quality_one_pass_vbr(const VP9_COMP *cpi) {
416 const RATE_CONTROL *const rc = &cpi->rc;
417 const unsigned int curr_frame = cpi->common.current_video_frame;
418 int active_worst_quality;
420 if (cpi->common.frame_type == KEY_FRAME) {
421 active_worst_quality = curr_frame == 0 ? rc->worst_quality
422 : rc->last_q[KEY_FRAME] * 2;
424 if (!rc->is_src_frame_alt_ref &&
425 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
426 active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 5 / 4
427 : rc->last_q[INTER_FRAME];
429 active_worst_quality = curr_frame == 1 ? rc->last_q[KEY_FRAME] * 2
430 : rc->last_q[INTER_FRAME] * 2;
434 return MIN(active_worst_quality, rc->worst_quality);
437 // Adjust active_worst_quality level based on buffer level.
438 static int calc_active_worst_quality_one_pass_cbr(const VP9_COMP *cpi) {
439 // Adjust active_worst_quality: If buffer is above the optimal/target level,
440 // bring active_worst_quality down depending on fullness of buffer.
441 // If buffer is below the optimal level, let the active_worst_quality go from
442 // ambient Q (at buffer = optimal level) to worst_quality level
443 // (at buffer = critical level).
444 const VP9_COMMON *const cm = &cpi->common;
445 const VP9EncoderConfig *oxcf = &cpi->oxcf;
446 const RATE_CONTROL *rc = &cpi->rc;
447 // Buffer level below which we push active_worst to worst_quality.
448 int64_t critical_level = oxcf->optimal_buffer_level >> 2;
449 int64_t buff_lvl_step = 0;
451 int active_worst_quality;
452 if (cm->frame_type == KEY_FRAME)
453 return rc->worst_quality;
454 if (cm->current_video_frame > 1)
455 active_worst_quality = MIN(rc->worst_quality,
456 rc->avg_frame_qindex[INTER_FRAME] * 5 / 4);
458 active_worst_quality = MIN(rc->worst_quality,
459 rc->avg_frame_qindex[KEY_FRAME] * 3 / 2);
460 if (rc->buffer_level > oxcf->optimal_buffer_level) {
462 // Maximum limit for down adjustment, ~30%.
463 int max_adjustment_down = active_worst_quality / 3;
464 if (max_adjustment_down) {
465 buff_lvl_step = ((oxcf->maximum_buffer_size -
466 oxcf->optimal_buffer_level) / max_adjustment_down);
468 adjustment = (int)((rc->buffer_level - oxcf->optimal_buffer_level) /
470 active_worst_quality -= adjustment;
472 } else if (rc->buffer_level > critical_level) {
473 // Adjust up from ambient Q.
474 if (critical_level) {
475 buff_lvl_step = (oxcf->optimal_buffer_level - critical_level);
478 (int)((rc->worst_quality - rc->avg_frame_qindex[INTER_FRAME]) *
479 (oxcf->optimal_buffer_level - rc->buffer_level) /
482 active_worst_quality = rc->avg_frame_qindex[INTER_FRAME] + adjustment;
485 // Set to worst_quality if buffer is below critical level.
486 active_worst_quality = rc->worst_quality;
488 return active_worst_quality;
491 static int rc_pick_q_and_bounds_one_pass_cbr(const VP9_COMP *cpi,
494 const VP9_COMMON *const cm = &cpi->common;
495 const RATE_CONTROL *const rc = &cpi->rc;
496 int active_best_quality;
497 int active_worst_quality = calc_active_worst_quality_one_pass_cbr(cpi);
500 if (frame_is_intra_only(cm)) {
501 active_best_quality = rc->best_quality;
502 // Handle the special case for key frames forced when we have75 reached
503 // the maximum key frame interval. Here force the Q to a range
504 // based on the ambient Q to reduce the risk of popping.
505 if (rc->this_key_frame_forced) {
506 int qindex = rc->last_boosted_qindex;
507 double last_boosted_q = vp9_convert_qindex_to_q(qindex);
508 int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
509 (last_boosted_q * 0.75));
510 active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
511 } else if (cm->current_video_frame > 0) {
512 // not first frame of one pass and kf_boost is set
513 double q_adj_factor = 1.0;
516 active_best_quality = get_active_quality(rc->avg_frame_qindex[KEY_FRAME],
520 kf_high_motion_minq);
522 // Allow somewhat lower kf minq with small image formats.
523 if ((cm->width * cm->height) <= (352 * 288)) {
524 q_adj_factor -= 0.25;
527 // Convert the adjustment factor to a qindex delta
528 // on active_best_quality.
529 q_val = vp9_convert_qindex_to_q(active_best_quality);
530 active_best_quality += vp9_compute_qdelta(rc, q_val,
531 q_val * q_adj_factor);
533 } else if (!rc->is_src_frame_alt_ref &&
535 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
536 // Use the lower of active_worst_quality and recent
537 // average Q as basis for GF/ARF best Q limit unless last frame was
539 if (rc->frames_since_key > 1 &&
540 rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
541 q = rc->avg_frame_qindex[INTER_FRAME];
543 q = active_worst_quality;
545 active_best_quality = get_active_quality(
546 q, rc->gfu_boost, gf_low, gf_high,
547 arfgf_low_motion_minq, arfgf_high_motion_minq);
549 // Use the lower of active_worst_quality and recent/average Q.
550 if (cm->current_video_frame > 1) {
551 if (rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality)
552 active_best_quality = inter_minq[rc->avg_frame_qindex[INTER_FRAME]];
554 active_best_quality = inter_minq[active_worst_quality];
556 if (rc->avg_frame_qindex[KEY_FRAME] < active_worst_quality)
557 active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
559 active_best_quality = inter_minq[active_worst_quality];
563 // Clip the active best and worst quality values to limits
564 active_best_quality = clamp(active_best_quality,
565 rc->best_quality, rc->worst_quality);
566 active_worst_quality = clamp(active_worst_quality,
567 active_best_quality, rc->worst_quality);
569 *top_index = active_worst_quality;
570 *bottom_index = active_best_quality;
572 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
573 // Limit Q range for the adaptive loop.
574 if (cm->frame_type == KEY_FRAME &&
575 !rc->this_key_frame_forced &&
576 !(cm->current_video_frame == 0)) {
578 vp9_clear_system_state();
579 qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
580 active_worst_quality, 2.0);
581 *top_index = active_worst_quality + qdelta;
582 *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
586 // Special case code to try and match quality with forced key frames
587 if (cm->frame_type == KEY_FRAME && rc->this_key_frame_forced) {
588 q = rc->last_boosted_qindex;
590 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
591 active_best_quality, active_worst_quality);
592 if (q > *top_index) {
593 // Special case when we are targeting the max allowed rate
594 if (rc->this_frame_target >= rc->max_frame_bandwidth)
600 assert(*top_index <= rc->worst_quality &&
601 *top_index >= rc->best_quality);
602 assert(*bottom_index <= rc->worst_quality &&
603 *bottom_index >= rc->best_quality);
604 assert(q <= rc->worst_quality && q >= rc->best_quality);
608 static int rc_pick_q_and_bounds_one_pass_vbr(const VP9_COMP *cpi,
611 const VP9_COMMON *const cm = &cpi->common;
612 const RATE_CONTROL *const rc = &cpi->rc;
613 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
614 const int cq_level = oxcf->cq_level;
615 int active_best_quality;
616 int active_worst_quality = calc_active_worst_quality_one_pass_vbr(cpi);
619 if (frame_is_intra_only(cm)) {
620 active_best_quality = rc->best_quality;
621 #if !CONFIG_MULTIPLE_ARF
622 // Handle the special case for key frames forced when we have75 reached
623 // the maximum key frame interval. Here force the Q to a range
624 // based on the ambient Q to reduce the risk of popping.
625 if (rc->this_key_frame_forced) {
626 int qindex = rc->last_boosted_qindex;
627 double last_boosted_q = vp9_convert_qindex_to_q(qindex);
628 int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
629 last_boosted_q * 0.75);
630 active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
631 } else if (cm->current_video_frame > 0) {
632 // not first frame of one pass and kf_boost is set
633 double q_adj_factor = 1.0;
636 active_best_quality = get_active_quality(rc->avg_frame_qindex[KEY_FRAME],
640 kf_high_motion_minq);
642 // Allow somewhat lower kf minq with small image formats.
643 if ((cm->width * cm->height) <= (352 * 288)) {
644 q_adj_factor -= 0.25;
647 // Convert the adjustment factor to a qindex delta
648 // on active_best_quality.
649 q_val = vp9_convert_qindex_to_q(active_best_quality);
650 active_best_quality += vp9_compute_qdelta(rc, q_val,
651 q_val * q_adj_factor);
655 // Force the KF quantizer to be 30% of the active_worst_quality.
656 current_q = vp9_convert_qindex_to_q(active_worst_quality);
657 active_best_quality = active_worst_quality
658 + vp9_compute_qdelta(rc, current_q, current_q * 0.3);
660 } else if (!rc->is_src_frame_alt_ref &&
661 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
662 // Use the lower of active_worst_quality and recent
663 // average Q as basis for GF/ARF best Q limit unless last frame was
665 if (rc->frames_since_key > 1 &&
666 rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
667 q = rc->avg_frame_qindex[INTER_FRAME];
669 q = rc->avg_frame_qindex[KEY_FRAME];
671 // For constrained quality dont allow Q less than the cq level
672 if (oxcf->rc_mode == RC_MODE_CONSTRAINED_QUALITY) {
676 active_best_quality = get_active_quality(q, rc->gfu_boost,
678 arfgf_low_motion_minq,
679 arfgf_high_motion_minq);
681 // Constrained quality use slightly lower active best.
682 active_best_quality = active_best_quality * 15 / 16;
684 } else if (oxcf->rc_mode == RC_MODE_CONSTANT_QUALITY) {
685 if (!cpi->refresh_alt_ref_frame) {
686 active_best_quality = cq_level;
688 active_best_quality = get_active_quality(
689 q, rc->gfu_boost, gf_low, gf_high,
690 arfgf_low_motion_minq, arfgf_high_motion_minq);
693 active_best_quality = get_active_quality(
694 q, rc->gfu_boost, gf_low, gf_high,
695 arfgf_low_motion_minq, arfgf_high_motion_minq);
698 if (oxcf->rc_mode == RC_MODE_CONSTANT_QUALITY) {
699 active_best_quality = cq_level;
701 // Use the lower of active_worst_quality and recent/average Q.
702 if (cm->current_video_frame > 1)
703 active_best_quality = inter_minq[rc->avg_frame_qindex[INTER_FRAME]];
705 active_best_quality = inter_minq[rc->avg_frame_qindex[KEY_FRAME]];
706 // For the constrained quality mode we don't want
707 // q to fall below the cq level.
708 if ((oxcf->rc_mode == RC_MODE_CONSTRAINED_QUALITY) &&
709 (active_best_quality < cq_level)) {
710 active_best_quality = cq_level;
715 // Clip the active best and worst quality values to limits
716 active_best_quality = clamp(active_best_quality,
717 rc->best_quality, rc->worst_quality);
718 active_worst_quality = clamp(active_worst_quality,
719 active_best_quality, rc->worst_quality);
721 *top_index = active_worst_quality;
722 *bottom_index = active_best_quality;
724 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
727 vp9_clear_system_state();
729 // Limit Q range for the adaptive loop.
730 if (cm->frame_type == KEY_FRAME &&
731 !rc->this_key_frame_forced &&
732 !(cm->current_video_frame == 0)) {
733 qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
734 active_worst_quality, 2.0);
735 } else if (!rc->is_src_frame_alt_ref &&
736 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
737 qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
738 active_worst_quality, 1.75);
740 *top_index = active_worst_quality + qdelta;
741 *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
745 if (oxcf->rc_mode == RC_MODE_CONSTANT_QUALITY) {
746 q = active_best_quality;
747 // Special case code to try and match quality with forced key frames
748 } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
749 q = rc->last_boosted_qindex;
751 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
752 active_best_quality, active_worst_quality);
753 if (q > *top_index) {
754 // Special case when we are targeting the max allowed rate
755 if (rc->this_frame_target >= rc->max_frame_bandwidth)
761 #if CONFIG_MULTIPLE_ARF
762 // Force the quantizer determined by the coding order pattern.
763 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
764 cpi->oxcf.rc_mode != RC_MODE_CONSTANT_QUALITY) {
766 double current_q = vp9_convert_qindex_to_q(active_worst_quality);
767 int level = cpi->this_frame_weight;
769 new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
770 q = active_worst_quality +
771 vp9_compute_qdelta(rc, current_q, new_q);
775 printf("frame:%d q:%d\n", cm->current_video_frame, q);
778 assert(*top_index <= rc->worst_quality &&
779 *top_index >= rc->best_quality);
780 assert(*bottom_index <= rc->worst_quality &&
781 *bottom_index >= rc->best_quality);
782 assert(q <= rc->worst_quality && q >= rc->best_quality);
786 static int rc_pick_q_and_bounds_two_pass(const VP9_COMP *cpi,
789 const VP9_COMMON *const cm = &cpi->common;
790 const RATE_CONTROL *const rc = &cpi->rc;
791 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
792 const int cq_level = oxcf->cq_level;
793 int active_best_quality;
794 int active_worst_quality = cpi->twopass.active_worst_quality;
797 if (frame_is_intra_only(cm) || vp9_is_upper_layer_key_frame(cpi)) {
798 #if !CONFIG_MULTIPLE_ARF
799 // Handle the special case for key frames forced when we have75 reached
800 // the maximum key frame interval. Here force the Q to a range
801 // based on the ambient Q to reduce the risk of popping.
802 if (rc->this_key_frame_forced) {
803 int qindex = rc->last_boosted_qindex;
804 double last_boosted_q = vp9_convert_qindex_to_q(qindex);
805 int delta_qindex = vp9_compute_qdelta(rc, last_boosted_q,
806 last_boosted_q * 0.75);
807 active_best_quality = MAX(qindex + delta_qindex, rc->best_quality);
809 // Not forced keyframe.
810 double q_adj_factor = 1.0;
812 // Baseline value derived from cpi->active_worst_quality and kf boost.
813 active_best_quality = get_active_quality(active_worst_quality,
817 kf_high_motion_minq);
819 // Allow somewhat lower kf minq with small image formats.
820 if ((cm->width * cm->height) <= (352 * 288)) {
821 q_adj_factor -= 0.25;
824 // Make a further adjustment based on the kf zero motion measure.
825 q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
827 // Convert the adjustment factor to a qindex delta
828 // on active_best_quality.
829 q_val = vp9_convert_qindex_to_q(active_best_quality);
830 active_best_quality += vp9_compute_qdelta(rc, q_val,
831 q_val * q_adj_factor);
835 // Force the KF quantizer to be 30% of the active_worst_quality.
836 current_q = vp9_convert_qindex_to_q(active_worst_quality);
837 active_best_quality = active_worst_quality
838 + vp9_compute_qdelta(rc, current_q, current_q * 0.3);
840 } else if (!rc->is_src_frame_alt_ref &&
841 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
842 // Use the lower of active_worst_quality and recent
843 // average Q as basis for GF/ARF best Q limit unless last frame was
845 if (rc->frames_since_key > 1 &&
846 rc->avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
847 q = rc->avg_frame_qindex[INTER_FRAME];
849 q = active_worst_quality;
851 // For constrained quality dont allow Q less than the cq level
852 if (oxcf->rc_mode == RC_MODE_CONSTRAINED_QUALITY) {
856 active_best_quality = get_active_quality(q, rc->gfu_boost,
858 arfgf_low_motion_minq,
859 arfgf_high_motion_minq);
861 // Constrained quality use slightly lower active best.
862 active_best_quality = active_best_quality * 15 / 16;
864 } else if (oxcf->rc_mode == RC_MODE_CONSTANT_QUALITY) {
865 if (!cpi->refresh_alt_ref_frame) {
866 active_best_quality = cq_level;
868 active_best_quality = get_active_quality(
869 q, rc->gfu_boost, gf_low, gf_high,
870 arfgf_low_motion_minq, arfgf_high_motion_minq);
873 active_best_quality = get_active_quality(
874 q, rc->gfu_boost, gf_low, gf_high,
875 arfgf_low_motion_minq, arfgf_high_motion_minq);
878 if (oxcf->rc_mode == RC_MODE_CONSTANT_QUALITY) {
879 active_best_quality = cq_level;
881 active_best_quality = inter_minq[active_worst_quality];
883 // For the constrained quality mode we don't want
884 // q to fall below the cq level.
885 if ((oxcf->rc_mode == RC_MODE_CONSTRAINED_QUALITY) &&
886 (active_best_quality < cq_level)) {
887 active_best_quality = cq_level;
892 // Clip the active best and worst quality values to limits.
893 active_best_quality = clamp(active_best_quality,
894 rc->best_quality, rc->worst_quality);
895 active_worst_quality = clamp(active_worst_quality,
896 active_best_quality, rc->worst_quality);
898 *top_index = active_worst_quality;
899 *bottom_index = active_best_quality;
901 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
904 vp9_clear_system_state();
906 // Limit Q range for the adaptive loop.
907 if ((cm->frame_type == KEY_FRAME || vp9_is_upper_layer_key_frame(cpi)) &&
908 !rc->this_key_frame_forced) {
909 qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
910 active_worst_quality, 2.0);
911 } else if (!rc->is_src_frame_alt_ref &&
912 (oxcf->rc_mode != RC_MODE_CBR) &&
913 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
914 qdelta = vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type,
915 active_worst_quality, 1.75);
917 *top_index = active_worst_quality + qdelta;
918 *top_index = (*top_index > *bottom_index) ? *top_index : *bottom_index;
922 if (oxcf->rc_mode == RC_MODE_CONSTANT_QUALITY) {
923 q = active_best_quality;
924 // Special case code to try and match quality with forced key frames.
925 } else if ((cm->frame_type == KEY_FRAME) && rc->this_key_frame_forced) {
926 q = rc->last_boosted_qindex;
928 q = vp9_rc_regulate_q(cpi, rc->this_frame_target,
929 active_best_quality, active_worst_quality);
930 if (q > *top_index) {
931 // Special case when we are targeting the max allowed rate.
932 if (rc->this_frame_target >= rc->max_frame_bandwidth)
938 #if CONFIG_MULTIPLE_ARF
939 // Force the quantizer determined by the coding order pattern.
940 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
941 cpi->oxcf.rc_mode != RC_MODE_CONSTANT_QUALITY) {
943 double current_q = vp9_convert_qindex_to_q(active_worst_quality);
944 int level = cpi->this_frame_weight;
946 new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
947 q = active_worst_quality +
948 vp9_compute_qdelta(rc, current_q, new_q);
952 printf("frame:%d q:%d\n", cm->current_video_frame, q);
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 vp9_rc_pick_q_and_bounds(const VP9_COMP *cpi,
964 int *bottom_index, int *top_index) {
966 if (cpi->pass == 0) {
967 if (cpi->oxcf.rc_mode == RC_MODE_CBR)
968 q = rc_pick_q_and_bounds_one_pass_cbr(cpi, bottom_index, top_index);
970 q = rc_pick_q_and_bounds_one_pass_vbr(cpi, bottom_index, top_index);
972 q = rc_pick_q_and_bounds_two_pass(cpi, bottom_index, top_index);
975 // Q of 0 is disabled because we force tx size to be
977 if (cpi->sf.use_nonrd_pick_mode) {
980 if (cpi->sf.force_frame_boost == 1)
981 q -= cpi->sf.max_delta_qindex;
983 if (q < *bottom_index)
985 else if (q > *top_index)
991 void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi,
993 int *frame_under_shoot_limit,
994 int *frame_over_shoot_limit) {
995 if (cpi->oxcf.rc_mode == RC_MODE_CONSTANT_QUALITY) {
996 *frame_under_shoot_limit = 0;
997 *frame_over_shoot_limit = INT_MAX;
999 // For very small rate targets where the fractional adjustment
1000 // may be tiny make sure there is at least a minimum range.
1001 const int tolerance = (cpi->sf.recode_tolerance * frame_target) / 100;
1002 *frame_under_shoot_limit = MAX(frame_target - tolerance - 200, 0);
1003 *frame_over_shoot_limit = MIN(frame_target + tolerance + 200,
1004 cpi->rc.max_frame_bandwidth);
1008 void vp9_rc_set_frame_target(VP9_COMP *cpi, int target) {
1009 const VP9_COMMON *const cm = &cpi->common;
1010 RATE_CONTROL *const rc = &cpi->rc;
1012 rc->this_frame_target = target;
1014 // Target rate per SB64 (including partial SB64s.
1015 rc->sb64_target_rate = ((int64_t)rc->this_frame_target * 64 * 64) /
1016 (cm->width * cm->height);
1019 static void update_alt_ref_frame_stats(VP9_COMP *cpi) {
1020 // this frame refreshes means next frames don't unless specified by user
1021 RATE_CONTROL *const rc = &cpi->rc;
1022 rc->frames_since_golden = 0;
1024 #if CONFIG_MULTIPLE_ARF
1025 if (!cpi->multi_arf_enabled)
1027 // Clear the alternate reference update pending flag.
1028 rc->source_alt_ref_pending = 0;
1030 // Set the alternate reference frame active flag
1031 rc->source_alt_ref_active = 1;
1034 static void update_golden_frame_stats(VP9_COMP *cpi) {
1035 RATE_CONTROL *const rc = &cpi->rc;
1037 // Update the Golden frame usage counts.
1038 if (cpi->refresh_golden_frame) {
1039 // this frame refreshes means next frames don't unless specified by user
1040 rc->frames_since_golden = 0;
1042 if (!rc->source_alt_ref_pending)
1043 rc->source_alt_ref_active = 0;
1045 // Decrement count down till next gf
1046 if (rc->frames_till_gf_update_due > 0)
1047 rc->frames_till_gf_update_due--;
1049 } else if (!cpi->refresh_alt_ref_frame) {
1050 // Decrement count down till next gf
1051 if (rc->frames_till_gf_update_due > 0)
1052 rc->frames_till_gf_update_due--;
1054 rc->frames_since_golden++;
1058 void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
1059 const VP9_COMMON *const cm = &cpi->common;
1060 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1061 RATE_CONTROL *const rc = &cpi->rc;
1062 const int qindex = cm->base_qindex;
1064 // Update rate control heuristics
1065 rc->projected_frame_size = (int)(bytes_used << 3);
1067 // Post encode loop adjustment of Q prediction.
1068 vp9_rc_update_rate_correction_factors(
1069 cpi, (cpi->sf.recode_loop >= ALLOW_RECODE_KFARFGF ||
1070 oxcf->rc_mode == RC_MODE_CBR) ? 2 : 0);
1072 // Keep a record of last Q and ambient average Q.
1073 if (cm->frame_type == KEY_FRAME) {
1074 rc->last_q[KEY_FRAME] = qindex;
1075 rc->avg_frame_qindex[KEY_FRAME] =
1076 ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[KEY_FRAME] + qindex, 2);
1077 } else if (!rc->is_src_frame_alt_ref &&
1078 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) &&
1079 !(cpi->use_svc && oxcf->rc_mode == RC_MODE_CBR)) {
1080 rc->last_q[2] = qindex;
1081 rc->avg_frame_qindex[2] =
1082 ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[2] + qindex, 2);
1084 rc->last_q[INTER_FRAME] = qindex;
1085 rc->avg_frame_qindex[INTER_FRAME] =
1086 ROUND_POWER_OF_TWO(3 * rc->avg_frame_qindex[INTER_FRAME] + qindex, 2);
1088 rc->tot_q += vp9_convert_qindex_to_q(qindex);
1089 rc->avg_q = rc->tot_q / rc->ni_frames;
1090 // Calculate the average Q for normal inter frames (not key or GFU frames).
1091 rc->ni_tot_qi += qindex;
1092 rc->ni_av_qi = rc->ni_tot_qi / rc->ni_frames;
1095 // Keep record of last boosted (KF/KF/ARF) Q value.
1096 // If the current frame is coded at a lower Q then we also update it.
1097 // If all mbs in this group are skipped only update if the Q value is
1098 // better than that already stored.
1099 // This is used to help set quality in forced key frames to reduce popping
1100 if ((qindex < rc->last_boosted_qindex) ||
1101 ((cpi->static_mb_pct < 100) &&
1102 ((cm->frame_type == KEY_FRAME) || cpi->refresh_alt_ref_frame ||
1103 (cpi->refresh_golden_frame && !rc->is_src_frame_alt_ref)))) {
1104 rc->last_boosted_qindex = qindex;
1107 update_buffer_level(cpi, rc->projected_frame_size);
1109 // Rolling monitors of whether we are over or underspending used to help
1110 // regulate min and Max Q in two pass.
1111 if (cm->frame_type != KEY_FRAME) {
1112 rc->rolling_target_bits = ROUND_POWER_OF_TWO(
1113 rc->rolling_target_bits * 3 + rc->this_frame_target, 2);
1114 rc->rolling_actual_bits = ROUND_POWER_OF_TWO(
1115 rc->rolling_actual_bits * 3 + rc->projected_frame_size, 2);
1116 rc->long_rolling_target_bits = ROUND_POWER_OF_TWO(
1117 rc->long_rolling_target_bits * 31 + rc->this_frame_target, 5);
1118 rc->long_rolling_actual_bits = ROUND_POWER_OF_TWO(
1119 rc->long_rolling_actual_bits * 31 + rc->projected_frame_size, 5);
1122 // Actual bits spent
1123 rc->total_actual_bits += rc->projected_frame_size;
1124 rc->total_target_bits += cm->show_frame ? rc->avg_frame_bandwidth : 0;
1126 rc->total_target_vs_actual = rc->total_actual_bits - rc->total_target_bits;
1128 if (oxcf->play_alternate && cpi->refresh_alt_ref_frame &&
1129 (cm->frame_type != KEY_FRAME))
1130 // Update the alternate reference frame stats as appropriate.
1131 update_alt_ref_frame_stats(cpi);
1133 // Update the Golden frame stats as appropriate.
1134 update_golden_frame_stats(cpi);
1136 if (cm->frame_type == KEY_FRAME)
1137 rc->frames_since_key = 0;
1138 if (cm->show_frame) {
1139 rc->frames_since_key++;
1140 rc->frames_to_key--;
1144 void vp9_rc_postencode_update_drop_frame(VP9_COMP *cpi) {
1145 // Update buffer level with zero size, update frame counters, and return.
1146 update_buffer_level(cpi, 0);
1147 cpi->common.last_frame_type = cpi->common.frame_type;
1148 cpi->rc.frames_since_key++;
1149 cpi->rc.frames_to_key--;
1152 static int test_for_kf_one_pass(VP9_COMP *cpi) {
1153 // Placeholder function for auto key frame
1156 // Use this macro to turn on/off use of alt-refs in one-pass mode.
1157 #define USE_ALTREF_FOR_ONE_PASS 1
1159 static int calc_pframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1160 static const int af_ratio = 10;
1161 const RATE_CONTROL *const rc = &cpi->rc;
1163 #if USE_ALTREF_FOR_ONE_PASS
1164 target = (!rc->is_src_frame_alt_ref &&
1165 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) ?
1166 (rc->avg_frame_bandwidth * rc->baseline_gf_interval * af_ratio) /
1167 (rc->baseline_gf_interval + af_ratio - 1) :
1168 (rc->avg_frame_bandwidth * rc->baseline_gf_interval) /
1169 (rc->baseline_gf_interval + af_ratio - 1);
1171 target = rc->avg_frame_bandwidth;
1173 return vp9_rc_clamp_pframe_target_size(cpi, target);
1176 static int calc_iframe_target_size_one_pass_vbr(const VP9_COMP *const cpi) {
1177 static const int kf_ratio = 25;
1178 const RATE_CONTROL *rc = &cpi->rc;
1179 const int target = rc->avg_frame_bandwidth * kf_ratio;
1180 return vp9_rc_clamp_iframe_target_size(cpi, target);
1183 void vp9_rc_get_one_pass_vbr_params(VP9_COMP *cpi) {
1184 VP9_COMMON *const cm = &cpi->common;
1185 RATE_CONTROL *const rc = &cpi->rc;
1187 if (!cpi->refresh_alt_ref_frame &&
1188 (cm->current_video_frame == 0 ||
1189 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1190 rc->frames_to_key == 0 ||
1191 (cpi->oxcf.auto_key && test_for_kf_one_pass(cpi)))) {
1192 cm->frame_type = KEY_FRAME;
1193 rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1194 rc->frames_to_key == 0;
1195 rc->frames_to_key = cpi->oxcf.key_freq;
1196 rc->kf_boost = DEFAULT_KF_BOOST;
1197 rc->source_alt_ref_active = 0;
1199 cm->frame_type = INTER_FRAME;
1201 if (rc->frames_till_gf_update_due == 0) {
1202 rc->baseline_gf_interval = DEFAULT_GF_INTERVAL;
1203 rc->frames_till_gf_update_due = rc->baseline_gf_interval;
1204 // NOTE: frames_till_gf_update_due must be <= frames_to_key.
1205 if (rc->frames_till_gf_update_due > rc->frames_to_key)
1206 rc->frames_till_gf_update_due = rc->frames_to_key;
1207 cpi->refresh_golden_frame = 1;
1208 rc->source_alt_ref_pending = USE_ALTREF_FOR_ONE_PASS;
1209 rc->gfu_boost = DEFAULT_GF_BOOST;
1211 if (cm->frame_type == KEY_FRAME)
1212 target = calc_iframe_target_size_one_pass_vbr(cpi);
1214 target = calc_pframe_target_size_one_pass_vbr(cpi);
1215 vp9_rc_set_frame_target(cpi, target);
1218 static int calc_pframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1219 const VP9EncoderConfig *oxcf = &cpi->oxcf;
1220 const RATE_CONTROL *rc = &cpi->rc;
1221 const SVC *const svc = &cpi->svc;
1222 const int64_t diff = oxcf->optimal_buffer_level - rc->buffer_level;
1223 const int64_t one_pct_bits = 1 + oxcf->optimal_buffer_level / 100;
1224 int min_frame_target = MAX(rc->avg_frame_bandwidth >> 4, FRAME_OVERHEAD_BITS);
1225 int target = rc->avg_frame_bandwidth;
1226 if (svc->number_temporal_layers > 1 &&
1227 oxcf->rc_mode == RC_MODE_CBR) {
1228 // Note that for layers, avg_frame_bandwidth is the cumulative
1229 // per-frame-bandwidth. For the target size of this frame, use the
1230 // layer average frame size (i.e., non-cumulative per-frame-bw).
1231 int current_temporal_layer = svc->temporal_layer_id;
1232 const LAYER_CONTEXT *lc = &svc->layer_context[current_temporal_layer];
1233 target = lc->avg_frame_size;
1234 min_frame_target = MAX(lc->avg_frame_size >> 4, FRAME_OVERHEAD_BITS);
1237 // Lower the target bandwidth for this frame.
1238 const int pct_low = (int)MIN(diff / one_pct_bits, oxcf->under_shoot_pct);
1239 target -= (target * pct_low) / 200;
1240 } else if (diff < 0) {
1241 // Increase the target bandwidth for this frame.
1242 const int pct_high = (int)MIN(-diff / one_pct_bits, oxcf->over_shoot_pct);
1243 target += (target * pct_high) / 200;
1245 return MAX(min_frame_target, target);
1248 static int calc_iframe_target_size_one_pass_cbr(const VP9_COMP *cpi) {
1249 const RATE_CONTROL *rc = &cpi->rc;
1250 const VP9EncoderConfig *oxcf = &cpi->oxcf;
1251 const SVC *const svc = &cpi->svc;
1253 if (cpi->common.current_video_frame == 0) {
1254 target = ((cpi->oxcf.starting_buffer_level / 2) > INT_MAX)
1255 ? INT_MAX : (int)(cpi->oxcf.starting_buffer_level / 2);
1258 double framerate = oxcf->framerate;
1259 if (svc->number_temporal_layers > 1 &&
1260 oxcf->rc_mode == RC_MODE_CBR) {
1261 // Use the layer framerate for temporal layers CBR mode.
1262 const LAYER_CONTEXT *lc = &svc->layer_context[svc->temporal_layer_id];
1263 framerate = lc->framerate;
1265 kf_boost = MAX(kf_boost, (int)(2 * framerate - 16));
1266 if (rc->frames_since_key < framerate / 2) {
1267 kf_boost = (int)(kf_boost * rc->frames_since_key /
1270 target = ((16 + kf_boost) * rc->avg_frame_bandwidth) >> 4;
1272 return vp9_rc_clamp_iframe_target_size(cpi, target);
1275 void vp9_rc_get_svc_params(VP9_COMP *cpi) {
1276 VP9_COMMON *const cm = &cpi->common;
1277 RATE_CONTROL *const rc = &cpi->rc;
1278 int target = rc->avg_frame_bandwidth;
1279 if ((cm->current_video_frame == 0) ||
1280 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1281 (cpi->oxcf.auto_key && (rc->frames_since_key %
1282 cpi->oxcf.key_freq == 0))) {
1283 cm->frame_type = KEY_FRAME;
1284 rc->source_alt_ref_active = 0;
1286 if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
1287 cpi->svc.layer_context[cpi->svc.spatial_layer_id].is_key_frame = 1;
1290 if (cpi->pass == 0 && cpi->oxcf.rc_mode == RC_MODE_CBR) {
1291 target = calc_iframe_target_size_one_pass_cbr(cpi);
1294 cm->frame_type = INTER_FRAME;
1296 if (cpi->use_svc && cpi->svc.number_temporal_layers == 1) {
1297 LAYER_CONTEXT *lc = &cpi->svc.layer_context[cpi->svc.spatial_layer_id];
1298 if (cpi->svc.spatial_layer_id == 0) {
1299 lc->is_key_frame = 0;
1301 lc->is_key_frame = cpi->svc.layer_context[0].is_key_frame;
1305 if (cpi->pass == 0 && cpi->oxcf.rc_mode == RC_MODE_CBR) {
1306 target = calc_pframe_target_size_one_pass_cbr(cpi);
1309 vp9_rc_set_frame_target(cpi, target);
1310 rc->frames_till_gf_update_due = INT_MAX;
1311 rc->baseline_gf_interval = INT_MAX;
1314 void vp9_rc_get_one_pass_cbr_params(VP9_COMP *cpi) {
1315 VP9_COMMON *const cm = &cpi->common;
1316 RATE_CONTROL *const rc = &cpi->rc;
1318 if ((cm->current_video_frame == 0 ||
1319 (cpi->frame_flags & FRAMEFLAGS_KEY) ||
1320 rc->frames_to_key == 0 ||
1321 (cpi->oxcf.auto_key && test_for_kf_one_pass(cpi)))) {
1322 cm->frame_type = KEY_FRAME;
1323 rc->this_key_frame_forced = cm->current_video_frame != 0 &&
1324 rc->frames_to_key == 0;
1325 rc->frames_to_key = cpi->oxcf.key_freq;
1326 rc->kf_boost = DEFAULT_KF_BOOST;
1327 rc->source_alt_ref_active = 0;
1328 target = calc_iframe_target_size_one_pass_cbr(cpi);
1330 cm->frame_type = INTER_FRAME;
1331 target = calc_pframe_target_size_one_pass_cbr(cpi);
1333 vp9_rc_set_frame_target(cpi, target);
1334 // Don't use gf_update by default in CBR mode.
1335 rc->frames_till_gf_update_due = INT_MAX;
1336 rc->baseline_gf_interval = INT_MAX;
1339 int vp9_compute_qdelta(const RATE_CONTROL *rc, double qstart, double qtarget) {
1340 int start_index = rc->worst_quality;
1341 int target_index = rc->worst_quality;
1344 // Convert the average q value to an index.
1345 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1347 if (vp9_convert_qindex_to_q(i) >= qstart)
1351 // Convert the q target to an index
1352 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1354 if (vp9_convert_qindex_to_q(i) >= qtarget)
1358 return target_index - start_index;
1361 int vp9_compute_qdelta_by_rate(const RATE_CONTROL *rc, FRAME_TYPE frame_type,
1362 int qindex, double rate_target_ratio) {
1363 int target_index = rc->worst_quality;
1366 // Look up the current projected bits per block for the base index
1367 const int base_bits_per_mb = vp9_rc_bits_per_mb(frame_type, qindex, 1.0);
1369 // Find the target bits per mb based on the base value and given ratio.
1370 const int target_bits_per_mb = (int)(rate_target_ratio * base_bits_per_mb);
1372 // Convert the q target to an index
1373 for (i = rc->best_quality; i < rc->worst_quality; ++i) {
1375 if (vp9_rc_bits_per_mb(frame_type, i, 1.0) <= target_bits_per_mb )
1379 return target_index - qindex;
1382 void vp9_rc_update_framerate(VP9_COMP *cpi) {
1383 const VP9_COMMON *const cm = &cpi->common;
1384 const VP9EncoderConfig *const oxcf = &cpi->oxcf;
1385 RATE_CONTROL *const rc = &cpi->rc;
1388 rc->avg_frame_bandwidth = (int)(oxcf->target_bandwidth / oxcf->framerate);
1389 rc->min_frame_bandwidth = (int)(rc->avg_frame_bandwidth *
1390 oxcf->two_pass_vbrmin_section / 100);
1392 rc->min_frame_bandwidth = MAX(rc->min_frame_bandwidth, FRAME_OVERHEAD_BITS);
1394 // A maximum bitrate for a frame is defined.
1395 // The baseline for this aligns with HW implementations that
1396 // can support decode of 1080P content up to a bitrate of MAX_MB_RATE bits
1397 // per 16x16 MB (averaged over a frame). However this limit is extended if
1398 // a very high rate is given on the command line or the the rate cannnot
1399 // be acheived because of a user specificed max q (e.g. when the user
1400 // specifies lossless encode.
1401 vbr_max_bits = (int)(((int64_t)rc->avg_frame_bandwidth *
1402 oxcf->two_pass_vbrmax_section) / 100);
1403 rc->max_frame_bandwidth = MAX(MAX((cm->MBs * MAX_MB_RATE), MAXRATE_1080P),
1406 // Set Maximum gf/arf interval
1407 rc->max_gf_interval = 16;
1409 // Extended interval for genuinely static scenes
1410 rc->static_scene_max_gf_interval = cpi->oxcf.key_freq >> 1;
1412 // Special conditions when alt ref frame enabled in lagged compress mode
1413 if (oxcf->play_alternate && oxcf->lag_in_frames) {
1414 if (rc->max_gf_interval > oxcf->lag_in_frames - 1)
1415 rc->max_gf_interval = oxcf->lag_in_frames - 1;
1417 if (rc->static_scene_max_gf_interval > oxcf->lag_in_frames - 1)
1418 rc->static_scene_max_gf_interval = oxcf->lag_in_frames - 1;
1421 if (rc->max_gf_interval > rc->static_scene_max_gf_interval)
1422 rc->max_gf_interval = rc->static_scene_max_gf_interval;