From 560245911eebdb34365a9fe1bcd513b3a5f40480 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Goran=20Meki=C4=87?= Date: Fri, 4 Dec 2026 12:20:17 +0100 Subject: [PATCH] Implement Lag, Invert and Transient --- Cargo.lock | 111 ++++---- Cargo.toml | 2 +- src/bitcrusher/plugin.rs | 2 +- src/chorus/plugin.rs | 2 +- src/common/spectrum.rs | 149 +++++++++-- src/compressor/gui.rs | 14 +- src/compressor/plugin.rs | 2 +- src/deesser/plugin.rs | 2 +- src/delay/gui.rs | 10 +- src/delay/plugin.rs | 2 +- src/drums/download.rs | 2 +- src/drums/plugin.rs | 2 +- src/eq/plugin.rs | 2 +- src/flanger/gui.rs | 6 +- src/flanger/plugin.rs | 2 +- src/formant/plugin.rs | 2 +- src/gate/plugin.rs | 2 +- src/invert/dsp.rs | 27 ++ src/invert/gui.rs | 292 +++++++++++++++++++++ src/invert/mod.rs | 7 + src/invert/params.rs | 48 ++++ src/invert/plugin.rs | 463 +++++++++++++++++++++++++++++++++ src/invert/state.rs | 5 + src/kick/plugin.rs | 2 +- src/lag/dsp.rs | 125 +++++++++ src/lag/gui.rs | 446 ++++++++++++++++++++++++++++++++ src/lag/mod.rs | 7 + src/lag/params.rs | 61 +++++ src/lag/plugin.rs | 542 +++++++++++++++++++++++++++++++++++++++ src/lag/state.rs | 5 + src/lib.rs | 17 +- src/limiter/plugin.rs | 2 +- src/modeler/plugin.rs | 2 +- src/phaser/gui.rs | 11 +- src/phaser/plugin.rs | 2 +- src/random/plugin.rs | 2 +- src/reverb/plugin.rs | 2 +- src/sampler/plugin.rs | 2 +- src/saturator/plugin.rs | 2 +- src/stereo/gui.rs | 26 +- src/stereo/plugin.rs | 2 +- src/synth/plugin.rs | 2 +- src/transient/dsp.rs | 469 +++++++++++++++++++++++++++------ src/transient/gui.rs | 537 +++++++++++++++++++++++++++++++++----- src/transient/params.rs | 258 ++++++++++++++++--- src/transient/plugin.rs | 334 ++++++++++++++++++++---- src/tuner/plugin.rs | 2 +- src/vocoder/plugin.rs | 2 +- src/volume/plugin.rs | 2 +- src/wah/plugin.rs | 2 +- 50 files changed, 3672 insertions(+), 350 deletions(-) create mode 100644 src/invert/dsp.rs create mode 100644 src/invert/gui.rs create mode 100644 src/invert/mod.rs create mode 100644 src/invert/params.rs create mode 100644 src/invert/plugin.rs create mode 100644 src/invert/state.rs create mode 100644 src/lag/dsp.rs create mode 100644 src/lag/gui.rs create mode 100644 src/lag/mod.rs create mode 100644 src/lag/params.rs create mode 100644 src/lag/plugin.rs create mode 100644 src/lag/state.rs diff --git a/Cargo.lock b/Cargo.lock index 4058ba3..e978607 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,9 +26,9 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "ahash" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54dae3d1d7b8956f3506c4e999a74e77f932a59153ccf38ab8cf96db74bb9dc0" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" dependencies = [ "cfg-if", "getrandom 0.4.3", @@ -98,9 +98,9 @@ checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" [[package]] name = "android_system_properties" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +checksum = "204ddd8b860c1ff4b89d3cef1d23180caa4d0c34d34c9c2b009bc441ffb94d0f" dependencies = [ "libc", ] @@ -136,9 +136,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" [[package]] name = "as-raw-xcb-connection" @@ -280,9 +280,9 @@ dependencies = [ [[package]] name = "async-task" -version = "4.7.1" +version = "4.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" +checksum = "ba73fde82d895a41b0f864a3657264424d9804474e343edc5ca2a4a804218736" [[package]] name = "async-trait" @@ -616,7 +616,7 @@ dependencies = [ "js-sys", "num-traits", "wasm-bindgen", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1001,7 +1001,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.101.0", ] [[package]] @@ -1405,9 +1405,9 @@ checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-lite" -version = "2.6.1" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +checksum = "28aadd44bf60a243dd4f49b467a5ff30fee9e4dbaed326795d433ffa8a561730" dependencies = [ "fastrand", "futures-core", @@ -1463,7 +1463,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ "rustix 1.1.6", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -1687,9 +1687,9 @@ checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" [[package]] name = "http" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05" dependencies = [ "bytes", "itoa", @@ -2105,9 +2105,9 @@ dependencies = [ [[package]] name = "image-webp" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +checksum = "7c8d2831f3eb9706eeac62164959a288f12c047a3c53b353c6c00d5d60eb5c7f" dependencies = [ "byteorder-lite", "quick-error", @@ -2169,7 +2169,7 @@ dependencies = [ "simd_cesu8", "thiserror 2.0.21", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -2314,7 +2314,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -2324,7 +2324,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" dependencies = [ "cfg-if", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -2520,9 +2520,9 @@ checksum = "0806877c16abfdc601427c661ac1afbe142c0f77701debe586997911af2f25fe" [[package]] name = "maolan-editor" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c7268dd1b7035c59a5a0c115a316d572764120e0de205a2997ff4132bd02741" +checksum = "e3a30bb33e27252d90fb370f63b6cb774dd012669acaa86bff203c8d14f6eacb" dependencies = [ "maolan-widgets", "rfd", @@ -2572,9 +2572,9 @@ dependencies = [ [[package]] name = "maolan-widgets" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f08e81dc23ef2499b6a6fd03a64399bc4762909507b893c0c8ea6298650073c" +checksum = "ccb617a8a731a1a980da32c0b88f11765376816d81b1fa848d3fb277f5d91dff" dependencies = [ "bytemuck", "iced", @@ -3433,7 +3433,7 @@ dependencies = [ "libc", "redox_syscall 0.5.18", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3445,7 +3445,7 @@ dependencies = [ "libc", "redox_syscall 0.9.5", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3488,9 +3488,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.18" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "piper" @@ -3539,16 +3539,16 @@ dependencies = [ [[package]] name = "polling" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +checksum = "7ef68681b8567f8908e84dbaf3e0ca8d6200671d9c4b6b791b6ced20341465bb" dependencies = [ "cfg-if", "concurrent-queue", "hermit-abi", "pin-project-lite", "rustix 1.1.6", - "windows-sys 0.61.2", + "windows-sys 0.101.0", ] [[package]] @@ -4069,9 +4069,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.46" +version = "0.23.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +checksum = "86c8de8f13bac4bb046743409c751e2343621c0293a805c143ede57c5c95c3f8" dependencies = [ "log", "once_cell", @@ -4219,9 +4219,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c" dependencies = [ "cfg-if", "cpufeatures", @@ -5674,7 +5674,7 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement 0.60.2", "windows-interface 0.59.3", - "windows-link", + "windows-link 0.2.1", "windows-result 0.4.1", "windows-strings 0.5.1", ] @@ -5686,7 +5686,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ "windows-core 0.62.2", - "windows-link", + "windows-link 0.2.1", "windows-threading", ] @@ -5740,6 +5740,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-link" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4" + [[package]] name = "windows-numerics" version = "0.3.1" @@ -5747,7 +5753,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ "windows-core 0.62.2", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -5765,7 +5771,7 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -5784,7 +5790,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -5811,7 +5817,16 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-sys" +version = "0.101.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c" +dependencies = [ + "windows-link 0.101.0", ] [[package]] @@ -5836,7 +5851,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -6024,9 +6039,9 @@ checksum = "acf4d1bc32aa46eec18caa634ec3cf4c05bfa151f12b93b510b15190f69a1ca8" [[package]] name = "xcursor" -version = "0.3.11" +version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" +checksum = "083a6e8d274c0502e7dc9b37f9bc26fdaf666efc9002c38815ea50d19a179aac" [[package]] name = "xkbcommon-dl" @@ -6266,9 +6281,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.8.2" +version = "9.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" +checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9" dependencies = [ "constant_time_eq", "crc32fast", @@ -6310,9 +6325,9 @@ dependencies = [ [[package]] name = "zune-core" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18" [[package]] name = "zune-inflate" diff --git a/Cargo.toml b/Cargo.toml index 85d87e1..45c9b0c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,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.2", features = ["canvas"] } maolan-editor = { version = "0.1.6", default-features = false, features = ["embedded"] } -maolan-widgets = "0.1.7" +maolan-widgets = "0.1.8" 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/bitcrusher/plugin.rs b/src/bitcrusher/plugin.rs index 572c67e..42f7326 100644 --- a/src/bitcrusher/plugin.rs +++ b/src/bitcrusher/plugin.rs @@ -29,7 +29,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.bitcrusher\0"; const PLUGIN_NAME: &[u8] = b"Maolan Bitcrusher\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Bit-depth and sample-rate reduction\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_DISTORTION: *const c_char = CLAP_PLUGIN_FEATURE_DISTORTION.as_ptr(); diff --git a/src/chorus/plugin.rs b/src/chorus/plugin.rs index 25926cd..d03f10d 100644 --- a/src/chorus/plugin.rs +++ b/src/chorus/plugin.rs @@ -25,7 +25,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.chorus\0"; const PLUGIN_NAME: &[u8] = b"Maolan Chorus\0"; const PLUGIN_URL: &[u8] = b"\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Stereo chorus based on Mire Chorus\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/common/spectrum.rs b/src/common/spectrum.rs index 9d70ff6..7cfc37a 100644 --- a/src/common/spectrum.rs +++ b/src/common/spectrum.rs @@ -199,6 +199,8 @@ pub struct SpectrumThresholdCurve { pub selected_color: Option, pub width: f32, pub selected_width: f32, + pub selected_band: Option, + pub band_splits: Vec, pub on_select: Option, pub on_select_at: Option Message + Send + Sync>>, pub on_drag_db: Option Message + Send + Sync>>, @@ -223,6 +225,8 @@ impl Clone for SpectrumThresholdCurve { selected_color: self.selected_color, width: self.width, selected_width: self.selected_width, + selected_band: self.selected_band, + band_splits: self.band_splits.clone(), on_select: self.on_select.clone(), on_select_at: self.on_select_at.clone(), on_drag_db: self.on_drag_db.clone(), @@ -245,6 +249,8 @@ pub struct SpectralAnalyzerWidget { pub bins_db: [[f32; BINS]; 2], pub stereo: bool, pub display_range_db: f32, + pub db_range: Option<(f32, f32)>, + pub show_db_labels: bool, pub markers: Vec>, pub threshold_curves: Vec>, pub gain_reduction_db: Vec, @@ -261,6 +267,8 @@ impl SpectralAnalyzerWidget SpectralAnalyzerWidget Self { + self.db_range = Some((min_db.min(max_db - 1.0), max_db)); + self + } + + pub fn with_db_labels(mut self, show: bool) -> Self { + self.show_db_labels = show; + self + } + pub fn with_spectrum_markers(mut self, markers: Vec>) -> Self { self.markers = markers; self @@ -325,7 +343,9 @@ impl SpectralAnalyzerWidget f32 { - if self.display_range_db > 0.0 { + if let Some((min, _)) = self.db_range { + min + } else if self.display_range_db > 0.0 { display_range_bounds(self.display_range_db).0 } else { -60.0 @@ -333,7 +353,9 @@ impl SpectralAnalyzerWidget f32 { - if self.display_range_db > 0.0 { + if let Some((_, max)) = self.db_range { + max + } else if self.display_range_db > 0.0 { display_range_bounds(self.display_range_db).1 } else { 0.0 @@ -353,12 +375,10 @@ impl SpectralAnalyzerWidget f32 { - db_to_y( - db, - bounds, - Self::SPECTRUM_DISPLAY_MIN_DB, - Self::SPECTRUM_DISPLAY_MAX_DB, - ) + let (min, max) = self + .db_range + .unwrap_or((Self::SPECTRUM_DISPLAY_MIN_DB, Self::SPECTRUM_DISPLAY_MAX_DB)); + db_to_y(db, bounds, min, max) } fn smoothed_points(&self, bins_db: &[f32; BINS], bounds: Rectangle) -> Vec { @@ -442,6 +462,44 @@ impl SpectralAnalyzerWidget, + bounds: Rectangle, + band: usize, + ) -> Path { + let lower = band + .checked_sub(1) + .and_then(|index| curve.band_splits.get(index)); + let upper = curve.band_splits.get(band); + let mut points: Vec<(f32, f32)> = curve + .points + .iter() + .copied() + .filter(|(freq, _)| { + lower.is_none_or(|split| *freq >= *split) + && upper.is_none_or(|split| *freq < *split) + }) + .collect(); + if let Some(freq) = lower + && let Some(db) = interpolate_curve_db(&curve.points, *freq) + { + points.insert(0, (*freq, db)); + } + if let Some(freq) = upper + && let Some(db) = interpolate_curve_db(&curve.points, *freq) + { + points.push((*freq, db)); + } + let points: Vec = points + .into_iter() + .map(|(freq, db)| { + Point::new(Self::freq_to_x(freq, bounds), self.curve_to_y(db, bounds)) + }) + .collect(); + Path::new(|b| Self::draw_smooth_points(&points, b)) + } + fn closest_curve(&self, pos: Point, bounds: Rectangle) -> Option { let mut closest = None; let mut closest_distance = 8.0_f32; @@ -812,19 +870,21 @@ impl Program .with_color(c) .with_width(1.0), ); - frame.fill_text(Text { - content: if db == 0.0 { - "0".to_string() - } else if db.fract().abs() < 0.01 { - format!("{db:+.0}") - } else { - format!("{db:+.1}") - }, - position: Point::new(4.0, y + 2.0), - color: Color::from_rgba(0.72, 0.76, 0.82, 0.45), - size: 9.0.into(), - ..Text::default() - }); + if self.show_db_labels { + frame.fill_text(Text { + content: if db == 0.0 { + "0".to_string() + } else if db.fract().abs() < 0.01 { + format!("{db:+.0}") + } else { + format!("{db:+.1}") + }, + position: Point::new(4.0, y + 2.0), + color: Color::from_rgba(0.72, 0.76, 0.82, 0.45), + size: 9.0.into(), + ..Text::default() + }); + } } for hz in [ @@ -880,7 +940,6 @@ impl Program } for curve in &self.threshold_curves { - let path = self.threshold_curve_path(curve, local_bounds); let color = if curve.selected { curve .selected_color @@ -890,17 +949,29 @@ impl Program .color .unwrap_or_else(|| Color::from_rgba(1.0, 0.48, 0.25, 0.72)) }; - let width = if curve.selected { + let width = if curve.selected && curve.selected_band.is_none() { curve.selected_width } else { curve.width }; frame.stroke( - &path, + &self.threshold_curve_path(curve, local_bounds), canvas_module::Stroke::default() .with_color(color) .with_width(width), ); + if let Some(band) = curve.selected_band { + frame.stroke( + &self.selected_band_curve_path(curve, local_bounds, band), + canvas_module::Stroke::default() + .with_color( + curve + .selected_color + .unwrap_or_else(|| Color::from_rgba(1.0, 0.86, 0.22, 0.96)), + ) + .with_width(curve.selected_width), + ); + } } if !self.gain_reduction_db.is_empty() { @@ -930,6 +1001,27 @@ impl Program } } +fn interpolate_curve_db(points: &[(f32, f32)], freq: f32) -> Option { + let (_, first_db) = *points.first()?; + let (last_freq, last_db) = *points.last()?; + if freq <= points.first()?.0 { + return Some(first_db); + } + if freq >= last_freq { + return Some(last_db); + } + points.windows(2).find_map(|window| { + let [(low_freq, low_db), (high_freq, high_db)] = window else { + return None; + }; + if freq < *low_freq || freq > *high_freq { + return None; + } + let t = (freq / low_freq).ln() / (high_freq / low_freq).ln(); + Some(low_db + (high_db - low_db) * t) + }) +} + pub fn format_freq(freq_hz: f32) -> String { if freq_hz >= 1000.0 { format!("{:.0}k", freq_hz / 1000.0) @@ -1079,6 +1171,15 @@ mod tests { } } + #[test] + fn curve_interpolation_finds_exact_crossover_value() { + let points = [(100.0, -12.0), (1_000.0, -2.0)]; + assert_eq!(interpolate_curve_db(&points, 100.0), Some(-12.0)); + assert_eq!(interpolate_curve_db(&points, 1_000.0), Some(-2.0)); + let midpoint = interpolate_curve_db(&points, 10.0_f32.sqrt() * 100.0).unwrap(); + assert!((midpoint + 7.0).abs() < 1.0e-5); + } + #[test] fn db_axis_roundtrips_display_range() { let bounds = Rectangle { diff --git a/src/compressor/gui.rs b/src/compressor/gui.rs index 0c36cdc..fd5b190 100644 --- a/src/compressor/gui.rs +++ b/src/compressor/gui.rs @@ -953,7 +953,9 @@ fn threshold_curves(params: ThresholdCurveParams) -> Vec Vec Vec for App { type Parent = ParentWindowHandle; fn title() -> String { - String::from("Maolan MB Compressor") + String::from("Maolan Compressor") } fn size() -> (u32, u32) { diff --git a/src/compressor/plugin.rs b/src/compressor/plugin.rs index a1c03cf..8f93149 100644 --- a/src/compressor/plugin.rs +++ b/src/compressor/plugin.rs @@ -37,7 +37,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.compressor\0"; const PLUGIN_NAME: &[u8] = b"Maolan Compressor\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Rust CLAP Compressor based on LSP\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_COMPRESSOR: *const c_char = CLAP_PLUGIN_FEATURE_COMPRESSOR.as_ptr(); diff --git a/src/deesser/plugin.rs b/src/deesser/plugin.rs index 1c449b4..d7f7c8f 100644 --- a/src/deesser/plugin.rs +++ b/src/deesser/plugin.rs @@ -26,7 +26,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.deesser\0"; const PLUGIN_NAME: &[u8] = b"Maolan DeEsser\0"; const PLUGIN_URL: &[u8] = b"\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Sibilance reduction processor\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/delay/gui.rs b/src/delay/gui.rs index 1dff376..81632ff 100644 --- a/src/delay/gui.rs +++ b/src/delay/gui.rs @@ -3,7 +3,7 @@ use std::{ffi::CStr, sync::Arc}; use maolan_baseview::iced::{ Alignment, Element, Length, Task, Theme, alignment::{Horizontal, Vertical}, - widget::{column, container, row, text, toggler}, + widget::{column, container, row, text}, }; #[cfg(target_os = "macos")] use maolan_clap::ffi::CLAP_WINDOW_API_COCOA; @@ -273,9 +273,11 @@ fn view(state: &State) -> Element<'_, Message> { let time_mode_value = state.shared.params.get(ParamId::TimeMode) as f32; let time_mode_switch = row![ text("Time").size(14), - text("ms").size(13), - toggler(time_mode_value >= 0.5).on_toggle(|v| Message::SetBoolParam(ParamId::TimeMode, v)), - text("Note").size(13), + horizontal_multi_toggler( + ["ms", "Note"], + usize::from(time_mode_value >= 0.5), + |index| Message::SetBoolParam(ParamId::TimeMode, index == 1), + ), ] .spacing(6) .align_y(Alignment::Center); diff --git a/src/delay/plugin.rs b/src/delay/plugin.rs index 78f44fd..c9823a7 100644 --- a/src/delay/plugin.rs +++ b/src/delay/plugin.rs @@ -35,7 +35,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.delay\0"; const PLUGIN_NAME: &[u8] = b"Maolan Delay\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Rust CLAP delay with ms/note sync\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr(); diff --git a/src/drums/download.rs b/src/drums/download.rs index ee7e4bb..9d521d9 100644 --- a/src/drums/download.rs +++ b/src/drums/download.rs @@ -31,7 +31,7 @@ fn kit_url(kit_name: &str) -> Option<&'static str> { fn cache_dir() -> PathBuf { let cache_base = dirs::cache_dir().unwrap_or_else(|| PathBuf::from("/tmp")); - cache_base.join("drums") + cache_base.join("maolan").join("drums") } fn kit_folder_name(kit_name: &str) -> String { diff --git a/src/drums/plugin.rs b/src/drums/plugin.rs index 9cd884f..51ba272 100644 --- a/src/drums/plugin.rs +++ b/src/drums/plugin.rs @@ -38,7 +38,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.drums\0"; const PLUGIN_NAME: &[u8] = b"Maolan Drums\0"; const PLUGIN_VENDOR: &[u8] = b"maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Drum sampler CLAP plugin\0"; const FEATURE_INSTRUMENT: *const c_char = CLAP_PLUGIN_FEATURE_INSTRUMENT.as_ptr(); diff --git a/src/eq/plugin.rs b/src/eq/plugin.rs index 7eaeb27..b42fa17 100644 --- a/src/eq/plugin.rs +++ b/src/eq/plugin.rs @@ -58,7 +58,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.equalizer\0"; const PLUGIN_NAME: &[u8] = b"Maolan EQ\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Rust CLAP Equalizer\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); diff --git a/src/flanger/gui.rs b/src/flanger/gui.rs index 8b8c756..8ccdcc0 100644 --- a/src/flanger/gui.rs +++ b/src/flanger/gui.rs @@ -13,7 +13,7 @@ use maolan_clap::ffi::CLAP_WINDOW_API_X11; use maolan_baseview::iced::{ Alignment, Element, Length, Task, Theme, alignment::{Horizontal, Vertical}, - widget::{column, container, pick_list, row, text, toggler}, + widget::{column, container, pick_list, row, text}, }; #[cfg(any( target_os = "windows", @@ -206,7 +206,9 @@ fn switch<'a>(id: ParamId, label: &'a str, state: &'a State) -> Element<'a, Mess let value = state.shared.params.get(id) >= 0.5; row![ text(label).size(13), - toggler(value).on_toggle(move |v| Message::SetBoolParam(id, v)), + horizontal_multi_toggler(["Off", "On"], usize::from(value), move |index| { + Message::SetBoolParam(id, index == 1) + }), ] .spacing(6) .align_y(Alignment::Center) diff --git a/src/flanger/plugin.rs b/src/flanger/plugin.rs index 2cb2d23..da82ece 100644 --- a/src/flanger/plugin.rs +++ b/src/flanger/plugin.rs @@ -36,7 +36,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.flanger\0"; const PLUGIN_NAME: &[u8] = b"Maolan Flanger\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Stereo flanger with LFO-modulated delay and feedback\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/formant/plugin.rs b/src/formant/plugin.rs index dbf9367..7c41580 100644 --- a/src/formant/plugin.rs +++ b/src/formant/plugin.rs @@ -29,7 +29,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.formant\0"; const PLUGIN_NAME: &[u8] = b"Maolan Formant\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Stereo formant filter based on Mire Formant\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/gate/plugin.rs b/src/gate/plugin.rs index c9cc0a7..e559d2b 100644 --- a/src/gate/plugin.rs +++ b/src/gate/plugin.rs @@ -34,7 +34,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.gate\0"; const PLUGIN_NAME: &[u8] = b"Maolan Gate\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Stereo downward expander and noise gate\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_GATE: *const c_char = CLAP_PLUGIN_FEATURE_GATE.as_ptr(); diff --git a/src/invert/dsp.rs b/src/invert/dsp.rs new file mode 100644 index 0000000..d7012f5 --- /dev/null +++ b/src/invert/dsp.rs @@ -0,0 +1,27 @@ +pub fn process(buffer: &mut [f32], invert: bool) { + if invert { + for sample in buffer { + *sample = -*sample; + } + } +} + +#[cfg(test)] +mod tests { + use super::process; + + #[test] + fn leaves_signal_unchanged_when_disabled() { + let original = [0.25, -0.5, 0.75, -1.0]; + let mut buffer = original; + process(&mut buffer, false); + assert_eq!(buffer, original); + } + + #[test] + fn inverts_signal_polarity_when_enabled() { + let mut buffer = [0.25, -0.5, 0.75, -1.0]; + process(&mut buffer, true); + assert_eq!(buffer, [-0.25, 0.5, -0.75, 1.0]); + } +} diff --git a/src/invert/gui.rs b/src/invert/gui.rs new file mode 100644 index 0000000..96ee9a5 --- /dev/null +++ b/src/invert/gui.rs @@ -0,0 +1,292 @@ +use std::{ffi::CStr, sync::Arc}; + +use maolan_baseview::iced::{ + Alignment, Element, Length, Task, Theme, + alignment::{Horizontal, Vertical}, + widget::{column, container, row, text}, +}; +#[cfg(target_os = "macos")] +use maolan_clap::ffi::CLAP_WINDOW_API_COCOA; +#[cfg(target_os = "windows")] +use maolan_clap::ffi::CLAP_WINDOW_API_WIN32; +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +use maolan_clap::ffi::CLAP_WINDOW_API_X11; +use maolan_widgets::multi_toggler::horizontal_multi_toggler; +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" +))] +use raw_window_handle::RawWindowHandle; +use raw_window_handle::{HandleError, HasWindowHandle, WindowHandle}; + +use crate::{ + common::preset::{self, PresetProvider, PresetUi}, + invert::{params::ParamId, plugin::SharedState}, +}; + +pub const EDITOR_WIDTH: u32 = 440; +pub const EDITOR_HEIGHT: u32 = 230; + +pub fn preferred_api() -> &'static CStr { + #[cfg(target_os = "windows")] + { + CLAP_WINDOW_API_WIN32 + } + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + CLAP_WINDOW_API_X11 + } + #[cfg(target_os = "macos")] + { + CLAP_WINDOW_API_COCOA + } +} + +pub fn is_api_supported(api: &CStr, _is_floating: bool) -> bool { + api == preferred_api() +} + +pub enum ParentWindowHandle { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + X11(usize), + #[cfg(target_os = "macos")] + Cocoa(*mut std::ffi::c_void), + #[cfg(target_os = "windows")] + Win32(*mut std::ffi::c_void), +} + +impl HasWindowHandle for ParentWindowHandle { + fn window_handle(&self) -> Result, HandleError> { + match self { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + ParentWindowHandle::X11(window) => { + let handle = raw_window_handle::XlibWindowHandle::new(*window as _); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Xlib(handle)) }) + } + #[cfg(target_os = "windows")] + ParentWindowHandle::Win32(hwnd) => { + let handle = raw_window_handle::Win32WindowHandle::new( + std::num::NonZeroIsize::new(*hwnd as isize).unwrap(), + ); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Win32(handle)) }) + } + #[cfg(target_os = "macos")] + ParentWindowHandle::Cocoa(ns_view) => { + let handle = raw_window_handle::AppKitWindowHandle::new( + std::ptr::NonNull::new(*ns_view).expect("null NSView"), + ); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::AppKit(handle)) }) + } + } + } +} + +#[derive(Debug, Clone)] +pub enum Message { + SetChannels(usize), + SetInverted(ParamId, bool), + Preset(preset::Msg), +} + +impl From for Message { + fn from(msg: preset::Msg) -> Self { + Message::Preset(msg) + } +} + +struct State { + shared: Arc, + preset_ui: PresetUi, +} + +fn init(shared: Arc) -> (State, Task) { + ( + State { + shared, + preset_ui: PresetUi::new(SharedState::DIR_NAME), + }, + Task::none(), + ) +} + +fn update(state: &mut State, message: Message) -> Task { + match message { + Message::SetChannels(index) => { + state.shared.mark_gesture_begin_pending(ParamId::Channels); + state + .shared + .set_param_outbound_only(ParamId::Channels, (index + 1) as f64); + state.shared.mark_gesture_end_pending(ParamId::Channels); + } + Message::SetInverted(id, inverted) => { + state.shared.mark_gesture_begin_pending(id); + state + .shared + .set_param_outbound_only(id, if inverted { 1.0 } else { 0.0 }); + state.shared.mark_gesture_end_pending(id); + } + Message::Preset(msg) => { + preset::update(&mut state.preset_ui, msg, state.shared.as_ref()); + } + } + Task::none() +} + +fn view(state: &State) -> Element<'_, Message> { + let channels = state.shared.channels() as usize; + let channels_toggle = horizontal_multi_toggler( + ["Mono", "Stereo"], + channels.saturating_sub(1), + Message::SetChannels, + ); + let left = row![ + text(if channels == 2 { "Left" } else { "Channel" }), + horizontal_multi_toggler( + ["Off", "On"], + usize::from(state.shared.params.get_bool(ParamId::Left)), + |index| Message::SetInverted(ParamId::Left, index == 1), + ), + ] + .spacing(12) + .align_y(Alignment::Center); + let mut controls = row![left].spacing(32).align_y(Alignment::Center); + if channels == 2 { + controls = controls.push( + row![ + text("Right"), + horizontal_multi_toggler( + ["Off", "On"], + usize::from(state.shared.params.get_bool(ParamId::Right)), + |index| Message::SetInverted(ParamId::Right, index == 1), + ), + ] + .spacing(12) + .align_y(Alignment::Center), + ); + } + + let content = column![preset::bar(&state.preset_ui), channels_toggle, controls] + .spacing(24) + .align_x(Alignment::Start); + + container(content) + .padding(24) + .width(Length::Fill) + .height(Length::Fill) + .align_x(Horizontal::Left) + .align_y(Vertical::Top) + .into() +} + +fn theme(_state: &State) -> Theme { + Theme::TokyoNight +} + +fn build_app(shared: Arc) -> impl maolan_baseview::iced::Program { + maolan_baseview::iced::application(move || init(shared.clone()), update, view) + .font(maolan_widgets::iced_fonts::LUCIDE_FONT_BYTES) + .theme(theme) + .run() +} + +pub struct App; + +impl crate::common::gui_bridge::GuiApp for App { + type Parent = ParentWindowHandle; + + fn title() -> String { + String::from("Maolan Invert") + } + + fn size() -> (u32, u32) { + (EDITOR_WIDTH, EDITOR_HEIGHT) + } + + fn always_redraw() -> bool { + false + } + + fn notify_closed_on_hide() -> bool { + true + } + + fn opens_parented_window() -> bool { + true + } + + fn preferred_api() -> &'static CStr { + preferred_api() + } + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" + ))] + fn parent_from_window( + window: &maolan_clap::ffi::clap_window, + api: &CStr, + ) -> Option { + crate::invert::gui::parent_from_window(window, api) + } + + fn build_app( + shared: std::sync::Arc, + ) -> impl maolan_baseview::iced::Program { + build_app(shared) + } +} + +pub type GuiBridge = crate::common::gui_bridge::GuiBridge; + +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" +))] +pub fn parent_from_window( + window: &maolan_clap::ffi::clap_window, + api: &CStr, +) -> Option { + use maolan_clap::ffi::{CLAP_WINDOW_API_COCOA, CLAP_WINDOW_API_WIN32, CLAP_WINDOW_API_X11}; + if api == CLAP_WINDOW_API_X11 { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + Some(ParentWindowHandle::X11(unsafe { + window.clap_window__.x11 as usize + })) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd")))] + { + None + } + } else if api == CLAP_WINDOW_API_WIN32 { + #[cfg(target_os = "windows")] + { + Some(ParentWindowHandle::Win32(unsafe { + window.clap_window__.win32 + })) + } + #[cfg(not(target_os = "windows"))] + { + None + } + } else if api == CLAP_WINDOW_API_COCOA { + #[cfg(target_os = "macos")] + { + Some(ParentWindowHandle::Cocoa(unsafe { + window.clap_window__.cocoa + })) + } + #[cfg(not(target_os = "macos"))] + { + None + } + } else { + None + } +} diff --git a/src/invert/mod.rs b/src/invert/mod.rs new file mode 100644 index 0000000..a21b470 --- /dev/null +++ b/src/invert/mod.rs @@ -0,0 +1,7 @@ +pub mod dsp; +pub mod gui; +mod params; +mod plugin; +mod state; + +pub use plugin::{clap_create_plugin, descriptor_ptr as clap_descriptor_ptr}; diff --git a/src/invert/params.rs b/src/invert/params.rs new file mode 100644 index 0000000..b5b76e2 --- /dev/null +++ b/src/invert/params.rs @@ -0,0 +1,48 @@ +use maolan_clap::ffi::{ + CLAP_PARAM_IS_AUTOMATABLE, CLAP_PARAM_IS_ENUM, CLAP_PARAM_IS_STEPPED, + CLAP_PARAM_REQUIRES_PROCESS, +}; + +crate::define_params! { + pub enum ParamId { + Left = 0, + Right = 1, + Channels = 2, + } + pub const PARAMS: [ParamDef] = [ + { + id: ParamId::Left, + name: "Invert Left", + module: "Polarity", + min: 0.0, + max: 1.0, + default: 0.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Right, + name: "Invert Right", + module: "Polarity", + min: 0.0, + max: 1.0, + default: 0.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Channels, + name: "Channels", + module: "Configuration", + min: 1.0, + max: 2.0, + default: 2.0, + step: 1.0, + flags: ENUM_FLAGS, + } + ]; +} + +const AUTOMATABLE: u32 = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_REQUIRES_PROCESS; +const STEPPED: u32 = AUTOMATABLE | CLAP_PARAM_IS_STEPPED; +const ENUM_FLAGS: u32 = STEPPED | CLAP_PARAM_IS_ENUM; diff --git a/src/invert/plugin.rs b/src/invert/plugin.rs new file mode 100644 index 0000000..239e925 --- /dev/null +++ b/src/invert/plugin.rs @@ -0,0 +1,463 @@ +use std::{ + ffi::{CStr, c_char, c_void}, + sync::atomic::{AtomicU32, Ordering}, +}; + +use maolan_clap::{ + ffi::{ + CLAP_EXT_AUDIO_PORTS, CLAP_EXT_GUI, CLAP_EXT_PARAMS, CLAP_EXT_STATE, CLAP_EXT_TAIL, + CLAP_PLUGIN_FEATURE_AUDIO_EFFECT, CLAP_PLUGIN_FEATURE_MONO, CLAP_PLUGIN_FEATURE_STEREO, + CLAP_PLUGIN_FEATURE_UTILITY, CLAP_PROCESS_CONTINUE, CLAP_VERSION, clap_host, clap_plugin, + clap_plugin_descriptor, clap_process_status, + }, + process::Process, +}; + +use crate::common::clap_harness::{ + DescriptorMeta, ParamHost, ParamSharedState, ParamSpec, PortConfig, Processor, SharedBase, + StateHooks, +}; +use crate::common::{apply_param_events, emit_pending_param_events_to_host}; +use crate::invert::{ + dsp, + gui::GuiBridge, + params::{PARAMS, ParamId, sanitize_param_value}, + state::{PluginState, STATE_HEADER_PREFIX}, +}; +use crate::{ + clap_create_fn, clap_descriptor, clap_gui_ext, clap_params_ext, clap_state_ext, clap_tail_ext, + mono_pair, +}; + +const PLUGIN_ID: &[u8] = b"rs.maolan.invert\0"; +const PLUGIN_NAME: &[u8] = b"Maolan Invert\0"; +const PLUGIN_URL: &[u8] = b"\0"; +const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); +const PLUGIN_DESCRIPTION: &[u8] = b"Independent mono and stereo polarity inversion\0"; +const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); +const FEATURE_UTILITY: *const c_char = CLAP_PLUGIN_FEATURE_UTILITY.as_ptr(); +const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr(); +const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); +const FEATURE_PTRS: &[*const c_char] = &[ + FEATURE_AUDIO_EFFECT, + FEATURE_UTILITY, + FEATURE_MONO, + FEATURE_STEREO, + std::ptr::null(), +]; + +static META: DescriptorMeta = DescriptorMeta { + id: PLUGIN_ID, + name: PLUGIN_NAME, + vendor: PLUGIN_VENDOR, + url: PLUGIN_URL, + version: PLUGIN_VERSION, + description: PLUGIN_DESCRIPTION, + features: FEATURE_PTRS, +}; + +clap_descriptor!(META); + +#[derive(Debug)] +pub struct SharedState { + core: ParamSharedState, + channels: AtomicU32, +} + +impl Default for SharedState { + fn default() -> Self { + let core = ParamSharedState::default(); + let channels = core.params.get(ParamId::Channels).round() as u32; + Self { + core, + channels: AtomicU32::new(channels), + } + } +} + +impl std::ops::Deref for SharedState { + type Target = ParamSharedState; + + fn deref(&self) -> &Self::Target { + &self.core + } +} + +impl SharedBase for SharedState { + fn set_host(&self, host: *const clap_host) { + self.core.set_host(host); + } + + fn clear_host(&self) { + self.core.clear_host(); + } + + fn set_sample_rate(&self, sample_rate: f64) { + self.core.set_sample_rate(sample_rate); + } + + fn notify_gui_closed(&self) { + self.core.request_gui_closed(); + } + + fn on_param_set(&self, param_index: usize) { + if param_index == ParamId::Channels.as_index() { + self.sync_channels_from_params(); + self.core.request_audio_ports_rescan(); + } + } +} + +impl ParamHost for SharedState { + type Param = ParamId; + + fn params(&self) -> &crate::common::param_store::ParamStore { + &self.core.params + } +} + +impl crate::common::SharedStateExt for SharedState { + fn params_get(&self, id: ParamId) -> f64 { + self.core.params_get(id) + } + + fn set_gesture_active(&self, id: ParamId, active: bool) { + self.core.set_gesture_active(id, active); + } + + fn is_gesture_active(&self, id: ParamId) -> bool { + self.core.is_gesture_active(id) + } + + fn set_param_from_host(&self, id: ParamId, value: f64) { + self.core.set_param_from_host(id, value); + if id == ParamId::Channels { + self.sync_channels_from_params(); + self.core.request_audio_ports_rescan(); + } + } + + fn take_pending_param_notifications(&self) -> u64 { + self.core.take_pending_param_notifications() + } + + fn requeue_pending_param_notifications(&self, bits: u64) { + self.core.requeue_pending_param_notifications(bits); + } + + fn take_pending_gesture_begin(&self) -> u64 { + self.core.take_pending_gesture_begin() + } + + fn requeue_pending_gesture_begin(&self, bits: u64) { + self.core.requeue_pending_gesture_begin(bits); + } + + fn take_pending_gesture_end(&self) -> u64 { + self.core.take_pending_gesture_end() + } + + fn requeue_pending_gesture_end(&self, bits: u64) { + self.core.requeue_pending_gesture_end(bits); + } +} + +crate::impl_param_presets!(SharedState, ParamId, "invert", "maolan-invert-preset"); + +impl SharedState { + pub fn bump_params_version(&self) {} + + pub fn channels(&self) -> u32 { + self.channels.load(Ordering::Acquire) + } + + fn sync_channels_from_params(&self) { + let channels = self.params.get(ParamId::Channels).round() as u32; + self.channels.store(channels.clamp(1, 2), Ordering::Release); + } + + pub fn set_param_outbound_only(&self, id: ParamId, value: f64) { + self.core.set_param_outbound_only(id, value); + if id == ParamId::Channels { + self.sync_channels_from_params(); + self.core.request_audio_ports_rescan(); + } + } +} + +impl ParamSpec for ParamId { + fn param_defs() -> &'static [crate::common::clap_harness::ParamDef] { + &PARAMS + } + + fn param_text(id: Self, value: f64) -> String { + param_text(id, value) + } + + fn parse_param_text(id: Self, text: &str) -> Option { + parse_param_text(id, text) + } +} + +fn param_text(id: ParamId, value: f64) -> String { + match id { + ParamId::Left | ParamId::Right => { + if value >= 0.5 { + "Inverted".to_string() + } else { + "Normal".to_string() + } + } + ParamId::Channels => { + if value.round() as u32 >= 2 { + "Stereo".to_string() + } else { + "Mono".to_string() + } + } + } +} + +fn parse_param_text(id: ParamId, text: &str) -> Option { + let text = text.trim(); + match id { + ParamId::Left | ParamId::Right => match text.to_ascii_lowercase().as_str() { + "inverted" | "on" | "1" => Some(1.0), + "normal" | "off" | "0" => Some(0.0), + _ => text.parse().ok(), + }, + ParamId::Channels => match text.to_ascii_lowercase().as_str() { + "mono" | "1" => Some(1.0), + "stereo" | "2" => Some(2.0), + _ => text.parse().ok(), + }, + } +} + +struct AudioProcessor { + temp_left: Vec, + temp_right: Vec, +} + +impl AudioProcessor { + fn new(max_frames: u32) -> Self { + Self { + temp_left: vec![0.0; max_frames as usize], + temp_right: vec![0.0; max_frames as usize], + } + } + + fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { + apply_param_events(shared, &process.in_events(), sanitize_param_value); + { + let mut out_events = process.out_events(); + emit_pending_param_events_to_host(shared, &mut out_events); + } + + let frames = process.frames_count() as usize; + if self.temp_left.len() < frames { + self.temp_left.resize(frames, 0.0); + self.temp_right.resize(frames, 0.0); + } + let inputs_count = process.audio_inputs_count(); + let outputs_count = process.audio_outputs_count(); + + if inputs_count >= 2 && outputs_count >= 2 { + let input_l = process.audio_inputs(0); + let input_r = process.audio_inputs(1); + self.temp_left[..frames].copy_from_slice(input_l.data32(0)); + self.temp_right[..frames].copy_from_slice(input_r.data32(0)); + dsp::process( + &mut self.temp_left[..frames], + shared.params.get_bool(ParamId::Left), + ); + dsp::process( + &mut self.temp_right[..frames], + shared.params.get_bool(ParamId::Right), + ); + + let mut output_l = process.audio_outputs(0); + output_l.data32(0)[..frames].copy_from_slice(&self.temp_left[..frames]); + let mut output_r = process.audio_outputs(1); + output_r.data32(0)[..frames].copy_from_slice(&self.temp_right[..frames]); + } else if inputs_count >= 1 && outputs_count >= 1 { + let input = process.audio_inputs(0); + self.temp_left[..frames].copy_from_slice(input.data32(0)); + dsp::process( + &mut self.temp_left[..frames], + shared.params.get_bool(ParamId::Left), + ); + let mut output = process.audio_outputs(0); + output.data32(0)[..frames].copy_from_slice(&self.temp_left[..frames]); + } + + CLAP_PROCESS_CONTINUE + } +} + +impl Processor for AudioProcessor { + fn new( + _sample_rate: f64, + max_frames: u32, + _bus_data: Option, + ) -> Self { + AudioProcessor::new(max_frames) + } + + fn reset(&mut self) {} + + fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { + AudioProcessor::process(self, shared, process) + } +} + +impl StateHooks for PluginState { + fn save(shared: &SharedState) -> Option> { + PluginState::from_runtime(&shared.params) + .to_bytes(STATE_HEADER_PREFIX) + .ok() + } + + fn load(shared: &SharedState, bytes: &[u8]) -> bool { + let Ok(state) = PluginState::from_bytes(bytes, STATE_HEADER_PREFIX) else { + return false; + }; + state.apply(&shared.params); + shared.sync_channels_from_params(); + shared.core.request_audio_ports_rescan(); + true + } +} + +unsafe extern "C-unwind" fn ext_audio_ports_count( + plugin: *const clap_plugin, + _is_input: bool, +) -> u32 { + if plugin.is_null() { + return 0; + } + let instance = unsafe { + crate::common::clap_harness::instance::(plugin) + }; + instance.shared.channels() +} + +unsafe extern "C-unwind" fn ext_audio_ports_get( + plugin: *const clap_plugin, + index: u32, + is_input: bool, + info: *mut maolan_clap::ffi::clap_audio_port_info, +) -> bool { + if plugin.is_null() || info.is_null() { + return false; + } + let instance = unsafe { + crate::common::clap_harness::instance::(plugin) + }; + let channels = instance.shared.channels(); + if index >= channels { + return false; + } + let info = unsafe { &mut *info }; + info.id = index; + info.flags = maolan_clap::ffi::CLAP_AUDIO_PORT_IS_MAIN; + info.channel_count = 1; + info.port_type = maolan_clap::ffi::CLAP_PORT_MONO.as_ptr(); + info.in_place_pair = maolan_clap::ffi::CLAP_INVALID_ID; + let name = match (is_input, channels, index) { + (true, 2, 0) => "Left input", + (true, 2, 1) => "Right input", + (true, 1, 0) => "Input", + (false, 2, 0) => "Left output", + (false, 2, 1) => "Right output", + (false, 1, 0) => "Output", + _ => "", + }; + crate::common::copy_str_to_array(name, &mut info.name); + true +} + +static AUDIO_PORTS_EXT: maolan_clap::ffi::clap_plugin_audio_ports = + maolan_clap::ffi::clap_plugin_audio_ports { + count: Some(ext_audio_ports_count), + get: Some(ext_audio_ports_get), + }; + +clap_params_ext!(SharedState, AudioProcessor, GuiBridge); +clap_state_ext!(SharedState, AudioProcessor, GuiBridge, PluginState); +clap_tail_ext!(SharedState, AudioProcessor, GuiBridge, 0); +clap_gui_ext!(SharedState, AudioProcessor, GuiBridge); + +unsafe extern "C-unwind" fn plugin_get_extension( + plugin: *const clap_plugin, + id: *const c_char, +) -> *const c_void { + if plugin.is_null() || id.is_null() { + return std::ptr::null(); + } + let id = unsafe { CStr::from_ptr(id) }; + if id == CLAP_EXT_AUDIO_PORTS { + &raw const AUDIO_PORTS_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_PARAMS { + &raw const PARAMS_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_STATE { + &raw const STATE_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_TAIL { + &raw const TAIL_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_GUI { + &raw const GUI_EXT as *const _ as *const c_void + } else { + std::ptr::null() + } +} + +const PORTS: PortConfig = PortConfig { + inputs: mono_pair!("Left", "Right"), + outputs: mono_pair!("Left", "Right"), +}; + +clap_create_fn!(SharedState, AudioProcessor, GuiBridge, PORTS); + +#[cfg(test)] +mod tests { + use super::*; + use crate::common::SharedStateExt; + + #[test] + fn parameter_text_roundtrips() { + for id in ParamId::all() { + let value = PARAMS[id.as_index()].default; + let text = param_text(id, value); + assert_eq!(parse_param_text(id, &text), Some(value)); + } + } + + #[test] + fn channels_param_updates_audio_port_count() { + let shared = SharedState::default(); + assert_eq!(shared.channels(), 2); + shared.set_param_outbound_only(ParamId::Channels, 1.0); + assert_eq!(shared.channels(), 1); + shared.set_param_from_host(ParamId::Channels, 2.0); + assert_eq!(shared.channels(), 2); + } + + #[test] + fn state_roundtrip_preserves_parameters() { + let shared = SharedState::default(); + shared.set_param_outbound_only(ParamId::Left, 1.0); + shared.set_param_outbound_only(ParamId::Channels, 1.0); + let bytes = PluginState::from_runtime(&shared.params) + .to_bytes(STATE_HEADER_PREFIX) + .expect("state should save"); + + let restored = SharedState::default(); + PluginState::from_bytes(&bytes, STATE_HEADER_PREFIX) + .expect("state should load") + .apply(&restored.params); + restored.sync_channels_from_params(); + assert_eq!(restored.params.get(ParamId::Left), 1.0); + assert_eq!(restored.channels(), 1); + } +} diff --git a/src/invert/state.rs b/src/invert/state.rs new file mode 100644 index 0000000..ec6d5a8 --- /dev/null +++ b/src/invert/state.rs @@ -0,0 +1,5 @@ +use crate::invert::params::ParamId; + +pub type PluginState = crate::common::json_state::JsonParamState; + +pub const STATE_HEADER_PREFIX: &str = "maolan-invert-state-v"; diff --git a/src/kick/plugin.rs b/src/kick/plugin.rs index c608ae5..3392939 100644 --- a/src/kick/plugin.rs +++ b/src/kick/plugin.rs @@ -56,7 +56,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.kick\0"; const PLUGIN_NAME: &[u8] = b"Maolan Kick\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.2.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Percussive synthesizer CLAP plugin\0"; const FEATURE_INSTRUMENT: *const c_char = CLAP_PLUGIN_FEATURE_INSTRUMENT.as_ptr(); diff --git a/src/lag/dsp.rs b/src/lag/dsp.rs new file mode 100644 index 0000000..c4c7d7c --- /dev/null +++ b/src/lag/dsp.rs @@ -0,0 +1,125 @@ +pub const MAX_DELAY_SAMPLES: usize = 65_536; + +#[derive(Debug, Clone)] +struct DelayLine { + buffer: Vec, + write_index: usize, +} + +impl DelayLine { + fn new() -> Self { + Self { + buffer: vec![0.0; MAX_DELAY_SAMPLES + 1], + write_index: 0, + } + } + + fn reset(&mut self) { + self.buffer.fill(0.0); + self.write_index = 0; + } + + fn process(&mut self, input: f32, delay: usize) -> f32 { + let delay = delay.min(MAX_DELAY_SAMPLES); + self.buffer[self.write_index] = input; + let output = if delay == 0 { + input + } else { + let read_index = (self.write_index + self.buffer.len() - delay) % self.buffer.len(); + self.buffer[read_index] + }; + self.write_index = (self.write_index + 1) % self.buffer.len(); + output + } +} + +#[derive(Debug, Clone)] +pub struct Lag { + left: DelayLine, + right: DelayLine, +} + +impl Default for Lag { + fn default() -> Self { + Self { + left: DelayLine::new(), + right: DelayLine::new(), + } + } +} + +impl Lag { + pub fn reset(&mut self) { + self.left.reset(); + self.right.reset(); + } + + pub fn process_mono(&mut self, buffer: &mut [f32], delay: usize) { + for sample in buffer { + *sample = self.left.process(*sample, delay); + } + } + + pub fn process_stereo(&mut self, left: &mut [f32], right: &mut [f32], delays: [usize; 2]) { + for (left, right) in left.iter_mut().zip(right.iter_mut()) { + *left = self.left.process(*left, delays[0]); + *right = self.right.process(*right, delays[1]); + } + } +} + +#[cfg(test)] +mod tests { + use super::{Lag, MAX_DELAY_SAMPLES}; + + #[test] + fn zero_delay_passes_input_through() { + let original = [0.25, -0.5, 0.75, -1.0]; + let mut buffer = original; + Lag::default().process_mono(&mut buffer, 0); + assert_eq!(buffer, original); + } + + #[test] + fn delays_an_impulse_by_the_selected_sample_count() { + let mut buffer = [1.0, 0.0, 0.0, 0.0, 0.0]; + Lag::default().process_mono(&mut buffer, 3); + assert_eq!(buffer, [0.0, 0.0, 0.0, 1.0, 0.0]); + } + + #[test] + fn stereo_channels_have_independent_delays() { + let mut left = [1.0, 0.0, 0.0, 0.0]; + let mut right = [1.0, 0.0, 0.0, 0.0]; + Lag::default().process_stereo(&mut left, &mut right, [1, 3]); + assert_eq!(left, [0.0, 1.0, 0.0, 0.0]); + assert_eq!(right, [0.0, 0.0, 0.0, 1.0]); + } + + #[test] + fn history_is_available_when_delay_increases() { + let mut lag = Lag::default(); + lag.process_mono(&mut [1.0, 2.0, 3.0], 0); + let mut buffer = [4.0, 5.0, 6.0]; + lag.process_mono(&mut buffer, 3); + assert_eq!(buffer, [1.0, 2.0, 3.0]); + } + + #[test] + fn reset_clears_delay_history() { + let mut lag = Lag::default(); + lag.process_mono(&mut [1.0, 2.0, 3.0], 0); + lag.reset(); + let mut buffer = [4.0, 5.0]; + lag.process_mono(&mut buffer, 2); + assert_eq!(buffer, [0.0, 0.0]); + } + + #[test] + fn delay_is_limited_to_allocated_capacity() { + let mut buffer = vec![0.0; MAX_DELAY_SAMPLES + 2]; + buffer[0] = 1.0; + Lag::default().process_mono(&mut buffer, usize::MAX); + assert_eq!(buffer[MAX_DELAY_SAMPLES], 1.0); + } +} diff --git a/src/lag/gui.rs b/src/lag/gui.rs new file mode 100644 index 0000000..1b12669 --- /dev/null +++ b/src/lag/gui.rs @@ -0,0 +1,446 @@ +use std::{ffi::CStr, sync::Arc}; + +use maolan_baseview::iced::{ + Alignment, Element, Length, Task, Theme, + alignment::{Horizontal, Vertical}, + widget::{column, container, row, text}, +}; +#[cfg(target_os = "macos")] +use maolan_clap::ffi::CLAP_WINDOW_API_COCOA; +#[cfg(target_os = "windows")] +use maolan_clap::ffi::CLAP_WINDOW_API_WIN32; +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +use maolan_clap::ffi::CLAP_WINDOW_API_X11; +use maolan_widgets::{knob::Knob, multi_toggler::horizontal_multi_toggler}; +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" +))] +use raw_window_handle::RawWindowHandle; +use raw_window_handle::{HandleError, HasWindowHandle, WindowHandle}; + +use crate::{ + common::preset::{self, PresetProvider, PresetUi}, + lag::{ + dsp::MAX_DELAY_SAMPLES, + params::{PARAMS, ParamId}, + plugin::SharedState, + }, +}; + +pub const EDITOR_WIDTH: u32 = 540; +pub const EDITOR_HEIGHT: u32 = 300; + +pub fn preferred_api() -> &'static CStr { + #[cfg(target_os = "windows")] + { + CLAP_WINDOW_API_WIN32 + } + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + CLAP_WINDOW_API_X11 + } + #[cfg(target_os = "macos")] + { + CLAP_WINDOW_API_COCOA + } +} + +pub fn is_api_supported(api: &CStr, _is_floating: bool) -> bool { + api == preferred_api() +} + +pub enum ParentWindowHandle { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + X11(usize), + #[cfg(target_os = "macos")] + Cocoa(*mut std::ffi::c_void), + #[cfg(target_os = "windows")] + Win32(*mut std::ffi::c_void), +} + +impl HasWindowHandle for ParentWindowHandle { + fn window_handle(&self) -> Result, HandleError> { + match self { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + ParentWindowHandle::X11(window) => { + let handle = raw_window_handle::XlibWindowHandle::new(*window as _); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Xlib(handle)) }) + } + #[cfg(target_os = "windows")] + ParentWindowHandle::Win32(hwnd) => { + let handle = raw_window_handle::Win32WindowHandle::new( + std::num::NonZeroIsize::new(*hwnd as isize).unwrap(), + ); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::Win32(handle)) }) + } + #[cfg(target_os = "macos")] + ParentWindowHandle::Cocoa(ns_view) => { + let handle = raw_window_handle::AppKitWindowHandle::new( + std::ptr::NonNull::new(*ns_view).expect("null NSView"), + ); + Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::AppKit(handle)) }) + } + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DelayUnit { + Samples, + Milliseconds, +} + +#[derive(Debug, Clone)] +pub enum Message { + SetParam(ParamId, f32), + ReleaseParam(ParamId), + SetChannels(usize), + SetLinked(bool), + SetUnit(usize), + Preset(preset::Msg), +} + +impl From for Message { + fn from(msg: preset::Msg) -> Self { + Message::Preset(msg) + } +} + +struct State { + shared: Arc, + active_gestures: Vec, + unit: DelayUnit, + preset_ui: PresetUi, +} + +fn init(shared: Arc) -> (State, Task) { + ( + State { + shared, + active_gestures: vec![false; ParamId::COUNT], + unit: DelayUnit::Samples, + preset_ui: PresetUi::new(SharedState::DIR_NAME), + }, + Task::none(), + ) +} + +fn update(state: &mut State, message: Message) -> Task { + match message { + Message::SetParam(id, value) => { + let value = match state.unit { + DelayUnit::Samples => value, + DelayUnit::Milliseconds => value * state.shared.sample_rate() as f32 / 1_000.0, + }; + let index = id.as_index(); + if !state.active_gestures[index] { + state.active_gestures[index] = true; + state.shared.mark_gesture_begin_pending(id); + } + state.shared.set_param_outbound_only(id, value as f64); + if matches!(id, ParamId::Left | ParamId::Right) + && state.shared.params.get_bool(ParamId::Link) + { + let other = if id == ParamId::Left { + ParamId::Right + } else { + ParamId::Left + }; + state.shared.set_param_outbound_only(other, value as f64); + } + } + Message::ReleaseParam(id) => { + let index = id.as_index(); + if state.active_gestures[index] { + state.active_gestures[index] = false; + state.shared.mark_gesture_end_pending(id); + } + } + Message::SetChannels(index) => { + state.shared.mark_gesture_begin_pending(ParamId::Channels); + state + .shared + .set_param_outbound_only(ParamId::Channels, (index + 1) as f64); + state.shared.mark_gesture_end_pending(ParamId::Channels); + } + Message::SetLinked(linked) => { + state.shared.mark_gesture_begin_pending(ParamId::Link); + state + .shared + .set_param_outbound_only(ParamId::Link, if linked { 1.0 } else { 0.0 }); + state.shared.mark_gesture_end_pending(ParamId::Link); + if linked { + let left = state.shared.params.get(ParamId::Left); + state.shared.set_param_outbound_only(ParamId::Right, left); + } + } + Message::SetUnit(index) => { + state.unit = if index == 1 { + DelayUnit::Milliseconds + } else { + DelayUnit::Samples + }; + } + Message::Preset(msg) => { + preset::update(&mut state.preset_ui, msg, state.shared.as_ref()); + } + } + Task::none() +} + +fn view(state: &State) -> Element<'_, Message> { + let channels = state.shared.channels() as usize; + let channels_toggle = horizontal_multi_toggler( + ["Mono", "Stereo"], + channels.saturating_sub(1), + Message::SetChannels, + ); + let linked = state.shared.params.get_bool(ParamId::Link); + let link_toggle = column![ + text("Link"), + horizontal_multi_toggler(["Off", "On"], usize::from(linked), |index| { + Message::SetLinked(index == 1) + }) + ] + .spacing(4) + .align_x(Alignment::Center); + let unit_toggle = horizontal_multi_toggler( + ["Samples", "ms"], + usize::from(state.unit == DelayUnit::Milliseconds), + Message::SetUnit, + ); + let configuration: Element<'_, Message> = if channels == 2 { + row![channels_toggle, unit_toggle, link_toggle] + .spacing(8) + .align_y(Alignment::Center) + .into() + } else { + row![channels_toggle, unit_toggle] + .spacing(8) + .align_y(Alignment::Center) + .into() + }; + let sample_rate = state.shared.sample_rate() as f32; + let left_knob = knob( + if channels == 2 { "Left" } else { "Lag" }, + ParamId::Left, + state.shared.params.get(ParamId::Left) as f32, + state.unit, + sample_rate, + ); + let controls: Element<'_, Message> = if channels == 2 { + let right_value = if linked { + state.shared.params.get(ParamId::Left) + } else { + state.shared.params.get(ParamId::Right) + } as f32; + row![ + left_knob, + knob( + "Right", + ParamId::Right, + right_value, + state.unit, + sample_rate + ), + ] + .spacing(24) + .align_y(Alignment::Center) + .into() + } else { + left_knob + }; + + let content = column![preset::bar(&state.preset_ui), configuration, controls] + .spacing(24) + .align_x(Alignment::Start); + + container(content) + .padding(24) + .width(Length::Fill) + .height(Length::Fill) + .align_x(Horizontal::Left) + .align_y(Vertical::Top) + .into() +} + +fn knob( + label: &'static str, + id: ParamId, + samples: f32, + unit: DelayUnit, + sample_rate: f32, +) -> Element<'static, Message> { + let def = PARAMS[id.as_index()]; + let (value, max, default, step, value_text) = match unit { + DelayUnit::Samples => ( + samples, + def.max as f32, + def.default as f32, + def.step as f32, + format!("{samples:.0}"), + ), + DelayUnit::Milliseconds => { + let milliseconds = samples_to_milliseconds(samples, sample_rate); + ( + milliseconds, + MAX_DELAY_SAMPLES as f32 * 1_000.0 / sample_rate.max(1.0), + samples_to_milliseconds(def.default as f32, sample_rate), + 0.01, + if milliseconds < 10.0 { + format!("{milliseconds:.2}") + } else { + format!("{milliseconds:.1}") + }, + ) + } + }; + maolan_widgets::knob::knob( + Knob { + label: label.to_string(), + value, + range: 0.0..=max, + default, + step, + value_text, + assigned: false, + }, + move |value| Message::SetParam(id, value), + Message::ReleaseParam(id), + ) +} + +fn samples_to_milliseconds(samples: f32, sample_rate: f32) -> f32 { + samples * 1_000.0 / sample_rate.max(1.0) +} + +fn theme(_state: &State) -> Theme { + Theme::TokyoNight +} + +fn build_app(shared: Arc) -> impl maolan_baseview::iced::Program { + maolan_baseview::iced::application(move || init(shared.clone()), update, view) + .font(maolan_widgets::iced_fonts::LUCIDE_FONT_BYTES) + .theme(theme) + .run() +} + +pub struct App; + +impl crate::common::gui_bridge::GuiApp for App { + type Parent = ParentWindowHandle; + + fn title() -> String { + String::from("Maolan Lag") + } + + fn size() -> (u32, u32) { + (EDITOR_WIDTH, EDITOR_HEIGHT) + } + + fn always_redraw() -> bool { + false + } + + fn notify_closed_on_hide() -> bool { + true + } + + fn opens_parented_window() -> bool { + true + } + + fn preferred_api() -> &'static CStr { + preferred_api() + } + + #[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" + ))] + fn parent_from_window( + window: &maolan_clap::ffi::clap_window, + api: &CStr, + ) -> Option { + crate::lag::gui::parent_from_window(window, api) + } + + fn build_app( + shared: std::sync::Arc, + ) -> impl maolan_baseview::iced::Program { + build_app(shared) + } +} + +pub type GuiBridge = crate::common::gui_bridge::GuiBridge; + +#[cfg(any( + target_os = "windows", + target_os = "macos", + target_os = "linux", + target_os = "freebsd" +))] +pub fn parent_from_window( + window: &maolan_clap::ffi::clap_window, + api: &CStr, +) -> Option { + use maolan_clap::ffi::{CLAP_WINDOW_API_COCOA, CLAP_WINDOW_API_WIN32, CLAP_WINDOW_API_X11}; + if api == CLAP_WINDOW_API_X11 { + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + Some(ParentWindowHandle::X11(unsafe { + window.clap_window__.x11 as usize + })) + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd")))] + { + None + } + } else if api == CLAP_WINDOW_API_WIN32 { + #[cfg(target_os = "windows")] + { + Some(ParentWindowHandle::Win32(unsafe { + window.clap_window__.win32 + })) + } + #[cfg(not(target_os = "windows"))] + { + None + } + } else if api == CLAP_WINDOW_API_COCOA { + #[cfg(target_os = "macos")] + { + Some(ParentWindowHandle::Cocoa(unsafe { + window.clap_window__.cocoa + })) + } + #[cfg(not(target_os = "macos"))] + { + None + } + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::common::clap_harness::SharedBase; + + #[test] + fn millisecond_edits_are_stored_as_samples() { + let shared = Arc::new(SharedState::default()); + shared.set_sample_rate(48_000.0); + let (mut state, _) = init(shared.clone()); + let _ = update(&mut state, Message::SetUnit(1)); + let _ = update(&mut state, Message::SetParam(ParamId::Left, 10.0)); + assert_eq!(shared.params.get(ParamId::Left), 480.0); + assert_eq!(samples_to_milliseconds(480.0, 48_000.0), 10.0); + } +} diff --git a/src/lag/mod.rs b/src/lag/mod.rs new file mode 100644 index 0000000..a21b470 --- /dev/null +++ b/src/lag/mod.rs @@ -0,0 +1,7 @@ +pub mod dsp; +pub mod gui; +mod params; +mod plugin; +mod state; + +pub use plugin::{clap_create_plugin, descriptor_ptr as clap_descriptor_ptr}; diff --git a/src/lag/params.rs b/src/lag/params.rs new file mode 100644 index 0000000..8fc1af7 --- /dev/null +++ b/src/lag/params.rs @@ -0,0 +1,61 @@ +use maolan_clap::ffi::{ + CLAP_PARAM_IS_AUTOMATABLE, CLAP_PARAM_IS_ENUM, CLAP_PARAM_IS_STEPPED, + CLAP_PARAM_REQUIRES_PROCESS, +}; + +use crate::lag::dsp::MAX_DELAY_SAMPLES; + +crate::define_params! { + pub enum ParamId { + Left = 0, + Right = 1, + Link = 2, + Channels = 3, + } + pub const PARAMS: [ParamDef] = [ + { + id: ParamId::Left, + name: "Left Lag", + module: "Latency", + min: 0.0, + max: MAX_DELAY_SAMPLES as f64, + default: 0.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Right, + name: "Right Lag", + module: "Latency", + min: 0.0, + max: MAX_DELAY_SAMPLES as f64, + default: 0.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Link, + name: "Link Channels", + module: "Latency", + min: 0.0, + max: 1.0, + default: 0.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Channels, + name: "Channels", + module: "Configuration", + min: 1.0, + max: 2.0, + default: 2.0, + step: 1.0, + flags: ENUM_FLAGS, + } + ]; +} + +const AUTOMATABLE: u32 = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_REQUIRES_PROCESS; +const STEPPED: u32 = AUTOMATABLE | CLAP_PARAM_IS_STEPPED; +const ENUM_FLAGS: u32 = STEPPED | CLAP_PARAM_IS_ENUM; diff --git a/src/lag/plugin.rs b/src/lag/plugin.rs new file mode 100644 index 0000000..f221aad --- /dev/null +++ b/src/lag/plugin.rs @@ -0,0 +1,542 @@ +use std::{ + ffi::{CStr, c_char, c_void}, + sync::atomic::{AtomicU32, Ordering}, +}; + +use maolan_clap::{ + ffi::{ + CLAP_EXT_AUDIO_PORTS, CLAP_EXT_GUI, CLAP_EXT_LATENCY, CLAP_EXT_PARAMS, CLAP_EXT_STATE, + CLAP_EXT_TAIL, CLAP_PLUGIN_FEATURE_AUDIO_EFFECT, CLAP_PLUGIN_FEATURE_DELAY, + CLAP_PLUGIN_FEATURE_MONO, CLAP_PLUGIN_FEATURE_STEREO, CLAP_PROCESS_CONTINUE, CLAP_VERSION, + clap_host, clap_plugin, clap_plugin_descriptor, clap_process_status, + }, + process::Process, +}; + +use crate::common::clap_harness::{ + DescriptorMeta, ParamHost, ParamSharedState, ParamSpec, PortConfig, Processor, SharedBase, + StateHooks, +}; +use crate::common::{apply_param_events, emit_pending_param_events_to_host}; +use crate::lag::{ + dsp::Lag, + gui::GuiBridge, + params::{PARAMS, ParamId, sanitize_param_value}, + state::{PluginState, STATE_HEADER_PREFIX}, +}; +use crate::{ + clap_create_fn, clap_descriptor, clap_gui_ext, clap_params_ext, clap_state_ext, clap_tail_ext, + mono_pair, +}; + +const PLUGIN_ID: &[u8] = b"rs.maolan.lag\0"; +const PLUGIN_NAME: &[u8] = b"Maolan Lag\0"; +const PLUGIN_URL: &[u8] = b"\0"; +const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); +const PLUGIN_DESCRIPTION: &[u8] = b"Independent mono and stereo latency in samples\0"; +const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); +const FEATURE_DELAY: *const c_char = CLAP_PLUGIN_FEATURE_DELAY.as_ptr(); +const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr(); +const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); +const FEATURE_PTRS: &[*const c_char] = &[ + FEATURE_AUDIO_EFFECT, + FEATURE_DELAY, + FEATURE_MONO, + FEATURE_STEREO, + std::ptr::null(), +]; + +static META: DescriptorMeta = DescriptorMeta { + id: PLUGIN_ID, + name: PLUGIN_NAME, + vendor: PLUGIN_VENDOR, + url: PLUGIN_URL, + version: PLUGIN_VERSION, + description: PLUGIN_DESCRIPTION, + features: FEATURE_PTRS, +}; + +clap_descriptor!(META); + +#[derive(Debug)] +pub struct SharedState { + core: ParamSharedState, + channels: AtomicU32, +} + +impl Default for SharedState { + fn default() -> Self { + let core = ParamSharedState::default(); + let channels = core.params.get(ParamId::Channels).round() as u32; + Self { + core, + channels: AtomicU32::new(channels), + } + } +} + +impl std::ops::Deref for SharedState { + type Target = ParamSharedState; + + fn deref(&self) -> &Self::Target { + &self.core + } +} + +impl SharedBase for SharedState { + fn set_host(&self, host: *const clap_host) { + self.core.set_host(host); + } + + fn clear_host(&self) { + self.core.clear_host(); + } + + fn set_sample_rate(&self, sample_rate: f64) { + self.core.set_sample_rate(sample_rate); + } + + fn notify_gui_closed(&self) { + self.core.request_gui_closed(); + } + + fn on_param_set(&self, param_index: usize) { + if param_index == ParamId::Channels.as_index() { + self.sync_channels_from_params(); + self.core.request_audio_ports_rescan(); + self.core.request_latency_changed(); + } else if matches!( + ParamId::from_raw(param_index as u32), + Some(ParamId::Left | ParamId::Right | ParamId::Link) + ) { + self.core.request_latency_changed(); + } + } +} + +impl ParamHost for SharedState { + type Param = ParamId; + + fn params(&self) -> &crate::common::param_store::ParamStore { + &self.core.params + } +} + +impl crate::common::SharedStateExt for SharedState { + fn params_get(&self, id: ParamId) -> f64 { + self.core.params_get(id) + } + + fn set_gesture_active(&self, id: ParamId, active: bool) { + self.core.set_gesture_active(id, active); + } + + fn is_gesture_active(&self, id: ParamId) -> bool { + self.core.is_gesture_active(id) + } + + fn set_param_from_host(&self, id: ParamId, value: f64) { + self.core.set_param_from_host(id, value); + self.handle_param_change(id); + } + + fn take_pending_param_notifications(&self) -> u64 { + self.core.take_pending_param_notifications() + } + + fn requeue_pending_param_notifications(&self, bits: u64) { + self.core.requeue_pending_param_notifications(bits); + } + + fn take_pending_gesture_begin(&self) -> u64 { + self.core.take_pending_gesture_begin() + } + + fn requeue_pending_gesture_begin(&self, bits: u64) { + self.core.requeue_pending_gesture_begin(bits); + } + + fn take_pending_gesture_end(&self) -> u64 { + self.core.take_pending_gesture_end() + } + + fn requeue_pending_gesture_end(&self, bits: u64) { + self.core.requeue_pending_gesture_end(bits); + } +} + +crate::impl_param_presets!(SharedState, ParamId, "lag", "maolan-lag-preset"); + +impl SharedState { + pub fn bump_params_version(&self) {} + + pub fn channels(&self) -> u32 { + self.channels.load(Ordering::Acquire) + } + + fn sync_channels_from_params(&self) { + let channels = self.params.get(ParamId::Channels).round() as u32; + self.channels.store(channels.clamp(1, 2), Ordering::Release); + } + + pub fn set_param_outbound_only(&self, id: ParamId, value: f64) { + self.core.set_param_outbound_only(id, value); + self.handle_param_change(id); + } + + fn handle_param_change(&self, id: ParamId) { + if id == ParamId::Channels { + self.sync_channels_from_params(); + self.core.request_audio_ports_rescan(); + } + self.core.request_latency_changed(); + } + + pub fn delays_samples(&self) -> [usize; 2] { + let left = self.params.get(ParamId::Left).round() as usize; + let right = if self.channels() == 2 && !self.params.get_bool(ParamId::Link) { + self.params.get(ParamId::Right).round() as usize + } else { + left + }; + [left, right] + } + + pub fn latency_samples(&self) -> u32 { + self.delays_samples().into_iter().max().unwrap_or(0) as u32 + } +} + +impl ParamSpec for ParamId { + fn param_defs() -> &'static [crate::common::clap_harness::ParamDef] { + &PARAMS + } + + fn param_text(id: Self, value: f64) -> String { + param_text(id, value) + } + + fn parse_param_text(id: Self, text: &str) -> Option { + parse_param_text(id, text) + } +} + +fn param_text(id: ParamId, value: f64) -> String { + match id { + ParamId::Left | ParamId::Right => format!("{value:.0} samples"), + ParamId::Link => { + if value >= 0.5 { + "Linked".to_string() + } else { + "Unlinked".to_string() + } + } + ParamId::Channels => { + if value.round() as u32 >= 2 { + "Stereo".to_string() + } else { + "Mono".to_string() + } + } + } +} + +fn parse_param_text(id: ParamId, text: &str) -> Option { + let text = text.trim(); + match id { + ParamId::Left | ParamId::Right => text + .trim_end_matches("samples") + .trim_end_matches("sample") + .trim() + .parse() + .ok(), + ParamId::Link => match text.to_ascii_lowercase().as_str() { + "linked" | "on" | "1" => Some(1.0), + "unlinked" | "off" | "0" => Some(0.0), + _ => text.parse().ok(), + }, + ParamId::Channels => match text.to_ascii_lowercase().as_str() { + "mono" | "1" => Some(1.0), + "stereo" | "2" => Some(2.0), + _ => text.parse().ok(), + }, + } +} + +struct AudioProcessor { + dsp: Lag, + temp_left: Vec, + temp_right: Vec, +} + +impl AudioProcessor { + fn new(max_frames: u32) -> Self { + Self { + dsp: Lag::default(), + temp_left: vec![0.0; max_frames as usize], + temp_right: vec![0.0; max_frames as usize], + } + } + + fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { + apply_param_events(shared, &process.in_events(), sanitize_param_value); + { + let mut out_events = process.out_events(); + emit_pending_param_events_to_host(shared, &mut out_events); + } + + let frames = process.frames_count() as usize; + if self.temp_left.len() < frames { + self.temp_left.resize(frames, 0.0); + self.temp_right.resize(frames, 0.0); + } + let delays = shared.delays_samples(); + let inputs_count = process.audio_inputs_count(); + let outputs_count = process.audio_outputs_count(); + + if inputs_count >= 2 && outputs_count >= 2 { + let input_l = process.audio_inputs(0); + let input_r = process.audio_inputs(1); + self.temp_left[..frames].copy_from_slice(input_l.data32(0)); + self.temp_right[..frames].copy_from_slice(input_r.data32(0)); + self.dsp.process_stereo( + &mut self.temp_left[..frames], + &mut self.temp_right[..frames], + delays, + ); + + let mut output_l = process.audio_outputs(0); + output_l.data32(0)[..frames].copy_from_slice(&self.temp_left[..frames]); + let mut output_r = process.audio_outputs(1); + output_r.data32(0)[..frames].copy_from_slice(&self.temp_right[..frames]); + } else if inputs_count >= 1 && outputs_count >= 1 { + let input = process.audio_inputs(0); + self.temp_left[..frames].copy_from_slice(input.data32(0)); + self.dsp + .process_mono(&mut self.temp_left[..frames], delays[0]); + let mut output = process.audio_outputs(0); + output.data32(0)[..frames].copy_from_slice(&self.temp_left[..frames]); + } + + CLAP_PROCESS_CONTINUE + } +} + +impl Processor for AudioProcessor { + fn new( + _sample_rate: f64, + max_frames: u32, + _bus_data: Option, + ) -> Self { + AudioProcessor::new(max_frames) + } + + fn reset(&mut self) { + self.dsp.reset(); + } + + fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { + AudioProcessor::process(self, shared, process) + } +} + +impl StateHooks for PluginState { + fn save(shared: &SharedState) -> Option> { + PluginState::from_runtime(&shared.params) + .to_bytes(STATE_HEADER_PREFIX) + .ok() + } + + fn load(shared: &SharedState, bytes: &[u8]) -> bool { + let Ok(state) = PluginState::from_bytes(bytes, STATE_HEADER_PREFIX) else { + return false; + }; + state.apply(&shared.params); + shared.sync_channels_from_params(); + shared.core.request_audio_ports_rescan(); + shared.core.request_latency_changed(); + true + } +} + +unsafe extern "C-unwind" fn ext_audio_ports_count( + plugin: *const clap_plugin, + _is_input: bool, +) -> u32 { + if plugin.is_null() { + return 0; + } + let instance = unsafe { + crate::common::clap_harness::instance::(plugin) + }; + instance.shared.channels() +} + +unsafe extern "C-unwind" fn ext_audio_ports_get( + plugin: *const clap_plugin, + index: u32, + is_input: bool, + info: *mut maolan_clap::ffi::clap_audio_port_info, +) -> bool { + if plugin.is_null() || info.is_null() { + return false; + } + let instance = unsafe { + crate::common::clap_harness::instance::(plugin) + }; + let channels = instance.shared.channels(); + if index >= channels { + return false; + } + let info = unsafe { &mut *info }; + info.id = index; + info.flags = maolan_clap::ffi::CLAP_AUDIO_PORT_IS_MAIN; + info.channel_count = 1; + info.port_type = maolan_clap::ffi::CLAP_PORT_MONO.as_ptr(); + info.in_place_pair = maolan_clap::ffi::CLAP_INVALID_ID; + let name = match (is_input, channels, index) { + (true, 2, 0) => "Left input", + (true, 2, 1) => "Right input", + (true, 1, 0) => "Input", + (false, 2, 0) => "Left output", + (false, 2, 1) => "Right output", + (false, 1, 0) => "Output", + _ => "", + }; + crate::common::copy_str_to_array(name, &mut info.name); + true +} + +static AUDIO_PORTS_EXT: maolan_clap::ffi::clap_plugin_audio_ports = + maolan_clap::ffi::clap_plugin_audio_ports { + count: Some(ext_audio_ports_count), + get: Some(ext_audio_ports_get), + }; + +unsafe extern "C-unwind" fn ext_latency_get(plugin: *const clap_plugin) -> u32 { + if plugin.is_null() { + return 0; + } + let instance = unsafe { + crate::common::clap_harness::instance::(plugin) + }; + instance.shared.latency_samples() +} + +static LATENCY_EXT: maolan_clap::ffi::clap_plugin_latency = maolan_clap::ffi::clap_plugin_latency { + get: Some(ext_latency_get), +}; + +clap_params_ext!(SharedState, AudioProcessor, GuiBridge); +clap_state_ext!(SharedState, AudioProcessor, GuiBridge, PluginState); +clap_tail_ext!(SharedState, AudioProcessor, GuiBridge, 0); +clap_gui_ext!(SharedState, AudioProcessor, GuiBridge); + +unsafe extern "C-unwind" fn plugin_get_extension( + plugin: *const clap_plugin, + id: *const c_char, +) -> *const c_void { + if plugin.is_null() || id.is_null() { + return std::ptr::null(); + } + let id = unsafe { CStr::from_ptr(id) }; + if id == CLAP_EXT_AUDIO_PORTS { + &raw const AUDIO_PORTS_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_PARAMS { + &raw const PARAMS_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_STATE { + &raw const STATE_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_LATENCY { + &raw const LATENCY_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_TAIL { + &raw const TAIL_EXT as *const _ as *const c_void + } else if id == CLAP_EXT_GUI { + &raw const GUI_EXT as *const _ as *const c_void + } else { + std::ptr::null() + } +} + +const PORTS: PortConfig = PortConfig { + inputs: mono_pair!("Left", "Right"), + outputs: mono_pair!("Left", "Right"), +}; + +clap_create_fn!(SharedState, AudioProcessor, GuiBridge, PORTS); + +#[cfg(test)] +mod tests { + use super::*; + use crate::common::SharedStateExt; + + #[test] + fn parameter_text_roundtrips() { + for id in ParamId::all() { + let value = PARAMS[id.as_index()].default; + let text = param_text(id, value); + assert_eq!(parse_param_text(id, &text), Some(value)); + } + } + + #[test] + fn channels_param_updates_audio_port_count() { + let shared = SharedState::default(); + assert_eq!(shared.channels(), 2); + shared.set_param_outbound_only(ParamId::Channels, 1.0); + assert_eq!(shared.channels(), 1); + shared.set_param_from_host(ParamId::Channels, 2.0); + assert_eq!(shared.channels(), 2); + } + + #[test] + fn unlinked_stereo_latency_is_the_longer_channel_delay() { + let shared = SharedState::default(); + shared.set_param_outbound_only(ParamId::Left, 12.0); + shared.set_param_outbound_only(ParamId::Right, 30.0); + assert_eq!(shared.delays_samples(), [12, 30]); + assert_eq!(shared.latency_samples(), 30); + } + + #[test] + fn linked_stereo_uses_left_delay_for_both_channels() { + let shared = SharedState::default(); + shared.set_param_outbound_only(ParamId::Left, 12.0); + shared.set_param_outbound_only(ParamId::Right, 30.0); + shared.set_param_outbound_only(ParamId::Link, 1.0); + assert_eq!(shared.delays_samples(), [12, 12]); + assert_eq!(shared.latency_samples(), 12); + } + + #[test] + fn mono_ignores_right_delay() { + let shared = SharedState::default(); + shared.set_param_outbound_only(ParamId::Left, 12.0); + shared.set_param_outbound_only(ParamId::Right, 30.0); + shared.set_param_outbound_only(ParamId::Channels, 1.0); + assert_eq!(shared.delays_samples(), [12, 12]); + assert_eq!(shared.latency_samples(), 12); + } + + #[test] + fn state_roundtrip_preserves_parameters() { + let shared = SharedState::default(); + shared.set_param_outbound_only(ParamId::Left, 24.0); + shared.set_param_outbound_only(ParamId::Right, 48.0); + shared.set_param_outbound_only(ParamId::Link, 1.0); + shared.set_param_outbound_only(ParamId::Channels, 1.0); + let bytes = PluginState::from_runtime(&shared.params) + .to_bytes(STATE_HEADER_PREFIX) + .expect("state should save"); + + let restored = SharedState::default(); + PluginState::from_bytes(&bytes, STATE_HEADER_PREFIX) + .expect("state should load") + .apply(&restored.params); + restored.sync_channels_from_params(); + assert_eq!(restored.params.get(ParamId::Left), 24.0); + assert_eq!(restored.params.get(ParamId::Right), 48.0); + assert!(restored.params.get_bool(ParamId::Link)); + assert_eq!(restored.channels(), 1); + } +} diff --git a/src/lag/state.rs b/src/lag/state.rs new file mode 100644 index 0000000..46574a5 --- /dev/null +++ b/src/lag/state.rs @@ -0,0 +1,5 @@ +use crate::lag::params::ParamId; + +pub type PluginState = crate::common::json_state::JsonParamState; + +pub const STATE_HEADER_PREFIX: &str = "maolan-lag-state-v"; diff --git a/src/lib.rs b/src/lib.rs index aa447f8..d391d69 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,7 +22,9 @@ pub mod eq; pub mod flanger; pub mod formant; pub mod gate; +pub mod invert; pub mod kick; +pub mod lag; pub mod limiter; pub mod modeler; pub mod phaser; @@ -47,7 +49,7 @@ struct PluginApi { create: CreateFn, } -static PLUGINS: [PluginApi; 25] = [ +static PLUGINS: [PluginApi; 27] = [ PluginApi { descriptor: eq::clap_descriptor_ptr, create: eq::clap_create_plugin, @@ -60,6 +62,14 @@ static PLUGINS: [PluginApi; 25] = [ descriptor: gate::clap_descriptor_ptr, create: gate::clap_create_plugin, }, + PluginApi { + descriptor: invert::clap_descriptor_ptr, + create: invert::clap_create_plugin, + }, + PluginApi { + descriptor: lag::clap_descriptor_ptr, + create: lag::clap_create_plugin, + }, PluginApi { descriptor: limiter::clap_descriptor_ptr, create: limiter::clap_create_plugin, @@ -235,7 +245,7 @@ mod tests { #[test] fn factory_exports_unique_descriptors_including_new_effects() { - assert_eq!(unsafe { factory_get_plugin_count(null()) }, 25); + assert_eq!(unsafe { factory_get_plugin_count(null()) }, 27); let mut ids = HashSet::new(); for index in 0..PLUGINS.len() as u32 { let descriptor = unsafe { factory_get_plugin_descriptor(null(), index) }; @@ -248,5 +258,8 @@ mod tests { } assert!(ids.contains("rs.maolan.transient")); assert!(ids.contains("rs.maolan.bitcrusher")); + assert!(ids.contains("rs.maolan.invert")); + assert!(ids.contains("rs.maolan.lag")); + assert!(ids.contains("rs.maolan.transient")); } } diff --git a/src/limiter/plugin.rs b/src/limiter/plugin.rs index bbda6ee..1b2570a 100644 --- a/src/limiter/plugin.rs +++ b/src/limiter/plugin.rs @@ -33,7 +33,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.limiter\0"; const PLUGIN_NAME: &[u8] = b"Maolan Limiter\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Maolan lookahead peak limiter\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/modeler/plugin.rs b/src/modeler/plugin.rs index 6f54627..55e86f4 100644 --- a/src/modeler/plugin.rs +++ b/src/modeler/plugin.rs @@ -51,7 +51,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.modeler\0"; const PLUGIN_NAME: &[u8] = b"Maolan Modeler\0"; const PLUGIN_VENDOR: &[u8] = b"maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Rust CLAP Neural Amp Modeler\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_DISTORTION: *const c_char = CLAP_PLUGIN_FEATURE_DISTORTION.as_ptr(); diff --git a/src/phaser/gui.rs b/src/phaser/gui.rs index 0423928..68fa6aa 100644 --- a/src/phaser/gui.rs +++ b/src/phaser/gui.rs @@ -10,7 +10,7 @@ use maolan_clap::ffi::CLAP_WINDOW_API_X11; use maolan_baseview::iced::{ Alignment, Element, Length, Task, Theme, alignment::{Horizontal, Vertical}, - widget::{column, container, row, text, toggler}, + widget::{column, container, row, text}, }; #[cfg(any( target_os = "windows", @@ -22,6 +22,7 @@ use raw_window_handle::RawWindowHandle; use raw_window_handle::{HandleError, HasWindowHandle, WindowHandle}; use maolan_widgets::knob::Knob; +use maolan_widgets::multi_toggler::horizontal_multi_toggler; use crate::{ common::preset::{self, PresetProvider, PresetUi}, @@ -190,13 +191,13 @@ fn view(state: &State) -> Element<'_, Message> { fn delay_switch(state: &State) -> Element<'_, Message> { let enabled = state.shared.params.get(ParamId::FeedbackDelayOn) >= 0.5; - let value_text = if enabled { "On" } else { "Off" }; - container( column![ text("Delay").size(11), - toggler(enabled).on_toggle(|v| Message::BoolParamChanged(ParamId::FeedbackDelayOn, v)), - text(value_text).size(10), + horizontal_multi_toggler(["Off", "On"], usize::from(enabled), |index| { + Message::BoolParamChanged(ParamId::FeedbackDelayOn, index == 1) + }) + .label_extent(32.0), ] .spacing(7) .align_x(Alignment::Center), diff --git a/src/phaser/plugin.rs b/src/phaser/plugin.rs index 7bd7c23..2a89c16 100644 --- a/src/phaser/plugin.rs +++ b/src/phaser/plugin.rs @@ -29,7 +29,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.phaser\0"; const PLUGIN_NAME: &[u8] = b"Maolan Phaser\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Stereo phaser based on Mire Phaser\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/random/plugin.rs b/src/random/plugin.rs index ff5de69..19885b5 100644 --- a/src/random/plugin.rs +++ b/src/random/plugin.rs @@ -36,7 +36,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.random\0"; const PLUGIN_NAME: &[u8] = b"Maolan Random\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Random pitches for singing practice\0"; const FEATURE_INSTRUMENT: *const c_char = CLAP_PLUGIN_FEATURE_INSTRUMENT.as_ptr(); diff --git a/src/reverb/plugin.rs b/src/reverb/plugin.rs index 0f57d98..4acf151 100644 --- a/src/reverb/plugin.rs +++ b/src/reverb/plugin.rs @@ -36,7 +36,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.reverb\0"; const PLUGIN_NAME: &[u8] = b"Maolan Reverb\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Modulated feedback-delay reverb with 22 modes\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr(); diff --git a/src/sampler/plugin.rs b/src/sampler/plugin.rs index 5767aba..fca0a40 100644 --- a/src/sampler/plugin.rs +++ b/src/sampler/plugin.rs @@ -69,7 +69,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.sampler\0"; const PLUGIN_NAME: &[u8] = b"Maolan Sampler\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Polyphonic sample player\0"; /// Process-wide counter handing out unique instance ids for bundle naming. diff --git a/src/saturator/plugin.rs b/src/saturator/plugin.rs index a9fb7eb..c45a9af 100644 --- a/src/saturator/plugin.rs +++ b/src/saturator/plugin.rs @@ -30,7 +30,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.saturator\0"; const PLUGIN_NAME: &[u8] = b"Maolan Saturator\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Rust CLAP Saturator based on Saturator\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/stereo/gui.rs b/src/stereo/gui.rs index 00368ce..70bc4f9 100644 --- a/src/stereo/gui.rs +++ b/src/stereo/gui.rs @@ -4,7 +4,7 @@ use maolan_baseview::iced::{ Alignment, Color, Element, Length, Point, Rectangle, Size, Task, Theme, alignment::{Horizontal, Vertical}, mouse::Cursor, - widget::{canvas, checkbox, column, container, row, scrollable, text, toggler}, + widget::{canvas, checkbox, column, container, row, scrollable, text}, }; #[cfg(target_os = "macos")] use maolan_clap::ffi::CLAP_WINDOW_API_COCOA; @@ -210,9 +210,11 @@ fn view(state: &State) -> Element<'_, Message> { controls = controls.push( row![ text("Gain").size(14), - text("Off").size(13), - toggler(state.shared.gain_on()).on_toggle(Message::ToggleGain), - text("On").size(13), + horizontal_multi_toggler( + ["Off", "On"], + usize::from(state.shared.gain_on()), + |index| { Message::ToggleGain(index == 1) } + ), ] .spacing(6) .align_y(Alignment::Center), @@ -267,9 +269,11 @@ fn view(state: &State) -> Element<'_, Message> { controls = controls.push( row![ text("Delay").size(14), - text("Off").size(13), - toggler(state.shared.delay_on()).on_toggle(Message::ToggleDelay), - text("On").size(13), + horizontal_multi_toggler( + ["Off", "On"], + usize::from(state.shared.delay_on()), + |index| Message::ToggleDelay(index == 1), + ), ] .spacing(6) .align_y(Alignment::Center), @@ -287,9 +291,11 @@ fn view(state: &State) -> Element<'_, Message> { controls = controls.push( row![ text("Character").size(14), - text("Off").size(13), - toggler(state.shared.character_on()).on_toggle(Message::ToggleCharacter), - text("On").size(13), + horizontal_multi_toggler( + ["Off", "On"], + usize::from(state.shared.character_on()), + |index| Message::ToggleCharacter(index == 1), + ), ] .spacing(6) .align_y(Alignment::Center), diff --git a/src/stereo/plugin.rs b/src/stereo/plugin.rs index 7113307..fcf5203 100644 --- a/src/stereo/plugin.rs +++ b/src/stereo/plugin.rs @@ -33,7 +33,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.stereo\0"; const PLUGIN_NAME: &[u8] = b"Maolan Stereo\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Multiband stereo width processor with gain, delay and character sections\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); diff --git a/src/synth/plugin.rs b/src/synth/plugin.rs index be3ac19..073ed1b 100644 --- a/src/synth/plugin.rs +++ b/src/synth/plugin.rs @@ -62,7 +62,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.synth\0"; const PLUGIN_NAME: &[u8] = b"Maolan Synth\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Polyphonic synthesizer inspired by Surge XT\0"; const GUI_AUDIO_PARAM_INTERVAL_NS: u64 = 16_666_667; diff --git a/src/transient/dsp.rs b/src/transient/dsp.rs index 9f3cc73..c9190bf 100644 --- a/src/transient/dsp.rs +++ b/src/transient/dsp.rs @@ -1,32 +1,278 @@ +pub const MAX_BANDS: usize = 4; +const MAX_SPLITS: usize = MAX_BANDS - 1; + +#[derive(Debug, Clone, Copy)] +pub struct BandParams { + pub on: bool, + pub range_db: f32, + pub sensitivity: f32, +} + +impl Default for BandParams { + fn default() -> Self { + Self { + on: true, + range_db: -6.0, + sensitivity: 0.0, + } + } +} + #[derive(Debug, Clone, Copy)] pub struct TransientParams { - pub attack_db: f32, - pub sustain_db: f32, - pub attack_ms: f32, + pub band_count: usize, + pub split_hz: [f32; MAX_SPLITS], + pub bands: [BandParams; MAX_BANDS], + pub master_range_db: f32, + pub master_sensitivity: f32, + pub duration_ms: f32, pub release_ms: f32, - pub dry_wet: f32, pub output_gain_db: f32, } -#[derive(Debug, Clone)] -pub struct TransientShaper { +impl Default for TransientParams { + fn default() -> Self { + Self { + band_count: 1, + split_hz: [120.0, 1000.0, 6000.0], + bands: [BandParams::default(); MAX_BANDS], + master_range_db: 0.0, + master_sensitivity: 0.0, + duration_ms: 5.0, + release_ms: 20.0, + output_gain_db: 0.0, + } + } +} + +#[derive(Debug, Clone, Copy, Default)] +struct Biquad { + b0: f32, + b1: f32, + b2: f32, + a1: f32, + a2: f32, + x1: f32, + x2: f32, + y1: f32, + y2: f32, +} + +impl Biquad { + fn set_lowpass(&mut self, cutoff_hz: f32, sample_rate: f32, q: f32) { + let (b0, b1, b2, a0, a1, a2) = lowpass_coefficients(cutoff_hz, sample_rate, q); + self.set_coefficients(b0, b1, b2, a0, a1, a2); + } + + fn set_highpass(&mut self, cutoff_hz: f32, sample_rate: f32, q: f32) { + let w0 = 2.0 * std::f32::consts::PI * cutoff_hz / sample_rate; + let cw = w0.cos(); + let alpha = w0.sin() / (2.0 * q.max(1.0e-6)); + self.set_coefficients( + (1.0 + cw) * 0.5, + -(1.0 + cw), + (1.0 + cw) * 0.5, + 1.0 + alpha, + -2.0 * cw, + 1.0 - alpha, + ); + } + + fn set_coefficients(&mut self, b0: f32, b1: f32, b2: f32, a0: f32, a1: f32, a2: f32) { + self.b0 = b0 / a0; + self.b1 = b1 / a0; + self.b2 = b2 / a0; + self.a1 = a1 / a0; + self.a2 = a2 / a0; + } + + fn process(&mut self, input: f32) -> f32 { + let output = self.b0 * input + self.b1 * self.x1 + self.b2 * self.x2 + - self.a1 * self.y1 + - self.a2 * self.y2; + self.x2 = self.x1; + self.x1 = input; + self.y2 = self.y1; + self.y1 = output; + output + } + + fn reset(&mut self) { + *self = Self { + b0: self.b0, + b1: self.b1, + b2: self.b2, + a1: self.a1, + a2: self.a2, + ..Self::default() + }; + } +} + +fn lowpass_coefficients( + cutoff_hz: f32, sample_rate: f32, + q: f32, +) -> (f32, f32, f32, f32, f32, f32) { + let w0 = 2.0 * std::f32::consts::PI * cutoff_hz / sample_rate; + let cw = w0.cos(); + let alpha = w0.sin() / (2.0 * q.max(1.0e-6)); + ( + (1.0 - cw) * 0.5, + 1.0 - cw, + (1.0 - cw) * 0.5, + 1.0 + alpha, + -2.0 * cw, + 1.0 - alpha, + ) +} + +#[derive(Debug, Clone, Copy, Default)] +struct LR4Split { + low1: Biquad, + low2: Biquad, + high1: Biquad, + high2: Biquad, +} + +impl LR4Split { + fn set_cutoff(&mut self, cutoff_hz: f32, sample_rate: f32) { + let q = 1.0 / 2.0_f32.sqrt(); + self.low1.set_lowpass(cutoff_hz, sample_rate, q); + self.low2.set_lowpass(cutoff_hz, sample_rate, q); + self.high1.set_highpass(cutoff_hz, sample_rate, q); + self.high2.set_highpass(cutoff_hz, sample_rate, q); + } + + fn process(&mut self, input: f32) -> (f32, f32) { + let low = self.low2.process(self.low1.process(input)); + let high = self.high2.process(self.high1.process(input)); + (low, high) + } + + fn reset(&mut self) { + self.low1.reset(); + self.low2.reset(); + self.high1.reset(); + self.high2.reset(); + } +} + +#[derive(Debug, Clone, Default)] +struct StereoSplitBank { + left: [LR4Split; MAX_SPLITS], + right: [LR4Split; MAX_SPLITS], +} + +impl StereoSplitBank { + fn set_cutoffs(&mut self, split_hz: [f32; MAX_SPLITS], sample_rate: f32) { + for (index, cutoff) in split_hz.iter().copied().enumerate() { + self.left[index].set_cutoff(cutoff, sample_rate); + self.right[index].set_cutoff(cutoff, sample_rate); + } + } + + fn split( + &mut self, + left: f32, + right: f32, + bands: usize, + ) -> ([f32; MAX_BANDS], [f32; MAX_BANDS]) { + let mut out_left = [0.0; MAX_BANDS]; + let mut out_right = [0.0; MAX_BANDS]; + let mut remaining_left = left; + let mut remaining_right = right; + for split in 0..bands.saturating_sub(1) { + let (low_left, high_left) = self.left[split].process(remaining_left); + let (low_right, high_right) = self.right[split].process(remaining_right); + out_left[split] = low_left; + out_right[split] = low_right; + remaining_left = high_left; + remaining_right = high_right; + } + out_left[bands - 1] = remaining_left; + out_right[bands - 1] = remaining_right; + (out_left, out_right) + } + + fn reset(&mut self) { + for split in self.left.iter_mut().chain(self.right.iter_mut()) { + split.reset(); + } + } +} + +#[derive(Debug, Clone, Copy)] +struct DetectorCoefficients { + fast: f32, + slow: f32, + release: f32, +} + +#[derive(Debug, Clone, Copy, Default)] +struct BandTransient { fast_envelope: f32, slow_envelope: f32, + gain_db: f32, } -impl TransientShaper { +impl BandTransient { + fn reset(&mut self) { + *self = Self::default(); + } + + fn process( + &mut self, + level: f32, + band: BandParams, + master_range_db: f32, + master_sensitivity: f32, + coefficients: DetectorCoefficients, + ) -> f32 { + self.fast_envelope += coefficients.fast * (level - self.fast_envelope); + self.slow_envelope += coefficients.slow * (level - self.slow_envelope); + let velocity_db = + gain_to_db(self.fast_envelope.max(1.0e-8)) - gain_to_db(self.slow_envelope.max(1.0e-8)); + let sensitivity = (band.sensitivity + master_sensitivity).clamp(-90.0, 20.0); + let threshold_db = 10.0 - sensitivity; + let strength = ((velocity_db - threshold_db) / (24.0 - threshold_db)).clamp(0.0, 1.0); + let range_db = (band.range_db + master_range_db).clamp(-90.0, 20.0); + let target_db = if band.on { range_db * strength } else { 0.0 }; + let coefficient = if target_db == 0.0 { + coefficients.release + } else { + coefficients.fast + }; + self.gain_db += coefficient * (target_db - self.gain_db); + self.gain_db + } +} + +#[derive(Debug, Clone)] +pub struct MultibandTransient { + sample_rate: f32, + splitters: StereoSplitBank, + bands: [BandTransient; MAX_BANDS], +} + +impl MultibandTransient { pub fn new(sample_rate: f32) -> Self { Self { sample_rate: sample_rate.max(1.0), - fast_envelope: 0.0, - slow_envelope: 0.0, + splitters: StereoSplitBank::default(), + bands: [BandTransient::default(); MAX_BANDS], } } pub fn reset(&mut self) { - self.fast_envelope = 0.0; - self.slow_envelope = 0.0; + self.splitters.reset(); + for band in &mut self.bands { + band.reset(); + } + } + + pub fn band_gain_db(&self, band: usize) -> f32 { + self.bands.get(band).map_or(0.0, |band| band.gain_db) } pub fn process_stereo( @@ -35,42 +281,77 @@ impl TransientShaper { right: &mut [f32], params: &TransientParams, ) { - let fast_coefficient = time_coefficient(params.attack_ms, self.sample_rate); - let slow_coefficient = time_coefficient(params.release_ms, self.sample_rate); + let mut split_hz = params.split_hz; + split_hz.sort_by(|a, b| a.total_cmp(b)); + for cutoff in &mut split_hz { + *cutoff = cutoff.clamp(20.0, self.sample_rate * 0.45); + } + self.splitters.set_cutoffs(split_hz, self.sample_rate); + let band_count = params.band_count.clamp(1, MAX_BANDS); + let coefficients = DetectorCoefficients { + fast: time_coefficient(params.duration_ms, self.sample_rate), + slow: time_coefficient((params.duration_ms * 4.0).min(500.0), self.sample_rate), + release: time_coefficient(params.release_ms, self.sample_rate), + }; let output_gain = db_to_gain(params.output_gain_db); - let mix = params.dry_wet.clamp(0.0, 1.0); for (left, right) in left.iter_mut().zip(right.iter_mut()) { - let dry_left = *left; - let dry_right = *right; - let level = dry_left.abs().max(dry_right.abs()); - self.fast_envelope += fast_coefficient * (level - self.fast_envelope); - self.slow_envelope += slow_coefficient * (level - self.slow_envelope); - - let fast_db = gain_to_db(self.fast_envelope.max(1.0e-6)); - let slow_db = gain_to_db(self.slow_envelope.max(1.0e-6)); - let transient_db = fast_db - slow_db; - let strength = (transient_db.abs() / 12.0).clamp(0.0, 1.0); - let gain_db = if transient_db >= 0.0 { - params.attack_db * strength - } else { - params.sustain_db * strength - }; - let gain = db_to_gain(gain_db); - - *left = (dry_left * gain * mix + dry_left * (1.0 - mix)) * output_gain; - *right = (dry_right * gain * mix + dry_right * (1.0 - mix)) * output_gain; + let (band_left, band_right) = self.splitters.split(*left, *right, band_count); + let mut output_left = 0.0; + let mut output_right = 0.0; + for band in 0..band_count { + let level = band_left[band].abs().max(band_right[band].abs()); + let gain_db = self.bands[band].process( + level, + params.bands[band], + params.master_range_db, + params.master_sensitivity, + coefficients, + ); + let gain = db_to_gain(gain_db); + output_left += band_left[band] * gain; + output_right += band_right[band] * gain; + } + *left = output_left * output_gain; + *right = output_right * output_gain; + } + for band in self.bands.iter_mut().skip(band_count) { + band.reset(); } } pub fn process_mono(&mut self, buffer: &mut [f32], params: &TransientParams) { + let mut split_hz = params.split_hz; + split_hz.sort_by(|a, b| a.total_cmp(b)); + for cutoff in &mut split_hz { + *cutoff = cutoff.clamp(20.0, self.sample_rate * 0.45); + } + self.splitters.set_cutoffs(split_hz, self.sample_rate); + let band_count = params.band_count.clamp(1, MAX_BANDS); + let coefficients = DetectorCoefficients { + fast: time_coefficient(params.duration_ms, self.sample_rate), + slow: time_coefficient((params.duration_ms * 4.0).min(500.0), self.sample_rate), + release: time_coefficient(params.release_ms, self.sample_rate), + }; + let output_gain = db_to_gain(params.output_gain_db); + for sample in buffer { - let mut right = *sample; - self.process_stereo( - std::slice::from_mut(sample), - std::slice::from_mut(&mut right), - params, - ); + let (band_left, _) = self.splitters.split(*sample, 0.0, band_count); + let mut output = 0.0; + for band in 0..band_count { + let gain_db = self.bands[band].process( + band_left[band].abs(), + params.bands[band], + params.master_range_db, + params.master_sensitivity, + coefficients, + ); + output += band_left[band] * db_to_gain(gain_db); + } + *sample = output * output_gain; + } + for band in self.bands.iter_mut().skip(band_count) { + band.reset(); } } } @@ -89,71 +370,93 @@ fn gain_to_db(gain: f32) -> f32 { #[cfg(test)] mod tests { - use super::{TransientParams, TransientShaper}; - - fn params() -> TransientParams { - TransientParams { - attack_db: 0.0, - sustain_db: 0.0, - attack_ms: 1.0, - release_ms: 100.0, - dry_wet: 1.0, - output_gain_db: 0.0, - } - } + use super::{MAX_BANDS, MultibandTransient, TransientParams}; #[test] fn neutral_settings_preserve_audio() { - let mut shaper = TransientShaper::new(48_000.0); let original = [0.0, 0.5, -0.25, 0.1]; let mut left = original; let mut right = original; - shaper.process_stereo(&mut left, &mut right, ¶ms()); + let mut params = TransientParams::default(); + params.bands[0].range_db = 0.0; + MultibandTransient::new(48_000.0).process_stereo(&mut left, &mut right, ¶ms); assert_eq!(left, original); assert_eq!(right, original); } #[test] - fn positive_attack_boosts_transient() { - let mut shaper = TransientShaper::new(48_000.0); - let mut params = params(); - params.attack_db = 12.0; - let mut left = [1.0; 16]; - let mut right = [1.0; 16]; + fn positive_range_boosts_detected_attack() { + let mut params = TransientParams::default(); + params.bands[0].range_db = 12.0; + params.duration_ms = 0.1; + let mut left = [1.0; 32]; + let mut right = [1.0; 32]; + let mut shaper = MultibandTransient::new(48_000.0); shaper.process_stereo(&mut left, &mut right, ¶ms); assert!(left[0] > 1.0); assert!(right[0] > 1.0); } #[test] - fn negative_sustain_reduces_decay() { - let mut shaper = TransientShaper::new(1_000.0); - let mut params = params(); - params.sustain_db = -12.0; - let mut input = vec![1.0; 200]; - input.extend(std::iter::repeat_n(0.25, 100)); - let original = input.clone(); - let mut right = input.clone(); - shaper.process_stereo(&mut input, &mut right, ¶ms); + fn negative_range_attenuates_detected_attack() { + let mut params = TransientParams::default(); + params.bands[0].range_db = -12.0; + params.duration_ms = 0.1; + let mut buffer = [1.0; 32]; + MultibandTransient::new(48_000.0).process_mono(&mut buffer, ¶ms); + assert!(buffer[0] < 1.0); + assert!(buffer[0] > 0.0); + } + + #[test] + fn disabled_band_keeps_its_audio() { + let mut params = TransientParams::default(); + params.bands[0].range_db = 12.0; + params.bands[0].on = false; + let original = [1.0; 16]; + let mut buffer = original; + MultibandTransient::new(48_000.0).process_mono(&mut buffer, ¶ms); + assert_eq!(buffer, original); + } + + #[test] + fn master_range_adjusts_every_band() { + let params = TransientParams { + master_range_db: 12.0, + duration_ms: 0.1, + ..TransientParams::default() + }; + let mut buffer = [1.0; 16]; + MultibandTransient::new(48_000.0).process_mono(&mut buffer, ¶ms); + assert!(buffer[0] > 1.0); + } + + #[test] + fn four_band_neutral_processing_reconstructs_dc() { + let mut params = TransientParams { + band_count: MAX_BANDS, + ..TransientParams::default() + }; + for band in &mut params.bands { + band.range_db = 0.0; + } + let mut buffer = vec![1.0; 2048]; + MultibandTransient::new(48_000.0).process_mono(&mut buffer, ¶ms); assert!( - input[250] < original[250], - "processed {}, original {}", - input[250], - original[250] + (buffer[2047] - 1.0).abs() < 2.0e-4, + "reconstructed DC: {}", + buffer[2047] ); - assert!(right[250] < original[250]); } #[test] - fn stereo_detector_is_linked() { - let mut shaper = TransientShaper::new(48_000.0); - let mut params = params(); - params.attack_db = 12.0; - let mut left = [0.25; 8]; - let mut right = [1.0; 8]; - shaper.process_stereo(&mut left, &mut right, ¶ms); - assert!(left[0] > 0.25); - assert!(right[0] > 1.0); - assert!((left[0] / 0.25 - right[0]).abs() < 1.0e-5); + fn reset_clears_detector_and_gain_state() { + let mut params = TransientParams::default(); + params.bands[0].range_db = 12.0; + let mut shaper = MultibandTransient::new(48_000.0); + shaper.process_mono(&mut [1.0; 16], ¶ms); + assert_ne!(shaper.band_gain_db(0), 0.0); + shaper.reset(); + assert_eq!(shaper.band_gain_db(0), 0.0); } } diff --git a/src/transient/gui.rs b/src/transient/gui.rs index e0bcd70..18b3a95 100644 --- a/src/transient/gui.rs +++ b/src/transient/gui.rs @@ -1,9 +1,14 @@ -use std::{ffi::CStr, sync::Arc}; +use std::{ + ffi::CStr, + sync::{Arc, atomic::Ordering}, + thread, + time::Duration, +}; use maolan_baseview::iced::{ - Alignment, Element, Length, Task, Theme, + Alignment, Color, Element, Length, Task, Theme, alignment::{Horizontal, Vertical}, - widget::{column, container, row}, + widget::{column, container, row, text}, }; #[cfg(target_os = "macos")] use maolan_clap::ffi::CLAP_WINDOW_API_COCOA; @@ -12,25 +17,30 @@ use maolan_clap::ffi::CLAP_WINDOW_API_WIN32; #[cfg(any(target_os = "linux", target_os = "freebsd"))] use maolan_clap::ffi::CLAP_WINDOW_API_X11; use maolan_widgets::knob::Knob; -#[cfg(any( - target_os = "windows", - target_os = "macos", - target_os = "linux", - target_os = "freebsd" -))] +use maolan_widgets::multi_toggler::horizontal_multi_toggler; +use maolan_widgets::vertical_slider::{VerticalSlider, vertical_slider}; +use maolan_widgets::vertical_ticks::vertical_ticks; +use maolan_widgets::vu_meter::vu_meter; use raw_window_handle::RawWindowHandle; use raw_window_handle::{HandleError, HasWindowHandle, WindowHandle}; use crate::{ - common::preset::{self, PresetProvider, PresetUi}, + common::{ + preset::{self, PresetProvider, PresetUi}, + spectrum::{ + DEFAULT_SPECTRUM_BINS, SPECTRUM_FLOOR_DB, SpectralAnalyzerWidget, SpectrumMarker, + SpectrumThresholdCurve, + }, + }, transient::{ + dsp::MAX_BANDS, params::{PARAMS, ParamId}, plugin::SharedState, }, }; -pub const EDITOR_WIDTH: u32 = 640; -pub const EDITOR_HEIGHT: u32 = 210; +pub const EDITOR_WIDTH: u32 = 1024; +pub const EDITOR_HEIGHT: u32 = 620; pub fn preferred_api() -> &'static CStr { #[cfg(target_os = "windows")] @@ -90,6 +100,13 @@ impl HasWindowHandle for ParentWindowHandle { pub enum Message { SetParam(ParamId, f32), ReleaseParam(ParamId), + SetBandOn(usize, bool), + SelectBand(usize), + StartBandParam(usize, ParamId), + DragBandParam(usize, ParamId, f32), + ReleaseBandParam(ParamId), + CreateBand(f32), + UiTick, Preset(preset::Msg), } @@ -102,6 +119,8 @@ impl From for Message { struct State { shared: Arc, active_gestures: Vec, + spectrum_db: [[f32; DEFAULT_SPECTRUM_BINS]; 2], + selected_band: usize, preset_ui: PresetUi, } @@ -110,9 +129,20 @@ fn init(shared: Arc) -> (State, Task) { State { shared, active_gestures: vec![false; ParamId::COUNT], + spectrum_db: [[SPECTRUM_FLOOR_DB; DEFAULT_SPECTRUM_BINS]; 2], + selected_band: 0, preset_ui: PresetUi::new(SharedState::DIR_NAME), }, - Task::none(), + next_ui_tick_task(), + ) +} + +fn next_ui_tick_task() -> Task { + Task::perform( + async move { + thread::sleep(Duration::from_millis(33)); + }, + |_| Message::UiTick, ) } @@ -133,6 +163,60 @@ fn update(state: &mut State, message: Message) -> Task { state.shared.mark_gesture_end_pending(id); } } + Message::SetBandOn(band, on) => { + let id = ParamId::band_on(band); + state.shared.mark_gesture_begin_pending(id); + state + .shared + .set_param_outbound_only(id, if on { 1.0 } else { 0.0 }); + state.shared.mark_gesture_end_pending(id); + } + Message::SelectBand(band) => { + state.selected_band = band.min(active_band_count(&state.shared).saturating_sub(1)); + } + Message::StartBandParam(band, id) => { + state.selected_band = band.min(active_band_count(&state.shared).saturating_sub(1)); + begin_band_gesture(state, id); + } + Message::DragBandParam(band, id, delta) => { + state.selected_band = band.min(active_band_count(&state.shared).saturating_sub(1)); + begin_band_gesture(state, id); + let def = PARAMS[id.as_index()]; + let value = (state.shared.params.get(id) + f64::from(delta)).clamp(def.min, def.max); + state.shared.set_param_outbound_only(id, value); + } + Message::ReleaseBandParam(id) => { + let index = id.as_index(); + if state.active_gestures[index] { + state.active_gestures[index] = false; + state.shared.mark_gesture_end_pending(id); + } + } + Message::CreateBand(freq) => { + let count = active_band_count(&state.shared); + if count < MAX_BANDS { + let mut splits = active_splits(&state.shared); + splits.push(freq.clamp(20.0, 20_000.0)); + splits.sort_by(|a, b| a.total_cmp(b)); + for (index, split) in splits.iter().copied().enumerate() { + set_discrete(state, ParamId::split(index), f64::from(split)); + } + set_discrete(state, ParamId::BandCount, (count + 1) as f64); + state.selected_band = splits + .iter() + .position(|split| (*split - freq).abs() < 1.0) + .map(|index| index + 1) + .unwrap_or(count) + .min(MAX_BANDS - 1); + } + } + Message::UiTick => { + state.spectrum_db = state.shared.spectrum_db(); + state.selected_band = state + .selected_band + .min(active_band_count(&state.shared).saturating_sub(1)); + return next_ui_tick_task(); + } Message::Preset(msg) => { preset::update(&mut state.preset_ui, msg, state.shared.as_ref()); } @@ -140,44 +224,95 @@ fn update(state: &mut State, message: Message) -> Task { Task::none() } +fn begin_band_gesture(state: &mut State, id: ParamId) { + let index = id.as_index(); + if !state.active_gestures[index] { + state.active_gestures[index] = true; + state.shared.mark_gesture_begin_pending(id); + } +} + +fn set_discrete(state: &State, id: ParamId, value: f64) { + state.shared.mark_gesture_begin_pending(id); + state.shared.set_param_outbound_only(id, value); + state.shared.mark_gesture_end_pending(id); +} + fn view(state: &State) -> Element<'_, Message> { let p = |id: ParamId| state.shared.params.get(id) as f32; + let band_count = active_band_count(&state.shared); + let splits = active_splits(&state.shared); + let analyzer = SpectralAnalyzerWidget::new( + state.spectrum_db, + state.shared.channels.load(Ordering::Acquire) >= 2, + ) + .with_db_range(-90.0, 20.0) + .with_db_labels(false) + .with_threshold_curves(transient_curves( + &splits, + band_count, + state.shared.sample_rate() as f32, + std::array::from_fn(|band| p(ParamId::band_range(band))), + std::array::from_fn(|band| p(ParamId::band_sensitivity(band))), + state.selected_band, + )) + .with_spectrum_markers( + (0..band_count.saturating_sub(1)) + .map(|index| { + let id = ParamId::split(index); + SpectrumMarker::draggable( + splits[index], + move |freq| Message::SetParam(id, freq), + Message::ReleaseParam(id), + ) + }) + .collect(), + ) + .on_double_click(|freq, _db| Message::CreateBand(freq)) + .view_fill(); + + let channels = if state.shared.channels.load(Ordering::Acquire) >= 2 { + 2 + } else { + 1 + }; + let display_row = row![ + vu_meter(channels, state.shared.input_levels_db()), + vertical_ticks(), + analyzer, + vertical_ticks(), + gain_slider(ParamId::OutputGain, p(ParamId::OutputGain)), + vu_meter(channels, state.shared.output_levels_db()), + ] + .spacing(8) + .height(Length::Fill) + .align_y(Alignment::Center); + + let master = row![ + text("Master").size(16), + knob("Range", ParamId::MasterRange, p(ParamId::MasterRange)), + knob( + "Sensitivity", + ParamId::MasterSensitivity, + p(ParamId::MasterSensitivity), + ), + knob("Duration", ParamId::Duration, p(ParamId::Duration)), + knob("Release", ParamId::Release, p(ParamId::Release)), + ] + .spacing(12) + .align_y(Alignment::Center); + let content = column![ preset::bar(&state.preset_ui), - row![ - knob("Attack", ParamId::Attack, p(ParamId::Attack), "dB", 0.1), - knob("Sustain", ParamId::Sustain, p(ParamId::Sustain), "dB", 0.1), - knob("Mix", ParamId::DryWet, p(ParamId::DryWet), "%", 0.01), - knob( - "Attack Time", - ParamId::AttackTime, - p(ParamId::AttackTime), - "ms", - 0.1, - ), - knob( - "Release Time", - ParamId::ReleaseTime, - p(ParamId::ReleaseTime), - "ms", - 1.0, - ), - knob( - "Output", - ParamId::OutputGain, - p(ParamId::OutputGain), - "dB", - 0.1, - ), - ] - .spacing(12) - .align_y(Alignment::Center), + display_row, + band_strip(state), + master, ] - .spacing(24) + .spacing(12) .align_x(Alignment::Start); container(content) - .padding(24) + .padding(16) .width(Length::Fill) .height(Length::Fill) .align_x(Horizontal::Left) @@ -185,30 +320,268 @@ fn view(state: &State) -> Element<'_, Message> { .into() } -fn theme(_state: &State) -> Theme { - Theme::TokyoNight +fn active_band_count(shared: &SharedState) -> usize { + shared + .params + .get(ParamId::BandCount) + .round() + .clamp(1.0, MAX_BANDS as f64) as usize } -fn knob( - label: &'static str, - id: ParamId, - value: f32, - units: &'static str, - step: f32, -) -> Element<'static, Message> { +fn active_splits(shared: &SharedState) -> Vec { + let mut splits: Vec = (0..active_band_count(shared).saturating_sub(1)) + .map(|index| shared.params.get(ParamId::split(index)) as f32) + .collect(); + splits.sort_by(|a, b| a.total_cmp(b)); + splits +} + +fn band_strip(state: &State) -> Element<'_, Message> { + let band = state + .selected_band + .min(active_band_count(&state.shared).saturating_sub(1)); + let p = |id: ParamId| state.shared.params.get(id) as f32; + container( + row![ + horizontal_multi_toggler( + ["Off", "On"], + usize::from(state.shared.params.get_bool(ParamId::band_on(band))), + move |index| Message::SetBandOn(band, index == 1), + ) + .label_extent(40.0), + knob( + "Range", + ParamId::band_range(band), + p(ParamId::band_range(band)) + ), + knob( + "Sensitivity", + ParamId::band_sensitivity(band), + p(ParamId::band_sensitivity(band)), + ), + ] + .spacing(16) + .align_y(Alignment::Center), + ) + .padding(4) + .width(Length::Fill) + .into() +} + +fn transient_curves( + splits: &[f32], + band_count: usize, + sample_rate: f32, + ranges: [f32; MAX_BANDS], + sensitivities: [f32; MAX_BANDS], + selected_band: usize, +) -> Vec> { + let range_points = contour_points(splits, band_count, sample_rate, &ranges); + let sensitivity_points = contour_points(splits, band_count, sample_rate, &sensitivities); + vec![ + band_curve( + range_points, + splits, + band_count, + Color::from_rgba(1.0, 0.83, 0.10, 0.85), + ParamId::band_range, + selected_band, + ), + band_curve( + sensitivity_points, + splits, + band_count, + Color::from_rgba(0.18, 0.76, 0.95, 0.85), + ParamId::band_sensitivity, + selected_band, + ), + ] +} + +fn band_curve( + points: Vec<(f32, f32)>, + splits: &[f32], + band_count: usize, + color: Color, + param_for_band: fn(usize) -> ParamId, + selected_band: usize, +) -> SpectrumThresholdCurve { + let select_splits = splits.to_vec(); + let drag_splits = splits.to_vec(); + let release_splits = splits.to_vec(); + SpectrumThresholdCurve { + points, + selected: true, + color: Some(color), + selected_color: Some(color), + width: 1.0, + selected_width: 2.0, + selected_band: Some(selected_band.min(band_count - 1)), + band_splits: splits.to_vec(), + on_select: None, + on_select_at: Some(Arc::new(move |freq| { + Message::SelectBand(band_for_freq(freq, &select_splits).min(band_count - 1)) + })), + on_drag_db: None, + on_drag_db_at: Some(Arc::new(move |freq, delta| { + let band = band_for_freq(freq, &drag_splits).min(band_count - 1); + Message::DragBandParam(band, param_for_band(band), delta) + })), + on_double_click_at: None, + on_release: None, + on_release_at: Some(Arc::new(move |freq| { + let band = band_for_freq(freq, &release_splits).min(band_count - 1); + Message::ReleaseBandParam(param_for_band(band)) + })), + on_middle_select_at: None, + on_middle_drag_db_at: None, + on_middle_release_at: None, + on_right_select_at: None, + on_right_drag_db_at: None, + on_right_release_at: None, + } +} + +fn contour_points( + splits: &[f32], + band_count: usize, + sample_rate: f32, + values: &[f32; MAX_BANDS], +) -> Vec<(f32, f32)> { + const POINTS: usize = 192; + (0..POINTS) + .map(|point| { + let t = point as f32 / (POINTS - 1) as f32; + let freq = 20.0 * (1_000.0_f32).powf(t); + let value = blended_band_value(freq, splits, band_count, sample_rate, values); + (freq, value) + }) + .collect() +} + +fn blended_band_value( + freq: f32, + splits: &[f32], + band_count: usize, + sample_rate: f32, + values: &[f32; MAX_BANDS], +) -> f32 { + let mut weighted_sum = 0.0; + let mut total_weight = 0.0; + for (band, value) in values.iter().copied().enumerate().take(band_count) { + let weight = detector_band_magnitude(band, freq, splits, sample_rate).powi(2); + weighted_sum += value * weight; + total_weight += weight; + } + if total_weight > 1.0e-9 { + weighted_sum / total_weight + } else { + values[band_for_freq(freq, splits).min(band_count.saturating_sub(1))] + } +} + +fn band_for_freq(freq: f32, splits: &[f32]) -> usize { + splits.iter().take_while(|split| freq >= **split).count() +} + +fn detector_band_magnitude(band: usize, freq: f32, splits: &[f32], sample_rate: f32) -> f32 { + let mut response = 1.0; + for split in splits.iter().take(band) { + response *= lr4_highpass_magnitude(freq, *split, sample_rate); + } + if let Some(split) = splits.get(band) { + response *= lr4_lowpass_magnitude(freq, *split, sample_rate); + } + response +} + +fn lr4_lowpass_magnitude(freq: f32, cutoff: f32, sample_rate: f32) -> f32 { + let magnitude = BiquadCoeffs::new(cutoff, sample_rate, false).magnitude(freq, sample_rate); + magnitude * magnitude +} + +fn lr4_highpass_magnitude(freq: f32, cutoff: f32, sample_rate: f32) -> f32 { + let magnitude = BiquadCoeffs::new(cutoff, sample_rate, true).magnitude(freq, sample_rate); + magnitude * magnitude +} + +struct BiquadCoeffs { + b0: f32, + b1: f32, + b2: f32, + a1: f32, + a2: f32, +} + +impl BiquadCoeffs { + fn new(cutoff_hz: f32, sample_rate: f32, highpass: bool) -> Self { + let w0 = 2.0 * std::f32::consts::PI * cutoff_hz / sample_rate; + let cw = w0.cos(); + let alpha = w0.sin() / 2.0_f32.sqrt(); + let a0 = 1.0 + alpha; + let (b0, b1, b2) = if highpass { + ((1.0 + cw) * 0.5, -(1.0 + cw), (1.0 + cw) * 0.5) + } else { + ((1.0 - cw) * 0.5, 1.0 - cw, (1.0 - cw) * 0.5) + }; + Self { + b0: b0 / a0, + b1: b1 / a0, + b2: b2 / a0, + a1: -2.0 * cw / a0, + a2: (1.0 - alpha) / a0, + } + } + + fn magnitude(&self, freq: f32, sample_rate: f32) -> f32 { + let w = 2.0 * std::f32::consts::PI * freq / sample_rate; + let (sin_w, cos_w) = w.sin_cos(); + let (sin_2w, cos_2w) = (2.0 * w).sin_cos(); + let num_re = self.b0 + self.b1 * cos_w + self.b2 * cos_2w; + let num_im = -self.b1 * sin_w - self.b2 * sin_2w; + let den_re = 1.0 + self.a1 * cos_w + self.a2 * cos_2w; + let den_im = -self.a1 * sin_w - self.a2 * sin_2w; + (num_re * num_re + num_im * num_im).sqrt() + / (den_re * den_re + den_im * den_im).sqrt().max(1.0e-12) + } +} + +fn gain_slider(id: ParamId, value: f32) -> Element<'static, Message> { let def = PARAMS[id.as_index()]; - let value_text = match units { - "dB" | "ms" => format!("{value:.1} {units}"), - "%" => format!("{:.0}%", value * 100.0), - _ => format!("{value:.2}"), + vertical_slider( + VerticalSlider { + value, + range: def.min as f32..=def.max as f32, + default: def.default as f32, + step: 0.1, + value_text: format!("{value:.1} dB"), + }, + move |value| Message::SetParam(id, value), + Message::ReleaseParam(id), + ) +} + +fn knob(label: impl Into, id: ParamId, value: f32) -> Element<'static, Message> { + let def = PARAMS[id.as_index()]; + let value_text = match id { + ParamId::MasterRange + | ParamId::OutputGain + | ParamId::Band1Range + | ParamId::Band2Range + | ParamId::Band3Range + | ParamId::Band4Range => format!("{value:.1} dB"), + ParamId::Split1 | ParamId::Split2 | ParamId::Split3 => format!("{value:.0} Hz"), + ParamId::Duration | ParamId::Release if value.abs() < 10.0 => format!("{value:.2} ms"), + ParamId::Duration | ParamId::Release => format!("{value:.0} ms"), + _ => format!("{value:.1}"), }; maolan_widgets::knob::knob( Knob { - label: label.to_string(), + label: label.into(), value, range: def.min as f32..=def.max as f32, default: def.default as f32, - step, + step: def.step as f32, value_text, assigned: false, }, @@ -217,6 +590,10 @@ fn knob( ) } +fn theme(_state: &State) -> Theme { + Theme::TokyoNight +} + fn build_app(shared: Arc) -> impl maolan_baseview::iced::Program { maolan_baseview::iced::application(move || init(shared.clone()), update, view) .font(maolan_widgets::iced_fonts::LUCIDE_FONT_BYTES) @@ -323,3 +700,47 @@ pub fn parent_from_window( None } } + +#[cfg(test)] +mod tests { + use super::*; + + fn state() -> State { + State { + shared: Arc::new(SharedState::default()), + active_gestures: vec![false; ParamId::COUNT], + spectrum_db: [[SPECTRUM_FLOOR_DB; DEFAULT_SPECTRUM_BINS]; 2], + selected_band: 0, + preset_ui: PresetUi::new(SharedState::DIR_NAME), + } + } + + #[test] + fn double_click_creates_sorted_bands_up_to_limit() { + let mut state = state(); + let _ = update(&mut state, Message::CreateBand(2_000.0)); + let _ = update(&mut state, Message::CreateBand(200.0)); + let _ = update(&mut state, Message::CreateBand(8_000.0)); + let _ = update(&mut state, Message::CreateBand(500.0)); + assert_eq!(state.shared.params.get(ParamId::BandCount), 4.0); + assert_eq!(active_splits(&state.shared), [200.0, 2_000.0, 8_000.0]); + assert_eq!(state.selected_band, 3); + } + + #[test] + fn contours_use_actual_parameter_values() { + let curves = transient_curves(&[], 1, 48_000.0, [-12.0; MAX_BANDS], [4.0; MAX_BANDS], 0); + assert_eq!(curves.len(), 2); + assert!(curves[0].points.iter().all(|(_, db)| *db == -12.0)); + assert!(curves[1].points.iter().all(|(_, db)| *db == 4.0)); + } + + #[test] + fn band_toggle_does_not_change_band_count() { + let mut state = state(); + let _ = update(&mut state, Message::CreateBand(500.0)); + let _ = update(&mut state, Message::SetBandOn(1, false)); + assert!(!state.shared.params.get_bool(ParamId::Band2On)); + assert_eq!(state.shared.params.get(ParamId::BandCount), 2.0); + } +} diff --git a/src/transient/params.rs b/src/transient/params.rs index f9bc50e..0fca379 100644 --- a/src/transient/params.rs +++ b/src/transient/params.rs @@ -1,71 +1,238 @@ -use maolan_clap::ffi::{CLAP_PARAM_IS_AUTOMATABLE, CLAP_PARAM_REQUIRES_PROCESS}; +use maolan_clap::ffi::{ + CLAP_PARAM_IS_AUTOMATABLE, CLAP_PARAM_IS_STEPPED, CLAP_PARAM_REQUIRES_PROCESS, +}; crate::define_params! { pub enum ParamId { - Attack = 0, - Sustain = 1, - AttackTime = 2, - ReleaseTime = 3, - DryWet = 4, - OutputGain = 5, + BandCount = 0, + Split1 = 1, + Split2 = 2, + Split3 = 3, + MasterRange = 4, + MasterSensitivity = 5, + Duration = 6, + Release = 7, + OutputGain = 8, + Band1On = 9, + Band1Range = 10, + Band1Sensitivity = 11, + Band2On = 12, + Band2Range = 13, + Band2Sensitivity = 14, + Band3On = 15, + Band3Range = 16, + Band3Sensitivity = 17, + Band4On = 18, + Band4Range = 19, + Band4Sensitivity = 20, } pub const PARAMS: [ParamDef] = [ { - id: ParamId::Attack, - name: "Attack", - module: "Transient", - min: -24.0, - max: 24.0, + id: ParamId::BandCount, + name: "Band Count", + module: "Configuration", + min: 1.0, + max: 4.0, + default: 1.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Split1, + name: "Crossover 1", + module: "Configuration", + min: 20.0, + max: 20000.0, + default: 120.0, + step: 1.0, + flags: AUTOMATABLE, + } + { + id: ParamId::Split2, + name: "Crossover 2", + module: "Configuration", + min: 20.0, + max: 20000.0, + default: 1000.0, + step: 1.0, + flags: AUTOMATABLE, + } + { + id: ParamId::Split3, + name: "Crossover 3", + module: "Configuration", + min: 20.0, + max: 20000.0, + default: 6000.0, + step: 1.0, + flags: AUTOMATABLE, + } + { + id: ParamId::MasterRange, + name: "Master Range", + module: "Master", + min: -90.0, + max: 20.0, + default: 0.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::MasterSensitivity, + name: "Master Sensitivity", + module: "Master", + min: -90.0, + max: 20.0, default: 0.0, step: 0.1, flags: AUTOMATABLE, } { - id: ParamId::Sustain, - name: "Sustain", - module: "Transient", - min: -24.0, - max: 24.0, + id: ParamId::Duration, + name: "Duration", + module: "Master", + min: 0.01, + max: 500.0, + default: 5.0, + step: 0.01, + flags: AUTOMATABLE, + } + { + id: ParamId::Release, + name: "Release", + module: "Master", + min: 0.5, + max: 500.0, + default: 20.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::OutputGain, + name: "Output Gain", + module: "Master", + min: -18.0, + max: 18.0, default: 0.0, step: 0.1, flags: AUTOMATABLE, } { - id: ParamId::AttackTime, - name: "Attack Time", - module: "Detector", - min: 0.1, + id: ParamId::Band1On, + name: "Band 1 On", + module: "Band 1", + min: 0.0, + max: 1.0, + default: 1.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Band1Range, + name: "Band 1 Range", + module: "Band 1", + min: -90.0, max: 20.0, + default: -6.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Band1Sensitivity, + name: "Band 1 Sensitivity", + module: "Band 1", + min: -90.0, + max: 20.0, + default: 0.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Band2On, + name: "Band 2 On", + module: "Band 2", + min: 0.0, + max: 1.0, default: 1.0, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Band2Range, + name: "Band 2 Range", + module: "Band 2", + min: -90.0, + max: 20.0, + default: -6.0, step: 0.1, flags: AUTOMATABLE, } { - id: ParamId::ReleaseTime, - name: "Release Time", - module: "Detector", - min: 10.0, - max: 1000.0, - default: 100.0, + id: ParamId::Band2Sensitivity, + name: "Band 2 Sensitivity", + module: "Band 2", + min: -90.0, + max: 20.0, + default: 0.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Band3On, + name: "Band 3 On", + module: "Band 3", + min: 0.0, + max: 1.0, + default: 1.0, step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Band3Range, + name: "Band 3 Range", + module: "Band 3", + min: -90.0, + max: 20.0, + default: -6.0, + step: 0.1, + flags: AUTOMATABLE, + } + { + id: ParamId::Band3Sensitivity, + name: "Band 3 Sensitivity", + module: "Band 3", + min: -90.0, + max: 20.0, + default: 0.0, + step: 0.1, flags: AUTOMATABLE, } { - id: ParamId::DryWet, - name: "Dry/Wet", - module: "Mix", + id: ParamId::Band4On, + name: "Band 4 On", + module: "Band 4", min: 0.0, max: 1.0, default: 1.0, - step: 0.01, + step: 1.0, + flags: STEPPED, + } + { + id: ParamId::Band4Range, + name: "Band 4 Range", + module: "Band 4", + min: -90.0, + max: 20.0, + default: -6.0, + step: 0.1, flags: AUTOMATABLE, } { - id: ParamId::OutputGain, - name: "Output Gain", - module: "Output", - min: -24.0, - max: 24.0, + id: ParamId::Band4Sensitivity, + name: "Band 4 Sensitivity", + module: "Band 4", + min: -90.0, + max: 20.0, default: 0.0, step: 0.1, flags: AUTOMATABLE, @@ -73,4 +240,23 @@ crate::define_params! { ]; } +impl ParamId { + pub fn band_on(band: usize) -> Self { + Self::from_raw(9 + band as u32 * 3).unwrap() + } + + pub fn band_range(band: usize) -> Self { + Self::from_raw(10 + band as u32 * 3).unwrap() + } + + pub fn band_sensitivity(band: usize) -> Self { + Self::from_raw(11 + band as u32 * 3).unwrap() + } + + pub fn split(index: usize) -> Self { + Self::from_raw(1 + index as u32).unwrap() + } +} + const AUTOMATABLE: u32 = CLAP_PARAM_IS_AUTOMATABLE | CLAP_PARAM_REQUIRES_PROCESS; +const STEPPED: u32 = AUTOMATABLE | CLAP_PARAM_IS_STEPPED; diff --git a/src/transient/plugin.rs b/src/transient/plugin.rs index eacdf0a..78ae7bb 100644 --- a/src/transient/plugin.rs +++ b/src/transient/plugin.rs @@ -1,4 +1,7 @@ -use std::ffi::{CStr, c_char, c_void}; +use std::{ + ffi::{CStr, c_char, c_void}, + sync::atomic::Ordering, +}; use maolan_clap::{ ffi::{ @@ -11,14 +14,16 @@ use maolan_clap::{ }; use crate::common::clap_harness::{ - DescriptorMeta, ParamSharedState, ParamSpec, PortConfig, Processor, StateHooks, + DescriptorMeta, ParamHost, ParamSharedState, ParamSpec, PortConfig, Processor, SharedBase, + StateHooks, }; -use crate::common::{apply_param_events, emit_pending_param_events_to_host}; +use crate::common::spectrum::{DEFAULT_SPECTRUM_BINS, StereoSpectrumAnalyzer}; +use crate::common::{SharedStateExt, apply_param_events, emit_pending_param_events_to_host}; use crate::transient::{ - dsp::{TransientParams, TransientShaper}, + dsp::{BandParams, MultibandTransient, TransientParams}, gui::GuiBridge, params::{PARAMS, ParamId, sanitize_param_value}, - state::PluginState, + state::{PluginState, STATE_HEADER_PREFIX}, }; use crate::{ clap_audio_ports_ext, clap_create_fn, clap_descriptor, clap_gui_ext, clap_params_ext, @@ -29,8 +34,8 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.transient\0"; const PLUGIN_NAME: &[u8] = b"Maolan Transient\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; -const PLUGIN_DESCRIPTION: &[u8] = b"Stereo-linked transient shaper\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); +const PLUGIN_DESCRIPTION: &[u8] = b"Dynamic four-band transient shaper\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_TRANSIENT_SHAPER: *const c_char = CLAP_PLUGIN_FEATURE_TRANSIENT_SHAPER.as_ptr(); const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr(); @@ -55,10 +60,142 @@ static META: DescriptorMeta = DescriptorMeta { clap_descriptor!(META); -pub type SharedState = ParamSharedState; +#[derive(Debug)] +pub struct SharedState { + core: ParamSharedState, + pub channels: std::sync::atomic::AtomicU32, + input_level_left_db: portable_atomic::AtomicF32, + input_level_right_db: portable_atomic::AtomicF32, + output_level_left_db: portable_atomic::AtomicF32, + output_level_right_db: portable_atomic::AtomicF32, + spectrum_db: crate::common::spectrum::SharedSpectrum, +} + +impl Default for SharedState { + fn default() -> Self { + Self { + core: ParamSharedState::default(), + channels: std::sync::atomic::AtomicU32::new(1), + input_level_left_db: portable_atomic::AtomicF32::new(-90.0), + input_level_right_db: portable_atomic::AtomicF32::new(-90.0), + output_level_left_db: portable_atomic::AtomicF32::new(-90.0), + output_level_right_db: portable_atomic::AtomicF32::new(-90.0), + spectrum_db: crate::common::spectrum::SharedSpectrum::default(), + } + } +} + +impl std::ops::Deref for SharedState { + type Target = ParamSharedState; + + fn deref(&self) -> &Self::Target { + &self.core + } +} + +impl std::ops::DerefMut for SharedState { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.core + } +} + +impl SharedBase for SharedState { + fn set_host(&self, host: *const clap_host) { + self.core.set_host(host); + } + + fn clear_host(&self) { + self.core.clear_host(); + } + + fn set_sample_rate(&self, sample_rate: f64) { + self.core.set_sample_rate(sample_rate); + } + + fn notify_gui_closed(&self) { + self.core.request_gui_closed(); + } +} + +impl ParamHost for SharedState { + type Param = ParamId; + + fn params(&self) -> &crate::common::param_store::ParamStore { + &self.core.params + } +} + +impl SharedStateExt for SharedState { + fn params_get(&self, id: ParamId) -> f64 { + self.core.params_get(id) + } + + fn set_gesture_active(&self, id: ParamId, active: bool) { + self.core.set_gesture_active(id, active); + } + + fn is_gesture_active(&self, id: ParamId) -> bool { + self.core.is_gesture_active(id) + } + + fn set_param_from_host(&self, id: ParamId, value: f64) { + self.core.set_param_from_host(id, value); + } + + fn take_pending_param_notifications(&self) -> u64 { + self.core.take_pending_param_notifications() + } + + fn requeue_pending_param_notifications(&self, bits: u64) { + self.core.requeue_pending_param_notifications(bits); + } + + fn take_pending_gesture_begin(&self) -> u64 { + self.core.take_pending_gesture_begin() + } + + fn requeue_pending_gesture_begin(&self, bits: u64) { + self.core.requeue_pending_gesture_begin(bits); + } + + fn take_pending_gesture_end(&self) -> u64 { + self.core.take_pending_gesture_end() + } -impl ParamSharedState { + fn requeue_pending_gesture_end(&self, bits: u64) { + self.core.requeue_pending_gesture_end(bits); + } +} + +impl SharedState { pub fn bump_params_version(&self) {} + + pub fn input_levels_db(&self) -> [f32; 2] { + [ + self.input_level_left_db.load(Ordering::Relaxed), + self.input_level_right_db.load(Ordering::Relaxed), + ] + } + + pub fn output_levels_db(&self) -> [f32; 2] { + [ + self.output_level_left_db.load(Ordering::Relaxed), + self.output_level_right_db.load(Ordering::Relaxed), + ] + } + + pub fn spectrum_db(&self) -> [[f32; DEFAULT_SPECTRUM_BINS]; 2] { + self.spectrum_db.get() + } + + fn set_levels(&self, input: [f32; 2], output: [f32; 2]) { + self.input_level_left_db.store(input[0], Ordering::Relaxed); + self.input_level_right_db.store(input[1], Ordering::Relaxed); + self.output_level_left_db + .store(output[0], Ordering::Relaxed); + self.output_level_right_db + .store(output[1], Ordering::Relaxed); + } } crate::impl_param_presets!(SharedState, ParamId, "transient", "maolan-transient-preset"); @@ -77,25 +214,46 @@ impl ParamSpec for ParamId { } } +fn runtime_params(shared: &SharedState) -> TransientParams { + TransientParams { + band_count: shared.params.get(ParamId::BandCount).round() as usize, + split_hz: [ + shared.params.get(ParamId::Split1) as f32, + shared.params.get(ParamId::Split2) as f32, + shared.params.get(ParamId::Split3) as f32, + ], + bands: std::array::from_fn(|band| BandParams { + on: shared.params.get_bool(ParamId::band_on(band)), + range_db: shared.params.get(ParamId::band_range(band)) as f32, + sensitivity: shared.params.get(ParamId::band_sensitivity(band)) as f32, + }), + master_range_db: shared.params.get(ParamId::MasterRange) as f32, + master_sensitivity: shared.params.get(ParamId::MasterSensitivity) as f32, + duration_ms: shared.params.get(ParamId::Duration) as f32, + release_ms: shared.params.get(ParamId::Release) as f32, + output_gain_db: shared.params.get(ParamId::OutputGain) as f32, + } +} + struct AudioProcessor { - dsp: TransientShaper, + dsp: MultibandTransient, temp_left: Vec, temp_right: Vec, + spectrum: StereoSpectrumAnalyzer, + spectrum_samples_since_update: usize, } impl AudioProcessor { fn new(sample_rate: f64, max_frames: u32) -> Self { Self { - dsp: TransientShaper::new(sample_rate as f32), + dsp: MultibandTransient::new(sample_rate as f32), temp_left: vec![0.0; max_frames as usize], temp_right: vec![0.0; max_frames as usize], + spectrum: StereoSpectrumAnalyzer::new(), + spectrum_samples_since_update: 0, } } - fn reset(&mut self) { - self.dsp.reset(); - } - fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { apply_param_events(shared, &process.in_events(), sanitize_param_value); { @@ -108,40 +266,65 @@ impl AudioProcessor { self.temp_left.resize(frames, 0.0); self.temp_right.resize(frames, 0.0); } - - let params = TransientParams { - attack_db: shared.params.get(ParamId::Attack) as f32, - sustain_db: shared.params.get(ParamId::Sustain) as f32, - attack_ms: shared.params.get(ParamId::AttackTime) as f32, - release_ms: shared.params.get(ParamId::ReleaseTime) as f32, - dry_wet: shared.params.get(ParamId::DryWet) as f32, - output_gain_db: shared.params.get(ParamId::OutputGain) as f32, - }; + let params = runtime_params(shared); let inputs_count = process.audio_inputs_count(); let outputs_count = process.audio_outputs_count(); + let mut spectrum_ready = false; if inputs_count >= 2 && outputs_count >= 2 { + shared.channels.store(2, Ordering::Release); let input_l = process.audio_inputs(0); let input_r = process.audio_inputs(1); self.temp_left[..frames].copy_from_slice(input_l.data32(0)); self.temp_right[..frames].copy_from_slice(input_r.data32(0)); + let input_levels = [ + peak_db(&self.temp_left[..frames]), + peak_db(&self.temp_right[..frames]), + ]; self.dsp.process_stereo( &mut self.temp_left[..frames], &mut self.temp_right[..frames], ¶ms, ); + shared.set_levels( + input_levels, + [ + peak_db(&self.temp_left[..frames]), + peak_db(&self.temp_right[..frames]), + ], + ); let mut output_l = process.audio_outputs(0); output_l.data32(0)[..frames].copy_from_slice(&self.temp_left[..frames]); let mut output_r = process.audio_outputs(1); output_r.data32(0)[..frames].copy_from_slice(&self.temp_right[..frames]); + self.spectrum + .push_stereo(&self.temp_left[..frames], &self.temp_right[..frames]); + spectrum_ready = true; } else if inputs_count >= 1 && outputs_count >= 1 { + shared.channels.store(1, Ordering::Release); let input = process.audio_inputs(0); self.temp_left[..frames].copy_from_slice(input.data32(0)); + let input_level = peak_db(&self.temp_left[..frames]); self.dsp .process_mono(&mut self.temp_left[..frames], ¶ms); + shared.set_levels( + [input_level, -90.0], + [peak_db(&self.temp_left[..frames]), -90.0], + ); let mut output = process.audio_outputs(0); output.data32(0)[..frames].copy_from_slice(&self.temp_left[..frames]); + self.spectrum.push_mono(&self.temp_left[..frames]); + spectrum_ready = true; + } + + self.spectrum_samples_since_update = + self.spectrum_samples_since_update.saturating_add(frames); + let update_interval = (shared.sample_rate() as f32 / 10.0).round().max(1.0) as usize; + if spectrum_ready && self.spectrum_samples_since_update >= update_interval { + self.spectrum_samples_since_update = 0; + let spectrum = self.spectrum.compute(shared.sample_rate() as f32); + shared.spectrum_db.set(&spectrum[0], &spectrum[1]); } CLAP_PROCESS_CONTINUE @@ -158,7 +341,9 @@ impl Processor for AudioProcessor { } fn reset(&mut self) { - AudioProcessor::reset(self); + self.dsp.reset(); + self.spectrum.reset(); + self.spectrum_samples_since_update = 0; } fn process(&mut self, shared: &SharedState, process: &mut Process) -> clap_process_status { @@ -166,46 +351,84 @@ impl Processor for AudioProcessor { } } +fn peak_db(samples: &[f32]) -> f32 { + let peak = crate::simd::peak_abs(samples); + if peak > 0.0 { + (20.0 * peak.log10()).clamp(-90.0, 20.0) + } else { + -90.0 + } +} + fn param_text(id: ParamId, value: f64) -> String { match id { - ParamId::Attack | ParamId::Sustain | ParamId::OutputGain => format!("{value:.1} dB"), - ParamId::AttackTime | ParamId::ReleaseTime => format!("{value:.1} ms"), - ParamId::DryWet => format!("{:.0}%", value * 100.0), + ParamId::BandCount => format!("{value:.0}"), + ParamId::Split1 | ParamId::Split2 | ParamId::Split3 => format!("{value:.0} Hz"), + ParamId::MasterRange + | ParamId::OutputGain + | ParamId::Band1Range + | ParamId::Band2Range + | ParamId::Band3Range + | ParamId::Band4Range => format!("{value:.1} dB"), + ParamId::MasterSensitivity + | ParamId::Band1Sensitivity + | ParamId::Band2Sensitivity + | ParamId::Band3Sensitivity + | ParamId::Band4Sensitivity => format!("{value:.1}"), + ParamId::Duration | ParamId::Release => format!("{value:.2} ms"), + ParamId::Band1On | ParamId::Band2On | ParamId::Band3On | ParamId::Band4On => { + if value >= 0.5 { + "On".to_string() + } else { + "Off".to_string() + } + } } } fn parse_param_text(id: ParamId, text: &str) -> Option { let text = text.trim(); match id { - ParamId::Attack | ParamId::Sustain | ParamId::OutputGain => text + ParamId::BandCount => text.parse().ok(), + ParamId::Split1 | ParamId::Split2 | ParamId::Split3 => { + text.trim_end_matches("Hz").trim().parse().ok() + } + ParamId::MasterRange + | ParamId::OutputGain + | ParamId::Band1Range + | ParamId::Band2Range + | ParamId::Band3Range + | ParamId::Band4Range => text .trim_end_matches("db") .trim_end_matches("dB") .trim() .parse() .ok(), - ParamId::AttackTime | ParamId::ReleaseTime => { - text.trim_end_matches("ms").trim().parse().ok() + ParamId::MasterSensitivity + | ParamId::Band1Sensitivity + | ParamId::Band2Sensitivity + | ParamId::Band3Sensitivity + | ParamId::Band4Sensitivity => text.parse().ok(), + ParamId::Duration | ParamId::Release => text.trim_end_matches("ms").trim().parse().ok(), + ParamId::Band1On | ParamId::Band2On | ParamId::Band3On | ParamId::Band4On => { + match text.to_ascii_lowercase().as_str() { + "on" | "1" => Some(1.0), + "off" | "0" => Some(0.0), + _ => text.parse().ok(), + } } - ParamId::DryWet => text - .trim_end_matches('%') - .trim() - .parse::() - .ok() - .map(|value| value / 100.0), } } impl StateHooks for PluginState { fn save(shared: &SharedState) -> Option> { PluginState::from_runtime(&shared.params) - .to_bytes(crate::transient::state::STATE_HEADER_PREFIX) + .to_bytes(STATE_HEADER_PREFIX) .ok() } fn load(shared: &SharedState, bytes: &[u8]) -> bool { - let Ok(state) = - PluginState::from_bytes(bytes, crate::transient::state::STATE_HEADER_PREFIX) - else { + let Ok(state) = PluginState::from_bytes(bytes, STATE_HEADER_PREFIX) else { return false; }; state.apply(&shared.params); @@ -264,18 +487,33 @@ mod tests { } #[test] - fn state_roundtrip_preserves_parameters() { + fn band_helpers_cover_all_bands() { + for band in 0..crate::transient::dsp::MAX_BANDS { + assert_eq!(ParamId::band_on(band).as_index(), 9 + band * 3); + assert_eq!(ParamId::band_range(band).as_index(), 10 + band * 3); + assert_eq!(ParamId::band_sensitivity(band).as_index(), 11 + band * 3); + } + } + + #[test] + fn state_roundtrip_preserves_dynamic_bands() { let shared = SharedState::default(); - shared.params.set(ParamId::Attack, 8.0); - shared.params.set(ParamId::Sustain, -6.0); + shared.params.set(ParamId::BandCount, 4.0); + shared.params.set(ParamId::Split2, 1800.0); + shared.params.set(ParamId::Band3Range, -8.0); + shared.params.set(ParamId::Band4On, 0.0); + shared.params.set(ParamId::MasterSensitivity, 3.0); let bytes = PluginState::from_runtime(&shared.params) - .to_bytes(crate::transient::state::STATE_HEADER_PREFIX) + .to_bytes(STATE_HEADER_PREFIX) .expect("state should save"); let restored = SharedState::default(); - PluginState::from_bytes(&bytes, crate::transient::state::STATE_HEADER_PREFIX) + PluginState::from_bytes(&bytes, STATE_HEADER_PREFIX) .expect("state should load") .apply(&restored.params); - assert_eq!(restored.params.get(ParamId::Attack), 8.0); - assert_eq!(restored.params.get(ParamId::Sustain), -6.0); + assert_eq!(restored.params.get(ParamId::BandCount), 4.0); + assert_eq!(restored.params.get(ParamId::Split2), 1800.0); + assert_eq!(restored.params.get(ParamId::Band3Range), -8.0); + assert!(!restored.params.get_bool(ParamId::Band4On)); + assert_eq!(restored.params.get(ParamId::MasterSensitivity), 3.0); } } diff --git a/src/tuner/plugin.rs b/src/tuner/plugin.rs index 675a677..26abee5 100644 --- a/src/tuner/plugin.rs +++ b/src/tuner/plugin.rs @@ -30,7 +30,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.tuner\0"; const PLUGIN_NAME: &[u8] = b"Maolan Tuner\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Monophonic pitch tuner using YIN\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_ANALYZER: *const c_char = CLAP_PLUGIN_FEATURE_ANALYZER.as_ptr(); diff --git a/src/vocoder/plugin.rs b/src/vocoder/plugin.rs index d6d9fe4..87e78ed 100644 --- a/src/vocoder/plugin.rs +++ b/src/vocoder/plugin.rs @@ -29,7 +29,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.vocoder\0"; const PLUGIN_NAME: &[u8] = b"Maolan Vocoder\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Stereo vocoder based on Mire Vocoder\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_STEREO: *const c_char = CLAP_PLUGIN_FEATURE_STEREO.as_ptr(); diff --git a/src/volume/plugin.rs b/src/volume/plugin.rs index 9af3894..5c55991 100644 --- a/src/volume/plugin.rs +++ b/src/volume/plugin.rs @@ -29,7 +29,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.volume\0"; const PLUGIN_NAME: &[u8] = b"Maolan Volume\0"; const PLUGIN_URL: &[u8] = b"\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Stereo volume control with input and output meters\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr(); diff --git a/src/wah/plugin.rs b/src/wah/plugin.rs index 386a60b..85f5ec1 100644 --- a/src/wah/plugin.rs +++ b/src/wah/plugin.rs @@ -30,7 +30,7 @@ const PLUGIN_ID: &[u8] = b"rs.maolan.wah\0"; const PLUGIN_NAME: &[u8] = b"Maolan Wah\0"; const PLUGIN_VENDOR: &[u8] = b"Maolan\0"; const PLUGIN_URL: &[u8] = b"\0"; -const PLUGIN_VERSION: &[u8] = b"0.1.0\0"; +const PLUGIN_VERSION: &[u8] = concat!(env!("CARGO_PKG_VERSION"), "\0").as_bytes(); const PLUGIN_DESCRIPTION: &[u8] = b"Resonant wah-wah with pedal, LFO and envelope modes\0"; const FEATURE_AUDIO_EFFECT: *const c_char = CLAP_PLUGIN_FEATURE_AUDIO_EFFECT.as_ptr(); const FEATURE_MONO: *const c_char = CLAP_PLUGIN_FEATURE_MONO.as_ptr();