diff --git a/daw-backend/src/audio/engine.rs b/daw-backend/src/audio/engine.rs index 2bb7c53..b07d840 100644 --- a/daw-backend/src/audio/engine.rs +++ b/daw-backend/src/audio/engine.rs @@ -1153,6 +1153,7 @@ impl Engine { "Gain" => Box::new(GainNode::new("Gain".to_string())), "Mixer" => Box::new(MixerNode::new("Mixer".to_string())), "Filter" => Box::new(FilterNode::new("Filter".to_string())), + "SVF" => Box::new(SVFNode::new("SVF".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())), @@ -1244,6 +1245,7 @@ impl Engine { "Gain" => Box::new(GainNode::new("Gain".to_string())), "Mixer" => Box::new(MixerNode::new("Mixer".to_string())), "Filter" => Box::new(FilterNode::new("Filter".to_string())), + "SVF" => Box::new(SVFNode::new("SVF".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())), diff --git a/daw-backend/src/audio/node_graph/graph.rs b/daw-backend/src/audio/node_graph/graph.rs index 4cd1f46..865d256 100644 --- a/daw-backend/src/audio/node_graph/graph.rs +++ b/daw-backend/src/audio/node_graph/graph.rs @@ -988,6 +988,7 @@ impl AudioGraph { "Gain" => Box::new(GainNode::new("Gain")), "Mixer" => Box::new(MixerNode::new("Mixer")), "Filter" => Box::new(FilterNode::new("Filter")), + "SVF" => Box::new(SVFNode::new("SVF")), "ADSR" => Box::new(ADSRNode::new("ADSR")), "LFO" => Box::new(LFONode::new("LFO")), "NoiseGenerator" => Box::new(NoiseGeneratorNode::new("Noise")), diff --git a/daw-backend/src/audio/node_graph/nodes/mod.rs b/daw-backend/src/audio/node_graph/nodes/mod.rs index d37f4d3..80599bb 100644 --- a/daw-backend/src/audio/node_graph/nodes/mod.rs +++ b/daw-backend/src/audio/node_graph/nodes/mod.rs @@ -39,6 +39,7 @@ mod sequencer; mod simple_sampler; mod slew_limiter; mod splitter; +mod svf; mod template_io; mod vocoder; mod voice_allocator; @@ -85,6 +86,7 @@ pub use sequencer::SequencerNode; pub use simple_sampler::SimpleSamplerNode; pub use slew_limiter::SlewLimiterNode; pub use splitter::SplitterNode; +pub use svf::SVFNode; pub use template_io::{TemplateInputNode, TemplateOutputNode}; pub use vocoder::VocoderNode; pub use voice_allocator::VoiceAllocatorNode; diff --git a/daw-backend/src/audio/node_graph/nodes/svf.rs b/daw-backend/src/audio/node_graph/nodes/svf.rs new file mode 100644 index 0000000..44b8ee5 --- /dev/null +++ b/daw-backend/src/audio/node_graph/nodes/svf.rs @@ -0,0 +1,199 @@ +use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType, cv_input_or_default}; +use crate::audio::midi::MidiEvent; +use crate::dsp::svf::SvfFilter; + +const PARAM_CUTOFF: u32 = 0; +const PARAM_RESONANCE: u32 = 1; + +/// State Variable Filter node — simultaneously outputs lowpass, highpass, +/// bandpass, and notch from one filter, with per-sample CV modulation of +/// cutoff and resonance. +pub struct SVFNode { + name: String, + filter: SvfFilter, + cutoff: f32, + resonance: f32, + sample_rate: u32, + inputs: Vec, + outputs: Vec, + parameters: Vec, +} + +impl SVFNode { + pub fn new(name: impl Into) -> Self { + let name = name.into(); + + let inputs = vec![ + NodePort::new("Audio In", SignalType::Audio, 0), + NodePort::new("Cutoff CV", SignalType::CV, 1), + NodePort::new("Resonance CV", SignalType::CV, 2), + ]; + + let outputs = vec![ + NodePort::new("Lowpass", SignalType::Audio, 0), + NodePort::new("Highpass", SignalType::Audio, 1), + NodePort::new("Bandpass", SignalType::Audio, 2), + NodePort::new("Notch", SignalType::Audio, 3), + ]; + + let parameters = vec![ + Parameter::new(PARAM_CUTOFF, "Cutoff", 20.0, 20000.0, 1000.0, ParameterUnit::Frequency), + Parameter::new(PARAM_RESONANCE, "Resonance", 0.0, 1.0, 0.0, ParameterUnit::Generic), + ]; + + let mut filter = SvfFilter::new(); + filter.set_params(1000.0, 0.0, 44100.0); + + Self { + name, + filter, + cutoff: 1000.0, + resonance: 0.0, + sample_rate: 44100, + inputs, + outputs, + parameters, + } + } +} + +impl AudioNode for SVFNode { + 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.filter.set_params(self.cutoff, self.resonance, self.sample_rate as f32); + } + PARAM_RESONANCE => { + self.resonance = value.clamp(0.0, 1.0); + self.filter.set_params(self.cutoff, self.resonance, self.sample_rate as f32); + } + _ => {} + } + } + + fn get_parameter(&self, id: u32) -> f32 { + match id { + PARAM_CUTOFF => self.cutoff, + PARAM_RESONANCE => self.resonance, + _ => 0.0, + } + } + + fn process( + &mut self, + inputs: &[&[f32]], + outputs: &mut [&mut [f32]], + _midi_inputs: &[&[MidiEvent]], + _midi_outputs: &mut [&mut Vec], + sample_rate: u32, + ) { + if inputs.is_empty() || outputs.len() < 4 { + return; + } + + if self.sample_rate != sample_rate { + self.sample_rate = sample_rate; + self.filter.set_params(self.cutoff, self.resonance, sample_rate as f32); + } + + let input = inputs[0]; + // All 4 outputs are stereo interleaved + let frames = input.len() / 2; + let sr = self.sample_rate as f32; + + // Check if CV inputs are connected (sample first frame to detect NaN) + let has_cutoff_cv = !cv_input_or_default(inputs, 1, 0, f32::NAN).is_nan(); + let has_resonance_cv = !cv_input_or_default(inputs, 2, 0, f32::NAN).is_nan(); + + let mut last_cutoff = self.cutoff; + let mut last_resonance = self.resonance; + + for frame in 0..frames { + // Update coefficients from CV if connected + if has_cutoff_cv || has_resonance_cv { + let cutoff = if has_cutoff_cv { + let cv = cv_input_or_default(inputs, 1, frame, 0.5); + let octave_shift = (cv.clamp(0.0, 1.0) - 0.5) * 4.0; + (self.cutoff * 2.0_f32.powf(octave_shift)).clamp(20.0, 20000.0) + } else { + self.cutoff + }; + + let resonance = if has_resonance_cv { + cv_input_or_default(inputs, 2, frame, self.resonance).clamp(0.0, 1.0) + } else { + self.resonance + }; + + if cutoff != last_cutoff || resonance != last_resonance { + self.filter.set_params(cutoff, resonance, sr); + last_cutoff = cutoff; + last_resonance = resonance; + } + } + + // Process both channels, writing all 4 outputs + for ch in 0..2 { + let idx = frame * 2 + ch; + let (lp, hp, bp, notch) = self.filter.process_sample_quad(input[idx], ch); + outputs[0][idx] = lp; + outputs[1][idx] = hp; + outputs[2][idx] = bp; + outputs[3][idx] = notch; + } + } + } + + fn reset(&mut self) { + self.filter.reset(); + } + + fn node_type(&self) -> &str { + "SVF" + } + + fn name(&self) -> &str { + &self.name + } + + fn clone_node(&self) -> Box { + let mut filter = SvfFilter::new(); + filter.set_params(self.cutoff, self.resonance, self.sample_rate as f32); + + Box::new(Self { + name: self.name.clone(), + filter, + cutoff: self.cutoff, + resonance: self.resonance, + sample_rate: self.sample_rate, + inputs: self.inputs.clone(), + outputs: self.outputs.clone(), + parameters: self.parameters.clone(), + }) + } + + fn as_any_mut(&mut self) -> &mut dyn std::any::Any { + self + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } +} diff --git a/daw-backend/src/dsp/mod.rs b/daw-backend/src/dsp/mod.rs index 8c5eae0..3e052fe 100644 --- a/daw-backend/src/dsp/mod.rs +++ b/daw-backend/src/dsp/mod.rs @@ -1,3 +1,5 @@ pub mod biquad; +pub mod svf; pub use biquad::BiquadFilter; +pub use svf::SvfFilter; diff --git a/daw-backend/src/dsp/svf.rs b/daw-backend/src/dsp/svf.rs new file mode 100644 index 0000000..315667e --- /dev/null +++ b/daw-backend/src/dsp/svf.rs @@ -0,0 +1,135 @@ +use std::f32::consts::PI; + +/// State Variable Filter mode +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SvfMode { + Lowpass = 0, + Highpass = 1, + Bandpass = 2, + Notch = 3, +} + +impl SvfMode { + pub fn from_f32(value: f32) -> Self { + match value.round() as i32 { + 1 => SvfMode::Highpass, + 2 => SvfMode::Bandpass, + 3 => SvfMode::Notch, + _ => SvfMode::Lowpass, + } + } +} + +/// Linear trapezoidal integrated State Variable Filter (Simper/Cytomic) +/// +/// Zero-delay feedback topology. Per-sample cutoff modulation is cheap — +/// just update `g` and `k` coefficients (no per-sample trig needed if +/// cutoff hasn't changed). +#[derive(Clone)] +pub struct SvfFilter { + // Coefficients + g: f32, // frequency warping: tan(π * cutoff / sample_rate) + k: f32, // damping: 2 - 2*resonance + a1: f32, // 1 / (1 + g*(g+k)) + a2: f32, // g * a1 + + // State per channel (up to 2 for stereo) + ic1eq: [f32; 2], + ic2eq: [f32; 2], + + mode: SvfMode, +} + +impl SvfFilter { + /// Create a new SVF with default parameters (1kHz lowpass, no resonance) + pub fn new() -> Self { + let mut filter = Self { + g: 0.0, + k: 2.0, + a1: 0.0, + a2: 0.0, + ic1eq: [0.0; 2], + ic2eq: [0.0; 2], + mode: SvfMode::Lowpass, + }; + filter.set_params(1000.0, 0.0, 44100.0); + filter + } + + /// Set filter parameters + /// + /// # Arguments + /// * `cutoff_hz` - Cutoff frequency in Hz (clamped to valid range) + /// * `resonance` - Resonance 0.0 (none) to 1.0 (self-oscillation) + /// * `sample_rate` - Sample rate in Hz + #[inline] + pub fn set_params(&mut self, cutoff_hz: f32, resonance: f32, sample_rate: f32) { + // Clamp cutoff to avoid instability near Nyquist + let cutoff = cutoff_hz.clamp(5.0, sample_rate * 0.49); + let resonance = resonance.clamp(0.0, 1.0); + + self.g = (PI * cutoff / sample_rate).tan(); + self.k = 2.0 - 2.0 * resonance; + self.a1 = 1.0 / (1.0 + self.g * (self.g + self.k)); + self.a2 = self.g * self.a1; + } + + /// Set filter mode + pub fn set_mode(&mut self, mode: SvfMode) { + self.mode = mode; + } + + /// Process a single sample, returning all four outputs: (lowpass, highpass, bandpass, notch) + #[inline] + pub fn process_sample_quad(&mut self, input: f32, channel: usize) -> (f32, f32, f32, f32) { + let ch = channel.min(1); + + let v3 = input - self.ic2eq[ch]; + let v1 = self.a1 * self.ic1eq[ch] + self.a2 * v3; + let v2 = self.ic2eq[ch] + self.g * v1; + + self.ic1eq[ch] = 2.0 * v1 - self.ic1eq[ch]; + self.ic2eq[ch] = 2.0 * v2 - self.ic2eq[ch]; + + let hp = input - self.k * v1 - v2; + (v2, hp, v1, hp + v2) + } + + /// Process a single sample with a selected mode + #[inline] + pub fn process_sample(&mut self, input: f32, channel: usize) -> f32 { + let (lp, hp, bp, notch) = self.process_sample_quad(input, channel); + match self.mode { + SvfMode::Lowpass => lp, + SvfMode::Highpass => hp, + SvfMode::Bandpass => bp, + SvfMode::Notch => notch, + } + } + + /// Process a buffer of interleaved samples + pub fn process_buffer(&mut self, buffer: &mut [f32], channels: usize) { + if channels == 1 { + for sample in buffer.iter_mut() { + *sample = self.process_sample(*sample, 0); + } + } else if channels == 2 { + for frame in buffer.chunks_exact_mut(2) { + frame[0] = self.process_sample(frame[0], 0); + frame[1] = self.process_sample(frame[1], 1); + } + } + } + + /// Reset filter state (clear delay lines) + pub fn reset(&mut self) { + self.ic1eq = [0.0; 2]; + self.ic2eq = [0.0; 2]; + } +} + +impl Default for SvfFilter { + fn default() -> Self { + Self::new() + } +} diff --git a/lightningbeam-ui/lightningbeam-editor/src/main.rs b/lightningbeam-ui/lightningbeam-editor/src/main.rs index 7b8aa9c..d93552c 100644 --- a/lightningbeam-ui/lightningbeam-editor/src/main.rs +++ b/lightningbeam-ui/lightningbeam-editor/src/main.rs @@ -140,6 +140,34 @@ fn main() -> eframe::Result { let options = eframe::NativeOptions { viewport: viewport_builder, + wgpu_options: egui_wgpu::WgpuConfiguration { + wgpu_setup: egui_wgpu::WgpuSetup::CreateNew(egui_wgpu::WgpuSetupCreateNew { + device_descriptor: std::sync::Arc::new(|adapter| { + let features = adapter.features(); + // Request SHADER_F16 if available — needed on Mesa/llvmpipe for vello's + // unpack2x16float (enables the SHADER_F16_IN_F32 downlevel capability) + let optional_features = wgpu::Features::SHADER_F16; + + let base_limits = if adapter.get_info().backend == wgpu::Backend::Gl { + wgpu::Limits::downlevel_webgl2_defaults() + } else { + wgpu::Limits::default() + }; + + wgpu::DeviceDescriptor { + label: Some("lightningbeam wgpu device"), + required_features: features & optional_features, + required_limits: wgpu::Limits { + max_texture_dimension_2d: 8192, + ..base_limits + }, + ..Default::default() + } + }), + ..Default::default() + }), + ..Default::default() + }, ..Default::default() }; diff --git a/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/graph_data.rs b/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/graph_data.rs index 1f0da9e..160a4a3 100644 --- a/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/graph_data.rs +++ b/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/graph_data.rs @@ -35,6 +35,7 @@ pub enum NodeTemplate { // Effects Filter, + Svf, Gain, Echo, Reverb, @@ -100,6 +101,7 @@ impl NodeTemplate { NodeTemplate::SimpleSampler => "SimpleSampler", NodeTemplate::MultiSampler => "MultiSampler", NodeTemplate::Filter => "Filter", + NodeTemplate::Svf => "SVF", NodeTemplate::Gain => "Gain", NodeTemplate::Echo => "Echo", NodeTemplate::Reverb => "Reverb", @@ -400,6 +402,7 @@ impl NodeTemplateTrait for NodeTemplate { NodeTemplate::MultiSampler => "Multi Sampler".into(), // Effects NodeTemplate::Filter => "Filter".into(), + NodeTemplate::Svf => "SVF".into(), NodeTemplate::Gain => "Gain".into(), NodeTemplate::Echo => "Echo".into(), NodeTemplate::Reverb => "Reverb".into(), @@ -452,7 +455,7 @@ impl NodeTemplateTrait for NodeTemplate { NodeTemplate::MidiInput | NodeTemplate::AudioInput | NodeTemplate::AutomationInput | NodeTemplate::Beat => vec!["Inputs"], NodeTemplate::Oscillator | NodeTemplate::WavetableOscillator | NodeTemplate::FmSynth | NodeTemplate::Noise | NodeTemplate::SimpleSampler | NodeTemplate::MultiSampler => vec!["Generators"], - NodeTemplate::Filter | NodeTemplate::Gain | NodeTemplate::Echo | NodeTemplate::Reverb + NodeTemplate::Filter | NodeTemplate::Svf | NodeTemplate::Gain | NodeTemplate::Echo | NodeTemplate::Reverb | NodeTemplate::Chorus | NodeTemplate::Flanger | NodeTemplate::Phaser | NodeTemplate::Distortion | NodeTemplate::BitCrusher | NodeTemplate::Compressor | NodeTemplate::Limiter | NodeTemplate::Eq | NodeTemplate::Pan | NodeTemplate::RingModulator | NodeTemplate::Vocoder => vec!["Effects"], @@ -513,6 +516,20 @@ impl NodeTemplateTrait for NodeTemplate { ValueType::float_param(0.0, 0.0, 3.0, "", 2, Some(&["LPF", "HPF", "BPF", "Notch"])), InputParamKind::ConstantOnly, true); graph.add_output_param(node_id, "Audio Out".into(), DataType::Audio); } + NodeTemplate::Svf => { + graph.add_input_param(node_id, "Audio In".into(), DataType::Audio, ValueType::float(0.0), InputParamKind::ConnectionOnly, true); + graph.add_input_param(node_id, "Cutoff CV".into(), DataType::CV, ValueType::float(0.0), InputParamKind::ConnectionOnly, true); + graph.add_input_param(node_id, "Resonance CV".into(), DataType::CV, ValueType::float(0.0), InputParamKind::ConnectionOnly, true); + // Parameters + graph.add_input_param(node_id, "Cutoff".into(), DataType::CV, + ValueType::float_param(1000.0, 20.0, 20000.0, " Hz", 0, None), InputParamKind::ConstantOnly, true); + graph.add_input_param(node_id, "Resonance".into(), DataType::CV, + ValueType::float_param(0.0, 0.0, 1.0, "", 1, None), InputParamKind::ConstantOnly, true); + graph.add_output_param(node_id, "Lowpass".into(), DataType::Audio); + graph.add_output_param(node_id, "Highpass".into(), DataType::Audio); + graph.add_output_param(node_id, "Bandpass".into(), DataType::Audio); + graph.add_output_param(node_id, "Notch".into(), DataType::Audio); + } NodeTemplate::Gain => { graph.add_input_param(node_id, "Audio In".into(), DataType::Audio, ValueType::float(0.0), InputParamKind::ConnectionOnly, true); graph.add_input_param(node_id, "Gain CV".into(), DataType::CV, ValueType::float(0.0), InputParamKind::ConnectionOnly, true); @@ -1676,6 +1693,7 @@ impl NodeTemplateIter for AllNodeTemplates { NodeTemplate::MultiSampler, // Effects NodeTemplate::Filter, + NodeTemplate::Svf, NodeTemplate::Gain, NodeTemplate::Echo, NodeTemplate::Reverb, diff --git a/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/mod.rs b/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/mod.rs index 93c8184..c719c95 100644 --- a/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/mod.rs +++ b/lightningbeam-ui/lightningbeam-editor/src/panes/node_graph/mod.rs @@ -2125,6 +2125,7 @@ impl NodeGraphPane { "SimpleSampler" => Some(NodeTemplate::SimpleSampler), "MultiSampler" => Some(NodeTemplate::MultiSampler), "Filter" => Some(NodeTemplate::Filter), + "SVF" => Some(NodeTemplate::Svf), "Gain" => Some(NodeTemplate::Gain), "Echo" | "Delay" => Some(NodeTemplate::Echo), "Reverb" => Some(NodeTemplate::Reverb),