use std::{array::from_fn, cmp::Ordering};
use crate::{
DEFAULT_MAX_WINDOW_LOG, EncodeOpt, Encoded, LOW_LATENCY_WINDOW_LOG, Level, Type,
encode::{
MIN_OBSERVE, effective_window_log, encode_into_with, encode_owned_with, encode_vec_with,
},
probe::ContentBucket,
};
const ALL_CNT: usize = Level::ALL.len();
const ONLINE_CNT: usize = Level::ONLINE_CNT;
const BUCKET_CNT: usize = 3;
const PRIOR_TIME_SPB: [f64; ALL_CNT] = [
1.0 / 9.0e8, 1.0 / 5.5e8, 1.0 / 2.8e8, 1.0 / 1.4e8, 1.0 / 5.5e7, 1.0 / 2.2e7, 1.0 / 8.0e6, 1.0 / 3.0e6, ];
const PRIOR_RATIO_TABLE: [[f64; ALL_CNT]; BUCKET_CNT] = [
[0.86, 0.82, 0.78, 0.74, 0.70, 0.67, 0.64, 0.61], [0.68, 0.62, 0.56, 0.49, 0.43, 0.39, 0.36, 0.33], [0.42, 0.36, 0.30, 0.25, 0.21, 0.18, 0.16, 0.14], ];
const DECODE_SPB: f64 = 1.0 / 1.2e9;
const DEFAULT_CPU_WEIGHT: f64 = 0.02;
const ALPHA: f64 = 0.2;
const HW_ALPHA: f64 = 0.25;
const MAX_SHIFT: f64 = 4.0;
const HW_SCALE_MIN: f64 = 1e-3;
const HW_SCALE_MAX: f64 = 1e3;
const MIN_SPB: f64 = 1e-12;
const MAX_SPB: f64 = 1.0;
const RATIO_MIN: f64 = 1e-6;
const RATIO_MAX: f64 = 1.0 - RATIO_MIN;
const RAW_HYSTERESIS: f64 = 1.05;
const SWITCH_HYSTERESIS: f64 = 1.03;
const EXPLORE_INTERVAL: u32 = 64;
#[inline]
fn ratio_to_odds(ratio: f64) -> f64 {
let r = ratio.clamp(RATIO_MIN, RATIO_MAX);
r / (1.0 - r)
}
#[inline]
fn finite_nonneg(v: f64) -> f64 {
if v.is_finite() { v.max(0.0) } else { 0.0 }
}
#[inline]
fn odds_to_ratio(odds: f64) -> f64 {
if !odds.is_finite() {
return RATIO_MAX;
}
(odds / (1.0 + odds)).clamp(RATIO_MIN, RATIO_MAX)
}
#[inline]
const fn approx_level_ctx_bytes(level: Level, eff_wlog: u32) -> u64 {
let win = 1u64 << eff_wlog;
let table_mul = match level {
Level::UltraFast | Level::SuperFast | Level::Fastest => 1,
Level::Fast | Level::Balanced => 2,
Level::Strong | Level::High => 4,
Level::Best => 8,
};
win + win * table_mul
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NetSignal {
pub bw_bps: u64,
pub workers: u16,
pub backlog_bytes: u64,
pub overlap_rho: f64,
pub max_encode_us: u64,
pub max_queue_us: u64,
pub max_window_log: u32,
pub mem_budget_bytes: u64,
pub cpu_weight: f64,
pub bw_weight: f64,
}
impl Default for NetSignal {
#[inline]
fn default() -> Self {
Self::serial(0)
}
}
impl NetSignal {
#[must_use]
pub const fn serial(bw_bps: u64) -> Self {
Self {
bw_bps,
workers: 1,
backlog_bytes: 0,
overlap_rho: 0.0,
max_encode_us: 0,
max_queue_us: 0,
max_window_log: DEFAULT_MAX_WINDOW_LOG,
mem_budget_bytes: 0,
cpu_weight: DEFAULT_CPU_WEIGHT,
bw_weight: 0.0,
}
}
#[must_use]
pub const fn pipeline(bw_bps: u64, workers: u16, backlog_bytes: u64) -> Self {
let w = if workers == 0 { 1 } else { workers };
Self {
bw_bps,
workers: w,
backlog_bytes,
overlap_rho: 0.85,
max_encode_us: 40_000,
max_queue_us: 250_000,
max_window_log: DEFAULT_MAX_WINDOW_LOG,
mem_budget_bytes: 32 << 20,
cpu_weight: DEFAULT_CPU_WEIGHT,
bw_weight: 0.0,
}
}
#[must_use]
pub const fn low_latency(bw_bps: u64, rtt_us: u64) -> Self {
let raw = rtt_us / 6;
let budget = if rtt_us == 0 {
2_000
} else if raw < 800 {
800
} else if raw > 5_000 {
5_000
} else {
raw
};
Self {
bw_bps,
workers: 1,
backlog_bytes: 0,
overlap_rho: 0.0,
max_encode_us: budget,
max_queue_us: 0,
max_window_log: LOW_LATENCY_WINDOW_LOG,
mem_budget_bytes: 1 << 20,
cpu_weight: DEFAULT_CPU_WEIGHT,
bw_weight: 0.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Choice {
Off,
Level(Level),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Stat {
pub level: Level,
pub speed: f64,
pub ratio: f64,
pub sample_cnt: u32,
}
#[derive(Debug, Clone, Copy)]
struct BucketModel {
spb_li: [f64; ALL_CNT],
ratio_li: [f64; ALL_CNT],
sample_li: [u32; ALL_CNT],
}
impl BucketModel {
const fn new(bucket_idx: usize) -> Self {
Self {
spb_li: PRIOR_TIME_SPB,
ratio_li: PRIOR_RATIO_TABLE[bucket_idx],
sample_li: [0; ALL_CNT],
}
}
fn enforce_monotone(&mut self, i: usize) {
for j in (0..i).rev() {
self.spb_li[j] = self.spb_li[j].min(self.spb_li[j + 1]);
self.ratio_li[j] = self.ratio_li[j].max(self.ratio_li[j + 1]);
}
for j in (i + 1)..ALL_CNT {
self.spb_li[j] = self.spb_li[j].max(self.spb_li[j - 1]);
self.ratio_li[j] = self.ratio_li[j].min(self.ratio_li[j - 1]);
}
}
fn sync_unsampled_spb(&mut self, hw_scale: f64) {
for j in 0..ALL_CNT {
if self.sample_li[j] == 0 {
self.spb_li[j] = (PRIOR_TIME_SPB[j] * hw_scale).clamp(MIN_SPB, MAX_SPB);
}
}
for k in 0..ALL_CNT {
if self.sample_li[k] > 0 {
self.enforce_monotone(k);
}
}
}
}
#[derive(Debug, Clone)]
pub struct Adaptive {
bucket_li: [BucketModel; BUCKET_CNT],
hw_scale: f64,
last_choice_li: [Option<Choice>; BUCKET_CNT],
step: u32,
explore_up: bool,
explore_bucket: u8,
}
impl Default for Adaptive {
fn default() -> Self {
Self::new()
}
}
impl Adaptive {
#[must_use]
pub const fn new() -> Self {
Self {
bucket_li: [
BucketModel::new(0),
BucketModel::new(1),
BucketModel::new(2),
],
hw_scale: 1.0,
last_choice_li: [None; BUCKET_CNT],
step: 0,
explore_up: true,
explore_bucket: 0,
}
}
#[inline]
fn level_spb(&self, bucket_idx: usize, level_idx: usize) -> f64 {
self.bucket_li[bucket_idx].spb_li[level_idx].clamp(MIN_SPB, MAX_SPB)
}
fn level_cost(&self, bucket_idx: usize, level_idx: usize, sig: &NetSignal) -> f64 {
let spb = self.level_spb(bucket_idx, level_idx);
let ratio = self.bucket_li[bucket_idx].ratio_li[level_idx];
let net_spb = 1.0 / (sig.bw_bps as f64);
let ser = spb + ratio * net_spb + DECODE_SPB;
let w = f64::from(sig.workers.max(1));
let rho = finite_nonneg(sig.overlap_rho).min(1.0);
let cpu_w = finite_nonneg(sig.cpu_weight);
let bw_w = finite_nonneg(sig.bw_weight);
let pipe = (spb / w).max(ratio * net_spb).max(DECODE_SPB);
(1.0 - rho) * ser + rho * pipe + cpu_w * spb + bw_w * ratio * net_spb
}
fn level_feasible(
&self,
bucket_idx: usize,
level_idx: usize,
len: usize,
sig: &NetSignal,
) -> bool {
let spb = self.level_spb(bucket_idx, level_idx);
if sig.max_encode_us > 0 {
let est_us = (len as f64) * spb * 1e6;
if est_us > sig.max_encode_us as f64 {
return false;
}
}
if sig.max_queue_us > 0 {
let q_bytes = sig.backlog_bytes.saturating_add(len as u64) as f64;
let est_q_us = q_bytes * spb * 1e6 / f64::from(sig.workers.max(1));
if est_q_us > sig.max_queue_us as f64 {
return false;
}
}
if sig.mem_budget_bytes > 0 {
let eff_wlog = effective_window_log(len, sig.max_window_log);
if approx_level_ctx_bytes(Level::ALL[level_idx], eff_wlog) > sig.mem_budget_bytes {
return false;
}
}
true
}
#[must_use]
pub fn choice(&self, net_speed: u64) -> Choice {
let sig = NetSignal::serial(net_speed);
self.plan(128 * 1024, ContentBucket::Medium, &sig)
}
#[must_use]
pub fn plan(&self, data_len: usize, bucket: ContentBucket, sig: &NetSignal) -> Choice {
let Some(bidx) = bucket.index() else {
return Choice::Off;
};
if sig.bw_bps == 0 {
return Choice::Level(Level::Balanced);
}
let raw_cost = (1.0 + finite_nonneg(sig.bw_weight)) / (sig.bw_bps as f64);
let ceiling = raw_cost / RAW_HYSTERESIS;
let mut best_cost = ceiling;
let mut best = Choice::Off;
for (idx, &level) in Level::ALL.iter().take(ONLINE_CNT).enumerate() {
if !self.level_feasible(bidx, idx, data_len, sig) {
continue;
}
let cost = self.level_cost(bidx, idx, sig);
if cost < best_cost {
best_cost = cost;
best = Choice::Level(level);
}
}
if let (Some(Choice::Level(prev_lvl)), Choice::Level(new_lvl)) =
(self.last_choice_li[bidx], best)
&& prev_lvl != new_lvl
&& prev_lvl.index() < ONLINE_CNT
{
let prev_idx = prev_lvl.index();
if self.level_feasible(bidx, prev_idx, data_len, sig) {
let prev_cost = self.level_cost(bidx, prev_idx, sig);
if prev_cost <= best_cost * SWITCH_HYSTERESIS {
return Choice::Level(prev_lvl);
}
}
}
best
}
fn advance_explore_slot(
&mut self,
bidx: usize,
base: Choice,
data_len: usize,
sig: &NetSignal,
) -> Choice {
if sig.backlog_bytes > 0 && sig.max_queue_us > 0 {
return base;
}
match base {
Choice::Off => {
if self.level_feasible(bidx, 0, data_len, sig)
&& self.level_spb(bidx, 0) * (sig.bw_bps as f64) <= MAX_SHIFT
{
Choice::Level(Level::ALL[0])
} else {
Choice::Off
}
}
Choice::Level(cur) => {
let i = cur.index();
let lo = i
.checked_sub(1)
.filter(|&j| self.level_feasible(bidx, j, data_len, sig));
let hi =
(i + 1 < ONLINE_CNT && self.level_feasible(bidx, i + 1, data_len, sig)).then_some(i + 1);
let probe = match (lo, hi) {
(Some(a), Some(b)) => {
match self.bucket_li[bidx].sample_li[a].cmp(&self.bucket_li[bidx].sample_li[b]) {
Ordering::Less => a,
Ordering::Greater => b,
Ordering::Equal => {
self.explore_up = !self.explore_up;
if self.explore_up { b } else { a }
}
}
}
(Some(j), None) | (None, Some(j)) => j,
(None, None) => return Choice::Level(cur),
};
Choice::Level(Level::ALL[probe])
}
}
}
fn maybe_explore_step(&mut self) -> bool {
self.step += 1;
if self.step < EXPLORE_INTERVAL {
return false;
}
self.step = 0;
true
}
#[must_use]
pub fn plan_buckets(&mut self, data_len: usize, sig: &NetSignal) -> [Choice; BUCKET_CNT] {
let mut out = [
self.plan(data_len, ContentBucket::Low, sig),
self.plan(data_len, ContentBucket::Medium, sig),
self.plan(data_len, ContentBucket::High, sig),
];
for (bidx, &choice) in out.iter().enumerate() {
self.last_choice_li[bidx] = Some(choice);
}
if sig.bw_bps > 0 && data_len >= MIN_OBSERVE && self.maybe_explore_step() {
let bidx = usize::from(self.explore_bucket) % BUCKET_CNT;
self.explore_bucket = ((bidx + 1) % BUCKET_CNT) as u8;
out[bidx] = self.advance_explore_slot(bidx, out[bidx], data_len, sig);
}
out
}
fn pick_opt(
&mut self,
data_len: usize,
bucket: ContentBucket,
sig: &NetSignal,
observable: bool,
) -> Option<EncodeOpt> {
let bidx = bucket.index()?;
let base = self.plan(data_len, bucket, sig);
self.last_choice_li[bidx] = Some(base);
let choice = if sig.bw_bps > 0 && observable && self.maybe_explore_step() {
self.advance_explore_slot(bidx, base, data_len, sig)
} else {
base
};
match choice {
Choice::Off => None,
Choice::Level(level) => Some(EncodeOpt::new(level).with_max_window_log(sig.max_window_log)),
}
}
#[must_use]
pub fn encode_signal(&mut self, data: &[u8], sig: &NetSignal) -> Vec<u8> {
let raw_len = data.len();
encode_vec_with(
data,
self,
|this, bucket, obs| this.pick_opt(raw_len, bucket, sig, obs),
true,
|this, opt, bucket, wire_len, ns| {
this.observe_bucket(opt.level, bucket, raw_len, wire_len, ns);
},
)
}
#[must_use]
pub fn encode_owned_signal(&mut self, data: Vec<u8>, sig: &NetSignal) -> Encoded {
let raw_len = data.len();
encode_owned_with(
data,
self,
|this, bucket, obs| this.pick_opt(raw_len, bucket, sig, obs),
true,
|this, opt, bucket, wire_len, ns| {
this.observe_bucket(opt.level, bucket, raw_len, wire_len, ns);
},
)
}
pub fn encode_into_signal(&mut self, data: &[u8], sig: &NetSignal, out: &mut Vec<u8>) -> Type {
let raw_len = data.len();
encode_into_with(
data,
self,
|this, bucket, obs| this.pick_opt(raw_len, bucket, sig, obs),
out,
true,
|this, opt, bucket, wire_len, ns| {
this.observe_bucket(opt.level, bucket, raw_len, wire_len, ns);
},
)
}
#[must_use]
pub fn encode(&mut self, data: &[u8], net_speed: u64) -> Vec<u8> {
self.encode_signal(data, &NetSignal::serial(net_speed))
}
#[must_use]
pub fn encode_owned(&mut self, data: Vec<u8>, net_speed: u64) -> Encoded {
self.encode_owned_signal(data, &NetSignal::serial(net_speed))
}
pub fn encode_into(&mut self, data: &[u8], net_speed: u64, out: &mut Vec<u8>) -> Type {
self.encode_into_signal(data, &NetSignal::serial(net_speed), out)
}
pub fn observe_bucket(
&mut self,
level: Level,
bucket: ContentBucket,
raw_len: usize,
wire_len: usize,
elapsed_ns: u64,
) {
let Some(bidx) = bucket.index() else {
return;
};
if raw_len == 0 || elapsed_ns == 0 {
return;
}
let spb = (elapsed_ns as f64 * 1e-9) / (raw_len as f64);
let ratio = (wire_len as f64) / (raw_len.saturating_add(1) as f64);
self.observe_at(bidx, level, spb, ratio);
}
pub fn observe(&mut self, level: Level, speed: f64, ratio: f64) {
if !speed.is_finite() || speed <= 0.0 || !ratio.is_finite() {
return;
}
self.observe_at(1, level, 1.0 / speed, ratio);
}
fn observe_at(&mut self, bidx: usize, level: Level, spb: f64, ratio: f64) {
if !spb.is_finite() || spb <= 0.0 || !ratio.is_finite() {
return;
}
let i = level.index();
let obs_scale =
(spb / PRIOR_TIME_SPB[i]).clamp(self.hw_scale / MAX_SHIFT, self.hw_scale * MAX_SHIFT);
let next_scale = self.hw_scale + (obs_scale - self.hw_scale) * HW_ALPHA;
self.hw_scale = if next_scale.is_finite() {
next_scale.clamp(HW_SCALE_MIN, HW_SCALE_MAX)
} else {
1.0
};
{
let b = &mut self.bucket_li[bidx];
let cur_spb = b.spb_li[i];
let clamped_spb = spb.clamp(
(cur_spb / MAX_SHIFT).max(MIN_SPB),
(cur_spb * MAX_SHIFT).min(MAX_SPB),
);
let n = b.sample_li[i].saturating_add(1);
b.sample_li[i] = n;
let weight = (1.0 / f64::from(n)).clamp(ALPHA, 0.5);
let ln_next = cur_spb.ln() + (clamped_spb.ln() - cur_spb.ln()) * weight;
b.spb_li[i] = ln_next.exp().clamp(MIN_SPB, MAX_SPB);
b.ratio_li[i] += (ratio.clamp(0.0, 1.0) - b.ratio_li[i]) * weight;
let odds_scale = ratio_to_odds(b.ratio_li[i]) / ratio_to_odds(PRIOR_RATIO_TABLE[bidx][i]);
for j in 0..ALL_CNT {
if b.sample_li[j] == 0 {
b.ratio_li[j] = odds_to_ratio(ratio_to_odds(PRIOR_RATIO_TABLE[bidx][j]) * odds_scale);
}
}
}
for bk in &mut self.bucket_li {
bk.sync_unsampled_spb(self.hw_scale);
}
self.bucket_li[bidx].enforce_monotone(i);
}
#[must_use]
pub fn stats(&self) -> [Stat; ALL_CNT] {
let dom = (0..BUCKET_CNT)
.max_by_key(|&bi| {
let sum: u32 = self.bucket_li[bi].sample_li.iter().sum();
(sum, usize::from(bi == 1))
})
.unwrap_or(1);
let b = &self.bucket_li[dom];
from_fn(|i| {
let total_cnt: u32 = self.bucket_li.iter().map(|bk| bk.sample_li[i]).sum();
Stat {
level: Level::ALL[i],
speed: 1.0 / self.level_spb(dom, i),
ratio: b.ratio_li[i],
sample_cnt: total_cnt,
}
})
}
#[must_use]
pub fn bucket_stats(&self, bucket: ContentBucket) -> [Stat; ALL_CNT] {
let bidx = bucket.index().unwrap_or(1);
let b = &self.bucket_li[bidx];
from_fn(|i| Stat {
level: Level::ALL[i],
speed: 1.0 / b.spb_li[i].max(MIN_SPB),
ratio: b.ratio_li[i],
sample_cnt: b.sample_li[i],
})
}
}