Add audio node graph editing

This commit is contained in:
Skyler Lehmkuhl
2025-10-25 03:29:54 -04:00
parent 19e99fa8bf
commit 16f4a2a359
43 changed files with 7110 additions and 824 deletions
+546
View File
@@ -0,0 +1,546 @@
use super::node_trait::AudioNode;
use super::types::{ConnectionError, SignalType};
use crate::audio::midi::MidiEvent;
use petgraph::algo::has_path_connecting;
use petgraph::stable_graph::{NodeIndex, StableGraph};
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
use petgraph::Direction;
/// Connection information between nodes
#[derive(Debug, Clone)]
pub struct Connection {
pub from_port: usize,
pub to_port: usize,
}
/// Wrapper for audio nodes in the graph
pub struct GraphNode {
pub node: Box<dyn AudioNode>,
/// Buffers for each audio/CV output port
pub output_buffers: Vec<Vec<f32>>,
/// Buffers for each MIDI output port
pub midi_output_buffers: Vec<Vec<MidiEvent>>,
}
impl GraphNode {
pub fn new(node: Box<dyn AudioNode>, buffer_size: usize) -> Self {
let outputs = node.outputs();
// Allocate buffers based on signal type
// Audio signals are stereo (2 samples per frame), CV is mono (1 sample per frame)
let mut output_buffers = Vec::new();
let mut midi_output_buffers = Vec::new();
for port in outputs.iter() {
match port.signal_type {
SignalType::Audio => {
output_buffers.push(vec![0.0; buffer_size * 2]); // Stereo (interleaved L/R)
}
SignalType::CV => {
output_buffers.push(vec![0.0; buffer_size]); // Mono
}
SignalType::Midi => {
output_buffers.push(vec![]); // Placeholder for indexing alignment
let mut midi_buf = Vec::new();
midi_buf.reserve(128); // Max 128 MIDI events per cycle
midi_output_buffers.push(midi_buf);
}
}
}
Self {
node,
output_buffers,
midi_output_buffers,
}
}
}
/// Audio processing graph for instruments/effects
pub struct InstrumentGraph {
/// The audio graph (StableGraph allows node removal without index invalidation)
graph: StableGraph<GraphNode, Connection>,
/// MIDI input mapping (which nodes receive MIDI)
midi_targets: Vec<NodeIndex>,
/// Audio output node index (where we read final audio)
output_node: Option<NodeIndex>,
/// Sample rate
sample_rate: u32,
/// Buffer size for internal processing
buffer_size: usize,
/// Temporary buffers for node audio/CV inputs during processing
input_buffers: Vec<Vec<f32>>,
/// Temporary buffers for node MIDI inputs during processing
midi_input_buffers: Vec<Vec<MidiEvent>>,
}
impl InstrumentGraph {
/// Create a new empty instrument graph
pub fn new(sample_rate: u32, buffer_size: usize) -> Self {
Self {
graph: StableGraph::new(),
midi_targets: Vec::new(),
output_node: None,
sample_rate,
buffer_size,
// Pre-allocate input buffers with stereo size (2x) to accommodate Audio signals
// CV signals will only use the first half
input_buffers: vec![vec![0.0; buffer_size * 2]; 16],
// Pre-allocate MIDI input buffers (max 128 events per port)
midi_input_buffers: (0..16).map(|_| Vec::with_capacity(128)).collect(),
}
}
/// Add a node to the graph
pub fn add_node(&mut self, node: Box<dyn AudioNode>) -> NodeIndex {
let graph_node = GraphNode::new(node, self.buffer_size);
self.graph.add_node(graph_node)
}
/// Connect two nodes with type checking
pub fn connect(
&mut self,
from: NodeIndex,
from_port: usize,
to: NodeIndex,
to_port: usize,
) -> Result<(), ConnectionError> {
// Validate the connection
self.validate_connection(from, from_port, to, to_port)?;
// Add the edge
self.graph.add_edge(from, to, Connection { from_port, to_port });
Ok(())
}
/// Disconnect two nodes
pub fn disconnect(
&mut self,
from: NodeIndex,
from_port: usize,
to: NodeIndex,
to_port: usize,
) {
// Find and remove the edge
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);
}
}
}
/// Remove a node from the graph
pub fn remove_node(&mut self, node: NodeIndex) {
self.graph.remove_node(node);
// Update MIDI targets
self.midi_targets.retain(|&idx| idx != node);
// Update output node
if self.output_node == Some(node) {
self.output_node = None;
}
}
/// Validate a connection is type-compatible and wouldn't create a cycle
fn validate_connection(
&self,
from: NodeIndex,
from_port: usize,
to: NodeIndex,
to_port: usize,
) -> Result<(), ConnectionError> {
// Check nodes exist
let from_node = self.graph.node_weight(from).ok_or(ConnectionError::InvalidPort)?;
let to_node = self.graph.node_weight(to).ok_or(ConnectionError::InvalidPort)?;
// Check ports are valid
let from_outputs = from_node.node.outputs();
let to_inputs = to_node.node.inputs();
if from_port >= from_outputs.len() || to_port >= to_inputs.len() {
return Err(ConnectionError::InvalidPort);
}
// Check signal types match
let from_type = from_outputs[from_port].signal_type;
let to_type = to_inputs[to_port].signal_type;
if from_type != to_type {
return Err(ConnectionError::TypeMismatch {
expected: to_type,
got: from_type,
});
}
// Check for cycles: if there's already a path from 'to' to 'from',
// then adding 'from' -> 'to' would create a cycle
if has_path_connecting(&self.graph, to, from, None) {
return Err(ConnectionError::WouldCreateCycle);
}
Ok(())
}
/// Set which node receives MIDI events
pub fn set_midi_target(&mut self, node: NodeIndex, enabled: bool) {
if enabled {
if !self.midi_targets.contains(&node) {
self.midi_targets.push(node);
}
} else {
self.midi_targets.retain(|&idx| idx != node);
}
}
/// Set the output node (where final audio is read from)
pub fn set_output_node(&mut self, node: Option<NodeIndex>) {
self.output_node = node;
}
/// Add a node to a VoiceAllocator's template graph
pub fn add_node_to_voice_allocator_template(
&mut self,
voice_allocator_idx: NodeIndex,
node: Box<dyn AudioNode>,
) -> Result<u32, String> {
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
// Get the VoiceAllocator node
if let Some(graph_node) = self.graph.node_weight_mut(voice_allocator_idx) {
// We need to downcast to VoiceAllocatorNode
// This is tricky with trait objects, so we'll need to use Any
// For now, let's use a different approach - store the node pointer temporarily
// Check node type first
if graph_node.node.node_type() != "VoiceAllocator" {
return Err("Node is not a VoiceAllocator".to_string());
}
// Get mutable reference and downcast using raw pointers
let node_ptr = &mut *graph_node.node as *mut dyn AudioNode;
// SAFETY: We just checked that this is a VoiceAllocator
// This is safe because we know the concrete type
unsafe {
let va_ptr = node_ptr as *mut VoiceAllocatorNode;
let va = &mut *va_ptr;
// Add node to template graph
let node_idx = va.template_graph_mut().add_node(node);
let node_id = node_idx.index() as u32;
// Rebuild voice instances from template
va.rebuild_voices();
return Ok(node_id);
}
}
Err("VoiceAllocator node not found".to_string())
}
/// Connect nodes in a VoiceAllocator's template graph
pub fn connect_in_voice_allocator_template(
&mut self,
voice_allocator_idx: NodeIndex,
from_node: u32,
from_port: usize,
to_node: u32,
to_port: usize,
) -> Result<(), String> {
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
// Get the VoiceAllocator node
if let Some(graph_node) = self.graph.node_weight_mut(voice_allocator_idx) {
// Check node type first
if graph_node.node.node_type() != "VoiceAllocator" {
return Err("Node is not a VoiceAllocator".to_string());
}
// Get mutable reference and downcast using raw pointers
let node_ptr = &mut *graph_node.node as *mut dyn AudioNode;
// SAFETY: We just checked that this is a VoiceAllocator
unsafe {
let va_ptr = node_ptr as *mut VoiceAllocatorNode;
let va = &mut *va_ptr;
// Connect in template graph
let from_idx = NodeIndex::new(from_node as usize);
let to_idx = NodeIndex::new(to_node as usize);
va.template_graph_mut().connect(from_idx, from_port, to_idx, to_port)
.map_err(|e| format!("{:?}", e))?;
// Rebuild voice instances from template
va.rebuild_voices();
return Ok(());
}
}
Err("VoiceAllocator node not found".to_string())
}
/// Process the graph and produce audio output
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent]) {
// Use the requested output buffer size for processing
let process_size = output_buffer.len();
// Clear all output buffers (audio/CV and MIDI)
for node in self.graph.node_weights_mut() {
for buffer in &mut node.output_buffers {
let len = buffer.len();
buffer[..process_size.min(len)].fill(0.0);
}
for midi_buffer in &mut node.midi_output_buffers {
midi_buffer.clear();
}
}
// Distribute incoming MIDI events to target nodes' MIDI output buffers
// This puts MIDI into the graph so it can flow through connections
for &target_idx in &self.midi_targets {
if let Some(node) = self.graph.node_weight_mut(target_idx) {
// Find the first MIDI output port and add events there
if !node.midi_output_buffers.is_empty() {
node.midi_output_buffers[0].extend_from_slice(midi_events);
}
}
}
// Topological sort for processing order
let topo = petgraph::algo::toposort(&self.graph, None)
.unwrap_or_else(|_| {
// If there's a cycle (shouldn't happen due to validation), just process in index order
self.graph.node_indices().collect()
});
// Process nodes in topological order
for node_idx in topo {
// Get input port information
let inputs = self.graph[node_idx].node.inputs();
let num_audio_cv_inputs = inputs.iter().filter(|p| p.signal_type != SignalType::Midi).count();
let num_midi_inputs = inputs.iter().filter(|p| p.signal_type == SignalType::Midi).count();
// Clear audio/CV input buffers
for i in 0..num_audio_cv_inputs {
if i < self.input_buffers.len() {
self.input_buffers[i].fill(0.0);
}
}
// Clear MIDI input buffers
for i in 0..num_midi_inputs {
if i < self.midi_input_buffers.len() {
self.midi_input_buffers[i].clear();
}
}
// Collect inputs from connected nodes
let incoming = self.graph.edges_directed(node_idx, Direction::Incoming).collect::<Vec<_>>();
for edge in incoming {
let source_idx = edge.source();
let conn = edge.weight();
let source_node = &self.graph[source_idx];
// Determine source port type
if conn.from_port < source_node.node.outputs().len() {
let source_port_type = source_node.node.outputs()[conn.from_port].signal_type;
match source_port_type {
SignalType::Audio | SignalType::CV => {
// Copy audio/CV data
if conn.to_port < num_audio_cv_inputs && conn.from_port < source_node.output_buffers.len() {
let source_buffer = &source_node.output_buffers[conn.from_port];
if conn.to_port < self.input_buffers.len() {
for (dst, src) in self.input_buffers[conn.to_port].iter_mut().zip(source_buffer.iter()) {
*dst += src;
}
}
}
}
SignalType::Midi => {
// Copy MIDI events
// Map from global port index to MIDI-only port index
let midi_port_idx = inputs.iter()
.take(conn.to_port + 1)
.filter(|p| p.signal_type == SignalType::Midi)
.count() - 1;
let source_midi_idx = source_node.node.outputs().iter()
.take(conn.from_port + 1)
.filter(|p| p.signal_type == SignalType::Midi)
.count() - 1;
if midi_port_idx < self.midi_input_buffers.len() &&
source_midi_idx < source_node.midi_output_buffers.len() {
self.midi_input_buffers[midi_port_idx]
.extend_from_slice(&source_node.midi_output_buffers[source_midi_idx]);
}
}
}
}
}
// Prepare audio/CV input slices
let input_slices: Vec<&[f32]> = (0..num_audio_cv_inputs)
.map(|i| {
if i < self.input_buffers.len() {
&self.input_buffers[i][..process_size.min(self.input_buffers[i].len())]
} else {
&[][..]
}
})
.collect();
// Prepare MIDI input slices
let midi_input_slices: Vec<&[MidiEvent]> = (0..num_midi_inputs)
.map(|i| {
if i < self.midi_input_buffers.len() {
&self.midi_input_buffers[i][..]
} else {
&[][..]
}
})
.collect();
// Get mutable access to output buffers
let node = &mut self.graph[node_idx];
let outputs = node.node.outputs();
let num_audio_cv_outputs = outputs.iter().filter(|p| p.signal_type != SignalType::Midi).count();
let num_midi_outputs = outputs.iter().filter(|p| p.signal_type == SignalType::Midi).count();
// Create mutable slices for audio/CV outputs
let mut output_slices: Vec<&mut [f32]> = Vec::with_capacity(num_audio_cv_outputs);
for i in 0..num_audio_cv_outputs {
if i < node.output_buffers.len() {
// Safety: We need to work around borrowing rules here
// This is safe because each output buffer is independent
let buffer = &mut node.output_buffers[i] as *mut Vec<f32>;
unsafe {
let slice = &mut (*buffer)[..process_size.min((*buffer).len())];
output_slices.push(slice);
}
}
}
// Create mutable references for MIDI outputs
let mut midi_output_refs: Vec<&mut Vec<MidiEvent>> = Vec::with_capacity(num_midi_outputs);
for i in 0..num_midi_outputs {
if i < node.midi_output_buffers.len() {
// Safety: Similar to above
let buffer = &mut node.midi_output_buffers[i] as *mut Vec<MidiEvent>;
unsafe {
midi_output_refs.push(&mut *buffer);
}
}
}
// Process the node with both audio/CV and MIDI
node.node.process(&input_slices, &mut output_slices, &midi_input_slices, &mut midi_output_refs, self.sample_rate);
}
// Copy output node's first output to the provided buffer
if let Some(output_idx) = self.output_node {
if let Some(output_node) = self.graph.node_weight(output_idx) {
if !output_node.output_buffers.is_empty() {
let len = output_buffer.len().min(output_node.output_buffers[0].len());
output_buffer[..len].copy_from_slice(&output_node.output_buffers[0][..len]);
}
}
}
}
/// Get node by index
pub fn get_node(&self, idx: NodeIndex) -> Option<&dyn AudioNode> {
self.graph.node_weight(idx).map(|n| &*n.node)
}
/// Get oscilloscope data from a specific node
pub fn get_oscilloscope_data(&self, idx: NodeIndex, sample_count: usize) -> Option<Vec<f32>> {
self.get_node(idx).and_then(|node| node.get_oscilloscope_data(sample_count))
}
/// Get node mutably by index
/// Note: Due to lifetime constraints with trait objects, this returns a mutable reference
/// to the GraphNode, from which you can access the node
pub fn get_graph_node_mut(&mut self, idx: NodeIndex) -> Option<&mut GraphNode> {
self.graph.node_weight_mut(idx)
}
/// Get all node indices
pub fn node_indices(&self) -> impl Iterator<Item = NodeIndex> + '_ {
self.graph.node_indices()
}
/// 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()))
}
/// Reset all nodes in the graph
pub fn reset(&mut self) {
// Collect indices first to avoid borrow checker issues
let indices: Vec<_> = self.graph.node_indices().collect();
for node_idx in indices {
if let Some(node) = self.graph.node_weight_mut(node_idx) {
node.node.reset();
}
}
}
/// Clone the graph structure with all nodes and connections
pub fn clone_graph(&self) -> Self {
let mut new_graph = Self::new(self.sample_rate, self.buffer_size);
// Map from old NodeIndex to new NodeIndex
let mut index_map = std::collections::HashMap::new();
// Clone all nodes
for node_idx in self.graph.node_indices() {
if let Some(graph_node) = self.graph.node_weight(node_idx) {
let cloned_node = graph_node.node.clone_node();
let new_idx = new_graph.add_node(cloned_node);
index_map.insert(node_idx, new_idx);
}
}
// Clone all connections
for edge in self.graph.edge_references() {
let source = edge.source();
let target = edge.target();
let conn = edge.weight();
if let (Some(&new_source), Some(&new_target)) = (index_map.get(&source), index_map.get(&target)) {
let _ = new_graph.connect(new_source, conn.from_port, new_target, conn.to_port);
}
}
// Clone MIDI targets
for &old_target in &self.midi_targets {
if let Some(&new_target) = index_map.get(&old_target) {
new_graph.set_midi_target(new_target, true);
}
}
// Clone output node reference
if let Some(old_output) = self.output_node {
if let Some(&new_output) = index_map.get(&old_output) {
new_graph.output_node = Some(new_output);
}
}
new_graph
}
}
+8
View File
@@ -0,0 +1,8 @@
mod graph;
mod node_trait;
mod types;
pub mod nodes;
pub use graph::{Connection, GraphNode, InstrumentGraph};
pub use node_trait::AudioNode;
pub use types::{ConnectionError, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
@@ -0,0 +1,67 @@
use super::types::{NodeCategory, NodePort, Parameter};
use crate::audio::midi::MidiEvent;
/// Custom node trait for audio processing nodes
///
/// All nodes must be Send to be usable in the audio thread.
/// Nodes should be real-time safe: no allocations, no blocking operations.
pub trait AudioNode: Send {
/// Node category for UI organization
fn category(&self) -> NodeCategory;
/// Input port definitions
fn inputs(&self) -> &[NodePort];
/// Output port definitions
fn outputs(&self) -> &[NodePort];
/// User-facing parameters
fn parameters(&self) -> &[Parameter];
/// Set parameter by ID
fn set_parameter(&mut self, id: u32, value: f32);
/// Get parameter by ID
fn get_parameter(&self, id: u32) -> f32;
/// Process audio buffers
///
/// # Arguments
/// * `inputs` - Audio/CV input buffers for each input port
/// * `outputs` - Audio/CV output buffers for each output port
/// * `midi_inputs` - MIDI event buffers for each MIDI input port
/// * `midi_outputs` - MIDI event buffers for each MIDI output port
/// * `sample_rate` - Current sample rate in Hz
fn process(
&mut self,
inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
midi_outputs: &mut [&mut Vec<MidiEvent>],
sample_rate: u32,
);
/// Handle MIDI events (for nodes with MIDI inputs)
fn handle_midi(&mut self, _event: &MidiEvent) {
// Default: do nothing
}
/// Reset internal state (clear delays, resonances, etc.)
fn reset(&mut self);
/// Get the node type name (for serialization)
fn node_type(&self) -> &str;
/// Get a unique identifier for this node instance
fn name(&self) -> &str;
/// Clone this node into a new boxed instance
/// Required for VoiceAllocator to create multiple instances
fn clone_node(&self) -> Box<dyn AudioNode>;
/// Get oscilloscope data if this is an oscilloscope node
/// Returns None for non-oscilloscope nodes
fn get_oscilloscope_data(&self, _sample_count: usize) -> Option<Vec<f32>> {
None
}
}
@@ -0,0 +1,215 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_ATTACK: u32 = 0;
const PARAM_DECAY: u32 = 1;
const PARAM_SUSTAIN: u32 = 2;
const PARAM_RELEASE: u32 = 3;
#[derive(Debug, Clone, Copy, PartialEq)]
enum EnvelopeStage {
Idle,
Attack,
Decay,
Sustain,
Release,
}
/// ADSR Envelope Generator
/// Outputs a CV signal (0.0-1.0) based on gate input and ADSR parameters
pub struct ADSRNode {
name: String,
attack: f32, // seconds
decay: f32, // seconds
sustain: f32, // level (0.0-1.0)
release: f32, // seconds
stage: EnvelopeStage,
level: f32, // current envelope level
gate_was_high: bool,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl ADSRNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Gate", SignalType::CV, 0),
];
let outputs = vec![
NodePort::new("Envelope Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(PARAM_ATTACK, "Attack", 0.001, 5.0, 0.01, ParameterUnit::Time),
Parameter::new(PARAM_DECAY, "Decay", 0.001, 5.0, 0.1, ParameterUnit::Time),
Parameter::new(PARAM_SUSTAIN, "Sustain", 0.0, 1.0, 0.7, ParameterUnit::Generic),
Parameter::new(PARAM_RELEASE, "Release", 0.001, 5.0, 0.2, ParameterUnit::Time),
];
Self {
name,
attack: 0.01,
decay: 0.1,
sustain: 0.7,
release: 0.2,
stage: EnvelopeStage::Idle,
level: 0.0,
gate_was_high: false,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for ADSRNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_ATTACK => self.attack = value.clamp(0.001, 5.0),
PARAM_DECAY => self.decay = value.clamp(0.001, 5.0),
PARAM_SUSTAIN => self.sustain = value.clamp(0.0, 1.0),
PARAM_RELEASE => self.release = value.clamp(0.001, 5.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_ATTACK => self.attack,
PARAM_DECAY => self.decay,
PARAM_SUSTAIN => self.sustain,
PARAM_RELEASE => self.release,
_ => 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 sample_rate_f32 = sample_rate as f32;
// CV signals are mono
let frames = output.len();
for frame in 0..frames {
// Read gate input (if available)
let gate_high = if !inputs.is_empty() && frame < inputs[0].len() {
inputs[0][frame] > 0.5 // Gate is high if CV > 0.5
} else {
false
};
// Detect gate transitions
if gate_high && !self.gate_was_high {
// Note on: Start attack
self.stage = EnvelopeStage::Attack;
} else if !gate_high && self.gate_was_high {
// Note off: Start release
self.stage = EnvelopeStage::Release;
}
self.gate_was_high = gate_high;
// Process envelope stage
match self.stage {
EnvelopeStage::Idle => {
self.level = 0.0;
}
EnvelopeStage::Attack => {
// Rise from current level to 1.0
let increment = 1.0 / (self.attack * sample_rate_f32);
self.level += increment;
if self.level >= 1.0 {
self.level = 1.0;
self.stage = EnvelopeStage::Decay;
}
}
EnvelopeStage::Decay => {
// Fall from 1.0 to sustain level
let target = self.sustain;
let decrement = (1.0 - target) / (self.decay * sample_rate_f32);
self.level -= decrement;
if self.level <= target {
self.level = target;
self.stage = EnvelopeStage::Sustain;
}
}
EnvelopeStage::Sustain => {
// Hold at sustain level
self.level = self.sustain;
}
EnvelopeStage::Release => {
// Fall from current level to 0.0
let decrement = self.level / (self.release * sample_rate_f32);
self.level -= decrement;
if self.level <= 0.001 {
self.level = 0.0;
self.stage = EnvelopeStage::Idle;
}
}
}
// Write envelope value (CV is mono)
output[frame] = self.level;
}
}
fn reset(&mut self) {
self.stage = EnvelopeStage::Idle;
self.level = 0.0;
self.gate_was_high = false;
}
fn node_type(&self) -> &str {
"ADSR"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
attack: self.attack,
decay: self.decay,
sustain: self.sustain,
release: self.release,
stage: EnvelopeStage::Idle, // Reset state
level: 0.0, // Reset level
gate_was_high: false, // Reset gate
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,151 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_ATTACK: u32 = 0;
const PARAM_RELEASE: u32 = 1;
/// Audio to CV converter (Envelope Follower)
/// Converts audio amplitude to control voltage
pub struct AudioToCVNode {
name: String,
envelope: f32, // Current envelope value
attack: f32, // Attack time in seconds
release: f32, // Release time in seconds
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl AudioToCVNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
let outputs = vec![
NodePort::new("CV Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(PARAM_ATTACK, "Attack", 0.001, 1.0, 0.01, ParameterUnit::Time),
Parameter::new(PARAM_RELEASE, "Release", 0.001, 1.0, 0.1, ParameterUnit::Time),
];
Self {
name,
envelope: 0.0,
attack: 0.01,
release: 0.1,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for AudioToCVNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_ATTACK => self.attack = value.clamp(0.001, 1.0),
PARAM_RELEASE => self.release = value.clamp(0.001, 1.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_ATTACK => self.attack,
PARAM_RELEASE => self.release,
_ => 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 inputs.is_empty() || outputs.is_empty() {
return;
}
let input = inputs[0];
let output = &mut outputs[0];
// Audio input is stereo (interleaved L/R), CV output is mono
let audio_frames = input.len() / 2;
let cv_frames = output.len();
let frames = audio_frames.min(cv_frames);
// Calculate attack and release coefficients
let sample_rate_f32 = sample_rate as f32;
let attack_coeff = (-1.0 / (self.attack * sample_rate_f32)).exp();
let release_coeff = (-1.0 / (self.release * sample_rate_f32)).exp();
for frame in 0..frames {
// Get stereo samples
let left = input[frame * 2];
let right = input[frame * 2 + 1];
// Calculate RMS-like value (average of absolute values for simplicity)
let amplitude = (left.abs() + right.abs()) / 2.0;
// Envelope follower with attack/release
if amplitude > self.envelope {
// Attack: follow signal up quickly
self.envelope = amplitude * (1.0 - attack_coeff) + self.envelope * attack_coeff;
} else {
// Release: decay slowly
self.envelope = amplitude * (1.0 - release_coeff) + self.envelope * release_coeff;
}
// Output CV (mono)
output[frame] = self.envelope;
}
}
fn reset(&mut self) {
self.envelope = 0.0;
}
fn node_type(&self) -> &str {
"AudioToCV"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
envelope: 0.0, // Reset envelope
attack: self.attack,
release: self.release,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,201 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use crate::dsp::biquad::BiquadFilter;
const PARAM_CUTOFF: u32 = 0;
const PARAM_RESONANCE: u32 = 1;
const PARAM_TYPE: u32 = 2;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FilterType {
Lowpass = 0,
Highpass = 1,
}
impl FilterType {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => FilterType::Highpass,
_ => FilterType::Lowpass,
}
}
}
/// Filter node using biquad implementation
pub struct FilterNode {
name: String,
filter: BiquadFilter,
cutoff: f32,
resonance: f32,
filter_type: FilterType,
sample_rate: u32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl FilterNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
NodePort::new("Cutoff CV", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_CUTOFF, "Cutoff", 20.0, 20000.0, 1000.0, ParameterUnit::Frequency),
Parameter::new(PARAM_RESONANCE, "Resonance", 0.1, 10.0, 0.707, ParameterUnit::Generic),
Parameter::new(PARAM_TYPE, "Type", 0.0, 1.0, 0.0, ParameterUnit::Generic),
];
let filter = BiquadFilter::lowpass(1000.0, 0.707, 44100.0);
Self {
name,
filter,
cutoff: 1000.0,
resonance: 0.707,
filter_type: FilterType::Lowpass,
sample_rate: 44100,
inputs,
outputs,
parameters,
}
}
fn update_filter(&mut self) {
match self.filter_type {
FilterType::Lowpass => {
self.filter.set_lowpass(self.cutoff, self.resonance, self.sample_rate as f32);
}
FilterType::Highpass => {
self.filter.set_highpass(self.cutoff, self.resonance, self.sample_rate as f32);
}
}
}
}
impl AudioNode for FilterNode {
fn category(&self) -> NodeCategory {
NodeCategory::Effect
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_CUTOFF => {
self.cutoff = value.clamp(20.0, 20000.0);
self.update_filter();
}
PARAM_RESONANCE => {
self.resonance = value.clamp(0.1, 10.0);
self.update_filter();
}
PARAM_TYPE => {
self.filter_type = FilterType::from_f32(value);
self.update_filter();
}
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_CUTOFF => self.cutoff,
PARAM_RESONANCE => self.resonance,
PARAM_TYPE => self.filter_type as i32 as 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 inputs.is_empty() || outputs.is_empty() {
return;
}
// Update sample rate if changed
if self.sample_rate != sample_rate {
self.sample_rate = sample_rate;
self.update_filter();
}
let input = inputs[0];
let output = &mut outputs[0];
let len = input.len().min(output.len());
// Copy input to output
output[..len].copy_from_slice(&input[..len]);
// Check for CV modulation (modulates cutoff)
if inputs.len() > 1 && !inputs[1].is_empty() {
// CV input modulates cutoff frequency
// For now, just use the base cutoff - per-sample modulation would be expensive
// TODO: Sample CV at frame rate and update filter periodically
}
// Apply filter (processes stereo interleaved)
self.filter.process_buffer(&mut output[..len], 2);
}
fn reset(&mut self) {
self.filter.reset();
}
fn node_type(&self) -> &str {
"Filter"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
// Create new filter with same parameters but reset state
let mut new_filter = BiquadFilter::new();
// Set filter to match current type
match self.filter_type {
FilterType::Lowpass => {
new_filter.set_lowpass(self.sample_rate as f32, self.cutoff, self.resonance);
}
FilterType::Highpass => {
new_filter.set_highpass(self.sample_rate as f32, self.cutoff, self.resonance);
}
}
Box::new(Self {
name: self.name.clone(),
filter: new_filter,
cutoff: self.cutoff,
resonance: self.resonance,
filter_type: self.filter_type,
sample_rate: self.sample_rate,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,130 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
const PARAM_GAIN: u32 = 0;
/// Gain/volume control node
pub struct GainNode {
name: String,
gain: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl GainNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
NodePort::new("Gain CV", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_GAIN, "Gain", 0.0, 2.0, 1.0, ParameterUnit::Generic),
];
Self {
name,
gain: 1.0,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for GainNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_GAIN => self.gain = value.clamp(0.0, 2.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_GAIN => self.gain,
_ => 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 inputs.is_empty() || outputs.is_empty() {
return;
}
let input = inputs[0];
let output = &mut outputs[0];
// Audio signals are stereo (interleaved L/R)
// Process by frames, not samples
let frames = input.len().min(output.len()) / 2;
for frame in 0..frames {
// Calculate final gain
let mut final_gain = self.gain;
// CV input acts as a VCA (voltage-controlled amplifier)
// CV ranges from 0.0 (silence) to 1.0 (full gain parameter value)
if inputs.len() > 1 && frame < inputs[1].len() {
let cv = inputs[1][frame];
final_gain *= cv; // Multiply gain by CV (0.0 = silence, 1.0 = full gain)
}
// Apply gain to both channels
output[frame * 2] = input[frame * 2] * final_gain; // Left
output[frame * 2 + 1] = input[frame * 2 + 1] * final_gain; // Right
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"Gain"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
gain: self.gain,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,105 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
/// MIDI Input node - receives MIDI events from the track and passes them through
pub struct MidiInputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
pending_events: Vec<MidiEvent>,
}
impl MidiInputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![];
let outputs = vec![
NodePort::new("MIDI Out", SignalType::Midi, 0),
];
Self {
name,
inputs,
outputs,
parameters: vec![],
pending_events: Vec::new(),
}
}
/// Add MIDI events to be processed
pub fn add_midi_events(&mut self, events: Vec<MidiEvent>) {
self.pending_events.extend(events);
}
/// Get pending MIDI events (used for routing to connected nodes)
pub fn take_midi_events(&mut self) -> Vec<MidiEvent> {
std::mem::take(&mut self.pending_events)
}
}
impl AudioNode for MidiInputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.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,
) {
// MidiInput receives MIDI from external sources (marked as MIDI target)
// and outputs it through the graph
// The MIDI was already placed in midi_outputs by the graph before calling process()
}
fn reset(&mut self) {
self.pending_events.clear();
}
fn node_type(&self) -> &str {
"MidiInput"
}
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(),
parameters: self.parameters.clone(),
pending_events: Vec::new(),
})
}
fn handle_midi(&mut self, event: &MidiEvent) {
self.pending_events.push(*event);
}
}
@@ -0,0 +1,185 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
/// MIDI to CV converter
/// Converts MIDI note events to control voltage signals
pub struct MidiToCVNode {
name: String,
note: u8, // Current MIDI note number
gate: f32, // Gate CV (1.0 when note on, 0.0 when off)
velocity: f32, // Velocity CV (0.0-1.0)
pitch_cv: f32, // Pitch CV (0.0-1.0 V/oct)
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl MidiToCVNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
// MIDI input port for receiving MIDI through graph connections
let inputs = vec![
NodePort::new("MIDI In", SignalType::Midi, 0),
];
let outputs = vec![
NodePort::new("V/Oct", SignalType::CV, 0), // 0.0-1.0 pitch CV
NodePort::new("Gate", SignalType::CV, 1), // 1.0 = on, 0.0 = off
NodePort::new("Velocity", SignalType::CV, 2), // 0.0-1.0
];
Self {
name,
note: 60, // Middle C
gate: 0.0,
velocity: 0.0,
pitch_cv: Self::midi_note_to_voct(60),
inputs,
outputs,
parameters: vec![], // No user parameters
}
}
/// Convert MIDI note to V/oct CV (0-1 range representing pitch)
/// Maps MIDI notes 0-127 to CV 0.0-1.0 for pitch tracking
fn midi_note_to_voct(note: u8) -> f32 {
// Simple linear mapping: each semitone is 1/127 of the CV range
note as f32 / 127.0
}
}
impl AudioNode for MidiToCVNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, _id: u32, _value: f32) {
// No parameters
}
fn get_parameter(&self, _id: u32) -> f32 {
0.0
}
fn handle_midi(&mut self, event: &MidiEvent) {
let status = event.status & 0xF0;
match status {
0x90 => {
// Note on
if event.data2 > 0 {
// Velocity > 0 means note on
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
} else {
// Velocity = 0 means note off
if event.data1 == self.note {
self.gate = 0.0;
}
}
}
0x80 => {
// Note off
if event.data1 == self.note {
self.gate = 0.0;
}
}
_ => {}
}
}
fn process(
&mut self,
_inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
// Process MIDI events from input buffer
if !midi_inputs.is_empty() {
for event in midi_inputs[0] {
let status = event.status & 0xF0;
match status {
0x90 if event.data2 > 0 => {
// Note on
self.note = event.data1;
self.pitch_cv = Self::midi_note_to_voct(self.note);
self.velocity = event.data2 as f32 / 127.0;
self.gate = 1.0;
}
0x80 | 0x90 => {
// Note off (or note on with velocity 0)
if event.data1 == self.note {
self.gate = 0.0;
}
}
_ => {}
}
}
}
if outputs.len() < 3 {
return;
}
// CV signals are mono
// Use split_at_mut to get multiple mutable references
let (pitch_and_rest, rest) = outputs.split_at_mut(1);
let (gate_and_rest, velocity_slice) = rest.split_at_mut(1);
let pitch_out = &mut pitch_and_rest[0];
let gate_out = &mut gate_and_rest[0];
let velocity_out = &mut velocity_slice[0];
let frames = pitch_out.len();
// Output constant CV values for the entire buffer
for frame in 0..frames {
pitch_out[frame] = self.pitch_cv;
gate_out[frame] = self.gate;
velocity_out[frame] = self.velocity;
}
}
fn reset(&mut self) {
self.gate = 0.0;
self.velocity = 0.0;
}
fn node_type(&self) -> &str {
"MidiToCV"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
note: 60, // Reset to middle C
gate: 0.0, // Reset gate
velocity: 0.0, // Reset velocity
pitch_cv: Self::midi_note_to_voct(60), // Reset pitch
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,145 @@
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
pub struct MixerNode {
name: String,
gains: [f32; 4],
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl MixerNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
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),
];
let outputs = vec![
NodePort::new("Mixed Out", SignalType::Audio, 0),
];
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 {
name,
gains: [1.0, 1.0, 1.0, 1.0],
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for MixerNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
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),
_ => {}
}
}
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,
}
}
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];
// 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];
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 + 1] += input[frame * 2 + 1] * gain; // Right
}
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"Mixer"
}
fn name(&self) -> &str {
&self.name
}
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(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,25 @@
mod adsr;
mod audio_to_cv;
mod filter;
mod gain;
mod midi_input;
mod midi_to_cv;
mod mixer;
mod oscillator;
mod oscilloscope;
mod output;
mod template_io;
mod voice_allocator;
pub use adsr::ADSRNode;
pub use audio_to_cv::AudioToCVNode;
pub use filter::FilterNode;
pub use gain::GainNode;
pub use midi_input::MidiInputNode;
pub use midi_to_cv::MidiToCVNode;
pub use mixer::MixerNode;
pub use oscillator::OscillatorNode;
pub use oscilloscope::OscilloscopeNode;
pub use output::AudioOutputNode;
pub use template_io::{TemplateInputNode, TemplateOutputNode};
pub use voice_allocator::VoiceAllocatorNode;
@@ -0,0 +1,198 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use std::f32::consts::PI;
const PARAM_FREQUENCY: u32 = 0;
const PARAM_AMPLITUDE: u32 = 1;
const PARAM_WAVEFORM: u32 = 2;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Waveform {
Sine = 0,
Saw = 1,
Square = 2,
Triangle = 3,
}
impl Waveform {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => Waveform::Saw,
2 => Waveform::Square,
3 => Waveform::Triangle,
_ => Waveform::Sine,
}
}
}
/// Oscillator node with multiple waveforms
pub struct OscillatorNode {
name: String,
frequency: f32,
amplitude: f32,
waveform: Waveform,
phase: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl OscillatorNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("V/Oct", SignalType::CV, 0),
NodePort::new("FM", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_FREQUENCY, "Frequency", 20.0, 20000.0, 440.0, ParameterUnit::Frequency),
Parameter::new(PARAM_AMPLITUDE, "Amplitude", 0.0, 1.0, 0.5, ParameterUnit::Generic),
Parameter::new(PARAM_WAVEFORM, "Waveform", 0.0, 3.0, 0.0, ParameterUnit::Generic),
];
Self {
name,
frequency: 440.0,
amplitude: 0.5,
waveform: Waveform::Sine,
phase: 0.0,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for OscillatorNode {
fn category(&self) -> NodeCategory {
NodeCategory::Generator
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_FREQUENCY => self.frequency = value.clamp(20.0, 20000.0),
PARAM_AMPLITUDE => self.amplitude = value.clamp(0.0, 1.0),
PARAM_WAVEFORM => self.waveform = Waveform::from_f32(value),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_FREQUENCY => self.frequency,
PARAM_AMPLITUDE => self.amplitude,
PARAM_WAVEFORM => self.waveform as i32 as 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 sample_rate_f32 = sample_rate as f32;
// Audio signals are stereo (interleaved L/R)
// Process by frames, not samples
let frames = output.len() / 2;
for frame in 0..frames {
// Start with base frequency
let mut frequency = self.frequency;
// V/Oct input: 0.0-1.0 maps to MIDI notes 0-127
if !inputs.is_empty() && frame < inputs[0].len() {
let voct = inputs[0][frame]; // Read V/Oct CV (mono)
if voct > 0.001 {
// Convert CV to MIDI note number (0-1 -> 0-127)
let midi_note = voct * 127.0;
// Convert MIDI note to frequency: f = 440 * 2^((n-69)/12)
frequency = 440.0 * 2.0_f32.powf((midi_note - 69.0) / 12.0);
}
}
// FM input: modulates the frequency
if inputs.len() > 1 && frame < inputs[1].len() {
let fm = inputs[1][frame]; // Read FM CV (mono)
frequency *= 1.0 + fm;
}
let freq_mod = frequency;
// Generate waveform sample based on waveform type
let sample = match self.waveform {
Waveform::Sine => (self.phase * 2.0 * PI).sin(),
Waveform::Saw => 2.0 * self.phase - 1.0, // Ramp from -1 to 1
Waveform::Square => {
if self.phase < 0.5 { 1.0 } else { -1.0 }
}
Waveform::Triangle => {
// Triangle: rises from -1 to 1, falls back to -1
4.0 * (self.phase - 0.5).abs() - 1.0
}
} * self.amplitude;
// Write to both channels (mono source duplicated to stereo)
output[frame * 2] = sample; // Left
output[frame * 2 + 1] = sample; // Right
// Update phase once per frame
self.phase += freq_mod / sample_rate_f32;
if self.phase >= 1.0 {
self.phase -= 1.0;
}
}
}
fn reset(&mut self) {
self.phase = 0.0;
}
fn node_type(&self) -> &str {
"Oscillator"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
frequency: self.frequency,
amplitude: self.amplitude,
waveform: self.waveform,
phase: 0.0, // Reset phase for new instance
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,253 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use std::sync::{Arc, Mutex};
const PARAM_TIME_SCALE: u32 = 0;
const PARAM_TRIGGER_MODE: u32 = 1;
const PARAM_TRIGGER_LEVEL: u32 = 2;
const BUFFER_SIZE: usize = 96000; // 2 seconds at 48kHz (stereo)
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TriggerMode {
FreeRunning = 0,
RisingEdge = 1,
FallingEdge = 2,
}
impl TriggerMode {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => TriggerMode::RisingEdge,
2 => TriggerMode::FallingEdge,
_ => TriggerMode::FreeRunning,
}
}
}
/// Circular buffer for storing audio samples
struct CircularBuffer {
buffer: Vec<f32>,
write_pos: usize,
capacity: usize,
}
impl CircularBuffer {
fn new(capacity: usize) -> Self {
Self {
buffer: vec![0.0; capacity],
write_pos: 0,
capacity,
}
}
fn write(&mut self, samples: &[f32]) {
for &sample in samples {
self.buffer[self.write_pos] = sample;
self.write_pos = (self.write_pos + 1) % self.capacity;
}
}
fn read(&self, count: usize) -> Vec<f32> {
let count = count.min(self.capacity);
let mut result = Vec::with_capacity(count);
// Read backwards from current write position
let start_pos = if self.write_pos >= count {
self.write_pos - count
} else {
self.capacity - (count - self.write_pos)
};
for i in 0..count {
let pos = (start_pos + i) % self.capacity;
result.push(self.buffer[pos]);
}
result
}
fn clear(&mut self) {
self.buffer.fill(0.0);
self.write_pos = 0;
}
}
/// Oscilloscope node for visualizing audio signals
pub struct OscilloscopeNode {
name: String,
time_scale: f32, // Milliseconds to display (10-1000ms)
trigger_mode: TriggerMode,
trigger_level: f32, // -1.0 to 1.0
last_sample: f32, // For edge detection
// Shared buffer for reading from Tauri commands
buffer: Arc<Mutex<CircularBuffer>>,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl OscilloscopeNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_TIME_SCALE, "Time Scale", 10.0, 1000.0, 100.0, ParameterUnit::Milliseconds),
Parameter::new(PARAM_TRIGGER_MODE, "Trigger", 0.0, 2.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_TRIGGER_LEVEL, "Trigger Level", -1.0, 1.0, 0.0, ParameterUnit::Generic),
];
Self {
name,
time_scale: 100.0,
trigger_mode: TriggerMode::FreeRunning,
trigger_level: 0.0,
last_sample: 0.0,
buffer: Arc::new(Mutex::new(CircularBuffer::new(BUFFER_SIZE))),
inputs,
outputs,
parameters,
}
}
/// Get a clone of the buffer Arc for reading from external code (Tauri commands)
pub fn get_buffer(&self) -> Arc<Mutex<CircularBuffer>> {
Arc::clone(&self.buffer)
}
/// Read samples from the buffer (for Tauri commands)
pub fn read_samples(&self, count: usize) -> Vec<f32> {
if let Ok(buffer) = self.buffer.lock() {
buffer.read(count)
} else {
vec![0.0; count]
}
}
/// Clear the buffer
pub fn clear_buffer(&self) {
if let Ok(mut buffer) = self.buffer.lock() {
buffer.clear();
}
}
/// Check if trigger condition is met
fn is_triggered(&self, current_sample: f32) -> bool {
match self.trigger_mode {
TriggerMode::FreeRunning => true,
TriggerMode::RisingEdge => {
self.last_sample <= self.trigger_level && current_sample > self.trigger_level
}
TriggerMode::FallingEdge => {
self.last_sample >= self.trigger_level && current_sample < self.trigger_level
}
}
}
}
impl AudioNode for OscilloscopeNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_TIME_SCALE => self.time_scale = value.clamp(10.0, 1000.0),
PARAM_TRIGGER_MODE => self.trigger_mode = TriggerMode::from_f32(value),
PARAM_TRIGGER_LEVEL => self.trigger_level = value.clamp(-1.0, 1.0),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_TIME_SCALE => self.time_scale,
PARAM_TRIGGER_MODE => self.trigger_mode as i32 as f32,
PARAM_TRIGGER_LEVEL => self.trigger_level,
_ => 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 inputs.is_empty() || outputs.is_empty() {
return;
}
let input = inputs[0];
let output = &mut outputs[0];
let len = input.len().min(output.len());
// Pass through audio (copy input to output)
output[..len].copy_from_slice(&input[..len]);
// Capture samples to buffer
if let Ok(mut buffer) = self.buffer.lock() {
buffer.write(&input[..len]);
}
// Update last sample for trigger detection (use left channel, frame 0)
if !input.is_empty() {
self.last_sample = input[0];
}
}
fn reset(&mut self) {
self.last_sample = 0.0;
self.clear_buffer();
}
fn node_type(&self) -> &str {
"Oscilloscope"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
time_scale: self.time_scale,
trigger_mode: self.trigger_mode,
trigger_level: self.trigger_level,
last_sample: 0.0,
buffer: Arc::new(Mutex::new(CircularBuffer::new(BUFFER_SIZE))),
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
fn get_oscilloscope_data(&self, sample_count: usize) -> Option<Vec<f32>> {
Some(self.read_samples(sample_count))
}
}
@@ -0,0 +1,96 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
/// Audio output node - collects audio and passes it to the main output
pub struct AudioOutputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
}
impl AudioOutputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
// Output node has an output for graph consistency, but it's typically the final node
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
Self {
name,
inputs,
outputs,
}
}
}
impl AudioNode for AudioOutputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Output
}
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 inputs.is_empty() || outputs.is_empty() {
return;
}
// Simply pass through the input to the output
let input = inputs[0];
let output = &mut outputs[0];
let len = input.len().min(output.len());
output[..len].copy_from_slice(&input[..len]);
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"AudioOutput"
}
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(),
})
}
}
@@ -0,0 +1,176 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
/// Template Input node - represents the MIDI input for one voice in a VoiceAllocator
pub struct TemplateInputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl TemplateInputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![];
let outputs = vec![
NodePort::new("MIDI Out", SignalType::Midi, 0),
];
Self {
name,
inputs,
outputs,
parameters: vec![],
}
}
}
impl AudioNode for TemplateInputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
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,
) {
// TemplateInput receives MIDI from VoiceAllocator and outputs it
// The MIDI was already placed in midi_outputs by the graph before calling process()
// So there's nothing to do here - the MIDI is already in the output buffer
}
fn reset(&mut self) {}
fn node_type(&self) -> &str {
"TemplateInput"
}
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(),
parameters: self.parameters.clone(),
})
}
fn handle_midi(&mut self, _event: &MidiEvent) {
// Pass through to connected nodes
}
}
/// Template Output node - represents the audio output from one voice in a VoiceAllocator
pub struct TemplateOutputNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl TemplateOutputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
Self {
name,
inputs,
outputs,
parameters: vec![],
}
}
}
impl AudioNode for TemplateOutputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Output
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
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 input to output - the graph reads from output buffers
if !inputs.is_empty() && !outputs.is_empty() {
let input = inputs[0];
let output = &mut outputs[0];
let len = input.len().min(output.len());
output[..len].copy_from_slice(&input[..len]);
}
}
fn reset(&mut self) {}
fn node_type(&self) -> &str {
"TemplateOutput"
}
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(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,344 @@
use crate::audio::midi::MidiEvent;
use crate::audio::node_graph::{AudioNode, InstrumentGraph, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
const PARAM_VOICE_COUNT: u32 = 0;
const MAX_VOICES: usize = 16; // Maximum allowed voices
const DEFAULT_VOICES: usize = 8;
/// Voice state for voice allocation
#[derive(Clone)]
struct VoiceState {
active: bool,
note: u8,
age: u32, // For voice stealing
pending_events: Vec<MidiEvent>, // MIDI events to send to this voice
}
impl VoiceState {
fn new() -> Self {
Self {
active: false,
note: 0,
age: 0,
pending_events: Vec::new(),
}
}
}
/// VoiceAllocatorNode - A group node that creates N polyphonic instances of its internal graph
///
/// This node acts as a container for a "voice template" graph. At runtime, it creates
/// N instances of that graph (one per voice) and routes MIDI note events to them.
/// All voice outputs are mixed together into a single output.
pub struct VoiceAllocatorNode {
name: String,
/// The template graph (edited by user via UI)
template_graph: InstrumentGraph,
/// Runtime voice instances (clones of template)
voice_instances: Vec<InstrumentGraph>,
/// Voice allocation state
voices: [VoiceState; MAX_VOICES],
/// Number of active voices (configurable parameter)
voice_count: usize,
/// Mix buffer for combining voice outputs
mix_buffer: Vec<f32>,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl VoiceAllocatorNode {
pub fn new(name: impl Into<String>, sample_rate: u32, buffer_size: usize) -> Self {
let name = name.into();
// MIDI input for receiving note events
let inputs = vec![
NodePort::new("MIDI In", SignalType::Midi, 0),
];
// Single mixed audio output
let outputs = vec![
NodePort::new("Mixed Out", SignalType::Audio, 0),
];
// Voice count parameter
let parameters = vec![
Parameter::new(PARAM_VOICE_COUNT, "Voices", 1.0, MAX_VOICES as f32, DEFAULT_VOICES as f32, ParameterUnit::Generic),
];
// Create empty template graph
let template_graph = InstrumentGraph::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))
.collect();
Self {
name,
template_graph,
voice_instances,
voices: std::array::from_fn(|_| VoiceState::new()),
voice_count: DEFAULT_VOICES,
mix_buffer: vec![0.0; buffer_size * 2], // Stereo
inputs,
outputs,
parameters,
}
}
/// Get mutable reference to template graph (for UI editing)
pub fn template_graph_mut(&mut self) -> &mut InstrumentGraph {
&mut self.template_graph
}
/// Get reference to template graph (for serialization)
pub fn template_graph(&self) -> &InstrumentGraph {
&self.template_graph
}
/// Rebuild voice instances from template (called after template is edited)
pub fn rebuild_voices(&mut self) {
// Clone template to all voice instances
for voice in &mut self.voice_instances {
*voice = self.template_graph.clone_graph();
// Find TemplateInput and TemplateOutput nodes
let mut template_input_idx = None;
let mut template_output_idx = None;
for node_idx in voice.node_indices() {
if let Some(node) = voice.get_node(node_idx) {
match node.node_type() {
"TemplateInput" => template_input_idx = Some(node_idx),
"TemplateOutput" => template_output_idx = Some(node_idx),
_ => {}
}
}
}
// Mark ONLY TemplateInput as a MIDI target
// MIDI will flow through graph connections to other nodes (like MidiToCV)
if let Some(input_idx) = template_input_idx {
voice.set_midi_target(input_idx, true);
}
// Set TemplateOutput as output node
voice.set_output_node(template_output_idx);
}
}
/// Find a free voice, or steal the oldest one
fn find_voice_for_note_on(&mut self) -> usize {
// Only search within active voice_count
// First, look for an inactive voice
for (i, voice) in self.voices[..self.voice_count].iter().enumerate() {
if !voice.active {
return i;
}
}
// No free voices, steal the oldest one within voice_count
self.voices[..self.voice_count]
.iter()
.enumerate()
.max_by_key(|(_, v)| v.age)
.map(|(i, _)| i)
.unwrap_or(0)
}
/// Find all voices playing a specific note
fn find_voices_for_note_off(&self, note: u8) -> Vec<usize> {
self.voices[..self.voice_count]
.iter()
.enumerate()
.filter_map(|(i, v)| {
if v.active && v.note == note {
Some(i)
} else {
None
}
})
.collect()
}
}
impl AudioNode for VoiceAllocatorNode {
fn category(&self) -> NodeCategory {
NodeCategory::Utility
}
fn inputs(&self) -> &[NodePort] {
&self.inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, id: u32, value: f32) {
match id {
PARAM_VOICE_COUNT => {
let new_count = (value.round() as usize).clamp(1, MAX_VOICES);
if new_count != self.voice_count {
self.voice_count = new_count;
// Stop voices beyond the new count
for voice in &mut self.voices[new_count..] {
voice.active = false;
}
}
}
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_VOICE_COUNT => self.voice_count as f32,
_ => 0.0,
}
}
fn handle_midi(&mut self, event: &MidiEvent) {
let status = event.status & 0xF0;
match status {
0x90 => {
// Note on
if event.data2 > 0 {
let voice_idx = self.find_voice_for_note_on();
self.voices[voice_idx].active = true;
self.voices[voice_idx].note = event.data1;
self.voices[voice_idx].age = 0;
// Store MIDI event for this voice to process
self.voices[voice_idx].pending_events.push(*event);
} else {
// Velocity = 0 means note off - send to ALL voices playing this note
let voice_indices = self.find_voices_for_note_off(event.data1);
for voice_idx in voice_indices {
self.voices[voice_idx].active = false;
self.voices[voice_idx].pending_events.push(*event);
}
}
}
0x80 => {
// Note off - send to ALL voices playing this note
let voice_indices = self.find_voices_for_note_off(event.data1);
for voice_idx in voice_indices {
self.voices[voice_idx].active = false;
self.voices[voice_idx].pending_events.push(*event);
}
}
_ => {
// Other MIDI events (CC, pitch bend, etc.) - send to all active voices
for voice_idx in 0..self.voice_count {
if self.voices[voice_idx].active {
self.voices[voice_idx].pending_events.push(*event);
}
}
}
}
}
fn process(
&mut self,
_inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
_sample_rate: u32,
) {
// Process MIDI events from input (allocate notes to voices)
if !midi_inputs.is_empty() {
for event in midi_inputs[0] {
self.handle_midi(event);
}
}
if outputs.is_empty() {
return;
}
let output = &mut outputs[0];
let output_len = output.len();
// Process each active voice and mix (only up to voice_count)
for voice_idx in 0..self.voice_count {
let voice_state = &mut self.voices[voice_idx];
if voice_state.active {
voice_state.age = voice_state.age.saturating_add(1);
// Get pending MIDI events for this voice
let midi_events = std::mem::take(&mut voice_state.pending_events);
// IMPORTANT: Process only the slice of mix_buffer that matches output size
// This prevents phase discontinuities in oscillators
let mix_slice = &mut self.mix_buffer[..output_len];
mix_slice.fill(0.0);
// Process this voice's graph with its MIDI events
self.voice_instances[voice_idx].process(mix_slice, &midi_events);
// Mix into output (accumulate)
for (i, sample) in mix_slice.iter().enumerate() {
output[i] += sample;
}
}
}
// Apply normalization to prevent clipping (divide by active voice count)
let active_count = self.voices[..self.voice_count].iter().filter(|v| v.active).count();
if active_count > 1 {
let scale = 1.0 / (active_count as f32).sqrt(); // Use sqrt for better loudness perception
for sample in output.iter_mut() {
*sample *= scale;
}
}
}
fn reset(&mut self) {
for voice in &mut self.voices {
voice.active = false;
voice.pending_events.clear();
}
for graph in &mut self.voice_instances {
graph.reset();
}
self.template_graph.reset();
}
fn node_type(&self) -> &str {
"VoiceAllocator"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
// Clone creates a new VoiceAllocator with the same template graph
// Voice instances will be rebuilt when rebuild_voices() is called
Box::new(Self {
name: self.name.clone(),
template_graph: self.template_graph.clone_graph(),
voice_instances: self.voice_instances.iter().map(|g| g.clone_graph()).collect(),
voices: std::array::from_fn(|_| VoiceState::new()), // Reset voices
voice_count: self.voice_count,
mix_buffer: vec![0.0; self.mix_buffer.len()],
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
+96
View File
@@ -0,0 +1,96 @@
use serde::{Deserialize, Serialize};
/// Three distinct signal types for graph edges
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SignalType {
/// Audio-rate signals (-1.0 to 1.0 typically) - Blue in UI
Audio,
/// MIDI events (discrete messages) - Green in UI
Midi,
/// Control Voltage (modulation signals, typically 0.0 to 1.0) - Orange in UI
CV,
}
/// Port definition for node inputs/outputs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodePort {
pub name: String,
pub signal_type: SignalType,
pub index: usize,
}
impl NodePort {
pub fn new(name: impl Into<String>, signal_type: SignalType, index: usize) -> Self {
Self {
name: name.into(),
signal_type,
index,
}
}
}
/// Node category for UI organization
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum NodeCategory {
Input,
Generator,
Effect,
Utility,
Output,
}
/// User-facing parameter definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Parameter {
pub id: u32,
pub name: String,
pub min: f32,
pub max: f32,
pub default: f32,
pub unit: ParameterUnit,
}
impl Parameter {
pub fn new(id: u32, name: impl Into<String>, min: f32, max: f32, default: f32, unit: ParameterUnit) -> Self {
Self {
id,
name: name.into(),
min,
max,
default,
unit,
}
}
}
/// Units for parameter values
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ParameterUnit {
Generic,
Frequency, // Hz
Decibels, // dB
Time, // seconds
Percent, // 0-100
}
/// Errors that can occur during graph operations
#[derive(Debug, Clone)]
pub enum ConnectionError {
TypeMismatch { expected: SignalType, got: SignalType },
InvalidPort,
WouldCreateCycle,
}
impl std::fmt::Display for ConnectionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConnectionError::TypeMismatch { expected, got } => {
write!(f, "Signal type mismatch: expected {:?}, got {:?}", expected, got)
}
ConnectionError::InvalidPort => write!(f, "Invalid port index"),
ConnectionError::WouldCreateCycle => write!(f, "Connection would create a cycle"),
}
}
}
impl std::error::Error for ConnectionError {}