Skip to main content

weirdnet_streaming/
transport.rs

1//! Follow-transport: a headless master starts, stops, moves and paces several instances
2//! so they play on one session time.
3//!
4//! Every process keeps its own local monotonic clock (the engine's `now_ns`). The master's clock
5//! is the session clock; each instance learns its offset to it from the master's messages (the
6//! largest `master_ns - local_ns` seen, which is the true offset less the smallest one-way
7//! delay). A [`Transport::Start`] says "transport frame `frame` plays at session time `at_ns`";
8//! from then on the instance knows where its transport should be at any moment.
9//!
10//! Engine commands take effect at the next audio block, so [`Follower::step`] works out which
11//! block that is from the engine's last [`Observed`] timing and asks for the transport frame
12//! that block should start on: the start lands on the right frame (the first block at or after the start time begins
13//! on the frame due then), and when the device clock drifts against the monotonic
14//! clock the follower locates again once the error passes its tolerance.
15use serde::{Deserialize, Serialize};
16
17/// A follow-transport message, on the transport service (an app names the service, for example `/<app>/transport`).
18#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
19pub enum Transport {
20    /// Get ready to play `project` at `bpm`; answered with [`Transport::Ready`].
21    Prepare {
22        /// The project's name, for the log.
23        project: String,
24        /// The tempo the master runs at.
25        bpm: f32,
26        /// The master's session time when sent.
27        master_ns: u64,
28    },
29    /// An instance is ready.
30    Ready {
31        /// Its instance id.
32        instance: String,
33        /// Its device output latency, frames (0 when unknown or none).
34        output_latency: u32,
35        /// Its sample rate.
36        sample_rate: u32,
37        /// Its loop length, frames.
38        loop_frames: u64,
39    },
40    /// Transport frame `frame` plays at session time `at_ns`.
41    Start {
42        /// Session time.
43        at_ns: u64,
44        /// Transport frame.
45        frame: u64,
46        /// The master's session time when sent.
47        master_ns: u64,
48    },
49    /// Stop at session time `at_ns` (now if already past).
50    Stop {
51        /// Session time.
52        at_ns: u64,
53        /// The master's session time when sent.
54        master_ns: u64,
55    },
56    /// Move: transport frame `frame` plays at `at_ns` (while playing), or the cursor goes there.
57    Locate {
58        /// Session time.
59        at_ns: u64,
60        /// Transport frame.
61        frame: u64,
62        /// The master's session time when sent.
63        master_ns: u64,
64    },
65    /// Change tempo.
66    Tempo {
67        /// Beats per minute.
68        bpm: f32,
69        /// The master's session time when sent.
70        master_ns: u64,
71    },
72    /// Keeps the clocks together and repeats the plan, so an instance that missed a message
73    /// catches up.
74    Beacon {
75        /// The master's session time when sent.
76        master_ns: u64,
77        /// The plan: playing from `frame` at `at_ns`, or stopped.
78        plan: Option<(u64, u64)>,
79    },
80}
81
82impl Transport {
83    /// The master's send time carried by every message but `Ready`.
84    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/// The offset from a local monotonic clock to the session clock.
98#[derive(Clone, Copy, Debug, Default)]
99pub struct SessionClock {
100    offset: Option<i128>,
101    seen: u64,
102}
103
104impl SessionClock {
105    /// Notes a master message sent at session time `master_ns` and received at local `local_ns`.
106    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    /// Whether any message has been seen.
113    pub fn known(&self) -> bool {
114        self.offset.is_some()
115    }
116
117    /// Local time to session time.
118    pub fn to_session(&self, local_ns: u64) -> i128 {
119        i128::from(local_ns) + self.offset.unwrap_or(0)
120    }
121
122    /// Session time to local time.
123    pub fn to_local(&self, session_ns: i128) -> i128 {
124        session_ns - self.offset.unwrap_or(0)
125    }
126
127    /// The offset, ns.
128    pub fn offset(&self) -> Option<i128> {
129        self.offset
130    }
131}
132
133/// What the engine said about its last block, plus the local time now.
134#[derive(Clone, Copy, Debug)]
135pub struct Observed {
136    /// Local monotonic time now.
137    pub now_ns: u64,
138    /// When the last block began, local.
139    pub callback_ns: u64,
140    /// Its first output frame.
141    pub output_frame: u64,
142    /// The transport frame (in the loop) it began on.
143    pub transport_frame: u64,
144    /// Whether the transport ran in it.
145    pub playing: bool,
146    /// Its length, frames.
147    pub block_frames: u32,
148    /// The sample rate.
149    pub sample_rate: u32,
150    /// The loop length, frames.
151    pub loop_frames: u64,
152}
153
154/// What the instance should tell its engine.
155#[derive(Clone, Copy, Debug, PartialEq)]
156pub enum Action {
157    /// Locate to this frame and play.
158    Start(u64),
159    /// Stop where it is.
160    Stop,
161    /// Locate to this frame (playing on).
162    Locate(u64),
163    /// Change tempo.
164    Tempo(f32),
165}
166
167/// Follows a master's transport.
168#[derive(Clone, Debug)]
169pub struct Follower {
170    clock: SessionClock,
171    plan: Option<(i128, u64)>,
172    stop_at: Option<i128>,
173    /// Allowed error before locating again, frames.
174    pub tolerance: u64,
175    waiting_since: Option<u64>,
176    /// Locates done to correct drift or a late start.
177    pub corrections: u64,
178    /// The last measured error (actual minus expected), frames.
179    pub last_error: i64,
180    /// The largest error measured after the first correct block, frames.
181    pub worst_error: u64,
182    settled: bool,
183    /// Since when (local ns) a due correction has waited for a stretch of the loop with no hit in it.
184    deferred_since: Option<u64>,
185    /// Corrections put off because the jump would have replayed or skipped a hit.
186    pub deferrals: u64,
187}
188
189/// How long a due correction may wait for a jump with no hit in it, ns.
190pub const MAX_DEFER_NS: u64 = 500_000_000;
191/// Past this many times the tolerance, a correction does not wait.
192pub const MAX_DEFER_ERROR: u64 = 4;
193
194/// Whether a sorted list of loop frames has one in `len` frames from `start`, wrapping at `loop_frames`.
195fn 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    /// A follower that relocates when off by more than `tolerance` frames.
229    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    /// The session clock.
246    pub fn clock(&self) -> &SessionClock {
247        &self.clock
248    }
249
250    /// The plan: (session time, frame) when playing.
251    pub fn plan(&self) -> Option<(i128, u64)> {
252        self.plan
253    }
254
255    /// Takes a message received at local time `local_ns`; returns an immediate action (a tempo
256    /// change) if there is one. Start, stop and locate act through [`Follower::step`].
257    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    /// Where the transport should be (in the loop) at local time `local_ns`, if playing.
284    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    /// The absolute transport position (loops counted from the plan's frame) of a block that
291    /// began on loop frame `transport_frame` at local time `local_ns`, while following.
292    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    /// Decides what to tell the engine now, from its last block's timing.
304    pub fn step(&mut self, o: &Observed) -> Option<Action> {
305        self.step_with(o, &[])
306    }
307
308    /// [`Follower::step`] knowing the loop frames where hits start (`events`, sorted). A drift correction is a jump of the
309    /// transport: back, it plays the frames it jumps over again; forward, it skips them. A hit in there would sound twice or not
310    /// at all. So a due correction waits (up to [`MAX_DEFER_NS`], and only while the error is under [`MAX_DEFER_ERROR`] times the
311    /// tolerance) for a block where the jump crosses no hit. Voices already sounding are not touched by a jump either way.
312    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        // The block a command sent now lands in.
317        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        // A command is in flight until a block after it has run.
331        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            // Not yet: the next block begins before the start. (Starting a block late and
339            // locating on lands exactly; starting early would play ahead of the session.)
340            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            // ahead: back to target, replaying [target, here); behind: on to target, skipping [here, target)
360            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/// Counts loops in the engine's loop-wrapped transport frame when not following: a jump back
383/// by more than half a loop is a wrap; a small one is a locate.
384#[derive(Clone, Copy, Debug, Default)]
385pub struct Unwrap {
386    last: u64,
387    base: u64,
388}
389
390impl Unwrap {
391    /// The absolute position for this block's `transport_frame`.
392    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    /// A manual sink driven in simulated time: blocks every `block` device frames, a device
413    /// clock off by `ppm`, commands taking effect at the next block, and a local clock with its
414    /// own zero.
415    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        /// (true ns at block start, absolute transport position) of every playing block.
430        log: Vec<(f64, u64, bool)>,
431        abs: u64,
432        follower: Follower,
433        /// Loop frames where hits start; the follower is told them when `aware`.
434        events: Vec<u64>,
435        aware: bool,
436        /// Corrections whose jump replayed or skipped a hit.
437        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        /// Absolute transport position at true time t (interpolated from the block log).
532        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; // 0.2–0.5 ms
555        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            // The window polls every 4 ms, with jitter.
585            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        // Both started within one block of the session start time.
597        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        // Every 100 ms after the first second, positions agree to within a block.
605        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        // 80 ppm over a minute is ~230 frames, past the 128-frame tolerance of the 256-frame
621        // instance: it had to correct.
622        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        // a dense loop: a hit every 300 frames (320 in the two-second loop), and a lot of drift
629        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        // 2.5 loops after the start, the engine shows half a loop in: 2 loops are counted.
679        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        // Joined late: a beacon with a plan that started a second ago starts it mid-loop.
697        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}