1use core::time::Duration;
67
68use crate::config::TICKS_PER_US;
69use crate::stall_memory::MaxHold;
70use crate::time::{
71 Clock27, duration_add, duration_between, instant_micros, micros_as_duration, window_micros,
72};
73use alloc::vec::Vec;
74use broadcast_common::clock33::pcr_signed_distance;
75
76pub const MAX_TRACKS: usize = 16;
78
79pub const DEFAULT_TRACK: u32 = 0;
81
82pub const COALESCE: Duration = Duration::from_millis(1);
85
86pub const LEARN_STEPS: u32 = 2;
90
91fn before(a: Clock27, b: Clock27) -> bool {
93 pcr_signed_distance(a.ticks(), b.ticks()) > 0
94}
95
96#[derive(Clone, Copy, Debug)]
98struct Step {
99 prev_end: Clock27,
101 prev_at: Duration,
102 cur_end: Clock27,
104 cur_at: Duration,
105 cur_epoch: u64,
107 pending: bool,
109}
110
111#[derive(Clone, Copy, Debug)]
113pub(crate) struct StepRules {
114 pub(crate) max_interval: Duration,
116 pub(crate) max_excess: Duration,
118 pub(crate) gap_end_at: Option<Duration>,
120 pub(crate) epoch: u64,
123}
124
125#[derive(Clone, Debug)]
126struct Track {
127 id: u32,
128 registered: bool,
129 end: Option<Clock27>,
130 seen_at: Duration,
132 step: Option<Step>,
133 first_at: Duration,
135 windows: u32,
137 gran: MaxHold,
139}
140
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub(crate) struct Effective {
144 pub(crate) end: Clock27,
145 pub(crate) limiting: u32,
147}
148
149impl Track {
150 fn commit_window(&mut self, rules: StepRules) {
153 let Some(s) = self.step.as_mut() else {
154 return;
155 };
156 if !s.pending {
157 return;
158 }
159 s.pending = false;
160 self.windows = self.windows.saturating_add(1);
161 let (prev_end, prev_at, cur_end, cur_at) = (s.prev_end, s.prev_at, s.cur_end, s.cur_at);
162 s.prev_end = cur_end;
163 s.prev_at = cur_at;
164 let advance = pcr_signed_distance(prev_end.ticks(), cur_end.ticks());
165 let interval = duration_between(prev_at, cur_at);
166 if advance <= 0 || interval.is_zero() || interval >= rules.max_interval {
167 return;
168 }
169 if rules.gap_end_at.is_some_and(|g| g > prev_at) {
170 return;
171 }
172 let step = u64::try_from(advance).unwrap_or(0) / TICKS_PER_US;
173 if step > instant_micros(interval).saturating_add(instant_micros(rules.max_excess)) {
174 return;
175 }
176 self.gran.observe(instant_micros(cur_at), step);
177 }
178
179 fn observe_step(&mut self, now: Duration, end: Clock27, rules: StepRules) {
182 let same_window = self.step.as_ref().is_some_and(|s| {
183 s.cur_epoch == rules.epoch
184 && (rules.epoch > 0 || duration_between(s.cur_at, now) < COALESCE)
185 });
186 if !same_window {
187 self.commit_window(rules);
188 }
189 match self.step.as_mut() {
190 None => {
191 self.step = Some(Step {
192 prev_end: end,
193 prev_at: now,
194 cur_end: end,
195 cur_at: now,
196 cur_epoch: rules.epoch,
197 pending: true,
198 });
199 }
200 Some(s) => {
201 s.cur_epoch = rules.epoch;
202 s.cur_end = end;
203 s.cur_at = now;
204 s.pending = true;
205 }
206 }
207 }
208}
209
210#[derive(Clone, Debug)]
212pub(crate) struct TrackSet {
213 v: Vec<Track>,
214 gran_hold: Duration,
215 gran_decay: Duration,
216 last_delivery: Option<Duration>,
219 first_delivery: Option<Duration>,
224}
225
226impl TrackSet {
227 pub(crate) fn new(gran_hold: Duration, gran_decay: Duration) -> Self {
228 Self {
229 v: Vec::new(),
230 gran_hold,
231 gran_decay,
232 last_delivery: None,
233 first_delivery: None,
234 }
235 }
236
237 pub(crate) fn len(&self) -> usize {
238 self.v.len()
239 }
240
241 pub(crate) fn clear(&mut self) {
242 self.v.clear();
243 self.last_delivery = None;
244 self.first_delivery = None;
245 }
246
247 fn slot(&mut self, id: u32, now: Duration) -> Option<&mut Track> {
248 let i = match self.v.iter().position(|t| t.id == id) {
249 Some(i) => i,
250 None => {
251 if self.v.len() >= MAX_TRACKS {
252 return None;
253 }
254 self.v.push(Track {
255 id,
256 registered: false,
257 end: None,
258 seen_at: now,
259 step: None,
260 first_at: now,
261 windows: 0,
262 gran: MaxHold::new(
263 window_micros(self.gran_hold),
264 window_micros(self.gran_decay),
265 ),
266 });
267 self.v.len() - 1
268 }
269 };
270 self.v.get_mut(i)
271 }
272
273 pub(crate) fn register(&mut self, id: u32, now: Duration) {
274 if let Some(t) = self.slot(id, now) {
275 t.registered = true;
276 }
277 }
278
279 pub(crate) fn unregister(&mut self, id: u32) {
281 self.v.retain(|t| t.id != id);
282 }
283
284 pub(crate) fn deliver(
287 &mut self,
288 id: u32,
289 now: Duration,
290 end: Clock27,
291 rules: StepRules,
292 ) -> Option<bool> {
293 let t = self.slot(id, now)?;
294 let first = t.end.is_none();
295 t.end = Some(end);
296 t.seen_at = t.seen_at.max(now);
297 if first {
298 t.seen_at = now;
299 t.step = None;
300 t.first_at = now;
301 }
302 t.observe_step(now, end, rules);
303 self.last_delivery = Some(self.last_delivery.map_or(now, |l| l.max(now)));
304 self.first_delivery.get_or_insert(now);
305 Some(first)
306 }
307
308 pub(crate) fn close_windows(&mut self, rules: StepRules) {
310 for t in &mut self.v {
311 t.commit_window(rules);
312 }
313 }
314
315 fn silence_clock(&self, now: Duration) -> Option<Duration> {
324 let last = self.last_delivery?;
325 let step = self
326 .v
327 .iter()
328 .map(|t| t.gran.value(instant_micros(now)))
329 .max()
330 .unwrap_or(0);
331 Some(last.max(now.min(duration_add(last, micros_as_duration(step)))))
332 }
333
334 fn is_silent(&self, t: &Track, silence: &Duration, clock: Option<Duration>) -> bool {
336 let since = match (t.end, self.first_delivery) {
339 (None, Some(f)) => t.seen_at.max(f),
340 _ => t.seen_at,
341 };
342 clock.is_some_and(|l| duration_between(since, l) >= *silence)
343 }
344
345 pub(crate) fn is_live(&self, id: u32, now: Duration, silence: Duration) -> bool {
347 let clock = self.silence_clock(now);
348 self.v
349 .iter()
350 .any(|t| t.id == id && !self.is_silent(t, &silence, clock))
351 }
352
353 pub(crate) fn granularity(&self, now: Duration, silence: Duration) -> Duration {
355 let clock = self.silence_clock(now);
356 self.v
357 .iter()
358 .filter(|t| !self.is_silent(t, &silence, clock))
359 .map(|t| micros_as_duration(t.gran.value(instant_micros(now))))
360 .max()
361 .unwrap_or(Duration::ZERO)
362 }
363
364 pub(crate) fn granularity_known(
369 &self,
370 now: Duration,
371 silence: Duration,
372 max_wait: Duration,
373 ) -> bool {
374 let clock = self.silence_clock(now);
375 self.v
376 .iter()
377 .filter(|t| t.end.is_some() && !self.is_silent(t, &silence, clock))
378 .all(|t| t.windows > LEARN_STEPS || duration_between(t.first_at, now) >= max_wait)
379 }
380
381 pub(crate) fn rebaseline(&mut self, now: Duration) {
384 self.v.retain(|t| t.registered);
385 self.last_delivery = None;
386 self.first_delivery = None;
387 for t in &mut self.v {
388 t.end = None;
389 t.step = None;
390 t.seen_at = now;
391 }
392 }
393
394 pub(crate) fn effective(
400 &self,
401 now: Duration,
402 silence: Duration,
403 pending_blocks: bool,
404 ) -> Option<Effective> {
405 let clock = self.silence_clock(now);
406 let mut min: Option<Effective> = None;
407 for t in self
408 .v
409 .iter()
410 .filter(|t| !self.is_silent(t, &silence, clock))
411 {
412 let Some(end) = t.end else {
413 if pending_blocks {
414 return None;
415 }
416 continue;
417 };
418 if min.is_none_or(|m| before(end, m.end)) {
419 min = Some(Effective {
420 end,
421 limiting: t.id,
422 });
423 }
424 }
425 min
426 }
427}
428
429#[cfg(test)]
430mod tests {
431 use super::{StepRules, TrackSet};
432 use crate::time::Clock27;
433 use core::time::Duration;
434
435 fn set() -> TrackSet {
436 TrackSet::new(Duration::from_secs(30), Duration::from_secs(30))
437 }
438
439 fn rules(
440 epoch: u64,
441 max_interval: Duration,
442 max_excess: Duration,
443 gap: Option<Duration>,
444 ) -> StepRules {
445 StepRules {
446 max_interval,
447 max_excess,
448 gap_end_at: gap,
449 epoch,
450 }
451 }
452
453 fn short(epoch: u64, gap: Option<Duration>) -> StepRules {
454 rules(
455 epoch,
456 Duration::from_secs(3),
457 Duration::from_millis(200),
458 gap,
459 )
460 }
461
462 fn ticks(n: u64) -> Clock27 {
463 Clock27::from_27mhz(n).expect("on the clock")
464 }
465
466 fn clock(secs: u64) -> Clock27 {
467 Clock27::from_27mhz(secs * 27_000_000).expect("whole seconds are on the clock")
468 }
469
470 #[test]
471 fn equal_ends_keep_the_first_track_as_the_limiting_one() {
472 let mut s = set();
473 let r = short(0, None);
474 assert_eq!(s.deliver(0, Duration::ZERO, clock(5), r), Some(true));
475 assert_eq!(s.deliver(1, Duration::ZERO, clock(5), r), Some(true));
476 let e = s
477 .effective(Duration::ZERO, Duration::from_secs(3), true)
478 .expect("both tracks delivered");
479 assert_eq!(e.limiting, 0);
480 assert_eq!(e.end, clock(5));
481 }
482
483 #[test]
484 fn a_zero_length_delivery_interval_is_not_a_step() {
485 let mut s = set();
486 let r = short(1, None);
487 s.deliver(0, Duration::ZERO, ticks(0), r);
488 s.close_windows(r);
489 s.deliver(0, Duration::ZERO, ticks(540_000), r);
490 s.close_windows(r);
491 assert_eq!(
492 s.granularity(Duration::ZERO, Duration::from_secs(3)),
493 Duration::ZERO
494 );
495 }
496
497 #[test]
498 fn a_delivery_interval_at_the_silence_timeout_is_not_a_step() {
499 let mut s = set();
500 let r = short(1, None);
501 s.deliver(0, Duration::ZERO, ticks(0), r);
502 s.close_windows(r);
503 s.deliver(0, Duration::from_secs(3), ticks(540_000), r);
504 s.close_windows(r);
505 assert_eq!(
506 s.granularity(Duration::from_secs(3), Duration::from_secs(3)),
507 Duration::ZERO
508 );
509 }
510
511 #[test]
512 fn a_gap_after_the_delivery_interval_suppresses_the_step() {
513 let mut s = set();
514 let r = short(1, Some(Duration::from_secs(1)));
515 s.deliver(0, Duration::ZERO, ticks(0), r);
516 s.close_windows(r);
517 s.deliver(0, Duration::from_secs(1), ticks(540_000), r);
518 s.close_windows(r);
519 assert_eq!(
520 s.granularity(Duration::from_secs(1), Duration::from_secs(3)),
521 Duration::ZERO
522 );
523 }
524
525 #[test]
526 fn a_gap_at_the_previous_delivery_instant_is_not_inside_the_interval() {
527 let mut s = set();
528 let r = short(1, Some(Duration::ZERO));
529 s.deliver(0, Duration::ZERO, ticks(0), r);
530 s.close_windows(r);
531 s.deliver(0, Duration::from_secs(1), ticks(540_000), r);
532 s.close_windows(r);
533 assert_eq!(
534 s.granularity(Duration::from_secs(1), Duration::from_secs(3)),
535 Duration::from_millis(20)
536 );
537 }
538
539 #[test]
540 fn a_step_exactly_at_the_interval_plus_allowance_is_recorded() {
541 let mut s = set();
542 let r = short(1, None);
543 s.deliver(0, Duration::ZERO, ticks(0), r);
544 s.close_windows(r);
545 s.deliver(0, Duration::from_secs(1), ticks(32_400_000), r);
546 s.close_windows(r);
547 assert_eq!(
548 s.granularity(Duration::from_secs(1), Duration::from_secs(3)),
549 Duration::from_millis(1_200)
550 );
551 }
552
553 #[test]
554 fn deliveries_in_one_chunk_epoch_are_one_window_however_far_apart() {
555 let mut s = set();
556 let r = short(1, None);
557 s.deliver(0, Duration::ZERO, ticks(0), r);
558 s.deliver(0, Duration::from_millis(2), ticks(540_000), r);
559 s.deliver(0, Duration::from_millis(4), ticks(1_080_000), r);
560 s.deliver(0, Duration::from_millis(6), ticks(1_620_000), r);
561 assert!(!s.granularity_known(
562 Duration::from_millis(6),
563 Duration::from_secs(3),
564 Duration::MAX
565 ));
566 }
567
568 #[test]
569 fn deliveries_exactly_one_coalescing_window_apart_are_separate_windows() {
570 let mut s = set();
571 let r = short(0, None);
572 s.deliver(0, Duration::ZERO, ticks(0), r);
573 s.deliver(0, Duration::from_millis(1), ticks(540_000), r);
574 s.deliver(0, Duration::from_millis(3), ticks(1_080_000), r);
575 s.deliver(0, Duration::from_millis(5), ticks(1_620_000), r);
576 assert!(s.granularity_known(
577 Duration::from_millis(5),
578 Duration::from_secs(3),
579 Duration::MAX
580 ));
581 }
582
583 #[test]
584 fn clearing_the_set_forgets_every_track_and_delivery() {
585 let mut s = set();
586 let r = short(0, None);
587 s.deliver(0, Duration::ZERO, clock(1), r);
588 s.register(7, Duration::ZERO);
589 assert_eq!(s.len(), 2);
590 s.clear();
591 assert_eq!(s.len(), 0);
592 assert_eq!(
593 s.effective(Duration::ZERO, Duration::from_secs(3), true),
594 None
595 );
596 assert!(!s.is_live(0, Duration::ZERO, Duration::from_secs(3)));
597 assert_eq!(
598 s.granularity(Duration::ZERO, Duration::from_secs(3)),
599 Duration::ZERO
600 );
601 }
602
603 #[test]
604 fn only_a_known_speaking_track_is_live() {
605 let mut s = set();
606 let r = short(0, None);
607 let silence = Duration::from_secs(3);
608 s.deliver(1, Duration::ZERO, clock(0), r);
609 assert!(s.is_live(1, Duration::ZERO, silence));
610 assert!(!s.is_live(9, Duration::ZERO, silence));
611 s.deliver(2, Duration::ZERO, clock(0), r);
612 s.deliver(2, Duration::from_secs(20), clock(20), r);
613 assert!(!s.is_live(1, Duration::from_secs(20), silence));
614 s.deliver(1, Duration::from_secs(20), clock(20), r);
615 assert!(s.is_live(1, Duration::from_secs(20), silence));
616 }
617
618 #[test]
619 fn a_track_that_never_delivered_does_not_block_the_granularity_gate() {
620 let mut s = set();
621 let r = short(1, None);
622 s.register(1, Duration::ZERO);
623 s.deliver(0, Duration::ZERO, ticks(0), r);
624 s.close_windows(r);
625 s.deliver(0, Duration::from_millis(1), ticks(540_000), r);
626 s.close_windows(r);
627 s.deliver(0, Duration::from_millis(2), ticks(1_080_000), r);
628 s.close_windows(r);
629 s.deliver(0, Duration::from_millis(3), ticks(1_620_000), r);
630 s.close_windows(r);
631 assert!(s.granularity_known(
632 Duration::from_millis(3),
633 Duration::from_secs(3),
634 Duration::MAX
635 ));
636 }
637}