Skip to main content

weirdnet_audio_engine/
router.rs

1//! A fan-in router: named endpoints wired by routes and mixed on the audio thread.
2//!
3//! Endpoints, each with an id (a route graph's port id fits):
4//!
5//! * **sources** render on the audio thread (an [`crate::EngineAudio`], a talkback bus, any [`RenderFn`]);
6//! * **inputs** are fed from another thread through a [`RouterInput`] (a stream, a capture);
7//! * **buses** sum what is routed to their input name and offer the sum under their output name, so mixes chain (channel strips
8//!   into a master);
9//! * **taps** hand what is routed to them to another thread through a [`RouterTap`] (a recorder, a stream publisher);
10//! * the **device** ([`DEVICE`]) is what the router's render function plays.
11//!
12//! A route carries one endpoint's output to another's input with a gain. Fan-out and fan-in are free; a loop between buses is
13//! refused. Each destination sums its inputs in f32 in the order of their ids, so a mix is the same every time. A source can be
14//! muted or soloed (solo is per destination: when an input of a destination is soloed, its other inputs are silent), and a
15//! destination can have a limiter.
16//!
17//! The control side ([`RouterControl`]) works out a plan and hands it to the audio side ([`RouterAudio`]) through lock-free queues.
18//! The audio side never blocks, locks or allocates: old plans and removed sources travel back and are dropped on the control
19//! thread. With the `route` feature, [`RouterControl`] is a `weirdnet_audio_route::Executor`: it applies the connections of a
20//! route graph whose two ends are endpoints here, and lists the others for a remote executor.
21//!
22//! ```
23//! use weirdnet_audio_engine::router::{DEVICE, Route, router};
24//! use weirdnet_audio_engine::SinkConfig;
25//!
26//! let (mut control, mut audio) = router(SinkConfig::new(48_000, 1));
27//! control.add_source("a", Box::new(|out: &mut [f32]| out.fill(0.25)))?;
28//! control.add_source("b", Box::new(|out: &mut [f32]| out.fill(0.5)))?;
29//! control.set_routes(vec![Route::new("a", DEVICE), Route::new("b", DEVICE).gain_db(-6.0)])?;
30//! let mut block = [0.0f32; 64];
31//! audio.render(&mut block);
32//! assert!((block[0] - (0.25 + 0.5 * 0.501)).abs() < 1e-3);
33//! # Ok::<(), weirdnet_audio_engine::router::RouterError>(())
34//! ```
35
36use crate::sink::{RenderFn, SinkConfig};
37use crate::talkback::db_to_gain;
38use crossbeam_queue::ArrayQueue;
39use std::collections::{BTreeMap, BTreeSet};
40use std::fmt;
41use std::sync::Arc;
42use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
43
44/// The most endpoints a router holds (a bus counts once), the device included.
45pub const MAX_ENDPOINTS: usize = 64;
46
47/// The id of the device endpoint, which every router has.
48pub const DEVICE: &str = "device";
49
50/// Frames mixed at a time; a longer block is mixed in pieces.
51const CHUNK: usize = 512;
52
53/// Room in the queues between the two sides.
54const QUEUE: usize = 256;
55
56/// What an endpoint is.
57#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
58pub enum EndpointKind {
59    /// Renders on the audio thread.
60    Source,
61    /// Fed from another thread.
62    Input,
63    /// A bus's input: routes into it are summed.
64    BusIn,
65    /// A bus's output: the sum, to route on.
66    BusOut,
67    /// Read from another thread.
68    Tap,
69    /// The device.
70    Device,
71}
72
73impl EndpointKind {
74    /// Whether routes can start here.
75    pub fn feeds(self) -> bool {
76        matches!(self, EndpointKind::Source | EndpointKind::Input | EndpointKind::BusOut)
77    }
78
79    /// Whether routes can end here.
80    pub fn takes(self) -> bool {
81        matches!(self, EndpointKind::BusIn | EndpointKind::Tap | EndpointKind::Device)
82    }
83}
84
85/// One endpoint's output carried to another's input.
86#[derive(Clone, Debug, PartialEq)]
87pub struct Route {
88    /// A source, an input or a bus output.
89    pub from: String,
90    /// A bus input, a tap or the device.
91    pub to: String,
92    /// Linear gain.
93    pub gain: f32,
94}
95
96impl Route {
97    /// A route at unity gain.
98    pub fn new(from: &str, to: &str) -> Route {
99        Route { from: from.to_string(), to: to.to_string(), gain: 1.0 }
100    }
101
102    /// The same route with a gain in decibels.
103    pub fn gain_db(mut self, db: f32) -> Route {
104        self.gain = db_to_gain(db);
105        self
106    }
107}
108
109/// Why the router refused a change.
110#[derive(Clone, Debug, PartialEq, Eq)]
111pub enum RouterError {
112    /// An endpoint with this id exists already.
113    Exists(String),
114    /// No endpoint with this id.
115    Unknown(String),
116    /// [`MAX_ENDPOINTS`] are in use.
117    Full,
118    /// A route must start at a source, an input or a bus output.
119    NotAnOutput(String),
120    /// A route must end at a bus input, a tap or the device.
121    NotAnInput(String),
122    /// The same two endpoints are routed twice.
123    Duplicate(String, String),
124    /// The routes would feed a bus back into itself (the bus named).
125    Cycle(String),
126    /// The device cannot be removed.
127    Device,
128    /// The audio side has not taken the earlier changes yet (it is not running); try again once it renders.
129    Busy,
130}
131
132impl fmt::Display for RouterError {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        match self {
135            RouterError::Exists(id) => write!(f, "an endpoint {id} exists already"),
136            RouterError::Unknown(id) => write!(f, "no endpoint {id}"),
137            RouterError::Full => write!(f, "the router holds at most {MAX_ENDPOINTS} endpoints"),
138            RouterError::NotAnOutput(id) => write!(f, "{id} is not an output: a route starts at a source, an input or a bus output"),
139            RouterError::NotAnInput(id) => write!(f, "{id} is not an input: a route ends at a bus input, a tap or the device"),
140            RouterError::Duplicate(a, b) => write!(f, "{a} is routed to {b} twice"),
141            RouterError::Cycle(id) => write!(f, "the routes would feed bus {id} back into itself"),
142            RouterError::Device => write!(f, "the device endpoint cannot be removed"),
143            RouterError::Busy => write!(f, "the audio side has not taken the earlier changes yet"),
144        }
145    }
146}
147
148impl std::error::Error for RouterError {}
149
150struct Ring {
151    queue: ArrayQueue<f32>,
152    /// Inputs: samples dropped because the queue was full, plus missing samples played as silence. Taps: samples nobody read in time.
153    lost: AtomicU64,
154}
155
156/// Where another thread feeds an input endpoint: interleaved samples at the router's rate and channels.
157#[derive(Clone)]
158pub struct RouterInput(Arc<Ring>);
159
160impl RouterInput {
161    /// Queues samples. When the queue is full the oldest go, so the input stays current rather than late.
162    pub fn push(&self, samples: &[f32]) {
163        for &s in samples {
164            if self.0.queue.force_push(s).is_some() {
165                self.0.lost.fetch_add(1, Ordering::Relaxed);
166            }
167        }
168    }
169
170    /// Samples waiting.
171    pub fn queued(&self) -> usize {
172        self.0.queue.len()
173    }
174
175    /// Samples dropped while full plus samples that were missing when the audio side needed them.
176    pub fn lost(&self) -> u64 {
177        self.0.lost.load(Ordering::Relaxed)
178    }
179}
180
181/// Where another thread reads a tap endpoint: interleaved samples at the router's rate and channels.
182#[derive(Clone)]
183pub struct RouterTap(Arc<Ring>);
184
185impl RouterTap {
186    /// Reads up to `out.len()` samples and returns how many it wrote.
187    pub fn read(&self, out: &mut [f32]) -> usize {
188        let mut n = 0;
189        while n < out.len() {
190            let Some(s) = self.0.queue.pop() else { break };
191            out[n] = s;
192            n += 1;
193        }
194        n
195    }
196
197    /// Samples lost because nobody read them in time.
198    pub fn lost(&self) -> u64 {
199        self.0.lost.load(Ordering::Relaxed)
200    }
201}
202
203enum Body {
204    Empty,
205    Render(RenderFn),
206    Ring(Arc<Ring>),
207}
208
209struct Mix {
210    dest: usize,
211    inputs: Vec<(usize, f32)>,
212    /// A limiter ceiling, linear.
213    limit: Option<f32>,
214}
215
216#[derive(Default)]
217struct Plan {
218    renders: Vec<usize>,
219    pulls: Vec<usize>,
220    mixes: Vec<Mix>,
221    taps: Vec<usize>,
222}
223
224enum Msg {
225    Install(usize, Body),
226    Clear(usize),
227    Plan(Box<Plan>),
228}
229
230// Held only so that the control thread, not the audio thread, drops it.
231#[allow(dead_code)]
232enum Garbage {
233    Body(Body),
234    Plan(Box<Plan>),
235}
236
237struct Shared {
238    peaks: [AtomicU32; MAX_ENDPOINTS],
239    frames: AtomicU64,
240}
241
242struct Endpoint {
243    slot: usize,
244    kind: EndpointKind,
245}
246
247/// The control side: endpoints, routes, mute, solo and limiters. Every change takes effect at the audio side's next block.
248pub struct RouterControl {
249    config: SinkConfig,
250    msgs: Arc<ArrayQueue<Msg>>,
251    garbage: Arc<ArrayQueue<Garbage>>,
252    shared: Arc<Shared>,
253    endpoints: BTreeMap<String, Endpoint>,
254    /// A bus's two names, by slot.
255    buses: BTreeMap<usize, (String, String)>,
256    free: Vec<usize>,
257    routes: Vec<Route>,
258    muted: BTreeSet<String>,
259    soloed: BTreeSet<String>,
260    limits: BTreeMap<String, f32>,
261    #[cfg_attr(not(feature = "route"), allow(dead_code))]
262    pub(crate) skipped: Vec<String>,
263}
264
265/// The audio side: make it a sink's render function with [`RouterAudio::into_render`], or call [`RouterAudio::render`].
266pub struct RouterAudio {
267    msgs: Arc<ArrayQueue<Msg>>,
268    garbage: Arc<ArrayQueue<Garbage>>,
269    shared: Arc<Shared>,
270    channels: usize,
271    release: f32,
272    bodies: Vec<Body>,
273    bufs: Vec<Vec<f32>>,
274    limiter: Vec<f32>,
275    plan: Box<Plan>,
276}
277
278/// A router for a device with `config`. Every endpoint has the device's rate and channels.
279pub fn router(config: SinkConfig) -> (RouterControl, RouterAudio) {
280    let msgs = Arc::new(ArrayQueue::new(QUEUE));
281    let garbage = Arc::new(ArrayQueue::new(QUEUE));
282    let shared = Arc::new(Shared { peaks: std::array::from_fn(|_| AtomicU32::new(0)), frames: AtomicU64::new(0) });
283    let ch = usize::from(config.channels.max(1));
284    let mut endpoints = BTreeMap::new();
285    endpoints.insert(DEVICE.to_string(), Endpoint { slot: 0, kind: EndpointKind::Device });
286    let mut control = RouterControl {
287        config,
288        msgs: msgs.clone(),
289        garbage: garbage.clone(),
290        shared: shared.clone(),
291        endpoints,
292        buses: BTreeMap::new(),
293        free: (1..MAX_ENDPOINTS).rev().collect(),
294        routes: Vec::new(),
295        muted: BTreeSet::new(),
296        soloed: BTreeSet::new(),
297        limits: BTreeMap::new(),
298        skipped: Vec::new(),
299    };
300    let audio = RouterAudio {
301        msgs,
302        garbage,
303        shared,
304        channels: ch,
305        // the limiter recovers with a 50 ms time constant
306        release: 1.0 - (-1.0 / (0.05 * config.sample_rate.max(1) as f32)).exp(),
307        bodies: (0..MAX_ENDPOINTS).map(|_| Body::Empty).collect(),
308        bufs: (0..MAX_ENDPOINTS).map(|_| vec![0.0; CHUNK * ch]).collect(),
309        limiter: vec![1.0; MAX_ENDPOINTS],
310        plan: Box::new(Plan::default()),
311    };
312    let _ = control.publish();
313    (control, audio)
314}
315
316impl RouterControl {
317    /// The router's rate and channels.
318    pub fn config(&self) -> SinkConfig {
319        self.config
320    }
321
322    /// Drops what the audio side handed back. Every other call does this too.
323    pub fn tidy(&self) {
324        while let Some(g) = self.garbage.pop() {
325            drop(g);
326        }
327    }
328
329    fn send(&self, msg: Msg) -> Result<(), RouterError> {
330        self.tidy();
331        self.msgs.push(msg).map_err(|_| RouterError::Busy)
332    }
333
334    fn claim(&mut self, ids: &[&str]) -> Result<usize, RouterError> {
335        self.tidy();
336        for id in ids {
337            if self.endpoints.contains_key(*id) {
338                return Err(RouterError::Exists(id.to_string()));
339            }
340        }
341        if self.msgs.len() + 2 > QUEUE {
342            return Err(RouterError::Busy);
343        }
344        self.free.pop().ok_or(RouterError::Full)
345    }
346
347    fn add(&mut self, id: &str, kind: EndpointKind, body: Body) -> Result<(), RouterError> {
348        let slot = self.claim(&[id])?;
349        self.send(Msg::Install(slot, body))?;
350        self.endpoints.insert(id.to_string(), Endpoint { slot, kind });
351        self.publish()
352    }
353
354    /// Adds a source rendered on the audio thread once per block, routed or not (so its clock keeps running).
355    pub fn add_source(&mut self, id: &str, render: RenderFn) -> Result<(), RouterError> {
356        self.add(id, EndpointKind::Source, Body::Render(render))
357    }
358
359    /// Adds an input fed from another thread, with room for `frames` frames. Missing samples play as silence.
360    pub fn add_input(&mut self, id: &str, frames: usize) -> Result<RouterInput, RouterError> {
361        let ring = self.ring(frames);
362        self.add(id, EndpointKind::Input, Body::Ring(ring.clone()))?;
363        Ok(RouterInput(ring))
364    }
365
366    /// Adds a tap read from another thread, with room for `frames` frames.
367    pub fn add_tap(&mut self, id: &str, frames: usize) -> Result<RouterTap, RouterError> {
368        let ring = self.ring(frames);
369        self.add(id, EndpointKind::Tap, Body::Ring(ring.clone()))?;
370        Ok(RouterTap(ring))
371    }
372
373    /// Adds a bus: routes into `input` are summed, and the sum leaves from `output`.
374    pub fn add_bus(&mut self, input: &str, output: &str) -> Result<(), RouterError> {
375        if input == output {
376            return Err(RouterError::Exists(output.to_string()));
377        }
378        let slot = self.claim(&[input, output])?;
379        self.endpoints.insert(input.to_string(), Endpoint { slot, kind: EndpointKind::BusIn });
380        self.endpoints.insert(output.to_string(), Endpoint { slot, kind: EndpointKind::BusOut });
381        self.buses.insert(slot, (input.to_string(), output.to_string()));
382        self.publish()
383    }
384
385    fn ring(&self, frames: usize) -> Arc<Ring> {
386        Arc::new(Ring { queue: ArrayQueue::new((frames.max(1)) * usize::from(self.config.channels.max(1))), lost: AtomicU64::new(0) })
387    }
388
389    /// Removes an endpoint (either name removes a bus) and every route that touches it.
390    pub fn remove(&mut self, id: &str) -> Result<(), RouterError> {
391        self.tidy();
392        let Some(e) = self.endpoints.get(id) else { return Err(RouterError::Unknown(id.to_string())) };
393        if e.kind == EndpointKind::Device {
394            return Err(RouterError::Device);
395        }
396        let slot = e.slot;
397        let names: Vec<String> = match self.buses.get(&slot) {
398            Some((a, b)) => vec![a.clone(), b.clone()],
399            None => vec![id.to_string()],
400        };
401        let kept: Vec<Route> = self.routes.iter().filter(|r| !names.contains(&r.from) && !names.contains(&r.to)).cloned().collect();
402        let old = std::mem::replace(&mut self.routes, kept);
403        for n in &names {
404            self.endpoints.remove(n);
405            self.muted.remove(n);
406            self.soloed.remove(n);
407            self.limits.remove(n);
408        }
409        self.buses.remove(&slot);
410        if let Err(e) = self.publish().and_then(|()| self.send(Msg::Clear(slot))) {
411            self.routes = old;
412            return Err(e);
413        }
414        self.free.push(slot);
415        Ok(())
416    }
417
418    /// Replaces every route. Nothing changes if one is refused.
419    pub fn set_routes(&mut self, routes: Vec<Route>) -> Result<(), RouterError> {
420        self.tidy();
421        self.check(&routes)?;
422        let old = std::mem::replace(&mut self.routes, routes);
423        self.publish().inspect_err(|_| self.routes = old.clone())
424    }
425
426    /// Adds one route (replacing the gain of the same two endpoints if they are routed already).
427    pub fn connect(&mut self, route: Route) -> Result<(), RouterError> {
428        let mut routes: Vec<Route> = self.routes.iter().filter(|r| !(r.from == route.from && r.to == route.to)).cloned().collect();
429        routes.push(route);
430        self.set_routes(routes)
431    }
432
433    /// Removes the route from `from` to `to`, if there is one.
434    pub fn disconnect(&mut self, from: &str, to: &str) -> Result<(), RouterError> {
435        let routes = self.routes.iter().filter(|r| !(r.from == from && r.to == to)).cloned().collect();
436        self.set_routes(routes)
437    }
438
439    /// The routes.
440    pub fn routes(&self) -> &[Route] {
441        &self.routes
442    }
443
444    /// The endpoints, by id.
445    pub fn endpoints(&self) -> impl Iterator<Item = (&str, EndpointKind)> {
446        self.endpoints.iter().map(|(id, e)| (id.as_str(), e.kind))
447    }
448
449    /// The kind of endpoint `id`.
450    pub fn kind(&self, id: &str) -> Option<EndpointKind> {
451        self.endpoints.get(id).map(|e| e.kind)
452    }
453
454    /// Mutes or unmutes everything that leaves `id` (a source, an input or a bus output).
455    pub fn set_muted(&mut self, id: &str, muted: bool) -> Result<(), RouterError> {
456        self.feeder(id)?;
457        if muted {
458            self.muted.insert(id.to_string())
459        } else {
460            self.muted.remove(id)
461        };
462        self.publish()
463    }
464
465    /// Solos `id`: at each destination it feeds, the inputs that are not soloed go silent.
466    pub fn set_solo(&mut self, id: &str, solo: bool) -> Result<(), RouterError> {
467        self.feeder(id)?;
468        if solo {
469            self.soloed.insert(id.to_string())
470        } else {
471            self.soloed.remove(id)
472        };
473        self.publish()
474    }
475
476    /// Puts a limiter with a ceiling of `ceiling_db` on destination `id` (a bus input, a tap or the device), or takes it off.
477    pub fn set_limit(&mut self, id: &str, ceiling_db: Option<f32>) -> Result<(), RouterError> {
478        match self.kind(id) {
479            None => return Err(RouterError::Unknown(id.to_string())),
480            Some(k) if !k.takes() => return Err(RouterError::NotAnInput(id.to_string())),
481            _ => {}
482        }
483        match ceiling_db {
484            Some(db) => self.limits.insert(id.to_string(), db_to_gain(db)),
485            None => self.limits.remove(id),
486        };
487        self.publish()
488    }
489
490    /// The peak of the last block at endpoint `id` (linear; after its mix and limiter for a destination).
491    pub fn level(&self, id: &str) -> Option<f32> {
492        self.endpoints.get(id).map(|e| f32::from_bits(self.shared.peaks[e.slot].load(Ordering::Relaxed)))
493    }
494
495    /// Frames the audio side has rendered.
496    pub fn frames(&self) -> u64 {
497        self.shared.frames.load(Ordering::Relaxed)
498    }
499
500    fn feeder(&self, id: &str) -> Result<(), RouterError> {
501        match self.kind(id) {
502            None => Err(RouterError::Unknown(id.to_string())),
503            Some(k) if !k.feeds() => Err(RouterError::NotAnOutput(id.to_string())),
504            _ => Ok(()),
505        }
506    }
507
508    fn check(&self, routes: &[Route]) -> Result<(), RouterError> {
509        let mut seen = BTreeSet::new();
510        for r in routes {
511            match self.kind(&r.from) {
512                None => return Err(RouterError::Unknown(r.from.clone())),
513                Some(k) if !k.feeds() => return Err(RouterError::NotAnOutput(r.from.clone())),
514                _ => {}
515            }
516            match self.kind(&r.to) {
517                None => return Err(RouterError::Unknown(r.to.clone())),
518                Some(k) if !k.takes() => return Err(RouterError::NotAnInput(r.to.clone())),
519                _ => {}
520            }
521            if !seen.insert((r.from.as_str(), r.to.as_str())) {
522                return Err(RouterError::Duplicate(r.from.clone(), r.to.clone()));
523            }
524        }
525        self.bus_order(routes).map(|_| ())
526    }
527
528    /// The buses in an order where each comes after every bus that feeds it.
529    fn bus_order(&self, routes: &[Route]) -> Result<Vec<usize>, RouterError> {
530        let mut feeds: BTreeMap<usize, BTreeSet<usize>> = self.buses.keys().map(|s| (*s, BTreeSet::new())).collect();
531        for r in routes {
532            let (a, b) = (&self.endpoints[&r.from], &self.endpoints[&r.to]);
533            if a.kind == EndpointKind::BusOut && b.kind == EndpointKind::BusIn {
534                if a.slot == b.slot {
535                    return Err(RouterError::Cycle(self.buses[&a.slot].0.clone()));
536                }
537                feeds.entry(b.slot).or_default().insert(a.slot);
538            }
539        }
540        let mut order = Vec::new();
541        let mut done = BTreeSet::new();
542        while done.len() < feeds.len() {
543            let ready: Vec<usize> =
544                feeds.iter().filter(|(s, ins)| !done.contains(*s) && ins.iter().all(|i| done.contains(i))).map(|(s, _)| *s).collect();
545            if ready.is_empty() {
546                let stuck = feeds.keys().find(|s| !done.contains(*s)).copied().unwrap_or(0);
547                return Err(RouterError::Cycle(self.buses.get(&stuck).map(|b| b.0.clone()).unwrap_or_default()));
548            }
549            for s in ready {
550                done.insert(s);
551                order.push(s);
552            }
553        }
554        Ok(order)
555    }
556
557    fn mix_for(&self, dest_id: &str, dest: usize) -> Mix {
558        let mut ins: Vec<&Route> = self.routes.iter().filter(|r| r.to == dest_id).collect();
559        ins.sort_by(|a, b| a.from.cmp(&b.from));
560        let solo = ins.iter().any(|r| self.soloed.contains(&r.from));
561        let inputs = ins
562            .into_iter()
563            .filter(|r| !self.muted.contains(&r.from) && (!solo || self.soloed.contains(&r.from)))
564            .map(|r| (self.endpoints[&r.from].slot, r.gain))
565            .collect();
566        Mix { dest, inputs, limit: self.limits.get(dest_id).copied() }
567    }
568
569    fn publish(&mut self) -> Result<(), RouterError> {
570        let order = self.bus_order(&self.routes)?;
571        let mut plan = Plan::default();
572        for e in self.endpoints.values() {
573            match e.kind {
574                EndpointKind::Source => plan.renders.push(e.slot),
575                EndpointKind::Input => plan.pulls.push(e.slot),
576                _ => {}
577            }
578        }
579        for slot in order {
580            let name = self.buses[&slot].0.clone();
581            plan.mixes.push(self.mix_for(&name, slot));
582        }
583        for (id, e) in &self.endpoints {
584            if e.kind == EndpointKind::Tap {
585                plan.mixes.push(self.mix_for(id, e.slot));
586                plan.taps.push(e.slot);
587            }
588        }
589        plan.mixes.push(self.mix_for(DEVICE, 0));
590        self.send(Msg::Plan(Box::new(plan)))
591    }
592}
593
594impl RouterAudio {
595    fn bin(&self, g: Garbage) {
596        // The queue is large and the control side empties it on every call; if it is ever full the item is dropped here.
597        let _ = self.garbage.push(g);
598    }
599
600    fn take_messages(&mut self) {
601        while let Some(m) = self.msgs.pop() {
602            match m {
603                Msg::Install(slot, body) => {
604                    let old = std::mem::replace(&mut self.bodies[slot], body);
605                    self.limiter[slot] = 1.0;
606                    self.bin(Garbage::Body(old));
607                }
608                Msg::Clear(slot) => {
609                    let old = std::mem::replace(&mut self.bodies[slot], Body::Empty);
610                    self.shared.peaks[slot].store(0, Ordering::Relaxed);
611                    self.bin(Garbage::Body(old));
612                }
613                Msg::Plan(p) => {
614                    let old = std::mem::replace(&mut self.plan, p);
615                    self.bin(Garbage::Plan(old));
616                }
617            }
618        }
619    }
620
621    /// Mixes one block of interleaved device output.
622    pub fn render(&mut self, out: &mut [f32]) {
623        self.take_messages();
624        let ch = self.channels;
625        let mut done = 0;
626        while done < out.len() {
627            let n = (out.len() - done).min(CHUNK * ch);
628            self.chunk(n);
629            out[done..done + n].copy_from_slice(&self.bufs[0][..n]);
630            done += n;
631        }
632        self.shared.frames.fetch_add((out.len() / ch) as u64, Ordering::Relaxed);
633    }
634
635    fn chunk(&mut self, n: usize) {
636        let plan = &self.plan;
637        for &s in &plan.renders {
638            if let Body::Render(f) = &mut self.bodies[s] {
639                f(&mut self.bufs[s][..n]);
640            } else {
641                self.bufs[s][..n].fill(0.0);
642            }
643            store_peak(&self.shared.peaks[s], &self.bufs[s][..n]);
644        }
645        for &s in &plan.pulls {
646            let buf = &mut self.bufs[s][..n];
647            match &self.bodies[s] {
648                Body::Ring(r) => {
649                    let mut missing = 0u64;
650                    for x in buf.iter_mut() {
651                        *x = r.queue.pop().unwrap_or_else(|| {
652                            missing += 1;
653                            0.0
654                        });
655                    }
656                    if missing > 0 {
657                        r.lost.fetch_add(missing, Ordering::Relaxed);
658                    }
659                }
660                _ => buf.fill(0.0),
661            }
662            store_peak(&self.shared.peaks[s], buf);
663        }
664        for mix in &plan.mixes {
665            let mut acc = std::mem::take(&mut self.bufs[mix.dest]);
666            let a = &mut acc[..n];
667            a.fill(0.0);
668            for &(src, gain) in &mix.inputs {
669                for (x, y) in a.iter_mut().zip(&self.bufs[src][..n]) {
670                    *x += gain * y;
671                }
672            }
673            if let Some(ceiling) = mix.limit {
674                limit(a, self.channels, ceiling, self.release, &mut self.limiter[mix.dest]);
675            }
676            store_peak(&self.shared.peaks[mix.dest], a);
677            self.bufs[mix.dest] = acc;
678        }
679        for &t in &plan.taps {
680            if let Body::Ring(r) = &self.bodies[t] {
681                let mut lost = 0u64;
682                for &x in &self.bufs[t][..n] {
683                    if r.queue.push(x).is_err() {
684                        lost += 1;
685                    }
686                }
687                if lost > 0 {
688                    r.lost.fetch_add(lost, Ordering::Relaxed);
689                }
690            }
691        }
692    }
693
694    /// The render function for a sink.
695    pub fn into_render(mut self) -> RenderFn {
696        Box::new(move |out: &mut [f32]| self.render(out))
697    }
698}
699
700fn store_peak(cell: &AtomicU32, buf: &[f32]) {
701    let p = buf.iter().fold(0f32, |m, x| m.max(x.abs()));
702    cell.store(p.to_bits(), Ordering::Relaxed);
703}
704
705/// A peak limiter that reacts at once and recovers with `release` per frame; nothing leaves above `ceiling`.
706fn limit(buf: &mut [f32], channels: usize, ceiling: f32, release: f32, gain: &mut f32) {
707    for frame in buf.chunks_mut(channels) {
708        let peak = frame.iter().fold(0f32, |m, x| m.max(x.abs()));
709        let want = if peak > ceiling { ceiling / peak } else { 1.0 };
710        *gain = (*gain + (1.0 - *gain) * release).min(want);
711        for x in frame {
712            *x *= *gain;
713        }
714    }
715}