diff --git a/src/gate/dsp.rs b/src/gate/dsp.rs new file mode 100644 index 0000000..e912ab7 --- /dev/null +++ b/src/gate/dsp.rs @@ -0,0 +1,579 @@ +const MIN_LEVEL: f32 = 1.0e-10; +const DETECTOR_TIME_SECONDS: f32 = 0.005; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GateStatus { + Closed = 0, + Holding = 1, + Open = 2, +} + +#[derive(Debug, Clone, Copy)] +pub struct GateParams { + pub threshold_db: f32, + pub ratio: f32, + pub range_db: f32, + pub attack_ms: f32, + pub hold_ms: f32, + pub release_ms: f32, + pub hysteresis_db: f32, + pub sidechain_hpf_hz: f32, + pub sidechain_lpf_hz: f32, + pub monitor: bool, +} + +impl Default for GateParams { + fn default() -> Self { + Self { + threshold_db: -50.0, + ratio: 4.0, + range_db: 80.0, + attack_ms: 1.0, + hold_ms: 50.0, + release_ms: 150.0, + hysteresis_db: 3.0, + sidechain_hpf_hz: 20.0, + sidechain_lpf_hz: 20_000.0, + monitor: false, + } + } +} + +#[derive(Debug, Clone, Copy)] +pub struct GateMeter { + pub detector_db: f32, + pub gain_reduction_db: f32, + pub status: GateStatus, +} + +#[derive(Debug, Clone, Copy, Default)] +struct Biquad { + b0: f32, + b1: f32, + b2: f32, + a1: f32, + a2: f32, + x1: f32, + x2: f32, + y1: f32, + y2: f32, +} + +impl Biquad { + fn set_coefficients(&mut self, b0: f32, b1: f32, b2: f32, a0: f32, a1: f32, a2: f32) { + self.b0 = b0 / a0; + self.b1 = b1 / a0; + self.b2 = b2 / a0; + self.a1 = a1 / a0; + self.a2 = a2 / a0; + } + + fn set_highpass(&mut self, cutoff_hz: f32, sample_rate: f32) { + let cutoff_hz = cutoff_hz.clamp(1.0, sample_rate * 0.45); + let w0 = 2.0 * std::f32::consts::PI * cutoff_hz / sample_rate; + let (sin, cos) = w0.sin_cos(); + let alpha = sin / 2.0_f32.sqrt(); + self.set_coefficients( + (1.0 + cos) * 0.5, + -(1.0 + cos), + (1.0 + cos) * 0.5, + 1.0 + alpha, + -2.0 * cos, + 1.0 - alpha, + ); + } + + fn set_lowpass(&mut self, cutoff_hz: f32, sample_rate: f32) { + let cutoff_hz = cutoff_hz.clamp(1.0, sample_rate * 0.45); + let w0 = 2.0 * std::f32::consts::PI * cutoff_hz / sample_rate; + let (sin, cos) = w0.sin_cos(); + let alpha = sin / 2.0_f32.sqrt(); + self.set_coefficients( + (1.0 - cos) * 0.5, + 1.0 - cos, + (1.0 - cos) * 0.5, + 1.0 + alpha, + -2.0 * cos, + 1.0 - alpha, + ); + } + + fn process(&mut self, input: f32) -> f32 { + let output = self.b0 * input + self.b1 * self.x1 + self.b2 * self.x2 + - self.a1 * self.y1 + - self.a2 * self.y2; + self.x2 = self.x1; + self.x1 = input; + self.y2 = self.y1; + self.y1 = output; + output + } + + fn reset(&mut self) { + self.x1 = 0.0; + self.x2 = 0.0; + self.y1 = 0.0; + self.y2 = 0.0; + } +} + +#[derive(Debug, Clone)] +pub struct Gate { + sample_rate: f32, + hpf_l: Biquad, + hpf_r: Biquad, + lpf_l: Biquad, + lpf_r: Biquad, + detector_level: f32, + gain_db: f32, + hold_samples_remaining: usize, + status: GateStatus, + initialized: bool, + detector_coefficient: f32, + attack_coefficient: f32, + release_coefficient: f32, + hold_samples: usize, + configured_hpf_hz: f32, + configured_lpf_hz: f32, + configured_attack_ms: f32, + configured_release_ms: f32, + configured_hold_ms: f32, +} + +impl Default for Gate { + fn default() -> Self { + let sample_rate = 48_000.0; + Self { + sample_rate, + hpf_l: Biquad::default(), + hpf_r: Biquad::default(), + lpf_l: Biquad::default(), + lpf_r: Biquad::default(), + detector_level: MIN_LEVEL, + gain_db: 0.0, + hold_samples_remaining: 0, + status: GateStatus::Closed, + initialized: false, + detector_coefficient: time_coefficient(DETECTOR_TIME_SECONDS, sample_rate), + attack_coefficient: 1.0, + release_coefficient: 1.0, + hold_samples: 0, + configured_hpf_hz: f32::NAN, + configured_lpf_hz: f32::NAN, + configured_attack_ms: f32::NAN, + configured_release_ms: f32::NAN, + configured_hold_ms: f32::NAN, + } + } +} + +impl Gate { + pub fn new(sample_rate: f32) -> Self { + let mut gate = Self::default(); + gate.set_sample_rate(sample_rate); + gate + } + + pub fn set_sample_rate(&mut self, sample_rate: f32) { + self.sample_rate = sample_rate.max(1.0); + self.detector_coefficient = time_coefficient(DETECTOR_TIME_SECONDS, self.sample_rate); + self.configured_hpf_hz = f32::NAN; + self.configured_lpf_hz = f32::NAN; + self.configured_attack_ms = f32::NAN; + self.configured_release_ms = f32::NAN; + self.configured_hold_ms = f32::NAN; + self.reset(); + } + + pub fn reset(&mut self) { + self.hpf_l.reset(); + self.hpf_r.reset(); + self.lpf_l.reset(); + self.lpf_r.reset(); + self.detector_level = MIN_LEVEL; + self.gain_db = 0.0; + self.hold_samples_remaining = 0; + self.status = GateStatus::Closed; + self.initialized = false; + } + + fn configure(&mut self, params: &GateParams) { + let hpf_hz = params.sidechain_hpf_hz.max(1.0); + let lpf_hz = params.sidechain_lpf_hz.max(1.0); + if self.configured_hpf_hz != hpf_hz { + self.hpf_l.set_highpass(hpf_hz, self.sample_rate); + self.hpf_r.set_highpass(hpf_hz, self.sample_rate); + self.configured_hpf_hz = hpf_hz; + } + if self.configured_lpf_hz != lpf_hz { + self.lpf_l.set_lowpass(lpf_hz, self.sample_rate); + self.lpf_r.set_lowpass(lpf_hz, self.sample_rate); + self.configured_lpf_hz = lpf_hz; + } + if self.configured_attack_ms != params.attack_ms { + self.attack_coefficient = time_coefficient(params.attack_ms * 0.001, self.sample_rate); + self.configured_attack_ms = params.attack_ms; + } + if self.configured_release_ms != params.release_ms { + self.release_coefficient = + time_coefficient(params.release_ms * 0.001, self.sample_rate); + self.configured_release_ms = params.release_ms; + } + if self.configured_hold_ms != params.hold_ms { + self.hold_samples = + (params.hold_ms.max(0.0) * 0.001 * self.sample_rate).round() as usize; + self.configured_hold_ms = params.hold_ms; + } + } + + fn expansion_gain_db(level_db: f32, close_threshold_db: f32, ratio: f32, range_db: f32) -> f32 { + if level_db >= close_threshold_db { + return 0.0; + } + let ratio = ratio.max(1.0); + let reduction = (close_threshold_db - level_db) * (1.0 - ratio.recip()); + -reduction.min(range_db.max(0.0)) + } + + fn target_gain_db(&mut self, level_db: f32, params: &GateParams) -> f32 { + let close_threshold_db = params.threshold_db - params.hysteresis_db.max(0.0); + match self.status { + GateStatus::Open => { + if level_db >= close_threshold_db { + 0.0 + } else if self.hold_samples > 0 { + self.status = GateStatus::Holding; + self.hold_samples_remaining = self.hold_samples; + self.target_gain_db(level_db, params) + } else { + self.status = GateStatus::Closed; + Self::expansion_gain_db( + level_db, + close_threshold_db, + params.ratio, + params.range_db, + ) + } + } + GateStatus::Holding => { + if level_db >= close_threshold_db { + self.status = GateStatus::Open; + self.hold_samples_remaining = 0; + 0.0 + } else if self.hold_samples_remaining > 0 { + self.hold_samples_remaining -= 1; + 0.0 + } else { + self.status = GateStatus::Closed; + Self::expansion_gain_db( + level_db, + close_threshold_db, + params.ratio, + params.range_db, + ) + } + } + GateStatus::Closed => { + if level_db >= params.threshold_db { + self.status = GateStatus::Open; + self.hold_samples_remaining = 0; + 0.0 + } else { + Self::expansion_gain_db( + level_db, + close_threshold_db, + params.ratio, + params.range_db, + ) + } + } + } + } + + fn smooth_gain(&mut self, target_db: f32) -> f32 { + if !self.initialized { + self.gain_db = target_db; + self.initialized = true; + return self.gain_db; + } + let coefficient = if target_db > self.gain_db { + self.attack_coefficient + } else { + self.release_coefficient + }; + self.gain_db += coefficient * (target_db - self.gain_db); + self.gain_db + } + + pub fn process_stereo( + &mut self, + left: &mut [f32], + right: &mut [f32], + detector_left: &[f32], + detector_right: &[f32], + params: &GateParams, + ) -> GateMeter { + self.configure(params); + let frames = left + .len() + .min(right.len()) + .min(detector_left.len()) + .min(detector_right.len()); + let mut detector_db = 20.0 * self.detector_level.max(MIN_LEVEL).log10(); + + for i in 0..frames { + let input_l = finite_or_zero(left[i]); + let input_r = finite_or_zero(right[i]); + let key_l = self + .lpf_l + .process(self.hpf_l.process(finite_or_zero(detector_left[i]))); + let key_r = self + .lpf_r + .process(self.hpf_r.process(finite_or_zero(detector_right[i]))); + let peak = key_l.abs().max(key_r.abs()).max(MIN_LEVEL); + self.detector_level += self.detector_coefficient * (peak - self.detector_level); + self.detector_level = self.detector_level.clamp(MIN_LEVEL, 1.0e6); + detector_db = 20.0 * self.detector_level.log10(); + + let target_db = self.target_gain_db(detector_db, params); + let gain_db = self.smooth_gain(target_db); + if params.monitor { + left[i] = key_l; + right[i] = key_r; + } else { + let gain = 10.0_f32.powf(gain_db * 0.05); + left[i] = input_l * gain; + right[i] = input_r * gain; + } + } + + GateMeter { + detector_db, + gain_reduction_db: -self.gain_db, + status: self.status, + } + } +} + +fn finite_or_zero(value: f32) -> f32 { + if value.is_finite() { value } else { 0.0 } +} + +fn time_coefficient(time_seconds: f32, sample_rate: f32) -> f32 { + if time_seconds <= 0.0 { + 1.0 + } else { + let samples = (time_seconds * sample_rate).max(1.0); + let target = 1.0 - std::f32::consts::FRAC_1_SQRT_2; + 1.0 - (target.ln() / samples).exp() + } +} + +#[cfg(test)] +mod tests { + use super::{Gate, GateParams, GateStatus}; + + fn params() -> GateParams { + GateParams { + threshold_db: -20.0, + attack_ms: 0.0, + hold_ms: 0.0, + release_ms: 0.0, + ..GateParams::default() + } + } + + fn key_signal(input: f32, frames: usize, sample_rate: f32) -> Vec { + let frequency = sample_rate * 0.05; + (0..frames) + .map(|i| { + input * (2.0 * std::f32::consts::PI * frequency * i as f32 / sample_rate).sin() + }) + .collect() + } + + fn process_constant(gate: &mut Gate, input: f32, frames: usize, params: &GateParams) { + let mut left = key_signal(input, frames, gate.sample_rate); + let mut right = key_signal(input, frames, gate.sample_rate); + let detector_left = left.clone(); + let detector_right = right.clone(); + gate.process_stereo( + &mut left, + &mut right, + &detector_left, + &detector_right, + params, + ); + } + + #[test] + fn expansion_is_ratio_and_range_limited() { + assert_eq!(Gate::expansion_gain_db(-40.0, -20.0, 4.0, 80.0), -15.0); + assert_eq!(Gate::expansion_gain_db(-100.0, -20.0, 4.0, 30.0), -30.0); + assert_eq!(Gate::expansion_gain_db(-10.0, -20.0, 4.0, 80.0), 0.0); + assert_eq!(Gate::expansion_gain_db(-40.0, -20.0, 1.0, 80.0), 0.0); + } + + #[test] + fn loud_signal_passes_and_silence_reaches_full_range() { + let mut gate = Gate::new(48_000.0); + let params = GateParams { + ratio: 100.0, + ..params() + }; + process_constant(&mut gate, 1.0, 4096, ¶ms); + let mut left = vec![1.0; 64]; + let mut right = vec![1.0; 64]; + let detector_left = key_signal(1.0, 64, 48_000.0); + let detector_right = key_signal(1.0, 64, 48_000.0); + let meter = gate.process_stereo( + &mut left, + &mut right, + &detector_left, + &detector_right, + ¶ms, + ); + assert_eq!(meter.status, GateStatus::Open); + assert!(left.iter().all(|&sample| (sample - 1.0).abs() < 1.0e-4)); + assert!(right.iter().all(|&sample| (sample - 1.0).abs() < 1.0e-4)); + + process_constant(&mut gate, 0.0, 4096, ¶ms); + let left = vec![0.0; 1]; + let right = vec![0.0; 1]; + let mut output_l = vec![1.0]; + let mut output_r = vec![1.0]; + let meter = gate.process_stereo(&mut output_l, &mut output_r, &left, &right, ¶ms); + assert!( + meter.gain_reduction_db >= 79.9, + "meter: {meter:?}, output: {}", + output_l[0] + ); + assert!(output_l[0].abs() < 1.0e-3); + assert!(output_r[0].abs() < 1.0e-3); + } + + #[test] + fn hold_is_counted_in_samples() { + let mut gate = Gate::new(1000.0); + let params = GateParams { + hold_ms: 50.0, + ..params() + }; + process_constant(&mut gate, 1.0, 1024, ¶ms); + assert_eq!(gate.status, GateStatus::Open); + + let left = vec![0.0; 50]; + let right = vec![0.0; 50]; + let mut output_l = vec![1.0; 50]; + let mut output_r = vec![1.0; 50]; + let meter = gate.process_stereo(&mut output_l, &mut output_r, &left, &right, ¶ms); + assert_eq!(meter.status, GateStatus::Holding); + assert!(meter.gain_reduction_db.abs() < 1.0e-4); + + let mut output_l = vec![1.0; 128]; + let mut output_r = vec![1.0; 128]; + let meter = gate.process_stereo(&mut output_l, &mut output_r, &left, &right, ¶ms); + assert_eq!(meter.status, GateStatus::Closed); + } + + #[test] + fn hysteresis_requires_crossing_both_thresholds() { + let mut gate = Gate::new(1000.0); + let params = GateParams { + hysteresis_db: 3.0, + ..params() + }; + process_constant(&mut gate, 1.0, 1024, ¶ms); + gate.detector_level = 10.0_f32.powf(-21.0 / 20.0); + assert_eq!(gate.target_gain_db(-21.0, ¶ms), 0.0); + assert_eq!(gate.status, GateStatus::Open); + + gate.status = GateStatus::Closed; + gate.target_gain_db(-21.0, ¶ms); + assert_eq!(gate.status, GateStatus::Closed); + gate.target_gain_db(-19.0, ¶ms); + assert_eq!(gate.status, GateStatus::Open); + } + + #[test] + fn stereo_channels_share_one_gain_envelope() { + let mut gate = Gate::new(48_000.0); + let params = params(); + let detector_left = key_signal(1.0, 4096, 48_000.0); + let detector_right = vec![0.0; 4096]; + let mut left = vec![1.0; 4096]; + let mut right = vec![1.0; 4096]; + gate.process_stereo( + &mut left, + &mut right, + &detector_left, + &detector_right, + ¶ms, + ); + let last = left.len() - 1; + assert!((left[last] - right[last]).abs() < 1.0e-6); + assert!(right[last] > 0.99); + } + + #[test] + fn sidechain_highpass_rejects_low_frequency_key() { + let params = GateParams { + sidechain_hpf_hz: 1000.0, + ..params() + }; + let mut low_gate = Gate::new(48_000.0); + let mut high_gate = Gate::new(48_000.0); + let low: Vec = (0..8192) + .map(|i| (2.0 * std::f32::consts::PI * 50.0 * i as f32 / 48_000.0).sin()) + .collect(); + let high: Vec = (0..8192) + .map(|i| (2.0 * std::f32::consts::PI * 5000.0 * i as f32 / 48_000.0).sin()) + .collect(); + let mut output_l = vec![1.0; 8192]; + let mut output_r = vec![1.0; 8192]; + let low_meter = low_gate.process_stereo(&mut output_l, &mut output_r, &low, &low, ¶ms); + let high_meter = + high_gate.process_stereo(&mut output_l, &mut output_r, &high, &high, ¶ms); + assert_eq!(low_meter.status, GateStatus::Closed); + assert_eq!(high_meter.status, GateStatus::Open); + } + + #[test] + fn monitor_outputs_filtered_key_instead_of_gated_audio() { + let mut gate = Gate::new(48_000.0); + let params = GateParams { + monitor: true, + sidechain_hpf_hz: 1000.0, + ..params() + }; + let key = vec![0.0; 256]; + let mut left = vec![1.0; 256]; + let mut right = vec![1.0; 256]; + gate.process_stereo(&mut left, &mut right, &key, &key, ¶ms); + assert!(left.iter().all(|&sample| sample == 0.0)); + assert!(right.iter().all(|&sample| sample == 0.0)); + } + + #[test] + fn non_finite_inputs_are_sanitized() { + let mut gate = Gate::new(48_000.0); + let params = params(); + let key = vec![f32::NAN, f32::INFINITY, 0.0, 0.0]; + let mut left = vec![f32::NAN, f32::NEG_INFINITY, 1.0, 0.0]; + let mut right = left.clone(); + gate.process_stereo(&mut left, &mut right, &key, &key, ¶ms); + assert!(left.iter().all(|sample| sample.is_finite())); + assert!(right.iter().all(|sample| sample.is_finite())); + } + + #[test] + fn reset_restores_closed_uninitialized_state() { + let mut gate = Gate::new(48_000.0); + process_constant(&mut gate, 1.0, 4096, ¶ms()); + assert_eq!(gate.status, GateStatus::Open); + gate.reset(); + assert_eq!(gate.status, GateStatus::Closed); + assert!(!gate.initialized); + assert_eq!(gate.hold_samples_remaining, 0); + } +} diff --git a/src/gate/gui.rs b/src/gate/gui.rs new file mode 100644 index 0000000..bc610fc --- /dev/null +++ b/src/gate/gui.rs @@ -0,0 +1,414 @@ +use std::{ffi::CStr, sync::Arc, thread, time::Duration}; + +use maolan_baseview::iced::{ + Alignment, Element, Length, Task, Theme, + alignment::{Horizontal, Vertical}, + widget::{column, container, row, text}, +}; +#[cfg(target_os = "macos")] +use maolan_clap::ffi::CLAP_WINDOW_API_COCOA; +#[cfg(target_os = "windows")] +use maolan_clap::ffi::CLAP_WINDOW_API_WIN32; +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +use maolan_clap::ffi::CLAP_WINDOW_API_X11; +use maolan_widgets::{ + knob::Knob, + meters, + multi_toggler::{LabelPosition, horizontal_multi_toggler}, +}; +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" +))] +use raw_window_handle::RawWindowHandle; +use raw_window_handle::{HandleError, HasWindowHandle, WindowHandle}; + +use crate::{ + common::preset::{self, PresetProvider, PresetUi}, + gate::{ + dsp::GateStatus, + params::{PARAMS, ParamId}, + plugin::{SharedState, param_text}, + }, +}; + +pub const EDITOR_WIDTH: u32 = 720; +pub const EDITOR_HEIGHT: u32 = 390; + +pub fn preferred_api() -> &'static CStr { + #[cfg(target_os = "windows")] + { + CLAP_WINDOW_API_WIN32 + } + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + CLAP_WINDOW_API_X11 + } + #[cfg(target_os = "macos")] + { + CLAP_WINDOW_API_COCOA + } +} + +pub fn is_api_supported(api: &CStr, _is_floating: bool) -> bool { + api == preferred_api() +} + +pub enum ParentWindowHandle { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + X11(usize), + #[cfg(target_os = "macos")] + Cocoa(*mut std::ffi::c_void), + #[cfg(target_os = "windows")] + Win32(*mut std::ffi::c_void), +} + +impl HasWindowHandle for ParentWindowHandle { + fn window_handle(&self) -> Result, HandleError> { + match self { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + ParentWindowHandle::X11(window) => { + let handle = raw_window_handle::XlibWindowHandle::new(*window as _); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Xlib(handle)) }) + } + #[cfg(target_os = "windows")] + ParentWindowHandle::Win32(hwnd) => { + let handle = raw_window_handle::Win32WindowHandle::new( + std::num::NonZeroIsize::new(*hwnd as isize).unwrap(), + ); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Win32(handle)) }) + } + #[cfg(target_os = "macos")] + ParentWindowHandle::Cocoa(ns_view) => { + let handle = raw_window_handle::AppKitWindowHandle::new( + std::ptr::NonNull::new(*ns_view).expect("null NSView"), + ); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::AppKit(handle)) }) + } + } + } +} + +#[derive(Debug, Clone)] +pub enum Message { + SetParam(ParamId, f32), + ReleaseParam(ParamId), + SetBoolParam(ParamId, bool), + UiTick, + Preset(preset::Msg), +} + +impl From for Message { + fn from(msg: preset::Msg) -> Self { + Message::Preset(msg) + } +} + +struct State { + shared: Arc, + active_gestures: Vec, + preset_ui: PresetUi, +} + +fn init(shared: Arc) -> (State, Task) { + ( + State { + shared, + active_gestures: vec![false; ParamId::COUNT], + preset_ui: PresetUi::new(SharedState::DIR_NAME), + }, + next_ui_tick_task(), + ) +} + +fn next_ui_tick_task() -> Task { + Task::perform( + async move { + thread::sleep(Duration::from_millis(33)); + }, + |_| Message::UiTick, + ) +} + +fn update(state: &mut State, message: Message) -> Task { + match message { + Message::SetParam(id, value) => { + let idx = id.as_index(); + if !state.active_gestures[idx] { + state.active_gestures[idx] = true; + state.shared.mark_gesture_begin_pending(id); + } + state.shared.set_param_outbound_only(id, value as f64); + } + Message::ReleaseParam(id) => { + let idx = id.as_index(); + if state.active_gestures[idx] { + state.active_gestures[idx] = false; + state.shared.mark_gesture_end_pending(id); + } + } + Message::SetBoolParam(id, value) => { + state.shared.mark_gesture_begin_pending(id); + state + .shared + .set_param_outbound_only(id, if value { 1.0 } else { 0.0 }); + state.shared.mark_gesture_end_pending(id); + state.shared.mark_dirty(); + } + Message::UiTick => return next_ui_tick_task(), + Message::Preset(msg) => { + preset::update(&mut state.preset_ui, msg, state.shared.as_ref()); + } + } + Task::none() +} + +fn knob<'a>(id: ParamId, label: &'a str, state: &'a State) -> Element<'a, Message> { + let value = state.shared.params.get(id); + let def = &PARAMS[id.as_index()]; + maolan_widgets::knob::knob( + Knob { + label: label.to_string(), + value: value as f32, + range: def.min as f32..=def.max as f32, + default: def.default as f32, + step: def.step as f32, + value_text: param_text(id, value), + assigned: false, + }, + move |value| Message::SetParam(id, value), + Message::ReleaseParam(id), + ) +} + +fn meter_column<'a>(title: &'a str, level_db: f32, readout: String) -> Element<'a, Message> { + let levels = [level_db.clamp(-90.0, 20.0)]; + column![ + text(title).size(13), + container(meters::meters(1, &levels, 110.0)) + .width(Length::Shrink) + .height(Length::Fixed(110.0)), + text(readout).size(11), + ] + .spacing(5) + .align_x(Alignment::Center) + .into() +} + +fn view(state: &State) -> Element<'_, Message> { + let external = state.shared.params.get_bool(ParamId::ExternalSidechain); + let monitor = state.shared.params.get_bool(ParamId::Monitor); + let (detector_db, gain_reduction_db, status) = state.shared.meter(); + let status_text = match status { + GateStatus::Closed => "Closed", + GateStatus::Holding => "Holding", + GateStatus::Open => "Open", + }; + let detector_text = if detector_db <= -200.0 { + "-inf dB".to_string() + } else { + format!("{detector_db:.1} dB") + }; + + let detector_controls = row![ + column![ + text("External SC").size(13), + horizontal_multi_toggler(["Internal", "External"], usize::from(external), |index| { + Message::SetBoolParam(ParamId::ExternalSidechain, index == 1) + },) + .label_position(LabelPosition::Below), + ] + .spacing(5) + .align_x(Alignment::Center), + column![ + text("Monitor").size(13), + horizontal_multi_toggler(["Off", "Monitor"], usize::from(monitor), |index| { + Message::SetBoolParam(ParamId::Monitor, index == 1) + },) + .label_position(LabelPosition::Below), + ] + .spacing(5) + .align_x(Alignment::Center), + ] + .spacing(8) + .align_y(Alignment::Center); + + let controls = column![ + row![ + knob(ParamId::Threshold, "Threshold", state), + knob(ParamId::Ratio, "Ratio", state), + knob(ParamId::Range, "Range", state), + knob(ParamId::Hysteresis, "Hysteresis", state), + ] + .spacing(8) + .align_y(Alignment::Center), + row![ + knob(ParamId::Attack, "Attack", state), + knob(ParamId::Hold, "Hold", state), + knob(ParamId::Release, "Release", state), + ] + .spacing(8) + .align_y(Alignment::Center), + row![ + knob(ParamId::SidechainHpf, "SC HPF", state), + knob(ParamId::SidechainLpf, "SC LPF", state), + detector_controls, + ] + .spacing(12) + .align_y(Alignment::Center), + ] + .spacing(12); + + let metering = row![ + meter_column("Detector", detector_db, detector_text), + meter_column( + "Reduction", + -gain_reduction_db, + format!("{gain_reduction_db:.1} dB"), + ), + column![ + text("State").size(13), + text(status_text).size(16), + text(if monitor { + "Monitoring key" + } else { + "Main output" + }) + .size(11), + ] + .spacing(8) + .align_x(Alignment::Center), + ] + .spacing(20) + .align_y(Alignment::Center); + + let content = column![ + preset::bar(&state.preset_ui), + row![controls, metering] + .spacing(24) + .align_y(Alignment::Center), + ] + .spacing(16) + .align_x(Alignment::Start); + + container(content) + .padding(24) + .width(Length::Fill) + .height(Length::Fill) + .align_x(Horizontal::Left) + .align_y(Vertical::Top) + .into() +} + +fn theme(_state: &State) -> Theme { + Theme::TokyoNight +} + +fn build_app(shared: Arc) -> impl maolan_baseview::iced::Program { + maolan_baseview::iced::application(move || init(shared.clone()), update, view) + .font(maolan_widgets::iced_fonts::LUCIDE_FONT_BYTES) + .theme(theme) + .run() +} + +pub struct App; + +impl crate::common::gui_bridge::GuiApp for App { + type Parent = ParentWindowHandle; + + fn title() -> String { + String::from("Maolan Gate") + } + + fn size() -> (u32, u32) { + (EDITOR_WIDTH, EDITOR_HEIGHT) + } + + fn always_redraw() -> bool { + false + } + + fn notify_closed_on_hide() -> bool { + true + } + + fn opens_parented_window() -> bool { + true + } + + fn preferred_api() -> &'static CStr { + preferred_api() + } + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" + ))] + fn parent_from_window( + window: &maolan_clap::ffi::clap_window, + api: &CStr, + ) -> Option { + crate::gate::gui::parent_from_window(window, api) + } + + fn build_app( + shared: std::sync::Arc, + ) -> impl maolan_baseview::iced::Program { + build_app(shared) + } +} + +pub type GuiBridge = crate::common::gui_bridge::GuiBridge; + +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" +))] +pub fn parent_from_window( + window: &maolan_clap::ffi::clap_window, + api: &CStr, +) -> Option { + use maolan_clap::ffi::{CLAP_WINDOW_API_COCOA, CLAP_WINDOW_API_WIN32, CLAP_WINDOW_API_X11}; + if api == CLAP_WINDOW_API_X11 { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + Some(ParentWindowHandle::X11(unsafe { + window.clap_window__.x11 as usize + })) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd")))] + { + None + } + } else if api == CLAP_WINDOW_API_WIN32 { + #[cfg(target_os = "windows")] + { + Some(ParentWindowHandle::Win32(unsafe { + window.clap_window__.win32 + })) + } + #[cfg(not(target_os = "windows"))] + { + None + } + } else if api == CLAP_WINDOW_API_COCOA { + #[cfg(target_os = "macos")] + { + Some(ParentWindowHandle::Cocoa(unsafe { + window.clap_window__.cocoa + })) + } + #[cfg(not(target_os = "macos"))] + { + None + } + } else { + None + } +} diff --git a/src/gate/mod.rs b/src/gate/mod.rs new file mode 100644 index 0000000..a21b470 --- /dev/null +++ b/src/gate/mod.rs @@ -0,0 +1,7 @@ +pub mod dsp; +pub mod gui; +mod params; +mod plugin; +mod state; + +pub use plugin::{clap_create_plugin, descriptor_ptr as clap_descriptor_ptr}; diff --git a/src/gate/params.rs b/src/gate/params.rs new file mode 100644 index 0000000..838a65e --- /dev/null +++ b/src/gate/params.rs @@ -0,0 +1,134 @@ +use maolan_clap::ffi::{ + CLAP_PARAM_IS_AUTOMATABLE, CLAP_PARAM_IS_STEPPED, CLAP_PARAM_REQUIRES_PROCESS, +}; + +crate::define_params! { + pub enum ParamId { + Threshold = 0, + Ratio = 1, + Range = 2, + Attack = 3, + Hold = 4, + Release = 5, + Hysteresis = 6, + SidechainHpf = 7, + SidechainLpf = 8, + ExternalSidechain = 9, + Monitor = 10, + } + pub const PARAMS: [ParamDef] = [ + { + id: ParamId::Threshold, + name: "Threshold", + module: "Gate", + min: -80.0, + max: 0.0, + default: -50.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Ratio, + name: "Ratio", + module: "Gate", + min: 1.0, + max: 100.0, + default: 4.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Range, + name: "Range", + module: "Gate", + min: 0.0, + max: 100.0, + default: 80.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Attack, + name: "Attack", + module: "Gate", + min: 0.01, + max: 100.0, + default: 1.0, + step: 0.01, + flags: AUTOMATABLE, + } + { + id: ParamId::Hold, + name: "Hold", + module: "Gate", + min: 0.0, + max: 500.0, + default: 50.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Release, + name: "Release", + module: "Gate", + min: 1.0, + max: 2000.0, + default: 150.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Hysteresis, + name: "Hysteresis", + module: "Gate", + min: 0.0, + max: 24.0, + default: 3.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::SidechainHpf, + name: "Sidechain HPF", + module: "Detector", + min: 20.0, + max: 2000.0, + default: 20.0, + step: 1.0, + flags: AUTOMATABLE, + } + { + id: ParamId::SidechainLpf, + name: "Sidechain LPF", + module: "Detector", + min: 1000.0, + max: 20000.0, + default: 20000.0, + step: 1.0, + flags: AUTOMATABLE, + } + { + id: ParamId::ExternalSidechain, + name: "External Sidechain", + module: "Detector", + min: 0.0, + max: 1.0, + default: 0.0, + step: 1.0, + flags: BOOL_FLAGS, + } + { + id: ParamId::Monitor, + name: "Monitor", + module: "Detector", + min: 0.0, + max: 1.0, + default: 0.0, + step: 1.0, + flags: BOOL_FLAGS, + } + ]; +} + +const AUTOMATABLE: u32 = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_REQUIRES_PROCESS; +const BOOL_FLAGS: u32 = AUTOMATABLE | CLAP_PARAM_IS_STEPPED; diff --git a/src/gate/plugin.rs b/src/gate/plugin.rs new file mode 100644 index 0000000..c9cc0a7 --- /dev/null +++ b/src/gate/plugin.rs @@ -0,0 +1,533 @@ +use std::{ + ffi::{CStr, c_char, c_void}, + sync::atomic::Ordering, +}; + +use maolan_clap::{ + ffi::{ + CLAP_AUDIO_PORT_IS_MAIN, CLAP_EXT_AUDIO_PORTS, CLAP_EXT_GUI, CLAP_EXT_PARAMS, + CLAP_EXT_STATE, CLAP_EXT_TAIL, CLAP_INVALID_ID, CLAP_PLUGIN_FEATURE_AUDIO_EFFECT, + CLAP_PLUGIN_FEATURE_GATE, CLAP_PLUGIN_FEATURE_MONO, CLAP_PLUGIN_FEATURE_STEREO, + CLAP_PORT_MONO, CLAP_PROCESS_CONTINUE, CLAP_VERSION, clap_audio_port_info, clap_host, + clap_plugin, clap_plugin_descriptor, clap_process_status, + }, + process::Process, +}; + +use crate::common::clap_harness::{ + DescriptorMeta, ParamHost, ParamSharedState, ParamSpec, PortConfig, Processor, SharedBase, + StateHooks, +}; +use crate::common::{apply_param_events, emit_pending_param_events_to_host}; +use crate::gate::{ + dsp::{Gate, GateParams, GateStatus}, + gui::GuiBridge, + params::{PARAMS, ParamId, sanitize_param_value}, + state::PluginState, +}; +use crate::{ + clap_create_fn, clap_descriptor, clap_gui_ext, clap_params_ext, clap_state_ext, clap_tail_ext, + mono_pair, +}; + +const PLUGIN_ID: &[u8] = b"rs.maolan.gate\0"; +const PLUGIN_NAME: &[u8] = b"Maolan Gate\0"; +const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; +const PLUGIN_URL: &[u8] = b"\0"; +const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_DESCRIPTION: &[u8] = b"Stereo downward expander and noise gate\0"; +const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); +const FEATURE_GATE: *const c_char = CLAP_PLUGIN_FEATURE_GATE.as_ptr(); +const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr(); +const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); +const FEATURE_PTRS: &[*const c_char] = &[ + FEATURE_AUDIO_EFFECT, + FEATURE_GATE, + FEATURE_MONO, + FEATURE_STEREO, + std::ptr::null(), +]; + +static META: DescriptorMeta = DescriptorMeta { + id: PLUGIN_ID, + name: PLUGIN_NAME, + vendor: PLUGIN_VENDOR, + url: PLUGIN_URL, + version: PLUGIN_VERSION, + description: PLUGIN_DESCRIPTION, + features: FEATURE_PTRS, +}; + +clap_descriptor!(META); + +#[derive(Debug)] +pub struct SharedState { + core: ParamSharedState, + detector_level_db: portable_atomic::AtomicF32, + gain_reduction_db: portable_atomic::AtomicF32, + status: std::sync::atomic::AtomicU32, +} + +impl Default for SharedState { + fn default() -> Self { + Self { + core: ParamSharedState::default(), + detector_level_db: portable_atomic::AtomicF32::new(-200.0), + gain_reduction_db: portable_atomic::AtomicF32::new(0.0), + status: std::sync::atomic::AtomicU32::new(GateStatus::Closed as u32), + } + } +} + +impl std::ops::Deref for SharedState { + type Target = ParamSharedState; + + fn deref(&self) -> &Self::Target { + &self.core + } +} + +impl std::ops::DerefMut for SharedState { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.core + } +} + +impl SharedBase for SharedState { + fn set_host(&self, host: *const clap_host) { + self.core.set_host(host); + } + + fn clear_host(&self) { + self.core.clear_host(); + } + + fn set_sample_rate(&self, sample_rate: f64) { + self.core.set_sample_rate(sample_rate); + } + + fn notify_gui_closed(&self) { + self.core.request_gui_closed(); + } +} + +impl ParamHost for SharedState { + type Param = ParamId; + + fn params(&self) -> &crate::common::param_store::ParamStore { + &self.core.params + } +} + +crate::delegate_param_shared_ext!(SharedState, ParamId); + +impl ParamSpec for ParamId { + fn param_defs() -> &'static [crate::common::clap_harness::ParamDef] { + &PARAMS + } + + fn param_text(id: Self, value: f64) -> String { + param_text(id, value) + } + + fn parse_param_text(id: Self, text: &str) -> Option { + parse_param_text(id, text) + } + + fn on_param_set(id: Self, shared: &ParamSharedState) { + if id == ParamId::ExternalSidechain { + shared.request_audio_ports_rescan(); + } + } +} + +impl SharedState { + pub fn bump_params_version(&self) { + self.core.request_audio_ports_rescan(); + } + + pub fn meter(&self) -> (f32, f32, GateStatus) { + let status = match self.status.load(Ordering::Relaxed) { + 1 => GateStatus::Holding, + 2 => GateStatus::Open, + _ => GateStatus::Closed, + }; + ( + self.detector_level_db.load(Ordering::Relaxed), + self.gain_reduction_db.load(Ordering::Relaxed), + status, + ) + } + + fn set_meter(&self, meter: crate::gate::dsp::GateMeter) { + self.detector_level_db + .store(meter.detector_db, Ordering::Relaxed); + self.gain_reduction_db + .store(meter.gain_reduction_db.max(0.0), Ordering::Relaxed); + self.status.store(meter.status as u32, Ordering::Relaxed); + } +} + +crate::impl_param_presets!(SharedState, ParamId, "gate", "maolan-gate-preset"); + +struct AudioProcessor { + gate: Gate, + temp_left: Vec, + temp_right: Vec, + detector_left: Vec, + detector_right: Vec, +} + +impl AudioProcessor { + fn new(sample_rate: f64, max_frames: u32) -> Self { + Self { + gate: Gate::new(sample_rate as f32), + temp_left: vec![0.0; max_frames as usize], + temp_right: vec![0.0; max_frames as usize], + detector_left: vec![0.0; max_frames as usize], + detector_right: vec![0.0; max_frames as usize], + } + } + + fn reset(&mut self) { + self.gate.reset(); + } + + fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { + apply_param_events(shared, &process.in_events(), sanitize_param_value); + { + let mut out_events = process.out_events(); + emit_pending_param_events_to_host(shared, &mut out_events); + } + + let frames = process.frames_count() as usize; + if self.temp_left.len() < frames { + self.temp_left.resize(frames, 0.0); + self.temp_right.resize(frames, 0.0); + self.detector_left.resize(frames, 0.0); + self.detector_right.resize(frames, 0.0); + } + + let inputs_count = process.audio_inputs_count() as usize; + let outputs_count = process.audio_outputs_count() as usize; + let stereo = inputs_count >= 2 && outputs_count >= 2; + let main_channels = if stereo { + 2 + } else if inputs_count >= 1 && outputs_count >= 1 { + 1 + } else { + 0 + }; + if main_channels == 0 { + return CLAP_PROCESS_CONTINUE; + } + + { + let input_l = process.audio_inputs(0); + self.temp_left[..frames].copy_from_slice(input_l.data32(0)); + } + if stereo { + let input_r = process.audio_inputs(1); + self.temp_right[..frames].copy_from_slice(input_r.data32(0)); + } else { + self.temp_right[..frames].fill(0.0); + } + + let external_requested = shared.params.get_bool(ParamId::ExternalSidechain); + let mut external_copied = false; + if external_requested && inputs_count >= main_channels * 2 { + let sc_l = process.audio_inputs(main_channels as u32); + let sc_r = stereo.then(|| process.audio_inputs(main_channels as u32 + 1)); + let right_valid = !stereo + || sc_r + .as_ref() + .is_some_and(|port| port.data32(0).len() >= frames); + if sc_l.data32(0).len() >= frames && right_valid { + self.detector_left[..frames].copy_from_slice(&sc_l.data32(0)[..frames]); + if let Some(sc_r) = sc_r { + self.detector_right[..frames].copy_from_slice(&sc_r.data32(0)[..frames]); + } else { + self.detector_right[..frames].fill(0.0); + } + external_copied = true; + } + } + if !external_copied { + self.detector_left[..frames].copy_from_slice(&self.temp_left[..frames]); + self.detector_right[..frames].copy_from_slice(&self.temp_right[..frames]); + } + + let params = GateParams { + threshold_db: shared.params.get(ParamId::Threshold) as f32, + ratio: shared.params.get(ParamId::Ratio) as f32, + range_db: shared.params.get(ParamId::Range) as f32, + attack_ms: shared.params.get(ParamId::Attack) as f32, + hold_ms: shared.params.get(ParamId::Hold) as f32, + release_ms: shared.params.get(ParamId::Release) as f32, + hysteresis_db: shared.params.get(ParamId::Hysteresis) as f32, + sidechain_hpf_hz: shared.params.get(ParamId::SidechainHpf) as f32, + sidechain_lpf_hz: shared.params.get(ParamId::SidechainLpf) as f32, + monitor: shared.params.get_bool(ParamId::Monitor), + }; + let meter = self.gate.process_stereo( + &mut self.temp_left[..frames], + &mut self.temp_right[..frames], + &self.detector_left[..frames], + &self.detector_right[..frames], + ¶ms, + ); + shared.set_meter(meter); + + { + let mut output_l = process.audio_outputs(0); + output_l.data32(0)[..frames].copy_from_slice(&self.temp_left[..frames]); + } + if stereo { + let mut output_r = process.audio_outputs(1); + output_r.data32(0)[..frames].copy_from_slice(&self.temp_right[..frames]); + } + + CLAP_PROCESS_CONTINUE + } +} + +impl Processor for AudioProcessor { + fn new( + sample_rate: f64, + max_frames: u32, + _bus_data: Option, + ) -> Self { + AudioProcessor::new(sample_rate, max_frames) + } + + fn reset(&mut self) { + AudioProcessor::reset(self); + } + + fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { + AudioProcessor::process(self, shared, process) + } +} + +pub(crate) fn param_text(id: ParamId, value: f64) -> String { + match id { + ParamId::Threshold | ParamId::Range | ParamId::Hysteresis => format!("{value:.1} dB"), + ParamId::Ratio => format!("{value:.1}:1"), + ParamId::Attack | ParamId::Hold | ParamId::Release => format!("{value:.2} ms"), + ParamId::SidechainHpf | ParamId::SidechainLpf => format!("{value:.0} Hz"), + ParamId::ExternalSidechain => { + if value >= 0.5 { + "External".to_string() + } else { + "Internal".to_string() + } + } + ParamId::Monitor => { + if value >= 0.5 { + "Monitor".to_string() + } else { + "Off".to_string() + } + } + } +} + +fn parse_number(text: &str, suffix: &str) -> Option { + text.trim().trim_end_matches(suffix).trim_end().parse().ok() +} + +fn parse_param_text(id: ParamId, text: &str) -> Option { + match id { + ParamId::Threshold | ParamId::Range | ParamId::Hysteresis => parse_number(text, "dB"), + ParamId::Ratio => parse_number(text, ":1"), + ParamId::Attack | ParamId::Hold | ParamId::Release => parse_number(text, "ms"), + ParamId::SidechainHpf | ParamId::SidechainLpf => { + let normalized = text.trim().to_ascii_lowercase(); + if let Some(value) = normalized.strip_suffix("khz") { + value + .trim_end() + .parse::() + .ok() + .map(|value| value * 1000.0) + } else { + parse_number(&normalized, "hz") + } + } + ParamId::ExternalSidechain => match text.trim().to_ascii_lowercase().as_str() { + "external" | "on" => Some(1.0), + "internal" | "off" => Some(0.0), + _ => text.parse().ok(), + }, + ParamId::Monitor => match text.trim().to_ascii_lowercase().as_str() { + "monitor" | "on" => Some(1.0), + "off" => Some(0.0), + _ => text.parse().ok(), + }, + } +} + +impl StateHooks for PluginState { + fn save(shared: &SharedState) -> Option> { + PluginState::from_runtime(&shared.params) + .to_bytes(crate::gate::state::STATE_HEADER_PREFIX) + .ok() + } + + fn load(shared: &SharedState, bytes: &[u8]) -> bool { + let Ok(state) = PluginState::from_bytes(bytes, crate::gate::state::STATE_HEADER_PREFIX) + else { + return false; + }; + state.apply(&shared.params); + shared.core.request_audio_ports_rescan(); + true + } +} + +fn audio_port_count(is_input: bool, external_sidechain: bool) -> u32 { + if is_input && external_sidechain { 4 } else { 2 } +} + +unsafe extern "C-unwind" fn ext_audio_ports_count( + plugin: *const clap_plugin, + is_input: bool, +) -> u32 { + if plugin.is_null() { + return 0; + } + let instance = unsafe { + crate::common::clap_harness::instance::(plugin) + }; + audio_port_count( + is_input, + instance.shared.params.get_bool(ParamId::ExternalSidechain), + ) +} + +unsafe extern "C-unwind" fn ext_audio_ports_get( + plugin: *const clap_plugin, + index: u32, + is_input: bool, + info: *mut clap_audio_port_info, +) -> bool { + if plugin.is_null() || info.is_null() { + return false; + } + let instance = unsafe { + crate::common::clap_harness::instance::(plugin) + }; + let external = instance.shared.params.get_bool(ParamId::ExternalSidechain); + if index >= audio_port_count(is_input, external) { + return false; + } + let info = unsafe { &mut *info }; + info.id = index; + info.channel_count = 1; + info.port_type = CLAP_PORT_MONO.as_ptr(); + info.in_place_pair = CLAP_INVALID_ID; + let is_sidechain = is_input && external && index >= 2; + info.flags = if is_sidechain { + 0 + } else { + CLAP_AUDIO_PORT_IS_MAIN + }; + let name = match (is_input, index) { + (true, 0) => "in_l", + (true, 1) => "in_r", + (true, 2) => "sc_l", + (true, 3) => "sc_r", + (false, 0) => "out_l", + (false, 1) => "out_r", + _ => "", + }; + crate::common::copy_str_to_array(name, &mut info.name); + true +} + +static AUDIO_PORTS_EXT: maolan_clap::ffi::clap_plugin_audio_ports = + maolan_clap::ffi::clap_plugin_audio_ports { + count: Some(ext_audio_ports_count), + get: Some(ext_audio_ports_get), + }; + +clap_params_ext!(SharedState, AudioProcessor, GuiBridge); +clap_state_ext!(SharedState, AudioProcessor, GuiBridge, PluginState); +clap_tail_ext!(SharedState, AudioProcessor, GuiBridge, 0); +clap_gui_ext!(SharedState, AudioProcessor, GuiBridge); + +unsafe extern "C-unwind" fn plugin_get_extension( + plugin: *const clap_plugin, + id: *const c_char, +) -> *const c_void { + if plugin.is_null() || id.is_null() { + return std::ptr::null(); + } + let id = unsafe { CStr::from_ptr(id) }; + if id == CLAP_EXT_AUDIO_PORTS { + &raw const AUDIO_PORTS_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_PARAMS { + &raw const PARAMS_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_STATE { + &raw const STATE_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_TAIL { + &raw const TAIL_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_GUI { + &raw const GUI_EXT as *const _ as *const c_void + } else { + std::ptr::null() + } +} + +const PORTS: PortConfig = PortConfig { + inputs: mono_pair!("in_l", "in_r"), + outputs: mono_pair!("out_l", "out_r"), +}; + +clap_create_fn!(SharedState, AudioProcessor, GuiBridge, PORTS,); + +#[cfg(test)] +mod tests { + use super::{ParamId, PluginState, SharedState, audio_port_count}; + use crate::gate::state::STATE_HEADER_PREFIX; + + #[test] + fn parameter_text_roundtrips() { + for id in ParamId::all() { + let value = super::PARAMS[id.as_index()].default; + let text = super::param_text(id, value); + let parsed = super::parse_param_text(id, &text).expect("parameter text should parse"); + assert!( + (parsed - value).abs() < 0.011, + "{id:?}: {value} -> {text} -> {parsed}" + ); + } + } + + #[test] + fn external_sidechain_adds_two_input_ports_only() { + assert_eq!(audio_port_count(true, false), 2); + assert_eq!(audio_port_count(false, false), 2); + assert_eq!(audio_port_count(true, true), 4); + assert_eq!(audio_port_count(false, true), 2); + } + + #[test] + fn state_roundtrip_preserves_parameters() { + let shared = SharedState::default(); + shared.params.set(ParamId::Threshold, -37.0); + shared.params.set(ParamId::Ratio, 12.0); + shared.params.set(ParamId::ExternalSidechain, 1.0); + let state = PluginState::from_runtime(&shared.params); + let bytes = state + .to_bytes(STATE_HEADER_PREFIX) + .expect("state should save"); + + let restored = SharedState::default(); + let state = + PluginState::from_bytes(&bytes, STATE_HEADER_PREFIX).expect("state should load"); + state.apply(&restored.params); + assert_eq!(restored.params.get(ParamId::Threshold), -37.0); + assert_eq!(restored.params.get(ParamId::Ratio), 12.0); + assert_eq!(restored.params.get(ParamId::ExternalSidechain), 1.0); + } +} diff --git a/src/gate/state.rs b/src/gate/state.rs new file mode 100644 index 0000000..f9bf2a7 --- /dev/null +++ b/src/gate/state.rs @@ -0,0 +1,5 @@ +use crate::gate::params::ParamId; + +pub type PluginState = crate::common::json_state::JsonParamState; + +pub const STATE_HEADER_PREFIX: &str = "maolan-gate-state-v"; diff --git a/src/lib.rs b/src/lib.rs index 4818c87..0fecb87 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,7 @@ pub mod drums; pub mod eq; pub mod flanger; pub mod formant; +pub mod gate; pub mod kick; pub mod limiter; pub mod modeler; @@ -44,7 +45,7 @@ struct PluginApi { create: CreateFn, } -static PLUGINS: [PluginApi; 22] = [ +static PLUGINS: [PluginApi; 23] = [ PluginApi { descriptor: eq::clap_descriptor_ptr, create: eq::clap_create_plugin, @@ -53,6 +54,10 @@ static PLUGINS: [PluginApi; 22] = [ descriptor: compressor::clap_descriptor_ptr, create: compressor::clap_create_plugin, }, + PluginApi { + descriptor: gate::clap_descriptor_ptr, + create: gate::clap_create_plugin, + }, PluginApi { descriptor: limiter::clap_descriptor_ptr, create: limiter::clap_create_plugin,