BlueGit

ict rusty-teams

fix(linux): send Auto mic via Pulse and harden call audio teardown (#13)

Default Auto/Low keep the ADM device track on Linux; software capture no longer falls back to a silent ALSA default, and hangup no longer joins the feeder on the Tokio worker.

metis Joe Mild · pushed by metis

Authored 2026-11-13 · 2 weeks ago

Hash
730dac2e2f38fad210d831555c684aa9085f35ad
Parent
ffaf850e
10 files changed +142 −96
ROADMAP.md +1 −1
@@ -181,7 +181,7 @@ Feature parity with the Microsoft Teams desktop client.
181 181 | 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 |
182 182 | 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 |
183 183 | 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 |
184 | Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto (device track with WebRTC echo cancellation, AGC, NS plus RNNoise ML suppression), Low (same without RNNoise) or Off, Music mode keeps echo cancellation only. No High level. Off and Music mode run a cpal mic through our own APM; checked with synthetic sources only, not with a real mic in a call |
184 | 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 |
185 185 | 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 |
186 186 | 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 |
187 187 | 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 |
@@ -181,7 +181,7 @@ Feature parity with the Microsoft Teams desktop client.
181| 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 |
181| 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 |
182| 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 |
182| 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 |
183| 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 |
183| 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 |
184| Noise suppression, music mode | Partial | Mic menu and Settings > Devices: Auto (device track with WebRTC echo cancellation, AGC, NS plus RNNoise ML suppression), Low (same without RNNoise) or Off, Music mode keeps echo cancellation only. No High level. Off and Music mode run a cpal mic through our own APM; checked with synthetic sources only, not with a real mic in a call |
184| 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 |
185| 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 |
185| 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 |
186| 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 |
186| 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 |
187| 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 |
187| 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/app-base/src/diagnostics.rs +7 −1
@@ -16,7 +16,7 @@ const WEBRTC_AUDIO_MARKERS: [&str; 5] = [
16 16 "WebRtcVoiceEngine",
17 17 "webrtc_voice_engine",
18 18 ];
19 const WEBRTC_SKIPPED: [&str; 1] = ["audio_device_buffer"];
19 const WEBRTC_SKIPPED: [&str; 3] = ["audio_device_buffer", "requesting data", "will write"];
20 20 const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;
21 21
22 22 pub fn install(path: PathBuf) {
@@ -116,6 +116,12 @@ mod tests {
116 116 assert!(!keeps_webrtc_line(
117 117 "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
118 118 ));
119 assert!(!keeps_webrtc_line(
120 "(audio_device_pulse_linux.cc:2236): requesting data"
121 ));
122 assert!(!keeps_webrtc_line(
123 "(audio_device_pulse_linux.cc:2256): will write"
124 ));
119 125 assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));
120 126 }
121 127 }
@@ -16,7 +16,7 @@ const WEBRTC_AUDIO_MARKERS: [&str; 5] = [
16 "WebRtcVoiceEngine",
16 "WebRtcVoiceEngine",
17 "webrtc_voice_engine",
17 "webrtc_voice_engine",
18];
18];
19const WEBRTC_SKIPPED: [&str; 1] = ["audio_device_buffer"];
19const WEBRTC_SKIPPED: [&str; 3] = ["audio_device_buffer", "requesting data", "will write"];
20const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;
20const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;
21
21
22pub fn install(path: PathBuf) {
22pub fn install(path: PathBuf) {
@@ -116,6 +116,12 @@ mod tests {
116 assert!(!keeps_webrtc_line(
116 assert!(!keeps_webrtc_line(
117 "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
117 "(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
118 ));
118 ));
119 assert!(!keeps_webrtc_line(
120 "(audio_device_pulse_linux.cc:2236): requesting data"
121 ));
122 assert!(!keeps_webrtc_line(
123 "(audio_device_pulse_linux.cc:2256): will write"
124 ));
119 assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));
125 assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));
120 }
126 }
121}
127}
crates/calling/examples/audio_probe.rs +1 −1
@@ -172,7 +172,7 @@ mod probe {
172 172 let started = Instant::now();
173 173 let mut next = Instant::now();
174 174 while started.elapsed() < Duration::from_secs(seconds) {
175 let (frame, _) = queue.next_frame();
175 let frame = queue.next_frame().unwrap_or_else(|| vec![0; FRAME_SAMPLES]);
176 176 dump.write(&frame);
177 177 window.extend_from_slice(&frame);
178 178 if window.len() >= frames_per_window * FRAME_SAMPLES {
@@ -172,7 +172,7 @@ mod probe {
172 let started = Instant::now();
172 let started = Instant::now();
173 let mut next = Instant::now();
173 let mut next = Instant::now();
174 while started.elapsed() < Duration::from_secs(seconds) {
174 while started.elapsed() < Duration::from_secs(seconds) {
175 let (frame, _) = queue.next_frame();
175 let frame = queue.next_frame().unwrap_or_else(|| vec![0; FRAME_SAMPLES]);
176 dump.write(&frame);
176 dump.write(&frame);
177 window.extend_from_slice(&frame);
177 window.extend_from_slice(&frame);
178 if window.len() >= frames_per_window * FRAME_SAMPLES {
178 if window.len() >= frames_per_window * FRAME_SAMPLES {
crates/calling/examples/loopback_probe.rs +1 −2
@@ -21,8 +21,7 @@ fn main() {
21 21 let begin = Instant::now();
22 22 while begin.elapsed() < CAPTURE_TIME {
23 23 std::thread::sleep(FRAME_PERIOD);
24 let (frame, had_data) = queue.next_frame();
25 if had_data {
24 if let Some(frame) = queue.next_frame() {
26 25 frames += 1;
27 26 if frame.iter().any(|&sample| sample != 0) {
28 27 loud_frames += 1;
@@ -21,8 +21,7 @@ fn main() {
21 let begin = Instant::now();
21 let begin = Instant::now();
22 while begin.elapsed() < CAPTURE_TIME {
22 while begin.elapsed() < CAPTURE_TIME {
23 std::thread::sleep(FRAME_PERIOD);
23 std::thread::sleep(FRAME_PERIOD);
24 let (frame, had_data) = queue.next_frame();
24 if let Some(frame) = queue.next_frame() {
25 if had_data {
26 frames += 1;
25 frames += 1;
27 if frame.iter().any(|&sample| sample != 0) {
26 if frame.iter().any(|&sample| sample != 0) {
28 loud_frames += 1;
27 loud_frames += 1;
crates/calling/src/call.rs +9 −2
@@ -2554,6 +2554,10 @@ async fn drive(
2554 2554 }
2555 2555 }
2556 2556 }
2557 if software_audio.is_some() {
2558 timeline.record("software audio", "stopping before tear down");
2559 drop(software_audio);
2560 }
2557 2561 live.callbacks = Some(callbacks);
2558 2562 Ok(())
2559 2563 }
@@ -3297,7 +3301,7 @@ fn software_wanted(
3297 3301
3298 3302 fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
3299 3303 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3300 if cfg!(windows) && !factory.adm_recording_enabled() {
3304 if !factory.adm_recording_enabled() {
3301 3305 factory.set_adm_recording_enabled(true);
3302 3306 devices::select_input(factory, input);
3303 3307 }
@@ -3325,6 +3329,9 @@ fn sync_software_audio(
3325 3329 if running == wanted && !restart {
3326 3330 return;
3327 3331 }
3332 if running.is_some() {
3333 timeline.record("software audio", "stopping");
3334 }
3328 3335 *software_audio = None;
3329 3336 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3330 3337 let Some(plan) = wanted else {
@@ -3340,7 +3347,7 @@ fn sync_software_audio(
3340 3347 if let Some(source) = &audio.microphone_source {
3341 3348 timeline.record("mic capture", source.clone());
3342 3349 }
3343 if cfg!(windows) && audio.microphone_source.is_some() {
3350 if audio.microphone_source.is_some() {
3344 3351 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3345 3352 factory.set_adm_recording_enabled(false);
3346 3353 }
@@ -2554,6 +2554,10 @@ async fn drive(
2554 }
2554 }
2555 }
2555 }
2556 }
2556 }
2557 if software_audio.is_some() {
2558 timeline.record("software audio", "stopping before tear down");
2559 drop(software_audio);
2560 }
2557 live.callbacks = Some(callbacks);
2561 live.callbacks = Some(callbacks);
2558 Ok(())
2562 Ok(())
2559}
2563}
@@ -3297,7 +3301,7 @@ fn software_wanted(
3297
3301
3298fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
3302fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
3299 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3303 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3300 if cfg!(windows) && !factory.adm_recording_enabled() {
3304 if !factory.adm_recording_enabled() {
3301 factory.set_adm_recording_enabled(true);
3305 factory.set_adm_recording_enabled(true);
3302 devices::select_input(factory, input);
3306 devices::select_input(factory, input);
3303 }
3307 }
@@ -3325,6 +3329,9 @@ fn sync_software_audio(
3325 if running == wanted && !restart {
3329 if running == wanted && !restart {
3326 return;
3330 return;
3327 }
3331 }
3332 if running.is_some() {
3333 timeline.record("software audio", "stopping");
3334 }
3328 *software_audio = None;
3335 *software_audio = None;
3329 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3336 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3330 let Some(plan) = wanted else {
3337 let Some(plan) = wanted else {
@@ -3340,7 +3347,7 @@ fn sync_software_audio(
3340 if let Some(source) = &audio.microphone_source {
3347 if let Some(source) = &audio.microphone_source {
3341 timeline.record("mic capture", source.clone());
3348 timeline.record("mic capture", source.clone());
3342 }
3349 }
3343 if cfg!(windows) && audio.microphone_source.is_some() {
3350 if audio.microphone_source.is_some() {
3344 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3351 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3345 factory.set_adm_recording_enabled(false);
3352 factory.set_adm_recording_enabled(false);
3346 }
3353 }
crates/calling/src/gain_stage.rs +22 −13
@@ -4,9 +4,12 @@ use webrtc_sys::apm::GainProcessor;
4 4
5 5 use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
6 6
7 const LIFT_DEFAULT_GAIN_DB: f32 = 12.0;
7 /// Start flat; quiet mics climb through adaptive AGC2 instead of blasting a hot PipeWire input.
8 const LIFT_DEFAULT_GAIN_DB: f32 = 0.0;
8 9 const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;
9 10 const OUTPUT_FIXED_GAIN_DB: f32 = 8.0;
11 /// Only restore DeepFilterNet's level drop when the post-filter frame is still quiet.
12 const OUTPUT_APPLY_BELOW_DBFS: f32 = -25.0;
10 13 const SPEECH_FLOOR_DBFS: f32 = -55.0;
11 14 const MIN_SPEECH_FRAMES: u32 = 100;
12 15
@@ -50,7 +53,10 @@ impl GainStage {
50 53 if frame.len() != FRAME_SAMPLES {
51 54 return;
52 55 }
53 let input_dbfs = if self.learns { frame_dbfs(frame) } else { 0.0 };
56 let input_dbfs = frame_dbfs(frame);
57 if !self.learns && input_dbfs > OUTPUT_APPLY_BELOW_DBFS {
58 return;
59 }
54 60 let processed = self.module.process(frame, SAMPLE_RATE as i32);
55 61 if processed && self.learns && input_dbfs > SPEECH_FLOOR_DBFS {
56 62 self.measured_gain_db_sum += frame_dbfs(frame) - input_dbfs;
@@ -84,18 +90,21 @@ mod tests {
84 90 }
85 91
86 92 #[test]
87 fn the_fixed_output_stage_adds_its_gain() {
93 fn the_fixed_output_stage_adds_its_gain_only_to_quiet_frames() {
88 94 let mut stage = GainStage::output();
89 let mut last = Vec::new();
90 for frame_index in 0..100 {
91 let mut frame: Vec<i16> = (0..FRAME_SAMPLES)
92 .map(|sample| (((frame_index * FRAME_SAMPLES + sample) as f32 * 0.04).sin() * 2000.0) as i16)
93 .collect();
94 stage.process(&mut frame);
95 last = frame;
96 }
97 let added = frame_dbfs(&last) - 20.0 * (2000.0_f32 / std::f32::consts::SQRT_2 / 32768.0).log10();
98 assert!((added - OUTPUT_FIXED_GAIN_DB).abs() < 0.5, "added {added:.2} dB");
95 let mut quiet: Vec<i16> = (0..FRAME_SAMPLES)
96 .map(|sample| ((sample as f32 * 0.04).sin() * 200.0) as i16)
97 .collect();
98 let before = frame_dbfs(&quiet);
99 stage.process(&mut quiet);
100 assert!(frame_dbfs(&quiet) - before > 6.0, "quiet speech should be lifted");
101
102 let mut loud: Vec<i16> = (0..FRAME_SAMPLES)
103 .map(|sample| ((sample as f32 * 0.04).sin() * 8000.0) as i16)
104 .collect();
105 let loud_before = loud.clone();
106 stage.process(&mut loud);
107 assert_eq!(loud, loud_before, "already-loud frames stay untouched");
99 108 }
100 109
101 110 #[test]
@@ -4,9 +4,12 @@ use webrtc_sys::apm::GainProcessor;
4
4
5use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
5use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
6
6
7const LIFT_DEFAULT_GAIN_DB: f32 = 12.0;
7/// Start flat; quiet mics climb through adaptive AGC2 instead of blasting a hot PipeWire input.
8const LIFT_DEFAULT_GAIN_DB: f32 = 0.0;
8const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;
9const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;
9const OUTPUT_FIXED_GAIN_DB: f32 = 8.0;
10const OUTPUT_FIXED_GAIN_DB: f32 = 8.0;
11/// Only restore DeepFilterNet's level drop when the post-filter frame is still quiet.
12const OUTPUT_APPLY_BELOW_DBFS: f32 = -25.0;
10const SPEECH_FLOOR_DBFS: f32 = -55.0;
13const SPEECH_FLOOR_DBFS: f32 = -55.0;
11const MIN_SPEECH_FRAMES: u32 = 100;
14const MIN_SPEECH_FRAMES: u32 = 100;
12
15
@@ -50,7 +53,10 @@ impl GainStage {
50 if frame.len() != FRAME_SAMPLES {
53 if frame.len() != FRAME_SAMPLES {
51 return;
54 return;
52 }
55 }
53 let input_dbfs = if self.learns { frame_dbfs(frame) } else { 0.0 };
56 let input_dbfs = frame_dbfs(frame);
57 if !self.learns && input_dbfs > OUTPUT_APPLY_BELOW_DBFS {
58 return;
59 }
54 let processed = self.module.process(frame, SAMPLE_RATE as i32);
60 let processed = self.module.process(frame, SAMPLE_RATE as i32);
55 if processed && self.learns && input_dbfs > SPEECH_FLOOR_DBFS {
61 if processed && self.learns && input_dbfs > SPEECH_FLOOR_DBFS {
56 self.measured_gain_db_sum += frame_dbfs(frame) - input_dbfs;
62 self.measured_gain_db_sum += frame_dbfs(frame) - input_dbfs;
@@ -84,18 +90,21 @@ mod tests {
84 }
90 }
85
91
86 #[test]
92 #[test]
87 fn the_fixed_output_stage_adds_its_gain() {
93 fn the_fixed_output_stage_adds_its_gain_only_to_quiet_frames() {
88 let mut stage = GainStage::output();
94 let mut stage = GainStage::output();
89 let mut last = Vec::new();
95 let mut quiet: Vec<i16> = (0..FRAME_SAMPLES)
90 for frame_index in 0..100 {
96 .map(|sample| ((sample as f32 * 0.04).sin() * 200.0) as i16)
91 let mut frame: Vec<i16> = (0..FRAME_SAMPLES)
97 .collect();
92 .map(|sample| (((frame_index * FRAME_SAMPLES + sample) as f32 * 0.04).sin() * 2000.0) as i16)
98 let before = frame_dbfs(&quiet);
93 .collect();
99 stage.process(&mut quiet);
94 stage.process(&mut frame);
100 assert!(frame_dbfs(&quiet) - before > 6.0, "quiet speech should be lifted");
95 last = frame;
101
96 }
102 let mut loud: Vec<i16> = (0..FRAME_SAMPLES)
97 let added = frame_dbfs(&last) - 20.0 * (2000.0_f32 / std::f32::consts::SQRT_2 / 32768.0).log10();
103 .map(|sample| ((sample as f32 * 0.04).sin() * 8000.0) as i16)
98 assert!((added - OUTPUT_FIXED_GAIN_DB).abs() < 0.5, "added {added:.2} dB");
104 .collect();
105 let loud_before = loud.clone();
106 stage.process(&mut loud);
107 assert_eq!(loud, loud_before, "already-loud frames stay untouched");
99 }
108 }
100
109
101 #[test]
110 #[test]
crates/calling/src/mic_processing.rs +11 −4
@@ -72,8 +72,12 @@ impl MicSettings {
72 72 self.uses_device_track_on(cfg!(windows))
73 73 }
74 74
75 /// On Linux, Auto and Low keep the Pulse ADM device track (same path Web Teams uses).
76 /// Music mode and Off still run the software chain; Windows always does.
75 77 pub fn uses_device_track_on(self, windows: bool) -> bool {
76 !windows && !self.music_mode && self.noise_suppression == NoiseSuppression::Low
78 !windows
79 && !self.music_mode
80 && matches!(self.noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low)
77 81 }
78 82
79 83 pub fn ml_noise_suppression(self) -> bool {
@@ -86,9 +90,10 @@ mod tests {
86 90 use super::*;
87 91
88 92 #[test]
89 fn auto_leaves_noise_to_the_ml_stage_and_keeps_the_rest_of_the_apm() {
93 fn auto_uses_the_device_track_on_linux_and_keeps_ml_for_the_windows_chain() {
90 94 let settings = MicSettings::default();
91 assert!(!settings.uses_device_track_on(false));
95 assert!(settings.uses_device_track_on(false));
96 assert!(!settings.uses_device_track_on(true));
92 97 assert!(settings.ml_noise_suppression());
93 98 assert_eq!(
94 99 settings.apm_config(),
@@ -120,7 +125,9 @@ mod tests {
120 125 for music_mode in [false, true] {
121 126 let settings = MicSettings { noise_suppression, music_mode };
122 127 assert!(!settings.uses_device_track_on(true));
123 assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression == NoiseSuppression::Low);
128 let linux_device = !music_mode
129 && matches!(noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low);
130 assert_eq!(settings.uses_device_track_on(false), linux_device);
124 131 }
125 132 }
126 133 }
@@ -72,8 +72,12 @@ impl MicSettings {
72 self.uses_device_track_on(cfg!(windows))
72 self.uses_device_track_on(cfg!(windows))
73 }
73 }
74
74
75 /// On Linux, Auto and Low keep the Pulse ADM device track (same path Web Teams uses).
76 /// Music mode and Off still run the software chain; Windows always does.
75 pub fn uses_device_track_on(self, windows: bool) -> bool {
77 pub fn uses_device_track_on(self, windows: bool) -> bool {
76 !windows && !self.music_mode && self.noise_suppression == NoiseSuppression::Low
78 !windows
79 && !self.music_mode
80 && matches!(self.noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low)
77 }
81 }
78
82
79 pub fn ml_noise_suppression(self) -> bool {
83 pub fn ml_noise_suppression(self) -> bool {
@@ -86,9 +90,10 @@ mod tests {
86 use super::*;
90 use super::*;
87
91
88 #[test]
92 #[test]
89 fn auto_leaves_noise_to_the_ml_stage_and_keeps_the_rest_of_the_apm() {
93 fn auto_uses_the_device_track_on_linux_and_keeps_ml_for_the_windows_chain() {
90 let settings = MicSettings::default();
94 let settings = MicSettings::default();
91 assert!(!settings.uses_device_track_on(false));
95 assert!(settings.uses_device_track_on(false));
96 assert!(!settings.uses_device_track_on(true));
92 assert!(settings.ml_noise_suppression());
97 assert!(settings.ml_noise_suppression());
93 assert_eq!(
98 assert_eq!(
94 settings.apm_config(),
99 settings.apm_config(),
@@ -120,7 +125,9 @@ mod tests {
120 for music_mode in [false, true] {
125 for music_mode in [false, true] {
121 let settings = MicSettings { noise_suppression, music_mode };
126 let settings = MicSettings { noise_suppression, music_mode };
122 assert!(!settings.uses_device_track_on(true));
127 assert!(!settings.uses_device_track_on(true));
123 assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression == NoiseSuppression::Low);
128 let linux_device = !music_mode
129 && matches!(noise_suppression, NoiseSuppression::Auto | NoiseSuppression::Low);
130 assert_eq!(settings.uses_device_track_on(false), linux_device);
124 }
131 }
125 }
132 }
126 }
133 }
crates/calling/src/pcm.rs +15 −12
@@ -18,12 +18,14 @@ impl SampleQueue {
18 18 queued.drain(..excess);
19 19 }
20 20
21 pub fn next_frame(&self) -> (Vec<i16>, bool) {
21 /// Returns a full 10 ms frame when enough samples are queued. Partial frames stay queued
22 /// so AEC and the encoder never see zero-padded speech.
23 pub fn next_frame(&self) -> Option<Vec<i16>> {
22 24 let mut queued = self.samples.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
23 let available = queued.len().min(FRAME_SAMPLES);
24 let mut frame: Vec<i16> = queued.drain(..available).collect();
25 frame.resize(FRAME_SAMPLES, 0);
26 (frame, available > 0)
25 if queued.len() < FRAME_SAMPLES {
26 return None;
27 }
28 Some(queued.drain(..FRAME_SAMPLES).collect())
27 29 }
28 30 }
29 31
@@ -67,14 +69,15 @@ mod tests {
67 69 use super::*;
68 70
69 71 #[test]
70 fn frames_come_out_in_order_and_pad_with_silence() {
72 fn partial_frames_stay_queued_until_a_full_frame_is_ready() {
71 73 let queue = SampleQueue::default();
72 74 queue.push(&[1, 2, 3]);
73 let (frame, had_data) = queue.next_frame();
74 assert!(had_data);
75 assert!(queue.next_frame().is_none());
76 queue.push(&vec![4; FRAME_SAMPLES - 3]);
77 let frame = queue.next_frame().expect("full frame");
75 78 assert_eq!(frame.len(), FRAME_SAMPLES);
76 assert_eq!(&frame[..4], &[1, 2, 3, 0]);
77 assert!(!queue.next_frame().1);
79 assert_eq!(&frame[..4], &[1, 2, 3, 4]);
80 assert!(queue.next_frame().is_none());
78 81 }
79 82
80 83 #[test]
@@ -82,11 +85,11 @@ mod tests {
82 85 let queue = SampleQueue::default();
83 86 queue.push(&vec![1; MAX_QUEUED_SAMPLES]);
84 87 queue.push(&vec![2; FRAME_SAMPLES]);
85 let (frame, _) = queue.next_frame();
88 let frame = queue.next_frame().expect("full frame");
86 89 assert_eq!(frame[0], 1);
87 90 let mut last = frame;
88 91 for _ in 1..MAX_QUEUED_SAMPLES / FRAME_SAMPLES {
89 last = queue.next_frame().0;
92 last = queue.next_frame().expect("full frame");
90 93 }
91 94 assert_eq!(last[FRAME_SAMPLES - 1], 2);
92 95 }
@@ -18,12 +18,14 @@ impl SampleQueue {
18 queued.drain(..excess);
18 queued.drain(..excess);
19 }
19 }
20
20
21 pub fn next_frame(&self) -> (Vec<i16>, bool) {
21 /// Returns a full 10 ms frame when enough samples are queued. Partial frames stay queued
22 /// so AEC and the encoder never see zero-padded speech.
23 pub fn next_frame(&self) -> Option<Vec<i16>> {
22 let mut queued = self.samples.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
24 let mut queued = self.samples.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
23 let available = queued.len().min(FRAME_SAMPLES);
25 if queued.len() < FRAME_SAMPLES {
24 let mut frame: Vec<i16> = queued.drain(..available).collect();
26 return None;
25 frame.resize(FRAME_SAMPLES, 0);
27 }
26 (frame, available > 0)
28 Some(queued.drain(..FRAME_SAMPLES).collect())
27 }
29 }
28}
30}
29
31
@@ -67,14 +69,15 @@ mod tests {
67 use super::*;
69 use super::*;
68
70
69 #[test]
71 #[test]
70 fn frames_come_out_in_order_and_pad_with_silence() {
72 fn partial_frames_stay_queued_until_a_full_frame_is_ready() {
71 let queue = SampleQueue::default();
73 let queue = SampleQueue::default();
72 queue.push(&[1, 2, 3]);
74 queue.push(&[1, 2, 3]);
73 let (frame, had_data) = queue.next_frame();
75 assert!(queue.next_frame().is_none());
74 assert!(had_data);
76 queue.push(&vec![4; FRAME_SAMPLES - 3]);
77 let frame = queue.next_frame().expect("full frame");
75 assert_eq!(frame.len(), FRAME_SAMPLES);
78 assert_eq!(frame.len(), FRAME_SAMPLES);
76 assert_eq!(&frame[..4], &[1, 2, 3, 0]);
79 assert_eq!(&frame[..4], &[1, 2, 3, 4]);
77 assert!(!queue.next_frame().1);
80 assert!(queue.next_frame().is_none());
78 }
81 }
79
82
80 #[test]
83 #[test]
@@ -82,11 +85,11 @@ mod tests {
82 let queue = SampleQueue::default();
85 let queue = SampleQueue::default();
83 queue.push(&vec![1; MAX_QUEUED_SAMPLES]);
86 queue.push(&vec![1; MAX_QUEUED_SAMPLES]);
84 queue.push(&vec![2; FRAME_SAMPLES]);
87 queue.push(&vec![2; FRAME_SAMPLES]);
85 let (frame, _) = queue.next_frame();
88 let frame = queue.next_frame().expect("full frame");
86 assert_eq!(frame[0], 1);
89 assert_eq!(frame[0], 1);
87 let mut last = frame;
90 let mut last = frame;
88 for _ in 1..MAX_QUEUED_SAMPLES / FRAME_SAMPLES {
91 for _ in 1..MAX_QUEUED_SAMPLES / FRAME_SAMPLES {
89 last = queue.next_frame().0;
92 last = queue.next_frame().expect("full frame");
90 }
93 }
91 assert_eq!(last[FRAME_SAMPLES - 1], 2);
94 assert_eq!(last[FRAME_SAMPLES - 1], 2);
92 }
95 }
crates/calling/src/software_audio.rs +45 −47
@@ -2,7 +2,7 @@ use std::sync::Arc;
2 2 use std::sync::atomic::{AtomicBool, Ordering};
3 3 use std::time::{Duration, Instant};
4 4
5 use futures_util::StreamExt;
5 use futures_util::{FutureExt, StreamExt};
6 6 use libwebrtc::audio_source::native::NativeAudioSource;
7 7 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
8 8 use libwebrtc::audio_stream::native::NativeAudioStream;
@@ -10,7 +10,6 @@ use libwebrtc::prelude::*;
10 10 use tokio::task::JoinHandle;
11 11
12 12 use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
13 use crate::band_meter::HighBandMeter;
14 13 use crate::audio_io::AudioMode;
15 14 use crate::capture::Capture;
16 15 use crate::devices::DeviceChoice;
@@ -22,10 +21,10 @@ use crate::pcm::SampleQueue;
22 21 use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
23 22 use crate::wav_dump::StageDumps;
24 23
25 const SOURCE_QUEUE_MS: u32 = 100;
24 /// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime.
25 const SOURCE_QUEUE_MS: u32 = 0;
26 26 const FRAME_PERIOD: Duration = Duration::from_millis(10);
27 27 const MAX_LAG: Duration = Duration::from_millis(100);
28 const BAND_REPORT_PERIOD: Duration = Duration::from_secs(10);
29 28 const SYSTEM_TONE_HZ: f32 = 660.0;
30 29 const SYNTHETIC_AMPLITUDE: f32 = 0.3;
31 30
@@ -36,11 +35,11 @@ enum FrameSource {
36 35 }
37 36
38 37 impl FrameSource {
39 fn next_frame(&mut self) -> Vec<i16> {
38 fn next_frame(&mut self) -> Option<Vec<i16>> {
40 39 match self {
41 FrameSource::Captured(queue) => queue.next_frame().0,
42 FrameSource::Tone(generator) => generator.next_frame(),
43 FrameSource::Silence => vec![0; FRAME_SAMPLES],
40 FrameSource::Captured(queue) => queue.next_frame(),
41 FrameSource::Tone(generator) => Some(generator.next_frame()),
42 FrameSource::Silence => Some(vec![0; FRAME_SAMPLES]),
44 43 }
45 44 }
46 45 }
@@ -61,48 +60,44 @@ struct Feeder {
61 60 far_end: SampleQueue,
62 61 microphone_muted: Arc<AtomicBool>,
63 62 running: Arc<AtomicBool>,
64 runtime: tokio::runtime::Handle,
65 63 }
66 64
67 65 impl Feeder {
68 66 fn run(mut self) {
69 67 let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());
70 68 let mut due = Instant::now();
71 let mut last_capture = Duration::ZERO;
72 69 while self.running.load(Ordering::SeqCst) {
73 70 due += FRAME_PERIOD;
74 71 let now = Instant::now();
75 72 if due > now {
76 73 std::thread::sleep(due - now);
77 74 } else if now - due > MAX_LAG {
78 eprintln!(
79 "calls: audio feeder fell {} ms behind, last capture_frame took {} ms; echo canceller re-aligns",
80 (now - due).as_millis(),
81 last_capture.as_millis()
82 );
83 75 due = now;
84 76 }
85 let (mut far_end, has_far_end) = self.far_end.next_frame();
86 if has_far_end {
77 if let Some(mut far_end) = self.far_end.next_frame() {
87 78 chain.process_far_end(&mut far_end);
88 79 }
89 80 let muted = self.microphone_muted.load(Ordering::SeqCst);
90 let mut microphone = self.microphone.next_frame();
91 if !muted {
92 chain.process(&mut microphone);
93 }
94 let computer = self.computer.next_frame();
81 let microphone = match self.microphone.next_frame() {
82 Some(mut frame) if !muted => {
83 chain.process(&mut frame);
84 frame
85 }
86 Some(frame) => frame,
87 // Underrun: send silence without feeding AEC/gain a zero-padded partial.
88 None => vec![0; FRAME_SAMPLES],
89 };
90 let computer = self.computer.next_frame().unwrap_or_else(|| vec![0; FRAME_SAMPLES]);
95 91 let frame = AudioFrame {
96 92 data: mix_frames(&microphone, &computer, muted).into(),
97 93 sample_rate: SAMPLE_RATE,
98 94 num_channels: 1,
99 95 samples_per_channel: FRAME_SAMPLES as u32,
100 96 };
101 let capture_started = Instant::now();
102 if self.runtime.block_on(self.source.capture_frame(&frame)).is_err() {
103 break;
97 match self.source.capture_frame(&frame).now_or_never() {
98 Some(Ok(())) => {}
99 Some(Err(_)) | None => break,
104 100 }
105 last_capture = capture_started.elapsed();
106 101 }
107 102 }
108 103 }
@@ -190,9 +185,9 @@ impl SoftwareAudio {
190 185 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
191 186 let track = factory.create_audio_track("microphone", source.clone());
192 187 let far_end = SampleQueue::default();
193 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone())));
194 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
195 188 let running = Arc::new(AtomicBool::new(true));
189 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone(), running.clone())));
190 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
196 191 let feeder = Feeder {
197 192 processing: plan.processing,
198 193 ml_noise: plan.ml_noise,
@@ -202,7 +197,6 @@ impl SoftwareAudio {
202 197 far_end,
203 198 microphone_muted: microphone_muted.clone(),
204 199 running: running.clone(),
205 runtime: tokio::runtime::Handle::current(),
206 200 };
207 201 let thread = std::thread::Builder::new()
208 202 .name("share-audio".into())
@@ -229,30 +223,34 @@ impl SoftwareAudio {
229 223
230 224 impl Drop for SoftwareAudio {
231 225 fn drop(&mut self) {
226 // Signal stop so the far-end task closes its WebRTC sink on its own thread, then detach both
227 // workers. Joining the feeder on a Tokio worker used to hang when capture_frame waited on a
228 // drained queue; aborting the far-end mid-OnData raced with remove_sink.
232 229 self.running.store(false, Ordering::SeqCst);
233 if let Some(task) = self.far_end_task.take() {
234 task.abort();
235 }
236 if let Some(thread) = self.feeder.take() {
237 let _ = thread.join();
238 }
230 drop(self.far_end_task.take());
231 drop(self.feeder.take());
239 232 }
240 233 }
241 234
242 async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue) {
235 async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue, running: Arc<AtomicBool>) {
243 236 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
244 let mut band_meter = HighBandMeter::default();
245 let mut next_report = Instant::now() + BAND_REPORT_PERIOD;
246 while let Some(frame) = stream.next().await {
247 queue.push(&frame.data);
248 band_meter.add(&frame.data);
249 if Instant::now() >= next_report {
250 next_report += BAND_REPORT_PERIOD;
251 if let Some(share) = band_meter.take_share() {
252 eprintln!("calls: far-end audio energy above 8 kHz: {:.2}%", share * 100.);
237 while running.load(Ordering::SeqCst) {
238 tokio::select! {
239 biased;
240 _ = wait_stopped(&running) => break,
241 frame = stream.next() => match frame {
242 Some(frame) => queue.push(&frame.data),
243 None => break,
253 244 }
254 245 }
255 246 }
247 stream.close();
248 }
249
250 async fn wait_stopped(running: &AtomicBool) {
251 while running.load(Ordering::SeqCst) {
252 tokio::time::sleep(Duration::from_millis(10)).await;
253 }
256 254 }
257 255
258 256 #[cfg(test)]
@@ -273,10 +271,10 @@ mod tests {
273 271 }
274 272
275 273 #[test]
276 fn default_settings_run_the_software_chain_on_both_platforms() {
274 fn default_settings_use_the_device_track_on_linux() {
277 275 let default = MicSettings::default();
278 276 assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
279 assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_some());
277 assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());
280 278 let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
281 279 assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
282 280 }
@@ -2,7 +2,7 @@ use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::time::{Duration, Instant};
3use std::time::{Duration, Instant};
4
4
5use futures_util::StreamExt;
5use futures_util::{FutureExt, StreamExt};
6use libwebrtc::audio_source::native::NativeAudioSource;
6use libwebrtc::audio_source::native::NativeAudioSource;
7use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
7use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
8use libwebrtc::audio_stream::native::NativeAudioStream;
8use libwebrtc::audio_stream::native::NativeAudioStream;
@@ -10,7 +10,6 @@ use libwebrtc::prelude::*;
10use tokio::task::JoinHandle;
10use tokio::task::JoinHandle;
11
11
12use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
12use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
13use crate::band_meter::HighBandMeter;
14use crate::audio_io::AudioMode;
13use crate::audio_io::AudioMode;
15use crate::capture::Capture;
14use crate::capture::Capture;
16use crate::devices::DeviceChoice;
15use crate::devices::DeviceChoice;
@@ -22,10 +21,10 @@ use crate::pcm::SampleQueue;
22use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
21use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
23use crate::wav_dump::StageDumps;
22use crate::wav_dump::StageDumps;
24
23
25const SOURCE_QUEUE_MS: u32 = 100;
24/// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime.
25const SOURCE_QUEUE_MS: u32 = 0;
26const FRAME_PERIOD: Duration = Duration::from_millis(10);
26const FRAME_PERIOD: Duration = Duration::from_millis(10);
27const MAX_LAG: Duration = Duration::from_millis(100);
27const MAX_LAG: Duration = Duration::from_millis(100);
28const BAND_REPORT_PERIOD: Duration = Duration::from_secs(10);
29const SYSTEM_TONE_HZ: f32 = 660.0;
28const SYSTEM_TONE_HZ: f32 = 660.0;
30const SYNTHETIC_AMPLITUDE: f32 = 0.3;
29const SYNTHETIC_AMPLITUDE: f32 = 0.3;
31
30
@@ -36,11 +35,11 @@ enum FrameSource {
36}
35}
37
36
38impl FrameSource {
37impl FrameSource {
39 fn next_frame(&mut self) -> Vec<i16> {
38 fn next_frame(&mut self) -> Option<Vec<i16>> {
40 match self {
39 match self {
41 FrameSource::Captured(queue) => queue.next_frame().0,
40 FrameSource::Captured(queue) => queue.next_frame(),
42 FrameSource::Tone(generator) => generator.next_frame(),
41 FrameSource::Tone(generator) => Some(generator.next_frame()),
43 FrameSource::Silence => vec![0; FRAME_SAMPLES],
42 FrameSource::Silence => Some(vec![0; FRAME_SAMPLES]),
44 }
43 }
45 }
44 }
46}
45}
@@ -61,48 +60,44 @@ struct Feeder {
61 far_end: SampleQueue,
60 far_end: SampleQueue,
62 microphone_muted: Arc<AtomicBool>,
61 microphone_muted: Arc<AtomicBool>,
63 running: Arc<AtomicBool>,
62 running: Arc<AtomicBool>,
64 runtime: tokio::runtime::Handle,
65}
63}
66
64
67impl Feeder {
65impl Feeder {
68 fn run(mut self) {
66 fn run(mut self) {
69 let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());
67 let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());
70 let mut due = Instant::now();
68 let mut due = Instant::now();
71 let mut last_capture = Duration::ZERO;
72 while self.running.load(Ordering::SeqCst) {
69 while self.running.load(Ordering::SeqCst) {
73 due += FRAME_PERIOD;
70 due += FRAME_PERIOD;
74 let now = Instant::now();
71 let now = Instant::now();
75 if due > now {
72 if due > now {
76 std::thread::sleep(due - now);
73 std::thread::sleep(due - now);
77 } else if now - due > MAX_LAG {
74 } else if now - due > MAX_LAG {
78 eprintln!(
79 "calls: audio feeder fell {} ms behind, last capture_frame took {} ms; echo canceller re-aligns",
80 (now - due).as_millis(),
81 last_capture.as_millis()
82 );
83 due = now;
75 due = now;
84 }
76 }
85 let (mut far_end, has_far_end) = self.far_end.next_frame();
77 if let Some(mut far_end) = self.far_end.next_frame() {
86 if has_far_end {
87 chain.process_far_end(&mut far_end);
78 chain.process_far_end(&mut far_end);
88 }
79 }
89 let muted = self.microphone_muted.load(Ordering::SeqCst);
80 let muted = self.microphone_muted.load(Ordering::SeqCst);
90 let mut microphone = self.microphone.next_frame();
81 let microphone = match self.microphone.next_frame() {
91 if !muted {
82 Some(mut frame) if !muted => {
92 chain.process(&mut microphone);
83 chain.process(&mut frame);
93 }
84 frame
94 let computer = self.computer.next_frame();
85 }
86 Some(frame) => frame,
87 // Underrun: send silence without feeding AEC/gain a zero-padded partial.
88 None => vec![0; FRAME_SAMPLES],
89 };
90 let computer = self.computer.next_frame().unwrap_or_else(|| vec![0; FRAME_SAMPLES]);
95 let frame = AudioFrame {
91 let frame = AudioFrame {
96 data: mix_frames(&microphone, &computer, muted).into(),
92 data: mix_frames(&microphone, &computer, muted).into(),
97 sample_rate: SAMPLE_RATE,
93 sample_rate: SAMPLE_RATE,
98 num_channels: 1,
94 num_channels: 1,
99 samples_per_channel: FRAME_SAMPLES as u32,
95 samples_per_channel: FRAME_SAMPLES as u32,
100 };
96 };
101 let capture_started = Instant::now();
97 match self.source.capture_frame(&frame).now_or_never() {
102 if self.runtime.block_on(self.source.capture_frame(&frame)).is_err() {
98 Some(Ok(())) => {}
103 break;
99 Some(Err(_)) | None => break,
104 }
100 }
105 last_capture = capture_started.elapsed();
106 }
101 }
107 }
102 }
108}
103}
@@ -190,9 +185,9 @@ impl SoftwareAudio {
190 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
185 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, SOURCE_QUEUE_MS);
191 let track = factory.create_audio_track("microphone", source.clone());
186 let track = factory.create_audio_track("microphone", source.clone());
192 let far_end = SampleQueue::default();
187 let far_end = SampleQueue::default();
193 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone())));
194 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
195 let running = Arc::new(AtomicBool::new(true));
188 let running = Arc::new(AtomicBool::new(true));
189 let far_end_task = remote.map(|remote| tokio::spawn(feed_far_end(remote, far_end.clone(), running.clone())));
190 let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
196 let feeder = Feeder {
191 let feeder = Feeder {
197 processing: plan.processing,
192 processing: plan.processing,
198 ml_noise: plan.ml_noise,
193 ml_noise: plan.ml_noise,
@@ -202,7 +197,6 @@ impl SoftwareAudio {
202 far_end,
197 far_end,
203 microphone_muted: microphone_muted.clone(),
198 microphone_muted: microphone_muted.clone(),
204 running: running.clone(),
199 running: running.clone(),
205 runtime: tokio::runtime::Handle::current(),
206 };
200 };
207 let thread = std::thread::Builder::new()
201 let thread = std::thread::Builder::new()
208 .name("share-audio".into())
202 .name("share-audio".into())
@@ -229,30 +223,34 @@ impl SoftwareAudio {
229
223
230impl Drop for SoftwareAudio {
224impl Drop for SoftwareAudio {
231 fn drop(&mut self) {
225 fn drop(&mut self) {
226 // Signal stop so the far-end task closes its WebRTC sink on its own thread, then detach both
227 // workers. Joining the feeder on a Tokio worker used to hang when capture_frame waited on a
228 // drained queue; aborting the far-end mid-OnData raced with remove_sink.
232 self.running.store(false, Ordering::SeqCst);
229 self.running.store(false, Ordering::SeqCst);
233 if let Some(task) = self.far_end_task.take() {
230 drop(self.far_end_task.take());
234 task.abort();
231 drop(self.feeder.take());
235 }
236 if let Some(thread) = self.feeder.take() {
237 let _ = thread.join();
238 }
239 }
232 }
240}
233}
241
234
242async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue) {
235async fn feed_far_end(remote: RtcAudioTrack, queue: SampleQueue, running: Arc<AtomicBool>) {
243 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
236 let mut stream = NativeAudioStream::new(remote, SAMPLE_RATE as i32, 1);
244 let mut band_meter = HighBandMeter::default();
237 while running.load(Ordering::SeqCst) {
245 let mut next_report = Instant::now() + BAND_REPORT_PERIOD;
238 tokio::select! {
246 while let Some(frame) = stream.next().await {
239 biased;
247 queue.push(&frame.data);
240 _ = wait_stopped(&running) => break,
248 band_meter.add(&frame.data);
241 frame = stream.next() => match frame {
249 if Instant::now() >= next_report {
242 Some(frame) => queue.push(&frame.data),
250 next_report += BAND_REPORT_PERIOD;
243 None => break,
251 if let Some(share) = band_meter.take_share() {
252 eprintln!("calls: far-end audio energy above 8 kHz: {:.2}%", share * 100.);
253 }
244 }
254 }
245 }
255 }
246 }
247 stream.close();
248}
249
250async fn wait_stopped(running: &AtomicBool) {
251 while running.load(Ordering::SeqCst) {
252 tokio::time::sleep(Duration::from_millis(10)).await;
253 }
256}
254}
257
255
258#[cfg(test)]
256#[cfg(test)]
@@ -273,10 +271,10 @@ mod tests {
273 }
271 }
274
272
275 #[test]
273 #[test]
276 fn default_settings_run_the_software_chain_on_both_platforms() {
274 fn default_settings_use_the_device_track_on_linux() {
277 let default = MicSettings::default();
275 let default = MicSettings::default();
278 assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
276 assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
279 assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_some());
277 assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());
280 let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
278 let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
281 assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
279 assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
282 }
280 }
crates/calling/src/sound_capture.rs +30 −13
@@ -34,10 +34,14 @@ fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
34 34
35 35 fn named_input(choice: &DeviceChoice) -> Option<Device> {
36 36 let DeviceChoice::Device(wanted) = choice else { return None };
37 cpal::default_host()
38 .input_devices()
39 .ok()?
40 .find(|device| device.description().is_ok_and(|description| description.name() == wanted))
37 let host = cpal::default_host();
38 let mut devices = host.input_devices().ok()?;
39 devices.find(|device| {
40 device.description().is_ok_and(|description| {
41 let name = description.name();
42 name == *wanted || name.contains(wanted) || wanted.contains(&name)
43 })
44 })
41 45 }
42 46
43 47 pub struct MicrophoneStart {
@@ -56,24 +60,37 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic
56 60 })
57 61 }
58 62 Err(error) => {
59 let capture = start_cpal_microphone(choice, queue)?;
60 Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })
63 let (capture, name) = start_cpal_microphone(choice, queue)?;
64 Ok(MicrophoneStart {
65 capture,
66 source: format!("cpal ({name}), wasapi communications failed: {error}"),
67 })
61 68 }
62 69 }
63 70 }
64 71
65 72 #[cfg(not(windows))]
66 73 pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
67 let capture = start_cpal_microphone(choice, queue)?;
68 Ok(MicrophoneStart { capture, source: "cpal".into() })
74 let (capture, name) = start_cpal_microphone(choice, queue)?;
75 Ok(MicrophoneStart { capture, source: format!("cpal ({name})") })
69 76 }
70 77
71 fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
72 let device = named_input(choice)
73 .or_else(|| cpal::default_host().default_input_device())
74 .ok_or_else(|| Error::Audio("no microphone".into()))?;
78 fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {
79 let device = match choice {
80 DeviceChoice::SystemDefault => cpal::default_host()
81 .default_input_device()
82 .ok_or_else(|| Error::Audio("no microphone".into()))?,
83 DeviceChoice::Device(wanted) => named_input(choice).ok_or_else(|| {
84 Error::Audio(format!("microphone `{wanted}` not found for capture; pick Default device or another mic"))
85 })?,
86 };
87 let name = device
88 .description()
89 .map(|description| description.name().to_owned())
90 .unwrap_or_else(|_| "unknown".into());
75 91 let config = device.default_input_config().map_err(|error| audio_error("microphone format", error))?;
76 start_cpal_input(device, config.sample_format(), config.config(), queue)
92 let capture = start_cpal_input(device, config.sample_format(), config.config(), queue)?;
93 Ok((capture, name))
77 94 }
78 95
79 96 #[cfg(windows)]
@@ -34,10 +34,14 @@ fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
34
34
35fn named_input(choice: &DeviceChoice) -> Option<Device> {
35fn named_input(choice: &DeviceChoice) -> Option<Device> {
36 let DeviceChoice::Device(wanted) = choice else { return None };
36 let DeviceChoice::Device(wanted) = choice else { return None };
37 cpal::default_host()
37 let host = cpal::default_host();
38 .input_devices()
38 let mut devices = host.input_devices().ok()?;
39 .ok()?
39 devices.find(|device| {
40 .find(|device| device.description().is_ok_and(|description| description.name() == wanted))
40 device.description().is_ok_and(|description| {
41 let name = description.name();
42 name == *wanted || name.contains(wanted) || wanted.contains(&name)
43 })
44 })
41}
45}
42
46
43pub struct MicrophoneStart {
47pub struct MicrophoneStart {
@@ -56,24 +60,37 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic
56 })
60 })
57 }
61 }
58 Err(error) => {
62 Err(error) => {
59 let capture = start_cpal_microphone(choice, queue)?;
63 let (capture, name) = start_cpal_microphone(choice, queue)?;
60 Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })
64 Ok(MicrophoneStart {
65 capture,
66 source: format!("cpal ({name}), wasapi communications failed: {error}"),
67 })
61 }
68 }
62 }
69 }
63}
70}
64
71
65#[cfg(not(windows))]
72#[cfg(not(windows))]
66pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
73pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
67 let capture = start_cpal_microphone(choice, queue)?;
74 let (capture, name) = start_cpal_microphone(choice, queue)?;
68 Ok(MicrophoneStart { capture, source: "cpal".into() })
75 Ok(MicrophoneStart { capture, source: format!("cpal ({name})") })
69}
76}
70
77
71fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
78fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {
72 let device = named_input(choice)
79 let device = match choice {
73 .or_else(|| cpal::default_host().default_input_device())
80 DeviceChoice::SystemDefault => cpal::default_host()
74 .ok_or_else(|| Error::Audio("no microphone".into()))?;
81 .default_input_device()
82 .ok_or_else(|| Error::Audio("no microphone".into()))?,
83 DeviceChoice::Device(wanted) => named_input(choice).ok_or_else(|| {
84 Error::Audio(format!("microphone `{wanted}` not found for capture; pick Default device or another mic"))
85 })?,
86 };
87 let name = device
88 .description()
89 .map(|description| description.name().to_owned())
90 .unwrap_or_else(|_| "unknown".into());
75 let config = device.default_input_config().map_err(|error| audio_error("microphone format", error))?;
91 let config = device.default_input_config().map_err(|error| audio_error("microphone format", error))?;
76 start_cpal_input(device, config.sample_format(), config.config(), queue)
92 let capture = start_cpal_input(device, config.sample_format(), config.config(), queue)?;
93 Ok((capture, name))
77}
94}
78
95
79#[cfg(windows)]
96#[cfg(windows)]