weirdnet-streaming 0.1.0

Streaming for Weirdnet: live and recorded audio streams over weirdnet-net with per-listener queues, clocks and remote routing, a follow-transport protocol (start, stop, locate, tempo, beacon), and loop-positioned streams with alignment for record-along.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
//! Follow-transport: a headless master starts, stops, moves and paces several instances
//! so they play on one session time.
//!
//! Every process keeps its own local monotonic clock (the engine's `now_ns`). The master's clock
//! is the session clock; each instance learns its offset to it from the master's messages (the
//! largest `master_ns - local_ns` seen, which is the true offset less the smallest one-way
//! delay). A [`Transport::Start`] says "transport frame `frame` plays at session time `at_ns`";
//! from then on the instance knows where its transport should be at any moment.
//!
//! Engine commands take effect at the next audio block, so [`Follower::step`] works out which
//! block that is from the engine's last [`Observed`] timing and asks for the transport frame
//! that block should start on: the start lands on the right frame (the first block at or after the start time begins
//! on the frame due then), and when the device clock drifts against the monotonic
//! clock the follower locates again once the error passes its tolerance.
use serde::{Deserialize, Serialize};

/// A follow-transport message, on the transport service (an app names the service, for example `/<app>/transport`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Transport {
    /// Get ready to play `project` at `bpm`; answered with [`Transport::Ready`].
    Prepare {
        /// The project's name, for the log.
        project: String,
        /// The tempo the master runs at.
        bpm: f32,
        /// The master's session time when sent.
        master_ns: u64,
    },
    /// An instance is ready.
    Ready {
        /// Its instance id.
        instance: String,
        /// Its device output latency, frames (0 when unknown or none).
        output_latency: u32,
        /// Its sample rate.
        sample_rate: u32,
        /// Its loop length, frames.
        loop_frames: u64,
    },
    /// Transport frame `frame` plays at session time `at_ns`.
    Start {
        /// Session time.
        at_ns: u64,
        /// Transport frame.
        frame: u64,
        /// The master's session time when sent.
        master_ns: u64,
    },
    /// Stop at session time `at_ns` (now if already past).
    Stop {
        /// Session time.
        at_ns: u64,
        /// The master's session time when sent.
        master_ns: u64,
    },
    /// Move: transport frame `frame` plays at `at_ns` (while playing), or the cursor goes there.
    Locate {
        /// Session time.
        at_ns: u64,
        /// Transport frame.
        frame: u64,
        /// The master's session time when sent.
        master_ns: u64,
    },
    /// Change tempo.
    Tempo {
        /// Beats per minute.
        bpm: f32,
        /// The master's session time when sent.
        master_ns: u64,
    },
    /// Keeps the clocks together and repeats the plan, so an instance that missed a message
    /// catches up.
    Beacon {
        /// The master's session time when sent.
        master_ns: u64,
        /// The plan: playing from `frame` at `at_ns`, or stopped.
        plan: Option<(u64, u64)>,
    },
}

impl Transport {
    /// The master's send time carried by every message but `Ready`.
    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,
        }
    }
}

/// The offset from a local monotonic clock to the session clock.
#[derive(Clone, Copy, Debug, Default)]
pub struct SessionClock {
    offset: Option<i128>,
    seen: u64,
}

impl SessionClock {
    /// Notes a master message sent at session time `master_ns` and received at local `local_ns`.
    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;
    }

    /// Whether any message has been seen.
    pub fn known(&self) -> bool {
        self.offset.is_some()
    }

    /// Local time to session time.
    pub fn to_session(&self, local_ns: u64) -> i128 {
        i128::from(local_ns) + self.offset.unwrap_or(0)
    }

    /// Session time to local time.
    pub fn to_local(&self, session_ns: i128) -> i128 {
        session_ns - self.offset.unwrap_or(0)
    }

    /// The offset, ns.
    pub fn offset(&self) -> Option<i128> {
        self.offset
    }
}

/// What the engine said about its last block, plus the local time now.
#[derive(Clone, Copy, Debug)]
pub struct Observed {
    /// Local monotonic time now.
    pub now_ns: u64,
    /// When the last block began, local.
    pub callback_ns: u64,
    /// Its first output frame.
    pub output_frame: u64,
    /// The transport frame (in the loop) it began on.
    pub transport_frame: u64,
    /// Whether the transport ran in it.
    pub playing: bool,
    /// Its length, frames.
    pub block_frames: u32,
    /// The sample rate.
    pub sample_rate: u32,
    /// The loop length, frames.
    pub loop_frames: u64,
}

/// What the instance should tell its engine.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Action {
    /// Locate to this frame and play.
    Start(u64),
    /// Stop where it is.
    Stop,
    /// Locate to this frame (playing on).
    Locate(u64),
    /// Change tempo.
    Tempo(f32),
}

/// Follows a master's transport.
#[derive(Clone, Debug)]
pub struct Follower {
    clock: SessionClock,
    plan: Option<(i128, u64)>,
    stop_at: Option<i128>,
    /// Allowed error before locating again, frames.
    pub tolerance: u64,
    waiting_since: Option<u64>,
    /// Locates done to correct drift or a late start.
    pub corrections: u64,
    /// The last measured error (actual minus expected), frames.
    pub last_error: i64,
    /// The largest error measured after the first correct block, frames.
    pub worst_error: u64,
    settled: bool,
    /// Since when (local ns) a due correction has waited for a stretch of the loop with no hit in it.
    deferred_since: Option<u64>,
    /// Corrections put off because the jump would have replayed or skipped a hit.
    pub deferrals: u64,
}

/// How long a due correction may wait for a jump with no hit in it, ns.
pub const MAX_DEFER_NS: u64 = 500_000_000;
/// Past this many times the tolerance, a correction does not wait.
pub const MAX_DEFER_ERROR: u64 = 4;

/// Whether a sorted list of loop frames has one in `len` frames from `start`, wrapping at `loop_frames`.
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 {
    /// A follower that relocates when off by more than `tolerance` frames.
    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,
        }
    }

    /// The session clock.
    pub fn clock(&self) -> &SessionClock {
        &self.clock
    }

    /// The plan: (session time, frame) when playing.
    pub fn plan(&self) -> Option<(i128, u64)> {
        self.plan
    }

    /// Takes a message received at local time `local_ns`; returns an immediate action (a tempo
    /// change) if there is one. Start, stop and locate act through [`Follower::step`].
    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,
        }
    }

    /// Where the transport should be (in the loop) at local time `local_ns`, if playing.
    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)
    }

    /// The absolute transport position (loops counted from the plan's frame) of a block that
    /// began on loop frame `transport_frame` at local time `local_ns`, while following.
    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)
    }

    /// Decides what to tell the engine now, from its last block's timing.
    pub fn step(&mut self, o: &Observed) -> Option<Action> {
        self.step_with(o, &[])
    }

    /// [`Follower::step`] knowing the loop frames where hits start (`events`, sorted). A drift correction is a jump of the
    /// transport: back, it plays the frames it jumps over again; forward, it skips them. A hit in there would sound twice or not
    /// at all. So a due correction waits (up to [`MAX_DEFER_NS`], and only while the error is under [`MAX_DEFER_ERROR`] times the
    /// tolerance) for a block where the jump crosses no hit. Voices already sounding are not touched by a jump either way.
    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);
        // The block a command sent now lands in.
        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)?;
        // A command is in flight until a block after it has run.
        if let Some(w) = self.waiting_since {
            if o.callback_ns <= w {
                return None;
            }
            self.waiting_since = None;
        }
        if !o.playing {
            // Not yet: the next block begins before the start. (Starting a block late and
            // locating on lands exactly; starting early would play ahead of the session.)
            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);
            // ahead: back to target, replaying [target, here); behind: on to target, skipping [here, target)
            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
    }
}

/// Counts loops in the engine's loop-wrapped transport frame when not following: a jump back
/// by more than half a loop is a wrap; a small one is a locate.
#[derive(Clone, Copy, Debug, Default)]
pub struct Unwrap {
    last: u64,
    base: u64,
}

impl Unwrap {
    /// The absolute position for this block's `transport_frame`.
    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::*;

    /// A manual sink driven in simulated time: blocks every `block` device frames, a device
    /// clock off by `ppm`, commands taking effect at the next block, and a local clock with its
    /// own zero.
    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,
        /// (true ns at block start, absolute transport position) of every playing block.
        log: Vec<(f64, u64, bool)>,
        abs: u64,
        follower: Follower,
        /// Loop frames where hits start; the follower is told them when `aware`.
        events: Vec<u64>,
        aware: bool,
        /// Corrections whose jump replayed or skipped a hit.
        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);
            }
        }
        /// Absolute transport position at true time t (interpolated from the block log).
        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; // 0.2–0.5 ms
        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) }
            }
            // The window polls every 4 ms, with jitter.
            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);
        // Both started within one block of the session start time.
        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");
        // Every 100 ms after the first second, positions agree to within a block.
        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");
        // 80 ppm over a minute is ~230 frames, past the 128-frame tolerance of the 256-frame
        // instance: it had to correct.
        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() {
        // a dense loop: a hit every 300 frames (320 in the two-second loop), and a lot of drift
        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);
        // 2.5 loops after the start, the engine shows half a loop in: 2 loops are counted.
        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,
        };
        // Joined late: a beacon with a plan that started a second ago starts it mid-loop.
        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)));
    }
}