1use 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
44pub const MAX_ENDPOINTS: usize = 64;
46
47pub const DEVICE: &str = "device";
49
50const CHUNK: usize = 512;
52
53const QUEUE: usize = 256;
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
58pub enum EndpointKind {
59 Source,
61 Input,
63 BusIn,
65 BusOut,
67 Tap,
69 Device,
71}
72
73impl EndpointKind {
74 pub fn feeds(self) -> bool {
76 matches!(self, EndpointKind::Source | EndpointKind::Input | EndpointKind::BusOut)
77 }
78
79 pub fn takes(self) -> bool {
81 matches!(self, EndpointKind::BusIn | EndpointKind::Tap | EndpointKind::Device)
82 }
83}
84
85#[derive(Clone, Debug, PartialEq)]
87pub struct Route {
88 pub from: String,
90 pub to: String,
92 pub gain: f32,
94}
95
96impl Route {
97 pub fn new(from: &str, to: &str) -> Route {
99 Route { from: from.to_string(), to: to.to_string(), gain: 1.0 }
100 }
101
102 pub fn gain_db(mut self, db: f32) -> Route {
104 self.gain = db_to_gain(db);
105 self
106 }
107}
108
109#[derive(Clone, Debug, PartialEq, Eq)]
111pub enum RouterError {
112 Exists(String),
114 Unknown(String),
116 Full,
118 NotAnOutput(String),
120 NotAnInput(String),
122 Duplicate(String, String),
124 Cycle(String),
126 Device,
128 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 lost: AtomicU64,
154}
155
156#[derive(Clone)]
158pub struct RouterInput(Arc<Ring>);
159
160impl RouterInput {
161 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 pub fn queued(&self) -> usize {
172 self.0.queue.len()
173 }
174
175 pub fn lost(&self) -> u64 {
177 self.0.lost.load(Ordering::Relaxed)
178 }
179}
180
181#[derive(Clone)]
183pub struct RouterTap(Arc<Ring>);
184
185impl RouterTap {
186 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 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 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#[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
247pub 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 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
265pub 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
278pub 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 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 pub fn config(&self) -> SinkConfig {
319 self.config
320 }
321
322 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 pub fn add_source(&mut self, id: &str, render: RenderFn) -> Result<(), RouterError> {
356 self.add(id, EndpointKind::Source, Body::Render(render))
357 }
358
359 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 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 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 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 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 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 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 pub fn routes(&self) -> &[Route] {
441 &self.routes
442 }
443
444 pub fn endpoints(&self) -> impl Iterator<Item = (&str, EndpointKind)> {
446 self.endpoints.iter().map(|(id, e)| (id.as_str(), e.kind))
447 }
448
449 pub fn kind(&self, id: &str) -> Option<EndpointKind> {
451 self.endpoints.get(id).map(|e| e.kind)
452 }
453
454 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 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 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 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 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 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 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 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 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
705fn 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}