diff --git a/Cargo.lock b/Cargo.lock index 46cd0cd68..2c61dfe41 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1042,7 +1042,16 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34ddef2995421ab6a5c779542c81ee77c115206f4ad9d5a8e05f4ff49716a3dd" dependencies = [ - "bit-vec", + "bit-vec 0.9.1", +] + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec 0.10.2", ] [[package]] @@ -1051,6 +1060,16 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -1134,6 +1153,30 @@ dependencies = [ "cipher", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -1779,6 +1822,17 @@ version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +[[package]] +name = "derive-new" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cdc8d50f426189eef89dac62fabfa0abb27d5cc008f25bf4156a0203325becc" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "digest" version = "0.10.7" @@ -1883,6 +1937,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +[[package]] +name = "downcast-rs" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc" + [[package]] name = "dpi" version = "0.1.2" @@ -1895,6 +1955,18 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "dyn-hash" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e" + [[package]] name = "easyfft" version = "0.4.2" @@ -2228,6 +2300,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "erased-serde" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66" +dependencies = [ + "serde", + "serde_core", + "typeid", +] + [[package]] name = "errno" version = "0.3.14" @@ -2334,6 +2417,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -2351,6 +2444,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-ord" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" + [[package]] name = "flume" version = "0.11.1" @@ -4102,6 +4201,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -4379,6 +4487,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "maplit" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" + [[package]] name = "matchers" version = "0.2.0" @@ -4394,6 +4508,16 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + [[package]] name = "md-5" version = "0.10.6" @@ -4443,6 +4567,16 @@ dependencies = [ "autocfg", ] +[[package]] +name = "metrics" +version = "0.24.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2" +dependencies = [ + "portable-atomic", + "rapidhash", +] + [[package]] name = "mime" version = "0.3.17" @@ -4471,6 +4605,15 @@ dependencies = [ "unicase", ] +[[package]] +name = "minijinja" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "509eeb2603a84eccabb4d75f6ec8ba23b46bbf441aaeb863d6b83a5887fd51e4" +dependencies = [ + "serde", +] + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -4549,7 +4692,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2bf919621e7975acb27d881bae2fb993e0d45c8e0446e85e6272971e00dc8df" dependencies = [ "arrayvec", - "bit-set", + "bit-set 0.9.1", "bitflags 2.13.2", "cfg-if", "cfg_aliases", @@ -4568,6 +4711,21 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "ndarray" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", +] + [[package]] name = "ndk" version = "0.9.0" @@ -4647,6 +4805,24 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom-language" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2de2bc5b451bfedaef92c90b8939a8fff5770bdcc1fafd6239d086aab8fa6b29" +dependencies = [ + "nom", +] + [[package]] name = "notify" version = "8.2.1" @@ -4691,6 +4867,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -4748,6 +4934,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ + "num-bigint", "num-integer", "num-traits", "serde", @@ -5603,6 +5790,29 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +[[package]] +name = "prost" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9f016da56b311cff4659f5e7335c4d5fda5ca86cae4f48b8ce1cf3335246a7d" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9a367f131d93b3395fc6207c11e67098493ab040def4ce3085adbf186687f7e" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -5784,6 +5994,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" +[[package]] +name = "rand_distr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d431c2703ccf129de4d45253c03f49ebb22b97d6ad79ee3ecfc7e3f4862c1d8" +dependencies = [ + "num-traits", + "rand 0.10.3", +] + [[package]] name = "rand_pcg" version = "0.10.2" @@ -5799,6 +6019,15 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" +[[package]] +name = "rapidhash" +version = "4.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" +dependencies = [ + "rustversion", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -5817,6 +6046,12 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + [[package]] name = "rayon" version = "1.12.0" @@ -6927,6 +7162,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" +[[package]] +name = "string-interner" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad3df9b59e2eded8d825c7c4363ad339a20fb6bc0b9a4778560f518f59910b15" +dependencies = [ + "hashbrown 0.16.1", + "serde", +] + [[package]] name = "stringprep" version = "0.1.5" @@ -6948,6 +7193,7 @@ dependencies = [ "axum-server", "base64 0.22.1", "bcrypt", + "byte-slice-cast", "cairo-rs", "chrono", "clap", @@ -6989,12 +7235,14 @@ dependencies = [ "nvml-wrapper", "objc2-foundation 0.3.2", "parking_lot", + "realfft", "reqwest", "rust-embed", "rustls", "serde", "serde_json", "serial_test", + "sha2 0.10.9", "socket2 0.6.5", "sqlx", "strom-frontend", @@ -7013,6 +7261,7 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", + "tract-onnx", "url", "urlencoding", "utoipa", @@ -7203,6 +7452,17 @@ dependencies = [ "version-compare", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "target-lexicon" version = "0.13.5" @@ -7722,6 +7982,175 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "tract-core" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5690191b7344a995507bed7523aeea052f907aa1316c0500540eec801e824a1c" +dependencies = [ + "anyhow", + "anymap3", + "bit-set 0.11.1", + "derive-new", + "downcast-rs 2.0.2", + "dyn-clone", + "erased-serde", + "inventory", + "lazy_static", + "log", + "maplit", + "metrics", + "ndarray", + "num-complex", + "num-integer", + "num-traits", + "pastey", + "rustfft", + "serde", + "smallvec", + "tract-data", + "tract-linalg", +] + +[[package]] +name = "tract-data" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5feff0e09b8cf92be4932457bda1b2156e348bbaf8311753da7f9b102c4af0b3" +dependencies = [ + "anyhow", + "downcast-rs 2.0.2", + "dyn-clone", + "dyn-hash", + "half", + "inventory", + "itertools", + "lazy_static", + "libm", + "maplit", + "ndarray", + "nom", + "nom-language", + "num-integer", + "num-traits", + "parking_lot", + "smallvec", + "string-interner", +] + +[[package]] +name = "tract-extra" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9b3105cbc51d3a24e6b640e18c7d6cdedebeef5b9435a74518e7658ee93578" +dependencies = [ + "tract-nnef", +] + +[[package]] +name = "tract-hir" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a84e8187c517f1a641dcd1b764f1dca2b6b8d39d4c78b2743e1b69874e65b735" +dependencies = [ + "derive-new", + "log", + "tract-core", +] + +[[package]] +name = "tract-linalg" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d389398bb62713b4dd4fc92c3a36ae1552faf522e17b1ae3f636537893a55c" +dependencies = [ + "byteorder", + "cc", + "derive-new", + "downcast-rs 2.0.2", + "dyn-clone", + "dyn-hash", + "half", + "inventory", + "lazy_static", + "libc", + "log", + "minijinja", + "num-traits", + "pastey", + "tract-data", + "walkdir", +] + +[[package]] +name = "tract-nnef" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "def0bced596beb4318148cac90de95dc9953089bb1df86ce2ef4c733ee450773" +dependencies = [ + "byteorder", + "erased-serde", + "log", + "nom", + "nom-language", + "serde", + "serde_json", + "simd-adler32", + "tar", + "tract-core", + "walkdir", +] + +[[package]] +name = "tract-onnx" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "994cd1cb5ea6747ac82707e39ae9588784f6794f96a4a86d137e71ebc49e2689" +dependencies = [ + "bytes", + "derive-new", + "log", + "memmap2", + "nom", + "nom-language", + "num-integer", + "num-rational", + "num-traits", + "prost", + "smallvec", + "tract-extra", + "tract-hir", + "tract-nnef", + "tract-onnx-opl", + "tract-transformers", +] + +[[package]] +name = "tract-onnx-opl" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee1b86a41af0b03fa2bb6d50c86d79ec363ba12e8c76fb0bff1d899d584bf310" +dependencies = [ + "getrandom 0.4.3", + "log", + "rand 0.10.3", + "rand_distr", + "rustfft", + "tract-extra", + "tract-nnef", +] + +[[package]] +name = "tract-transformers" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77f24c7b447fb64b64e90b2e8194d33f729efe9022ac9136c10ed2e70abb6de0" +dependencies = [ + "float-ord", + "rayon", + "tract-nnef", +] + [[package]] name = "transpose" version = "0.2.3" @@ -8146,7 +8575,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", - "downcast-rs", + "downcast-rs 1.2.1", "rustix 1.1.6", "scoped-tls", "smallvec", @@ -8380,8 +8809,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f519832254e56965a9940c4af57dcb75f702b6f6fa4a0b172f685395843a4d7" dependencies = [ "arrayvec", - "bit-set", - "bit-vec", + "bit-set 0.9.1", + "bit-vec 0.9.1", "bitflags 2.13.2", "bytemuck", "cfg_aliases", @@ -8452,7 +8881,7 @@ dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set", + "bit-set 0.9.1", "bitflags 2.13.2", "block2 0.6.2", "bytemuck", @@ -8975,6 +9404,16 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix 1.1.6", +] + [[package]] name = "xcursor" version = "0.3.11" diff --git a/Cargo.toml b/Cargo.toml index 91c5a084c..45dc8e105 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,3 +70,24 @@ gloo-net = { version = "0.7", features = ["websocket"] } # (Ubuntu 24.04 LTS). Drop it once upstream no longer requires 1.26. [patch.crates-io] gst-plugin-isobmff = { git = "https://github.com/srperens/gst-plugin-isobmff", tag = "v0.15.4-strom1" } + +# Voice isolation runs a neural network in pure Rust; unoptimised it cannot +# keep up with live audio, so debug builds and tests optimise these crates. +[profile.dev.package.tract-core] +opt-level = 3 +[profile.dev.package.tract-data] +opt-level = 3 +[profile.dev.package.tract-linalg] +opt-level = 3 +[profile.dev.package.tract-hir] +opt-level = 3 +[profile.dev.package.tract-onnx] +opt-level = 3 +[profile.dev.package.tract-onnx-opl] +opt-level = 3 +[profile.dev.package.tract-nnef] +opt-level = 3 +[profile.dev.package.rustfft] +opt-level = 3 +[profile.dev.package.realfft] +opt-level = 3 diff --git a/Dockerfile b/Dockerfile index 683779b97..d137907a8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -228,7 +228,7 @@ RUN --mount=type=secret,id=aws_access_key_id \ export CMAKE_C_FLAGS="-std=gnu17" && \ export CMAKE_CXX_FLAGS="-std=gnu++17" && \ export RUSTFLAGS="-L /usr/lib/aarch64-linux-gnu" && \ - cargo zigbuild --release --package strom --no-default-features --features no-gui,efp --target aarch64-unknown-linux-gnu.2.36 && \ + cargo zigbuild --release --package strom --no-default-features --features no-gui,efp,voice-isolation --target aarch64-unknown-linux-gnu.2.36 && \ # Move the binary to expected location (cargo-zigbuild puts it in target/aarch64-unknown-linux-gnu/release) mkdir -p target/release && \ cp target/aarch64-unknown-linux-gnu/release/strom target/release/strom; \ diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 30245914a..6dcdd4498 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -8,8 +8,11 @@ default-run = "strom" autotests = false [features] -default = ["nvidia"] +default = ["nvidia", "voice-isolation"] no-gui = [] +# DPDFNet speech enhancement on mixer channels, run with tract (pure Rust). +# The model is downloaded at build time and embedded in the binary. +voice-isolation = ["dep:tract-onnx", "dep:realfft", "dep:byte-slice-cast"] nvidia = ["dep:nvml-wrapper"] efp = ["dep:gst-plugin-efp"] @@ -74,6 +77,11 @@ gst-plugin-isobmff.workspace = true gst-plugin-stromdsp = { git = "https://github.com/Eyevinn/strom-dsp", tag = "v0.2.4", package = "gst-plugin-stromdsp" } gst-plugin-efp = { git = "https://github.com/Eyevinn/efp", tag = "v0.4.1", package = "gst-plugin-efp", optional = true } +# Voice isolation (DPDFNet model inference) +tract-onnx = { version = "0.23", optional = true } +realfft = { version = "3.5", optional = true } +byte-slice-cast = { version = "1.2", optional = true } + # Encoding base64 = "0.22" @@ -146,6 +154,7 @@ eframe = { workspace = true } [build-dependencies] chrono = "0.4" +sha2 = "0.10" uuid = { version = "1.23", features = ["v4"] } # NVML does not exist on macOS, so the `nvidia` feature pulls in nothing there diff --git a/backend/build.rs b/backend/build.rs index f8d6e6d73..0ff88d838 100644 --- a/backend/build.rs +++ b/backend/build.rs @@ -11,6 +11,10 @@ fn main() { // Set version and build information set_version_info(); + if std::env::var_os("CARGO_FEATURE_VOICE_ISOLATION").is_some() { + fetch_voice_isolation_model(); + } + // Embed Windows resources (icon, version info) #[cfg(windows)] embed_windows_resources(); @@ -414,3 +418,44 @@ fn embed_windows_resources() { eprintln!("cargo:warning=Failed to compile Windows resources: {}", e); } } + +/// DPDFNet 48 kHz model (Apache-2.0, Ceva), as re-hosted by sherpa-onnx. +const VOICE_MODEL_URL: &str = + "https://github.com/k2-fsa/sherpa-onnx/releases/download/speech-enhancement-models/dpdfnet2_48khz_hr.onnx"; +const VOICE_MODEL_SHA256: &str = "0b399f8a58dc4d70d8cd97541f5c39869406145193b957d00a03b66070944928"; + +/// Put the voice isolation model in OUT_DIR for `include_bytes!`. Downloads it +/// with curl unless STROM_VOICE_ISOLATION_MODEL names a local copy (offline +/// builds). Either way the file must match the pinned hash. +fn fetch_voice_isolation_model() { + use sha2::{Digest, Sha256}; + + println!("cargo:rerun-if-env-changed=STROM_VOICE_ISOLATION_MODEL"); + let out = PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("dpdfnet2_48khz_hr.onnx"); + let matches = |p: &Path| { + fs::read(p) + .map(|b| format!("{:x}", Sha256::digest(&b)) == VOICE_MODEL_SHA256) + .unwrap_or(false) + }; + if matches(&out) { + return; + } + if let Some(local) = std::env::var_os("STROM_VOICE_ISOLATION_MODEL") { + fs::copy(&local, &out).expect("copy STROM_VOICE_ISOLATION_MODEL"); + } else { + let status = Command::new("curl") + .args(["-fsSL", "--retry", "3", "-o"]) + .arg(&out) + .arg(VOICE_MODEL_URL) + .status() + .expect("run curl to download the voice isolation model"); + assert!( + status.success(), + "downloading {VOICE_MODEL_URL} failed: {status}" + ); + } + assert!( + matches(&out), + "voice isolation model does not match sha256 {VOICE_MODEL_SHA256}" + ); +} diff --git a/backend/src/blocks/builtin/mixer/builder.rs b/backend/src/blocks/builtin/mixer/builder.rs index dace09fde..b13d68fde 100644 --- a/backend/src/blocks/builtin/mixer/builder.rs +++ b/backend/src/blocks/builtin/mixer/builder.rs @@ -9,6 +9,7 @@ use tracing::{debug, info, warn}; use super::elements::*; use super::metering::connect_mixer_meter_handler; use super::properties::*; +use super::voice_isolation::push_voice_isolation; use super::{METER_INTERVAL_NS, MIN_KNEE_LINEAR}; use strom_types::mixer::{ DEFAULT_DSP_BACKEND, DEFAULT_INTERNAL_BUS_LATENCY_MS, DEFAULT_LATENCY_MS, @@ -811,6 +812,15 @@ impl BlockBuilder for MixerBuilder { let hpf = make_hpf_element(&hpf_id, hpf_enabled, hpf_freq)?; elements.push((hpf_id.clone(), hpf)); + let voice_isolation = push_voice_isolation( + instance_id, + ch, + properties, + sample_rate, + &mut elements, + &mut internal_links, + )?; + // ---------------------------------------------------------------- // Gate (LSP Gate Stereo with fallback) // ---------------------------------------------------------------- @@ -1096,7 +1106,7 @@ impl BlockBuilder for MixerBuilder { // ---------------------------------------------------------------- // Main chain links // ---------------------------------------------------------------- - // Chain: convert → resample → caps → gain → hpf → gate → comp → eq → level → pre_fader_tee + // Chain: convert → resample → caps → gain → hpf → [voice isolation] → gate → comp → eq → level → pre_fader_tee // The channel `level` element sits pre-fader (after EQ/dynamics, before // pan/fader/mute) so the meter reflects the signal hitting the fader. internal_links.push(( @@ -1115,10 +1125,22 @@ impl BlockBuilder for MixerBuilder { ElementPadRef::pad(&gain_id, "src"), ElementPadRef::pad(&hpf_id, "sink"), )); - internal_links.push(( - ElementPadRef::pad(&hpf_id, "src"), - ElementPadRef::pad(&gate_id, "sink"), - )); + match &voice_isolation { + Some((first, last)) => { + internal_links.push(( + ElementPadRef::pad(&hpf_id, "src"), + ElementPadRef::pad(first, "sink"), + )); + internal_links.push(( + ElementPadRef::pad(last, "src"), + ElementPadRef::pad(&gate_id, "sink"), + )); + } + None => internal_links.push(( + ElementPadRef::pad(&hpf_id, "src"), + ElementPadRef::pad(&gate_id, "sink"), + )), + } internal_links.push(( ElementPadRef::pad(&gate_id, "src"), ElementPadRef::pad(&comp_id, "sink"), diff --git a/backend/src/blocks/builtin/mixer/definition.rs b/backend/src/blocks/builtin/mixer/definition.rs index 1336970f8..631b153dc 100644 --- a/backend/src/blocks/builtin/mixer/definition.rs +++ b/backend/src/blocks/builtin/mixer/definition.rs @@ -746,6 +746,48 @@ pub(super) fn mixer_definition() -> BlockDefinition { visible_when: None, }); + // ============================================================ + // Voice isolation properties + // ============================================================ + exposed_properties.push(ExposedProperty { + name: format!("ch{}_voice_isolation", ch), + label: format!("Ch {} Voice Isolation", ch), + description: format!( + "Keep speech and suppress everything else on channel {} (music, fans, typing). \ + Delays the channel 60 ms while on.", + ch + ), + property_type: PropertyType::Bool, + default_value: Some(PropertyValue::Bool(false)), + mapping: PropertyMapping { + element_id: format!("voiceiso_{}", ch - 1), + property_name: "enabled".to_string(), + transform: None, + }, + live: true, + persist: None, + visible_when: None, + }); + + exposed_properties.push(ExposedProperty { + name: format!("ch{}_voice_isolation_limit", ch), + label: format!("Ch {} Voice Isolation Limit", ch), + description: format!( + "Most voice isolation may reduce channel {} at any frequency, in dB (0-100; 100 = no limit)", + ch + ), + property_type: PropertyType::Float, + default_value: Some(PropertyValue::Float(VOICE_ISOLATION_NO_LIMIT_DB as f64)), + mapping: PropertyMapping { + element_id: format!("voiceiso_{}", ch - 1), + property_name: "attenuation-limit".to_string(), + transform: None, + }, + live: true, + persist: None, + visible_when: None, + }); + // ============================================================ // Gate properties // ============================================================ diff --git a/backend/src/blocks/builtin/mixer/mod.rs b/backend/src/blocks/builtin/mixer/mod.rs index 1e6e5237e..2ff44218f 100644 --- a/backend/src/blocks/builtin/mixer/mod.rs +++ b/backend/src/blocks/builtin/mixer/mod.rs @@ -73,6 +73,9 @@ mod metering; mod properties; #[cfg(test)] mod tests; +mod voice_isolation; +#[cfg(all(test, feature = "voice-isolation"))] +mod voice_isolation_tests; use strom_types::mixer::{ DEFAULT_CHANNELS, MAX_AUX_BUSES, MAX_CHANNELS, MAX_GROUPS, MIN_KNEE_LINEAR, diff --git a/backend/src/blocks/builtin/mixer/tests.rs b/backend/src/blocks/builtin/mixer/tests.rs index 20100436d..8c857f94a 100644 --- a/backend/src/blocks/builtin/mixer/tests.rs +++ b/backend/src/blocks/builtin/mixer/tests.rs @@ -24,7 +24,7 @@ fn type_name(element: &gst::Element) -> &'static str { element.type_().name() } -fn props(pairs: &[(&str, PropertyValue)]) -> HashMap { +pub(super) fn props(pairs: &[(&str, PropertyValue)]) -> HashMap { pairs .iter() .map(|(k, v)| (k.to_string(), v.clone())) @@ -511,7 +511,7 @@ const INSTANCE: &str = "mx"; /// Two channels, one aux, one group: small enough to read, and it exercises /// every kind of bus the builder wires. -fn small_mixer_props(extra: &[(&str, PropertyValue)]) -> HashMap { +pub(super) fn small_mixer_props(extra: &[(&str, PropertyValue)]) -> HashMap { let mut p = props(&[ ("num_channels", PropertyValue::UInt(2)), ("num_aux_buses", PropertyValue::UInt(1)), @@ -522,13 +522,13 @@ fn small_mixer_props(extra: &[(&str, PropertyValue)]) -> HashMap &gst::Element { + pub(super) fn element(&self, id: &str) -> &gst::Element { let full = format!("{INSTANCE}:{id}"); self.result .elements @@ -538,7 +538,7 @@ impl Assembled { .unwrap_or_else(|| panic!("builder produced no element {full}")) } - fn has_element(&self, id: &str) -> bool { + pub(super) fn has_element(&self, id: &str) -> bool { let full = format!("{INSTANCE}:{id}"); self.result.elements.iter().any(|(k, _)| *k == full) } @@ -579,7 +579,7 @@ fn resolve_pad(element: &gst::Element, name: &str) -> gst::Pad { /// Build through the real builder and link the result the way the pipeline /// manager does: named pads pad-to-pad, element refs by `Element::link`. -fn assemble(properties: &HashMap) -> Assembled { +pub(super) fn assemble(properties: &HashMap) -> Assembled { init_gst(); let ctx = BlockBuildContext::new(Vec::new(), "all".to_string()); let result = MixerBuilder @@ -1043,7 +1043,7 @@ fn test_sample_rate_property_parsing() { } /// Link an `audiotestsrc` into `channel`. -fn feed(m: &Assembled, channel: usize, live: bool) { +pub(super) fn feed(m: &Assembled, channel: usize, live: bool) { let src = gst::ElementFactory::make("audiotestsrc") .property("is-live", live) .build() diff --git a/backend/src/blocks/builtin/mixer/voice_isolation.rs b/backend/src/blocks/builtin/mixer/voice_isolation.rs new file mode 100644 index 000000000..72be6625c --- /dev/null +++ b/backend/src/blocks/builtin/mixer/voice_isolation.rs @@ -0,0 +1,105 @@ +//! Voice isolation on a channel strip, between the HPF and the gate. + +use std::collections::HashMap; + +use gstreamer as gst; +use strom_types::element::ElementPadRef; +use strom_types::mixer::VOICE_ISOLATION_NO_LIMIT_DB; +use strom_types::PropertyValue; + +use super::properties::{get_bool_prop, get_float_prop}; +use crate::blocks::BlockBuildError; + +/// Add channel `ch`'s voice isolation and return the ids to link in after +/// the HPF and before the gate, or `None` when Strom is built without it. +/// +/// The element is always present and passes audio through until enabled, so +/// the switch works while the flow runs. It only runs at 48 kHz; a mixer at +/// another rate converts to 48 kHz and back around it. +pub(super) fn push_voice_isolation( + instance_id: &str, + ch: usize, + properties: &HashMap, + sample_rate: u32, + elements: &mut Vec<(String, gst::Element)>, + internal_links: &mut Vec<(ElementPadRef, ElementPadRef)>, +) -> Result, BlockBuildError> { + let ch_num = ch + 1; + let enabled = get_bool_prop(properties, &format!("ch{}_voice_isolation", ch_num), false); + let limit = get_float_prop( + properties, + &format!("ch{}_voice_isolation_limit", ch_num), + VOICE_ISOLATION_NO_LIMIT_DB as f64, + ); + + #[cfg(not(feature = "voice-isolation"))] + { + let _ = (instance_id, limit, sample_rate, elements, internal_links); + if enabled { + tracing::warn!( + "Mixer channel {} asks for voice isolation, but this Strom was built without it", + ch_num + ); + } + Ok(None) + } + + #[cfg(feature = "voice-isolation")] + { + use crate::gst::voice_isolation; + + let vi_id = format!("{}:voiceiso_{}", instance_id, ch); + let vi = gst::ElementFactory::make(voice_isolation::ELEMENT_NAME) + .name(&vi_id) + .property("enabled", enabled) + .property("attenuation-limit", limit) + .build() + .map_err(|e| { + BlockBuildError::ElementCreation(format!("voice isolation ch{}: {}", ch_num, e)) + })?; + elements.push((vi_id.clone(), vi)); + + if sample_rate == voice_isolation::SAMPLE_RATE { + return Ok(Some((vi_id.clone(), vi_id))); + } + + // audioresample → capsfilter at each rate, on both sides. + let mut convert = |suffix: &str, rate: u32| -> Result<(String, String), BlockBuildError> { + let resample_id = format!("{}:voiceiso_{}_resample_{}", instance_id, ch, suffix); + let caps_id = format!("{}:voiceiso_{}_caps_{}", instance_id, ch, suffix); + let resample = gst::ElementFactory::make("audioresample") + .name(&resample_id) + .build() + .map_err(|e| BlockBuildError::ElementCreation(format!("{}: {}", resample_id, e)))?; + let caps = gst::Caps::builder("audio/x-raw") + .field("format", "F32LE") + .field("rate", rate as i32) + .field("channels", 2i32) + .field("layout", "interleaved") + .build(); + let capsfilter = gst::ElementFactory::make("capsfilter") + .name(&caps_id) + .property("caps", &caps) + .build() + .map_err(|e| BlockBuildError::ElementCreation(format!("{}: {}", caps_id, e)))?; + elements.push((resample_id.clone(), resample)); + elements.push((caps_id.clone(), capsfilter)); + internal_links.push(( + ElementPadRef::pad(&resample_id, "src"), + ElementPadRef::pad(&caps_id, "sink"), + )); + Ok((resample_id, caps_id)) + }; + let (in_first, in_last) = convert("in", voice_isolation::SAMPLE_RATE)?; + let (out_first, out_last) = convert("out", sample_rate)?; + internal_links.push(( + ElementPadRef::pad(&in_last, "src"), + ElementPadRef::pad(&vi_id, "sink"), + )); + internal_links.push(( + ElementPadRef::pad(&vi_id, "src"), + ElementPadRef::pad(&out_first, "sink"), + )); + Ok(Some((in_first, out_last))) + } +} diff --git a/backend/src/blocks/builtin/mixer/voice_isolation_tests.rs b/backend/src/blocks/builtin/mixer/voice_isolation_tests.rs new file mode 100644 index 000000000..3ea69f1a4 --- /dev/null +++ b/backend/src/blocks/builtin/mixer/voice_isolation_tests.rs @@ -0,0 +1,94 @@ +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use gstreamer as gst; +use gstreamer::prelude::*; +use strom_types::PropertyValue; + +use super::tests::{assemble, feed, small_mixer_props, Assembled}; + +/// The element `id`'s src pad feeds, by element name without the block prefix. +fn feeds(m: &Assembled, id: &str) -> String { + let next = m + .element(id) + .static_pad("src") + .and_then(|p| p.peer()) + .and_then(|p| p.parent_element()) + .unwrap_or_else(|| panic!("{id} feeds nothing")); + next.name().trim_start_matches("mx:").to_string() +} + +#[test] +fn test_voice_isolation_sits_between_hpf_and_gate() { + let m = assemble(&small_mixer_props(&[ + ("ch1_voice_isolation", PropertyValue::Bool(true)), + ("ch1_voice_isolation_limit", PropertyValue::Float(30.0)), + ])); + + let on = m.element("voiceiso_0"); + assert!(on.property::("enabled")); + assert_eq!(on.property::("attenuation-limit"), 30.0); + // Present on every channel so it can be switched on live. + assert!(!m.element("voiceiso_1").property::("enabled")); + + for ch in 0..2 { + assert_eq!(feeds(&m, &format!("hpf_{ch}")), format!("voiceiso_{ch}")); + assert_eq!(feeds(&m, &format!("voiceiso_{ch}")), format!("gate_{ch}")); + } + assert!( + !m.has_element("voiceiso_0_resample_in"), + "no conversion at 48 kHz" + ); +} + +/// The model runs only at 48 kHz. A mixer at 44.1 kHz converts around it; +/// without that the strip would refuse to link. +#[test] +fn test_voice_isolation_converts_around_a_non_48k_mixer() { + let mut properties = small_mixer_props(&[("ch1_voice_isolation", PropertyValue::Bool(true))]); + properties.insert( + "sample_rate".to_string(), + PropertyValue::String("44100".to_string()), + ); + let m = assemble(&properties); + assert!(m.has_element("voiceiso_0_resample_in")); + assert!(m.has_element("voiceiso_0_resample_out")); + + feed(&m, 0, true); + let sink = gst::ElementFactory::make("fakesink") + .property("sync", false) + .build() + .unwrap(); + m.pipeline.add(&sink).unwrap(); + m.element("main_out_tee") + .link_pads(Some("src_%u"), &sink, None) + .unwrap(); + let buffers = Arc::new(AtomicUsize::new(0)); + let counter = buffers.clone(); + sink.static_pad("sink") + .unwrap() + .add_probe(gst::PadProbeType::BUFFER, move |_, _| { + counter.fetch_add(1, Ordering::Relaxed); + gst::PadProbeReturn::Ok + }); + + m.pipeline.set_state(gst::State::Playing).unwrap(); + let bus = m.pipeline.bus().unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + while buffers.load(Ordering::Relaxed) < 20 { + assert!(Instant::now() < deadline, "no audio reached main_out"); + if let Some(msg) = bus.timed_pop_filtered( + gst::ClockTime::from_mseconds(50), + &[gst::MessageType::Error], + ) { + panic!("pipeline error: {msg:?}"); + } + } + let rate = m + .element("voiceiso_0") + .static_pad("sink") + .and_then(|p| p.current_caps()) + .and_then(|c| c.structure(0).and_then(|s| s.get::("rate").ok())); + assert_eq!(rate, Some(48_000)); +} diff --git a/backend/src/gst/mod.rs b/backend/src/gst/mod.rs index b87466597..26162053c 100644 --- a/backend/src/gst/mod.rs +++ b/backend/src/gst/mod.rs @@ -33,13 +33,16 @@ pub mod ts_arrival_clock; pub(crate) mod underlay; pub mod video_adapt; pub mod video_input_bridge; +#[cfg(feature = "voice-isolation")] +pub mod voice_isolation; pub mod volume_ramp; pub mod whep_probe; /// Register the GStreamer plugins Strom links in statically (gst-plugins-rs -/// WebRTC, inter, RTP, audiofx, isobmff, strom-dsp, and EFP with the `efp` -/// feature). Call once, after `gst::init()`, before any flow is built. Panics -/// when a plugin fails to register: the blocks that use it could not work. +/// WebRTC, inter, RTP, audiofx, isobmff, strom-dsp, voice isolation with the +/// `voice-isolation` feature, and EFP with the `efp` feature). Call once, after +/// `gst::init()`, before any flow is built. Panics when a plugin fails to +/// register: the blocks that use it could not work. /// /// isobmff is the exception. GStreamer 1.28 installs its own `isobmff` plugin /// with the same element names as Strom's fork (`isofmp4mux`, `cmafmux`, ...). @@ -73,6 +76,8 @@ pub fn register_dsp_plugins() { ONCE.call_once(|| { gst_plugin_stromdsp::plugin_register_static() .expect("Could not register strom-dsp plugins"); + #[cfg(feature = "voice-isolation")] + voice_isolation::register().expect("Could not register the voice isolation element"); }); } diff --git a/backend/src/gst/voice_isolation/engine.rs b/backend/src/gst/voice_isolation/engine.rs new file mode 100644 index 000000000..39bd7f0bc --- /dev/null +++ b/backend/src/gst/voice_isolation/engine.rs @@ -0,0 +1,234 @@ +//! DPDFNet streaming speech enhancement, one 10 ms hop at a time. +//! +//! Framing follows DPDFNet's own streaming wrapper: vorbis window of 960 +//! samples, hop 480, rfft -> model (one frame plus a recurrent state vector) +//! -> irfft * window -> overlap-add. Output lags input by `MODEL_DELAY`. + +use std::collections::HashMap; +use std::sync::Arc; + +use realfft::num_complex::Complex32; +use realfft::{ComplexToReal, RealFftPlanner, RealToComplex}; +use strom_types::mixer::VOICE_ISOLATION_NO_LIMIT_DB; +use tract_onnx::prelude::*; + +pub(super) const SAMPLE_RATE: i32 = 48_000; +pub(super) const HOP: usize = 480; +const WIN: usize = 2 * HOP; +const BINS: usize = WIN / 2 + 1; +/// Frames between an input spectrum and the model output that enhances it. +const MODEL_DELAY_FRAMES: usize = 4; +/// Input-to-output delay in samples: one hop of overlap-add plus the model's frames. +pub(super) const MODEL_DELAY: usize = HOP + MODEL_DELAY_FRAMES * HOP; + +static MODEL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/dpdfnet2_48khz_hr.onnx")); + +pub(super) struct Engine { + /// Each hop runs in a fresh session of this plan. tract's GRUs carry + /// their final hidden state into the next run of a session instead of + /// starting from the model's initial_h, and DPDFNet's GRUs run across + /// frequency within one frame, so a reused session leaks each frame into + /// the next and the recurrent state drifts until speech is suppressed. + plan: Arc, + init_state: Tensor, + /// The model's recurrent state, fed back in on every hop. + state: Tensor, + fwd: Arc>, + inv: Arc>, + window: Vec, + /// The last WIN input samples. + hist: Vec, + ola: Vec, + time_buf: Vec, + freq_buf: Vec, + scratch_fwd: Vec, + scratch_inv: Vec, + /// Interleaved re/im, [BINS][2], the model's input and output layout. + spec: Vec, + spec_out: Vec, + /// Input spectra of the last MODEL_DELAY_FRAMES hops, for the attenuation limit. + noisy: Vec>, + noisy_pos: usize, + /// Share of the input spectrum mixed back in; 0 removes everything the model removes. + alpha: f32, +} + +impl Engine { + /// Parse and optimise the embedded model. Takes most of a second, so + /// callers run it off the streaming thread. + pub(super) fn load() -> Result { + let err = |e: TractError| format!("{e:#}"); + let onnx = tract_onnx::onnx(); + let proto = onnx.proto_model_for_read(&mut &MODEL[..]).map_err(err)?; + let metadata: HashMap<&str, &str> = proto + .metadata_props + .iter() + .map(|p| (p.key.as_str(), p.value.as_str())) + .collect(); + let init_state = tensor1(&initial_state(&metadata)?); + let plan = onnx + .model_for_proto_model(&proto) + .map_err(err)? + .with_input_fact(0, f32::fact([1, 1, BINS, 2]).into()) + .map_err(err)? + .with_input_fact(1, f32::fact([init_state.len()]).into()) + .map_err(err)? + .into_optimized() + .map_err(err)? + .into_runnable() + .map_err(err)?; + + let mut planner = RealFftPlanner::::new(); + let fwd = planner.plan_fft_forward(WIN); + let inv = planner.plan_fft_inverse(WIN); + let window = (0..WIN) + .map(|i| { + let s = (0.5 * std::f32::consts::PI * (i as f32 + 0.5) / HOP as f32).sin(); + (0.5 * std::f32::consts::PI * s * s).sin() + }) + .collect(); + Ok(Self { + state: init_state.clone(), + init_state, + plan, + time_buf: fwd.make_input_vec(), + freq_buf: fwd.make_output_vec(), + scratch_fwd: fwd.make_scratch_vec(), + scratch_inv: inv.make_scratch_vec(), + fwd, + inv, + window, + hist: vec![0.0; WIN], + ola: vec![0.0; WIN], + spec: vec![0.0; BINS * 2], + spec_out: vec![0.0; BINS * 2], + noisy: vec![vec![0.0; BINS * 2]; MODEL_DELAY_FRAMES], + noisy_pos: 0, + alpha: 0.0, + }) + } + + /// Forget everything heard so far. + pub(super) fn reset(&mut self) { + self.state = self.init_state.clone(); + self.hist.fill(0.0); + self.ola.fill(0.0); + for n in &mut self.noisy { + n.fill(0.0); + } + } + + /// Cap how far the model may pull any bin down; VOICE_ISOLATION_NO_LIMIT_DB + /// or more means no cap. + pub(super) fn set_attenuation_limit(&mut self, db: f64) { + self.alpha = if db >= VOICE_ISOLATION_NO_LIMIT_DB as f64 { + 0.0 + } else { + 10f64.powf(-db / 20.0) as f32 + }; + } + + /// Enhance one hop: `input` and `output` are HOP samples each. + pub(super) fn process_hop(&mut self, input: &[f32], output: &mut [f32]) -> Result<(), String> { + self.hist.copy_within(HOP.., 0); + self.hist[WIN - HOP..].copy_from_slice(input); + for ((t, h), w) in self.time_buf.iter_mut().zip(&self.hist).zip(&self.window) { + *t = h * w; + } + self.fwd + .process_with_scratch( + &mut self.time_buf, + &mut self.freq_buf, + &mut self.scratch_fwd, + ) + .map_err(|e| e.to_string())?; + for (k, c) in self.freq_buf.iter().enumerate() { + self.spec[2 * k] = c.re; + self.spec[2 * k + 1] = c.im; + } + + let err = |e: TractError| format!("{e:#}"); + let spec = Tensor::from_shape(&[1, 1, BINS, 2], &self.spec).map_err(err)?; + let state = std::mem::take(&mut self.state); + let mut outputs = self + .plan + .run(tvec!(spec.into(), state.into())) + .map_err(err)?; + self.state = outputs.remove(1).into_tensor(); + let spec_e = outputs[0].try_as_plain_ram().map_err(err)?; + self.spec_out + .copy_from_slice(spec_e.as_slice::().map_err(err)?); + + // The model's output lags its input by MODEL_DELAY_FRAMES, so the + // limit blends in the input spectrum from that many hops ago. + let noisy = &mut self.noisy[self.noisy_pos]; + if self.alpha > 0.0 { + for (e, n) in self.spec_out.iter_mut().zip(noisy.iter()) { + *e = self.alpha * n + (1.0 - self.alpha) * *e; + } + } + noisy.copy_from_slice(&self.spec); + self.noisy_pos = (self.noisy_pos + 1) % MODEL_DELAY_FRAMES; + + for (k, c) in self.freq_buf.iter_mut().enumerate() { + *c = Complex32::new(self.spec_out[2 * k], self.spec_out[2 * k + 1]); + } + // A real signal has no imaginary DC or Nyquist term; realfft refuses one. + self.freq_buf[0].im = 0.0; + self.freq_buf[BINS - 1].im = 0.0; + self.inv + .process_with_scratch( + &mut self.freq_buf, + &mut self.time_buf, + &mut self.scratch_inv, + ) + .map_err(|e| e.to_string())?; + // realfft's inverse is unnormalised. + let norm = 1.0 / WIN as f32; + for ((o, t), w) in self.ola.iter_mut().zip(&self.time_buf).zip(&self.window) { + *o += t * w * norm; + } + output.copy_from_slice(&self.ola[..HOP]); + self.ola.copy_within(HOP.., 0); + self.ola[WIN - HOP..].fill(0.0); + Ok(()) + } +} + +/// The recurrent state vector starts at zero except for two normalisation +/// blocks whose starting values the export stores in the model metadata. +fn initial_state(metadata: &HashMap<&str, &str>) -> Result, String> { + let get = |k: &str| { + metadata + .get(k) + .copied() + .ok_or_else(|| format!("model metadata lacks {k}")) + }; + let floats = |k: &str| -> Result, String> { + get(k)? + .split(',') + .map(|v| v.trim().parse::().map_err(|e| format!("{k}: {e}"))) + .collect() + }; + for (k, want) in [ + ("n_fft", WIN), + ("hop_length", HOP), + ("sample_rate", SAMPLE_RATE as usize), + ] { + let got: usize = get(k)?.parse().map_err(|e| format!("{k}: {e}"))?; + if got != want { + return Err(format!("model {k} is {got}, expected {want}")); + } + } + let size: usize = get("state_size")? + .parse() + .map_err(|e| format!("state_size: {e}"))?; + let (erb, spec) = (floats("erb_norm_init")?, floats("spec_norm_init")?); + if erb.len() + spec.len() > size { + return Err("normalisation init larger than the state".into()); + } + let mut state = vec![0.0; size]; + state[..erb.len()].copy_from_slice(&erb); + state[erb.len()..erb.len() + spec.len()].copy_from_slice(&spec); + Ok(state) +} diff --git a/backend/src/gst/voice_isolation/imp.rs b/backend/src/gst/voice_isolation/imp.rs new file mode 100644 index 000000000..c371c0b97 --- /dev/null +++ b/backend/src/gst/voice_isolation/imp.rs @@ -0,0 +1,425 @@ +use std::collections::VecDeque; +use std::sync::mpsc; +use std::sync::{LazyLock, Mutex}; + +use byte_slice_cast::*; +use gstreamer as gst; +use gstreamer::glib; +use gstreamer::prelude::*; +use gstreamer::subclass::prelude::*; +use gstreamer_base as gst_base; +use gstreamer_base::prelude::BaseTransformExt; +use gstreamer_base::subclass::base_transform::BaseTransformMode; +use gstreamer_base::subclass::prelude::*; +use strom_types::mixer::VOICE_ISOLATION_NO_LIMIT_DB; + +use super::engine::{Engine, HOP, MODEL_DELAY, SAMPLE_RATE}; + +static CAT: LazyLock = LazyLock::new(|| { + gst::DebugCategory::new( + "stromvoiceisolation", + gst::DebugColorFlags::empty(), + Some("Strom voice isolation"), + ) +}); + +/// Wet output lags its input by this much: the model's delay plus one hop, +/// so a buffer that ends mid-hop can still be answered in full. +pub(super) const CONTENT_DELAY: usize = MODEL_DELAY + HOP; +/// Crossfade between dry and wet when the switch flips. +const FADE: usize = HOP; +const NO_LIMIT_DB: f64 = VOICE_ISOLATION_NO_LIMIT_DB as f64; + +#[derive(Clone, Copy)] +struct Settings { + enabled: bool, + attenuation_limit: f64, +} + +impl Default for Settings { + fn default() -> Self { + Self { + enabled: false, + attenuation_limit: NO_LIMIT_DB, + } + } +} + +#[derive(Default)] +struct State { + channels: usize, + /// The last CONTENT_DELAY mono input samples, oldest first, so a start + /// can pick up where the dry signal is instead of from silence. + history: VecDeque, + engine: Option, + loading: Option>>, + load_failed: bool, + /// The engine is fed and wet output is mixed in (at gain `wet`). + running: bool, + wet: f32, + pending: Vec, + out: VecDeque, + mono: Vec, + hop_out: Vec, +} + +#[derive(Default)] +pub struct VoiceIsolation { + settings: Mutex, + state: Mutex, +} + +#[glib::object_subclass] +impl ObjectSubclass for VoiceIsolation { + const NAME: &'static str = "StromVoiceIsolation"; + type Type = super::VoiceIsolation; + type ParentType = gst_base::BaseTransform; +} + +impl ObjectImpl for VoiceIsolation { + fn properties() -> &'static [glib::ParamSpec] { + static PROPS: LazyLock> = LazyLock::new(|| { + vec![ + glib::ParamSpecBoolean::builder("enabled") + .nick("Enabled") + .blurb("Keep speech and suppress everything else (adds 60 ms while on)") + .default_value(false) + .mutable_playing() + .build(), + glib::ParamSpecDouble::builder("attenuation-limit") + .nick("Attenuation limit") + .blurb("Most the model may reduce any frequency, in dB; 100 means no limit") + .minimum(0.0) + .maximum(NO_LIMIT_DB) + .default_value(NO_LIMIT_DB) + .mutable_playing() + .build(), + ] + }); + PROPS.as_ref() + } + + fn set_property(&self, _id: usize, value: &glib::Value, pspec: &glib::ParamSpec) { + let mut settings = self.settings.lock().unwrap(); + match pspec.name() { + "enabled" => { + settings.enabled = value.get().expect("type checked upstream"); + if settings.enabled { + // Fading out leaves passthrough on; processing needs it off. + self.obj().set_passthrough(false); + } + } + "attenuation-limit" => { + settings.attenuation_limit = value.get().expect("type checked upstream"); + } + _ => unimplemented!(), + } + } + + fn property(&self, _id: usize, pspec: &glib::ParamSpec) -> glib::Value { + let settings = self.settings.lock().unwrap(); + match pspec.name() { + "enabled" => settings.enabled.to_value(), + "attenuation-limit" => settings.attenuation_limit.to_value(), + _ => unimplemented!(), + } + } + + fn constructed(&self) { + self.parent_constructed(); + self.obj() + .set_passthrough(!self.settings.lock().unwrap().enabled); + } +} + +impl GstObjectImpl for VoiceIsolation {} + +impl ElementImpl for VoiceIsolation { + fn metadata() -> Option<&'static gst::subclass::ElementMetadata> { + static META: LazyLock = LazyLock::new(|| { + gst::subclass::ElementMetadata::new( + "Voice isolation", + "Filter/Effect/Audio", + "Keeps speech and suppresses background sound with the DPDFNet model. \ + While enabled the audio is delayed 60 ms inside unchanged timestamps; \ + no latency is reported, so channels without it are not held back.", + "Strom", + ) + }); + Some(&*META) + } + + fn pad_templates() -> &'static [gst::PadTemplate] { + static TEMPLATES: LazyLock> = LazyLock::new(|| { + let caps = gst::Caps::builder("audio/x-raw") + .field("format", "F32LE") + .field("rate", SAMPLE_RATE) + .field("channels", gst::IntRange::new(1, 8)) + .field("layout", "interleaved") + .build(); + vec![ + gst::PadTemplate::new( + "src", + gst::PadDirection::Src, + gst::PadPresence::Always, + &caps, + ) + .unwrap(), + gst::PadTemplate::new( + "sink", + gst::PadDirection::Sink, + gst::PadPresence::Always, + &caps, + ) + .unwrap(), + ] + }); + TEMPLATES.as_ref() + } +} + +impl BaseTransformImpl for VoiceIsolation { + const MODE: BaseTransformMode = BaseTransformMode::AlwaysInPlace; + const PASSTHROUGH_ON_SAME_CAPS: bool = false; + const TRANSFORM_IP_ON_PASSTHROUGH: bool = true; + + fn set_caps(&self, incaps: &gst::Caps, _outcaps: &gst::Caps) -> Result<(), gst::LoggableError> { + let channels = incaps + .structure(0) + .and_then(|s| s.get::("channels").ok()) + .ok_or_else(|| gst::loggable_error!(CAT, "caps without channels: {incaps}"))?; + self.state.lock().unwrap().channels = channels as usize; + Ok(()) + } + + fn stop(&self) -> Result<(), gst::ErrorMessage> { + // Keep a loaded engine across restarts; drop everything else. + let mut state = self.state.lock().unwrap(); + let engine = state.engine.take(); + *state = State { + engine, + ..Default::default() + }; + Ok(()) + } + + fn sink_event(&self, event: gst::Event) -> bool { + if let gst::EventView::FlushStop(_) = event.view() { + let mut state = self.state.lock().unwrap(); + state.running = false; + state.wet = 0.0; + state.history.clear(); + } + self.parent_sink_event(event) + } + + fn transform_ip_passthrough( + &self, + buf: &gst::Buffer, + ) -> Result { + let map = buf.map_readable().map_err(|_| gst::FlowError::Error)?; + let samples = map + .as_slice_of::() + .map_err(|_| gst::FlowError::Error)?; + let mut state = self.state.lock().unwrap(); + let state = &mut *state; + downmix(samples, state.channels, &mut state.mono); + remember(&mut state.history, &state.mono); + drop(map); + self.leave_passthrough_if_enabled(); + Ok(gst::FlowSuccess::Ok) + } + + fn transform_ip(&self, buf: &mut gst::BufferRef) -> Result { + let settings = *self.settings.lock().unwrap(); + let mut map = buf.map_writable().map_err(|_| gst::FlowError::Error)?; + let samples = map + .as_mut_slice_of::() + .map_err(|_| gst::FlowError::Error)?; + let mut guard = self.state.lock().unwrap(); + let state = &mut *guard; + let channels = state.channels.max(1); + downmix(samples, channels, &mut state.mono); + + if settings.enabled + && state.engine.is_none() + && state.loading.is_none() + && !state.load_failed + { + self.start_loading(state); + } + if let Some(rx) = &state.loading { + match rx.try_recv() { + Ok(Ok(engine)) => { + gst::info!(CAT, imp = self, "model loaded"); + state.engine = Some(engine); + state.loading = None; + } + Ok(Err(e)) => { + gst::element_imp_warning!( + self, + gst::LibraryError::Init, + ["voice isolation model failed to load: {e}"] + ); + state.load_failed = true; + state.loading = None; + } + Err(mpsc::TryRecvError::Empty) => {} + Err(mpsc::TryRecvError::Disconnected) => { + state.load_failed = true; + state.loading = None; + } + } + } + + let want_wet = settings.enabled && state.engine.is_some(); + if want_wet && !state.running { + if let Err(e) = self.start(state) { + gst::element_imp_warning!( + self, + gst::LibraryError::Failed, + ["voice isolation failed to start: {e}"] + ); + state.load_failed = true; + } + } + if state.running { + if let Err(e) = self.run(state, settings.attenuation_limit) { + gst::element_imp_warning!( + self, + gst::LibraryError::Failed, + ["voice isolation stopped: {e}"] + ); + state.load_failed = true; + state.running = false; + state.wet = 0.0; + state.out.clear(); + } else { + mix(samples, channels, &mut state.out, &mut state.wet, want_wet); + if !want_wet && state.wet == 0.0 { + state.running = false; + state.out.clear(); + } + } + } + remember(&mut state.history, &state.mono); + + let idle = !state.running; + drop(guard); + if idle { + // Under the settings lock, so a concurrent enable is not undone. + let settings = self.settings.lock().unwrap(); + if !settings.enabled { + self.obj().set_passthrough(true); + } + } + Ok(gst::FlowSuccess::Ok) + } +} + +impl VoiceIsolation { + fn start_loading(&self, state: &mut State) { + let (tx, rx) = mpsc::channel(); + let spawned = std::thread::Builder::new() + .name("voiceiso-load".into()) + .spawn(move || { + let _ = tx.send(Engine::load()); + }); + match spawned { + Ok(_) => state.loading = Some(rx), + Err(e) => { + gst::element_imp_warning!( + self, + gst::LibraryError::Init, + ["cannot start the model loader: {e}"] + ); + state.load_failed = true; + } + } + } + + /// `enabled` was set while a buffer decided to go idle; undo that. + fn leave_passthrough_if_enabled(&self) { + let settings = self.settings.lock().unwrap(); + if settings.enabled { + self.obj().set_passthrough(false); + } + } + + /// Prime the engine with the recent dry signal so wet output continues + /// from it, then drop what the model emits for audio before that. + fn start(&self, state: &mut State) -> Result<(), String> { + let engine = state.engine.as_mut().expect("checked by caller"); + engine.reset(); + let mut primed = Vec::with_capacity(CONTENT_DELAY); + let mut hop_out = vec![0.0; HOP]; + let history: Vec = std::iter::repeat_n(0.0, CONTENT_DELAY - state.history.len()) + .chain(state.history.iter().copied()) + .collect(); + for hop in history.as_chunks::().0 { + engine.process_hop(hop, &mut hop_out)?; + primed.extend_from_slice(&hop_out); + } + state.out = primed[MODEL_DELAY..].iter().copied().collect(); + state.pending.clear(); + state.hop_out = hop_out; + state.running = true; + gst::debug!(CAT, imp = self, "started"); + Ok(()) + } + + fn run(&self, state: &mut State, attenuation_limit: f64) -> Result<(), String> { + let engine = state.engine.as_mut().expect("running implies an engine"); + engine.set_attenuation_limit(attenuation_limit); + state.pending.extend_from_slice(&state.mono); + let mut done = 0; + while state.pending.len() - done >= HOP { + engine.process_hop(&state.pending[done..done + HOP], &mut state.hop_out)?; + state.out.extend(state.hop_out.iter().copied()); + done += HOP; + } + state.pending.drain(..done); + Ok(()) + } +} + +fn downmix(samples: &[f32], channels: usize, mono: &mut Vec) { + let channels = channels.max(1); + let scale = 1.0 / channels as f32; + mono.clear(); + mono.extend( + samples + .chunks_exact(channels) + .map(|f| f.iter().sum::() * scale), + ); +} + +fn remember(history: &mut VecDeque, mono: &[f32]) { + history.extend(mono.iter().copied()); + let excess = history.len().saturating_sub(CONTENT_DELAY); + history.drain(..excess); +} + +/// Write the wet signal into every channel, crossfading with the dry signal +/// while `wet` moves toward 1 (`want_wet`) or 0. +fn mix( + samples: &mut [f32], + channels: usize, + out: &mut VecDeque, + wet: &mut f32, + want_wet: bool, +) { + let step = 1.0 / FADE as f32; + for frame in samples.chunks_exact_mut(channels) { + let w = out.pop_front().unwrap_or(0.0); + *wet = if want_wet { + (*wet + step).min(1.0) + } else { + (*wet - step).max(0.0) + }; + let g = *wet; + for s in frame { + *s = *s * (1.0 - g) + w * g; + } + } +} diff --git a/backend/src/gst/voice_isolation/mod.rs b/backend/src/gst/voice_isolation/mod.rs new file mode 100644 index 000000000..3d7020bbf --- /dev/null +++ b/backend/src/gst/voice_isolation/mod.rs @@ -0,0 +1,38 @@ +//! `stromvoiceisolation`: DPDFNet speech enhancement as a GStreamer element. +//! +//! Off, it passes audio through untouched. On, it keeps speech and +//! suppresses everything else (music, fans, typing, knocks, breaths), writing +//! the mono result into every channel 60 ms late. It reports no latency: the +//! pipeline's latency is fixed when the flow starts, and reporting 60 ms would +//! hold back every channel of the mixer, on or off. + +use gstreamer as gst; +use gstreamer::glib; +use gstreamer::prelude::*; + +mod engine; +mod imp; + +pub const ELEMENT_NAME: &str = "stromvoiceisolation"; +/// The rate the model runs at; the element accepts nothing else. +pub const SAMPLE_RATE: u32 = engine::SAMPLE_RATE as u32; +/// How late the audio is while the element is enabled, in samples at SAMPLE_RATE. +pub const CONTENT_DELAY_SAMPLES: usize = imp::CONTENT_DELAY; + +glib::wrapper! { + pub struct VoiceIsolation(ObjectSubclass) + @extends gstreamer_base::BaseTransform, gst::Element, gst::Object; +} + +/// Make the element available to `gst::ElementFactory::make`. +pub fn register() -> Result<(), glib::BoolError> { + gst::Element::register( + None, + ELEMENT_NAME, + gst::Rank::NONE, + VoiceIsolation::static_type(), + ) +} + +#[cfg(test)] +mod tests; diff --git a/backend/src/gst/voice_isolation/tests.rs b/backend/src/gst/voice_isolation/tests.rs new file mode 100644 index 000000000..4e1d20856 --- /dev/null +++ b/backend/src/gst/voice_isolation/tests.rs @@ -0,0 +1,303 @@ +use std::time::{Duration, Instant}; + +use gstreamer as gst; +use gstreamer::prelude::*; +use gstreamer_app as gst_app; + +use super::{register, CONTENT_DELAY_SAMPLES, ELEMENT_NAME, SAMPLE_RATE}; + +const CHANNELS: usize = 2; +const BUF: usize = 480; + +struct Harness { + pipeline: gst::Pipeline, + src: gst_app::AppSrc, + sink: gst_app::AppSink, + element: gst::Element, + pts: gst::ClockTime, +} + +impl Harness { + fn new(enabled: bool) -> Self { + let _ = gst::init(); + let _ = register(); + let caps = gst::Caps::builder("audio/x-raw") + .field("format", "F32LE") + .field("rate", SAMPLE_RATE as i32) + .field("channels", CHANNELS as i32) + .field("layout", "interleaved") + .build(); + let src = gst_app::AppSrc::builder() + .caps(&caps) + .format(gst::Format::Time) + .build(); + let element = gst::ElementFactory::make(ELEMENT_NAME) + .property("enabled", enabled) + .build() + .unwrap(); + let sink = gst_app::AppSink::builder().sync(false).build(); + let pipeline = gst::Pipeline::new(); + pipeline + .add_many([src.upcast_ref(), &element, sink.upcast_ref()]) + .unwrap(); + gst::Element::link_many([src.upcast_ref(), &element, sink.upcast_ref()]).unwrap(); + pipeline.set_state(gst::State::Playing).unwrap(); + Self { + pipeline, + src, + sink, + element, + pts: gst::ClockTime::ZERO, + } + } + + /// Push one buffer of interleaved samples and return what comes out. + fn process(&mut self, samples: &[f32]) -> (Vec, Option) { + let mut bytes = Vec::with_capacity(samples.len() * 4); + for s in samples { + bytes.extend_from_slice(&s.to_le_bytes()); + } + let mut buffer = gst::Buffer::from_mut_slice(bytes); + let duration = gst::ClockTime::from_nseconds( + (samples.len() / CHANNELS) as u64 * 1_000_000_000 / SAMPLE_RATE as u64, + ); + { + let b = buffer.get_mut().unwrap(); + b.set_pts(self.pts); + b.set_duration(duration); + } + self.pts += duration; + self.src.push_buffer(buffer).unwrap(); + let sample = self + .sink + .try_pull_sample(gst::ClockTime::from_seconds(5)) + .expect("element returned no buffer"); + let out = sample.buffer().unwrap(); + let map = out.map_readable().unwrap(); + let samples = map + .as_slice() + .as_chunks::<4>() + .0 + .iter() + .map(|b| f32::from_le_bytes(*b)) + .collect(); + (samples, out.pts()) + } +} + +impl Drop for Harness { + fn drop(&mut self) { + let _ = self.pipeline.set_state(gst::State::Null); + } +} + +/// Deterministic white noise at about -20 dBFS, the same in every channel. +fn noise(state: &mut u32, frames: usize) -> Vec { + let mut out = Vec::with_capacity(frames * CHANNELS); + for _ in 0..frames { + *state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let v = ((*state >> 8) as f32 / (1u32 << 24) as f32 - 0.5) * 0.35; + out.extend(std::iter::repeat_n(v, CHANNELS)); + } + out +} + +fn energy(samples: &[f32]) -> f64 { + samples.iter().map(|s| (*s as f64) * (*s as f64)).sum() +} + +/// Off, the element must leave audio alone for as long as it runs, not only +/// until a model would have finished loading. An enabled element fed the +/// same audio shows when a load would have finished on this host, however +/// slow it is; the check runs until then and one second past it. +#[test] +fn disabled_passes_audio_through_unchanged() { + let mut h = Harness::new(false); + let mut on = Harness::new(true); + let mut rng = 1; + let deadline = Instant::now() + Duration::from_secs(60); + let mut until = None; + let mut i = 0; + while until.is_none_or(|t| Instant::now() < t) { + let input = noise(&mut rng, BUF); + let (output, pts) = h.process(&input); + assert_eq!(output, input, "buffer {i} changed while disabled"); + assert_eq!(pts, Some(gst::ClockTime::from_mseconds(10 * i))); + if until.is_none() && on.process(&input).0 != input { + until = Some(Instant::now() + Duration::from_secs(1)); + } + assert!(Instant::now() < deadline, "the enabled element never ran"); + i += 1; + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// Noise is what the model removes. Once the model has loaded the output +/// must fall at least 20 dB below the input, buffers keep their size and +/// timestamps, and switching off returns the dry signal exactly. +#[test] +fn enabled_suppresses_noise_and_switches_back_cleanly() { + let mut h = Harness::new(true); + let mut rng = 7; + let deadline = Instant::now() + Duration::from_secs(20); + let (mut in_e, mut out_e, mut window) = (0.0, 0.0, 0); + let mut i = 0u64; + loop { + let input = noise(&mut rng, BUF); + let (output, pts) = h.process(&input); + assert_eq!(output.len(), input.len(), "buffer size changed"); + assert_eq!( + pts, + Some(gst::ClockTime::from_mseconds(10 * i)), + "timestamp changed" + ); + i += 1; + in_e += energy(&input); + out_e += energy(&output); + window += 1; + // Judge 0.5 s at a time, so the dry buffers before the model is + // loaded and the crossfade in do not count. + if window == 50 { + let reduction_db = 10.0 * (in_e / out_e.max(1e-20)).log10(); + if reduction_db >= 20.0 { + break; + } + assert!( + Instant::now() < deadline, + "noise only reduced {reduction_db:.1} dB after {i} buffers" + ); + (in_e, out_e, window) = (0.0, 0.0, 0); + } + std::thread::sleep(Duration::from_millis(1)); + } + + h.element.set_property("enabled", false); + // One buffer covers the crossfade back to dry; after that, exact. + let _ = h.process(&noise(&mut rng, BUF)); + for j in 0..20 { + let input = noise(&mut rng, BUF); + let (output, _) = h.process(&input); + assert_eq!( + output, input, + "buffer {j} after disabling is not the dry signal" + ); + } +} + +/// Buffers that are not whole hops must still be answered in full: with no +/// limit on the blend (0 dB) the wet signal is the input itself, so once the +/// crossfade is over every output sample is the input exactly +/// CONTENT_DELAY_SAMPLES earlier. Running short of wet samples would put +/// zeros in, and shift everything after them. +#[test] +fn odd_buffer_sizes_come_back_whole_and_60_ms_late() { + let mut h = Harness::new(true); + h.element.set_property("attenuation-limit", 0.0f64); + let mut rng = 3; + let (mut dry, mut wet) = (Vec::new(), Vec::new()); + // Keep channel 0 of everything in and out, to compare sample by sample. + let mut round = |h: &mut Harness, dry: &mut Vec, wet: &mut Vec| { + for frames in [441, 960, 17, 1024, 480, 1, 479, 481] { + let input = noise(&mut rng, frames); + let (output, _) = h.process(&input); + assert_eq!(output.len(), input.len()); + dry.extend(input.iter().step_by(CHANNELS)); + wet.extend(output.iter().step_by(CHANNELS)); + } + }; + let late_from = |dry: &[f32], wet: &[f32], from: usize| { + (from.max(CONTENT_DELAY_SAMPLES)..wet.len()) + .find(|&n| (wet[n] - dry[n - CONTENT_DELAY_SAMPLES]).abs() >= 1e-4) + }; + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let from = wet.len(); + round(&mut h, &mut dry, &mut wet); + if late_from(&dry, &wet, from).is_none() { + break; + } + assert!( + Instant::now() < deadline, + "output never became the delayed input" + ); + std::thread::sleep(Duration::from_millis(5)); + } + let from = wet.len(); + for _ in 0..20 { + round(&mut h, &mut dry, &mut wet); + } + assert_eq!( + late_from(&dry, &wet, from), + None, + "output is not the input {CONTENT_DELAY_SAMPLES} samples late" + ); +} + +/// With the model loaded and running, dropping the pipeline must finalize the +/// element: nothing (the loader thread included) may keep it alive. +#[test] +fn element_is_finalized_after_running() { + let mut h = Harness::new(true); + let mut rng = 11; + let deadline = Instant::now() + Duration::from_secs(20); + loop { + let input = noise(&mut rng, BUF); + if h.process(&input).0 != input { + break; + } + assert!(Instant::now() < deadline, "the model never ran"); + std::thread::sleep(Duration::from_millis(1)); + } + let element = h.element.downgrade(); + let pipeline = h.pipeline.downgrade(); + drop(h); + assert!( + pipeline.upgrade().is_none(), + "pipeline still alive after drop" + ); + assert!( + element.upgrade().is_none(), + "voice isolation element still alive after drop" + ); +} + +/// `Engine::reset` must forget everything, so a reset engine answers the +/// same audio exactly as a fresh one. tract's GRUs keep their final hidden +/// state between runs of one session, so a session reused across hops carries +/// each frame's GRU state into the next, and past a reset. +#[test] +fn reset_engine_matches_a_fresh_one() { + use super::engine::{Engine, HOP}; + + let mono = |rng: &mut u32, hops: usize| -> Vec { + noise(rng, hops * HOP) + .into_iter() + .step_by(CHANNELS) + .collect() + }; + let run = |e: &mut Engine, input: &[f32]| -> Vec { + let mut out = vec![0.0; input.len()]; + for (i, o) in input.chunks(HOP).zip(out.chunks_mut(HOP)) { + e.process_hop(i, o).unwrap(); + } + out + }; + let probe = mono(&mut 5, 50); + + let fresh = run(&mut Engine::load().unwrap(), &probe); + + let mut e = Engine::load().unwrap(); + run(&mut e, &mono(&mut 9, 50)); + e.reset(); + let after_reset = run(&mut e, &probe); + + let diff = fresh + .iter() + .zip(&after_reset) + .map(|(a, b)| (a - b).abs()) + .fold(0.0f32, f32::max); + assert!( + diff < 1e-6 && energy(&fresh) > 0.0, + "a reset engine differs from a fresh one by up to {diff}" + ); +} diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 3c9bbb5f0..345777ca0 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -49,6 +49,7 @@ Make sure you have the following installed: |---------|-------------|--------------------| | `nvidia` | NVIDIA GPU monitoring (default) | None | | `efp` | EFP/SRT input and output blocks | `cmake` | +| `voice-isolation` | Per-channel voice isolation in the mixer (default). `build.rs` downloads the 10.6 MB model with `curl` and embeds it; set `STROM_VOICE_ISOLATION_MODEL` to a local copy for offline builds, or build without default features to leave it out | `curl` and network access, or a local model file | | `no-gui` | Build without the native GUI (server only; used by the Docker image) | None | ```bash diff --git a/frontend/src/mixer/api.rs b/frontend/src/mixer/api.rs index a93d79bd2..b3695150c 100644 --- a/frontend/src/mixer/api.rs +++ b/frontend/src/mixer/api.rs @@ -93,6 +93,14 @@ impl MixerEditor { format!("ch{}_hpf_freq", ch1), PropertyValue::Float(channel.hpf_freq as f64), ), + ("voice", "enabled") => ( + format!("ch{}_voice_isolation", ch1), + PropertyValue::Bool(channel.voice_isolation), + ), + ("voice", "limit") => ( + format!("ch{}_voice_isolation_limit", ch1), + PropertyValue::Float(channel.voice_isolation_limit as f64), + ), ("gate", "threshold") => ( format!("ch{}_gate_threshold", ch1), PropertyValue::Float(channel.gate_threshold as f64), diff --git a/frontend/src/mixer/detail.rs b/frontend/src/mixer/detail.rs index b89166667..9d8e9dee9 100644 --- a/frontend/src/mixer/detail.rs +++ b/frontend/src/mixer/detail.rs @@ -93,11 +93,12 @@ impl MixerEditor { ui.add_space(8.0); egui::Grid::new(format!("ch_processing_{}", index)) - .num_columns(5) + .num_columns(6) .spacing([8.0, 0.0]) .show(ui, |ui| { self.render_gain_section(ui, ctx, index); self.render_hpf_section(ui, ctx, index); + self.render_voice_isolation_section(ui, ctx, index); self.render_gate_section(ui, ctx, index); self.render_comp_section(ui, ctx, index); self.render_eq_section(ui, ctx, index); @@ -517,6 +518,64 @@ impl MixerEditor { }); } + pub(super) fn render_voice_isolation_section( + &mut self, + ui: &mut Ui, + ctx: &Context, + index: usize, + ) { + let color = Color32::from_rgb(60, 140, 170); + let enabled = self.channels[index].voice_isolation; + + section_frame(color, enabled).show(ui, |ui| { + ui.vertical(|ui| { + ui.set_min_height(SECTION_MIN_HEIGHT); + // Keeps speech and suppresses music, fans, typing and other + // background sound; delays the channel 60 ms while on. + if section_toggle(ui, "Voice", color, enabled) { + self.channels[index].voice_isolation = !self.channels[index].voice_isolation; + self.update_processing_param(ctx, index, "voice", "enabled"); + } + + ui.add_space(4.0); + if !enabled { + ui.disable(); + } + + ui.horizontal(|ui| { + ui.label("Max cut:"); + let limit = &mut self.channels[index].voice_isolation_limit; + let none = *limit >= VOICE_ISOLATION_NO_LIMIT_DB; + if ui + .add( + egui::DragValue::new(limit) + .range(6.0..=VOICE_ISOLATION_NO_LIMIT_DB) + .suffix(if none { " dB (none)" } else { " dB" }) + .speed(1.0) + .fixed_decimals(0), + ) + .on_hover_text("Most it may reduce any frequency; 100 dB means no limit") + .changed() + { + self.update_processing_param(ctx, index, "voice", "limit"); + } + }); + + ui.add_space(4.0); + if ui + .small_button(egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE) + .on_hover_text("Reset") + .clicked() + { + self.channels[index].voice_isolation = false; + self.channels[index].voice_isolation_limit = VOICE_ISOLATION_NO_LIMIT_DB; + self.update_processing_param(ctx, index, "voice", "enabled"); + self.update_processing_param(ctx, index, "voice", "limit"); + } + }); + }); + } + pub(super) fn render_gate_section(&mut self, ui: &mut Ui, ctx: &Context, index: usize) { let color = Color32::from_rgb(0, 150, 0); let enabled = self.channels[index].gate_enabled; diff --git a/frontend/src/mixer/mod.rs b/frontend/src/mixer/mod.rs index 93453002f..10dd70d4b 100644 --- a/frontend/src/mixer/mod.rs +++ b/frontend/src/mixer/mod.rs @@ -80,6 +80,10 @@ struct ChannelStrip { hpf_enabled: bool, /// HPF cutoff frequency (Hz) hpf_freq: f32, + /// Voice isolation enabled + voice_isolation: bool, + /// Voice isolation attenuation limit (dB, VOICE_ISOLATION_NO_LIMIT_DB = none) + voice_isolation_limit: f32, /// Gate enabled gate_enabled: bool, /// Gate threshold (dB) @@ -151,6 +155,8 @@ impl ChannelStrip { aux_pre: DEFAULT_AUX_PRE, hpf_enabled: false, hpf_freq: DEFAULT_HPF_FREQ, + voice_isolation: false, + voice_isolation_limit: VOICE_ISOLATION_NO_LIMIT_DB, gate_enabled: false, gate_threshold: DEFAULT_GATE_THRESHOLD, gate_attack: DEFAULT_GATE_ATTACK, diff --git a/frontend/src/mixer/state.rs b/frontend/src/mixer/state.rs index c8a7790fc..beb5eb6c0 100644 --- a/frontend/src/mixer/state.rs +++ b/frontend/src/mixer/state.rs @@ -234,6 +234,17 @@ impl MixerEditor { { ch.hpf_freq = *f as f32; } + // Voice isolation + if let Some(PropertyValue::Bool(b)) = + properties.get(&format!("ch{}_voice_isolation", ch_num)) + { + ch.voice_isolation = *b; + } + if let Some(PropertyValue::Float(f)) = + properties.get(&format!("ch{}_voice_isolation_limit", ch_num)) + { + ch.voice_isolation_limit = *f as f32; + } // Gate if let Some(PropertyValue::Bool(b)) = properties.get(&format!("ch{}_gate_enabled", ch_num)) @@ -470,6 +481,17 @@ impl MixerEditor { // HPF set_b!(format!("ch{}_hpf_enabled", n), ch.hpf_enabled, false); set_f!(format!("ch{}_hpf_freq", n), ch.hpf_freq, DEFAULT_HPF_FREQ); + // Voice isolation + set_b!( + format!("ch{}_voice_isolation", n), + ch.voice_isolation, + false + ); + set_f!( + format!("ch{}_voice_isolation_limit", n), + ch.voice_isolation_limit, + VOICE_ISOLATION_NO_LIMIT_DB + ); // Gate set_b!(format!("ch{}_gate_enabled", n), ch.gate_enabled, false); set_f!( @@ -581,6 +603,8 @@ impl MixerEditor { ch.aux_pre = DEFAULT_AUX_PRE; ch.hpf_enabled = false; ch.hpf_freq = DEFAULT_HPF_FREQ; + ch.voice_isolation = false; + ch.voice_isolation_limit = VOICE_ISOLATION_NO_LIMIT_DB; ch.gate_enabled = false; ch.gate_threshold = DEFAULT_GATE_THRESHOLD; ch.gate_attack = DEFAULT_GATE_ATTACK; diff --git a/types/src/mixer.rs b/types/src/mixer.rs index 6191d58a8..48d8c5c55 100644 --- a/types/src/mixer.rs +++ b/types/src/mixer.rs @@ -10,6 +10,10 @@ pub const DEFAULT_PAN: f32 = 0.0; // HPF pub const DEFAULT_HPF_FREQ: f32 = 80.0; +// Voice isolation +/// An attenuation limit at or above this means no limit. +pub const VOICE_ISOLATION_NO_LIMIT_DB: f32 = 100.0; + // Gate pub const DEFAULT_GATE_THRESHOLD: f32 = -40.0; pub const DEFAULT_GATE_ATTACK: f32 = 5.0;