feat(calling): Linux/macOS Auto DeepFilterNet on the Pulse capture hook
Wire the unused WebRTC capture post-processor so Auto noise suppression runs DeepFilterNet plus a speech gate on the device track, matching Windows quality without leaving Pulse/CoreAudio. Verified in a live call.
@@ -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); on Windows Auto runs the software chain with DeepFilterNet. Off and Music mode run a cpal mic through our own APM. No High level. Checked with synthetic sources; Linux Auto aligned with Pulse after the mic-quality fix |
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 |
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); on Windows Auto runs the software chain with DeepFilterNet. Off and Music mode run a cpal mic through our own APM. No High level. Checked with synthetic sources; Linux Auto aligned with Pulse after the mic-quality fix |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 |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 |@@ -1380,6 +1380,7 @@ async fn drive(
1380
1380
),
1381
1381
false,
1382
1382
&mut software_audio,
1383
mic_settings,
1383
1384
control,
1384
1385
timeline,
1385
1386
);
@@ -1671,7 +1672,7 @@ async fn drive(
1671
1672
Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1672
1673
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1673
1674
local_video.stop_share();
1674
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, control, timeline);
1675
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);
1675
1676
clear_share(control);
1676
1677
control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1677
1678
}
@@ -2149,7 +2150,7 @@ async fn drive(
2149
2150
timeline.record("remote audio track", "receiving");
2150
2151
let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
2151
2152
if !had_far_end && software_audio.is_some() {
2152
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()), true, &mut software_audio, control, timeline);
2153
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()), true, &mut software_audio, mic_settings, control, timeline);
2153
2154
}
2154
2155
if options.record_remote {
2155
2156
tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
@@ -2210,7 +2211,7 @@ async fn drive(
2210
2211
let audio = live.audio.as_ref().expect("audio set above");
2211
2212
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
2212
2213
audio_disabled = true;
2213
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, control, timeline);
2214
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2214
2215
if audio.uses_devices() {
2215
2216
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2216
2217
factory.set_adm_recording_enabled(false);
@@ -2227,13 +2228,13 @@ async fn drive(
2227
2228
input = choice;
2228
2229
control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2229
2230
if software_audio.is_some() {
2230
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()), true, &mut software_audio, control, timeline);
2231
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()), true, &mut software_audio, mic_settings, control, timeline);
2231
2232
}
2232
2233
}
2233
2234
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
2234
2235
mic_settings = settings;
2235
2236
crate::noise_stage::apply(mic_settings);
2236
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, control, timeline);
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);
2237
2238
}
2238
2239
Some(CallCommand::SetMicSettings(settings)) => {
2239
2240
mic_settings = settings;
@@ -2401,7 +2402,7 @@ async fn drive(
2401
2402
match local_video.start_share(&source) {
2402
2403
Ok(()) => {
2403
2404
announce_share(control, &source);
2404
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, control, timeline);
2405
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);
2405
2406
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2406
2407
Ok((browser_offer, signaled, reply_tags)) => {
2407
2408
timeline.record_sdp("local offer", &signaled.sdp);
@@ -2433,7 +2434,7 @@ async fn drive(
2433
2434
Ok(()) => {
2434
2435
announce_share(control, &source);
2435
2436
tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2436
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, control, timeline);
2437
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);
2437
2438
}
2438
2439
Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2439
2440
}
@@ -2450,7 +2451,7 @@ async fn drive(
2450
2451
} else if direct && local_video.sharing() {
2451
2452
local_video.stop_share();
2452
2453
clear_share(control);
2453
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, control, timeline);
2454
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);
2454
2455
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2455
2456
Ok((browser_offer, signaled, reply_tags)) => {
2456
2457
timeline.record_sdp("local offer", &signaled.sdp);
@@ -2462,14 +2463,14 @@ async fn drive(
2462
2463
}
2463
2464
} else if local_video.sharing() {
2464
2465
local_video.stop_share();
2465
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, control, timeline);
2466
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);
2466
2467
clear_share(control);
2467
2468
tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2468
2469
}
2469
2470
}
2470
2471
Some(CallCommand::SetShareSound(on)) => {
2471
2472
share_sound_wanted = on;
2472
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, control, timeline);
2473
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);
2473
2474
}
2474
2475
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2475
2476
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
@@ -2939,7 +2940,7 @@ async fn drive(
2939
2940
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2940
2941
}
2941
2942
if input_changed && software_audio.is_some() {
2942
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()), true, &mut software_audio, control, timeline);
2943
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()), true, &mut software_audio, mic_settings, control, timeline);
2943
2944
}
2944
2945
}
2945
2946
}
@@ -4187,11 +4188,14 @@ fn sync_software_audio(
4187
4188
wanted: Option<SoftwareAudioPlan>,
4188
4189
restart: bool,
4189
4190
software_audio: &mut Option<SoftwareAudio>,
4191
mic_settings: MicSettings,
4190
4192
control: &CallControl,
4191
4193
timeline: &Timeline,
4192
4194
) {
4193
4195
let running = software_audio.as_ref().map(|audio| audio.plan);
4194
4196
if running == wanted && !restart {
4197
// Keep the capture hook off while MicChain owns the mic (computer sound / Off / music).
4198
crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4195
4199
return;
4196
4200
}
4197
4201
if running.is_some() {
@@ -4202,6 +4206,7 @@ fn sync_software_audio(
4202
4206
let Some(plan) = wanted else {
4203
4207
restore_device_track(factory, input, peer, device_track, timeline);
4204
4208
control.send(CallUpdate::ShareSound(false));
4209
crate::noise_stage::apply_for_outgoing(mic_settings, true);
4205
4210
return;
4206
4211
};
4207
4212
let started = SoftwareAudio::start(
@@ -4250,6 +4255,7 @@ fn sync_software_audio(
4250
4255
control.send(CallUpdate::Notice(notice.into()));
4251
4256
}
4252
4257
}
4258
crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4253
4259
}
4254
4260
4255
4261
async fn tear_down(
@@ -4259,6 +4265,8 @@ async fn tear_down(
4259
4265
report: &mut CallReport,
4260
4266
cancelled: bool,
4261
4267
) {
4268
// Drop DeepFilterNet capture hook so the next call starts without a stale post-processor.
4269
crate::noise_stage::clear();
4262
4270
for peer in &live.peers {
4263
4271
peer.close();
4264
4272
}
@@ -1380,6 +1380,7 @@ async fn drive(1380
),1380
),1381
false,1381
false,1382
&mut software_audio,1382
&mut software_audio,1383
mic_settings,1383
control,1384
control,1384
timeline,1385
timeline,1385
);1386
);@@ -1671,7 +1672,7 @@ async fn drive(1671
Change::Camera(on) => control.send(CallUpdate::Camera(on)),1672
Change::Camera(on) => control.send(CallUpdate::Camera(on)),1672
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {1673
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {1673
local_video.stop_share();1674
local_video.stop_share();1674
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, control, timeline);1675
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);1675
clear_share(control);1676
clear_share(control);1676
control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));1677
control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));1677
}1678
}@@ -2149,7 +2150,7 @@ async fn drive(2149
timeline.record("remote audio track", "receiving");2150
timeline.record("remote audio track", "receiving");2150
let had_far_end = remote_audio.replace(remote_track.clone()).is_some();2151
let had_far_end = remote_audio.replace(remote_track.clone()).is_some();2151
if !had_far_end && software_audio.is_some() {2152
if !had_far_end && software_audio.is_some() {2152
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()), true, &mut software_audio, control, timeline);2153
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()), true, &mut software_audio, mic_settings, control, timeline);2153
}2154
}2154
if options.record_remote {2155
if options.record_remote {2155
tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));2156
tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));@@ -2210,7 +2211,7 @@ async fn drive(2210
let audio = live.audio.as_ref().expect("audio set above");2211
let audio = live.audio.as_ref().expect("audio set above");2211
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);2212
muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);2212
audio_disabled = true;2213
audio_disabled = true;2213
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, control, timeline);2214
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);2214
if audio.uses_devices() {2215
if audio.uses_devices() {2215
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;2216
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;2216
factory.set_adm_recording_enabled(false);2217
factory.set_adm_recording_enabled(false);@@ -2227,13 +2228,13 @@ async fn drive(2227
input = choice;2228
input = choice;2228
control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });2229
control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });2229
if software_audio.is_some() {2230
if software_audio.is_some() {2230
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()), true, &mut software_audio, control, timeline);2231
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()), true, &mut software_audio, mic_settings, control, timeline);2231
}2232
}2232
}2233
}2233
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {2234
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {2234
mic_settings = settings;2235
mic_settings = settings;2235
crate::noise_stage::apply(mic_settings);2236
crate::noise_stage::apply(mic_settings);2236
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, control, timeline);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);2237
}2238
}2238
Some(CallCommand::SetMicSettings(settings)) => {2239
Some(CallCommand::SetMicSettings(settings)) => {2239
mic_settings = settings;2240
mic_settings = settings;@@ -2401,7 +2402,7 @@ async fn drive(2401
match local_video.start_share(&source) {2402
match local_video.start_share(&source) {2402
Ok(()) => {2403
Ok(()) => {2403
announce_share(control, &source);2404
announce_share(control, &source);2404
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, control, timeline);2405
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);2405
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2406
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2406
Ok((browser_offer, signaled, reply_tags)) => {2407
Ok((browser_offer, signaled, reply_tags)) => {2407
timeline.record_sdp("local offer", &signaled.sdp);2408
timeline.record_sdp("local offer", &signaled.sdp);@@ -2433,7 +2434,7 @@ async fn drive(2433
Ok(()) => {2434
Ok(()) => {2434
announce_share(control, &source);2435
announce_share(control, &source);2435
tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);2436
tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);2436
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, control, timeline);2437
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);2437
}2438
}2438
Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),2439
Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),2439
}2440
}@@ -2450,7 +2451,7 @@ async fn drive(2450
} else if direct && local_video.sharing() {2451
} else if direct && local_video.sharing() {2451
local_video.stop_share();2452
local_video.stop_share();2452
clear_share(control);2453
clear_share(control);2453
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, control, timeline);2454
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);2454
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2455
match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {2455
Ok((browser_offer, signaled, reply_tags)) => {2456
Ok((browser_offer, signaled, reply_tags)) => {2456
timeline.record_sdp("local offer", &signaled.sdp);2457
timeline.record_sdp("local offer", &signaled.sdp);@@ -2462,14 +2463,14 @@ async fn drive(2462
}2463
}2463
} else if local_video.sharing() {2464
} else if local_video.sharing() {2464
local_video.stop_share();2465
local_video.stop_share();2465
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, control, timeline);2466
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);2466
clear_share(control);2467
clear_share(control);2467
tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);2468
tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);2468
}2469
}2469
}2470
}2470
Some(CallCommand::SetShareSound(on)) => {2471
Some(CallCommand::SetShareSound(on)) => {2471
share_sound_wanted = on;2472
share_sound_wanted = on;2472
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, control, timeline);2473
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);2473
}2474
}2474
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),2475
Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),2475
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {2476
Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {@@ -2939,7 +2940,7 @@ async fn drive(2939
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());2940
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());2940
}2941
}2941
if input_changed && software_audio.is_some() {2942
if input_changed && software_audio.is_some() {2942
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()), true, &mut software_audio, control, timeline);2943
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()), true, &mut software_audio, mic_settings, control, timeline);2943
}2944
}2944
}2945
}2945
}2946
}@@ -4187,11 +4188,14 @@ fn sync_software_audio(4187
wanted: Option<SoftwareAudioPlan>,4188
wanted: Option<SoftwareAudioPlan>,4188
restart: bool,4189
restart: bool,4189
software_audio: &mut Option<SoftwareAudio>,4190
software_audio: &mut Option<SoftwareAudio>,4191
mic_settings: MicSettings,4190
control: &CallControl,4192
control: &CallControl,4191
timeline: &Timeline,4193
timeline: &Timeline,4192
) {4194
) {4193
let running = software_audio.as_ref().map(|audio| audio.plan);4195
let running = software_audio.as_ref().map(|audio| audio.plan);4194
if running == wanted && !restart {4196
if running == wanted && !restart {4197
// Keep the capture hook off while MicChain owns the mic (computer sound / Off / music).4198
crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());4195
return;4199
return;4196
}4200
}4197
if running.is_some() {4201
if running.is_some() {@@ -4202,6 +4206,7 @@ fn sync_software_audio(4202
let Some(plan) = wanted else {4206
let Some(plan) = wanted else {4203
restore_device_track(factory, input, peer, device_track, timeline);4207
restore_device_track(factory, input, peer, device_track, timeline);4204
control.send(CallUpdate::ShareSound(false));4208
control.send(CallUpdate::ShareSound(false));4209
crate::noise_stage::apply_for_outgoing(mic_settings, true);4205
return;4210
return;4206
};4211
};4207
let started = SoftwareAudio::start(4212
let started = SoftwareAudio::start(@@ -4250,6 +4255,7 @@ fn sync_software_audio(4250
control.send(CallUpdate::Notice(notice.into()));4255
control.send(CallUpdate::Notice(notice.into()));4251
}4256
}4252
}4257
}4258
crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());4253
}4259
}4254
4260
4255
async fn tear_down(4261
async fn tear_down(@@ -4259,6 +4265,8 @@ async fn tear_down(4259
report: &mut CallReport,4265
report: &mut CallReport,4260
cancelled: bool,4266
cancelled: bool,4261
) {4267
) {4268
// Drop DeepFilterNet capture hook so the next call starts without a stale post-processor.4269
crate::noise_stage::clear();4262
for peer in &live.peers {4270
for peer in &live.peers {4263
peer.close();4271
peer.close();4264
}4272
}@@ -1,3 +1,4 @@
1
use std::sync::atomic::{AtomicBool, Ordering};
1
2
use std::sync::{Mutex, Once};
2
3
3
4
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
@@ -6,15 +7,26 @@ use ndarray::{ArrayView2, ArrayViewMut2};
6
7
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
7
8
use crate::mic_processing::MicSettings;
8
9
10
/// WebRTC `AudioBuffer` full-band channels are FloatS16 (`[-32768, 32768]`).
9
11
const PCM_SCALE: f32 = 32768.0;
10
12
const ATTENUATION_LIMIT_DB: f32 = 30.0;
11
13
const MIN_LOCAL_SNR_DB: f32 = -15.0;
12
14
const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;
13
15
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;
14
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;
15
24
16
25
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);
17
26
static PREPARE: Once = Once::new();
27
static HOOK_STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());
28
static HOOK_ARMED: AtomicBool = AtomicBool::new(false);
29
static WRONG_FRAME_LOGGED: Once = Once::new();
18
30
19
31
fn load_model() -> Option<DfTract> {
20
32
let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB))
@@ -97,11 +109,64 @@ fn ready_model() -> Option<DfTract> {
97
109
.map(DfTract::fork)
98
110
}
99
111
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 {
118
settings.ml_noise_suppression() && settings.uses_device_track() && device_track_outgoing
119
}
120
121
pub fn hook_armed() -> bool {
122
HOOK_ARMED.load(Ordering::Relaxed)
123
}
124
125
fn capture_hook(channel_index: usize, samples: &mut [f32]) {
126
if !HOOK_ARMED.load(Ordering::Relaxed) {
127
return;
128
}
129
let Ok(mut stage) = HOOK_STAGE.try_lock() else {
130
return;
131
};
132
stage.process(channel_index, samples);
133
}
134
135
fn install_hook(armed: bool) {
136
HOOK_ARMED.store(armed, Ordering::Relaxed);
137
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));
138
}
139
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).
148
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {
149
if settings.ml_noise_suppression() {
150
prepare();
151
}
152
install_hook(should_arm_hook(settings, device_track_outgoing));
153
}
154
155
/// Drop the capture hook on hangup so the next call starts clean.
156
pub fn clear() {
157
install_hook(false);
158
}
159
100
160
pub struct NoiseStage {
101
161
channels: Vec<Option<DfTract>>,
102
162
input: Vec<f32>,
103
163
output: Vec<f32>,
104
164
pcm: Vec<f32>,
165
gate_hangover: Vec<u32>,
166
noise_floor: Vec<f32>,
167
noise_frames: Vec<u32>,
168
/// When false, only DeepFilterNet runs (used by the attenuation-limit unit test).
169
pub gate: bool,
105
170
}
106
171
107
172
impl NoiseStage {
@@ -111,21 +176,79 @@ impl NoiseStage {
111
176
input: Vec::new(),
112
177
output: Vec::new(),
113
178
pcm: Vec::new(),
179
gate_hangover: Vec::new(),
180
noise_floor: Vec::new(),
181
noise_frames: Vec::new(),
182
gate: true,
114
183
}
115
184
}
116
185
117
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
118
if samples.len() != FRAME_SAMPLES {
119
return;
120
}
186
fn ensure_channel(&mut self, channel_index: usize) {
121
187
while self.channels.len() <= channel_index {
122
188
self.channels.push(None);
123
189
}
124
let channel = &mut self.channels[channel_index];
125
if channel.is_none() {
126
*channel = ready_model();
190
while self.gate_hangover.len() <= channel_index {
191
self.gate_hangover.push(0);
192
}
193
while self.noise_floor.len() <= channel_index {
194
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);
195
}
196
while self.noise_frames.len() <= channel_index {
197
self.noise_frames.push(0);
198
}
199
if self.channels[channel_index].is_none() {
200
self.channels[channel_index] = ready_model();
201
}
202
}
203
204
/// Learns residual noise after DeepFilterNet; speech sits well above that floor and keeps a short hangover.
205
fn apply_gate(&mut self, channel_index: usize, samples: &mut [f32]) {
206
if !self.gate {
207
return;
208
}
209
while self.gate_hangover.len() <= channel_index {
210
self.gate_hangover.push(0);
127
211
}
128
let Some(model) = channel.as_mut() else {
212
while self.noise_floor.len() <= channel_index {
213
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);
214
}
215
while self.noise_frames.len() <= channel_index {
216
self.noise_frames.push(0);
217
}
218
let frame_energy = energy_of(samples);
219
let floor = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY);
220
let learning = self.noise_frames[channel_index] < GATE_NOISE_LEARN_FRAMES;
221
let near_floor = frame_energy <= floor * 2.0;
222
if learning || near_floor {
223
self.noise_floor[channel_index] = floor * 0.95 + frame_energy * 0.05;
224
self.noise_frames[channel_index] =
225
self.noise_frames[channel_index].saturating_add(1);
226
}
227
let open_at = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY) * GATE_OPEN_OVER_NOISE;
228
if frame_energy > open_at {
229
self.gate_hangover[channel_index] = GATE_HANGOVER_FRAMES;
230
return;
231
}
232
if self.gate_hangover[channel_index] > 0 {
233
self.gate_hangover[channel_index] -= 1;
234
return;
235
}
236
samples.fill(0.0);
237
}
238
239
/// FloatS16 frames from the WebRTC capture hook (or converted PCM).
240
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
241
if samples.len() != FRAME_SAMPLES {
242
WRONG_FRAME_LOGGED.call_once(|| {
243
eprintln!(
244
"noise stage: expected {FRAME_SAMPLES} samples at {SAMPLE_RATE} Hz, got {}",
245
samples.len()
246
);
247
});
248
return;
249
}
250
self.ensure_channel(channel_index);
251
let Some(model) = self.channels[channel_index].as_mut() else {
129
252
return;
130
253
};
131
254
self.input.clear();
@@ -144,6 +267,7 @@ impl NoiseStage {
144
267
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
145
268
*sample = enhanced * PCM_SCALE;
146
269
}
270
self.apply_gate(channel_index, samples);
147
271
}
148
272
149
273
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
@@ -164,15 +288,10 @@ impl Default for NoiseStage {
164
288
}
165
289
}
166
290
167
pub fn apply(settings: MicSettings) {
168
if settings.ml_noise_suppression() {
169
prepare();
170
}
171
}
172
173
291
#[cfg(test)]
174
292
mod tests {
175
293
use super::*;
294
use crate::mic_processing::NoiseSuppression;
176
295
use std::time::{Duration, Instant};
177
296
178
297
fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {
@@ -187,7 +306,7 @@ mod tests {
187
306
}
188
307
189
308
fn energy(samples: &[f32]) -> f32 {
190
samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32
309
energy_of(samples)
191
310
}
192
311
193
312
fn stage_with_model() -> NoiseStage {
@@ -220,6 +339,7 @@ mod tests {
220
339
let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();
221
340
let mut stage = NoiseStage {
222
341
channels: vec![Some(model)],
342
gate: false,
223
343
..NoiseStage::new()
224
344
};
225
345
let mut state = 0x1234_5678_u32;
@@ -268,4 +388,105 @@ mod tests {
268
388
eprintln!("deep filter per 10 ms frame: {per_frame:?}");
269
389
assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));
270
390
}
391
392
#[test]
393
fn speech_above_the_learned_noise_floor_stays_audible() {
394
let mut stage = NoiseStage::new();
395
// Teach the gate a quiet residual floor (as DeepFilterNet leaves after noise).
396
for _ in 0..GATE_NOISE_LEARN_FRAMES {
397
let mut residual = vec![20.0_f32; FRAME_SAMPLES];
398
stage.apply_gate(0, &mut residual);
399
}
400
let speech_amp = 800.0_f32;
401
let mut speech: Vec<f32> = (0..FRAME_SAMPLES)
402
.map(|sample| {
403
if sample % 2 == 0 {
404
speech_amp
405
} else {
406
-speech_amp
407
}
408
})
409
.collect();
410
let before = energy(&speech);
411
stage.apply_gate(0, &mut speech);
412
assert!(
413
energy(&speech) > before * 0.9,
414
"speech above the noise floor must pass the gate"
415
);
416
}
417
418
#[test]
419
fn residual_noise_is_gated_to_silence_after_hangover() {
420
let mut stage = stage_with_model();
421
let mut state = 0xabcdefu32;
422
for _ in 0..(GATE_HANGOVER_FRAMES + 30) {
423
let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
424
stage.process(0, &mut frame);
425
}
426
let mut quiet = white_noise(FRAME_SAMPLES, 3000.0, &mut state);
427
stage.process(0, &mut quiet);
428
assert!(
429
energy(&quiet) < 1.0,
430
"gated residual should be near silence, energy {}",
431
energy(&quiet)
432
);
433
}
434
435
#[test]
436
fn linux_auto_arms_the_hook_and_other_modes_do_not() {
437
clear();
438
let auto = MicSettings::default();
439
assert!(should_arm_hook(auto, true));
440
assert!(!should_arm_hook(auto, false), "MicChain / computer sound");
441
apply_for_outgoing(auto, true);
442
assert!(hook_armed());
443
444
let low = MicSettings {
445
noise_suppression: NoiseSuppression::Low,
446
music_mode: false,
447
};
448
assert!(!should_arm_hook(low, true));
449
apply_for_outgoing(low, true);
450
assert!(!hook_armed());
451
452
let off = MicSettings {
453
noise_suppression: NoiseSuppression::Off,
454
music_mode: false,
455
};
456
assert!(!should_arm_hook(off, false));
457
apply_for_outgoing(off, false);
458
assert!(!hook_armed());
459
460
let music = MicSettings {
461
noise_suppression: NoiseSuppression::Auto,
462
music_mode: true,
463
};
464
assert!(!should_arm_hook(music, false));
465
apply_for_outgoing(music, false);
466
assert!(!hook_armed());
467
468
// Windows Auto never uses the device track, so the hook stays off.
469
assert!(!auto.uses_device_track_on(true));
470
assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));
471
472
clear();
473
assert!(!hook_armed());
474
}
475
476
#[test]
477
fn hook_and_mic_chain_never_arm_together() {
478
let auto = MicSettings::default();
479
// Device track outgoing → hook, no MicChain ml path for Linux Auto.
480
assert!(should_arm_hook(auto, true));
481
assert!(
482
auto.ml_noise_suppression() && auto.uses_device_track(),
483
"Linux Auto: hook owns DeepFilterNet"
484
);
485
// Software outgoing → MicChain may run ml, hook stays off.
486
assert!(!should_arm_hook(auto, false));
487
assert!(
488
auto.ml_noise_suppression() && !should_arm_hook(auto, false),
489
"software path: MicChain only"
490
);
491
}
271
492
}
@@ -1,3 +1,4 @@1
use std::sync::atomic::{AtomicBool, Ordering};1
use std::sync::{Mutex, Once};2
use std::sync::{Mutex, Once};2
3
3
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};4
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};@@ -6,15 +7,26 @@ use ndarray::{ArrayView2, ArrayViewMut2};6
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};7
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};7
use crate::mic_processing::MicSettings;8
use crate::mic_processing::MicSettings;8
9
10
/// WebRTC `AudioBuffer` full-band channels are FloatS16 (`[-32768, 32768]`).9
const PCM_SCALE: f32 = 32768.0;11
const PCM_SCALE: f32 = 32768.0;10
const ATTENUATION_LIMIT_DB: f32 = 30.0;12
const ATTENUATION_LIMIT_DB: f32 = 30.0;11
const MIN_LOCAL_SNR_DB: f32 = -15.0;13
const MIN_LOCAL_SNR_DB: f32 = -15.0;12
const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;14
const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;13
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;15
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;14
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.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;15
24
16
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);25
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);17
static PREPARE: Once = Once::new();26
static PREPARE: Once = Once::new();27
static HOOK_STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());28
static HOOK_ARMED: AtomicBool = AtomicBool::new(false);29
static WRONG_FRAME_LOGGED: Once = Once::new();18
30
19
fn load_model() -> Option<DfTract> {31
fn load_model() -> Option<DfTract> {20
let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB))32
let mut model = DfTract::new(DfParams::default(), &runtime_params(ATTENUATION_LIMIT_DB))@@ -97,11 +109,64 @@ fn ready_model() -> Option<DfTract> {97
.map(DfTract::fork)109
.map(DfTract::fork)98
}110
}99
111
112
fn energy_of(samples: &[f32]) -> f32 {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_outgoing119
}120
121
pub fn hook_armed() -> bool {122
HOOK_ARMED.load(Ordering::Relaxed)123
}124
125
fn capture_hook(channel_index: usize, samples: &mut [f32]) {126
if !HOOK_ARMED.load(Ordering::Relaxed) {127
return;128
}129
let Ok(mut stage) = HOOK_STAGE.try_lock() else {130
return;131
};132
stage.process(channel_index, samples);133
}134
135
fn install_hook(armed: bool) {136
HOOK_ARMED.store(armed, Ordering::Relaxed);137
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));138
}139
140
/// Prepare DeepFilterNet when Auto needs it, and arm the capture hook only while the141
/// 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 mic147
/// (Off, music mode, computer sound, Windows).148
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {149
if settings.ml_noise_suppression() {150
prepare();151
}152
install_hook(should_arm_hook(settings, device_track_outgoing));153
}154
155
/// Drop the capture hook on hangup so the next call starts clean.156
pub fn clear() {157
install_hook(false);158
}159
100
pub struct NoiseStage {160
pub struct NoiseStage {101
channels: Vec<Option<DfTract>>,161
channels: Vec<Option<DfTract>>,102
input: Vec<f32>,162
input: Vec<f32>,103
output: Vec<f32>,163
output: Vec<f32>,104
pcm: Vec<f32>,164
pcm: Vec<f32>,165
gate_hangover: Vec<u32>,166
noise_floor: Vec<f32>,167
noise_frames: Vec<u32>,168
/// When false, only DeepFilterNet runs (used by the attenuation-limit unit test).169
pub gate: bool,105
}170
}106
171
107
impl NoiseStage {172
impl NoiseStage {@@ -111,21 +176,79 @@ impl NoiseStage {111
input: Vec::new(),176
input: Vec::new(),112
output: Vec::new(),177
output: Vec::new(),113
pcm: Vec::new(),178
pcm: Vec::new(),179
gate_hangover: Vec::new(),180
noise_floor: Vec::new(),181
noise_frames: Vec::new(),182
gate: true,114
}183
}115
}184
}116
185
117
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {186
fn ensure_channel(&mut self, channel_index: usize) {118
if samples.len() != FRAME_SAMPLES {119
return;120
}121
while self.channels.len() <= channel_index {187
while self.channels.len() <= channel_index {122
self.channels.push(None);188
self.channels.push(None);123
}189
}124
let channel = &mut self.channels[channel_index];190
while self.gate_hangover.len() <= channel_index {125
if channel.is_none() {191
self.gate_hangover.push(0);126
*channel = ready_model();192
}193
while self.noise_floor.len() <= channel_index {194
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);195
}196
while self.noise_frames.len() <= channel_index {197
self.noise_frames.push(0);198
}199
if self.channels[channel_index].is_none() {200
self.channels[channel_index] = ready_model();201
}202
}203
204
/// Learns residual noise after DeepFilterNet; speech sits well above that floor and keeps a short hangover.205
fn apply_gate(&mut self, channel_index: usize, samples: &mut [f32]) {206
if !self.gate {207
return;208
}209
while self.gate_hangover.len() <= channel_index {210
self.gate_hangover.push(0);127
}211
}128
let Some(model) = channel.as_mut() else {212
while self.noise_floor.len() <= channel_index {213
self.noise_floor.push(GATE_MIN_NOISE_ENERGY);214
}215
while self.noise_frames.len() <= channel_index {216
self.noise_frames.push(0);217
}218
let frame_energy = energy_of(samples);219
let floor = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY);220
let learning = self.noise_frames[channel_index] < GATE_NOISE_LEARN_FRAMES;221
let near_floor = frame_energy <= floor * 2.0;222
if learning || near_floor {223
self.noise_floor[channel_index] = floor * 0.95 + frame_energy * 0.05;224
self.noise_frames[channel_index] =225
self.noise_frames[channel_index].saturating_add(1);226
}227
let open_at = self.noise_floor[channel_index].max(GATE_MIN_NOISE_ENERGY) * GATE_OPEN_OVER_NOISE;228
if frame_energy > open_at {229
self.gate_hangover[channel_index] = GATE_HANGOVER_FRAMES;230
return;231
}232
if self.gate_hangover[channel_index] > 0 {233
self.gate_hangover[channel_index] -= 1;234
return;235
}236
samples.fill(0.0);237
}238
239
/// FloatS16 frames from the WebRTC capture hook (or converted PCM).240
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {241
if samples.len() != FRAME_SAMPLES {242
WRONG_FRAME_LOGGED.call_once(|| {243
eprintln!(244
"noise stage: expected {FRAME_SAMPLES} samples at {SAMPLE_RATE} Hz, got {}",245
samples.len()246
);247
});248
return;249
}250
self.ensure_channel(channel_index);251
let Some(model) = self.channels[channel_index].as_mut() else {129
return;252
return;130
};253
};131
self.input.clear();254
self.input.clear();@@ -144,6 +267,7 @@ impl NoiseStage {144
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {267
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {145
*sample = enhanced * PCM_SCALE;268
*sample = enhanced * PCM_SCALE;146
}269
}270
self.apply_gate(channel_index, samples);147
}271
}148
272
149
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {273
pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {@@ -164,15 +288,10 @@ impl Default for NoiseStage {164
}288
}165
}289
}166
290
167
pub fn apply(settings: MicSettings) {168
if settings.ml_noise_suppression() {169
prepare();170
}171
}172
173
#[cfg(test)]291
#[cfg(test)]174
mod tests {292
mod tests {175
use super::*;293
use super::*;294
use crate::mic_processing::NoiseSuppression;176
use std::time::{Duration, Instant};295
use std::time::{Duration, Instant};177
296
178
fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {297
fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {@@ -187,7 +306,7 @@ mod tests {187
}306
}188
307
189
fn energy(samples: &[f32]) -> f32 {308
fn energy(samples: &[f32]) -> f32 {190
samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32309
energy_of(samples)191
}310
}192
311
193
fn stage_with_model() -> NoiseStage {312
fn stage_with_model() -> NoiseStage {@@ -220,6 +339,7 @@ mod tests {220
let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();339
let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();221
let mut stage = NoiseStage {340
let mut stage = NoiseStage {222
channels: vec![Some(model)],341
channels: vec![Some(model)],342
gate: false,223
..NoiseStage::new()343
..NoiseStage::new()224
};344
};225
let mut state = 0x1234_5678_u32;345
let mut state = 0x1234_5678_u32;@@ -268,4 +388,105 @@ mod tests {268
eprintln!("deep filter per 10 ms frame: {per_frame:?}");388
eprintln!("deep filter per 10 ms frame: {per_frame:?}");269
assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));389
assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));270
}390
}391
392
#[test]393
fn speech_above_the_learned_noise_floor_stays_audible() {394
let mut stage = NoiseStage::new();395
// Teach the gate a quiet residual floor (as DeepFilterNet leaves after noise).396
for _ in 0..GATE_NOISE_LEARN_FRAMES {397
let mut residual = vec![20.0_f32; FRAME_SAMPLES];398
stage.apply_gate(0, &mut residual);399
}400
let speech_amp = 800.0_f32;401
let mut speech: Vec<f32> = (0..FRAME_SAMPLES)402
.map(|sample| {403
if sample % 2 == 0 {404
speech_amp405
} else {406
-speech_amp407
}408
})409
.collect();410
let before = energy(&speech);411
stage.apply_gate(0, &mut speech);412
assert!(413
energy(&speech) > before * 0.9,414
"speech above the noise floor must pass the gate"415
);416
}417
418
#[test]419
fn residual_noise_is_gated_to_silence_after_hangover() {420
let mut stage = stage_with_model();421
let mut state = 0xabcdefu32;422
for _ in 0..(GATE_HANGOVER_FRAMES + 30) {423
let mut frame = white_noise(FRAME_SAMPLES, 3000.0, &mut state);424
stage.process(0, &mut frame);425
}426
let mut quiet = white_noise(FRAME_SAMPLES, 3000.0, &mut state);427
stage.process(0, &mut quiet);428
assert!(429
energy(&quiet) < 1.0,430
"gated residual should be near silence, energy {}",431
energy(&quiet)432
);433
}434
435
#[test]436
fn linux_auto_arms_the_hook_and_other_modes_do_not() {437
clear();438
let auto = MicSettings::default();439
assert!(should_arm_hook(auto, true));440
assert!(!should_arm_hook(auto, false), "MicChain / computer sound");441
apply_for_outgoing(auto, true);442
assert!(hook_armed());443
444
let low = MicSettings {445
noise_suppression: NoiseSuppression::Low,446
music_mode: false,447
};448
assert!(!should_arm_hook(low, true));449
apply_for_outgoing(low, true);450
assert!(!hook_armed());451
452
let off = MicSettings {453
noise_suppression: NoiseSuppression::Off,454
music_mode: false,455
};456
assert!(!should_arm_hook(off, false));457
apply_for_outgoing(off, false);458
assert!(!hook_armed());459
460
let music = MicSettings {461
noise_suppression: NoiseSuppression::Auto,462
music_mode: true,463
};464
assert!(!should_arm_hook(music, false));465
apply_for_outgoing(music, false);466
assert!(!hook_armed());467
468
// Windows Auto never uses the device track, so the hook stays off.469
assert!(!auto.uses_device_track_on(true));470
assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));471
472
clear();473
assert!(!hook_armed());474
}475
476
#[test]477
fn hook_and_mic_chain_never_arm_together() {478
let auto = MicSettings::default();479
// Device track outgoing → hook, no MicChain ml path for Linux Auto.480
assert!(should_arm_hook(auto, true));481
assert!(482
auto.ml_noise_suppression() && auto.uses_device_track(),483
"Linux Auto: hook owns DeepFilterNet"484
);485
// Software outgoing → MicChain may run ml, hook stays off.486
assert!(!should_arm_hook(auto, false));487
assert!(488
auto.ml_noise_suppression() && !should_arm_hook(auto, false),489
"software path: MicChain only"490
);491
}271
}492
}