1use serde::{Deserialize, Serialize};
16
17#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
19pub enum Transport {
20 Prepare {
22 project: String,
24 bpm: f32,
26 master_ns: u64,
28 },
29 Ready {
31 instance: String,
33 output_latency: u32,
35 sample_rate: u32,
37 loop_frames: u64,
39 },
40 Start {
42 at_ns: u64,
44 frame: u64,
46 master_ns: u64,
48 },
49 Stop {
51 at_ns: u64,
53 master_ns: u64,
55 },
56 Locate {
58 at_ns: u64,
60 frame: u64,
62 master_ns: u64,
64 },
65 Tempo {
67 bpm: f32,
69 master_ns: u64,
71 },
72 Beacon {
75 master_ns: u64,
77 plan: Option<(u64, u64)>,
79 },
80}
81
82impl Transport {
83 pub fn master_ns(&self) -> Option<u64> {
85 match self {
86 Transport::Prepare { master_ns, .. }
87 | Transport::Start { master_ns, .. }
88 | Transport::Stop { master_ns, .. }
89 | Transport::Locate { master_ns, .. }
90 | Transport::Tempo { master_ns, .. }
91 | Transport::Beacon { master_ns, .. } => Some(*master_ns),
92 Transport::Ready { .. } => None,
93 }
94 }
95}
96
97#[derive(Clone, Copy, Debug, Default)]
99pub struct SessionClock {
100 offset: Option<i128>,
101 seen: u64,
102}
103
104impl SessionClock {
105 pub fn observe(&mut self, master_ns: u64, local_ns: u64) {
107 let o = i128::from(master_ns) - i128::from(local_ns);
108 self.offset = Some(self.offset.map_or(o, |x| x.max(o)));
109 self.seen += 1;
110 }
111
112 pub fn known(&self) -> bool {
114 self.offset.is_some()
115 }
116
117 pub fn to_session(&self, local_ns: u64) -> i128 {
119 i128::from(local_ns) + self.offset.unwrap_or(0)
120 }
121
122 pub fn to_local(&self, session_ns: i128) -> i128 {
124 session_ns - self.offset.unwrap_or(0)
125 }
126
127 pub fn offset(&self) -> Option<i128> {
129 self.offset
130 }
131}
132
133#[derive(Clone, Copy, Debug)]
135pub struct Observed {
136 pub now_ns: u64,
138 pub callback_ns: u64,
140 pub output_frame: u64,
142 pub transport_frame: u64,
144 pub playing: bool,
146 pub block_frames: u32,
148 pub sample_rate: u32,
150 pub loop_frames: u64,
152}
153
154#[derive(Clone, Copy, Debug, PartialEq)]
156pub enum Action {
157 Start(u64),
159 Stop,
161 Locate(u64),
163 Tempo(f32),
165}
166
167#[derive(Clone, Debug)]
169pub struct Follower {
170 clock: SessionClock,
171 plan: Option<(i128, u64)>,
172 stop_at: Option<i128>,
173 pub tolerance: u64,
175 waiting_since: Option<u64>,
176 pub corrections: u64,
178 pub last_error: i64,
180 pub worst_error: u64,
182 settled: bool,
183 deferred_since: Option<u64>,
185 pub deferrals: u64,
187}
188
189pub const MAX_DEFER_NS: u64 = 500_000_000;
191pub const MAX_DEFER_ERROR: u64 = 4;
193
194fn any_in(events: &[u64], start: u64, len: u64, loop_frames: u64) -> bool {
196 let has = |a: u64, b: u64| {
197 let i = events.partition_point(|&e| e < a);
198 events.get(i).is_some_and(|&e| e < b)
199 };
200 if len == 0 || events.is_empty() {
201 return false;
202 }
203 if loop_frames == 0 || start + len <= loop_frames {
204 return has(start, start + len);
205 }
206 has(start, loop_frames) || has(0, (start + len - loop_frames).min(loop_frames))
207}
208
209impl Default for Follower {
210 fn default() -> Self {
211 Follower::new(256)
212 }
213}
214
215fn wrap(x: i128, l: u64) -> u64 {
216 if l == 0 { x.max(0) as u64 } else { x.rem_euclid(i128::from(l)) as u64 }
217}
218
219fn wrapped_diff(a: u64, b: u64, l: u64) -> i64 {
220 if l == 0 {
221 return a as i64 - b as i64;
222 }
223 let d = (i128::from(a) - i128::from(b)).rem_euclid(i128::from(l));
224 if d > i128::from(l) / 2 { (d - i128::from(l)) as i64 } else { d as i64 }
225}
226
227impl Follower {
228 pub fn new(tolerance: u64) -> Self {
230 Follower {
231 clock: SessionClock::default(),
232 plan: None,
233 stop_at: None,
234 tolerance,
235 waiting_since: None,
236 corrections: 0,
237 last_error: 0,
238 worst_error: 0,
239 settled: false,
240 deferred_since: None,
241 deferrals: 0,
242 }
243 }
244
245 pub fn clock(&self) -> &SessionClock {
247 &self.clock
248 }
249
250 pub fn plan(&self) -> Option<(i128, u64)> {
252 self.plan
253 }
254
255 pub fn on_message(&mut self, msg: &Transport, local_ns: u64) -> Option<Action> {
258 if let Some(m) = msg.master_ns() {
259 self.clock.observe(m, local_ns);
260 }
261 match *msg {
262 Transport::Start { at_ns, frame, .. } | Transport::Locate { at_ns, frame, .. } => {
263 if self.plan != Some((i128::from(at_ns), frame)) {
264 self.plan = Some((i128::from(at_ns), frame));
265 self.stop_at = None;
266 self.settled = false;
267 }
268 None
269 }
270 Transport::Beacon { plan: Some((at_ns, frame)), .. } if self.plan.is_none() && self.stop_at.is_none() => {
271 self.plan = Some((i128::from(at_ns), frame));
272 None
273 }
274 Transport::Stop { at_ns, .. } => {
275 self.stop_at = Some(i128::from(at_ns));
276 None
277 }
278 Transport::Tempo { bpm, .. } => Some(Action::Tempo(bpm)),
279 _ => None,
280 }
281 }
282
283 pub fn expected_at(&self, local_ns: i128, rate: u32) -> Option<i128> {
285 let (at, frame) = self.plan?;
286 let s = self.clock.to_session(0) + local_ns;
287 Some(i128::from(frame) + (s - at) * i128::from(rate) / 1_000_000_000)
288 }
289
290 pub fn abs_of(&self, transport_frame: u64, local_ns: u64, rate: u32, loop_frames: u64) -> Option<u64> {
293 let expected = self.expected_at(i128::from(local_ns), rate)?;
294 if loop_frames == 0 {
295 return Some(expected.max(0) as u64);
296 }
297 let l = i128::from(loop_frames);
298 let t = i128::from(transport_frame);
299 let loops = (expected - t + l / 2).div_euclid(l);
300 Some((loops * l + t).max(0) as u64)
301 }
302
303 pub fn step(&mut self, o: &Observed) -> Option<Action> {
305 self.step_with(o, &[])
306 }
307
308 pub fn step_with(&mut self, o: &Observed, events: &[u64]) -> Option<Action> {
313 let rate = o.sample_rate.max(1);
314 let block = u64::from(o.block_frames.max(1));
315 let block_ns = (block as i128 * 1_000_000_000 / i128::from(rate)).max(1);
316 let since = (i128::from(o.now_ns) - i128::from(o.callback_ns)).max(0);
318 let j = since / block_ns + 1;
319 let next_local = i128::from(o.callback_ns) + j * block_ns;
320 if let Some(stop) = self.stop_at
321 && self.clock.to_session(0) + next_local >= stop
322 {
323 self.plan = None;
324 self.stop_at = None;
325 if o.playing {
326 return Some(Action::Stop);
327 }
328 }
329 let expected_next = self.expected_at(next_local, rate)?;
330 if let Some(w) = self.waiting_since {
332 if o.callback_ns <= w {
333 return None;
334 }
335 self.waiting_since = None;
336 }
337 if !o.playing {
338 if expected_next < i128::from(self.plan?.1) {
341 return None;
342 }
343 self.waiting_since = Some(o.now_ns);
344 return Some(Action::Start(wrap(expected_next, o.loop_frames)));
345 }
346 let expected_now = self.expected_at(i128::from(o.callback_ns), rate)?;
347 if expected_now < 0 {
348 return None;
349 }
350 let err = wrapped_diff(o.transport_frame, wrap(expected_now, o.loop_frames), o.loop_frames);
351 self.last_error = err;
352 if self.settled {
353 self.worst_error = self.worst_error.max(err.unsigned_abs());
354 }
355 if err.unsigned_abs() > self.tolerance {
356 let here_next = wrap(i128::from(o.transport_frame) + j * block as i128, o.loop_frames);
357 let target = wrap(expected_next, o.loop_frames);
358 let jump = wrapped_diff(here_next, target, o.loop_frames);
359 let (from, len) = if jump > 0 { (target, jump as u64) } else { (here_next, jump.unsigned_abs()) };
361 let urgent = err.unsigned_abs() > self.tolerance * MAX_DEFER_ERROR
362 || self.deferred_since.is_some_and(|t| o.now_ns.saturating_sub(t) >= MAX_DEFER_NS);
363 if !urgent && any_in(events, from, len, o.loop_frames) {
364 if self.deferred_since.is_none() {
365 self.deferred_since = Some(o.now_ns);
366 self.deferrals += 1;
367 }
368 return None;
369 }
370 self.deferred_since = None;
371 self.corrections += 1;
372 self.waiting_since = Some(o.now_ns);
373 self.settled = false;
374 return Some(Action::Locate(wrap(expected_next, o.loop_frames)));
375 }
376 self.settled = true;
377 self.deferred_since = None;
378 None
379 }
380}
381
382#[derive(Clone, Copy, Debug, Default)]
385pub struct Unwrap {
386 last: u64,
387 base: u64,
388}
389
390impl Unwrap {
391 pub fn abs(&mut self, transport_frame: u64, playing: bool, loop_frames: u64) -> u64 {
393 if !playing {
394 *self = Unwrap::default();
395 return transport_frame;
396 }
397 let half = loop_frames / 2;
398 if transport_frame + half < self.last {
399 self.base += loop_frames;
400 } else if transport_frame > self.last + half && self.base >= loop_frames {
401 self.base -= loop_frames;
402 }
403 self.last = transport_frame;
404 self.base + transport_frame
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411
412 struct Sim {
416 rate: u32,
417 ppm: f64,
418 block: u32,
419 zero: u64,
420 loop_frames: u64,
421 output_frame: u64,
422 transport: u64,
423 playing: bool,
424 pending: Vec<Action>,
425 last_cb: u64,
426 last_tf: u64,
427 last_playing: bool,
428 next_cb_true: f64,
429 log: Vec<(f64, u64, bool)>,
431 abs: u64,
432 follower: Follower,
433 events: Vec<u64>,
435 aware: bool,
436 bad: u64,
438 }
439
440 impl Sim {
441 fn new(ppm: f64, block: u32, zero: u64) -> Sim {
442 Sim {
443 rate: 48_000,
444 ppm,
445 block,
446 zero,
447 loop_frames: 96_000,
448 output_frame: 0,
449 transport: 0,
450 playing: false,
451 pending: vec![],
452 last_cb: zero,
453 last_tf: 0,
454 last_playing: false,
455 next_cb_true: 0.0,
456 log: vec![],
457 abs: 0,
458 follower: Follower::new(u64::from(block) / 2),
459 events: vec![],
460 aware: false,
461 bad: 0,
462 }
463 }
464 fn block_ns(&self) -> f64 {
465 f64::from(self.block) * 1e9 / (f64::from(self.rate) * (1.0 + self.ppm * 1e-6))
466 }
467 fn run_until(&mut self, t: f64) {
468 while self.next_cb_true <= t {
469 for a in self.pending.drain(..) {
470 match a {
471 Action::Start(f) => {
472 self.transport = f;
473 self.abs = f;
474 self.playing = true;
475 }
476 Action::Locate(f) => {
477 let d = wrapped_diff(f, self.transport, self.loop_frames);
478 let (from, len) = if d < 0 { (f, d.unsigned_abs()) } else { (self.transport, d as u64) };
479 if any_in(&self.events, from, len, self.loop_frames) {
480 self.bad += 1;
481 }
482 self.transport = f;
483 self.abs = (self.abs as i64 + d) as u64;
484 }
485 Action::Stop => self.playing = false,
486 Action::Tempo(_) => {}
487 }
488 }
489 self.last_cb = self.zero + self.next_cb_true as u64;
490 self.last_tf = self.transport;
491 self.last_playing = self.playing;
492 self.log.push((self.next_cb_true, self.abs, self.playing));
493 self.output_frame += u64::from(self.block);
494 if self.playing {
495 self.transport = (self.transport + u64::from(self.block)) % self.loop_frames;
496 self.abs += u64::from(self.block);
497 }
498 self.next_cb_true += self.block_ns();
499 }
500 }
501 fn observed(&self, t: f64) -> Observed {
502 Observed {
503 now_ns: self.zero + t as u64,
504 callback_ns: self.last_cb,
505 output_frame: self.output_frame - u64::from(self.block),
506 transport_frame: self.last_tf,
507 playing: self.last_playing,
508 block_frames: self.block,
509 sample_rate: self.rate,
510 loop_frames: self.loop_frames,
511 }
512 }
513 fn poll(&mut self, t: f64) {
514 self.run_until(t);
515 let o = self.observed(t);
516 let events = if self.aware { std::mem::take(&mut self.events) } else { vec![] };
517 let a = self.follower.step_with(&o, &events);
518 if self.aware {
519 self.events = events;
520 }
521 if let Some(a) = a {
522 self.pending.push(a);
523 }
524 }
525 fn deliver(&mut self, msg: &Transport, t: f64) {
526 self.run_until(t);
527 if let Some(a) = self.follower.on_message(msg, self.zero + t as u64) {
528 self.pending.push(a);
529 }
530 }
531 fn pos_at(&self, t: f64) -> Option<f64> {
533 let i = self.log.iter().rposition(|(bt, _, _)| *bt <= t)?;
534 let (bt, abs, playing) = self.log[i];
535 if !playing {
536 return None;
537 }
538 Some(abs as f64 + (t - bt) * f64::from(self.rate) * (1.0 + self.ppm * 1e-6) / 1e9)
539 }
540 }
541
542 fn run(ppm_a: f64, ppm_b: f64, seconds: f64) -> (Sim, Sim, f64) {
543 run_with(ppm_a, ppm_b, seconds, &[], false)
544 }
545
546 fn run_with(ppm_a: f64, ppm_b: f64, seconds: f64, events: &[u64], aware: bool) -> (Sim, Sim, f64) {
547 let master_zero = 5_000_000_000u64;
548 let mut a = Sim::new(ppm_a, 256, 123_456_789);
549 let mut b = Sim::new(ppm_b, 480, 987_654_321_000);
550 for s in [&mut a, &mut b] {
551 s.events = events.to_vec();
552 s.aware = aware;
553 }
554 let delay = |k: u64| 200_000.0 + (k * 7919 % 300_000) as f64; let start_true = 0.6e9;
556 let mut k = 0u64;
557 let mut t = 0.0f64;
558 let mut next_beacon = 0.0;
559 let mut sent_start = false;
560 let mut msgs: Vec<(f64, usize, Transport)> = vec![];
561 while t < seconds * 1e9 {
562 if t >= next_beacon {
563 let plan = sent_start.then_some((master_zero + start_true as u64, 0));
564 let m = Transport::Beacon { master_ns: master_zero + t as u64, plan };
565 for who in 0..2 {
566 k += 1;
567 msgs.push((t + delay(k), who, m.clone()));
568 }
569 next_beacon += 0.25e9;
570 }
571 if !sent_start && t >= 0.1e9 {
572 sent_start = true;
573 let m = Transport::Start { at_ns: master_zero + start_true as u64, frame: 0, master_ns: master_zero + t as u64 };
574 for who in 0..2 {
575 k += 1;
576 msgs.push((t + delay(k), who, m.clone()));
577 }
578 }
579 msgs.sort_by(|x, y| x.0.total_cmp(&y.0));
580 while msgs.first().is_some_and(|m| m.0 <= t) {
581 let (at, who, m) = msgs.remove(0);
582 if who == 0 { a.deliver(&m, at) } else { b.deliver(&m, at) }
583 }
584 a.poll(t);
586 b.poll(t + 1_300_000.0);
587 k += 1;
588 t += 4_000_000.0 + (k * 104_729 % 1_500_000) as f64;
589 }
590 (a, b, start_true)
591 }
592
593 #[test]
594 fn two_instances_start_together_and_stay_with_drift() {
595 let (a, b, start) = run(80.0, -80.0, 60.0);
596 let first = |s: &Sim| s.log.iter().find(|x| x.2).map(|x| (x.0, x.1)).unwrap();
598 let (ta, fa) = first(&a);
599 let (tb, fb) = first(&b);
600 let err_a = ta - start - fa as f64 * 1e9 / 48_000.0;
601 let err_b = tb - start - fb as f64 * 1e9 / 48_000.0;
602 let block_ns = 256.0 * 1e9 / 48_000.0;
603 assert!(err_a.abs() <= block_ns && err_b.abs() <= block_ns, "start errors {err_a} {err_b} ns");
604 let mut worst = 0.0f64;
606 let mut t = start + 1e9;
607 while t < 59e9 {
608 let d = a.pos_at(t).unwrap() - b.pos_at(t).unwrap();
609 worst = worst.max(d.abs());
610 t += 1e8;
611 }
612 eprintln!(
613 "start errors {err_a:.0} {err_b:.0} ns; worst {worst:.1} frames; corrections {} {}; offsets {:?} {:?}",
614 a.follower.corrections,
615 b.follower.corrections,
616 a.follower.clock().offset(),
617 b.follower.clock().offset()
618 );
619 assert!(worst <= 480.0, "worst difference {worst} frames");
620 assert!(a.follower.corrections >= 1, "{} {}", a.follower.corrections, b.follower.corrections);
623 assert!(a.follower.clock().known() && b.follower.clock().known());
624 }
625
626 #[test]
627 fn a_drift_correction_waits_for_a_jump_that_crosses_no_hit() {
628 let events: Vec<u64> = (0..320).map(|i| i * 300).collect();
630 let (blind_a, blind_b, _) = run_with(200.0, -200.0, 60.0, &events, false);
631 let (a, b, start) = run_with(200.0, -200.0, 60.0, &events, true);
632 eprintln!(
633 "blind: corrections {} {}, over a hit {} {}; aware: corrections {} {}, over a hit {} {}, deferred {} {}",
634 blind_a.follower.corrections,
635 blind_b.follower.corrections,
636 blind_a.bad,
637 blind_b.bad,
638 a.follower.corrections,
639 b.follower.corrections,
640 a.bad,
641 b.bad,
642 a.follower.deferrals,
643 b.follower.deferrals
644 );
645 assert!(blind_a.bad + blind_b.bad > 0, "without the hits known, some corrections land on one");
646 assert!(a.follower.corrections >= 1 && b.follower.corrections >= 1, "they still correct");
647 assert_eq!(a.bad + b.bad, 0, "no correction replays or skips a hit");
648 let mut worst = 0.0f64;
649 let mut t = start + 1e9;
650 while t < 59e9 {
651 worst = worst.max((a.pos_at(t).unwrap() - b.pos_at(t).unwrap()).abs());
652 t += 1e8;
653 }
654 assert!(worst <= 480.0 + 2.0 * 128.0, "they stay together while a correction waits: worst {worst} frames");
655 }
656
657 #[test]
658 fn any_in_wraps_at_the_loop_end() {
659 let ev = [0, 100, 5_000];
660 assert!(any_in(&ev, 50, 60, 6_000));
661 assert!(!any_in(&ev, 101, 4_000, 6_000));
662 assert!(any_in(&ev, 5_900, 200, 6_000), "across the loop start");
663 assert!(!any_in(&ev, 5_001, 998, 6_000));
664 assert!(!any_in(&[], 0, 6_000, 6_000));
665 assert!(!any_in(&ev, 100, 0, 6_000));
666 }
667
668 #[test]
669 fn unwrap_tells_a_wrap_from_a_locate() {
670 let mut u = Unwrap::default();
671 assert_eq!(u.abs(90_000, true, 96_000), 90_000);
672 assert_eq!(u.abs(1_000, true, 96_000), 97_000, "a wrap");
673 assert_eq!(u.abs(900, true, 96_000), 96_900, "a small locate back stays in the loop");
674 assert_eq!(u.abs(95_900, true, 96_000), 95_900, "a locate back across the loop start");
675 assert_eq!(u.abs(5, false, 96_000), 5);
676 let mut f = Follower::new(128);
677 f.on_message(&Transport::Start { at_ns: 1_000_000_000, frame: 0, master_ns: 1_000_000_000 }, 1_000_000_000);
678 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));
680 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));
681 }
682
683 #[test]
684 fn stop_and_late_join_by_beacon() {
685 let mut f = Follower::new(128);
686 let o = |now: u64, playing: bool| Observed {
687 now_ns: now,
688 callback_ns: now - 1_000_000,
689 output_frame: 0,
690 transport_frame: 0,
691 playing,
692 block_frames: 256,
693 sample_rate: 48_000,
694 loop_frames: 96_000,
695 };
696 f.on_message(&Transport::Beacon { master_ns: 10_000_000_000, plan: Some((9_000_000_000, 0)) }, 1_000_000_000);
698 match f.step(&o(1_000_000_000, false)) {
699 Some(Action::Start(fr)) => assert!((48_000..48_000 + 600).contains(&fr), "{fr}"),
700 other => panic!("{other:?}"),
701 }
702 f.on_message(&Transport::Stop { at_ns: 0, master_ns: 10_100_000_000 }, 1_100_000_000);
703 assert_eq!(f.step(&o(1_100_000_000, true)), Some(Action::Stop));
704 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)));
705 }
706}