use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Transport {
Prepare {
project: String,
bpm: f32,
master_ns: u64,
},
Ready {
instance: String,
output_latency: u32,
sample_rate: u32,
loop_frames: u64,
},
Start {
at_ns: u64,
frame: u64,
master_ns: u64,
},
Stop {
at_ns: u64,
master_ns: u64,
},
Locate {
at_ns: u64,
frame: u64,
master_ns: u64,
},
Tempo {
bpm: f32,
master_ns: u64,
},
Beacon {
master_ns: u64,
plan: Option<(u64, u64)>,
},
}
impl Transport {
pub fn master_ns(&self) -> Option<u64> {
match self {
Transport::Prepare { master_ns, .. }
| Transport::Start { master_ns, .. }
| Transport::Stop { master_ns, .. }
| Transport::Locate { master_ns, .. }
| Transport::Tempo { master_ns, .. }
| Transport::Beacon { master_ns, .. } => Some(*master_ns),
Transport::Ready { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SessionClock {
offset: Option<i128>,
seen: u64,
}
impl SessionClock {
pub fn observe(&mut self, master_ns: u64, local_ns: u64) {
let o = i128::from(master_ns) - i128::from(local_ns);
self.offset = Some(self.offset.map_or(o, |x| x.max(o)));
self.seen += 1;
}
pub fn known(&self) -> bool {
self.offset.is_some()
}
pub fn to_session(&self, local_ns: u64) -> i128 {
i128::from(local_ns) + self.offset.unwrap_or(0)
}
pub fn to_local(&self, session_ns: i128) -> i128 {
session_ns - self.offset.unwrap_or(0)
}
pub fn offset(&self) -> Option<i128> {
self.offset
}
}
#[derive(Clone, Copy, Debug)]
pub struct Observed {
pub now_ns: u64,
pub callback_ns: u64,
pub output_frame: u64,
pub transport_frame: u64,
pub playing: bool,
pub block_frames: u32,
pub sample_rate: u32,
pub loop_frames: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Action {
Start(u64),
Stop,
Locate(u64),
Tempo(f32),
}
#[derive(Clone, Debug)]
pub struct Follower {
clock: SessionClock,
plan: Option<(i128, u64)>,
stop_at: Option<i128>,
pub tolerance: u64,
waiting_since: Option<u64>,
pub corrections: u64,
pub last_error: i64,
pub worst_error: u64,
settled: bool,
deferred_since: Option<u64>,
pub deferrals: u64,
}
pub const MAX_DEFER_NS: u64 = 500_000_000;
pub const MAX_DEFER_ERROR: u64 = 4;
fn any_in(events: &[u64], start: u64, len: u64, loop_frames: u64) -> bool {
let has = |a: u64, b: u64| {
let i = events.partition_point(|&e| e < a);
events.get(i).is_some_and(|&e| e < b)
};
if len == 0 || events.is_empty() {
return false;
}
if loop_frames == 0 || start + len <= loop_frames {
return has(start, start + len);
}
has(start, loop_frames) || has(0, (start + len - loop_frames).min(loop_frames))
}
impl Default for Follower {
fn default() -> Self {
Follower::new(256)
}
}
fn wrap(x: i128, l: u64) -> u64 {
if l == 0 { x.max(0) as u64 } else { x.rem_euclid(i128::from(l)) as u64 }
}
fn wrapped_diff(a: u64, b: u64, l: u64) -> i64 {
if l == 0 {
return a as i64 - b as i64;
}
let d = (i128::from(a) - i128::from(b)).rem_euclid(i128::from(l));
if d > i128::from(l) / 2 { (d - i128::from(l)) as i64 } else { d as i64 }
}
impl Follower {
pub fn new(tolerance: u64) -> Self {
Follower {
clock: SessionClock::default(),
plan: None,
stop_at: None,
tolerance,
waiting_since: None,
corrections: 0,
last_error: 0,
worst_error: 0,
settled: false,
deferred_since: None,
deferrals: 0,
}
}
pub fn clock(&self) -> &SessionClock {
&self.clock
}
pub fn plan(&self) -> Option<(i128, u64)> {
self.plan
}
pub fn on_message(&mut self, msg: &Transport, local_ns: u64) -> Option<Action> {
if let Some(m) = msg.master_ns() {
self.clock.observe(m, local_ns);
}
match *msg {
Transport::Start { at_ns, frame, .. } | Transport::Locate { at_ns, frame, .. } => {
if self.plan != Some((i128::from(at_ns), frame)) {
self.plan = Some((i128::from(at_ns), frame));
self.stop_at = None;
self.settled = false;
}
None
}
Transport::Beacon { plan: Some((at_ns, frame)), .. } if self.plan.is_none() && self.stop_at.is_none() => {
self.plan = Some((i128::from(at_ns), frame));
None
}
Transport::Stop { at_ns, .. } => {
self.stop_at = Some(i128::from(at_ns));
None
}
Transport::Tempo { bpm, .. } => Some(Action::Tempo(bpm)),
_ => None,
}
}
pub fn expected_at(&self, local_ns: i128, rate: u32) -> Option<i128> {
let (at, frame) = self.plan?;
let s = self.clock.to_session(0) + local_ns;
Some(i128::from(frame) + (s - at) * i128::from(rate) / 1_000_000_000)
}
pub fn abs_of(&self, transport_frame: u64, local_ns: u64, rate: u32, loop_frames: u64) -> Option<u64> {
let expected = self.expected_at(i128::from(local_ns), rate)?;
if loop_frames == 0 {
return Some(expected.max(0) as u64);
}
let l = i128::from(loop_frames);
let t = i128::from(transport_frame);
let loops = (expected - t + l / 2).div_euclid(l);
Some((loops * l + t).max(0) as u64)
}
pub fn step(&mut self, o: &Observed) -> Option<Action> {
self.step_with(o, &[])
}
pub fn step_with(&mut self, o: &Observed, events: &[u64]) -> Option<Action> {
let rate = o.sample_rate.max(1);
let block = u64::from(o.block_frames.max(1));
let block_ns = (block as i128 * 1_000_000_000 / i128::from(rate)).max(1);
let since = (i128::from(o.now_ns) - i128::from(o.callback_ns)).max(0);
let j = since / block_ns + 1;
let next_local = i128::from(o.callback_ns) + j * block_ns;
if let Some(stop) = self.stop_at
&& self.clock.to_session(0) + next_local >= stop
{
self.plan = None;
self.stop_at = None;
if o.playing {
return Some(Action::Stop);
}
}
let expected_next = self.expected_at(next_local, rate)?;
if let Some(w) = self.waiting_since {
if o.callback_ns <= w {
return None;
}
self.waiting_since = None;
}
if !o.playing {
if expected_next < i128::from(self.plan?.1) {
return None;
}
self.waiting_since = Some(o.now_ns);
return Some(Action::Start(wrap(expected_next, o.loop_frames)));
}
let expected_now = self.expected_at(i128::from(o.callback_ns), rate)?;
if expected_now < 0 {
return None;
}
let err = wrapped_diff(o.transport_frame, wrap(expected_now, o.loop_frames), o.loop_frames);
self.last_error = err;
if self.settled {
self.worst_error = self.worst_error.max(err.unsigned_abs());
}
if err.unsigned_abs() > self.tolerance {
let here_next = wrap(i128::from(o.transport_frame) + j * block as i128, o.loop_frames);
let target = wrap(expected_next, o.loop_frames);
let jump = wrapped_diff(here_next, target, o.loop_frames);
let (from, len) = if jump > 0 { (target, jump as u64) } else { (here_next, jump.unsigned_abs()) };
let urgent = err.unsigned_abs() > self.tolerance * MAX_DEFER_ERROR
|| self.deferred_since.is_some_and(|t| o.now_ns.saturating_sub(t) >= MAX_DEFER_NS);
if !urgent && any_in(events, from, len, o.loop_frames) {
if self.deferred_since.is_none() {
self.deferred_since = Some(o.now_ns);
self.deferrals += 1;
}
return None;
}
self.deferred_since = None;
self.corrections += 1;
self.waiting_since = Some(o.now_ns);
self.settled = false;
return Some(Action::Locate(wrap(expected_next, o.loop_frames)));
}
self.settled = true;
self.deferred_since = None;
None
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Unwrap {
last: u64,
base: u64,
}
impl Unwrap {
pub fn abs(&mut self, transport_frame: u64, playing: bool, loop_frames: u64) -> u64 {
if !playing {
*self = Unwrap::default();
return transport_frame;
}
let half = loop_frames / 2;
if transport_frame + half < self.last {
self.base += loop_frames;
} else if transport_frame > self.last + half && self.base >= loop_frames {
self.base -= loop_frames;
}
self.last = transport_frame;
self.base + transport_frame
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Sim {
rate: u32,
ppm: f64,
block: u32,
zero: u64,
loop_frames: u64,
output_frame: u64,
transport: u64,
playing: bool,
pending: Vec<Action>,
last_cb: u64,
last_tf: u64,
last_playing: bool,
next_cb_true: f64,
log: Vec<(f64, u64, bool)>,
abs: u64,
follower: Follower,
events: Vec<u64>,
aware: bool,
bad: u64,
}
impl Sim {
fn new(ppm: f64, block: u32, zero: u64) -> Sim {
Sim {
rate: 48_000,
ppm,
block,
zero,
loop_frames: 96_000,
output_frame: 0,
transport: 0,
playing: false,
pending: vec![],
last_cb: zero,
last_tf: 0,
last_playing: false,
next_cb_true: 0.0,
log: vec![],
abs: 0,
follower: Follower::new(u64::from(block) / 2),
events: vec![],
aware: false,
bad: 0,
}
}
fn block_ns(&self) -> f64 {
f64::from(self.block) * 1e9 / (f64::from(self.rate) * (1.0 + self.ppm * 1e-6))
}
fn run_until(&mut self, t: f64) {
while self.next_cb_true <= t {
for a in self.pending.drain(..) {
match a {
Action::Start(f) => {
self.transport = f;
self.abs = f;
self.playing = true;
}
Action::Locate(f) => {
let d = wrapped_diff(f, self.transport, self.loop_frames);
let (from, len) = if d < 0 { (f, d.unsigned_abs()) } else { (self.transport, d as u64) };
if any_in(&self.events, from, len, self.loop_frames) {
self.bad += 1;
}
self.transport = f;
self.abs = (self.abs as i64 + d) as u64;
}
Action::Stop => self.playing = false,
Action::Tempo(_) => {}
}
}
self.last_cb = self.zero + self.next_cb_true as u64;
self.last_tf = self.transport;
self.last_playing = self.playing;
self.log.push((self.next_cb_true, self.abs, self.playing));
self.output_frame += u64::from(self.block);
if self.playing {
self.transport = (self.transport + u64::from(self.block)) % self.loop_frames;
self.abs += u64::from(self.block);
}
self.next_cb_true += self.block_ns();
}
}
fn observed(&self, t: f64) -> Observed {
Observed {
now_ns: self.zero + t as u64,
callback_ns: self.last_cb,
output_frame: self.output_frame - u64::from(self.block),
transport_frame: self.last_tf,
playing: self.last_playing,
block_frames: self.block,
sample_rate: self.rate,
loop_frames: self.loop_frames,
}
}
fn poll(&mut self, t: f64) {
self.run_until(t);
let o = self.observed(t);
let events = if self.aware { std::mem::take(&mut self.events) } else { vec![] };
let a = self.follower.step_with(&o, &events);
if self.aware {
self.events = events;
}
if let Some(a) = a {
self.pending.push(a);
}
}
fn deliver(&mut self, msg: &Transport, t: f64) {
self.run_until(t);
if let Some(a) = self.follower.on_message(msg, self.zero + t as u64) {
self.pending.push(a);
}
}
fn pos_at(&self, t: f64) -> Option<f64> {
let i = self.log.iter().rposition(|(bt, _, _)| *bt <= t)?;
let (bt, abs, playing) = self.log[i];
if !playing {
return None;
}
Some(abs as f64 + (t - bt) * f64::from(self.rate) * (1.0 + self.ppm * 1e-6) / 1e9)
}
}
fn run(ppm_a: f64, ppm_b: f64, seconds: f64) -> (Sim, Sim, f64) {
run_with(ppm_a, ppm_b, seconds, &[], false)
}
fn run_with(ppm_a: f64, ppm_b: f64, seconds: f64, events: &[u64], aware: bool) -> (Sim, Sim, f64) {
let master_zero = 5_000_000_000u64;
let mut a = Sim::new(ppm_a, 256, 123_456_789);
let mut b = Sim::new(ppm_b, 480, 987_654_321_000);
for s in [&mut a, &mut b] {
s.events = events.to_vec();
s.aware = aware;
}
let delay = |k: u64| 200_000.0 + (k * 7919 % 300_000) as f64; let start_true = 0.6e9;
let mut k = 0u64;
let mut t = 0.0f64;
let mut next_beacon = 0.0;
let mut sent_start = false;
let mut msgs: Vec<(f64, usize, Transport)> = vec![];
while t < seconds * 1e9 {
if t >= next_beacon {
let plan = sent_start.then_some((master_zero + start_true as u64, 0));
let m = Transport::Beacon { master_ns: master_zero + t as u64, plan };
for who in 0..2 {
k += 1;
msgs.push((t + delay(k), who, m.clone()));
}
next_beacon += 0.25e9;
}
if !sent_start && t >= 0.1e9 {
sent_start = true;
let m = Transport::Start { at_ns: master_zero + start_true as u64, frame: 0, master_ns: master_zero + t as u64 };
for who in 0..2 {
k += 1;
msgs.push((t + delay(k), who, m.clone()));
}
}
msgs.sort_by(|x, y| x.0.total_cmp(&y.0));
while msgs.first().is_some_and(|m| m.0 <= t) {
let (at, who, m) = msgs.remove(0);
if who == 0 { a.deliver(&m, at) } else { b.deliver(&m, at) }
}
a.poll(t);
b.poll(t + 1_300_000.0);
k += 1;
t += 4_000_000.0 + (k * 104_729 % 1_500_000) as f64;
}
(a, b, start_true)
}
#[test]
fn two_instances_start_together_and_stay_with_drift() {
let (a, b, start) = run(80.0, -80.0, 60.0);
let first = |s: &Sim| s.log.iter().find(|x| x.2).map(|x| (x.0, x.1)).unwrap();
let (ta, fa) = first(&a);
let (tb, fb) = first(&b);
let err_a = ta - start - fa as f64 * 1e9 / 48_000.0;
let err_b = tb - start - fb as f64 * 1e9 / 48_000.0;
let block_ns = 256.0 * 1e9 / 48_000.0;
assert!(err_a.abs() <= block_ns && err_b.abs() <= block_ns, "start errors {err_a} {err_b} ns");
let mut worst = 0.0f64;
let mut t = start + 1e9;
while t < 59e9 {
let d = a.pos_at(t).unwrap() - b.pos_at(t).unwrap();
worst = worst.max(d.abs());
t += 1e8;
}
eprintln!(
"start errors {err_a:.0} {err_b:.0} ns; worst {worst:.1} frames; corrections {} {}; offsets {:?} {:?}",
a.follower.corrections,
b.follower.corrections,
a.follower.clock().offset(),
b.follower.clock().offset()
);
assert!(worst <= 480.0, "worst difference {worst} frames");
assert!(a.follower.corrections >= 1, "{} {}", a.follower.corrections, b.follower.corrections);
assert!(a.follower.clock().known() && b.follower.clock().known());
}
#[test]
fn a_drift_correction_waits_for_a_jump_that_crosses_no_hit() {
let events: Vec<u64> = (0..320).map(|i| i * 300).collect();
let (blind_a, blind_b, _) = run_with(200.0, -200.0, 60.0, &events, false);
let (a, b, start) = run_with(200.0, -200.0, 60.0, &events, true);
eprintln!(
"blind: corrections {} {}, over a hit {} {}; aware: corrections {} {}, over a hit {} {}, deferred {} {}",
blind_a.follower.corrections,
blind_b.follower.corrections,
blind_a.bad,
blind_b.bad,
a.follower.corrections,
b.follower.corrections,
a.bad,
b.bad,
a.follower.deferrals,
b.follower.deferrals
);
assert!(blind_a.bad + blind_b.bad > 0, "without the hits known, some corrections land on one");
assert!(a.follower.corrections >= 1 && b.follower.corrections >= 1, "they still correct");
assert_eq!(a.bad + b.bad, 0, "no correction replays or skips a hit");
let mut worst = 0.0f64;
let mut t = start + 1e9;
while t < 59e9 {
worst = worst.max((a.pos_at(t).unwrap() - b.pos_at(t).unwrap()).abs());
t += 1e8;
}
assert!(worst <= 480.0 + 2.0 * 128.0, "they stay together while a correction waits: worst {worst} frames");
}
#[test]
fn any_in_wraps_at_the_loop_end() {
let ev = [0, 100, 5_000];
assert!(any_in(&ev, 50, 60, 6_000));
assert!(!any_in(&ev, 101, 4_000, 6_000));
assert!(any_in(&ev, 5_900, 200, 6_000), "across the loop start");
assert!(!any_in(&ev, 5_001, 998, 6_000));
assert!(!any_in(&[], 0, 6_000, 6_000));
assert!(!any_in(&ev, 100, 0, 6_000));
}
#[test]
fn unwrap_tells_a_wrap_from_a_locate() {
let mut u = Unwrap::default();
assert_eq!(u.abs(90_000, true, 96_000), 90_000);
assert_eq!(u.abs(1_000, true, 96_000), 97_000, "a wrap");
assert_eq!(u.abs(900, true, 96_000), 96_900, "a small locate back stays in the loop");
assert_eq!(u.abs(95_900, true, 96_000), 95_900, "a locate back across the loop start");
assert_eq!(u.abs(5, false, 96_000), 5);
let mut f = Follower::new(128);
f.on_message(&Transport::Start { at_ns: 1_000_000_000, frame: 0, master_ns: 1_000_000_000 }, 1_000_000_000);
assert_eq!(f.abs_of(48_000, 1_000_000_000 + 5_000_000_000, 48_000, 96_000), Some(2 * 96_000 + 48_000));
assert_eq!(f.abs_of(47_990, 1_000_000_000 + 5_000_000_000, 48_000, 96_000), Some(2 * 96_000 + 47_990));
}
#[test]
fn stop_and_late_join_by_beacon() {
let mut f = Follower::new(128);
let o = |now: u64, playing: bool| Observed {
now_ns: now,
callback_ns: now - 1_000_000,
output_frame: 0,
transport_frame: 0,
playing,
block_frames: 256,
sample_rate: 48_000,
loop_frames: 96_000,
};
f.on_message(&Transport::Beacon { master_ns: 10_000_000_000, plan: Some((9_000_000_000, 0)) }, 1_000_000_000);
match f.step(&o(1_000_000_000, false)) {
Some(Action::Start(fr)) => assert!((48_000..48_000 + 600).contains(&fr), "{fr}"),
other => panic!("{other:?}"),
}
f.on_message(&Transport::Stop { at_ns: 0, master_ns: 10_100_000_000 }, 1_100_000_000);
assert_eq!(f.step(&o(1_100_000_000, true)), Some(Action::Stop));
assert_eq!(f.on_message(&Transport::Tempo { bpm: 90.0, master_ns: 10_200_000_000 }, 1_200_000_000), Some(Action::Tempo(90.0)));
}
}