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};
pub const MAX_ENDPOINTS: usize = 64;
pub const DEVICE: &str = "device";
const CHUNK: usize = 512;
const QUEUE: usize = 256;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum EndpointKind {
Source,
Input,
BusIn,
BusOut,
Tap,
Device,
}
impl EndpointKind {
pub fn feeds(self) -> bool {
matches!(self, EndpointKind::Source | EndpointKind::Input | EndpointKind::BusOut)
}
pub fn takes(self) -> bool {
matches!(self, EndpointKind::BusIn | EndpointKind::Tap | EndpointKind::Device)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Route {
pub from: String,
pub to: String,
pub gain: f32,
}
impl Route {
pub fn new(from: &str, to: &str) -> Route {
Route { from: from.to_string(), to: to.to_string(), gain: 1.0 }
}
pub fn gain_db(mut self, db: f32) -> Route {
self.gain = db_to_gain(db);
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RouterError {
Exists(String),
Unknown(String),
Full,
NotAnOutput(String),
NotAnInput(String),
Duplicate(String, String),
Cycle(String),
Device,
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>,
lost: AtomicU64,
}
#[derive(Clone)]
pub struct RouterInput(Arc<Ring>);
impl RouterInput {
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);
}
}
}
pub fn queued(&self) -> usize {
self.0.queue.len()
}
pub fn lost(&self) -> u64 {
self.0.lost.load(Ordering::Relaxed)
}
}
#[derive(Clone)]
pub struct RouterTap(Arc<Ring>);
impl RouterTap {
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
}
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)>,
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>),
}
#[allow(dead_code)]
enum Garbage {
Body(Body),
Plan(Box<Plan>),
}
struct Shared {
peaks: [AtomicU32; MAX_ENDPOINTS],
frames: AtomicU64,
}
struct Endpoint {
slot: usize,
kind: EndpointKind,
}
pub struct RouterControl {
config: SinkConfig,
msgs: Arc<ArrayQueue<Msg>>,
garbage: Arc<ArrayQueue<Garbage>>,
shared: Arc<Shared>,
endpoints: BTreeMap<String, Endpoint>,
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>,
}
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>,
}
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,
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 {
pub fn config(&self) -> SinkConfig {
self.config
}
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()
}
pub fn add_source(&mut self, id: &str, render: RenderFn) -> Result<(), RouterError> {
self.add(id, EndpointKind::Source, Body::Render(render))
}
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))
}
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))
}
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) })
}
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(())
}
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())
}
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)
}
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)
}
pub fn routes(&self) -> &[Route] {
&self.routes
}
pub fn endpoints(&self) -> impl Iterator<Item = (&str, EndpointKind)> {
self.endpoints.iter().map(|(id, e)| (id.as_str(), e.kind))
}
pub fn kind(&self, id: &str) -> Option<EndpointKind> {
self.endpoints.get(id).map(|e| e.kind)
}
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()
}
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()
}
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()
}
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)))
}
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(|_| ())
}
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) {
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));
}
}
}
}
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);
}
}
}
}
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);
}
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;
}
}
}