weirdnet-songnotes 0.11.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
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
//! The session clock and transport (S4): the session host is the clock master, and every other
//! app follows it. Transport and tempo travel on the session's `/songnotes/transport` protocol,
//! not through audio routing.
//!
//! Session time is the host's own monotonic clock, in nanoseconds. A follower learns its offset
//! to it from request and answer exchanges ([`TransportReq::Sync`]), keeping the one with the
//! shortest round trip among the recent ones. The same exchange carries the [`Plan`], so a
//! follower that missed one catches up at the next.
//!
//! The plan is musical, not in frames: "beat `beat` plays at session time `at_ns`, at `bpm`",
//! as a list of [`Segment`]s. Each app turns beats into its own frames at its own rate. A start
//! is set a lead time ahead (so followers hear of it first). A tempo change lands on the first
//! bar boundary at least a lead time ahead, so every app and every stem stays on one grid.
//!
//! [`TransportHost`] and [`TransportFollower`] are state machines with no I/O. [`service`] serves
//! the host and calls it over weirdnet-service. A follower asks the host to start, stop, locate or
//! change tempo with [`TransportReq::Control`]; the host decides (by default the caller needs
//! [`TRANSPORT_CONTROL`](crate::perm::TRANSPORT_CONTROL)).
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, VecDeque};

/// The protocol name.
pub const TRANSPORT_PROTOCOL: &str = "/songnotes/transport";
/// The protocol version.
pub const TRANSPORT_VERSION: u32 = 1;
/// The default lead: a start or a tempo change is set at least this far ahead, nanoseconds.
pub const DEFAULT_LEAD_NS: u64 = 1_000_000_000;
/// How often a follower should sync, milliseconds.
pub const SYNC_MS: u64 = 250;
/// How many recent exchanges a follower keeps to pick the shortest round trip from.
pub const KEEP_SAMPLES: usize = 16;
/// A follower not heard from in this long is dropped from the host's list, nanoseconds.
pub const FOLLOWER_GONE_NS: u64 = 5_000_000_000;

/// From this session time on, the transport plays at `bpm`, and beat `beat` is at `at_ns`.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Segment {
    /// Session time, ns.
    pub at_ns: u64,
    /// The beat (quarter notes from the song's start) at `at_ns`.
    pub beat: f64,
    /// Tempo, beats a minute.
    pub bpm: f64,
}

impl Segment {
    fn ns_per_beat(&self) -> f64 {
        60e9 / self.bpm
    }
}

/// The transport as the host has it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Plan {
    /// Bumped on every change.
    pub rev: u64,
    /// Beats in a bar.
    pub beats_per_bar: u32,
    /// The latest tempo (the one in force, or the one that will be).
    pub bpm: f64,
    /// Playing (or about to).
    pub rolling: bool,
    /// While rolling: the segments, in time order. The first is the start.
    pub segments: Vec<Segment>,
    /// While stopped: where the transport stands, beats.
    pub stopped_beat: f64,
}

impl Plan {
    /// A stopped plan at beat 0.
    pub fn new(bpm: f64, beats_per_bar: u32) -> Plan {
        Plan { rev: 0, beats_per_bar: beats_per_bar.max(1), bpm, rolling: false, segments: Vec::new(), stopped_beat: 0.0 }
    }

    fn segment_at(&self, t: u64) -> Option<&Segment> {
        if !self.rolling {
            return None;
        }
        self.segments.iter().rev().find(|s| s.at_ns <= t).or(self.segments.first())
    }

    /// When the transport starts, session time (`None` when stopped).
    pub fn start_ns(&self) -> Option<u64> {
        self.rolling.then(|| self.segments.first().map(|s| s.at_ns)).flatten()
    }

    /// The beat at session time `t`, when rolling and started. Before the start it is `None`.
    pub fn beat_at(&self, t: u64) -> Option<f64> {
        let s = self.segment_at(t)?;
        if t < s.at_ns {
            return None;
        }
        Some(s.beat + (t - s.at_ns) as f64 / s.ns_per_beat())
    }

    /// The tempo at session time `t` (the latest one when stopped).
    pub fn bpm_at(&self, t: u64) -> f64 {
        self.segment_at(t).map_or(self.bpm, |s| s.bpm)
    }

    /// When beat `beat` plays, session time, while rolling. A beat before the start is placed at
    /// the start's tempo (a count-in), and may be before it.
    pub fn time_of(&self, beat: f64) -> Option<i128> {
        if !self.rolling {
            return None;
        }
        let s = self.segments.iter().rev().find(|s| s.beat <= beat).or(self.segments.first())?;
        Some(i128::from(s.at_ns) + ((beat - s.beat) * s.ns_per_beat()).round() as i128)
    }
}

/// What a follower says about itself on each sync, so the host knows who is ready.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Ready {
    /// The app (`drummachine`, `controller`, ...).
    pub app: String,
    /// An instance name, unique on its machine.
    pub instance: String,
    /// Its device output latency, frames (0 when unknown or none).
    pub output_latency_frames: u32,
    /// Its sample rate.
    pub sample_rate: u32,
}

/// A transport change a follower asks for.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Control {
    /// Start a lead time from now, from where it stands.
    Start,
    /// Stop now.
    Stop,
    /// Move to a beat (a lead time ahead while rolling).
    Locate {
        /// The beat.
        beat: f64,
    },
    /// Change tempo (on the next bar boundary a lead time ahead while rolling).
    Tempo {
        /// Beats a minute.
        bpm: f64,
    },
}

/// A request to the host.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TransportReq {
    /// A clock exchange: `t1` is the follower's clock when sent. Also asks for the plan when the
    /// host's revision is past `since`, and reports the follower.
    Sync {
        /// Local time at the follower when sent, ns.
        t1: u64,
        /// The plan revision the follower has (`u64::MAX` for none).
        since: u64,
        /// The follower, when it plays along.
        me: Option<Ready>,
    },
    /// Ask for a change.
    Control(Control),
}

/// The host's answer.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TransportResp {
    /// A clock exchange answered.
    Sync {
        /// As sent.
        t1: u64,
        /// The host's clock when answering, ns.
        t2: u64,
        /// The plan, when newer than the follower's.
        plan: Option<Plan>,
    },
    /// A change made; the new plan.
    Done(Plan),
}

/// A follower the host has heard from.
#[derive(Clone, Debug, PartialEq)]
pub struct Follower {
    /// What it said.
    pub ready: Ready,
    /// Who it is (the caller's id).
    pub peer: String,
    /// When it last synced, host time.
    pub seen_ns: u64,
}

/// The host's side: the plan and the followers.
#[derive(Clone, Debug)]
pub struct TransportHost {
    plan: Plan,
    lead_ns: u64,
    followers: BTreeMap<(String, String), Follower>,
}

impl TransportHost {
    /// A stopped transport at `bpm` with `beats_per_bar`.
    pub fn new(bpm: f64, beats_per_bar: u32) -> TransportHost {
        TransportHost { plan: Plan::new(bpm, beats_per_bar), lead_ns: DEFAULT_LEAD_NS, followers: BTreeMap::new() }
    }

    /// The plan.
    pub fn plan(&self) -> &Plan {
        &self.plan
    }

    /// Sets the lead (see the module docs).
    pub fn set_lead_ns(&mut self, ns: u64) {
        self.lead_ns = ns;
    }

    /// The followers heard from in the last [`FOLLOWER_GONE_NS`] before `now`.
    pub fn followers(&self, now: u64) -> Vec<Follower> {
        self.followers.values().filter(|f| now.saturating_sub(f.seen_ns) < FOLLOWER_GONE_NS).cloned().collect()
    }

    fn changed(&mut self) {
        self.plan.rev += 1;
    }

    /// Starts a lead time after `now`, from where it stands. Returns the start time. Starting
    /// while rolling changes nothing.
    pub fn start(&mut self, now: u64) -> u64 {
        if let Some(s) = self.plan.start_ns() {
            return s;
        }
        let at = now + self.lead_ns;
        self.plan.rolling = true;
        self.plan.segments = vec![Segment { at_ns: at, beat: self.plan.stopped_beat, bpm: self.plan.bpm }];
        self.changed();
        at
    }

    /// Stops at `now` and keeps the beat it reached.
    pub fn stop(&mut self, now: u64) {
        if !self.plan.rolling {
            return;
        }
        let first = self.plan.segments.first().map_or(0.0, |s| s.beat);
        self.plan.stopped_beat = self.plan.beat_at(now).unwrap_or(first);
        self.plan.rolling = false;
        self.plan.segments.clear();
        self.changed();
    }

    /// Moves to `beat`: while rolling, it plays from there a lead time after `now`.
    pub fn locate(&mut self, beat: f64, now: u64) {
        if self.plan.rolling {
            self.plan.segments = vec![Segment { at_ns: now + self.lead_ns, beat, bpm: self.plan.bpm }];
        } else {
            self.plan.stopped_beat = beat;
        }
        self.changed();
    }

    /// Changes tempo. While rolling and started, it takes effect on the first bar boundary at
    /// least a lead time after `now`, and that time is returned. Otherwise at once.
    pub fn set_tempo(&mut self, bpm: f64, now: u64) -> Option<u64> {
        if !(bpm.is_finite() && bpm > 0.0) {
            return None;
        }
        self.plan.bpm = bpm;
        let when = now + self.lead_ns;
        let landed = match self.plan.beat_at(now).and_then(|_| self.plan.beat_at(when)) {
            None => {
                // stopped, or not started yet: the start segment takes the new tempo
                for s in &mut self.plan.segments {
                    s.bpm = bpm;
                }
                self.plan.segments.truncate(1);
                None
            }
            Some(b) => {
                let bpb = f64::from(self.plan.beats_per_bar);
                let bar = (b / bpb - 1e-9).ceil() * bpb;
                let at = self.plan.time_of(bar).expect("rolling").max(0) as u64;
                // keep the segment in force now and the new one
                let current = *self.plan.segment_at(now).expect("rolling");
                self.plan.segments.retain(|s| s.at_ns >= current.at_ns && s.at_ns < at);
                self.plan.segments.push(Segment { at_ns: at, beat: bar, bpm });
                Some(at)
            }
        };
        self.changed();
        landed
    }

    /// Applies a follower's control request (after the caller was allowed).
    pub fn control(&mut self, c: &Control, now: u64) -> Plan {
        match c {
            Control::Start => {
                self.start(now);
            }
            Control::Stop => self.stop(now),
            Control::Locate { beat } => self.locate(*beat, now),
            Control::Tempo { bpm } => {
                self.set_tempo(*bpm, now);
            }
        }
        self.plan.clone()
    }

    /// Answers `req` from `peer` at host time `now`. `may_control` says whether this peer may
    /// change the transport.
    pub fn handle(&mut self, peer: &str, req: TransportReq, now: u64, may_control: bool) -> Result<TransportResp, String> {
        match req {
            TransportReq::Sync { t1, since, me } => {
                if let Some(r) = me {
                    self.followers.insert((peer.to_string(), r.instance.clone()), Follower { ready: r, peer: peer.to_string(), seen_ns: now });
                }
                self.followers.retain(|_, f| now.saturating_sub(f.seen_ns) < FOLLOWER_GONE_NS);
                let plan = (since == u64::MAX || self.plan.rev > since).then(|| self.plan.clone());
                Ok(TransportResp::Sync { t1, t2: now, plan })
            }
            TransportReq::Control(c) => {
                if !may_control {
                    return Err("transport.control".into());
                }
                Ok(TransportResp::Done(self.control(&c, now)))
            }
        }
    }
}

/// One clock exchange.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ClockSample {
    /// Host time minus local time, ns.
    pub offset_ns: i64,
    /// The round trip, ns.
    pub rtt_ns: u64,
    /// Local time when it came back.
    pub local_ns: u64,
}

/// The follower's side: the clock offset to the host and the plan. Every time is local (the
/// follower's own monotonic clock, the one its engine uses) unless it says session.
#[derive(Clone, Debug, Default)]
pub struct TransportFollower {
    samples: VecDeque<ClockSample>,
    plan: Option<Plan>,
    me: Option<Ready>,
}

impl TransportFollower {
    /// A follower that knows nothing yet.
    pub fn new() -> TransportFollower {
        TransportFollower::default()
    }

    /// Says who this follower is on each sync.
    pub fn set_ready(&mut self, me: Ready) {
        self.me = Some(me);
    }

    /// The request to send now (`local_now` is this follower's clock).
    pub fn sync_request(&self, local_now: u64) -> TransportReq {
        TransportReq::Sync { t1: local_now, since: self.plan.as_ref().map_or(u64::MAX, |p| p.rev), me: self.me.clone() }
    }

    /// Takes the answer to a sync that came back at `local_now`. Returns whether the plan changed.
    pub fn on_answer(&mut self, resp: TransportResp, local_now: u64) -> bool {
        match resp {
            TransportResp::Sync { t1, t2, plan } => {
                if local_now >= t1 {
                    let rtt = local_now - t1;
                    let mid = t1 as i128 + i128::from(rtt / 2);
                    self.samples.push_back(ClockSample { offset_ns: (i128::from(t2) - mid) as i64, rtt_ns: rtt, local_ns: local_now });
                    while self.samples.len() > KEEP_SAMPLES {
                        self.samples.pop_front();
                    }
                }
                self.take(plan)
            }
            TransportResp::Done(p) => self.take(Some(p)),
        }
    }

    fn take(&mut self, plan: Option<Plan>) -> bool {
        match plan {
            Some(p) if self.plan.as_ref().is_none_or(|q| q.rev != p.rev) => {
                self.plan = Some(p);
                true
            }
            _ => false,
        }
    }

    /// The exchange in use: the shortest round trip among the recent ones.
    pub fn clock(&self) -> Option<ClockSample> {
        self.samples.iter().min_by_key(|s| s.rtt_ns).copied()
    }

    /// Host time minus local time, ns.
    pub fn offset_ns(&self) -> Option<i64> {
        self.clock().map(|s| s.offset_ns)
    }

    /// Session time at local time `local`.
    pub fn session_time(&self, local: u64) -> Option<i128> {
        Some(i128::from(local) + i128::from(self.offset_ns()?))
    }

    /// Local time at session time `session`.
    pub fn local_time(&self, session: i128) -> Option<i128> {
        Some(session - i128::from(self.offset_ns()?))
    }

    /// The plan, once heard.
    pub fn plan(&self) -> Option<&Plan> {
        self.plan.as_ref()
    }

    /// The beat at local time `local` (`None` while stopped, before the start or before the
    /// clock is known).
    pub fn beat_at(&self, local: u64) -> Option<f64> {
        let t = self.session_time(local)?;
        self.plan.as_ref()?.beat_at(u64::try_from(t).ok()?)
    }

    /// When beat `beat` plays, local time.
    pub fn local_time_of(&self, beat: f64) -> Option<i128> {
        self.local_time(self.plan.as_ref()?.time_of(beat)?)
    }
}

/// `/songnotes/transport` as a protocol id.
pub fn protocol() -> weirdnet_service::ProtocolId {
    weirdnet_service::ProtocolId::new(TRANSPORT_PROTOCOL, TRANSPORT_VERSION).expect("a valid protocol id")
}

/// A monotonic clock in nanoseconds, from the first call in this process.
pub fn monotonic_ns() -> u64 {
    static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
    START.get_or_init(std::time::Instant::now).elapsed().as_nanos() as u64
}

/// Serving [`TransportHost`] on weirdnet-service, and calling it.
pub mod service {
    use super::*;
    use std::sync::{Arc, Mutex};
    use weirdnet_service::{Access, Admitted, Authorize, Caller, Service, ServiceError};

    /// Decides whether a caller (its peer id) may change the transport.
    pub type MayControl = Arc<dyn Fn(&str) -> bool + Send + Sync>;
    /// The host's clock, ns.
    pub type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;

    /// The service.
    pub struct TransportService {
        /// The host.
        pub host: Arc<Mutex<TransportHost>>,
        /// The host's clock (session time).
        pub clock: Clock,
        /// Who may change the transport.
        pub may_control: MayControl,
    }

    impl Service for TransportService {
        type Request = TransportReq;
        type Response = TransportResp;

        fn access(&self, r: &TransportReq) -> Access {
            Access::new(match r {
                TransportReq::Sync { .. } => "transport.sync",
                TransportReq::Control(_) => "transport.control",
            })
        }

        async fn call(&self, who: Admitted, r: TransportReq) -> Result<TransportResp, ServiceError> {
            let peer = who.user.clone().unwrap_or_default();
            let may = matches!(r, TransportReq::Control(_)) && (self.may_control)(&peer);
            let now = (self.clock)();
            let mut host = self.host.lock().unwrap_or_else(|e| e.into_inner());
            host.handle(&peer, r, now, may).map_err(|c| ServiceError::App { code: c.clone(), message: c })
        }
    }

    /// Admits any peer; the service and `may_control` decide the rest.
    pub fn authorizer() -> impl Authorize {
        move |caller: &Caller, _: &Access| Ok(Admitted::new(caller.peer.clone()).with_user(caller.peer.clone()))
    }

    /// One sync with the host `to`: sends the follower's request and takes the answer. `clock` is
    /// the follower's clock. Returns whether the plan changed.
    pub async fn sync(
        client: &weirdnet_service::Client,
        to: &str,
        f: &Mutex<TransportFollower>,
        clock: &(dyn Fn() -> u64 + Sync),
    ) -> Result<bool, ServiceError> {
        let s = client.session::<TransportReq, TransportResp>(to, &protocol()).await?;
        let req = f.lock().unwrap_or_else(|e| e.into_inner()).sync_request(clock());
        let resp = s.call(&req).await?;
        let back = clock();
        Ok(f.lock().unwrap_or_else(|e| e.into_inner()).on_answer(resp, back))
    }

    /// Asks the host `to` for a change; the answer updates the follower.
    pub async fn control(client: &weirdnet_service::Client, to: &str, f: &Mutex<TransportFollower>, c: Control) -> Result<Plan, ServiceError> {
        let s = client.session::<TransportReq, TransportResp>(to, &protocol()).await?;
        match s.call(&TransportReq::Control(c)).await? {
            TransportResp::Done(p) => {
                f.lock().unwrap_or_else(|e| e.into_inner()).on_answer(TransportResp::Done(p.clone()), 0);
                Ok(p)
            }
            other => Err(ServiceError::App { code: "unexpected".into(), message: format!("{other:?}") }),
        }
    }
}