Repository Public
1//! ORIX Sonata2//! File: crates/sonata-compiler/src/graph.rs3//! Description: Builds the DSP IR (mixing graph) of a Program for one sample rate: strips,4//! inserts, faders, sends, buses, latency compensation, master, limiter, output.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_ir::*;10use std::collections::BTreeMap;1112/// Options of the graph builder.13#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]14pub struct GraphOptions {15 /// Remove strips that cannot be heard: muted tracks and buses, and, when at least one16 /// track is soloed, every track that is not. Use for offline bounces. Leave off for live17 /// playback so the mixer can un-mute without a new graph (the fader nodes then mute).18 pub prune_silent: bool,19}2021struct Builder {22 nodes: Vec<DspNode>,23 edges: Vec<Edge>,24}2526impl Builder {27 fn node(&mut self, kind: NodeKind, channels_in: u8, latency: u32) -> NodeId {28 let id = self.nodes.len() as NodeId;29 self.nodes.push(DspNode { id, kind, channels_in, channels_out: 2, latency, total_latency: 0 });30 id31 }32 fn edge(&mut self, from: NodeId, to: NodeId) {33 self.edges.push(Edge { from, to });34 }35 /// Inserts → returns the pre-fader point.36 fn inserts(&mut self, mut at: NodeId, strip: Strip, effects: &[EffectSpec], registry: &Registry, rate: u32) -> NodeId {37 for (index, spec) in effects.iter().enumerate() {38 let latency = registry.effect(&spec.kind).map(|d| d.latency.at(rate)).unwrap_or(0);39 let n = self.node(NodeKind::Effect { strip, index: index as u32, spec: spec.clone() }, 2, latency);40 self.edge(at, n);41 at = n;42 }43 at44 }45}4647/// Buses that can reach themselves through outputs or sends.48fn bus_cycle(program: &Program) -> Option<Vec<u32>> {49 let n = program.buses.len();50 let targets = |b: &Bus| -> Vec<u32> {51 let mut t: Vec<u32> = b.sends.iter().map(|s| s.bus).collect();52 if let Output::Bus(o) = b.output {53 t.push(o);54 }55 t56 };57 // 0 = unvisited, 1 = on the stack, 2 = done.58 fn visit(i: usize, program: &Program, targets: &dyn Fn(&Bus) -> Vec<u32>, state: &mut [u8], stack: &mut Vec<u32>) -> Option<Vec<u32>> {59 state[i] = 1;60 stack.push(i as u32);61 for t in targets(&program.buses[i]) {62 let t = t as usize;63 if t >= state.len() {64 continue;65 }66 if state[t] == 1 {67 let from = stack.iter().position(|x| *x as usize == t).unwrap_or(0);68 let mut cycle = stack[from..].to_vec();69 cycle.push(t as u32);70 return Some(cycle);71 }72 if state[t] == 0 {73 if let Some(c) = visit(t, program, targets, state, stack) {74 return Some(c);75 }76 }77 }78 stack.pop();79 state[i] = 2;80 None81 }82 let mut state = vec![0u8; n];83 for i in 0..n {84 if state[i] == 0 {85 if let Some(c) = visit(i, program, &targets, &mut state, &mut Vec::new()) {86 return Some(c);87 }88 }89 }90 None91}9293/// Builds the mixing graph of `program` at `sample_rate`.94///95/// Rules (documented in `Documentation/spec/sonata-language.md`, "Mixing graph"):96/// * a track is `source → inserts → fader → output`, with sends tapped before the fader97/// (`pre`) or after it;98/// * a bus sums what it receives, then `inserts → fader → output`;99/// * the master sums, then `inserts → fader → limiter (if peak_limit) → output`;100/// * a bus that receives nothing is not built (it would only process silence);101/// * parallel paths reaching a sum are aligned with `LatencyDelay` nodes, so an effect with102/// latency never smears the mix; the graph reports its total latency;103/// * node ids follow declaration order, so the same Program always gives the same graph.104pub fn build_graph_with(program: &Program, sample_rate: u32, registry: &Registry, options: GraphOptions) -> Result<DspGraph, Vec<Diagnostic>> {105 let mut diags = Vec::new();106 let bus_count = program.buses.len() as u32;107 let valid_bus = |id: u32| id < bus_count;108 for t in &program.tracks {109 if t.sends.iter().any(|s| !valid_bus(s.bus)) || matches!(t.output, Output::Bus(b) if !valid_bus(b)) {110 diags.push(Diagnostic::error("G5010", t.span, format!("track '{}' is routed to a bus that does not exist", t.name)));111 }112 }113 for b in &program.buses {114 if b.sends.iter().any(|s| !valid_bus(s.bus)) || matches!(b.output, Output::Bus(o) if !valid_bus(o)) {115 diags.push(Diagnostic::error("G5010", b.span, format!("bus '{}' is routed to a bus that does not exist", b.name)));116 }117 }118 if !diags.is_empty() {119 return Err(diags);120 }121 if let Some(cycle) = bus_cycle(program) {122 let names: Vec<&str> = cycle.iter().map(|i| program.buses[*i as usize].name.as_str()).collect();123 let first = &program.buses[cycle[0] as usize];124 let mut d = Diagnostic::error("G5001", first.span, format!("bus routing forms a loop: {}", names.join(" → ")))125 .with_suggestion("audio buses cannot feed back into themselves; remove one of the sends or outputs");126 for i in &cycle[1..cycle.len() - 1] {127 d = d.with_related(program.buses[*i as usize].span, "part of the loop");128 }129 return Err(vec![d]);130 }131132 let any_solo = program.tracks.iter().any(|t| t.solo);133 let track_live = |t: &Track| !options.prune_silent || (!t.mute && (!any_solo || t.solo));134 // A bus is live when something live reaches it (and it is not pruned as muted).135 let mut bus_live = vec![false; program.buses.len()];136 let feeds = |sends: &[Send], output: Output| -> Vec<u32> {137 let mut v: Vec<u32> = sends.iter().map(|s| s.bus).collect();138 if let Output::Bus(b) = output {139 v.push(b);140 }141 v142 };143 for t in program.tracks.iter().filter(|t| track_live(t)) {144 for b in feeds(&t.sends, t.output) {145 bus_live[b as usize] = true;146 }147 }148 // Propagate through bus-to-bus routing (acyclic, so `len` passes suffice).149 for _ in 0..program.buses.len() {150 for (i, b) in program.buses.iter().enumerate() {151 if bus_live[i] && !(options.prune_silent && b.mute) {152 for target in feeds(&b.sends, b.output) {153 bus_live[target as usize] = true;154 }155 }156 }157 }158 for (i, b) in program.buses.iter().enumerate() {159 if options.prune_silent && b.mute {160 bus_live[i] = false;161 }162 }163164 let mut g = Builder { nodes: Vec::new(), edges: Vec::new() };165 let master_sum = g.node(NodeKind::Sum { strip: Strip::Master }, 2, 0);166 let bus_sums: Vec<Option<NodeId>> =167 program.buses.iter().enumerate().map(|(i, b)| if bus_live[i] { Some(g.node(NodeKind::Sum { strip: Strip::Bus(b.id) }, 2, 0)) } else { None }).collect();168 let route = |g: &mut Builder, strip: Strip, pre: NodeId, post: NodeId, sends: &[Send], output: Output| {169 for s in sends {170 if let Some(Some(sum)) = bus_sums.get(s.bus as usize) {171 let n = g.node(NodeKind::Send { from: strip, to_bus: s.bus, gain_db: s.gain_db, pre_fader: s.pre_fader }, 2, 0);172 g.edge(if s.pre_fader { pre } else { post }, n);173 g.edge(n, *sum);174 }175 }176 match output {177 Output::Master => g.edge(post, master_sum),178 Output::Bus(b) => {179 if let Some(Some(sum)) = bus_sums.get(b as usize) {180 g.edge(post, *sum);181 }182 }183 }184 };185 for t in program.tracks.iter().filter(|t| track_live(t)) {186 let strip = Strip::Track(t.id);187 let source = match t.kind {188 TrackKind::Instrument => g.node(NodeKind::Instrument { track: t.id }, 0, 0),189 TrackKind::Audio => g.node(NodeKind::AudioClips { track: t.id }, 0, 0),190 };191 let pre = g.inserts(source, strip, &t.effects, registry, sample_rate);192 let post = g.node(NodeKind::Fader { strip }, 2, 0);193 g.edge(pre, post);194 route(&mut g, strip, pre, post, &t.sends, t.output);195 }196 for (i, b) in program.buses.iter().enumerate() {197 let Some(sum) = bus_sums[i] else { continue };198 let strip = Strip::Bus(b.id);199 let pre = g.inserts(sum, strip, &b.effects, registry, sample_rate);200 let post = g.node(NodeKind::Fader { strip }, 2, 0);201 g.edge(pre, post);202 route(&mut g, strip, pre, post, &b.sends, b.output);203 }204 let pre = g.inserts(master_sum, Strip::Master, &program.master.effects, registry, sample_rate);205 let mut last = g.node(NodeKind::Fader { strip: Strip::Master }, 2, 0);206 g.edge(pre, last);207 if let Some(ceiling_db) = program.master.peak_limit_db {208 let latency = registry.effect("limiter").map(|d| d.latency.at(sample_rate)).unwrap_or(0);209 let lim = g.node(NodeKind::Limiter { ceiling_db }, 2, latency);210 g.edge(last, lim);211 last = lim;212 }213 let output = g.node(NodeKind::Output, 2, 0);214 g.edge(last, output);215216 // Latency compensation: walk in topological order; at every sum, delay the early inputs.217 let order = match DspGraph::topological_order(&g.nodes, &g.edges) {218 Ok(o) => o,219 Err(cycle) => {220 return Err(vec![Diagnostic::error("G5099", Span::default(), format!("internal error: the mixing graph has a cycle through nodes {cycle:?}"))])221 }222 };223 let mut total: BTreeMap<NodeId, u32> = BTreeMap::new();224 for id in order {225 let inputs: Vec<(usize, NodeId)> = g.edges.iter().enumerate().filter(|(_, e)| e.to == id).map(|(i, e)| (i, e.from)).collect();226 let max_in = inputs.iter().map(|(_, from)| total.get(from).copied().unwrap_or(0)).max().unwrap_or(0);227 if matches!(g.nodes[id as usize].kind, NodeKind::Sum { .. }) {228 for (edge_index, from) in inputs {229 let have = total.get(&from).copied().unwrap_or(0);230 if have < max_in {231 let d = g.node(NodeKind::LatencyDelay { samples: max_in - have }, 2, max_in - have);232 g.edges[edge_index].to = d;233 g.edge(d, id);234 total.insert(d, max_in);235 }236 }237 }238 total.insert(id, max_in + g.nodes[id as usize].latency);239 }240 for n in g.nodes.iter_mut() {241 n.total_latency = total.get(&n.id).copied().unwrap_or(0);242 }243 let order = match DspGraph::topological_order(&g.nodes, &g.edges) {244 Ok(o) => o,245 Err(cycle) => {246 return Err(vec![Diagnostic::error("G5099", Span::default(), format!("internal error: the mixing graph has a cycle through nodes {cycle:?}"))])247 }248 };249 let total_latency = g.nodes[output as usize].total_latency;250 let graph = DspGraph { sample_rate, nodes: g.nodes, edges: g.edges, order, output, total_latency };251 if let Err(e) = graph.validate() {252 return Err(vec![Diagnostic::error("G5099", Span::default(), format!("internal error: the mixing graph is invalid: {e}"))]);253 }254 Ok(graph)255}256