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
}
}
#[cfg(test)]
mod tests {
use super::{StepRules, TrackSet};
use crate::time::Clock27;
use core::time::Duration;
fn set() -> TrackSet {
TrackSet::new(Duration::from_secs(30), Duration::from_secs(30))
}
fn rules(
epoch: u64,
max_interval: Duration,
max_excess: Duration,
gap: Option<Duration>,
) -> StepRules {
StepRules {
max_interval,
max_excess,
gap_end_at: gap,
epoch,
}
}
fn short(epoch: u64, gap: Option<Duration>) -> StepRules {
rules(
epoch,
Duration::from_secs(3),
Duration::from_millis(200),
gap,
)
}
fn ticks(n: u64) -> Clock27 {
Clock27::from_27mhz(n).expect("on the clock")
}
fn clock(secs: u64) -> Clock27 {
Clock27::from_27mhz(secs * 27_000_000).expect("whole seconds are on the clock")
}
#[test]
fn equal_ends_keep_the_first_track_as_the_limiting_one() {
let mut s = set();
let r = short(0, None);
assert_eq!(s.deliver(0, Duration::ZERO, clock(5), r), Some(true));
assert_eq!(s.deliver(1, Duration::ZERO, clock(5), r), Some(true));
let e = s
.effective(Duration::ZERO, Duration::from_secs(3), true)
.expect("both tracks delivered");
assert_eq!(e.limiting, 0);
assert_eq!(e.end, clock(5));
}
#[test]
fn a_zero_length_delivery_interval_is_not_a_step() {
let mut s = set();
let r = short(1, None);
s.deliver(0, Duration::ZERO, ticks(0), r);
s.close_windows(r);
s.deliver(0, Duration::ZERO, ticks(540_000), r);
s.close_windows(r);
assert_eq!(
s.granularity(Duration::ZERO, Duration::from_secs(3)),
Duration::ZERO
);
}
#[test]
fn a_delivery_interval_at_the_silence_timeout_is_not_a_step() {
let mut s = set();
let r = short(1, None);
s.deliver(0, Duration::ZERO, ticks(0), r);
s.close_windows(r);
s.deliver(0, Duration::from_secs(3), ticks(540_000), r);
s.close_windows(r);
assert_eq!(
s.granularity(Duration::from_secs(3), Duration::from_secs(3)),
Duration::ZERO
);
}
#[test]
fn a_gap_after_the_delivery_interval_suppresses_the_step() {
let mut s = set();
let r = short(1, Some(Duration::from_secs(1)));
s.deliver(0, Duration::ZERO, ticks(0), r);
s.close_windows(r);
s.deliver(0, Duration::from_secs(1), ticks(540_000), r);
s.close_windows(r);
assert_eq!(
s.granularity(Duration::from_secs(1), Duration::from_secs(3)),
Duration::ZERO
);
}
#[test]
fn a_gap_at_the_previous_delivery_instant_is_not_inside_the_interval() {
let mut s = set();
let r = short(1, Some(Duration::ZERO));
s.deliver(0, Duration::ZERO, ticks(0), r);
s.close_windows(r);
s.deliver(0, Duration::from_secs(1), ticks(540_000), r);
s.close_windows(r);
assert_eq!(
s.granularity(Duration::from_secs(1), Duration::from_secs(3)),
Duration::from_millis(20)
);
}
#[test]
fn a_step_exactly_at_the_interval_plus_allowance_is_recorded() {
let mut s = set();
let r = short(1, None);
s.deliver(0, Duration::ZERO, ticks(0), r);
s.close_windows(r);
s.deliver(0, Duration::from_secs(1), ticks(32_400_000), r);
s.close_windows(r);
assert_eq!(
s.granularity(Duration::from_secs(1), Duration::from_secs(3)),
Duration::from_millis(1_200)
);
}
#[test]
fn deliveries_in_one_chunk_epoch_are_one_window_however_far_apart() {
let mut s = set();
let r = short(1, None);
s.deliver(0, Duration::ZERO, ticks(0), r);
s.deliver(0, Duration::from_millis(2), ticks(540_000), r);
s.deliver(0, Duration::from_millis(4), ticks(1_080_000), r);
s.deliver(0, Duration::from_millis(6), ticks(1_620_000), r);
assert!(!s.granularity_known(
Duration::from_millis(6),
Duration::from_secs(3),
Duration::MAX
));
}
#[test]
fn deliveries_exactly_one_coalescing_window_apart_are_separate_windows() {
let mut s = set();
let r = short(0, None);
s.deliver(0, Duration::ZERO, ticks(0), r);
s.deliver(0, Duration::from_millis(1), ticks(540_000), r);
s.deliver(0, Duration::from_millis(3), ticks(1_080_000), r);
s.deliver(0, Duration::from_millis(5), ticks(1_620_000), r);
assert!(s.granularity_known(
Duration::from_millis(5),
Duration::from_secs(3),
Duration::MAX
));
}
#[test]
fn clearing_the_set_forgets_every_track_and_delivery() {
let mut s = set();
let r = short(0, None);
s.deliver(0, Duration::ZERO, clock(1), r);
s.register(7, Duration::ZERO);
assert_eq!(s.len(), 2);
s.clear();
assert_eq!(s.len(), 0);
assert_eq!(
s.effective(Duration::ZERO, Duration::from_secs(3), true),
None
);
assert!(!s.is_live(0, Duration::ZERO, Duration::from_secs(3)));
assert_eq!(
s.granularity(Duration::ZERO, Duration::from_secs(3)),
Duration::ZERO
);
}
#[test]
fn only_a_known_speaking_track_is_live() {
let mut s = set();
let r = short(0, None);
let silence = Duration::from_secs(3);
s.deliver(1, Duration::ZERO, clock(0), r);
assert!(s.is_live(1, Duration::ZERO, silence));
assert!(!s.is_live(9, Duration::ZERO, silence));
s.deliver(2, Duration::ZERO, clock(0), r);
s.deliver(2, Duration::from_secs(20), clock(20), r);
assert!(!s.is_live(1, Duration::from_secs(20), silence));
s.deliver(1, Duration::from_secs(20), clock(20), r);
assert!(s.is_live(1, Duration::from_secs(20), silence));
}
#[test]
fn a_track_that_never_delivered_does_not_block_the_granularity_gate() {
let mut s = set();
let r = short(1, None);
s.register(1, Duration::ZERO);
s.deliver(0, Duration::ZERO, ticks(0), r);
s.close_windows(r);
s.deliver(0, Duration::from_millis(1), ticks(540_000), r);
s.close_windows(r);
s.deliver(0, Duration::from_millis(2), ticks(1_080_000), r);
s.close_windows(r);
s.deliver(0, Duration::from_millis(3), ticks(1_620_000), r);
s.close_windows(r);
assert!(s.granularity_known(
Duration::from_millis(3),
Duration::from_secs(3),
Duration::MAX
));
}
}