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.
19 #include "vp9/common/vp9_alloccommon.h"
20 #include "vp9/common/vp9_common.h"
21 #include "vp9/encoder/vp9_ratectrl.h"
22 #include "vp9/common/vp9_entropymode.h"
23 #include "vpx_mem/vpx_mem.h"
24 #include "vp9/common/vp9_systemdependent.h"
25 #include "vp9/encoder/vp9_encodemv.h"
26 #include "vp9/common/vp9_quant_common.h"
27 #include "vp9/common/vp9_seg_common.h"
29 #define LIMIT_QRANGE_FOR_ALTREF_AND_KEY 1
31 #define MIN_BPB_FACTOR 0.005
32 #define MAX_BPB_FACTOR 50
34 // Bits Per MB at different Q (Multiplied by 512)
35 #define BPER_MB_NORMBITS 9
37 // Tables relating active max Q to active min Q
38 static int kf_low_motion_minq[QINDEX_RANGE];
39 static int kf_high_motion_minq[QINDEX_RANGE];
40 static int gf_low_motion_minq[QINDEX_RANGE];
41 static int gf_high_motion_minq[QINDEX_RANGE];
42 static int inter_minq[QINDEX_RANGE];
43 static int afq_low_motion_minq[QINDEX_RANGE];
44 static int afq_high_motion_minq[QINDEX_RANGE];
45 static int gf_high = 2000;
46 static int gf_low = 400;
47 static int kf_high = 5000;
48 static int kf_low = 400;
50 // Functions to compute the active minq lookup table entries based on a
51 // formulaic approach to facilitate easier adjustment of the Q tables.
52 // The formulae were derived from computing a 3rd order polynomial best
53 // fit to the original data (after plotting real maxq vs minq (not q index))
54 static int calculate_minq_index(double maxq,
55 double x3, double x2, double x1, double c) {
57 const double minqtarget = MIN(((x3 * maxq + x2) * maxq + x1) * maxq + c,
60 // Special case handling to deal with the step from q2.0
61 // down to lossless mode represented by q 1.0.
62 if (minqtarget <= 2.0)
65 for (i = 0; i < QINDEX_RANGE; i++) {
66 if (minqtarget <= vp9_convert_qindex_to_q(i))
70 return QINDEX_RANGE - 1;
73 void vp9_rc_init_minq_luts(void) {
76 for (i = 0; i < QINDEX_RANGE; i++) {
77 const double maxq = vp9_convert_qindex_to_q(i);
80 kf_low_motion_minq[i] = calculate_minq_index(maxq,
85 kf_high_motion_minq[i] = calculate_minq_index(maxq,
91 gf_low_motion_minq[i] = calculate_minq_index(maxq,
96 gf_high_motion_minq[i] = calculate_minq_index(maxq,
101 afq_low_motion_minq[i] = calculate_minq_index(maxq,
106 afq_high_motion_minq[i] = calculate_minq_index(maxq,
111 inter_minq[i] = calculate_minq_index(maxq,
119 // These functions use formulaic calculations to make playing with the
120 // quantizer tables easier. If necessary they can be replaced by lookup
121 // tables if and when things settle down in the experimental bitstream
122 double vp9_convert_qindex_to_q(int qindex) {
123 // Convert the index to a real Q value (scaled down to match old Q values)
124 return vp9_ac_quant(qindex, 0) / 4.0;
127 int vp9_rc_bits_per_mb(FRAME_TYPE frame_type, int qindex,
128 double correction_factor) {
129 const double q = vp9_convert_qindex_to_q(qindex);
130 int enumerator = frame_type == KEY_FRAME ? 3300000 : 2250000;
132 // q based adjustment to baseline enumerator
133 enumerator += (int)(enumerator * q) >> 12;
134 return (int)(0.5 + (enumerator * correction_factor / q));
137 void vp9_save_coding_context(VP9_COMP *cpi) {
138 CODING_CONTEXT *const cc = &cpi->coding_context;
139 VP9_COMMON *cm = &cpi->common;
141 // Stores a snapshot of key state variables which can subsequently be
142 // restored with a call to vp9_restore_coding_context. These functions are
143 // intended for use in a re-code loop in vp9_compress_frame where the
144 // quantizer value is adjusted between loop iterations.
145 vp9_copy(cc->nmvjointcost, cpi->mb.nmvjointcost);
146 vp9_copy(cc->nmvcosts, cpi->mb.nmvcosts);
147 vp9_copy(cc->nmvcosts_hp, cpi->mb.nmvcosts_hp);
149 vp9_copy(cc->segment_pred_probs, cm->seg.pred_probs);
151 vpx_memcpy(cpi->coding_context.last_frame_seg_map_copy,
152 cm->last_frame_seg_map, (cm->mi_rows * cm->mi_cols));
154 vp9_copy(cc->last_ref_lf_deltas, cm->lf.last_ref_deltas);
155 vp9_copy(cc->last_mode_lf_deltas, cm->lf.last_mode_deltas);
160 void vp9_restore_coding_context(VP9_COMP *cpi) {
161 CODING_CONTEXT *const cc = &cpi->coding_context;
162 VP9_COMMON *cm = &cpi->common;
164 // Restore key state variables to the snapshot state stored in the
165 // previous call to vp9_save_coding_context.
166 vp9_copy(cpi->mb.nmvjointcost, cc->nmvjointcost);
167 vp9_copy(cpi->mb.nmvcosts, cc->nmvcosts);
168 vp9_copy(cpi->mb.nmvcosts_hp, cc->nmvcosts_hp);
170 vp9_copy(cm->seg.pred_probs, cc->segment_pred_probs);
172 vpx_memcpy(cm->last_frame_seg_map,
173 cpi->coding_context.last_frame_seg_map_copy,
174 (cm->mi_rows * cm->mi_cols));
176 vp9_copy(cm->lf.last_ref_deltas, cc->last_ref_lf_deltas);
177 vp9_copy(cm->lf.last_mode_deltas, cc->last_mode_lf_deltas);
182 void vp9_setup_key_frame(VP9_COMP *cpi) {
183 VP9_COMMON *cm = &cpi->common;
185 vp9_setup_past_independence(cm);
187 // interval before next GF
188 cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
189 /* All buffers are implicitly updated on key frames. */
190 cpi->refresh_golden_frame = 1;
191 cpi->refresh_alt_ref_frame = 1;
194 void vp9_setup_inter_frame(VP9_COMP *cpi) {
195 VP9_COMMON *cm = &cpi->common;
196 if (cm->error_resilient_mode || cm->intra_only)
197 vp9_setup_past_independence(cm);
199 assert(cm->frame_context_idx < FRAME_CONTEXTS);
200 cm->fc = cm->frame_contexts[cm->frame_context_idx];
203 static int estimate_bits_at_q(int frame_kind, int q, int mbs,
204 double correction_factor) {
205 const int bpm = (int)(vp9_rc_bits_per_mb(frame_kind, q, correction_factor));
207 // Attempt to retain reasonable accuracy without overflow. The cutoff is
208 // chosen such that the maximum product of Bpm and MBs fits 31 bits. The
209 // largest Bpm takes 20 bits.
210 return (mbs > (1 << 11)) ? (bpm >> BPER_MB_NORMBITS) * mbs
211 : (bpm * mbs) >> BPER_MB_NORMBITS;
215 static void calc_iframe_target_size(VP9_COMP *cpi) {
216 // boost defaults to half second
219 // Clear down mmx registers to allow floating point in what follows
220 vp9_clear_system_state(); // __asm emms;
223 target = cpi->rc.per_frame_bandwidth;
226 if (cpi->pass == 0) {
227 if (cpi->common.current_video_frame == 0) {
228 target = cpi->oxcf.starting_buffer_level / 2;
230 // TODO(marpan): Add in adjustment based on Q.
231 // If this keyframe was forced, use a more recent Q estimate.
232 // int Q = (cpi->common.frame_flags & FRAMEFLAGS_KEY) ?
233 // cpi->rc.avg_frame_qindex : cpi->rc.ni_av_qi;
234 int initial_boost = 32;
235 // Boost depends somewhat on frame rate.
236 int kf_boost = MAX(initial_boost, (int)(2 * cpi->output_framerate - 16));
237 // Adjustment up based on q: need to fix.
238 // kf_boost = kf_boost * kfboost_qadjust(Q) / 100;
239 // Frame separation adjustment (down).
240 if (cpi->rc.frames_since_key < cpi->output_framerate / 2) {
241 kf_boost = (int)(kf_boost * cpi->rc.frames_since_key /
242 (cpi->output_framerate / 2));
244 kf_boost = (kf_boost < 16) ? 16 : kf_boost;
245 target = ((16 + kf_boost) * cpi->rc.per_frame_bandwidth) >> 4;
247 cpi->rc.active_worst_quality = cpi->rc.worst_quality;
250 if (cpi->oxcf.rc_max_intra_bitrate_pct) {
251 int max_rate = cpi->rc.per_frame_bandwidth
252 * cpi->oxcf.rc_max_intra_bitrate_pct / 100;
254 if (target > max_rate)
257 cpi->rc.this_frame_target = target;
260 // Do the best we can to define the parameters for the next GF based
261 // on what information we have available.
263 // In this experimental code only two pass is supported
264 // so we just use the interval determined in the two pass code.
265 static void calc_gf_params(VP9_COMP *cpi) {
266 // Set the gf interval
267 cpi->rc.frames_till_gf_update_due = cpi->rc.baseline_gf_interval;
270 // Update the buffer level: leaky bucket model.
271 void vp9_update_buffer_level(VP9_COMP *const cpi, int encoded_frame_size) {
272 VP9_COMMON *const cm = &cpi->common;
273 // Non-viewable frames are a special case and are treated as pure overhead.
274 if (!cm->show_frame) {
275 cpi->rc.bits_off_target -= encoded_frame_size;
277 cpi->rc.bits_off_target += cpi->rc.av_per_frame_bandwidth -
280 // Clip the buffer level to the maximum specified buffer size.
281 if (cpi->rc.bits_off_target > cpi->oxcf.maximum_buffer_size) {
282 cpi->rc.bits_off_target = cpi->oxcf.maximum_buffer_size;
284 cpi->rc.buffer_level = cpi->rc.bits_off_target;
287 int vp9_drop_frame(VP9_COMP *const cpi) {
288 if (!cpi->oxcf.drop_frames_water_mark) {
291 if (cpi->rc.buffer_level < 0) {
292 // Always drop if buffer is below 0.
295 // If buffer is below drop_mark, for now just drop every other frame
296 // (starting with the next frame) until it increases back over drop_mark.
297 int drop_mark = (int)(cpi->oxcf.drop_frames_water_mark *
298 cpi->oxcf.optimal_buffer_level / 100);
299 if ((cpi->rc.buffer_level > drop_mark) &&
300 (cpi->rc.decimation_factor > 0)) {
301 --cpi->rc.decimation_factor;
302 } else if (cpi->rc.buffer_level <= drop_mark &&
303 cpi->rc.decimation_factor == 0) {
304 cpi->rc.decimation_factor = 1;
306 if (cpi->rc.decimation_factor > 0) {
307 if (cpi->rc.decimation_count > 0) {
308 --cpi->rc.decimation_count;
311 cpi->rc.decimation_count = cpi->rc.decimation_factor;
315 cpi->rc.decimation_count = 0;
322 // Adjust active_worst_quality level based on buffer level.
323 static int adjust_active_worst_quality_from_buffer_level(const VP9_COMP *cpi) {
324 // Adjust active_worst_quality: If buffer is above the optimal/target level,
325 // bring active_worst_quality down depending on fullness over buffer.
326 // If buffer is below the optimal level, let the active_worst_quality go from
327 // ambient Q (at buffer = optimal level) to worst_quality level
328 // (at buffer = critical level).
329 int active_worst_quality = cpi->rc.active_worst_quality;
330 // Maximum limit for down adjustment, ~20%.
331 int max_adjustment_down = active_worst_quality / 5;
332 // Buffer level below which we push active_worst to worst_quality.
333 int critical_level = cpi->oxcf.optimal_buffer_level >> 2;
335 int buff_lvl_step = 0;
336 if (cpi->rc.buffer_level > cpi->oxcf.optimal_buffer_level) {
338 if (max_adjustment_down) {
339 buff_lvl_step = (int)((cpi->oxcf.maximum_buffer_size -
340 cpi->oxcf.optimal_buffer_level) / max_adjustment_down);
342 adjustment = (int)((cpi->rc.buffer_level -
343 cpi->oxcf.optimal_buffer_level) / buff_lvl_step);
345 active_worst_quality -= adjustment;
347 } else if (cpi->rc.buffer_level > critical_level) {
348 // Adjust up from ambient Q.
349 if (critical_level) {
350 buff_lvl_step = (cpi->oxcf.optimal_buffer_level - critical_level);
353 (cpi->rc.worst_quality - cpi->rc.avg_frame_qindex[INTER_FRAME]) *
354 (cpi->oxcf.optimal_buffer_level - cpi->rc.buffer_level) /
357 active_worst_quality = cpi->rc.avg_frame_qindex[INTER_FRAME] + adjustment;
360 // Set to worst_quality if buffer is below critical level.
361 active_worst_quality = cpi->rc.worst_quality;
363 return active_worst_quality;
366 // Adjust target frame size with respect to the buffering constraints:
367 static int target_size_from_buffer_level(const VP9_COMP *cpi) {
368 int this_frame_target = cpi->rc.this_frame_target;
370 int percent_high = 0;
371 int one_percent_bits = (int)(1 + cpi->oxcf.optimal_buffer_level / 100);
372 if (cpi->rc.buffer_level < cpi->oxcf.optimal_buffer_level) {
373 percent_low = (int)((cpi->oxcf.optimal_buffer_level - cpi->rc.buffer_level)
375 if (percent_low > cpi->oxcf.under_shoot_pct) {
376 percent_low = cpi->oxcf.under_shoot_pct;
377 } else if (percent_low < 0) {
380 // Lower the target bandwidth for this frame.
381 this_frame_target -= (this_frame_target * percent_low) / 200;
382 } else if (cpi->rc.buffer_level > cpi->oxcf.optimal_buffer_level) {
383 percent_high = (int)((cpi->rc.buffer_level - cpi->oxcf.optimal_buffer_level)
385 if (percent_high > cpi->oxcf.over_shoot_pct) {
386 percent_high = cpi->oxcf.over_shoot_pct;
387 } else if (percent_high < 0) {
390 // Increase the target bandwidth for this frame.
391 this_frame_target += (this_frame_target * percent_high) / 200;
393 return this_frame_target;
396 static void calc_pframe_target_size(VP9_COMP *const cpi) {
397 int min_frame_target = MAX(cpi->rc.min_frame_bandwidth,
398 cpi->rc.av_per_frame_bandwidth >> 5);
399 if (cpi->refresh_alt_ref_frame) {
400 // Special alt reference frame case
401 // Per frame bit target for the alt ref frame
402 cpi->rc.per_frame_bandwidth = cpi->twopass.gf_bits;
403 cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
405 // Normal frames (gf and inter).
406 cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
407 // Set target frame size based on buffer level, for 1 pass CBR.
408 if (cpi->pass == 0 && cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) {
409 // Need to decide how low min_frame_target should be for 1-pass CBR.
410 // For now, use: cpi->rc.av_per_frame_bandwidth / 16:
411 min_frame_target = MAX(cpi->rc.av_per_frame_bandwidth >> 4,
412 FRAME_OVERHEAD_BITS);
413 cpi->rc.this_frame_target = target_size_from_buffer_level(cpi);
414 // Adjust qp-max based on buffer level.
415 cpi->rc.active_worst_quality =
416 adjust_active_worst_quality_from_buffer_level(cpi);
420 // Check that the total sum of adjustments is not above the maximum allowed.
421 // That is, having allowed for the KF and GF penalties, we have not pushed
422 // the current inter-frame target too low. If the adjustment we apply here is
423 // not capable of recovering all the extra bits we have spent in the KF or GF,
424 // then the remainder will have to be recovered over a longer time span via
425 // other buffer / rate control mechanisms.
426 if (cpi->rc.this_frame_target < min_frame_target) {
427 cpi->rc.this_frame_target = min_frame_target;
430 // Adjust target frame size for Golden Frames:
431 if (cpi->refresh_golden_frame) {
432 // If we are using alternate ref instead of gf then do not apply the boost
433 // It will instead be applied to the altref update
434 // Jims modified boost
435 if (!cpi->rc.source_alt_ref_active) {
436 // The spend on the GF is defined in the two pass code
437 // for two pass encodes
438 cpi->rc.this_frame_target = cpi->rc.per_frame_bandwidth;
440 // If there is an active ARF at this location use the minimum
441 // bits on this frame even if it is a constructed arf.
442 // The active maximum quantizer insures that an appropriate
443 // number of bits will be spent if needed for constructed ARFs.
444 cpi->rc.this_frame_target = 0;
449 void vp9_rc_update_rate_correction_factors(VP9_COMP *cpi, int damp_var) {
450 const int q = cpi->common.base_qindex;
451 int correction_factor = 100;
452 double rate_correction_factor;
453 double adjustment_limit;
455 int projected_size_based_on_q = 0;
457 // Clear down mmx registers to allow floating point in what follows
458 vp9_clear_system_state(); // __asm emms;
460 if (cpi->common.frame_type == KEY_FRAME) {
461 rate_correction_factor = cpi->rc.key_frame_rate_correction_factor;
463 if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
464 rate_correction_factor = cpi->rc.gf_rate_correction_factor;
466 rate_correction_factor = cpi->rc.rate_correction_factor;
469 // Work out how big we would have expected the frame to be at this Q given
470 // the current correction factor.
471 // Stay in double to avoid int overflow when values are large
472 projected_size_based_on_q = estimate_bits_at_q(cpi->common.frame_type, q,
474 rate_correction_factor);
476 // Work out a size correction factor.
477 if (projected_size_based_on_q > 0)
479 (100 * cpi->rc.projected_frame_size) / projected_size_based_on_q;
481 // More heavily damped adjustment used if we have been oscillating either side
485 adjustment_limit = 0.75;
488 adjustment_limit = 0.375;
492 adjustment_limit = 0.25;
496 if (correction_factor > 102) {
497 // We are not already at the worst allowable quality
499 (int)(100 + ((correction_factor - 100) * adjustment_limit));
500 rate_correction_factor =
501 ((rate_correction_factor * correction_factor) / 100);
503 // Keep rate_correction_factor within limits
504 if (rate_correction_factor > MAX_BPB_FACTOR)
505 rate_correction_factor = MAX_BPB_FACTOR;
506 } else if (correction_factor < 99) {
507 // We are not already at the best allowable quality
509 (int)(100 - ((100 - correction_factor) * adjustment_limit));
510 rate_correction_factor =
511 ((rate_correction_factor * correction_factor) / 100);
513 // Keep rate_correction_factor within limits
514 if (rate_correction_factor < MIN_BPB_FACTOR)
515 rate_correction_factor = MIN_BPB_FACTOR;
518 if (cpi->common.frame_type == KEY_FRAME) {
519 cpi->rc.key_frame_rate_correction_factor = rate_correction_factor;
521 if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
522 cpi->rc.gf_rate_correction_factor = rate_correction_factor;
524 cpi->rc.rate_correction_factor = rate_correction_factor;
529 int vp9_rc_regulate_q(const VP9_COMP *cpi, int target_bits_per_frame,
530 int active_best_quality, int active_worst_quality) {
531 int q = active_worst_quality;
534 int last_error = INT_MAX;
535 int target_bits_per_mb;
536 int bits_per_mb_at_this_q;
537 double correction_factor;
539 // Select the appropriate correction factor based upon type of frame.
540 if (cpi->common.frame_type == KEY_FRAME) {
541 correction_factor = cpi->rc.key_frame_rate_correction_factor;
543 if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame)
544 correction_factor = cpi->rc.gf_rate_correction_factor;
546 correction_factor = cpi->rc.rate_correction_factor;
549 // Calculate required scaling factor based on target frame size and size of
550 // frame produced using previous Q.
551 if (target_bits_per_frame >= (INT_MAX >> BPER_MB_NORMBITS))
553 (target_bits_per_frame / cpi->common.MBs)
554 << BPER_MB_NORMBITS; // Case where we would overflow int
557 (target_bits_per_frame << BPER_MB_NORMBITS) / cpi->common.MBs;
559 i = active_best_quality;
562 bits_per_mb_at_this_q = (int)vp9_rc_bits_per_mb(cpi->common.frame_type, i,
565 if (bits_per_mb_at_this_q <= target_bits_per_mb) {
566 if ((target_bits_per_mb - bits_per_mb_at_this_q) <= last_error)
573 last_error = bits_per_mb_at_this_q - target_bits_per_mb;
575 } while (++i <= active_worst_quality);
580 static int get_active_quality(int q,
584 int *low_motion_minq,
585 int *high_motion_minq) {
586 int active_best_quality;
587 if (gfu_boost > high) {
588 active_best_quality = low_motion_minq[q];
589 } else if (gfu_boost < low) {
590 active_best_quality = high_motion_minq[q];
592 const int gap = high - low;
593 const int offset = high - gfu_boost;
594 const int qdiff = high_motion_minq[q] - low_motion_minq[q];
595 const int adjustment = ((offset * qdiff) + (gap >> 1)) / gap;
596 active_best_quality = low_motion_minq[q] + adjustment;
598 return active_best_quality;
601 int vp9_rc_pick_q_and_adjust_q_bounds(const VP9_COMP *cpi,
604 const VP9_COMMON *const cm = &cpi->common;
605 int active_best_quality;
606 int active_worst_quality = cpi->rc.active_worst_quality;
609 if (frame_is_intra_only(cm)) {
610 active_best_quality = cpi->rc.best_quality;
611 #if !CONFIG_MULTIPLE_ARF
612 // Handle the special case for key frames forced when we have75 reached
613 // the maximum key frame interval. Here force the Q to a range
614 // based on the ambient Q to reduce the risk of popping.
615 if (cpi->rc.this_key_frame_forced) {
617 int qindex = cpi->rc.last_boosted_qindex;
618 double last_boosted_q = vp9_convert_qindex_to_q(qindex);
620 delta_qindex = vp9_compute_qdelta(cpi, last_boosted_q,
621 (last_boosted_q * 0.75));
622 active_best_quality = MAX(qindex + delta_qindex,
623 cpi->rc.best_quality);
624 } else if (!(cpi->pass == 0 && cpi->common.current_video_frame == 0)) {
625 // not first frame of one pass
626 double q_adj_factor = 1.0;
629 // Baseline value derived from cpi->active_worst_quality and kf boost
630 active_best_quality = get_active_quality(active_worst_quality,
634 kf_high_motion_minq);
636 // Allow somewhat lower kf minq with small image formats.
637 if ((cm->width * cm->height) <= (352 * 288)) {
638 q_adj_factor -= 0.25;
641 // Make a further adjustment based on the kf zero motion measure.
642 q_adj_factor += 0.05 - (0.001 * (double)cpi->twopass.kf_zeromotion_pct);
644 // Convert the adjustment factor to a qindex delta
645 // on active_best_quality.
646 q_val = vp9_convert_qindex_to_q(active_best_quality);
647 active_best_quality +=
648 vp9_compute_qdelta(cpi, q_val, (q_val * q_adj_factor));
652 // Force the KF quantizer to be 30% of the active_worst_quality.
653 current_q = vp9_convert_qindex_to_q(active_worst_quality);
654 active_best_quality = active_worst_quality
655 + vp9_compute_qdelta(cpi, current_q, current_q * 0.3);
657 } else if (!cpi->rc.is_src_frame_alt_ref &&
658 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
660 // Use the lower of active_worst_quality and recent
661 // average Q as basis for GF/ARF best Q limit unless last frame was
663 if (cpi->rc.frames_since_key > 1 &&
664 cpi->rc.avg_frame_qindex[INTER_FRAME] < active_worst_quality) {
665 q = cpi->rc.avg_frame_qindex[INTER_FRAME];
667 q = active_worst_quality;
669 // For constrained quality dont allow Q less than the cq level
670 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
671 if (q < cpi->cq_target_quality)
672 q = cpi->cq_target_quality;
673 if (cpi->rc.frames_since_key > 1) {
674 active_best_quality = get_active_quality(q, cpi->rc.gfu_boost,
677 afq_high_motion_minq);
679 active_best_quality = get_active_quality(q, cpi->rc.gfu_boost,
682 gf_high_motion_minq);
684 // Constrained quality use slightly lower active best.
685 active_best_quality = active_best_quality * 15 / 16;
687 } else if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
688 if (!cpi->refresh_alt_ref_frame) {
689 active_best_quality = cpi->cq_target_quality;
691 if (cpi->rc.frames_since_key > 1) {
692 active_best_quality = get_active_quality(
693 q, cpi->rc.gfu_boost, gf_low, gf_high,
694 afq_low_motion_minq, afq_high_motion_minq);
696 active_best_quality = get_active_quality(
697 q, cpi->rc.gfu_boost, gf_low, gf_high,
698 gf_low_motion_minq, gf_high_motion_minq);
702 active_best_quality = get_active_quality(
703 q, cpi->rc.gfu_boost, gf_low, gf_high,
704 gf_low_motion_minq, gf_high_motion_minq);
707 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
708 active_best_quality = cpi->cq_target_quality;
710 if (cpi->pass == 0 &&
711 cpi->rc.avg_frame_qindex[INTER_FRAME] < active_worst_quality)
712 // 1-pass: for now, use the average Q for the active_best, if its lower
713 // than active_worst.
714 active_best_quality = inter_minq[cpi->rc.avg_frame_qindex[INTER_FRAME]];
716 active_best_quality = inter_minq[active_worst_quality];
718 // For the constrained quality mode we don't want
719 // q to fall below the cq level.
720 if ((cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) &&
721 (active_best_quality < cpi->cq_target_quality)) {
722 // If we are strongly undershooting the target rate in the last
723 // frames then use the user passed in cq value not the auto
725 if (cpi->rc.rolling_actual_bits < cpi->rc.min_frame_bandwidth)
726 active_best_quality = cpi->oxcf.cq_level;
728 active_best_quality = cpi->cq_target_quality;
733 // Clip the active best and worst quality values to limits
734 if (active_worst_quality > cpi->rc.worst_quality)
735 active_worst_quality = cpi->rc.worst_quality;
737 if (active_best_quality < cpi->rc.best_quality)
738 active_best_quality = cpi->rc.best_quality;
740 if (active_best_quality > cpi->rc.worst_quality)
741 active_best_quality = cpi->rc.worst_quality;
743 if (active_worst_quality < active_best_quality)
744 active_worst_quality = active_best_quality;
746 *top_index = active_worst_quality;
747 *bottom_index = active_best_quality;
749 #if LIMIT_QRANGE_FOR_ALTREF_AND_KEY
750 // Limit Q range for the adaptive loop.
751 if (cm->frame_type == KEY_FRAME && !cpi->rc.this_key_frame_forced) {
752 if (!(cpi->pass == 0 && cpi->common.current_video_frame == 0)) {
753 *top_index = active_worst_quality;
755 (active_worst_quality + active_best_quality * 3) / 4;
757 } else if (!cpi->rc.is_src_frame_alt_ref &&
758 (cpi->oxcf.end_usage != USAGE_STREAM_FROM_SERVER) &&
759 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
761 (active_worst_quality + active_best_quality) / 2;
765 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
766 q = active_best_quality;
767 // Special case code to try and match quality with forced key frames
768 } else if ((cm->frame_type == KEY_FRAME) && cpi->rc.this_key_frame_forced) {
769 q = cpi->rc.last_boosted_qindex;
771 q = vp9_rc_regulate_q(cpi, cpi->rc.this_frame_target,
772 active_best_quality, active_worst_quality);
776 #if CONFIG_MULTIPLE_ARF
777 // Force the quantizer determined by the coding order pattern.
778 if (cpi->multi_arf_enabled && (cm->frame_type != KEY_FRAME) &&
779 cpi->oxcf.end_usage != USAGE_CONSTANT_QUALITY) {
781 double current_q = vp9_convert_qindex_to_q(active_worst_quality);
782 int level = cpi->this_frame_weight;
784 new_q = current_q * (1.0 - (0.2 * (cpi->max_arf_level - level)));
785 q = active_worst_quality +
786 vp9_compute_qdelta(cpi, current_q, new_q);
790 printf("frame:%d q:%d\n", cm->current_video_frame, q);
796 void vp9_rc_compute_frame_size_bounds(const VP9_COMP *cpi,
797 int this_frame_target,
798 int *frame_under_shoot_limit,
799 int *frame_over_shoot_limit) {
800 // Set-up bounds on acceptable frame size:
801 if (cpi->oxcf.end_usage == USAGE_CONSTANT_QUALITY) {
802 *frame_under_shoot_limit = 0;
803 *frame_over_shoot_limit = INT_MAX;
805 if (cpi->common.frame_type == KEY_FRAME) {
806 *frame_over_shoot_limit = this_frame_target * 9 / 8;
807 *frame_under_shoot_limit = this_frame_target * 7 / 8;
809 if (cpi->refresh_alt_ref_frame || cpi->refresh_golden_frame) {
810 *frame_over_shoot_limit = this_frame_target * 9 / 8;
811 *frame_under_shoot_limit = this_frame_target * 7 / 8;
813 // Stron overshoot limit for constrained quality
814 if (cpi->oxcf.end_usage == USAGE_CONSTRAINED_QUALITY) {
815 *frame_over_shoot_limit = this_frame_target * 11 / 8;
816 *frame_under_shoot_limit = this_frame_target * 2 / 8;
818 *frame_over_shoot_limit = this_frame_target * 11 / 8;
819 *frame_under_shoot_limit = this_frame_target * 5 / 8;
824 // For very small rate targets where the fractional adjustment
825 // (eg * 7/8) may be tiny make sure there is at least a minimum
827 *frame_over_shoot_limit += 200;
828 *frame_under_shoot_limit -= 200;
829 if (*frame_under_shoot_limit < 0)
830 *frame_under_shoot_limit = 0;
834 // return of 0 means drop frame
835 int vp9_rc_pick_frame_size_target(VP9_COMP *cpi) {
836 VP9_COMMON *cm = &cpi->common;
838 if (cm->frame_type == KEY_FRAME)
839 calc_iframe_target_size(cpi);
841 calc_pframe_target_size(cpi);
843 // Target rate per SB64 (including partial SB64s.
844 cpi->rc.sb64_target_rate = ((int64_t)cpi->rc.this_frame_target * 64 * 64) /
845 (cpi->common.width * cpi->common.height);
849 void vp9_rc_postencode_update(VP9_COMP *cpi, uint64_t bytes_used) {
850 VP9_COMMON *const cm = &cpi->common;
851 // Update rate control heuristics
852 cpi->rc.projected_frame_size = (bytes_used << 3);
854 // Post encode loop adjustment of Q prediction.
855 vp9_rc_update_rate_correction_factors(
856 cpi, (cpi->sf.recode_loop ||
857 cpi->oxcf.end_usage == USAGE_STREAM_FROM_SERVER) ? 2 : 0);
859 // Keep a record of last Q and ambient average Q.
860 if (cm->frame_type == KEY_FRAME) {
861 cpi->rc.last_q[KEY_FRAME] = cm->base_qindex;
862 cpi->rc.avg_frame_qindex[KEY_FRAME] =
863 (2 + 3 * cpi->rc.avg_frame_qindex[KEY_FRAME] + cm->base_qindex) >> 2;
864 } else if (!cpi->rc.is_src_frame_alt_ref &&
865 (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame)) {
866 cpi->rc.last_q[2] = cm->base_qindex;
867 cpi->rc.avg_frame_qindex[2] =
868 (2 + 3 * cpi->rc.avg_frame_qindex[2] + cm->base_qindex) >> 2;
870 cpi->rc.last_q[INTER_FRAME] = cm->base_qindex;
871 cpi->rc.avg_frame_qindex[INTER_FRAME] =
872 (2 + 3 * cpi->rc.avg_frame_qindex[INTER_FRAME] +
873 cm->base_qindex) >> 2;
875 cpi->rc.tot_q += vp9_convert_qindex_to_q(cm->base_qindex);
876 cpi->rc.avg_q = cpi->rc.tot_q / (double)cpi->rc.ni_frames;
878 // Calculate the average Q for normal inter frames (not key or GFU frames).
879 cpi->rc.ni_tot_qi += cm->base_qindex;
880 cpi->rc.ni_av_qi = cpi->rc.ni_tot_qi / cpi->rc.ni_frames;
883 // Keep record of last boosted (KF/KF/ARF) Q value.
884 // If the current frame is coded at a lower Q then we also update it.
885 // If all mbs in this group are skipped only update if the Q value is
886 // better than that already stored.
887 // This is used to help set quality in forced key frames to reduce popping
888 if ((cm->base_qindex < cpi->rc.last_boosted_qindex) ||
889 ((cpi->static_mb_pct < 100) &&
890 ((cm->frame_type == KEY_FRAME) || cpi->refresh_alt_ref_frame ||
891 (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)))) {
892 cpi->rc.last_boosted_qindex = cm->base_qindex;
895 vp9_update_buffer_level(cpi, cpi->rc.projected_frame_size);
897 // Rolling monitors of whether we are over or underspending used to help
898 // regulate min and Max Q in two pass.
899 if (cm->frame_type != KEY_FRAME) {
900 cpi->rc.rolling_target_bits =
901 ((cpi->rc.rolling_target_bits * 3) +
902 cpi->rc.this_frame_target + 2) / 4;
903 cpi->rc.rolling_actual_bits =
904 ((cpi->rc.rolling_actual_bits * 3) +
905 cpi->rc.projected_frame_size + 2) / 4;
906 cpi->rc.long_rolling_target_bits =
907 ((cpi->rc.long_rolling_target_bits * 31) +
908 cpi->rc.this_frame_target + 16) / 32;
909 cpi->rc.long_rolling_actual_bits =
910 ((cpi->rc.long_rolling_actual_bits * 31) +
911 cpi->rc.projected_frame_size + 16) / 32;
915 cpi->rc.total_actual_bits += cpi->rc.projected_frame_size;
918 cpi->rc.total_target_vs_actual += (cpi->rc.this_frame_target -
919 cpi->rc.projected_frame_size);
921 #ifndef DISABLE_RC_LONG_TERM_MEM
922 // Update bits left to the kf and gf groups to account for overshoot or
923 // undershoot on these frames
924 if (cm->frame_type == KEY_FRAME) {
925 cpi->twopass.kf_group_bits += cpi->rc.this_frame_target -
926 cpi->rc.projected_frame_size;
928 cpi->twopass.kf_group_bits = MAX(cpi->twopass.kf_group_bits, 0);
929 } else if (cpi->refresh_golden_frame || cpi->refresh_alt_ref_frame) {
930 cpi->twopass.gf_group_bits += cpi->rc.this_frame_target -
931 cpi->rc.projected_frame_size;
933 cpi->twopass.gf_group_bits = MAX(cpi->twopass.gf_group_bits, 0);