Skip to main content

weirdnet_streaming/
along.rs

1//! Record-along on the network: your dry stream (your own voices, each frame stamped with its loop position), your last loop as a
2//! stamped recorded take, and playing a collaborator's take or live dry stream aligned to your loop.
3
4use crate::align::{Mode, bars_for};
5use crate::bus::{Ends, Input};
6use crate::lock;
7use crate::stage::{Grid, StageKind, StageStreamMeta, frame_meta, marker_of, take_stream};
8use crate::{Frame, Hub, Publisher, StreamEvent, StreamId};
9use serde::{Deserialize, Serialize};
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, Mutex};
12use std::time::Duration;
13
14/// Your live dry stream.
15pub const DRY: &str = "dry";
16/// Your last loop, recorded and stamped.
17pub const DRY_TAKE: &str = "dry-take";
18/// What your device plays (the device-output tap), stamped like the dry stream.
19pub const OUT: &str = "out";
20
21/// Which positioned tap to stream.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Tap {
24    /// Your own voices.
25    Dry,
26    /// What goes to the device.
27    Out,
28}
29
30/// The grid on your side now.
31pub fn grid(ends: &Ends) -> Option<Grid> {
32    let s = &ends.shared;
33    let (lf, lt, bf) = (s.loop_frames.load(Ordering::Relaxed), s.loop_ticks.load(Ordering::Relaxed), s.bar_frames.load(Ordering::Relaxed));
34    (lf > 0 && lt > 0 && bf > 0).then(|| Grid { loop_frames: lf, loop_ticks: lt, loop_bars: (lf / bf).max(1) as u16 })
35}
36
37/// Your transport position now, in absolute frames, while playing (estimated from the audio clock).
38pub fn local_now(ends: &Ends) -> Option<u64> {
39    let s = &ends.shared;
40    if !s.playing.load(Ordering::Relaxed) {
41        return None;
42    }
43    let rendered = s.rendered.load(Ordering::Relaxed) / u64::from(ends.channels.max(1));
44    Some((s.xport_transport.load(Ordering::Relaxed) as i64 + rendered as i64 - s.xport_output.load(Ordering::Relaxed) as i64).max(0) as u64)
45}
46
47/// Whole loops to add to a sender's absolute position so that, `delay` frames (the bar delay) later, it still lies at least
48/// `margin` frames ahead of `now`. The two transports run the same grid but started at different times, so this keeps the
49/// position on the loop and picks the next time round that can still be played.
50pub fn loop_offset(sender_abs: u64, now: u64, loop_frames: u64, delay: u64, margin: u64) -> i64 {
51    let need = now as i64 + margin as i64 - delay as i64 - sender_abs as i64;
52    need.div_euclid(loop_frames as i64) + i64::from(need.rem_euclid(loop_frames as i64) != 0)
53}
54
55/// How far ahead of now a live source is first placed: a jitter buffer of 2048 frames (about 43 ms at 48 kHz).
56pub const MARGIN: u64 = 2048;
57
58/// The last full loop of your dry audio: interleaved samples and the absolute position of the first.
59#[derive(Default)]
60pub struct LastLoop {
61    samples: Vec<f32>,
62    start: u64,
63}
64
65impl LastLoop {
66    fn push(&mut self, at: u64, block: &[f32], ch: usize, loop_frames: u64) {
67        if self.samples.is_empty() || at != self.start + (self.samples.len() / ch) as u64 {
68            self.samples.clear();
69            self.start = at;
70        }
71        self.samples.extend_from_slice(block);
72        let max = loop_frames as usize * ch;
73        if self.samples.len() > max {
74            let cut = (self.samples.len() - max) / ch * ch;
75            self.samples.drain(..cut);
76            self.start += (cut / ch) as u64;
77        }
78    }
79    /// A full loop and where it starts, if one has been played.
80    pub fn full(&self, loop_frames: u64, ch: usize) -> Option<(&[f32], u64)> {
81        (self.samples.len() == loop_frames as usize * ch).then_some((&self.samples[..], self.start))
82    }
83}
84
85/// Moves the dry tap into stamped frames on `publisher`, keeping the last loop in `last`. Runs until `stop`.
86pub async fn pump_dry(ends: Arc<Mutex<Ends>>, publisher: Publisher, last: Arc<Mutex<LastLoop>>, stop: Arc<AtomicBool>) {
87    pump_tap(ends, Tap::Dry, publisher, Some(last), stop).await
88}
89
90/// Moves a positioned tap into stamped frames on `publisher` (keeping the last loop in `last`,
91/// if given). Runs until `stop`.
92pub async fn pump_tap(ends: Arc<Mutex<Ends>>, tap: Tap, publisher: Publisher, last: Option<Arc<Mutex<LastLoop>>>, stop: Arc<AtomicBool>) {
93    let switch = |e: &Ends, on: bool| match tap {
94        Tap::Dry => e.shared.dry_on.store(on, Ordering::Relaxed),
95        Tap::Out => e.shared.out_on.store(on, Ordering::Relaxed),
96    };
97    switch(&lock(&ends), true);
98    let ch = lock(&ends).channels as usize;
99    let (mut seq, mut pts) = (0u64, 0u64);
100    while !stop.load(Ordering::Relaxed) {
101        tokio::time::sleep(Duration::from_millis(3)).await;
102        let mut guard = lock(&ends);
103        let e = &mut *guard;
104        loop {
105            let (at_ring, ring) = match tap {
106                Tap::Dry => (&mut e.dry_at, &mut e.dry),
107                Tap::Out => (&mut e.out_at, &mut e.out),
108            };
109            let Ok((at, n)) = at_ring.pop() else { break };
110            // the device output is stamped where it is heard
111            let at = if tap == Tap::Out { at + e.shared.out_latency.load(Ordering::Relaxed) } else { at };
112            let len = n as usize * ch;
113            let mut block = Vec::with_capacity(len);
114            let avail = len.min(ring.slots());
115            if let Ok(c) = ring.read_chunk(avail) {
116                let (a, b) = c.as_slices();
117                block.extend_from_slice(a);
118                block.extend_from_slice(b);
119                c.commit_all();
120            }
121            let Some(g) = grid(e) else { continue };
122            if let Some(last) = &last {
123                lock(last).push(at, &block, ch, g.loop_frames);
124            }
125            let mut f = Frame::pcm_f32(seq, pts, ch as u16, &block);
126            f.meta = Some(frame_meta(Some(g.marker(at))));
127            pts += u64::from(n);
128            seq += 1;
129            let _ = publisher.send(f);
130        }
131        if tap == Tap::Dry {
132            while e.spent.pop().is_ok() {}
133        }
134    }
135    switch(&lock(&ends), false);
136    publisher.finish();
137}
138
139/// Publish your last loop as the recorded stream [`DRY_TAKE`], stamped with where it starts on the loop. Returns its frames.
140pub fn publish_take(hub: &Hub, ends: &Ends, last: &LastLoop, mut meta: StageStreamMeta) -> Result<u64, String> {
141    let g = grid(ends).ok_or("no loop yet")?;
142    let ch = ends.channels as usize;
143    let (samples, start) = last
144        .full(g.loop_frames, ch)
145        .ok_or_else(|| format!("play a whole loop with the dry stream on first ({} of {} frames so far)", last.samples.len() / ch, g.loop_frames))?;
146    meta.kind = StageKind::Dry;
147    let src = take_stream(DRY_TAKE, samples, ends.sample_rate, ends.channels, g, meta, start % g.loop_frames);
148    hub.remove(&StreamId::new(DRY_TAKE));
149    hub.add_recorded(src);
150    Ok(g.loop_frames)
151}
152
153/// What a play-along source measured.
154#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
155pub struct AlongStats {
156    /// Frames received.
157    pub frames: u64,
158    /// Mean one-way delay, milliseconds.
159    pub delay_ms_mean: f64,
160    /// Interarrival jitter, milliseconds.
161    pub jitter_ms: f64,
162    /// Bars of delay the source plays with.
163    pub bars: u32,
164    /// Frames that arrived too late to play in place.
165    pub late: u64,
166    /// Frames in the received take.
167    pub take_frames: u64,
168}
169
170/// Play a collaborator's recorded take (Mode::Recorded) or live dry stream (other modes) into `slot`.
171pub async fn play_along(
172    mut sub: crate::net::Subscriber,
173    slot: usize,
174    mode: Mode,
175    ends: Arc<Mutex<Ends>>,
176    stats: Arc<Mutex<AlongStats>>,
177    stop: Arc<AtomicBool>,
178) {
179    let send = |cmd: Input| {
180        let _ = lock(&ends).input.push(cmd);
181    };
182    send(Input::Source { slot, mode });
183    let info = sub.info().clone();
184    let meta: Option<StageStreamMeta> = info.meta.as_ref().and_then(|m| serde_json::from_slice(m).ok());
185    if mode == Mode::Recorded {
186        let mut samples = Vec::new();
187        let mut first = None;
188        while let Some(ev) = sub.next().await {
189            match ev {
190                StreamEvent::Frame(f) => {
191                    first = first.or(marker_of(&f));
192                    samples.extend(f.f32_samples());
193                }
194                StreamEvent::Ended => break,
195                _ => {}
196            }
197        }
198        let Some(g) = grid(&lock(&ends)) else { return };
199        // the first frame's marker is exact; the stamp in ticks is the fallback
200        let start = first.map(|m| g.within(m)).or(meta.and_then(|m| m.start_tick).map(|t| g.tick_to_frame(t))).unwrap_or(0) % g.loop_frames;
201        lock(&stats).take_frames = (samples.len() / info.param("channels").and_then(|c| c.parse().ok()).unwrap_or(2)) as u64;
202        send(Input::Take { slot, samples, start_frame: start });
203        while !stop.load(Ordering::Relaxed) {
204            tokio::time::sleep(Duration::from_millis(50)).await;
205            while lock(&ends).spent.pop().is_ok() {}
206        }
207        send(Input::Remove { slot });
208        return;
209    }
210    let (mut sum, mut n, mut bars) = (0.0f64, 0u64, 0u32);
211    let mut offset: Option<i64> = None;
212    while !stop.load(Ordering::Relaxed) {
213        let ev = match tokio::time::timeout(Duration::from_millis(200), sub.next()).await {
214            Ok(Some(ev)) => ev,
215            Ok(None) => break,
216            Err(_) => continue,
217        };
218        let StreamEvent::Frame(f) = ev else { continue };
219        let now = crate::listen::wall_us();
220        let (g, rate, now_frames) = {
221            let mut e = lock(&ends);
222            while e.spent.pop().is_ok() {}
223            (grid(&e), e.sample_rate, local_now(&e))
224        };
225        let Some(g) = g else { continue };
226        if let Some(t) = crate::listen::sent_us(&f) {
227            sum += now.saturating_sub(t) as f64 / 1000.0;
228            n += 1;
229        }
230        let mut s = lock(&stats);
231        s.frames = sub.stats().frames;
232        s.jitter_ms = sub.stats().jitter_ms;
233        s.delay_ms_mean = if n > 0 { sum / n as f64 } else { 0.0 };
234        if let Mode::LiveBars(0) = mode {
235            // automatic: the smallest whole number of bars that covers the delay and jitter; it only grows
236            let want = bars_for(s.delay_ms_mean, s.jitter_ms, 1024, g.bar_frames(), rate);
237            if want > bars {
238                bars = want;
239                drop(s);
240                send(Input::Bars { slot, bars });
241                s = lock(&stats);
242            }
243        }
244        s.bars = bars.max(if let Mode::LiveBars(b) = mode { b } else { 0 });
245        s.late = lock(&ends).shared.late.load(Ordering::Relaxed);
246        drop(s);
247        let (Some(m), Some(now_frames)) = (marker_of(&f), now_frames) else {
248            offset = None;
249            continue;
250        };
251        let abs = g.abs(m);
252        let delay = u64::from(bars.max(if let Mode::LiveBars(b) = mode { b } else { 0 }).max(1)) * g.bar_frames();
253        let k = *offset.get_or_insert_with(|| loop_offset(abs, now_frames, g.loop_frames, delay, MARGIN));
254        let at = (abs as i64 + k * g.loop_frames as i64).max(0) as u64;
255        send(Input::Frame { slot, at, samples: f.f32_samples() });
256    }
257    send(Input::Remove { slot });
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn the_offset_keeps_the_position_and_picks_the_next_playable_round() {
266        // loop 100, one bar of 50 delay, margin 5
267        let k = loop_offset(1030, 3020, 100, 50, 5);
268        assert_eq!(k, 20);
269        let at = |k: i64| 1030 + k * 100 + 50;
270        assert_eq!(at(k) % 100, 80, "the same place on the loop, one bar (50) later");
271        assert!(at(k) >= 3025 && at(k - 1) < 3025, "the earliest round that is still ahead");
272        // a sender ahead of you in loops gets a negative offset
273        assert_eq!(loop_offset(9030, 3020, 100, 50, 5), -60);
274    }
275}