fix(calling): DeepFilterNet hook without noise gate, with frame budget
- Noise gate removed (learned floor, hard zeroing); attenuation limit 30 -> 40 dB instead - Hook switches itself off for the call after 5 frames over 6 ms; WebRTC noise suppression keeps running, timeline records it - Dead apply() and test-only accessors removed, comments trimmed - Tests: frame budget, arming per mode and overload until hangup Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -188,7 +188,7 @@ Feature parity with the Microsoft Teams desktop client.
188
188
| Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |
189
189
| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Transcription-only sessions (item media source `Transcript`) show the transcript without a recording card. "Audio only" comes from the chat event (`videoContent="CurtainOnly"`), with the video size check as fallback. Both signals read live on real recordings, fixtures unit tested; the transcript-only path was not run live |
190
190
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
191
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto and Low on Linux keep the Pulse ADM device track (same path as Web Teams); Linux/macOS Auto runs DeepFilterNet plus a speech gate on that capture hook so room noise stays silent. On Windows Auto runs the software chain with the same model. Off and Music mode run a cpal mic through our own APM. No High level. Linux Auto live-tested in a real call |
191
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto and Low on Linux keep the Pulse ADM device track (same path as Web Teams); Linux/macOS Auto adds DeepFilterNet after WebRTC noise suppression on that capture hook; if it runs over its frame budget it switches off for the call. On Windows Auto runs the software chain with the same model. Off and Music mode run a cpal mic through our own APM. No High level. Linux Auto live-tested in a real call |
192
192
| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |
193
193
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |
194
194
| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |
@@ -188,7 +188,7 @@ Feature parity with the Microsoft Teams desktop client.188
| Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |188
| Recording | Done | Organizer "..." > Record and transcribe: Start recording, Record audio only, Start transcription only; Stop recording / Stop transcription / Stop both (confirm) through the recorder bot; header chip red "Recording" / "Recording audio" or blue "Transcribing" for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; video, audio only, transcription only and every stop variant run live; a stop sent while the recorder still settles is retried. Consent needs a tenant with the policy on |189
| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Transcription-only sessions (item media source `Transcript`) show the transcript without a recording card. "Audio only" comes from the chat event (`videoContent="CurtainOnly"`), with the video size check as fallback. Both signals read live on real recordings, fixtures unit tested; the transcript-only path was not run live |189
| Meeting recap tab | Partial | Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; occurrences, details and delete run live against real recordings. Transcription-only sessions (item media source `Transcript`) show the transcript without a recording card. "Audio only" comes from the chat event (`videoContent="CurtainOnly"`), with the video size check as fallback. Both signals read live on real recordings, fixtures unit tested; the transcript-only path was not run live |190
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |190
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |191
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto and Low on Linux keep the Pulse ADM device track (same path as Web Teams); Linux/macOS Auto runs DeepFilterNet plus a speech gate on that capture hook so room noise stays silent. On Windows Auto runs the software chain with the same model. Off and Music mode run a cpal mic through our own APM. No High level. Linux Auto live-tested in a real call |191
| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto and Low on Linux keep the Pulse ADM device track (same path as Web Teams); Linux/macOS Auto adds DeepFilterNet after WebRTC noise suppression on that capture hook; if it runs over its frame budget it switches off for the call. On Windows Auto runs the software chain with the same model. Off and Music mode run a cpal mic through our own APM. No High level. Linux Auto live-tested in a real call |192
| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |192
| Push to talk | Partial | Hold Ctrl+Space while muted to talk, release to mute; main window focused, not inside text fields; hint chip on the stage. Unit tested, not tried on the Windows build |193
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |193
| Breakout rooms (participant) | Partial | Move message from the participant update or the replacement invite: notice "Moving you to <room>", leave and join the room, "Return to main meeting" in the header, a closed room goes back to the main meeting. Parsing unit tested; needs an organizer who moves people |194
| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |194
| Call health and encryption | Partial | Header shows signal bars and a shield; click opens "Call health" with loss, round trip, jitter, bitrate, "Secured by Teams encryption", DTLS-SRTP cipher and media path (direct or via Microsoft media server). Unstable network banner with "Turn off incoming video", overloaded computer banner with "Turn off effects". Thresholds unit tested; not yet seen on a bad live network |@@ -1363,7 +1363,6 @@ async fn drive(
1363
1363
let mut mic_settings = MicSettings::default();
1364
1364
let mut audio_disabled = false;
1365
1365
let mut remote_audio: Option<RtcAudioTrack> = None;
1366
// sync_software_audio arms/disarms the capture hook from the outgoing track state.
1367
1366
sync_software_audio(
1368
1367
&factory,
1369
1368
options,
@@ -2233,12 +2232,10 @@ async fn drive(
2233
2232
}
2234
2233
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
2235
2234
mic_settings = settings;
2236
// Let sync_software_audio be the single authority for hook arming.
2237
2235
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2238
2236
}
2239
2237
Some(CallCommand::SetMicSettings(settings)) => {
2240
2238
mic_settings = settings;
2241
// Audio is off both ways: prepare Auto if needed, keep the capture hook disarmed.
2242
2239
crate::noise_stage::apply_for_outgoing(mic_settings, false);
2243
2240
}
2244
2241
Some(CallCommand::SelectOutput(choice)) => {
@@ -4195,7 +4192,6 @@ fn sync_software_audio(
4195
4192
) {
4196
4193
let running = software_audio.as_ref().map(|audio| audio.plan);
4197
4194
if running == wanted && !restart {
4198
// Keep the capture hook off while MicChain owns the mic (computer sound / Off / music).
4199
4195
crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4200
4196
return;
4201
4197
}
@@ -4266,7 +4262,9 @@ async fn tear_down(
4266
4262
report: &mut CallReport,
4267
4263
cancelled: bool,
4268
4264
) {
4269
// Drop DeepFilterNet capture hook so the next call starts without a stale post-processor.
4265
if crate::noise_stage::overloaded() {
4266
timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
4267
}
4270
4268
crate::noise_stage::clear();
4271
4269
for peer in &live.peers {
4272
4270
peer.close();
@@ -1363,7 +1363,6 @@ async fn drive(1363
let mut mic_settings = MicSettings::default();1363
let mut mic_settings = MicSettings::default();1364
let mut audio_disabled = false;1364
let mut audio_disabled = false;1365
let mut remote_audio: Option<RtcAudioTrack> = None;1365
let mut remote_audio: Option<RtcAudioTrack> = None;1366
// sync_software_audio arms/disarms the capture hook from the outgoing track state.1367
sync_software_audio(1366
sync_software_audio(1368
&factory,1367
&factory,1369
options,1368
options,@@ -2233,12 +2232,10 @@ async fn drive(2233
}2232
}2234
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {2233
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {2235
mic_settings = settings;2234
mic_settings = settings;2236
// Let sync_software_audio be the single authority for hook arming.2237
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2235
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2238
}2236
}2239
Some(CallCommand::SetMicSettings(settings)) => {2237
Some(CallCommand::SetMicSettings(settings)) => {2240
mic_settings = settings;2238
mic_settings = settings;2241
// Audio is off both ways: prepare Auto if needed, keep the capture hook disarmed.2242
crate::noise_stage::apply_for_outgoing(mic_settings, false);2239
crate::noise_stage::apply_for_outgoing(mic_settings, false);2243
}2240
}2244
Some(CallCommand::SelectOutput(choice)) => {2241
Some(CallCommand::SelectOutput(choice)) => {@@ -4195,7 +4192,6 @@ fn sync_software_audio(4195
) {4192
) {4196
let running = software_audio.as_ref().map(|audio| audio.plan);4193
let running = software_audio.as_ref().map(|audio| audio.plan);4197
if running == wanted && !restart {4194
if running == wanted && !restart {4198
// Keep the capture hook off while MicChain owns the mic (computer sound / Off / music).4199
crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());4195
crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());4200
return;4196
return;4201
}4197
}@@ -4266,7 +4262,9 @@ async fn tear_down(4266
report: &mut CallReport,4262
report: &mut CallReport,4267
cancelled: bool,4263
cancelled: bool,4268
) {4264
) {4269
// Drop DeepFilterNet capture hook so the next call starts without a stale post-processor.4265
if crate::noise_stage::overloaded() {4266
timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");4267
}4270
crate::noise_stage::clear();4268
crate::noise_stage::clear();4271
for peer in &live.peers {4269
for peer in &live.peers {4272
peer.close();4270
peer.close();@@ -1,5 +1,6 @@
1
1
use std::sync::atomic::{AtomicBool, Ordering};
2
2
use std::sync::{Mutex, Once};
3
use std::time::{Duration, Instant};
3
4
4
5
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
5
6
use ndarray::{ArrayView2, ArrayViewMut2};
@@ -7,26 +8,20 @@ use ndarray::{ArrayView2, ArrayViewMut2};
7
8
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
8
9
use crate::mic_processing::MicSettings;
9
10
10
/// WebRTC `AudioBuffer` full-band channels are FloatS16 (`[-32768, 32768]`).
11
11
const PCM_SCALE: f32 = 32768.0;
12
const ATTENUATION_LIMIT_DB: f32 = 30.0;
12
const ATTENUATION_LIMIT_DB: f32 = 40.0;
13
13
const MIN_LOCAL_SNR_DB: f32 = -15.0;
14
14
const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;
15
15
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;
16
16
const WARM_UP_FRAMES: usize = 100;
17
/// Keep the gate open briefly after speech so word endings are not cut.
18
const GATE_HANGOVER_FRAMES: u32 = 20;
19
/// Open when post-filter energy is this many times the learned residual-noise floor (~9 dB).
20
const GATE_OPEN_OVER_NOISE: f32 = 8.0;
21
/// Ignore a near-empty floor so the first frames after hangup do not stick open.
22
const GATE_MIN_NOISE_ENERGY: f32 = 50.0;
23
const GATE_NOISE_LEARN_FRAMES: u32 = 50;
17
const FRAME_BUDGET: Duration = Duration::from_millis(6);
18
const SLOW_FRAME_LIMIT: u32 = 5;
24
19
25
20
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);
26
21
static PREPARE: Once = Once::new();
27
22
static HOOK_STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());
28
23
static HOOK_ARMED: AtomicBool = AtomicBool::new(false);
29
static WRONG_FRAME_LOGGED: Once = Once::new();
24
static OVERLOADED: AtomicBool = AtomicBool::new(false);
30
25
31
26
fn load_model() -> Option<DfTract> {
32
27
let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB))
@@ -109,19 +104,10 @@ fn ready_model() -> Option<DfTract> {
109
104
.map(DfTract::fork)
110
105
}
111
106
112
fn energy_of(samples: &[f32]) -> f32 {
113
samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len().max(1) as f32
114
}
115
116
/// Whether Auto on the platform device track should install the capture post-processor hook.
117
pub fn should_arm_hook(settings: MicSettings, device_track_outgoing: bool) -> bool {
107
fn should_arm_hook(settings: MicSettings, device_track_outgoing: bool) -> bool {
118
108
settings.ml_noise_suppression() && settings.uses_device_track() && device_track_outgoing
119
109
}
120
110
121
pub fn hook_armed() -> bool {
122
HOOK_ARMED.load(Ordering::Relaxed)
123
}
124
125
111
fn capture_hook(channel_index: usize, samples: &mut [f32]) {
126
112
if !HOOK_ARMED.load(Ordering::Relaxed) {
127
113
return;
@@ -129,7 +115,12 @@ fn capture_hook(channel_index: usize, samples: &mut [f32]) {
129
115
let Ok(mut stage) = HOOK_STAGE.try_lock() else {
130
116
return;
131
117
};
118
let started = Instant::now();
132
119
stage.process(channel_index, samples);
120
if stage.budget.record(started.elapsed()) {
121
OVERLOADED.store(true, Ordering::Relaxed);
122
HOOK_ARMED.store(false, Ordering::Relaxed);
123
}
133
124
}
134
125
135
126
fn install_hook(armed: bool) {
@@ -137,39 +128,56 @@ fn install_hook(armed: bool) {
137
128
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));
138
129
}
139
130
140
/// Prepare DeepFilterNet when Auto needs it, and arm the capture hook only while the
141
/// Pulse / CoreAudio device track is the outgoing microphone.
142
pub fn apply(settings: MicSettings) {
143
apply_for_outgoing(settings, settings.uses_device_track());
144
}
145
146
/// Same as [`apply`], but `device_track_outgoing` is false while MicChain owns the mic
147
/// (Off, music mode, computer sound, Windows).
131
/// Arms DeepFilterNet on the capture hook only while the Pulse / CoreAudio device track is the
132
/// outgoing microphone. WebRTC's own noise suppression keeps running before it either way.
148
133
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {
149
134
if settings.ml_noise_suppression() {
150
135
prepare();
151
136
}
152
install_hook(should_arm_hook(settings, device_track_outgoing));
137
let armed =
138
should_arm_hook(settings, device_track_outgoing) && !OVERLOADED.load(Ordering::Relaxed);
139
install_hook(armed);
140
}
141
142
/// True once the hook ran over its frame budget and switched itself off for this call.
143
pub fn overloaded() -> bool {
144
OVERLOADED.load(Ordering::Relaxed)
153
145
}
154
146
155
/// Drop the capture hook on hangup and reset learned gate state so the next call starts clean.
156
147
pub fn clear() {
157
148
install_hook(false);
149
OVERLOADED.store(false, Ordering::Relaxed);
158
150
if let Ok(mut stage) = HOOK_STAGE.lock() {
159
151
*stage = NoiseStage::new();
160
152
}
161
153
}
162
154
155
#[derive(Default)]
156
struct FrameBudget {
157
slow_frames: u32,
158
}
159
160
impl FrameBudget {
161
const fn new() -> Self {
162
FrameBudget { slow_frames: 0 }
163
}
164
165
fn record(&mut self, elapsed: Duration) -> bool {
166
if elapsed > FRAME_BUDGET {
167
self.slow_frames += 1;
168
} else {
169
self.slow_frames = 0;
170
}
171
self.slow_frames >= SLOW_FRAME_LIMIT
172
}
173
}
174
163
175
pub struct NoiseStage {
164
176
channels: Vec<Option<DfTract>>,
165
177
input: Vec<f32>,
166
178
output: Vec<f32>,
167
179
pcm: Vec<f32>,
168
gate_hangover: Vec<u32>,
169
noise_floor: Vec<f32>,
170
noise_frames: Vec<u32>,
171
/// When false, only DeepFilterNet runs (used by the attenuation-limit unit test).
172
pub gate: bool,
180
budget: FrameBudget,
173
181
}
174
182
175
183
impl NoiseStage {
@@ -179,79 +187,22 @@ impl NoiseStage {
179
187
input: Vec::new(),
180
188
output: Vec::new(),
181
189
pcm: Vec::new(),
182
gate_hangover: Vec::new(),
183
noise_floor: Vec::new(),
184
noise_frames: Vec::new(),
185
gate: true,
190
budget: FrameBudget::new(),
186
191
}
187
192
}
188
193
189
fn ensure_channel(&mut self, channel_index: usize) {
190
while self.channels.len() <= channel_index {
191
self.channels.push(None);
192
}
193
while self.gate_hangover.len() <= channel_index {
194
self.gate_hangover.push(0);
195
}
196
while self.noise_floor.len() <= channel_index {
197
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);
198
}
199
while self.noise_frames.len() <= channel_index {
200
self.noise_frames.push(0);
201
}
202
if self.channels[channel_index].is_none() {
203
self.channels[channel_index] = ready_model();
204
}
205
}
206
207
/// Learns residual noise after DeepFilterNet; speech sits well above that floor and keeps a short hangover.
208
fn apply_gate(&mut self, channel_index: usize, samples: &mut [f32]) {
209
if !self.gate {
210
return;
211
}
212
while self.gate_hangover.len() <= channel_index {
213
self.gate_hangover.push(0);
214
}
215
while self.noise_floor.len() <= channel_index {
216
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);
217
}
218
while self.noise_frames.len() <= channel_index {
219
self.noise_frames.push(0);
220
}
221
let frame_energy = energy_of(samples);
222
let floor = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY);
223
let learning = self.noise_frames[channel_index] < GATE_NOISE_LEARN_FRAMES;
224
let near_floor = frame_energy <= floor * 2.0;
225
if learning || near_floor {
226
self.noise_floor[channel_index] = floor * 0.95 + frame_energy * 0.05;
227
self.noise_frames[channel_index] =
228
self.noise_frames[channel_index].saturating_add(1);
229
}
230
let open_at = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY) * GATE_OPEN_OVER_NOISE;
231
if frame_energy > open_at {
232
self.gate_hangover[channel_index] = GATE_HANGOVER_FRAMES;
233
return;
234
}
235
if self.gate_hangover[channel_index] > 0 {
236
self.gate_hangover[channel_index] -= 1;
237
return;
238
}
239
samples.fill(0.0);
240
}
241
242
/// FloatS16 frames from the WebRTC capture hook (or converted PCM).
243
194
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
244
195
if samples.len() != FRAME_SAMPLES {
245
WRONG_FRAME_LOGGED.call_once(|| {
246
eprintln!(
247
"noise stage: expected {FRAME_SAMPLES} samples at {SAMPLE_RATE} Hz, got {}",
248
samples.len()
249
);
250
});
251
196
return;
252
197
}
253
self.ensure_channel(channel_index);
254
let Some(model) = self.channels[channel_index].as_mut() else {
198
while self.channels.len() <= channel_index {
199
self.channels.push(None);
200
}
201
let channel = &mut self.channels[channel_index];
202
if channel.is_none() {
203
*channel = ready_model();
204
}
205
let Some(model) = channel.as_mut() else {
255
206
return;
256
207
};
257
208
self.input.clear();
@@ -270,7 +221,6 @@ impl NoiseStage {
270
221
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
271
222
*sample = enhanced * PCM_SCALE;
272
223
}
273
self.apply_gate(channel_index, samples);
274
224
}
275
225
276
226
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
@@ -295,7 +245,6 @@ impl Default for NoiseStage {
295
245
mod tests {
296
246
use super::*;
297
247
use crate::mic_processing::NoiseSuppression;
298
use std::time::{Duration, Instant};
299
248
300
249
fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {
301
250
(0..frame_len)
@@ -309,7 +258,7 @@ mod tests {
309
258
}
310
259
311
260
fn energy(samples: &[f32]) -> f32 {
312
energy_of(samples)
261
samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32
313
262
}
314
263
315
264
fn stage_with_model() -> NoiseStage {
@@ -342,7 +291,6 @@ mod tests {
342
291
let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();
343
292
let mut stage = NoiseStage {
344
293
channels: vec![Some(model)],
345
gate: false,
346
294
..NoiseStage::new()
347
295
};
348
296
let mut state = 0x1234_5678_u32;
@@ -393,117 +341,49 @@ mod tests {
393
341
}
394
342
395
343
#[test]
396
fn speech_above_the_learned_noise_floor_stays_audible() {
397
let mut stage = NoiseStage::new();
398
// Teach the gate a quiet residual floor (as DeepFilterNet leaves after noise).
399
for _ in 0..GATE_NOISE_LEARN_FRAMES {
400
let mut residual = vec![20.0_f32; FRAME_SAMPLES];
401
stage.apply_gate(0, &mut residual);
344
fn a_short_slow_stretch_is_tolerated_and_a_long_one_trips_the_budget() {
345
let slow = FRAME_BUDGET * 2;
346
let fast = FRAME_BUDGET / 2;
347
let mut budget = FrameBudget::new();
348
for _ in 1..SLOW_FRAME_LIMIT {
349
assert!(!budget.record(slow));
402
350
}
403
let speech_amp = 800.0_f32;
404
let mut speech: Vec<f32> = (0..FRAME_SAMPLES)
405
.map(|sample| {
406
if sample % 2 == 0 {
407
speech_amp
408
} else {
409
-speech_amp
410
}
411
})
412
.collect();
413
let before = energy(&speech);
414
stage.apply_gate(0, &mut speech);
415
assert!(
416
energy(&speech) > before * 0.9,
417
"speech above the noise floor must pass the gate"
418
);
419
}
420
421
#[test]
422
fn residual_noise_is_gated_to_silence_after_hangover() {
423
let mut stage = stage_with_model();
424
let mut state = 0xabcdefu32;
425
for _ in 0..(GATE_HANGOVER_FRAMES + 30) {
426
let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
427
stage.process(0, &mut frame);
351
assert!(!budget.record(fast));
352
for _ in 1..SLOW_FRAME_LIMIT {
353
assert!(!budget.record(slow));
428
354
}
429
let mut quiet = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
430
stage.process(0, &mut quiet);
431
assert!(
432
energy(&quiet) < 1.0,
433
"gated residual should be near silence, energy {}",
434
energy(&quiet)
435
);
355
assert!(budget.record(slow));
436
356
}
437
357
438
358
#[test]
439
fn linux_auto_arms_the_hook_and_other_modes_do_not() {
440
clear();
359
fn only_linux_and_macos_auto_arm_the_hook_and_an_overload_keeps_it_off_until_hangup() {
441
360
let auto = MicSettings::default();
442
// Windows never uses the device track, so Auto stays in MicChain even when
443
// the caller says the device track is outgoing. Linux and macOS arm the hook.
444
assert_eq!(should_arm_hook(auto, true), auto.uses_device_track());
445
assert!(!should_arm_hook(auto, false), "MicChain / computer sound");
446
apply_for_outgoing(auto, true);
447
assert_eq!(hook_armed(), auto.uses_device_track());
448
449
361
let low = MicSettings {
450
362
noise_suppression: NoiseSuppression::Low,
451
363
music_mode: false,
452
364
};
453
assert!(!should_arm_hook(low, true));
454
apply_for_outgoing(low, true);
455
assert!(!hook_armed());
456
457
let off = MicSettings {
458
noise_suppression: NoiseSuppression::Off,
459
music_mode: false,
460
};
461
assert!(!should_arm_hook(off, false));
462
apply_for_outgoing(off, false);
463
assert!(!hook_armed());
464
465
365
let music = MicSettings {
466
366
noise_suppression: NoiseSuppression::Auto,
467
367
music_mode: true,
468
368
};
469
assert!(!should_arm_hook(music, false));
470
apply_for_outgoing(music, false);
471
assert!(!hook_armed());
472
473
// Windows Auto never uses the device track, so the hook stays off.
474
assert!(!auto.uses_device_track_on(true));
369
assert!(!should_arm_hook(auto, false));
370
assert!(!should_arm_hook(low, true));
371
assert!(!should_arm_hook(music, true));
475
372
assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));
476
373
477
374
clear();
478
assert!(!hook_armed());
479
}
375
apply_for_outgoing(auto, true);
376
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());
480
377
481
#[test]
482
fn clear_resets_learned_gate_state() {
483
apply_for_outgoing(MicSettings::default(), true);
484
{
485
let mut stage = HOOK_STAGE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
486
stage.noise_floor = vec![999_999.0];
487
stage.gate_hangover = vec![GATE_HANGOVER_FRAMES];
488
stage.noise_frames = vec![GATE_NOISE_LEARN_FRAMES];
489
}
490
clear();
491
assert!(!hook_armed());
492
let stage = HOOK_STAGE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
493
assert!(stage.noise_floor.is_empty());
494
assert!(stage.gate_hangover.is_empty());
495
assert!(stage.noise_frames.is_empty());
496
}
378
OVERLOADED.store(true, Ordering::Relaxed);
379
apply_for_outgoing(auto, true);
380
assert!(!HOOK_ARMED.load(Ordering::Relaxed));
381
assert!(overloaded());
497
382
498
#[test]
499
fn hook_and_mic_chain_never_arm_together() {
500
let auto = MicSettings::default();
501
// Device track outgoing arms the hook only where Auto stays on Pulse/CoreAudio.
502
assert_eq!(should_arm_hook(auto, true), auto.uses_device_track());
503
assert!(auto.ml_noise_suppression());
504
assert!(auto.uses_device_track_on(false));
505
assert!(!auto.uses_device_track_on(true));
506
// Software outgoing → MicChain may run ml, hook stays off.
507
assert!(!should_arm_hook(auto, false));
383
clear();
384
assert!(!overloaded());
385
apply_for_outgoing(auto, true);
386
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());
387
clear();
508
388
}
509
389
}
@@ -1,5 +1,6 @@1
use std::sync::atomic::{AtomicBool, Ordering};1
use std::sync::atomic::{AtomicBool, Ordering};2
use std::sync::{Mutex, Once};2
use std::sync::{Mutex, Once};3
use std::time::{Duration, Instant};3
4
4
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};5
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};5
use ndarray::{ArrayView2, ArrayViewMut2};6
use ndarray::{ArrayView2, ArrayViewMut2};@@ -7,26 +8,20 @@ use ndarray::{ArrayView2, ArrayViewMut2};7
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};8
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};8
use crate::mic_processing::MicSettings;9
use crate::mic_processing::MicSettings;9
10
10
/// WebRTC `AudioBuffer` full-band channels are FloatS16 (`[-32768, 32768]`).11
const PCM_SCALE: f32 = 32768.0;11
const PCM_SCALE: f32 = 32768.0;12
const ATTENUATION_LIMIT_DB: f32 = 30.0;12
const ATTENUATION_LIMIT_DB: f32 = 40.0;13
const MIN_LOCAL_SNR_DB: f32 = -15.0;13
const MIN_LOCAL_SNR_DB: f32 = -15.0;14
const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;14
const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;15
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;15
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;16
const WARM_UP_FRAMES: usize = 100;16
const WARM_UP_FRAMES: usize = 100;17
/// Keep the gate open briefly after speech so word endings are not cut.17
const FRAME_BUDGET: Duration = Duration::from_millis(6);18
const GATE_HANGOVER_FRAMES: u32 = 20;18
const SLOW_FRAME_LIMIT: u32 = 5;19
/// Open when post-filter energy is this many times the learned residual-noise floor (~9 dB).20
const GATE_OPEN_OVER_NOISE: f32 = 8.0;21
/// Ignore a near-empty floor so the first frames after hangup do not stick open.22
const GATE_MIN_NOISE_ENERGY: f32 = 50.0;23
const GATE_NOISE_LEARN_FRAMES: u32 = 50;24
19
25
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);20
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);26
static PREPARE: Once = Once::new();21
static PREPARE: Once = Once::new();27
static HOOK_STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());22
static HOOK_STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());28
static HOOK_ARMED: AtomicBool = AtomicBool::new(false);23
static HOOK_ARMED: AtomicBool = AtomicBool::new(false);29
static WRONG_FRAME_LOGGED: Once = Once::new();24
static OVERLOADED: AtomicBool = AtomicBool::new(false);30
25
31
fn load_model() -> Option<DfTract> {26
fn load_model() -> Option<DfTract> {32
let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB))27
let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB))@@ -109,19 +104,10 @@ fn ready_model() -> Option<DfTract> {109
.map(DfTract::fork)104
.map(DfTract::fork)110
}105
}111
106
112
fn energy_of(samples: &[f32]) -> f32 {107
fn should_arm_hook(settings: MicSettings, device_track_outgoing: bool) -> bool {113
samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len().max(1) as f32114
}115
116
/// Whether Auto on the platform device track should install the capture post-processor hook.117
pub fn should_arm_hook(settings: MicSettings, device_track_outgoing: bool) -> bool {118
settings.ml_noise_suppression() && settings.uses_device_track() && device_track_outgoing108
settings.ml_noise_suppression() && settings.uses_device_track() && device_track_outgoing119
}109
}120
110
121
pub fn hook_armed() -> bool {122
HOOK_ARMED.load(Ordering::Relaxed)123
}124
125
fn capture_hook(channel_index: usize, samples: &mut [f32]) {111
fn capture_hook(channel_index: usize, samples: &mut [f32]) {126
if !HOOK_ARMED.load(Ordering::Relaxed) {112
if !HOOK_ARMED.load(Ordering::Relaxed) {127
return;113
return;@@ -129,7 +115,12 @@ fn capture_hook(channel_index: usize, samples: &mut [f32]) {129
let Ok(mut stage) = HOOK_STAGE.try_lock() else {115
let Ok(mut stage) = HOOK_STAGE.try_lock() else {130
return;116
return;131
};117
};118
let started = Instant::now();132
stage.process(channel_index, samples);119
stage.process(channel_index, samples);120
if stage.budget.record(started.elapsed()) {121
OVERLOADED.store(true, Ordering::Relaxed);122
HOOK_ARMED.store(false, Ordering::Relaxed);123
}133
}124
}134
125
135
fn install_hook(armed: bool) {126
fn install_hook(armed: bool) {@@ -137,39 +128,56 @@ fn install_hook(armed: bool) {137
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));128
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));138
}129
}139
130
140
/// Prepare DeepFilterNet when Auto needs it, and arm the capture hook only while the131
/// Arms DeepFilterNet on the capture hook only while the Pulse / CoreAudio device track is the141
/// Pulse / CoreAudio device track is the outgoing microphone.132
/// outgoing microphone. WebRTC's own noise suppression keeps running before it either way.142
pub fn apply(settings: MicSettings) {143
apply_for_outgoing(settings, settings.uses_device_track());144
}145
146
/// Same as [`apply`], but `device_track_outgoing` is false while MicChain owns the mic147
/// (Off, music mode, computer sound, Windows).148
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {133
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {149
if settings.ml_noise_suppression() {134
if settings.ml_noise_suppression() {150
prepare();135
prepare();151
}136
}152
install_hook(should_arm_hook(settings, device_track_outgoing));137
let armed =138
should_arm_hook(settings, device_track_outgoing) && !OVERLOADED.load(Ordering::Relaxed);139
install_hook(armed);140
}141
142
/// True once the hook ran over its frame budget and switched itself off for this call.143
pub fn overloaded() -> bool {144
OVERLOADED.load(Ordering::Relaxed)153
}145
}154
146
155
/// Drop the capture hook on hangup and reset learned gate state so the next call starts clean.156
pub fn clear() {147
pub fn clear() {157
install_hook(false);148
install_hook(false);149
OVERLOADED.store(false, Ordering::Relaxed);158
if let Ok(mut stage) = HOOK_STAGE.lock() {150
if let Ok(mut stage) = HOOK_STAGE.lock() {159
*stage = NoiseStage::new();151
*stage = NoiseStage::new();160
}152
}161
}153
}162
154
155
#[derive(Default)]156
struct FrameBudget {157
slow_frames: u32,158
}159
160
impl FrameBudget {161
const fn new() -> Self {162
FrameBudget { slow_frames: 0 }163
}164
165
fn record(&mut self, elapsed: Duration) -> bool {166
if elapsed > FRAME_BUDGET {167
self.slow_frames += 1;168
} else {169
self.slow_frames = 0;170
}171
self.slow_frames >= SLOW_FRAME_LIMIT172
}173
}174
163
pub struct NoiseStage {175
pub struct NoiseStage {164
channels: Vec<Option<DfTract>>,176
channels: Vec<Option<DfTract>>,165
input: Vec<f32>,177
input: Vec<f32>,166
output: Vec<f32>,178
output: Vec<f32>,167
pcm: Vec<f32>,179
pcm: Vec<f32>,168
gate_hangover: Vec<u32>,180
budget: FrameBudget,169
noise_floor: Vec<f32>,170
noise_frames: Vec<u32>,171
/// When false, only DeepFilterNet runs (used by the attenuation-limit unit test).172
pub gate: bool,173
}181
}174
182
175
impl NoiseStage {183
impl NoiseStage {@@ -179,79 +187,22 @@ impl NoiseStage {179
input: Vec::new(),187
input: Vec::new(),180
output: Vec::new(),188
output: Vec::new(),181
pcm: Vec::new(),189
pcm: Vec::new(),182
gate_hangover: Vec::new(),190
budget: FrameBudget::new(),183
noise_floor: Vec::new(),184
noise_frames: Vec::new(),185
gate: true,186
}191
}187
}192
}188
193
189
fn ensure_channel(&mut self, channel_index: usize) {190
while self.channels.len() <= channel_index {191
self.channels.push(None);192
}193
while self.gate_hangover.len() <= channel_index {194
self.gate_hangover.push(0);195
}196
while self.noise_floor.len() <= channel_index {197
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);198
}199
while self.noise_frames.len() <= channel_index {200
self.noise_frames.push(0);201
}202
if self.channels[channel_index].is_none() {203
self.channels[channel_index] = ready_model();204
}205
}206
207
/// Learns residual noise after DeepFilterNet; speech sits well above that floor and keeps a short hangover.208
fn apply_gate(&mut self, channel_index: usize, samples: &mut [f32]) {209
if !self.gate {210
return;211
}212
while self.gate_hangover.len() <= channel_index {213
self.gate_hangover.push(0);214
}215
while self.noise_floor.len() <= channel_index {216
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);217
}218
while self.noise_frames.len() <= channel_index {219
self.noise_frames.push(0);220
}221
let frame_energy = energy_of(samples);222
let floor = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY);223
let learning = self.noise_frames[channel_index] < GATE_NOISE_LEARN_FRAMES;224
let near_floor = frame_energy <= floor * 2.0;225
if learning || near_floor {226
self.noise_floor[channel_index] = floor * 0.95 + frame_energy * 0.05;227
self.noise_frames[channel_index] =228
self.noise_frames[channel_index].saturating_add(1);229
}230
let open_at = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY) * GATE_OPEN_OVER_NOISE;231
if frame_energy > open_at {232
self.gate_hangover[channel_index] = GATE_HANGOVER_FRAMES;233
return;234
}235
if self.gate_hangover[channel_index] > 0 {236
self.gate_hangover[channel_index] -= 1;237
return;238
}239
samples.fill(0.0);240
}241
242
/// FloatS16 frames from the WebRTC capture hook (or converted PCM).243
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {194
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {244
if samples.len() != FRAME_SAMPLES {195
if samples.len() != FRAME_SAMPLES {245
WRONG_FRAME_LOGGED.call_once(|| {246
eprintln!(247
"noise stage: expected {FRAME_SAMPLES} samples at {SAMPLE_RATE} Hz, got {}",248
samples.len()249
);250
});251
return;196
return;252
}197
}253
self.ensure_channel(channel_index);198
while self.channels.len() <= channel_index {254
let Some(model) = self.channels[channel_index].as_mut() else {199
self.channels.push(None);200
}201
let channel = &mut self.channels[channel_index];202
if channel.is_none() {203
*channel = ready_model();204
}205
let Some(model) = channel.as_mut() else {255
return;206
return;256
};207
};257
self.input.clear();208
self.input.clear();@@ -270,7 +221,6 @@ impl NoiseStage {270
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {221
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {271
*sample = enhanced * PCM_SCALE;222
*sample = enhanced * PCM_SCALE;272
}223
}273
self.apply_gate(channel_index, samples);274
}224
}275
225
276
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {226
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {@@ -295,7 +245,6 @@ impl Default for NoiseStage {295
mod tests {245
mod tests {296
use super::*;246
use super::*;297
use crate::mic_processing::NoiseSuppression;247
use crate::mic_processing::NoiseSuppression;298
use std::time::{Duration, Instant};299
248
300
fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {249
fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {301
(0..frame_len)250
(0..frame_len)@@ -309,7 +258,7 @@ mod tests {309
}258
}310
259
311
fn energy(samples: &[f32]) -> f32 {260
fn energy(samples: &[f32]) -> f32 {312
energy_of(samples)261
samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32313
}262
}314
263
315
fn stage_with_model() -> NoiseStage {264
fn stage_with_model() -> NoiseStage {@@ -342,7 +291,6 @@ mod tests {342
let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();291
let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();343
let mut stage = NoiseStage {292
let mut stage = NoiseStage {344
channels: vec![Some(model)],293
channels: vec![Some(model)],345
gate: false,346
..NoiseStage::new()294
..NoiseStage::new()347
};295
};348
let mut state = 0x1234_5678_u32;296
let mut state = 0x1234_5678_u32;@@ -393,117 +341,49 @@ mod tests {393
}341
}394
342
395
#[test]343
#[test]396
fn speech_above_the_learned_noise_floor_stays_audible() {344
fn a_short_slow_stretch_is_tolerated_and_a_long_one_trips_the_budget() {397
let mut stage = NoiseStage::new();345
let slow = FRAME_BUDGET * 2;398
// Teach the gate a quiet residual floor (as DeepFilterNet leaves after noise).346
let fast = FRAME_BUDGET / 2;399
for _ in 0..GATE_NOISE_LEARN_FRAMES {347
let mut budget = FrameBudget::new();400
let mut residual = vec![20.0_f32; FRAME_SAMPLES];348
for _ in 1..SLOW_FRAME_LIMIT {401
stage.apply_gate(0, &mut residual);349
assert!(!budget.record(slow));402
}350
}403
let speech_amp = 800.0_f32;351
assert!(!budget.record(fast));404
let mut speech: Vec<f32> = (0..FRAME_SAMPLES)352
for _ in 1..SLOW_FRAME_LIMIT {405
.map(|sample| {353
assert!(!budget.record(slow));406
if sample % 2 == 0 {407
speech_amp408
} else {409
-speech_amp410
}411
})412
.collect();413
let before = energy(&speech);414
stage.apply_gate(0, &mut speech);415
assert!(416
energy(&speech) > before * 0.9,417
"speech above the noise floor must pass the gate"418
);419
}420
421
#[test]422
fn residual_noise_is_gated_to_silence_after_hangover() {423
let mut stage = stage_with_model();424
let mut state = 0xabcdefu32;425
for _ in 0..(GATE_HANGOVER_FRAMES + 30) {426
let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);427
stage.process(0, &mut frame);428
}354
}429
let mut quiet = white_noise(FRAME_SAMPLES, 3000.0, &mut state);355
assert!(budget.record(slow));430
stage.process(0, &mut quiet);431
assert!(432
energy(&quiet) < 1.0,433
"gated residual should be near silence, energy {}",434
energy(&quiet)435
);436
}356
}437
357
438
#[test]358
#[test]439
fn linux_auto_arms_the_hook_and_other_modes_do_not() {359
fn only_linux_and_macos_auto_arm_the_hook_and_an_overload_keeps_it_off_until_hangup() {440
clear();441
let auto = MicSettings::default();360
let auto = MicSettings::default();442
// Windows never uses the device track, so Auto stays in MicChain even when443
// the caller says the device track is outgoing. Linux and macOS arm the hook.444
assert_eq!(should_arm_hook(auto, true), auto.uses_device_track());445
assert!(!should_arm_hook(auto, false), "MicChain / computer sound");446
apply_for_outgoing(auto, true);447
assert_eq!(hook_armed(), auto.uses_device_track());448
449
let low = MicSettings {361
let low = MicSettings {450
noise_suppression: NoiseSuppression::Low,362
noise_suppression: NoiseSuppression::Low,451
music_mode: false,363
music_mode: false,452
};364
};453
assert!(!should_arm_hook(low, true));454
apply_for_outgoing(low, true);455
assert!(!hook_armed());456
457
let off = MicSettings {458
noise_suppression: NoiseSuppression::Off,459
music_mode: false,460
};461
assert!(!should_arm_hook(off, false));462
apply_for_outgoing(off, false);463
assert!(!hook_armed());464
465
let music = MicSettings {365
let music = MicSettings {466
noise_suppression: NoiseSuppression::Auto,366
noise_suppression: NoiseSuppression::Auto,467
music_mode: true,367
music_mode: true,468
};368
};469
assert!(!should_arm_hook(music, false));369
assert!(!should_arm_hook(auto, false));470
apply_for_outgoing(music, false);370
assert!(!should_arm_hook(low, true));471
assert!(!hook_armed());371
assert!(!should_arm_hook(music, true));472
473
// Windows Auto never uses the device track, so the hook stays off.474
assert!(!auto.uses_device_track_on(true));475
assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));372
assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));476
373
477
clear();374
clear();478
assert!(!hook_armed());375
apply_for_outgoing(auto, true);479
}376
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());480
377
481
#[test]378
OVERLOADED.store(true, Ordering::Relaxed);482
fn clear_resets_learned_gate_state() {379
apply_for_outgoing(auto, true);483
apply_for_outgoing(MicSettings::default(), true);380
assert!(!HOOK_ARMED.load(Ordering::Relaxed));484
{381
assert!(overloaded());485
let mut stage = HOOK_STAGE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());486
stage.noise_floor = vec![999_999.0];487
stage.gate_hangover = vec![GATE_HANGOVER_FRAMES];488
stage.noise_frames = vec![GATE_NOISE_LEARN_FRAMES];489
}490
clear();491
assert!(!hook_armed());492
let stage = HOOK_STAGE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());493
assert!(stage.noise_floor.is_empty());494
assert!(stage.gate_hangover.is_empty());495
assert!(stage.noise_frames.is_empty());496
}497
382
498
#[test]383
clear();499
fn hook_and_mic_chain_never_arm_together() {384
assert!(!overloaded());500
let auto = MicSettings::default();385
apply_for_outgoing(auto, true);501
// Device track outgoing arms the hook only where Auto stays on Pulse/CoreAudio.386
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());502
assert_eq!(should_arm_hook(auto, true), auto.uses_device_track());387
clear();503
assert!(auto.ml_noise_suppression());504
assert!(auto.uses_device_track_on(false));505
assert!(!auto.uses_device_track_on(true));506
// Software outgoing → MicChain may run ml, hook stays off.507
assert!(!should_arm_hook(auto, false));508
}388
}509
}389
}