weirdnet-audio-engine 0.5.0

Audio engine pieces for Weirdnet: the AudioSink trait, a manual sink for tests, a cpal device sink (feature `cpal`) and a waveform player.
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
707
708
709
710
711
712
713
714
715
//! A fan-in router: named endpoints wired by routes and mixed on the audio thread.
//!
//! Endpoints, each with an id (a route graph's port id fits):
//!
//! * **sources** render on the audio thread (an [`crate::EngineAudio`], a talkback bus, any [`RenderFn`]);
//! * **inputs** are fed from another thread through a [`RouterInput`] (a stream, a capture);
//! * **buses** sum what is routed to their input name and offer the sum under their output name, so mixes chain (channel strips
//!   into a master);
//! * **taps** hand what is routed to them to another thread through a [`RouterTap`] (a recorder, a stream publisher);
//! * the **device** ([`DEVICE`]) is what the router's render function plays.
//!
//! 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
//! 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
//! muted or soloed (solo is per destination: when an input of a destination is soloed, its other inputs are silent), and a
//! destination can have a limiter.
//!
//! The control side ([`RouterControl`]) works out a plan and hands it to the audio side ([`RouterAudio`]) through lock-free queues.
//! The audio side never blocks, locks or allocates: old plans and removed sources travel back and are dropped on the control
//! thread. With the `route` feature, [`RouterControl`] is a `weirdnet_audio_route::Executor`: it applies the connections of a
//! route graph whose two ends are endpoints here, and lists the others for a remote executor.
//!
//! ```
//! use weirdnet_audio_engine::router::{DEVICE, Route, router};
//! use weirdnet_audio_engine::SinkConfig;
//!
//! let (mut control, mut audio) = router(SinkConfig::new(48_000, 1));
//! control.add_source("a", Box::new(|out: &mut [f32]| out.fill(0.25)))?;
//! control.add_source("b", Box::new(|out: &mut [f32]| out.fill(0.5)))?;
//! control.set_routes(vec![Route::new("a", DEVICE), Route::new("b", DEVICE).gain_db(-6.0)])?;
//! let mut block = [0.0f32; 64];
//! audio.render(&mut block);
//! assert!((block[0] - (0.25 + 0.5 * 0.501)).abs() < 1e-3);
//! # Ok::<(), weirdnet_audio_engine::router::RouterError>(())
//! ```

use crate::sink::{RenderFn, SinkConfig};
use crate::talkback::db_to_gain;
use crossbeam_queue::ArrayQueue;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};

/// The most endpoints a router holds (a bus counts once), the device included.
pub const MAX_ENDPOINTS: usize = 64;

/// The id of the device endpoint, which every router has.
pub const DEVICE: &str = "device";

/// Frames mixed at a time; a longer block is mixed in pieces.
const CHUNK: usize = 512;

/// Room in the queues between the two sides.
const QUEUE: usize = 256;

/// What an endpoint is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum EndpointKind {
    /// Renders on the audio thread.
    Source,
    /// Fed from another thread.
    Input,
    /// A bus's input: routes into it are summed.
    BusIn,
    /// A bus's output: the sum, to route on.
    BusOut,
    /// Read from another thread.
    Tap,
    /// The device.
    Device,
}

impl EndpointKind {
    /// Whether routes can start here.
    pub fn feeds(self) -> bool {
        matches!(self, EndpointKind::Source | EndpointKind::Input | EndpointKind::BusOut)
    }

    /// Whether routes can end here.
    pub fn takes(self) -> bool {
        matches!(self, EndpointKind::BusIn | EndpointKind::Tap | EndpointKind::Device)
    }
}

/// One endpoint's output carried to another's input.
#[derive(Clone, Debug, PartialEq)]
pub struct Route {
    /// A source, an input or a bus output.
    pub from: String,
    /// A bus input, a tap or the device.
    pub to: String,
    /// Linear gain.
    pub gain: f32,
}

impl Route {
    /// A route at unity gain.
    pub fn new(from: &str, to: &str) -> Route {
        Route { from: from.to_string(), to: to.to_string(), gain: 1.0 }
    }

    /// The same route with a gain in decibels.
    pub fn gain_db(mut self, db: f32) -> Route {
        self.gain = db_to_gain(db);
        self
    }
}

/// Why the router refused a change.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RouterError {
    /// An endpoint with this id exists already.
    Exists(String),
    /// No endpoint with this id.
    Unknown(String),
    /// [`MAX_ENDPOINTS`] are in use.
    Full,
    /// A route must start at a source, an input or a bus output.
    NotAnOutput(String),
    /// A route must end at a bus input, a tap or the device.
    NotAnInput(String),
    /// The same two endpoints are routed twice.
    Duplicate(String, String),
    /// The routes would feed a bus back into itself (the bus named).
    Cycle(String),
    /// The device cannot be removed.
    Device,
    /// The audio side has not taken the earlier changes yet (it is not running); try again once it renders.
    Busy,
}

impl fmt::Display for RouterError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RouterError::Exists(id) => write!(f, "an endpoint {id} exists already"),
            RouterError::Unknown(id) => write!(f, "no endpoint {id}"),
            RouterError::Full => write!(f, "the router holds at most {MAX_ENDPOINTS} endpoints"),
            RouterError::NotAnOutput(id) => write!(f, "{id} is not an output: a route starts at a source, an input or a bus output"),
            RouterError::NotAnInput(id) => write!(f, "{id} is not an input: a route ends at a bus input, a tap or the device"),
            RouterError::Duplicate(a, b) => write!(f, "{a} is routed to {b} twice"),
            RouterError::Cycle(id) => write!(f, "the routes would feed bus {id} back into itself"),
            RouterError::Device => write!(f, "the device endpoint cannot be removed"),
            RouterError::Busy => write!(f, "the audio side has not taken the earlier changes yet"),
        }
    }
}

impl std::error::Error for RouterError {}

struct Ring {
    queue: ArrayQueue<f32>,
    /// Inputs: samples dropped because the queue was full, plus missing samples played as silence. Taps: samples nobody read in time.
    lost: AtomicU64,
}

/// Where another thread feeds an input endpoint: interleaved samples at the router's rate and channels.
#[derive(Clone)]
pub struct RouterInput(Arc<Ring>);

impl RouterInput {
    /// Queues samples. When the queue is full the oldest go, so the input stays current rather than late.
    pub fn push(&self, samples: &[f32]) {
        for &s in samples {
            if self.0.queue.force_push(s).is_some() {
                self.0.lost.fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    /// Samples waiting.
    pub fn queued(&self) -> usize {
        self.0.queue.len()
    }

    /// Samples dropped while full plus samples that were missing when the audio side needed them.
    pub fn lost(&self) -> u64 {
        self.0.lost.load(Ordering::Relaxed)
    }
}

/// Where another thread reads a tap endpoint: interleaved samples at the router's rate and channels.
#[derive(Clone)]
pub struct RouterTap(Arc<Ring>);

impl RouterTap {
    /// Reads up to `out.len()` samples and returns how many it wrote.
    pub fn read(&self, out: &mut [f32]) -> usize {
        let mut n = 0;
        while n < out.len() {
            let Some(s) = self.0.queue.pop() else { break };
            out[n] = s;
            n += 1;
        }
        n
    }

    /// Samples lost because nobody read them in time.
    pub fn lost(&self) -> u64 {
        self.0.lost.load(Ordering::Relaxed)
    }
}

enum Body {
    Empty,
    Render(RenderFn),
    Ring(Arc<Ring>),
}

struct Mix {
    dest: usize,
    inputs: Vec<(usize, f32)>,
    /// A limiter ceiling, linear.
    limit: Option<f32>,
}

#[derive(Default)]
struct Plan {
    renders: Vec<usize>,
    pulls: Vec<usize>,
    mixes: Vec<Mix>,
    taps: Vec<usize>,
}

enum Msg {
    Install(usize, Body),
    Clear(usize),
    Plan(Box<Plan>),
}

// Held only so that the control thread, not the audio thread, drops it.
#[allow(dead_code)]
enum Garbage {
    Body(Body),
    Plan(Box<Plan>),
}

struct Shared {
    peaks: [AtomicU32; MAX_ENDPOINTS],
    frames: AtomicU64,
}

struct Endpoint {
    slot: usize,
    kind: EndpointKind,
}

/// The control side: endpoints, routes, mute, solo and limiters. Every change takes effect at the audio side's next block.
pub struct RouterControl {
    config: SinkConfig,
    msgs: Arc<ArrayQueue<Msg>>,
    garbage: Arc<ArrayQueue<Garbage>>,
    shared: Arc<Shared>,
    endpoints: BTreeMap<String, Endpoint>,
    /// A bus's two names, by slot.
    buses: BTreeMap<usize, (String, String)>,
    free: Vec<usize>,
    routes: Vec<Route>,
    muted: BTreeSet<String>,
    soloed: BTreeSet<String>,
    limits: BTreeMap<String, f32>,
    #[cfg_attr(not(feature = "route"), allow(dead_code))]
    pub(crate) skipped: Vec<String>,
}

/// The audio side: make it a sink's render function with [`RouterAudio::into_render`], or call [`RouterAudio::render`].
pub struct RouterAudio {
    msgs: Arc<ArrayQueue<Msg>>,
    garbage: Arc<ArrayQueue<Garbage>>,
    shared: Arc<Shared>,
    channels: usize,
    release: f32,
    bodies: Vec<Body>,
    bufs: Vec<Vec<f32>>,
    limiter: Vec<f32>,
    plan: Box<Plan>,
}

/// A router for a device with `config`. Every endpoint has the device's rate and channels.
pub fn router(config: SinkConfig) -> (RouterControl, RouterAudio) {
    let msgs = Arc::new(ArrayQueue::new(QUEUE));
    let garbage = Arc::new(ArrayQueue::new(QUEUE));
    let shared = Arc::new(Shared { peaks: std::array::from_fn(|_| AtomicU32::new(0)), frames: AtomicU64::new(0) });
    let ch = usize::from(config.channels.max(1));
    let mut endpoints = BTreeMap::new();
    endpoints.insert(DEVICE.to_string(), Endpoint { slot: 0, kind: EndpointKind::Device });
    let mut control = RouterControl {
        config,
        msgs: msgs.clone(),
        garbage: garbage.clone(),
        shared: shared.clone(),
        endpoints,
        buses: BTreeMap::new(),
        free: (1..MAX_ENDPOINTS).rev().collect(),
        routes: Vec::new(),
        muted: BTreeSet::new(),
        soloed: BTreeSet::new(),
        limits: BTreeMap::new(),
        skipped: Vec::new(),
    };
    let audio = RouterAudio {
        msgs,
        garbage,
        shared,
        channels: ch,
        // the limiter recovers with a 50 ms time constant
        release: 1.0 - (-1.0 / (0.05 * config.sample_rate.max(1) as f32)).exp(),
        bodies: (0..MAX_ENDPOINTS).map(|_| Body::Empty).collect(),
        bufs: (0..MAX_ENDPOINTS).map(|_| vec![0.0; CHUNK * ch]).collect(),
        limiter: vec![1.0; MAX_ENDPOINTS],
        plan: Box::new(Plan::default()),
    };
    let _ = control.publish();
    (control, audio)
}

impl RouterControl {
    /// The router's rate and channels.
    pub fn config(&self) -> SinkConfig {
        self.config
    }

    /// Drops what the audio side handed back. Every other call does this too.
    pub fn tidy(&self) {
        while let Some(g) = self.garbage.pop() {
            drop(g);
        }
    }

    fn send(&self, msg: Msg) -> Result<(), RouterError> {
        self.tidy();
        self.msgs.push(msg).map_err(|_| RouterError::Busy)
    }

    fn claim(&mut self, ids: &[&str]) -> Result<usize, RouterError> {
        self.tidy();
        for id in ids {
            if self.endpoints.contains_key(*id) {
                return Err(RouterError::Exists(id.to_string()));
            }
        }
        if self.msgs.len() + 2 > QUEUE {
            return Err(RouterError::Busy);
        }
        self.free.pop().ok_or(RouterError::Full)
    }

    fn add(&mut self, id: &str, kind: EndpointKind, body: Body) -> Result<(), RouterError> {
        let slot = self.claim(&[id])?;
        self.send(Msg::Install(slot, body))?;
        self.endpoints.insert(id.to_string(), Endpoint { slot, kind });
        self.publish()
    }

    /// Adds a source rendered on the audio thread once per block, routed or not (so its clock keeps running).
    pub fn add_source(&mut self, id: &str, render: RenderFn) -> Result<(), RouterError> {
        self.add(id, EndpointKind::Source, Body::Render(render))
    }

    /// Adds an input fed from another thread, with room for `frames` frames. Missing samples play as silence.
    pub fn add_input(&mut self, id: &str, frames: usize) -> Result<RouterInput, RouterError> {
        let ring = self.ring(frames);
        self.add(id, EndpointKind::Input, Body::Ring(ring.clone()))?;
        Ok(RouterInput(ring))
    }

    /// Adds a tap read from another thread, with room for `frames` frames.
    pub fn add_tap(&mut self, id: &str, frames: usize) -> Result<RouterTap, RouterError> {
        let ring = self.ring(frames);
        self.add(id, EndpointKind::Tap, Body::Ring(ring.clone()))?;
        Ok(RouterTap(ring))
    }

    /// Adds a bus: routes into `input` are summed, and the sum leaves from `output`.
    pub fn add_bus(&mut self, input: &str, output: &str) -> Result<(), RouterError> {
        if input == output {
            return Err(RouterError::Exists(output.to_string()));
        }
        let slot = self.claim(&[input, output])?;
        self.endpoints.insert(input.to_string(), Endpoint { slot, kind: EndpointKind::BusIn });
        self.endpoints.insert(output.to_string(), Endpoint { slot, kind: EndpointKind::BusOut });
        self.buses.insert(slot, (input.to_string(), output.to_string()));
        self.publish()
    }

    fn ring(&self, frames: usize) -> Arc<Ring> {
        Arc::new(Ring { queue: ArrayQueue::new((frames.max(1)) * usize::from(self.config.channels.max(1))), lost: AtomicU64::new(0) })
    }

    /// Removes an endpoint (either name removes a bus) and every route that touches it.
    pub fn remove(&mut self, id: &str) -> Result<(), RouterError> {
        self.tidy();
        let Some(e) = self.endpoints.get(id) else { return Err(RouterError::Unknown(id.to_string())) };
        if e.kind == EndpointKind::Device {
            return Err(RouterError::Device);
        }
        let slot = e.slot;
        let names: Vec<String> = match self.buses.get(&slot) {
            Some((a, b)) => vec![a.clone(), b.clone()],
            None => vec![id.to_string()],
        };
        let kept: Vec<Route> = self.routes.iter().filter(|r| !names.contains(&r.from) && !names.contains(&r.to)).cloned().collect();
        let old = std::mem::replace(&mut self.routes, kept);
        for n in &names {
            self.endpoints.remove(n);
            self.muted.remove(n);
            self.soloed.remove(n);
            self.limits.remove(n);
        }
        self.buses.remove(&slot);
        if let Err(e) = self.publish().and_then(|()| self.send(Msg::Clear(slot))) {
            self.routes = old;
            return Err(e);
        }
        self.free.push(slot);
        Ok(())
    }

    /// Replaces every route. Nothing changes if one is refused.
    pub fn set_routes(&mut self, routes: Vec<Route>) -> Result<(), RouterError> {
        self.tidy();
        self.check(&routes)?;
        let old = std::mem::replace(&mut self.routes, routes);
        self.publish().inspect_err(|_| self.routes = old.clone())
    }

    /// Adds one route (replacing the gain of the same two endpoints if they are routed already).
    pub fn connect(&mut self, route: Route) -> Result<(), RouterError> {
        let mut routes: Vec<Route> = self.routes.iter().filter(|r| !(r.from == route.from && r.to == route.to)).cloned().collect();
        routes.push(route);
        self.set_routes(routes)
    }

    /// Removes the route from `from` to `to`, if there is one.
    pub fn disconnect(&mut self, from: &str, to: &str) -> Result<(), RouterError> {
        let routes = self.routes.iter().filter(|r| !(r.from == from && r.to == to)).cloned().collect();
        self.set_routes(routes)
    }

    /// The routes.
    pub fn routes(&self) -> &[Route] {
        &self.routes
    }

    /// The endpoints, by id.
    pub fn endpoints(&self) -> impl Iterator<Item = (&str, EndpointKind)> {
        self.endpoints.iter().map(|(id, e)| (id.as_str(), e.kind))
    }

    /// The kind of endpoint `id`.
    pub fn kind(&self, id: &str) -> Option<EndpointKind> {
        self.endpoints.get(id).map(|e| e.kind)
    }

    /// Mutes or unmutes everything that leaves `id` (a source, an input or a bus output).
    pub fn set_muted(&mut self, id: &str, muted: bool) -> Result<(), RouterError> {
        self.feeder(id)?;
        if muted {
            self.muted.insert(id.to_string())
        } else {
            self.muted.remove(id)
        };
        self.publish()
    }

    /// Solos `id`: at each destination it feeds, the inputs that are not soloed go silent.
    pub fn set_solo(&mut self, id: &str, solo: bool) -> Result<(), RouterError> {
        self.feeder(id)?;
        if solo {
            self.soloed.insert(id.to_string())
        } else {
            self.soloed.remove(id)
        };
        self.publish()
    }

    /// Puts a limiter with a ceiling of `ceiling_db` on destination `id` (a bus input, a tap or the device), or takes it off.
    pub fn set_limit(&mut self, id: &str, ceiling_db: Option<f32>) -> Result<(), RouterError> {
        match self.kind(id) {
            None => return Err(RouterError::Unknown(id.to_string())),
            Some(k) if !k.takes() => return Err(RouterError::NotAnInput(id.to_string())),
            _ => {}
        }
        match ceiling_db {
            Some(db) => self.limits.insert(id.to_string(), db_to_gain(db)),
            None => self.limits.remove(id),
        };
        self.publish()
    }

    /// The peak of the last block at endpoint `id` (linear; after its mix and limiter for a destination).
    pub fn level(&self, id: &str) -> Option<f32> {
        self.endpoints.get(id).map(|e| f32::from_bits(self.shared.peaks[e.slot].load(Ordering::Relaxed)))
    }

    /// Frames the audio side has rendered.
    pub fn frames(&self) -> u64 {
        self.shared.frames.load(Ordering::Relaxed)
    }

    fn feeder(&self, id: &str) -> Result<(), RouterError> {
        match self.kind(id) {
            None => Err(RouterError::Unknown(id.to_string())),
            Some(k) if !k.feeds() => Err(RouterError::NotAnOutput(id.to_string())),
            _ => Ok(()),
        }
    }

    fn check(&self, routes: &[Route]) -> Result<(), RouterError> {
        let mut seen = BTreeSet::new();
        for r in routes {
            match self.kind(&r.from) {
                None => return Err(RouterError::Unknown(r.from.clone())),
                Some(k) if !k.feeds() => return Err(RouterError::NotAnOutput(r.from.clone())),
                _ => {}
            }
            match self.kind(&r.to) {
                None => return Err(RouterError::Unknown(r.to.clone())),
                Some(k) if !k.takes() => return Err(RouterError::NotAnInput(r.to.clone())),
                _ => {}
            }
            if !seen.insert((r.from.as_str(), r.to.as_str())) {
                return Err(RouterError::Duplicate(r.from.clone(), r.to.clone()));
            }
        }
        self.bus_order(routes).map(|_| ())
    }

    /// The buses in an order where each comes after every bus that feeds it.
    fn bus_order(&self, routes: &[Route]) -> Result<Vec<usize>, RouterError> {
        let mut feeds: BTreeMap<usize, BTreeSet<usize>> = self.buses.keys().map(|s| (*s, BTreeSet::new())).collect();
        for r in routes {
            let (a, b) = (&self.endpoints[&r.from], &self.endpoints[&r.to]);
            if a.kind == EndpointKind::BusOut && b.kind == EndpointKind::BusIn {
                if a.slot == b.slot {
                    return Err(RouterError::Cycle(self.buses[&a.slot].0.clone()));
                }
                feeds.entry(b.slot).or_default().insert(a.slot);
            }
        }
        let mut order = Vec::new();
        let mut done = BTreeSet::new();
        while done.len() < feeds.len() {
            let ready: Vec<usize> =
                feeds.iter().filter(|(s, ins)| !done.contains(*s) && ins.iter().all(|i| done.contains(i))).map(|(s, _)| *s).collect();
            if ready.is_empty() {
                let stuck = feeds.keys().find(|s| !done.contains(*s)).copied().unwrap_or(0);
                return Err(RouterError::Cycle(self.buses.get(&stuck).map(|b| b.0.clone()).unwrap_or_default()));
            }
            for s in ready {
                done.insert(s);
                order.push(s);
            }
        }
        Ok(order)
    }

    fn mix_for(&self, dest_id: &str, dest: usize) -> Mix {
        let mut ins: Vec<&Route> = self.routes.iter().filter(|r| r.to == dest_id).collect();
        ins.sort_by(|a, b| a.from.cmp(&b.from));
        let solo = ins.iter().any(|r| self.soloed.contains(&r.from));
        let inputs = ins
            .into_iter()
            .filter(|r| !self.muted.contains(&r.from) && (!solo || self.soloed.contains(&r.from)))
            .map(|r| (self.endpoints[&r.from].slot, r.gain))
            .collect();
        Mix { dest, inputs, limit: self.limits.get(dest_id).copied() }
    }

    fn publish(&mut self) -> Result<(), RouterError> {
        let order = self.bus_order(&self.routes)?;
        let mut plan = Plan::default();
        for e in self.endpoints.values() {
            match e.kind {
                EndpointKind::Source => plan.renders.push(e.slot),
                EndpointKind::Input => plan.pulls.push(e.slot),
                _ => {}
            }
        }
        for slot in order {
            let name = self.buses[&slot].0.clone();
            plan.mixes.push(self.mix_for(&name, slot));
        }
        for (id, e) in &self.endpoints {
            if e.kind == EndpointKind::Tap {
                plan.mixes.push(self.mix_for(id, e.slot));
                plan.taps.push(e.slot);
            }
        }
        plan.mixes.push(self.mix_for(DEVICE, 0));
        self.send(Msg::Plan(Box::new(plan)))
    }
}

impl RouterAudio {
    fn bin(&self, g: Garbage) {
        // The queue is large and the control side empties it on every call; if it is ever full the item is dropped here.
        let _ = self.garbage.push(g);
    }

    fn take_messages(&mut self) {
        while let Some(m) = self.msgs.pop() {
            match m {
                Msg::Install(slot, body) => {
                    let old = std::mem::replace(&mut self.bodies[slot], body);
                    self.limiter[slot] = 1.0;
                    self.bin(Garbage::Body(old));
                }
                Msg::Clear(slot) => {
                    let old = std::mem::replace(&mut self.bodies[slot], Body::Empty);
                    self.shared.peaks[slot].store(0, Ordering::Relaxed);
                    self.bin(Garbage::Body(old));
                }
                Msg::Plan(p) => {
                    let old = std::mem::replace(&mut self.plan, p);
                    self.bin(Garbage::Plan(old));
                }
            }
        }
    }

    /// Mixes one block of interleaved device output.
    pub fn render(&mut self, out: &mut [f32]) {
        self.take_messages();
        let ch = self.channels;
        let mut done = 0;
        while done < out.len() {
            let n = (out.len() - done).min(CHUNK * ch);
            self.chunk(n);
            out[done..done + n].copy_from_slice(&self.bufs[0][..n]);
            done += n;
        }
        self.shared.frames.fetch_add((out.len() / ch) as u64, Ordering::Relaxed);
    }

    fn chunk(&mut self, n: usize) {
        let plan = &self.plan;
        for &s in &plan.renders {
            if let Body::Render(f) = &mut self.bodies[s] {
                f(&mut self.bufs[s][..n]);
            } else {
                self.bufs[s][..n].fill(0.0);
            }
            store_peak(&self.shared.peaks[s], &self.bufs[s][..n]);
        }
        for &s in &plan.pulls {
            let buf = &mut self.bufs[s][..n];
            match &self.bodies[s] {
                Body::Ring(r) => {
                    let mut missing = 0u64;
                    for x in buf.iter_mut() {
                        *x = r.queue.pop().unwrap_or_else(|| {
                            missing += 1;
                            0.0
                        });
                    }
                    if missing > 0 {
                        r.lost.fetch_add(missing, Ordering::Relaxed);
                    }
                }
                _ => buf.fill(0.0),
            }
            store_peak(&self.shared.peaks[s], buf);
        }
        for mix in &plan.mixes {
            let mut acc = std::mem::take(&mut self.bufs[mix.dest]);
            let a = &mut acc[..n];
            a.fill(0.0);
            for &(src, gain) in &mix.inputs {
                for (x, y) in a.iter_mut().zip(&self.bufs[src][..n]) {
                    *x += gain * y;
                }
            }
            if let Some(ceiling) = mix.limit {
                limit(a, self.channels, ceiling, self.release, &mut self.limiter[mix.dest]);
            }
            store_peak(&self.shared.peaks[mix.dest], a);
            self.bufs[mix.dest] = acc;
        }
        for &t in &plan.taps {
            if let Body::Ring(r) = &self.bodies[t] {
                let mut lost = 0u64;
                for &x in &self.bufs[t][..n] {
                    if r.queue.push(x).is_err() {
                        lost += 1;
                    }
                }
                if lost > 0 {
                    r.lost.fetch_add(lost, Ordering::Relaxed);
                }
            }
        }
    }

    /// The render function for a sink.
    pub fn into_render(mut self) -> RenderFn {
        Box::new(move |out: &mut [f32]| self.render(out))
    }
}

fn store_peak(cell: &AtomicU32, buf: &[f32]) {
    let p = buf.iter().fold(0f32, |m, x| m.max(x.abs()));
    cell.store(p.to_bits(), Ordering::Relaxed);
}

/// A peak limiter that reacts at once and recovers with `release` per frame; nothing leaves above `ceiling`.
fn limit(buf: &mut [f32], channels: usize, ceiling: f32, release: f32, gain: &mut f32) {
    for frame in buf.chunks_mut(channels) {
        let peak = frame.iter().fold(0f32, |m, x| m.max(x.abs()));
        let want = if peak > ceiling { ceiling / peak } else { 1.0 };
        *gain = (*gain + (1.0 - *gain) * release).min(want);
        for x in frame {
            *x *= *gain;
        }
    }
}