use crate::errors::{
BunsenError,
BunsenResult,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClockAnchor {
pub sample: usize,
pub time: f64,
}
#[derive(Debug, Clone, PartialEq)]
pub struct StreamClock {
rate: usize,
anchors: Vec<ClockAnchor>,
}
impl StreamClock {
pub fn uniform(rate: usize) -> Self {
assert_ne!(rate, 0, "a clock needs a non-zero sample rate");
Self {
rate,
anchors: vec![ClockAnchor {
sample: 0,
time: 0.0,
}],
}
}
pub fn rate(&self) -> usize {
self.rate
}
pub fn anchors(&self) -> &[ClockAnchor] {
&self.anchors
}
pub fn anchor(
&mut self,
sample: usize,
time: f64,
) -> BunsenResult<()> {
if !time.is_finite() {
return Err(BunsenError::Invalid(format!(
"anchor time must be finite, got {time}"
)));
}
let last = self.anchors.last().expect("never empty");
if sample < last.sample {
return Err(BunsenError::Invalid(format!(
"anchors must not go backwards: sample {sample} after {}",
last.sample,
)));
}
if sample == last.sample {
self.anchors.pop();
}
self.anchors.push(ClockAnchor { sample, time });
Ok(())
}
pub fn time_at(
&self,
sample: usize,
) -> f64 {
let at = self.anchors.partition_point(|a| a.sample <= sample);
let base = self.anchors[at.saturating_sub(1)];
let delta = sample as f64 - base.sample as f64;
base.time + delta / self.rate as f64
}
pub fn slice(
&self,
from: usize,
to: usize,
) -> Self {
assert!(to >= from, "slice end {to} is before its start {from}");
let mut anchors = vec![ClockAnchor {
sample: 0,
time: self.time_at(from),
}];
anchors.extend(
self.anchors
.iter()
.filter(|a| a.sample > from && a.sample < to)
.map(|a| ClockAnchor {
sample: a.sample - from,
time: a.time,
}),
);
Self {
rate: self.rate,
anchors,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn close(
a: f64,
b: f64,
) -> bool {
(a - b).abs() < 1e-9
}
#[test]
fn test_uniform_is_sample_over_rate() {
let clock = StreamClock::uniform(16_000);
assert_eq!(clock.rate(), 16_000);
assert_eq!(clock.anchors().len(), 1);
for sample in [0, 1, 160, 16_000, 48_000, 10_000_000] {
assert!(close(clock.time_at(sample), sample as f64 / 16_000.0));
}
}
#[test]
fn test_anchor_shifts_from_there_on() {
let mut clock = StreamClock::uniform(16_000);
clock.anchor(32_000, 12.5).unwrap();
assert!(
close(clock.time_at(16_000), 1.0),
"before the anchor: unchanged"
);
assert!(close(clock.time_at(32_000), 12.5));
assert!(
close(clock.time_at(48_000), 13.5),
"after: advances from the anchor"
);
}
#[test]
fn test_anchor_before_the_first_extrapolates_backwards() {
let mut clock = StreamClock::uniform(16_000);
clock.anchor(0, 100.0).unwrap();
assert!(
close(clock.time_at(0), 100.0),
"re-anchoring sample 0 replaces it"
);
assert_eq!(clock.anchors().len(), 1);
let mut late = StreamClock {
rate: 16_000,
anchors: vec![ClockAnchor {
sample: 16_000,
time: 5.0,
}],
};
assert!(close(late.time_at(0), 4.0));
late.anchor(16_000, 6.0).unwrap();
assert!(close(late.time_at(0), 5.0));
}
#[test]
fn test_anchors_stay_monotone() {
let mut clock = StreamClock::uniform(16_000);
clock.anchor(1_000, 1.0).unwrap();
assert!(clock.anchor(999, 2.0).is_err(), "backwards in sample");
assert!(clock.anchor(2_000, f64::NAN).is_err());
assert!(clock.anchor(2_000, f64::INFINITY).is_err());
assert_eq!(
clock.anchors().len(),
2,
"a rejected anchor leaves no trace"
);
clock.anchor(2_000, 0.5).unwrap();
assert!(
clock
.anchors()
.windows(2)
.all(|w| w[0].sample <= w[1].sample)
);
}
#[test]
fn test_slice_round_trips() {
let mut clock = StreamClock::uniform(16_000);
clock.anchor(10_000, 3.0).unwrap();
clock.anchor(40_000, 9.0).unwrap();
for (from, to) in [
(0, 5_000),
(5_000, 20_000),
(10_000, 50_000),
(30_000, 30_001),
] {
let sliced = clock.slice(from, to);
assert_eq!(sliced.rate(), clock.rate());
assert_eq!(sliced.anchors()[0].sample, 0);
for s in [0, 1, 320, 4_999, 12_000, 25_000]
.into_iter()
.filter(|&s| from + s < to)
{
assert!(
close(sliced.time_at(s), clock.time_at(from + s)),
"from {from} to {to}, sample {s}",
);
}
}
let sliced = clock.slice(5_000, 40_000);
assert_eq!(sliced.anchors().len(), 2);
assert_eq!(sliced.anchors()[1].sample, 5_000);
assert!(close(sliced.anchors()[1].time, 3.0));
}
#[test]
fn test_timestamp_token_resolution() {
let mut clock = StreamClock::uniform(16_000);
clock.anchor(0, 60.0).unwrap();
let origin = 48_000; assert!(close(clock.time_at(origin + 100 * 320), 60.0 + 3.0 + 2.0));
}
}