use crate::config::{Micros, TICKS_PER_US, Ticks27};
use crate::stall_memory::MaxHold;
use alloc::vec::Vec;
use broadcast_common::clock33::pcr_signed_distance;
pub const MAX_TRACKS: usize = 16;
pub const DEFAULT_TRACK: u32 = 0;
pub const COALESCE_US: Micros = 1_000;
pub const LEARN_STEPS: u32 = 2;
fn before(a: Ticks27, b: Ticks27) -> bool {
pcr_signed_distance(a, b) > 0
}
#[derive(Clone, Copy, Debug)]
struct Step {
prev_end: Ticks27,
prev_at: Micros,
cur_end: Ticks27,
cur_at: Micros,
cur_epoch: u64,
pending: bool,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct StepRules {
pub(crate) max_interval_us: Micros,
pub(crate) max_excess_us: Micros,
pub(crate) gap_end_at: Option<Micros>,
pub(crate) epoch: u64,
}
#[derive(Clone, Debug)]
struct Track {
id: u32,
registered: bool,
end: Option<Ticks27>,
seen_at: Micros,
step: Option<Step>,
first_at: Micros,
windows: u32,
gran: MaxHold,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Effective {
pub(crate) end: Ticks27,
pub(crate) limiting: u32,
}
impl Track {
fn commit_window(&mut self, rules: StepRules) {
let Some(s) = self.step.as_mut() else {
return;
};
if !s.pending {
return;
}
s.pending = false;
self.windows = self.windows.saturating_add(1);
let (prev_end, prev_at, cur_end, cur_at) = (s.prev_end, s.prev_at, s.cur_end, s.cur_at);
s.prev_end = cur_end;
s.prev_at = cur_at;
let advance = pcr_signed_distance(prev_end, cur_end);
let interval = cur_at.saturating_sub(prev_at);
if advance <= 0 || interval == 0 || interval >= rules.max_interval_us {
return;
}
if rules.gap_end_at.is_some_and(|g| g > prev_at) {
return;
}
let step_us = u64::try_from(advance).unwrap_or(0) / TICKS_PER_US;
if step_us > interval.saturating_add(rules.max_excess_us) {
return;
}
self.gran.observe(cur_at, step_us);
}
fn observe_step(&mut self, now: Micros, end: Ticks27, rules: StepRules) {
let same_window = self.step.as_ref().is_some_and(|s| {
s.cur_epoch == rules.epoch
&& (rules.epoch > 0 || now.saturating_sub(s.cur_at) < COALESCE_US)
});
if !same_window {
self.commit_window(rules);
}
match self.step.as_mut() {
None => {
self.step = Some(Step {
prev_end: end,
prev_at: now,
cur_end: end,
cur_at: now,
cur_epoch: rules.epoch,
pending: true,
});
}
Some(s) => {
s.cur_epoch = rules.epoch;
s.cur_end = end;
s.cur_at = now;
s.pending = true;
}
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct TrackSet {
v: Vec<Track>,
gran_hold_us: Micros,
gran_decay_us: Micros,
last_delivery: Option<Micros>,
first_delivery: Option<Micros>,
}
impl TrackSet {
pub(crate) fn new(gran_hold_us: Micros, gran_decay_us: Micros) -> Self {
Self {
v: Vec::new(),
gran_hold_us,
gran_decay_us,
last_delivery: None,
first_delivery: None,
}
}
pub(crate) fn len(&self) -> usize {
self.v.len()
}
pub(crate) fn clear(&mut self) {
self.v.clear();
self.last_delivery = None;
self.first_delivery = None;
}
fn slot(&mut self, id: u32, now: Micros) -> Option<&mut Track> {
let i = match self.v.iter().position(|t| t.id == id) {
Some(i) => i,
None => {
if self.v.len() >= MAX_TRACKS {
return None;
}
self.v.push(Track {
id,
registered: false,
end: None,
seen_at: now,
step: None,
first_at: now,
windows: 0,
gran: MaxHold::new(self.gran_hold_us, self.gran_decay_us),
});
self.v.len() - 1
}
};
self.v.get_mut(i)
}
pub(crate) fn register(&mut self, id: u32, now: Micros) {
if let Some(t) = self.slot(id, now) {
t.registered = true;
}
}
pub(crate) fn unregister(&mut self, id: u32) {
self.v.retain(|t| t.id != id);
}
pub(crate) fn deliver(
&mut self,
id: u32,
now: Micros,
end: Ticks27,
rules: StepRules,
) -> Option<bool> {
let t = self.slot(id, now)?;
let first = t.end.is_none();
t.end = Some(end);
t.seen_at = t.seen_at.max(now);
if first {
t.seen_at = now;
t.step = None;
t.first_at = now;
}
t.observe_step(now, end, rules);
self.last_delivery = Some(self.last_delivery.map_or(now, |l| l.max(now)));
self.first_delivery.get_or_insert(now);
Some(first)
}
pub(crate) fn close_windows(&mut self, rules: StepRules) {
for t in &mut self.v {
t.commit_window(rules);
}
}
fn silence_clock(&self, now: Micros) -> Option<Micros> {
let last = self.last_delivery?;
let step = self.v.iter().map(|t| t.gran.value(now)).max().unwrap_or(0);
Some(last.max(now.min(last.saturating_add(step))))
}
fn is_silent(&self, t: &Track, silence_us: Micros, clock: Option<Micros>) -> bool {
let since = match (t.end, self.first_delivery) {
(None, Some(f)) => t.seen_at.max(f),
_ => t.seen_at,
};
clock.is_some_and(|l| l.saturating_sub(since) >= silence_us)
}
pub(crate) fn is_live(&self, id: u32, now: Micros, silence_us: Micros) -> bool {
let clock = self.silence_clock(now);
self.v
.iter()
.any(|t| t.id == id && !self.is_silent(t, silence_us, clock))
}
pub(crate) fn granularity_us(&self, now: Micros, silence_us: Micros) -> Micros {
let clock = self.silence_clock(now);
self.v
.iter()
.filter(|t| !self.is_silent(t, silence_us, clock))
.map(|t| t.gran.value(now))
.max()
.unwrap_or(0)
}
pub(crate) fn granularity_known(
&self,
now: Micros,
silence_us: Micros,
max_wait_us: Micros,
) -> bool {
let clock = self.silence_clock(now);
self.v
.iter()
.filter(|t| t.end.is_some() && !self.is_silent(t, silence_us, clock))
.all(|t| t.windows > LEARN_STEPS || now.saturating_sub(t.first_at) >= max_wait_us)
}
pub(crate) fn rebaseline(&mut self, now: Micros) {
self.v.retain(|t| t.registered);
self.last_delivery = None;
self.first_delivery = None;
for t in &mut self.v {
t.end = None;
t.step = None;
t.seen_at = now;
}
}
pub(crate) fn effective(
&self,
now: Micros,
silence_us: Micros,
pending_blocks: bool,
) -> Option<Effective> {
let clock = self.silence_clock(now);
let mut min: Option<Effective> = None;
for t in self
.v
.iter()
.filter(|t| !self.is_silent(t, silence_us, clock))
{
let Some(end) = t.end else {
if pending_blocks {
return None;
}
continue;
};
if min.is_none_or(|m| before(end, m.end)) {
min = Some(Effective {
end,
limiting: t.id,
});
}
}
min
}
}