BlueGit

ict rusty-teams

feat(calling): DeepFilterNet3 mic noise removal, AGC after it, Opus 40 kbps fullband

- DeepFilterNet3 (vendored libDF, ported to tract 0.23, warm-up against dropped first sentence) replaces RNNoise
- software mic chain: high-pass + AEC3 -> DeepFilterNet -> AGC2 with +6 dB fixed gain and limiter, speech near -16 dBFS like Teams
- Low keeps WebRTC noise suppression, Auto uses DeepFilterNet only
- Opus fmtp asks libwebrtc for maxaveragebitrate=40000 and maxplaybackrate=48000
- CALLING_AUDIO_DUMP=<dir> writes one WAV per mic stage; mic_chain_wav example runs a WAV through the chain

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-15 · 6 weeks ago

Hash
150972e0fac4b1bc6d54d3894eb68678e9b3a030
Parent
7e021686
17 files changed +2495 −111
Cargo.lock +89 −41
@@ -421,12 +421,6 @@ dependencies = [
421 421 "syn 2.0.119",
422 422 ]
423 423
424 [[package]]
425 name = "array-init"
426 version = "2.1.0"
427 source = "registry+https://github.com/rust-lang/crates.io-index"
428 checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
429
430 424 [[package]]
431 425 name = "arraydeque"
432 426 version = "0.5.1"
@@ -1202,15 +1196,17 @@ dependencies = [
1202 1196 "chatsvc",
1203 1197 "chrono",
1204 1198 "cpal",
1199 "deep_filter",
1205 1200 "flate2",
1206 1201 "futures-util",
1207 1202 "image",
1208 1203 "libwebrtc",
1209 "nnnoiseless",
1204 "ndarray",
1210 1205 "nokhwa",
1211 1206 "serde",
1212 1207 "serde_json",
1213 1208 "session",
1209 "tempfile",
1214 1210 "thiserror 2.0.21",
1215 1211 "tokio",
1216 1212 "tract-onnx",
@@ -2164,6 +2160,26 @@ version = "0.3.2"
2164 2160 source = "registry+https://github.com/rust-lang/crates.io-index"
2165 2161 checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
2166 2162
2163 [[package]]
2164 name = "deep_filter"
2165 version = "0.5.7-pre"
2166 dependencies = [
2167 "anyhow",
2168 "flate2",
2169 "itertools 0.12.1",
2170 "log",
2171 "ndarray",
2172 "num-complex",
2173 "realfft",
2174 "rust-ini",
2175 "rustfft",
2176 "tar",
2177 "tract-core",
2178 "tract-hir",
2179 "tract-onnx",
2180 "tract-pulse",
2181 ]
2182
2167 2183 [[package]]
2168 2184 name = "deranged"
2169 2185 version = "0.5.8"
@@ -2326,6 +2342,15 @@ dependencies = [
2326 2342 "libloading 0.8.9",
2327 2343 ]
2328 2344
2345 [[package]]
2346 name = "dlv-list"
2347 version = "0.5.2"
2348 source = "registry+https://github.com/rust-lang/crates.io-index"
2349 checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"
2350 dependencies = [
2351 "const-random",
2352 ]
2353
2329 2354 [[package]]
2330 2355 name = "document-features"
2331 2356 version = "0.2.12"
@@ -2398,19 +2423,6 @@ version = "1.0.0"
2398 2423 source = "registry+https://github.com/rust-lang/crates.io-index"
2399 2424 checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e"
2400 2425
2401 [[package]]
2402 name = "easyfft"
2403 version = "0.4.2"
2404 source = "registry+https://github.com/rust-lang/crates.io-index"
2405 checksum = "767e39eef2ad8a3b6f1d733be3ec70364d21d437d06d4f18ea76ce08df20b75f"
2406 dependencies = [
2407 "array-init",
2408 "generic_singleton",
2409 "num-complex",
2410 "realfft",
2411 "rustfft",
2412 ]
2413
2414 2426 [[package]]
2415 2427 name = "ego-tree"
2416 2428 version = "0.10.0"
@@ -3109,16 +3121,6 @@ dependencies = [
3109 3121 "version_check",
3110 3122 ]
3111 3123
3112 [[package]]
3113 name = "generic_singleton"
3114 version = "0.5.3"
3115 source = "registry+https://github.com/rust-lang/crates.io-index"
3116 checksum = "ab6e923c8e978e57cf63e2e200ca967d1d20f0ea2662b28f6d4e11c44aa6ab16"
3117 dependencies = [
3118 "anymap3",
3119 "parking_lot",
3120 ]
3121
3122 3124 [[package]]
3123 3125 name = "gethostname"
3124 3126 version = "1.1.0"
@@ -4070,6 +4072,8 @@ dependencies = [
4070 4072 [[package]]
4071 4073 name = "gpui-pre-windows"
4072 4074 version = "0.3.8"
4075 source = "registry+https://github.com/rust-lang/crates.io-index"
4076 checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"
4073 4077 dependencies = [
4074 4078 "accesskit",
4075 4079 "accesskit_windows",
@@ -4832,6 +4836,15 @@ dependencies = [
4832 4836 "either",
4833 4837 ]
4834 4838
4839 [[package]]
4840 name = "itertools"
4841 version = "0.12.1"
4842 source = "registry+https://github.com/rust-lang/crates.io-index"
4843 checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
4844 dependencies = [
4845 "either",
4846 ]
4847
4835 4848 [[package]]
4836 4849 name = "itertools"
4837 4850 version = "0.13.0"
@@ -5740,16 +5753,6 @@ version = "1.0.6"
5740 5753 source = "registry+https://github.com/rust-lang/crates.io-index"
5741 5754 checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
5742 5755
5743 [[package]]
5744 name = "nnnoiseless"
5745 version = "0.5.2"
5746 source = "registry+https://github.com/rust-lang/crates.io-index"
5747 checksum = "805d5964d1e7a0006a7fdced7dae75084d66d18b35f1dfe81bd76929b1f8da0c"
5748 dependencies = [
5749 "easyfft",
5750 "once_cell",
5751 ]
5752
5753 5756 [[package]]
5754 5757 name = "no_std_io2"
5755 5758 version = "0.9.4"
@@ -5982,7 +5985,6 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
5982 5985 dependencies = [
5983 5986 "bytemuck",
5984 5987 "num-traits",
5985 "serde",
5986 5988 ]
5987 5989
5988 5990 [[package]]
@@ -6561,6 +6563,16 @@ dependencies = [
6561 6563 "num-traits",
6562 6564 ]
6563 6565
6566 [[package]]
6567 name = "ordered-multimap"
6568 version = "0.7.3"
6569 source = "registry+https://github.com/rust-lang/crates.io-index"
6570 checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"
6571 dependencies = [
6572 "dlv-list",
6573 "hashbrown 0.14.5",
6574 ]
6575
6564 6576 [[package]]
6565 6577 name = "ordered-stream"
6566 6578 version = "0.2.0"
@@ -7914,6 +7926,16 @@ dependencies = [
7914 7926 "triomphe",
7915 7927 ]
7916 7928
7929 [[package]]
7930 name = "rust-ini"
7931 version = "0.21.3"
7932 source = "registry+https://github.com/rust-lang/crates.io-index"
7933 checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"
7934 dependencies = [
7935 "cfg-if 1.0.5",
7936 "ordered-multimap",
7937 ]
7938
7917 7939 [[package]]
7918 7940 name = "rustc-demangle"
7919 7941 version = "0.1.28"
@@ -9776,6 +9798,32 @@ dependencies = [
9776 9798 "tract-nnef",
9777 9799 ]
9778 9800
9801 [[package]]
9802 name = "tract-pulse"
9803 version = "0.23.8"
9804 source = "registry+https://github.com/rust-lang/crates.io-index"
9805 checksum = "55022cad5e575b1bb2f1b7eaaa42837828de2c975167eb450eb11b68307dbe5b"
9806 dependencies = [
9807 "downcast-rs 2.0.2",
9808 "erased-serde",
9809 "lazy_static",
9810 "log",
9811 "serde",
9812 "tract-pulse-opl",
9813 "tract-transformers",
9814 ]
9815
9816 [[package]]
9817 name = "tract-pulse-opl"
9818 version = "0.23.8"
9819 source = "registry+https://github.com/rust-lang/crates.io-index"
9820 checksum = "17fb7c893409929cffc5fa72d09ff9d035c33b7ac98481c5e7fded58322e4f30"
9821 dependencies = [
9822 "downcast-rs 2.0.2",
9823 "lazy_static",
9824 "tract-nnef",
9825 ]
9826
9779 9827 [[package]]
9780 9828 name = "tract-transformers"
9781 9829 version = "0.23.8"
@@ -421,12 +421,6 @@ dependencies = [
421 "syn 2.0.119",
421 "syn 2.0.119",
422]
422]
423
423
424[[package]]
425name = "array-init"
426version = "2.1.0"
427source = "registry+https://github.com/rust-lang/crates.io-index"
428checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc"
429
430[[package]]
424[[package]]
431name = "arraydeque"
425name = "arraydeque"
432version = "0.5.1"
426version = "0.5.1"
@@ -1202,15 +1196,17 @@ dependencies = [
1202 "chatsvc",
1196 "chatsvc",
1203 "chrono",
1197 "chrono",
1204 "cpal",
1198 "cpal",
1199 "deep_filter",
1205 "flate2",
1200 "flate2",
1206 "futures-util",
1201 "futures-util",
1207 "image",
1202 "image",
1208 "libwebrtc",
1203 "libwebrtc",
1209 "nnnoiseless",
1204 "ndarray",
1210 "nokhwa",
1205 "nokhwa",
1211 "serde",
1206 "serde",
1212 "serde_json",
1207 "serde_json",
1213 "session",
1208 "session",
1209 "tempfile",
1214 "thiserror 2.0.21",
1210 "thiserror 2.0.21",
1215 "tokio",
1211 "tokio",
1216 "tract-onnx",
1212 "tract-onnx",
@@ -2164,6 +2160,26 @@ version = "0.3.2"
2164source = "registry+https://github.com/rust-lang/crates.io-index"
2160source = "registry+https://github.com/rust-lang/crates.io-index"
2165checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
2161checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
2166
2162
2163[[package]]
2164name = "deep_filter"
2165version = "0.5.7-pre"
2166dependencies = [
2167 "anyhow",
2168 "flate2",
2169 "itertools 0.12.1",
2170 "log",
2171 "ndarray",
2172 "num-complex",
2173 "realfft",
2174 "rust-ini",
2175 "rustfft",
2176 "tar",
2177 "tract-core",
2178 "tract-hir",
2179 "tract-onnx",
2180 "tract-pulse",
2181]
2182
2167[[package]]
2183[[package]]
2168name = "deranged"
2184name = "deranged"
2169version = "0.5.8"
2185version = "0.5.8"
@@ -2326,6 +2342,15 @@ dependencies = [
2326 "libloading 0.8.9",
2342 "libloading 0.8.9",
2327]
2343]
2328
2344
2345[[package]]
2346name = "dlv-list"
2347version = "0.5.2"
2348source = "registry+https://github.com/rust-lang/crates.io-index"
2349checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"
2350dependencies = [
2351 "const-random",
2352]
2353
2329[[package]]
2354[[package]]
2330name = "document-features"
2355name = "document-features"
2331version = "0.2.12"
2356version = "0.2.12"
@@ -2398,19 +2423,6 @@ version = "1.0.0"
2398source = "registry+https://github.com/rust-lang/crates.io-index"
2423source = "registry+https://github.com/rust-lang/crates.io-index"
2399checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e"
2424checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e"
2400
2425
2401[[package]]
2402name = "easyfft"
2403version = "0.4.2"
2404source = "registry+https://github.com/rust-lang/crates.io-index"
2405checksum = "767e39eef2ad8a3b6f1d733be3ec70364d21d437d06d4f18ea76ce08df20b75f"
2406dependencies = [
2407 "array-init",
2408 "generic_singleton",
2409 "num-complex",
2410 "realfft",
2411 "rustfft",
2412]
2413
2414[[package]]
2426[[package]]
2415name = "ego-tree"
2427name = "ego-tree"
2416version = "0.10.0"
2428version = "0.10.0"
@@ -3109,16 +3121,6 @@ dependencies = [
3109 "version_check",
3121 "version_check",
3110]
3122]
3111
3123
3112[[package]]
3113name = "generic_singleton"
3114version = "0.5.3"
3115source = "registry+https://github.com/rust-lang/crates.io-index"
3116checksum = "ab6e923c8e978e57cf63e2e200ca967d1d20f0ea2662b28f6d4e11c44aa6ab16"
3117dependencies = [
3118 "anymap3",
3119 "parking_lot",
3120]
3121
3122[[package]]
3124[[package]]
3123name = "gethostname"
3125name = "gethostname"
3124version = "1.1.0"
3126version = "1.1.0"
@@ -4070,6 +4072,8 @@ dependencies = [
4070[[package]]
4072[[package]]
4071name = "gpui-pre-windows"
4073name = "gpui-pre-windows"
4072version = "0.3.8"
4074version = "0.3.8"
4075source = "registry+https://github.com/rust-lang/crates.io-index"
4076checksum = "371f9bb13f97e3bea2f8b8e5e81232bb74d735153c244ae67f7400e743925b1c"
4073dependencies = [
4077dependencies = [
4074 "accesskit",
4078 "accesskit",
4075 "accesskit_windows",
4079 "accesskit_windows",
@@ -4832,6 +4836,15 @@ dependencies = [
4832 "either",
4836 "either",
4833]
4837]
4834
4838
4839[[package]]
4840name = "itertools"
4841version = "0.12.1"
4842source = "registry+https://github.com/rust-lang/crates.io-index"
4843checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
4844dependencies = [
4845 "either",
4846]
4847
4835[[package]]
4848[[package]]
4836name = "itertools"
4849name = "itertools"
4837version = "0.13.0"
4850version = "0.13.0"
@@ -5740,16 +5753,6 @@ version = "1.0.6"
5740source = "registry+https://github.com/rust-lang/crates.io-index"
5753source = "registry+https://github.com/rust-lang/crates.io-index"
5741checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
5754checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
5742
5755
5743[[package]]
5744name = "nnnoiseless"
5745version = "0.5.2"
5746source = "registry+https://github.com/rust-lang/crates.io-index"
5747checksum = "805d5964d1e7a0006a7fdced7dae75084d66d18b35f1dfe81bd76929b1f8da0c"
5748dependencies = [
5749 "easyfft",
5750 "once_cell",
5751]
5752
5753[[package]]
5756[[package]]
5754name = "no_std_io2"
5757name = "no_std_io2"
5755version = "0.9.4"
5758version = "0.9.4"
@@ -5982,7 +5985,6 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
5982dependencies = [
5985dependencies = [
5983 "bytemuck",
5986 "bytemuck",
5984 "num-traits",
5987 "num-traits",
5985 "serde",
5986]
5988]
5987
5989
5988[[package]]
5990[[package]]
@@ -6561,6 +6563,16 @@ dependencies = [
6561 "num-traits",
6563 "num-traits",
6562]
6564]
6563
6565
6566[[package]]
6567name = "ordered-multimap"
6568version = "0.7.3"
6569source = "registry+https://github.com/rust-lang/crates.io-index"
6570checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"
6571dependencies = [
6572 "dlv-list",
6573 "hashbrown 0.14.5",
6574]
6575
6564[[package]]
6576[[package]]
6565name = "ordered-stream"
6577name = "ordered-stream"
6566version = "0.2.0"
6578version = "0.2.0"
@@ -7914,6 +7926,16 @@ dependencies = [
7914 "triomphe",
7926 "triomphe",
7915]
7927]
7916
7928
7929[[package]]
7930name = "rust-ini"
7931version = "0.21.3"
7932source = "registry+https://github.com/rust-lang/crates.io-index"
7933checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"
7934dependencies = [
7935 "cfg-if 1.0.5",
7936 "ordered-multimap",
7937]
7938
7917[[package]]
7939[[package]]
7918name = "rustc-demangle"
7940name = "rustc-demangle"
7919version = "0.1.28"
7941version = "0.1.28"
@@ -9776,6 +9798,32 @@ dependencies = [
9776 "tract-nnef",
9798 "tract-nnef",
9777]
9799]
9778
9800
9801[[package]]
9802name = "tract-pulse"
9803version = "0.23.8"
9804source = "registry+https://github.com/rust-lang/crates.io-index"
9805checksum = "55022cad5e575b1bb2f1b7eaaa42837828de2c975167eb450eb11b68307dbe5b"
9806dependencies = [
9807 "downcast-rs 2.0.2",
9808 "erased-serde",
9809 "lazy_static",
9810 "log",
9811 "serde",
9812 "tract-pulse-opl",
9813 "tract-transformers",
9814]
9815
9816[[package]]
9817name = "tract-pulse-opl"
9818version = "0.23.8"
9819source = "registry+https://github.com/rust-lang/crates.io-index"
9820checksum = "17fb7c893409929cffc5fa72d09ff9d035c33b7ac98481c5e7fded58322e4f30"
9821dependencies = [
9822 "downcast-rs 2.0.2",
9823 "lazy_static",
9824 "tract-nnef",
9825]
9826
9779[[package]]
9827[[package]]
9780name = "tract-transformers"
9828name = "tract-transformers"
9781version = "0.23.8"
9829version = "0.23.8"
crates/calling/Cargo.toml +5 −1
@@ -14,7 +14,8 @@ flate2 = "1"
14 14 image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
15 15 futures-util.workspace = true
16 16 libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }
17 nnnoiseless = { version = "0.5", default-features = false }
17 deep_filter = { path = "../../vendor/deep_filter" }
18 ndarray = "0.17"
18 19 nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
19 20 serde.workspace = true
20 21 webrtc-sys = "=0.3.48"
@@ -40,3 +41,6 @@ windows-core = "0.62"
40 41
41 42 [target.'cfg(windows)'.dev-dependencies]
42 43 webview.workspace = true
44
45 [dev-dependencies]
46 tempfile.workspace = true
@@ -14,7 +14,8 @@ flate2 = "1"
14image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
14image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
15futures-util.workspace = true
15futures-util.workspace = true
16libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }
16libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }
17nnnoiseless = { version = "0.5", default-features = false }
17deep_filter = { path = "../../vendor/deep_filter" }
18ndarray = "0.17"
18nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
19nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
19serde.workspace = true
20serde.workspace = true
20webrtc-sys = "=0.3.48"
21webrtc-sys = "=0.3.48"
@@ -40,3 +41,6 @@ windows-core = "0.62"
40
41
41[target.'cfg(windows)'.dev-dependencies]
42[target.'cfg(windows)'.dev-dependencies]
42webview.workspace = true
43webview.workspace = true
44
45[dev-dependencies]
46tempfile.workspace = true
crates/calling/examples/mic_chain_wav.rs added +32 −0
@@ -0,0 +1,32 @@
1 //! Runs a 48 kHz mono 16-bit WAV through the mic chain and writes every stage next to it.
2 //! Usage: cargo run -p calling --release --example mic_chain_wav -- <input.wav> <output-dir> [auto|low|off]
3
4 use calling::audio::{ClipGenerator, FRAME_SAMPLES};
5 use calling::mic_chain::MicChain;
6 use calling::wav_dump::StageDumps;
7 use calling::{MicSettings, NoiseSuppression};
8
9 fn main() {
10 let mut arguments = std::env::args().skip(1);
11 let (Some(input), Some(output)) = (arguments.next(), arguments.next()) else {
12 eprintln!("usage: mic_chain_wav <input.wav> <output-dir> [auto|low|off]");
13 std::process::exit(2);
14 };
15 let level = arguments.next().and_then(|key| NoiseSuppression::from_key(&key)).unwrap_or_default();
16 let bytes = std::fs::read(&input).expect("read input");
17 let mut clip = ClipGenerator::from_wav(&bytes).expect("48 kHz mono 16-bit WAV");
18 let frames = bytes.len().saturating_sub(44) / 2 / FRAME_SAMPLES;
19 let settings = MicSettings { noise_suppression: level, music_mode: false };
20 let dumps = StageDumps::create(std::path::Path::new(&output)).expect("create output dir");
21 let mut chain = MicChain::new(settings.apm_config(), settings.ml_noise_suppression(), Some(dumps));
22 let waiting = std::time::Instant::now();
23 while settings.ml_noise_suppression() && !calling::noise_stage::is_ready() && waiting.elapsed().as_secs() < 30 {
24 std::thread::sleep(std::time::Duration::from_millis(20));
25 }
26 let started = std::time::Instant::now();
27 for _ in 0..frames {
28 let mut frame = clip.next_frame();
29 chain.process(&mut frame);
30 }
31 eprintln!("{frames} frames in {:?}", started.elapsed());
32 }
@@ -0,0 +1,32 @@
1//! Runs a 48 kHz mono 16-bit WAV through the mic chain and writes every stage next to it.
2//! Usage: cargo run -p calling --release --example mic_chain_wav -- <input.wav> <output-dir> [auto|low|off]
3
4use calling::audio::{ClipGenerator, FRAME_SAMPLES};
5use calling::mic_chain::MicChain;
6use calling::wav_dump::StageDumps;
7use calling::{MicSettings, NoiseSuppression};
8
9fn main() {
10 let mut arguments = std::env::args().skip(1);
11 let (Some(input), Some(output)) = (arguments.next(), arguments.next()) else {
12 eprintln!("usage: mic_chain_wav <input.wav> <output-dir> [auto|low|off]");
13 std::process::exit(2);
14 };
15 let level = arguments.next().and_then(|key| NoiseSuppression::from_key(&key)).unwrap_or_default();
16 let bytes = std::fs::read(&input).expect("read input");
17 let mut clip = ClipGenerator::from_wav(&bytes).expect("48 kHz mono 16-bit WAV");
18 let frames = bytes.len().saturating_sub(44) / 2 / FRAME_SAMPLES;
19 let settings = MicSettings { noise_suppression: level, music_mode: false };
20 let dumps = StageDumps::create(std::path::Path::new(&output)).expect("create output dir");
21 let mut chain = MicChain::new(settings.apm_config(), settings.ml_noise_suppression(), Some(dumps));
22 let waiting = std::time::Instant::now();
23 while settings.ml_noise_suppression() && !calling::noise_stage::is_ready() && waiting.elapsed().as_secs() < 30 {
24 std::thread::sleep(std::time::Duration::from_millis(20));
25 }
26 let started = std::time::Instant::now();
27 for _ in 0..frames {
28 let mut frame = clip.next_frame();
29 chain.process(&mut frame);
30 }
31 eprintln!("{frames} frames in {:?}", started.elapsed());
32}
crates/calling/src/lib.rs +2 −0
@@ -32,7 +32,9 @@ pub mod meeting;
32 32 pub mod meeting_options;
33 33 pub mod mic_processing;
34 34 pub mod mixer;
35 pub mod mic_chain;
35 36 pub mod noise_stage;
37 pub mod wav_dump;
36 38 pub mod mute;
37 39 pub mod organizer;
38 40 pub mod pcm;
@@ -32,7 +32,9 @@ pub mod meeting;
32pub mod meeting_options;
32pub mod meeting_options;
33pub mod mic_processing;
33pub mod mic_processing;
34pub mod mixer;
34pub mod mixer;
35pub mod mic_chain;
35pub mod noise_stage;
36pub mod noise_stage;
37pub mod wav_dump;
36pub mod mute;
38pub mod mute;
37pub mod organizer;
39pub mod organizer;
38pub mod pcm;
40pub mod pcm;
crates/calling/src/mic_chain.rs added +74 −0
@@ -0,0 +1,74 @@
1 use libwebrtc::native::apm::AudioProcessingModule;
2
3 use crate::audio::SAMPLE_RATE;
4 use crate::mic_processing::ApmConfig;
5 use crate::noise_stage::NoiseStage;
6 use crate::wav_dump::StageDumps;
7
8 /// High-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.
9 pub struct MicChain {
10 front: Option<AudioProcessingModule>,
11 ml_noise: Option<NoiseStage>,
12 gain: Option<AudioProcessingModule>,
13 dumps: Option<StageDumps>,
14 }
15
16 impl MicChain {
17 pub fn new(processing: ApmConfig, ml_noise: bool, dumps: Option<StageDumps>) -> MicChain {
18 if ml_noise {
19 crate::noise_stage::prepare();
20 }
21 MicChain {
22 front: processing.front_module(),
23 ml_noise: ml_noise.then(NoiseStage::new),
24 gain: processing.gain_module(),
25 dumps,
26 }
27 }
28
29 pub fn process_far_end(&mut self, frame: &mut [i16]) {
30 if let Some(front) = self.front.as_mut() {
31 let _ = front.process_reverse_stream(frame, SAMPLE_RATE as i32, 1);
32 }
33 }
34
35 pub fn process(&mut self, frame: &mut [i16]) {
36 self.dump(0, frame);
37 if let Some(front) = self.front.as_mut() {
38 let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);
39 }
40 self.dump(1, frame);
41 if let Some(noise_stage) = self.ml_noise.as_mut() {
42 noise_stage.process_pcm(0, frame);
43 }
44 self.dump(2, frame);
45 if let Some(gain) = self.gain.as_mut() {
46 let _ = gain.process_stream(frame, SAMPLE_RATE as i32, 1);
47 }
48 self.dump(3, frame);
49 }
50
51 fn dump(&mut self, stage_index: usize, frame: &[i16]) {
52 if let Some(dumps) = self.dumps.as_mut() {
53 dumps.write(stage_index, frame);
54 }
55 }
56 }
57
58 #[cfg(test)]
59 mod tests {
60 use super::*;
61 use crate::audio::SineGenerator;
62 use crate::mic_processing::MicSettings;
63
64 #[test]
65 fn off_leaves_the_frame_untouched() {
66 let off = MicSettings { noise_suppression: crate::mic_processing::NoiseSuppression::Off, music_mode: false };
67 let mut chain = MicChain::new(off.apm_config(), off.ml_noise_suppression(), None);
68 let mut generator = SineGenerator::new(300.0, 0.2);
69 let original = generator.next_frame();
70 let mut frame = original.clone();
71 chain.process(&mut frame);
72 assert_eq!(frame, original);
73 }
74 }
@@ -0,0 +1,74 @@
1use libwebrtc::native::apm::AudioProcessingModule;
2
3use crate::audio::SAMPLE_RATE;
4use crate::mic_processing::ApmConfig;
5use crate::noise_stage::NoiseStage;
6use crate::wav_dump::StageDumps;
7
8/// High-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.
9pub struct MicChain {
10 front: Option<AudioProcessingModule>,
11 ml_noise: Option<NoiseStage>,
12 gain: Option<AudioProcessingModule>,
13 dumps: Option<StageDumps>,
14}
15
16impl MicChain {
17 pub fn new(processing: ApmConfig, ml_noise: bool, dumps: Option<StageDumps>) -> MicChain {
18 if ml_noise {
19 crate::noise_stage::prepare();
20 }
21 MicChain {
22 front: processing.front_module(),
23 ml_noise: ml_noise.then(NoiseStage::new),
24 gain: processing.gain_module(),
25 dumps,
26 }
27 }
28
29 pub fn process_far_end(&mut self, frame: &mut [i16]) {
30 if let Some(front) = self.front.as_mut() {
31 let _ = front.process_reverse_stream(frame, SAMPLE_RATE as i32, 1);
32 }
33 }
34
35 pub fn process(&mut self, frame: &mut [i16]) {
36 self.dump(0, frame);
37 if let Some(front) = self.front.as_mut() {
38 let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);
39 }
40 self.dump(1, frame);
41 if let Some(noise_stage) = self.ml_noise.as_mut() {
42 noise_stage.process_pcm(0, frame);
43 }
44 self.dump(2, frame);
45 if let Some(gain) = self.gain.as_mut() {
46 let _ = gain.process_stream(frame, SAMPLE_RATE as i32, 1);
47 }
48 self.dump(3, frame);
49 }
50
51 fn dump(&mut self, stage_index: usize, frame: &[i16]) {
52 if let Some(dumps) = self.dumps.as_mut() {
53 dumps.write(stage_index, frame);
54 }
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61 use crate::audio::SineGenerator;
62 use crate::mic_processing::MicSettings;
63
64 #[test]
65 fn off_leaves_the_frame_untouched() {
66 let off = MicSettings { noise_suppression: crate::mic_processing::NoiseSuppression::Off, music_mode: false };
67 let mut chain = MicChain::new(off.apm_config(), off.ml_noise_suppression(), None);
68 let mut generator = SineGenerator::new(300.0, 0.2);
69 let original = generator.next_frame();
70 let mut frame = original.clone();
71 chain.process(&mut frame);
72 assert_eq!(frame, original);
73 }
74}
crates/calling/src/mic_processing.rs +31 −12
@@ -51,10 +51,13 @@ impl ApmConfig {
51 51 self == ApmConfig { echo_canceller: false, gain_controller: false, high_pass_filter: false, noise_suppression: false }
52 52 }
53 53
54 pub fn module(self) -> Option<AudioProcessingModule> {
55 (!self.is_passthrough()).then(|| {
56 AudioProcessingModule::new(self.echo_canceller, self.gain_controller, self.high_pass_filter, self.noise_suppression)
57 })
54 pub fn front_module(self) -> Option<AudioProcessingModule> {
55 (self.echo_canceller || self.high_pass_filter || self.noise_suppression)
56 .then(|| AudioProcessingModule::new(self.echo_canceller, false, self.high_pass_filter, self.noise_suppression))
57 }
58
59 pub fn gain_module(self) -> Option<AudioProcessingModule> {
60 self.gain_controller.then(|| AudioProcessingModule::new(false, true, false, false))
58 61 }
59 62 }
60 63
@@ -64,7 +67,8 @@ impl MicSettings {
64 67 return ApmConfig { echo_canceller: true, gain_controller: false, high_pass_filter: false, noise_suppression: false };
65 68 }
66 69 let on = self.noise_suppression != NoiseSuppression::Off;
67 ApmConfig { echo_canceller: on, gain_controller: on, high_pass_filter: on, noise_suppression: on }
70 let apm_noise_suppression = self.noise_suppression == NoiseSuppression::Low;
71 ApmConfig { echo_canceller: on, gain_controller: on, high_pass_filter: on, noise_suppression: apm_noise_suppression }
68 72 }
69 73
70 74 pub fn uses_device_track(self) -> bool {
@@ -85,21 +89,35 @@ mod tests {
85 89 use super::*;
86 90
87 91 #[test]
88 fn auto_keeps_the_device_track_with_everything_on() {
92 fn auto_leaves_noise_to_the_ml_stage_and_keeps_the_rest_of_the_apm() {
89 93 let settings = MicSettings::default();
90 assert!(settings.uses_device_track());
94 assert!(settings.uses_device_track_on(false));
95 assert!(settings.ml_noise_suppression());
91 96 assert_eq!(
92 97 settings.apm_config(),
93 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: true }
98 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: false }
94 99 );
95 100 }
96 101
97 102 #[test]
98 fn low_keeps_the_device_track_with_the_apm_only() {
103 fn low_keeps_the_device_track_with_the_apm_noise_suppression() {
99 104 let settings = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
100 assert!(settings.uses_device_track());
105 assert!(settings.uses_device_track_on(false));
101 106 assert!(!settings.ml_noise_suppression());
102 assert_eq!(settings.apm_config(), MicSettings::default().apm_config());
107 assert_eq!(
108 settings.apm_config(),
109 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: true }
110 );
111 }
112
113 #[test]
114 fn gain_runs_in_its_own_module_after_the_front_stages() {
115 let config = MicSettings::default().apm_config();
116 assert!(config.front_module().is_some());
117 assert!(config.gain_module().is_some());
118 let music = MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.apm_config();
119 assert!(music.front_module().is_some());
120 assert!(music.gain_module().is_none());
103 121 }
104 122
105 123 #[test]
@@ -125,7 +143,8 @@ mod tests {
125 143 let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
126 144 assert!(!settings.uses_device_track());
127 145 assert!(settings.apm_config().is_passthrough());
128 assert!(settings.apm_config().module().is_none());
146 assert!(settings.apm_config().front_module().is_none());
147 assert!(settings.apm_config().gain_module().is_none());
129 148 }
130 149
131 150 #[test]
@@ -51,10 +51,13 @@ impl ApmConfig {
51 self == ApmConfig { echo_canceller: false, gain_controller: false, high_pass_filter: false, noise_suppression: false }
51 self == ApmConfig { echo_canceller: false, gain_controller: false, high_pass_filter: false, noise_suppression: false }
52 }
52 }
53
53
54 pub fn module(self) -> Option<AudioProcessingModule> {
54 pub fn front_module(self) -> Option<AudioProcessingModule> {
55 (!self.is_passthrough()).then(|| {
55 (self.echo_canceller || self.high_pass_filter || self.noise_suppression)
56 AudioProcessingModule::new(self.echo_canceller, self.gain_controller, self.high_pass_filter, self.noise_suppression)
56 .then(|| AudioProcessingModule::new(self.echo_canceller, false, self.high_pass_filter, self.noise_suppression))
57 })
57 }
58
59 pub fn gain_module(self) -> Option<AudioProcessingModule> {
60 self.gain_controller.then(|| AudioProcessingModule::new(false, true, false, false))
58 }
61 }
59}
62}
60
63
@@ -64,7 +67,8 @@ impl MicSettings {
64 return ApmConfig { echo_canceller: true, gain_controller: false, high_pass_filter: false, noise_suppression: false };
67 return ApmConfig { echo_canceller: true, gain_controller: false, high_pass_filter: false, noise_suppression: false };
65 }
68 }
66 let on = self.noise_suppression != NoiseSuppression::Off;
69 let on = self.noise_suppression != NoiseSuppression::Off;
67 ApmConfig { echo_canceller: on, gain_controller: on, high_pass_filter: on, noise_suppression: on }
70 let apm_noise_suppression = self.noise_suppression == NoiseSuppression::Low;
71 ApmConfig { echo_canceller: on, gain_controller: on, high_pass_filter: on, noise_suppression: apm_noise_suppression }
68 }
72 }
69
73
70 pub fn uses_device_track(self) -> bool {
74 pub fn uses_device_track(self) -> bool {
@@ -85,21 +89,35 @@ mod tests {
85 use super::*;
89 use super::*;
86
90
87 #[test]
91 #[test]
88 fn auto_keeps_the_device_track_with_everything_on() {
92 fn auto_leaves_noise_to_the_ml_stage_and_keeps_the_rest_of_the_apm() {
89 let settings = MicSettings::default();
93 let settings = MicSettings::default();
90 assert!(settings.uses_device_track());
94 assert!(settings.uses_device_track_on(false));
95 assert!(settings.ml_noise_suppression());
91 assert_eq!(
96 assert_eq!(
92 settings.apm_config(),
97 settings.apm_config(),
93 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: true }
98 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: false }
94 );
99 );
95 }
100 }
96
101
97 #[test]
102 #[test]
98 fn low_keeps_the_device_track_with_the_apm_only() {
103 fn low_keeps_the_device_track_with_the_apm_noise_suppression() {
99 let settings = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
104 let settings = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
100 assert!(settings.uses_device_track());
105 assert!(settings.uses_device_track_on(false));
101 assert!(!settings.ml_noise_suppression());
106 assert!(!settings.ml_noise_suppression());
102 assert_eq!(settings.apm_config(), MicSettings::default().apm_config());
107 assert_eq!(
108 settings.apm_config(),
109 ApmConfig { echo_canceller: true, gain_controller: true, high_pass_filter: true, noise_suppression: true }
110 );
111 }
112
113 #[test]
114 fn gain_runs_in_its_own_module_after_the_front_stages() {
115 let config = MicSettings::default().apm_config();
116 assert!(config.front_module().is_some());
117 assert!(config.gain_module().is_some());
118 let music = MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.apm_config();
119 assert!(music.front_module().is_some());
120 assert!(music.gain_module().is_none());
103 }
121 }
104
122
105 #[test]
123 #[test]
@@ -125,7 +143,8 @@ mod tests {
125 let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
143 let settings = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
126 assert!(!settings.uses_device_track());
144 assert!(!settings.uses_device_track());
127 assert!(settings.apm_config().is_passthrough());
145 assert!(settings.apm_config().is_passthrough());
128 assert!(settings.apm_config().module().is_none());
146 assert!(settings.apm_config().front_module().is_none());
147 assert!(settings.apm_config().gain_module().is_none());
129 }
148 }
130
149
131 #[test]
150 #[test]
crates/calling/src/noise_stage.rs +173 −42
@@ -1,39 +1,143 @@
1 1 use std::sync::atomic::{AtomicBool, Ordering};
2 use std::sync::Mutex;
2 use std::sync::{Mutex, Once};
3 3
4 use nnnoiseless::{DenoiseState, FRAME_SIZE};
4 use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
5 use ndarray::{ArrayView2, ArrayViewMut2};
5 6
7 use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
6 8 use crate::mic_processing::MicSettings;
7 9
10 const PCM_SCALE: f32 = 32768.0;
11 const ATTENUATION_LIMIT_DB: f32 = 100.0;
12 const MIN_LOCAL_SNR_DB: f32 = -15.0;
13 const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;
14 const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;
15 const WARM_UP_FRAMES: usize = 100;
16
8 17 static ENABLED: AtomicBool = AtomicBool::new(false);
9 18 static STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());
19 static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);
20 static PREPARE: Once = Once::new();
21
22 fn load_model() -> Option<DfTract> {
23 let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB)).ok().filter(|model| model.hop_size == FRAME_SAMPLES)?;
24 warm_up(&mut model);
25 Some(model)
26 }
27
28 /// A cold model that hears only noise for a few seconds drops the next sentence; a second of vowel-like sound first avoids that.
29 fn warm_up(model: &mut DfTract) {
30 let mut enhanced = vec![0.0; FRAME_SAMPLES];
31 for frame_index in 0..WARM_UP_FRAMES {
32 let noisy = vowel_frame(frame_index);
33 let (Ok(noisy), Ok(enhanced)) =
34 (ArrayView2::from_shape((1, FRAME_SAMPLES), &noisy), ArrayViewMut2::from_shape((1, FRAME_SAMPLES), &mut enhanced))
35 else {
36 return;
37 };
38 let _ = model.process(noisy, enhanced);
39 }
40 }
41
42 fn vowel_frame(frame_index: usize) -> Vec<f32> {
43 let pitch = 110.0 + 40.0 * ((frame_index as f32) * 0.07).sin();
44 (0..FRAME_SAMPLES)
45 .map(|sample_index| {
46 let time = (frame_index * FRAME_SAMPLES + sample_index) as f32 / SAMPLE_RATE as f32;
47 (1..=30)
48 .map(|harmonic| {
49 let frequency = pitch * harmonic as f32;
50 let formant = [700.0_f32, 1200.0, 2600.0]
51 .iter()
52 .map(|center| (-((frequency - center) / 150.0).powi(2)).exp())
53 .sum::<f32>()
54 + 0.05;
55 formant * (std::f32::consts::TAU * frequency * time).sin()
56 })
57 .sum::<f32>()
58 * 0.03
59 })
60 .collect()
61 }
62
63 /// The deep-filter CLI defaults; the library defaults (-10 dB floor) drop quiet sentences after a noisy start.
64 fn runtime_params(attenuation_limit_db: f32) -> RuntimeParams {
65 RuntimeParams::default_with_ch(1)
66 .with_atten_lim(attenuation_limit_db)
67 .with_thresholds(MIN_LOCAL_SNR_DB, MAX_LOCAL_SNR_ERB_DB, MAX_LOCAL_SNR_DF_DB)
68 .with_mask_reduce(ReduceMask::MAX)
69 }
70
71 /// Builds the DeepFilterNet3 model off the audio thread; frames pass through unchanged until it is ready.
72 pub fn prepare() {
73 PREPARE.call_once(|| {
74 let _ = std::thread::Builder::new().name("deep-filter-load".into()).spawn(|| {
75 let model = load_model();
76 *PROTOTYPE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = model;
77 });
78 });
79 }
80
81 pub fn is_ready() -> bool {
82 PROTOTYPE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).is_some()
83 }
84
85 fn ready_model() -> Option<DfTract> {
86 PROTOTYPE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().map(DfTract::fork)
87 }
10 88
11 89 pub struct NoiseStage {
12 channels: Vec<Box<DenoiseState<'static>>>,
90 channels: Vec<Option<DfTract>>,
91 input: Vec<f32>,
92 output: Vec<f32>,
93 pcm: Vec<f32>,
13 94 }
14 95
15 96 impl NoiseStage {
16 97 pub const fn new() -> Self {
17 NoiseStage { channels: Vec::new() }
98 NoiseStage { channels: Vec::new(), input: Vec::new(), output: Vec::new(), pcm: Vec::new() }
18 99 }
19 100
20 101 pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
21 if samples.len() != FRAME_SIZE {
102 if samples.len() != FRAME_SAMPLES {
22 103 return;
23 104 }
24 105 while self.channels.len() <= channel_index {
25 self.channels.push(DenoiseState::new());
106 self.channels.push(None);
107 }
108 let channel = &mut self.channels[channel_index];
109 if channel.is_none() {
110 *channel = ready_model();
111 }
112 let Some(model) = channel.as_mut() else {
113 return;
114 };
115 self.input.clear();
116 self.input.extend(samples.iter().map(|sample| sample / PCM_SCALE));
117 self.output.resize(FRAME_SAMPLES, 0.0);
118 let (Ok(noisy), Ok(enhanced)) = (
119 ArrayView2::from_shape((1, FRAME_SAMPLES), &self.input),
120 ArrayViewMut2::from_shape((1, FRAME_SAMPLES), &mut self.output),
121 ) else {
122 return;
123 };
124 if model.process(noisy, enhanced).is_err() {
125 return;
126 }
127 for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
128 *sample = enhanced * PCM_SCALE;
26 129 }
27 let input: [f32; FRAME_SIZE] = std::array::from_fn(|index| samples[index]);
28 self.channels[channel_index].process_frame(samples, &input);
29 130 }
30 131
31 132 pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
32 let mut floats: Vec<f32> = samples.iter().map(|sample| f32::from(*sample)).collect();
133 let mut floats = std::mem::take(&mut self.pcm);
134 floats.clear();
135 floats.extend(samples.iter().map(|sample| f32::from(*sample)));
33 136 self.process(channel_index, &mut floats);
34 for (sample, processed) in samples.iter_mut().zip(floats) {
137 for (sample, processed) in samples.iter_mut().zip(&floats) {
35 138 *sample = processed.clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16;
36 139 }
140 self.pcm = floats;
37 141 }
38 142 }
39 143
@@ -52,6 +156,9 @@ fn process_capture(channel_index: usize, samples: &mut [f32]) {
52 156 }
53 157
54 158 pub fn apply(settings: MicSettings) {
159 if settings.ml_noise_suppression() {
160 prepare();
161 }
55 162 webrtc_sys::noise_hook::set_capture_hook(Some(process_capture));
56 163 ENABLED.store(settings.ml_noise_suppression(), Ordering::Relaxed);
57 164 }
@@ -59,15 +166,15 @@ pub fn apply(settings: MicSettings) {
59 166 #[cfg(test)]
60 167 mod tests {
61 168 use super::*;
169 use std::time::{Duration, Instant};
62 170
63 fn white_noise(frame_len: usize) -> Vec<f32> {
64 let mut state = 0x2545_f491_u32;
171 fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {
65 172 (0..frame_len)
66 173 .map(|_| {
67 state ^= state << 13;
68 state ^= state >> 17;
69 state ^= state << 5;
70 (state as f32 / u32::MAX as f32 - 0.5) * 6000.0
174 *state ^= *state << 13;
175 *state ^= *state >> 17;
176 *state ^= *state << 5;
177 (*state as f32 / u32::MAX as f32 - 0.5) * 2.0 * amplitude
71 178 })
72 179 .collect()
73 180 }
@@ -76,49 +183,73 @@ mod tests {
76 183 samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32
77 184 }
78 185
186 fn stage_with_model() -> NoiseStage {
187 let model = load_model().expect("DeepFilterNet3 loads with a 10 ms hop at 48 kHz");
188 NoiseStage { channels: vec![Some(model)], ..NoiseStage::new() }
189 }
190
79 191 #[test]
80 192 fn white_noise_loses_most_of_its_energy() {
81 let mut stage = NoiseStage::new();
82 let mut last_energy_ratio = 1.0;
83 for _ in 0..50 {
84 let mut frame = white_noise(FRAME_SIZE);
85 let before = energy(&frame);
193 let mut stage = stage_with_model();
194 let mut state = 0x2545_f491_u32;
195 let (mut before, mut after) = (0.0, 0.0);
196 for frame_index in 0..200 {
197 let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
198 let input_energy = energy(&frame);
86 199 stage.process(0, &mut frame);
87 last_energy_ratio = energy(&frame) / before;
200 if frame_index >= 100 {
201 before += input_energy;
202 after += energy(&frame);
203 }
88 204 }
89 assert!(last_energy_ratio < 0.1, "energy ratio {last_energy_ratio}");
205 assert!(after / before < 0.01, "energy ratio {}", after / before);
90 206 }
91 207
92 208 #[test]
93 fn other_frame_lengths_pass_through_unchanged() {
94 let mut stage = NoiseStage::new();
95 for frame_len in [160, 441, FRAME_SIZE * 2] {
96 let original = white_noise(frame_len);
97 let mut frame = original.clone();
209 fn the_attenuation_limit_caps_what_the_model_removes() {
210 let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();
211 let mut stage = NoiseStage { channels: vec![Some(model)], ..NoiseStage::new() };
212 let mut state = 0x1234_5678_u32;
213 let (mut before, mut after) = (0.0, 0.0);
214 for frame_index in 0..200 {
215 let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
216 let input_energy = energy(&frame);
98 217 stage.process(0, &mut frame);
99 assert_eq!(frame, original);
218 if frame_index >= 100 {
219 before += input_energy;
220 after += energy(&frame);
221 }
100 222 }
223 let ratio_db = 10.0 * (after / before).log10();
224 assert!((-7.5..=-4.5).contains(&ratio_db), "noise reduced by {ratio_db:.1} dB");
101 225 }
102 226
103 227 #[test]
104 fn each_channel_keeps_its_own_state() {
105 let mut stage = NoiseStage::new();
106 let mut frame = white_noise(FRAME_SIZE);
107 stage.process(1, &mut frame);
108 assert_eq!(stage.channels.len(), 2);
228 fn other_frame_lengths_pass_through_unchanged() {
229 let mut stage = stage_with_model();
230 let mut state = 7_u32;
231 for frame_len in [160, 441, FRAME_SAMPLES * 2] {
232 let original = white_noise(frame_len, 3000.0, &mut state);
233 let mut frame = original.clone();
234 stage.process(0, &mut frame);
235 assert_eq!(frame, original);
236 }
109 237 }
110 238
111 239 #[test]
112 fn rnnoise_costs_little_per_ten_ms_frame() {
113 let mut stage = NoiseStage::new();
114 let frames = 500;
115 let started = std::time::Instant::now();
240 fn deep_filter_keeps_up_with_real_time() {
241 let mut stage = stage_with_model();
242 let mut state = 11_u32;
243 let frames = 300;
244 let mut busy = Duration::ZERO;
116 245 for _ in 0..frames {
117 let mut frame = white_noise(FRAME_SIZE);
246 let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
247 let started = Instant::now();
118 248 stage.process(0, &mut frame);
249 busy += started.elapsed();
119 250 }
120 let per_frame = started.elapsed() / frames;
121 eprintln!("rnnoise per 10 ms frame (incl. noise generation): {per_frame:?}");
122 assert!(per_frame < std::time::Duration::from_millis(50));
251 let per_frame = busy / frames;
252 eprintln!("deep filter per 10 ms frame: {per_frame:?}");
253 assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));
123 254 }
124 255 }
@@ -1,39 +1,143 @@
1use std::sync::atomic::{AtomicBool, Ordering};
1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::Mutex;
2use std::sync::{Mutex, Once};
3
3
4use nnnoiseless::{DenoiseState, FRAME_SIZE};
4use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
5use ndarray::{ArrayView2, ArrayViewMut2};
5
6
7use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
6use crate::mic_processing::MicSettings;
8use crate::mic_processing::MicSettings;
7
9
10const PCM_SCALE: f32 = 32768.0;
11const ATTENUATION_LIMIT_DB: f32 = 100.0;
12const MIN_LOCAL_SNR_DB: f32 = -15.0;
13const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;
14const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;
15const WARM_UP_FRAMES: usize = 100;
16
8static ENABLED: AtomicBool = AtomicBool::new(false);
17static ENABLED: AtomicBool = AtomicBool::new(false);
9static STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());
18static STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());
19static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);
20static PREPARE: Once = Once::new();
21
22fn load_model() -> Option<DfTract> {
23 let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB)).ok().filter(|model| model.hop_size == FRAME_SAMPLES)?;
24 warm_up(&mut model);
25 Some(model)
26}
27
28/// A cold model that hears only noise for a few seconds drops the next sentence; a second of vowel-like sound first avoids that.
29fn warm_up(model: &mut DfTract) {
30 let mut enhanced = vec![0.0; FRAME_SAMPLES];
31 for frame_index in 0..WARM_UP_FRAMES {
32 let noisy = vowel_frame(frame_index);
33 let (Ok(noisy), Ok(enhanced)) =
34 (ArrayView2::from_shape((1, FRAME_SAMPLES), &noisy), ArrayViewMut2::from_shape((1, FRAME_SAMPLES), &mut enhanced))
35 else {
36 return;
37 };
38 let _ = model.process(noisy, enhanced);
39 }
40}
41
42fn vowel_frame(frame_index: usize) -> Vec<f32> {
43 let pitch = 110.0 + 40.0 * ((frame_index as f32) * 0.07).sin();
44 (0..FRAME_SAMPLES)
45 .map(|sample_index| {
46 let time = (frame_index * FRAME_SAMPLES + sample_index) as f32 / SAMPLE_RATE as f32;
47 (1..=30)
48 .map(|harmonic| {
49 let frequency = pitch * harmonic as f32;
50 let formant = [700.0_f32, 1200.0, 2600.0]
51 .iter()
52 .map(|center| (-((frequency - center) / 150.0).powi(2)).exp())
53 .sum::<f32>()
54 + 0.05;
55 formant * (std::f32::consts::TAU * frequency * time).sin()
56 })
57 .sum::<f32>()
58 * 0.03
59 })
60 .collect()
61}
62
63/// The deep-filter CLI defaults; the library defaults (-10 dB floor) drop quiet sentences after a noisy start.
64fn runtime_params(attenuation_limit_db: f32) -> RuntimeParams {
65 RuntimeParams::default_with_ch(1)
66 .with_atten_lim(attenuation_limit_db)
67 .with_thresholds(MIN_LOCAL_SNR_DB, MAX_LOCAL_SNR_ERB_DB, MAX_LOCAL_SNR_DF_DB)
68 .with_mask_reduce(ReduceMask::MAX)
69}
70
71/// Builds the DeepFilterNet3 model off the audio thread; frames pass through unchanged until it is ready.
72pub fn prepare() {
73 PREPARE.call_once(|| {
74 let _ = std::thread::Builder::new().name("deep-filter-load".into()).spawn(|| {
75 let model = load_model();
76 *PROTOTYPE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = model;
77 });
78 });
79}
80
81pub fn is_ready() -> bool {
82 PROTOTYPE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).is_some()
83}
84
85fn ready_model() -> Option<DfTract> {
86 PROTOTYPE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).as_ref().map(DfTract::fork)
87}
10
88
11pub struct NoiseStage {
89pub struct NoiseStage {
12 channels: Vec<Box<DenoiseState<'static>>>,
90 channels: Vec<Option<DfTract>>,
91 input: Vec<f32>,
92 output: Vec<f32>,
93 pcm: Vec<f32>,
13}
94}
14
95
15impl NoiseStage {
96impl NoiseStage {
16 pub const fn new() -> Self {
97 pub const fn new() -> Self {
17 NoiseStage { channels: Vec::new() }
98 NoiseStage { channels: Vec::new(), input: Vec::new(), output: Vec::new(), pcm: Vec::new() }
18 }
99 }
19
100
20 pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
101 pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
21 if samples.len() != FRAME_SIZE {
102 if samples.len() != FRAME_SAMPLES {
22 return;
103 return;
23 }
104 }
24 while self.channels.len() <= channel_index {
105 while self.channels.len() <= channel_index {
25 self.channels.push(DenoiseState::new());
106 self.channels.push(None);
107 }
108 let channel = &mut self.channels[channel_index];
109 if channel.is_none() {
110 *channel = ready_model();
111 }
112 let Some(model) = channel.as_mut() else {
113 return;
114 };
115 self.input.clear();
116 self.input.extend(samples.iter().map(|sample| sample / PCM_SCALE));
117 self.output.resize(FRAME_SAMPLES, 0.0);
118 let (Ok(noisy), Ok(enhanced)) = (
119 ArrayView2::from_shape((1, FRAME_SAMPLES), &self.input),
120 ArrayViewMut2::from_shape((1, FRAME_SAMPLES), &mut self.output),
121 ) else {
122 return;
123 };
124 if model.process(noisy, enhanced).is_err() {
125 return;
126 }
127 for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
128 *sample = enhanced * PCM_SCALE;
26 }
129 }
27 let input: [f32; FRAME_SIZE] = std::array::from_fn(|index| samples[index]);
28 self.channels[channel_index].process_frame(samples, &input);
29 }
130 }
30
131
31 pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
132 pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
32 let mut floats: Vec<f32> = samples.iter().map(|sample| f32::from(*sample)).collect();
133 let mut floats = std::mem::take(&mut self.pcm);
134 floats.clear();
135 floats.extend(samples.iter().map(|sample| f32::from(*sample)));
33 self.process(channel_index, &mut floats);
136 self.process(channel_index, &mut floats);
34 for (sample, processed) in samples.iter_mut().zip(floats) {
137 for (sample, processed) in samples.iter_mut().zip(&floats) {
35 *sample = processed.clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16;
138 *sample = processed.clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16;
36 }
139 }
140 self.pcm = floats;
37 }
141 }
38}
142}
39
143
@@ -52,6 +156,9 @@ fn process_capture(channel_index: usize, samples: &mut [f32]) {
52}
156}
53
157
54pub fn apply(settings: MicSettings) {
158pub fn apply(settings: MicSettings) {
159 if settings.ml_noise_suppression() {
160 prepare();
161 }
55 webrtc_sys::noise_hook::set_capture_hook(Some(process_capture));
162 webrtc_sys::noise_hook::set_capture_hook(Some(process_capture));
56 ENABLED.store(settings.ml_noise_suppression(), Ordering::Relaxed);
163 ENABLED.store(settings.ml_noise_suppression(), Ordering::Relaxed);
57}
164}
@@ -59,15 +166,15 @@ pub fn apply(settings: MicSettings) {
59#[cfg(test)]
166#[cfg(test)]
60mod tests {
167mod tests {
61 use super::*;
168 use super::*;
169 use std::time::{Duration, Instant};
62
170
63 fn white_noise(frame_len: usize) -> Vec<f32> {
171 fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {
64 let mut state = 0x2545_f491_u32;
65 (0..frame_len)
172 (0..frame_len)
66 .map(|_| {
173 .map(|_| {
67 state ^= state << 13;
174 *state ^= *state << 13;
68 state ^= state >> 17;
175 *state ^= *state >> 17;
69 state ^= state << 5;
176 *state ^= *state << 5;
70 (state as f32 / u32::MAX as f32 - 0.5) * 6000.0
177 (*state as f32 / u32::MAX as f32 - 0.5) * 2.0 * amplitude
71 })
178 })
72 .collect()
179 .collect()
73 }
180 }
@@ -76,49 +183,73 @@ mod tests {
76 samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32
183 samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32
77 }
184 }
78
185
186 fn stage_with_model() -> NoiseStage {
187 let model = load_model().expect("DeepFilterNet3 loads with a 10 ms hop at 48 kHz");
188 NoiseStage { channels: vec![Some(model)], ..NoiseStage::new() }
189 }
190
79 #[test]
191 #[test]
80 fn white_noise_loses_most_of_its_energy() {
192 fn white_noise_loses_most_of_its_energy() {
81 let mut stage = NoiseStage::new();
193 let mut stage = stage_with_model();
82 let mut last_energy_ratio = 1.0;
194 let mut state = 0x2545_f491_u32;
83 for _ in 0..50 {
195 let (mut before, mut after) = (0.0, 0.0);
84 let mut frame = white_noise(FRAME_SIZE);
196 for frame_index in 0..200 {
85 let before = energy(&frame);
197 let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
198 let input_energy = energy(&frame);
86 stage.process(0, &mut frame);
199 stage.process(0, &mut frame);
87 last_energy_ratio = energy(&frame) / before;
200 if frame_index >= 100 {
201 before += input_energy;
202 after += energy(&frame);
203 }
88 }
204 }
89 assert!(last_energy_ratio < 0.1, "energy ratio {last_energy_ratio}");
205 assert!(after / before < 0.01, "energy ratio {}", after / before);
90 }
206 }
91
207
92 #[test]
208 #[test]
93 fn other_frame_lengths_pass_through_unchanged() {
209 fn the_attenuation_limit_caps_what_the_model_removes() {
94 let mut stage = NoiseStage::new();
210 let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();
95 for frame_len in [160, 441, FRAME_SIZE * 2] {
211 let mut stage = NoiseStage { channels: vec![Some(model)], ..NoiseStage::new() };
96 let original = white_noise(frame_len);
212 let mut state = 0x1234_5678_u32;
97 let mut frame = original.clone();
213 let (mut before, mut after) = (0.0, 0.0);
214 for frame_index in 0..200 {
215 let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
216 let input_energy = energy(&frame);
98 stage.process(0, &mut frame);
217 stage.process(0, &mut frame);
99 assert_eq!(frame, original);
218 if frame_index >= 100 {
219 before += input_energy;
220 after += energy(&frame);
221 }
100 }
222 }
223 let ratio_db = 10.0 * (after / before).log10();
224 assert!((-7.5..=-4.5).contains(&ratio_db), "noise reduced by {ratio_db:.1} dB");
101 }
225 }
102
226
103 #[test]
227 #[test]
104 fn each_channel_keeps_its_own_state() {
228 fn other_frame_lengths_pass_through_unchanged() {
105 let mut stage = NoiseStage::new();
229 let mut stage = stage_with_model();
106 let mut frame = white_noise(FRAME_SIZE);
230 let mut state = 7_u32;
107 stage.process(1, &mut frame);
231 for frame_len in [160, 441, FRAME_SAMPLES * 2] {
108 assert_eq!(stage.channels.len(), 2);
232 let original = white_noise(frame_len, 3000.0, &mut state);
233 let mut frame = original.clone();
234 stage.process(0, &mut frame);
235 assert_eq!(frame, original);
236 }
109 }
237 }
110
238
111 #[test]
239 #[test]
112 fn rnnoise_costs_little_per_ten_ms_frame() {
240 fn deep_filter_keeps_up_with_real_time() {
113 let mut stage = NoiseStage::new();
241 let mut stage = stage_with_model();
114 let frames = 500;
242 let mut state = 11_u32;
115 let started = std::time::Instant::now();
243 let frames = 300;
244 let mut busy = Duration::ZERO;
116 for _ in 0..frames {
245 for _ in 0..frames {
117 let mut frame = white_noise(FRAME_SIZE);
246 let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
247 let started = Instant::now();
118 stage.process(0, &mut frame);
248 stage.process(0, &mut frame);
249 busy += started.elapsed();
119 }
250 }
120 let per_frame = started.elapsed() / frames;
251 let per_frame = busy / frames;
121 eprintln!("rnnoise per 10 ms frame (incl. noise generation): {per_frame:?}");
252 eprintln!("deep filter per 10 ms frame: {per_frame:?}");
122 assert!(per_frame < std::time::Duration::from_millis(50));
253 assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));
123 }
254 }
124}
255}
crates/calling/src/sdp.rs +32 −4
@@ -638,6 +638,23 @@ fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute>
638 638 .collect()
639 639 }
640 640
641 const OPUS_SEND_QUALITY: [(&str, &str); 2] = [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
642
643 /// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate.
644 fn with_opus_send_quality(fmtp: &str) -> String {
645 let mut value = fmtp.to_owned();
646 for (name, setting) in OPUS_SEND_QUALITY {
647 if value.split([' ', ';']).any(|parameter| parameter.split('=').next() == Some(name)) {
648 continue;
649 }
650 if !value.ends_with(' ') {
651 value.push(if value.contains(' ') { ';' } else { ' ' });
652 }
653 value.push_str(&format!("{name}={setting}"));
654 }
655 value
656 }
657
641 658 fn browser_rtp_line(
642 659 teams_line: &Media,
643 660 offered: &Media,
@@ -698,16 +715,17 @@ fn browser_rtp_line(
698 715 if !kept_set.contains(payload.as_str()) {
699 716 continue;
700 717 }
701 fmtp_payloads.insert(payload);
702 718 let cleaned = value
703 719 .split(';')
704 720 .filter(|parameter| !parameter.starts_with("rtx-time="))
705 721 .collect::<Vec<_>>()
706 722 .join(";");
707 attributes.push(Attribute::new("fmtp", cleaned));
723 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
724 fmtp_payloads.insert(payload);
725 attributes.push(Attribute::new("fmtp", if is_opus { with_opus_send_quality(&cleaned) } else { cleaned }));
708 726 }
709 727 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
710 attributes.push(Attribute::new("fmtp", format!("{opus} usedtx=1")));
728 attributes.push(Attribute::new("fmtp", with_opus_send_quality(&format!("{opus} usedtx=1"))));
711 729 }
712 730 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
713 731 && !fmtp_payloads.contains(red)
@@ -1104,7 +1122,7 @@ mod tests {
1104 1122 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n");
1105 1123 assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}");
1106 1124 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1107 assert!(browser.contains("a=fmtp:111 usedtx=1\n"));
1125 assert!(browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n"));
1108 1126 assert!(browser.contains("a=fmtp:97 111/111\n"));
1109 1127 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1110 1128 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
@@ -1187,4 +1205,14 @@ mod tests {
1187 1205 assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1188 1206 assert_eq!(folded_mids("x", 2), vec!["x-0".to_owned(), "x".to_owned()]);
1189 1207 }
1208
1209 #[test]
1210 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1211 assert_eq!(
1212 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1213 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1214 );
1215 assert_eq!(with_opus_send_quality("111 maxplaybackrate=16000"), "111 maxplaybackrate=16000;maxaveragebitrate=40000");
1216 assert_eq!(with_opus_send_quality("111"), "111 maxaveragebitrate=40000;maxplaybackrate=48000");
1217 }
1190 1218 }
@@ -638,6 +638,23 @@ fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute>
638 .collect()
638 .collect()
639}
639}
640
640
641const OPUS_SEND_QUALITY: [(&str, &str); 2] = [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
642
643/// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate.
644fn with_opus_send_quality(fmtp: &str) -> String {
645 let mut value = fmtp.to_owned();
646 for (name, setting) in OPUS_SEND_QUALITY {
647 if value.split([' ', ';']).any(|parameter| parameter.split('=').next() == Some(name)) {
648 continue;
649 }
650 if !value.ends_with(' ') {
651 value.push(if value.contains(' ') { ';' } else { ' ' });
652 }
653 value.push_str(&format!("{name}={setting}"));
654 }
655 value
656}
657
641fn browser_rtp_line(
658fn browser_rtp_line(
642 teams_line: &Media,
659 teams_line: &Media,
643 offered: &Media,
660 offered: &Media,
@@ -698,16 +715,17 @@ fn browser_rtp_line(
698 if !kept_set.contains(payload.as_str()) {
715 if !kept_set.contains(payload.as_str()) {
699 continue;
716 continue;
700 }
717 }
701 fmtp_payloads.insert(payload);
702 let cleaned = value
718 let cleaned = value
703 .split(';')
719 .split(';')
704 .filter(|parameter| !parameter.starts_with("rtx-time="))
720 .filter(|parameter| !parameter.starts_with("rtx-time="))
705 .collect::<Vec<_>>()
721 .collect::<Vec<_>>()
706 .join(";");
722 .join(";");
707 attributes.push(Attribute::new("fmtp", cleaned));
723 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
724 fmtp_payloads.insert(payload);
725 attributes.push(Attribute::new("fmtp", if is_opus { with_opus_send_quality(&cleaned) } else { cleaned }));
708 }
726 }
709 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
727 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
710 attributes.push(Attribute::new("fmtp", format!("{opus} usedtx=1")));
728 attributes.push(Attribute::new("fmtp", with_opus_send_quality(&format!("{opus} usedtx=1"))));
711 }
729 }
712 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
730 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
713 && !fmtp_payloads.contains(red)
731 && !fmtp_payloads.contains(red)
@@ -1104,7 +1122,7 @@ mod tests {
1104 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n");
1122 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n");
1105 assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}");
1123 assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}");
1106 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1124 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1107 assert!(browser.contains("a=fmtp:111 usedtx=1\n"));
1125 assert!(browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n"));
1108 assert!(browser.contains("a=fmtp:97 111/111\n"));
1126 assert!(browser.contains("a=fmtp:97 111/111\n"));
1109 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1127 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1110 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1128 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
@@ -1187,4 +1205,14 @@ mod tests {
1187 assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1205 assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1188 assert_eq!(folded_mids("x", 2), vec!["x-0".to_owned(), "x".to_owned()]);
1206 assert_eq!(folded_mids("x", 2), vec!["x-0".to_owned(), "x".to_owned()]);
1189 }
1207 }
1208
1209 #[test]
1210 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1211 assert_eq!(
1212 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1213 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1214 );
1215 assert_eq!(with_opus_send_quality("111 maxplaybackrate=16000"), "111 maxplaybackrate=16000;maxaveragebitrate=40000");
1216 assert_eq!(with_opus_send_quality("111"), "111 maxaveragebitrate=40000;maxplaybackrate=48000");
1217 }
1190}
1218}
crates/calling/src/software_audio.rs +9 −11
@@ -16,9 +16,10 @@ use crate::devices::DeviceChoice;
16 16 use crate::error::{Error, Result};
17 17 use crate::mic_processing::{ApmConfig, MicSettings};
18 18 use crate::mixer::mix_frames;
19 use crate::noise_stage::NoiseStage;
19 use crate::mic_chain::MicChain;
20 20 use crate::pcm::SampleQueue;
21 21 use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
22 use crate::wav_dump::StageDumps;
22 23
23 24 const SOURCE_QUEUE_MS: u32 = 100;
24 25 const FRAME_PERIOD: Duration = Duration::from_millis(10);
@@ -51,7 +52,7 @@ pub struct SoftwareAudioPlan {
51 52
52 53 struct Feeder {
53 54 processing: ApmConfig,
54 ml_noise: Option<NoiseStage>,
55 ml_noise: bool,
55 56 source: NativeAudioSource,
56 57 microphone: FrameSource,
57 58 computer: FrameSource,
@@ -63,7 +64,7 @@ struct Feeder {
63 64
64 65 impl Feeder {
65 66 fn run(mut self) {
66 let mut processing = self.processing.module();
67 let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());
67 68 let mut due = Instant::now();
68 69 while self.running.load(Ordering::SeqCst) {
69 70 due += FRAME_PERIOD;
@@ -74,16 +75,13 @@ impl Feeder {
74 75 due = now;
75 76 }
76 77 let (mut far_end, has_far_end) = self.far_end.next_frame();
77 if has_far_end && let Some(processing) = processing.as_mut() {
78 let _ = processing.process_reverse_stream(&mut far_end, SAMPLE_RATE as i32, 1);
78 if has_far_end {
79 chain.process_far_end(&mut far_end);
79 80 }
80 81 let muted = self.microphone_muted.load(Ordering::SeqCst);
81 82 let mut microphone = self.microphone.next_frame();
82 if !muted && let Some(processing) = processing.as_mut() {
83 let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1);
84 }
85 if !muted && let Some(noise_stage) = self.ml_noise.as_mut() {
86 noise_stage.process_pcm(0, &mut microphone);
83 if !muted {
84 chain.process(&mut microphone);
87 85 }
88 86 let computer = self.computer.next_frame();
89 87 let frame = AudioFrame {
@@ -187,7 +185,7 @@ impl SoftwareAudio {
187 185 let running = Arc::new(AtomicBool::new(true));
188 186 let feeder = Feeder {
189 187 processing: plan.processing,
190 ml_noise: plan.ml_noise.then(NoiseStage::new),
188 ml_noise: plan.ml_noise,
191 189 source,
192 190 microphone,
193 191 computer,
@@ -16,9 +16,10 @@ use crate::devices::DeviceChoice;
16use crate::error::{Error, Result};
16use crate::error::{Error, Result};
17use crate::mic_processing::{ApmConfig, MicSettings};
17use crate::mic_processing::{ApmConfig, MicSettings};
18use crate::mixer::mix_frames;
18use crate::mixer::mix_frames;
19use crate::noise_stage::NoiseStage;
19use crate::mic_chain::MicChain;
20use crate::pcm::SampleQueue;
20use crate::pcm::SampleQueue;
21use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
21use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
22use crate::wav_dump::StageDumps;
22
23
23const SOURCE_QUEUE_MS: u32 = 100;
24const SOURCE_QUEUE_MS: u32 = 100;
24const FRAME_PERIOD: Duration = Duration::from_millis(10);
25const FRAME_PERIOD: Duration = Duration::from_millis(10);
@@ -51,7 +52,7 @@ pub struct SoftwareAudioPlan {
51
52
52struct Feeder {
53struct Feeder {
53 processing: ApmConfig,
54 processing: ApmConfig,
54 ml_noise: Option<NoiseStage>,
55 ml_noise: bool,
55 source: NativeAudioSource,
56 source: NativeAudioSource,
56 microphone: FrameSource,
57 microphone: FrameSource,
57 computer: FrameSource,
58 computer: FrameSource,
@@ -63,7 +64,7 @@ struct Feeder {
63
64
64impl Feeder {
65impl Feeder {
65 fn run(mut self) {
66 fn run(mut self) {
66 let mut processing = self.processing.module();
67 let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());
67 let mut due = Instant::now();
68 let mut due = Instant::now();
68 while self.running.load(Ordering::SeqCst) {
69 while self.running.load(Ordering::SeqCst) {
69 due += FRAME_PERIOD;
70 due += FRAME_PERIOD;
@@ -74,16 +75,13 @@ impl Feeder {
74 due = now;
75 due = now;
75 }
76 }
76 let (mut far_end, has_far_end) = self.far_end.next_frame();
77 let (mut far_end, has_far_end) = self.far_end.next_frame();
77 if has_far_end && let Some(processing) = processing.as_mut() {
78 if has_far_end {
78 let _ = processing.process_reverse_stream(&mut far_end, SAMPLE_RATE as i32, 1);
79 chain.process_far_end(&mut far_end);
79 }
80 }
80 let muted = self.microphone_muted.load(Ordering::SeqCst);
81 let muted = self.microphone_muted.load(Ordering::SeqCst);
81 let mut microphone = self.microphone.next_frame();
82 let mut microphone = self.microphone.next_frame();
82 if !muted && let Some(processing) = processing.as_mut() {
83 if !muted {
83 let _ = processing.process_stream(&mut microphone, SAMPLE_RATE as i32, 1);
84 chain.process(&mut microphone);
84 }
85 if !muted && let Some(noise_stage) = self.ml_noise.as_mut() {
86 noise_stage.process_pcm(0, &mut microphone);
87 }
85 }
88 let computer = self.computer.next_frame();
86 let computer = self.computer.next_frame();
89 let frame = AudioFrame {
87 let frame = AudioFrame {
@@ -187,7 +185,7 @@ impl SoftwareAudio {
187 let running = Arc::new(AtomicBool::new(true));
185 let running = Arc::new(AtomicBool::new(true));
188 let feeder = Feeder {
186 let feeder = Feeder {
189 processing: plan.processing,
187 processing: plan.processing,
190 ml_noise: plan.ml_noise.then(NoiseStage::new),
188 ml_noise: plan.ml_noise,
191 source,
189 source,
192 microphone,
190 microphone,
193 computer,
191 computer,
crates/calling/src/wav_dump.rs added +123 −0
@@ -0,0 +1,123 @@
1 use std::fs::File;
2 use std::io::{BufWriter, Seek, SeekFrom, Write};
3 use std::path::{Path, PathBuf};
4
5 use crate::audio::SAMPLE_RATE;
6
7 pub const AUDIO_DUMP_ENV: &str = "CALLING_AUDIO_DUMP";
8 const HEADER_BYTES: u32 = 44;
9
10 /// Mono 16-bit WAV writer for checking each mic processing stage; the header gets its sizes on drop.
11 pub struct WavDump {
12 writer: BufWriter<File>,
13 data_bytes: u32,
14 }
15
16 impl WavDump {
17 pub fn create(path: &Path) -> std::io::Result<WavDump> {
18 let mut writer = BufWriter::new(File::create(path)?);
19 writer.write_all(&header(0))?;
20 Ok(WavDump { writer, data_bytes: 0 })
21 }
22
23 pub fn write(&mut self, samples: &[i16]) {
24 for sample in samples {
25 if self.writer.write_all(&sample.to_le_bytes()).is_err() {
26 return;
27 }
28 self.data_bytes += 2;
29 }
30 }
31
32 fn finish(&mut self) -> std::io::Result<()> {
33 self.writer.seek(SeekFrom::Start(0))?;
34 self.writer.write_all(&header(self.data_bytes))?;
35 self.writer.flush()
36 }
37 }
38
39 impl Drop for WavDump {
40 fn drop(&mut self) {
41 let _ = self.finish();
42 }
43 }
44
45 fn header(data_bytes: u32) -> Vec<u8> {
46 let byte_rate = SAMPLE_RATE * 2;
47 let mut header = Vec::with_capacity(HEADER_BYTES as usize);
48 header.extend_from_slice(b"RIFF");
49 header.extend_from_slice(&(HEADER_BYTES - 8 + data_bytes).to_le_bytes());
50 header.extend_from_slice(b"WAVEfmt ");
51 header.extend_from_slice(&16u32.to_le_bytes());
52 header.extend_from_slice(&1u16.to_le_bytes());
53 header.extend_from_slice(&1u16.to_le_bytes());
54 header.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
55 header.extend_from_slice(&byte_rate.to_le_bytes());
56 header.extend_from_slice(&2u16.to_le_bytes());
57 header.extend_from_slice(&16u16.to_le_bytes());
58 header.extend_from_slice(b"data");
59 header.extend_from_slice(&data_bytes.to_le_bytes());
60 header
61 }
62
63 /// One WAV per stage of the mic chain, written only when `CALLING_AUDIO_DUMP` names a directory.
64 pub struct StageDumps {
65 stages: Vec<WavDump>,
66 }
67
68 impl StageDumps {
69 pub const STAGES: [&str; 4] = ["1-raw", "2-echo-highpass", "3-noise", "4-gain"];
70
71 pub fn from_env() -> Option<StageDumps> {
72 let directory = PathBuf::from(std::env::var_os(AUDIO_DUMP_ENV)?);
73 StageDumps::create(&directory).ok()
74 }
75
76 pub fn create(directory: &Path) -> std::io::Result<StageDumps> {
77 std::fs::create_dir_all(directory)?;
78 let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S");
79 let stages = StageDumps::STAGES
80 .iter()
81 .map(|stage| WavDump::create(&directory.join(format!("mic-{stamp}-{stage}.wav"))))
82 .collect::<std::io::Result<Vec<_>>>()?;
83 Ok(StageDumps { stages })
84 }
85
86 pub fn write(&mut self, stage_index: usize, samples: &[i16]) {
87 if let Some(stage) = self.stages.get_mut(stage_index) {
88 stage.write(samples);
89 }
90 }
91 }
92
93 #[cfg(test)]
94 mod tests {
95 use super::*;
96
97 #[test]
98 fn a_dump_is_a_readable_wav_with_the_written_samples() {
99 let directory = tempfile::tempdir().unwrap();
100 let path = directory.path().join("dump.wav");
101 {
102 let mut dump = WavDump::create(&path).unwrap();
103 dump.write(&[1, -2, 3]);
104 }
105 let bytes = std::fs::read(&path).unwrap();
106 assert_eq!(&bytes[0..4], b"RIFF");
107 assert_eq!(u32::from_le_bytes(bytes[24..28].try_into().unwrap()), SAMPLE_RATE);
108 assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), 6);
109 assert_eq!(&bytes[44..], &[1, 0, 254, 255, 3, 0]);
110 }
111
112 #[test]
113 fn every_stage_gets_its_own_file() {
114 let directory = tempfile::tempdir().unwrap();
115 let mut dumps = StageDumps::create(directory.path()).unwrap();
116 dumps.write(3, &[5]);
117 drop(dumps);
118 let names: Vec<String> =
119 std::fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().into_string().unwrap()).collect();
120 assert_eq!(names.len(), StageDumps::STAGES.len());
121 assert!(names.iter().any(|name| name.ends_with("4-gain.wav")));
122 }
123 }
@@ -0,0 +1,123 @@
1use std::fs::File;
2use std::io::{BufWriter, Seek, SeekFrom, Write};
3use std::path::{Path, PathBuf};
4
5use crate::audio::SAMPLE_RATE;
6
7pub const AUDIO_DUMP_ENV: &str = "CALLING_AUDIO_DUMP";
8const HEADER_BYTES: u32 = 44;
9
10/// Mono 16-bit WAV writer for checking each mic processing stage; the header gets its sizes on drop.
11pub struct WavDump {
12 writer: BufWriter<File>,
13 data_bytes: u32,
14}
15
16impl WavDump {
17 pub fn create(path: &Path) -> std::io::Result<WavDump> {
18 let mut writer = BufWriter::new(File::create(path)?);
19 writer.write_all(&header(0))?;
20 Ok(WavDump { writer, data_bytes: 0 })
21 }
22
23 pub fn write(&mut self, samples: &[i16]) {
24 for sample in samples {
25 if self.writer.write_all(&sample.to_le_bytes()).is_err() {
26 return;
27 }
28 self.data_bytes += 2;
29 }
30 }
31
32 fn finish(&mut self) -> std::io::Result<()> {
33 self.writer.seek(SeekFrom::Start(0))?;
34 self.writer.write_all(&header(self.data_bytes))?;
35 self.writer.flush()
36 }
37}
38
39impl Drop for WavDump {
40 fn drop(&mut self) {
41 let _ = self.finish();
42 }
43}
44
45fn header(data_bytes: u32) -> Vec<u8> {
46 let byte_rate = SAMPLE_RATE * 2;
47 let mut header = Vec::with_capacity(HEADER_BYTES as usize);
48 header.extend_from_slice(b"RIFF");
49 header.extend_from_slice(&(HEADER_BYTES - 8 + data_bytes).to_le_bytes());
50 header.extend_from_slice(b"WAVEfmt ");
51 header.extend_from_slice(&16u32.to_le_bytes());
52 header.extend_from_slice(&1u16.to_le_bytes());
53 header.extend_from_slice(&1u16.to_le_bytes());
54 header.extend_from_slice(&SAMPLE_RATE.to_le_bytes());
55 header.extend_from_slice(&byte_rate.to_le_bytes());
56 header.extend_from_slice(&2u16.to_le_bytes());
57 header.extend_from_slice(&16u16.to_le_bytes());
58 header.extend_from_slice(b"data");
59 header.extend_from_slice(&data_bytes.to_le_bytes());
60 header
61}
62
63/// One WAV per stage of the mic chain, written only when `CALLING_AUDIO_DUMP` names a directory.
64pub struct StageDumps {
65 stages: Vec<WavDump>,
66}
67
68impl StageDumps {
69 pub const STAGES: [&str; 4] = ["1-raw", "2-echo-highpass", "3-noise", "4-gain"];
70
71 pub fn from_env() -> Option<StageDumps> {
72 let directory = PathBuf::from(std::env::var_os(AUDIO_DUMP_ENV)?);
73 StageDumps::create(&directory).ok()
74 }
75
76 pub fn create(directory: &Path) -> std::io::Result<StageDumps> {
77 std::fs::create_dir_all(directory)?;
78 let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S");
79 let stages = StageDumps::STAGES
80 .iter()
81 .map(|stage| WavDump::create(&directory.join(format!("mic-{stamp}-{stage}.wav"))))
82 .collect::<std::io::Result<Vec<_>>>()?;
83 Ok(StageDumps { stages })
84 }
85
86 pub fn write(&mut self, stage_index: usize, samples: &[i16]) {
87 if let Some(stage) = self.stages.get_mut(stage_index) {
88 stage.write(samples);
89 }
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96
97 #[test]
98 fn a_dump_is_a_readable_wav_with_the_written_samples() {
99 let directory = tempfile::tempdir().unwrap();
100 let path = directory.path().join("dump.wav");
101 {
102 let mut dump = WavDump::create(&path).unwrap();
103 dump.write(&[1, -2, 3]);
104 }
105 let bytes = std::fs::read(&path).unwrap();
106 assert_eq!(&bytes[0..4], b"RIFF");
107 assert_eq!(u32::from_le_bytes(bytes[24..28].try_into().unwrap()), SAMPLE_RATE);
108 assert_eq!(u32::from_le_bytes(bytes[40..44].try_into().unwrap()), 6);
109 assert_eq!(&bytes[44..], &[1, 0, 254, 255, 3, 0]);
110 }
111
112 #[test]
113 fn every_stage_gets_its_own_file() {
114 let directory = tempfile::tempdir().unwrap();
115 let mut dumps = StageDumps::create(directory.path()).unwrap();
116 dumps.write(3, &[5]);
117 drop(dumps);
118 let names: Vec<String> =
119 std::fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().into_string().unwrap()).collect();
120 assert_eq!(names.len(), StageDumps::STAGES.len());
121 assert!(names.iter().any(|name| name.ends_with("4-gain.wav")));
122 }
123}
vendor/deep_filter/Cargo.toml added +33 −0
@@ -0,0 +1,33 @@
1 # Trimmed copy of libDF (DeepFilterNet, https://github.com/Rikorose/DeepFilterNet @ d375b2d):
2 # real-time tract runtime and the DeepFilterNet3 model only, ported to tract 0.23.
3 [package]
4 name = "deep_filter"
5 version = "0.5.7-pre"
6 edition = "2021"
7 license = "MIT OR Apache-2.0"
8 publish = false
9
10 [lib]
11 name = "df"
12 path = "src/lib.rs"
13
14 [features]
15 default = ["default-model"]
16 default-model = []
17 timings = []
18
19 [dependencies]
20 anyhow = "1"
21 flate2 = "1"
22 itertools = "0.12"
23 log = "0.4"
24 ndarray = "0.17"
25 num-complex = "0.4"
26 realfft = "3.1"
27 rust-ini = "0.21"
28 rustfft = "6.1"
29 tar = "0.4"
30 tract-core = "0.23"
31 tract-hir = "0.23"
32 tract-onnx = "0.23"
33 tract-pulse = "0.23"
@@ -0,0 +1,33 @@
1# Trimmed copy of libDF (DeepFilterNet, https://github.com/Rikorose/DeepFilterNet @ d375b2d):
2# real-time tract runtime and the DeepFilterNet3 model only, ported to tract 0.23.
3[package]
4name = "deep_filter"
5version = "0.5.7-pre"
6edition = "2021"
7license = "MIT OR Apache-2.0"
8publish = false
9
10[lib]
11name = "df"
12path = "src/lib.rs"
13
14[features]
15default = ["default-model"]
16default-model = []
17timings = []
18
19[dependencies]
20anyhow = "1"
21flate2 = "1"
22itertools = "0.12"
23log = "0.4"
24ndarray = "0.17"
25num-complex = "0.4"
26realfft = "3.1"
27rust-ini = "0.21"
28rustfft = "6.1"
29tar = "0.4"
30tract-core = "0.23"
31tract-hir = "0.23"
32tract-onnx = "0.23"
33tract-pulse = "0.23"
vendor/deep_filter/LICENSE-APACHE added +201 −0
@@ -0,0 +1,201 @@
1 Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
7 1. Definitions.
8
9 "License" shall mean the terms and conditions for use, reproduction,
10 and distribution as defined by Sections 1 through 9 of this document.
11
12 "Licensor" shall mean the copyright owner or entity authorized by
13 the copyright owner that is granting the License.
14
15 "Legal Entity" shall mean the union of the acting entity and all
16 other entities that control, are controlled by, or are under common
17 control with that entity. For the purposes of this definition,
18 "control" means (i) the power, direct or indirect, to cause the
19 direction or management of such entity, whether by contract or
20 otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 outstanding shares, or (iii) beneficial ownership of such entity.
22
23 "You" (or "Your") shall mean an individual or Legal Entity
24 exercising permissions granted by this License.
25
26 "Source" form shall mean the preferred form for making modifications,
27 including but not limited to software source code, documentation
28 source, and configuration files.
29
30 "Object" form shall mean any form resulting from mechanical
31 transformation or translation of a Source form, including but
32 not limited to compiled object code, generated documentation,
33 and conversions to other media types.
34
35 "Work" shall mean the work of authorship, whether in Source or
36 Object form, made available under the License, as indicated by a
37 copyright notice that is included in or attached to the work
38 (an example is provided in the Appendix below).
39
40 "Derivative Works" shall mean any work, whether in Source or Object
41 form, that is based on (or derived from) the Work and for which the
42 editorial revisions, annotations, elaborations, or other modifications
43 represent, as a whole, an original work of authorship. For the purposes
44 of this License, Derivative Works shall not include works that remain
45 separable from, or merely link (or bind by name) to the interfaces of,
46 the Work and Derivative Works thereof.
47
48 "Contribution" shall mean any work of authorship, including
49 the original version of the Work and any modifications or additions
50 to that Work or Derivative Works thereof, that is intentionally
51 submitted to Licensor for inclusion in the Work by the copyright owner
52 or by an individual or Legal Entity authorized to submit on behalf of
53 the copyright owner. For the purposes of this definition, "submitted"
54 means any form of electronic, verbal, or written communication sent
55 to the Licensor or its representatives, including but not limited to
56 communication on electronic mailing lists, source code control systems,
57 and issue tracking systems that are managed by, or on behalf of, the
58 Licensor for the purpose of discussing and improving the Work, but
59 excluding communication that is conspicuously marked or otherwise
60 designated in writing by the copyright owner as "Not a Contribution."
61
62 "Contributor" shall mean Licensor and any individual or Legal Entity
63 on behalf of whom a Contribution has been received by Licensor and
64 subsequently incorporated within the Work.
65
66 2. Grant of Copyright License. Subject to the terms and conditions of
67 this License, each Contributor hereby grants to You a perpetual,
68 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 copyright license to reproduce, prepare Derivative Works of,
70 publicly display, publicly perform, sublicense, and distribute the
71 Work and such Derivative Works in Source or Object form.
72
73 3. Grant of Patent License. Subject to the terms and conditions of
74 this License, each Contributor hereby grants to You a perpetual,
75 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 (except as stated in this section) patent license to make, have made,
77 use, offer to sell, sell, import, and otherwise transfer the Work,
78 where such license applies only to those patent claims licensable
79 by such Contributor that are necessarily infringed by their
80 Contribution(s) alone or by combination of their Contribution(s)
81 with the Work to which such Contribution(s) was submitted. If You
82 institute patent litigation against any entity (including a
83 cross-claim or counterclaim in a lawsuit) alleging that the Work
84 or a Contribution incorporated within the Work constitutes direct
85 or contributory patent infringement, then any patent licenses
86 granted to You under this License for that Work shall terminate
87 as of the date such litigation is filed.
88
89 4. Redistribution. You may reproduce and distribute copies of the
90 Work or Derivative Works thereof in any medium, with or without
91 modifications, and in Source or Object form, provided that You
92 meet the following conditions:
93
94 (a) You must give any other recipients of the Work or
95 Derivative Works a copy of this License; and
96
97 (b) You must cause any modified files to carry prominent notices
98 stating that You changed the files; and
99
100 (c) You must retain, in the Source form of any Derivative Works
101 that You distribute, all copyright, patent, trademark, and
102 attribution notices from the Source form of the Work,
103 excluding those notices that do not pertain to any part of
104 the Derivative Works; and
105
106 (d) If the Work includes a "NOTICE" text file as part of its
107 distribution, then any Derivative Works that You distribute must
108 include a readable copy of the attribution notices contained
109 within such NOTICE file, excluding those notices that do not
110 pertain to any part of the Derivative Works, in at least one
111 of the following places: within a NOTICE text file distributed
112 as part of the Derivative Works; within the Source form or
113 documentation, if provided along with the Derivative Works; or,
114 within a display generated by the Derivative Works, if and
115 wherever such third-party notices normally appear. The contents
116 of the NOTICE file are for informational purposes only and
117 do not modify the License. You may add Your own attribution
118 notices within Derivative Works that You distribute, alongside
119 or as an addendum to the NOTICE text from the Work, provided
120 that such additional attribution notices cannot be construed
121 as modifying the License.
122
123 You may add Your own copyright statement to Your modifications and
124 may provide additional or different license terms and conditions
125 for use, reproduction, or distribution of Your modifications, or
126 for any such Derivative Works as a whole, provided Your use,
127 reproduction, and distribution of the Work otherwise complies with
128 the conditions stated in this License.
129
130 5. Submission of Contributions. Unless You explicitly state otherwise,
131 any Contribution intentionally submitted for inclusion in the Work
132 by You to the Licensor shall be under the terms and conditions of
133 this License, without any additional terms or conditions.
134 Notwithstanding the above, nothing herein shall supersede or modify
135 the terms of any separate license agreement you may have executed
136 with Licensor regarding such Contributions.
137
138 6. Trademarks. This License does not grant permission to use the trade
139 names, trademarks, service marks, or product names of the Licensor,
140 except as required for reasonable and customary use in describing the
141 origin of the Work and reproducing the content of the NOTICE file.
142
143 7. Disclaimer of Warranty. Unless required by applicable law or
144 agreed to in writing, Licensor provides the Work (and each
145 Contributor provides its Contributions) on an "AS IS" BASIS,
146 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 implied, including, without limitation, any warranties or conditions
148 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 PARTICULAR PURPOSE. You are solely responsible for determining the
150 appropriateness of using or redistributing the Work and assume any
151 risks associated with Your exercise of permissions under this License.
152
153 8. Limitation of Liability. In no event and under no legal theory,
154 whether in tort (including negligence), contract, or otherwise,
155 unless required by applicable law (such as deliberate and grossly
156 negligent acts) or agreed to in writing, shall any Contributor be
157 liable to You for damages, including any direct, indirect, special,
158 incidental, or consequential damages of any character arising as a
159 result of this License or out of the use or inability to use the
160 Work (including but not limited to damages for loss of goodwill,
161 work stoppage, computer failure or malfunction, or any and all
162 other commercial damages or losses), even if such Contributor
163 has been advised of the possibility of such damages.
164
165 9. Accepting Warranty or Additional Liability. While redistributing
166 the Work or Derivative Works thereof, You may choose to offer,
167 and charge a fee for, acceptance of support, warranty, indemnity,
168 or other liability obligations and/or rights consistent with this
169 License. However, in accepting such obligations, You may act only
170 on Your own behalf and on Your sole responsibility, not on behalf
171 of any other Contributor, and only if You agree to indemnify,
172 defend, and hold each Contributor harmless for any liability
173 incurred by, or claims asserted against, such Contributor by reason
174 of your accepting any such warranty or additional liability.
175
176 END OF TERMS AND CONDITIONS
177
178 APPENDIX: How to apply the Apache License to your work.
179
180 To apply the Apache License to your work, attach the following
181 boilerplate notice, with the fields enclosed by brackets "[]"
182 replaced with your own identifying information. (Don't include
183 the brackets!) The text should be enclosed in the appropriate
184 comment syntax for the file format. We also recommend that a
185 file or class name and description of purpose be included on the
186 same "printed page" as the copyright notice for easier
187 identification within third-party archives.
188
189 Copyright 2021 Hendrik Schröter
190
191 Licensed under the Apache License, Version 2.0 (the "License");
192 you may not use this file except in compliance with the License.
193 You may obtain a copy of the License at
194
195 http://www.apache.org/licenses/LICENSE-2.0
196
197 Unless required by applicable law or agreed to in writing, software
198 distributed under the License is distributed on an "AS IS" BASIS,
199 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 See the License for the specific language governing permissions and
201 limitations under the License.
@@ -0,0 +1,201 @@
1 Apache License
2 Version 2.0, January 2004
3 http://www.apache.org/licenses/
4
5TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
71. Definitions.
8
9 "License" shall mean the terms and conditions for use, reproduction,
10 and distribution as defined by Sections 1 through 9 of this document.
11
12 "Licensor" shall mean the copyright owner or entity authorized by
13 the copyright owner that is granting the License.
14
15 "Legal Entity" shall mean the union of the acting entity and all
16 other entities that control, are controlled by, or are under common
17 control with that entity. For the purposes of this definition,
18 "control" means (i) the power, direct or indirect, to cause the
19 direction or management of such entity, whether by contract or
20 otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 outstanding shares, or (iii) beneficial ownership of such entity.
22
23 "You" (or "Your") shall mean an individual or Legal Entity
24 exercising permissions granted by this License.
25
26 "Source" form shall mean the preferred form for making modifications,
27 including but not limited to software source code, documentation
28 source, and configuration files.
29
30 "Object" form shall mean any form resulting from mechanical
31 transformation or translation of a Source form, including but
32 not limited to compiled object code, generated documentation,
33 and conversions to other media types.
34
35 "Work" shall mean the work of authorship, whether in Source or
36 Object form, made available under the License, as indicated by a
37 copyright notice that is included in or attached to the work
38 (an example is provided in the Appendix below).
39
40 "Derivative Works" shall mean any work, whether in Source or Object
41 form, that is based on (or derived from) the Work and for which the
42 editorial revisions, annotations, elaborations, or other modifications
43 represent, as a whole, an original work of authorship. For the purposes
44 of this License, Derivative Works shall not include works that remain
45 separable from, or merely link (or bind by name) to the interfaces of,
46 the Work and Derivative Works thereof.
47
48 "Contribution" shall mean any work of authorship, including
49 the original version of the Work and any modifications or additions
50 to that Work or Derivative Works thereof, that is intentionally
51 submitted to Licensor for inclusion in the Work by the copyright owner
52 or by an individual or Legal Entity authorized to submit on behalf of
53 the copyright owner. For the purposes of this definition, "submitted"
54 means any form of electronic, verbal, or written communication sent
55 to the Licensor or its representatives, including but not limited to
56 communication on electronic mailing lists, source code control systems,
57 and issue tracking systems that are managed by, or on behalf of, the
58 Licensor for the purpose of discussing and improving the Work, but
59 excluding communication that is conspicuously marked or otherwise
60 designated in writing by the copyright owner as "Not a Contribution."
61
62 "Contributor" shall mean Licensor and any individual or Legal Entity
63 on behalf of whom a Contribution has been received by Licensor and
64 subsequently incorporated within the Work.
65
662. Grant of Copyright License. Subject to the terms and conditions of
67 this License, each Contributor hereby grants to You a perpetual,
68 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 copyright license to reproduce, prepare Derivative Works of,
70 publicly display, publicly perform, sublicense, and distribute the
71 Work and such Derivative Works in Source or Object form.
72
733. Grant of Patent License. Subject to the terms and conditions of
74 this License, each Contributor hereby grants to You a perpetual,
75 worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 (except as stated in this section) patent license to make, have made,
77 use, offer to sell, sell, import, and otherwise transfer the Work,
78 where such license applies only to those patent claims licensable
79 by such Contributor that are necessarily infringed by their
80 Contribution(s) alone or by combination of their Contribution(s)
81 with the Work to which such Contribution(s) was submitted. If You
82 institute patent litigation against any entity (including a
83 cross-claim or counterclaim in a lawsuit) alleging that the Work
84 or a Contribution incorporated within the Work constitutes direct
85 or contributory patent infringement, then any patent licenses
86 granted to You under this License for that Work shall terminate
87 as of the date such litigation is filed.
88
894. Redistribution. You may reproduce and distribute copies of the
90 Work or Derivative Works thereof in any medium, with or without
91 modifications, and in Source or Object form, provided that You
92 meet the following conditions:
93
94 (a) You must give any other recipients of the Work or
95 Derivative Works a copy of this License; and
96
97 (b) You must cause any modified files to carry prominent notices
98 stating that You changed the files; and
99
100 (c) You must retain, in the Source form of any Derivative Works
101 that You distribute, all copyright, patent, trademark, and
102 attribution notices from the Source form of the Work,
103 excluding those notices that do not pertain to any part of
104 the Derivative Works; and
105
106 (d) If the Work includes a "NOTICE" text file as part of its
107 distribution, then any Derivative Works that You distribute must
108 include a readable copy of the attribution notices contained
109 within such NOTICE file, excluding those notices that do not
110 pertain to any part of the Derivative Works, in at least one
111 of the following places: within a NOTICE text file distributed
112 as part of the Derivative Works; within the Source form or
113 documentation, if provided along with the Derivative Works; or,
114 within a display generated by the Derivative Works, if and
115 wherever such third-party notices normally appear. The contents
116 of the NOTICE file are for informational purposes only and
117 do not modify the License. You may add Your own attribution
118 notices within Derivative Works that You distribute, alongside
119 or as an addendum to the NOTICE text from the Work, provided
120 that such additional attribution notices cannot be construed
121 as modifying the License.
122
123 You may add Your own copyright statement to Your modifications and
124 may provide additional or different license terms and conditions
125 for use, reproduction, or distribution of Your modifications, or
126 for any such Derivative Works as a whole, provided Your use,
127 reproduction, and distribution of the Work otherwise complies with
128 the conditions stated in this License.
129
1305. Submission of Contributions. Unless You explicitly state otherwise,
131 any Contribution intentionally submitted for inclusion in the Work
132 by You to the Licensor shall be under the terms and conditions of
133 this License, without any additional terms or conditions.
134 Notwithstanding the above, nothing herein shall supersede or modify
135 the terms of any separate license agreement you may have executed
136 with Licensor regarding such Contributions.
137
1386. Trademarks. This License does not grant permission to use the trade
139 names, trademarks, service marks, or product names of the Licensor,
140 except as required for reasonable and customary use in describing the
141 origin of the Work and reproducing the content of the NOTICE file.
142
1437. Disclaimer of Warranty. Unless required by applicable law or
144 agreed to in writing, Licensor provides the Work (and each
145 Contributor provides its Contributions) on an "AS IS" BASIS,
146 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 implied, including, without limitation, any warranties or conditions
148 of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 PARTICULAR PURPOSE. You are solely responsible for determining the
150 appropriateness of using or redistributing the Work and assume any
151 risks associated with Your exercise of permissions under this License.
152
1538. Limitation of Liability. In no event and under no legal theory,
154 whether in tort (including negligence), contract, or otherwise,
155 unless required by applicable law (such as deliberate and grossly
156 negligent acts) or agreed to in writing, shall any Contributor be
157 liable to You for damages, including any direct, indirect, special,
158 incidental, or consequential damages of any character arising as a
159 result of this License or out of the use or inability to use the
160 Work (including but not limited to damages for loss of goodwill,
161 work stoppage, computer failure or malfunction, or any and all
162 other commercial damages or losses), even if such Contributor
163 has been advised of the possibility of such damages.
164
1659. Accepting Warranty or Additional Liability. While redistributing
166 the Work or Derivative Works thereof, You may choose to offer,
167 and charge a fee for, acceptance of support, warranty, indemnity,
168 or other liability obligations and/or rights consistent with this
169 License. However, in accepting such obligations, You may act only
170 on Your own behalf and on Your sole responsibility, not on behalf
171 of any other Contributor, and only if You agree to indemnify,
172 defend, and hold each Contributor harmless for any liability
173 incurred by, or claims asserted against, such Contributor by reason
174 of your accepting any such warranty or additional liability.
175
176END OF TERMS AND CONDITIONS
177
178APPENDIX: How to apply the Apache License to your work.
179
180 To apply the Apache License to your work, attach the following
181 boilerplate notice, with the fields enclosed by brackets "[]"
182 replaced with your own identifying information. (Don't include
183 the brackets!) The text should be enclosed in the appropriate
184 comment syntax for the file format. We also recommend that a
185 file or class name and description of purpose be included on the
186 same "printed page" as the copyright notice for easier
187 identification within third-party archives.
188
189Copyright 2021 Hendrik Schröter
190
191Licensed under the Apache License, Version 2.0 (the "License");
192you may not use this file except in compliance with the License.
193You may obtain a copy of the License at
194
195 http://www.apache.org/licenses/LICENSE-2.0
196
197Unless required by applicable law or agreed to in writing, software
198distributed under the License is distributed on an "AS IS" BASIS,
199WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200See the License for the specific language governing permissions and
201limitations under the License.
vendor/deep_filter/LICENSE-MIT added +19 −0
@@ -0,0 +1,19 @@
1 The MIT License (MIT)
2 Copyright (c) 2021 Hendrik Schröter
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8 the Software, and to permit persons to whom the Software is furnished to do so,
9 subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17 COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,19 @@
1The MIT License (MIT)
2Copyright (c) 2021 Hendrik Schröter
3
4Permission is hereby granted, free of charge, to any person obtaining a copy of
5this software and associated documentation files (the "Software"), to deal in
6the Software without restriction, including without limitation the rights to
7use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8the Software, and to permit persons to whom the Software is furnished to do so,
9subject to the following conditions:
10
11The above copyright notice and this permission notice shall be included in all
12copies or substantial portions of the Software.
13
14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vendor/deep_filter/models/DeepFilterNet3_onnx.tar.gz added Binary file +0 −0

The contents of this binary file are not shown.

vendor/deep_filter/src/lib.rs added +594 −0
@@ -0,0 +1,594 @@
1 #![allow(mismatched_lifetime_syntaxes)]
2 #![allow(dead_code)]
3
4 use std::ops::MulAssign;
5 use std::sync::Arc;
6 use std::vec::Vec;
7
8 use itertools::izip;
9 use realfft::{ComplexToReal, RealFftPlanner, RealToComplex};
10
11 pub type Complex32 = num_complex::Complex32;
12
13 pub const MEAN_NORM_INIT: [f32; 2] = [-60., -90.];
14 pub const UNIT_NORM_INIT: [f32; 2] = [0.001, 0.0001];
15
16 pub mod tract;
17
18 pub(crate) fn freq2erb(freq_hz: f32) -> f32 {
19 9.265 * (freq_hz / (24.7 * 9.265)).ln_1p()
20 }
21 pub(crate) fn erb2freq(n_erb: f32) -> f32 {
22 24.7 * 9.265 * ((n_erb / 9.265).exp() - 1.)
23 }
24
25 #[derive(Clone)]
26 pub struct DFState {
27 pub sr: usize,
28 pub frame_size: usize, // hop_size
29 pub window_size: usize, // Same as fft_size
30 pub freq_size: usize, // fft_size / 2 + 1
31 pub fft_forward: Arc<dyn RealToComplex<f32>>,
32 pub fft_inverse: Arc<dyn ComplexToReal<f32>>,
33 pub window: Vec<f32>,
34 pub wnorm: f32,
35 pub erb: Vec<usize>, // frequencies bandwidth (in bands) per ERB band
36 analysis_mem: Vec<f32>,
37 analysis_scratch: Vec<Complex32>,
38 synthesis_mem: Vec<f32>,
39 synthesis_scratch: Vec<Complex32>,
40 mean_norm_state: Vec<f32>,
41 unit_norm_state: Vec<f32>,
42 }
43
44 pub fn erb_fb(sr: usize, fft_size: usize, nb_bands: usize, min_nb_freqs: usize) -> Vec<usize> {
45 // Init ERB filter bank
46 let nyq_freq = sr / 2;
47 let freq_width = sr as f32 / fft_size as f32;
48 let erb_low: f32 = freq2erb(0.);
49 let erb_high: f32 = freq2erb(nyq_freq as f32);
50 let mut erb = vec![0; nb_bands];
51 let step = (erb_high - erb_low) / nb_bands as f32;
52 let min_nb_freqs = min_nb_freqs as i32; // Minimum number of frequency bands per erb band
53 let mut prev_freq = 0; // Last frequency band of the previous erb band
54 let mut freq_over = 0; // Number of frequency bands that are already stored in previous erb bands
55 for i in 1..nb_bands + 1 {
56 let f = erb2freq(erb_low + i as f32 * step);
57 let fb = (f / freq_width).round() as usize;
58 let mut nb_freqs = fb as i32 - prev_freq as i32 - freq_over;
59 if nb_freqs < min_nb_freqs {
60 // Not enough freq bins in current bark bin
61 freq_over = min_nb_freqs - nb_freqs; // keep track of number of enforced bins
62 nb_freqs = min_nb_freqs; // enforce min_nb_freqs
63 } else {
64 freq_over = 0
65 }
66 erb[i - 1] = nb_freqs as usize;
67 prev_freq = fb;
68 }
69 erb[nb_bands - 1] += 1; // since we have WINDOW_SIZE/2+1 frequency bins
70 let too_large = erb.iter().sum::<usize>() - (fft_size / 2 + 1);
71 if too_large > 0 {
72 erb[nb_bands - 1] -= too_large;
73 }
74 debug_assert!(erb.iter().sum::<usize>() == fft_size / 2 + 1);
75 erb
76 }
77
78 // TODO Check delay for diferent hop sizes
79 impl DFState {
80 pub fn new(
81 sr: usize,
82 fft_size: usize,
83 hop_size: usize,
84 nb_bands: usize,
85 min_nb_freqs: usize,
86 ) -> Self {
87 assert!(hop_size * 2 <= fft_size);
88 let mut fft = RealFftPlanner::<f32>::new();
89 let frame_size = hop_size;
90 let window_size = fft_size;
91 let window_size_h = fft_size / 2;
92 let freq_size = fft_size / 2 + 1;
93 let forward = fft.plan_fft_forward(fft_size);
94 let backward = fft.plan_fft_inverse(fft_size);
95 let analysis_mem = vec![0.; fft_size - frame_size];
96 let synthesis_mem = vec![0.; fft_size - frame_size];
97 let analysis_scratch = forward.make_scratch_vec();
98 let synthesis_scratch = backward.make_scratch_vec();
99
100 let erb = erb_fb(sr, fft_size, nb_bands, min_nb_freqs);
101
102 let pi = std::f64::consts::PI;
103 // Initialize the vorbis window: sin(pi/2*sin^2(pi*n/N))
104 let mut window = vec![0.0; fft_size];
105 for (i, w) in window.iter_mut().enumerate() {
106 let sin = (0.5 * pi * (i as f64 + 0.5) / window_size_h as f64).sin();
107 *w = (0.5 * pi * sin * sin).sin() as f32;
108 }
109 let wnorm = 1. / (window_size.pow(2) as f32 / (2 * frame_size) as f32);
110 let mean_norm_state = Vec::new();
111 let unit_norm_state = Vec::new();
112
113 DFState {
114 sr,
115 frame_size,
116 window_size,
117 freq_size,
118 fft_forward: forward,
119 fft_inverse: backward,
120 erb,
121 analysis_mem,
122 analysis_scratch,
123 synthesis_mem,
124 synthesis_scratch,
125 window,
126 wnorm,
127 mean_norm_state,
128 unit_norm_state,
129 }
130 }
131
132 pub fn reset(&mut self) {
133 self.analysis_mem.fill(0.);
134 self.synthesis_mem.fill(0.);
135 }
136
137 pub fn process_frame(&mut self, input: &[f32], output: &mut [f32]) {
138 debug_assert_eq!(input.len(), self.frame_size);
139 debug_assert_eq!(output.len(), self.frame_size);
140 process_frame(input, output, self);
141 }
142
143 pub fn analysis(&mut self, input: &[f32], output: &mut [Complex32]) {
144 debug_assert_eq!(input.len(), self.frame_size);
145 debug_assert_eq!(output.len(), self.freq_size);
146 frame_analysis(input, output, self)
147 }
148
149 pub fn synthesis(&mut self, input: &mut [Complex32], output: &mut [f32]) {
150 debug_assert_eq!(input.len(), self.freq_size);
151 debug_assert_eq!(output.len(), self.frame_size);
152 frame_synthesis(input, output, self)
153 }
154
155 pub fn init_norm_states(&mut self, nb_df_freqs: usize) {
156 self.init_mean_norm_state();
157 self.init_unit_norm_state(nb_df_freqs);
158 }
159
160 pub fn init_mean_norm_state(&mut self) {
161 let min = MEAN_NORM_INIT[0];
162 let max = MEAN_NORM_INIT[1];
163 let nb_erb = self.erb.len();
164 let step = (max - min) / (nb_erb - 1) as f32;
165 let mut state = Vec::with_capacity(nb_erb);
166 for i in 0..nb_erb {
167 state.push(min + i as f32 * step);
168 }
169 self.mean_norm_state = state;
170 }
171 pub fn init_unit_norm_state(&mut self, nb_freqs: usize) {
172 let min = UNIT_NORM_INIT[0];
173 let max = UNIT_NORM_INIT[1];
174 let step = (max - min) / (nb_freqs - 1) as f32;
175 let mut state = Vec::with_capacity(nb_freqs);
176 for i in 0..nb_freqs {
177 state.push(min + i as f32 * step);
178 }
179 self.unit_norm_state = state;
180 }
181
182 pub fn feat_erb(&mut self, input: &[Complex32], alpha: f32, output: &mut [f32]) {
183 compute_band_corr(output, input, input, &self.erb); // ERB FB
184 for o in output.iter_mut() {
185 *o = (*o + 1e-10).log10() * 10.;
186 }
187 band_mean_norm_erb(output, &mut self.mean_norm_state, alpha); // Exponential mean norm
188 }
189
190 pub fn feat_cplx(&mut self, input: &[Complex32], alpha: f32, output: &mut [Complex32]) {
191 output.clone_from_slice(input);
192 band_unit_norm(output, &mut self.unit_norm_state, alpha)
193 }
194
195 pub fn feat_cplx_t(&mut self, input: &[Complex32], alpha: f32, output: &mut [f32]) {
196 band_unit_norm_t(input, &mut self.unit_norm_state, alpha, output)
197 }
198
199 pub fn apply_mask(&self, output: &mut [Complex32], gains: &[f32]) {
200 apply_interp_band_gain(output, gains, &self.erb)
201 }
202 }
203
204 impl Default for DFState {
205 fn default() -> Self {
206 Self::new(48000, 960, 480, 32, 2)
207 }
208 }
209
210 pub fn band_mean_norm_freq(xs: &[Complex32], xout: &mut [f32], state: &mut [f32], alpha: f32) {
211 debug_assert_eq!(xs.len(), state.len());
212 debug_assert_eq!(xout.len(), state.len());
213 for (x, s, xo) in izip!(xs.iter(), state.iter_mut(), xout.iter_mut()) {
214 let xabs = x.norm();
215 *s = xabs * (1. - alpha) + *s * alpha;
216 *xo = xabs - *s;
217 }
218 }
219
220 pub fn band_mean_norm_erb(xs: &mut [f32], state: &mut [f32], alpha: f32) {
221 debug_assert_eq!(xs.len(), state.len());
222 for (x, s) in xs.iter_mut().zip(state.iter_mut()) {
223 *s = *x * (1. - alpha) + *s * alpha;
224 *x -= *s;
225 *x /= 40.;
226 }
227 }
228
229 pub fn band_unit_norm(xs: &mut [Complex32], state: &mut [f32], alpha: f32) {
230 debug_assert_eq!(xs.len(), state.len());
231 for (x, s) in xs.iter_mut().zip(state.iter_mut()) {
232 *s = x.norm() * (1. - alpha) + *s * alpha;
233 *x /= s.sqrt();
234 }
235 }
236
237 /// Band unit norm, but with transposed output type. I.e. out contains first all real elements,
238 /// followed by all imaginary elements. This memory layout is different from Complex32 slice which
239 /// contains real and imaginary part as interleaved values.
240 pub fn band_unit_norm_t(xs: &[Complex32], state: &mut [f32], alpha: f32, out: &mut [f32]) {
241 debug_assert_eq!(xs.len(), state.len());
242 debug_assert_eq!(xs.len(), out.len() / 2);
243 let (o_re, o_im) = out.split_at_mut(xs.len());
244 for (x, s, o_re, o_im) in izip!(
245 xs.iter(),
246 state.iter_mut(),
247 o_re.iter_mut(),
248 o_im.iter_mut(),
249 ) {
250 *s = x.norm() * (1. - alpha) + *s * alpha;
251 *o_re /= s.sqrt();
252 *o_im /= s.sqrt();
253 }
254 }
255
256 pub fn compute_band_corr(out: &mut [f32], x: &[Complex32], p: &[Complex32], erb_fb: &[usize]) {
257 for y in out.iter_mut() {
258 *y = 0.0;
259 }
260 debug_assert_eq!(erb_fb.len(), out.len());
261
262 let mut bcsum = 0;
263 for (&band_size, out_b) in erb_fb.iter().zip(out.iter_mut()) {
264 let k = 1. / band_size as f32;
265 for j in 0..band_size {
266 let idx = bcsum + j;
267 *out_b += (x[idx].re * p[idx].re + x[idx].im * p[idx].im) * k;
268 }
269 bcsum += band_size;
270 }
271 }
272
273 pub fn band_compr(out: &mut [f32], x: &[f32], erb_fb: &[usize]) {
274 for y in out.iter_mut() {
275 *y = 0.0;
276 }
277 debug_assert_eq!(erb_fb.len(), out.len());
278
279 let mut bcsum = 0;
280 for (&band_size, out_b) in erb_fb.iter().zip(out.iter_mut()) {
281 let k = 1. / band_size as f32;
282 for j in 0..band_size {
283 let idx = bcsum + j;
284 *out_b += x[idx] * k;
285 }
286 bcsum += band_size;
287 }
288 }
289
290 pub fn apply_interp_band_gain<T>(out: &mut [T], band_e: &[f32], erb_fb: &[usize])
291 where
292 T: MulAssign<f32>,
293 {
294 let mut bcsum = 0;
295 for (&band_size, &b) in erb_fb.iter().zip(band_e.iter()) {
296 for j in 0..band_size {
297 let idx = bcsum + j;
298 out[idx] *= b;
299 }
300 bcsum += band_size;
301 }
302 }
303
304 fn interp_band_gain(out: &mut [f32], band_e: &[f32], erb_fb: &[usize]) {
305 let mut bcsum = 0;
306 for (&band_size, &b) in erb_fb.iter().zip(band_e.iter()) {
307 for j in 0..band_size {
308 let idx = bcsum + j;
309 out[idx] = b;
310 }
311 bcsum += band_size;
312 }
313 }
314
315 fn apply_band_gain(out: &mut [Complex32], band_e: &[f32], erb_fb: &[usize]) {
316 let mut bcsum = 0;
317 for (&band_size, b) in erb_fb.iter().zip(band_e.iter()) {
318 for j in 0..band_size {
319 let idx = bcsum + j;
320 out[idx] *= *b;
321 }
322 bcsum += band_size;
323 }
324 }
325
326 fn process_frame(input: &[f32], output: &mut [f32], state: &mut DFState) {
327 let mut freq_mem = vec![Complex32::default(); state.freq_size];
328 frame_analysis(input, &mut freq_mem, state);
329 frame_synthesis(&mut freq_mem, output, state);
330 }
331
332 fn frame_analysis(input: &[f32], output: &mut [Complex32], state: &mut DFState) {
333 debug_assert_eq!(input.len(), state.frame_size);
334 debug_assert_eq!(output.len(), state.freq_size);
335
336 let mut buf = state.fft_forward.make_input_vec();
337 // First part of the window on the previous frame
338 let (buf_first, buf_second) = buf.split_at_mut(state.window_size - state.frame_size);
339 let (window_first, window_second) = state.window.split_at(state.window_size - state.frame_size);
340 let analysis_split = state.analysis_mem.len() - state.frame_size;
341 for (&y, &w, x) in izip!(
342 state.analysis_mem.iter(),
343 window_first.iter(),
344 buf_first.iter_mut(),
345 ) {
346 *x = y * w;
347 }
348 // Second part of the window on the new input frame
349 for ((&y, &w), x) in input.iter().zip(window_second.iter()).zip(buf_second.iter_mut()) {
350 *x = y * w;
351 }
352 // Shift analysis_mem
353 if analysis_split > 0 {
354 // hop_size is < window_size / 2
355 state.analysis_mem.rotate_left(state.frame_size);
356 }
357 // Copy input to analysis_mem for next iteration
358 for (x, &y) in state.analysis_mem[analysis_split..].iter_mut().zip(input) {
359 *x = y
360 }
361 state
362 .fft_forward
363 .process_with_scratch(&mut buf, output, &mut state.analysis_scratch)
364 .expect("FFT forward failed");
365 // Apply normalization in analysis only
366 let norm = state.wnorm;
367 for x in output.iter_mut() {
368 *x *= norm;
369 }
370 }
371
372 fn frame_synthesis(input: &mut [Complex32], output: &mut [f32], state: &mut DFState) {
373 let mut x = state.fft_inverse.make_output_vec();
374 match state
375 .fft_inverse
376 .process_with_scratch(input, &mut x, &mut state.synthesis_scratch)
377 {
378 Err(realfft::FftError::InputValues(_, _)) => (),
379 Err(e) => panic!("Error during fft_inverse: {:?}", e),
380 Ok(_) => (),
381 }
382 apply_window_in_place(&mut x, &state.window);
383 let (x_first, x_second) = x.split_at(state.frame_size);
384 for ((&xi, &mem), out) in x_first.iter().zip(state.synthesis_mem.iter()).zip(output.iter_mut())
385 {
386 *out = xi + mem;
387 }
388
389 let split = state.synthesis_mem.len() - state.frame_size;
390 if split > 0 {
391 state.synthesis_mem.rotate_left(state.frame_size);
392 }
393 let (s_first, s_second) = state.synthesis_mem.split_at_mut(split);
394 let (xs_first, xs_second) = x_second.split_at(split);
395 for (&xi, mem) in xs_first.iter().zip(s_first.iter_mut()) {
396 // Overlap add for next frame
397 *mem += xi;
398 }
399 for (&xi, mem) in xs_second.iter().zip(s_second.iter_mut()) {
400 // Override left shifted buffer
401 *mem = xi;
402 }
403 }
404
405 fn apply_window(xs: &[f32], window: &[f32]) -> Vec<f32> {
406 let mut out = vec![0.; window.len()];
407 for (&x, &w, o) in izip!(xs.iter(), window.iter(), out.iter_mut()) {
408 *o = x * w;
409 }
410 out
411 }
412
413 fn apply_window_in_place<'a, I>(xs: &mut [f32], window: I)
414 where
415 I: IntoIterator<Item = &'a f32>,
416 {
417 for (x, &w) in xs.iter_mut().zip(window) {
418 *x *= w;
419 }
420 }
421
422 pub fn post_filter(noisy: &[Complex32], enh: &mut [Complex32], beta: f32) {
423 let beta_p1 = beta + 1.;
424 let eps = 1e-12;
425 let pi = std::f32::consts::PI;
426 let mut g = [0.0; 4];
427 let mut g_sin = [0.0; 4];
428 let mut pf = [0.0; 4];
429 for (n, e) in noisy.chunks_exact(4).zip(enh.chunks_exact_mut(4)) {
430 g[0] = (e[0].norm() / (n[0].norm() + eps)).min(1.).max(eps);
431 g[1] = (e[1].norm() / (n[1].norm() + eps)).min(1.).max(eps);
432 g[2] = (e[2].norm() / (n[2].norm() + eps)).min(1.).max(eps);
433 g[3] = (e[3].norm() / (n[3].norm() + eps)).min(1.).max(eps);
434 g_sin[0] = g[0] * (g[0] * pi / 2.0).sin();
435 g_sin[1] = g[1] * (g[1] * pi / 2.0).sin();
436 g_sin[2] = g[2] * (g[2] * pi / 2.0).sin();
437 g_sin[3] = g[3] * (g[3] * pi / 2.0).sin();
438 pf[0] = (beta_p1 * g[0] / (1. + beta * (g[0] / g_sin[0]).powi(2))) / g[0];
439 pf[1] = (beta_p1 * g[1] / (1. + beta * (g[1] / g_sin[1]).powi(2))) / g[1];
440 pf[2] = (beta_p1 * g[2] / (1. + beta * (g[2] / g_sin[2]).powi(2))) / g[2];
441 pf[3] = (beta_p1 * g[3] / (1. + beta * (g[3] / g_sin[3]).powi(2))) / g[3];
442 e[0] *= pf[0];
443 e[1] *= pf[1];
444 e[2] *= pf[2];
445 e[3] *= pf[3];
446 }
447 }
448
449 pub(crate) struct NonNan(f32);
450
451 impl NonNan {
452 fn new(val: f32) -> Option<NonNan> {
453 if val.is_nan() {
454 None
455 } else {
456 Some(NonNan(val))
457 }
458 }
459 fn get(&self) -> f32 {
460 self.0
461 }
462 }
463
464 pub fn find_max<'a, I>(vals: I) -> Option<f32>
465 where
466 I: IntoIterator<Item = &'a f32>,
467 {
468 vals.into_iter().try_fold(f32::MIN, |acc, v| {
469 let nonnan: NonNan = match NonNan::new(*v) {
470 None => return None,
471 Some(x) => x,
472 };
473 Some(nonnan.get().max(acc))
474 })
475 }
476
477 pub fn find_max_abs<'a, I>(vals: I) -> Option<f32>
478 where
479 I: IntoIterator<Item = &'a f32>,
480 {
481 vals.into_iter().try_fold(0., |acc, v| {
482 let nonnan: NonNan = match NonNan::new(v.abs()) {
483 None => return None,
484 Some(x) => x,
485 };
486 Some(nonnan.get().max(acc))
487 })
488 }
489
490 pub fn find_min<'a, I>(vals: I) -> Option<f32>
491 where
492 I: IntoIterator<Item = &'a f32>,
493 {
494 vals.into_iter().try_fold(f32::MAX, |acc, v| {
495 let nonnan: NonNan = match NonNan::new(*v) {
496 None => return None,
497 Some(x) => x,
498 };
499 Some(nonnan.get().min(acc))
500 })
501 }
502
503 pub fn find_min_abs<'a, I>(vals: I) -> Option<f32>
504 where
505 I: IntoIterator<Item = &'a f32>,
506 {
507 vals.into_iter().try_fold(0., |acc, v| {
508 let nonnan: NonNan = match NonNan::new(v.abs()) {
509 None => return None,
510 Some(x) => x,
511 };
512 Some(nonnan.get().min(acc))
513 })
514 }
515
516 pub fn argmax<'a, I>(vals: I) -> Option<usize>
517 where
518 I: IntoIterator<Item = &'a f32>,
519 {
520 let mut index = 0;
521 let mut high = f32::MIN;
522 vals.into_iter().enumerate().for_each(|(i, v)| {
523 if v > &high {
524 high = *v;
525 index = i;
526 }
527 });
528 Some(index)
529 }
530
531 pub fn argmax_abs<'a, I>(vals: I) -> Option<usize>
532 where
533 I: IntoIterator<Item = &'a f32>,
534 {
535 let mut index = 0;
536 let mut high = f32::MIN;
537 vals.into_iter().enumerate().for_each(|(i, v)| {
538 if v > &high {
539 high = v.abs();
540 index = i;
541 }
542 });
543 Some(index)
544 }
545
546 pub fn rms<'a, I>(vals: I) -> f32
547 where
548 I: IntoIterator<Item = &'a f32>,
549 {
550 let mut n = 0;
551 let pow_sum = vals.into_iter().fold(0., |acc, v| {
552 n += 1;
553 acc + v.powi(2)
554 });
555 (pow_sum / n as f32).sqrt()
556 }
557 pub fn rms_v<I>(vals: I) -> f32
558 where
559 I: IntoIterator<Item = f32>,
560 {
561 let mut n = 0;
562 let pow_sum = vals.into_iter().fold(0., |acc, v| {
563 n += 1;
564 acc + v.powi(2)
565 });
566 (pow_sum / n as f32).sqrt()
567 }
568
569 pub fn mean<'a, I>(vals: I) -> f32
570 where
571 I: IntoIterator<Item = &'a f32>,
572 {
573 let mut n = 0;
574 let sum = vals.into_iter().fold(0., |acc, v| {
575 n += 1;
576 acc + v
577 });
578 sum / n as f32
579 }
580
581 pub fn median<T>(x: &mut [T]) -> T
582 where
583 T: PartialOrd<T> + Copy,
584 {
585 if x.len() == 1 {
586 return x[0];
587 }
588 if x.is_empty() {
589 panic!("Empty input slice");
590 }
591 x.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
592 let mid = x.len() / 2;
593 x[mid]
594 }
@@ -0,0 +1,594 @@
1#![allow(mismatched_lifetime_syntaxes)]
2#![allow(dead_code)]
3
4use std::ops::MulAssign;
5use std::sync::Arc;
6use std::vec::Vec;
7
8use itertools::izip;
9use realfft::{ComplexToReal, RealFftPlanner, RealToComplex};
10
11pub type Complex32 = num_complex::Complex32;
12
13pub const MEAN_NORM_INIT: [f32; 2] = [-60., -90.];
14pub const UNIT_NORM_INIT: [f32; 2] = [0.001, 0.0001];
15
16pub mod tract;
17
18pub(crate) fn freq2erb(freq_hz: f32) -> f32 {
19 9.265 * (freq_hz / (24.7 * 9.265)).ln_1p()
20}
21pub(crate) fn erb2freq(n_erb: f32) -> f32 {
22 24.7 * 9.265 * ((n_erb / 9.265).exp() - 1.)
23}
24
25#[derive(Clone)]
26pub struct DFState {
27 pub sr: usize,
28 pub frame_size: usize, // hop_size
29 pub window_size: usize, // Same as fft_size
30 pub freq_size: usize, // fft_size / 2 + 1
31 pub fft_forward: Arc<dyn RealToComplex<f32>>,
32 pub fft_inverse: Arc<dyn ComplexToReal<f32>>,
33 pub window: Vec<f32>,
34 pub wnorm: f32,
35 pub erb: Vec<usize>, // frequencies bandwidth (in bands) per ERB band
36 analysis_mem: Vec<f32>,
37 analysis_scratch: Vec<Complex32>,
38 synthesis_mem: Vec<f32>,
39 synthesis_scratch: Vec<Complex32>,
40 mean_norm_state: Vec<f32>,
41 unit_norm_state: Vec<f32>,
42}
43
44pub fn erb_fb(sr: usize, fft_size: usize, nb_bands: usize, min_nb_freqs: usize) -> Vec<usize> {
45 // Init ERB filter bank
46 let nyq_freq = sr / 2;
47 let freq_width = sr as f32 / fft_size as f32;
48 let erb_low: f32 = freq2erb(0.);
49 let erb_high: f32 = freq2erb(nyq_freq as f32);
50 let mut erb = vec![0; nb_bands];
51 let step = (erb_high - erb_low) / nb_bands as f32;
52 let min_nb_freqs = min_nb_freqs as i32; // Minimum number of frequency bands per erb band
53 let mut prev_freq = 0; // Last frequency band of the previous erb band
54 let mut freq_over = 0; // Number of frequency bands that are already stored in previous erb bands
55 for i in 1..nb_bands + 1 {
56 let f = erb2freq(erb_low + i as f32 * step);
57 let fb = (f / freq_width).round() as usize;
58 let mut nb_freqs = fb as i32 - prev_freq as i32 - freq_over;
59 if nb_freqs < min_nb_freqs {
60 // Not enough freq bins in current bark bin
61 freq_over = min_nb_freqs - nb_freqs; // keep track of number of enforced bins
62 nb_freqs = min_nb_freqs; // enforce min_nb_freqs
63 } else {
64 freq_over = 0
65 }
66 erb[i - 1] = nb_freqs as usize;
67 prev_freq = fb;
68 }
69 erb[nb_bands - 1] += 1; // since we have WINDOW_SIZE/2+1 frequency bins
70 let too_large = erb.iter().sum::<usize>() - (fft_size / 2 + 1);
71 if too_large > 0 {
72 erb[nb_bands - 1] -= too_large;
73 }
74 debug_assert!(erb.iter().sum::<usize>() == fft_size / 2 + 1);
75 erb
76}
77
78// TODO Check delay for diferent hop sizes
79impl DFState {
80 pub fn new(
81 sr: usize,
82 fft_size: usize,
83 hop_size: usize,
84 nb_bands: usize,
85 min_nb_freqs: usize,
86 ) -> Self {
87 assert!(hop_size * 2 <= fft_size);
88 let mut fft = RealFftPlanner::<f32>::new();
89 let frame_size = hop_size;
90 let window_size = fft_size;
91 let window_size_h = fft_size / 2;
92 let freq_size = fft_size / 2 + 1;
93 let forward = fft.plan_fft_forward(fft_size);
94 let backward = fft.plan_fft_inverse(fft_size);
95 let analysis_mem = vec![0.; fft_size - frame_size];
96 let synthesis_mem = vec![0.; fft_size - frame_size];
97 let analysis_scratch = forward.make_scratch_vec();
98 let synthesis_scratch = backward.make_scratch_vec();
99
100 let erb = erb_fb(sr, fft_size, nb_bands, min_nb_freqs);
101
102 let pi = std::f64::consts::PI;
103 // Initialize the vorbis window: sin(pi/2*sin^2(pi*n/N))
104 let mut window = vec![0.0; fft_size];
105 for (i, w) in window.iter_mut().enumerate() {
106 let sin = (0.5 * pi * (i as f64 + 0.5) / window_size_h as f64).sin();
107 *w = (0.5 * pi * sin * sin).sin() as f32;
108 }
109 let wnorm = 1. / (window_size.pow(2) as f32 / (2 * frame_size) as f32);
110 let mean_norm_state = Vec::new();
111 let unit_norm_state = Vec::new();
112
113 DFState {
114 sr,
115 frame_size,
116 window_size,
117 freq_size,
118 fft_forward: forward,
119 fft_inverse: backward,
120 erb,
121 analysis_mem,
122 analysis_scratch,
123 synthesis_mem,
124 synthesis_scratch,
125 window,
126 wnorm,
127 mean_norm_state,
128 unit_norm_state,
129 }
130 }
131
132 pub fn reset(&mut self) {
133 self.analysis_mem.fill(0.);
134 self.synthesis_mem.fill(0.);
135 }
136
137 pub fn process_frame(&mut self, input: &[f32], output: &mut [f32]) {
138 debug_assert_eq!(input.len(), self.frame_size);
139 debug_assert_eq!(output.len(), self.frame_size);
140 process_frame(input, output, self);
141 }
142
143 pub fn analysis(&mut self, input: &[f32], output: &mut [Complex32]) {
144 debug_assert_eq!(input.len(), self.frame_size);
145 debug_assert_eq!(output.len(), self.freq_size);
146 frame_analysis(input, output, self)
147 }
148
149 pub fn synthesis(&mut self, input: &mut [Complex32], output: &mut [f32]) {
150 debug_assert_eq!(input.len(), self.freq_size);
151 debug_assert_eq!(output.len(), self.frame_size);
152 frame_synthesis(input, output, self)
153 }
154
155 pub fn init_norm_states(&mut self, nb_df_freqs: usize) {
156 self.init_mean_norm_state();
157 self.init_unit_norm_state(nb_df_freqs);
158 }
159
160 pub fn init_mean_norm_state(&mut self) {
161 let min = MEAN_NORM_INIT[0];
162 let max = MEAN_NORM_INIT[1];
163 let nb_erb = self.erb.len();
164 let step = (max - min) / (nb_erb - 1) as f32;
165 let mut state = Vec::with_capacity(nb_erb);
166 for i in 0..nb_erb {
167 state.push(min + i as f32 * step);
168 }
169 self.mean_norm_state = state;
170 }
171 pub fn init_unit_norm_state(&mut self, nb_freqs: usize) {
172 let min = UNIT_NORM_INIT[0];
173 let max = UNIT_NORM_INIT[1];
174 let step = (max - min) / (nb_freqs - 1) as f32;
175 let mut state = Vec::with_capacity(nb_freqs);
176 for i in 0..nb_freqs {
177 state.push(min + i as f32 * step);
178 }
179 self.unit_norm_state = state;
180 }
181
182 pub fn feat_erb(&mut self, input: &[Complex32], alpha: f32, output: &mut [f32]) {
183 compute_band_corr(output, input, input, &self.erb); // ERB FB
184 for o in output.iter_mut() {
185 *o = (*o + 1e-10).log10() * 10.;
186 }
187 band_mean_norm_erb(output, &mut self.mean_norm_state, alpha); // Exponential mean norm
188 }
189
190 pub fn feat_cplx(&mut self, input: &[Complex32], alpha: f32, output: &mut [Complex32]) {
191 output.clone_from_slice(input);
192 band_unit_norm(output, &mut self.unit_norm_state, alpha)
193 }
194
195 pub fn feat_cplx_t(&mut self, input: &[Complex32], alpha: f32, output: &mut [f32]) {
196 band_unit_norm_t(input, &mut self.unit_norm_state, alpha, output)
197 }
198
199 pub fn apply_mask(&self, output: &mut [Complex32], gains: &[f32]) {
200 apply_interp_band_gain(output, gains, &self.erb)
201 }
202}
203
204impl Default for DFState {
205 fn default() -> Self {
206 Self::new(48000, 960, 480, 32, 2)
207 }
208}
209
210pub fn band_mean_norm_freq(xs: &[Complex32], xout: &mut [f32], state: &mut [f32], alpha: f32) {
211 debug_assert_eq!(xs.len(), state.len());
212 debug_assert_eq!(xout.len(), state.len());
213 for (x, s, xo) in izip!(xs.iter(), state.iter_mut(), xout.iter_mut()) {
214 let xabs = x.norm();
215 *s = xabs * (1. - alpha) + *s * alpha;
216 *xo = xabs - *s;
217 }
218}
219
220pub fn band_mean_norm_erb(xs: &mut [f32], state: &mut [f32], alpha: f32) {
221 debug_assert_eq!(xs.len(), state.len());
222 for (x, s) in xs.iter_mut().zip(state.iter_mut()) {
223 *s = *x * (1. - alpha) + *s * alpha;
224 *x -= *s;
225 *x /= 40.;
226 }
227}
228
229pub fn band_unit_norm(xs: &mut [Complex32], state: &mut [f32], alpha: f32) {
230 debug_assert_eq!(xs.len(), state.len());
231 for (x, s) in xs.iter_mut().zip(state.iter_mut()) {
232 *s = x.norm() * (1. - alpha) + *s * alpha;
233 *x /= s.sqrt();
234 }
235}
236
237/// Band unit norm, but with transposed output type. I.e. out contains first all real elements,
238/// followed by all imaginary elements. This memory layout is different from Complex32 slice which
239/// contains real and imaginary part as interleaved values.
240pub fn band_unit_norm_t(xs: &[Complex32], state: &mut [f32], alpha: f32, out: &mut [f32]) {
241 debug_assert_eq!(xs.len(), state.len());
242 debug_assert_eq!(xs.len(), out.len() / 2);
243 let (o_re, o_im) = out.split_at_mut(xs.len());
244 for (x, s, o_re, o_im) in izip!(
245 xs.iter(),
246 state.iter_mut(),
247 o_re.iter_mut(),
248 o_im.iter_mut(),
249 ) {
250 *s = x.norm() * (1. - alpha) + *s * alpha;
251 *o_re /= s.sqrt();
252 *o_im /= s.sqrt();
253 }
254}
255
256pub fn compute_band_corr(out: &mut [f32], x: &[Complex32], p: &[Complex32], erb_fb: &[usize]) {
257 for y in out.iter_mut() {
258 *y = 0.0;
259 }
260 debug_assert_eq!(erb_fb.len(), out.len());
261
262 let mut bcsum = 0;
263 for (&band_size, out_b) in erb_fb.iter().zip(out.iter_mut()) {
264 let k = 1. / band_size as f32;
265 for j in 0..band_size {
266 let idx = bcsum + j;
267 *out_b += (x[idx].re * p[idx].re + x[idx].im * p[idx].im) * k;
268 }
269 bcsum += band_size;
270 }
271}
272
273pub fn band_compr(out: &mut [f32], x: &[f32], erb_fb: &[usize]) {
274 for y in out.iter_mut() {
275 *y = 0.0;
276 }
277 debug_assert_eq!(erb_fb.len(), out.len());
278
279 let mut bcsum = 0;
280 for (&band_size, out_b) in erb_fb.iter().zip(out.iter_mut()) {
281 let k = 1. / band_size as f32;
282 for j in 0..band_size {
283 let idx = bcsum + j;
284 *out_b += x[idx] * k;
285 }
286 bcsum += band_size;
287 }
288}
289
290pub fn apply_interp_band_gain<T>(out: &mut [T], band_e: &[f32], erb_fb: &[usize])
291where
292 T: MulAssign<f32>,
293{
294 let mut bcsum = 0;
295 for (&band_size, &b) in erb_fb.iter().zip(band_e.iter()) {
296 for j in 0..band_size {
297 let idx = bcsum + j;
298 out[idx] *= b;
299 }
300 bcsum += band_size;
301 }
302}
303
304fn interp_band_gain(out: &mut [f32], band_e: &[f32], erb_fb: &[usize]) {
305 let mut bcsum = 0;
306 for (&band_size, &b) in erb_fb.iter().zip(band_e.iter()) {
307 for j in 0..band_size {
308 let idx = bcsum + j;
309 out[idx] = b;
310 }
311 bcsum += band_size;
312 }
313}
314
315fn apply_band_gain(out: &mut [Complex32], band_e: &[f32], erb_fb: &[usize]) {
316 let mut bcsum = 0;
317 for (&band_size, b) in erb_fb.iter().zip(band_e.iter()) {
318 for j in 0..band_size {
319 let idx = bcsum + j;
320 out[idx] *= *b;
321 }
322 bcsum += band_size;
323 }
324}
325
326fn process_frame(input: &[f32], output: &mut [f32], state: &mut DFState) {
327 let mut freq_mem = vec![Complex32::default(); state.freq_size];
328 frame_analysis(input, &mut freq_mem, state);
329 frame_synthesis(&mut freq_mem, output, state);
330}
331
332fn frame_analysis(input: &[f32], output: &mut [Complex32], state: &mut DFState) {
333 debug_assert_eq!(input.len(), state.frame_size);
334 debug_assert_eq!(output.len(), state.freq_size);
335
336 let mut buf = state.fft_forward.make_input_vec();
337 // First part of the window on the previous frame
338 let (buf_first, buf_second) = buf.split_at_mut(state.window_size - state.frame_size);
339 let (window_first, window_second) = state.window.split_at(state.window_size - state.frame_size);
340 let analysis_split = state.analysis_mem.len() - state.frame_size;
341 for (&y, &w, x) in izip!(
342 state.analysis_mem.iter(),
343 window_first.iter(),
344 buf_first.iter_mut(),
345 ) {
346 *x = y * w;
347 }
348 // Second part of the window on the new input frame
349 for ((&y, &w), x) in input.iter().zip(window_second.iter()).zip(buf_second.iter_mut()) {
350 *x = y * w;
351 }
352 // Shift analysis_mem
353 if analysis_split > 0 {
354 // hop_size is < window_size / 2
355 state.analysis_mem.rotate_left(state.frame_size);
356 }
357 // Copy input to analysis_mem for next iteration
358 for (x, &y) in state.analysis_mem[analysis_split..].iter_mut().zip(input) {
359 *x = y
360 }
361 state
362 .fft_forward
363 .process_with_scratch(&mut buf, output, &mut state.analysis_scratch)
364 .expect("FFT forward failed");
365 // Apply normalization in analysis only
366 let norm = state.wnorm;
367 for x in output.iter_mut() {
368 *x *= norm;
369 }
370}
371
372fn frame_synthesis(input: &mut [Complex32], output: &mut [f32], state: &mut DFState) {
373 let mut x = state.fft_inverse.make_output_vec();
374 match state
375 .fft_inverse
376 .process_with_scratch(input, &mut x, &mut state.synthesis_scratch)
377 {
378 Err(realfft::FftError::InputValues(_, _)) => (),
379 Err(e) => panic!("Error during fft_inverse: {:?}", e),
380 Ok(_) => (),
381 }
382 apply_window_in_place(&mut x, &state.window);
383 let (x_first, x_second) = x.split_at(state.frame_size);
384 for ((&xi, &mem), out) in x_first.iter().zip(state.synthesis_mem.iter()).zip(output.iter_mut())
385 {
386 *out = xi + mem;
387 }
388
389 let split = state.synthesis_mem.len() - state.frame_size;
390 if split > 0 {
391 state.synthesis_mem.rotate_left(state.frame_size);
392 }
393 let (s_first, s_second) = state.synthesis_mem.split_at_mut(split);
394 let (xs_first, xs_second) = x_second.split_at(split);
395 for (&xi, mem) in xs_first.iter().zip(s_first.iter_mut()) {
396 // Overlap add for next frame
397 *mem += xi;
398 }
399 for (&xi, mem) in xs_second.iter().zip(s_second.iter_mut()) {
400 // Override left shifted buffer
401 *mem = xi;
402 }
403}
404
405fn apply_window(xs: &[f32], window: &[f32]) -> Vec<f32> {
406 let mut out = vec![0.; window.len()];
407 for (&x, &w, o) in izip!(xs.iter(), window.iter(), out.iter_mut()) {
408 *o = x * w;
409 }
410 out
411}
412
413fn apply_window_in_place<'a, I>(xs: &mut [f32], window: I)
414where
415 I: IntoIterator<Item = &'a f32>,
416{
417 for (x, &w) in xs.iter_mut().zip(window) {
418 *x *= w;
419 }
420}
421
422pub fn post_filter(noisy: &[Complex32], enh: &mut [Complex32], beta: f32) {
423 let beta_p1 = beta + 1.;
424 let eps = 1e-12;
425 let pi = std::f32::consts::PI;
426 let mut g = [0.0; 4];
427 let mut g_sin = [0.0; 4];
428 let mut pf = [0.0; 4];
429 for (n, e) in noisy.chunks_exact(4).zip(enh.chunks_exact_mut(4)) {
430 g[0] = (e[0].norm() / (n[0].norm() + eps)).min(1.).max(eps);
431 g[1] = (e[1].norm() / (n[1].norm() + eps)).min(1.).max(eps);
432 g[2] = (e[2].norm() / (n[2].norm() + eps)).min(1.).max(eps);
433 g[3] = (e[3].norm() / (n[3].norm() + eps)).min(1.).max(eps);
434 g_sin[0] = g[0] * (g[0] * pi / 2.0).sin();
435 g_sin[1] = g[1] * (g[1] * pi / 2.0).sin();
436 g_sin[2] = g[2] * (g[2] * pi / 2.0).sin();
437 g_sin[3] = g[3] * (g[3] * pi / 2.0).sin();
438 pf[0] = (beta_p1 * g[0] / (1. + beta * (g[0] / g_sin[0]).powi(2))) / g[0];
439 pf[1] = (beta_p1 * g[1] / (1. + beta * (g[1] / g_sin[1]).powi(2))) / g[1];
440 pf[2] = (beta_p1 * g[2] / (1. + beta * (g[2] / g_sin[2]).powi(2))) / g[2];
441 pf[3] = (beta_p1 * g[3] / (1. + beta * (g[3] / g_sin[3]).powi(2))) / g[3];
442 e[0] *= pf[0];
443 e[1] *= pf[1];
444 e[2] *= pf[2];
445 e[3] *= pf[3];
446 }
447}
448
449pub(crate) struct NonNan(f32);
450
451impl NonNan {
452 fn new(val: f32) -> Option<NonNan> {
453 if val.is_nan() {
454 None
455 } else {
456 Some(NonNan(val))
457 }
458 }
459 fn get(&self) -> f32 {
460 self.0
461 }
462}
463
464pub fn find_max<'a, I>(vals: I) -> Option<f32>
465where
466 I: IntoIterator<Item = &'a f32>,
467{
468 vals.into_iter().try_fold(f32::MIN, |acc, v| {
469 let nonnan: NonNan = match NonNan::new(*v) {
470 None => return None,
471 Some(x) => x,
472 };
473 Some(nonnan.get().max(acc))
474 })
475}
476
477pub fn find_max_abs<'a, I>(vals: I) -> Option<f32>
478where
479 I: IntoIterator<Item = &'a f32>,
480{
481 vals.into_iter().try_fold(0., |acc, v| {
482 let nonnan: NonNan = match NonNan::new(v.abs()) {
483 None => return None,
484 Some(x) => x,
485 };
486 Some(nonnan.get().max(acc))
487 })
488}
489
490pub fn find_min<'a, I>(vals: I) -> Option<f32>
491where
492 I: IntoIterator<Item = &'a f32>,
493{
494 vals.into_iter().try_fold(f32::MAX, |acc, v| {
495 let nonnan: NonNan = match NonNan::new(*v) {
496 None => return None,
497 Some(x) => x,
498 };
499 Some(nonnan.get().min(acc))
500 })
501}
502
503pub fn find_min_abs<'a, I>(vals: I) -> Option<f32>
504where
505 I: IntoIterator<Item = &'a f32>,
506{
507 vals.into_iter().try_fold(0., |acc, v| {
508 let nonnan: NonNan = match NonNan::new(v.abs()) {
509 None => return None,
510 Some(x) => x,
511 };
512 Some(nonnan.get().min(acc))
513 })
514}
515
516pub fn argmax<'a, I>(vals: I) -> Option<usize>
517where
518 I: IntoIterator<Item = &'a f32>,
519{
520 let mut index = 0;
521 let mut high = f32::MIN;
522 vals.into_iter().enumerate().for_each(|(i, v)| {
523 if v > &high {
524 high = *v;
525 index = i;
526 }
527 });
528 Some(index)
529}
530
531pub fn argmax_abs<'a, I>(vals: I) -> Option<usize>
532where
533 I: IntoIterator<Item = &'a f32>,
534{
535 let mut index = 0;
536 let mut high = f32::MIN;
537 vals.into_iter().enumerate().for_each(|(i, v)| {
538 if v > &high {
539 high = v.abs();
540 index = i;
541 }
542 });
543 Some(index)
544}
545
546pub fn rms<'a, I>(vals: I) -> f32
547where
548 I: IntoIterator<Item = &'a f32>,
549{
550 let mut n = 0;
551 let pow_sum = vals.into_iter().fold(0., |acc, v| {
552 n += 1;
553 acc + v.powi(2)
554 });
555 (pow_sum / n as f32).sqrt()
556}
557pub fn rms_v<I>(vals: I) -> f32
558where
559 I: IntoIterator<Item = f32>,
560{
561 let mut n = 0;
562 let pow_sum = vals.into_iter().fold(0., |acc, v| {
563 n += 1;
564 acc + v.powi(2)
565 });
566 (pow_sum / n as f32).sqrt()
567}
568
569pub fn mean<'a, I>(vals: I) -> f32
570where
571 I: IntoIterator<Item = &'a f32>,
572{
573 let mut n = 0;
574 let sum = vals.into_iter().fold(0., |acc, v| {
575 n += 1;
576 acc + v
577 });
578 sum / n as f32
579}
580
581pub fn median<T>(x: &mut [T]) -> T
582where
583 T: PartialOrd<T> + Copy,
584{
585 if x.len() == 1 {
586 return x[0];
587 }
588 if x.is_empty() {
589 panic!("Empty input slice");
590 }
591 x.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
592 let mid = x.len() / 2;
593 x[mid]
594}
vendor/deep_filter/src/tract.rs added +1075 −0
@@ -0,0 +1,1075 @@
1 use std::fs::File;
2 use std::io::{Cursor, Read};
3 use std::path::{Path, PathBuf};
4 #[cfg(feature = "timings")]
5 use std::time::Instant;
6
7 use anyhow::{bail, Context, Result};
8 use flate2::read::GzDecoder;
9 use ini::Ini;
10 use ndarray::{prelude::*, Axis};
11 use tar::Archive;
12 use tract_core::internal::tract_itertools::izip;
13 use tract_core::internal::tract_smallvec::alloc::collections::VecDeque;
14 use tract_core::ops;
15 use tract_core::prelude::*;
16 use tract_onnx::{prelude::*, tract_hir::shapefactoid};
17 use tract_pulse::{internal::ToDim, model::*};
18
19 use crate::*;
20
21 #[derive(Clone)]
22 pub struct DfParams {
23 config: Ini,
24 enc: Vec<u8>,
25 erb_dec: Vec<u8>,
26 df_dec: Vec<u8>,
27 }
28
29 impl DfParams {
30 pub fn new(tar_file: PathBuf) -> Result<Self> {
31 let file = File::open(tar_file).context("Could not open model tar file.")?;
32 Self::from_targz(file)
33 }
34 pub fn from_bytes(tar_buf: &[u8]) -> Result<Self> {
35 Self::from_targz(tar_buf)
36 }
37 fn from_targz<R: Read>(f: R) -> Result<Self> {
38 let tar = GzDecoder::new(f);
39 let mut archive = Archive::new(tar);
40 let mut enc = Vec::new();
41 let mut erb_dec = Vec::new();
42 let mut df_dec = Vec::new();
43 let mut config = Ini::new();
44 for e in archive.entries().context("Could not extract models from tar file.")? {
45 let mut file = e.context("Could not open model tar entry.")?;
46 let path = file.path().unwrap();
47 if path.ends_with("enc.onnx") {
48 file.read_to_end(&mut enc)?;
49 } else if path.ends_with("erb_dec.onnx") {
50 file.read_to_end(&mut erb_dec)?;
51 } else if path.ends_with("df_dec.onnx") {
52 file.read_to_end(&mut df_dec)?;
53 } else if path.ends_with("config.ini") {
54 config =
55 Ini::read_from(&mut file).context("Could not load config from tar file.")?;
56 } else if path.ends_with("version.txt") {
57 let mut version = String::new();
58 file.read_to_string(&mut version).expect("Could not read version.txt");
59 log::info!("Loading model with id: {}", version);
60 } else {
61 log::warn!("Found non-matching item in model tar file: {:?}", path)
62 }
63 }
64 Ok(Self {
65 config,
66 enc,
67 erb_dec,
68 df_dec,
69 })
70 }
71 }
72 impl Default for DfParams {
73 #[allow(unreachable_code)]
74 fn default() -> Self {
75 #[cfg(feature = "default-model")]
76 {
77 log::debug!("Loading model DeepFilterNet3_onnx.tar.gz");
78 DfParams::from_bytes(include_bytes!("../models/DeepFilterNet3_onnx.tar.gz"))
79 .expect("Could not load model config")
80 }
81 #[cfg(not(feature = "default-model"))]
82 panic!("Not compiled with a default model")
83 }
84 }
85
86 #[derive(Clone)]
87 pub enum ReduceMask {
88 NONE = 0,
89 MAX = 1,
90 MEAN = 2,
91 }
92 impl Default for ReduceMask {
93 fn default() -> Self {
94 ReduceMask::NONE
95 }
96 }
97 impl TryFrom<i32> for ReduceMask {
98 type Error = ();
99
100 fn try_from(v: i32) -> Result<Self, Self::Error> {
101 match v {
102 x if x == ReduceMask::NONE as i32 => Ok(ReduceMask::NONE),
103 x if x == ReduceMask::MAX as i32 => Ok(ReduceMask::MAX),
104 x if x == ReduceMask::MEAN as i32 => Ok(ReduceMask::MEAN),
105 _ => Err(()),
106 }
107 }
108 }
109 pub struct RuntimeParams {
110 pub n_ch: usize,
111 pub post_filter: bool,
112 pub post_filter_beta: f32,
113 pub atten_lim_db: f32,
114 pub min_db_thresh: f32,
115 pub max_db_erb_thresh: f32,
116 pub max_db_df_thresh: f32,
117 pub reduce_mask: ReduceMask,
118 }
119 impl RuntimeParams {
120 pub fn new(
121 n_ch: usize,
122 post_filter_beta: f32,
123 atten_lim_db: f32,
124 min_db_thresh: f32,
125 max_db_erb_thresh: f32,
126 max_db_df_thresh: f32,
127 reduce_mask: ReduceMask,
128 ) -> Self {
129 let post_filter = post_filter_beta > 0.;
130 Self {
131 n_ch,
132 post_filter,
133 post_filter_beta,
134 atten_lim_db,
135 min_db_thresh,
136 max_db_erb_thresh,
137 max_db_df_thresh,
138 reduce_mask,
139 }
140 }
141 pub fn with_post_filter(mut self, beta: f32) -> Self {
142 assert!(beta >= 0.); // Cannot be negative
143 if beta > 0. {
144 self.post_filter = true;
145 }
146 self.post_filter_beta = beta;
147 self
148 }
149 pub fn with_atten_lim(mut self, atten_lim_db: f32) -> Self {
150 self.atten_lim_db = atten_lim_db;
151 self
152 }
153 pub fn with_thresholds(
154 mut self,
155 min_db_thresh: f32,
156 max_db_erb_thresh: f32,
157 max_db_df_thresh: f32,
158 ) -> Self {
159 self.min_db_thresh = min_db_thresh;
160 self.max_db_erb_thresh = max_db_erb_thresh;
161 self.max_db_df_thresh = max_db_df_thresh;
162 self
163 }
164 pub fn with_mask_reduce(mut self, red: ReduceMask) -> Self {
165 self.reduce_mask = red;
166 self
167 }
168 pub fn default_with_ch(channels: usize) -> Self {
169 RuntimeParams {
170 n_ch: channels,
171 post_filter: false,
172 post_filter_beta: 0.02,
173 atten_lim_db: 100.,
174 min_db_thresh: -10.,
175 max_db_erb_thresh: 30.,
176 max_db_df_thresh: 20.,
177 reduce_mask: ReduceMask::MEAN,
178 }
179 }
180 }
181 impl Default for RuntimeParams {
182 fn default() -> Self {
183 Self::default_with_ch(1)
184 }
185 }
186
187 pub type TractModel = TypedSimpleState;
188
189 #[derive(Clone)]
190 pub struct DfTract {
191 enc: TractModel,
192 erb_dec: TractModel,
193 df_dec: TractModel,
194 pub lookahead: usize,
195 pub df_lookahead: usize,
196 pub conv_lookahead: usize,
197 pub sr: usize,
198 pub ch: usize,
199 pub fft_size: usize,
200 pub hop_size: usize,
201 pub nb_erb: usize,
202 pub min_nb_erb_freqs: usize,
203 pub nb_df: usize,
204 pub n_freqs: usize,
205 pub df_order: usize,
206 pub post_filter: bool,
207 pub post_filter_beta: f32,
208 pub alpha: f32,
209 pub min_db_thresh: f32,
210 pub max_db_erb_thresh: f32,
211 pub max_db_df_thresh: f32,
212 pub reduce_mask: ReduceMask,
213 pub atten_lim: Option<f32>,
214 pub df_states: Vec<DFState>,
215 pub spec_buf: Tensor, // Real-valued spectrogram buffer of shape [n_ch, 1, 1, n_freqs, 2]
216 erb_buf: TValue, // Real-valued ERB feature buffer of shape [n_ch, 1, 1, n_erb]
217 cplx_buf: TValue, // Real-valued complex epectrum shape for DF of shape [n_ch, 1, nb_df, 2]
218 m_zeros: Vec<f32>, // Preallocated buffer for applying a zero mask
219 rolling_spec_buf_y: VecDeque<Tensor>, // Enhanced stage 1 spec buf
220 rolling_spec_buf_x: VecDeque<Tensor>, // Noisy spec buf
221 skip_counter: usize, // Increment when wanting to skip processing due to low RMS
222 }
223
224 #[cfg(feature = "default-model")]
225 impl Default for DfTract {
226 fn default() -> Self {
227 let r_params = RuntimeParams::default();
228 let df_params = DfParams::default();
229 DfTract::new(df_params, &r_params).expect("Could not load DfTract")
230 }
231 }
232
233 impl DfTract {
234 /// A clone with its own feature buffers; the derived clone shares them and process() writes them in place.
235 pub fn fork(&self) -> Self {
236 let mut copy = self.clone();
237 copy.erb_buf = TValue::from(Tensor::clone(&self.erb_buf));
238 copy.cplx_buf = TValue::from(Tensor::clone(&self.cplx_buf));
239 copy
240 }
241
242 pub fn new(dfp: DfParams, rp: &RuntimeParams) -> Result<Self> {
243 #[cfg(feature = "timings")]
244 let t0 = Instant::now();
245 let config = dfp.config;
246 let model_cfg = config.section(Some("deepfilternet")).unwrap();
247 let df_cfg = config.section(Some("df")).unwrap();
248 let ch = rp.n_ch;
249
250 let enc = init_encoder_from_read(&mut Cursor::new(dfp.enc), df_cfg, ch)?;
251 let erb_dec = init_erb_decoder_from_read(
252 &mut Cursor::new(dfp.erb_dec),
253 model_cfg,
254 df_cfg,
255 ch,
256 Some(rp.reduce_mask.clone()),
257 )?;
258 let df_dec =
259 init_df_decoder_from_read(&mut Cursor::new(dfp.df_dec), model_cfg, df_cfg, ch)?;
260 let enc = enc.into_runnable()?.spawn()?;
261 let erb_dec = erb_dec.into_runnable()?.spawn()?;
262 let df_dec = df_dec.into_runnable()?.spawn()?;
263 #[cfg(feature = "timings")]
264 let t1 = Instant::now();
265
266 let sr = df_cfg.get("sr").unwrap().parse::<usize>()?;
267 let hop_size = df_cfg.get("hop_size").unwrap().parse::<usize>()?;
268 let fft_size = df_cfg.get("fft_size").unwrap().parse::<usize>()?;
269 let min_nb_erb_freqs = df_cfg.get("min_nb_erb_freqs").unwrap().parse::<usize>()?;
270 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
271 let nb_df = df_cfg.get("nb_df").unwrap().parse::<usize>()?;
272 let df_order = df_cfg
273 .get("df_order")
274 .unwrap_or_else(|| model_cfg.get("df_order").unwrap())
275 .parse::<usize>()?;
276 let conv_lookahead = model_cfg.get("conv_lookahead").unwrap().parse::<usize>()?;
277 let df_lookahead = df_cfg
278 .get("df_lookahead")
279 .unwrap_or_else(|| model_cfg.get("df_lookahead").unwrap())
280 .parse::<usize>()?;
281 let n_freqs = fft_size / 2 + 1;
282 let alpha = if let Some(a) = df_cfg.get("norm_alpha") {
283 a.parse::<f32>()?
284 } else {
285 let tau = df_cfg.get("norm_tau").unwrap().parse::<f32>()?;
286 calc_norm_alpha(sr, hop_size, tau)
287 };
288 let atten_lim = rp.atten_lim_db.abs();
289 let atten_lim = if atten_lim >= 100. {
290 None
291 } else if atten_lim < 0.01 {
292 log::warn!("Attenuation limit too strong. No noise reduction will be performed");
293 Some(1.)
294 } else {
295 log::info!("Running with an attenuation limit of {:.0} dB", atten_lim);
296 Some(10f32.powf(-atten_lim / 20.))
297 };
298 let spec_shape = [1, 1, 1, n_freqs, 2];
299 let spec_buf = unsafe { Tensor::uninitialized_dt(f32::datum_type(), &spec_shape)? };
300 let erb_buf = TValue::from(unsafe {
301 Tensor::uninitialized_dt(f32::datum_type(), &[1, 1, 1, nb_erb])?
302 });
303 let cplx_buf = TValue::from(unsafe {
304 Tensor::uninitialized_dt(f32::datum_type(), &[1, 1, nb_df, 2])?
305 });
306 let m_zeros = vec![0.; nb_erb];
307
308 let model_type = config.section(Some("train")).unwrap().get("model").unwrap();
309 let lookahead = match model_type {
310 "deepfilternet2" => bail!(
311 "DeepFilterNet2 models are deprecated. Please use version v0.3.1 for these models."
312 ),
313 "deepfilternet3" => conv_lookahead.max(df_lookahead),
314 _ => bail!("Unsupported model type {}", model_type),
315 };
316 log::info!(
317 "Running with model type {} lookahead {}",
318 model_type,
319 lookahead
320 );
321
322 let rolling_spec_buf_y = VecDeque::with_capacity(df_order + lookahead);
323 let rolling_spec_buf_x = VecDeque::with_capacity(lookahead.max(df_order));
324
325 let mut state = DFState::new(sr, fft_size, hop_size, nb_erb, min_nb_erb_freqs);
326 state.init_norm_states(nb_df);
327 let df_states = vec![state];
328
329 let mut m = Self {
330 enc,
331 erb_dec,
332 df_dec,
333 lookahead,
334 conv_lookahead,
335 df_lookahead,
336 sr,
337 ch,
338 fft_size,
339 hop_size,
340 nb_erb,
341 min_nb_erb_freqs,
342 nb_df,
343 n_freqs,
344 df_order,
345 alpha,
346 min_db_thresh: rp.min_db_thresh,
347 max_db_erb_thresh: rp.max_db_erb_thresh,
348 max_db_df_thresh: rp.max_db_df_thresh,
349 reduce_mask: rp.reduce_mask.clone(),
350 atten_lim,
351 spec_buf,
352 erb_buf,
353 cplx_buf,
354 m_zeros,
355 rolling_spec_buf_y,
356 rolling_spec_buf_x,
357 df_states,
358 post_filter: rp.post_filter,
359 post_filter_beta: rp.post_filter_beta,
360 skip_counter: 0,
361 };
362 m.init()?;
363 #[cfg(feature = "timings")]
364 log::info!(
365 "Init DfTract in {:.2}ms (models in {:.2}ms)",
366 t0.elapsed().as_secs_f32() * 1000.,
367 (t1 - t0).as_secs_f32() * 1000.
368 );
369
370 Ok(m)
371 }
372
373 pub fn set_pf_beta(&mut self, beta: f32) {
374 log::debug!("Setting post-filter beta to {beta}");
375 self.post_filter_beta = beta;
376 if beta > 0. {
377 self.post_filter = true;
378 } else if beta == 0. {
379 self.post_filter = false;
380 } else {
381 log::warn!("Post-filter beta cannot be smaller than 0.");
382 self.post_filter = false;
383 self.post_filter_beta = 0.;
384 }
385 }
386
387 pub fn set_atten_lim(&mut self, db: f32) {
388 let lim = db.abs();
389 self.atten_lim = if lim >= 100. {
390 None
391 } else if lim < 0.01 {
392 log::warn!("Attenuation limit too strong. No noise reduction will be performed");
393 Some(1.)
394 } else {
395 log::debug!("Setting attenuation limit to {:.1} dB", lim);
396 Some(10f32.powf(-lim / 20.))
397 };
398 }
399
400 pub fn init(&mut self) -> Result<()> {
401 let ch = self.ch;
402 let spec_shape = [ch, 1, 1, self.n_freqs, 2];
403 self.rolling_spec_buf_y.clear();
404 for _ in 0..(self.df_order + self.conv_lookahead) {
405 self.rolling_spec_buf_y
406 .push_back(tensor0(0f32).broadcast_scalar_to_shape(&spec_shape)?);
407 }
408 for _ in 0..self.df_order.max(self.lookahead) {
409 self.rolling_spec_buf_x
410 .push_back(tensor0(0f32).broadcast_scalar_to_shape(&spec_shape)?);
411 }
412 if ch > self.df_states.len() {
413 for _ in self.df_states.len()..ch {
414 let mut state = DFState::new(
415 self.sr,
416 self.fft_size,
417 self.hop_size,
418 self.nb_erb,
419 self.min_nb_erb_freqs,
420 );
421 state.init_norm_states(self.nb_df);
422 self.df_states.push(state)
423 }
424 }
425 self.spec_buf = Tensor::zero::<f32>(&spec_shape)?;
426 self.erb_buf = TValue::from(Tensor::zero::<f32>(&[ch, 1, 1, self.nb_erb])?);
427 self.cplx_buf = TValue::from(Tensor::zero::<f32>(&[ch, 1, self.nb_df, 2])?);
428
429 Ok(())
430 }
431
432 /// Process a FD sample and return the raw gains and DF coefs.
433 ///
434 /// Warning:
435 /// `self.spec_buf` needs to be initialized correctly before calling this method!
436 ///
437 /// Returns:
438 /// - lsnr: Local SNR estiamte.
439 /// - gains: Gain estimates of shape `[n_ch, 1, 1, n_erb]`.
440 /// - coefs: Real-valued DF coefficients estimates of shape `[n_ch, 1, 1, n_erb, 2]`.
441 pub fn process_raw(&mut self) -> Result<(f32, Option<Tensor>, Option<Tensor>)> {
442 let spec = self.spec_buf.to_plain_array_view()?;
443 let ch = spec.len_of(Axis(0));
444
445 for (nsy_ch, mut erb_ch, mut cplx_ch, state) in izip!(
446 spec.axis_iter(Axis(0)),
447 tvalue_to_array_view_mut(&mut self.erb_buf).axis_iter_mut(Axis(0)),
448 tvalue_to_array_view_mut(&mut self.cplx_buf).axis_iter_mut(Axis(0)),
449 self.df_states.iter_mut()
450 ) {
451 let nsy_ch = as_slice_complex(nsy_ch.as_slice().unwrap());
452 state.feat_erb(nsy_ch, self.alpha, erb_ch.as_slice_mut().unwrap());
453 state.feat_cplx(
454 &nsy_ch[..self.nb_df],
455 self.alpha,
456 as_slice_mut_complex(cplx_ch.as_slice_mut().unwrap()),
457 );
458 }
459 // Run encoder
460 let mut enc_emb = self.enc.run(tvec!(
461 self.erb_buf.clone(),
462 TValue::from(self.cplx_buf.clone().into_tensor().permute_axes(&[0, 3, 1, 2])?)
463 ))?;
464
465 let lsnr_value = enc_emb.pop().unwrap();
466 let lsnr = *lsnr_value.try_as_plain_ram()?.to_scalar::<f32>()?;
467 let c0 = enc_emb.pop().unwrap();
468 let emb = enc_emb.pop().unwrap();
469
470 let (apply_gains, apply_gain_zeros, apply_df) = self.apply_stages(lsnr);
471
472 log::trace!(
473 "Enhancing frame with lsnr {:>5.1} dB. Applying stage 1: {} and stage 2: {}.",
474 lsnr,
475 apply_gains,
476 apply_df
477 );
478
479 let m = if apply_gains {
480 let dec_input = tvec!(
481 emb.clone(),
482 enc_emb.pop().unwrap(), // e3
483 enc_emb.pop().unwrap(), // e2
484 enc_emb.pop().unwrap(), // e1
485 enc_emb.pop().unwrap(), // e0
486 );
487 let mut m = self.erb_dec.run(dec_input)?;
488 let mut m = m.pop().unwrap().into_tensor();
489 m.remove_axis(1)?;
490 m.remove_axis(1)?;
491 Some(m)
492 } else if apply_gain_zeros {
493 Some(Tensor::zero::<f32>(&[self.ch, self.nb_erb])?)
494 } else {
495 None
496 };
497
498 let coefs = if apply_df {
499 let mut coefs = self.df_dec.run(tvec!(emb, c0))?.pop().unwrap().into_tensor();
500 coefs.set_shape(&[ch, self.nb_df, self.df_order, 2])?;
501 Some(coefs)
502 } else {
503 None
504 };
505
506 Ok((lsnr, m, coefs))
507 }
508
509 /// Process a noisy time domain sample and return the enhanced sample via mutable argument.
510 pub fn process(&mut self, noisy: ArrayView2<f32>, mut enh: ArrayViewMut2<f32>) -> Result<f32> {
511 debug_assert_eq!(noisy.len_of(Axis(0)), enh.len_of(Axis(0)));
512 debug_assert_eq!(noisy.len_of(Axis(1)), enh.len_of(Axis(1)));
513 debug_assert_eq!(noisy.len_of(Axis(1)), self.hop_size);
514 let (max_a, e) = noisy.iter().fold((0f32, 0f32), |acc, x| {
515 (acc.0.max(x.abs()), acc.1 + x.powi(2))
516 });
517 let rms = e / noisy.len() as f32;
518 if rms < 1e-7 {
519 self.skip_counter += 1;
520 } else {
521 self.skip_counter = 0;
522 }
523 if self.skip_counter > 5 {
524 enh.fill(0.);
525 return Ok(-15.);
526 }
527 if max_a > 0.9999 {
528 log::warn!("Possible clipping detected ({:.3}).", max_a)
529 }
530
531 // Signal model: y = f(s + n) = f(x)
532 self.rolling_spec_buf_y.pop_front();
533 self.rolling_spec_buf_x.pop_front();
534 for (ns_ch, mut rbuf, state) in izip!(
535 noisy.axis_iter(Axis(0)),
536 self.spec_buf.to_plain_array_view_mut()?.axis_iter_mut(Axis(0)),
537 self.df_states.iter_mut(),
538 ) {
539 let spec = as_slice_mut_complex(rbuf.as_slice_mut().unwrap());
540 state.analysis(ns_ch.as_slice().unwrap(), spec);
541 }
542 self.rolling_spec_buf_y.push_back(self.spec_buf.clone());
543 self.rolling_spec_buf_x.push_back(self.spec_buf.clone());
544 if self.atten_lim.unwrap_or_default() == 1. {
545 enh.assign(&noisy);
546 return Ok(35.);
547 }
548
549 let (lsnr, gains, coefs) = self.process_raw()?;
550
551 let (apply_erb, _, _) = self.apply_stages(lsnr);
552 let mut spec = self
553 .rolling_spec_buf_y
554 .get_mut(self.df_order - 1)
555 .unwrap()
556 .to_plain_array_view_mut()?;
557 if let Some(gains) = gains {
558 let mut gains = gains.into_plain_array()?;
559 if gains.shape()[0] < noisy.shape()[0] {
560 // Mask was reduced to single channel
561 let gain_slc = gains.as_slice_mut().unwrap();
562 for mut spec_ch in spec.axis_iter_mut(Axis(0)) {
563 self.df_states[0].apply_mask(
564 as_slice_mut_complex(spec_ch.as_slice_mut().unwrap()),
565 gain_slc,
566 );
567 }
568 } else {
569 // Same number of channels of gains and spec
570 for (gains_ch, mut spec_ch) in
571 gains.axis_iter(Axis(0)).zip(spec.axis_iter_mut(Axis(0)))
572 {
573 let gain_slc = gains_ch.as_slice().unwrap();
574 self.df_states[0].apply_mask(
575 as_slice_mut_complex(spec_ch.as_slice_mut().unwrap()),
576 gain_slc,
577 );
578 }
579 }
580 self.skip_counter = 0;
581 } else {
582 // gains are None => skipped due to LSNR
583 self.skip_counter += 1;
584 }
585
586 // This spectrum will only be used for the upper frequecies
587 let spec = self.rolling_spec_buf_y.get_mut(self.df_order - 1).unwrap();
588 self.spec_buf.clone_from(spec);
589 if let Some(coefs) = coefs {
590 df(
591 &self.rolling_spec_buf_x,
592 coefs,
593 self.nb_df,
594 self.df_order,
595 self.n_freqs,
596 &mut self.spec_buf,
597 )?;
598 };
599
600 let spec_noisy = as_arrayview_complex(
601 self.rolling_spec_buf_x
602 .get(self.lookahead.max(self.df_order) - self.lookahead - 1)
603 .unwrap()
604 .to_plain_array_view::<f32>()
605 .unwrap(),
606 &[self.ch, self.n_freqs],
607 )
608 .into_dimensionality::<Ix2>()
609 .unwrap();
610 let mut spec_enh = as_arrayview_mut_complex(
611 self.spec_buf.to_plain_array_view_mut::<f32>().unwrap(),
612 &[self.ch, self.n_freqs],
613 )
614 .into_dimensionality::<Ix2>()
615 .unwrap();
616
617 // Run post filter
618 if apply_erb && self.post_filter {
619 post_filter(
620 spec_noisy.as_slice().unwrap(),
621 spec_enh.as_slice_mut().unwrap(),
622 self.post_filter_beta,
623 );
624 }
625
626 // Limit noise attenuation by mixing back some of the noisy signal
627 if let Some(lim) = self.atten_lim {
628 spec_enh.map_inplace(|x| *x *= 1. - lim);
629 spec_enh.scaled_add(lim.into(), &spec_noisy);
630 }
631
632 for (state, spec_ch, mut enh_out_ch) in izip!(
633 self.df_states.iter_mut(),
634 spec_enh.axis_iter(Axis(0)),
635 enh.axis_iter_mut(Axis(0)),
636 ) {
637 state.synthesis(
638 spec_ch.to_owned().as_slice_mut().unwrap(),
639 enh_out_ch.as_slice_mut().unwrap(),
640 );
641 }
642 Ok(lsnr)
643 }
644
645 /// For some frames, processing may be skipped based on the current local snr and the defined
646 /// thresholds. This methods indiciated whether stage 1 (gains) and stage 2 (DF) can be
647 /// skipped.
648 ///
649 /// Args:
650 /// - lsnr: Current local SNR estimate
651 ///
652 /// Returns:
653 /// - apply_gains: Local SNR is above `min_dfb_erb_thresh`, gains are estimated and should be
654 /// applied
655 /// - apply_gain_zeros: Local SNR is less than `min_db_thresh`, no speech is detected.
656 /// Zeros should be applied instead of the gain estimates.
657 /// - apply_df: Local SNR is greater than `max_db_df_thresh` and the estimated DF coefs
658 /// should be applied
659 pub fn apply_stages(&self, lsnr: f32) -> (bool, bool, bool) {
660 if lsnr < self.min_db_thresh {
661 // Only noise detected, just apply a zero mask
662 (false, true, false)
663 } else if lsnr > self.max_db_erb_thresh {
664 // Clean speech signal detected, don't apply any processing
665 (false, false, false)
666 } else if lsnr > self.max_db_df_thresh {
667 // Only little noisy signal detected, just apply 1st stage, skip DF stage
668 (true, false, false)
669 } else {
670 // Regular noisy signal detected, apply 1st and 2nd stage
671 (true, false, true)
672 }
673 }
674
675 pub fn set_spec_buffer(&mut self, spec: ArrayView2<f32>) -> Result<()> {
676 debug_assert_eq!(self.spec_buf.shape(), spec.shape());
677 let mut buf = self.spec_buf.to_plain_array_view_mut()?.into_shape_with_order([self.ch, self.n_freqs])?;
678 for (i_ch, mut b_ch) in spec.outer_iter().zip(buf.outer_iter_mut()) {
679 for (&i, b) in i_ch.iter().zip(b_ch.iter_mut()) {
680 *b = i
681 }
682 }
683 Ok(())
684 }
685
686 pub fn get_spec_noisy(&self) -> ArrayView2<Complex32> {
687 as_arrayview_complex(
688 self.rolling_spec_buf_x
689 .get(self.lookahead.max(self.df_order) - self.lookahead - 1)
690 .unwrap()
691 .to_plain_array_view::<f32>()
692 .unwrap(),
693 &[self.ch, self.n_freqs],
694 )
695 .into_dimensionality::<Ix2>()
696 .unwrap()
697 }
698 pub fn get_spec_enh(&self) -> ArrayView2<Complex32> {
699 as_arrayview_complex(
700 self.spec_buf.to_plain_array_view::<f32>().unwrap(),
701 &[self.ch, self.n_freqs],
702 )
703 .into_dimensionality::<Ix2>()
704 .unwrap()
705 }
706 pub fn get_mut_spec_enh(&mut self) -> ArrayViewMut2<Complex32> {
707 as_arrayview_mut_complex(
708 self.spec_buf.to_plain_array_view_mut::<f32>().unwrap(),
709 &[self.ch, self.n_freqs],
710 )
711 .into_dimensionality::<Ix2>()
712 .unwrap()
713 }
714 }
715
716 /// Deep Filtering.
717 ///
718 /// Args:
719 /// - spec: Spectrogram buffer for the corresponding time steps. Needs to contain `df_order + conv_lookahead` frames and applies DF to the oldest frames.
720 /// - coefs: Complex DF coefficients of shape `[C, N, F', 2]`, `N`: `df_order`, `F'`: `nb_df`
721 /// - nb_df: Number of DF frequency bins
722 /// - df_order: Deep Filtering order
723 /// - n_freqs: Number of FFT bins
724 /// - spec_out: Ouput buffer of shape `[C, F, 2]`, `F`: `n_freqs`
725 fn df(
726 spec: &VecDeque<Tensor>,
727 coefs: Tensor,
728 nb_df: usize,
729 df_order: usize,
730 n_freqs: usize,
731 spec_out: &mut Tensor,
732 ) -> Result<()> {
733 let ch = spec.back().unwrap().shape()[0];
734 debug_assert_eq!(n_freqs, spec.back().unwrap().shape()[3]);
735 debug_assert_eq!(n_freqs, spec_out.shape()[3]);
736 debug_assert_eq!(ch, coefs.shape()[0]);
737 debug_assert_eq!(nb_df, coefs.shape()[1]);
738 debug_assert_eq!(df_order, coefs.shape()[2]);
739 debug_assert_eq!(ch, spec_out.shape()[0]);
740 debug_assert!(spec.len() >= df_order);
741 let mut o_f: ArrayViewMut2<Complex32> =
742 as_arrayview_mut_complex(spec_out.to_plain_array_view_mut::<f32>()?, &[ch, n_freqs])
743 .into_dimensionality()?;
744 // Zero relevant frequency bins of output
745 o_f.slice_mut(s![.., ..nb_df]).fill(Complex32::default());
746 let coefs_arr: ArrayView3<Complex32> =
747 as_arrayview_complex(coefs.to_plain_array_view::<f32>()?, &[ch, nb_df, df_order])
748 .into_dimensionality()?;
749 // Transform spec to an complex array and iterate over time frames of spec and coefs
750 let spec_iter = spec.iter().map(|s| {
751 as_arrayview_complex(s.to_plain_array_view::<f32>().unwrap(), &[ch, n_freqs])
752 .into_dimensionality::<Ix2>()
753 .unwrap()
754 });
755 // Iterate over DF frames
756 for (s_f, c_f) in spec_iter.zip(coefs_arr.axis_iter(Axis(2))) {
757 // Iterate over channels
758 for (s_ch, c_ch, mut o_ch) in
759 izip!(s_f.outer_iter(), c_f.outer_iter(), o_f.outer_iter_mut())
760 {
761 // Apply DF for each frequency bin up to `nb_df`
762 for (&s, &c, o) in izip!(s_ch, c_ch, o_ch.iter_mut()) {
763 *o += s * c
764 }
765 }
766 }
767 Ok(())
768 }
769
770 fn init_encoder_impl(
771 mut m: InferenceModel,
772 df_cfg: &ini::Properties,
773 n_ch: usize,
774 ) -> Result<TypedModel> {
775 log::debug!("Start init encoder.");
776 let s = m.symbols.sym("S");
777
778 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
779 let nb_df = df_cfg.get("nb_df").unwrap().parse::<usize>()?;
780 let feat_erb = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, 1, s, nb_erb));
781 let feat_spec = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, 2, s, nb_df));
782
783 log::debug!(
784 "Encoder input: \n feat_erb [{:?}]\n feat_spec [{:?}]",
785 feat_erb.shape,
786 feat_spec.shape,
787 );
788 m = m
789 .with_input_fact(0, feat_erb)?
790 .with_input_fact(1, feat_spec)?
791 .with_input_names(["feat_erb", "feat_spec"])?
792 .with_outputs_by_name(["e0", "e1", "e2", "e3", "emb", "c0", "lsnr"])?;
793
794 m.analyse(true)?;
795 let mut m = m.into_typed()?;
796
797 m.declutter()?;
798 let pulsed = PulsedModel::new(&m, s, &1.to_dim())?;
799 log::info!("Init encoder");
800 let m = pulsed.into_typed()?.into_optimized()?;
801 Ok(m)
802 }
803 fn init_encoder(m: &Path, df_cfg: &ini::Properties, n_ch: usize) -> Result<TypedModel> {
804 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_path(m)?;
805 init_encoder_impl(m, df_cfg, n_ch)
806 }
807
808 fn init_encoder_from_read(
809 m: &mut dyn Read,
810 df_cfg: &ini::Properties,
811 n_ch: usize,
812 ) -> Result<TypedModel> {
813 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_read(m)?;
814 init_encoder_impl(m, df_cfg, n_ch)
815 }
816
817 fn init_erb_decoder_impl(
818 mut m: InferenceModel,
819 net_cfg: &ini::Properties,
820 df_cfg: &ini::Properties,
821 n_ch: usize,
822 mask_reduction: Option<ReduceMask>,
823 ) -> Result<TypedModel> {
824 log::debug!("Start init ERB decoder.");
825 let s = m.symbols.sym("S");
826
827 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
828 let layer_width = net_cfg.get("conv_ch").unwrap().parse::<usize>()?;
829 let n_hidden = layer_width * nb_erb / 4;
830
831 let emb = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, s, n_hidden));
832 let e3f = nb_erb / 4;
833 let e3 = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, layer_width, s, e3f));
834 let e2 = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, layer_width, s, e3f));
835 let e1f = nb_erb / 2;
836 let e1 = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, layer_width, s, e1f));
837 let e0 = InferenceFact::dt_shape(
838 f32::datum_type(),
839 shapefactoid!(n_ch, layer_width, s, nb_erb),
840 );
841 log::debug!(
842 "ERB decoder input: \n emb [{:?}]\n e3 [{:?}]\n e2 [{:?}]\n e1 [{:?}]\n e0 [{:?}]",
843 emb.shape,
844 e3.shape,
845 e2.shape,
846 e1.shape,
847 e0.shape
848 );
849 let mut output_name = "m".to_string();
850
851 m = m
852 .with_input_fact(0, emb)?
853 .with_input_fact(1, e3)?
854 .with_input_fact(2, e2)?
855 .with_input_fact(3, e1)?
856 .with_input_fact(4, e0)?
857 .with_input_names(["emb", "e3", "e2", "e1", "e0"])?;
858 // .with_outputs_by_name([output_name])?;
859
860 m.analyse(true)?;
861
862 let mut m = m.into_typed()?;
863
864 m.declutter()?;
865 let pulsed = PulsedModel::new(&m, s, &1.to_dim())?;
866 let mut m = pulsed.into_typed()?;
867 log::info!("Init ERB decoder");
868
869 if let Some(r) = mask_reduction {
870 let outlets = m.output_outlets()?;
871 let mask_outlet = outlets[0];
872 let ch_axis = 0;
873 match r {
874 ReduceMask::MAX => {
875 output_name = "reduce_mask_max".to_string();
876 m.wire_node(
877 "reduce_mask_max",
878 ops::nn::Reduce::new(tvec!(ch_axis), ops::nn::Reducer::Max),
879 &[mask_outlet],
880 )?;
881 }
882 ReduceMask::MEAN => {
883 let sum = m.wire_node(
884 "reduce_mask_sum".to_string(),
885 ops::nn::Reduce::new(tvec!(ch_axis), ops::nn::Reducer::Sum),
886 &[mask_outlet],
887 )?[0];
888 let ch_i = m
889 .add_const(
890 "ch".to_string(),
891 Tensor::from_shape(&[1, 1, 1, 1], &[1. / n_ch as f32])?,
892 )
893 .unwrap();
894 output_name = "reduce_mask_div_ch".to_string();
895 m.wire_node(
896 "reduce_mask_div_ch",
897 tract_core::ops::math::mul(),
898 &[sum, ch_i],
899 )?;
900 }
901 _ => (),
902 }
903 }
904 m = m.with_outputs_by_name(&[output_name])?;
905
906 let m = m.into_optimized()?;
907
908 Ok(m)
909 }
910 fn init_erb_decoder(
911 m: &Path,
912 net_cfg: &ini::Properties,
913 df_cfg: &ini::Properties,
914 n_ch: usize,
915 mask_reduction: Option<ReduceMask>,
916 ) -> Result<TypedModel> {
917 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_path(m)?;
918 init_erb_decoder_impl(m, net_cfg, df_cfg, n_ch, mask_reduction)
919 }
920 fn init_erb_decoder_from_read(
921 m: &mut dyn Read,
922 net_cfg: &ini::Properties,
923 df_cfg: &ini::Properties,
924 n_ch: usize,
925 mask_reduction: Option<ReduceMask>,
926 ) -> Result<TypedModel> {
927 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_read(m)?;
928 init_erb_decoder_impl(m, net_cfg, df_cfg, n_ch, mask_reduction)
929 }
930
931 fn init_df_decoder_impl(
932 mut m: InferenceModel,
933 net_cfg: &ini::Properties,
934 df_cfg: &ini::Properties,
935 n_ch: usize,
936 ) -> Result<TypedModel> {
937 log::debug!("Start init DF decoder.");
938 let s = m.symbols.sym("S");
939
940 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
941 let nb_df = df_cfg.get("nb_df").unwrap().parse::<usize>()?;
942 let layer_width = net_cfg.get("conv_ch").unwrap().parse::<usize>()?;
943 let n_hidden = layer_width * nb_erb / 4;
944
945 let emb = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, s, n_hidden));
946 let c0 = InferenceFact::dt_shape(
947 f32::datum_type(),
948 shapefactoid!(n_ch, layer_width, s, nb_df),
949 );
950
951 log::debug!(
952 "ERB decoder input: \n emb [{:?}]\n c0 [{:?}]",
953 emb.shape,
954 c0.shape,
955 );
956 m = m
957 .with_input_fact(0, emb)?
958 .with_input_fact(1, c0)?
959 .with_input_names(["emb", "c0"])?
960 .with_outputs_by_name(["coefs"])?;
961
962 m.analyse(true)?;
963 let mut m = m.into_typed()?;
964
965 m.declutter()?;
966 let pulsed = PulsedModel::new(&m, s, &1.to_dim())?;
967 log::info!("Init DF decoder");
968 let m = pulsed.into_typed()?.into_optimized()?;
969 Ok(m)
970 }
971 fn init_df_decoder(
972 m: &Path,
973 net_cfg: &ini::Properties,
974 df_cfg: &ini::Properties,
975 n_ch: usize,
976 ) -> Result<TypedModel> {
977 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_path(m)?;
978 init_df_decoder_impl(m, net_cfg, df_cfg, n_ch)
979 }
980 fn init_df_decoder_from_read(
981 m: &mut dyn Read,
982 net_cfg: &ini::Properties,
983 df_cfg: &ini::Properties,
984 n_ch: usize,
985 ) -> Result<TypedModel> {
986 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_read(m)?;
987 init_df_decoder_impl(m, net_cfg, df_cfg, n_ch)
988 }
989
990 fn calc_norm_alpha(sr: usize, hop_size: usize, tau: f32) -> f32 {
991 let dt = hop_size as f32 / sr as f32;
992 let alpha = f32::exp(-dt / tau);
993 let mut a = 1.0;
994 let mut precision = 3;
995 while a >= 1.0 {
996 a = (alpha * 10i32.pow(precision) as f32).round() / 10i32.pow(precision) as f32;
997 precision += 1;
998 }
999 a
1000 }
1001
1002 pub fn as_slice_complex(buffer: &[f32]) -> &[Complex32] {
1003 unsafe {
1004 let ptr = buffer.as_ptr() as *const Complex32;
1005 let len = buffer.len();
1006 std::slice::from_raw_parts(ptr, len / 2)
1007 }
1008 }
1009
1010 #[allow(clippy::needless_pass_by_ref_mut)]
1011 pub fn as_slice_mut_complex(buffer: &mut [f32]) -> &mut [Complex32] {
1012 unsafe {
1013 let ptr = buffer.as_ptr() as *mut Complex32;
1014 let len = buffer.len();
1015 std::slice::from_raw_parts_mut(ptr, len / 2)
1016 }
1017 }
1018
1019 #[allow(clippy::needless_pass_by_ref_mut)]
1020 pub fn as_slice_mut_real(buffer: &mut [Complex32]) -> &mut [f32] {
1021 unsafe {
1022 let ptr = buffer.as_ptr() as *mut f32;
1023 let len = buffer.len();
1024 std::slice::from_raw_parts_mut(ptr, len * 2)
1025 }
1026 }
1027
1028 pub fn slice_as_arrayview<'a>(
1029 buffer: &[f32],
1030 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1031 ) -> ArrayViewD<'a, f32> {
1032 debug_assert_eq!(buffer.len(), shape.iter().product::<usize>());
1033 unsafe {
1034 let ptr = buffer.as_ptr(); // as *mut Complex32;
1035 ArrayViewD::from_shape_ptr(shape, ptr)
1036 }
1037 }
1038 pub fn mut_slice_as_arrayviewmut<'a>(
1039 buffer: &mut [f32],
1040 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1041 ) -> ArrayViewMutD<'a, f32> {
1042 debug_assert_eq!(buffer.len(), shape.iter().product::<usize>());
1043 unsafe {
1044 let ptr = buffer.as_mut_ptr(); // as *mut Complex32;
1045 ArrayViewMutD::from_shape_ptr(shape, ptr)
1046 }
1047 }
1048 pub fn as_arrayview_complex<'a>(
1049 buffer: ArrayViewD<'a, f32>,
1050 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1051 ) -> ArrayViewD<'a, Complex32> {
1052 debug_assert_eq!(buffer.shape().last().unwrap(), &2);
1053 debug_assert_eq!(buffer.len(), 2 * shape.iter().product::<usize>());
1054 unsafe {
1055 let ptr = buffer.as_ptr() as *mut Complex32;
1056 ArrayViewD::from_shape_ptr(shape, ptr)
1057 }
1058 }
1059 pub fn as_arrayview_mut_complex<'a>(
1060 buffer: ArrayViewMutD<'a, f32>,
1061 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1062 ) -> ArrayViewMutD<'a, Complex32> {
1063 debug_assert_eq!(buffer.shape().last().unwrap(), &2);
1064 debug_assert_eq!(buffer.len(), 2 * shape.iter().product::<usize>());
1065 unsafe {
1066 let ptr = buffer.as_ptr() as *mut Complex32;
1067 ArrayViewMutD::from_shape_ptr(shape, ptr)
1068 }
1069 }
1070 pub fn tvalue_to_array_view_mut(x: &mut TValue) -> ArrayViewMutD<f32> {
1071 unsafe {
1072 let x: &Tensor = x;
1073 ArrayViewMutD::from_shape_ptr(x.shape(), x.as_ptr_unchecked::<f32>() as *mut f32)
1074 }
1075 }
@@ -0,0 +1,1075 @@
1use std::fs::File;
2use std::io::{Cursor, Read};
3use std::path::{Path, PathBuf};
4#[cfg(feature = "timings")]
5use std::time::Instant;
6
7use anyhow::{bail, Context, Result};
8use flate2::read::GzDecoder;
9use ini::Ini;
10use ndarray::{prelude::*, Axis};
11use tar::Archive;
12use tract_core::internal::tract_itertools::izip;
13use tract_core::internal::tract_smallvec::alloc::collections::VecDeque;
14use tract_core::ops;
15use tract_core::prelude::*;
16use tract_onnx::{prelude::*, tract_hir::shapefactoid};
17use tract_pulse::{internal::ToDim, model::*};
18
19use crate::*;
20
21#[derive(Clone)]
22pub struct DfParams {
23 config: Ini,
24 enc: Vec<u8>,
25 erb_dec: Vec<u8>,
26 df_dec: Vec<u8>,
27}
28
29impl DfParams {
30 pub fn new(tar_file: PathBuf) -> Result<Self> {
31 let file = File::open(tar_file).context("Could not open model tar file.")?;
32 Self::from_targz(file)
33 }
34 pub fn from_bytes(tar_buf: &[u8]) -> Result<Self> {
35 Self::from_targz(tar_buf)
36 }
37 fn from_targz<R: Read>(f: R) -> Result<Self> {
38 let tar = GzDecoder::new(f);
39 let mut archive = Archive::new(tar);
40 let mut enc = Vec::new();
41 let mut erb_dec = Vec::new();
42 let mut df_dec = Vec::new();
43 let mut config = Ini::new();
44 for e in archive.entries().context("Could not extract models from tar file.")? {
45 let mut file = e.context("Could not open model tar entry.")?;
46 let path = file.path().unwrap();
47 if path.ends_with("enc.onnx") {
48 file.read_to_end(&mut enc)?;
49 } else if path.ends_with("erb_dec.onnx") {
50 file.read_to_end(&mut erb_dec)?;
51 } else if path.ends_with("df_dec.onnx") {
52 file.read_to_end(&mut df_dec)?;
53 } else if path.ends_with("config.ini") {
54 config =
55 Ini::read_from(&mut file).context("Could not load config from tar file.")?;
56 } else if path.ends_with("version.txt") {
57 let mut version = String::new();
58 file.read_to_string(&mut version).expect("Could not read version.txt");
59 log::info!("Loading model with id: {}", version);
60 } else {
61 log::warn!("Found non-matching item in model tar file: {:?}", path)
62 }
63 }
64 Ok(Self {
65 config,
66 enc,
67 erb_dec,
68 df_dec,
69 })
70 }
71}
72impl Default for DfParams {
73 #[allow(unreachable_code)]
74 fn default() -> Self {
75 #[cfg(feature = "default-model")]
76 {
77 log::debug!("Loading model DeepFilterNet3_onnx.tar.gz");
78 DfParams::from_bytes(include_bytes!("../models/DeepFilterNet3_onnx.tar.gz"))
79 .expect("Could not load model config")
80 }
81 #[cfg(not(feature = "default-model"))]
82 panic!("Not compiled with a default model")
83 }
84}
85
86#[derive(Clone)]
87pub enum ReduceMask {
88 NONE = 0,
89 MAX = 1,
90 MEAN = 2,
91}
92impl Default for ReduceMask {
93 fn default() -> Self {
94 ReduceMask::NONE
95 }
96}
97impl TryFrom<i32> for ReduceMask {
98 type Error = ();
99
100 fn try_from(v: i32) -> Result<Self, Self::Error> {
101 match v {
102 x if x == ReduceMask::NONE as i32 => Ok(ReduceMask::NONE),
103 x if x == ReduceMask::MAX as i32 => Ok(ReduceMask::MAX),
104 x if x == ReduceMask::MEAN as i32 => Ok(ReduceMask::MEAN),
105 _ => Err(()),
106 }
107 }
108}
109pub struct RuntimeParams {
110 pub n_ch: usize,
111 pub post_filter: bool,
112 pub post_filter_beta: f32,
113 pub atten_lim_db: f32,
114 pub min_db_thresh: f32,
115 pub max_db_erb_thresh: f32,
116 pub max_db_df_thresh: f32,
117 pub reduce_mask: ReduceMask,
118}
119impl RuntimeParams {
120 pub fn new(
121 n_ch: usize,
122 post_filter_beta: f32,
123 atten_lim_db: f32,
124 min_db_thresh: f32,
125 max_db_erb_thresh: f32,
126 max_db_df_thresh: f32,
127 reduce_mask: ReduceMask,
128 ) -> Self {
129 let post_filter = post_filter_beta > 0.;
130 Self {
131 n_ch,
132 post_filter,
133 post_filter_beta,
134 atten_lim_db,
135 min_db_thresh,
136 max_db_erb_thresh,
137 max_db_df_thresh,
138 reduce_mask,
139 }
140 }
141 pub fn with_post_filter(mut self, beta: f32) -> Self {
142 assert!(beta >= 0.); // Cannot be negative
143 if beta > 0. {
144 self.post_filter = true;
145 }
146 self.post_filter_beta = beta;
147 self
148 }
149 pub fn with_atten_lim(mut self, atten_lim_db: f32) -> Self {
150 self.atten_lim_db = atten_lim_db;
151 self
152 }
153 pub fn with_thresholds(
154 mut self,
155 min_db_thresh: f32,
156 max_db_erb_thresh: f32,
157 max_db_df_thresh: f32,
158 ) -> Self {
159 self.min_db_thresh = min_db_thresh;
160 self.max_db_erb_thresh = max_db_erb_thresh;
161 self.max_db_df_thresh = max_db_df_thresh;
162 self
163 }
164 pub fn with_mask_reduce(mut self, red: ReduceMask) -> Self {
165 self.reduce_mask = red;
166 self
167 }
168 pub fn default_with_ch(channels: usize) -> Self {
169 RuntimeParams {
170 n_ch: channels,
171 post_filter: false,
172 post_filter_beta: 0.02,
173 atten_lim_db: 100.,
174 min_db_thresh: -10.,
175 max_db_erb_thresh: 30.,
176 max_db_df_thresh: 20.,
177 reduce_mask: ReduceMask::MEAN,
178 }
179 }
180}
181impl Default for RuntimeParams {
182 fn default() -> Self {
183 Self::default_with_ch(1)
184 }
185}
186
187pub type TractModel = TypedSimpleState;
188
189#[derive(Clone)]
190pub struct DfTract {
191 enc: TractModel,
192 erb_dec: TractModel,
193 df_dec: TractModel,
194 pub lookahead: usize,
195 pub df_lookahead: usize,
196 pub conv_lookahead: usize,
197 pub sr: usize,
198 pub ch: usize,
199 pub fft_size: usize,
200 pub hop_size: usize,
201 pub nb_erb: usize,
202 pub min_nb_erb_freqs: usize,
203 pub nb_df: usize,
204 pub n_freqs: usize,
205 pub df_order: usize,
206 pub post_filter: bool,
207 pub post_filter_beta: f32,
208 pub alpha: f32,
209 pub min_db_thresh: f32,
210 pub max_db_erb_thresh: f32,
211 pub max_db_df_thresh: f32,
212 pub reduce_mask: ReduceMask,
213 pub atten_lim: Option<f32>,
214 pub df_states: Vec<DFState>,
215 pub spec_buf: Tensor, // Real-valued spectrogram buffer of shape [n_ch, 1, 1, n_freqs, 2]
216 erb_buf: TValue, // Real-valued ERB feature buffer of shape [n_ch, 1, 1, n_erb]
217 cplx_buf: TValue, // Real-valued complex epectrum shape for DF of shape [n_ch, 1, nb_df, 2]
218 m_zeros: Vec<f32>, // Preallocated buffer for applying a zero mask
219 rolling_spec_buf_y: VecDeque<Tensor>, // Enhanced stage 1 spec buf
220 rolling_spec_buf_x: VecDeque<Tensor>, // Noisy spec buf
221 skip_counter: usize, // Increment when wanting to skip processing due to low RMS
222}
223
224#[cfg(feature = "default-model")]
225impl Default for DfTract {
226 fn default() -> Self {
227 let r_params = RuntimeParams::default();
228 let df_params = DfParams::default();
229 DfTract::new(df_params, &r_params).expect("Could not load DfTract")
230 }
231}
232
233impl DfTract {
234 /// A clone with its own feature buffers; the derived clone shares them and process() writes them in place.
235 pub fn fork(&self) -> Self {
236 let mut copy = self.clone();
237 copy.erb_buf = TValue::from(Tensor::clone(&self.erb_buf));
238 copy.cplx_buf = TValue::from(Tensor::clone(&self.cplx_buf));
239 copy
240 }
241
242 pub fn new(dfp: DfParams, rp: &RuntimeParams) -> Result<Self> {
243 #[cfg(feature = "timings")]
244 let t0 = Instant::now();
245 let config = dfp.config;
246 let model_cfg = config.section(Some("deepfilternet")).unwrap();
247 let df_cfg = config.section(Some("df")).unwrap();
248 let ch = rp.n_ch;
249
250 let enc = init_encoder_from_read(&mut Cursor::new(dfp.enc), df_cfg, ch)?;
251 let erb_dec = init_erb_decoder_from_read(
252 &mut Cursor::new(dfp.erb_dec),
253 model_cfg,
254 df_cfg,
255 ch,
256 Some(rp.reduce_mask.clone()),
257 )?;
258 let df_dec =
259 init_df_decoder_from_read(&mut Cursor::new(dfp.df_dec), model_cfg, df_cfg, ch)?;
260 let enc = enc.into_runnable()?.spawn()?;
261 let erb_dec = erb_dec.into_runnable()?.spawn()?;
262 let df_dec = df_dec.into_runnable()?.spawn()?;
263 #[cfg(feature = "timings")]
264 let t1 = Instant::now();
265
266 let sr = df_cfg.get("sr").unwrap().parse::<usize>()?;
267 let hop_size = df_cfg.get("hop_size").unwrap().parse::<usize>()?;
268 let fft_size = df_cfg.get("fft_size").unwrap().parse::<usize>()?;
269 let min_nb_erb_freqs = df_cfg.get("min_nb_erb_freqs").unwrap().parse::<usize>()?;
270 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
271 let nb_df = df_cfg.get("nb_df").unwrap().parse::<usize>()?;
272 let df_order = df_cfg
273 .get("df_order")
274 .unwrap_or_else(|| model_cfg.get("df_order").unwrap())
275 .parse::<usize>()?;
276 let conv_lookahead = model_cfg.get("conv_lookahead").unwrap().parse::<usize>()?;
277 let df_lookahead = df_cfg
278 .get("df_lookahead")
279 .unwrap_or_else(|| model_cfg.get("df_lookahead").unwrap())
280 .parse::<usize>()?;
281 let n_freqs = fft_size / 2 + 1;
282 let alpha = if let Some(a) = df_cfg.get("norm_alpha") {
283 a.parse::<f32>()?
284 } else {
285 let tau = df_cfg.get("norm_tau").unwrap().parse::<f32>()?;
286 calc_norm_alpha(sr, hop_size, tau)
287 };
288 let atten_lim = rp.atten_lim_db.abs();
289 let atten_lim = if atten_lim >= 100. {
290 None
291 } else if atten_lim < 0.01 {
292 log::warn!("Attenuation limit too strong. No noise reduction will be performed");
293 Some(1.)
294 } else {
295 log::info!("Running with an attenuation limit of {:.0} dB", atten_lim);
296 Some(10f32.powf(-atten_lim / 20.))
297 };
298 let spec_shape = [1, 1, 1, n_freqs, 2];
299 let spec_buf = unsafe { Tensor::uninitialized_dt(f32::datum_type(), &spec_shape)? };
300 let erb_buf = TValue::from(unsafe {
301 Tensor::uninitialized_dt(f32::datum_type(), &[1, 1, 1, nb_erb])?
302 });
303 let cplx_buf = TValue::from(unsafe {
304 Tensor::uninitialized_dt(f32::datum_type(), &[1, 1, nb_df, 2])?
305 });
306 let m_zeros = vec![0.; nb_erb];
307
308 let model_type = config.section(Some("train")).unwrap().get("model").unwrap();
309 let lookahead = match model_type {
310 "deepfilternet2" => bail!(
311 "DeepFilterNet2 models are deprecated. Please use version v0.3.1 for these models."
312 ),
313 "deepfilternet3" => conv_lookahead.max(df_lookahead),
314 _ => bail!("Unsupported model type {}", model_type),
315 };
316 log::info!(
317 "Running with model type {} lookahead {}",
318 model_type,
319 lookahead
320 );
321
322 let rolling_spec_buf_y = VecDeque::with_capacity(df_order + lookahead);
323 let rolling_spec_buf_x = VecDeque::with_capacity(lookahead.max(df_order));
324
325 let mut state = DFState::new(sr, fft_size, hop_size, nb_erb, min_nb_erb_freqs);
326 state.init_norm_states(nb_df);
327 let df_states = vec![state];
328
329 let mut m = Self {
330 enc,
331 erb_dec,
332 df_dec,
333 lookahead,
334 conv_lookahead,
335 df_lookahead,
336 sr,
337 ch,
338 fft_size,
339 hop_size,
340 nb_erb,
341 min_nb_erb_freqs,
342 nb_df,
343 n_freqs,
344 df_order,
345 alpha,
346 min_db_thresh: rp.min_db_thresh,
347 max_db_erb_thresh: rp.max_db_erb_thresh,
348 max_db_df_thresh: rp.max_db_df_thresh,
349 reduce_mask: rp.reduce_mask.clone(),
350 atten_lim,
351 spec_buf,
352 erb_buf,
353 cplx_buf,
354 m_zeros,
355 rolling_spec_buf_y,
356 rolling_spec_buf_x,
357 df_states,
358 post_filter: rp.post_filter,
359 post_filter_beta: rp.post_filter_beta,
360 skip_counter: 0,
361 };
362 m.init()?;
363 #[cfg(feature = "timings")]
364 log::info!(
365 "Init DfTract in {:.2}ms (models in {:.2}ms)",
366 t0.elapsed().as_secs_f32() * 1000.,
367 (t1 - t0).as_secs_f32() * 1000.
368 );
369
370 Ok(m)
371 }
372
373 pub fn set_pf_beta(&mut self, beta: f32) {
374 log::debug!("Setting post-filter beta to {beta}");
375 self.post_filter_beta = beta;
376 if beta > 0. {
377 self.post_filter = true;
378 } else if beta == 0. {
379 self.post_filter = false;
380 } else {
381 log::warn!("Post-filter beta cannot be smaller than 0.");
382 self.post_filter = false;
383 self.post_filter_beta = 0.;
384 }
385 }
386
387 pub fn set_atten_lim(&mut self, db: f32) {
388 let lim = db.abs();
389 self.atten_lim = if lim >= 100. {
390 None
391 } else if lim < 0.01 {
392 log::warn!("Attenuation limit too strong. No noise reduction will be performed");
393 Some(1.)
394 } else {
395 log::debug!("Setting attenuation limit to {:.1} dB", lim);
396 Some(10f32.powf(-lim / 20.))
397 };
398 }
399
400 pub fn init(&mut self) -> Result<()> {
401 let ch = self.ch;
402 let spec_shape = [ch, 1, 1, self.n_freqs, 2];
403 self.rolling_spec_buf_y.clear();
404 for _ in 0..(self.df_order + self.conv_lookahead) {
405 self.rolling_spec_buf_y
406 .push_back(tensor0(0f32).broadcast_scalar_to_shape(&spec_shape)?);
407 }
408 for _ in 0..self.df_order.max(self.lookahead) {
409 self.rolling_spec_buf_x
410 .push_back(tensor0(0f32).broadcast_scalar_to_shape(&spec_shape)?);
411 }
412 if ch > self.df_states.len() {
413 for _ in self.df_states.len()..ch {
414 let mut state = DFState::new(
415 self.sr,
416 self.fft_size,
417 self.hop_size,
418 self.nb_erb,
419 self.min_nb_erb_freqs,
420 );
421 state.init_norm_states(self.nb_df);
422 self.df_states.push(state)
423 }
424 }
425 self.spec_buf = Tensor::zero::<f32>(&spec_shape)?;
426 self.erb_buf = TValue::from(Tensor::zero::<f32>(&[ch, 1, 1, self.nb_erb])?);
427 self.cplx_buf = TValue::from(Tensor::zero::<f32>(&[ch, 1, self.nb_df, 2])?);
428
429 Ok(())
430 }
431
432 /// Process a FD sample and return the raw gains and DF coefs.
433 ///
434 /// Warning:
435 /// `self.spec_buf` needs to be initialized correctly before calling this method!
436 ///
437 /// Returns:
438 /// - lsnr: Local SNR estiamte.
439 /// - gains: Gain estimates of shape `[n_ch, 1, 1, n_erb]`.
440 /// - coefs: Real-valued DF coefficients estimates of shape `[n_ch, 1, 1, n_erb, 2]`.
441 pub fn process_raw(&mut self) -> Result<(f32, Option<Tensor>, Option<Tensor>)> {
442 let spec = self.spec_buf.to_plain_array_view()?;
443 let ch = spec.len_of(Axis(0));
444
445 for (nsy_ch, mut erb_ch, mut cplx_ch, state) in izip!(
446 spec.axis_iter(Axis(0)),
447 tvalue_to_array_view_mut(&mut self.erb_buf).axis_iter_mut(Axis(0)),
448 tvalue_to_array_view_mut(&mut self.cplx_buf).axis_iter_mut(Axis(0)),
449 self.df_states.iter_mut()
450 ) {
451 let nsy_ch = as_slice_complex(nsy_ch.as_slice().unwrap());
452 state.feat_erb(nsy_ch, self.alpha, erb_ch.as_slice_mut().unwrap());
453 state.feat_cplx(
454 &nsy_ch[..self.nb_df],
455 self.alpha,
456 as_slice_mut_complex(cplx_ch.as_slice_mut().unwrap()),
457 );
458 }
459 // Run encoder
460 let mut enc_emb = self.enc.run(tvec!(
461 self.erb_buf.clone(),
462 TValue::from(self.cplx_buf.clone().into_tensor().permute_axes(&[0, 3, 1, 2])?)
463 ))?;
464
465 let lsnr_value = enc_emb.pop().unwrap();
466 let lsnr = *lsnr_value.try_as_plain_ram()?.to_scalar::<f32>()?;
467 let c0 = enc_emb.pop().unwrap();
468 let emb = enc_emb.pop().unwrap();
469
470 let (apply_gains, apply_gain_zeros, apply_df) = self.apply_stages(lsnr);
471
472 log::trace!(
473 "Enhancing frame with lsnr {:>5.1} dB. Applying stage 1: {} and stage 2: {}.",
474 lsnr,
475 apply_gains,
476 apply_df
477 );
478
479 let m = if apply_gains {
480 let dec_input = tvec!(
481 emb.clone(),
482 enc_emb.pop().unwrap(), // e3
483 enc_emb.pop().unwrap(), // e2
484 enc_emb.pop().unwrap(), // e1
485 enc_emb.pop().unwrap(), // e0
486 );
487 let mut m = self.erb_dec.run(dec_input)?;
488 let mut m = m.pop().unwrap().into_tensor();
489 m.remove_axis(1)?;
490 m.remove_axis(1)?;
491 Some(m)
492 } else if apply_gain_zeros {
493 Some(Tensor::zero::<f32>(&[self.ch, self.nb_erb])?)
494 } else {
495 None
496 };
497
498 let coefs = if apply_df {
499 let mut coefs = self.df_dec.run(tvec!(emb, c0))?.pop().unwrap().into_tensor();
500 coefs.set_shape(&[ch, self.nb_df, self.df_order, 2])?;
501 Some(coefs)
502 } else {
503 None
504 };
505
506 Ok((lsnr, m, coefs))
507 }
508
509 /// Process a noisy time domain sample and return the enhanced sample via mutable argument.
510 pub fn process(&mut self, noisy: ArrayView2<f32>, mut enh: ArrayViewMut2<f32>) -> Result<f32> {
511 debug_assert_eq!(noisy.len_of(Axis(0)), enh.len_of(Axis(0)));
512 debug_assert_eq!(noisy.len_of(Axis(1)), enh.len_of(Axis(1)));
513 debug_assert_eq!(noisy.len_of(Axis(1)), self.hop_size);
514 let (max_a, e) = noisy.iter().fold((0f32, 0f32), |acc, x| {
515 (acc.0.max(x.abs()), acc.1 + x.powi(2))
516 });
517 let rms = e / noisy.len() as f32;
518 if rms < 1e-7 {
519 self.skip_counter += 1;
520 } else {
521 self.skip_counter = 0;
522 }
523 if self.skip_counter > 5 {
524 enh.fill(0.);
525 return Ok(-15.);
526 }
527 if max_a > 0.9999 {
528 log::warn!("Possible clipping detected ({:.3}).", max_a)
529 }
530
531 // Signal model: y = f(s + n) = f(x)
532 self.rolling_spec_buf_y.pop_front();
533 self.rolling_spec_buf_x.pop_front();
534 for (ns_ch, mut rbuf, state) in izip!(
535 noisy.axis_iter(Axis(0)),
536 self.spec_buf.to_plain_array_view_mut()?.axis_iter_mut(Axis(0)),
537 self.df_states.iter_mut(),
538 ) {
539 let spec = as_slice_mut_complex(rbuf.as_slice_mut().unwrap());
540 state.analysis(ns_ch.as_slice().unwrap(), spec);
541 }
542 self.rolling_spec_buf_y.push_back(self.spec_buf.clone());
543 self.rolling_spec_buf_x.push_back(self.spec_buf.clone());
544 if self.atten_lim.unwrap_or_default() == 1. {
545 enh.assign(&noisy);
546 return Ok(35.);
547 }
548
549 let (lsnr, gains, coefs) = self.process_raw()?;
550
551 let (apply_erb, _, _) = self.apply_stages(lsnr);
552 let mut spec = self
553 .rolling_spec_buf_y
554 .get_mut(self.df_order - 1)
555 .unwrap()
556 .to_plain_array_view_mut()?;
557 if let Some(gains) = gains {
558 let mut gains = gains.into_plain_array()?;
559 if gains.shape()[0] < noisy.shape()[0] {
560 // Mask was reduced to single channel
561 let gain_slc = gains.as_slice_mut().unwrap();
562 for mut spec_ch in spec.axis_iter_mut(Axis(0)) {
563 self.df_states[0].apply_mask(
564 as_slice_mut_complex(spec_ch.as_slice_mut().unwrap()),
565 gain_slc,
566 );
567 }
568 } else {
569 // Same number of channels of gains and spec
570 for (gains_ch, mut spec_ch) in
571 gains.axis_iter(Axis(0)).zip(spec.axis_iter_mut(Axis(0)))
572 {
573 let gain_slc = gains_ch.as_slice().unwrap();
574 self.df_states[0].apply_mask(
575 as_slice_mut_complex(spec_ch.as_slice_mut().unwrap()),
576 gain_slc,
577 );
578 }
579 }
580 self.skip_counter = 0;
581 } else {
582 // gains are None => skipped due to LSNR
583 self.skip_counter += 1;
584 }
585
586 // This spectrum will only be used for the upper frequecies
587 let spec = self.rolling_spec_buf_y.get_mut(self.df_order - 1).unwrap();
588 self.spec_buf.clone_from(spec);
589 if let Some(coefs) = coefs {
590 df(
591 &self.rolling_spec_buf_x,
592 coefs,
593 self.nb_df,
594 self.df_order,
595 self.n_freqs,
596 &mut self.spec_buf,
597 )?;
598 };
599
600 let spec_noisy = as_arrayview_complex(
601 self.rolling_spec_buf_x
602 .get(self.lookahead.max(self.df_order) - self.lookahead - 1)
603 .unwrap()
604 .to_plain_array_view::<f32>()
605 .unwrap(),
606 &[self.ch, self.n_freqs],
607 )
608 .into_dimensionality::<Ix2>()
609 .unwrap();
610 let mut spec_enh = as_arrayview_mut_complex(
611 self.spec_buf.to_plain_array_view_mut::<f32>().unwrap(),
612 &[self.ch, self.n_freqs],
613 )
614 .into_dimensionality::<Ix2>()
615 .unwrap();
616
617 // Run post filter
618 if apply_erb && self.post_filter {
619 post_filter(
620 spec_noisy.as_slice().unwrap(),
621 spec_enh.as_slice_mut().unwrap(),
622 self.post_filter_beta,
623 );
624 }
625
626 // Limit noise attenuation by mixing back some of the noisy signal
627 if let Some(lim) = self.atten_lim {
628 spec_enh.map_inplace(|x| *x *= 1. - lim);
629 spec_enh.scaled_add(lim.into(), &spec_noisy);
630 }
631
632 for (state, spec_ch, mut enh_out_ch) in izip!(
633 self.df_states.iter_mut(),
634 spec_enh.axis_iter(Axis(0)),
635 enh.axis_iter_mut(Axis(0)),
636 ) {
637 state.synthesis(
638 spec_ch.to_owned().as_slice_mut().unwrap(),
639 enh_out_ch.as_slice_mut().unwrap(),
640 );
641 }
642 Ok(lsnr)
643 }
644
645 /// For some frames, processing may be skipped based on the current local snr and the defined
646 /// thresholds. This methods indiciated whether stage 1 (gains) and stage 2 (DF) can be
647 /// skipped.
648 ///
649 /// Args:
650 /// - lsnr: Current local SNR estimate
651 ///
652 /// Returns:
653 /// - apply_gains: Local SNR is above `min_dfb_erb_thresh`, gains are estimated and should be
654 /// applied
655 /// - apply_gain_zeros: Local SNR is less than `min_db_thresh`, no speech is detected.
656 /// Zeros should be applied instead of the gain estimates.
657 /// - apply_df: Local SNR is greater than `max_db_df_thresh` and the estimated DF coefs
658 /// should be applied
659 pub fn apply_stages(&self, lsnr: f32) -> (bool, bool, bool) {
660 if lsnr < self.min_db_thresh {
661 // Only noise detected, just apply a zero mask
662 (false, true, false)
663 } else if lsnr > self.max_db_erb_thresh {
664 // Clean speech signal detected, don't apply any processing
665 (false, false, false)
666 } else if lsnr > self.max_db_df_thresh {
667 // Only little noisy signal detected, just apply 1st stage, skip DF stage
668 (true, false, false)
669 } else {
670 // Regular noisy signal detected, apply 1st and 2nd stage
671 (true, false, true)
672 }
673 }
674
675 pub fn set_spec_buffer(&mut self, spec: ArrayView2<f32>) -> Result<()> {
676 debug_assert_eq!(self.spec_buf.shape(), spec.shape());
677 let mut buf = self.spec_buf.to_plain_array_view_mut()?.into_shape_with_order([self.ch, self.n_freqs])?;
678 for (i_ch, mut b_ch) in spec.outer_iter().zip(buf.outer_iter_mut()) {
679 for (&i, b) in i_ch.iter().zip(b_ch.iter_mut()) {
680 *b = i
681 }
682 }
683 Ok(())
684 }
685
686 pub fn get_spec_noisy(&self) -> ArrayView2<Complex32> {
687 as_arrayview_complex(
688 self.rolling_spec_buf_x
689 .get(self.lookahead.max(self.df_order) - self.lookahead - 1)
690 .unwrap()
691 .to_plain_array_view::<f32>()
692 .unwrap(),
693 &[self.ch, self.n_freqs],
694 )
695 .into_dimensionality::<Ix2>()
696 .unwrap()
697 }
698 pub fn get_spec_enh(&self) -> ArrayView2<Complex32> {
699 as_arrayview_complex(
700 self.spec_buf.to_plain_array_view::<f32>().unwrap(),
701 &[self.ch, self.n_freqs],
702 )
703 .into_dimensionality::<Ix2>()
704 .unwrap()
705 }
706 pub fn get_mut_spec_enh(&mut self) -> ArrayViewMut2<Complex32> {
707 as_arrayview_mut_complex(
708 self.spec_buf.to_plain_array_view_mut::<f32>().unwrap(),
709 &[self.ch, self.n_freqs],
710 )
711 .into_dimensionality::<Ix2>()
712 .unwrap()
713 }
714}
715
716/// Deep Filtering.
717///
718/// Args:
719/// - spec: Spectrogram buffer for the corresponding time steps. Needs to contain `df_order + conv_lookahead` frames and applies DF to the oldest frames.
720/// - coefs: Complex DF coefficients of shape `[C, N, F', 2]`, `N`: `df_order`, `F'`: `nb_df`
721/// - nb_df: Number of DF frequency bins
722/// - df_order: Deep Filtering order
723/// - n_freqs: Number of FFT bins
724/// - spec_out: Ouput buffer of shape `[C, F, 2]`, `F`: `n_freqs`
725fn df(
726 spec: &VecDeque<Tensor>,
727 coefs: Tensor,
728 nb_df: usize,
729 df_order: usize,
730 n_freqs: usize,
731 spec_out: &mut Tensor,
732) -> Result<()> {
733 let ch = spec.back().unwrap().shape()[0];
734 debug_assert_eq!(n_freqs, spec.back().unwrap().shape()[3]);
735 debug_assert_eq!(n_freqs, spec_out.shape()[3]);
736 debug_assert_eq!(ch, coefs.shape()[0]);
737 debug_assert_eq!(nb_df, coefs.shape()[1]);
738 debug_assert_eq!(df_order, coefs.shape()[2]);
739 debug_assert_eq!(ch, spec_out.shape()[0]);
740 debug_assert!(spec.len() >= df_order);
741 let mut o_f: ArrayViewMut2<Complex32> =
742 as_arrayview_mut_complex(spec_out.to_plain_array_view_mut::<f32>()?, &[ch, n_freqs])
743 .into_dimensionality()?;
744 // Zero relevant frequency bins of output
745 o_f.slice_mut(s![.., ..nb_df]).fill(Complex32::default());
746 let coefs_arr: ArrayView3<Complex32> =
747 as_arrayview_complex(coefs.to_plain_array_view::<f32>()?, &[ch, nb_df, df_order])
748 .into_dimensionality()?;
749 // Transform spec to an complex array and iterate over time frames of spec and coefs
750 let spec_iter = spec.iter().map(|s| {
751 as_arrayview_complex(s.to_plain_array_view::<f32>().unwrap(), &[ch, n_freqs])
752 .into_dimensionality::<Ix2>()
753 .unwrap()
754 });
755 // Iterate over DF frames
756 for (s_f, c_f) in spec_iter.zip(coefs_arr.axis_iter(Axis(2))) {
757 // Iterate over channels
758 for (s_ch, c_ch, mut o_ch) in
759 izip!(s_f.outer_iter(), c_f.outer_iter(), o_f.outer_iter_mut())
760 {
761 // Apply DF for each frequency bin up to `nb_df`
762 for (&s, &c, o) in izip!(s_ch, c_ch, o_ch.iter_mut()) {
763 *o += s * c
764 }
765 }
766 }
767 Ok(())
768}
769
770fn init_encoder_impl(
771 mut m: InferenceModel,
772 df_cfg: &ini::Properties,
773 n_ch: usize,
774) -> Result<TypedModel> {
775 log::debug!("Start init encoder.");
776 let s = m.symbols.sym("S");
777
778 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
779 let nb_df = df_cfg.get("nb_df").unwrap().parse::<usize>()?;
780 let feat_erb = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, 1, s, nb_erb));
781 let feat_spec = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, 2, s, nb_df));
782
783 log::debug!(
784 "Encoder input: \n feat_erb [{:?}]\n feat_spec [{:?}]",
785 feat_erb.shape,
786 feat_spec.shape,
787 );
788 m = m
789 .with_input_fact(0, feat_erb)?
790 .with_input_fact(1, feat_spec)?
791 .with_input_names(["feat_erb", "feat_spec"])?
792 .with_outputs_by_name(["e0", "e1", "e2", "e3", "emb", "c0", "lsnr"])?;
793
794 m.analyse(true)?;
795 let mut m = m.into_typed()?;
796
797 m.declutter()?;
798 let pulsed = PulsedModel::new(&m, s, &1.to_dim())?;
799 log::info!("Init encoder");
800 let m = pulsed.into_typed()?.into_optimized()?;
801 Ok(m)
802}
803fn init_encoder(m: &Path, df_cfg: &ini::Properties, n_ch: usize) -> Result<TypedModel> {
804 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_path(m)?;
805 init_encoder_impl(m, df_cfg, n_ch)
806}
807
808fn init_encoder_from_read(
809 m: &mut dyn Read,
810 df_cfg: &ini::Properties,
811 n_ch: usize,
812) -> Result<TypedModel> {
813 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_read(m)?;
814 init_encoder_impl(m, df_cfg, n_ch)
815}
816
817fn init_erb_decoder_impl(
818 mut m: InferenceModel,
819 net_cfg: &ini::Properties,
820 df_cfg: &ini::Properties,
821 n_ch: usize,
822 mask_reduction: Option<ReduceMask>,
823) -> Result<TypedModel> {
824 log::debug!("Start init ERB decoder.");
825 let s = m.symbols.sym("S");
826
827 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
828 let layer_width = net_cfg.get("conv_ch").unwrap().parse::<usize>()?;
829 let n_hidden = layer_width * nb_erb / 4;
830
831 let emb = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, s, n_hidden));
832 let e3f = nb_erb / 4;
833 let e3 = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, layer_width, s, e3f));
834 let e2 = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, layer_width, s, e3f));
835 let e1f = nb_erb / 2;
836 let e1 = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, layer_width, s, e1f));
837 let e0 = InferenceFact::dt_shape(
838 f32::datum_type(),
839 shapefactoid!(n_ch, layer_width, s, nb_erb),
840 );
841 log::debug!(
842 "ERB decoder input: \n emb [{:?}]\n e3 [{:?}]\n e2 [{:?}]\n e1 [{:?}]\n e0 [{:?}]",
843 emb.shape,
844 e3.shape,
845 e2.shape,
846 e1.shape,
847 e0.shape
848 );
849 let mut output_name = "m".to_string();
850
851 m = m
852 .with_input_fact(0, emb)?
853 .with_input_fact(1, e3)?
854 .with_input_fact(2, e2)?
855 .with_input_fact(3, e1)?
856 .with_input_fact(4, e0)?
857 .with_input_names(["emb", "e3", "e2", "e1", "e0"])?;
858 // .with_outputs_by_name([output_name])?;
859
860 m.analyse(true)?;
861
862 let mut m = m.into_typed()?;
863
864 m.declutter()?;
865 let pulsed = PulsedModel::new(&m, s, &1.to_dim())?;
866 let mut m = pulsed.into_typed()?;
867 log::info!("Init ERB decoder");
868
869 if let Some(r) = mask_reduction {
870 let outlets = m.output_outlets()?;
871 let mask_outlet = outlets[0];
872 let ch_axis = 0;
873 match r {
874 ReduceMask::MAX => {
875 output_name = "reduce_mask_max".to_string();
876 m.wire_node(
877 "reduce_mask_max",
878 ops::nn::Reduce::new(tvec!(ch_axis), ops::nn::Reducer::Max),
879 &[mask_outlet],
880 )?;
881 }
882 ReduceMask::MEAN => {
883 let sum = m.wire_node(
884 "reduce_mask_sum".to_string(),
885 ops::nn::Reduce::new(tvec!(ch_axis), ops::nn::Reducer::Sum),
886 &[mask_outlet],
887 )?[0];
888 let ch_i = m
889 .add_const(
890 "ch".to_string(),
891 Tensor::from_shape(&[1, 1, 1, 1], &[1. / n_ch as f32])?,
892 )
893 .unwrap();
894 output_name = "reduce_mask_div_ch".to_string();
895 m.wire_node(
896 "reduce_mask_div_ch",
897 tract_core::ops::math::mul(),
898 &[sum, ch_i],
899 )?;
900 }
901 _ => (),
902 }
903 }
904 m = m.with_outputs_by_name(&[output_name])?;
905
906 let m = m.into_optimized()?;
907
908 Ok(m)
909}
910fn init_erb_decoder(
911 m: &Path,
912 net_cfg: &ini::Properties,
913 df_cfg: &ini::Properties,
914 n_ch: usize,
915 mask_reduction: Option<ReduceMask>,
916) -> Result<TypedModel> {
917 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_path(m)?;
918 init_erb_decoder_impl(m, net_cfg, df_cfg, n_ch, mask_reduction)
919}
920fn init_erb_decoder_from_read(
921 m: &mut dyn Read,
922 net_cfg: &ini::Properties,
923 df_cfg: &ini::Properties,
924 n_ch: usize,
925 mask_reduction: Option<ReduceMask>,
926) -> Result<TypedModel> {
927 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_read(m)?;
928 init_erb_decoder_impl(m, net_cfg, df_cfg, n_ch, mask_reduction)
929}
930
931fn init_df_decoder_impl(
932 mut m: InferenceModel,
933 net_cfg: &ini::Properties,
934 df_cfg: &ini::Properties,
935 n_ch: usize,
936) -> Result<TypedModel> {
937 log::debug!("Start init DF decoder.");
938 let s = m.symbols.sym("S");
939
940 let nb_erb = df_cfg.get("nb_erb").unwrap().parse::<usize>()?;
941 let nb_df = df_cfg.get("nb_df").unwrap().parse::<usize>()?;
942 let layer_width = net_cfg.get("conv_ch").unwrap().parse::<usize>()?;
943 let n_hidden = layer_width * nb_erb / 4;
944
945 let emb = InferenceFact::dt_shape(f32::datum_type(), shapefactoid!(n_ch, s, n_hidden));
946 let c0 = InferenceFact::dt_shape(
947 f32::datum_type(),
948 shapefactoid!(n_ch, layer_width, s, nb_df),
949 );
950
951 log::debug!(
952 "ERB decoder input: \n emb [{:?}]\n c0 [{:?}]",
953 emb.shape,
954 c0.shape,
955 );
956 m = m
957 .with_input_fact(0, emb)?
958 .with_input_fact(1, c0)?
959 .with_input_names(["emb", "c0"])?
960 .with_outputs_by_name(["coefs"])?;
961
962 m.analyse(true)?;
963 let mut m = m.into_typed()?;
964
965 m.declutter()?;
966 let pulsed = PulsedModel::new(&m, s, &1.to_dim())?;
967 log::info!("Init DF decoder");
968 let m = pulsed.into_typed()?.into_optimized()?;
969 Ok(m)
970}
971fn init_df_decoder(
972 m: &Path,
973 net_cfg: &ini::Properties,
974 df_cfg: &ini::Properties,
975 n_ch: usize,
976) -> Result<TypedModel> {
977 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_path(m)?;
978 init_df_decoder_impl(m, net_cfg, df_cfg, n_ch)
979}
980fn init_df_decoder_from_read(
981 m: &mut dyn Read,
982 net_cfg: &ini::Properties,
983 df_cfg: &ini::Properties,
984 n_ch: usize,
985) -> Result<TypedModel> {
986 let m = tract_onnx::onnx().with_ignore_output_shapes(true).model_for_read(m)?;
987 init_df_decoder_impl(m, net_cfg, df_cfg, n_ch)
988}
989
990fn calc_norm_alpha(sr: usize, hop_size: usize, tau: f32) -> f32 {
991 let dt = hop_size as f32 / sr as f32;
992 let alpha = f32::exp(-dt / tau);
993 let mut a = 1.0;
994 let mut precision = 3;
995 while a >= 1.0 {
996 a = (alpha * 10i32.pow(precision) as f32).round() / 10i32.pow(precision) as f32;
997 precision += 1;
998 }
999 a
1000}
1001
1002pub fn as_slice_complex(buffer: &[f32]) -> &[Complex32] {
1003 unsafe {
1004 let ptr = buffer.as_ptr() as *const Complex32;
1005 let len = buffer.len();
1006 std::slice::from_raw_parts(ptr, len / 2)
1007 }
1008}
1009
1010#[allow(clippy::needless_pass_by_ref_mut)]
1011pub fn as_slice_mut_complex(buffer: &mut [f32]) -> &mut [Complex32] {
1012 unsafe {
1013 let ptr = buffer.as_ptr() as *mut Complex32;
1014 let len = buffer.len();
1015 std::slice::from_raw_parts_mut(ptr, len / 2)
1016 }
1017}
1018
1019#[allow(clippy::needless_pass_by_ref_mut)]
1020pub fn as_slice_mut_real(buffer: &mut [Complex32]) -> &mut [f32] {
1021 unsafe {
1022 let ptr = buffer.as_ptr() as *mut f32;
1023 let len = buffer.len();
1024 std::slice::from_raw_parts_mut(ptr, len * 2)
1025 }
1026}
1027
1028pub fn slice_as_arrayview<'a>(
1029 buffer: &[f32],
1030 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1031) -> ArrayViewD<'a, f32> {
1032 debug_assert_eq!(buffer.len(), shape.iter().product::<usize>());
1033 unsafe {
1034 let ptr = buffer.as_ptr(); // as *mut Complex32;
1035 ArrayViewD::from_shape_ptr(shape, ptr)
1036 }
1037}
1038pub fn mut_slice_as_arrayviewmut<'a>(
1039 buffer: &mut [f32],
1040 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1041) -> ArrayViewMutD<'a, f32> {
1042 debug_assert_eq!(buffer.len(), shape.iter().product::<usize>());
1043 unsafe {
1044 let ptr = buffer.as_mut_ptr(); // as *mut Complex32;
1045 ArrayViewMutD::from_shape_ptr(shape, ptr)
1046 }
1047}
1048pub fn as_arrayview_complex<'a>(
1049 buffer: ArrayViewD<'a, f32>,
1050 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1051) -> ArrayViewD<'a, Complex32> {
1052 debug_assert_eq!(buffer.shape().last().unwrap(), &2);
1053 debug_assert_eq!(buffer.len(), 2 * shape.iter().product::<usize>());
1054 unsafe {
1055 let ptr = buffer.as_ptr() as *mut Complex32;
1056 ArrayViewD::from_shape_ptr(shape, ptr)
1057 }
1058}
1059pub fn as_arrayview_mut_complex<'a>(
1060 buffer: ArrayViewMutD<'a, f32>,
1061 shape: &[usize], // having an explicit shape parameter allows to also squeeze axes.
1062) -> ArrayViewMutD<'a, Complex32> {
1063 debug_assert_eq!(buffer.shape().last().unwrap(), &2);
1064 debug_assert_eq!(buffer.len(), 2 * shape.iter().product::<usize>());
1065 unsafe {
1066 let ptr = buffer.as_ptr() as *mut Complex32;
1067 ArrayViewMutD::from_shape_ptr(shape, ptr)
1068 }
1069}
1070pub fn tvalue_to_array_view_mut(x: &mut TValue) -> ArrayViewMutD<f32> {
1071 unsafe {
1072 let x: &Tensor = x;
1073 ArrayViewMutD::from_shape_ptr(x.shape(), x.as_ptr_unchecked::<f32>() as *mut f32)
1074 }
1075}
vendor/webrtc-sys/include/livekit/apm.h +3 −0
@@ -37,6 +37,9 @@ struct AudioProcessingConfig {
37 37 config.echo_canceller.enabled = echo_canceller_enabled;
38 38 config.gain_controller2.enabled = gain_controller_enabled;
39 39 config.gain_controller2.adaptive_digital.enabled = gain_controller_enabled;
40 // Speech settles near -16 dBFS like Teams instead of AGC2's -22 dBFS; the limiter after the fixed gain keeps peaks below -1 dBFS.
41 config.gain_controller2.adaptive_digital.initial_gain_db = 0.0f;
42 config.gain_controller2.fixed_digital.gain_db = gain_controller_enabled ? 6.0f : 0.0f;
40 43 config.high_pass_filter.enabled = high_pass_filter_enabled;
41 44 config.noise_suppression.enabled = noise_suppression_enabled;
42 45 return config;
@@ -37,6 +37,9 @@ struct AudioProcessingConfig {
37 config.echo_canceller.enabled = echo_canceller_enabled;
37 config.echo_canceller.enabled = echo_canceller_enabled;
38 config.gain_controller2.enabled = gain_controller_enabled;
38 config.gain_controller2.enabled = gain_controller_enabled;
39 config.gain_controller2.adaptive_digital.enabled = gain_controller_enabled;
39 config.gain_controller2.adaptive_digital.enabled = gain_controller_enabled;
40 // Speech settles near -16 dBFS like Teams instead of AGC2's -22 dBFS; the limiter after the fixed gain keeps peaks below -1 dBFS.
41 config.gain_controller2.adaptive_digital.initial_gain_db = 0.0f;
42 config.gain_controller2.fixed_digital.gain_db = gain_controller_enabled ? 6.0f : 0.0f;
40 config.high_pass_filter.enabled = high_pass_filter_enabled;
43 config.high_pass_filter.enabled = high_pass_filter_enabled;
41 config.noise_suppression.enabled = noise_suppression_enabled;
44 config.noise_suppression.enabled = noise_suppression_enabled;
42 return config;
45 return config;