BlueGit

ict rusty-teams

Merge pull request #48: feat(calling): Linux/macOS Auto DeepFilterNet on the Pulse capture hook

metis Daniel Däschle · pushed by metis

Authored 2026-11-16 · 2 weeks ago

Hash
2472a1475d974ccd33741a7f28d49a1425acea1d
3 files changed +277 −30
ROADMAP.md +1 −1
@@ -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 |
crates/calling/src/call.rs +23 −14
@@ -1361,9 +1361,9 @@ async fn drive(
1361 1361 let mut software_audio: Option<SoftwareAudio> = None;
1362 1362 let mut share_sound_wanted = false;
1363 1363 let mut mic_settings = MicSettings::default();
1364 crate::noise_stage::apply(mic_settings);
1365 1364 let mut audio_disabled = false;
1366 1365 let mut remote_audio: Option<RtcAudioTrack> = None;
1366 // sync_software_audio arms/disarms the capture hook from the outgoing track state.
1367 1367 sync_software_audio(
1368 1368 &factory,
1369 1369 options,
@@ -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(), &current.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(), &current.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(), &current.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(), &current.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(), &current.peer, &track, None, false, &mut software_audio, control, timeline);
2214 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.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,17 +2228,18 @@ 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(), &current.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(), &current.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 crate::noise_stage::apply(mic_settings);
2236 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2236 // Let sync_software_audio be the single authority for hook arming.
2237 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.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;
2240 crate::noise_stage::apply(mic_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);
2241 2243 }
2242 2244 Some(CallCommand::SelectOutput(choice)) => {
2243 2245 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
@@ -2401,7 +2403,7 @@ async fn drive(
2401 2403 match local_video.start_share(&source) {
2402 2404 Ok(()) => {
2403 2405 announce_share(control, &source);
2404 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2406 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2405 2407 match offer_same_peer(&current.peer, &current.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 2408 Ok((browser_offer, signaled, reply_tags)) => {
2407 2409 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2433,7 +2435,7 @@ async fn drive(
2433 2435 Ok(()) => {
2434 2436 announce_share(control, &source);
2435 2437 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(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2438 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2437 2439 }
2438 2440 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2439 2441 }
@@ -2450,7 +2452,7 @@ async fn drive(
2450 2452 } else if direct && local_video.sharing() {
2451 2453 local_video.stop_share();
2452 2454 clear_share(control);
2453 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2455 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2454 2456 match offer_same_peer(&current.peer, &current.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 2457 Ok((browser_offer, signaled, reply_tags)) => {
2456 2458 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2462,14 +2464,14 @@ async fn drive(
2462 2464 }
2463 2465 } else if local_video.sharing() {
2464 2466 local_video.stop_share();
2465 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2467 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2466 2468 clear_share(control);
2467 2469 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2468 2470 }
2469 2471 }
2470 2472 Some(CallCommand::SetShareSound(on)) => {
2471 2473 share_sound_wanted = on;
2472 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2474 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2473 2475 }
2474 2476 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2475 2477 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
@@ -2939,7 +2941,7 @@ async fn drive(
2939 2941 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2940 2942 }
2941 2943 if input_changed && software_audio.is_some() {
2942 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
2944 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2943 2945 }
2944 2946 }
2945 2947 }
@@ -4187,11 +4189,14 @@ fn sync_software_audio(
4187 4189 wanted: Option<SoftwareAudioPlan>,
4188 4190 restart: bool,
4189 4191 software_audio: &mut Option<SoftwareAudio>,
4192 mic_settings: MicSettings,
4190 4193 control: &CallControl,
4191 4194 timeline: &Timeline,
4192 4195 ) {
4193 4196 let running = software_audio.as_ref().map(|audio| audio.plan);
4194 4197 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 4200 return;
4196 4201 }
4197 4202 if running.is_some() {
@@ -4202,6 +4207,7 @@ fn sync_software_audio(
4202 4207 let Some(plan) = wanted else {
4203 4208 restore_device_track(factory, input, peer, device_track, timeline);
4204 4209 control.send(CallUpdate::ShareSound(false));
4210 crate::noise_stage::apply_for_outgoing(mic_settings, true);
4205 4211 return;
4206 4212 };
4207 4213 let started = SoftwareAudio::start(
@@ -4250,6 +4256,7 @@ fn sync_software_audio(
4250 4256 control.send(CallUpdate::Notice(notice.into()));
4251 4257 }
4252 4258 }
4259 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4253 4260 }
4254 4261
4255 4262 async fn tear_down(
@@ -4259,6 +4266,8 @@ async fn tear_down(
4259 4266 report: &mut CallReport,
4260 4267 cancelled: bool,
4261 4268 ) {
4269 // Drop DeepFilterNet capture hook so the next call starts without a stale post-processor.
4270 crate::noise_stage::clear();
4262 4271 for peer in &live.peers {
4263 4272 peer.close();
4264 4273 }
@@ -1361,9 +1361,9 @@ async fn drive(
1361 let mut software_audio: Option<SoftwareAudio> = None;
1361 let mut software_audio: Option<SoftwareAudio> = None;
1362 let mut share_sound_wanted = false;
1362 let mut share_sound_wanted = false;
1363 let mut mic_settings = MicSettings::default();
1363 let mut mic_settings = MicSettings::default();
1364 crate::noise_stage::apply(mic_settings);
1365 let mut audio_disabled = false;
1364 let mut audio_disabled = false;
1366 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(
1367 sync_software_audio(
1368 &factory,
1368 &factory,
1369 options,
1369 options,
@@ -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(), &current.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(), &current.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(), &current.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(), &current.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(), &current.peer, &track, None, false, &mut software_audio, control, timeline);
2214 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.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,17 +2228,18 @@ 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(), &current.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(), &current.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 // Let sync_software_audio be the single authority for hook arming.
2236 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.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(), &current.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;
2240 crate::noise_stage::apply(mic_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);
2241 }
2243 }
2242 Some(CallCommand::SelectOutput(choice)) => {
2244 Some(CallCommand::SelectOutput(choice)) => {
2243 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2245 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
@@ -2401,7 +2403,7 @@ async fn drive(
2401 match local_video.start_share(&source) {
2403 match local_video.start_share(&source) {
2402 Ok(()) => {
2404 Ok(()) => {
2403 announce_share(control, &source);
2405 announce_share(control, &source);
2404 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2406 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.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(&current.peer, &current.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 {
2407 match offer_same_peer(&current.peer, &current.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)) => {
2408 Ok((browser_offer, signaled, reply_tags)) => {
2407 timeline.record_sdp("local offer", &signaled.sdp);
2409 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2433,7 +2435,7 @@ async fn drive(
2433 Ok(()) => {
2435 Ok(()) => {
2434 announce_share(control, &source);
2436 announce_share(control, &source);
2435 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2437 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(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2438 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2437 }
2439 }
2438 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2440 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2439 }
2441 }
@@ -2450,7 +2452,7 @@ async fn drive(
2450 } else if direct && local_video.sharing() {
2452 } else if direct && local_video.sharing() {
2451 local_video.stop_share();
2453 local_video.stop_share();
2452 clear_share(control);
2454 clear_share(control);
2453 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2455 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.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(&current.peer, &current.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 {
2456 match offer_same_peer(&current.peer, &current.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)) => {
2457 Ok((browser_offer, signaled, reply_tags)) => {
2456 timeline.record_sdp("local offer", &signaled.sdp);
2458 timeline.record_sdp("local offer", &signaled.sdp);
@@ -2462,14 +2464,14 @@ async fn drive(
2462 }
2464 }
2463 } else if local_video.sharing() {
2465 } else if local_video.sharing() {
2464 local_video.stop_share();
2466 local_video.stop_share();
2465 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2467 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.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);
2468 clear_share(control);
2467 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2469 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2468 }
2470 }
2469 }
2471 }
2470 Some(CallCommand::SetShareSound(on)) => {
2472 Some(CallCommand::SetShareSound(on)) => {
2471 share_sound_wanted = on;
2473 share_sound_wanted = on;
2472 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2474 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2473 }
2475 }
2474 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2476 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 {
2477 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
@@ -2939,7 +2941,7 @@ async fn drive(
2939 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2941 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2940 }
2942 }
2941 if input_changed && software_audio.is_some() {
2943 if input_changed && software_audio.is_some() {
2942 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
2944 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline);
2943 }
2945 }
2944 }
2946 }
2945 }
2947 }
@@ -4187,11 +4189,14 @@ fn sync_software_audio(
4187 wanted: Option<SoftwareAudioPlan>,
4189 wanted: Option<SoftwareAudioPlan>,
4188 restart: bool,
4190 restart: bool,
4189 software_audio: &mut Option<SoftwareAudio>,
4191 software_audio: &mut Option<SoftwareAudio>,
4192 mic_settings: MicSettings,
4190 control: &CallControl,
4193 control: &CallControl,
4191 timeline: &Timeline,
4194 timeline: &Timeline,
4192) {
4195) {
4193 let running = software_audio.as_ref().map(|audio| audio.plan);
4196 let running = software_audio.as_ref().map(|audio| audio.plan);
4194 if running == wanted && !restart {
4197 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 return;
4200 return;
4196 }
4201 }
4197 if running.is_some() {
4202 if running.is_some() {
@@ -4202,6 +4207,7 @@ fn sync_software_audio(
4202 let Some(plan) = wanted else {
4207 let Some(plan) = wanted else {
4203 restore_device_track(factory, input, peer, device_track, timeline);
4208 restore_device_track(factory, input, peer, device_track, timeline);
4204 control.send(CallUpdate::ShareSound(false));
4209 control.send(CallUpdate::ShareSound(false));
4210 crate::noise_stage::apply_for_outgoing(mic_settings, true);
4205 return;
4211 return;
4206 };
4212 };
4207 let started = SoftwareAudio::start(
4213 let started = SoftwareAudio::start(
@@ -4250,6 +4256,7 @@ fn sync_software_audio(
4250 control.send(CallUpdate::Notice(notice.into()));
4256 control.send(CallUpdate::Notice(notice.into()));
4251 }
4257 }
4252 }
4258 }
4259 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4253}
4260}
4254
4261
4255async fn tear_down(
4262async fn tear_down(
@@ -4259,6 +4266,8 @@ async fn tear_down(
4259 report: &mut CallReport,
4266 report: &mut CallReport,
4260 cancelled: bool,
4267 cancelled: bool,
4261) {
4268) {
4269 // Drop DeepFilterNet capture hook so the next call starts without a stale post-processor.
4270 crate::noise_stage::clear();
4262 for peer in &live.peers {
4271 for peer in &live.peers {
4263 peer.close();
4272 peer.close();
4264 }
4273 }
crates/calling/src/noise_stage.rs +253 −15
@@ -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,67 @@ 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 and reset learned gate state so the next call starts clean.
156 pub fn clear() {
157 install_hook(false);
158 if let Ok(mut stage) = HOOK_STAGE.lock() {
159 *stage = NoiseStage::new();
160 }
161 }
162
100 163 pub struct NoiseStage {
101 164 channels: Vec<Option<DfTract>>,
102 165 input: Vec<f32>,
103 166 output: Vec<f32>,
104 167 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,
105 173 }
106 174
107 175 impl NoiseStage {
@@ -111,21 +179,79 @@ impl NoiseStage {
111 179 input: Vec::new(),
112 180 output: Vec::new(),
113 181 pcm: Vec::new(),
182 gate_hangover: Vec::new(),
183 noise_floor: Vec::new(),
184 noise_frames: Vec::new(),
185 gate: true,
114 186 }
115 187 }
116 188
117 pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
118 if samples.len() != FRAME_SAMPLES {
119 return;
120 }
189 fn ensure_channel(&mut self, channel_index: usize) {
121 190 while self.channels.len() <= channel_index {
122 191 self.channels.push(None);
123 192 }
124 let channel = &mut self.channels[channel_index];
125 if channel.is_none() {
126 *channel = ready_model();
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]) {
244 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;
127 252 }
128 let Some(model) = channel.as_mut() else {
253 self.ensure_channel(channel_index);
254 let Some(model) = self.channels[channel_index].as_mut() else {
129 255 return;
130 256 };
131 257 self.input.clear();
@@ -144,6 +270,7 @@ impl NoiseStage {
144 270 for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
145 271 *sample = enhanced * PCM_SCALE;
146 272 }
273 self.apply_gate(channel_index, samples);
147 274 }
148 275
149 276 pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
@@ -164,15 +291,10 @@ impl Default for NoiseStage {
164 291 }
165 292 }
166 293
167 pub fn apply(settings: MicSettings) {
168 if settings.ml_noise_suppression() {
169 prepare();
170 }
171 }
172
173 294 #[cfg(test)]
174 295 mod tests {
175 296 use super::*;
297 use crate::mic_processing::NoiseSuppression;
176 298 use std::time::{Duration, Instant};
177 299
178 300 fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {
@@ -187,7 +309,7 @@ mod tests {
187 309 }
188 310
189 311 fn energy(samples: &[f32]) -> f32 {
190 samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32
312 energy_of(samples)
191 313 }
192 314
193 315 fn stage_with_model() -> NoiseStage {
@@ -220,6 +342,7 @@ mod tests {
220 342 let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();
221 343 let mut stage = NoiseStage {
222 344 channels: vec![Some(model)],
345 gate: false,
223 346 ..NoiseStage::new()
224 347 };
225 348 let mut state = 0x1234_5678_u32;
@@ -268,4 +391,119 @@ mod tests {
268 391 eprintln!("deep filter per 10 ms frame: {per_frame:?}");
269 392 assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));
270 393 }
394
395 #[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);
402 }
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);
428 }
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 );
436 }
437
438 #[test]
439 fn linux_auto_arms_the_hook_and_other_modes_do_not() {
440 clear();
441 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 let low = MicSettings {
450 noise_suppression: NoiseSuppression::Low,
451 music_mode: false,
452 };
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 {
466 noise_suppression: NoiseSuppression::Auto,
467 music_mode: true,
468 };
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));
475 assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));
476
477 clear();
478 assert!(!hook_armed());
479 }
480
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 }
497
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));
508 }
271 509 }
@@ -1,3 +1,4 @@
1use std::sync::atomic::{AtomicBool, Ordering};
1use std::sync::{Mutex, Once};
2use std::sync::{Mutex, Once};
2
3
3use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
4use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
@@ -6,15 +7,26 @@ use ndarray::{ArrayView2, ArrayViewMut2};
6use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
7use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
7use crate::mic_processing::MicSettings;
8use crate::mic_processing::MicSettings;
8
9
10/// WebRTC `AudioBuffer` full-band channels are FloatS16 (`[-32768, 32768]`).
9const PCM_SCALE: f32 = 32768.0;
11const PCM_SCALE: f32 = 32768.0;
10const ATTENUATION_LIMIT_DB: f32 = 30.0;
12const ATTENUATION_LIMIT_DB: f32 = 30.0;
11const MIN_LOCAL_SNR_DB: f32 = -15.0;
13const MIN_LOCAL_SNR_DB: f32 = -15.0;
12const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;
14const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;
13const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;
15const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;
14const WARM_UP_FRAMES: usize = 100;
16const WARM_UP_FRAMES: usize = 100;
17/// Keep the gate open briefly after speech so word endings are not cut.
18const GATE_HANGOVER_FRAMES: u32 = 20;
19/// Open when post-filter energy is this many times the learned residual-noise floor (~9 dB).
20const GATE_OPEN_OVER_NOISE: f32 = 8.0;
21/// Ignore a near-empty floor so the first frames after hangup do not stick open.
22const GATE_MIN_NOISE_ENERGY: f32 = 50.0;
23const GATE_NOISE_LEARN_FRAMES: u32 = 50;
15
24
16static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);
25static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);
17static PREPARE: Once = Once::new();
26static PREPARE: Once = Once::new();
27static HOOK_STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());
28static HOOK_ARMED: AtomicBool = AtomicBool::new(false);
29static WRONG_FRAME_LOGGED: Once = Once::new();
18
30
19fn load_model() -> Option<DfTract> {
31fn 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,67 @@ fn ready_model() -> Option<DfTract> {
97 .map(DfTract::fork)
109 .map(DfTract::fork)
98}
110}
99
111
112fn 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.
117pub 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
121pub fn hook_armed() -> bool {
122 HOOK_ARMED.load(Ordering::Relaxed)
123}
124
125fn 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
135fn 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.
142pub 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).
148pub 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 and reset learned gate state so the next call starts clean.
156pub fn clear() {
157 install_hook(false);
158 if let Ok(mut stage) = HOOK_STAGE.lock() {
159 *stage = NoiseStage::new();
160 }
161}
162
100pub struct NoiseStage {
163pub struct NoiseStage {
101 channels: Vec<Option<DfTract>>,
164 channels: Vec<Option<DfTract>>,
102 input: Vec<f32>,
165 input: Vec<f32>,
103 output: Vec<f32>,
166 output: Vec<f32>,
104 pcm: Vec<f32>,
167 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,
105}
173}
106
174
107impl NoiseStage {
175impl NoiseStage {
@@ -111,21 +179,79 @@ impl NoiseStage {
111 input: Vec::new(),
179 input: Vec::new(),
112 output: Vec::new(),
180 output: Vec::new(),
113 pcm: Vec::new(),
181 pcm: Vec::new(),
182 gate_hangover: Vec::new(),
183 noise_floor: Vec::new(),
184 noise_frames: Vec::new(),
185 gate: true,
114 }
186 }
115 }
187 }
116
188
117 pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
189 fn ensure_channel(&mut self, channel_index: usize) {
118 if samples.len() != FRAME_SAMPLES {
119 return;
120 }
121 while self.channels.len() <= channel_index {
190 while self.channels.len() <= channel_index {
122 self.channels.push(None);
191 self.channels.push(None);
123 }
192 }
124 let channel = &mut self.channels[channel_index];
193 while self.gate_hangover.len() <= channel_index {
125 if channel.is_none() {
194 self.gate_hangover.push(0);
126 *channel = ready_model();
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]) {
244 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;
127 }
252 }
128 let Some(model) = channel.as_mut() else {
253 self.ensure_channel(channel_index);
254 let Some(model) = self.channels[channel_index].as_mut() else {
129 return;
255 return;
130 };
256 };
131 self.input.clear();
257 self.input.clear();
@@ -144,6 +270,7 @@ impl NoiseStage {
144 for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
270 for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
145 *sample = enhanced * PCM_SCALE;
271 *sample = enhanced * PCM_SCALE;
146 }
272 }
273 self.apply_gate(channel_index, samples);
147 }
274 }
148
275
149 pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
276 pub fn process_pcm(&mut self, channel_index: usize, samples: &mut [i16]) {
@@ -164,15 +291,10 @@ impl Default for NoiseStage {
164 }
291 }
165}
292}
166
293
167pub fn apply(settings: MicSettings) {
168 if settings.ml_noise_suppression() {
169 prepare();
170 }
171}
172
173#[cfg(test)]
294#[cfg(test)]
174mod tests {
295mod tests {
175 use super::*;
296 use super::*;
297 use crate::mic_processing::NoiseSuppression;
176 use std::time::{Duration, Instant};
298 use std::time::{Duration, Instant};
177
299
178 fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {
300 fn white_noise(frame_len: usize, amplitude: f32, state: &mut u32) -> Vec<f32> {
@@ -187,7 +309,7 @@ mod tests {
187 }
309 }
188
310
189 fn energy(samples: &[f32]) -> f32 {
311 fn energy(samples: &[f32]) -> f32 {
190 samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32
312 energy_of(samples)
191 }
313 }
192
314
193 fn stage_with_model() -> NoiseStage {
315 fn stage_with_model() -> NoiseStage {
@@ -220,6 +342,7 @@ mod tests {
220 let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();
342 let model = DfTract::new(DfParams::default(), &runtime_params(6.0)).unwrap();
221 let mut stage = NoiseStage {
343 let mut stage = NoiseStage {
222 channels: vec![Some(model)],
344 channels: vec![Some(model)],
345 gate: false,
223 ..NoiseStage::new()
346 ..NoiseStage::new()
224 };
347 };
225 let mut state = 0x1234_5678_u32;
348 let mut state = 0x1234_5678_u32;
@@ -268,4 +391,119 @@ mod tests {
268 eprintln!("deep filter per 10 ms frame: {per_frame:?}");
391 eprintln!("deep filter per 10 ms frame: {per_frame:?}");
269 assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));
392 assert!(per_frame < Duration::from_millis(if cfg!(debug_assertions) { 60 } else { 5 }));
270 }
393 }
394
395 #[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);
402 }
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);
428 }
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 );
436 }
437
438 #[test]
439 fn linux_auto_arms_the_hook_and_other_modes_do_not() {
440 clear();
441 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 let low = MicSettings {
450 noise_suppression: NoiseSuppression::Low,
451 music_mode: false,
452 };
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 {
466 noise_suppression: NoiseSuppression::Auto,
467 music_mode: true,
468 };
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));
475 assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));
476
477 clear();
478 assert!(!hook_armed());
479 }
480
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 }
497
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));
508 }
271}
509}