Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ir/src/graph.rs3//! Description: Audio DSP IR — the typed mixing graph derived from a Program for one sample4//! rate: sources, inserts, faders, sends, buses, latency compensation, master, output.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::music::EffectSpec;10use serde::{Deserialize, Serialize};11use std::collections::BTreeMap;1213pub type NodeId = u32;1415/// Who owns a strip of the mixer.16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]17#[serde(tag = "kind", content = "id", rename_all = "snake_case")]18pub enum Strip {19 Track(u32),20 Bus(u32),21 Master,22}2324#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]25#[serde(tag = "op", rename_all = "snake_case")]26pub enum NodeKind {27 /// Voices of an instrument track rendered to stereo. No input.28 Instrument { track: u32 },29 /// Audio clips of an audio track rendered to stereo. No input.30 AudioClips { track: u32 },31 /// One insert effect; `index` is its position in the strip's chain.32 Effect { strip: Strip, index: u32, spec: EffectSpec },33 /// Fader (dB, smoothed), mute and pan (constant-power, -3 dB centre) of a strip.34 Fader { strip: Strip },35 /// Send tap: scales its input by `gain_db` towards a bus.36 Send { from: Strip, to_bus: u32, gain_db: f64, pre_fader: bool },37 /// Sums all its inputs (input of a bus or of the master).38 Sum { strip: Strip },39 /// Pure delay inserted by the compiler to align parallel paths.40 LatencyDelay { samples: u32 },41 /// Safety limiter of the master: look-ahead, sample-peak ceiling (inter-sample peaks are42 /// measured by the analysis, not limited). The node's `latency` is its look-ahead.43 Limiter { ceiling_db: f64 },44 /// Final stereo output. Exactly one per graph.45 Output,46}4748#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]49pub struct DspNode {50 pub id: NodeId,51 pub kind: NodeKind,52 pub channels_in: u8,53 pub channels_out: u8,54 /// Latency introduced by this node itself, in samples at the graph's sample rate.55 pub latency: u32,56 /// Latency accumulated from the sources to this node's output (after compensation,57 /// all inputs of a `Sum` have the same value).58 pub total_latency: u32,59}6061#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]62pub struct Edge {63 pub from: NodeId,64 pub to: NodeId,65}6667/// The mixing graph for one sample rate. Invariants (see [`DspGraph::validate`]): acyclic,68/// `order` is a topological order containing every live node once, one `Output`, every non-source69/// node has an input, every edge joins existing nodes with matching channel counts.70#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]71pub struct DspGraph {72 pub sample_rate: u32,73 pub nodes: Vec<DspNode>,74 pub edges: Vec<Edge>,75 pub order: Vec<NodeId>,76 pub output: NodeId,77 /// Latency of the whole graph, reported to the host and used to align exports.78 pub total_latency: u32,79}8081impl DspGraph {82 pub fn node(&self, id: NodeId) -> Option<&DspNode> {83 self.nodes.get(id as usize).filter(|n| n.id == id)84 }8586 pub fn inputs_of(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {87 self.edges.iter().filter(move |e| e.to == id).map(|e| e.from)88 }8990 /// Kahn topological sort. Ties are broken by ascending node id, so the order is deterministic.91 /// Returns the ids on a cycle as the error.92 pub fn topological_order(nodes: &[DspNode], edges: &[Edge]) -> Result<Vec<NodeId>, Vec<NodeId>> {93 let mut indeg: BTreeMap<NodeId, usize> = nodes.iter().map(|n| (n.id, 0)).collect();94 for e in edges {95 if let Some(d) = indeg.get_mut(&e.to) {96 *d += 1;97 }98 }99 let mut ready: std::collections::BTreeSet<NodeId> = indeg.iter().filter(|(_, d)| **d == 0).map(|(id, _)| *id).collect();100 let mut order = Vec::with_capacity(nodes.len());101 while let Some(&id) = ready.iter().next() {102 ready.remove(&id);103 order.push(id);104 for e in edges.iter().filter(|e| e.from == id) {105 if let Some(d) = indeg.get_mut(&e.to) {106 *d -= 1;107 if *d == 0 {108 ready.insert(e.to);109 }110 }111 }112 }113 if order.len() == nodes.len() {114 Ok(order)115 } else {116 Err(indeg.into_iter().filter(|(id, _)| !order.contains(id)).map(|(id, _)| id).collect())117 }118 }119120 pub fn validate(&self) -> Result<(), String> {121 for (i, n) in self.nodes.iter().enumerate() {122 if n.id as usize != i {123 return Err(format!("node at index {i} has id {}", n.id));124 }125 }126 let count = self.nodes.len() as u32;127 for e in &self.edges {128 if e.from >= count || e.to >= count {129 return Err("edge references a missing node".into());130 }131 let (a, b) = (&self.nodes[e.from as usize], &self.nodes[e.to as usize]);132 if a.channels_out != b.channels_in {133 return Err(format!("channel mismatch on edge {} -> {}: {} vs {}", e.from, e.to, a.channels_out, b.channels_in));134 }135 }136 let outputs = self.nodes.iter().filter(|n| matches!(n.kind, NodeKind::Output)).count();137 if outputs != 1 {138 return Err(format!("graph has {outputs} output nodes, expected 1"));139 }140 if !matches!(self.node(self.output).map(|n| &n.kind), Some(NodeKind::Output)) {141 return Err("graph output id does not designate the Output node".into());142 }143 for n in &self.nodes {144 let is_source = matches!(n.kind, NodeKind::Instrument { .. } | NodeKind::AudioClips { .. } | NodeKind::Sum { .. });145 if !is_source && self.inputs_of(n.id).next().is_none() {146 return Err(format!("node {} has no input", n.id));147 }148 let single = !matches!(n.kind, NodeKind::Sum { .. } | NodeKind::Instrument { .. } | NodeKind::AudioClips { .. });149 if single && self.inputs_of(n.id).count() > 1 {150 return Err(format!("node {} has several inputs but is not a Sum", n.id));151 }152 }153 let expect = Self::topological_order(&self.nodes, &self.edges).map_err(|c| format!("graph has a cycle through nodes {c:?}"))?;154 if expect.len() != self.order.len() {155 return Err("order does not contain every node".into());156 }157 let mut pos = vec![usize::MAX; self.nodes.len()];158 for (i, id) in self.order.iter().enumerate() {159 if *id >= count || pos[*id as usize] != usize::MAX {160 return Err("order contains an invalid or repeated node".into());161 }162 pos[*id as usize] = i;163 }164 for e in &self.edges {165 if pos[e.from as usize] >= pos[e.to as usize] {166 return Err("order is not topological".into());167 }168 }169 for n in &self.nodes {170 if matches!(n.kind, NodeKind::Sum { .. }) {171 let mut lat = self.inputs_of(n.id).map(|i| self.nodes[i as usize].total_latency);172 if let Some(first) = lat.next() {173 if lat.any(|l| l != first) {174 return Err(format!("inputs of sum node {} are not latency-aligned", n.id));175 }176 }177 }178 }179 Ok(())180 }181}182183#[cfg(test)]184mod tests {185 use super::*;186187 fn n(id: u32, kind: NodeKind, cin: u8) -> DspNode {188 DspNode { id, kind, channels_in: cin, channels_out: 2, latency: 0, total_latency: 0 }189 }190191 #[test]192 fn validates_a_minimal_graph_and_detects_cycles() {193 let nodes = vec![194 n(0, NodeKind::Instrument { track: 0 }, 0),195 n(1, NodeKind::Fader { strip: Strip::Track(0) }, 2),196 n(2, NodeKind::Sum { strip: Strip::Master }, 2),197 n(3, NodeKind::Output, 2),198 ];199 let edges = vec![Edge { from: 0, to: 1 }, Edge { from: 1, to: 2 }, Edge { from: 2, to: 3 }];200 let order = DspGraph::topological_order(&nodes, &edges).unwrap();201 assert_eq!(order, vec![0, 1, 2, 3]);202 let mut g = DspGraph { sample_rate: 48_000, nodes, edges, order, output: 3, total_latency: 0 };203 g.validate().unwrap();204 g.edges.push(Edge { from: 2, to: 1 });205 assert!(DspGraph::topological_order(&g.nodes, &g.edges).is_err());206 assert!(g.validate().is_err());207 }208}209