Skip to main content

weirdnet_streaming/
bus.rs

1//! The audio side of listen-along, safe on the audio thread: a wrapper around the engine's render callback that copies the master out
2//! into a ring (the tap, read by the network side to stream it) and adds samples from another ring (the mix, filled by a subscription
3//! to someone else's master out). No locks and no allocation in the callback.
4
5use crate::align::{Mode, Source};
6use rtrb::{Consumer, Producer, RingBuffer};
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
9
10/// The engine's render callback: fills an interleaved block.
11pub type Render = Box<dyn FnMut(&mut [f32]) + Send>;
12
13/// Counters and switches shared by the audio thread and the network side.
14#[derive(Default)]
15pub struct Shared {
16    /// Copy the master out into the tap.
17    pub tap_on: AtomicBool,
18    /// Play what arrives in the mix.
19    pub listening: AtomicBool,
20    /// Samples the tap could not hold (the network side was late).
21    pub tap_dropped: AtomicU64,
22    /// Times the mix ran dry while listening.
23    pub underruns: AtomicU64,
24    /// Samples played from the mix.
25    pub played: AtomicU64,
26    /// Samples rendered in all (the audio clock).
27    pub rendered: AtomicU64,
28    /// The transport, posted by the window from the engine's timing: at output frame `xport_output` the transport was at
29    /// `xport_transport` (absolute frames since play), while `playing`.
30    pub xport_output: AtomicU64,
31    /// The transport frame (absolute, since play) at `xport_output`.
32    pub xport_transport: AtomicU64,
33    /// Whether the transport is playing.
34    pub playing: AtomicBool,
35    /// Frames in one loop.
36    pub loop_frames: AtomicU64,
37    /// Frames in one bar.
38    pub bar_frames: AtomicU64,
39    /// Ticks in one loop.
40    pub loop_ticks: AtomicU64,
41    /// Copy your own voices, with their loop positions, into the dry tap.
42    pub dry_on: AtomicBool,
43    /// Live input frames dropped because their slot had passed.
44    pub late: AtomicU64,
45    /// Copy what goes to the device (your voices, collaborators and what you listen to: the
46    /// last thing in the block), with positions, into the device-output tap.
47    pub out_on: AtomicBool,
48    /// The device's output latency in frames: the device-output stream is stamped where its
49    /// audio is heard, this much after it leaves the block.
50    pub out_latency: AtomicU64,
51}
52
53impl Shared {
54    /// Post the transport (call often from the window; the engine timing is good to a block).
55    pub fn set_transport(&self, output_frame: u64, transport_frame: u64, playing: bool, loop_frames: u64, bar_frames: u64, loop_ticks: u64) {
56        self.loop_ticks.store(loop_ticks, Ordering::Relaxed);
57        self.xport_output.store(output_frame, Ordering::Relaxed);
58        self.xport_transport.store(transport_frame, Ordering::Relaxed);
59        self.loop_frames.store(loop_frames, Ordering::Relaxed);
60        self.bar_frames.store(bar_frames, Ordering::Relaxed);
61        self.playing.store(playing, Ordering::Relaxed);
62    }
63}
64
65/// What the network side tells the stream input.
66pub enum Input {
67    /// Add or replace the source in a slot.
68    Source {
69        /// Which collaborator slot (below [`SLOTS`]).
70        slot: usize,
71        /// How the source is aligned.
72        mode: Mode,
73    },
74    /// A recorded take for a slot, its first sample at `start_frame` on your loop.
75    Take {
76        /// Which collaborator slot (below [`SLOTS`]).
77        slot: usize,
78        /// Interleaved samples.
79        samples: Vec<f32>,
80        /// Where on the loop the first sample belongs.
81        start_frame: u64,
82    },
83    /// A live frame for a slot, played at `at` (your absolute frames) plus the bar delay.
84    Frame {
85        /// Which collaborator slot (below [`SLOTS`]).
86        slot: usize,
87        /// Absolute frame at which the first sample plays, before the bar delay.
88        at: u64,
89        /// Interleaved samples.
90        samples: Vec<f32>,
91    },
92    /// Sets the bars of delay for a live slot.
93    Bars {
94        /// Which collaborator slot (below [`SLOTS`]).
95        slot: usize,
96        /// Whole bars of delay.
97        bars: u32,
98    },
99    /// Sets a slot's gain and mute.
100    Gain {
101        /// Which collaborator slot (below [`SLOTS`]).
102        slot: usize,
103        /// Linear gain.
104        gain: f32,
105        /// Whether the slot is silenced.
106        mute: bool,
107    },
108    /// Empties a slot.
109    Remove {
110        /// Which collaborator slot (below [`SLOTS`]).
111        slot: usize,
112    },
113}
114
115/// Slots for collaborators' inputs.
116pub const SLOTS: usize = 4;
117
118/// The network side's ends of the rings.
119pub struct Ends {
120    /// The master out, interleaved, while [`Shared::tap_on`].
121    pub tap: Consumer<f32>,
122    /// Samples to play, interleaved, while [`Shared::listening`].
123    pub mix: Producer<f32>,
124    /// Your voices while [`Shared::dry_on`] and playing: each block's absolute start position and length, then its samples in `dry`.
125    pub dry_at: Consumer<(u64, u32)>,
126    /// The samples of your voices, matching `dry_at`.
127    pub dry: Consumer<f32>,
128    /// What goes to the device while [`Shared::out_on`] and playing, laid out like `dry_at` and `dry`.
129    pub out_at: Consumer<(u64, u32)>,
130    /// The samples of the device output, matching `out_at`.
131    pub out: Consumer<f32>,
132    /// Commands for the stream input.
133    pub input: Producer<Input>,
134    /// Buffers the audio thread is done with, to free here.
135    pub spent: Consumer<Vec<f32>>,
136    /// The flags and counters shared with the audio thread.
137    pub shared: Arc<Shared>,
138    /// The sample rate of every ring, Hz.
139    pub sample_rate: u32,
140    /// Channels per frame in every ring.
141    pub channels: u16,
142}
143
144/// How much arrives before the mix starts playing, and again after it ran dry.
145pub const PREBUFFER_MS: u32 = 40;
146
147/// Wrap `render` for `sample_rate` and `channels`. The rings hold two seconds each.
148pub fn wrap(mut render: Render, sample_rate: u32, channels: u16) -> (Render, Ends) {
149    let cap = sample_rate as usize * channels as usize * 2;
150    let (mut tap_p, tap_c) = RingBuffer::<f32>::new(cap);
151    let (mix_p, mut mix_c) = RingBuffer::<f32>::new(cap);
152    let (mut dry_p, dry_c) = RingBuffer::<f32>::new(cap);
153    let (mut dry_at_p, dry_at_c) = RingBuffer::<(u64, u32)>::new(1024);
154    let (mut out_p, out_c) = RingBuffer::<f32>::new(cap);
155    let (mut out_at_p, out_at_c) = RingBuffer::<(u64, u32)>::new(1024);
156    let (input_p, mut input_c) = RingBuffer::<Input>::new(1024);
157    let (mut spent_p, spent_c) = RingBuffer::<Vec<f32>>::new(4096);
158    let mut sources: [Option<Source>; SLOTS] = Default::default();
159    let ch = channels as usize;
160    let shared = Arc::new(Shared::default());
161    let s = shared.clone();
162    let prebuffer = (sample_rate * PREBUFFER_MS / 1000) as usize * channels as usize;
163    let mut started = false;
164    let wrapped: Render = Box::new(move |out: &mut [f32]| {
165        render(out);
166        let block_start = s.rendered.fetch_add(out.len() as u64, Ordering::Relaxed) / ch as u64;
167        let frames = (out.len() / ch) as u64;
168        let local = s.playing.load(Ordering::Relaxed).then(|| {
169            let (xo, xt) = (s.xport_output.load(Ordering::Relaxed), s.xport_transport.load(Ordering::Relaxed));
170            (xt as i64 + block_start as i64 - xo as i64).max(0) as u64
171        });
172        // samples first, then the header: the reader takes a header only once its samples are there
173        if let (true, Some(at)) = (s.dry_on.load(Ordering::Relaxed), local)
174            && dry_at_p.slots() > 0
175            && let Ok(chunk) = dry_p.write_chunk_uninit(out.len())
176        {
177            chunk.fill_from_iter(out.iter().copied());
178            let _ = dry_at_p.push((at, frames as u32));
179        }
180        if s.tap_on.load(Ordering::Relaxed) {
181            let n = out.len().min(tap_p.slots());
182            if let Ok(chunk) = tap_p.write_chunk_uninit(n) {
183                chunk.fill_from_iter(out[..n].iter().copied());
184            }
185            if n < out.len() {
186                s.tap_dropped.fetch_add((out.len() - n) as u64, Ordering::Relaxed);
187            }
188        }
189        // the stream input: collaborators aligned to your loop (after the taps, so your dry stream stays yours)
190        while let Ok(cmd) = input_c.pop() {
191            match cmd {
192                Input::Source { slot, mode } if slot < SLOTS => sources[slot] = Some(Source::new(mode, channels)),
193                Input::Take { slot, samples, start_frame } if slot < SLOTS => {
194                    let lf = s.loop_frames.load(Ordering::Relaxed);
195                    if let Some(src) = sources[slot].as_mut()
196                        && lf > 0
197                    {
198                        src.set_take(&samples, start_frame, lf);
199                    }
200                    let _ = spent_p.push(samples);
201                }
202                Input::Frame { slot, at, samples } if slot < SLOTS => match sources[slot].as_mut() {
203                    Some(src) => src.push(at, samples),
204                    None => {
205                        let _ = spent_p.push(samples);
206                    }
207                },
208                Input::Bars { slot, bars } if slot < SLOTS => {
209                    if let Some(src) = sources[slot].as_mut() {
210                        src.set_bars(bars);
211                    }
212                }
213                Input::Gain { slot, gain, mute } if slot < SLOTS => {
214                    if let Some(src) = sources[slot].as_mut() {
215                        src.gain = gain;
216                        src.mute = mute;
217                    }
218                }
219                Input::Remove { slot } if slot < SLOTS => sources[slot] = None,
220                _ => {}
221            }
222        }
223        let (lf, bf) = (s.loop_frames.load(Ordering::Relaxed), s.bar_frames.load(Ordering::Relaxed));
224        let mut late = 0;
225        for src in sources.iter_mut().flatten() {
226            src.render_into(out, local, lf, bf, &mut |v| {
227                let _ = spent_p.push(v);
228            });
229            late += src.late;
230        }
231        s.late.store(late, Ordering::Relaxed);
232        'mix: {
233            if !s.listening.load(Ordering::Relaxed) {
234                started = false;
235                let n = mix_c.slots();
236                if let Ok(c) = mix_c.read_chunk(n) {
237                    c.commit_all();
238                }
239                break 'mix;
240            }
241            if !started {
242                if mix_c.slots() < prebuffer {
243                    break 'mix;
244                }
245                started = true;
246            }
247            let n = out.len().min(mix_c.slots());
248            if let Ok(c) = mix_c.read_chunk(n) {
249                let (a, b) = c.as_slices();
250                for (o, v) in out.iter_mut().zip(a.iter().chain(b.iter())) {
251                    *o += *v;
252                }
253                c.commit_all();
254            }
255            s.played.fetch_add(n as u64, Ordering::Relaxed);
256            if n < out.len() {
257                s.underruns.fetch_add(1, Ordering::Relaxed);
258                started = false;
259            }
260        }
261        // the device-output tap: exactly what this block sends to the device
262        if let (true, Some(at)) = (s.out_on.load(Ordering::Relaxed), local)
263            && out_at_p.slots() > 0
264            && let Ok(chunk) = out_p.write_chunk_uninit(out.len())
265        {
266            chunk.fill_from_iter(out.iter().copied());
267            let _ = out_at_p.push((at, frames as u32));
268        }
269    });
270    (
271        wrapped,
272        Ends {
273            tap: tap_c,
274            mix: mix_p,
275            dry_at: dry_at_c,
276            dry: dry_c,
277            out_at: out_at_c,
278            out: out_c,
279            input: input_p,
280            spent: spent_c,
281            shared,
282            sample_rate,
283            channels,
284        },
285    )
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291
292    #[test]
293    fn the_tap_copies_and_the_mix_adds_after_the_prebuffer() {
294        let (mut r, mut e) = wrap(Box::new(|o: &mut [f32]| o.fill(0.25)), 1000, 1);
295        let mut out = vec![0.0; 10];
296        r(&mut out);
297        assert_eq!(e.tap.slots(), 0, "the tap is off by default");
298        e.shared.tap_on.store(true, Ordering::Relaxed);
299        r(&mut out);
300        assert_eq!(e.tap.slots(), 10);
301        e.shared.listening.store(true, Ordering::Relaxed);
302        for _ in 0..30 {
303            e.mix.push(0.5).unwrap();
304        }
305        r(&mut out);
306        assert!(out.iter().all(|v| (*v - 0.25).abs() < 1e-6), "30 samples is under the 40 ms prebuffer");
307        for _ in 0..30 {
308            e.mix.push(0.5).unwrap();
309        }
310        r(&mut out);
311        assert!(out.iter().all(|v| (*v - 0.75).abs() < 1e-6), "mixed in once enough arrived");
312        assert_eq!(e.shared.played.load(Ordering::Relaxed), 10);
313    }
314}