Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ir/src/patch.rs3//! Description: Patch graphs — the typed per-voice DSP graph written in `graph { }` blocks and4//! edited in Instrument Lab. Executed by the `patch` engine of sonata-instruments.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::diag::Span;10use serde::{Deserialize, Serialize};11use std::collections::BTreeMap;1213/// Rate of a signal inside a patch.14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]15#[serde(rename_all = "snake_case")]16pub enum Rate {17 /// One value per sample (type `Signal`).18 Audio,19 /// One value per control block (type `ControlSignal`).20 Control,21}2223/// Per-note values a patch can read.24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]25#[serde(rename_all = "snake_case")]26pub enum NoteInput {27 /// Fundamental frequency in Hz, pitch bend included.28 Freq,29 /// MIDI pitch (fractional).30 Pitch,31 /// Velocity in [0, 1].32 Velocity,33 /// 1 while the note is held, 0 after note-off.34 Gate,35 /// Seconds since note-on.36 Time,37}3839/// What feeds an input port.40#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]41#[serde(tag = "from", content = "value", rename_all = "snake_case")]42pub enum PatchInput {43 Const(f64),44 /// Output of the node at this index in `PatchSpec::nodes`.45 Node(u32),46 Note(NoteInput),47}4849/// One node. `kind` is a registry patch-node kind (`sine`, `saw`, `adsr`, `lowpass`, `add`,50/// `mul`, `delay`, ...). Ports not listed in `inputs` take the registry default.51#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]52pub struct PatchNode {53 /// Name given in source (`node osc1 = ...`), or a generated name for sub-expressions (`_3`).54 pub name: String,55 pub kind: String,56 pub inputs: BTreeMap<String, PatchInput>,57 pub rate: Rate,58 pub span: Span,59}6061/// A validated patch. Invariants established by the compiler:62/// * every `PatchInput::Node(i)` is in range;63/// * `nodes` is in evaluation order: a node only reads earlier nodes, **except** `delay` nodes,64/// whose `in` port may read any node (a feedback loop is causal only through a delay);65/// * `output` is in range and audio rate.66#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]67pub struct PatchSpec {68 pub nodes: Vec<PatchNode>,69 pub output: u32,70 /// Index of the node whose reaching zero after note-off ends the voice (an envelope);71 /// `None` means the voice ends after a fixed release time given by the engine.72 pub amp_envelope: Option<u32>,73}7475impl PatchSpec {76 /// Checks the structural invariants; returns a description of the first violation.77 pub fn validate(&self) -> Result<(), String> {78 let n = self.nodes.len() as u32;79 if n == 0 {80 return Err("patch has no node".into());81 }82 if self.output >= n {83 return Err("patch output is out of range".into());84 }85 if self.nodes[self.output as usize].rate != Rate::Audio {86 return Err("patch output must be an audio-rate signal".into());87 }88 if let Some(e) = self.amp_envelope {89 if e >= n {90 return Err("amp envelope is out of range".into());91 }92 }93 for (i, node) in self.nodes.iter().enumerate() {94 for (port, input) in &node.inputs {95 if let PatchInput::Node(j) = input {96 if *j >= n {97 return Err(format!("node '{}' port '{}' reads a missing node", node.name, port));98 }99 let feedback_ok = node.kind == "delay" && port == "in";100 if *j as usize >= i && !feedback_ok {101 return Err(format!("node '{}' port '{}' forms a loop without a delay", node.name, port));102 }103 }104 }105 }106 Ok(())107 }108}109110#[cfg(test)]111mod tests {112 use super::*;113114 fn node(name: &str, kind: &str, inputs: &[(&str, PatchInput)]) -> PatchNode {115 PatchNode {116 name: name.into(),117 kind: kind.into(),118 inputs: inputs.iter().cloned().map(|(k, v)| (k.to_string(), v)).collect(),119 rate: Rate::Audio,120 span: Span::default(),121 }122 }123124 #[test]125 fn rejects_delay_free_loop_and_accepts_delayed_feedback() {126 let looped = PatchSpec {127 nodes: vec![node("a", "add", &[("a", PatchInput::Node(1))]), node("b", "gain", &[("in", PatchInput::Node(0))])],128 output: 1,129 amp_envelope: None,130 };131 assert!(looped.validate().unwrap_err().contains("loop without a delay"));132 let ok = PatchSpec {133 nodes: vec![134 node("d", "delay", &[("in", PatchInput::Node(1)), ("time", PatchInput::Const(0.01))]),135 node("mix", "add", &[("a", PatchInput::Node(0)), ("b", PatchInput::Note(NoteInput::Gate))]),136 ],137 output: 1,138 amp_envelope: None,139 };140 ok.validate().unwrap();141 }142}143