diff --git a/Cargo.lock b/Cargo.lock index 0fb0667..958d1f3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2602,9 +2602,9 @@ dependencies = [ [[package]] name = "maolan-widgets" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3453db14abcd023fa269d3eca7c97cc4d197b6164ea8e314c8591de562afaec5" +checksum = "d40abf7b434a82ec7b99d264acef501ef3461e9aa766b00966db3defda4a8117" dependencies = [ "iced", "iced_aw", diff --git a/Cargo.toml b/Cargo.toml index 00f3286..6a317ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ pitch-detection = "0.3.0" symphonia = { version = "0.6.1", features = ["aac", "alac", "flac", "isomp4", "mp3", "ogg", "vorbis", "wav"] } maolan-baseview = { version = "0.1.1", features = ["canvas"] } maolan-editor = { version = "0.1.3", default-features = false } -maolan-widgets = "0.1.1" +maolan-widgets = "0.1.2" parking_lot = "0.13.0" portable-atomic = { version = "1.15.0", features = ["float"] } quick-xml = { version = "0.42.0", features = ["serialize"] } diff --git a/src/common/filter.rs b/src/common/filter.rs index 437dbb8..69ce4b1 100644 --- a/src/common/filter.rs +++ b/src/common/filter.rs @@ -13,12 +13,7 @@ pub enum FilterType { CombPos = 6, CombNeg = 7, Allpass = 8, - Ladder = 9, - K35Lp = 10, - K35Hp = 11, DiodeLadder = 12, - CutoffWarp = 13, - ResonanceWarp = 14, Lowpass12dB = 15, Highpass12dB = 16, Bandpass12dB = 17, @@ -39,23 +34,6 @@ pub enum FilterType { CytomicHs = 31, TriPole = 32, SampleHold = 33, - - CutoffWarpHp = 34, - CutoffWarpBp = 35, - CutoffWarpNotch = 36, - CutoffWarpAp = 37, - - ResonanceWarpLp = 38, - ResonanceWarpHp = 39, - ResonanceWarpNotch = 40, - ResonanceWarpAp = 41, - - Obxd2PoleLp = 42, - Obxd2PoleHp = 43, - Obxd2PoleBp = 44, - Obxd2PoleNotch = 45, - Obxd4Pole = 46, - ObxdXpander = 47, Notch24dB = 48, } @@ -71,12 +49,7 @@ impl FilterType { 6 => FilterType::CombPos, 7 => FilterType::CombNeg, 8 => FilterType::Allpass, - 9 => FilterType::Ladder, - 10 => FilterType::K35Lp, - 11 => FilterType::K35Hp, 12 => FilterType::DiodeLadder, - 13 => FilterType::CutoffWarp, - 14 => FilterType::ResonanceWarp, 15 => FilterType::Lowpass12dB, 16 => FilterType::Highpass12dB, 17 => FilterType::Bandpass12dB, @@ -96,22 +69,8 @@ impl FilterType { 31 => FilterType::CytomicHs, 32 => FilterType::TriPole, 33 => FilterType::SampleHold, - 34 => FilterType::CutoffWarpHp, - 35 => FilterType::CutoffWarpBp, - 36 => FilterType::CutoffWarpNotch, - 37 => FilterType::CutoffWarpAp, - 38 => FilterType::ResonanceWarpLp, - 39 => FilterType::ResonanceWarpHp, - 40 => FilterType::ResonanceWarpNotch, - 41 => FilterType::ResonanceWarpAp, - 42 => FilterType::Obxd2PoleLp, - 43 => FilterType::Obxd2PoleHp, - 44 => FilterType::Obxd2PoleBp, - 45 => FilterType::Obxd2PoleNotch, - 46 => FilterType::Obxd4Pole, - 47 => FilterType::ObxdXpander, 48 => FilterType::Notch24dB, - _ => FilterType::ResonanceWarpAp, + _ => FilterType::Lowpass, } } } @@ -162,12 +121,7 @@ impl FilterType { FilterType::CombPos => "Comb+", FilterType::CombNeg => "Comb-", FilterType::Allpass => "Allpass", - FilterType::Ladder => "Ladder", - FilterType::K35Lp => "K35 LP", - FilterType::K35Hp => "K35 HP", FilterType::DiodeLadder => "Diode Ldr", - FilterType::CutoffWarp => "CW LP", - FilterType::ResonanceWarp => "RW LP", FilterType::Lowpass12dB => "LP 12", FilterType::Highpass12dB => "HP 12", FilterType::Bandpass12dB => "BP 12", @@ -187,20 +141,6 @@ impl FilterType { FilterType::CytomicHs => "SVF Hi Shf", FilterType::TriPole => "TriPole", FilterType::SampleHold => "S&H", - FilterType::CutoffWarpHp => "CW HP", - FilterType::CutoffWarpBp => "CW BP", - FilterType::CutoffWarpNotch => "CW Notch", - FilterType::CutoffWarpAp => "CW AP", - FilterType::ResonanceWarpLp => "RW LP", - FilterType::ResonanceWarpHp => "RW HP", - FilterType::ResonanceWarpNotch => "RW Notch", - FilterType::ResonanceWarpAp => "RW AP", - FilterType::Obxd2PoleLp => "OBXd 2p LP", - FilterType::Obxd2PoleHp => "OBXd 2p HP", - FilterType::Obxd2PoleBp => "OBXd 2p BP", - FilterType::Obxd2PoleNotch => "OBXd 2p Nt", - FilterType::Obxd4Pole => "OBXd 4p", - FilterType::ObxdXpander => "OBXd Xpndr", FilterType::Notch24dB => "Notch 24", } } @@ -221,22 +161,6 @@ pub enum FilterSubtype { SoftClip = 4, SineSat = 5, Ojd = 6, - - XpanderLp1 = 7, - XpanderLp2 = 8, - XpanderLp3 = 9, - XpanderLp4 = 10, - XpanderHp1 = 11, - XpanderHp2 = 12, - XpanderHp3 = 13, - XpanderBp2 = 14, - XpanderBp4 = 15, - XpanderN2 = 16, - XpanderPh3 = 17, - XpanderHp2Lp1 = 18, - XpanderHp3Lp1 = 19, - XpanderN2Lp1 = 20, - XpanderPh3Lp1 = 21, } impl std::fmt::Display for FilterSubtype { @@ -249,21 +173,6 @@ impl std::fmt::Display for FilterSubtype { Self::SoftClip => "SoftClip", Self::SineSat => "SineSat", Self::Ojd => "Ojd", - Self::XpanderLp1 => "XpanderLp1", - Self::XpanderLp2 => "XpanderLp2", - Self::XpanderLp3 => "XpanderLp3", - Self::XpanderLp4 => "XpanderLp4", - Self::XpanderHp1 => "XpanderHp1", - Self::XpanderHp2 => "XpanderHp2", - Self::XpanderHp3 => "XpanderHp3", - Self::XpanderBp2 => "XpanderBp2", - Self::XpanderBp4 => "XpanderBp4", - Self::XpanderN2 => "XpanderN2", - Self::XpanderPh3 => "XpanderPh3", - Self::XpanderHp2Lp1 => "XpanderHp2Lp1", - Self::XpanderHp3Lp1 => "XpanderHp3Lp1", - Self::XpanderN2Lp1 => "XpanderN2Lp1", - Self::XpanderPh3Lp1 => "XpanderPh3Lp1", }; write!(f, "{name}") } @@ -278,22 +187,6 @@ impl FilterSubtype { 3 => FilterSubtype::Asymmetric, 4 => FilterSubtype::SoftClip, 5 => FilterSubtype::SineSat, - 6 => FilterSubtype::Ojd, - 7 => FilterSubtype::XpanderLp1, - 8 => FilterSubtype::XpanderLp2, - 9 => FilterSubtype::XpanderLp3, - 10 => FilterSubtype::XpanderLp4, - 11 => FilterSubtype::XpanderHp1, - 12 => FilterSubtype::XpanderHp2, - 13 => FilterSubtype::XpanderHp3, - 14 => FilterSubtype::XpanderBp2, - 15 => FilterSubtype::XpanderBp4, - 16 => FilterSubtype::XpanderN2, - 17 => FilterSubtype::XpanderPh3, - 18 => FilterSubtype::XpanderHp2Lp1, - 19 => FilterSubtype::XpanderHp3Lp1, - 20 => FilterSubtype::XpanderN2Lp1, - 21 => FilterSubtype::XpanderPh3Lp1, _ => FilterSubtype::Ojd, } } @@ -832,76 +725,6 @@ impl BiquadFilter { } } -#[derive(Debug, Clone)] -pub struct LadderFilter { - sample_rate: f32, - pub cutoff_hz: f32, - pub resonance: f32, - pub drive: f32, - pub subtype: FilterSubtype, - pub feedback_drive: f32, - stages: [f32; 4], - g: f32, - k: f32, -} - -impl LadderFilter { - pub fn new(sample_rate: f32) -> Self { - Self { - sample_rate, - cutoff_hz: 20000.0, - resonance: 0.0, - drive: 0.0, - subtype: FilterSubtype::Clean, - feedback_drive: 0.0, - stages: [0.0; 4], - g: 0.0, - k: 0.0, - } - } - - pub fn set_sample_rate(&mut self, sample_rate: f32) { - self.sample_rate = sample_rate; - } - - pub fn reset(&mut self) { - self.stages = [0.0; 4]; - } - - pub fn set_params(&mut self, cutoff: f32, resonance: f32) { - self.cutoff_hz = cutoff; - self.resonance = resonance; - } - - pub fn prepare_block(&mut self, _cutoff: f32, _resonance: f32, _block_size: usize) { - let fc = (self.cutoff_hz / self.sample_rate).clamp(0.0001, 0.4999); - let g = (std::f32::consts::PI * fc).tan(); - self.g = g / (1.0 + g); - self.k = self.resonance * 4.0; - } - - pub fn process(&mut self, input: f32) -> f32 { - let in_driven = apply_subtype(input, self.subtype, self.drive); - let fb_gain = 1.0 + self.feedback_drive * 4.0; - let fb = tanh_sat(self.stages[3] * fb_gain); - let mut x = in_driven - self.k * fb; - x = tanh_sat(x); - - for i in 0..4 { - self.stages[i] = self.stages[i] + self.g * (x - self.stages[i]); - x = self.stages[i]; - } - - match self.subtype { - FilterSubtype::Clean => self.stages[3], - FilterSubtype::MildDrive => self.stages[2], - FilterSubtype::HeavyDrive => self.stages[1], - FilterSubtype::Asymmetric => self.stages[0], - _ => self.stages[3], - } - } -} - #[derive(Debug, Clone)] pub struct CytomicSvfFilter { sample_rate: f32, @@ -1204,143 +1027,6 @@ impl VintageLadderFilter { } } -#[derive(Debug, Clone)] -pub struct K35Filter { - sample_rate: f32, - pub filter_type: FilterType, - pub cutoff_hz: f32, - pub resonance: f32, - pub saturation: f32, - pub drive: f32, - pub subtype: FilterSubtype, - lpf1_state: f32, - lpf2_state: f32, - hpf1_state: f32, - g_val: f32, - gp1: f32, - k: f32, - alpha: f32, -} - -impl K35Filter { - pub fn new(sample_rate: f32) -> Self { - Self { - sample_rate, - filter_type: FilterType::K35Lp, - cutoff_hz: 20000.0, - resonance: 0.7, - saturation: 0.0, - drive: 0.0, - subtype: FilterSubtype::Clean, - lpf1_state: 0.0, - lpf2_state: 0.0, - hpf1_state: 0.0, - g_val: 0.0, - gp1: 1.0, - k: 0.0, - alpha: 1.0, - } - } - - pub fn set_sample_rate(&mut self, sample_rate: f32) { - self.sample_rate = sample_rate; - } - - pub fn reset(&mut self) { - self.lpf1_state = 0.0; - self.lpf2_state = 0.0; - self.hpf1_state = 0.0; - } - - pub fn set_params(&mut self, cutoff: f32, resonance: f32) { - self.cutoff_hz = cutoff; - self.resonance = resonance; - } - - pub fn prepare_block(&mut self, _cutoff: f32, _resonance: f32, _block_size: usize) { - let wd = (self.cutoff_hz * 2.0 * std::f32::consts::PI).clamp(0.0, self.sample_rate * 0.499); - let wa = (2.0 * self.sample_rate) * (wd / self.sample_rate * 0.5).tan(); - let g = wa / self.sample_rate * 0.5; - self.gp1 = 1.0 + g; - self.g_val = g / self.gp1; - self.k = self.resonance.clamp(0.01, 1.96); - self.alpha = 1.0 / (1.0 - self.k * self.g_val + self.k * self.g_val * self.g_val); - } - - fn k35_saturate(&self, x: f32) -> f32 { - match self.subtype { - FilterSubtype::Clean => x, - FilterSubtype::MildDrive => tanh_sat(x * 2.0) / 2.0, - FilterSubtype::HeavyDrive => tanh_sat(x * 4.0) / 4.0, - FilterSubtype::Asymmetric => { - if x >= 0.0 { - tanh_sat(x * 3.0) / 3.0 - } else { - tanh_sat(x) - } - } - FilterSubtype::SoftClip => { - let threshold = 1.0 / 3.0; - if x.abs() <= threshold { - x * 2.0 - } else if x.abs() <= 2.0 * threshold { - let sign = x.signum(); - let t = x.abs() - threshold; - sign * (2.0 * threshold + t * (1.0 - t * 1.5)) - } else { - x.signum() * 4.0 / 3.0 - } - } - _ => { - let sat = 1.0 + self.drive * 3.0; - tanh_sat(x * sat) / sat - } - } - } - - pub fn process(&mut self, input: f32) -> f32 { - let in_driven = apply_subtype(input, self.subtype, self.drive); - - if self.filter_type == FilterType::K35Lp { - let lb = (self.k - self.k * self.g_val) / self.gp1; - let hb = -1.0 / self.gp1; - - let y1 = self.g_val * in_driven + (1.0 - self.g_val) * self.lpf1_state; - self.lpf1_state = y1; - - let s35 = lb * self.lpf2_state + hb * self.hpf1_state; - let u = self.alpha * (y1 + s35); - let u_driven = self.k35_saturate(u); - - let y = self.k * (self.g_val * u_driven + (1.0 - self.g_val) * self.lpf2_state); - self.lpf2_state = self.g_val * u_driven + (1.0 - self.g_val) * self.lpf2_state; - - let hpf_out = self.g_val * y + (1.0 - self.g_val) * self.hpf1_state; - self.hpf1_state = hpf_out; - - y / self.k.max(0.01) - } else { - let lb = 1.0 / self.gp1; - let hb = -self.g_val / self.gp1; - - let y1 = self.g_val * in_driven + (1.0 - self.g_val) * self.lpf1_state; - self.lpf1_state = y1; - - let s35 = lb * self.lpf2_state + hb * self.hpf1_state; - let u = self.alpha * (y1 + s35); - let u_driven = self.k35_saturate(u); - - let y = self.k * (self.g_val * u_driven + (1.0 - self.g_val) * self.lpf2_state); - self.lpf2_state = self.g_val * u_driven + (1.0 - self.g_val) * self.lpf2_state; - - let hpf_out = self.g_val * y + (1.0 - self.g_val) * self.hpf1_state; - self.hpf1_state = hpf_out; - - (in_driven - y) / self.k.max(0.01) - } - } -} - #[derive(Debug, Clone)] pub struct DiodeLadderFilter { sample_rate: f32, @@ -1406,460 +1092,6 @@ impl DiodeLadderFilter { } } -#[derive(Debug, Clone)] -pub struct WarpFilter { - sample_rate: f32, - pub filter_type: FilterType, - pub cutoff_hz: f32, - pub resonance: f32, - pub drive: f32, - pub subtype: FilterSubtype, - - l: [f32; 4], - b: [f32; 4], - f: f32, - q: f32, -} - -impl WarpFilter { - pub fn new(sample_rate: f32) -> Self { - Self { - sample_rate, - filter_type: FilterType::CutoffWarp, - cutoff_hz: 20000.0, - resonance: 0.7, - drive: 0.0, - subtype: FilterSubtype::Clean, - l: [0.0; 4], - b: [0.0; 4], - f: 0.0, - q: 0.0, - } - } - - pub fn set_sample_rate(&mut self, sample_rate: f32) { - self.sample_rate = sample_rate; - } - - pub fn reset(&mut self) { - self.l = [0.0; 4]; - self.b = [0.0; 4]; - } - - pub fn set_params(&mut self, cutoff: f32, resonance: f32) { - self.cutoff_hz = cutoff; - self.resonance = resonance; - } - - pub fn prepare_block(&mut self, _cutoff: f32, _resonance: f32, _block_size: usize) { - let omega = (self.cutoff_hz / self.sample_rate).clamp(0.0001, 0.4999); - self.f = 2.0 * (std::f32::consts::PI * omega).sin(); - self.q = 1.0 / self.resonance.max(0.1); - } - - fn apply_warp_sat(&self, x: f32) -> f32 { - let sat_idx = (self.subtype as u8) % 3; - match sat_idx { - 0 => x, - 1 => tanh_sat(x * 2.0) / 2.0, - 2 => { - let t = x.abs(); - if t < 1.0 { - x * (1.5 - 0.5 * t * t) - } else { - x.signum() - } - } - _ => x, - } - } - - pub fn process(&mut self, input: f32) -> f32 { - let stage_count = ((self.subtype as u8) / 3).clamp(1, 4) as usize; - let drive = 1.0 + self.drive * 2.0; - let in_driven = apply_subtype(input, self.subtype, self.drive); - - let mut h = 0.0f32; - for i in 0..stage_count { - let input_to_stage = if i == 0 { in_driven } else { self.b[i - 1] }; - self.l[i] = self.f.mul_add(self.b[i], self.l[i]); - h = self - .q - .mul_add(-self.b[i], input_to_stage * self.q - self.l[i]); - self.b[i] = self.f.mul_add(h, self.b[i]); - - self.b[i] = self.apply_warp_sat(self.b[i]); - } - - let last = stage_count - 1; - let l_last = self.l[last]; - let b_last = self.b[last]; - - let out = match self.filter_type { - FilterType::CutoffWarp => tanh_sat(l_last * 1.5) / 1.5, - FilterType::CutoffWarpHp => tanh_sat(h * 1.5) / 1.5, - FilterType::CutoffWarpBp => tanh_sat(b_last * 1.5) / 1.5, - FilterType::CutoffWarpNotch => tanh_sat((in_driven - b_last) * 1.5) / 1.5, - FilterType::CutoffWarpAp => tanh_sat((in_driven - 2.0 * b_last) * 1.5) / 1.5, - - FilterType::ResonanceWarp => tanh_sat(b_last * 2.0) / 2.0, - FilterType::ResonanceWarpLp => tanh_sat(l_last * 2.0) / 2.0, - FilterType::ResonanceWarpHp => tanh_sat(h * 2.0) / 2.0, - FilterType::ResonanceWarpNotch => tanh_sat((in_driven - b_last) * 2.0) / 2.0, - FilterType::ResonanceWarpAp => tanh_sat((in_driven - 2.0 * b_last) * 2.0) / 2.0, - _ => l_last, - }; - - out / drive.max(1.0) - } -} - -#[derive(Debug, Clone)] -pub struct Obxd2PoleFilter { - sample_rate: f32, - pub filter_type: FilterType, - pub cutoff_hz: f32, - pub resonance: f32, - pub drive: f32, - pub subtype: FilterSubtype, - s1: f32, - s2: f32, - cutoff: f32, - r: f32, -} - -impl Obxd2PoleFilter { - pub fn new(sample_rate: f32) -> Self { - Self { - sample_rate, - filter_type: FilterType::Obxd2PoleLp, - cutoff_hz: 20000.0, - resonance: 0.7, - drive: 0.0, - subtype: FilterSubtype::Clean, - s1: 0.0, - s2: 0.0, - cutoff: 0.0, - r: 0.0, - } - } - - pub fn set_sample_rate(&mut self, sample_rate: f32) { - self.sample_rate = sample_rate; - } - - pub fn reset(&mut self) { - self.s1 = 0.0; - self.s2 = 0.0; - } - - pub fn set_params(&mut self, cutoff: f32, resonance: f32) { - self.cutoff_hz = cutoff; - self.resonance = resonance; - } - - #[inline] - fn diode_pair_resistance_approx(x: f32) -> f32 { - let a = 0.0103592f32.mul_add(x, 0.00920833); - let b = a.mul_add(x, 0.185); - let c = b.mul_add(x, 0.05); - c.mul_add(x, 1.0) - } - - pub fn prepare_block(&mut self, _cutoff: f32, _resonance: f32, _block_size: usize) { - let sr = self.sample_rate; - self.cutoff = (std::f32::consts::PI * self.cutoff_hz / sr) - .tan() - .clamp(0.0, 10.0); - self.r = (1.0 - self.resonance * 0.85).max(0.01); - } - - pub fn process(&mut self, input: f32) -> f32 { - let in_driven = apply_subtype(input, self.subtype, self.drive); - - let self_osc = self.subtype != FilterSubtype::Clean; - let tcfb = Self::diode_pair_resistance_approx(self.s1 * 0.0876) - - if self_osc { 1.035 } else { 1.0 }; - - let denom = 1.0 + self.cutoff * (2.0 * (self.r + tcfb) + self.cutoff); - let v = (in_driven - 2.0 * self.s1 * (self.r + tcfb) - self.cutoff * self.s1 - self.s2) - / denom.max(1e-6); - - let y1 = self.cutoff.mul_add(v, self.s1); - self.s1 = self.cutoff.mul_add(v, y1); - - let y2 = self.cutoff.mul_add(y1, self.s2); - self.s2 = self.cutoff.mul_add(y1, y2); - - let mc = match self.filter_type { - FilterType::Obxd2PoleLp => y2, - FilterType::Obxd2PoleHp => v, - FilterType::Obxd2PoleBp => y1, - FilterType::Obxd2PoleNotch => v + y2, - _ => y2, - }; - - mc * 0.74 - } -} - -#[derive(Debug, Clone)] -pub struct Obxd4PoleFilter { - sample_rate: f32, - pub cutoff_hz: f32, - pub resonance: f32, - pub drive: f32, - pub subtype: FilterSubtype, - s1: f32, - s2: f32, - s3: f32, - s4: f32, - g: f32, - lpc: f32, - r: f32, - rcor: f32, - rcorinv: f32, -} - -impl Obxd4PoleFilter { - pub fn new(sample_rate: f32) -> Self { - Self { - sample_rate, - cutoff_hz: 20000.0, - resonance: 0.7, - drive: 0.0, - subtype: FilterSubtype::Clean, - s1: 0.0, - s2: 0.0, - s3: 0.0, - s4: 0.0, - g: 0.0, - lpc: 0.0, - r: 0.0, - rcor: 0.0, - rcorinv: 0.0, - } - } - - pub fn set_sample_rate(&mut self, sample_rate: f32) { - self.sample_rate = sample_rate; - } - - pub fn reset(&mut self) { - self.s1 = 0.0; - self.s2 = 0.0; - self.s3 = 0.0; - self.s4 = 0.0; - } - - pub fn set_params(&mut self, cutoff: f32, resonance: f32) { - self.cutoff_hz = cutoff; - self.resonance = resonance; - } - - #[inline] - fn tptpc(state: &mut f32, inp: f32, g: f32) -> f32 { - let v = (inp - *state) * g / (1.0 + g); - let res = v + *state; - *state = res + v; - res - } - - pub fn prepare_block(&mut self, _cutoff: f32, _resonance: f32, _block_size: usize) { - let sr = self.sample_rate; - let sr_inv = 1.0 / sr; - let rcrate = (44000.0f32 * sr_inv).sqrt(); - self.g = (std::f32::consts::PI * self.cutoff_hz / sr) - .tan() - .clamp(0.0, 10.0); - self.lpc = self.g / (1.0 + self.g); - self.r = 3.5 * self.resonance; - self.rcor = (970.0 / 44000.0) * rcrate; - self.rcorinv = 1.0 / self.rcor.max(1e-6); - } - - pub fn process(&mut self, input: f32) -> f32 { - let in_driven = apply_subtype(input, self.subtype, self.drive); - - let s = (self.lpc * (self.lpc * (self.lpc * self.s1 + self.s2) + self.s3) + self.s4) - / (1.0 + self.g); - let gg = self.lpc * self.lpc * self.lpc * self.lpc; - - let y0 = (in_driven - self.r * s) / (1.0 + self.r * gg).max(1e-6); - - let v = (y0 - self.s1) * self.lpc; - let res = v + self.s1; - self.s1 = res + v; - self.s1 = (self.s1 * self.rcor).atan() * self.rcorinv; - let y1 = res; - - let y2 = Self::tptpc(&mut self.s2, y1, self.g); - let y3 = Self::tptpc(&mut self.s3, y2, self.g); - let y4 = Self::tptpc(&mut self.s4, y3, self.g); - - let mc = match self.subtype { - FilterSubtype::Clean => y4, - FilterSubtype::MildDrive => y3, - FilterSubtype::HeavyDrive => y2, - FilterSubtype::Asymmetric => y1, - FilterSubtype::SoftClip => y3 + y4, - _ => y4, - }; - - let out = mc * (1.0 + self.r * 0.45); - out * 0.6 - } -} - -#[derive(Debug, Clone)] -pub struct ObxdXpanderFilter { - sample_rate: f32, - pub cutoff_hz: f32, - pub resonance: f32, - pub drive: f32, - pub subtype: FilterSubtype, - s1: f32, - s2: f32, - s3: f32, - s4: f32, - g: f32, - lpc: f32, - r: f32, - rcor: f32, - rcorinv: f32, -} - -impl ObxdXpanderFilter { - pub fn new(sample_rate: f32) -> Self { - Self { - sample_rate, - cutoff_hz: 20000.0, - resonance: 0.7, - drive: 0.0, - subtype: FilterSubtype::XpanderLp4, - s1: 0.0, - s2: 0.0, - s3: 0.0, - s4: 0.0, - g: 0.0, - lpc: 0.0, - r: 0.0, - rcor: 0.0, - rcorinv: 0.0, - } - } - - pub fn set_sample_rate(&mut self, sample_rate: f32) { - self.sample_rate = sample_rate; - } - - pub fn reset(&mut self) { - self.s1 = 0.0; - self.s2 = 0.0; - self.s3 = 0.0; - self.s4 = 0.0; - } - - pub fn set_params(&mut self, cutoff: f32, resonance: f32) { - self.cutoff_hz = cutoff; - self.resonance = resonance; - } - - #[inline] - fn tptpc(state: &mut f32, inp: f32, g: f32) -> f32 { - let v = (inp - *state) * g / (1.0 + g); - let res = v + *state; - *state = res + v; - res - } - - pub fn prepare_block(&mut self, _cutoff: f32, _resonance: f32, _block_size: usize) { - let sr = self.sample_rate; - let sr_inv = 1.0 / sr; - let rcrate = (44000.0f32 * sr_inv).sqrt(); - self.g = (std::f32::consts::PI * self.cutoff_hz / sr) - .tan() - .clamp(0.0, 10.0); - self.lpc = self.g / (1.0 + self.g); - self.r = 3.5 * self.resonance; - self.rcor = (970.0 / 44000.0) * rcrate; - self.rcorinv = 1.0 / self.rcor.max(1e-6); - } - - pub fn process(&mut self, input: f32) -> f32 { - let in_driven = apply_subtype(input, self.subtype, self.drive); - - let s = (self.lpc * (self.lpc * (self.lpc * self.s1 + self.s2) + self.s3) + self.s4) - / (1.0 + self.g); - let gg = self.lpc * self.lpc * self.lpc * self.lpc; - - let y0 = (in_driven - self.r * s) / (1.0 + self.r * gg).max(1e-6); - - let v = (y0 - self.s1) * self.lpc; - let res = v + self.s1; - self.s1 = res + v; - self.s1 = (self.s1 * self.rcor).atan() * self.rcorinv; - let y1 = res; - - let y2 = Self::tptpc(&mut self.s2, y1, self.g); - let y3 = Self::tptpc(&mut self.s3, y2, self.g); - let y4 = Self::tptpc(&mut self.s4, y3, self.g); - - let mc = match self.subtype { - FilterSubtype::XpanderLp1 => y1, - FilterSubtype::XpanderLp2 => y2, - FilterSubtype::XpanderLp3 => y3, - FilterSubtype::XpanderLp4 => y4, - FilterSubtype::XpanderHp1 => y0 - y1, - FilterSubtype::XpanderHp2 => (y0 - y1) + (y2 - y1), - FilterSubtype::XpanderHp3 => { - let t1 = y0 - 3.0 * y1; - let t2 = 3.0 * y2 - y3; - t1 + t2 - } - FilterSubtype::XpanderBp2 => 2.0 * (y2 - y1), - FilterSubtype::XpanderBp4 => { - let t1 = y2 - y3; - let t2 = y4 - y3; - 2.0 * (t1 + t2) - } - FilterSubtype::XpanderN2 => { - let t1 = y2 - y1; - y0 + 2.0 * t1 - } - FilterSubtype::XpanderPh3 => { - let t1 = y0 - 3.0 * y1; - let t2 = 3.0 * y2 - 2.0 * y3; - t1 + 2.0 * t2 - } - FilterSubtype::XpanderHp2Lp1 => { - let t1 = y2 - y1; - let t2 = y2 - y3; - t1 + t2 - } - FilterSubtype::XpanderHp3Lp1 => { - let t1 = 3.0 * y2 - y1; - let t2 = y4 - 3.0 * y3; - t1 + t2 - } - FilterSubtype::XpanderN2Lp1 => { - let t1 = 2.0 * y2 - y1; - let t2 = 2.0 * y3; - t1 - t2 - } - FilterSubtype::XpanderPh3Lp1 => { - let t1 = 3.0 * y2 - y1; - let t2 = 2.0 * y4 - 3.0 * y3; - t1 + 2.0 * t2 - } - _ => y4, - }; - - let out = mc * (1.0 + self.r * 0.45); - out * 0.6 - } -} - #[derive(Debug, Clone)] pub struct Notch24Filter { sample_rate: f32, @@ -1994,17 +1226,11 @@ pub enum Filter { Comb(CombFilter), Allpass(AllpassFilter), Biquad(BiquadFilter), - Ladder(LadderFilter), - K35(K35Filter), DiodeLadder(DiodeLadderFilter), - Warp(WarpFilter), VintageLadder(VintageLadderFilter), CytomicSvf(CytomicSvfFilter), TriPole(TriPoleFilter), SampleHold(SampleHoldFilter), - Obxd2Pole(Obxd2PoleFilter), - Obxd4Pole(Obxd4PoleFilter), - ObxdXpander(ObxdXpanderFilter), Notch24(Notch24Filter), } @@ -2014,17 +1240,11 @@ enum FilterFamily { Comb, Allpass, Biquad, - Ladder, - K35, DiodeLadder, - Warp, VintageLadder, CytomicSvf, TriPole, SampleHold, - Obxd2Pole, - Obxd4Pole, - ObxdXpander, Notch24, } @@ -2046,20 +1266,8 @@ impl FilterFamily { | FilterType::HighShelf | FilterType::Bell | FilterType::Notch12dB => FilterFamily::Biquad, - FilterType::Ladder => FilterFamily::Ladder, FilterType::VintageLadder => FilterFamily::VintageLadder, - FilterType::K35Lp | FilterType::K35Hp => FilterFamily::K35, FilterType::DiodeLadder => FilterFamily::DiodeLadder, - FilterType::CutoffWarp - | FilterType::ResonanceWarp - | FilterType::CutoffWarpHp - | FilterType::CutoffWarpBp - | FilterType::CutoffWarpNotch - | FilterType::CutoffWarpAp - | FilterType::ResonanceWarpLp - | FilterType::ResonanceWarpHp - | FilterType::ResonanceWarpNotch - | FilterType::ResonanceWarpAp => FilterFamily::Warp, FilterType::CytomicLp | FilterType::CytomicHp | FilterType::CytomicBp @@ -2071,12 +1279,6 @@ impl FilterFamily { | FilterType::CytomicHs => FilterFamily::CytomicSvf, FilterType::TriPole => FilterFamily::TriPole, FilterType::SampleHold => FilterFamily::SampleHold, - FilterType::Obxd2PoleLp - | FilterType::Obxd2PoleHp - | FilterType::Obxd2PoleBp - | FilterType::Obxd2PoleNotch => FilterFamily::Obxd2Pole, - FilterType::Obxd4Pole => FilterFamily::Obxd4Pole, - FilterType::ObxdXpander => FilterFamily::ObxdXpander, FilterType::Notch24dB => FilterFamily::Notch24, } } @@ -2111,18 +1313,7 @@ impl Filter { f.filter_type = filter_type; Filter::Biquad(f) } - FilterFamily::Ladder => Filter::Ladder(LadderFilter::new(sample_rate)), - FilterFamily::K35 => { - let mut f = K35Filter::new(sample_rate); - f.filter_type = filter_type; - Filter::K35(f) - } FilterFamily::DiodeLadder => Filter::DiodeLadder(DiodeLadderFilter::new(sample_rate)), - FilterFamily::Warp => { - let mut f = WarpFilter::new(sample_rate); - f.filter_type = filter_type; - Filter::Warp(f) - } FilterFamily::VintageLadder => { Filter::VintageLadder(VintageLadderFilter::new(sample_rate)) } @@ -2133,13 +1324,6 @@ impl Filter { } FilterFamily::TriPole => Filter::TriPole(TriPoleFilter::new(sample_rate)), FilterFamily::SampleHold => Filter::SampleHold(SampleHoldFilter::new(sample_rate)), - FilterFamily::Obxd2Pole => { - let mut f = Obxd2PoleFilter::new(sample_rate); - f.filter_type = filter_type; - Filter::Obxd2Pole(f) - } - FilterFamily::Obxd4Pole => Filter::Obxd4Pole(Obxd4PoleFilter::new(sample_rate)), - FilterFamily::ObxdXpander => Filter::ObxdXpander(ObxdXpanderFilter::new(sample_rate)), FilterFamily::Notch24 => Filter::Notch24(Notch24Filter::new(sample_rate)), } } @@ -2163,8 +1347,6 @@ impl Filter { match self { Filter::Svf(f) => f.filter_type = filter_type, Filter::Comb(f) => f.filter_type = filter_type, - Filter::K35(f) => f.filter_type = filter_type, - Filter::Warp(f) => f.filter_type = filter_type, Filter::Biquad(f) => f.filter_type = filter_type, Filter::CytomicSvf(f) => f.filter_type = filter_type, _ => {} @@ -2178,17 +1360,11 @@ impl Filter { Filter::Comb(_) => FilterFamily::Comb, Filter::Allpass(_) => FilterFamily::Allpass, Filter::Biquad(_) => FilterFamily::Biquad, - Filter::Ladder(_) => FilterFamily::Ladder, - Filter::K35(_) => FilterFamily::K35, Filter::DiodeLadder(_) => FilterFamily::DiodeLadder, - Filter::Warp(_) => FilterFamily::Warp, Filter::VintageLadder(_) => FilterFamily::VintageLadder, Filter::CytomicSvf(_) => FilterFamily::CytomicSvf, Filter::TriPole(_) => FilterFamily::TriPole, Filter::SampleHold(_) => FilterFamily::SampleHold, - Filter::Obxd2Pole(_) => FilterFamily::Obxd2Pole, - Filter::Obxd4Pole(_) => FilterFamily::Obxd4Pole, - Filter::ObxdXpander(_) => FilterFamily::ObxdXpander, Filter::Notch24(_) => FilterFamily::Notch24, } } @@ -2199,17 +1375,11 @@ impl Filter { Filter::Comb(f) => f.sample_rate, Filter::Allpass(f) => f.sample_rate, Filter::Biquad(f) => f.sample_rate, - Filter::Ladder(f) => f.sample_rate, - Filter::K35(f) => f.sample_rate, Filter::DiodeLadder(f) => f.sample_rate, - Filter::Warp(f) => f.sample_rate, Filter::VintageLadder(f) => f.sample_rate, Filter::CytomicSvf(f) => f.sample_rate, Filter::TriPole(f) => f.sample_rate, Filter::SampleHold(f) => f.sample_rate, - Filter::Obxd2Pole(f) => f.sample_rate, - Filter::Obxd4Pole(f) => f.sample_rate, - Filter::ObxdXpander(f) => f.sample_rate, Filter::Notch24(f) => f.sample_rate, } } @@ -2248,22 +1418,6 @@ impl Filter { gain_db: f.gain_db, feedback_drive: 0.0, }, - Filter::Ladder(f) => FilterSnapshot { - cutoff_hz: f.cutoff_hz, - resonance: f.resonance, - drive: f.drive, - subtype: f.subtype, - gain_db: 0.0, - feedback_drive: f.feedback_drive, - }, - Filter::K35(f) => FilterSnapshot { - cutoff_hz: f.cutoff_hz, - resonance: f.resonance, - drive: f.drive, - subtype: f.subtype, - gain_db: 0.0, - feedback_drive: 0.0, - }, Filter::DiodeLadder(f) => FilterSnapshot { cutoff_hz: f.cutoff_hz, resonance: f.resonance, @@ -2272,14 +1426,6 @@ impl Filter { gain_db: 0.0, feedback_drive: f.feedback_drive, }, - Filter::Warp(f) => FilterSnapshot { - cutoff_hz: f.cutoff_hz, - resonance: f.resonance, - drive: f.drive, - subtype: f.subtype, - gain_db: 0.0, - feedback_drive: 0.0, - }, Filter::VintageLadder(f) => FilterSnapshot { cutoff_hz: f.cutoff_hz, resonance: f.resonance, @@ -2312,30 +1458,6 @@ impl Filter { gain_db: 0.0, feedback_drive: 0.0, }, - Filter::Obxd2Pole(f) => FilterSnapshot { - cutoff_hz: f.cutoff_hz, - resonance: f.resonance, - drive: f.drive, - subtype: f.subtype, - gain_db: 0.0, - feedback_drive: 0.0, - }, - Filter::Obxd4Pole(f) => FilterSnapshot { - cutoff_hz: f.cutoff_hz, - resonance: f.resonance, - drive: f.drive, - subtype: f.subtype, - gain_db: 0.0, - feedback_drive: 0.0, - }, - Filter::ObxdXpander(f) => FilterSnapshot { - cutoff_hz: f.cutoff_hz, - resonance: f.resonance, - drive: f.drive, - subtype: f.subtype, - gain_db: 0.0, - feedback_drive: 0.0, - }, Filter::Notch24(f) => FilterSnapshot { cutoff_hz: f.cutoff_hz, resonance: f.resonance, @@ -2353,18 +1475,12 @@ impl Filter { Filter::Comb(f) => f.set_params(cutoff, resonance), Filter::Allpass(f) => f.set_params(cutoff, resonance), Filter::Biquad(f) => f.set_params(cutoff, resonance), - Filter::Ladder(f) => f.set_params(cutoff, resonance), - Filter::K35(f) => f.set_params(cutoff, resonance), Filter::DiodeLadder(f) => f.set_params(cutoff, resonance), - Filter::Warp(f) => f.set_params(cutoff, resonance), Filter::VintageLadder(f) => f.set_params(cutoff, resonance), Filter::CytomicSvf(f) => f.set_params(cutoff, resonance), Filter::TriPole(f) => f.set_params(cutoff, resonance), Filter::SampleHold(f) => f.set_params(cutoff, 0.0), - Filter::Obxd2Pole(f) => f.set_params(cutoff, resonance), - Filter::Obxd4Pole(f) => f.set_params(cutoff, resonance), Filter::Notch24(f) => f.set_params(cutoff, resonance), - Filter::ObxdXpander(f) => f.set_params(cutoff, resonance), } } @@ -2377,17 +1493,11 @@ impl Filter { Filter::Comb(f) => f.set_sample_rate(sample_rate), Filter::Allpass(f) => f.set_sample_rate(sample_rate), Filter::Biquad(f) => f.set_sample_rate(sample_rate), - Filter::Ladder(f) => f.set_sample_rate(sample_rate), - Filter::K35(f) => f.set_sample_rate(sample_rate), Filter::DiodeLadder(f) => f.set_sample_rate(sample_rate), - Filter::Warp(f) => f.set_sample_rate(sample_rate), Filter::VintageLadder(f) => f.set_sample_rate(sample_rate), Filter::CytomicSvf(f) => f.set_sample_rate(sample_rate), Filter::TriPole(f) => f.set_sample_rate(sample_rate), Filter::SampleHold(f) => f.set_sample_rate(sample_rate), - Filter::Obxd2Pole(f) => f.set_sample_rate(sample_rate), - Filter::Obxd4Pole(f) => f.set_sample_rate(sample_rate), - Filter::ObxdXpander(f) => f.set_sample_rate(sample_rate), Filter::Notch24(_) => {} } } @@ -2398,18 +1508,12 @@ impl Filter { Filter::Comb(f) => f.prepare_block(cutoff, resonance, block_size), Filter::Allpass(f) => f.prepare_block(cutoff, resonance, block_size), Filter::Biquad(f) => f.prepare_block(cutoff, resonance, block_size), - Filter::Ladder(f) => f.prepare_block(cutoff, resonance, block_size), - Filter::K35(f) => f.prepare_block(cutoff, resonance, block_size), Filter::DiodeLadder(f) => f.prepare_block(cutoff, resonance, block_size), - Filter::Warp(f) => f.prepare_block(cutoff, resonance, block_size), Filter::VintageLadder(f) => f.prepare_block(cutoff, resonance, block_size), Filter::CytomicSvf(f) => f.prepare_block(cutoff, resonance, block_size), Filter::TriPole(f) => f.prepare_block(cutoff, resonance, block_size), Filter::SampleHold(f) => f.prepare_block(cutoff, 0.0, block_size), - Filter::Obxd2Pole(f) => f.prepare_block(cutoff, resonance, block_size), - Filter::Obxd4Pole(f) => f.prepare_block(cutoff, resonance, block_size), Filter::Notch24(f) => f.prepare_block(cutoff, resonance, block_size), - Filter::ObxdXpander(f) => f.prepare_block(cutoff, resonance, block_size), } } @@ -2419,36 +1523,26 @@ impl Filter { Filter::Comb(f) => f.gain_db = gain, Filter::Biquad(f) => f.gain_db = gain, Filter::CytomicSvf(f) => f.gain_db = gain, - Filter::Obxd2Pole(_f) => {} - Filter::Obxd4Pole(_f) => {} - Filter::ObxdXpander(_f) => {} _ => {} } } pub fn set_drive(&mut self, drive: f32) { match self { - Filter::Ladder(f) => f.drive = drive, - Filter::K35(f) => f.drive = drive, Filter::Svf(f) => f.drive = drive, Filter::DiodeLadder(f) => f.drive = drive, - Filter::Warp(f) => f.drive = drive, Filter::VintageLadder(f) => f.drive = drive, Filter::Biquad(f) => f.drive = drive, Filter::CytomicSvf(f) => f.drive = drive, Filter::TriPole(f) => f.drive = drive, Filter::Comb(f) => f.drive = drive, Filter::Allpass(f) => f.drive = drive, - Filter::Obxd2Pole(f) => f.drive = drive, - Filter::Obxd4Pole(f) => f.drive = drive, - Filter::ObxdXpander(f) => f.drive = drive, _ => {} } } pub fn set_feedback_drive(&mut self, feedback_drive: f32) { match self { - Filter::Ladder(f) => f.feedback_drive = feedback_drive, Filter::VintageLadder(f) => f.feedback_drive = feedback_drive, Filter::DiodeLadder(f) => f.feedback_drive = feedback_drive, _ => {} @@ -2461,17 +1555,11 @@ impl Filter { Filter::Comb(f) => f.subtype = subtype, Filter::Allpass(f) => f.subtype = subtype, Filter::Biquad(f) => f.subtype = subtype, - Filter::Ladder(f) => f.subtype = subtype, - Filter::K35(f) => f.subtype = subtype, Filter::DiodeLadder(f) => f.subtype = subtype, - Filter::Warp(f) => f.subtype = subtype, Filter::VintageLadder(f) => f.subtype = subtype, Filter::CytomicSvf(f) => f.subtype = subtype, Filter::TriPole(f) => f.subtype = subtype, - Filter::Obxd2Pole(f) => f.subtype = subtype, - Filter::Obxd4Pole(f) => f.subtype = subtype, Filter::Notch24(f) => f.subtype = subtype, - Filter::ObxdXpander(f) => f.subtype = subtype, Filter::SampleHold(_f) => {} } } @@ -2482,18 +1570,12 @@ impl Filter { Filter::Comb(f) => f.reset(), Filter::Allpass(f) => f.reset(), Filter::Biquad(f) => f.reset(), - Filter::Ladder(f) => f.reset(), - Filter::K35(f) => f.reset(), Filter::DiodeLadder(f) => f.reset(), - Filter::Warp(f) => f.reset(), Filter::VintageLadder(f) => f.reset(), Filter::CytomicSvf(f) => f.reset(), Filter::TriPole(f) => f.reset(), Filter::SampleHold(f) => f.reset(), - Filter::Obxd2Pole(f) => f.reset(), - Filter::Obxd4Pole(f) => f.reset(), Filter::Notch24(f) => f.reset(), - Filter::ObxdXpander(f) => f.reset(), } } @@ -2503,18 +1585,12 @@ impl Filter { Filter::Comb(f) => f.process(input), Filter::Allpass(f) => f.process(input), Filter::Biquad(f) => f.process(input), - Filter::Ladder(f) => f.process(input), - Filter::K35(f) => f.process(input), Filter::DiodeLadder(f) => f.process(input), - Filter::Warp(f) => f.process(input), Filter::VintageLadder(f) => f.process(input), Filter::CytomicSvf(f) => f.process(input), Filter::TriPole(f) => f.process(input), Filter::SampleHold(f) => f.process(input), - Filter::Obxd2Pole(f) => f.process(input), - Filter::Obxd4Pole(f) => f.process(input), Filter::Notch24(f) => f.process(input), - Filter::ObxdXpander(f) => f.process(input), } } } @@ -2571,21 +1647,5 @@ fn apply_subtype(input: f32, subtype: FilterSubtype, drive: f32) -> f32 { }; y / d.max(1.0) } - - FilterSubtype::XpanderLp1 - | FilterSubtype::XpanderLp2 - | FilterSubtype::XpanderLp3 - | FilterSubtype::XpanderLp4 - | FilterSubtype::XpanderHp1 - | FilterSubtype::XpanderHp2 - | FilterSubtype::XpanderHp3 - | FilterSubtype::XpanderBp2 - | FilterSubtype::XpanderBp4 - | FilterSubtype::XpanderN2 - | FilterSubtype::XpanderPh3 - | FilterSubtype::XpanderHp2Lp1 - | FilterSubtype::XpanderHp3Lp1 - | FilterSubtype::XpanderN2Lp1 - | FilterSubtype::XpanderPh3Lp1 => input, } } diff --git a/src/common/lfo_assignment.rs b/src/common/lfo_assignment.rs index f087517..11df4ce 100644 --- a/src/common/lfo_assignment.rs +++ b/src/common/lfo_assignment.rs @@ -94,4 +94,22 @@ where set_param_once(route.depth, self.default_depth); } } + + pub fn unassign( + &self, + params: &ParamStore

, + lfo_index: usize, + target: u8, + mut set_param_once: impl FnMut(P, f32), + ) { + let source = self.lfo_source_value(lfo_index); + for route in self.routes { + if params.get(route.source) as u8 == source + && params.get(route.target) as u8 == target + && params.get(route.depth).abs() > 0.001 + { + set_param_once(route.depth, 0.0); + } + } + } } diff --git a/src/common/oscillator.rs b/src/common/oscillator.rs index d89cdbd..a4e4011 100644 --- a/src/common/oscillator.rs +++ b/src/common/oscillator.rs @@ -67,7 +67,6 @@ pub enum OscType { Fm2 = 2, Wavetable = 3, Window = 4, - Modern = 5, ShNoise = 6, String = 7, Fm3 = 8, @@ -75,16 +74,16 @@ pub enum OscType { Twist = 10, AudioInput = 11, Sample = 12, + Off = 13, } impl OscType { pub fn from_u8(v: u8) -> Self { match v { - 0 | 1 => OscType::Classic, + 0 | 1 | 5 => OscType::Classic, 2 => OscType::Fm2, 3 => OscType::Wavetable, 4 => OscType::Window, - 5 => OscType::Modern, 6 => OscType::ShNoise, 7 => OscType::String, 8 => OscType::Fm3, @@ -92,6 +91,7 @@ impl OscType { 10 => OscType::Twist, 11 => OscType::AudioInput, 12 => OscType::Sample, + 13 => OscType::Off, _ => OscType::AudioInput, } } @@ -100,12 +100,12 @@ impl OscType { impl std::fmt::Display for OscType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + OscType::Off => write!(f, "Off"), OscType::Classic => write!(f, "Classic"), OscType::Sine => write!(f, "Sine"), OscType::Fm2 => write!(f, "FM2"), OscType::Wavetable => write!(f, "Wavetable"), OscType::Window => write!(f, "Window"), - OscType::Modern => write!(f, "Modern"), OscType::ShNoise => write!(f, "ShNoise"), OscType::String => write!(f, "String"), OscType::Fm3 => write!(f, "FM3"), @@ -1384,13 +1384,13 @@ mod tests { #[test] fn set_sample_rate_keeps_every_variant_finite() { for ty in [ + OscType::Off, OscType::Classic, OscType::Sine, OscType::Fm2, OscType::Fm3, OscType::Wavetable, OscType::Window, - OscType::Modern, OscType::ShNoise, OscType::String, OscType::Alias, @@ -1410,6 +1410,15 @@ mod tests { } } } + + #[test] + fn off_oscillator_is_silent() { + let mut osc = Oscillator::new(OscType::Off, 48_000.0); + assert_eq!(osc.osc_type(), OscType::Off); + for _ in 0..256 { + assert_eq!(osc.next(1.0, 1.0, 1.0), (0.0, 0.0)); + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -2254,79 +2263,6 @@ impl WindowOsc { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ModernSubWaveform { - Square = 0, - Triangle = 1, - Saw = 2, -} - -impl ModernSubWaveform { - pub fn from_u8(v: u8) -> Self { - match v { - 1 => ModernSubWaveform::Triangle, - 2 => ModernSubWaveform::Saw, - _ => ModernSubWaveform::Square, - } - } -} - -impl std::fmt::Display for ModernSubWaveform { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - ModernSubWaveform::Square => write!(f, "Square"), - ModernSubWaveform::Triangle => write!(f, "Triangle"), - ModernSubWaveform::Saw => write!(f, "Saw"), - } - } -} - -#[derive(Debug, Clone)] -pub struct ModernOsc { - sample_rate: f32, - freq_hz: f32, - detune: f32, - width: f32, - sub_mix: f32, - sub_octave: i8, - sub_waveform: ModernSubWaveform, - sub_one: bool, - phases: [f32; 8], - /// DPW (differentiated parabolic waveform) history: the previous two - /// parabolic-wave samples per voice. Kept in f64 — the second difference - /// cancels down to ~dt², which f32 cannot represent at low pitch. - dpw_state: [[f64; 2]; 8], -} - -/// Surge-style Modern detune ladder: voice 0 (and the sub) at base pitch, -/// voices 1..=3 sharpened by fractions of the detune range, voices 4..=6 -/// flattened symmetrically. `detune` is 0..=1 (×50 cents). -#[inline] -fn modern_detune_ladder(detune: f32) -> [f32; 8] { - let detune_cents = detune * 50.0; - [ - 0.0, - detune_cents * 0.25, - detune_cents * 0.5, - detune_cents * 0.75, - -detune_cents * 0.25, - -detune_cents * 0.5, - -detune_cents * 0.75, - 0.0, - ] -} - -/// Periodic double integral of the unit sawtooth `2t - 1`: its second -/// derivative is exactly the sawtooth, so a discrete second difference of -/// sampled `dpw_parabola` values (scaled by `1/dt²`) yields a band-limited -/// saw (DPW). The parabola is chosen so both value and slope are continuous -/// across the phase wrap. -#[inline] -fn dpw_parabola(phase: f32) -> f64 { - let p = (phase as f64).rem_euclid(1.0); - p * p * p / 3.0 - p * p / 2.0 + p / 6.0 -} - /// Amplitude compensation for the discrete second-difference operator /// `x[n] - 2x[n-1] + x[n-2]`, whose frequency response is /// `4 sin²(ω/2)` instead of the continuous `ω²`. `dt` is the phase @@ -2343,159 +2279,6 @@ pub(crate) fn dpw_droop_compensation(dt: f32) -> f32 { } } -impl ModernOsc { - pub fn new(sample_rate: f32) -> Self { - let mut osc = Self { - sample_rate, - freq_hz: 440.0, - detune: 0.2, - width: 0.0, - sub_mix: 0.0, - sub_octave: -1, - sub_waveform: ModernSubWaveform::Square, - sub_one: false, - phases: [0.0; 8], - dpw_state: [[0.0; 2]; 8], - }; - osc.rebuild_dpw_history(); - osc - } - - pub fn set_freq_hz(&mut self, freq: f32) { - self.freq_hz = freq.max(0.1); - // The DPW history is indexed by phase; a frequency change alters the - // phase stride, so re-derive the history to avoid a one-sample spike - // (e.g. under portamento). - self.rebuild_dpw_history(); - } - - pub fn set_detune(&mut self, detune: f32) { - self.detune = detune.clamp(0.0, 1.0); - } - - pub fn set_width(&mut self, width: f32) { - self.width = width.clamp(-1.0, 1.0); - } - - pub fn set_sub_mix(&mut self, sub_mix: f32) { - self.sub_mix = sub_mix.clamp(0.0, 1.0); - } - - pub fn set_sub_octave(&mut self, oct: i8) { - self.sub_octave = match oct { - 1 => -2, - _ => -1, - }; - } - - pub fn set_sub_waveform(&mut self, wf: ModernSubWaveform) { - self.sub_waveform = wf; - } - - pub fn set_sub_one(&mut self, v: bool) { - self.sub_one = v; - } - - pub fn reset(&mut self) { - for p in &mut self.phases { - *p = rand::random(); - } - self.rebuild_dpw_history(); - } - - pub fn reset_to_zero(&mut self) { - self.phases.fill(0.0); - self.rebuild_dpw_history(); - } - - /// Re-derive the two-sample DPW history for each voice from its current - /// phase and per-voice stride, so the next rendered sample continues the - /// parabola exactly (no click on note-on / pitch change). - fn rebuild_dpw_history(&mut self) { - let base_inc = self.freq_hz / self.sample_rate; - let detunes = modern_detune_ladder(self.detune); - for (i, &det) in detunes.iter().enumerate() { - let dt = base_inc * 2.0f32.powf(det / 1200.0); - let phase = self.phases[i]; - self.dpw_state[i][0] = dpw_parabola(phase - dt); - self.dpw_state[i][1] = dpw_parabola(phase - 2.0 * dt); - } - } - - pub fn generate(&mut self) -> (f32, f32) { - let base_inc = self.freq_hz / self.sample_rate; - let mut sum_l = 0.0f32; - let mut sum_r = 0.0f32; - - let detunes = modern_detune_ladder(self.detune); - - for (i, detune) in detunes.iter().enumerate().take(7) { - let dt = base_inc * 2.0f32.powf(*detune / 1200.0); - let phase = self.phases[i]; - - // DPW saw: the discrete second difference of the double - // integral `dpw_parabola`, scaled by 1/dt² and compensated for - // the second-difference droop. Per-voice `dt` keeps it exact for - // each voice's instantaneous frequency. - let p = dpw_parabola(phase); - let d = p - 2.0 * self.dpw_state[i][0] + self.dpw_state[i][1]; - self.dpw_state[i][1] = self.dpw_state[i][0]; - self.dpw_state[i][0] = p; - let dt64 = dt as f64; - let mut out = (d / (dt64 * dt64)) as f32; - out *= dpw_droop_compensation(dt); - out = soft_clip(out); - - self.phases[i] += dt; - while self.phases[i] >= 1.0 { - self.phases[i] -= 1.0; - } - - let pan = if i == 0 { - 0.5 - } else { - let spread = self.width.abs(); - let side = if i <= 3 { 1.0 } else { -1.0 }; - 0.5 + side * spread * 0.5 - }; - sum_l += out * (1.0 - pan); - sum_r += out * pan; - } - - if self.sub_mix > 0.0 { - let sub_ratio = 2.0f32.powi(self.sub_octave as i32); - let extra_div = if self.sub_one { 2.0 } else { 1.0 }; - let sub_inc = base_inc * sub_ratio / extra_div; - let sub_phase = self.phases[7]; - let sub_out = match self.sub_waveform { - ModernSubWaveform::Square => { - if sub_phase < 0.5 { - 1.0 - } else { - -1.0 - } - } - ModernSubWaveform::Triangle => 1.0 - 4.0 * (sub_phase - 0.5).abs(), - ModernSubWaveform::Saw => { - let mut v = 2.0 * sub_phase - 1.0; - v -= poly_blep(sub_phase, sub_inc); - v - } - }; - self.phases[7] += sub_inc; - while self.phases[7] >= 1.0 { - self.phases[7] -= 1.0; - } - sum_l += sub_out * self.sub_mix; - sum_r += sub_out * self.sub_mix; - } - - let total_voices = 7.0 + self.sub_mix; - let atten = 1.0 / total_voices.sqrt(); - (sum_l * atten, sum_r * atten) - } -} - #[derive(Debug, Clone)] pub struct ShNoiseOsc { sample_rate: f32, @@ -3775,13 +3558,13 @@ impl SampleOsc { #[derive(Debug, Clone)] pub enum Oscillator { + Off, Classic(ClassicOsc), Sine(SineOsc), Fm2(Fm2Osc), Fm3(Fm3Osc), Wavetable(WavetableOsc), Window(WindowOsc), - Modern(ModernOsc), ShNoise(ShNoiseOsc), String(Box), Alias(Box), @@ -3793,13 +3576,13 @@ pub enum Oscillator { impl Oscillator { pub fn new(osc_type: OscType, sample_rate: f32) -> Self { match osc_type { + OscType::Off => Oscillator::Off, OscType::Classic => Oscillator::Classic(ClassicOsc::new(sample_rate)), OscType::Sine => Oscillator::Sine(SineOsc::new(sample_rate)), OscType::Fm2 => Oscillator::Fm2(Fm2Osc::new(sample_rate)), OscType::Fm3 => Oscillator::Fm3(Fm3Osc::new(sample_rate)), OscType::Wavetable => Oscillator::Wavetable(WavetableOsc::new(sample_rate)), OscType::Window => Oscillator::Window(WindowOsc::new(sample_rate)), - OscType::Modern => Oscillator::Modern(ModernOsc::new(sample_rate)), OscType::ShNoise => Oscillator::ShNoise(ShNoiseOsc::new(sample_rate)), OscType::String => Oscillator::String(Box::new(StringOsc::new(sample_rate))), OscType::Alias => Oscillator::Alias(Box::new(AliasOsc::new(sample_rate))), @@ -3811,13 +3594,13 @@ impl Oscillator { pub fn osc_type(&self) -> OscType { match self { + Oscillator::Off => OscType::Off, Oscillator::Classic(_) => OscType::Classic, Oscillator::Sine(_) => OscType::Sine, Oscillator::Fm2(_) => OscType::Fm2, Oscillator::Fm3(_) => OscType::Fm3, Oscillator::Wavetable(_) => OscType::Wavetable, Oscillator::Window(_) => OscType::Window, - Oscillator::Modern(_) => OscType::Modern, Oscillator::ShNoise(_) => OscType::ShNoise, Oscillator::String(_) => OscType::String, Oscillator::Alias(_) => OscType::Alias, @@ -3829,13 +3612,13 @@ impl Oscillator { pub fn set_freq_hz(&mut self, freq: f32) { match self { + Oscillator::Off => {} Oscillator::Classic(o) => o.set_freq_hz(freq), Oscillator::Sine(o) => o.set_freq_hz(freq), Oscillator::Fm2(o) => o.set_freq_hz(freq), Oscillator::Fm3(o) => o.set_freq_hz(freq), Oscillator::Wavetable(o) => o.set_freq_hz(freq), Oscillator::Window(o) => o.set_freq_hz(freq), - Oscillator::Modern(o) => o.set_freq_hz(freq), Oscillator::ShNoise(o) => o.set_freq_hz(freq), Oscillator::String(o) => o.set_freq_hz(freq), Oscillator::Alias(o) => o.set_freq_hz(freq), @@ -3870,7 +3653,6 @@ impl Oscillator { o.lowcut_r.set_sample_rate(sr); o.highcut_r.set_sample_rate(sr); } - Oscillator::Modern(o) => o.sample_rate = sr, Oscillator::ShNoise(o) => { o.sample_rate = sr; o.lowcut.set_sample_rate(sr); @@ -3898,19 +3680,19 @@ impl Oscillator { Oscillator::Alias(o) => o.sample_rate = sr, Oscillator::Twist(o) => o.set_sample_rate(sr), Oscillator::AudioInput(o) => o.sample_rate = sr, - Oscillator::Sample(_) => {} + Oscillator::Off | Oscillator::Sample(_) => {} } } pub fn reset(&mut self) { match self { + Oscillator::Off => {} Oscillator::Classic(o) => o.reset(), Oscillator::Sine(o) => o.reset(), Oscillator::Fm2(o) => o.reset(), Oscillator::Fm3(o) => o.reset(), Oscillator::Wavetable(o) => o.reset(), Oscillator::Window(o) => o.reset(), - Oscillator::Modern(o) => o.reset(), Oscillator::ShNoise(o) => o.reset(), Oscillator::String(o) => o.reset(), Oscillator::Alias(o) => o.reset(), @@ -3922,13 +3704,13 @@ impl Oscillator { pub fn reset_to_zero(&mut self) { match self { + Oscillator::Off => {} Oscillator::Classic(o) => o.reset_to_zero(), Oscillator::Sine(o) => o.reset_to_zero(), Oscillator::Fm2(o) => o.reset_to_zero(), Oscillator::Fm3(o) => o.reset_to_zero(), Oscillator::Wavetable(o) => o.reset_to_zero(), Oscillator::Window(o) => o.reset_to_zero(), - Oscillator::Modern(o) => o.reset_to_zero(), Oscillator::ShNoise(o) => o.reset_to_zero(), Oscillator::String(o) => o.reset_to_zero(), Oscillator::Alias(o) => o.reset_to_zero(), @@ -3940,13 +3722,13 @@ impl Oscillator { pub fn next(&mut self, fm_input: f32, audio_in_l: f32, audio_in_r: f32) -> (f32, f32) { match self { + Oscillator::Off => (0.0, 0.0), Oscillator::Classic(o) => o.next(fm_input), Oscillator::Sine(o) => o.next(fm_input), Oscillator::Fm2(o) => o.generate(), Oscillator::Fm3(o) => o.generate(), Oscillator::Wavetable(o) => o.next(fm_input), Oscillator::Window(o) => o.next(fm_input), - Oscillator::Modern(o) => o.generate(), Oscillator::ShNoise(o) => o.generate(), Oscillator::String(o) => o.generate(), Oscillator::Alias(o) => o.generate(), @@ -3979,8 +3761,7 @@ impl Oscillator { Oscillator::ShNoise(o) => o.set_unison(voices, detune), Oscillator::Alias(o) => o.set_unison(voices, detune), Oscillator::Twist(o) => o.set_unison(voices, detune), - Oscillator::Modern(_o) => {} - Oscillator::String(_o) => {} + Oscillator::Off | Oscillator::String(_) => {} Oscillator::AudioInput(_o) => {} Oscillator::Sample(_o) => {} } @@ -3997,8 +3778,7 @@ impl Oscillator { Oscillator::ShNoise(o) => o.set_unison_spread(spread), Oscillator::Alias(o) => o.set_unison_spread(spread), Oscillator::Twist(o) => o.set_unison_spread(spread), - Oscillator::Modern(_o) => {} - Oscillator::String(_o) => {} + Oscillator::Off | Oscillator::String(_) => {} Oscillator::AudioInput(_o) => {} Oscillator::Sample(_o) => {} } @@ -4012,13 +3792,12 @@ impl Oscillator { Oscillator::Fm3(o) => o.set_algorithm((shape * 3.0) as u8), Oscillator::Wavetable(o) => o.set_shape(shape), Oscillator::Window(o) => o.set_shape(shape), - Oscillator::Modern(o) => o.set_detune(shape), Oscillator::String(o) => o.set_damping(shape), Oscillator::Alias(o) => o.set_quant_bits(shape * 15.0 + 1.0), Oscillator::Twist(o) => o.set_model(crate::common::twist::TwistModel::from_u8( ((shape.clamp(0.0, 1.0) * 16.0) as u8).min(15), )), - Oscillator::ShNoise(_o) => {} + Oscillator::Off | Oscillator::ShNoise(_) => {} Oscillator::AudioInput(o) => o.set_gain(shape * 4.0), Oscillator::Sample(_o) => {} } @@ -4030,7 +3809,6 @@ impl Oscillator { Oscillator::Fm2(o) => o.set_depth(skew.clamp(0.0, 1.0)), Oscillator::Fm3(o) => o.set_ratio2((skew + 1.0) * 2.0 + 0.25), Oscillator::Wavetable(o) => o.set_skew(skew), - Oscillator::Modern(o) => o.set_width(skew), Oscillator::String(o) => o.set_pickup_pos(skew), Oscillator::Alias(o) => o.set_decim_factor(skew * 63.0 + 1.0), Oscillator::Sine(o) => o.set_feedback(skew.clamp(0.0, 1.0)), @@ -4050,7 +3828,6 @@ impl Oscillator { pub fn set_formant(&mut self, formant: f32) { match self { Oscillator::Window(o) => o.set_formant(formant), - Oscillator::Modern(o) => o.set_sub_mix((formant - 0.25) / 3.75), Oscillator::Fm3(o) => o.set_ratio3(formant * 4.0 + 0.25), Oscillator::Alias(o) => o.set_dirty(formant), Oscillator::Wavetable(o) => o.set_formant(formant), @@ -4082,18 +3859,6 @@ impl Oscillator { } } - pub fn set_sub_waveform(&mut self, wf: ModernSubWaveform) { - if let Oscillator::Modern(o) = self { - o.set_sub_waveform(wf) - } - } - - pub fn set_sub_one(&mut self, v: bool) { - if let Oscillator::Modern(o) = self { - o.set_sub_one(v) - } - } - pub fn set_partial_amplitude(&mut self, index: usize, amplitude: f32) { if let Oscillator::Alias(o) = self { o.set_partial_amplitude(index, amplitude) diff --git a/src/common/settings.rs b/src/common/settings.rs index b2cdbcd..5874fe6 100644 --- a/src/common/settings.rs +++ b/src/common/settings.rs @@ -2,7 +2,6 @@ use crate::common::{ envelope::{AttackShape, DecayReleaseShape, EnvelopeMode, EnvelopeRetriggerMode}, filter::{FilterSubtype, FilterType}, lfo::{LfoShape, LfoSyncDivision, LfoSyncMode, LfoTriggerMode}, - waveshaper::Waveshape, }; #[derive(Debug, Clone, PartialEq)] @@ -117,22 +116,3 @@ impl Default for LfoSettings { } } } - -#[derive(Debug, Clone, PartialEq)] -pub struct WaveshaperSettings { - pub shape: Waveshape, - pub drive: f32, - pub mix: f32, - pub enabled: bool, -} - -impl Default for WaveshaperSettings { - fn default() -> Self { - Self { - shape: Waveshape::Off, - drive: 0.0, - mix: 1.0, - enabled: false, - } - } -} diff --git a/src/common/state.rs b/src/common/state.rs index 5a006b3..f4ea9bb 100644 --- a/src/common/state.rs +++ b/src/common/state.rs @@ -215,8 +215,9 @@ impl PluginState { pub fn from_runtime(store: &ParamStore

) -> Self { let params = (0..P::COUNT) - .filter_map(|i| P::from_raw(i as u32)) - .map(|id| store.get(id)) + // State values are indexed by raw ID; retain retired slots so later + // parameters keep their IDs when apply() restores the array. + .map(|i| P::from_raw(i as u32).map_or(0.0, |id| store.get(id))) .collect(); Self { version: Self::CURRENT_VERSION, diff --git a/src/common/twist.rs b/src/common/twist.rs index 6dca7ab..f3d6c53 100644 --- a/src/common/twist.rs +++ b/src/common/twist.rs @@ -9,7 +9,6 @@ pub enum TwistModel { Wavefolder = 1, Fm = 2, Harmonic = 3, - String = 4, Noise = 5, Chords = 6, FilteredNoise = 7, @@ -29,7 +28,6 @@ impl TwistModel { 1 => TwistModel::Wavefolder, 2 => TwistModel::Fm, 3 => TwistModel::Harmonic, - 4 => TwistModel::String, 5 => TwistModel::Noise, 6 => TwistModel::Chords, 7 => TwistModel::FilteredNoise, @@ -73,11 +71,6 @@ pub struct TwistOsc { har_phases: [f32; 16], - string_buffer: Vec, - string_pos: usize, - string_exciter: f32, - string_filter: f32, - noise_filter_l: f32, noise_filter_r: f32, noise_filter_bp: f32, @@ -146,10 +139,6 @@ impl TwistOsc { fm_fb_buf: 0.0, wf_tri_state: [0.0; 2], har_phases: [0.0; 16], - string_buffer: vec![0.0; 2048], - string_pos: 0, - string_exciter: 0.0, - string_filter: 0.0, noise_filter_l: 0.0, noise_filter_r: 0.0, noise_filter_bp: 0.0, @@ -198,8 +187,6 @@ impl TwistOsc { self.fm_mod_phase = 0.0; self.fm_fb_buf = 0.0; self.har_phases = [0.0; 16]; - self.string_pos = 0; - self.string_buffer.fill(0.0); self.noise_filter_l = 0.0; self.noise_filter_r = 0.0; self.noise_filter_bp = 0.0; @@ -286,7 +273,6 @@ impl TwistOsc { TwistModel::Wavefolder => self.next_wavefolder(fm_input), TwistModel::Fm => self.next_fm(fm_input), TwistModel::Harmonic => self.next_harmonic(fm_input), - TwistModel::String => self.next_string(fm_input), TwistModel::Noise => self.next_noise(), TwistModel::Chords => self.next_chords(), TwistModel::FilteredNoise => self.next_filtered_noise(), @@ -489,42 +475,6 @@ impl TwistOsc { (out * norm, out * norm) } - fn next_string(&mut self, fm_input: f32) -> (f32, f32) { - let delay_len = (self.sample_rate / self.freq_hz).clamp(2.0, 2046.0) as usize; - let decay = 0.9 + self.timbre * 0.099; - let brightness = self.harmonics; - let pluck_pos = self.morph; - - let lp_coef = brightness * 0.9; - - if fm_input.abs() > 0.5 && self.string_exciter <= 0.0 { - self.string_exciter = 1.0; - } - - let excite = if self.string_exciter > 0.0 { - let noise = fast_rand() * 2.0 - 1.0; - let pos = (pluck_pos * delay_len as f32) as usize; - if self.string_pos == pos || self.string_pos == 0 { - self.string_exciter -= 0.01; - } - noise * self.string_exciter - } else { - 0.0 - }; - - let read_pos = (self.string_pos + delay_len) % self.string_buffer.len(); - let sample = self.string_buffer[read_pos]; - - self.string_filter = self.string_filter + lp_coef * (sample - self.string_filter); - - let next = (self.string_filter + sample) * 0.5 * decay + excite; - - self.string_buffer[self.string_pos] = next; - self.string_pos = (self.string_pos + 1) % self.string_buffer.len(); - - (sample, sample) - } - fn next_noise(&mut self) -> (f32, f32) { let filter_type = self.harmonics; let cutoff = 20.0 + self.timbre.powf(2.0) * 19980.0; diff --git a/src/sampler/gui.rs b/src/sampler/gui.rs index 13029de..daa6e12 100644 --- a/src/sampler/gui.rs +++ b/src/sampler/gui.rs @@ -2770,11 +2770,14 @@ fn adsr_panel<'a>(state: &'a State, ids: [ParamId; 4]) -> Element<'a, Message> { ids.map(|id| param_has_lfo_assignment(state, id)), ) .map(move |message| { - let index = match message { + let index = match &message { AdsrMessage::Change(i, _) | AdsrMessage::Release(i) | AdsrMessage::Reset(i) - | AdsrMessage::Assign(i) => i, + | AdsrMessage::Assign(i) + | AdsrMessage::Edit(i) + | AdsrMessage::EditChanged(i, _) + | AdsrMessage::EditSubmit(i) => *i, }; let id = ids[index]; match message { @@ -2782,6 +2785,9 @@ fn adsr_panel<'a>(state: &'a State, ids: [ParamId; 4]) -> Element<'a, Message> { AdsrMessage::Release(_) => Message::ReleaseParam(id), AdsrMessage::Reset(_) => Message::ResetParam(id), AdsrMessage::Assign(_) => Message::AssignLfoToParam(id), + AdsrMessage::Edit(_) | AdsrMessage::EditChanged(_, _) | AdsrMessage::EditSubmit(_) => { + Message::None + } } }) } @@ -3957,7 +3963,12 @@ fn group_eg_widget<'a>(params: Option, eg: usize) -> Element<'a, Mes }; Message::SetSelectedGroupParam(field, value) } - AdsrMessage::Release(_) | AdsrMessage::Reset(_) | AdsrMessage::Assign(_) => Message::None, + AdsrMessage::Release(_) + | AdsrMessage::Reset(_) + | AdsrMessage::Assign(_) + | AdsrMessage::Edit(_) + | AdsrMessage::EditChanged(_, _) + | AdsrMessage::EditSubmit(_) => Message::None, }) } diff --git a/src/synth/dsp/engine.rs b/src/synth/dsp/engine.rs index 1ec8f63..dd3d78d 100644 --- a/src/synth/dsp/engine.rs +++ b/src/synth/dsp/engine.rs @@ -245,12 +245,6 @@ impl SynthEngine { } } - pub fn update_pitch_eg_params(&mut self) { - for voice in &mut self.voices { - voice.update_pitch_eg_params(&self.params); - } - } - pub fn update_lfo_params(&mut self, idx: usize) { for voice in &mut self.voices { voice.update_lfo_params(&self.params, idx); @@ -284,12 +278,6 @@ impl SynthEngine { } } - pub fn update_waveshaper_params(&mut self) { - for voice in &mut self.voices { - voice.update_waveshaper_params(&self.params); - } - } - pub fn update_flavor_params(&mut self) { for voice in &mut self.voices { voice.update_flavor_params(&self.params); diff --git a/src/synth/dsp/mod.rs b/src/synth/dsp/mod.rs index 7e7ae22..46542ee 100644 --- a/src/synth/dsp/mod.rs +++ b/src/synth/dsp/mod.rs @@ -14,17 +14,14 @@ pub use crate::common::lfo::{ }; pub use crate::common::mts_esp::MtsEspClient; pub use crate::common::noise::{NoiseColorMode, NoiseGenerator, NoiseType}; -pub use crate::common::settings::{ - EnvelopeSettings, FilterSettings, LfoSettings, WaveshaperSettings, -}; +pub use crate::common::settings::{EnvelopeSettings, FilterSettings, LfoSettings}; pub use crate::common::tuning::Tuning; pub use crate::common::voice::{PlayMode, PortamentoCurve, StealMode, VoicePriority}; -pub use crate::common::waveshaper::{Waveshape, Waveshaper}; pub use engine::{SynthEngine, soft_clip_master}; pub use oscillator::{ AliasWaveform, ClassicOsc, ClassicWaveform, ExciterType, Fm2FeedbackMode, Fm3FeedbackMode, - ModernSubWaveform, OscType, Oscillator, SineShaperMode, WindowType, + OscType, Oscillator, SineShaperMode, WindowType, }; pub use twist::{TwistModel, TwistOsc}; pub use voice::{ diff --git a/src/synth/dsp/voice.rs b/src/synth/dsp/voice.rs index 0f9cbc1..fb4055b 100644 --- a/src/synth/dsp/voice.rs +++ b/src/synth/dsp/voice.rs @@ -5,9 +5,9 @@ use rand::random; use super::{ AdsrEnvelope, AliasWaveform, ClassicOsc, ClassicWaveform, EnvelopeSettings, ExciterType, Filter, FilterSettings, FilterType, FlavorFilter, Fm2FeedbackMode, Lfo, LfoSettings, LfoShape, - MSEG_MAX_NODES, MSEG_MAX_SEGMENTS, ModernSubWaveform, MsegCurve, MsegLoopMode, MtsEspClient, - NoiseColorMode, NoiseGenerator, NoiseType, OscType, Oscillator, PlayMode, PortamentoCurve, - SineShaperMode, Tuning, VoicePriority, Waveshape, Waveshaper, WaveshaperSettings, WindowType, + MSEG_MAX_NODES, MSEG_MAX_SEGMENTS, MsegCurve, MsegLoopMode, MtsEspClient, NoiseColorMode, + NoiseGenerator, NoiseType, OscType, Oscillator, PlayMode, PortamentoCurve, SineShaperMode, + Tuning, VoicePriority, WindowType, }; use parking_lot::Mutex; use std::sync::Arc; @@ -153,6 +153,8 @@ impl Default for OscSettings { pub struct NoiseSettings { pub noise_type: NoiseType, pub level: f32, + pub unison_voices: u8, + pub unison_spread: f32, pub filter_type: FilterType, pub filter_cutoff: f32, pub filter_resonance: f32, @@ -171,6 +173,8 @@ impl Default for NoiseSettings { Self { noise_type: NoiseType::White, level: 0.0, + unison_voices: 1, + unison_spread: 0.0, filter_type: FilterType::Lowpass, filter_cutoff: 8000.0, filter_resonance: 0.7, @@ -226,6 +230,12 @@ impl FilterRouting { } } +impl std::fmt::Display for FilterRouting { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.name()) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OscFmMode { Off = 0, @@ -407,7 +417,6 @@ pub enum ModSource { Lfo6 = 10, AmpEg = 11, FilterEg = 12, - PitchEg = 13, RandomBipolar = 14, RandomUnipolar = 15, AlternateBipolar = 16, @@ -449,7 +458,6 @@ impl ModSource { 10 => Some(ModSource::Lfo6), 11 => Some(ModSource::AmpEg), 12 => Some(ModSource::FilterEg), - 13 => Some(ModSource::PitchEg), 14 => Some(ModSource::RandomBipolar), 15 => Some(ModSource::RandomUnipolar), 16 => Some(ModSource::AlternateBipolar), @@ -513,10 +521,6 @@ pub enum ModTarget { FilterDecay = 28, FilterSustain = 29, FilterRelease = 30, - PitchAttack = 31, - PitchDecay = 32, - PitchSustain = 33, - PitchRelease = 34, Lfo1Rate = 35, Lfo1Amount = 36, Lfo1Deform = 37, @@ -539,7 +543,6 @@ pub enum ModTarget { OutputPan = 54, OutputWidth = 55, NoiseLevel = 56, - WaveshaperDrive = 57, Portamento = 58, FlavorCutoff = 59, FilterBalance = 60, @@ -565,6 +568,18 @@ pub enum ModTarget { ModRoute10Depth = 80, ModRoute11Depth = 81, ModRoute12Depth = 82, + Osc1EgAttack = 83, + Osc1EgDecay = 84, + Osc1EgSustain = 85, + Osc1EgRelease = 86, + Osc2EgAttack = 87, + Osc2EgDecay = 88, + Osc2EgSustain = 89, + Osc2EgRelease = 90, + Osc3EgAttack = 91, + Osc3EgDecay = 92, + Osc3EgSustain = 93, + Osc3EgRelease = 94, } impl ModTarget { @@ -601,10 +616,6 @@ impl ModTarget { 28 => Some(ModTarget::FilterDecay), 29 => Some(ModTarget::FilterSustain), 30 => Some(ModTarget::FilterRelease), - 31 => Some(ModTarget::PitchAttack), - 32 => Some(ModTarget::PitchDecay), - 33 => Some(ModTarget::PitchSustain), - 34 => Some(ModTarget::PitchRelease), 35 => Some(ModTarget::Lfo1Rate), 36 => Some(ModTarget::Lfo1Amount), 37 => Some(ModTarget::Lfo1Deform), @@ -627,7 +638,6 @@ impl ModTarget { 54 => Some(ModTarget::OutputPan), 55 => Some(ModTarget::OutputWidth), 56 => Some(ModTarget::NoiseLevel), - 57 => Some(ModTarget::WaveshaperDrive), 58 => Some(ModTarget::Portamento), 59 => Some(ModTarget::FlavorCutoff), 60 => Some(ModTarget::FilterBalance), @@ -653,11 +663,24 @@ impl ModTarget { 80 => Some(ModTarget::ModRoute10Depth), 81 => Some(ModTarget::ModRoute11Depth), 82 => Some(ModTarget::ModRoute12Depth), + 83 => Some(ModTarget::Osc1EgAttack), + 84 => Some(ModTarget::Osc1EgDecay), + 85 => Some(ModTarget::Osc1EgSustain), + 86 => Some(ModTarget::Osc1EgRelease), + 87 => Some(ModTarget::Osc2EgAttack), + 88 => Some(ModTarget::Osc2EgDecay), + 89 => Some(ModTarget::Osc2EgSustain), + 90 => Some(ModTarget::Osc2EgRelease), + 91 => Some(ModTarget::Osc3EgAttack), + 92 => Some(ModTarget::Osc3EgDecay), + 93 => Some(ModTarget::Osc3EgSustain), + 94 => Some(ModTarget::Osc3EgRelease), + _ => None, } } - pub const COUNT: u8 = 83; + pub const COUNT: u8 = 95; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -799,6 +822,7 @@ pub struct ModValues { f2_resonance: f32, f2_eg_amount: f32, f2_drive: f32, + osc_eg: [[f32; 4]; 3], amp_attack: f32, amp_decay: f32, amp_sustain: f32, @@ -807,10 +831,6 @@ pub struct ModValues { filter_decay: f32, filter_sustain: f32, filter_release: f32, - pitch_attack: f32, - pitch_decay: f32, - pitch_sustain: f32, - pitch_release: f32, lfo1_rate: f32, lfo1_amount: f32, lfo1_deform: f32, @@ -839,7 +859,6 @@ pub struct ModValues { output_pan: f32, output_width: f32, noise_level: f32, - waveshaper_drive: f32, portamento: f32, flavor_cutoff: f32, filter_balance: f32, @@ -853,7 +872,6 @@ pub struct ModValues { #[derive(Debug, Clone, Copy)] struct VoiceFilterContext { balance: f32, - ws_active: bool, f1_enabled: bool, f2_enabled: bool, per_source_routing: bool, @@ -867,7 +885,6 @@ struct VoiceFilterSampleParams { f2_cutoff: f32, f2_res: f32, f2_drive: f32, - ws_drive: f32, } #[derive(Debug, Clone)] @@ -878,8 +895,9 @@ pub struct VoiceParams { pub filter_routing: FilterRouting, pub filter_balance: f32, pub amp_eg: EnvelopeSettings, + /// None retains the legacy shared envelope for DSP callers. + pub osc_egs: Option<[EnvelopeSettings; 3]>, pub filter_eg: EnvelopeSettings, - pub pitch_eg: EnvelopeSettings, pub lfo1: LfoSettings, pub lfo2: LfoSettings, pub lfo3: LfoSettings, @@ -893,7 +911,6 @@ pub struct VoiceParams { pub scene_lfo5: LfoSettings, pub scene_lfo6: LfoSettings, pub noise: NoiseSettings, - pub waveshaper: WaveshaperSettings, pub flavor: super::FlavorType, pub flavor_cutoff: f32, pub flavor_resonance: f32, @@ -937,10 +954,8 @@ pub struct VoiceParams { pub step_seq_shuffle: f32, pub step_seq_trig_amp: u16, pub step_seq_trig_filter: u16, - pub step_seq_trig_pitch: u16, pub mseg_retrig_amp: u16, pub mseg_retrig_filter: u16, - pub mseg_retrig_pitch: u16, pub mseg_nodes: [f32; MSEG_MAX_NODES], pub mseg_curves: [MsegCurve; MSEG_MAX_SEGMENTS], pub mseg_loop_start: usize, @@ -980,14 +995,8 @@ impl Default for VoiceParams { filter_routing: FilterRouting::Series, filter_balance: 0.0, amp_eg: EnvelopeSettings::default(), + osc_egs: None, filter_eg: EnvelopeSettings::default(), - pitch_eg: EnvelopeSettings { - attack: 0.0, - decay: 0.0, - sustain: 0.0, - release: 0.0, - ..EnvelopeSettings::default() - }, lfo1: LfoSettings::default(), lfo2: LfoSettings::default(), lfo3: LfoSettings::default(), @@ -1001,7 +1010,6 @@ impl Default for VoiceParams { scene_lfo5: LfoSettings::default(), scene_lfo6: LfoSettings::default(), noise: NoiseSettings::default(), - waveshaper: WaveshaperSettings::default(), flavor: super::FlavorType::Off, flavor_cutoff: 8000.0, flavor_resonance: 0.5, @@ -1042,10 +1050,8 @@ impl Default for VoiceParams { step_seq_shuffle: 0.0, step_seq_trig_amp: 0, step_seq_trig_filter: 0, - step_seq_trig_pitch: 0, mseg_retrig_amp: 0, mseg_retrig_filter: 0, - mseg_retrig_pitch: 0, mseg_nodes: [0.0; MSEG_MAX_NODES], mseg_curves: [MsegCurve::Linear; MSEG_MAX_SEGMENTS], mseg_loop_start: 0, @@ -1083,9 +1089,9 @@ pub struct Voice { oscillators: [Oscillator; 3], wavetables: [Option>; 3], noise: NoiseGenerator, + noise_unison: [NoiseGenerator; 7], flavor: FlavorFilter, flavor2: FlavorFilter, - waveshaper: Waveshaper, filter1_l: Filter, filter1_r: Filter, filter2_l: Filter, @@ -1095,8 +1101,8 @@ pub struct Voice { lowcut_states_l2: [f32; 4], lowcut_states_r2: [f32; 4], amp_eg: AdsrEnvelope, + osc_egs: [AdsrEnvelope; 3], filter_eg: AdsrEnvelope, - pitch_eg: AdsrEnvelope, pub lfo1: Lfo, pub lfo2: Lfo, pub lfo3: Lfo, @@ -1135,7 +1141,6 @@ pub struct Voice { latest_key: f32, amp_eg_output: f32, filter_eg_output: f32, - pitch_eg_output: f32, random_value: f32, alternate_sign: f32, @@ -1167,6 +1172,26 @@ pub struct Voice { mts_esp: Option>>, } +fn configure_noise_source(source: &mut NoiseGenerator, settings: &NoiseSettings) { + source.noise_type = settings.noise_type; + source.color = settings.color; + source.color_mode = if settings.color_mode == 0 { + NoiseColorMode::Tilt + } else { + NoiseColorMode::Legacy + }; + source.filter_enabled = settings.filter_enabled; + if settings.filter_enabled { + source.filter.set_filter_type(settings.filter_type); + source + .filter + .set_params(settings.filter_cutoff, settings.filter_resonance); + source + .filter + .prepare_block(settings.filter_cutoff, settings.filter_resonance, 1); + } +} + impl Voice { pub fn new(sample_rate: f32) -> Self { Self { @@ -1178,9 +1203,9 @@ impl Voice { ], wavetables: [None, None, None], noise: NoiseGenerator::new(sample_rate), + noise_unison: std::array::from_fn(|_| NoiseGenerator::new(sample_rate)), flavor: FlavorFilter::new(sample_rate), flavor2: FlavorFilter::new(sample_rate), - waveshaper: Waveshaper::new(), filter1_l: Filter::new(FilterType::Lowpass, sample_rate), filter1_r: Filter::new(FilterType::Lowpass, sample_rate), filter2_l: Filter::new(FilterType::Lowpass, sample_rate), @@ -1190,8 +1215,8 @@ impl Voice { lowcut_states_l2: [0.0; 4], lowcut_states_r2: [0.0; 4], amp_eg: AdsrEnvelope::new(sample_rate), + osc_egs: std::array::from_fn(|_| AdsrEnvelope::new(sample_rate)), filter_eg: AdsrEnvelope::new(sample_rate), - pitch_eg: AdsrEnvelope::new(sample_rate), lfo1: Lfo::new(sample_rate), lfo2: Lfo::new(sample_rate), lfo3: Lfo::new(sample_rate), @@ -1226,7 +1251,6 @@ impl Voice { latest_key: 0.0, amp_eg_output: 0.0, filter_eg_output: 0.0, - pitch_eg_output: 0.0, random_value: random::() * 2.0 - 1.0, alternate_sign: 1.0, note_counter: 0, @@ -1256,9 +1280,9 @@ impl Voice { // Compute change flags before overwriting self.params so we can skip // redundant per-component setup on the audio thread. - let amp_eg_changed = self.params.amp_eg != params.amp_eg; + let amp_eg_changed = + self.params.amp_eg != params.amp_eg || self.params.osc_egs != params.osc_egs; let filter_eg_changed = self.params.filter_eg != params.filter_eg; - let pitch_eg_changed = self.params.pitch_eg != params.pitch_eg; let step_seq_changed = self.params.step_seq_values != params.step_seq_values || self.params.step_seq_loop_start != params.step_seq_loop_start @@ -1295,7 +1319,6 @@ impl Voice { let flavor_changed = self.params.flavor != params.flavor || self.params.flavor_cutoff != params.flavor_cutoff || self.params.flavor_resonance != params.flavor_resonance; - let waveshaper_changed = self.params.waveshaper != params.waveshaper; self.params = params.clone(); @@ -1307,6 +1330,7 @@ impl Voice { } if amp_eg_changed { + self.configure_osc_envelopes(params); self.amp_eg.set_params( params.amp_eg.attack, params.amp_eg.decay, @@ -1351,29 +1375,6 @@ impl Voice { .set_correct_analog_mode(params.filter_eg.correct_analog_mode); } - if pitch_eg_changed { - self.pitch_eg.set_params( - params.pitch_eg.attack, - params.pitch_eg.decay, - params.pitch_eg.sustain, - params.pitch_eg.release, - ); - self.pitch_eg.set_mode(params.pitch_eg.mode); - self.pitch_eg.set_shapes( - params.pitch_eg.attack_shape, - params.pitch_eg.decay_shape, - params.pitch_eg.release_shape, - ); - self.pitch_eg - .set_retrigger_mode(params.pitch_eg.retrigger_mode); - self.pitch_eg.set_tempo_sync(params.pitch_eg.tempo_sync); - self.pitch_eg.set_uber_release(params.pitch_eg.uber_release); - self.pitch_eg - .set_gated_release(params.pitch_eg.gated_release); - self.pitch_eg - .set_correct_analog_mode(params.pitch_eg.correct_analog_mode); - } - if lfo1_changed { self.lfo1.set_rate_hz(params.lfo1.rate_hz); self.lfo1.set_shape(params.lfo1.shape); @@ -1644,11 +1645,6 @@ impl Voice { o.set_lowcut(settings.window_lowcut); o.set_highcut(settings.window_highcut); } - if let Oscillator::Modern(o) = osc { - o.set_sub_octave(settings.sub_octave as i8); - o.set_sub_waveform(ModernSubWaveform::from_u8(settings.waveform)); - o.set_sub_one(settings.sub_one); - } if let Oscillator::Alias(o) = osc { for (i, &) in settings.alias_partials.iter().enumerate() { o.set_partial_amplitude(i, amp); @@ -1690,24 +1686,9 @@ impl Voice { } if noise_changed { - self.noise.noise_type = params.noise.noise_type; - self.noise.color = params.noise.color; - self.noise.color_mode = if params.noise.color_mode == 0 { - NoiseColorMode::Tilt - } else { - NoiseColorMode::Legacy - }; - self.noise.filter_enabled = params.noise.filter_enabled; - if params.noise.filter_enabled { - self.noise.filter.set_filter_type(params.noise.filter_type); - self.noise - .filter - .set_params(params.noise.filter_cutoff, params.noise.filter_resonance); - self.noise.filter.prepare_block( - params.noise.filter_cutoff, - params.noise.filter_resonance, - 1, - ); + configure_noise_source(&mut self.noise, ¶ms.noise); + for source in &mut self.noise_unison { + configure_noise_source(source, ¶ms.noise); } } @@ -1719,12 +1700,6 @@ impl Voice { self.flavor2.cutoff_hz = params.flavor_cutoff; self.flavor2.resonance = params.flavor_resonance; } - - if waveshaper_changed { - self.waveshaper.set_shape(params.waveshaper.shape); - self.waveshaper.drive = params.waveshaper.drive; - self.waveshaper.mix = params.waveshaper.mix; - } } pub fn update_filter_params(&mut self, params: &VoiceParams) { @@ -1863,11 +1838,6 @@ impl Voice { o.set_lowcut(settings.window_lowcut); o.set_highcut(settings.window_highcut); } - if let Oscillator::Modern(o) = osc { - o.set_sub_octave(settings.sub_octave as i8); - o.set_sub_waveform(ModernSubWaveform::from_u8(settings.waveform)); - o.set_sub_one(settings.sub_one); - } if let Oscillator::Alias(o) = osc { for (i, &) in settings.alias_partials.iter().enumerate() { o.set_partial_amplitude(i, amp); @@ -1908,7 +1878,71 @@ impl Voice { } } + fn configure_osc_envelopes(&mut self, params: &VoiceParams) { + for (i, envelope) in self.osc_egs.iter_mut().enumerate() { + let settings = params + .osc_egs + .as_ref() + .map_or(¶ms.amp_eg, |egs| &egs[i]); + envelope.set_params( + settings.attack, + settings.decay, + settings.sustain, + settings.release, + ); + envelope.set_mode(settings.mode); + envelope.set_shapes( + settings.attack_shape, + settings.decay_shape, + settings.release_shape, + ); + envelope.set_retrigger_mode(settings.retrigger_mode); + envelope.set_tempo_sync(settings.tempo_sync); + envelope.set_uber_release(settings.uber_release); + envelope.set_gated_release(settings.gated_release); + envelope.set_correct_analog_mode(settings.correct_analog_mode); + } + } + + fn amplitude_envelopes_active(&self) -> bool { + self.amp_eg.is_active() || self.osc_egs.iter().any(AdsrEnvelope::is_active) + } + + // Keep the final VCA for filter tails. Relative source gains give each + // oscillator its own envelope while identical envelopes preserve the old + // filter input level and output response (rather than applying ADSR twice). + fn next_osc_envelope_gains(&mut self, mods: &ModValues) -> ([f32; 3], f32, f32) { + let outputs: [f32; 3] = std::array::from_fn(|i| { + let settings = self + .params + .osc_egs + .as_ref() + .map_or(&self.params.amp_eg, |egs| &egs[i]); + let envelope = &mut self.osc_egs[i]; + envelope.set_attack((settings.attack + mods.amp_attack + mods.osc_eg[i][0]).max(0.0)); + envelope.set_decay((settings.decay + mods.amp_decay + mods.osc_eg[i][1]).max(0.0)); + envelope.set_sustain( + (settings.sustain + mods.amp_sustain + mods.osc_eg[i][2]).clamp(0.0, 1.0), + ); + envelope + .set_release((settings.release + mods.amp_release + mods.osc_eg[i][3]).max(0.0)); + envelope.next() + }); + let gain = outputs.iter().copied().fold(self.amp_eg_output, f32::max); + if gain > 0.0 { + ( + outputs.map(|value| value / gain), + self.amp_eg_output / gain, + gain, + ) + } else { + ([0.0; 3], 0.0, 0.0) + } + } + pub fn update_amp_eg_params(&mut self, params: &VoiceParams) { + self.configure_osc_envelopes(params); + self.params.osc_egs = params.osc_egs.clone(); self.params.amp_eg = params.amp_eg.clone(); self.amp_eg.set_params( params.amp_eg.attack, @@ -1955,30 +1989,6 @@ impl Voice { .set_correct_analog_mode(params.filter_eg.correct_analog_mode); } - pub fn update_pitch_eg_params(&mut self, params: &VoiceParams) { - self.params.pitch_eg = params.pitch_eg.clone(); - self.pitch_eg.set_params( - params.pitch_eg.attack, - params.pitch_eg.decay, - params.pitch_eg.sustain, - params.pitch_eg.release, - ); - self.pitch_eg.set_mode(params.pitch_eg.mode); - self.pitch_eg.set_shapes( - params.pitch_eg.attack_shape, - params.pitch_eg.decay_shape, - params.pitch_eg.release_shape, - ); - self.pitch_eg - .set_retrigger_mode(params.pitch_eg.retrigger_mode); - self.pitch_eg.set_tempo_sync(params.pitch_eg.tempo_sync); - self.pitch_eg.set_uber_release(params.pitch_eg.uber_release); - self.pitch_eg - .set_gated_release(params.pitch_eg.gated_release); - self.pitch_eg - .set_correct_analog_mode(params.pitch_eg.correct_analog_mode); - } - pub fn update_lfo_params(&mut self, params: &VoiceParams, idx: usize) { let settings = match idx { 0 => { @@ -2037,34 +2047,44 @@ impl Voice { lfo.set_env_tempo_sync(settings.env_tempo_sync); } - pub fn update_noise_params(&mut self, params: &VoiceParams) { - self.params.noise = params.noise.clone(); - self.noise.noise_type = params.noise.noise_type; - self.noise.color = params.noise.color; - self.noise.color_mode = if params.noise.color_mode == 0 { - NoiseColorMode::Tilt - } else { - NoiseColorMode::Legacy - }; - self.noise.filter_enabled = params.noise.filter_enabled; - if params.noise.filter_enabled { - self.noise.filter.set_filter_type(params.noise.filter_type); - self.noise - .filter - .set_params(params.noise.filter_cutoff, params.noise.filter_resonance); - self.noise.filter.prepare_block( - params.noise.filter_cutoff, - params.noise.filter_resonance, - 1, - ); + fn next_noise_unison_stereo(&mut self) -> (f32, f32) { + let voices = self.params.noise.unison_voices.clamp(1, 8) as usize; + let stereo = self.params.noise.stereo; + if voices == 1 { + self.noise.stereo = stereo; + return self.noise.next_stereo(); + } + + let spread = self.params.noise.unison_spread.clamp(0.0, 1.0); + let normalization = (voices as f32).sqrt().recip(); + let mut left = 0.0; + let mut right = 0.0; + for voice in 0..voices { + let source = if voice == 0 { + &mut self.noise + } else { + &mut self.noise_unison[voice - 1] + }; + source.stereo = stereo; + let (sample_l, sample_r) = source.next_stereo(); + let position = if voices == 1 { + 0.0 + } else { + voice as f32 / (voices - 1) as f32 * 2.0 - 1.0 + }; + let pan = position * spread; + left += sample_l * (1.0 - pan).sqrt(); + right += sample_r * (1.0 + pan).sqrt(); } + (left * normalization, right * normalization) } - pub fn update_waveshaper_params(&mut self, params: &VoiceParams) { - self.params.waveshaper = params.waveshaper.clone(); - self.waveshaper.set_shape(params.waveshaper.shape); - self.waveshaper.drive = params.waveshaper.drive; - self.waveshaper.mix = params.waveshaper.mix; + pub fn update_noise_params(&mut self, params: &VoiceParams) { + self.params.noise = params.noise.clone(); + configure_noise_source(&mut self.noise, ¶ms.noise); + for source in &mut self.noise_unison { + configure_noise_source(source, ¶ms.noise); + } } pub fn update_flavor_params(&mut self, params: &VoiceParams) { @@ -2226,8 +2246,10 @@ impl Voice { self.filter2_l = Filter::new(self.params.filter2.filter_type, sample_rate); self.filter2_r = Filter::new(self.params.filter2.filter_type, sample_rate); self.amp_eg.set_sample_rate(sample_rate); + for envelope in &mut self.osc_egs { + envelope.set_sample_rate(sample_rate); + } self.filter_eg.set_sample_rate(sample_rate); - self.pitch_eg.set_sample_rate(sample_rate); self.lfo1.set_sample_rate(sample_rate); self.lfo2.set_sample_rate(sample_rate); self.lfo3.set_sample_rate(sample_rate); @@ -2245,8 +2267,10 @@ impl Voice { pub fn set_eg_tempo(&mut self, tempo_bpm: f32) { self.amp_eg.set_tempo(tempo_bpm); + for envelope in &mut self.osc_egs { + envelope.set_tempo(tempo_bpm); + } self.filter_eg.set_tempo(tempo_bpm); - self.pitch_eg.set_tempo(tempo_bpm); } pub fn set_key_mod_values(&mut self, lowest: f32, highest: f32, latest: f32) { @@ -2271,7 +2295,7 @@ impl Voice { } else { self.params.portamento }; - if portamento_time <= 0.0 || !self.amp_eg.is_active() { + if portamento_time <= 0.0 || !self.amplitude_envelopes_active() { self.current_freq = self.target_freq; } @@ -2290,8 +2314,10 @@ impl Voice { self.filter2_r.reset(); self.amp_eg.trigger(); + for envelope in &mut self.osc_egs { + envelope.trigger(); + } self.filter_eg.trigger(); - self.pitch_eg.trigger(); self.last_scale_degree = freq_to_scale_degree(self.target_freq, &self.tuning); self.lfo1.reset(); @@ -2327,15 +2353,19 @@ impl Voice { self.uber_release = true; self.uber_fade = 1.0; self.amp_eg.release(); + for envelope in &mut self.osc_egs { + envelope.release(); + } self.filter_eg.release(); - self.pitch_eg.release(); } pub fn release(&mut self) { self.gate = false; self.amp_eg.release(); + for envelope in &mut self.osc_egs { + envelope.release(); + } self.filter_eg.release(); - self.pitch_eg.release(); self.lfo1.release(); self.lfo2.release(); self.lfo3.release(); @@ -2350,7 +2380,7 @@ impl Voice { } pub fn is_active(&self) -> bool { - self.active && (self.amp_eg.is_active() || self.gate) + self.active && (self.amplitude_envelopes_active() || self.gate) } pub fn note_age(&self) -> usize { @@ -2376,7 +2406,6 @@ impl Voice { ModSource::Lfo6 => self.lfo6_output, ModSource::AmpEg => self.amp_eg_output, ModSource::FilterEg => self.filter_eg_output, - ModSource::PitchEg => self.pitch_eg_output, ModSource::RandomBipolar => self.random_value, ModSource::RandomUnipolar => (self.random_value + 1.0) * 0.5, ModSource::AlternateBipolar => self.alternate_sign, @@ -2473,6 +2502,18 @@ impl Voice { ModTarget::Filter2Resonance => vals.f2_resonance += delta, ModTarget::Filter2EgAmount => vals.f2_eg_amount += delta, ModTarget::Filter2Drive => vals.f2_drive += delta, + ModTarget::Osc1EgAttack => vals.osc_eg[0][0] += delta, + ModTarget::Osc1EgDecay => vals.osc_eg[0][1] += delta, + ModTarget::Osc1EgSustain => vals.osc_eg[0][2] += delta, + ModTarget::Osc1EgRelease => vals.osc_eg[0][3] += delta, + ModTarget::Osc2EgAttack => vals.osc_eg[1][0] += delta, + ModTarget::Osc2EgDecay => vals.osc_eg[1][1] += delta, + ModTarget::Osc2EgSustain => vals.osc_eg[1][2] += delta, + ModTarget::Osc2EgRelease => vals.osc_eg[1][3] += delta, + ModTarget::Osc3EgAttack => vals.osc_eg[2][0] += delta, + ModTarget::Osc3EgDecay => vals.osc_eg[2][1] += delta, + ModTarget::Osc3EgSustain => vals.osc_eg[2][2] += delta, + ModTarget::Osc3EgRelease => vals.osc_eg[2][3] += delta, ModTarget::AmpAttack => vals.amp_attack += delta, ModTarget::AmpDecay => vals.amp_decay += delta, ModTarget::AmpSustain => vals.amp_sustain += delta, @@ -2481,10 +2522,6 @@ impl Voice { ModTarget::FilterDecay => vals.filter_decay += delta, ModTarget::FilterSustain => vals.filter_sustain += delta, ModTarget::FilterRelease => vals.filter_release += delta, - ModTarget::PitchAttack => vals.pitch_attack += delta, - ModTarget::PitchDecay => vals.pitch_decay += delta, - ModTarget::PitchSustain => vals.pitch_sustain += delta, - ModTarget::PitchRelease => vals.pitch_release += delta, ModTarget::Lfo1Rate => vals.lfo1_rate += delta, ModTarget::Lfo1Amount => vals.lfo1_amount += delta, ModTarget::Lfo1Deform => vals.lfo1_deform += delta, @@ -2513,7 +2550,6 @@ impl Voice { ModTarget::OutputPan => vals.output_pan += delta, ModTarget::OutputWidth => vals.output_width += delta, ModTarget::NoiseLevel => vals.noise_level += delta, - ModTarget::WaveshaperDrive => vals.waveshaper_drive += delta, ModTarget::Portamento => vals.portamento += delta, ModTarget::FlavorCutoff => vals.flavor_cutoff += delta, ModTarget::FilterBalance => vals.filter_balance += delta, @@ -2614,11 +2650,7 @@ impl Voice { /// section, in absolute Hz. When the section runs at 2×, the voice /// filters are built with the doubled rate, so the same absolute cutoff /// maps to the same frequency at either rate. - fn compute_filter_sample_params( - &self, - mods: &ModValues, - ws_active: bool, - ) -> VoiceFilterSampleParams { + fn compute_filter_sample_params(&self, mods: &ModValues) -> VoiceFilterSampleParams { let f1_enabled = self.params.filter1.enabled; let f1_cutoff = if f1_enabled { let has_lfo1_f1 = self.params.modulations.iter().any(|r| { @@ -2688,12 +2720,6 @@ impl Voice { 0.0 }; - let ws_drive = if ws_active { - (self.params.waveshaper.drive + mods.waveshaper_drive).clamp(0.0, 1.0) - } else { - 0.0 - }; - VoiceFilterSampleParams { f1_cutoff, f1_res, @@ -2701,13 +2727,12 @@ impl Voice { f2_cutoff, f2_res, f2_drive, - ws_drive, } } /// One sample of the nonlinear filter section: feedback injection, - /// per-sample filter coefficient updates, the routing/waveshaper chain, - /// balance mix, and the filter-feedback pickup. This is the single + /// per-sample filter coefficient updates, filter routing, balance mix, + /// and the filter-feedback pickup. This is the single /// implementation of the section; it runs at host rate when the /// oversample toggle is off (or nothing nonlinear is active) and twice /// per host sample at 2× when it is on. In the 2× case the filter @@ -2740,10 +2765,8 @@ impl Voice { .prepare_block(params.f2_cutoff, params.f2_res, 1); let balance = ctx.balance; - let ws_active = ctx.ws_active; let f1_enabled = ctx.f1_enabled; let f2_enabled = ctx.f2_enabled; - let ws_drive = params.ws_drive; let f1_drive = params.f1_drive; let f2_drive = params.f2_drive; let (mut char_l, mut char_r, f1_out_l, f1_out_r) = if ctx.per_source_routing { @@ -2763,25 +2786,9 @@ impl Voice { f2_l = self.filter2_l.process(f2_l); f2_r = self.filter2_r.process(f2_r); } - let sum_l = f1_l + f2_l; - let sum_r = f1_r + f2_r; - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(sum_l), ws.process(sum_r)) - } else { - (sum_l, sum_r) - }; - (ws_l, ws_r, f1_l, f1_r) + (f1_l + f2_l, f1_r + f2_r, f1_l, f1_r) } else if !f1_enabled && !f2_enabled { - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(pre_filter_l), ws.process(pre_filter_r)) - } else { - (pre_filter_l, pre_filter_r) - }; - (ws_l, ws_r, ws_l, ws_r) + (pre_filter_l, pre_filter_r, pre_filter_l, pre_filter_r) } else { match self.params.filter_routing { FilterRouting::Series => { @@ -2793,22 +2800,15 @@ impl Voice { s_l = self.filter1_l.process(s_l); s_r = self.filter1_r.process(s_r); } - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(s_l), ws.process(s_r)) - } else { - (s_l, s_r) - }; - let mut out_l = ws_l; - let mut out_r = ws_r; + let mut out_l = s_l; + let mut out_r = s_r; if f2_enabled { self.filter2_l.set_drive(f2_drive); self.filter2_r.set_drive(f2_drive); out_l = self.filter2_l.process(out_l); out_r = self.filter2_r.process(out_r); } - (out_l, out_r, ws_l, ws_r) + (out_l, out_r, s_l, s_r) } FilterRouting::Parallel => { let mut f1_l = pre_filter_l; @@ -2829,14 +2829,7 @@ impl Voice { } let sum_l = (f1_l + f2_l) * 0.5; let sum_r = (f1_r + f2_r) * 0.5; - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(sum_l), ws.process(sum_r)) - } else { - (sum_l, sum_r) - }; - (ws_l, ws_r, f1_l, f1_r) + (sum_l, sum_r, f1_l, f1_r) } FilterRouting::Wide => { let mut s_l = pre_filter_l; @@ -2847,22 +2840,15 @@ impl Voice { s_l = self.filter2_l.process(s_l); s_r = self.filter2_r.process(s_r); } - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(s_l), ws.process(s_r)) - } else { - (s_l, s_r) - }; - let mut out_l = ws_l; - let mut out_r = ws_r; + let mut out_l = s_l; + let mut out_r = s_r; if f1_enabled { self.filter1_l.set_drive(f1_drive); self.filter1_r.set_drive(f1_drive); out_l = self.filter1_l.process(out_l); out_r = self.filter1_r.process(out_r); } - (out_l, out_r, ws_l, ws_r) + (out_l, out_r, s_l, s_r) } FilterRouting::Split => { let mut f1_l = pre_filter_l; @@ -2883,14 +2869,7 @@ impl Voice { } let stereo_l = f1_l; let stereo_r = f2_r; - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(stereo_l), ws.process(stereo_r)) - } else { - (stereo_l, stereo_r) - }; - (ws_l, ws_r, stereo_l, stereo_r) + (stereo_l, stereo_r, stereo_l, stereo_r) } FilterRouting::Serial2 => { let mut s_l = pre_filter_l; @@ -2901,22 +2880,15 @@ impl Voice { s_l = self.filter2_l.process(s_l); s_r = self.filter2_r.process(s_r); } - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(s_l), ws.process(s_r)) - } else { - (s_l, s_r) - }; - let mut out_l = ws_l; - let mut out_r = ws_r; + let mut out_l = s_l; + let mut out_r = s_r; if f1_enabled { self.filter1_l.set_drive(f1_drive); self.filter1_r.set_drive(f1_drive); out_l = self.filter1_l.process(out_l); out_r = self.filter1_r.process(out_r); } - (out_l, out_r, ws_l, ws_r) + (out_l, out_r, s_l, s_r) } FilterRouting::Serial3 => { let mut s_l = pre_filter_l; @@ -2927,13 +2899,6 @@ impl Voice { s_l = self.filter1_l.process(s_l); s_r = self.filter1_r.process(s_r); } - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(s_l), ws.process(s_r)) - } else { - (s_l, s_r) - }; let mut f2_l = pre_filter_l; let mut f2_r = pre_filter_r; if f2_enabled { @@ -2942,9 +2907,9 @@ impl Voice { f2_l = self.filter2_l.process(f2_l); f2_r = self.filter2_r.process(f2_r); } - let out_l = ws_l * 0.7 + f2_l * 0.3; - let out_r = ws_r * 0.7 + f2_r * 0.3; - (out_l, out_r, ws_l, ws_r) + let out_l = s_l * 0.7 + f2_l * 0.3; + let out_r = s_r * 0.7 + f2_r * 0.3; + (out_l, out_r, s_l, s_r) } FilterRouting::Dual2 => { let mut f1_l = pre_filter_l; @@ -2957,22 +2922,15 @@ impl Voice { f1_l = self.filter1_l.process(f1_l); f1_r = self.filter1_r.process(f1_r); } - let (f1_ws_l, f1_ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(f1_l), ws.process(f1_r)) - } else { - (f1_l, f1_r) - }; if f2_enabled { self.filter2_l.set_drive(f2_drive); self.filter2_r.set_drive(f2_drive); f2_l = self.filter2_l.process(f2_l); f2_r = self.filter2_r.process(f2_r); } - let out_l = (f1_ws_l + f2_l) * 0.5; - let out_r = (f1_ws_r + f2_r) * 0.5; - (out_l, out_r, f1_ws_l, f1_ws_r) + let out_l = (f1_l + f2_l) * 0.5; + let out_r = (f1_r + f2_r) * 0.5; + (out_l, out_r, f1_l, f1_r) } FilterRouting::Ring => { let mut f1_l = pre_filter_l; @@ -2993,14 +2951,7 @@ impl Voice { } let ring_l = f1_l * f2_l; let ring_r = f1_r * f2_r; - let (ws_l, ws_r) = if ws_active { - let mut ws = self.waveshaper; - ws.drive = ws_drive; - (ws.process(ring_l), ws.process(ring_r)) - } else { - (ring_l, ring_r) - }; - (ws_l, ws_r, f1_l, f1_r) + (ring_l, ring_r, f1_l, f1_r) } } }; @@ -3114,8 +3065,9 @@ impl Voice { self.scene_lfo6_output = scene_lfo_bufs[5][i]; self.amp_eg_output = self.amp_eg.next(); + let (osc_eg_gains, _, envelope_gain) = + self.next_osc_envelope_gains(&ModValues::default()); self.filter_eg_output = self.filter_eg.next(); - self.pitch_eg_output = self.pitch_eg.next(); self.lfo1_output = self.lfo1.next(); self.lfo2_output = self.lfo2.next(); self.lfo3_output = self.lfo3.next(); @@ -3185,10 +3137,8 @@ impl Voice { } }; let pb_mul = 2.0f32.powf(self.pitch_bend * pb_range / 12.0); - let pitch_eg_mul = 2.0f32.powf(self.pitch_eg_output * 2.0); let lfo5_pitch_mul = 2.0f32.powf(self.lfo5_output * 50.0 / 1200.0); - self.oscillators[0] - .set_freq_hz(self.current_freq * pb_mul * pitch_eg_mul * lfo5_pitch_mul); + self.oscillators[0].set_freq_hz(self.current_freq * pb_mul * lfo5_pitch_mul); let (osc1_l, osc1_r) = self.oscillators[0].next(0.0, audio_l, audio_r); @@ -3196,7 +3146,6 @@ impl Voice { let lfo6_pitch_mul = 2.0f32.powf(self.lfo6_output * 50.0 / 1200.0); let osc2_freq = self.current_freq * pb_mul - * pitch_eg_mul * lfo6_pitch_mul * 2.0f32.powi(osc2_settings.octave as i32) * 2.0f32.powf(osc2_settings.semitone as f32 / 12.0) @@ -3210,7 +3159,6 @@ impl Voice { let osc3_settings = &self.params.oscs[2]; let osc3_freq = self.current_freq * pb_mul - * pitch_eg_mul * 2.0f32.powi(osc3_settings.octave as i32) * 2.0f32.powf(osc3_settings.semitone as f32 / 12.0) * 2.0f32.powf(osc3_settings.fine / 1200.0); @@ -3244,8 +3192,12 @@ impl Voice { }; let (mut mix_l, mut mix_r) = ( - osc1_l * osc1_level + osc2_l * osc2_level + osc3_l * osc3_level, - osc1_r * osc1_level + osc2_r * osc2_level + osc3_r * osc3_level, + osc1_l * osc1_level * osc_eg_gains[0] + + osc2_l * osc2_level * osc_eg_gains[1] + + osc3_l * osc3_level * osc_eg_gains[2], + osc1_r * osc1_level * osc_eg_gains[0] + + osc2_r * osc2_level * osc_eg_gains[1] + + osc3_r * osc3_level * osc_eg_gains[2], ); if f1_enabled { @@ -3268,12 +3220,12 @@ impl Voice { let vca_level = self.params.vca_level.clamp(0.0, 2.0); let vel_sense = self.params.vca_velsense.clamp(0.0, 1.0); let effective_vel = 1.0 - vel_sense + vel_sense * self.velocity; - let gain = self.amp_eg_output * effective_vel * vol * vca_level; + let gain = envelope_gain * effective_vel * vol * vca_level; out_l[i] = mix_l * gain; out_r[i] = mix_r * gain; } - if !self.amp_eg.is_active() && !self.gate { + if !self.amplitude_envelopes_active() && !self.gate { self.active = false; } return; @@ -3286,15 +3238,13 @@ impl Voice { }; // Decide the rate of the nonlinear filter section (filters with - // drive, waveshaper, filter feedback) for this whole block. The - // section only runs oversampled at 2× when the global toggle is on - // AND a nonlinear stage is active, so idle/dry voices pay nothing. - let ws_active = - self.params.waveshaper.enabled && self.params.waveshaper.shape != Waveshape::Off; + // drive and filter feedback) for this whole block. The section only + // runs oversampled at 2× when the global toggle is on AND a nonlinear + // stage is active, so idle/dry voices pay nothing. let f1_enabled = self.params.filter1.enabled; let f2_enabled = self.params.filter2.enabled; let fb_amount = self.params.filter_feedback.clamp(-1.0, 1.0).abs(); - let nonlinear_active = ws_active || f1_enabled || f2_enabled || fb_amount > 0.0; + let nonlinear_active = f1_enabled || f2_enabled || fb_amount > 0.0; let oversample = self.params.voice_oversample && nonlinear_active; let target_filter_rate = if oversample { self.sample_rate * 2.0 @@ -3418,8 +3368,10 @@ impl Voice { let current_degree = freq_to_scale_degree(self.current_freq, &self.tuning); if current_degree != self.last_scale_degree { self.amp_eg.trigger(); + for envelope in &mut self.osc_egs { + envelope.trigger(); + } self.filter_eg.trigger(); - self.pitch_eg.trigger(); self.last_scale_degree = current_degree; } } else { @@ -3487,15 +3439,6 @@ impl Voice { .set_sustain((self.params.filter_eg.sustain + mods.filter_sustain).clamp(0.0, 1.0)); self.filter_eg .set_release((self.params.filter_eg.release + mods.filter_release).max(0.0)); - self.pitch_eg - .set_attack((self.params.pitch_eg.attack + mods.pitch_attack).max(0.0)); - self.pitch_eg - .set_decay((self.params.pitch_eg.decay + mods.pitch_decay).max(0.0)); - self.pitch_eg - .set_sustain((self.params.pitch_eg.sustain + mods.pitch_sustain).clamp(0.0, 1.0)); - self.pitch_eg - .set_release((self.params.pitch_eg.release + mods.pitch_release).max(0.0)); - self.lfo1_output = self.lfo1.next(); self.lfo2_output = self.lfo2.next(); self.lfo3_output = self.lfo3.next(); @@ -3516,31 +3459,31 @@ impl Voice { let mask = 1u16 << lfo.stepseq.step_index.min(15); if self.params.step_seq_trig_amp & mask != 0 { self.amp_eg.trigger(); + for envelope in &mut self.osc_egs { + envelope.trigger(); + } } if self.params.step_seq_trig_filter & mask != 0 { self.filter_eg.trigger(); } - if self.params.step_seq_trig_pitch & mask != 0 { - self.pitch_eg.trigger(); - } } if *shape == LfoShape::Mseg && lfo.mseg_seg_changed { let mask = 1u16 << lfo.mseg_prev_seg.min(15); if self.params.mseg_retrig_amp & mask != 0 { self.amp_eg.trigger(); + for envelope in &mut self.osc_egs { + envelope.trigger(); + } } if self.params.mseg_retrig_filter & mask != 0 { self.filter_eg.trigger(); } - if self.params.mseg_retrig_pitch & mask != 0 { - self.pitch_eg.trigger(); - } } } self.amp_eg_output = self.amp_eg.next(); self.filter_eg_output = self.filter_eg.next(); - self.pitch_eg_output = self.pitch_eg.next(); + let (osc_eg_gains, noise_eg_gain, envelope_gain) = self.next_osc_envelope_gains(&mods); self.update_oscillator_freqs(&mods); @@ -3688,7 +3631,8 @@ impl Voice { } let passes = if any_soloed { osc.solo } else { !osc.mute }; if passes { - let level = (osc.level + mods.osc_level[idx]).clamp(0.0, 2.0); + let level = + (osc.level + mods.osc_level[idx]).clamp(0.0, 2.0) * osc_eg_gains[idx]; let s_l = osc_sample.0 * level; let s_r = osc_sample.1 * level; match osc.route { @@ -3710,13 +3654,13 @@ impl Voice { } } - let noise = &self.params.noise; + let noise = self.params.noise.clone(); if noise.enabled { let passes = if any_soloed { noise.solo } else { !noise.mute }; if passes { - let noise_level = (noise.level + mods.noise_level).clamp(0.0, 2.0); - self.noise.stereo = noise.stereo; - let (noise_l, noise_r) = self.noise.next_stereo(); + let noise_level = + (noise.level + mods.noise_level).clamp(0.0, 2.0) * noise_eg_gain; + let (noise_l, noise_r) = self.next_noise_unison_stereo(); let s_l = noise_l * noise_level; let s_r = noise_r * noise_level; match noise.route { @@ -3819,12 +3763,11 @@ impl Voice { let ctx = VoiceFilterContext { balance: (self.params.filter_balance + mods.filter_balance).clamp(-1.0, 1.0), - ws_active, f1_enabled, f2_enabled, per_source_routing, }; - let fp = self.compute_filter_sample_params(&mods, ws_active); + let fp = self.compute_filter_sample_params(&mods); let (mut char_l, mut char_r) = if oversample { // The halfband round trip adds a fixed ~31 base-rate samples @@ -3874,10 +3817,8 @@ impl Voice { } else { 1.0 }; - char_l *= - self.amp_eg_output * effective_vel * vol * vca_level * note_on_fade * uber_fade; - char_r *= - self.amp_eg_output * effective_vel * vol * vca_level * note_on_fade * uber_fade; + char_l *= envelope_gain * effective_vel * vol * vca_level * note_on_fade * uber_fade; + char_r *= envelope_gain * effective_vel * vol * vca_level * note_on_fade * uber_fade; let pan = (self.params.pan + mods.output_pan).clamp(-1.0, 1.0); let width = (self.params.width + mods.output_width).clamp(-1.0, 1.0); @@ -3892,7 +3833,7 @@ impl Voice { out_r[i] = (mid - side) * pan_r; } - if !self.amp_eg.is_active() && !self.gate { + if !self.amplitude_envelopes_active() && !self.gate { self.active = false; } } @@ -3911,7 +3852,6 @@ impl Voice { self.pitch_bend_smooth_state = self.pitch_bend; } - let pitch_eg_mod = self.pitch_eg_output * 2.0; let pb_range = if self.pitch_bend_smooth_state >= 0.0 { if self.params.pitch_bend_up > 0.0 { self.params.pitch_bend_up @@ -3949,7 +3889,7 @@ impl Voice { let octave_mul = 2.0f32.powi(settings.octave as i32); let semitone_mul = 2.0f32.powf(settings.semitone as f32 / 12.0); let fine_mul = 2.0f32.powf(settings.fine / 1200.0); - let pitch_mod_mul = 2.0f32.powf(mods.osc_pitch[idx] + pitch_eg_mod); + let pitch_mod_mul = 2.0f32.powf(mods.osc_pitch[idx]); let drift_cents = self.drift_phase[idx] * drift_amount * 20.0; let drift_mul = 2.0f32.powf(drift_cents / 1200.0); @@ -4015,6 +3955,155 @@ mod tests { use super::*; use std::io::Write; + fn envelope_test_voice(envelopes: [EnvelopeSettings; 3], oscillator: usize) -> Voice { + let mut params = VoiceParams { + amp_eg: EnvelopeSettings { + attack: 0.0, + decay: 0.0, + sustain: 1.0, + release: 0.0, + ..EnvelopeSettings::default() + }, + osc_egs: Some(envelopes), + ..VoiceParams::default() + }; + for (i, osc) in params.oscs.iter_mut().enumerate() { + osc.enabled = i == oscillator; + osc.phase_mode = OscPhaseMode::Zero; + osc.osc_type = OscType::Classic; + osc.level = 0.5; + } + params.filter1.enabled = false; + params.filter2.enabled = false; + params.flavor = crate::common::flavor::FlavorType::Off; + params.noise.enabled = false; + params.drift_amount = 0.0; + let mut voice = Voice::new(48000.0); + voice.set_params(¶ms); + voice.trigger(60, 1.0); + voice + } + + fn render_envelope_test(voice: &mut Voice, frames: usize) -> Vec { + let mut left = vec![0.0; frames]; + let mut right = vec![0.0; frames]; + let zero = vec![0.0; frames]; + voice.process_block(&mut left, &mut right, None, None, &[&zero; 6]); + assert!(left.iter().chain(&right).all(|s| s.is_finite())); + left + } + + #[test] + fn oscillator_envelope_sustain_only_controls_its_own_audio() { + let open = EnvelopeSettings { + attack: 0.0, + decay: 0.0, + sustain: 1.0, + release: 0.0, + ..EnvelopeSettings::default() + }; + for oscillator in 0..3 { + let mut egs = [open.clone(), open.clone(), open.clone()]; + // Silence the other two envelopes while keeping this oscillator open. + for (i, eg) in egs.iter_mut().enumerate() { + if i != oscillator { + eg.sustain = 0.0; + } + } + let mut voice = envelope_test_voice(egs.clone(), oscillator); + let samples = render_envelope_test(&mut voice, 4096); + assert!(samples[1024..].iter().any(|s| s.abs() > 0.01)); + egs[oscillator].sustain = 0.0; + let mut silent = envelope_test_voice(egs, oscillator); + let samples = render_envelope_test(&mut silent, 4096); + assert!(samples[1024..].iter().all(|s| s.abs() < 1e-6)); + } + } + + #[test] + fn longer_oscillator_release_survives_shared_amp_release() { + let short = EnvelopeSettings { + attack: 0.0, + decay: 0.0, + sustain: 1.0, + release: 0.0, + ..EnvelopeSettings::default() + }; + for oscillator in 0..3 { + let mut egs = [short.clone(), short.clone(), short.clone()]; + egs[oscillator].release = 0.2; + let mut voice = envelope_test_voice(egs, oscillator); + render_envelope_test(&mut voice, 1024); + voice.release(); + let tail = render_envelope_test(&mut voice, 1024); + assert!(voice.is_active()); + assert!(tail[128..].iter().any(|s| s.abs() > 0.001)); + render_envelope_test(&mut voice, 48000); + assert!(!voice.is_active()); + } + } + + #[test] + fn oscillator_envelope_edit_updates_an_active_voice() { + let open = EnvelopeSettings { + attack: 0.0, + decay: 0.0, + sustain: 1.0, + release: 0.0, + ..EnvelopeSettings::default() + }; + let mut voice = envelope_test_voice([open.clone(), open.clone(), open], 1); + assert!( + render_envelope_test(&mut voice, 2048)[1024..] + .iter() + .any(|s| s.abs() > 0.01) + ); + let mut params = voice.params.clone(); + params.osc_egs.as_mut().unwrap()[1].sustain = 0.0; + voice.update_amp_eg_params(¶ms); + // The output low-cut retains a tail even with the voice filters bypassed. + let tail = render_envelope_test(&mut voice, 48000); + assert_eq!(voice.osc_egs[1].next(), 0.0); + let peak = tail[47000..] + .iter() + .fold(0.0_f32, |peak, sample| peak.max(sample.abs())); + assert!(peak < 1e-6, "remaining output tail: {peak}"); + params.osc_egs.as_mut().unwrap()[1].sustain = 1.0; + voice.update_amp_eg_params(¶ms); + assert!( + render_envelope_test(&mut voice, 2048)[1024..] + .iter() + .any(|s| s.abs() > 0.01) + ); + } + + #[test] + fn oscillator_envelope_modulation_targets_are_independent() { + let open = EnvelopeSettings { + attack: 0.0, + decay: 0.0, + sustain: 1.0, + release: 0.0, + ..EnvelopeSettings::default() + }; + let mut voice = envelope_test_voice([open.clone(), open.clone(), open], 0); + voice.params.modulations[0] = ModRouting { + source: ModSource::Lfo1, + target: ModTarget::Osc2EgSustain, + depth: -1.0, + active: true, + ..ModRouting::default() + }; + voice.lfo1_output = 1.0; + let mods = voice.compute_mod_values(); + let mut result = ([0.0; 3], 0.0, 0.0); + for _ in 0..1024 { + voice.amp_eg_output = voice.amp_eg.next(); + result = voice.next_osc_envelope_gains(&mods); + } + assert_eq!(result.0, [1.0, 0.0, 1.0]); + } + fn write_wav_stereo( path: &std::path::Path, left: &[f32], @@ -4129,7 +4218,6 @@ mod tests { voice.params.filter1.enabled = false; voice.params.filter2.enabled = false; voice.params.filter_feedback = 0.0; - voice.params.waveshaper.enabled = false; voice.params.flavor = crate::common::flavor::FlavorType::Off; voice.params.amp_eg.attack = 0.0; voice.params.amp_eg.decay = 0.0; diff --git a/src/synth/gui.rs b/src/synth/gui.rs index 9928a21..2c52f8a 100644 --- a/src/synth/gui.rs +++ b/src/synth/gui.rs @@ -1,6 +1,5 @@ use std::{ ffi::CStr, - path::PathBuf, sync::{ Arc, atomic::{AtomicBool, Ordering}, @@ -19,9 +18,11 @@ use maolan_clap::ffi::CLAP_WINDOW_API_COCOA; 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::arch_slider::arch_slider; use maolan_widgets::horizontal_slider::HorizontalSlider; +use maolan_widgets::knob::{Knob, knob}; +use maolan_widgets::multi_toggler::{LabelPosition, horizontal_multi_toggler}; mod envelope; +mod oscillator_display; #[cfg(any( target_os = "windows", target_os = "macos", @@ -35,11 +36,12 @@ use crate::{ common::{ filter::FilterType, lfo_assignment::{LfoAssignmentConfig, LfoAssignmentState, ModRouteParamIds}, + preset::{self, PresetProvider, PresetUi}, wavetable::Wavetable, wavetable_factory::{CUSTOM_WAVETABLE_LABEL, FACTORY_COUNT, FACTORY_NAMES}, }, synth::{ - dsp::{ClassicWaveform, LfoShape, ModTarget, ModernSubWaveform, OscType}, + dsp::{FilterRouting, LfoShape, ModTarget, OscType}, params::{ParamDef, ParamId, param_def}, plugin::SharedState, }, @@ -114,14 +116,22 @@ pub enum Message { ToggleLfoAssignment(usize), SelectLfo(usize), SelectOsc(usize), - SelectFilter(usize), - SelectEg(usize), - SelectMisc(usize), - SelectRouting(usize), PickWavetableFile(usize), - PickSurgePreset, - SaveSynthPreset, - OpenSynthPreset, + BeginEnvelopeEdit(ParamId), + ChangeEnvelopeEdit(ParamId, String), + CommitEnvelopeEdit(ParamId), + CancelEnvelopeEdit, + Preset(preset::Msg), +} + +impl From for Message { + fn from(msg: preset::Msg) -> Self { + Message::Preset(msg) + } +} + +fn id_is_envelope_sustain(id: ParamId) -> bool { + param_def(id).is_some_and(|def| def.name.ends_with("Sustain")) } struct State { @@ -130,11 +140,9 @@ struct State { selected_lfo: usize, lfo_assignment: LfoAssignmentState, selected_osc: usize, - selected_filter: usize, - selected_eg: usize, - selected_misc: usize, - selected_routing: usize, - preset_status: Option, + preset_ui: PresetUi, + envelope_edit: Option<(ParamId, String)>, + envelope_input_id: maolan_baseview::iced::widget::Id, } fn init(shared: Arc) -> (State, Task) { @@ -145,11 +153,9 @@ fn init(shared: Arc) -> (State, Task) { selected_lfo: 0, lfo_assignment: LfoAssignmentState::default(), selected_osc: 0, - selected_filter: 0, - selected_eg: 0, - selected_misc: 0, - selected_routing: 0, - preset_status: None, + preset_ui: PresetUi::new(::DIR_NAME), + envelope_edit: None, + envelope_input_id: maolan_baseview::iced::widget::Id::unique(), }, Task::none(), ) @@ -165,6 +171,14 @@ fn update(state: &mut State, message: Message) -> Task { state.shared.mark_gesture_begin_pending(id); } state.shared.set_param_outbound_only(id, value as f64); + let enabled_id = match id { + ParamId::F1Type => Some(ParamId::F1Enabled), + ParamId::F2Type => Some(ParamId::F2Enabled), + _ => None, + }; + if let Some(enabled_id) = enabled_id { + state.shared.set_param_outbound_only(enabled_id, 1.0); + } } Message::ReleaseParam(id) => { let idx = id.as_index(); @@ -192,7 +206,7 @@ fn update(state: &mut State, message: Message) -> Task { } Message::AssignLfoToParam(id) => { if let Some(lfo_index) = state.lfo_assignment.armed_lfo() { - assign_lfo_to_param(state, lfo_index, id); + toggle_lfo_param_assignment(state, lfo_index, id); } } Message::ToggleLfoAssignment(index) => { @@ -205,18 +219,6 @@ fn update(state: &mut State, message: Message) -> Task { Message::SelectOsc(index) => { state.selected_osc = index; } - Message::SelectFilter(index) => { - state.selected_filter = index; - } - Message::SelectEg(index) => { - state.selected_eg = index; - } - Message::SelectMisc(index) => { - state.selected_misc = index; - } - Message::SelectRouting(index) => { - state.selected_routing = index; - } Message::PickWavetableFile(osc_index) => { if let Some(path) = rfd::FileDialog::new() .add_filter("Wavetables", &["wt", "vawt", "wav", "flac", "mp3", "ogg"]) @@ -241,81 +243,57 @@ fn update(state: &mut State, message: Message) -> Task { } } } - Message::PickSurgePreset => { - if let Some(path) = rfd::FileDialog::new() - .add_filter("Surge XT presets", &["fxp"]) - .pick_file() - { - match state.shared.load_surge_preset(&path) { - Ok(()) => { - let name = file_stem_display(&path); - let report = state.shared.surge_report.lock(); - let skipped = report.skipped.len(); - let errors = report.errors.len(); - let notes = report.notes.len(); - state.preset_status = Some(format!( - "Imported {name}: {skipped} skipped, {errors} errors, {notes} notes" - )); - } - Err(error) => { - state.preset_status = Some(format!("Import failed: {error}")); - } - } - } + Message::Preset(msg) => { + preset::update(&mut state.preset_ui, msg, state.shared.as_ref()); } - Message::SaveSynthPreset => { - if let Some(path) = rfd::FileDialog::new() - .add_filter("Maolan Synth presets", &["msynth"]) - .set_file_name("Untitled.msynth") - .save_file() + Message::BeginEnvelopeEdit(id) => { + let value = state.shared.params.get(id) as f32; + let value = if id_is_envelope_sustain(id) { + format!("{:.0}", value * 100.0) + } else { + value.to_string() + }; + state.envelope_edit = Some((id, value)); + return maolan_baseview::iced::widget::operation::focus( + state.envelope_input_id.clone(), + ); + } + Message::ChangeEnvelopeEdit(id, value) => { + if let Some((editing, draft)) = &mut state.envelope_edit + && *editing == id { - let path = ensure_msynth_extension(path); - match state.shared.save_synth_preset(&path) { - Ok(()) => { - state.preset_status = Some(format!("Saved {}", file_stem_display(&path))); - } - Err(error) => { - state.preset_status = Some(format!("Save failed: {error}")); - } - } + *draft = value; } } - Message::OpenSynthPreset => { - if let Some(path) = rfd::FileDialog::new() - .add_filter("Maolan Synth presets", &["msynth"]) - .pick_file() - { - match state.shared.load_synth_preset(&path) { - Ok(name) => { - let name = name.unwrap_or_else(|| file_stem_display(&path)); - state.preset_status = Some(format!("Opened {name}")); - } - Err(error) => { - state.preset_status = Some(format!("Open failed: {error}")); + Message::CommitEnvelopeEdit(id) => { + if let Some((editing, draft)) = state.envelope_edit.take() { + if editing != id { + state.envelope_edit = Some((editing, draft)); + } else if let Ok(mut value) = draft.trim().trim_end_matches('%').parse::() { + if id_is_envelope_sustain(id) { + value /= 100.0; } + let def = param_def(id).expect("valid envelope parameter"); + value = value.clamp(def.min as f32, def.max as f32); + let index = id.as_index(); + state.active_gestures[index] = true; + state.shared.mark_gesture_begin_pending(id); + state.shared.set_param_outbound_only(id, value as f64); + state.active_gestures[index] = false; + state.shared.mark_gesture_end_pending(id); + } else { + state.envelope_edit = Some((id, draft)); } } } + Message::CancelEnvelopeEdit => { + state.envelope_edit = None; + return Task::none(); + } } Task::none() } -fn ensure_msynth_extension(mut path: PathBuf) -> PathBuf { - if path - .extension() - .is_none_or(|extension| extension != "msynth") - { - path.set_extension("msynth"); - } - path -} - -fn file_stem_display(path: &std::path::Path) -> String { - path.file_stem() - .map(|stem| stem.to_string_lossy().into_owned()) - .unwrap_or_else(|| path.display().to_string()) -} - const MOD_ROUTES: [ModRouteParamIds; 12] = [ ModRouteParamIds { source: ParamId::ModRoute1Source, @@ -403,6 +381,23 @@ fn assign_lfo_to_param(state: &mut State, lfo_index: usize, id: ParamId) { ); } +fn toggle_lfo_param_assignment(state: &mut State, lfo_index: usize, id: ParamId) { + let Some(target) = mod_target_for_param(id) else { + return; + }; + let shared = Arc::clone(&state.shared); + let set_param = |id, value| { + shared.mark_gesture_begin_pending(id); + shared.set_param_outbound_only(id, value as f64); + shared.mark_gesture_end_pending(id); + }; + if LFO_ASSIGNMENT_CONFIG.has_lfo_assignment(&state.shared.params, lfo_index, target as u8) { + LFO_ASSIGNMENT_CONFIG.unassign(&state.shared.params, lfo_index, target as u8, set_param); + } else { + assign_lfo_to_param(state, lfo_index, id); + } +} + fn param_has_lfo_assignment(state: &State, id: ParamId) -> bool { let Some(target) = mod_target_for_param(id) else { return false; @@ -479,6 +474,18 @@ fn mod_target_for_param(id: ParamId) -> Option { ParamId::F2Resonance => Some(ModTarget::Filter2Resonance), ParamId::F2EgAmount => Some(ModTarget::Filter2EgAmount), ParamId::F2Drive => Some(ModTarget::Filter2Drive), + ParamId::Osc1EgAttack => Some(ModTarget::Osc1EgAttack), + ParamId::Osc1EgDecay => Some(ModTarget::Osc1EgDecay), + ParamId::Osc1EgSustain => Some(ModTarget::Osc1EgSustain), + ParamId::Osc1EgRelease => Some(ModTarget::Osc1EgRelease), + ParamId::Osc2EgAttack => Some(ModTarget::Osc2EgAttack), + ParamId::Osc2EgDecay => Some(ModTarget::Osc2EgDecay), + ParamId::Osc2EgSustain => Some(ModTarget::Osc2EgSustain), + ParamId::Osc2EgRelease => Some(ModTarget::Osc2EgRelease), + ParamId::Osc3EgAttack => Some(ModTarget::Osc3EgAttack), + ParamId::Osc3EgDecay => Some(ModTarget::Osc3EgDecay), + ParamId::Osc3EgSustain => Some(ModTarget::Osc3EgSustain), + ParamId::Osc3EgRelease => Some(ModTarget::Osc3EgRelease), ParamId::AmpAttack => Some(ModTarget::AmpAttack), ParamId::AmpDecay => Some(ModTarget::AmpDecay), ParamId::AmpSustain => Some(ModTarget::AmpSustain), @@ -487,15 +494,10 @@ fn mod_target_for_param(id: ParamId) -> Option { ParamId::FilterDecay => Some(ModTarget::FilterDecay), ParamId::FilterSustain => Some(ModTarget::FilterSustain), ParamId::FilterRelease => Some(ModTarget::FilterRelease), - ParamId::PitchAttack => Some(ModTarget::PitchAttack), - ParamId::PitchDecay => Some(ModTarget::PitchDecay), - ParamId::PitchSustain => Some(ModTarget::PitchSustain), - ParamId::PitchRelease => Some(ModTarget::PitchRelease), ParamId::Volume => Some(ModTarget::OutputVolume), ParamId::Pan => Some(ModTarget::OutputPan), ParamId::Width => Some(ModTarget::OutputWidth), ParamId::NoiseLevel => Some(ModTarget::NoiseLevel), - ParamId::WaveshaperDrive => Some(ModTarget::WaveshaperDrive), ParamId::Portamento => Some(ModTarget::Portamento), ParamId::FlavorCutoff => Some(ModTarget::FlavorCutoff), ParamId::FilterBalance => Some(ModTarget::FilterBalance), @@ -511,64 +513,31 @@ fn assignment_color() -> Color { Color::from_rgb(1.0, 0.83, 0.10) } -fn small_knob<'a>( - id: ParamId, - label: &'a str, - state: &'a State, - step: f32, -) -> Element<'a, Message> { +fn synth_knob(id: ParamId, label: &str, state: &State, step: f32) -> Element<'static, Message> { let value = state.shared.params.get(id) as f32; let def = param_def(id).expect("valid param id"); let assigned = param_has_lfo_assignment(state, id); let display_value = visual_param_value(state, id, value); - let mut slider = arch_slider(def.min as f32..=def.max as f32, display_value, move |v| { - Message::SetParam(id, v) - }) - .step(step) - .double_click_reset(def.default as f32) - .on_release(Message::ReleaseParam(id)) - .fill_from_start() - .width(Length::Fixed(41.0)) - .height(Length::Fixed(41.0)); - if assigned { - slider = slider - .filled_color(Color::from_rgb(0.82, 0.58, 0.08)) - .handle_color(assignment_color()); - } - - let value_text = param_value_text(id, display_value, def.step); - - let content = container( - column![text(label).size(11), slider, text(value_text).size(10)] - .spacing(2) - .align_x(Alignment::Center), - ) - .width(Length::Fixed(50.0)) - .padding(2) - .style(move |_theme: &Theme| { - let border_color = if assigned { - assignment_color() - } else { - Color::TRANSPARENT - }; - container::Style { - background: assigned - .then(|| Background::Color(Color::from_rgba(1.0, 0.83, 0.10, 0.10))), - border: Border { - color: border_color, - width: if assigned { 1.0 } else { 0.0 }, - radius: 3.0.into(), - }, - ..container::Style::default() - } - }); + let content = knob( + Knob { + label: label.to_string(), + value: display_value, + range: def.min as f32..=def.max as f32, + default: def.default as f32, + step, + value_text: param_value_text(id, display_value, def.step), + assigned, + }, + move |value| Message::SetParam(id, value), + Message::ReleaseParam(id), + ); if mod_target_for_param(id).is_some() { mouse_area(content) .on_press(Message::AssignLfoToParam(id)) .into() } else { - content.into() + content } } @@ -591,97 +560,98 @@ fn param_control<'a>(id: ParamId, label: &'a str, state: &'a State) -> Element<' if def.flags == crate::synth::params::TOGGLE { small_checkbox(id, label, state) } else { - small_knob(id, label, state, def.step as f32) + synth_knob(id, label, state, def.step as f32) } } -fn osc_type_dropdown<'a>(id: ParamId, state: &'a State) -> Element<'a, Message> { - let value = state.shared.params.get(id) as f32; - let osc_type = OscType::from_u8(value as u8); - let options = vec![ - OscType::Classic, - OscType::Fm2, - OscType::Wavetable, - OscType::Window, - OscType::Modern, - OscType::ShNoise, - OscType::String, - OscType::Fm3, - OscType::Alias, - OscType::Twist, - ]; - let dropdown = maolan_baseview::iced::widget::pick_list(options, Some(osc_type), move |t| { - Message::SetParam(id, t as u8 as f32) - }) - .placeholder("Type") - .width(Length::Fixed(84.0)); - - container( - column![text("Type").size(11), dropdown] - .spacing(2) - .align_x(Alignment::Center), - ) - .width(Length::Fixed(90.0)) - .into() -} - -fn waveform_dropdown<'a>(state: &'a State, osc_index: usize) -> Element<'a, Message> { - let (type_id, wave_id) = match osc_index { - 0 => (ParamId::Osc1Type, ParamId::Osc1Waveform), - 1 => (ParamId::Osc2Type, ParamId::Osc2Waveform), - _ => (ParamId::Osc3Type, ParamId::Osc3Waveform), - }; - let osc_type = OscType::from_u8(state.shared.params.get(type_id) as u8); - let value = state.shared.params.get(wave_id) as f32; +const OSC_TYPES: &[OscType] = &[ + OscType::Off, + OscType::Classic, + OscType::Fm2, + OscType::Wavetable, + OscType::Window, + OscType::ShNoise, + OscType::String, + OscType::Fm3, + OscType::Alias, + OscType::Twist, +]; +fn waveform_options(osc_type: OscType) -> Vec<&'static str> { match osc_type { - OscType::Classic => { - let waveform = ClassicWaveform::from_u8(value as u8); - let options = vec![ - ClassicWaveform::Saw, - ClassicWaveform::Square, - ClassicWaveform::Pulse, - ClassicWaveform::Triangle, - ClassicWaveform::Sine, - ]; - let dropdown = - maolan_baseview::iced::widget::pick_list(options, Some(waveform), move |t| { - Message::SetParam(wave_id, t as u8 as f32) - }) - .placeholder("Wave") - .width(Length::Fixed(84.0)); - - container( - column![text("Wave").size(11), dropdown] - .spacing(2) - .align_x(Alignment::Center), - ) - .width(Length::Fixed(90.0)) - .into() - } - OscType::Modern => { - let waveform = ModernSubWaveform::from_u8(value as u8); - let options = vec![ - ModernSubWaveform::Square, - ModernSubWaveform::Triangle, - ModernSubWaveform::Saw, - ]; - let dropdown = - maolan_baseview::iced::widget::pick_list(options, Some(waveform), move |t| { - Message::SetParam(wave_id, t as u8 as f32) - }) - .placeholder("Wave") - .width(Length::Fixed(84.0)); - - container( - column![text("Wave").size(11), dropdown] - .spacing(2) - .align_x(Alignment::Center), - ) - .width(Length::Fixed(90.0)) - .into() - } - _ => param_control(wave_id, "Wave", state), + OscType::Off => vec!["Off"], + OscType::Classic => vec!["Saw", "Square", "Pulse", "Triangle", "Sine"], + OscType::Sine => vec!["Sine"], + OscType::Fm2 => vec!["2-Operator Sine FM"], + OscType::Wavetable => vec!["Selected Wavetable"], + OscType::Window => vec![ + "Sine Window", + "Hann Window", + "Hamming Window", + "Blackman Window", + "Triangle Window", + "Cosine Window", + "Saw Window", + "Square Window", + "Rectangle Window", + ], + OscType::ShNoise => vec!["Sample & Hold Noise"], + OscType::String => vec![ + "Noise Exciter", + "Impulse Exciter", + "Pluck", + "Hammer", + "Bow", + "Pink Noise Exciter", + "Sine Burst", + "Ramp Burst", + "Triangle Burst", + "Square Burst", + "Sweep Burst", + "Long Noise", + "Long Pink Noise", + "Half Sine", + "Two Sines", + "Cosine Burst", + ], + OscType::Fm3 => vec!["3-Operator Sine FM"], + OscType::Alias => vec![ + "Saw", + "Sine", + "Pulse", + "Triangle", + "Noise", + "Square", + "TX2 Rectified", + "TX3 Half-Rectified", + "TX4 Squared", + "TX5 Cubed", + "TX6 Absolute Squared", + "TX7 Absolute Cubed", + "TX8 Saw Blend", + "16-Partial Additive", + "Ramp", + "Alias Memory", + ], + OscType::Twist => vec![ + "Virtual Analog", + "Wavefolder", + "2-Operator FM", + "Harmonic", + "Noise", + "Chords", + "Filtered Noise", + "Analog Kick", + "Analog Snare", + "Vowels", + "Granular Cloud", + "Inharmonic String", + "Modal Resonator", + "Particle Noise", + "Analog Hi-Hat", + ], + OscType::AudioInput => vec!["Audio Input"], + OscType::Sample => vec!["Sample"], } } @@ -728,23 +698,73 @@ fn wavetable_dropdown<'a>(state: &'a State, osc_index: usize) -> Element<'a, Mes .into() } +const FILTER_TYPES: &[FilterType] = &[ + FilterType::Off, + FilterType::Lowpass, + FilterType::Bandpass, + FilterType::Highpass, + FilterType::Notch, + FilterType::Peak, + FilterType::CombPos, + FilterType::CombNeg, + FilterType::Allpass, + FilterType::DiodeLadder, + FilterType::Lowpass12dB, + FilterType::Highpass12dB, + FilterType::Bandpass12dB, + FilterType::LowShelf, + FilterType::HighShelf, + FilterType::Bell, + FilterType::Notch12dB, + FilterType::VintageLadder, + FilterType::CytomicLp, + FilterType::CytomicHp, + FilterType::CytomicBp, + FilterType::CytomicNotch, + FilterType::CytomicPeak, + FilterType::CytomicAp, + FilterType::CytomicBell, + FilterType::CytomicLs, + FilterType::CytomicHs, + FilterType::TriPole, + FilterType::SampleHold, + FilterType::Notch24dB, +]; + fn filter_type_dropdown<'a>(id: ParamId, state: &'a State) -> Element<'a, Message> { let value = state.shared.params.get(id) as f32; let filter_type = FilterType::from_u8(value as u8); - let options: Vec = (1..=48).map(FilterType::from_u8).collect(); + let options = FILTER_TYPES.to_vec(); let dropdown = maolan_baseview::iced::widget::pick_list(options, Some(filter_type), move |t| { Message::SetParam(id, t as u8 as f32) }) .placeholder("Type") .width(Length::Fixed(84.0)); - container( - column![text("Type").size(11), dropdown] - .spacing(2) - .align_x(Alignment::Center), - ) - .width(Length::Fixed(90.0)) - .into() + container(dropdown).width(Length::Fixed(90.0)).into() +} + +fn filter_routing_dropdown(state: &State) -> Element<'_, Message> { + let value = state.shared.params.get(ParamId::FilterRouting) as f32; + let routing = FilterRouting::from_u8(value as u8); + let options = vec![ + FilterRouting::Series, + FilterRouting::Parallel, + FilterRouting::Wide, + FilterRouting::Split, + FilterRouting::Serial2, + FilterRouting::Serial3, + FilterRouting::Dual2, + FilterRouting::Ring, + ]; + let dropdown = + maolan_baseview::iced::widget::pick_list(options, Some(routing), move |routing| { + Message::SetParam(ParamId::FilterRouting, routing as u8 as f32) + }) + .placeholder("Route") + .width(Length::Fixed(84.0)); + + container(dropdown).width(Length::Fixed(90.0)).into() } fn lfo_shape_dropdown<'a>(id: ParamId, state: &'a State) -> Element<'a, Message> { @@ -762,21 +782,49 @@ fn lfo_shape_dropdown<'a>(id: ParamId, state: &'a State) -> Element<'a, Message> LfoShape::StepSeq, LfoShape::Mseg, ]; - let dropdown = maolan_baseview::iced::widget::pick_list(options, Some(shape), move |shape| { + maolan_baseview::iced::widget::pick_list(options, Some(shape), move |shape| { Message::SetParam(id, shape as u8 as f32) }) - .placeholder("Shape") - .width(Length::Fixed(84.0)); - - container( - column![text("Shape").size(11), dropdown] - .spacing(2) - .align_x(Alignment::Center), - ) .width(Length::Fixed(90.0)) .into() } +fn named_enum_dropdown<'a>( + id: ParamId, + options: &'static [&'static str], + width: f32, + state: &'a State, +) -> Element<'a, Message> { + let index = (state.shared.params.get(id) as usize).min(options.len() - 1); + let selected = options[index]; + let dropdown = maolan_baseview::iced::widget::pick_list( + options.to_vec(), + Some(selected), + move |selected| { + let value = options + .iter() + .position(|option| *option == selected) + .unwrap_or_default(); + Message::SetParam(id, value as f32) + }, + ) + .width(Length::Fixed(width)); + container(dropdown).width(Length::Fixed(width + 6.0)).into() +} + +const OSC_FM_MODE_NAMES: &[&str] = &[ + "Off", + "Osc 1 → 2", + "Osc 2 → 3", + "Osc 1 → 2 → 3", + "Osc 1 → 3", + "Ring 1 × 2", + "Ring 2 × 3", + "Osc 2 → 1", + "Osc 3 → 1", + "Osc 3 → 2", +]; + fn param_value_text(id: ParamId, value: f32, step: f64) -> String { match id { ParamId::Osc1Octave | ParamId::Osc2Octave | ParamId::Osc3Octave => { @@ -785,6 +833,16 @@ fn param_value_text(id: ParamId, value: f32, step: f64) -> String { ParamId::F1Type | ParamId::F2Type | ParamId::NoiseFilterType => { FilterType::from_u8(value as u8).name().to_string() } + ParamId::VoicePriority => match value as u8 { + 0 => "Last", + 1 => "High", + 2 => "Low", + 3 => "Always Latest", + 4 => "Always Highest", + 5 => "Always Lowest", + _ => "Latest / Retrigger High", + } + .to_string(), _ if step >= 1.0 => format!("{value:.0}"), _ => format!("{value:.2}"), } @@ -902,6 +960,14 @@ fn knob_column<'a>(items: Vec>) -> Element<'a, Message> { c.into() } +fn lfo_side_controls<'a>(items: Vec>) -> Element<'a, Message> { + let mut c = column![].spacing(6).align_x(Alignment::Start); + for item in items { + c = c.push(item); + } + c.into() +} + fn tab_button(label: &'static str, active: bool, msg: Message) -> Element<'static, Message> { button( container(text(label).size(11)) @@ -921,6 +987,20 @@ fn tab_button(label: &'static str, active: bool, msg: Message) -> Element<'stati .into() } +fn tab_label(label: &'static str) -> Element<'static, Message> { + button( + container(text(label).size(11)) + .width(Length::Fixed(52.0)) + .align_x(Horizontal::Center), + ) + .style(|theme: &Theme, _| { + let mut base = button::primary(theme, button::Status::Active); + base.border.radius = 4.0.into(); + base + }) + .into() +} + fn lfo_tab_button(label: &'static str, index: usize, state: &State) -> Element<'static, Message> { let active = state.selected_lfo == index; let armed = state.lfo_assignment.armed_lfo() == Some(index); @@ -951,32 +1031,17 @@ fn lfo_tab_button(label: &'static str, index: usize, state: &State) -> Element<' .into() } -/// Synth preset import/open/save controls, rendered above the main top bar. -fn preset_bar<'a>(state: &'a State) -> Element<'a, Message> { - let open_button = button(text("Open").size(11)).on_press(Message::OpenSynthPreset); - let save_button = button(text("Save").size(11)).on_press(Message::SaveSynthPreset); - let import_button = button(text("Import").size(11)).on_press(Message::PickSurgePreset); - let status_text = text(state.preset_status.as_deref().unwrap_or("")).size(11); - - container( - row![open_button, save_button, import_button, status_text] - .spacing(8) - .align_y(Alignment::Center), - ) - .padding(4) - .into() -} - fn view(state: &State) -> Element<'_, Message> { let fm_panel = panel_no_title(knob_row(vec![ - param_control(ParamId::OscFmMode, "Mode", state), + named_enum_dropdown(ParamId::OscFmMode, OSC_FM_MODE_NAMES, 112.0, state), param_control(ParamId::OscFmDepth, "Depth", state), ])); - let filter_routing = panel_no_title(knob_row(vec![ - param_control(ParamId::FilterRouting, "Route", state), - param_control(ParamId::FilterBalance, "Balance", state), - ])); + let filter_routing = column![ + filter_routing_dropdown(state), + hslider(ParamId::FilterBalance, "Balance", state), + ] + .spacing(4); let top_bar = row![ panel( @@ -993,197 +1058,100 @@ fn view(state: &State) -> Element<'_, Message> { param_control(ParamId::Polyphony, "Poly", state), param_control(ParamId::PlayMode, "Mode", state), param_control(ParamId::VoicePriority, "Priority", state), - param_control(ParamId::Portamento, "Port", state), + param_control(ParamId::Portamento, "Portamento", state), param_control(ParamId::PitchBendRange, "Bend", state), + horizontal_multi_toggler( + ["Off", "2x"], + usize::from(state.shared.params.get(ParamId::Oversample) > 0.5), + |index| Message::SetParam(ParamId::Oversample, index as f32), + ) + .label_position(LabelPosition::Below) + .into(), ]) ), - panel( - "Scene", - knob_row(vec![ - param_control(ParamId::OscDrift, "Drift", state), - param_control(ParamId::NoiseColor, "Noise Col", state), - ]) - ), - panel( - "Global", - knob_row(vec![param_control( - ParamId::Oversample, - "Oversample", - state - )]) - ), - column![ - row![ - tab_button("FM", state.selected_routing == 0, Message::SelectRouting(0)), - tab_button( - "Filter", - state.selected_routing == 1, - Message::SelectRouting(1) - ), - ] - .spacing(4) - .align_y(Alignment::Center), - match state.selected_routing { - 0 => fm_panel, - _ => filter_routing, - }, - ] - .spacing(4), + fm_panel, ] .spacing(10) .align_y(Alignment::Start); - let osc1 = panel_no_title( - column![ - knob_row(vec![ - osc_type_dropdown(ParamId::Osc1Type, state), - waveform_dropdown(state, 0), - wavetable_dropdown(state, 0), - param_control(ParamId::Osc1Octave, "Oct", state), - param_control(ParamId::Osc1Semitone, "Semi", state), - param_control(ParamId::Osc1Fine, "Fine", state), - param_control(ParamId::Osc1Shape, "Shape", state), - param_control(ParamId::Osc1Skew, "Skew", state), - ]), - knob_row(vec![ - param_control(ParamId::Osc1Unison, "Unison", state), - param_control(ParamId::Osc1UnisonDetune, "UniDet", state), - param_control(ParamId::Osc1Level, "Level", state), - param_control(ParamId::Osc1UnisonSpread, "UniSpr", state), - knob_column(vec![ - param_control(ParamId::Osc1Sync, "Sync", state), - param_control(ParamId::Osc1Enabled, "On", state), - ]), - ]), - ] - .spacing(6) - .into(), - ); - - let osc2 = panel_no_title( - column![ - knob_row(vec![ - osc_type_dropdown(ParamId::Osc2Type, state), - waveform_dropdown(state, 1), - wavetable_dropdown(state, 1), - param_control(ParamId::Osc2Octave, "Oct", state), - param_control(ParamId::Osc2Semitone, "Semi", state), - param_control(ParamId::Osc2Fine, "Fine", state), - param_control(ParamId::Osc2Shape, "Shape", state), - param_control(ParamId::Osc2Skew, "Skew", state), - ]), - knob_row(vec![ - param_control(ParamId::Osc2Unison, "Unison", state), - param_control(ParamId::Osc2UnisonDetune, "UniDet", state), - param_control(ParamId::Osc2Level, "Level", state), - param_control(ParamId::Osc2UnisonSpread, "UniSpr", state), - knob_column(vec![ - param_control(ParamId::Osc2Sync, "Sync", state), - param_control(ParamId::Osc2Enabled, "On", state), - ]), - ]), - ] - .spacing(6) - .into(), - ); - - let osc3 = panel_no_title( - column![ - knob_row(vec![ - osc_type_dropdown(ParamId::Osc3Type, state), - waveform_dropdown(state, 2), - wavetable_dropdown(state, 2), - param_control(ParamId::Osc3Octave, "Oct", state), - param_control(ParamId::Osc3Semitone, "Semi", state), - param_control(ParamId::Osc3Fine, "Fine", state), - param_control(ParamId::Osc3Shape, "Shape", state), - param_control(ParamId::Osc3Formant, "Formant", state), - ]), - knob_row(vec![ - param_control(ParamId::Osc3Unison, "Unison", state), - param_control(ParamId::Osc3UnisonDetune, "UniDet", state), - param_control(ParamId::Osc3Level, "Level", state), - param_control(ParamId::Osc3UnisonSpread, "UniSpr", state), - knob_column(vec![ - param_control(ParamId::Osc2Sync, "Sync", state), - param_control(ParamId::Osc2Enabled, "On", state), - ]), - ]), - ] - .spacing(6) - .into(), - ); - - let osc_selector = row![ - tab_button("Osc 1", state.selected_osc == 0, Message::SelectOsc(0)), - tab_button("Osc 2", state.selected_osc == 1, Message::SelectOsc(1)), - tab_button("Osc 3", state.selected_osc == 2, Message::SelectOsc(2)), + let osc1 = column![ + knob_row(vec![ + wavetable_dropdown(state, 0), + param_control(ParamId::Osc1Octave, "Oct", state), + param_control(ParamId::Osc1Semitone, "Semi", state), + param_control(ParamId::Osc1Fine, "Fine", state), + param_control(ParamId::Osc1Shape, "Shape", state), + param_control(ParamId::Osc1Skew, "Skew", state), + ]), + knob_row(vec![ + param_control(ParamId::Osc1Unison, "Unison", state), + param_control(ParamId::Osc1UnisonDetune, "UniDet", state), + param_control(ParamId::Osc1Level, "Level", state), + param_control(ParamId::Osc1UnisonSpread, "UniSpr", state), + param_control(ParamId::Osc1Sync, "Sync", state), + ]), ] - .spacing(4) - .align_y(Alignment::Center); - - let selected_osc_panel = match state.selected_osc { - 0 => osc1, - 1 => osc2, - _ => osc3, - }; - - let filter1 = panel_no_title( - column![ - knob_row(vec![ - filter_type_dropdown(ParamId::F1Type, state), - param_control(ParamId::F1Subtype, "Sub", state), - param_control(ParamId::F1Cutoff, "Cut", state), - param_control(ParamId::F1Resonance, "Res", state), - param_control(ParamId::F1EgAmount, "EG", state), - param_control(ParamId::F1KeyTrack, "Key", state), - param_control(ParamId::F1Drive, "Drive", state), - ]), - knob_row(vec![param_control(ParamId::F1Enabled, "On", state),]), - ] - .spacing(6) - .into(), - ); - - let filter2 = panel_no_title( - column![ - knob_row(vec![ - filter_type_dropdown(ParamId::F2Type, state), - param_control(ParamId::F2Subtype, "Sub", state), - param_control(ParamId::F2Cutoff, "Cut", state), - param_control(ParamId::F2Resonance, "Res", state), - param_control(ParamId::F2EgAmount, "EG", state), - param_control(ParamId::F2KeyTrack, "Key", state), - param_control(ParamId::F2Drive, "Drive", state), - ]), - knob_row(vec![param_control(ParamId::F2Enabled, "On", state),]), - ] - .spacing(6) - .into(), - ); - - let waveshaper = panel_no_title( - column![ - knob_row(vec![ - param_control(ParamId::WaveshaperShape, "Shape", state), - param_control(ParamId::WaveshaperDrive, "Drive", state), - param_control(ParamId::WaveshaperMix, "Mix", state), - ]), - knob_row(vec![param_control(ParamId::WaveshaperEnabled, "On", state),]), - ] - .spacing(6) - .into(), - ); - - let amp_eg = envelope::panel( - state, - [ - ParamId::AmpAttack, - ParamId::AmpDecay, - ParamId::AmpSustain, - ParamId::AmpRelease, - ], - ); + .spacing(6); + + let osc2 = column![ + knob_row(vec![ + wavetable_dropdown(state, 1), + param_control(ParamId::Osc2Octave, "Oct", state), + param_control(ParamId::Osc2Semitone, "Semi", state), + param_control(ParamId::Osc2Fine, "Fine", state), + param_control(ParamId::Osc2Shape, "Shape", state), + param_control(ParamId::Osc2Skew, "Skew", state), + ]), + knob_row(vec![ + param_control(ParamId::Osc2Unison, "Unison", state), + param_control(ParamId::Osc2UnisonDetune, "UniDet", state), + param_control(ParamId::Osc2Level, "Level", state), + param_control(ParamId::Osc2UnisonSpread, "UniSpr", state), + param_control(ParamId::Osc2Sync, "Sync", state), + ]), + ] + .spacing(6); + + let osc3 = column![ + knob_row(vec![ + wavetable_dropdown(state, 2), + param_control(ParamId::Osc3Octave, "Oct", state), + param_control(ParamId::Osc3Semitone, "Semi", state), + param_control(ParamId::Osc3Fine, "Fine", state), + param_control(ParamId::Osc3Shape, "Shape", state), + param_control(ParamId::Osc3Formant, "Formant", state), + ]), + knob_row(vec![ + param_control(ParamId::Osc3Unison, "Unison", state), + param_control(ParamId::Osc3UnisonDetune, "UniDet", state), + param_control(ParamId::Osc3Level, "Level", state), + param_control(ParamId::Osc3UnisonSpread, "UniSpr", state), + param_control(ParamId::Osc3Sync, "Sync", state), + ]), + ] + .spacing(6); + + let filter1 = knob_row(vec![ + filter_type_dropdown(ParamId::F1Type, state), + param_control(ParamId::F1Cutoff, "Cut", state), + param_control(ParamId::F1Resonance, "Res", state), + param_control(ParamId::F1EgAmount, "EG", state), + param_control(ParamId::F1KeyTrack, "Key", state), + ]); + + let filter2 = knob_row(vec![ + filter_type_dropdown(ParamId::F2Type, state), + param_control(ParamId::F2Cutoff, "Cut", state), + param_control(ParamId::F2Resonance, "Res", state), + param_control(ParamId::F2EgAmount, "EG", state), + param_control(ParamId::F2KeyTrack, "Key", state), + ]); + + let envelope_ids = super::params::OSC_ENVELOPE_IDS + .get(state.selected_osc) + .copied() + .unwrap_or(super::params::AMP_ENVELOPE_IDS); + let amp_eg = envelope::panel(state, envelope_ids); let filter_eg = envelope::panel( state, @@ -1195,100 +1163,51 @@ fn view(state: &State) -> Element<'_, Message> { ], ); - let pitch_eg = envelope::panel( - state, - [ - ParamId::PitchAttack, - ParamId::PitchDecay, - ParamId::PitchSustain, - ParamId::PitchRelease, - ], + let filters = panel_no_title( + column![filter1, filter2, row![filter_routing, filter_eg].spacing(6),] + .spacing(6) + .into(), ); - let filter_selector = row![ - tab_button( - "Filter 1", - state.selected_filter == 0, - Message::SelectFilter(0) - ), - tab_button( - "Filter 2", - state.selected_filter == 1, - Message::SelectFilter(1) - ), - ] - .spacing(4) - .align_y(Alignment::Center); - - let selected_filter_panel = match state.selected_filter { - 0 => filter1, - _ => filter2, - }; - - let eg_selector = row![ - tab_button("Amp", state.selected_eg == 0, Message::SelectEg(0)), - tab_button("Filter", state.selected_eg == 1, Message::SelectEg(1)), - tab_button("Pitch", state.selected_eg == 2, Message::SelectEg(2)), + let noise = column![ + knob_row(vec![ + param_control(ParamId::NoiseType, "Type", state), + param_control(ParamId::NoiseLevel, "Level", state), + param_control(ParamId::NoiseUnison, "Voices", state), + param_control(ParamId::NoiseUnisonSpread, "Spread", state), + param_control(ParamId::NoiseFilterType, "FType", state), + ]), + knob_row(vec![ + param_control(ParamId::NoiseFilterCutoff, "FCut", state), + param_control(ParamId::NoiseFilterResonance, "FRes", state), + knob_column(vec![ + param_control(ParamId::NoiseFilterEnabled, "FOn", state), + param_control(ParamId::NoiseEnabled, "On", state), + ]) + ]), ] - .spacing(4) - .align_y(Alignment::Center); - - let selected_eg_panel = match state.selected_eg { - 0 => amp_eg, - 1 => filter_eg, - _ => pitch_eg, - }; + .spacing(6); - let noise = panel_no_title( - column![ - knob_row(vec![ - param_control(ParamId::NoiseType, "Type", state), - param_control(ParamId::NoiseLevel, "Level", state), - param_control(ParamId::NoiseFilterType, "FType", state), - ]), - knob_row(vec![ - param_control(ParamId::NoiseFilterCutoff, "FCut", state), - param_control(ParamId::NoiseFilterResonance, "FRes", state), - knob_column(vec![ - param_control(ParamId::NoiseFilterEnabled, "FOn", state), - param_control(ParamId::NoiseEnabled, "On", state), - ]) - ]), - ] - .spacing(6) - .into(), - ); - - let flavor = panel_no_title(knob_row(vec![ - param_control(ParamId::FlavorType, "Type", state), - param_control(ParamId::FlavorCutoff, "Cut", state), - param_control(ParamId::FlavorResonance, "Res", state), - ])); - - let misc_selector = row![ - tab_button("Shaper", state.selected_misc == 0, Message::SelectMisc(0)), - tab_button("Noise", state.selected_misc == 1, Message::SelectMisc(1)), - tab_button("Flavor", state.selected_misc == 2, Message::SelectMisc(2)), + let osc_selector = row![ + tab_button("Osc 1", state.selected_osc == 0, Message::SelectOsc(0)), + tab_button("Osc 2", state.selected_osc == 1, Message::SelectOsc(1)), + tab_button("Osc 3", state.selected_osc == 2, Message::SelectOsc(2)), + tab_button("Noise", state.selected_osc == 3, Message::SelectOsc(3)), ] .spacing(4) .align_y(Alignment::Center); - let selected_misc_panel = match state.selected_misc { - 0 => waveshaper, - 1 => noise, - _ => flavor, + let selected_osc_panel = match state.selected_osc { + 0 => osc1, + 1 => osc2, + 2 => osc3, + _ => noise, }; + let oscillator_display = + oscillator_display::OscillatorDisplay::new(state.shared.clone(), state.selected_osc).view(); - let right_column = column![ - filter_selector, - selected_filter_panel, - row![ - column![eg_selector, selected_eg_panel].spacing(10), - column![misc_selector, selected_misc_panel].spacing(10), - ] - .spacing(10), - ] - .spacing(10); + let filter_selector = row![tab_label("Filters")].align_y(Alignment::Center); + let right_column = column![filter_selector, filters].spacing(6); let lfo1 = panel_no_title(knob_row(vec![ lfo_shape_dropdown(ParamId::Lfo1Shape, state), @@ -1297,7 +1216,7 @@ fn view(state: &State) -> Element<'_, Message> { param_control(ParamId::Lfo1Deform, "Deform", state), param_control(ParamId::Lfo1Phase, "Phase", state), param_control(ParamId::Lfo1Trigger, "Trig", state), - knob_column(vec![ + lfo_side_controls(vec![ param_control(ParamId::Lfo1Unipolar, "Uni", state), param_control(ParamId::Lfo1SyncMode, "Sync", state), ]), @@ -1310,7 +1229,7 @@ fn view(state: &State) -> Element<'_, Message> { param_control(ParamId::Lfo2Deform, "Deform", state), param_control(ParamId::Lfo2Phase, "Phase", state), param_control(ParamId::Lfo2Trigger, "Trig", state), - knob_column(vec![ + lfo_side_controls(vec![ param_control(ParamId::Lfo2Unipolar, "Uni", state), param_control(ParamId::Lfo2SyncMode, "Sync", state), ]), @@ -1323,7 +1242,7 @@ fn view(state: &State) -> Element<'_, Message> { param_control(ParamId::Lfo3Deform, "Deform", state), param_control(ParamId::Lfo3Phase, "Phase", state), param_control(ParamId::Lfo3Trigger, "Trig", state), - knob_column(vec![ + lfo_side_controls(vec![ param_control(ParamId::Lfo3Unipolar, "Uni", state), param_control(ParamId::Lfo3SyncMode, "Sync", state), ]), @@ -1336,7 +1255,7 @@ fn view(state: &State) -> Element<'_, Message> { param_control(ParamId::Lfo4Deform, "Deform", state), param_control(ParamId::Lfo4Phase, "Phase", state), param_control(ParamId::Lfo4Trigger, "Trig", state), - knob_column(vec![ + lfo_side_controls(vec![ param_control(ParamId::Lfo4Unipolar, "Uni", state), param_control(ParamId::Lfo4SyncMode, "Sync", state), ]), @@ -1349,7 +1268,7 @@ fn view(state: &State) -> Element<'_, Message> { param_control(ParamId::Lfo5Deform, "Deform", state), param_control(ParamId::Lfo5Phase, "Phase", state), param_control(ParamId::Lfo5Trigger, "Trig", state), - knob_column(vec![ + lfo_side_controls(vec![ param_control(ParamId::Lfo5Unipolar, "Uni", state), param_control(ParamId::Lfo5SyncMode, "Sync", state), ]), @@ -1362,7 +1281,7 @@ fn view(state: &State) -> Element<'_, Message> { param_control(ParamId::Lfo6Deform, "Deform", state), param_control(ParamId::Lfo6Phase, "Phase", state), param_control(ParamId::Lfo6Trigger, "Trig", state), - knob_column(vec![ + lfo_side_controls(vec![ param_control(ParamId::Lfo6Unipolar, "Uni", state), param_control(ParamId::Lfo6SyncMode, "Sync", state), ]), @@ -1388,20 +1307,28 @@ fn view(state: &State) -> Element<'_, Message> { _ => lfo6, }; - let left_column = column![ + let oscillator_section = column![ osc_selector, - selected_osc_panel, + panel_no_title( + row![ + oscillator_display, + column![selected_osc_panel, amp_eg].spacing(6), + ] + .spacing(6) + .into() + ), + ] + .spacing(6) + .height(Length::Shrink); + + let main_content = column![ + row![oscillator_section, right_column].spacing(10), lfo_selector, selected_lfo_panel ] .spacing(10); - let main_content = row![left_column, right_column] - .spacing(12) - .align_y(Alignment::Start); - - let preset_bar = preset_bar(state); - let content = column![preset_bar, top_bar, main_content] + let content = column![preset::bar(&state.preset_ui), top_bar, main_content] .spacing(12) .padding(16) .align_x(Alignment::Start); @@ -1418,10 +1345,41 @@ fn theme(_state: &State) -> Theme { Theme::TokyoNight } +fn cancel_envelope_edit_on_escape( + event: maolan_baseview::iced::Event, + _status: maolan_baseview::iced::event::Status, + _window: maolan_baseview::iced::window::Id, +) -> Option { + if matches!( + event, + maolan_baseview::iced::Event::Keyboard( + maolan_baseview::iced::keyboard::Event::KeyPressed { + key: maolan_baseview::iced::keyboard::Key::Named( + maolan_baseview::iced::keyboard::key::Named::Escape + ), + .. + } + ) + ) { + Some(Message::CancelEnvelopeEdit) + } else { + None + } +} + 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) - .subscription(|_state| maolan_baseview::iced::poll_events().map(|_| Message::Poll)) + .subscription(|state| { + let mut subscriptions = + vec![maolan_baseview::iced::poll_events().map(|_| Message::Poll)]; + if state.envelope_edit.is_some() { + subscriptions.push(maolan_baseview::iced::event::listen_raw( + cancel_envelope_edit_on_escape, + )); + } + maolan_baseview::iced::Subscription::batch(subscriptions) + }) .theme(theme) .run() } @@ -1547,7 +1505,14 @@ impl GuiBridge { #[cfg(test)] mod tests { - use super::{ParamId, param_value_text}; + use super::{FILTER_TYPES, FilterType, ParamId, param_def, param_value_text}; + + #[test] + fn filter_types_start_with_off_and_defaults_are_preserved() { + assert_eq!(FILTER_TYPES.first(), Some(&FilterType::Off)); + assert_eq!(param_def(ParamId::F1Type).unwrap().default, 1.0); + assert_eq!(param_def(ParamId::F2Type).unwrap().default, 0.0); + } #[test] fn octave_readout_shows_musical_offset() { @@ -1557,4 +1522,33 @@ mod tests { assert_eq!(param_value_text(ParamId::Osc1Octave, 4.0, 1.0), "1"); assert_eq!(param_value_text(ParamId::Osc1Octave, 5.0, 1.0), "2"); } + + #[test] + fn priority_readout_shows_descriptive_names() { + let names = [ + "Last", + "High", + "Low", + "Always Latest", + "Always Highest", + "Always Lowest", + "Latest / Retrigger High", + ]; + for (value, name) in names.into_iter().enumerate() { + assert_eq!( + param_value_text(ParamId::VoicePriority, value as f32, 1.0), + name + ); + } + } + + #[test] + fn sub_dependent_filter_types_are_not_available() { + let excluded = [ + 9, 10, 11, 13, 14, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + ]; + for id in excluded { + assert!(FILTER_TYPES.iter().all(|filter| *filter as u8 != id)); + } + } } diff --git a/src/synth/gui/envelope.rs b/src/synth/gui/envelope.rs index 9a7e65e..b05bcd0 100644 --- a/src/synth/gui/envelope.rs +++ b/src/synth/gui/envelope.rs @@ -1,6 +1,6 @@ use super::{Message, ParamId, State, param_def, param_has_lfo_assignment, visual_param_value}; use maolan_widgets::{ - adsr::{AdsrMessage, adsr_envelope}, + adsr::{AdsrMessage, adsr_envelope_with_edit}, iced::{Element, Length, widget::container}, }; @@ -12,12 +12,32 @@ pub(super) fn panel(state: &State, ids: [ParamId; 4]) -> Element<'_, Message> { }); let steps = ids.map(|id| param_def(id).expect("valid parameter").step as f32); let assigned = ids.map(|id| param_has_lfo_assignment(state, id)); - let graph = adsr_envelope(values, ranges, steps, assigned).map(move |message| { - let index = match message { + let editing_index = state + .envelope_edit + .as_ref() + .and_then(|(id, _)| ids.iter().position(|candidate| candidate == id)); + let edit_value = state + .envelope_edit + .as_ref() + .map_or("", |(_, value)| value.as_str()); + let graph = adsr_envelope_with_edit( + values, + ranges, + steps, + assigned, + editing_index, + edit_value, + state.envelope_input_id.clone(), + ) + .map(move |message| { + let index = match &message { AdsrMessage::Change(i, _) | AdsrMessage::Release(i) | AdsrMessage::Reset(i) - | AdsrMessage::Assign(i) => i, + | AdsrMessage::Assign(i) + | AdsrMessage::Edit(i) + | AdsrMessage::EditChanged(i, _) + | AdsrMessage::EditSubmit(i) => *i, }; let id = ids[index]; match message { @@ -25,6 +45,9 @@ pub(super) fn panel(state: &State, ids: [ParamId; 4]) -> Element<'_, Message> { AdsrMessage::Release(_) => Message::ReleaseParam(id), AdsrMessage::Reset(_) => Message::ResetParam(id), AdsrMessage::Assign(_) => Message::AssignLfoToParam(id), + AdsrMessage::Edit(_) => Message::BeginEnvelopeEdit(id), + AdsrMessage::EditChanged(_, value) => Message::ChangeEnvelopeEdit(id, value), + AdsrMessage::EditSubmit(_) => Message::CommitEnvelopeEdit(id), } }); container(graph).width(Length::Fixed(220.0)).into() diff --git a/src/synth/gui/oscillator_display.rs b/src/synth/gui/oscillator_display.rs new file mode 100644 index 0000000..c119f80 --- /dev/null +++ b/src/synth/gui/oscillator_display.rs @@ -0,0 +1,382 @@ +use std::sync::Arc; + +use maolan_baseview::iced::{ + Color, Element, Length, Point, Rectangle, Renderer, Theme, mouse, + widget::{ + Space, Stack, canvas, + canvas::{Frame, Geometry, Path, Program, Stroke}, + container, mouse_area, row, text, + }, +}; + +use crate::{ + common::{ + filter::FilterType, + wavetable_factory::{CUSTOM_WAVETABLE_LABEL, FACTORY_COUNT, FACTORY_NAMES, factory_table}, + }, + synth::{ + dsp::{ + AliasWaveform, ClassicWaveform, ExciterType, NoiseColorMode, NoiseGenerator, NoiseType, + OscType, Oscillator, WindowType, + }, + params::ParamId, + plugin::SharedState, + }, +}; + +const SAMPLE_RATE: f32 = 48_000.0; +const POINT_COUNT: usize = 512; + +pub struct OscillatorDisplay { + shared: Arc, + osc_index: usize, +} + +impl OscillatorDisplay { + pub fn new(shared: Arc, osc_index: usize) -> Self { + Self { shared, osc_index } + } + + pub fn view(self) -> Element<'static, super::Message> { + let (osc_type, waveform) = display_labels(&self.shared, self.osc_index); + let type_shared = self.shared.clone(); + let type_label: Element<'static, super::Message> = if self.osc_index == 3 { + text(osc_type).size(11).into() + } else { + mouse_area(text(osc_type).size(11)) + .on_scroll(move |delta| scroll_osc_type(&type_shared, self.osc_index, delta)) + .into() + }; + let waveform_shared = self.shared.clone(); + let waveform_label = mouse_area(text(waveform).size(11)) + .on_scroll(move |delta| scroll_waveform(&waveform_shared, self.osc_index, delta)); + let waveform_canvas = canvas(self) + .width(Length::Fixed(220.0)) + .height(Length::Fill) + .into(); + let labels = container(row![ + type_label, + Space::new().width(Length::Fill), + waveform_label, + ]) + .width(Length::Fill) + .padding(6); + + Stack::with_children(vec![waveform_canvas, labels.into()]).into() + } +} + +impl Program for OscillatorDisplay { + type State = (); + + fn draw( + &self, + _state: &Self::State, + renderer: &Renderer, + _theme: &Theme, + bounds: Rectangle, + _cursor: maolan_baseview::iced::mouse::Cursor, + ) -> Vec { + let samples = render_samples(&self.shared, self.osc_index); + let mut frame = Frame::new(renderer, bounds.size()); + frame.fill_rectangle( + Point::ORIGIN, + bounds.size(), + Color::from_rgb(0.075, 0.09, 0.115), + ); + + let center_y = bounds.height * 0.5; + let center = Path::line( + Point::new(0.0, center_y), + Point::new(bounds.width, center_y), + ); + frame.stroke( + ¢er, + Stroke::default() + .with_color(Color::from_rgba(0.55, 0.60, 0.66, 0.22)) + .with_width(1.0), + ); + + let path = Path::new(|builder| { + for (index, sample) in samples.iter().copied().enumerate() { + let x = index as f32 / (POINT_COUNT - 1) as f32 * bounds.width; + let y = center_y - sample.clamp(-1.0, 1.0) * center_y * 0.9; + if index == 0 { + builder.move_to(Point::new(x, y)); + } else { + builder.line_to(Point::new(x, y)); + } + } + }); + frame.stroke( + &path, + Stroke::default() + .with_color(Color::from_rgb(0.72, 0.58, 0.28)) + .with_width(1.6), + ); + + vec![frame.into_geometry()] + } +} + +fn scroll_osc_type( + shared: &SharedState, + osc_index: usize, + delta: mouse::ScrollDelta, +) -> super::Message { + let type_id = match osc_index { + 0 => ParamId::Osc1Type, + 1 => ParamId::Osc2Type, + _ => ParamId::Osc3Type, + }; + let current = OscType::from_u8(shared.params.get(type_id) as u8); + let current_index = super::OSC_TYPES + .iter() + .position(|&osc_type| osc_type == current) + .unwrap_or(0); + let next_index = offset_index( + current_index, + super::OSC_TYPES.len(), + scroll_direction(delta), + ); + super::Message::SetParam(type_id, super::OSC_TYPES[next_index] as u8 as f32) +} + +fn scroll_waveform( + shared: &SharedState, + osc_index: usize, + delta: mouse::ScrollDelta, +) -> super::Message { + let direction = scroll_direction(delta); + if osc_index == 3 { + let current = shared.params.get(ParamId::NoiseType) as usize; + let next = offset_index(current, 3, direction); + return super::Message::SetParam(ParamId::NoiseType, next as f32); + } + + let (type_id, waveform_id, shape_id, wavetable_id) = match osc_index { + 0 => ( + ParamId::Osc1Type, + ParamId::Osc1Waveform, + ParamId::Osc1Shape, + ParamId::Osc1Wavetable, + ), + 1 => ( + ParamId::Osc2Type, + ParamId::Osc2Waveform, + ParamId::Osc2Shape, + ParamId::Osc2Wavetable, + ), + _ => ( + ParamId::Osc3Type, + ParamId::Osc3Waveform, + ParamId::Osc3Shape, + ParamId::Osc3Wavetable, + ), + }; + let osc_type = OscType::from_u8(shared.params.get(type_id) as u8); + if osc_type == OscType::Wavetable { + let current = shared.params.get(wavetable_id) as usize; + let next = offset_index(current, FACTORY_COUNT, direction); + return super::Message::SetParam(wavetable_id, next as f32); + } + + let options = super::waveform_options(osc_type); + let current = if osc_type == OscType::Twist { + let shape = shared.params.get(shape_id) as f32; + let model = ((shape.clamp(0.0, 1.0) * 16.0) as usize).min(15); + if model >= 4 { model - 1 } else { model } + } else { + shared.params.get(waveform_id) as usize + }; + let next = offset_index(current, options.len(), direction); + if osc_type == OscType::Twist { + let model = if next >= 4 { next + 1 } else { next }; + super::Message::SetParam(shape_id, model as f32 / 16.0) + } else { + super::Message::SetParam(waveform_id, next as f32) + } +} + +fn scroll_direction(delta: mouse::ScrollDelta) -> isize { + let y = match delta { + mouse::ScrollDelta::Lines { y, .. } | mouse::ScrollDelta::Pixels { y, .. } => y, + }; + if y < 0.0 { + 1 + } else if y > 0.0 { + -1 + } else { + 0 + } +} + +fn offset_index(current: usize, len: usize, direction: isize) -> usize { + let current = current.min(len - 1); + if direction < 0 { + current.saturating_sub(1) + } else if direction > 0 { + (current + 1).min(len - 1) + } else { + current + } +} + +fn display_labels(shared: &SharedState, osc_index: usize) -> (String, String) { + if osc_index == 3 { + let noise_type = match NoiseType::from_u8(shared.params.get(ParamId::NoiseType) as u8) { + NoiseType::White => "White", + NoiseType::Pink => "Pink", + NoiseType::Brown => "Brown", + }; + return ("Noise".to_string(), noise_type.to_string()); + } + + let (type_id, waveform_id, shape_id, wavetable_id) = match osc_index { + 0 => ( + ParamId::Osc1Type, + ParamId::Osc1Waveform, + ParamId::Osc1Shape, + ParamId::Osc1Wavetable, + ), + 1 => ( + ParamId::Osc2Type, + ParamId::Osc2Waveform, + ParamId::Osc2Shape, + ParamId::Osc2Wavetable, + ), + _ => ( + ParamId::Osc3Type, + ParamId::Osc3Waveform, + ParamId::Osc3Shape, + ParamId::Osc3Wavetable, + ), + }; + let osc_type = OscType::from_u8(shared.params.get(type_id) as u8); + let options = super::waveform_options(osc_type); + let selected_index = if osc_type == OscType::Twist { + let shape = shared.params.get(shape_id) as f32; + let model = ((shape.clamp(0.0, 1.0) * 16.0) as usize).min(15); + if model >= 4 { model - 1 } else { model } + } else { + shared.params.get(waveform_id) as usize + }; + let waveform = if osc_type == OscType::Wavetable { + let table_index = shared.params.get(wavetable_id) as usize; + if table_index >= FACTORY_COUNT { + CUSTOM_WAVETABLE_LABEL + } else { + FACTORY_NAMES[table_index] + } + } else { + options.get(selected_index).copied().unwrap_or("") + }; + + (osc_type.to_string(), waveform.to_string()) +} + +fn render_samples(shared: &SharedState, osc_index: usize) -> Vec { + if osc_index == 3 { + return render_noise_samples(shared); + } + + let (type_id, waveform_id, shape_id, skew_id, formant_id, wavetable_id) = match osc_index { + 0 => ( + ParamId::Osc1Type, + ParamId::Osc1Waveform, + ParamId::Osc1Shape, + ParamId::Osc1Skew, + ParamId::Osc3Formant, + ParamId::Osc1Wavetable, + ), + 1 => ( + ParamId::Osc2Type, + ParamId::Osc2Waveform, + ParamId::Osc2Shape, + ParamId::Osc2Skew, + ParamId::Osc3Formant, + ParamId::Osc2Wavetable, + ), + _ => ( + ParamId::Osc3Type, + ParamId::Osc3Waveform, + ParamId::Osc3Shape, + ParamId::Osc3Skew, + ParamId::Osc3Formant, + ParamId::Osc3Wavetable, + ), + }; + let get = |id| shared.params.get(id) as f32; + let osc_type = OscType::from_u8(get(type_id) as u8); + let waveform = get(waveform_id) as u8; + let mut oscillator = Oscillator::new(osc_type, SAMPLE_RATE); + oscillator.reset_to_zero(); + oscillator.set_unison(1, 0.0); + oscillator.set_freq_hz(SAMPLE_RATE / POINT_COUNT as f32); + oscillator.set_shape(get(shape_id)); + oscillator.set_skew(get(skew_id)); + oscillator.set_formant(get(formant_id)); + + match &mut oscillator { + Oscillator::Classic(osc) => osc.set_waveform(ClassicWaveform::from_u8(waveform)), + Oscillator::Window(osc) => osc.set_window_type(WindowType::from_u8(waveform)), + Oscillator::String(osc) => osc.set_exciter(ExciterType::from_u8(waveform)), + Oscillator::Alias(osc) => osc.set_waveform(AliasWaveform::from_u8(waveform)), + _ => {} + } + + let table_index = get(wavetable_id) as usize; + let wavetable = if table_index >= FACTORY_COUNT { + shared.custom_wavetables[osc_index].lock().clone() + } else { + factory_table(table_index) + }; + oscillator.set_wavetable(wavetable.or_else(|| factory_table(0))); + + (0..POINT_COUNT) + .map(|_| { + let (left, right) = oscillator.next(0.0, 0.0, 0.0); + (left + right) * 0.5 + }) + .collect() +} + +fn render_noise_samples(shared: &SharedState) -> Vec { + let get = |id| shared.params.get(id) as f32; + let mut noise = NoiseGenerator::new(SAMPLE_RATE); + noise.noise_type = NoiseType::from_u8(get(ParamId::NoiseType) as u8); + noise.color = get(ParamId::NoiseColor); + noise.color_mode = if get(ParamId::NoiseColorMode) == 0.0 { + NoiseColorMode::Tilt + } else { + NoiseColorMode::Legacy + }; + noise.filter_enabled = get(ParamId::NoiseFilterEnabled) > 0.5; + if noise.filter_enabled { + let cutoff = get(ParamId::NoiseFilterCutoff); + let resonance = get(ParamId::NoiseFilterResonance); + noise + .filter + .set_filter_type(FilterType::from_u8(get(ParamId::NoiseFilterType) as u8)); + noise.filter.set_params(cutoff, resonance); + noise.filter.prepare_block(cutoff, resonance, 1); + } + + (0..POINT_COUNT).map(|_| noise.next()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classic_saw_preview_is_finite_and_nonzero() { + let shared = SharedState::default(); + let samples = render_samples(&shared, 0); + assert_eq!(samples.len(), POINT_COUNT); + assert!(samples.iter().all(|sample| sample.is_finite())); + let min = samples.iter().copied().fold(f32::INFINITY, f32::min); + let max = samples.iter().copied().fold(f32::NEG_INFINITY, f32::max); + assert!(max - min > 0.5, "unexpected preview range: {min}..{max}"); + } +} diff --git a/src/synth/mod.rs b/src/synth/mod.rs index 8050a5d..9e6820d 100644 --- a/src/synth/mod.rs +++ b/src/synth/mod.rs @@ -3,9 +3,7 @@ pub mod gui; mod params; pub mod plugin; mod preset; -pub mod render; mod state; -pub mod surge; pub mod wavetable; pub use plugin::{clap_create_plugin, clap_descriptor_ptr}; diff --git a/src/synth/params.rs b/src/synth/params.rs index 4bbf597..5fe4ead 100644 --- a/src/synth/params.rs +++ b/src/synth/params.rs @@ -5,9 +5,27 @@ use maolan_clap::ffi::{ use crate::common::wavetable_factory::FACTORY_COUNT; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[repr(u16)] -pub enum ParamId { +// Generate conversion from the variants themselves: parameter IDs contain retired slots. +macro_rules! synth_param_ids { + ($($name:ident = $value:literal,)*) => { + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[repr(u16)] + pub enum ParamId { + $($name = $value,)* + } + + impl ParamId { + pub fn from_raw(id: u32) -> Option { + match id { + $($value => Some(Self::$name),)* + _ => None, + } + } + } + }; +} + +synth_param_ids! { Osc1Type = 0, Osc1Octave = 1, Osc1Semitone = 2, @@ -72,12 +90,6 @@ pub enum ParamId { FilterRelease = 54, FilterEgMode = 55, - PitchAttack = 56, - PitchDecay = 57, - PitchSustain = 58, - PitchRelease = 59, - PitchEgMode = 60, - Lfo1Rate = 61, Lfo1Shape = 62, Lfo1Amount = 63, @@ -149,11 +161,6 @@ pub enum ParamId { NoiseFilterEnabled = 124, NoiseEnabled = 125, - WaveshaperShape = 126, - WaveshaperDrive = 127, - WaveshaperMix = 128, - WaveshaperEnabled = 129, - FlavorType = 130, FlavorCutoff = 131, FlavorResonance = 132, @@ -316,7 +323,6 @@ pub enum ParamId { PitchBendDown = 267, AmpEgRetrigger = 268, FilterEgRetrigger = 269, - PitchEgRetrigger = 270, StealMode = 271, PortamentoSync = 272, PortamentoRetrigger = 273, @@ -330,10 +336,8 @@ pub enum ParamId { Lfo6EnvTempoSync = 281, AmpEgTempoSync = 282, FilterEgTempoSync = 283, - PitchEgTempoSync = 284, StepSeqTrigAmp = 285, StepSeqTrigFilter = 286, - StepSeqTrigPitch = 287, F1FeedbackDrive = 288, F2FeedbackDrive = 289, Osc1FmDepth = 290, @@ -366,12 +370,10 @@ pub enum ParamId { Fm2Feedback = 317, AmpEgUberRelease = 318, FilterEgUberRelease = 319, - PitchEgUberRelease = 320, StringStereoSpread = 321, WavetableKeytrack = 322, AmpEgGatedRelease = 323, FilterEgGatedRelease = 324, - PitchEgGatedRelease = 325, TuningScale = 326, TuningRoot = 327, TuningSclIndex = 393, @@ -713,9 +715,6 @@ pub enum ParamId { FilterEgAttackCurve = 659, FilterEgDecayCurve = 660, FilterEgReleaseCurve = 661, - PitchEgAttackCurve = 662, - PitchEgDecayCurve = 663, - PitchEgReleaseCurve = 664, Osc1Solo = 665, Osc2Solo = 666, Osc3Solo = 667, @@ -729,10 +728,8 @@ pub enum ParamId { TwistLpgDecay = 675, AmpEgCorrectAnalog = 676, FilterEgCorrectAnalog = 677, - PitchEgCorrectAnalog = 678, MsegRetrigAmp = 679, MsegRetrigFilter = 680, - MsegRetrigPitch = 681, AliasPartial1 = 682, AliasPartial2 = 683, AliasPartial3 = 684, @@ -772,10 +769,25 @@ pub enum ParamId { Reserved717 = 717, Reserved718 = 718, Reserved719 = 719, + Osc1EgAttack = 720, + Osc1EgDecay = 721, + Osc1EgSustain = 722, + Osc1EgRelease = 723, + Osc2EgAttack = 724, + Osc2EgDecay = 725, + Osc2EgSustain = 726, + Osc2EgRelease = 727, + Osc3EgAttack = 728, + Osc3EgDecay = 729, + Osc3EgSustain = 730, + Osc3EgRelease = 731, + NoiseUnison = 732, + NoiseUnisonSpread = 733, + } impl ParamId { - pub const COUNT: usize = 720; + pub const COUNT: usize = 734; pub fn all() -> impl Iterator { PARAMS.iter().map(|param| param.id) @@ -784,14 +796,6 @@ impl ParamId { pub const fn as_index(self) -> usize { self as usize } - - pub fn from_raw(id: u32) -> Option { - if id < Self::COUNT as u32 { - Some(unsafe { std::mem::transmute::(id as u16) }) - } else { - None - } - } } #[derive(Debug, Clone, Copy)] @@ -862,8 +866,144 @@ macro_rules! def_toggle { }; } +pub const OSC_ENVELOPE_IDS: [[ParamId; 4]; 3] = [ + [ + ParamId::Osc1EgAttack, + ParamId::Osc1EgDecay, + ParamId::Osc1EgSustain, + ParamId::Osc1EgRelease, + ], + [ + ParamId::Osc2EgAttack, + ParamId::Osc2EgDecay, + ParamId::Osc2EgSustain, + ParamId::Osc2EgRelease, + ], + [ + ParamId::Osc3EgAttack, + ParamId::Osc3EgDecay, + ParamId::Osc3EgSustain, + ParamId::Osc3EgRelease, + ], +]; + +pub const AMP_ENVELOPE_IDS: [ParamId; 4] = [ + ParamId::AmpAttack, + ParamId::AmpDecay, + ParamId::AmpSustain, + ParamId::AmpRelease, +]; + pub static PARAMS: &[ParamDef] = &[ - def_enum!(ParamId::Osc1Type, "Type", "Osc1", 10.0, 0.0), + def_automatable!( + ParamId::Osc1EgAttack, + "Attack", + "Osc1EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc1EgDecay, + "Decay", + "Osc1EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc1EgSustain, + "Sustain", + "Osc1EG", + 0.0, + 1.0, + 1.0, + 0.01 + ), + def_automatable!( + ParamId::Osc1EgRelease, + "Release", + "Osc1EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc2EgAttack, + "Attack", + "Osc2EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc2EgDecay, + "Decay", + "Osc2EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc2EgSustain, + "Sustain", + "Osc2EG", + 0.0, + 1.0, + 1.0, + 0.01 + ), + def_automatable!( + ParamId::Osc2EgRelease, + "Release", + "Osc2EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc3EgAttack, + "Attack", + "Osc3EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc3EgDecay, + "Decay", + "Osc3EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_automatable!( + ParamId::Osc3EgSustain, + "Sustain", + "Osc3EG", + 0.0, + 1.0, + 1.0, + 0.01 + ), + def_automatable!( + ParamId::Osc3EgRelease, + "Release", + "Osc3EG", + 0.0, + 10.0, + 0.0, + 0.01 + ), + def_enum!(ParamId::Osc1Type, "Type", "Osc1", 13.0, 0.0), def_enum!(ParamId::Osc1Octave, "Octave", "Osc1", 6.0, 3.0), def_enum!(ParamId::Osc1Semitone, "Semitone", "Osc1", 24.0, 12.0), def_automatable!(ParamId::Osc1Fine, "Fine", "Osc1", -100.0, 100.0, 0.0, 1.0), @@ -882,7 +1022,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_automatable!(ParamId::Osc1Sync, "Sync", "Osc1", 0.0, 60.0, 0.0, 0.0), - def_enum!(ParamId::Osc2Type, "Type", "Osc2", 10.0, 0.0), + def_enum!(ParamId::Osc2Type, "Type", "Osc2", 13.0, 0.0), def_enum!(ParamId::Osc2Octave, "Octave", "Osc2", 6.0, 3.0), def_enum!(ParamId::Osc2Semitone, "Semitone", "Osc2", 24.0, 12.0), def_automatable!(ParamId::Osc2Fine, "Fine", "Osc2", -100.0, 100.0, 0.0, 1.0), @@ -901,7 +1041,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_automatable!(ParamId::Osc2Sync, "Sync", "Osc2", 0.0, 60.0, 0.0, 0.0), - def_enum!(ParamId::Osc3Type, "Type", "Osc3", 10.0, 2.0), + def_enum!(ParamId::Osc3Type, "Type", "Osc3", 13.0, 2.0), def_enum!(ParamId::Osc3Octave, "Octave", "Osc3", 6.0, 2.0), def_enum!(ParamId::Osc3Semitone, "Semitone", "Osc3", 24.0, 12.0), def_automatable!(ParamId::Osc3Fine, "Fine", "Osc3", -100.0, 100.0, 0.0, 1.0), @@ -1058,43 +1198,6 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::FilterEgMode, "Mode", "FilterEG", 0.0, 0.0), - def_automatable!( - ParamId::PitchAttack, - "Attack", - "PitchEG", - 0.0, - 10.0, - 0.0, - 0.01 - ), - def_automatable!( - ParamId::PitchDecay, - "Decay", - "PitchEG", - 0.0, - 10.0, - 0.0, - 0.01 - ), - def_automatable!( - ParamId::PitchSustain, - "Sustain", - "PitchEG", - 0.0, - 1.0, - 0.0, - 0.01 - ), - def_automatable!( - ParamId::PitchRelease, - "Release", - "PitchEG", - 0.0, - 10.0, - 0.0, - 0.01 - ), - def_enum!(ParamId::PitchEgMode, "Mode", "PitchEG", 0.0, 0.0), def_automatable!(ParamId::Lfo1Rate, "Rate", "LFO1", 0.01, 100.0, 1.0, 0.01), def_enum!(ParamId::Lfo1Shape, "Shape", "LFO1", 9.0, 0.0), def_automatable!(ParamId::Lfo1Amount, "Amount", "LFO1", 0.0, 1.0, 0.0, 0.01), @@ -1142,7 +1245,7 @@ pub static PARAMS: &[ParamDef] = &[ ), def_enum!(ParamId::PitchBendRange, "PB Range", "Global", 24.0, 2.0), def_enum!(ParamId::ModRoute1Source, "Source", "Mod1", 35.0, 0.0), - def_enum!(ParamId::ModRoute1Target, "Target", "Mod1", 82.0, 15.0), + def_enum!(ParamId::ModRoute1Target, "Target", "Mod1", 94.0, 15.0), def_automatable!( ParamId::ModRoute1Depth, "Depth", @@ -1153,7 +1256,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute2Source, "Source", "Mod2", 35.0, 0.0), - def_enum!(ParamId::ModRoute2Target, "Target", "Mod2", 82.0, 15.0), + def_enum!(ParamId::ModRoute2Target, "Target", "Mod2", 94.0, 15.0), def_automatable!( ParamId::ModRoute2Depth, "Depth", @@ -1164,7 +1267,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute3Source, "Source", "Mod3", 35.0, 0.0), - def_enum!(ParamId::ModRoute3Target, "Target", "Mod3", 82.0, 15.0), + def_enum!(ParamId::ModRoute3Target, "Target", "Mod3", 94.0, 15.0), def_automatable!( ParamId::ModRoute3Depth, "Depth", @@ -1175,7 +1278,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute4Source, "Source", "Mod4", 35.0, 0.0), - def_enum!(ParamId::ModRoute4Target, "Target", "Mod4", 82.0, 15.0), + def_enum!(ParamId::ModRoute4Target, "Target", "Mod4", 94.0, 15.0), def_automatable!( ParamId::ModRoute4Depth, "Depth", @@ -1186,7 +1289,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute5Source, "Source", "Mod5", 35.0, 0.0), - def_enum!(ParamId::ModRoute5Target, "Target", "Mod5", 82.0, 15.0), + def_enum!(ParamId::ModRoute5Target, "Target", "Mod5", 94.0, 15.0), def_automatable!( ParamId::ModRoute5Depth, "Depth", @@ -1197,7 +1300,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute6Source, "Source", "Mod6", 35.0, 0.0), - def_enum!(ParamId::ModRoute6Target, "Target", "Mod6", 82.0, 15.0), + def_enum!(ParamId::ModRoute6Target, "Target", "Mod6", 94.0, 15.0), def_automatable!( ParamId::ModRoute6Depth, "Depth", @@ -1208,7 +1311,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute7Source, "Source", "Mod7", 35.0, 0.0), - def_enum!(ParamId::ModRoute7Target, "Target", "Mod7", 82.0, 15.0), + def_enum!(ParamId::ModRoute7Target, "Target", "Mod7", 94.0, 15.0), def_automatable!( ParamId::ModRoute7Depth, "Depth", @@ -1219,7 +1322,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute8Source, "Source", "Mod8", 35.0, 0.0), - def_enum!(ParamId::ModRoute8Target, "Target", "Mod8", 82.0, 15.0), + def_enum!(ParamId::ModRoute8Target, "Target", "Mod8", 94.0, 15.0), def_automatable!( ParamId::ModRoute8Depth, "Depth", @@ -1230,7 +1333,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute9Source, "Source", "Mod9", 35.0, 0.0), - def_enum!(ParamId::ModRoute9Target, "Target", "Mod9", 82.0, 15.0), + def_enum!(ParamId::ModRoute9Target, "Target", "Mod9", 94.0, 15.0), def_automatable!( ParamId::ModRoute9Depth, "Depth", @@ -1241,7 +1344,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute10Source, "Source", "Mod10", 35.0, 0.0), - def_enum!(ParamId::ModRoute10Target, "Target", "Mod10", 82.0, 15.0), + def_enum!(ParamId::ModRoute10Target, "Target", "Mod10", 94.0, 15.0), def_automatable!( ParamId::ModRoute10Depth, "Depth", @@ -1252,7 +1355,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute11Source, "Source", "Mod11", 35.0, 0.0), - def_enum!(ParamId::ModRoute11Target, "Target", "Mod11", 82.0, 15.0), + def_enum!(ParamId::ModRoute11Target, "Target", "Mod11", 94.0, 15.0), def_automatable!( ParamId::ModRoute11Depth, "Depth", @@ -1263,7 +1366,7 @@ pub static PARAMS: &[ParamDef] = &[ 0.01 ), def_enum!(ParamId::ModRoute12Source, "Source", "Mod12", 35.0, 0.0), - def_enum!(ParamId::ModRoute12Target, "Target", "Mod12", 82.0, 15.0), + def_enum!(ParamId::ModRoute12Target, "Target", "Mod12", 94.0, 15.0), def_automatable!( ParamId::ModRoute12Depth, "Depth", @@ -1340,15 +1443,6 @@ pub static PARAMS: &[ParamDef] = &[ 0.0, 0.01 ), - def_automatable!( - ParamId::PitchEgUberRelease, - "Uber Release", - "PitchEG", - 0.0, - 1.0, - 0.0, - 0.01 - ), def_automatable!( ParamId::StringStereoSpread, "Stereo Spread", @@ -1365,12 +1459,6 @@ pub static PARAMS: &[ParamDef] = &[ "FilterEG", 0.0 ), - def_toggle!( - ParamId::PitchEgGatedRelease, - "Gated Release", - "PitchEG", - 0.0 - ), def_automatable!( ParamId::WavetableKeytrack, "Keytrack", @@ -1393,6 +1481,16 @@ pub static PARAMS: &[ParamDef] = &[ def_enum!(ParamId::TuningSclIndex, "SCL File", "Tuning", 63.0, 0.0), def_enum!(ParamId::NoiseType, "Type", "Noise", 2.0, 0.0), def_automatable!(ParamId::NoiseLevel, "Level", "Noise", 0.0, 1.0, 0.0, 0.01), + def_enum!(ParamId::NoiseUnison, "Unison", "Noise", 8.0, 1.0), + def_automatable!( + ParamId::NoiseUnisonSpread, + "Spread", + "Noise", + 0.0, + 1.0, + 0.0, + 0.01 + ), def_enum!(ParamId::NoiseFilterType, "Filter Type", "Noise", 14.0, 0.0), def_automatable!( ParamId::NoiseFilterCutoff, @@ -1414,26 +1512,6 @@ pub static PARAMS: &[ParamDef] = &[ ), def_toggle!(ParamId::NoiseFilterEnabled, "Filter On", "Noise", 0.0), def_toggle!(ParamId::NoiseEnabled, "Enabled", "Noise", 0.0), - def_enum!(ParamId::WaveshaperShape, "Shape", "Waveshaper", 45.0, 0.0), - def_automatable!( - ParamId::WaveshaperDrive, - "Drive", - "Waveshaper", - 0.0, - 1.0, - 0.0, - 0.01 - ), - def_automatable!( - ParamId::WaveshaperMix, - "Mix", - "Waveshaper", - 0.0, - 1.0, - 1.0, - 0.01 - ), - def_toggle!(ParamId::WaveshaperEnabled, "Enabled", "Waveshaper", 0.0), def_enum!(ParamId::FlavorType, "Type", "Flavor", 4.0, 0.0), def_automatable!( ParamId::FlavorCutoff, @@ -1455,8 +1533,8 @@ pub static PARAMS: &[ParamDef] = &[ ), def_enum!(ParamId::OscFmMode, "FM Mode", "Osc", 9.0, 0.0), def_automatable!(ParamId::OscFmDepth, "FM Depth", "Osc", 0.0, 1.0, 0.5, 0.01), - def_enum!(ParamId::F1Subtype, "Subtype", "Filter1", 21.0, 0.0), - def_enum!(ParamId::F2Subtype, "Subtype", "Filter2", 21.0, 0.0), + def_enum!(ParamId::F1Subtype, "Subtype", "Filter1", 6.0, 0.0), + def_enum!(ParamId::F2Subtype, "Subtype", "Filter2", 6.0, 0.0), def_automatable!( ParamId::FilterBalance, "Balance", @@ -2039,7 +2117,6 @@ pub static PARAMS: &[ParamDef] = &[ 1.0, 0.0 ), - def_enum!(ParamId::PitchEgRetrigger, "Retrigger", "PitchEG", 1.0, 0.0), def_enum!(ParamId::StealMode, "Steal Mode", "Global", 1.0, 0.0), def_toggle!(ParamId::PortamentoSync, "Tempo Sync", "Global", 0.0), def_toggle!( @@ -2066,7 +2143,6 @@ pub static PARAMS: &[ParamDef] = &[ def_toggle!(ParamId::Lfo6EnvTempoSync, "Env Tempo Sync", "LFO6", 0.0), def_toggle!(ParamId::AmpEgTempoSync, "Tempo Sync", "AmpEG", 0.0), def_toggle!(ParamId::FilterEgTempoSync, "Tempo Sync", "FilterEG", 0.0), - def_toggle!(ParamId::PitchEgTempoSync, "Tempo Sync", "PitchEG", 0.0), def_automatable!( ParamId::StepSeqTrigAmp, "Trig Amp", @@ -2085,15 +2161,6 @@ pub static PARAMS: &[ParamDef] = &[ 0.0, 1.0 ), - def_automatable!( - ParamId::StepSeqTrigPitch, - "Trig Pitch", - "StepSeq", - 0.0, - 65535.0, - 0.0, - 1.0 - ), def_automatable!( ParamId::F1FeedbackDrive, "Feedback Drive", @@ -3121,27 +3188,6 @@ pub static PARAMS: &[ParamDef] = &[ 3.0, 0.0 ), - def_enum!( - ParamId::PitchEgAttackCurve, - "Attack Curve", - "Pitch EG", - 3.0, - 0.0 - ), - def_enum!( - ParamId::PitchEgDecayCurve, - "Decay Curve", - "Pitch EG", - 3.0, - 0.0 - ), - def_enum!( - ParamId::PitchEgReleaseCurve, - "Release Curve", - "Pitch EG", - 3.0, - 0.0 - ), def_toggle!(ParamId::Osc1Solo, "Solo", "Osc1", 0.0), def_toggle!(ParamId::Osc2Solo, "Solo", "Osc2", 0.0), def_toggle!(ParamId::Osc3Solo, "Solo", "Osc3", 0.0), @@ -3176,12 +3222,6 @@ pub static PARAMS: &[ParamDef] = &[ "Filter EG", 0.0 ), - def_toggle!( - ParamId::PitchEgCorrectAnalog, - "Correct Analog", - "Pitch EG", - 0.0 - ), def_automatable!( ParamId::MsegRetrigAmp, "Retrig Amp", @@ -3200,15 +3240,6 @@ pub static PARAMS: &[ParamDef] = &[ 0.0, 1.0 ), - def_automatable!( - ParamId::MsegRetrigPitch, - "Retrig Pitch", - "MSEG", - 0.0, - 65535.0, - 0.0, - 1.0 - ), def_automatable!( ParamId::AliasPartial1, "Partial 1", @@ -3448,6 +3479,45 @@ impl crate::common::ClapParamId for ParamId { mod tests { use super::{ParamId, param_def}; + #[test] + fn raw_ids_reject_retired_and_out_of_range_slots() { + for raw in 56..=60 { + assert_eq!(ParamId::from_raw(raw), None); + } + for raw in [ParamId::COUNT as u32, u16::MAX as u32 + 1, u32::MAX] { + assert_eq!(ParamId::from_raw(raw), None); + } + for id in ParamId::all() { + assert_eq!(ParamId::from_raw(id as u32), Some(id)); + } + assert_eq!(ParamId::from_raw(719), Some(ParamId::Reserved719)); + } + + #[test] + fn state_roundtrip_preserves_parameter_slots() { + use super::ParamStore; + use crate::common::state::PluginState; + + let source = ParamStore::default(); + for raw in 0..ParamId::COUNT as u32 { + if let Some(id) = ParamId::from_raw(raw) { + source.set(id, f64::from(raw) + 0.25); + } + } + let state = PluginState::from_runtime(&source); + assert_eq!(state.params.len(), ParamId::COUNT); + assert_eq!(&state.params[56..61], &[0.0; 5]); + assert_eq!(state.params[61], 61.25); + let loaded = PluginState::from_bytes(&state.to_bytes().unwrap()).unwrap(); + let restored = ParamStore::default(); + loaded.apply(&restored); + for raw in 0..ParamId::COUNT as u32 { + if let Some(id) = ParamId::from_raw(raw) { + assert_eq!(restored.get(id), source.get(id), "parameter {raw}"); + } + } + } + #[test] fn oscillator_sync_defaults_are_off() { assert_eq!(param_def(ParamId::Osc1Sync).unwrap().default, 0.0); diff --git a/src/synth/plugin.rs b/src/synth/plugin.rs index a188321..323c01d 100644 --- a/src/synth/plugin.rs +++ b/src/synth/plugin.rs @@ -50,7 +50,7 @@ use crate::synth::{ LfoTriggerMode, ModDepthCurve, ModRouting, ModSource, ModTarget, MsegCurve, MsegLoopMode, MtsEspClient, NoiseSettings, NoiseType, OscFmMode, OscPhaseMode, OscRoute, OscSettings, OscType, PlayMode, PortamentoCurve, StealMode, SynthEngine, Tuning, VoiceParams, - VoicePriority, Waveshape, WaveshaperSettings, + VoicePriority, }, gui::GuiBridge, params::{PARAMS, ParamId, ParamStore, sanitize_param_value}, @@ -112,8 +112,6 @@ pub struct SharedState { pub custom_wavetable_paths: [Mutex>; 3], /// Directory the host asked us to copy external resources into. pub resource_dir: RwLock>, - /// Report of the last Surge XT preset import (GUI display + logging). - pub surge_report: Mutex, } fn migrate_legacy_sine(store: &ParamStore) { @@ -161,7 +159,6 @@ impl Default for SharedState { custom_wavetables: [const { Mutex::new(None) }; 3], custom_wavetable_paths: [const { Mutex::new(None) }; 3], resource_dir: RwLock::new(None), - surge_report: Mutex::new(crate::synth::surge::Report::default()), } } } @@ -251,23 +248,6 @@ impl SharedState { self.set_param_internal(id, value, false); } - /// Import a Surge XT `.fxp` preset: converted parameters are applied to the - /// store (no per-param host notifications; one version bump at the end) and - /// the import report is kept for the GUI and the log. - pub fn load_surge_preset(&self, path: &Path) -> Result<(), String> { - let result = crate::synth::surge::load_preset(path)?; - for (id, value) in &result.values { - self.set_param_from_host(*id, *value); - } - let report = result.report.to_display_string(); - if !report.is_empty() { - tracing::warn!("[surge] import report for '{}':\n{report}", result.name); - } - *self.surge_report.lock() = result.report; - self.bump_params_version(); - Ok(()) - } - pub fn save_synth_preset(&self, path: &Path) -> Result<(), String> { let wavetable_paths: Vec<(u8, String)> = self .custom_wavetable_paths @@ -540,7 +520,6 @@ pub(crate) fn build_voice_params(params: &ParamStore) -> VoiceParams { build_filter2_params(&mut result, params); build_amp_eg_params(&mut result, params); build_filter_eg_params(&mut result, params); - build_pitch_eg_params(&mut result, params); build_lfo_params(&mut result, params, 0); build_lfo_params(&mut result, params, 1); build_lfo_params(&mut result, params, 2); @@ -554,7 +533,6 @@ pub(crate) fn build_voice_params(params: &ParamStore) -> VoiceParams { build_scene_lfo_params(&mut result, params, 4); build_scene_lfo_params(&mut result, params, 5); build_noise_params(&mut result, params); - build_waveshaper_params(&mut result, params); build_flavor_params(&mut result, params); build_tuning_params(&mut result, params); build_output_vca_params(&mut result, params); @@ -684,7 +662,6 @@ fn build_step_seq_params(params: &mut VoiceParams, store: &ParamStore) { params.step_seq_shuffle = store.get(ParamId::StepSeqShuffle) as f32; params.step_seq_trig_amp = store.get(ParamId::StepSeqTrigAmp) as u16; params.step_seq_trig_filter = store.get(ParamId::StepSeqTrigFilter) as u16; - params.step_seq_trig_pitch = store.get(ParamId::StepSeqTrigPitch) as u16; } fn build_mseg_params(params: &mut VoiceParams, store: &ParamStore) { @@ -960,7 +937,6 @@ fn build_mseg_params(params: &mut VoiceParams, store: &ParamStore) { params.mseg_loop_mode = MsegLoopMode::from_u8(store.get(ParamId::MsegLoopMode) as u8); params.mseg_retrig_amp = store.get(ParamId::MsegRetrigAmp) as u16; params.mseg_retrig_filter = store.get(ParamId::MsegRetrigFilter) as u16; - params.mseg_retrig_pitch = store.get(ParamId::MsegRetrigPitch) as u16; } fn build_filter1_params(params: &mut VoiceParams, store: &ParamStore) { @@ -1038,6 +1014,13 @@ fn build_amp_eg_params(params: &mut VoiceParams, store: &ParamStore) { gated_release: store.get_bool(ParamId::AmpEgGatedRelease), correct_analog_mode: store.get_bool(ParamId::AmpEgCorrectAnalog), }; + params.osc_egs = Some(super::params::OSC_ENVELOPE_IDS.map(|ids| EnvelopeSettings { + attack: store.get(ids[0]) as f32, + decay: store.get(ids[1]) as f32, + sustain: store.get(ids[2]) as f32, + release: store.get(ids[3]) as f32, + ..params.amp_eg.clone() + })); } fn build_filter_eg_params(params: &mut VoiceParams, store: &ParamStore) { @@ -1062,28 +1045,6 @@ fn build_filter_eg_params(params: &mut VoiceParams, store: &ParamStore) { }; } -fn build_pitch_eg_params(params: &mut VoiceParams, store: &ParamStore) { - params.pitch_eg = EnvelopeSettings { - attack: store.get(ParamId::PitchAttack) as f32, - decay: store.get(ParamId::PitchDecay) as f32, - sustain: store.get(ParamId::PitchSustain) as f32, - release: store.get(ParamId::PitchRelease) as f32, - mode: if store.get(ParamId::PitchEgMode) > 0.5 { - EnvelopeMode::Analog - } else { - EnvelopeMode::Digital - }, - attack_shape: AttackShape::from_u8(eg_attack(store, ParamId::PitchEgAttackCurve)), - decay_shape: DecayReleaseShape::from_u8(eg_decay(store, ParamId::PitchEgDecayCurve)), - release_shape: DecayReleaseShape::from_u8(eg_release(store, ParamId::PitchEgReleaseCurve)), - retrigger_mode: EnvelopeRetriggerMode::from_u8(store.get(ParamId::PitchEgRetrigger) as u8), - tempo_sync: store.get_bool(ParamId::PitchEgTempoSync), - uber_release: store.get(ParamId::PitchEgUberRelease) as f32, - gated_release: store.get_bool(ParamId::PitchEgGatedRelease), - correct_analog_mode: store.get_bool(ParamId::PitchEgCorrectAnalog), - }; -} - fn build_lfo_params(params: &mut VoiceParams, store: &ParamStore, idx: usize) { let ( rate, @@ -1539,6 +1500,8 @@ fn build_noise_params(params: &mut VoiceParams, store: &ParamStore) { params.noise = NoiseSettings { noise_type: NoiseType::from_u8(store.get(ParamId::NoiseType) as u8), level: store.get(ParamId::NoiseLevel) as f32, + unison_voices: (store.get(ParamId::NoiseUnison) as u8).clamp(1, 8), + unison_spread: store.get(ParamId::NoiseUnisonSpread) as f32, filter_type: FilterType::from_u8(store.get(ParamId::NoiseFilterType) as u8), filter_cutoff: store.get(ParamId::NoiseFilterCutoff) as f32, filter_resonance: store.get(ParamId::NoiseFilterResonance) as f32, @@ -1553,15 +1516,6 @@ fn build_noise_params(params: &mut VoiceParams, store: &ParamStore) { }; } -fn build_waveshaper_params(params: &mut VoiceParams, store: &ParamStore) { - params.waveshaper = WaveshaperSettings { - shape: Waveshape::from_u8(store.get(ParamId::WaveshaperShape) as u8), - drive: store.get(ParamId::WaveshaperDrive) as f32, - mix: store.get(ParamId::WaveshaperMix) as f32, - enabled: store.get_bool(ParamId::WaveshaperEnabled), - }; -} - fn build_flavor_params(params: &mut VoiceParams, store: &ParamStore) { params.flavor = FlavorType::from_u8(store.get(ParamId::FlavorType) as u8); params.flavor_cutoff = store.get(ParamId::FlavorCutoff) as f32; @@ -1636,13 +1590,11 @@ struct ParamDirtyFlags { filters_routing_balance: bool, amp_eg: bool, filter_eg: bool, - pitch_eg: bool, oscs: bool, osc_globals: bool, lfos: [bool; 6], scene_lfos: [bool; 6], noise: bool, - waveshaper: bool, flavor: bool, modulations: bool, step_seq: bool, @@ -1844,8 +1796,20 @@ fn apply_param_id_to_voice_params( true } - // Amp EG - ParamId::AmpAttack + // Amp and oscillator envelopes + ParamId::Osc1EgAttack + | ParamId::Osc1EgDecay + | ParamId::Osc1EgSustain + | ParamId::Osc1EgRelease + | ParamId::Osc2EgAttack + | ParamId::Osc2EgDecay + | ParamId::Osc2EgSustain + | ParamId::Osc2EgRelease + | ParamId::Osc3EgAttack + | ParamId::Osc3EgDecay + | ParamId::Osc3EgSustain + | ParamId::Osc3EgRelease + | ParamId::AmpAttack | ParamId::AmpDecay | ParamId::AmpSustain | ParamId::AmpRelease @@ -1885,25 +1849,6 @@ fn apply_param_id_to_voice_params( true } - // Pitch EG - ParamId::PitchAttack - | ParamId::PitchDecay - | ParamId::PitchSustain - | ParamId::PitchRelease - | ParamId::PitchEgMode - | ParamId::PitchEgRetrigger - | ParamId::PitchEgTempoSync - | ParamId::PitchEgUberRelease - | ParamId::PitchEgGatedRelease - | ParamId::PitchEgCorrectAnalog - | ParamId::PitchEgAttackCurve - | ParamId::PitchEgDecayCurve - | ParamId::PitchEgReleaseCurve => { - build_pitch_eg_params(params, store); - dirty.pitch_eg = true; - true - } - // LFOs ParamId::Lfo1Rate | ParamId::Lfo1Shape @@ -2085,6 +2030,8 @@ fn apply_param_id_to_voice_params( // Noise ParamId::NoiseType | ParamId::NoiseLevel + | ParamId::NoiseUnison + | ParamId::NoiseUnisonSpread | ParamId::NoiseFilterType | ParamId::NoiseFilterCutoff | ParamId::NoiseFilterResonance @@ -2101,16 +2048,6 @@ fn apply_param_id_to_voice_params( true } - // Waveshaper - ParamId::WaveshaperShape - | ParamId::WaveshaperDrive - | ParamId::WaveshaperMix - | ParamId::WaveshaperEnabled => { - build_waveshaper_params(params, store); - dirty.waveshaper = true; - true - } - // Flavor ParamId::FlavorType | ParamId::FlavorCutoff | ParamId::FlavorResonance => { build_flavor_params(params, store); @@ -2298,8 +2235,7 @@ fn apply_param_id_to_voice_params( | ParamId::StepSeqLoopEnd | ParamId::StepSeqShuffle | ParamId::StepSeqTrigAmp - | ParamId::StepSeqTrigFilter - | ParamId::StepSeqTrigPitch => { + | ParamId::StepSeqTrigFilter => { build_step_seq_params(params, store); dirty.step_seq = true; true @@ -2565,8 +2501,7 @@ fn apply_param_id_to_voice_params( | ParamId::MsegLoopEnd | ParamId::MsegLoopMode | ParamId::MsegRetrigAmp - | ParamId::MsegRetrigFilter - | ParamId::MsegRetrigPitch => { + | ParamId::MsegRetrigFilter => { build_mseg_params(params, store); dirty.mseg = true; true @@ -2873,9 +2808,6 @@ impl AudioProcessor { if dirty.filter_eg { self.engine.update_filter_eg_params(); } - if dirty.pitch_eg { - self.engine.update_pitch_eg_params(); - } for i in 0..6 { if dirty.lfos[i] { self.engine.update_lfo_params(i); @@ -2887,9 +2819,6 @@ impl AudioProcessor { if dirty.noise { self.engine.update_noise_params(); } - if dirty.waveshaper { - self.engine.update_waveshaper_params(); - } if dirty.flavor { self.engine.update_flavor_params(); } @@ -3379,7 +3308,7 @@ unsafe extern "C-unwind" fn ext_state_load( let Ok(state) = PluginState::from_bytes(&bytes) else { return false; }; - state.apply(&inst.shared.params); + super::state::apply_synth_state(&state, &inst.shared.params); migrate_legacy_sine(&inst.shared.params); // Restore custom wavetables referenced by this patch. Loading happens on @@ -3999,6 +3928,19 @@ impl crate::common::clap_harness::GuiHooks for GuiBridge { } } +impl crate::common::preset::PresetProvider for SharedState { + const DIR_NAME: &'static str = "synth"; + const FORMAT: &'static str = "maolan-synth-preset"; + + fn save_preset(&self, path: &Path) -> Result<(), String> { + self.save_synth_preset(path) + } + + fn load_preset(&self, path: &Path) -> Result<(), String> { + self.load_synth_preset(path).map(|_| ()) + } +} + #[cfg(test)] mod tests { use super::{ diff --git a/src/synth/preset.rs b/src/synth/preset.rs index f4c8ba2..d3f507b 100644 --- a/src/synth/preset.rs +++ b/src/synth/preset.rs @@ -50,6 +50,15 @@ impl SynthPreset { }; store.set(id, sanitize_param_value(id, *value)); } + // Older presets have only the shared amp envelope. Seed each missing + // oscillator stage from it, including when loading over an edited patch. + for ids in super::params::OSC_ENVELOPE_IDS { + for (id, legacy) in ids.into_iter().zip(super::params::AMP_ENVELOPE_IDS) { + if !self.parameters.contains_key(¶m_key(id)) { + store.set(id, store.get(legacy)); + } + } + } } pub fn wavetable_paths(&self) -> Vec<(u8, String)> { @@ -114,3 +123,38 @@ fn wavetable_index_for_key(key: &str) -> Option { _ => None, } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::synth::params::{AMP_ENVELOPE_IDS, OSC_ENVELOPE_IDS}; + + #[test] + fn old_presets_seed_missing_stages_without_overwriting_new_stages() { + let source = ParamStore::default(); + for (id, value) in AMP_ENVELOPE_IDS.into_iter().zip([0.1, 0.2, 0.3, 0.4]) { + source.set(id, value); + } + let mut preset = SynthPreset::from_runtime(&source, None, &[]); + for ids in OSC_ENVELOPE_IDS { + for id in ids { + preset.parameters.remove(¶m_key(id)); + } + } + preset + .parameters + .insert(param_key(ParamId::Osc2EgRelease), 2.0); + let restored = ParamStore::default(); + preset.apply(&restored); + for ids in OSC_ENVELOPE_IDS { + for (id, legacy) in ids.into_iter().zip(AMP_ENVELOPE_IDS) { + let expected = if id == ParamId::Osc2EgRelease { + 2.0 + } else { + source.get(legacy) + }; + assert_eq!(restored.get(id), expected); + } + } + } +} diff --git a/src/synth/render.rs b/src/synth/render.rs deleted file mode 100644 index 1cc39d1..0000000 --- a/src/synth/render.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! Headless WAV renderer for A/B comparison of Surge XT presets against -//! Surge XT itself. Loads a preset through the Surge import path, applies the -//! converted parameters to a [`SynthEngine`], plays a single note and writes -//! stereo float32 WAV — the exact counterpart of Surge's `surge-render`. - -use std::path::Path; - -use crate::synth::dsp::SynthEngine; -use crate::synth::params::ParamStore; -use crate::synth::plugin::build_voice_params; -use crate::synth::surge; - -pub const SAMPLE_RATE: f32 = 48_000.0; -/// Matches Surge's BLOCK_SIZE so both engines quantize modulation the same way. -pub const BLOCK_SIZE: usize = 32; - -/// Render `preset` (a Surge `.fxp`) to `wav`: note `note` held for `hold` -/// seconds, then released, rendering `tail` seconds of release tail. -pub fn render_surge_preset( - preset: &Path, - wav: &Path, - note: u8, - hold: f32, - tail: f32, -) -> Result<(), String> { - let result = surge::load_preset(preset)?; - let store = ParamStore::default(); - for (id, value) in &result.values { - store.set(*id, *value); - } - - let mut engine = SynthEngine::new(SAMPLE_RATE, 32); - engine.params = build_voice_params(&store); - engine.update_params(); - // Match surge-render's fixed 120 BPM so tempo-synced LFOs/envelopes line up. - engine.set_tempo(120.0); - - let hold_blocks = (hold * SAMPLE_RATE / BLOCK_SIZE as f32).ceil() as usize; - let tail_blocks = (tail * SAMPLE_RATE / BLOCK_SIZE as f32).ceil() as usize; - let total = (hold_blocks + tail_blocks) * BLOCK_SIZE; - - let mut left = vec![0.0f32; total]; - let mut right = vec![0.0f32; total]; - let mut block_l = vec![0.0f32; BLOCK_SIZE]; - let mut block_r = vec![0.0f32; BLOCK_SIZE]; - engine.trigger(note, 100.0 / 127.0); - for block in 0..hold_blocks + tail_blocks { - if block == hold_blocks { - engine.release(note, 0.0); - } - engine.process_block(&mut block_l, &mut block_r, None, None); - let start = block * BLOCK_SIZE; - left[start..start + BLOCK_SIZE].copy_from_slice(&block_l); - right[start..start + BLOCK_SIZE].copy_from_slice(&block_r); - } - - write_wav(wav, &left, &right, SAMPLE_RATE as u32)?; - Ok(()) -} - -fn write_wav(path: &Path, left: &[f32], right: &[f32], sample_rate: u32) -> Result<(), String> { - use std::io::Write; - let frames = left.len().min(right.len()); - let mut data = Vec::with_capacity(frames * 2); - for i in 0..frames { - data.push(left[i]); - data.push(right[i]); - } - let data_bytes = (data.len() * 4) as u32; - let mut file = - std::fs::File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?; - let mut header = Vec::with_capacity(44); - header.extend_from_slice(b"RIFF"); - header.extend_from_slice(&(36 + data_bytes).to_le_bytes()); - header.extend_from_slice(b"WAVE"); - header.extend_from_slice(b"fmt "); - header.extend_from_slice(&16u32.to_le_bytes()); - header.extend_from_slice(&3u16.to_le_bytes()); // IEEE float - header.extend_from_slice(&2u16.to_le_bytes()); // stereo - header.extend_from_slice(&sample_rate.to_le_bytes()); - header.extend_from_slice(&(sample_rate * 8).to_le_bytes()); // byte rate - header.extend_from_slice(&8u16.to_le_bytes()); // block align - header.extend_from_slice(&32u16.to_le_bytes()); // bits - header.extend_from_slice(b"data"); - header.extend_from_slice(&data_bytes.to_le_bytes()); - let mut bytes = Vec::with_capacity(data.len() * 4); - for sample in &data { - bytes.extend_from_slice(&sample.to_le_bytes()); - } - file.write_all(&header) - .and_then(|()| file.write_all(&bytes)) - .map_err(|e| format!("write {}: {e}", path.display())) -} diff --git a/src/synth/state.rs b/src/synth/state.rs index d9f2c3a..9746bc0 100644 --- a/src/synth/state.rs +++ b/src/synth/state.rs @@ -1 +1,60 @@ +use super::params::{AMP_ENVELOPE_IDS, OSC_ENVELOPE_IDS, ParamStore}; pub use crate::common::state::PluginState; + +pub fn apply_synth_state(state: &PluginState, store: &ParamStore) { + state.apply(store); + for ids in OSC_ENVELOPE_IDS { + for (id, legacy) in ids.into_iter().zip(AMP_ENVELOPE_IDS) { + if state.params.len() <= id.as_index() { + store.set(id, store.get(legacy)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn legacy_state_initializes_each_oscillator_envelope() { + let source = ParamStore::default(); + for (id, value) in AMP_ENVELOPE_IDS.into_iter().zip([0.1, 0.2, 0.3, 0.4]) { + source.set(id, value); + } + let mut state = PluginState::from_runtime(&source); + state.params.truncate(720); + let restored = ParamStore::default(); + for ids in OSC_ENVELOPE_IDS { + for id in ids { + restored.set(id, 0.9); + } + } + apply_synth_state(&state, &restored); + for ids in OSC_ENVELOPE_IDS { + for (id, legacy) in ids.into_iter().zip(AMP_ENVELOPE_IDS) { + assert_eq!(restored.get(id), source.get(legacy)); + } + } + } + + #[test] + fn independent_envelopes_survive_state_roundtrip() { + let source = ParamStore::default(); + for (i, ids) in OSC_ENVELOPE_IDS.into_iter().enumerate() { + for (stage, id) in ids.into_iter().enumerate() { + source.set(id, (i * 4 + stage) as f64 / 20.0); + } + } + let state = + PluginState::from_bytes(&PluginState::from_runtime(&source).to_bytes().unwrap()) + .unwrap(); + let restored = ParamStore::default(); + apply_synth_state(&state, &restored); + for ids in OSC_ENVELOPE_IDS { + for id in ids { + assert_eq!(restored.get(id), source.get(id)); + } + } + } +} diff --git a/src/synth/surge/convert.rs b/src/synth/surge/convert.rs deleted file mode 100644 index 32e7d55..0000000 --- a/src/synth/surge/convert.rs +++ /dev/null @@ -1,2381 +0,0 @@ -//! Conversion of a parsed Surge patch XML into Maolan Synth parameter values. -//! -//! Coverage and deliberate omissions (all recorded in the [`Report`]): -//! - Surge is dual-scene; Maolan Synth is single-scene. The patch's active -//! scene (scene A for dual/split modes) is imported, the other is skipped. -//! - All effect slots, sends and FX bypass state are ignored on request. -//! - Oscillator types without a Maolan Synth equivalent (audio input) are -//! skipped per oscillator. -//! - MSEG segment data and formula modulators have no equivalent and are -//! reported; the MSEG *shape* is still selected. -//! - Wavetable choices referenced by name (and tables embedded in the -//! preset) are not imported; the currently selected table is kept. - -use std::collections::HashMap; - -use quick_xml::Reader; -use quick_xml::events::Event; - -use crate::synth::dsp::{ModSource, ModTarget}; -use crate::synth::params::ParamId; - -use super::LoadResult; -use super::fxp::SurgePatchFile; -use super::report::Report; -use super::units; - -/// One Surge parameter element from ``. -#[derive(Debug, Clone, Default)] -struct SurgeParam { - /// Raw `value` attribute when stored as an integer (`type="0"`). - int_value: Option, - /// Raw `value` attribute when stored as a float (`type="2"`). - float_value: Option, - temposync: bool, - deform_type: Option, - /// Modulation routes attached to this parameter. - routings: Vec, -} - -impl SurgeParam { - /// Float interpretation of the value. Old Surge revisions store - /// float-typed parameters as integers carrying the IEEE-754 bit pattern - /// of the float (Surge keeps `val.i`/`val.f` in a union), so params the - /// mapping declares as semantically float are read through here. - fn as_float(&self, semantic_float: bool) -> Option { - if let Some(value) = self.float_value { - return Some(value); - } - if semantic_float { - return self.int_value.map(|bits| f32::from_bits(bits as u32)); - } - None - } - - fn as_int(&self) -> Option { - self.int_value - .or_else(|| self.float_value.map(|value| value as i32)) - } -} - -/// One `` element. -#[derive(Debug, Clone)] -struct SurgeRouting { - source: i32, - depth: f32, - muted: bool, -} - -/// Fully parsed Surge patch XML. -#[derive(Debug, Default)] -struct ParsedPatch { - revision: u32, - meta_name: String, - /// Scene B content is present when any `b_*` parameter exists. - has_scene_b: bool, - params: HashMap, - /// Attribute maps of `` elements (step sequencers). - sequences: Vec>, - /// Attribute maps of `` elements inside ``. - custom_controllers: Vec>, -} - -fn attr_string(attributes: quick_xml::events::attributes::Attributes) -> HashMap { - attributes - .flatten() - .map(|attr| (attr.key.as_ref().to_string(), attr.value.into_owned())) - .collect() -} - -fn parse_xml(xml: &str) -> Result { - let mut reader = Reader::from_str(xml); - reader.config_mut().trim_text(true); - let mut patch = ParsedPatch::default(); - let mut buf = Vec::new(); - // Name of the parameter element we are currently inside (for modrouting - // children), None outside . - let mut current_param: Option = None; - let mut in_parameters = false; - let mut in_stepsequences = false; - let mut in_customcontroller = false; - - loop { - match reader.read_event_into(&mut buf) { - Err(error) => { - return Err(format!( - "patch XML parse error at byte {}: {error}", - reader.buffer_position() - )); - } - Ok(Event::Decl(_)) | Ok(Event::Text(_)) | Ok(Event::Comment(_)) => {} - Ok(Event::Eof) => break, - Ok(Event::Start(event)) => { - let name = event.name().as_ref().to_string(); - match name.as_str() { - "patch" => { - let attrs = attr_string(event.attributes()); - patch.revision = attrs - .get("revision") - .and_then(|value| value.parse().ok()) - .unwrap_or(0); - } - "meta" => { - let attrs = attr_string(event.attributes()); - patch.meta_name = attrs.get("name").cloned().unwrap_or_default(); - } - "parameters" => in_parameters = true, - "stepsequences" => in_stepsequences = true, - "customcontroller" => in_customcontroller = true, - "sequence" if in_stepsequences => { - patch.sequences.push(attr_string(event.attributes())); - } - "entry" if in_customcontroller => { - patch - .custom_controllers - .push(attr_string(event.attributes())); - } - "modrouting" => { - if let Some(param_name) = current_param.as_ref() { - let attrs = attr_string(event.attributes()); - let routing = SurgeRouting { - source: attrs - .get("source") - .and_then(|value| value.parse().ok()) - .unwrap_or(-1), - depth: attrs - .get("depth") - .and_then(|value| value.parse().ok()) - .unwrap_or(0.0), - muted: attrs.get("muted").is_some_and(|value| value == "1"), - }; - if let Some(param) = patch.params.get_mut(param_name) { - param.routings.push(routing); - } - } - } - _ if in_parameters => { - let attrs = attr_string(event.attributes()); - let mut param = SurgeParam::default(); - match attrs.get("type").map(String::as_str) { - Some("2") => { - param.float_value = - attrs.get("value").and_then(|value| value.parse().ok()); - } - _ => { - param.int_value = - attrs.get("value").and_then(|value| value.parse().ok()); - } - } - param.temposync = attrs.get("temposync").is_some_and(|value| value == "1"); - param.deform_type = attrs - .get("deform_type") - .and_then(|value| value.parse().ok()); - if name.starts_with("b_") { - patch.has_scene_b = true; - } - patch.params.insert(name.clone(), param); - current_param = Some(name); - } - _ => {} - } - } - Ok(Event::Empty(event)) => { - let name = event.name().as_ref().to_string(); - match name.as_str() { - "meta" => { - let attrs = attr_string(event.attributes()); - patch.meta_name = attrs.get("name").cloned().unwrap_or_default(); - } - "sequence" if in_stepsequences => { - patch.sequences.push(attr_string(event.attributes())); - } - "entry" if in_customcontroller => { - patch - .custom_controllers - .push(attr_string(event.attributes())); - } - "modrouting" => { - if let Some(param_name) = current_param.as_ref() { - let attrs = attr_string(event.attributes()); - let routing = SurgeRouting { - source: attrs - .get("source") - .and_then(|value| value.parse().ok()) - .unwrap_or(-1), - depth: attrs - .get("depth") - .and_then(|value| value.parse().ok()) - .unwrap_or(0.0), - muted: attrs.get("muted").is_some_and(|value| value == "1"), - }; - if let Some(param) = patch.params.get_mut(param_name) { - param.routings.push(routing); - } - } - } - _ if in_parameters => { - let attrs = attr_string(event.attributes()); - let mut param = SurgeParam::default(); - match attrs.get("type").map(String::as_str) { - Some("2") => { - param.float_value = - attrs.get("value").and_then(|value| value.parse().ok()); - } - _ => { - param.int_value = - attrs.get("value").and_then(|value| value.parse().ok()); - } - } - param.temposync = attrs.get("temposync").is_some_and(|value| value == "1"); - param.deform_type = attrs - .get("deform_type") - .and_then(|value| value.parse().ok()); - if name.starts_with("b_") { - patch.has_scene_b = true; - } - patch.params.insert(name.clone(), param); - } - _ => {} - } - } - Ok(Event::End(event)) => { - let name = event.name().as_ref().to_string(); - match name.as_str() { - "parameters" => { - in_parameters = false; - current_param = None; - } - "stepsequences" => in_stepsequences = false, - "customcontroller" => in_customcontroller = false, - _ if in_parameters && current_param.as_deref() == Some(name.as_str()) => { - current_param = None; - } - _ => {} - } - } - _ => {} - } - buf.clear(); - } - Ok(patch) -} - -fn get<'a>(patch: &'a ParsedPatch, prefix: &str, name: &str) -> Option<&'a SurgeParam> { - let mut key = String::with_capacity(prefix.len() + name.len()); - key.push_str(prefix); - key.push_str(name); - patch.params.get(&key) -} - -fn clamp01(value: f32) -> f64 { - value.clamp(0.0, 1.0) as f64 -} - -fn clamp_bipolar(value: f32) -> f64 { - value.clamp(-1.0, 1.0) as f64 -} - -/// `ct_freq_audible` storage value in Hz, clamped to our cutoff range. -fn cutoff_hz(raw: f32) -> f64 { - units::freq_audible_hz(raw).clamp(20.0, 20_000.0) as f64 -} - -/// Surge `osc_type` to our `OscType` discriminant. -fn map_osc_type(surge_type: i32) -> Option { - match surge_type { - 0 => Some(0), // classic - 1 => Some(0), // sine is a Classic waveform - 2 => Some(3), // wavetable - 3 => Some(6), // s&h noise - 5 => Some(8), // fm3 - 6 => Some(2), // fm2 - 7 => Some(4), // window - 8 => Some(5), // modern - 9 => Some(7), // string - 10 => Some(10), // twist - 11 => Some(9), // alias - _ => None, // 4 = audio input and anything unknown - } -} - -/// Surge filter type (`fut_*`, 0..35) to (our `FilterType` discriminant, -/// subtype handling hint). -fn map_filter_type(surge_type: i32) -> Option { - match surge_type { - 1 => Some(15), // lp12 -> LP 12 - 2 => Some(1), // lp24 -> LP 24 - 3 => Some(9), // lpmoog -> ladder - 4 => Some(16), // hp12 - 5 => Some(3), // hp24 - 6 => Some(17), // bp12 - 7 => Some(21), // notch12 - 8 => Some(6), // comb+ - 9 => Some(33), // s&h - 10 => Some(22), // vintage ladder - 11 => Some(42), // obxd 2p lp - 12 => Some(46), // obxd 4p - 13 => Some(10), // k35 lp - 14 => Some(11), // k35 hp - 15 => Some(12), // diode - 16 => Some(13), // cutoffwarp lp - 17 => Some(34), // cutoffwarp hp - 18 => Some(36), // cutoffwarp notch - 19 => Some(35), // cutoffwarp bp - 20 => Some(43), // obxd 2p hp - 21 => Some(45), // obxd 2p notch - 22 => Some(44), // obxd 2p bp - 23 => Some(2), // bp24 - 24 => Some(48), // notch24 - 25 => Some(7), // comb- - 26 => Some(8), // allpass - 27 => Some(37), // cutoffwarp ap - 28 => Some(38), // resonancewarp lp - 29 => Some(39), // resonancewarp hp - 30 => Some(40), // resonancewarp notch - 32 => Some(41), // resonancewarp ap - 33 => Some(32), // tripole - 35 => Some(47), // obxd xpander - // 31 (resonancewarp bp) and 34 (cytomic svf, handled via subtype) - // need special treatment and are returned as None here. - _ => None, - } -} - -/// Map a Surge filter subtype onto our `FilterSubtype` discriminant. -/// Surge subtypes are per-family (stage counts, saturation amounts), so -/// this is an approximation for most families. -fn map_filter_subtype(surge_type: i32, surge_subtype: i32) -> (u8, &'static str) { - match surge_type { - // Cytomic SVF: subtype selects the mode; we map it onto the matching - // dedicated filter type instead, so the subtype itself is Clean. - 34 => ( - 0, - "cytomic svf subtype selects lp/hp/bp/notch/peak/ap/bell/shelf; mapped to the matching filter type", - ), - // OB-Xd Xpander: 15 modes in the same order as ours (XpanderLp1 = 7). - 35 => ((7 + surge_subtype.clamp(0, 14)) as u8, ""), - // K35: saturation amount. - 13 | 14 => match surge_subtype { - 0 => (0, ""), - 1 | 2 => (1, ""), - _ => (2, ""), - }, - // Cutoff warp: saturator family approximated; stage count lost. - 16..=19 | 27 => match surge_subtype % 3 { - 1 => (4, "cutoff-warp stage count not represented"), - 2 => (6, "cutoff-warp stage count not represented"), - _ => (0, "cutoff-warp stage count not represented"), - }, - // Resonance warp. - 28..=32 => (0, "resonance-warp stage count not represented"), - // LP/HP/BP/notch Standard/Driven/Clean. - 1 | 2 | 4 | 5 | 6 | 7 | 23 | 24 | 26 => match surge_subtype { - 1 => (1, ""), - 2 => (0, ""), - _ => (0, ""), - }, - // Everything else (ladder slopes, vintage ladder, tri-pole, obxd - // 4-pole, comb wet): no direct counterpart. - _ => ( - 0, - "filter subtype has no Maolan Synth equivalent, using clean", - ), - } -} - -/// Surge `play_mode` (`pm_*`) to our `PlayMode` discriminant. -fn map_play_mode(surge_mode: i32) -> Option { - match surge_mode { - 0 => Some(0), // poly - 1 => Some(1), // mono - 2 => Some(4), // mono st - 3 => Some(5), // mono fp - 4 => Some(4), // mono st+fp -> mono st (approximation) - 5 => Some(3), // latch - _ => None, - } -} - -/// Surge LFO shape (`lt_*`) to our `LfoShape` discriminant. Formula (9) has -/// no equivalent. -fn map_lfo_shape(surge_shape: i32) -> Option { - match surge_shape { - 0 => Some(0), // sine - 1 => Some(1), // triangle - 2 => Some(4), // square - 3 => Some(3), // ramp - 4 => Some(6), // noise - 5 => Some(5), // s&h - 6 => Some(7), // envelope - 7 => Some(8), // stepseq - 8 => Some(9), // mseg - _ => None, - } -} - -/// Surge mod source (`ms_*`) to our `ModSource`. -fn map_mod_source(surge_source: i32) -> Option { - use ModSource::*; - Some(match surge_source { - 1 => Velocity, - 2 => Keytrack, - 3 => PolyAftertouch, - 4 => Aftertouch, - 5 => PitchBend, - 6 => ModWheel, - 15 => AmpEg, - 16 => FilterEg, - 17 => Lfo1, - 18 => Lfo2, - 19 => Lfo3, - 20 => Lfo4, - 21 => Lfo5, - 22 => Lfo6, - 23 => SceneLfo1, - 24 => SceneLfo2, - 25 => SceneLfo3, - 26 => SceneLfo4, - 27 => SceneLfo5, - 28 => SceneLfo6, - 29 => MpeTimbre, - 30 => ReleaseVelocity, - 31 => RandomBipolar, - 32 => RandomUnipolar, - 33 => AlternateBipolar, - 34 => AlternateUnipolar, - 35 => Breath, - 36 => Expression, - 37 => Sustain, - 38 => LowestKey, - 39 => HighestKey, - 40 => LatestKey, - _ => return None, - }) -} - -fn mod_source_reason(surge_source: i32) -> &'static str { - match surge_source { - 0 => "legacy 'original' source has no Maolan Synth equivalent", - 7..=14 => "macro/CC sources are not imported: Maolan Synth has no macro knobs", - _ => "mod source has no Maolan Synth equivalent", - } -} - -/// How a Surge modulation depth (in the target's native units) is scaled -/// onto our −1..1 route depth. -#[derive(Debug, Clone, Copy)] -enum DepthKind { - /// Target is 0..1 on both sides. - Direct01, - /// Target is −1..1 on both sides. - Bipolar, - /// Surge depth in semitones; our full scale is ±1 octave. - Semitones, - /// Surge depth in semitones; our full scale is ±60 semitones. - CutoffSemitones, - /// Surge resonance 0..1; ours is 0..10. - Resonance, - /// Surge `ct_envtime`-style log2 seconds depth; convert to seconds at a - /// 1 s base. - SecondsPow2, - /// Same for LFO rate (Hz at a 1 Hz base). - HzPow2, - /// Waveshaper drive in dB onto our 0..1 (±24 dB full scale). - Db24, -} - -impl DepthKind { - fn convert(self, depth: f32) -> f64 { - let value = match self { - DepthKind::Direct01 | DepthKind::Bipolar => depth, - DepthKind::Semitones => depth / 12.0, - DepthKind::CutoffSemitones => depth / 60.0, - DepthKind::Resonance => depth * 10.0, - DepthKind::SecondsPow2 | DepthKind::HzPow2 => (2.0f32).powf(depth) - 1.0, - DepthKind::Db24 => depth / 48.0, - }; - value.clamp(-1.0, 1.0) as f64 - } -} - -/// Per-oscillator `ParamId` lookup. -fn osc_param(osc: usize, name: &str) -> ParamId { - use ParamId::*; - match (osc, name) { - (0, "type") => Osc1Type, - (0, "enabled") => Osc1Enabled, - (0, "octave") => Osc1Octave, - (0, "semitone") => Osc1Semitone, - (0, "fine") => Osc1Fine, - (0, "shape") => Osc1Shape, - (0, "skew") => Osc1Skew, - (0, "formant") => Osc1Width2, // unused for osc 1/2; see caller - (0, "level") => Osc1Level, - (0, "mute") => Osc1Mute, - (0, "solo") => Osc1Solo, - (0, "route") => Osc1Route, - (0, "sync") => Osc1Sync, - (0, "sublevel") => Osc1SubLevel, - (0, "unison") => Osc1Unison, - (0, "detune") => Osc1UnisonDetune, - (0, "spread") => Osc1UnisonSpread, - (0, "fmdepth") => Osc1FmDepth, - (0, "shaper") => Osc1Shaper, - (1, "type") => Osc2Type, - (1, "enabled") => Osc2Enabled, - (1, "octave") => Osc2Octave, - (1, "semitone") => Osc2Semitone, - (1, "fine") => Osc2Fine, - (1, "shape") => Osc2Shape, - (1, "skew") => Osc2Skew, - (1, "level") => Osc2Level, - (1, "mute") => Osc2Mute, - (1, "solo") => Osc2Solo, - (1, "route") => Osc2Route, - (1, "sync") => Osc2Sync, - (1, "sublevel") => Osc2SubLevel, - (1, "unison") => Osc2Unison, - (1, "detune") => Osc2UnisonDetune, - (1, "spread") => Osc2UnisonSpread, - (1, "fmdepth") => Osc2FmDepth, - (1, "shaper") => Osc2Shaper, - (2, "type") => Osc3Type, - (2, "enabled") => Osc3Enabled, - (2, "octave") => Osc3Octave, - (2, "semitone") => Osc3Semitone, - (2, "fine") => Osc3Fine, - (2, "shape") => Osc3Shape, - (2, "skew") => Osc3Skew, - (2, "formant") => Osc3Formant, - (2, "level") => Osc3Level, - (2, "mute") => Osc3Mute, - (2, "solo") => Osc3Solo, - (2, "route") => Osc3Route, - (2, "sync") => Osc3Sync, - (2, "sublevel") => Osc3SubLevel, - (2, "unison") => Osc3Unison, - (2, "detune") => Osc3UnisonDetune, - (2, "spread") => Osc3UnisonSpread, - (2, "fmdepth") => Osc3FmDepth, - (2, "shaper") => Osc3Shaper, - _ => unreachable!("invalid osc param lookup"), - } -} - -/// Per-voice-LFO `ParamId` lookup (lfo index 0..5). -fn lfo_param(lfo: usize, name: &str) -> ParamId { - use ParamId::*; - match (lfo, name) { - (0, "rate") => Lfo1Rate, - (0, "shape") => Lfo1Shape, - (0, "amount") => Lfo1Amount, - (0, "deform") => Lfo1Deform, - (0, "trigger") => Lfo1Trigger, - (0, "envdelay") => Lfo1EnvDelay, - (0, "envattack") => Lfo1EnvAttack, - (0, "envhold") => Lfo1EnvHold, - (0, "envdecay") => Lfo1EnvDecay, - (0, "envsustain") => Lfo1EnvSustain, - (0, "envrelease") => Lfo1EnvRelease, - (0, "phase") => Lfo1Phase, - (0, "unipolar") => Lfo1Unipolar, - (0, "deformtype") => Lfo1DeformType, - (1, "rate") => Lfo2Rate, - (1, "shape") => Lfo2Shape, - (1, "amount") => Lfo2Amount, - (1, "deform") => Lfo2Deform, - (1, "trigger") => Lfo2Trigger, - (1, "envdelay") => Lfo2EnvDelay, - (1, "envattack") => Lfo2EnvAttack, - (1, "envhold") => Lfo2EnvHold, - (1, "envdecay") => Lfo2EnvDecay, - (1, "envsustain") => Lfo2EnvSustain, - (1, "envrelease") => Lfo2EnvRelease, - (1, "phase") => Lfo2Phase, - (1, "unipolar") => Lfo2Unipolar, - (1, "deformtype") => Lfo2DeformType, - (2, "rate") => Lfo3Rate, - (2, "shape") => Lfo3Shape, - (2, "amount") => Lfo3Amount, - (2, "deform") => Lfo3Deform, - (2, "trigger") => Lfo3Trigger, - (2, "envdelay") => Lfo3EnvDelay, - (2, "envattack") => Lfo3EnvAttack, - (2, "envhold") => Lfo3EnvHold, - (2, "envdecay") => Lfo3EnvDecay, - (2, "envsustain") => Lfo3EnvSustain, - (2, "envrelease") => Lfo3EnvRelease, - (2, "phase") => Lfo3Phase, - (2, "unipolar") => Lfo3Unipolar, - (2, "deformtype") => Lfo3DeformType, - (3, "rate") => Lfo4Rate, - (3, "shape") => Lfo4Shape, - (3, "amount") => Lfo4Amount, - (3, "deform") => Lfo4Deform, - (3, "trigger") => Lfo4Trigger, - (3, "envdelay") => Lfo4EnvDelay, - (3, "envattack") => Lfo4EnvAttack, - (3, "envhold") => Lfo4EnvHold, - (3, "envdecay") => Lfo4EnvDecay, - (3, "envsustain") => Lfo4EnvSustain, - (3, "envrelease") => Lfo4EnvRelease, - (3, "phase") => Lfo4Phase, - (3, "unipolar") => Lfo4Unipolar, - (3, "deformtype") => Lfo4DeformType, - (4, "rate") => Lfo5Rate, - (4, "shape") => Lfo5Shape, - (4, "amount") => Lfo5Amount, - (4, "deform") => Lfo5Deform, - (4, "trigger") => Lfo5Trigger, - (4, "envdelay") => Lfo5EnvDelay, - (4, "envattack") => Lfo5EnvAttack, - (4, "envhold") => Lfo5EnvHold, - (4, "envdecay") => Lfo5EnvDecay, - (4, "envsustain") => Lfo5EnvSustain, - (4, "envrelease") => Lfo5EnvRelease, - (4, "phase") => Lfo5Phase, - (4, "unipolar") => Lfo5Unipolar, - (4, "deformtype") => Lfo5DeformType, - (5, "rate") => Lfo6Rate, - (5, "shape") => Lfo6Shape, - (5, "amount") => Lfo6Amount, - (5, "deform") => Lfo6Deform, - (5, "trigger") => Lfo6Trigger, - (5, "envdelay") => Lfo6EnvDelay, - (5, "envattack") => Lfo6EnvAttack, - (5, "envhold") => Lfo6EnvHold, - (5, "envdecay") => Lfo6EnvDecay, - (5, "envsustain") => Lfo6EnvSustain, - (5, "envrelease") => Lfo6EnvRelease, - (5, "phase") => Lfo6Phase, - (5, "unipolar") => Lfo6Unipolar, - (5, "deformtype") => Lfo6DeformType, - _ => unreachable!("invalid lfo param lookup"), - } -} - -/// Per-scene-LFO `ParamId` lookup (scene lfo index 0..5, Surge units 6..11). -fn scene_lfo_param(lfo: usize, name: &str) -> ParamId { - use ParamId::*; - match (lfo, name) { - (0, "rate") => SceneLfo1Rate, - (0, "shape") => SceneLfo1Shape, - (0, "amount") => SceneLfo1Amount, - (0, "deform") => SceneLfo1Deform, - (1, "rate") => SceneLfo2Rate, - (1, "shape") => SceneLfo2Shape, - (1, "amount") => SceneLfo2Amount, - (1, "deform") => SceneLfo2Deform, - (2, "rate") => SceneLfo3Rate, - (2, "shape") => SceneLfo3Shape, - (2, "amount") => SceneLfo3Amount, - (2, "deform") => SceneLfo3Deform, - (3, "rate") => SceneLfo4Rate, - (3, "shape") => SceneLfo4Shape, - (3, "amount") => SceneLfo4Amount, - (3, "deform") => SceneLfo4Deform, - (4, "rate") => SceneLfo5Rate, - (4, "shape") => SceneLfo5Shape, - (4, "amount") => SceneLfo5Amount, - (4, "deform") => SceneLfo5Deform, - (5, "rate") => SceneLfo6Rate, - (5, "shape") => SceneLfo6Shape, - (5, "amount") => SceneLfo6Amount, - (5, "deform") => SceneLfo6Deform, - _ => unreachable!("invalid scene lfo param lookup"), - } -} - -/// EG parameter lookup. Surge unit 1 is the amp EG, unit 2 the filter EG. -fn eg_param(eg: usize, name: &str) -> ParamId { - use ParamId::*; - match (eg, name) { - (1, "attack") => AmpAttack, - (1, "decay") => AmpDecay, - (1, "sustain") => AmpSustain, - (1, "release") => AmpRelease, - (1, "mode") => AmpEgMode, - (1, "attackcurve") => AmpEgAttackCurve, - (1, "decaycurve") => AmpEgDecayCurve, - (1, "releasecurve") => AmpEgReleaseCurve, - (2, "attack") => FilterAttack, - (2, "decay") => FilterDecay, - (2, "sustain") => FilterSustain, - (2, "release") => FilterRelease, - (2, "mode") => FilterEgMode, - (2, "attackcurve") => FilterEgAttackCurve, - (2, "decaycurve") => FilterEgDecayCurve, - (2, "releasecurve") => FilterEgReleaseCurve, - _ => unreachable!("invalid eg param lookup"), - } -} - -/// Convert a parsed Surge `.fxp` into Maolan Synth parameter values. -pub fn convert_patch(file: &SurgePatchFile) -> Result { - let patch = parse_xml(&file.xml)?; - let mut report = Report::default(); - - // Embedded wavetables cannot be injected into Maolan Synth's oscillators. - for (slot, embedded) in file.embedded_wavetables.iter().enumerate() { - if *embedded { - report.skip( - format!( - "scene {} osc {} embedded wavetable", - slot / 3 + 1, - slot % 3 + 1 - ), - "Maolan Synth cannot load wavetables embedded in preset files", - ); - } - } - - // Choose which Surge scene to import: the active scene for single mode, - // scene A otherwise; the other scene is reported as skipped. - let scene_active = get(&patch, "", "scene_active") - .and_then(|param| param.as_int()) - .unwrap_or(0); - let scenemode = get(&patch, "", "scenemode") - .and_then(|param| param.as_int()) - .unwrap_or(0); - let prefix = match (scenemode, scene_active) { - (0, 1) => "b_", - _ => "a_", - }; - if scenemode != 0 { - let mode = match scenemode { - 1 => "key split", - 2 => "dual", - 3 => "channel split", - _ => "unknown", - }; - report.skip( - if prefix == "a_" { "scene B" } else { "scene A" }, - format!( - "patch plays in {mode} mode; Maolan Synth is single-scene and imported scene {}", - if prefix == "a_" { "A" } else { "B" } - ), - ); - } else if patch.has_scene_b && prefix == "a_" { - report.note("scene B exists in the patch but is not active; only scene A imported"); - } - - let mut values: Vec<(ParamId, f64)> = Vec::new(); - let mut push = |id: ParamId, value: f64| values.push((id, value)); - - convert_effects(&patch, &mut report); - convert_globals(&patch, prefix, &mut push, &mut report); - convert_oscillators(&patch, prefix, &mut push, &mut report); - convert_filters(&patch, prefix, &mut push, &mut report); - convert_envelopes(&patch, prefix, &mut push, &mut report); - convert_lfos(&patch, prefix, &mut push, &mut report); - convert_modulation(&patch, prefix, &mut push, &mut report); - - let name = if patch.meta_name.is_empty() { - file.name.clone() - } else { - patch.meta_name.clone() - }; - Ok(LoadResult { - name, - values, - report, - }) -} - -/// Effects are deliberately ignored; report how much was skipped so it is -/// visible the data was seen and dropped on purpose. -fn convert_effects(patch: &ParsedPatch, report: &mut Report) { - let mut active_slots = Vec::new(); - for slot in 1..=16 { - let name = format!("fx{slot}_type"); - if let Some(param) = patch.params.get(&name) - && param.as_int().unwrap_or(0) != 0 - { - active_slots.push(slot); - } - } - match active_slots.len() { - 0 => {} - 1 => report.skip( - format!("fx slot {}", active_slots[0]), - "effect ignored on request: Maolan Synth has no effect section", - ), - n => report.skip( - format!("{n} fx slots"), - "effects ignored on request: Maolan Synth has no effect section", - ), - } -} - -fn convert_globals( - patch: &ParsedPatch, - prefix: &str, - push: &mut dyn FnMut(ParamId, f64), - report: &mut Report, -) { - // Master volume is stored in dB (`ct_decibel_attenuation_clipper`, range - // -48..0), while the scene volume is a linear amplitude - // (`ct_amplitude_clipper`). Convert the master value before combining. - let global_db = patch - .params - .get("volume") - .and_then(|param| param.as_float(true)) - .map(f64::from); - let scene_volume = get(patch, prefix, "volume") - .and_then(|param| param.as_float(true)) - .map(f64::from); - if global_db.is_some() || scene_volume.is_some() { - let global_amp = global_db.map(|db| 10f64.powf(db / 20.0)).unwrap_or(1.0); - let combined = global_amp * scene_volume.unwrap_or(1.0); - push(ParamId::Volume, clamp01(combined as f32)); - if scene_volume.is_some_and(|volume| volume < 1.0) { - report.note("scene volume folded into master volume"); - } - } - - if let Some(param) = patch.params.get("polylimit") - && let Some(limit) = param.as_int() - { - push(ParamId::Polyphony, (limit.clamp(1, 32) - 1) as f64); - } - if let Some(param) = get(patch, prefix, "pbrange_up") - && let Some(st) = param.as_float(true) - { - push(ParamId::PitchBendUp, st.clamp(0.0, 24.0) as f64); - } - if let Some(param) = get(patch, prefix, "pbrange_dn") - && let Some(st) = param.as_float(true) - { - push(ParamId::PitchBendDown, st.clamp(0.0, 24.0) as f64); - } - if let Some(param) = get(patch, prefix, "portamento") - && let Some(raw) = param.as_float(true) - { - push( - ParamId::Portamento, - units::portatime_seconds(raw).clamp(0.0, 5.0) as f64, - ); - } - if let Some(param) = get(patch, prefix, "polymode") { - match param.as_int().and_then(map_play_mode) { - Some(mode) => push(ParamId::PlayMode, mode as f64), - None => report.skip( - format!("{prefix}polymode"), - "play mode has no Maolan Synth equivalent", - ), - } - } - - // FM routing: Surge fm_switch 0=off, 1="2>1", 2="3>2>1", 3="2>1<3". - if let Some(param) = get(patch, prefix, "fm_switch") - && let Some(mode) = param.as_int() - { - let mapped = match mode { - 0 => 0, - 1 => 7, // osc2 -> osc1 - 2 => 3, // osc1 -> osc2 -> osc3 chain - 3 => 8, // osc3 -> osc1 (approximation of "2>1<3") - _ => -1, - }; - if mapped >= 0 { - push(ParamId::OscFmMode, mapped as f64); - if mode == 3 { - report.note("fm routing '2>1<3' approximated as osc3 -> osc1"); - } - } else { - report.skip( - format!("{prefix}fm_switch"), - format!("fm routing mode {mode} unknown"), - ); - } - } - if let Some(param) = get(patch, prefix, "fm_depth") - && let Some(depth) = param.as_float(true) - { - push(ParamId::OscFmDepth, clamp01(depth)); - } - if let Some(param) = get(patch, prefix, "drift") - && let Some(drift) = param.as_float(true) - { - push(ParamId::OscDrift, clamp01(drift)); - } - if let Some(param) = get(patch, prefix, "pan") - && let Some(pan) = param.as_float(true) - { - push(ParamId::Pan, clamp_bipolar(pan)); - } - if let Some(param) = get(patch, prefix, "pan2") - && let Some(width) = param.as_float(true) - { - // Surge stores stereo width bipolar; ours is 0..1. - push(ParamId::Width, clamp01((width + 1.0) * 0.5)); - } - if let Some(param) = get(patch, prefix, "level_pfg") - && let Some(db) = param.as_float(true) - { - // ct_decibel: convert to linear gain in our 0..2 range. - push( - ParamId::PreFilterGain, - 10f32.powf(db / 20.0).clamp(0.0, 2.0) as f64, - ); - } - if let Some(param) = get(patch, prefix, "vca_level") - && let Some(db) = param.as_float(true) - { - // ct_decibel (-48..48, 0 = unity): convert to linear gain in our 0..2 - // range, like level_pfg above. - push( - ParamId::VcaLevel, - 10f32.powf(db / 20.0).clamp(0.0, 2.0) as f64, - ); - } - if let Some(param) = get(patch, prefix, "vca_velsense") - && let Some(db) = param.as_float(true) - { - // ct_decibel_attenuation (-48..0, 0 = velocity ignored). Our 0..1 - // vel sense interpolates between "velocity ignored" (0) and full - // tracking (1), so normalize the attenuation depth. - push(ParamId::VcaVelSense, clamp01(-db / 48.0)); - } -} - -fn convert_oscillators( - patch: &ParsedPatch, - prefix: &str, - push: &mut dyn FnMut(ParamId, f64), - report: &mut Report, -) { - // Scene-level transpose applied to every oscillator. - let scene_transpose = scene_pitch_offset(patch, prefix); - - let mut wavetable_noted = false; - let mut keytrack_pushed = false; - - for osc in 0..3 { - let name = format!("osc{}", osc + 1); - let Some(type_param) = get(patch, prefix, &format!("{name}_type")) else { - continue; - }; - let Some(surge_type) = type_param.as_int() else { - continue; - }; - let Some(our_type) = map_osc_type(surge_type) else { - report.skip( - format!("{prefix}{name}"), - if surge_type == 4 { - "audio-input oscillator has no Maolan Synth equivalent".to_string() - } else { - format!("oscillator type {surge_type} has no Maolan Synth equivalent") - }, - ); - continue; - }; - push(osc_param(osc, "type"), our_type as f64); - if surge_type == 1 { - push( - [ - ParamId::Osc1Waveform, - ParamId::Osc2Waveform, - ParamId::Osc3Waveform, - ][osc], - 4.0, - ); - } - // Surge has no per-oscillator on/off: all three always run and the - // mixer mute is the only switch. Maolan's Enabled defaults are off - // for osc 2/3, so import every oscillator as enabled and let the - // imported mute state (pushed below) carry the off state. A muted - // osc still functions as an FM modulator, exactly like Surge. - push(osc_param(osc, "enabled"), 1.0); - - if (our_type == 3 || our_type == 4) && !wavetable_noted { - report.note( - "wavetable/window oscillator table selection is not imported; the current table is kept", - ); - wavetable_noted = true; - } - - if let Some(param) = get(patch, prefix, &format!("{name}_octave")) - && let Some(oct) = param.as_int() - { - // Surge: -3..+3, Maolan: 0..6 with 3 = center. - push(osc_param(osc, "octave"), (oct + 3).clamp(0, 6) as f64); - } - if let Some(param) = get(patch, prefix, &format!("{name}_pitch")) - && let Some(pitch) = param.as_float(true) - { - let semitones = (pitch + scene_transpose).clamp(-12.0, 12.0); - if (pitch + scene_transpose - semitones).abs() > f32::EPSILON { - report.note(format!( - "osc{} pitch transposed by the scene offset was clamped to +/-12 semitones", - osc + 1 - )); - } - push( - osc_param(osc, "semitone"), - (semitones.round() + 12.0) as f64, - ); - push( - osc_param(osc, "fine"), - ((semitones - semitones.round()) * 100.0) as f64, - ); - } - if let Some(param) = get(patch, prefix, &format!("{name}_keytrack")) - && let Some(track) = param.as_float(true) - && !keytrack_pushed - { - // Maolan Synth has a single wavetable keytrack parameter. - push(ParamId::WavetableKeytrack, clamp01(track)); - keytrack_pushed = true; - } - if get(patch, prefix, &format!("{name}_retrigger")).is_some() { - report.note(format!( - "{prefix}{name}: per-oscillator retrigger flag not imported (no equivalent)" - )); - } - - // Mixer: level/mute/solo/route per oscillator source. - if let Some(param) = get(patch, prefix, &format!("level_o{}", osc + 1)) - && let Some(level) = param.as_float(true) - { - push(osc_param(osc, "level"), clamp01(level)); - } - if let Some(param) = get(patch, prefix, &format!("mute_o{}", osc + 1)) - && let Some(mute) = param.as_int() - { - push(osc_param(osc, "mute"), mute.clamp(0, 1) as f64); - } - if let Some(param) = get(patch, prefix, &format!("solo_o{}", osc + 1)) - && let Some(solo) = param.as_int() - { - push(osc_param(osc, "solo"), solo.clamp(0, 1) as f64); - } - if let Some(param) = get(patch, prefix, &format!("route_o{}", osc + 1)) - && let Some(route) = param.as_int() - { - push(osc_param(osc, "route"), route.clamp(0, 2) as f64); - } - - convert_osc_params(patch, prefix, osc, surge_type, push, report); - } - - // Ring modulation sources: Maolan Synth has routes and combinators but - // no ring level parameters. - if get(patch, prefix, "level_ring12").is_some() { - report.skip( - format!("{prefix}level_ring12/23"), - "ring-modulation levels have no Maolan Synth parameter (routes/combinators are imported)", - ); - } - for (slot, suffix) in [(1, "12"), (2, "23")] { - if let Some(param) = get(patch, prefix, &format!("route_ring{suffix}")) - && let Some(route) = param.as_int() - { - push( - match slot { - 1 => ParamId::Ring12Route, - _ => ParamId::Ring23Route, - }, - route.clamp(0, 2) as f64, - ); - } - // Ring mode lives in the level param's deform_type attribute. - if let Some(param) = get(patch, prefix, &format!("level_ring{suffix}")) - && let Some(mode) = param.deform_type - { - push( - match slot { - 1 => ParamId::Ring12Combinator, - _ => ParamId::Ring23Combinator, - }, - mode.clamp(0, 10) as f64, - ); - } - } - - // Noise source. Surge's noise channel has no on/off either; import it as - // enabled and let NoiseMute carry the off state (Maolan's default is off). - if get(patch, prefix, "level_noise").is_some() || get(patch, prefix, "mute_noise").is_some() { - push(ParamId::NoiseEnabled, 1.0); - } - if let Some(param) = get(patch, prefix, "level_noise") - && let Some(level) = param.as_float(true) - { - push(ParamId::NoiseLevel, clamp01(level)); - } - if let Some(param) = get(patch, prefix, "mute_noise") - && let Some(mute) = param.as_int() - { - push(ParamId::NoiseMute, mute.clamp(0, 1) as f64); - } - if let Some(param) = get(patch, prefix, "solo_noise") - && let Some(solo) = param.as_int() - { - push(ParamId::NoiseSolo, solo.clamp(0, 1) as f64); - } - if let Some(param) = get(patch, prefix, "route_noise") - && let Some(route) = param.as_int() - { - push(ParamId::NoiseRoute, route.clamp(0, 2) as f64); - } - if let Some(param) = get(patch, prefix, "noisecol") - && let Some(color) = param.as_float(true) - { - // Surge: -1..1, Maolan: 0..1. - push(ParamId::NoiseColor, clamp01((color + 1.0) * 0.5)); - } -} - -/// Scene-level octave+pitch offset in semitones. -fn scene_pitch_offset(patch: &ParsedPatch, prefix: &str) -> f32 { - let octave = get(patch, prefix, "octave") - .and_then(|param| param.as_int()) - .unwrap_or(0) as f32; - let pitch = get(patch, prefix, "pitch") - .and_then(|param| param.as_float(true)) - .unwrap_or(0.0); - octave * 12.0 + pitch -} - -/// Per-oscillator-type conversion of Surge `param0..param6`. Meaning and -/// valtype of each slot depend on the oscillator type; see the Surge -/// oscillator `init_ctrltypes` implementations. -fn convert_osc_params( - patch: &ParsedPatch, - prefix: &str, - osc: usize, - surge_type: i32, - push: &mut dyn FnMut(ParamId, f64), - report: &mut Report, -) { - let name = format!("osc{}", osc + 1); - let param = |index: usize| get(patch, prefix, &format!("{name}_param{index}")); - - let float = |index: usize, semantic: bool| -> Option { - param(index).and_then(|p| p.as_float(semantic)) - }; - let int = |index: usize| -> Option { param(index).and_then(|p| p.as_int()) }; - - // Shared unison block used by several osc types (slots 5/6). - let unison = |push: &mut dyn FnMut(ParamId, f64)| { - if let Some(detune) = float(5, true) { - push(osc_param(osc, "detune"), clamp01(detune)); - } - if let Some(voices) = int(6) { - push(osc_param(osc, "unison"), (voices.clamp(1, 16) - 1) as f64); - } - }; - - match surge_type { - // Classic: shape(bip), width1, width2, sub mix, sync, detune, voices. - 0 => { - if let Some(shape) = float(0, true) { - push(osc_param(osc, "skew"), clamp_bipolar(shape)); - } - if let Some(width) = float(1, true) { - push(osc_param(osc, "shape"), clamp01(width)); - } - if let Some(sub) = float(3, true) { - push(osc_param(osc, "sublevel"), clamp01(sub)); - } - if let Some(sync) = float(4, true) { - push(osc_param(osc, "sync"), sync.clamp(0.0, 60.0) as f64); - } - unison(push); - } - // Sine is imported as the Classic sine waveform; only its unison slots - // have a Classic equivalent. - 1 => { - if (0..5).any(|index| param(index).is_some()) { - report.skip( - format!("{prefix}{name}_param0..4"), - "sine-specific parameters have no Classic oscillator equivalent", - ); - } - unison(push); - } - // Wavetable: morph, skew vertical, saturate, formant, skew horizontal, - // detune, voices. - 2 => { - if let Some(morph) = float(0, true) { - push(osc_param(osc, "shape"), clamp01(morph)); - } - if let Some(skew) = float(1, true) { - push(osc_param(osc, "skew"), clamp_bipolar(skew)); - } - if let Some(saturate) = float(2, true) { - push(ParamId::WavetableSaturate, clamp01(saturate)); - } - if let Some(formant) = float(3, true) { - if osc == 2 { - push( - ParamId::Osc3Formant, - (formant + 12.0).clamp(0.0, 24.0) as f64, - ); - } else { - report.skip( - format!("{prefix}{name}_param3"), - "per-oscillator formant only exists on osc 3 in Maolan Synth", - ); - } - } - if let Some(skew_h) = float(4, true) { - push(ParamId::WavetableSkewV, clamp_bipolar(skew_h)); - } - unison(push); - } - // S&H noise: correlation, width, lowcut, highcut, sync, detune, - // voices. - 3 => { - if let Some(correlation) = float(0, true) { - push(ParamId::ShNoiseCorrelation, clamp_bipolar(correlation)); - } - if let Some(width) = float(1, true) { - push(ParamId::ShNoiseWidth, clamp01(width)); - } - if let Some(lowcut) = float(2, true) { - push(ParamId::ShNoiseLowcut, cutoff_hz(lowcut)); - } - if let Some(highcut) = float(3, true) { - push(ParamId::ShNoiseHighcut, cutoff_hz(highcut)); - } - if let Some(sync) = float(4, true) { - push(ParamId::ShNoiseSync, if sync > 0.0 { 1.0 } else { 0.0 }); - } - unison(push); - } - // FM3: m1 amt, m1 ratio, m2 amt, m2 ratio, m3 amt, m3 freq, fb. - 5 => { - if let Some(amount) = float(0, true) { - push(osc_param(osc, "fmdepth"), clamp01(amount)); - } - report.skip( - format!("{prefix}{name}_param1/param3"), - "FM3 modulator ratios have no Maolan Synth parameter", - ); - if let Some(feedback) = float(6, true) { - push(ParamId::Fm3Feedback, clamp01(feedback.max(0.0))); - } - } - // FM2: m1 amt, m1 ratio(int), m2 amt, m2 ratio(int), offset, phase, - // feedback. - 6 => { - if let Some(amount) = float(0, true) { - push(osc_param(osc, "fmdepth"), clamp01(amount)); - } - report.skip( - format!("{prefix}{name}_param1/param3"), - "FM2 modulator ratios have no Maolan Synth parameter", - ); - if let Some(offset) = float(4, true) { - // Surge: -10..10 Hz; ours stores cents-like x100 units. - push( - ParamId::Fm2M12Offset, - (offset * 100.0).clamp(-1000.0, 1000.0) as f64, - ); - report.note("FM2 m1/m2 offset mapped from Hz onto Maolan Synth's x100 scale"); - } - if let Some(phase) = float(5, true) { - push(ParamId::Fm2M12Phase, clamp01(phase)); - } - if let Some(feedback) = float(6, true) { - push(ParamId::Fm2Feedback, clamp01(feedback.max(0.0))); - } - } - // Window: morph, formant, window(int), lowcut, highcut, detune, - // voices. - 7 => { - if let Some(morph) = float(0, true) { - push(osc_param(osc, "shape"), clamp01(morph)); - } - if int(2).is_some() { - report.skip( - format!("{prefix}{name}_param2"), - "window shape selection has no Maolan Synth parameter", - ); - } - if let Some(lowcut) = float(3, true) { - push(ParamId::WindowLowcut, cutoff_hz(lowcut)); - } - if let Some(highcut) = float(4, true) { - push(ParamId::WindowHighcut, cutoff_hz(highcut)); - } - unison(push); - } - // Modern: saw(bip), pulse(bip), tri(bip), width, sync, detune, - // voices. Maolan's Modern oscillator has a waveform selector plus - // shape/skew, so this is an approximation. - 8 => { - let saw = float(0, true).unwrap_or(0.0); - let pulse = float(1, true).unwrap_or(0.0); - let tri = float(2, true).unwrap_or(0.0); - let (waveform, amount) = if saw.abs() >= pulse.abs() && saw.abs() >= tri.abs() { - (2.0, saw) // saw - } else if pulse.abs() >= tri.abs() { - (0.0, pulse) // square/pulse - } else { - (1.0, tri) // triangle - }; - push(osc_param(osc, "shape"), waveform); - push(osc_param(osc, "skew"), clamp_bipolar(amount)); - if let Some(width) = float(3, true) { - let id = match osc { - 0 => ParamId::Osc1Width2, - 1 => ParamId::Osc2Width2, - _ => ParamId::Osc3Width2, - }; - push(id, clamp01(width)); - } - if let Some(sync) = float(4, true) { - push(osc_param(osc, "sync"), sync.clamp(0.0, 60.0) as f64); - } - unison(push); - report.note("modern oscillator 3-way mix reduced to waveform selector + skew"); - } - // String: exciter(int), level, decay1, decay2, detune, balance, - // stiffness. - 9 => { - if let Some(level) = float(1, true) { - push(osc_param(osc, "level"), clamp01(level)); - } - if let Some(decay) = float(2, true) { - push(ParamId::StringDualDecay, clamp01(decay)); - } - if let Some(detune) = float(4, true) { - push(ParamId::StringDualDetune, clamp_bipolar(detune)); - } - if let Some(balance) = float(5, true) { - push(ParamId::StringStereoSpread, clamp_bipolar(balance)); - } - report.skip( - format!("{prefix}{name}_param0/3/6"), - "string exciter model, second-string decay and stiffness have no Maolan Synth parameter", - ); - } - // Twist: engine(int), harmonics, timbre, morph, aux mix, lpg - // response, lpg decay. - 10 => { - report.skip( - format!("{prefix}{name}_param0..3"), - "twist engine/harmonics/timbre/morph have no Maolan Synth parameter (models 6-15 are unreachable there)", - ); - if let Some(aux) = float(4, true) { - push(ParamId::TwistAuxMix, clamp_bipolar(aux)); - } - if let Some(response) = float(5, true) { - push(ParamId::TwistLpgResponse, clamp01(response.max(0.0))); - } - if let Some(decay) = float(6, true) { - push(ParamId::TwistLpgDecay, clamp01(decay)); - } - } - // Alias: wave(int), wrap, mask, threshold, bitcrush, detune, voices. - 11 => { - report.skip( - format!("{prefix}{name}_param0/param4"), - "alias wave selector and bitcrush have no Maolan Synth parameter", - ); - if let Some(wrap) = float(1, true) { - push(ParamId::AliasWrap, clamp01(wrap)); - } - if let Some(mask) = float(2, true) { - push(ParamId::AliasMask, clamp01(mask)); - } - if let Some(threshold) = float(3, true) { - push(ParamId::AliasThreshold, clamp01(threshold)); - } - unison(push); - } - _ => {} - } -} - -fn convert_filters( - patch: &ParsedPatch, - prefix: &str, - push: &mut dyn FnMut(ParamId, f64), - report: &mut Report, -) { - for unit in 0..2 { - let name = format!("filter{}", unit + 1); - let type_id = match unit { - 0 => ParamId::F1Type, - _ => ParamId::F2Type, - }; - let subtype_id = match unit { - 0 => ParamId::F1Subtype, - _ => ParamId::F2Subtype, - }; - let enabled_id = match unit { - 0 => ParamId::F1Enabled, - _ => ParamId::F2Enabled, - }; - let cutoff_id = match unit { - 0 => ParamId::F1Cutoff, - _ => ParamId::F2Cutoff, - }; - let resonance_id = match unit { - 0 => ParamId::F1Resonance, - _ => ParamId::F2Resonance, - }; - let eg_amount_id = match unit { - 0 => ParamId::F1EgAmount, - _ => ParamId::F2EgAmount, - }; - let keytrack_id = match unit { - 0 => ParamId::F1KeyTrack, - _ => ParamId::F2KeyTrack, - }; - - let Some(type_param) = get(patch, prefix, &format!("{name}_type")) else { - continue; - }; - let Some(surge_type) = type_param.as_int() else { - continue; - }; - - if surge_type == 0 { - // fut_none: the filter unit is off, not an error. - push(type_id, 0.0); // FilterType::Off - push(enabled_id, 0.0); - continue; - } - push(enabled_id, 1.0); - - let our_type: u8 = if surge_type == 34 { - // Cytomic SVF: subtype selects the mode. - let subtype = get(patch, prefix, &format!("{name}_subtype")) - .and_then(|param| param.as_int()) - .unwrap_or(0); - match subtype.clamp(0, 8) { - 0 => 23, - 1 => 24, - 2 => 25, - 3 => 26, - 4 => 27, - 5 => 28, - 6 => 29, - 7 => 30, - _ => 31, - } - } else { - match map_filter_type(surge_type) { - Some(mapped) => mapped, - None => { - report.skip( - format!("{prefix}{name}_type"), - format!("filter type {surge_type} has no Maolan Synth equivalent"), - ); - continue; - } - } - }; - push(type_id, our_type as f64); - - let surge_subtype = get(patch, prefix, &format!("{name}_subtype")) - .and_then(|param| param.as_int()) - .unwrap_or(0); - let (our_subtype, note) = map_filter_subtype(surge_type, surge_subtype); - push(subtype_id, our_subtype as f64); - if !note.is_empty() { - report.note(format!("filter{}: {note}", unit + 1)); - } - - if let Some(param) = get(patch, prefix, &format!("{name}_cutoff")) - && let Some(raw) = param.as_float(true) - { - if unit == 1 - && get(patch, prefix, "f2_cf_is_offset") - .and_then(|p| p.as_int()) - .unwrap_or(0) - == 1 - { - // Offset mode: the value is a semitone offset, not a - // frequency. Our F2CutoffOffset toggle handles the mode; - // store the offset frequency result as an absolute guess. - let base = get(patch, prefix, "filter1_cutoff") - .and_then(|p| p.as_float(true)) - .unwrap_or(0.0); - push(cutoff_id, cutoff_hz(base + raw)); - } else { - push(cutoff_id, cutoff_hz(raw)); - } - } - if let Some(param) = get(patch, prefix, &format!("{name}_resonance")) - && let Some(resonance) = param.as_float(true) - { - // Surge stores 0..1; ours is 0.01..10. - push(resonance_id, (resonance * 10.0).clamp(0.01, 10.0) as f64); - } - if let Some(param) = get(patch, prefix, &format!("{name}_envmod")) - && let Some(amount) = param.as_float(true) - { - // Surge stores semitones (ct_freq_mod, ±96); ours is ±1 at ±96 st. - push(eg_amount_id, (amount / 96.0).clamp(-1.0, 1.0) as f64); - } - if let Some(param) = get(patch, prefix, &format!("{name}_keytrack")) - && let Some(track) = param.as_float(true) - { - push(keytrack_id, clamp01(track)); - } - } - - if let Some(param) = get(patch, prefix, "f2_cf_is_offset") - && let Some(offset) = param.as_int() - { - push(ParamId::F2CutoffOffset, offset.clamp(0, 1) as f64); - } - if let Some(param) = get(patch, prefix, "f2_link_resonance") - && let Some(link) = param.as_int() - { - push(ParamId::F2ResLink, link.clamp(0, 1) as f64); - } - - // Filter block routing: Surge fbc_names to our FilterRouting. - if let Some(param) = get(patch, prefix, "fb_config") - && let Some(config) = param.as_int() - { - let routing = match config { - 0 => 0, // serial 1 -> series - 1 => 4, // serial 2 - 2 => 5, // serial 3 - 3 => 1, // dual 1 -> parallel - 4 => 6, // dual 2 - 5 => 2, // stereo -> wide (approximation) - 6 => 7, // ring - 7 => 2, // wide - _ => -1, - }; - if routing >= 0 { - push(ParamId::FilterRouting, routing as f64); - if config == 5 { - report.note("filter block 'stereo' mapped to wide routing"); - } - } - } - if let Some(param) = get(patch, prefix, "f_balance") - && let Some(balance) = param.as_float(true) - { - push(ParamId::FilterBalance, clamp_bipolar(balance)); - } - if let Some(param) = get(patch, prefix, "feedback") - && let Some(feedback) = param.as_float(true) - { - push(ParamId::FilterFeedback, clamp_bipolar(feedback)); - } - if let Some(param) = get(patch, prefix, "lowcut") - && let Some(raw) = param.as_float(true) - { - push(ParamId::Lowcut, cutoff_hz(raw)); - } - - // Per-voice waveshaper. - if let Some(param) = get(patch, prefix, "ws_type") - && let Some(shape) = param.as_int() - { - push(ParamId::WaveshaperShape, shape.clamp(0, 45) as f64); - push( - ParamId::WaveshaperEnabled, - if shape == 0 { 0.0 } else { 1.0 }, - ); - } - if let Some(param) = get(patch, prefix, "ws_drive") - && let Some(db) = param.as_float(true) - { - // ct_decibel_narrow +-24 dB onto our 0..1 drive. - push(ParamId::WaveshaperDrive, clamp01((db + 24.0) / 48.0)); - } -} - -fn convert_envelopes( - patch: &ParsedPatch, - prefix: &str, - push: &mut dyn FnMut(ParamId, f64), - report: &mut Report, -) { - // Surge unit 1 = amp EG, unit 2 = filter EG (see adsr[] registration). - for eg in 1..=2 { - for (stage, semantic) in [ - ("attack", "attack"), - ("decay", "decay"), - ("release", "release"), - ] { - let Some(param) = get(patch, prefix, &format!("env{eg}_{stage}")) else { - continue; - }; - let Some(raw) = param.as_float(true) else { - continue; - }; - let seconds = units::envtime_seconds(raw); - if seconds > 10.0 { - report.note(format!( - "{prefix}env{eg} {stage}: {seconds:.1}s exceeds the 10s range and was clamped" - )); - } - push(eg_param(eg, semantic), seconds.clamp(0.0, 10.0) as f64); - if param.temposync { - report.note(format!( - "{prefix}env{eg} {stage}: tempo-synced time converted to absolute seconds" - )); - } - } - if let Some(param) = get(patch, prefix, &format!("env{eg}_sustain")) - && let Some(sustain) = param.as_float(true) - { - push(eg_param(eg, "sustain"), clamp01(sustain)); - } - // Shapes match our enums 1:1 (0..2). - for (stage, key) in [ - ("attack", "attack_shape"), - ("decay", "decay_shape"), - ("release", "release_shape"), - ] { - if let Some(param) = get(patch, prefix, &format!("env{eg}_{key}")) - && let Some(shape) = param.as_int() - { - push( - eg_param(eg, &format!("{stage}curve")), - shape.clamp(0, 2) as f64, - ); - } - } - if get(patch, prefix, &format!("env{eg}_mode")).is_some() { - push(eg_param(eg, "mode"), 0.0); - } - } -} - -fn convert_lfos( - patch: &ParsedPatch, - prefix: &str, - push: &mut dyn FnMut(ParamId, f64), - report: &mut Report, -) { - // Surge units 0..5 are voice LFOs, 6..11 scene LFOs (XML names are - // 0-based: a_lfo0_..a_lfo5_, a_lfo6_..a_lfo11_; modrouting source 17 is - // ms_lfo1, the first voice LFO). - let mut stepseq_imported = false; - for unit in 0..12 { - let name = format!("lfo{unit}_"); - if get(patch, prefix, &format!("{name}shape")).is_none() { - continue; - } - let voice = unit < 6; - let index = unit % 6; - let param_id = |what: &str| { - if voice { - lfo_param(index, what) - } else { - scene_lfo_param(index, what) - } - }; - - let Some(surge_shape) = - get(patch, prefix, &format!("{name}shape")).and_then(|param| param.as_int()) - else { - continue; - }; - let Some(shape) = map_lfo_shape(surge_shape) else { - report.skip( - format!("{prefix}{name}"), - if surge_shape == 9 { - "formula modulator has no Maolan Synth equivalent".to_string() - } else { - format!("lfo shape {surge_shape} unknown") - }, - ); - continue; - }; - push(param_id("shape"), shape as f64); - if shape == 9 { - report.note(format!( - "{prefix}{name}: MSEG shape selected but segment data is not imported" - )); - } - - if let Some(param) = get(patch, prefix, &format!("{name}rate")) - && let Some(raw) = param.as_float(true) - { - let hz = units::lfo_rate_hz(raw); - push(param_id("rate"), hz.clamp(0.01, 100.0) as f64); - if param.temposync { - report.note(format!( - "{prefix}{name}rate: tempo-synced rate converted to absolute Hz" - )); - } - } - if let Some(param) = get(patch, prefix, &format!("{name}magnitude")) - && let Some(amount) = param.as_float(true) - { - push(param_id("amount"), clamp01(amount)); - } - if let Some(param) = get(patch, prefix, &format!("{name}deform")) - && let Some(deform) = param.as_float(true) - { - push(param_id("deform"), clamp_bipolar(deform)); - } - if let Some(param) = get(patch, prefix, &format!("{name}deform")) - && let Some(deform_type) = param.deform_type - && voice - { - push(param_id("deformtype"), deform_type.clamp(0, 2) as f64); - } - if let Some(param) = get(patch, prefix, &format!("{name}trigmode")) - && let Some(trigger) = param.as_int() - && voice - { - push(param_id("trigger"), trigger.clamp(0, 2) as f64); - } - if let Some(param) = get(patch, prefix, &format!("{name}unipolar")) - && let Some(unipolar) = param.as_int() - && voice - { - push(param_id("unipolar"), unipolar.clamp(0, 1) as f64); - } - if let Some(param) = get(patch, prefix, &format!("{name}startphase")) - && let Some(phase) = param.as_float(true) - && voice - { - push(param_id("phase"), phase.clamp(0.0, 1.0) as f64); - } - // LFO EG (DAHDSR). Scene LFOs have no EG in Maolan Synth. - if voice { - for (stage, what) in [ - ("delay", "envdelay"), - ("attack", "envattack"), - ("hold", "envhold"), - ("decay", "envdecay"), - ("release", "envrelease"), - ] { - if let Some(param) = get(patch, prefix, &format!("{name}{stage}")) - && let Some(raw) = param.as_float(true) - { - push( - param_id(what), - units::envtime_seconds(raw).clamp(0.0, 10.0) as f64, - ); - } - } - if let Some(param) = get(patch, prefix, &format!("{name}sustain")) - && let Some(sustain) = param.as_float(true) - { - push(param_id("envsustain"), clamp01(sustain)); - } - } - - // Step sequencer data for stepseq-shaped voice LFOs. - if shape == 8 && voice && !stepseq_imported { - if let Some(sequence) = patch.sequences.iter().find(|sequence| { - sequence - .get("i") - .is_some_and(|value| value.parse::() == Ok(unit)) - }) { - import_step_sequence(sequence, push); - stepseq_imported = true; - } - } else if shape == 8 && voice && stepseq_imported { - report.skip( - format!("{prefix}{name}step sequence"), - "Maolan Synth has a single step sequencer; the first one was imported", - ); - } - } - - // Macros (custom controllers) are not imported; note if any carry state. - if patch.custom_controllers.iter().any(|entry| { - entry - .get("v") - .is_some_and(|value| value != "0.000000" && value != "0") - }) { - report.note("macro knob values are not imported: Maolan Synth has no macro section"); - } -} - -fn import_step_sequence(sequence: &HashMap, push: &mut dyn FnMut(ParamId, f64)) { - use ParamId::*; - for step in 0..16 { - let value = sequence - .get(&format!("s{step}")) - .and_then(|value| value.parse::().ok()) - .unwrap_or(0.0); - // Surge stores steps 0..1 unipolar; ours is -1..1. - let id = match step { - 0 => StepSeq1, - 1 => StepSeq2, - 2 => StepSeq3, - 3 => StepSeq4, - 4 => StepSeq5, - 5 => StepSeq6, - 6 => StepSeq7, - 7 => StepSeq8, - 8 => StepSeq9, - 9 => StepSeq10, - 10 => StepSeq11, - 11 => StepSeq12, - 12 => StepSeq13, - 13 => StepSeq14, - 14 => StepSeq15, - _ => StepSeq16, - }; - push(id, ((value * 2.0 - 1.0).clamp(-1.0, 1.0)) as f64); - } - if let Some(start) = sequence - .get("loop_start") - .and_then(|value| value.parse::().ok()) - { - push(StepSeqLoopStart, start.clamp(0.0, 15.0)); - } - if let Some(end) = sequence - .get("loop_end") - .and_then(|value| value.parse::().ok()) - { - push(StepSeqLoopEnd, end.clamp(0.0, 15.0)); - } - if let Some(shuffle) = sequence - .get("shuffle") - .and_then(|value| value.parse::().ok()) - { - push(StepSeqShuffle, clamp01(shuffle)); - } - // Trigger masks: 64-bit (amp bits 0-15, filter 16-31, pitch 32-47), - // written either as one legacy `trigmask` or three 16-bit lanes. - let mut mask: u64 = 0; - if let Some(legacy) = sequence.get("trigmask").and_then(|value| { - value - .parse::() - .ok() - .or_else(|| u64::from_str_radix(value.trim_start_matches("0x"), 16).ok()) - }) { - mask = legacy; - } - for (lane, shift) in [ - ("trigmask_0to15", 0u64), - ("trigmask_16to31", 16u64), - ("trigmask_32to47", 32u64), - ] { - if let Some(word) = sequence - .get(lane) - .and_then(|value| value.parse::().ok()) - { - mask |= (word & 0xffff) << shift; - } - } - push(StepSeqTrigAmp, (mask & 0xffff) as f64); - push(StepSeqTrigFilter, ((mask >> 16) & 0xffff) as f64); - push(StepSeqTrigPitch, ((mask >> 32) & 0xffff) as f64); -} - -fn convert_modulation( - patch: &ParsedPatch, - prefix: &str, - push: &mut dyn FnMut(ParamId, f64), - report: &mut Report, -) { - // Oscillator types of the imported scene, needed to resolve param0/param1 - // mod targets (their meaning is per oscillator type). - let mut osc_types = [0i32; 3]; - for (osc, osc_type) in osc_types.iter_mut().enumerate() { - *osc_type = get(patch, prefix, &format!("osc{}_type", osc + 1)) - .and_then(|param| param.as_int()) - .unwrap_or(0); - } - - let mut route = 0usize; - let mut depth_note = false; - let mut unroutable = 0usize; - let mut fx_send_routes = 0usize; - - // Candidate mod targets: every parameter of the imported scene plus the - // global volume. FX parameter elements are excluded (effects ignored). - let mut names: Vec<&String> = patch - .params - .keys() - .filter(|key| key.starts_with(prefix) || key.as_str() == "volume") - .collect(); - names.sort(); - - for name in names { - let stripped = &name[prefix.len()..]; - let Some(param) = patch.params.get(name.as_str()) else { - continue; - }; - if param.routings.is_empty() { - continue; - } - let Some((target, depth_kind)) = mod_target_for(stripped, &osc_types) else { - let active = param - .routings - .iter() - .filter(|routing| !routing.muted) - .count(); - if active > 0 { - if stripped.starts_with("send_fx") { - fx_send_routes += active; - } else { - unroutable += active; - } - } - continue; - }; - for routing in ¶m.routings { - if routing.muted { - continue; - } - if route >= 12 { - report.skip( - format!("modrouting -> {name}"), - "mod matrix full (12 routes); Surge patches may use more", - ); - continue; - } - let Some(source) = map_mod_source(routing.source) else { - report.skip( - format!("modrouting -> {name}"), - mod_source_reason(routing.source), - ); - continue; - }; - let depth = depth_kind.convert(routing.depth); - if !depth_note { - report.note("modulation depths converted approximately from Surge native units"); - depth_note = true; - } - let base = 83 + route * 3; - let source_id = ParamId::from_raw(base as u32).expect("route source id"); - let target_id = ParamId::from_raw((base + 1) as u32).expect("route target id"); - let depth_id = ParamId::from_raw((base + 2) as u32).expect("route depth id"); - push(source_id, source as u8 as f64); - push(target_id, target as u8 as f64); - push(depth_id, depth); - route += 1; - } - } - - if unroutable > 0 { - report.note(format!( - "{unroutable} modulation route(s) skipped: their targets are not exposed in Maolan Synth's mod matrix (osc params beyond shape/skew, keytrack, feedback, sends, ...)" - )); - } - if fx_send_routes > 0 { - report.skip( - format!("{fx_send_routes} routes to fx sends"), - "effect routing ignored on request: Maolan Synth has no effect section", - ); - } -} - -/// Resolve a Surge parameter storage name (scene prefix stripped) to our -/// mod-matrix target plus the depth conversion for its native units. -fn mod_target_for(name: &str, osc_types: &[i32; 3]) -> Option<(ModTarget, DepthKind)> { - use DepthKind::*; - use ModTarget::*; - // Oscillator pitch/level. - for osc in 0..3 { - if name == format!("osc{}_pitch", osc + 1) { - return Some(([Osc1Pitch, Osc2Pitch, Osc3Pitch][osc], Semitones)); - } - if name == format!("level_o{}", osc + 1) { - return Some(([Osc1Level, Osc2Level, Osc3Level][osc], Direct01)); - } - // Osc shape/skew via param0/param1 for classic and wavetable oscs. - if name == format!("osc{}_param0", osc + 1) { - return match osc_types[osc] { - // Classic param0 = shape (bipolar) -> our skew. - 0 => Some(([Osc1Skew, Osc2Skew, Osc3Skew][osc], Bipolar)), - // Wavetable/window param0 = morph. - 2 | 7 => Some(([Osc1Shape, Osc2Shape, Osc3Shape][osc], Direct01)), - _ => None, - }; - } - if name == format!("osc{}_param1", osc + 1) && osc_types[osc] == 0 { - // Classic width1 -> our shape. - return Some(([Osc1Shape, Osc2Shape, Osc3Shape][osc], Direct01)); - } - } - // Filters. - for unit in 0..2 { - if name == format!("filter{}_cutoff", unit + 1) { - return Some(([Filter1Cutoff, Filter2Cutoff][unit], CutoffSemitones)); - } - if name == format!("filter{}_resonance", unit + 1) { - return Some(([Filter1Resonance, Filter2Resonance][unit], Resonance)); - } - if name == format!("filter{}_envmod", unit + 1) { - return Some(([Filter1EgAmount, Filter2EgAmount][unit], Bipolar)); - } - } - // Envelopes: env1 = amp, env2 = filter. - for (eg, stages) in [ - (1, [AmpAttack, AmpDecay, AmpSustain, AmpRelease]), - (2, [FilterAttack, FilterDecay, FilterSustain, FilterRelease]), - ] { - for (stage, target) in [ - ("attack", stages[0]), - ("decay", stages[1]), - ("sustain", stages[2]), - ("release", stages[3]), - ] { - if name == format!("env{eg}_{stage}") { - let kind = if stage == "sustain" { - Direct01 - } else { - SecondsPow2 - }; - return Some((target, kind)); - } - } - } - // Voice LFOs (0..5). - for unit in 0..6 { - if name == format!("lfo{unit}_rate") { - return Some(( - [Lfo1Rate, Lfo2Rate, Lfo3Rate, Lfo4Rate, Lfo5Rate, Lfo6Rate][unit], - HzPow2, - )); - } - if name == format!("lfo{unit}_magnitude") { - return Some(( - [ - Lfo1Amount, Lfo2Amount, Lfo3Amount, Lfo4Amount, Lfo5Amount, Lfo6Amount, - ][unit], - Direct01, - )); - } - if name == format!("lfo{unit}_deform") { - return Some(( - [ - Lfo1Deform, Lfo2Deform, Lfo3Deform, Lfo4Deform, Lfo5Deform, Lfo6Deform, - ][unit], - Bipolar, - )); - } - if name == format!("lfo{unit}_startphase") { - return Some(( - [ - Lfo1Phase, Lfo2Phase, Lfo3Phase, Lfo4Phase, Lfo5Phase, Lfo6Phase, - ][unit], - Direct01, - )); - } - } - // Output and misc. - let simple: &[(&str, ModTarget, DepthKind)] = &[ - ("volume", OutputVolume, Direct01), - ("pan", OutputPan, Bipolar), - ("fm_depth", OscFmDepth, Direct01), - ("level_noise", NoiseLevel, Direct01), - ("ws_drive", WaveshaperDrive, Db24), - ("portamento", Portamento, SecondsPow2), - ]; - for (key, target, kind) in simple { - if name == *key { - return Some((*target, *kind)); - } - } - None -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::synth::params::ParamId; - - /// Wrap a `` XML document in a valid FPCh/sub3 container. - fn wrap(xml: &str) -> Vec { - let xml_bytes = xml.as_bytes(); - let mut payload = Vec::new(); - payload.extend_from_slice(b"sub3"); - payload.extend_from_slice(&(xml_bytes.len() as u32).to_le_bytes()); - for _ in 0..6 { - payload.extend_from_slice(&0u32.to_le_bytes()); - } - payload.extend_from_slice(xml_bytes); - - let mut out = Vec::new(); - out.extend_from_slice(b"CcnK"); - out.extend_from_slice(&0u32.to_be_bytes()); - out.extend_from_slice(b"FPCh"); - out.extend_from_slice(&1u32.to_be_bytes()); - out.extend_from_slice(b"cjs3"); - out.extend_from_slice(&1u32.to_be_bytes()); - out.extend_from_slice(&1u32.to_be_bytes()); - out.extend_from_slice(&[0u8; 28]); - out.extend_from_slice(&(payload.len() as u32).to_be_bytes()); - out.extend_from_slice(&payload); - out - } - - fn load(xml: &str) -> LoadResult { - let data = wrap(xml); - let file = super::super::fxp::parse_fxp(&data).expect("container parses"); - convert_patch(&file).expect("patch converts") - } - - fn value_of(result: &LoadResult, id: ParamId) -> Option { - result - .values - .iter() - .find(|(param, _)| *param == id) - .map(|(_, value)| *value) - } - - const HEADER: &str = r#""#; - const FOOTER: &str = ""; - - #[test] - fn maps_globals_and_name() { - let xml = format!( - r#"{HEADER} - - - - - - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert_eq!(result.name, "Test Patch"); - // -6.02 dB master = 0.5 amplitude, times 0.5 scene volume folded in. - assert!((value_of(&result, ParamId::Volume).unwrap() - 0.25).abs() < 1e-3); - assert_eq!(value_of(&result, ParamId::Polyphony), Some(15.0)); - assert_eq!(value_of(&result, ParamId::PitchBendUp), Some(2.0)); - assert_eq!(value_of(&result, ParamId::PitchBendDown), Some(12.0)); - // 2^-2 s = 0.25 s portamento. - assert!((value_of(&result, ParamId::Portamento).unwrap() - 0.25).abs() < 1e-6); - assert_eq!(value_of(&result, ParamId::PlayMode), Some(0.0)); - } - - #[test] - fn maps_classic_oscillator_and_reinterprets_float_bits() { - // osc1_param1 (width1) is stored as an integer carrying the float - // bits of 0.5f32 (1056964608), as old Surge revisions do. - let xml = format!( - r#"{HEADER} - - - - - - - - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert_eq!(value_of(&result, ParamId::Osc1Type), Some(0.0)); - // Surge octave +1 -> our 4 (3 = center). - assert_eq!(value_of(&result, ParamId::Osc1Octave), Some(4.0)); - // 1.5 semitones rounds to 2 -> semitone 14 (12 = center), fine -50. - assert_eq!(value_of(&result, ParamId::Osc1Semitone), Some(14.0)); - assert!((value_of(&result, ParamId::Osc1Fine).unwrap() + 50.0).abs() < 1e-6); - // Classic shape (bipolar) -> skew; width1 0.5 -> shape. - assert_eq!(value_of(&result, ParamId::Osc1Skew), Some(-0.5)); - assert!((value_of(&result, ParamId::Osc1Shape).unwrap() - 0.5).abs() < 1e-6); - assert!((value_of(&result, ParamId::Osc1SubLevel).unwrap() - 0.25).abs() < 1e-6); - assert_eq!(value_of(&result, ParamId::Osc1Sync), Some(7.0)); - assert!((value_of(&result, ParamId::Osc1UnisonDetune).unwrap() - 0.1).abs() < 1e-6); - assert_eq!(value_of(&result, ParamId::Osc1Unison), Some(3.0)); - assert!((value_of(&result, ParamId::Osc1Level).unwrap() - 0.75).abs() < 1e-6); - assert_eq!(value_of(&result, ParamId::Osc1Route), Some(2.0)); - } - - #[test] - fn maps_filters_with_unit_conversion() { - let xml = format!( - r#"{HEADER} - - - - - - - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert_eq!(value_of(&result, ParamId::F1Type), Some(1.0)); // lp24 -> LP 24 - assert_eq!(value_of(&result, ParamId::F1Subtype), Some(1.0)); // driven - assert_eq!(value_of(&result, ParamId::F1Enabled), Some(1.0)); - // cutoff raw 33 -> 440 * 2^(33/12) Hz. - let expected = 440.0f32 * (2.0f32).powf(33.0 / 12.0); - assert!((value_of(&result, ParamId::F1Cutoff).unwrap() - expected as f64).abs() < 1.0); - // Resonance 0..1 -> 0..10. - assert!((value_of(&result, ParamId::F1Resonance).unwrap() - 5.0).abs() < 1e-6); - // envmod -24 st (ct_freq_mod) -> -24/96 = -0.25 of our ±96 st scale. - assert_eq!(value_of(&result, ParamId::F1EgAmount), Some(-0.25)); - assert_eq!(value_of(&result, ParamId::FilterRouting), Some(0.0)); // serial 1 - assert!((value_of(&result, ParamId::FilterBalance).unwrap() - 0.1).abs() < 1e-6); - assert_eq!(value_of(&result, ParamId::FilterFeedback), Some(-0.5)); - // lowcut raw -12 -> 440 * 2^-1 = 220 Hz. - assert!((value_of(&result, ParamId::Lowcut).unwrap() - 220.0).abs() < 0.1); - // ws_type 0 (none) -> waveshaper disabled. - assert_eq!(value_of(&result, ParamId::WaveshaperEnabled), Some(0.0)); - } - - #[test] - fn maps_envelopes_with_time_conversion() { - let xml = format!( - r#"{HEADER} - - - - - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert_eq!(value_of(&result, ParamId::AmpAttack), Some(1.0)); // 2^0 - assert_eq!(value_of(&result, ParamId::AmpDecay), Some(2.0)); // 2^1 - assert!((value_of(&result, ParamId::AmpSustain).unwrap() - 0.8).abs() < 1e-6); - assert_eq!(value_of(&result, ParamId::AmpRelease), Some(4.0)); // 2^2 - assert_eq!(value_of(&result, ParamId::AmpEgAttackCurve), Some(2.0)); - assert_eq!(value_of(&result, ParamId::AmpEgDecayCurve), Some(1.0)); - assert_eq!(value_of(&result, ParamId::AmpEgMode), Some(0.0)); - // 2^-8 s clamped above zero. - assert!((value_of(&result, ParamId::FilterAttack).unwrap() - 1.0 / 256.0).abs() < 1e-6); - } - - #[test] - fn maps_lfo_and_modrouting() { - let xml = format!( - r#"{HEADER} - - - - - - - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert_eq!(value_of(&result, ParamId::Lfo1Shape), Some(0.0)); - assert!((value_of(&result, ParamId::Lfo1Rate).unwrap() - 8.0).abs() < 1e-6); // 2^3 Hz - assert!((value_of(&result, ParamId::Lfo1Amount).unwrap() - 0.5).abs() < 1e-6); - assert_eq!(value_of(&result, ParamId::Lfo1Trigger), Some(1.0)); - // Route 1: lfo1 (source 17) -> filter1 cutoff, depth 24 st -> 24/60. - assert_eq!( - value_of(&result, ParamId::ModRoute1Source), - Some(ModSource::Lfo1 as u8 as f64) - ); - assert_eq!( - value_of(&result, ParamId::ModRoute1Target), - Some(ModTarget::Filter1Cutoff as u8 as f64) - ); - assert!((value_of(&result, ParamId::ModRoute1Depth).unwrap() - 0.4).abs() < 1e-6); - // Route 2: velocity (source 1) -> osc1 pitch, 6 st -> 6/12. - assert_eq!( - value_of(&result, ParamId::ModRoute2Source), - Some(ModSource::Velocity as u8 as f64) - ); - assert_eq!( - value_of(&result, ParamId::ModRoute2Target), - Some(ModTarget::Osc1Pitch as u8 as f64) - ); - assert!((value_of(&result, ParamId::ModRoute2Depth).unwrap() - 0.5).abs() < 1e-6); - } - - #[test] - fn ignores_effects_and_reports_them() { - let xml = format!( - r#"{HEADER} - - - - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert!(result.values.is_empty()); - assert_eq!(result.report.skipped.len(), 1); - let (element, reason) = &result.report.skipped[0]; - assert!(element.contains("2 fx slots"), "unexpected: {element}"); - assert!(reason.contains("effect"), "unexpected: {reason}"); - } - - #[test] - fn skips_scene_b_in_dual_mode() { - let xml = format!( - r#"{HEADER} - - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert_eq!(value_of(&result, ParamId::Osc1Type), Some(0.0)); - assert_eq!(value_of(&result, ParamId::Osc1Waveform), Some(4.0)); - assert!( - result - .report - .skipped - .iter() - .any(|(element, _)| element == "scene B"), - "expected scene B skip, got {:?}", - result.report.skipped - ); - } - - #[test] - fn skips_unsupported_oscillator_types_with_reason() { - let xml = format!( - r#"{HEADER} - - {FOOTER}"# - ); - let result = load(&xml); - assert!(value_of(&result, ParamId::Osc1Type).is_none()); - assert!( - result - .report - .skipped - .iter() - .any(|(element, reason)| element == "a_osc1" && reason.contains("audio-input")), - "got {:?}", - result.report.skipped - ); - } - - #[test] - fn imports_step_sequence_unipolar_to_bipolar() { - let xml = format!( - r#"{HEADER} - - - - - {FOOTER}"# - ); - let result = load(&xml); - assert_eq!(value_of(&result, ParamId::Lfo3Shape), Some(8.0)); // stepseq - assert_eq!(value_of(&result, ParamId::StepSeq1), Some(1.0)); // 1.0 -> +1 - assert_eq!(value_of(&result, ParamId::StepSeq2), Some(-1.0)); // 0.0 -> -1 - assert_eq!(value_of(&result, ParamId::StepSeqLoopEnd), Some(7.0)); - assert!((value_of(&result, ParamId::StepSeqShuffle).unwrap() - 0.25).abs() < 1e-6); - // trigmask 65537 = bits 0 (amp) and 16 (filter). - assert_eq!(value_of(&result, ParamId::StepSeqTrigAmp), Some(1.0)); - assert_eq!(value_of(&result, ParamId::StepSeqTrigFilter), Some(1.0)); - assert_eq!(value_of(&result, ParamId::StepSeqTrigPitch), Some(0.0)); - } -} diff --git a/src/synth/surge/fxp.rs b/src/synth/surge/fxp.rs deleted file mode 100644 index 27cb9ca..0000000 --- a/src/synth/surge/fxp.rs +++ /dev/null @@ -1,181 +0,0 @@ -//! Surge XT `.fxp` preset container parsing. -//! -//! A Surge `.fxp` file is a Steinberg *chunked* FXP preset whose payload is -//! Surge's own little-endian `sub3` blob: a 32-byte header followed by the -//! patch XML. Reference: `src/common/PatchFileHeaderStructs.h` and -//! `SurgeSynthesizerIO.cpp` in the Surge source. - -/// Parsed container of a Surge `.fxp` file. -#[derive(Debug)] -pub struct SurgePatchFile { - /// Patch name from the FXP program header. - pub name: String, - /// The `` XML document. - pub xml: String, - /// `true` for each scene/osc slot (index = scene * 3 + osc) whose patch - /// embeds a wavetable blob we do not convert. - pub embedded_wavetables: [bool; 6], -} - -fn be_u32(data: &[u8], offset: usize, what: &str) -> Result { - let bytes = data - .get(offset..offset + 4) - .ok_or_else(|| format!("file too short while reading {what}"))?; - Ok(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) -} - -fn le_u32(data: &[u8], offset: usize, what: &str) -> Result { - let bytes = data - .get(offset..offset + 4) - .ok_or_else(|| format!("file too short while reading {what}"))?; - Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) -} - -const CHUNK_MAGIC: u32 = u32::from_be_bytes(*b"CcnK"); -const FX_MAGIC_CHUNK: u32 = u32::from_be_bytes(*b"FPCh"); -const SURGE_FX_ID: u32 = u32::from_be_bytes(*b"cjs3"); -const INNER_TAG: &[u8; 4] = b"sub3"; - -/// Parse a Surge XT `.fxp` file into its XML document. -pub fn parse_fxp(data: &[u8]) -> Result { - // Outer Steinberg header, 60 bytes, big-endian. - if be_u32(data, 0, "chunk magic")? != CHUNK_MAGIC { - return Err("not an FXP file (missing CcnK magic)".to_string()); - } - if be_u32(data, 8, "fx magic")? != FX_MAGIC_CHUNK { - return Err("not a chunked FXP preset (expected FPCh); Surge parameter-dump presets are unsupported".to_string()); - } - if be_u32(data, 16, "fx id")? != SURGE_FX_ID { - return Err("not a Surge patch (fxID is not 'cjs3')".to_string()); - } - let name_bytes = data - .get(28..56) - .ok_or_else(|| "file too short while reading program name".to_string())?; - let name_end = name_bytes - .iter() - .position(|&b| b == 0) - .unwrap_or(name_bytes.len()); - let name = String::from_utf8_lossy(&name_bytes[..name_end]).into_owned(); - let chunk_size = be_u32(data, 56, "chunk size")? as usize; - let payload = data - .get(60..60 + chunk_size) - .ok_or_else(|| format!("file truncated: chunk size {chunk_size} exceeds file"))?; - - // Inner Surge blob. If the payload does not carry the `sub3` tag, Surge - // treats the whole payload as a raw XML document; accept that too. - if payload.get(0..4) != Some(INNER_TAG.as_slice()) { - let xml = String::from_utf8_lossy(payload).into_owned(); - return Ok(SurgePatchFile { - name, - xml, - embedded_wavetables: [false; 6], - }); - } - - let xml_size = le_u32(payload, 4, "xml size")? as usize; - let mut embedded = [false; 6]; - for (i, slot) in embedded.iter_mut().enumerate() { - *slot = le_u32(payload, 8 + i * 4, "wavetable size")? != 0; - } - let xml_start = 32usize; - let xml_end = xml_start - .checked_add(xml_size) - .ok_or_else(|| "xml size overflow".to_string())?; - let xml_bytes = payload - .get(xml_start..xml_end) - .ok_or_else(|| format!("file truncated: xml size {xml_size} exceeds payload"))?; - // Some released patches carry non-UTF-8 bytes (e.g. in the patch name); - // Surge reads them tolerantly, so decode lossily instead of failing. - let xml = String::from_utf8_lossy(xml_bytes).into_owned(); - - Ok(SurgePatchFile { - name, - xml, - embedded_wavetables: embedded, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Wrap an XML document in a valid FPCh/sub3 container, mirroring what - /// Surge writes. - fn wrap(xml: &str, name: &str, wtsizes: [u32; 6]) -> Vec { - let xml_bytes = xml.as_bytes(); - let mut payload = Vec::new(); - payload.extend_from_slice(b"sub3"); - payload.extend_from_slice(&(xml_bytes.len() as u32).to_le_bytes()); - for size in wtsizes { - payload.extend_from_slice(&size.to_le_bytes()); - } - payload.extend_from_slice(xml_bytes); - - let mut out = Vec::new(); - out.extend_from_slice(b"CcnK"); - out.extend_from_slice(&0u32.to_be_bytes()); - out.extend_from_slice(b"FPCh"); - out.extend_from_slice(&1u32.to_be_bytes()); - out.extend_from_slice(b"cjs3"); - out.extend_from_slice(&1u32.to_be_bytes()); - out.extend_from_slice(&1u32.to_be_bytes()); - let mut name_buf = [0u8; 28]; - let name_bytes = name.as_bytes(); - let len = name_bytes.len().min(27); - name_buf[..len].copy_from_slice(&name_bytes[..len]); - out.extend_from_slice(&name_buf); - out.extend_from_slice(&(payload.len() as u32).to_be_bytes()); - out.extend_from_slice(&payload); - out - } - - #[test] - fn parses_container() { - let data = wrap("", "Init", [0; 6]); - let parsed = parse_fxp(&data).expect("valid container"); - assert_eq!(parsed.name, "Init"); - assert!(parsed.xml.starts_with("", "WT", [0, 5, 0, 0, 0, 0]); - let parsed = parse_fxp(&data).expect("valid container"); - assert_eq!( - parsed.embedded_wavetables, - [false, true, false, false, false, false] - ); - } - - #[test] - fn rejects_non_fxp() { - assert!(parse_fxp(b"not an fxp at all").is_err()); - } - - #[test] - fn rejects_wrong_fx_magic() { - let mut data = wrap("", "X", [0; 6]); - data[8..12].copy_from_slice(b"FxCk"); - let err = parse_fxp(&data).unwrap_err(); - assert!(err.contains("FPCh"), "unexpected error: {err}"); - } - - #[test] - fn accepts_raw_xml_payload() { - let xml = ""; - let mut data = Vec::new(); - data.extend_from_slice(b"CcnK"); - data.extend_from_slice(&0u32.to_be_bytes()); - data.extend_from_slice(b"FPCh"); - data.extend_from_slice(&1u32.to_be_bytes()); - data.extend_from_slice(b"cjs3"); - data.extend_from_slice(&1u32.to_be_bytes()); - data.extend_from_slice(&1u32.to_be_bytes()); - data.extend_from_slice(&[0u8; 28]); - data.extend_from_slice(&(xml.len() as u32).to_be_bytes()); - data.extend_from_slice(xml.as_bytes()); - let parsed = parse_fxp(&data).expect("raw xml payload"); - assert!(parsed.xml.contains("Raw")); - } -} diff --git a/src/synth/surge/mod.rs b/src/synth/surge/mod.rs deleted file mode 100644 index 14953b2..0000000 --- a/src/synth/surge/mod.rs +++ /dev/null @@ -1,210 +0,0 @@ -//! Surge XT preset import for Maolan Synth. -//! -//! Surge XT stores patches as `.fxp` files (a chunked Steinberg FXP container -//! around a `sub3` blob holding an XML document). This module parses those -//! files and converts the synthesis-relevant parameters onto Maolan Synth's -//! parameter set, ignoring effect slots entirely. Everything that cannot be -//! converted is recorded in a [`Report`] so the user can see why. - -mod convert; -pub mod fxp; -mod report; -mod units; - -use std::path::{Path, PathBuf}; - -pub use report::Report; - -use crate::synth::params::ParamId; - -/// Default Surge XT preset directories scanned for `.fxp` files. -pub const PRESET_DIRS: &[&str] = &[ - "/usr/local/share/surge-xt/patches_factory", - "/usr/local/share/surge-xt/patches_3rdparty", -]; - -/// Environment variable overriding [`PRESET_DIRS`] (':'-separated paths). -pub const PRESET_PATH_ENV: &str = "SURGE_PRESET_PATH"; - -/// A Surge preset discovered by [`scan_presets`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PresetInfo { - pub path: PathBuf, - pub name: String, - /// Category sub-path relative to the preset root directory. - pub category: String, -} - -/// Successful import of a single Surge preset. -#[derive(Debug)] -pub struct LoadResult { - pub name: String, - /// Native-unit values to write into the synth's parameter store. - pub values: Vec<(ParamId, f64)>, - pub report: Report, -} - -/// Preset directories actually scanned: the `SURGE_PRESET_PATH` override if -/// set, otherwise the built-in Surge install locations. -fn preset_dirs() -> Vec { - if let Some(override_paths) = std::env::var_os(PRESET_PATH_ENV) { - let dirs: Vec = std::env::split_paths(&override_paths).collect(); - if !dirs.is_empty() { - return dirs; - } - } - PRESET_DIRS.iter().map(PathBuf::from).collect() -} - -/// Recursively scan the preset directories for `.fxp` files, sorted by -/// category then name. Categories are prefixed with the root directory name -/// (`patches_factory/…`, `patches_3rdparty/…`) so the two Surge trees never -/// collide. -pub fn scan_presets() -> Vec { - let mut presets = Vec::new(); - for dir in preset_dirs() { - let Ok(entries) = std::fs::read_dir(&dir) else { - continue; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - scan_dir(&path, &dir, &mut presets); - } else if path.extension().is_some_and(|ext| ext == "fxp") { - push_preset(&mut presets, path, &dir); - } - } - } - presets.sort_by(|a, b| { - a.category - .cmp(&b.category) - .then_with(|| a.name.cmp(&b.name)) - }); - presets -} - -fn push_preset(presets: &mut Vec, path: PathBuf, root: &Path) { - let relative = path - .parent() - .and_then(|parent| parent.strip_prefix(root).ok()) - .map(|rel| rel.to_string_lossy().into_owned()) - .unwrap_or_default(); - let root_name = root - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_default(); - let category = if relative.is_empty() { - root_name - } else { - format!("{root_name}/{relative}") - }; - presets.push(PresetInfo { - name: path - .file_stem() - .map(|stem| stem.to_string_lossy().into_owned()) - .unwrap_or_default(), - category, - path, - }); -} - -fn scan_dir(dir: &Path, root: &Path, presets: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - scan_dir(&path, root, presets); - } else if path.extension().is_some_and(|ext| ext == "fxp") { - push_preset(presets, path, root); - } - } -} - -/// Load and convert a Surge `.fxp` preset. -pub fn load_preset(path: &Path) -> Result { - let data = - std::fs::read(path).map_err(|error| format!("cannot read {}: {error}", path.display()))?; - let file = fxp::parse_fxp(&data)?; - convert::convert_patch(&file) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn scan_presets_finds_nested_fxp_files() { - let root = std::env::temp_dir().join(format!("maolan_surge_scan_{}", std::process::id())); - let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(root.join("Basses/Sub")).unwrap(); - std::fs::write(root.join("Basses/Sub/Wobble.fxp"), b"CcnK").unwrap(); - std::fs::write(root.join("Basses/Deep.fxp"), b"CcnK").unwrap(); - std::fs::write(root.join("Basses/ignore.txt"), b"no").unwrap(); - - // Point the scanner at our fixture via the env override. - // SAFETY: single-threaded test context; the override is removed below. - unsafe { std::env::set_var(PRESET_PATH_ENV, &root) }; - let presets = scan_presets(); - unsafe { std::env::remove_var(PRESET_PATH_ENV) }; - let _ = std::fs::remove_dir_all(&root); - - let prefix = root.file_name().unwrap().to_string_lossy(); - let sub_category = Path::new("Basses").join("Sub"); - assert_eq!(presets.len(), 2); - assert_eq!(presets[0].name, "Deep"); - assert_eq!(presets[0].category, format!("{prefix}/Basses")); - assert_eq!(presets[1].name, "Wobble"); - assert_eq!( - presets[1].category, - format!("{prefix}/{}", sub_category.display()) - ); - } - - /// Manual end-to-end check against the real Surge installation. Run with - /// `cargo test --lib -- --ignored`. - #[test] - #[ignore] - fn scan_real_surge_directories() { - let presets = scan_presets(); - assert!(!presets.is_empty(), "no presets found in {PRESET_DIRS:?}"); - let mut loaded = 0usize; - let mut failed: Vec = Vec::new(); - let mut total_skipped = 0usize; - let mut total_notes = 0usize; - for preset in &presets { - match load_preset(&preset.path) { - Ok(result) => { - loaded += 1; - total_skipped += result.report.skipped.len(); - total_notes += result.report.notes.len(); - for error in &result.report.errors { - eprintln!("[{}] ERROR: {error}", preset.path.display()); - } - } - Err(error) => failed.push(format!("{}: {error}", preset.path.display())), - } - } - eprintln!( - "scanned {} presets: {loaded} loaded, {} failed, {total_skipped} skipped entries, {total_notes} notes", - presets.len(), - failed.len() - ); - let mut reason_tally: std::collections::BTreeMap = Default::default(); - for preset in &presets { - if let Ok(result) = load_preset(&preset.path) { - for (_, reason) in &result.report.skipped { - *reason_tally.entry(reason.clone()).or_default() += 1; - } - } - } - for (reason, count) in reason_tally { - eprintln!("{count:6} {reason}"); - } - for failure in &failed { - eprintln!("FAILED: {failure}"); - } - assert!(failed.is_empty(), "{} presets failed to load", failed.len()); - } -} diff --git a/src/synth/surge/report.rs b/src/synth/surge/report.rs deleted file mode 100644 index e231a50..0000000 --- a/src/synth/surge/report.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! Human-readable report of what a Surge preset import did and could not do. - -/// Result report for one preset import. -#[derive(Debug, Clone, Default)] -pub struct Report { - /// Hard problems that prevented individual elements from loading. - pub errors: Vec, - /// Elements that were deliberately not converted: (element, reason). - pub skipped: Vec<(String, String)>, - /// Approximations made while converting. - pub notes: Vec, -} - -impl Report { - pub fn error(&mut self, message: impl Into) { - self.errors.push(message.into()); - } - - pub fn skip(&mut self, element: impl Into, reason: impl Into) { - self.skipped.push((element.into(), reason.into())); - } - - pub fn note(&mut self, message: impl Into) { - self.notes.push(message.into()); - } - - pub fn is_empty(&self) -> bool { - self.errors.is_empty() && self.skipped.is_empty() && self.notes.is_empty() - } - - /// Render the report for on-screen display. - pub fn to_display_string(&self) -> String { - let mut out = String::new(); - for error in &self.errors { - out.push_str(&format!("ERROR: {error}\n")); - } - for (element, reason) in &self.skipped { - out.push_str(&format!("skipped {element}: {reason}\n")); - } - for note in &self.notes { - out.push_str(&format!("note: {note}\n")); - } - out - } -} diff --git a/src/synth/surge/units.rs b/src/synth/surge/units.rs deleted file mode 100644 index 9074dc4..0000000 --- a/src/synth/surge/units.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! Unit conversions from Surge XT raw parameter storage values. -//! -//! Surge stores parameter values in native units dictated by each parameter's -//! control type (`ct_*`). The formulas below are taken from -//! `src/common/Parameter.cpp` in the Surge source (display type -//! `ATwoToTheBx`: `display = a * 2^(b * raw)` with defaults a = 1, b = 1). - -/// `ct_freq_audible` (filter/noise cutoffs): raw is in 1/12-octaves around -/// 440 Hz, i.e. a MIDI-note-style scale. `440 * 2^(raw / 12)`. -pub fn freq_audible_hz(raw: f32) -> f32 { - 440.0 * (2.0f32).powf(raw / 12.0) -} - -/// `ct_envtime` (EG attack/decay/release, LFO EG stage times): -/// `2^raw` seconds. -pub fn envtime_seconds(raw: f32) -> f32 { - (2.0f32).powf(raw) -} - -/// `ct_lforate`: `2^raw` Hz. -pub fn lfo_rate_hz(raw: f32) -> f32 { - (2.0f32).powf(raw) -} - -/// `ct_portatime`: `2^raw` seconds. -pub fn portatime_seconds(raw: f32) -> f32 { - (2.0f32).powf(raw) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn freq_audible_matches_surge_bounds() { - assert!((freq_audible_hz(-60.0) - 13.75).abs() < 0.01); - assert!((freq_audible_hz(0.0) - 440.0).abs() < 0.01); - assert!((freq_audible_hz(3.0) - 523.25).abs() < 0.01); - assert!((freq_audible_hz(70.0) - 25087.71).abs() < 1.0); - } - - #[test] - fn envtime_is_pow2() { - assert!((envtime_seconds(0.0) - 1.0).abs() < 1e-6); - assert!((envtime_seconds(-8.0) - 1.0 / 256.0).abs() < 1e-6); - assert!((envtime_seconds(5.0) - 32.0).abs() < 1e-4); - } - - #[test] - fn lfo_rate_is_pow2() { - assert!((lfo_rate_hz(0.0) - 1.0).abs() < 1e-6); - assert!((lfo_rate_hz(-7.0) - 1.0 / 128.0).abs() < 1e-6); - assert!((lfo_rate_hz(9.0) - 512.0).abs() < 1e-4); - } - - #[test] - fn portatime_is_pow2() { - assert!((portatime_seconds(-8.0) - 1.0 / 256.0).abs() < 1e-6); - assert!((portatime_seconds(2.0) - 4.0).abs() < 1e-4); - } -} diff --git a/tests/surge_ab.rs b/tests/surge_ab.rs deleted file mode 100644 index 14cc63f..0000000 --- a/tests/surge_ab.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! A/B render driver: renders every "clean" Surge preset (no FX, no macros — -//! see PRESETS.md) through Maolan Synth's engine as stereo WAV files, the -//! counterpart of Surge's `surge-render`. Pair with the compare script to -//! measure differences against the Surge renders. -//! -//! Run: cargo test --test surge_ab -- --ignored --nocapture - -use std::path::Path; - -use maolan_plugins::synth::render::render_surge_preset; -use maolan_plugins::synth::surge; - -fn is_clean(preset: &surge::PresetInfo) -> bool { - let Ok(result) = surge::load_preset(&preset.path) else { - return false; - }; - let dirty = result.report.skipped.iter().any(|(_, reason)| { - let reason = reason.to_lowercase(); - reason.contains("effect") || reason.contains("macro") - }) || result - .report - .notes - .iter() - .any(|note| note.to_lowercase().contains("macro")); - !dirty -} - -#[test] -#[ignore] -fn render_clean_presets_to_wav() { - let out_dir = Path::new("/tmp/ab/maolan"); - std::fs::create_dir_all(out_dir).unwrap(); - - let presets: Vec<_> = surge::scan_presets().into_iter().filter(is_clean).collect(); - assert!(!presets.is_empty(), "no clean presets found"); - let mut manifest = String::new(); - let mut failed = 0; - for preset in &presets { - let out = out_dir.join(format!("{}.wav", preset.name)); - if let Err(error) = render_surge_preset(&preset.path, &out, 60, 1.0, 0.5) { - eprintln!("FAILED {}: {error}", preset.path.display()); - failed += 1; - } - manifest.push_str(&format!("{}\t{}\n", preset.name, preset.path.display())); - } - std::fs::write("/tmp/ab/manifest.tsv", manifest).unwrap(); - eprintln!( - "rendered {} presets to {} ({} failed)", - presets.len(), - out_dir.display(), - failed - ); - assert_eq!(failed, 0); -} diff --git a/tests/synth_dsp.rs b/tests/synth_dsp.rs index cc7e166..41fda04 100644 --- a/tests/synth_dsp.rs +++ b/tests/synth_dsp.rs @@ -1,6 +1,6 @@ -use maolan_plugins::common::filter::{Filter, FilterType, SvfFilter}; +use maolan_plugins::common::filter::{Filter, FilterSubtype, FilterType, SvfFilter}; use maolan_plugins::synth::dsp::{ - FilterRouting, OscPhaseMode, OscType, SynthEngine, VoiceParams, Waveshape, soft_clip_master, + FilterRouting, OscPhaseMode, OscType, SynthEngine, VoiceParams, soft_clip_master, }; fn osc1_saw_test_engine() -> SynthEngine { @@ -26,14 +26,9 @@ fn osc1_saw_test_engine() -> SynthEngine { engine.params.filter_routing = FilterRouting::Ring; engine.params.flavor = maolan_plugins::common::flavor::FlavorType::Off; engine.params.noise.enabled = false; - engine.params.waveshaper.enabled = false; engine.params.filter_feedback = 0.0; engine.params.lowcut_hz = 20.0; - engine.params.pitch_eg.attack = 0.0; - engine.params.pitch_eg.decay = 0.0; - engine.params.pitch_eg.sustain = 0.0; - engine.params.pitch_eg.release = 0.0; engine.params.portamento = 0.0; engine.params.drift_amount = 0.0; @@ -182,12 +177,7 @@ fn test_osc1_only_single_pitch() { engine.params.filter2.enabled = false; engine.params.flavor = maolan_plugins::common::flavor::FlavorType::Off; engine.params.noise.enabled = false; - engine.params.waveshaper.enabled = false; - engine.params.pitch_eg.attack = 0.0; - engine.params.pitch_eg.decay = 0.0; - engine.params.pitch_eg.sustain = 0.0; - engine.params.pitch_eg.release = 0.0; engine.params.portamento = 0.0; engine.params.drift_amount = 0.0; @@ -230,92 +220,6 @@ fn test_osc1_only_single_pitch() { assert!(peak < 2.0, "Output too loud: {}", peak); } -#[test] -fn test_osc1_pitch_eg_effect() { - let mut engine = SynthEngine::new(48000.0, 8); - engine.params = VoiceParams::default(); - - engine.params.oscs[1].enabled = false; - engine.params.oscs[2].enabled = false; - - engine.params.oscs[0].osc_type = OscType::Classic; - engine.params.oscs[0].waveform = 0; - engine.params.oscs[0].sub_level = 0.0; - engine.params.oscs[0].sync = 0.0; - - engine.params.filter1.enabled = false; - engine.params.filter2.enabled = false; - engine.params.flavor = maolan_plugins::common::flavor::FlavorType::Off; - engine.params.noise.enabled = false; - engine.params.waveshaper.enabled = false; - - engine.update_params(); - - let mut out_l = vec![0.0f32; 48000]; - let mut out_r = vec![0.0f32; 48000]; - - engine.trigger(60, 0.8); - engine.process_block(&mut out_l, &mut out_r, None, None); - - let start = 24000; - let mut crossings = vec![]; - for i in (start + 1)..out_l.len() { - if out_l[i - 1] < 0.0 && out_l[i] >= 0.0 { - crossings.push(i); - } - } - - if crossings.len() >= 2 { - let avg_period = (crossings.last().unwrap() - crossings.first().unwrap()) as f32 - / (crossings.len() - 1) as f32; - let _est_freq = 48000.0 / avg_period; - } - - let mut engine2 = SynthEngine::new(48000.0, 8); - engine2.params = VoiceParams::default(); - engine2.params.oscs[1].enabled = false; - engine2.params.oscs[2].enabled = false; - engine2.params.oscs[0].osc_type = OscType::Classic; - engine2.params.oscs[0].waveform = 0; - engine2.params.oscs[0].sub_level = 0.0; - engine2.params.oscs[0].sync = 0.0; - engine2.params.filter1.enabled = false; - engine2.params.filter2.enabled = false; - engine2.params.flavor = maolan_plugins::common::flavor::FlavorType::Off; - engine2.params.noise.enabled = false; - engine2.params.waveshaper.enabled = false; - engine2.params.pitch_eg.attack = 0.0; - engine2.params.pitch_eg.decay = 0.0; - engine2.params.pitch_eg.sustain = 0.0; - engine2.params.pitch_eg.release = 0.0; - engine2.update_params(); - - out_l.fill(0.0); - out_r.fill(0.0); - engine2.trigger(60, 0.8); - engine2.process_block(&mut out_l, &mut out_r, None, None); - - let start = 24000; - let mut crossings = vec![]; - for i in (start + 1)..out_l.len() { - if out_l[i - 1] < 0.0 && out_l[i] >= 0.0 { - crossings.push(i); - } - } - - if crossings.len() >= 2 { - let avg_period = (crossings.last().unwrap() - crossings.first().unwrap()) as f32 - / (crossings.len() - 1) as f32; - let est_freq = 48000.0 / avg_period; - let ratio = est_freq / 261.63; - assert!( - ratio > 0.9 && ratio < 1.1, - "Frequency still wrong after disabling pitch_eg: {:.1} Hz", - est_freq - ); - } -} - #[test] fn test_osc1_debug_freq() { let mut engine = SynthEngine::new(48000.0, 8); @@ -332,12 +236,6 @@ fn test_osc1_debug_freq() { engine.params.filter2.enabled = false; engine.params.flavor = maolan_plugins::common::flavor::FlavorType::Off; engine.params.noise.enabled = false; - engine.params.waveshaper.enabled = false; - - engine.params.pitch_eg.sustain = 0.0; - engine.params.pitch_eg.attack = 0.0; - engine.params.pitch_eg.decay = 0.0; - engine.params.pitch_eg.release = 0.0; engine.params.portamento = 0.0; @@ -624,17 +522,16 @@ fn test_filter_family_switching_rebuilds_dsp() { let input: Vec = (0..block).map(|_| noise.next()).collect(); let input_rms = rms(&input); - let mut filter = Filter::new(FilterType::Ladder, sr); + let mut filter = Filter::new(FilterType::DiodeLadder, sr); filter.set_params(800.0, 0.7); filter.prepare_block(800.0, 0.7, block); - let ladder: Vec = input.iter().map(|&s| filter.process(s)).collect(); - assert!(matches!(filter, Filter::Ladder(_))); + let diode: Vec = input.iter().map(|&s| filter.process(s)).collect(); + assert!(matches!(filter, Filter::DiodeLadder(_))); - // Ladder -> CytomicSvf: a different DSP family must be built. filter.set_filter_type(FilterType::CytomicLp); assert!( matches!(filter, Filter::CytomicSvf(_)), - "Ladder -> CytomicLp must rebuild the CytomicSvf variant" + "DiodeLadder -> CytomicLp must rebuild the CytomicSvf variant" ); filter.prepare_block(800.0, 0.7, block); let cytomic: Vec = input.iter().map(|&s| filter.process(s)).collect(); @@ -649,14 +546,13 @@ fn test_filter_family_switching_rebuilds_dsp() { filter.prepare_block(800.0, 0.7, block); let svf: Vec = input.iter().map(|&s| filter.process(s)).collect(); - // SVF -> Ladder: the reverse direction must rebuild too. - filter.set_filter_type(FilterType::Ladder); + filter.set_filter_type(FilterType::DiodeLadder); assert!( - matches!(filter, Filter::Ladder(_)), - "Lowpass -> Ladder must rebuild the Ladder variant" + matches!(filter, Filter::DiodeLadder(_)), + "Lowpass -> DiodeLadder must rebuild the DiodeLadder variant" ); - for (name, seg) in [("ladder", &ladder), ("cytomic", &cytomic), ("svf", &svf)] { + for (name, seg) in [("diode", &diode), ("cytomic", &cytomic), ("svf", &svf)] { assert!( seg.iter().all(|s| s.is_finite()), "{name} segment contains NaN/INF" @@ -665,7 +561,7 @@ fn test_filter_family_switching_rebuilds_dsp() { // All three families are lowpasses at 800 Hz, so each must attenuate // white noise well below the input level (a passthrough would not). - for (name, seg) in [("ladder", &ladder), ("cytomic", &cytomic), ("svf", &svf)] { + for (name, seg) in [("diode", &diode), ("cytomic", &cytomic), ("svf", &svf)] { let seg_rms = rms(seg); assert!( seg_rms < input_rms * 0.6, @@ -674,7 +570,7 @@ fn test_filter_family_switching_rebuilds_dsp() { } // The families must not silently keep the previous family's DSP running. - let ladder_vs_cytomic = ladder + let diode_vs_cytomic = diode .iter() .zip(&cytomic) .map(|(a, b)| (a - b).abs()) @@ -687,8 +583,8 @@ fn test_filter_family_switching_rebuilds_dsp() { .sum::() / block as f32; assert!( - ladder_vs_cytomic > 1.0e-4, - "Ladder and Cytomic outputs identical (family switch was a no-op): {ladder_vs_cytomic}" + diode_vs_cytomic > 1.0e-4, + "Diode and Cytomic outputs identical (family switch was a no-op): {diode_vs_cytomic}" ); assert!( cytomic_vs_svf > 1.0e-4, @@ -704,7 +600,7 @@ fn test_filter_cutoff_preserved_across_family_switch() { let input: Vec = (0..block).map(|_| noise.next()).collect(); let input_rms = rms(&input); - let mut filter = Filter::new(FilterType::Ladder, sr); + let mut filter = Filter::new(FilterType::DiodeLadder, sr); filter.set_params(800.0, 0.7); filter.prepare_block(800.0, 0.7, block); let _warmup: Vec = input.iter().map(|&s| filter.process(s)).collect(); @@ -1105,7 +1001,7 @@ fn test_filter_feedback_full_amount_stays_bounded() { // this configuration grew without bound. let mut engine = osc1_saw_test_engine(); engine.params.filter1.enabled = true; - engine.params.filter1.filter_type = FilterType::Ladder; + engine.params.filter1.filter_type = FilterType::DiodeLadder; engine.params.filter1.cutoff_hz = 800.0; engine.params.filter1.resonance = 0.95; engine.params.filter_feedback = 1.0; @@ -1131,16 +1027,16 @@ fn test_filter_feedback_full_amount_stays_bounded() { } } -fn waveshaper_patch_engine(oversample: bool) -> SynthEngine { +fn nonlinear_filter_patch_engine(oversample: bool) -> SynthEngine { let mut engine = osc1_saw_test_engine(); engine.params.amp_eg.attack = 0.0; engine.params.amp_eg.decay = 0.0; engine.params.amp_eg.sustain = 1.0; engine.params.oscs[0].level = 0.8; engine.params.oscs[0].phase_mode = OscPhaseMode::Zero; - engine.params.waveshaper.enabled = true; - engine.params.waveshaper.shape = Waveshape::Tanh; - engine.params.waveshaper.drive = 0.8; + engine.params.filter1.enabled = true; + engine.params.filter1.subtype = FilterSubtype::HeavyDrive; + engine.params.filter1.drive = 0.8; engine.params.voice_oversample = oversample; engine.update_params(); engine @@ -1187,7 +1083,7 @@ fn test_oversample_toggle_default_is_on() { #[test] fn test_oversample_on_vs_off_stays_finite_and_similar_level() { fn render(oversample: bool) -> Vec { - let mut engine = waveshaper_patch_engine(oversample); + let mut engine = nonlinear_filter_patch_engine(oversample); let mut out_l = vec![0.0f32; 48000]; let mut out_r = vec![0.0f32; 48000]; engine.trigger(60, 0.8); @@ -1222,42 +1118,6 @@ fn test_oversample_on_vs_off_stays_finite_and_similar_level() { } } -#[test] -fn test_oversample_reduces_waveshaper_aliasing() { - fn render(oversample: bool) -> Vec { - let mut engine = waveshaper_patch_engine(oversample); - // Bright source high up the keyboard: harmonics reach well past the - // audible band, so host-rate waveshaping folds a lot of energy back - // below Nyquist. 48k render; inspect the last block only. - let mut out_l = vec![0.0f32; 48000]; - let mut out_r = vec![0.0f32; 48000]; - engine.trigger(84, 0.8); - engine.process_block(&mut out_l, &mut out_r, None, None); - out_l - } - - let on = render(true); - let off = render(false); - // ~10 Hz analysis spacing so the sharp square-wave harmonics (and their - // aliases) are actually captured by the DFT bins. - let tail_on = band_energy(&on[43008..], 48000.0, 18_000.0, 23_500.0, 550); - let tail_off = band_energy(&off[43008..], 48000.0, 18_000.0, 23_500.0, 550); - let total_on = band_energy(&on[43008..], 48000.0, 100.0, 23_500.0, 470); - let total_off = band_energy(&off[43008..], 48000.0, 100.0, 23_500.0, 470); - // The renders must carry the same overall energy (the toggle changes - // where high-frequency energy lands, not how much there is)... - let rel_on = tail_on / total_on; - let rel_off = tail_off / total_off; - // Measured on a drive-0.8 tanh-square at note 84, 48 kHz host rate: the - // oversampled render keeps ~58% of the host-rate 18-23.5 kHz energy — - // the difference is the harmonics that fold back into the band when the - // waveshaper runs at host rate. - assert!( - rel_on < rel_off * 0.75, - "oversampled render should have relatively less 18-23.5 kHz energy: on={rel_on} off={rel_off}" - ); -} - // ---- SYNTH.md P1 items 10/11: octave-space filter cutoff modulation and // engine output limiting. Modulation is multiplicative: every modulator // contributes semitones and `cutoff = base * 2^(semi/12)` (clamped @@ -1441,8 +1301,7 @@ fn test_master_limiter_bounds_loud_patch() { // The pre-limiter voice sum reaches roughly ±24 (six voices at ~±4 each), // far past ±1; the engine output must stay bounded, and the render peak // right at the ~1.0 ceiling proves the limiter engaged rather than the - // patch simply being quiet. (The waveshaper is gain-compensated — - // `shaped / drive_gain` — so it is left out; it would only attenuate.) + // patch simply being quiet. let mut engine = osc1_saw_test_engine(); engine.params.amp_eg.attack = 0.0; engine.params.amp_eg.decay = 0.0; @@ -1497,7 +1356,7 @@ fn test_master_limiter_transparent_for_quiet_patch() { ); } -// ---- SYNTH.md P1 item 8 (Classic hard sync, Twist VA, Modern DPW) and +// ---- SYNTH.md P1 item 8 (Classic hard sync and Twist VA) and // item 12 (StringOsc filter state). All alias assertions run at the 48 kHz // host rate with the voice-path 2x oversampling disabled so they // discriminate the oscillator-level band-limiting. @@ -1597,94 +1456,6 @@ fn test_twist_virtual_analog_is_band_limited() { ); } -/// Modern osc with the sub oscillator off and no detune: seven identical -/// DPW saws, so the render must be a clean band-limited saw at note pitch. -fn modern_test_engine() -> SynthEngine { - let mut engine = osc1_saw_test_engine(); - engine.params.amp_eg.attack = 0.0; - engine.params.amp_eg.decay = 0.0; - engine.params.amp_eg.sustain = 1.0; - engine.params.oscs[0].osc_type = OscType::Modern; - engine.params.oscs[0].shape = 0.0; // detune ladder off - engine.params.oscs[0].skew = 0.0; // width 0: all voices centered - engine.params.oscs[0].formant = 0.25; // sub_mix = 0 (sub is naive by design) - engine.params.voice_oversample = false; - engine.update_params(); - engine -} - -#[test] -fn test_modern_dpw_tracks_note_pitch() { - let mut engine = modern_test_engine(); - let mut out_l = vec![0.0f32; 48000]; - let mut out_r = vec![0.0f32; 48000]; - engine.trigger(60, 0.8); - engine.process_block(&mut out_l, &mut out_r, None, None); - - assert!( - out_l.iter().all(|s| s.is_finite()), - "Modern render produced NaN/INF" - ); - let level = rms(&out_l[4096..]); - assert!(level > 1.0e-3, "Modern osc must not be silent, rms {level}"); - - let freq = estimate_positive_zero_cross_freq(&out_l, 48000.0, 4096).expect("modern pitch"); - assert!( - (freq - 261.63).abs() < 5.0, - "Modern DPW saw must track note pitch, got {freq}" - ); -} - -#[test] -fn test_modern_dpw_is_band_limited_at_high_pitch() { - let mut engine = modern_test_engine(); - let mut out_l = vec![0.0f32; 48000]; - let mut out_r = vec![0.0f32; 48000]; - engine.trigger(96, 0.8); // 2093 Hz - engine.process_block(&mut out_l, &mut out_r, None, None); - - assert!( - out_l.iter().all(|s| s.is_finite()), - "Modern high-note render produced NaN/INF" - ); - - let tail = &out_l[43008..]; - let high = band_energy(tail, 48000.0, 18_000.0, 23_500.0, 550); - let total = band_energy(tail, 48000.0, 100.0, 23_500.0, 470); - let rel = high / total; - // Measured: DPW rel = 1.3e-2 and spurious/total = 5.6e-9; a naive saw - // measures rel = 7.3e-2 and spurious/total = 1.1e-2 (~2,000,000x more - // sub-fundamental energy). - let spurious = band_energy(tail, 48000.0, 100.0, 1900.0, 360); - assert!( - rel < 0.04, - "18-23.5 kHz band too hot for DPW Modern: rel={rel}" - ); - assert!( - spurious < total * 1.0e-4, - "sub-fundamental spurious energy too high: spurious={spurious:e} total={total:e}" - ); -} - -#[test] -fn test_modern_reset_has_no_dpw_click() { - // The DPW history is re-derived from the current phases on reset; the - // first samples of a note must continue the parabola exactly instead of - // emitting a one-sample spike from a stale history. - let mut engine = modern_test_engine(); - let mut out_l = vec![0.0f32; 1024]; - let mut out_r = vec![0.0f32; 1024]; - engine.trigger(60, 0.8); - engine.process_block(&mut out_l, &mut out_r, None, None); - - let first_peak = out_l[..16].iter().map(|&s| s.abs()).fold(0.0f32, f32::max); - let steady_peak = out_l[512..].iter().map(|&s| s.abs()).fold(0.0f32, f32::max); - assert!( - first_peak <= steady_peak * 1.5 + 0.05, - "DPW history reset click: first_peak={first_peak} steady={steady_peak}" - ); -} - // ---- SYNTH.md P1 item 12: StringOsc filter-state fixes ---- #[test]