use core::time::Duration;
use crate::config::TICKS_PER_US;
use crate::stall_memory::MaxHold;
use crate::time::{
Clock27, duration_add, duration_between, instant_micros, micros_as_duration, window_micros,
};
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: Duration = Duration::from_millis(1);
pub const LEARN_STEPS: u32 = 2;
fn before(a: Clock27, b: Clock27) -> bool {
pcr_signed_distance(a.ticks(), b.ticks()) > 0
}
#[derive(Clone, Copy, Debug)]
struct Step {
prev_end: Clock27,
prev_at: Duration,
cur_end: Clock27,
cur_at: Duration,
cur_epoch: u64,
pending: bool,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct StepRules {
pub(crate) max_interval: Duration,
pub(crate) max_excess: Duration,
pub(crate) gap_end_at: Option<Duration>,
pub(crate) epoch: u64,
}
#[derive(Clone, Debug)]
struct Track {
id: u32,
registered: bool,
end: Option<Clock27>,
seen_at: Duration,
step: Option<Step>,
first_at: Duration,
windows: u32,
gran: MaxHold,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Effective {
pub(crate) end: Clock27,
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.ticks(), cur_end.ticks());
let interval = duration_between(prev_at, cur_at);
if advance <= 0 || interval.is_zero() || interval >= rules.max_interval {
return;
}
if rules.gap_end_at.is_some_and(|g| g > prev_at) {
return;
}
let step = u64::try_from(advance).unwrap_or(0) / TICKS_PER_US;
if step > instant_micros(interval).saturating_add(instant_micros(rules.max_excess)) {
return;
}
self.gran.observe(instant_micros(cur_at), step);
}
fn observe_step(&mut self, now: Duration, end: Clock27, rules: StepRules) {
let same_window = self.step.as_ref().is_some_and(|s| {
s.cur_epoch == rules.epoch
&& (rules.epoch > 0 || duration_between(s.cur_at, now) < COALESCE)
});
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: Duration,
gran_decay: Duration,
last_delivery: Option<Duration>,
first_delivery: Option<Duration>,
}
impl TrackSet {
pub(crate) fn new(gran_hold: Duration, gran_decay: Duration) -> Self {
Self {
v: Vec::new(),
gran_hold,
gran_decay,
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: Duration) -> 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(
window_micros(self.gran_hold),
window_micros(self.gran_decay),
),
});
self.v.len() - 1
}
};
self.v.get_mut(i)
}
pub(crate) fn register(&mut self, id: u32, now: Duration) {
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: Duration,
end: Clock27,
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: Duration) -> Option<Duration> {
let last = self.last_delivery?;
let step = self
.v
.iter()
.map(|t| t.gran.value(instant_micros(now)))
.max()
.unwrap_or(0);
Some(last.max(now.min(duration_add(last, micros_as_duration(step)))))
}
fn is_silent(&self, t: &Track, silence: &Duration, clock: Option<Duration>) -> 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| duration_between(since, l) >= *silence)
}
pub(crate) fn is_live(&self, id: u32, now: Duration, silence: Duration) -> bool {
let clock = self.silence_clock(now);
self.v
.iter()
.any(|t| t.id == id && !self.is_silent(t, &silence, clock))
}
pub(crate) fn granularity(&self, now: Duration, silence: Duration) -> Duration {
let clock = self.silence_clock(now);
self.v
.iter()
.filter(|t| !self.is_silent(t, &silence, clock))
.map(|t| micros_as_duration(t.gran.value(instant_micros(now))))
.max()
.unwrap_or(Duration::ZERO)
}
pub(crate) fn granularity_known(
&self,
now: Duration,
silence: Duration,
max_wait: Duration,
) -> bool {
let clock = self.silence_clock(now);
self.v
.iter()
.filter(|t| t.end.is_some() && !self.is_silent(t, &silence, clock))
.all(|t| t.windows > LEARN_STEPS || duration_between(t.first_at, now) >= max_wait)
}
pub(crate) fn rebaseline(&mut self, now: Duration) {
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: Duration,
silence: Duration,
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, 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
}
}