Give metatracks explicit node graphs

This commit is contained in:
Skyler Lehmkuhl
2026-03-10 20:20:46 -04:00
parent f9b62bb090
commit 7a3f522735
16 changed files with 1381 additions and 385 deletions
+114 -2
View File
@@ -193,6 +193,15 @@ impl AudioGraph {
self.graph.add_edge(from, to, Connection { from_port, to_port });
self.topo_cache = None;
// Auto-grow MixerNode: always keep one spare port beyond the connected count
let n_incoming = self.graph.edges_directed(to, petgraph::Direction::Incoming).count();
if let Some(graph_node) = self.graph.node_weight_mut(to) {
use crate::audio::node_graph::nodes::MixerNode;
if let Some(mixer) = graph_node.node.as_any_mut().downcast_mut::<MixerNode>() {
mixer.ensure_min_ports(n_incoming + 1);
}
}
Ok(())
}
@@ -204,12 +213,24 @@ impl AudioGraph {
to: NodeIndex,
to_port: usize,
) {
// Find and remove the edge
let mut did_remove = false;
if let Some(edge_idx) = self.graph.find_edge(from, to) {
let conn = &self.graph[edge_idx];
if conn.from_port == from_port && conn.to_port == to_port {
self.graph.remove_edge(edge_idx);
self.topo_cache = None;
did_remove = true;
}
}
// Shrink MixerNode back to n_remaining + 1 spare after a disconnect
if did_remove {
let n_remaining = self.graph.edges_directed(to, petgraph::Direction::Incoming).count();
if let Some(graph_node) = self.graph.node_weight_mut(to) {
use crate::audio::node_graph::nodes::MixerNode;
if let Some(mixer) = graph_node.node.as_any_mut().downcast_mut::<MixerNode>() {
mixer.resize(n_remaining + 1);
}
}
}
}
@@ -716,6 +737,50 @@ impl AudioGraph {
self.graph.node_indices()
}
/// Reallocate a node's output buffers to match its current port list.
///
/// Must be called after `SubtrackInputsNode::update_subtracks` changes the port count,
/// since `GraphNode.output_buffers` was allocated at `add_node` time.
pub fn reallocate_node_output_buffers(&mut self, idx: NodeIndex, buffer_size: usize) {
if let Some(graph_node) = self.graph.node_weight_mut(idx) {
let outputs = graph_node.node.outputs();
graph_node.output_buffers.clear();
for port in outputs.iter() {
match port.signal_type {
super::types::SignalType::Audio => graph_node.output_buffers.push(vec![0.0; buffer_size * 2]),
super::types::SignalType::CV => graph_node.output_buffers.push(vec![0.0; buffer_size]),
super::types::SignalType::Midi => graph_node.output_buffers.push(vec![]),
}
}
self.topo_cache = None;
}
}
/// Remove all edges going OUT of a specific output port of a node.
pub fn disconnect_output_port(&mut self, node: NodeIndex, port: usize) {
let edges: Vec<_> = self.graph
.edges_directed(node, petgraph::Direction::Outgoing)
.filter(|e| e.weight().from_port == port)
.map(|e| e.id())
.collect();
for edge_id in edges {
self.graph.remove_edge(edge_id);
}
self.topo_cache = None;
}
/// Remove all edges going INTO a node (all input connections).
pub fn disconnect_all_inputs(&mut self, node: NodeIndex) {
let edges: Vec<_> = self.graph
.edges_directed(node, petgraph::Direction::Incoming)
.map(|e| e.id())
.collect();
for edge_id in edges {
self.graph.remove_edge(edge_id);
}
self.topo_cache = None;
}
/// Get all connections
pub fn connections(&self) -> impl Iterator<Item = (NodeIndex, NodeIndex, &Connection)> + '_ {
self.graph.edge_references().map(|e| (e.source(), e.target(), e.weight()))
@@ -787,7 +852,7 @@ impl AudioGraph {
/// Serialize the graph to a preset
pub fn to_preset(&self, name: impl Into<String>) -> crate::audio::node_graph::preset::GraphPreset {
use crate::audio::node_graph::preset::{GraphPreset, SerializedConnection, SerializedNode};
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
use crate::audio::node_graph::nodes::{VoiceAllocatorNode, MixerNode, SubtrackInputsNode};
let mut preset = GraphPreset::new(name);
@@ -805,6 +870,19 @@ impl AudioGraph {
serialized.set_parameter(param.id, value);
}
// Save port count for dynamic-port nodes so they round-trip correctly
if node.node_type() == "Mixer" {
if let Some(mixer) = node.as_any().downcast_ref::<MixerNode>() {
serialized.num_ports = Some(mixer.num_inputs() as u32);
}
}
if node.node_type() == "SubtrackInputs" {
if let Some(si) = node.as_any().downcast_ref::<SubtrackInputsNode>() {
serialized.num_ports = Some(si.num_subtracks() as u32);
serialized.port_names = si.subtracks().iter().map(|(_, name)| name.clone()).collect();
}
}
// For VoiceAllocator nodes, serialize the template graph
if node.node_type() == "VoiceAllocator" {
// Downcast using safe Any trait
@@ -1002,12 +1080,46 @@ impl AudioGraph {
let mut graph = Self::new(sample_rate, buffer_size);
let mut index_map: HashMap<u32, NodeIndex> = HashMap::new();
// Pre-pass: compute required min port count for dynamic-port nodes from the connection list.
// This ensures old presets (without num_ports) still size correctly regardless of
// connection-restoration order.
let mut required_ports: HashMap<u32, usize> = HashMap::new();
for conn in &preset.connections {
let entry = required_ports.entry(conn.to_node).or_insert(0);
*entry = (*entry).max(conn.to_port + 2); // port N + 1 spare
}
// Create all nodes
for serialized_node in &preset.nodes {
// Create the node based on type
let mut node = crate::audio::node_graph::nodes::create_node(&serialized_node.node_type, sample_rate, buffer_size)
.ok_or_else(|| format!("Unknown node type: {}", serialized_node.node_type))?;
// Pre-size dynamic-port nodes before graph.add_node() so output buffers are
// allocated at the correct size. num_ports takes priority; fall back to
// connection-count inference so old presets without num_ports still work.
if serialized_node.node_type == "Mixer" {
use crate::audio::node_graph::nodes::MixerNode;
if let Some(mixer) = node.as_any_mut().downcast_mut::<MixerNode>() {
let from_conns = required_ports.get(&serialized_node.id).copied().unwrap_or(1);
let target = serialized_node.num_ports.map(|n| n as usize).unwrap_or(0).max(from_conns).max(1);
mixer.resize(target);
}
}
if serialized_node.node_type == "SubtrackInputs" {
use crate::audio::node_graph::nodes::SubtrackInputsNode;
if let Some(si) = node.as_any_mut().downcast_mut::<SubtrackInputsNode>() {
let from_conns = required_ports.get(&serialized_node.id).copied().unwrap_or(0);
let target = serialized_node.num_ports.map(|n| n as usize).unwrap_or(0).max(from_conns);
if target > 0 {
let subtracks = (0..target)
.map(|i| (0u32, format!("Subtrack {}", i + 1)))
.collect();
si.update_subtracks(subtracks, buffer_size);
}
}
}
// VoiceAllocator needs its template graph deserialized and set
if serialized_node.node_type == "VoiceAllocator" {
if let Some(ref template_preset) = serialized_node.template_graph {
+67 -56
View File
@@ -1,48 +1,74 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_GAIN_1: u32 = 0;
const PARAM_GAIN_2: u32 = 1;
const PARAM_GAIN_3: u32 = 2;
const PARAM_GAIN_4: u32 = 3;
/// Mixer node - combines multiple audio inputs with independent gain controls
/// Mixer node — combines N audio inputs with independent gain controls.
///
/// The number of input ports is dynamic: one spare unconnected port is always present
/// beyond however many are currently wired, so users can keep patching in without
/// manually adding inputs. Port count is managed by `AudioGraph::connect` /
/// `AudioGraph::disconnect` calling `ensure_min_ports` / `resize`.
///
/// Gain values are stored separately from the port list so they survive resize
/// operations and can be set via `set_parameter` before the port is visible.
pub struct MixerNode {
name: String,
gains: [f32; 4],
/// Displayed input ports. Length = num_ports (connected + 1 spare).
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
/// Per-channel gains, indexed by port. May be longer than `inputs` if gains
/// were set before ports were created (handled gracefully).
gains: Vec<f32>,
/// Mirrored parameter list so `parameters()` stays in sync with `inputs`.
parameters: Vec<Parameter>,
}
impl MixerNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let mut node = Self {
name: name.into(),
inputs: Vec::new(),
outputs: vec![NodePort::new("Mixed Out", SignalType::Audio, 0)],
gains: Vec::new(),
parameters: Vec::new(),
};
node.resize(1); // start with one spare input
node
}
let inputs = vec![
NodePort::new("Input 1", SignalType::Audio, 0),
NodePort::new("Input 2", SignalType::Audio, 1),
NodePort::new("Input 3", SignalType::Audio, 2),
NodePort::new("Input 4", SignalType::Audio, 3),
];
/// Return the current number of input ports (connected + 1 spare).
pub fn num_inputs(&self) -> usize {
self.inputs.len()
}
let outputs = vec![
NodePort::new("Mixed Out", SignalType::Audio, 0),
];
/// Set the exact number of input ports.
///
/// Existing gain values are preserved. Truncates spare gains when shrinking,
/// but gain slots that have already been written survive a grow-shrink-grow cycle.
pub fn resize(&mut self, n: usize) {
let n = n.max(1); // always at least one spare
let parameters = vec![
Parameter::new(PARAM_GAIN_1, "Gain 1", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_2, "Gain 2", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_3, "Gain 3", 0.0, 2.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_GAIN_4, "Gain 4", 0.0, 2.0, 1.0, ParameterUnit::Generic),
];
self.inputs = (0..n)
.map(|i| NodePort::new(format!("Input {}", i + 1).as_str(), SignalType::Audio, i))
.collect();
Self {
name,
gains: [1.0, 1.0, 1.0, 1.0],
inputs,
outputs,
parameters,
// Extend gains with 1.0 for new slots; preserve existing values.
if self.gains.len() < n {
self.gains.resize(n, 1.0);
}
self.parameters = (0..n)
.map(|i| {
Parameter::new(i as u32, format!("Gain {}", i + 1).as_str(), 0.0, 2.0, 1.0, ParameterUnit::Generic)
})
.collect();
}
/// Ensure at least `n` input ports exist, growing if needed but never shrinking.
///
/// Called by `AudioGraph::connect` after adding a connection.
pub fn ensure_min_ports(&mut self, n: usize) {
if n > self.inputs.len() {
self.resize(n);
}
}
}
@@ -65,23 +91,17 @@ impl AudioNode for MixerNode {
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_GAIN_1 => self.gains[0] = value.clamp(0.0, 2.0),
PARAM_GAIN_2 => self.gains[1] = value.clamp(0.0, 2.0),
PARAM_GAIN_3 => self.gains[2] = value.clamp(0.0, 2.0),
PARAM_GAIN_4 => self.gains[3] = value.clamp(0.0, 2.0),
_ => {}
let idx = id as usize;
// Extend gains if this port hasn't been created yet (e.g. loaded from preset
// before connections are restored).
if idx >= self.gains.len() {
self.gains.resize(idx + 1, 1.0);
}
self.gains[idx] = value.clamp(0.0, 2.0);
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_GAIN_1 => self.gains[0],
PARAM_GAIN_2 => self.gains[1],
PARAM_GAIN_3 => self.gains[2],
PARAM_GAIN_4 => self.gains[3],
_ => 0.0,
}
self.gains.get(id as usize).copied().unwrap_or(1.0)
}
fn process(
@@ -97,32 +117,23 @@ impl AudioNode for MixerNode {
}
let output = &mut outputs[0];
// Audio signals are stereo (interleaved L/R)
let frames = output.len() / 2;
// Clear output buffer first
output.fill(0.0);
// Mix each input with its gain
for (input_idx, input) in inputs.iter().enumerate().take(4) {
if input_idx >= self.gains.len() {
break;
}
let gain = self.gains[input_idx];
for (input_idx, input) in inputs.iter().enumerate() {
let gain = self.gains.get(input_idx).copied().unwrap_or(1.0);
let input_frames = input.len() / 2;
let process_frames = frames.min(input_frames);
for frame in 0..process_frames {
output[frame * 2] += input[frame * 2] * gain; // Left
output[frame * 2] += input[frame * 2] * gain; // Left
output[frame * 2 + 1] += input[frame * 2 + 1] * gain; // Right
}
}
}
fn reset(&mut self) {
// No state to reset
// No per-frame state
}
fn node_type(&self) -> &str {
@@ -136,9 +147,9 @@ impl AudioNode for MixerNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
gains: self.gains,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
gains: self.gains.clone(),
parameters: self.parameters.clone(),
})
}
@@ -1,6 +1,7 @@
mod amp_sim;
pub mod bundled_models;
mod adsr;
mod subtrack_inputs;
mod arpeggiator;
mod audio_input;
mod audio_to_cv;
@@ -96,6 +97,7 @@ pub use vibrato::VibratoNode;
pub use vocoder::VocoderNode;
pub use voice_allocator::VoiceAllocatorNode;
pub use wavetable_oscillator::WavetableOscillatorNode;
pub use subtrack_inputs::SubtrackInputsNode;
/// Create a node instance by type name string.
///
@@ -152,6 +154,7 @@ pub fn create_node(node_type: &str, sample_rate: u32, buffer_size: usize) -> Opt
"Vibrato" => Box::new(VibratoNode::new("Vibrato")),
"AmpSim" => Box::new(AmpSimNode::new("Amp Sim")),
"AudioOutput" => Box::new(AudioOutputNode::new("Output")),
"SubtrackInputs" => Box::new(SubtrackInputsNode::new("Subtrack Inputs", vec![])),
_ => return None,
})
}
@@ -0,0 +1,177 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
use crate::audio::track::TrackId;
/// Subtrack inputs node for metatracks.
///
/// Exposes one output port per child track so users can route individual subtracks
/// independently in the mixing graph (e.g., for sidechain effects).
///
/// Audio is injected into pre-allocated per-slot buffers by the render system before
/// the graph is processed — no heap allocation occurs during audio rendering.
pub struct SubtrackInputsNode {
name: String,
/// Ordered list of (TrackId, display_name) for each subtrack slot.
/// TrackId is used by the render system to match the right buffer to the right slot.
subtracks: Vec<(TrackId, String)>,
/// Output port descriptors — rebuilt whenever subtracks changes.
outputs: Vec<NodePort>,
/// Pre-allocated audio buffers, one per subtrack slot (stereo interleaved, length = buffer_size * 2).
/// Filled by `inject_subtrack_audio` before graph processing; no alloc per frame.
buffers: Vec<Vec<f32>>,
/// The buffer size this node was last sized for.
buffer_size: usize,
}
impl SubtrackInputsNode {
pub fn new(name: impl Into<String>, subtracks: Vec<(TrackId, String)>) -> Self {
let outputs = Self::build_outputs(&subtracks);
let n = subtracks.len();
Self {
name: name.into(),
subtracks,
outputs,
buffers: vec![Vec::new(); n],
buffer_size: 0,
}
}
fn build_outputs(subtracks: &[(TrackId, String)]) -> Vec<NodePort> {
subtracks
.iter()
.enumerate()
.map(|(i, (_, name))| NodePort::new(name.as_str(), SignalType::Audio, i))
.collect()
}
/// Inject audio from a child track into its pre-allocated slot.
///
/// `idx` is the slot index (matching the order in `subtracks`).
/// Called by the render system once per child per frame — no allocation.
pub fn inject_subtrack_audio(&mut self, idx: usize, audio: &[f32]) {
if let Some(buf) = self.buffers.get_mut(idx) {
let len = buf.len().min(audio.len());
buf[..len].copy_from_slice(&audio[..len]);
// Zero any remaining samples if audio is shorter than the buffer
if audio.len() < buf.len() {
buf[audio.len()..].fill(0.0);
}
}
}
/// Rebuild ports and resize pre-allocated buffers.
///
/// Only reallocates when the subtrack list actually changes in size or content.
/// Pass `buffer_size` in frames (stereo buffers will be `buffer_size * 2` samples).
pub fn update_subtracks(&mut self, subtracks: Vec<(TrackId, String)>, buffer_size: usize) {
let n = subtracks.len();
self.outputs = Self::build_outputs(&subtracks);
self.subtracks = subtracks;
self.buffer_size = buffer_size;
// Resize buffers: keep existing allocations where possible
self.buffers.resize_with(n, Vec::new);
for buf in &mut self.buffers {
let target = buffer_size * 2; // stereo interleaved
if buf.len() != target {
buf.resize(target, 0.0);
}
}
}
/// Return the slot index for the given TrackId, or None if not found.
pub fn subtrack_index_for(&self, track_id: TrackId) -> Option<usize> {
self.subtracks.iter().position(|(id, _)| *id == track_id)
}
/// Return the number of subtrack slots.
pub fn num_subtracks(&self) -> usize {
self.subtracks.len()
}
/// Return the ordered subtrack list.
pub fn subtracks(&self) -> &[(TrackId, String)] {
&self.subtracks
}
}
impl AudioNode for SubtrackInputsNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
fn inputs(&self) -> &[NodePort] {
&[] // No inputs — audio is injected externally
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&[] // No user-facing parameters; port count is stored via num_ports in serialization
}
fn set_parameter(&mut self, _id: u32, _value: f32) {}
fn get_parameter(&self, _id: u32) -> f32 {
0.0
}
fn process(
&mut self,
_inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
_midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
// Copy each pre-filled buffer to its output port
for (i, output) in outputs.iter_mut().enumerate() {
if let Some(buf) = self.buffers.get(i) {
let len = output.len().min(buf.len());
if len > 0 {
output[..len].copy_from_slice(&buf[..len]);
}
if output.len() > len {
output[len..].fill(0.0);
}
} else {
output.fill(0.0);
}
}
}
fn reset(&mut self) {
for buf in &mut self.buffers {
buf.fill(0.0);
}
}
fn node_type(&self) -> &str {
"SubtrackInputs"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
subtracks: self.subtracks.clone(),
outputs: self.outputs.clone(),
// Don't clone audio buffers; fresh node starts silent
buffers: vec![vec![0.0; self.buffer_size * 2]; self.subtracks.len()],
buffer_size: self.buffer_size,
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -131,6 +131,16 @@ pub struct SerializedNode {
/// For AmpSim nodes: path to the .nam model file
#[serde(skip_serializing_if = "Option::is_none")]
pub nam_model_path: Option<String>,
/// For dynamic-port nodes (Mixer, SubtrackInputs): saved port count so ports
/// round-trip correctly through save/load independent of connection order.
#[serde(skip_serializing_if = "Option::is_none")]
pub num_ports: Option<u32>,
/// For SubtrackInputs: ordered port names (one per subtrack slot).
/// Allows the UI to display actual track names on the node's output ports.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub port_names: Vec<String>,
}
/// Serialized group definition (frontend-only visual grouping, stored opaquely by backend)
@@ -227,6 +237,8 @@ impl SerializedNode {
sample_data: None,
script_source: None,
nam_model_path: None,
num_ports: None,
port_names: Vec::new(),
}
}