#[derive(Clone, Copy, Debug)]
pub enum Quality {
Qp(i32),
Bitrate(u64),
}
#[derive(Clone, Copy, Debug)]
pub enum Reach {
TooComplex {
times: f64,
},
TooSimple {
times: f64,
},
}
#[derive(Debug)]
pub struct RateControl {
target: f64,
k: f64,
slope: f64,
last: Option<(f64, f64)>,
pairs: u32,
prev_qp: Option<i32>,
seen: u32,
spent: f64,
done: u32,
total: Option<u32>,
qp_min: i32,
qp_max: i32,
pinned_coarse: bool,
pinned_fine: bool,
}
pub const PROBE_QP: i32 = 26;
const BLIND_HORIZON: f64 = 12.0;
const MAX_QP_STEP: i32 = 8;
const DEFAULT_SLOPE: f64 = 0.116;
const SLOPE_RANGE: (f64, f64) = (0.04, 0.50);
impl RateControl {
pub fn new(bits_per_second: u64, fps: u32, total: Option<u32>) -> Self {
let fps = fps.max(1) as f64;
Self {
target: bits_per_second as f64 / 8.0 / fps,
k: 0.0,
slope: DEFAULT_SLOPE,
last: None,
pairs: 0,
prev_qp: None,
seen: 0,
spent: 0.0,
done: 0,
total,
qp_min: 0,
qp_max: 51,
pinned_coarse: false,
pinned_fine: false,
}
}
pub fn clamp_qp(mut self, min: i32, max: i32) -> Self {
self.qp_min = min.clamp(0, 51);
self.qp_max = max.clamp(self.qp_min, 51);
self
}
pub fn next_qp(&self) -> i32 {
if self.seen == 0 {
return PROBE_QP.clamp(self.qp_min, self.qp_max);
}
let debt = self.spent - self.target * f64::from(self.done);
let horizon = match self.total {
Some(n) if n > self.done => f64::from(n - self.done).min(BLIND_HORIZON),
_ => BLIND_HORIZON,
}
.max(1.0);
let want = self.target - debt / horizon;
let want = want.clamp(self.target * 0.25, self.target * 4.0);
let qp = ((self.k - want.max(1.0).log2()) / self.slope).round() as i32;
let qp = match self.prev_qp {
Some(p) => qp.clamp(p - MAX_QP_STEP, p + MAX_QP_STEP),
None => qp,
};
qp.clamp(self.qp_min, self.qp_max)
}
pub fn observe(&mut self, qp: i32, bytes: usize) {
let lg = (bytes.max(1) as f64).log2();
let q = f64::from(qp);
if let Some((q0, lg0)) = self.last
&& (q - q0).abs() >= 2.0
{
let obs = ((lg0 - lg) / (q - q0)).clamp(SLOPE_RANGE.0, SLOPE_RANGE.1);
let w = if self.pairs == 0 { 1.0 } else { 0.7 };
self.slope = self.slope * (1.0 - w) + obs * w;
self.pairs += 1;
}
self.last = Some((q, lg));
self.prev_qp = Some(qp);
self.pinned_coarse |= qp >= self.qp_max;
self.pinned_fine |= qp <= self.qp_min;
let k_obs = lg + q * self.slope;
let weight = if self.seen == 0 {
1.0
} else {
(1.0 / f64::from(self.seen + 1)).max(0.15)
};
self.k = self.k * (1.0 - weight) + k_obs * weight;
self.seen += 1;
self.spent += bytes as f64;
self.done += 1;
}
pub fn seed(&mut self, qp: i32, bytes: usize) {
let lg = (bytes.max(1) as f64).log2();
self.k = lg + f64::from(qp) * self.slope;
self.last = Some((f64::from(qp), lg));
self.seen = 1;
}
pub fn probe_again(&self) -> Option<i32> {
let (last, _) = self.last?;
let want = self.next_qp();
((want - last as i32).abs() > 6).then_some(want)
}
pub fn seed_pair(&mut self, qp: i32, bytes: usize) {
let lg = (bytes.max(1) as f64).log2();
let q = f64::from(qp);
if let Some((q0, lg0)) = self.last
&& (q - q0).abs() >= 2.0
{
self.slope = ((lg0 - lg) / (q - q0)).clamp(SLOPE_RANGE.0, SLOPE_RANGE.1);
self.pairs += 1;
}
self.k = lg + q * self.slope;
self.last = Some((q, lg));
}
pub fn spent(&self) -> f64 {
self.spent
}
pub fn outcome(&self) -> Option<Reach> {
if self.done == 0 {
return None;
}
let ratio = self.spent / (self.target * f64::from(self.done));
if self.pinned_coarse && ratio > 1.10 {
Some(Reach::TooComplex { times: ratio })
} else if self.pinned_fine && ratio < 0.90 {
Some(Reach::TooSimple { times: 1.0 / ratio })
} else {
None
}
}
pub fn group_size(&self, memory_limit: usize) -> usize {
const ROUNDS: usize = 8;
match self.total {
Some(n) if n > 0 => memory_limit.min(((n as usize) / ROUNDS).max(1)).max(1),
_ => memory_limit.min(BLIND_HORIZON as usize).max(1),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn coded_size(qp: i32, k: f64) -> usize {
(2f64.powf(k - f64::from(qp) * DEFAULT_SLOPE)) as usize
}
fn content_needing_qp(bits_per_second: u64, fps: u32, qp: f64) -> f64 {
let target = bits_per_second as f64 / 8.0 / f64::from(fps);
target.log2() + qp * DEFAULT_SLOPE
}
#[test]
fn it_converges_on_a_target() {
let mut rc = RateControl::new(4_000_000, 30, Some(60));
let k = content_needing_qp(4_000_000, 30, 38.0);
for _ in 0..60 {
let qp = rc.next_qp();
rc.observe(qp, coded_size(qp, k));
}
let mean = rc.spent() / 60.0;
let target = 4_000_000.0 / 8.0 / 30.0;
assert!(
(mean - target).abs() / target < 0.05,
"mean {mean:.0} bytes vs target {target:.0}"
);
}
#[test]
fn it_pays_back_a_bad_first_frame() {
let mut rc = RateControl::new(4_000_000, 30, Some(30));
let k = content_needing_qp(4_000_000, 30, 44.0);
let qp0 = rc.next_qp();
assert_eq!(qp0, PROBE_QP);
rc.observe(qp0, coded_size(qp0, k));
for _ in 1..30 {
let qp = rc.next_qp();
rc.observe(qp, coded_size(qp, k));
}
let mean = rc.spent() / 30.0;
let target = 4_000_000.0 / 8.0 / 30.0;
assert!(
(mean - target).abs() / target < 0.10,
"mean {mean:.0} vs target {target:.0} — the overspend was not paid back"
);
}
#[test]
fn it_does_not_oscillate_when_content_changes() {
let mut rc = RateControl::new(4_000_000, 30, Some(80));
let mut qps = Vec::new();
for i in 0..80 {
let k = content_needing_qp(4_000_000, 30, if i < 40 { 32.0 } else { 42.0 });
let qp = rc.next_qp();
rc.observe(qp, coded_size(qp, k));
qps.push(qp);
}
let tail = &qps[55..];
let swing = tail.iter().max().unwrap() - tail.iter().min().unwrap();
assert!(
swing <= 2,
"quantizer swings by {swing} after settling: {tail:?}"
);
}
#[test]
fn an_impossible_target_is_reported() {
let k = content_needing_qp(4_000_000, 30, 70.0);
let mut rc = RateControl::new(4_000_000, 30, Some(20));
for _ in 0..20 {
let qp = rc.next_qp();
rc.observe(qp, coded_size(qp, k));
}
match rc.outcome() {
Some(Reach::TooComplex { times }) => {
assert!(times > 1.3, "reported only {times:.2}x over")
}
other => panic!("expected TooComplex, got {other:?}"),
}
let k_ok = content_needing_qp(4_000_000, 30, 40.0);
let mut ok = RateControl::new(4_000_000, 30, Some(20));
for _ in 0..20 {
let qp = ok.next_qp();
ok.observe(qp, coded_size(qp, k_ok));
}
assert!(ok.outcome().is_none(), "this target is reachable");
}
#[test]
fn a_target_the_content_cannot_fill_is_reported() {
let k = content_needing_qp(20_000_000, 30, -40.0);
let mut rc = RateControl::new(20_000_000, 30, Some(20));
for _ in 0..20 {
let qp = rc.next_qp();
rc.observe(qp, coded_size(qp, k));
}
match rc.outcome() {
Some(Reach::TooSimple { times }) => assert!(times > 1.3, "only {times:.2}x under"),
other => panic!("expected TooSimple, got {other:?}"),
}
}
#[test]
fn it_works_without_knowing_the_clip_length() {
let mut rc = RateControl::new(4_000_000, 30, None);
let k = content_needing_qp(4_000_000, 30, 36.0);
for _ in 0..120 {
let qp = rc.next_qp();
rc.observe(qp, coded_size(qp, k));
}
let mean = rc.spent() / 120.0;
let target = 4_000_000.0 / 8.0 / 30.0;
assert!(
(mean - target).abs() / target < 0.10,
"mean {mean:.0} vs target {target:.0}"
);
}
}