use nodes for audio tracks

This commit is contained in:
Skyler Lehmkuhl
2025-11-02 06:33:10 -05:00
parent 988bbfd1a9
commit 66c4746767
11 changed files with 643 additions and 187 deletions
+157 -77
View File
@@ -1,7 +1,7 @@
use crate::audio::buffer_pool::BufferPool;
use crate::audio::clip::ClipId;
use crate::audio::midi::{MidiClip, MidiClipId, MidiEvent};
use crate::audio::node_graph::{nodes::*, InstrumentGraph};
use crate::audio::node_graph::{nodes::*, AudioGraph};
use crate::audio::pool::AudioPool;
use crate::audio::project::Project;
use crate::audio::recording::{MidiRecordingState, RecordingState};
@@ -689,12 +689,27 @@ impl Engine {
// Node graph commands
Command::GraphAddNode(track_id, node_type, x, y) => {
// Get MIDI track (graphs are only for MIDI tracks currently)
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
let graph = &mut track.instrument_graph;
{
// Create the node based on type
let node: Box<dyn crate::audio::node_graph::AudioNode> = match node_type.as_str() {
eprintln!("[DEBUG] GraphAddNode received: track_id={}, node_type={}, x={}, y={}", track_id, node_type, x, y);
// Get the track's graph (works for both MIDI and Audio tracks)
let graph = match self.project.get_track_mut(track_id) {
Some(TrackNode::Midi(track)) => {
eprintln!("[DEBUG] Found MIDI track, using instrument_graph");
Some(&mut track.instrument_graph)
},
Some(TrackNode::Audio(track)) => {
eprintln!("[DEBUG] Found Audio track, using effects_graph");
Some(&mut track.effects_graph)
},
_ => {
eprintln!("[DEBUG] Track not found or invalid type!");
None
}
};
if let Some(graph) = graph {
// Create the node based on type
let node: Box<dyn crate::audio::node_graph::AudioNode> = match node_type.as_str() {
"Oscillator" => Box::new(OscillatorNode::new("Oscillator".to_string())),
"Gain" => Box::new(GainNode::new("Gain".to_string())),
"Mixer" => Box::new(MixerNode::new("Mixer".to_string())),
@@ -729,6 +744,7 @@ impl Engine {
"MidiInput" => Box::new(MidiInputNode::new("MIDI Input".to_string())),
"MidiToCV" => Box::new(MidiToCVNode::new("MIDI→CV".to_string())),
"AudioToCV" => Box::new(AudioToCVNode::new("Audio→CV".to_string())),
"AudioInput" => Box::new(AudioInputNode::new("Audio Input".to_string())),
"AutomationInput" => Box::new(AutomationInputNode::new("Automation".to_string())),
"Oscilloscope" => Box::new(OscilloscopeNode::new("Oscilloscope".to_string())),
"TemplateInput" => Box::new(TemplateInputNode::new("Template Input".to_string())),
@@ -744,21 +760,29 @@ impl Engine {
}
};
// Add node to graph
let node_idx = graph.add_node(node);
let node_id = node_idx.index() as u32;
// Add node to graph
let node_idx = graph.add_node(node);
let node_id = node_idx.index() as u32;
eprintln!("[DEBUG] Node added with index: {:?}, converted to u32 id: {}", node_idx, node_id);
// Save position
graph.set_node_position(node_idx, x, y);
// Save position
graph.set_node_position(node_idx, x, y);
// Automatically set MIDI-receiving nodes as MIDI targets
if node_type == "MidiInput" || node_type == "VoiceAllocator" {
graph.set_midi_target(node_idx, true);
}
// Emit success event
let _ = self.event_tx.push(AudioEvent::GraphNodeAdded(track_id, node_id, node_type.clone()));
// Automatically set MIDI-receiving nodes as MIDI targets
if node_type == "MidiInput" || node_type == "VoiceAllocator" {
graph.set_midi_target(node_idx, true);
}
// Automatically set AudioOutput nodes as the graph output
if node_type == "AudioOutput" {
graph.set_output_node(Some(node_idx));
}
eprintln!("[DEBUG] Emitting GraphNodeAdded event: track_id={}, node_id={}, node_type={}", track_id, node_id, node_type);
// Emit success event
let _ = self.event_tx.push(AudioEvent::GraphNodeAdded(track_id, node_id, node_type.clone()));
} else {
eprintln!("[DEBUG] Graph was None, node not added!");
}
}
@@ -836,35 +860,55 @@ impl Engine {
}
Command::GraphRemoveNode(track_id, node_index) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
let graph = &mut track.instrument_graph;
{
let node_idx = NodeIndex::new(node_index as usize);
graph.remove_node(node_idx);
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
let graph = match self.project.get_track_mut(track_id) {
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
_ => None,
};
if let Some(graph) = graph {
let node_idx = NodeIndex::new(node_index as usize);
graph.remove_node(node_idx);
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
}
Command::GraphConnect(track_id, from, from_port, to, to_port) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
let graph = &mut track.instrument_graph;
{
let from_idx = NodeIndex::new(from as usize);
let to_idx = NodeIndex::new(to as usize);
eprintln!("[DEBUG] GraphConnect received: track_id={}, from={}, from_port={}, to={}, to_port={}", track_id, from, from_port, to, to_port);
match graph.connect(from_idx, from_port, to_idx, to_port) {
Ok(()) => {
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
Err(e) => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("{:?}", e)
));
}
let graph = match self.project.get_track_mut(track_id) {
Some(TrackNode::Midi(track)) => {
eprintln!("[DEBUG] Found MIDI track for connection");
Some(&mut track.instrument_graph)
},
Some(TrackNode::Audio(track)) => {
eprintln!("[DEBUG] Found Audio track for connection");
Some(&mut track.effects_graph)
},
_ => {
eprintln!("[DEBUG] Track not found for connection!");
None
}
};
if let Some(graph) = graph {
let from_idx = NodeIndex::new(from as usize);
let to_idx = NodeIndex::new(to as usize);
eprintln!("[DEBUG] Attempting to connect nodes: {:?} port {} -> {:?} port {}", from_idx, from_port, to_idx, to_port);
match graph.connect(from_idx, from_port, to_idx, to_port) {
Ok(()) => {
eprintln!("[DEBUG] Connection successful!");
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
Err(e) => {
eprintln!("[DEBUG] Connection failed: {:?}", e);
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("{:?}", e)
));
}
}
} else {
eprintln!("[DEBUG] No graph found, connection not made");
}
}
@@ -891,25 +935,37 @@ impl Engine {
}
Command::GraphDisconnect(track_id, from, from_port, to, to_port) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
let graph = &mut track.instrument_graph;
{
let from_idx = NodeIndex::new(from as usize);
let to_idx = NodeIndex::new(to as usize);
graph.disconnect(from_idx, from_port, to_idx, to_port);
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
eprintln!("[AUDIO ENGINE] GraphDisconnect: track={}, from={}, from_port={}, to={}, to_port={}", track_id, from, from_port, to, to_port);
let graph = match self.project.get_track_mut(track_id) {
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
Some(TrackNode::Audio(track)) => {
eprintln!("[AUDIO ENGINE] Found audio track, disconnecting in effects_graph");
Some(&mut track.effects_graph)
}
_ => {
eprintln!("[AUDIO ENGINE] Track not found!");
None
}
};
if let Some(graph) = graph {
let from_idx = NodeIndex::new(from as usize);
let to_idx = NodeIndex::new(to as usize);
graph.disconnect(from_idx, from_port, to_idx, to_port);
eprintln!("[AUDIO ENGINE] Disconnect completed");
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
}
Command::GraphSetParameter(track_id, node_index, param_id, value) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
let graph = &mut track.instrument_graph;
{
let node_idx = NodeIndex::new(node_index as usize);
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
graph_node.node.set_parameter(param_id, value);
}
let graph = match self.project.get_track_mut(track_id) {
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
_ => None,
};
if let Some(graph) = graph {
let node_idx = NodeIndex::new(node_index as usize);
if let Some(graph_node) = graph.get_graph_node_mut(node_idx) {
graph_node.node.set_parameter(param_id, value);
}
}
}
@@ -925,18 +981,24 @@ impl Engine {
}
Command::GraphSetOutputNode(track_id, node_index) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
let graph = &mut track.instrument_graph;
{
let node_idx = NodeIndex::new(node_index as usize);
graph.set_output_node(Some(node_idx));
}
let graph = match self.project.get_track_mut(track_id) {
Some(TrackNode::Midi(track)) => Some(&mut track.instrument_graph),
Some(TrackNode::Audio(track)) => Some(&mut track.effects_graph),
_ => None,
};
if let Some(graph) = graph {
let node_idx = NodeIndex::new(node_index as usize);
graph.set_output_node(Some(node_idx));
}
}
Command::GraphSavePreset(track_id, preset_path, preset_name, description, tags) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
let graph = &track.instrument_graph;
let graph = match self.project.get_track(track_id) {
Some(TrackNode::Midi(track)) => Some(&track.instrument_graph),
Some(TrackNode::Audio(track)) => Some(&track.effects_graph),
_ => None,
};
if let Some(graph) = graph {
// Serialize the graph to a preset
let mut preset = graph.to_preset(&preset_name);
preset.metadata.description = description;
@@ -969,14 +1031,21 @@ impl Engine {
// Extract the directory path from the preset path for resolving relative sample paths
let preset_base_path = std::path::Path::new(&preset_path).parent();
match InstrumentGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path) {
match AudioGraph::from_preset(&preset, self.sample_rate, 8192, preset_base_path) {
Ok(graph) => {
// Replace the track's graph
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
track.instrument_graph = graph;
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
// Emit preset loaded event after everything is loaded
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
match self.project.get_track_mut(track_id) {
Some(TrackNode::Midi(track)) => {
track.instrument_graph = graph;
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
}
Some(TrackNode::Audio(track)) => {
track.effects_graph = graph;
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
let _ = self.event_tx.push(AudioEvent::GraphPresetLoaded(track_id));
}
_ => {}
}
}
Err(e) => {
@@ -1197,15 +1266,26 @@ impl Engine {
fn handle_query(&mut self, query: Query) {
let response = match query {
Query::GetGraphState(track_id) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track(track_id) {
let graph = &track.instrument_graph;
let preset = graph.to_preset("temp");
match preset.to_json() {
Ok(json) => QueryResponse::GraphState(Ok(json)),
Err(e) => QueryResponse::GraphState(Err(format!("Failed to serialize graph: {:?}", e))),
match self.project.get_track(track_id) {
Some(TrackNode::Midi(track)) => {
let graph = &track.instrument_graph;
let preset = graph.to_preset("temp");
match preset.to_json() {
Ok(json) => QueryResponse::GraphState(Ok(json)),
Err(e) => QueryResponse::GraphState(Err(format!("Failed to serialize graph: {:?}", e))),
}
}
Some(TrackNode::Audio(track)) => {
let graph = &track.effects_graph;
let preset = graph.to_preset("temp");
match preset.to_json() {
Ok(json) => QueryResponse::GraphState(Ok(json)),
Err(e) => QueryResponse::GraphState(Err(format!("Failed to serialize graph: {:?}", e))),
}
}
_ => {
QueryResponse::GraphState(Err(format!("Track {} not found", track_id)))
}
} else {
QueryResponse::GraphState(Err(format!("Track {} not found or is not a MIDI track", track_id)))
}
}
Query::GetTemplateState(track_id, voice_allocator_id) => {
+3 -3
View File
@@ -57,7 +57,7 @@ impl GraphNode {
}
/// Audio processing graph for instruments/effects
pub struct InstrumentGraph {
pub struct AudioGraph {
/// The audio graph (StableGraph allows node removal without index invalidation)
graph: StableGraph<GraphNode, Connection>,
@@ -86,8 +86,8 @@ pub struct InstrumentGraph {
playback_time: f64,
}
impl InstrumentGraph {
/// Create a new empty instrument graph
impl AudioGraph {
/// Create a new empty audio graph
pub fn new(sample_rate: u32, buffer_size: usize) -> Self {
Self {
graph: StableGraph::new(),
+1 -1
View File
@@ -4,7 +4,7 @@ mod types;
pub mod nodes;
pub mod preset;
pub use graph::{Connection, GraphNode, InstrumentGraph};
pub use graph::{Connection, GraphNode, AudioGraph};
pub use node_trait::AudioNode;
pub use preset::{GraphPreset, PresetMetadata, SerializedConnection, SerializedNode};
pub use types::{ConnectionError, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
@@ -0,0 +1,127 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
/// Audio input node - receives audio from audio track clip playback
/// This node acts as the entry point for audio tracks, injecting clip audio into the effects graph
pub struct AudioInputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
/// Internal buffer to hold injected audio from clips
/// This is filled externally by AudioTrack::render() before graph processing
audio_buffer: Vec<f32>,
}
impl AudioInputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
// Audio input node has no inputs - audio is injected externally
let inputs = vec![];
// Outputs stereo audio
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
Self {
name,
inputs,
outputs,
audio_buffer: Vec::new(),
}
}
/// Inject audio from clip playback into this node
/// Should be called by AudioTrack::render() before processing the graph
pub fn inject_audio(&mut self, audio: &[f32]) {
self.audio_buffer.clear();
self.audio_buffer.extend_from_slice(audio);
}
/// Clear the internal audio buffer
pub fn clear_buffer(&mut self) {
self.audio_buffer.clear();
}
}
impl AudioNode for AudioInputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&[] // No parameters
}
fn set_parameter(&mut self, _id: u32, _value: f32) {
// No parameters
}
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,
) {
if outputs.is_empty() {
return;
}
let output = &mut outputs[0];
let len = output.len().min(self.audio_buffer.len());
// Copy audio from internal buffer to output
if len > 0 {
output[..len].copy_from_slice(&self.audio_buffer[..len]);
}
// Clear any remaining samples in output
if output.len() > len {
output[len..].fill(0.0);
}
}
fn reset(&mut self) {
self.audio_buffer.clear();
}
fn node_type(&self) -> &str {
"AudioInput"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
audio_buffer: Vec::new(), // Don't clone the buffer, start fresh
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -1,4 +1,5 @@
mod adsr;
mod audio_input;
mod audio_to_cv;
mod automation_input;
mod bit_crusher;
@@ -39,6 +40,7 @@ mod voice_allocator;
mod wavetable_oscillator;
pub use adsr::ADSRNode;
pub use audio_input::AudioInputNode;
pub use audio_to_cv::AudioToCVNode;
pub use automation_input::{AutomationInputNode, AutomationKeyframe, InterpolationType};
pub use bit_crusher::BitCrusherNode;
@@ -1,5 +1,5 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, InstrumentGraph, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::node_graph::{AudioNode, AudioGraph, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
const PARAM_VOICE_COUNT: u32 = 0;
const MAX_VOICES: usize = 16; // Maximum allowed voices
@@ -34,10 +34,10 @@ pub struct VoiceAllocatorNode {
name: String,
/// The template graph (edited by user via UI)
template_graph: InstrumentGraph,
template_graph: AudioGraph,
/// Runtime voice instances (clones of template)
voice_instances: Vec<InstrumentGraph>,
voice_instances: Vec<AudioGraph>,
/// Voice allocation state
voices: [VoiceState; MAX_VOICES],
@@ -73,11 +73,11 @@ impl VoiceAllocatorNode {
];
// Create empty template graph
let template_graph = InstrumentGraph::new(sample_rate, buffer_size);
let template_graph = AudioGraph::new(sample_rate, buffer_size);
// Create voice instances (initially empty clones of template)
let voice_instances: Vec<InstrumentGraph> = (0..MAX_VOICES)
.map(|_| InstrumentGraph::new(sample_rate, buffer_size))
let voice_instances: Vec<AudioGraph> = (0..MAX_VOICES)
.map(|_| AudioGraph::new(sample_rate, buffer_size))
.collect();
Self {
@@ -94,12 +94,12 @@ impl VoiceAllocatorNode {
}
/// Get mutable reference to template graph (for UI editing)
pub fn template_graph_mut(&mut self) -> &mut InstrumentGraph {
pub fn template_graph_mut(&mut self) -> &mut AudioGraph {
&mut self.template_graph
}
/// Get reference to template graph (for serialization)
pub fn template_graph(&self) -> &InstrumentGraph {
pub fn template_graph(&self) -> &AudioGraph {
&self.template_graph
}
+51 -5
View File
@@ -1,7 +1,8 @@
use super::automation::{AutomationLane, AutomationLaneId, ParameterId};
use super::clip::Clip;
use super::midi::{MidiClip, MidiEvent};
use super::node_graph::InstrumentGraph;
use super::node_graph::AudioGraph;
use super::node_graph::nodes::{AudioInputNode, AudioOutputNode};
use super::pool::AudioPool;
use std::collections::HashMap;
@@ -289,7 +290,7 @@ pub struct MidiTrack {
pub id: TrackId,
pub name: String,
pub clips: Vec<MidiClip>,
pub instrument_graph: InstrumentGraph,
pub instrument_graph: AudioGraph,
pub volume: f32,
pub muted: bool,
pub solo: bool,
@@ -311,7 +312,7 @@ impl MidiTrack {
id,
name,
clips: Vec::new(),
instrument_graph: InstrumentGraph::new(default_sample_rate, default_buffer_size),
instrument_graph: AudioGraph::new(default_sample_rate, default_buffer_size),
volume: 1.0,
muted: false,
solo: false,
@@ -491,11 +492,34 @@ pub struct AudioTrack {
/// Automation lanes for this track
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
next_automation_id: AutomationLaneId,
/// Effects processing graph for this audio track
pub effects_graph: AudioGraph,
}
impl AudioTrack {
/// Create a new audio track with default settings
pub fn new(id: TrackId, name: String) -> Self {
// Use default sample rate and a large buffer size that can accommodate any callback
let default_sample_rate = 48000;
let default_buffer_size = 8192;
// Create the effects graph with default AudioInput -> AudioOutput chain
let mut effects_graph = AudioGraph::new(default_sample_rate, default_buffer_size);
// Add AudioInput node
let input_node = Box::new(AudioInputNode::new("Audio Input"));
let input_id = effects_graph.add_node(input_node);
// Add AudioOutput node
let output_node = Box::new(AudioOutputNode::new("Audio Output"));
let output_id = effects_graph.add_node(output_node);
// Connect AudioInput -> AudioOutput
let _ = effects_graph.connect(input_id, 0, output_id, 0);
// Set the AudioOutput node as the graph's output
effects_graph.set_output_node(Some(output_id));
Self {
id,
name,
@@ -505,6 +529,7 @@ impl AudioTrack {
solo: false,
automation_lanes: HashMap::new(),
next_automation_id: 0,
effects_graph,
}
}
@@ -571,15 +596,17 @@ impl AudioTrack {
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
// Create a temporary buffer for clip rendering
let mut clip_buffer = vec![0.0f32; output.len()];
let mut rendered = 0;
// Render all active clips
// Render all active clips into the temporary buffer
for clip in &self.clips {
// Check if clip overlaps with current buffer time range
if clip.start_time < buffer_end_seconds && clip.end_time() > playhead_seconds {
rendered += self.render_clip(
clip,
output,
&mut clip_buffer,
pool,
playhead_seconds,
sample_rate,
@@ -588,6 +615,25 @@ impl AudioTrack {
}
}
// Clear output buffer before graph processing to ensure clean output
output.fill(0.0);
// Find and inject audio into the AudioInputNode
let node_indices: Vec<_> = self.effects_graph.node_indices().collect();
for node_idx in node_indices {
if let Some(graph_node) = self.effects_graph.get_graph_node_mut(node_idx) {
if graph_node.node.node_type() == "AudioInput" {
if let Some(input_node) = graph_node.node.as_any_mut().downcast_mut::<AudioInputNode>() {
input_node.inject_audio(&clip_buffer);
break;
}
}
}
}
// Process through the effects graph (this will write to output buffer)
self.effects_graph.process(output, &[], playhead_seconds);
// Evaluate and apply automation
let effective_volume = self.evaluate_automation_at_time(playhead_seconds);