Fix preset loading, add LFO, noise, pan and splitter nodes

This commit is contained in:
Skyler Lehmkuhl
2025-10-25 07:29:14 -04:00
parent 139946fb75
commit e57ae51397
16 changed files with 1466 additions and 128 deletions
+72 -1
View File
@@ -410,6 +410,7 @@ dependencies = [
"dasp_signal",
"midly",
"petgraph 0.6.5",
"rand",
"ratatui",
"rtrb",
"serde",
@@ -468,6 +469,17 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "getrandom"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -587,7 +599,7 @@ version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
dependencies = [
"getrandom",
"getrandom 0.3.4",
"libc",
]
@@ -854,6 +866,15 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro-crate"
version = "3.4.0"
@@ -887,6 +908,36 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.16",
]
[[package]]
name = "ratatui"
version = "0.26.3"
@@ -1804,3 +1855,23 @@ name = "wit-bindgen"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
[[package]]
name = "zerocopy"
version = "0.8.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
+1
View File
@@ -11,6 +11,7 @@ midly = "0.5"
serde = { version = "1.0", features = ["derive"] }
ratatui = "0.26"
crossterm = "0.27"
rand = "0.8"
# Node-based audio graph dependencies
dasp_graph = "0.11"
+42
View File
@@ -739,6 +739,10 @@ impl Engine {
"Mixer" => Box::new(MixerNode::new("Mixer".to_string())),
"Filter" => Box::new(FilterNode::new("Filter".to_string())),
"ADSR" => Box::new(ADSRNode::new("ADSR".to_string())),
"LFO" => Box::new(LFONode::new("LFO".to_string())),
"NoiseGenerator" => Box::new(NoiseGeneratorNode::new("Noise".to_string())),
"Splitter" => Box::new(SplitterNode::new("Splitter".to_string())),
"Pan" => Box::new(PanNode::new("Pan".to_string())),
"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())),
@@ -786,6 +790,10 @@ impl Engine {
"Mixer" => Box::new(MixerNode::new("Mixer".to_string())),
"Filter" => Box::new(FilterNode::new("Filter".to_string())),
"ADSR" => Box::new(ADSRNode::new("ADSR".to_string())),
"LFO" => Box::new(LFONode::new("LFO".to_string())),
"NoiseGenerator" => Box::new(NoiseGeneratorNode::new("Noise".to_string())),
"Splitter" => Box::new(SplitterNode::new("Splitter".to_string())),
"Pan" => Box::new(PanNode::new("Pan".to_string())),
"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())),
@@ -976,6 +984,35 @@ impl Engine {
}
}
}
Command::GraphSaveTemplatePreset(track_id, voice_allocator_id, preset_path, preset_name) => {
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(ref graph) = track.instrument_graph {
let va_idx = NodeIndex::new(voice_allocator_id as usize);
// Get the VoiceAllocator node and serialize its template
if let Some(node) = graph.get_node(va_idx) {
// Downcast to VoiceAllocatorNode
let node_ptr = node as *const dyn crate::audio::node_graph::AudioNode;
let node_ptr = node_ptr as *const VoiceAllocatorNode;
unsafe {
let va_node = &*node_ptr;
let template_preset = va_node.template_graph().to_preset(&preset_name);
// Write to file
if let Ok(json) = template_preset.to_json() {
if let Err(e) = std::fs::write(&preset_path, json) {
eprintln!("Failed to save template preset: {}", e);
}
}
}
}
}
}
}
}
}
@@ -1456,4 +1493,9 @@ impl EngineController {
pub fn graph_load_preset(&mut self, track_id: TrackId, preset_path: String) {
let _ = self.command_tx.push(Command::GraphLoadPreset(track_id, preset_path));
}
/// Save a VoiceAllocator's template graph as a preset
pub fn graph_save_template_preset(&mut self, track_id: TrackId, voice_allocator_id: u32, preset_path: String, preset_name: String) {
let _ = self.command_tx.push(Command::GraphSaveTemplatePreset(track_id, voice_allocator_id, preset_path, preset_name));
}
}
+24
View File
@@ -125,6 +125,17 @@ impl InstrumentGraph {
to: NodeIndex,
to_port: usize,
) -> Result<(), ConnectionError> {
eprintln!("[GRAPH] connect() called: {:?} port {} -> {:?} port {}", from, from_port, to, to_port);
// Check if this exact connection already exists
if let Some(edge_idx) = self.graph.find_edge(from, to) {
let existing_conn = &self.graph[edge_idx];
if existing_conn.from_port == from_port && existing_conn.to_port == to_port {
eprintln!("[GRAPH] Connection already exists, skipping duplicate");
return Ok(()); // Connection already exists, don't create duplicate
}
}
// Validate the connection
self.validate_connection(from, from_port, to, to_port)?;
@@ -310,6 +321,11 @@ impl InstrumentGraph {
// Use the requested output buffer size for processing
let process_size = output_buffer.len();
if process_size > self.buffer_size * 2 {
eprintln!("[GRAPH] WARNING: process_size {} > allocated buffer_size {} * 2",
process_size, self.buffer_size);
}
// Clear all output buffers (audio/CV and MIDI)
for node in self.graph.node_weights_mut() {
for buffer in &mut node.output_buffers {
@@ -670,8 +686,10 @@ impl InstrumentGraph {
index_map.insert(serialized_node.id, node_idx);
// Set parameters
eprintln!("[PRESET] Node {}: type={}, params={:?}", serialized_node.id, serialized_node.node_type, serialized_node.parameters);
for (&param_id, &value) in &serialized_node.parameters {
if let Some(graph_node) = graph.graph.node_weight_mut(node_idx) {
eprintln!("[PRESET] Setting param {} = {}", param_id, value);
graph_node.node.set_parameter(param_id, value);
}
}
@@ -681,26 +699,32 @@ impl InstrumentGraph {
}
// Create connections
eprintln!("[PRESET] Creating {} connections", preset.connections.len());
for conn in &preset.connections {
let from_idx = index_map.get(&conn.from_node)
.ok_or_else(|| format!("Connection from unknown node {}", conn.from_node))?;
let to_idx = index_map.get(&conn.to_node)
.ok_or_else(|| format!("Connection to unknown node {}", conn.to_node))?;
eprintln!("[PRESET] Connecting: node {} port {} -> node {} port {}", conn.from_node, conn.from_port, conn.to_node, conn.to_port);
graph.connect(*from_idx, conn.from_port, *to_idx, conn.to_port)
.map_err(|e| format!("Failed to connect nodes: {:?}", e))?;
}
// Set MIDI targets
eprintln!("[PRESET] Setting MIDI targets: {:?}", preset.midi_targets);
for &target_id in &preset.midi_targets {
if let Some(&target_idx) = index_map.get(&target_id) {
eprintln!("[PRESET] MIDI target: node {} -> index {:?}", target_id, target_idx);
graph.set_midi_target(target_idx, true);
}
}
// Set output node
eprintln!("[PRESET] Setting output node: {:?}", preset.output_node);
if let Some(output_id) = preset.output_node {
if let Some(&output_idx) = index_map.get(&output_id) {
eprintln!("[PRESET] Output node: {} -> index {:?}", output_id, output_idx);
graph.output_node = Some(output_idx);
}
}
@@ -0,0 +1,222 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use std::f32::consts::PI;
use rand::Rng;
const PARAM_FREQUENCY: u32 = 0;
const PARAM_AMPLITUDE: u32 = 1;
const PARAM_WAVEFORM: u32 = 2;
const PARAM_PHASE_OFFSET: u32 = 3;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LFOWaveform {
Sine = 0,
Triangle = 1,
Saw = 2,
Square = 3,
Random = 4,
}
impl LFOWaveform {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => LFOWaveform::Triangle,
2 => LFOWaveform::Saw,
3 => LFOWaveform::Square,
4 => LFOWaveform::Random,
_ => LFOWaveform::Sine,
}
}
}
/// Low Frequency Oscillator node for modulation
pub struct LFONode {
name: String,
frequency: f32,
amplitude: f32,
waveform: LFOWaveform,
phase_offset: f32,
phase: f32,
last_random_value: f32,
next_random_value: f32,
random_phase: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl LFONode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![];
let outputs = vec![
NodePort::new("CV Out", SignalType::CV, 0),
];
let parameters = vec![
Parameter::new(PARAM_FREQUENCY, "Frequency", 0.01, 20.0, 1.0, ParameterUnit::Frequency),
Parameter::new(PARAM_AMPLITUDE, "Amplitude", 0.0, 1.0, 1.0, ParameterUnit::Generic),
Parameter::new(PARAM_WAVEFORM, "Waveform", 0.0, 4.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_PHASE_OFFSET, "Phase", 0.0, 1.0, 0.0, ParameterUnit::Generic),
];
let mut rng = rand::thread_rng();
Self {
name,
frequency: 1.0,
amplitude: 1.0,
waveform: LFOWaveform::Sine,
phase_offset: 0.0,
phase: 0.0,
last_random_value: rng.gen_range(-1.0..1.0),
next_random_value: rng.gen_range(-1.0..1.0),
random_phase: 0.0,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for LFONode {
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_FREQUENCY => self.frequency = value.clamp(0.01, 20.0),
PARAM_AMPLITUDE => self.amplitude = value.clamp(0.0, 1.0),
PARAM_WAVEFORM => self.waveform = LFOWaveform::from_f32(value),
PARAM_PHASE_OFFSET => self.phase_offset = value.clamp(0.0, 1.0),
_ => {}
}
}
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,
PARAM_PHASE_OFFSET => self.phase_offset,
_ => 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
for sample_idx in 0..output.len() {
let current_phase = (self.phase + self.phase_offset) % 1.0;
// Generate waveform sample based on waveform type
let raw_sample = match self.waveform {
LFOWaveform::Sine => (current_phase * 2.0 * PI).sin(),
LFOWaveform::Triangle => {
// Triangle: rises from -1 to 1, falls back to -1
4.0 * (current_phase - 0.5).abs() - 1.0
}
LFOWaveform::Saw => {
// Sawtooth: ramp from -1 to 1
2.0 * current_phase - 1.0
}
LFOWaveform::Square => {
if current_phase < 0.5 { 1.0 } else { -1.0 }
}
LFOWaveform::Random => {
// Sample & hold random values with smooth interpolation
// Interpolate between last and next random value
let t = self.random_phase;
self.last_random_value * (1.0 - t) + self.next_random_value * t
}
};
// Scale to 0-1 range and apply amplitude
let sample = (raw_sample * 0.5 + 0.5) * self.amplitude;
output[sample_idx] = sample;
// Update phase
self.phase += self.frequency / sample_rate_f32;
if self.phase >= 1.0 {
self.phase -= 1.0;
// For random waveform, generate new random value at each cycle
if self.waveform == LFOWaveform::Random {
self.last_random_value = self.next_random_value;
let mut rng = rand::thread_rng();
self.next_random_value = rng.gen_range(-1.0..1.0);
self.random_phase = 0.0;
}
}
// Update random interpolation phase
if self.waveform == LFOWaveform::Random {
self.random_phase += self.frequency / sample_rate_f32;
if self.random_phase >= 1.0 {
self.random_phase -= 1.0;
}
}
}
}
fn reset(&mut self) {
self.phase = 0.0;
self.random_phase = 0.0;
let mut rng = rand::thread_rng();
self.last_random_value = rng.gen_range(-1.0..1.0);
self.next_random_value = rng.gen_range(-1.0..1.0);
}
fn node_type(&self) -> &str {
"LFO"
}
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_offset: self.phase_offset,
phase: 0.0, // Reset phase for new instance
last_random_value: self.last_random_value,
next_random_value: self.next_random_value,
random_phase: 0.0,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -2,12 +2,16 @@ mod adsr;
mod audio_to_cv;
mod filter;
mod gain;
mod lfo;
mod midi_input;
mod midi_to_cv;
mod mixer;
mod noise;
mod oscillator;
mod oscilloscope;
mod output;
mod pan;
mod splitter;
mod template_io;
mod voice_allocator;
@@ -15,11 +19,15 @@ pub use adsr::ADSRNode;
pub use audio_to_cv::AudioToCVNode;
pub use filter::FilterNode;
pub use gain::GainNode;
pub use lfo::LFONode;
pub use midi_input::MidiInputNode;
pub use midi_to_cv::MidiToCVNode;
pub use mixer::MixerNode;
pub use noise::NoiseGeneratorNode;
pub use oscillator::OscillatorNode;
pub use oscilloscope::OscilloscopeNode;
pub use output::AudioOutputNode;
pub use pan::PanNode;
pub use splitter::SplitterNode;
pub use template_io::{TemplateInputNode, TemplateOutputNode};
pub use voice_allocator::VoiceAllocatorNode;
@@ -0,0 +1,197 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use rand::Rng;
const PARAM_AMPLITUDE: u32 = 0;
const PARAM_COLOR: u32 = 1;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum NoiseColor {
White = 0,
Pink = 1,
}
impl NoiseColor {
fn from_f32(value: f32) -> Self {
match value.round() as i32 {
1 => NoiseColor::Pink,
_ => NoiseColor::White,
}
}
}
/// Noise generator node with white and pink noise
pub struct NoiseGeneratorNode {
name: String,
amplitude: f32,
color: NoiseColor,
// Pink noise state (Paul Kellet's pink noise algorithm)
pink_b0: f32,
pink_b1: f32,
pink_b2: f32,
pink_b3: f32,
pink_b4: f32,
pink_b5: f32,
pink_b6: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl NoiseGeneratorNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_AMPLITUDE, "Amplitude", 0.0, 1.0, 0.5, ParameterUnit::Generic),
Parameter::new(PARAM_COLOR, "Color", 0.0, 1.0, 0.0, ParameterUnit::Generic),
];
Self {
name,
amplitude: 0.5,
color: NoiseColor::White,
pink_b0: 0.0,
pink_b1: 0.0,
pink_b2: 0.0,
pink_b3: 0.0,
pink_b4: 0.0,
pink_b5: 0.0,
pink_b6: 0.0,
inputs,
outputs,
parameters,
}
}
/// Generate white noise sample
fn generate_white(&self) -> f32 {
let mut rng = rand::thread_rng();
rng.gen_range(-1.0..1.0)
}
/// Generate pink noise sample using Paul Kellet's algorithm
fn generate_pink(&mut self) -> f32 {
let mut rng = rand::thread_rng();
let white: f32 = rng.gen_range(-1.0..1.0);
self.pink_b0 = 0.99886 * self.pink_b0 + white * 0.0555179;
self.pink_b1 = 0.99332 * self.pink_b1 + white * 0.0750759;
self.pink_b2 = 0.96900 * self.pink_b2 + white * 0.1538520;
self.pink_b3 = 0.86650 * self.pink_b3 + white * 0.3104856;
self.pink_b4 = 0.55000 * self.pink_b4 + white * 0.5329522;
self.pink_b5 = -0.7616 * self.pink_b5 - white * 0.0168980;
let pink = self.pink_b0 + self.pink_b1 + self.pink_b2 + self.pink_b3 + self.pink_b4 + self.pink_b5 + self.pink_b6 + white * 0.5362;
self.pink_b6 = white * 0.115926;
// Scale to approximately -1 to 1
pink * 0.11
}
}
impl AudioNode for NoiseGeneratorNode {
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_AMPLITUDE => self.amplitude = value.clamp(0.0, 1.0),
PARAM_COLOR => self.color = NoiseColor::from_f32(value),
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_AMPLITUDE => self.amplitude,
PARAM_COLOR => self.color 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];
// Audio signals are stereo (interleaved L/R)
// Process by frames, not samples
let frames = output.len() / 2;
for frame in 0..frames {
let sample = match self.color {
NoiseColor::White => self.generate_white(),
NoiseColor::Pink => self.generate_pink(),
} * self.amplitude;
// Write to both channels (mono source duplicated to stereo)
output[frame * 2] = sample; // Left
output[frame * 2 + 1] = sample; // Right
}
}
fn reset(&mut self) {
self.pink_b0 = 0.0;
self.pink_b1 = 0.0;
self.pink_b2 = 0.0;
self.pink_b3 = 0.0;
self.pink_b4 = 0.0;
self.pink_b5 = 0.0;
self.pink_b6 = 0.0;
}
fn node_type(&self) -> &str {
"NoiseGenerator"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
amplitude: self.amplitude,
color: self.color,
pink_b0: 0.0,
pink_b1: 0.0,
pink_b2: 0.0,
pink_b3: 0.0,
pink_b4: 0.0,
pink_b5: 0.0,
pink_b6: 0.0,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,168 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
use std::f32::consts::PI;
const PARAM_PAN: u32 = 0;
/// Stereo panning node using constant-power panning law
/// Converts mono audio to stereo with controllable pan position
pub struct PanNode {
name: String,
pan: f32,
left_gain: f32,
right_gain: f32,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl PanNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let inputs = vec![
NodePort::new("Audio In", SignalType::Audio, 0),
NodePort::new("Pan CV", SignalType::CV, 1),
];
let outputs = vec![
NodePort::new("Audio Out", SignalType::Audio, 0),
];
let parameters = vec![
Parameter::new(PARAM_PAN, "Pan", -1.0, 1.0, 0.0, ParameterUnit::Generic),
];
let mut node = Self {
name,
pan: 0.0,
left_gain: 1.0,
right_gain: 1.0,
inputs,
outputs,
parameters,
};
node.update_gains();
node
}
/// Update left/right gains using constant-power panning law
fn update_gains(&mut self) {
// Constant-power panning: pan from -1 to +1 maps to angle 0 to PI/2
let angle = (self.pan + 1.0) * 0.5 * PI / 2.0;
self.left_gain = angle.cos();
self.right_gain = angle.sin();
}
}
impl AudioNode for PanNode {
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_PAN => {
self.pan = value.clamp(-1.0, 1.0);
self.update_gains();
}
_ => {}
}
}
fn get_parameter(&self, id: u32) -> f32 {
match id {
PARAM_PAN => self.pan,
_ => 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 audio_input = inputs[0];
let output = &mut outputs[0];
// Audio signals are stereo (interleaved L/R)
// Process by frames, not samples
let frames = audio_input.len() / 2;
let output_frames = output.len() / 2;
let frames_to_process = frames.min(output_frames);
for frame in 0..frames_to_process {
// Get base pan position
let mut pan = self.pan;
// Add CV modulation if connected
if inputs.len() > 1 && frame < inputs[1].len() {
let cv = inputs[1][frame]; // CV is mono
// CV is 0-1, map to -1 to +1 range
pan += (cv * 2.0 - 1.0);
pan = pan.clamp(-1.0, 1.0);
}
// Update gains if pan changed from CV
let angle = (pan + 1.0) * 0.5 * PI / 2.0;
let left_gain = angle.cos();
let right_gain = angle.sin();
// Read stereo input
let left_in = audio_input[frame * 2];
let right_in = audio_input[frame * 2 + 1];
// Mix both input channels with panning
// When pan is -1 (full left), left gets full signal, right gets nothing
// When pan is 0 (center), both get equal signal
// When pan is +1 (full right), right gets full signal, left gets nothing
output[frame * 2] = (left_in + right_in) * left_gain; // Left
output[frame * 2 + 1] = (left_in + right_in) * right_gain; // Right
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"Pan"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
pan: self.pan,
left_gain: self.left_gain,
right_gain: self.right_gain,
inputs: self.inputs.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
})
}
}
@@ -0,0 +1,104 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
use crate::audio::midi::MidiEvent;
/// Splitter node - copies input to multiple outputs for parallel routing
pub struct SplitterNode {
name: String,
inputs: Vec<NodePort>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
}
impl SplitterNode {
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("Out 1", SignalType::Audio, 0),
NodePort::new("Out 2", SignalType::Audio, 1),
NodePort::new("Out 3", SignalType::Audio, 2),
NodePort::new("Out 4", SignalType::Audio, 3),
];
let parameters = vec![];
Self {
name,
inputs,
outputs,
parameters,
}
}
}
impl AudioNode for SplitterNode {
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) {
// 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;
}
let input = inputs[0];
// Copy input to all outputs
for output in outputs.iter_mut() {
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 {
"Splitter"
}
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(),
})
}
}
+2
View File
@@ -142,6 +142,8 @@ pub enum Command {
GraphSavePreset(TrackId, String, String, String, Vec<String>),
/// Load a preset into a track's graph (track_id, preset_path)
GraphLoadPreset(TrackId, String),
/// Save a VoiceAllocator's template graph as a preset (track_id, voice_allocator_id, preset_path, preset_name)
GraphSaveTemplatePreset(TrackId, u32, String, String),
}
/// Events sent from audio thread back to UI/control thread