feat(calling): Windows mic effects match our chain, voice high-pass, Linux Auto on the same chain
- Windows: our stream turns off OS noise suppression, Voice Clarity deep noise suppression, AGC and compression, turns beamforming on; keeps the OS echo canceller and skips AEC3 then - 4th-order 120 Hz voice high-pass replaces WebRTC's 80 Hz one - Linux Auto uses the software chain like Windows; Low keeps the device track - mic_effects_probe example lists the Windows effects on the default mic; echo_call takes --seconds Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -58,7 +58,12 @@ async fn main() {
58
58
}
59
59
60
60
async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode, wav_path: Option<PathBuf>, hold: bool) {
61
let connected_for = if hold { HOLD_START + HOLD_LENGTH + AFTER_RESUME } else { HOLD_AFTER_CONNECTED };
61
let seconds = std::env::args().skip_while(|argument| argument != "--seconds").nth(1).and_then(|value| value.parse().ok());
62
let connected_for = match (hold, seconds) {
63
(true, _) => HOLD_START + HOLD_LENGTH + AFTER_RESUME,
64
(false, Some(seconds)) => Duration::from_secs(seconds),
65
(false, None) => HOLD_AFTER_CONNECTED,
66
};
62
67
let options = CallOptions {
63
68
audio,
64
69
hold_after_connected: Some(connected_for),
@@ -58,7 +58,12 @@ async fn main() {58
}58
}59
59
60
async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode, wav_path: Option<PathBuf>, hold: bool) {60
async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode, wav_path: Option<PathBuf>, hold: bool) {61
let connected_for = if hold { HOLD_START + HOLD_LENGTH + AFTER_RESUME } else { HOLD_AFTER_CONNECTED };61
let seconds = std::env::args().skip_while(|argument| argument != "--seconds").nth(1).and_then(|value| value.parse().ok());62
let connected_for = match (hold, seconds) {63
(true, _) => HOLD_START + HOLD_LENGTH + AFTER_RESUME,64
(false, Some(seconds)) => Duration::from_secs(seconds),65
(false, None) => HOLD_AFTER_CONNECTED,66
};62
let options = CallOptions {67
let options = CallOptions {63
audio,68
audio,64
hold_after_connected: Some(connected_for),69
hold_after_connected: Some(connected_for),@@ -0,0 +1,16 @@
1
//! Lists the Windows effects (AEC, noise suppression, AGC, beamforming...) on the default communications microphone.
2
3
fn main() {
4
#[cfg(windows)]
5
match calling::probe_effects(&calling::devices::DeviceChoice::SystemDefault) {
6
Ok((device, effects)) => {
7
println!("microphone: {device}");
8
for effect in effects {
9
println!(" {:<28} on={} can_set={}", effect.name(), effect.enabled, effect.can_set);
10
}
11
}
12
Err(error) => println!("probe failed: {error}"),
13
}
14
#[cfg(not(windows))]
15
println!("Windows only");
16
}
@@ -0,0 +1,16 @@1
//! Lists the Windows effects (AEC, noise suppression, AGC, beamforming...) on the default communications microphone.2
3
fn main() {4
#[cfg(windows)]5
match calling::probe_effects(&calling::devices::DeviceChoice::SystemDefault) {6
Ok((device, effects)) => {7
println!("microphone: {device}");8
for effect in effects {9
println!(" {:<28} on={} can_set={}", effect.name(), effect.enabled, effect.can_set);10
}11
}12
Err(error) => println!("probe failed: {error}"),13
}14
#[cfg(not(windows))]15
println!("Windows only");16
}@@ -28,12 +28,16 @@ pub mod matte;
28
28
mod loopback_windows;
29
29
#[cfg(windows)]
30
30
mod mic_windows;
31
#[cfg(windows)]
32
pub use mic_windows::probe_effects;
31
33
pub mod meeting;
32
34
pub mod meeting_options;
33
35
pub mod mic_processing;
34
36
pub mod mixer;
35
37
pub mod mic_chain;
38
pub mod mic_effects;
36
39
pub mod noise_stage;
40
pub mod voice_high_pass;
37
41
pub mod wav_dump;
38
42
pub mod mute;
39
43
pub mod organizer;
@@ -28,12 +28,16 @@ pub mod matte;28
mod loopback_windows;28
mod loopback_windows;29
#[cfg(windows)]29
#[cfg(windows)]30
mod mic_windows;30
mod mic_windows;31
#[cfg(windows)]32
pub use mic_windows::probe_effects;31
pub mod meeting;33
pub mod meeting;32
pub mod meeting_options;34
pub mod meeting_options;33
pub mod mic_processing;35
pub mod mic_processing;34
pub mod mixer;36
pub mod mixer;35
pub mod mic_chain;37
pub mod mic_chain;38
pub mod mic_effects;36
pub mod noise_stage;39
pub mod noise_stage;40
pub mod voice_high_pass;37
pub mod wav_dump;41
pub mod wav_dump;38
pub mod mute;42
pub mod mute;39
pub mod organizer;43
pub mod organizer;@@ -3,10 +3,12 @@ use libwebrtc::native::apm::AudioProcessingModule;
3
3
use crate::audio::SAMPLE_RATE;
4
4
use crate::mic_processing::ApmConfig;
5
5
use crate::noise_stage::NoiseStage;
6
use crate::voice_high_pass::VoiceHighPass;
6
7
use crate::wav_dump::StageDumps;
7
8
8
/// High-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.
9
/// Voice high-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.
9
10
pub struct MicChain {
11
high_pass: Option<VoiceHighPass>,
10
12
front: Option<AudioProcessingModule>,
11
13
ml_noise: Option<NoiseStage>,
12
14
gain: Option<AudioProcessingModule>,
@@ -19,6 +21,7 @@ impl MicChain {
19
21
crate::noise_stage::prepare();
20
22
}
21
23
MicChain {
24
high_pass: processing.high_pass_filter.then(VoiceHighPass::new),
22
25
front: processing.front_module(),
23
26
ml_noise: ml_noise.then(NoiseStage::new),
24
27
gain: processing.gain_module(),
@@ -34,6 +37,9 @@ impl MicChain {
34
37
35
38
pub fn process(&mut self, frame: &mut [i16]) {
36
39
self.dump(0, frame);
40
if let Some(high_pass) = self.high_pass.as_mut() {
41
high_pass.process(frame);
42
}
37
43
if let Some(front) = self.front.as_mut() {
38
44
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);
39
45
}
@@ -3,10 +3,12 @@ use libwebrtc::native::apm::AudioProcessingModule;3
use crate::audio::SAMPLE_RATE;3
use crate::audio::SAMPLE_RATE;4
use crate::mic_processing::ApmConfig;4
use crate::mic_processing::ApmConfig;5
use crate::noise_stage::NoiseStage;5
use crate::noise_stage::NoiseStage;6
use crate::voice_high_pass::VoiceHighPass;6
use crate::wav_dump::StageDumps;7
use crate::wav_dump::StageDumps;7
8
8
/// High-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.9
/// Voice high-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.9
pub struct MicChain {10
pub struct MicChain {11
high_pass: Option<VoiceHighPass>,10
front: Option<AudioProcessingModule>,12
front: Option<AudioProcessingModule>,11
ml_noise: Option<NoiseStage>,13
ml_noise: Option<NoiseStage>,12
gain: Option<AudioProcessingModule>,14
gain: Option<AudioProcessingModule>,@@ -19,6 +21,7 @@ impl MicChain {19
crate::noise_stage::prepare();21
crate::noise_stage::prepare();20
}22
}21
MicChain {23
MicChain {24
high_pass: processing.high_pass_filter.then(VoiceHighPass::new),22
front: processing.front_module(),25
front: processing.front_module(),23
ml_noise: ml_noise.then(NoiseStage::new),26
ml_noise: ml_noise.then(NoiseStage::new),24
gain: processing.gain_module(),27
gain: processing.gain_module(),@@ -34,6 +37,9 @@ impl MicChain {34
37
35
pub fn process(&mut self, frame: &mut [i16]) {38
pub fn process(&mut self, frame: &mut [i16]) {36
self.dump(0, frame);39
self.dump(0, frame);40
if let Some(high_pass) = self.high_pass.as_mut() {41
high_pass.process(frame);42
}37
if let Some(front) = self.front.as_mut() {43
if let Some(front) = self.front.as_mut() {38
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);44
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);39
}45
}@@ -0,0 +1,101 @@
1
#[derive(Debug, Clone, PartialEq, Eq)]
2
pub struct MicEffect {
3
pub id: u128,
4
pub enabled: bool,
5
pub can_set: bool,
6
}
7
8
impl MicEffect {
9
pub fn name(&self) -> String {
10
effect_name(self.id)
11
}
12
13
pub fn is_echo_cancellation(&self) -> bool {
14
known_prefix(self.id) == Some(ECHO_CANCELLATION)
15
}
16
17
/// The state to switch to, when it differs from the current one and Windows lets us change it.
18
pub fn change(&self) -> Option<bool> {
19
wanted_state(self.id).filter(|wanted| self.can_set && *wanted != self.enabled)
20
}
21
}
22
23
const EFFECT_SUFFIX: u128 = 0x8211_11e2_8c70_2c27d7f001fa;
24
const EFFECT_NAMES: [(u32, &str); 19] = [
25
(0x6f64adbe, "acoustic echo cancellation"),
26
(0x6f64adbf, "noise suppression"),
27
(0x6f64adc0, "automatic gain control"),
28
(0x6f64adc1, "beamforming"),
29
(0x6f64adc2, "constant tone removal"),
30
(0x6f64adc3, "equalizer"),
31
(0x6f64adc4, "loudness equalizer"),
32
(0x6f64adc5, "bass boost"),
33
(0x6f64adc6, "virtual surround"),
34
(0x6f64adc7, "virtual headphones"),
35
(0x6f64adc8, "speaker fill"),
36
(0x6f64adc9, "room correction"),
37
(0x6f64adca, "bass management"),
38
(0x6f64adcb, "environmental effects"),
39
(0x6f64adcc, "speaker protection"),
40
(0x6f64adcd, "speaker compensation"),
41
(0x6f64adce, "dynamic range compression"),
42
(0x6f64adcf, "far field beamforming"),
43
(0x6f64add0, "deep noise suppression"),
44
];
45
46
const ECHO_CANCELLATION: u32 = 0x6f64adbe;
47
const NOISE_SUPPRESSION: u32 = 0x6f64adbf;
48
const GAIN_CONTROL: u32 = 0x6f64adc0;
49
const BEAMFORMING: u32 = 0x6f64adc1;
50
const RANGE_COMPRESSION: u32 = 0x6f64adce;
51
const DEEP_NOISE_SUPPRESSION: u32 = 0x6f64add0;
52
53
fn known_prefix(guid: u128) -> Option<u32> {
54
(guid & ((1u128 << 96) - 1) == EFFECT_SUFFIX).then_some((guid >> 96) as u32)
55
}
56
57
/// DeepFilterNet and AGC2 replace the Windows noise, gain and compression stages, stacking them muffles speech.
58
/// The Windows echo canceller stays: it has the exact speaker signal, ours only a copy of the decoded stream.
59
pub fn wanted_state(guid: u128) -> Option<bool> {
60
match known_prefix(guid)? {
61
NOISE_SUPPRESSION | DEEP_NOISE_SUPPRESSION | GAIN_CONTROL | RANGE_COMPRESSION => Some(false),
62
BEAMFORMING => Some(true),
63
_ => None,
64
}
65
}
66
67
pub fn effect_name(guid: u128) -> String {
68
known_prefix(guid)
69
.and_then(|prefix| EFFECT_NAMES.iter().find(|(known, _)| *known == prefix))
70
.map_or_else(|| format!("{guid:032x}"), |(_, name)| (*name).to_owned())
71
}
72
73
#[cfg(test)]
74
mod tests {
75
use super::*;
76
77
#[test]
78
fn our_chain_replaces_windows_noise_gain_and_compression_but_keeps_its_echo_canceller() {
79
let guid = |prefix: u32| (u128::from(prefix) << 96) | EFFECT_SUFFIX;
80
assert_eq!(wanted_state(guid(NOISE_SUPPRESSION)), Some(false));
81
assert_eq!(wanted_state(guid(DEEP_NOISE_SUPPRESSION)), Some(false));
82
assert_eq!(wanted_state(guid(GAIN_CONTROL)), Some(false));
83
assert_eq!(wanted_state(guid(RANGE_COMPRESSION)), Some(false));
84
assert_eq!(wanted_state(guid(BEAMFORMING)), Some(true));
85
assert_eq!(wanted_state(guid(ECHO_CANCELLATION)), None);
86
assert_eq!(wanted_state(0x1234), None);
87
let echo = MicEffect { id: guid(ECHO_CANCELLATION), enabled: true, can_set: true };
88
assert!(echo.is_echo_cancellation() && echo.change().is_none());
89
let deep_noise = MicEffect { id: guid(DEEP_NOISE_SUPPRESSION), enabled: true, can_set: true };
90
assert_eq!(deep_noise.change(), Some(false));
91
assert_eq!(MicEffect { can_set: false, ..deep_noise }.change(), None);
92
assert_eq!(MicEffect { enabled: false, ..deep_noise }.change(), None);
93
}
94
95
#[test]
96
fn known_effect_guids_get_their_names() {
97
assert_eq!(effect_name(0x6f64adbe_8211_11e2_8c70_2c27d7f001fa), "acoustic echo cancellation");
98
assert_eq!(effect_name(0x6f64add0_8211_11e2_8c70_2c27d7f001fa), "deep noise suppression");
99
assert_eq!(effect_name(0x1234), "00000000000000000000000000001234");
100
}
101
}
@@ -0,0 +1,101 @@1
#[derive(Debug, Clone, PartialEq, Eq)]2
pub struct MicEffect {3
pub id: u128,4
pub enabled: bool,5
pub can_set: bool,6
}7
8
impl MicEffect {9
pub fn name(&self) -> String {10
effect_name(self.id)11
}12
13
pub fn is_echo_cancellation(&self) -> bool {14
known_prefix(self.id) == Some(ECHO_CANCELLATION)15
}16
17
/// The state to switch to, when it differs from the current one and Windows lets us change it.18
pub fn change(&self) -> Option<bool> {19
wanted_state(self.id).filter(|wanted| self.can_set && *wanted != self.enabled)20
}21
}22
23
const EFFECT_SUFFIX: u128 = 0x8211_11e2_8c70_2c27d7f001fa;24
const EFFECT_NAMES: [(u32, &str); 19] = [25
(0x6f64adbe, "acoustic echo cancellation"),26
(0x6f64adbf, "noise suppression"),27
(0x6f64adc0, "automatic gain control"),28
(0x6f64adc1, "beamforming"),29
(0x6f64adc2, "constant tone removal"),30
(0x6f64adc3, "equalizer"),31
(0x6f64adc4, "loudness equalizer"),32
(0x6f64adc5, "bass boost"),33
(0x6f64adc6, "virtual surround"),34
(0x6f64adc7, "virtual headphones"),35
(0x6f64adc8, "speaker fill"),36
(0x6f64adc9, "room correction"),37
(0x6f64adca, "bass management"),38
(0x6f64adcb, "environmental effects"),39
(0x6f64adcc, "speaker protection"),40
(0x6f64adcd, "speaker compensation"),41
(0x6f64adce, "dynamic range compression"),42
(0x6f64adcf, "far field beamforming"),43
(0x6f64add0, "deep noise suppression"),44
];45
46
const ECHO_CANCELLATION: u32 = 0x6f64adbe;47
const NOISE_SUPPRESSION: u32 = 0x6f64adbf;48
const GAIN_CONTROL: u32 = 0x6f64adc0;49
const BEAMFORMING: u32 = 0x6f64adc1;50
const RANGE_COMPRESSION: u32 = 0x6f64adce;51
const DEEP_NOISE_SUPPRESSION: u32 = 0x6f64add0;52
53
fn known_prefix(guid: u128) -> Option<u32> {54
(guid & ((1u128 << 96) - 1) == EFFECT_SUFFIX).then_some((guid >> 96) as u32)55
}56
57
/// DeepFilterNet and AGC2 replace the Windows noise, gain and compression stages, stacking them muffles speech.58
/// The Windows echo canceller stays: it has the exact speaker signal, ours only a copy of the decoded stream.59
pub fn wanted_state(guid: u128) -> Option<bool> {60
match known_prefix(guid)? {61
NOISE_SUPPRESSION | DEEP_NOISE_SUPPRESSION | GAIN_CONTROL | RANGE_COMPRESSION => Some(false),62
BEAMFORMING => Some(true),63
_ => None,64
}65
}66
67
pub fn effect_name(guid: u128) -> String {68
known_prefix(guid)69
.and_then(|prefix| EFFECT_NAMES.iter().find(|(known, _)| *known == prefix))70
.map_or_else(|| format!("{guid:032x}"), |(_, name)| (*name).to_owned())71
}72
73
#[cfg(test)]74
mod tests {75
use super::*;76
77
#[test]78
fn our_chain_replaces_windows_noise_gain_and_compression_but_keeps_its_echo_canceller() {79
let guid = |prefix: u32| (u128::from(prefix) << 96) | EFFECT_SUFFIX;80
assert_eq!(wanted_state(guid(NOISE_SUPPRESSION)), Some(false));81
assert_eq!(wanted_state(guid(DEEP_NOISE_SUPPRESSION)), Some(false));82
assert_eq!(wanted_state(guid(GAIN_CONTROL)), Some(false));83
assert_eq!(wanted_state(guid(RANGE_COMPRESSION)), Some(false));84
assert_eq!(wanted_state(guid(BEAMFORMING)), Some(true));85
assert_eq!(wanted_state(guid(ECHO_CANCELLATION)), None);86
assert_eq!(wanted_state(0x1234), None);87
let echo = MicEffect { id: guid(ECHO_CANCELLATION), enabled: true, can_set: true };88
assert!(echo.is_echo_cancellation() && echo.change().is_none());89
let deep_noise = MicEffect { id: guid(DEEP_NOISE_SUPPRESSION), enabled: true, can_set: true };90
assert_eq!(deep_noise.change(), Some(false));91
assert_eq!(MicEffect { can_set: false, ..deep_noise }.change(), None);92
assert_eq!(MicEffect { enabled: false, ..deep_noise }.change(), None);93
}94
95
#[test]96
fn known_effect_guids_get_their_names() {97
assert_eq!(effect_name(0x6f64adbe_8211_11e2_8c70_2c27d7f001fa), "acoustic echo cancellation");98
assert_eq!(effect_name(0x6f64add0_8211_11e2_8c70_2c27d7f001fa), "deep noise suppression");99
assert_eq!(effect_name(0x1234), "00000000000000000000000000001234");100
}101
}@@ -52,8 +52,8 @@ impl ApmConfig {
52
52
}
53
53
54
54
pub fn front_module(self) -> Option<AudioProcessingModule> {
55
(self.echo_canceller || self.high_pass_filter || self.noise_suppression)
56
.then(|| AudioProcessingModule::new(self.echo_canceller, false, self.high_pass_filter, self.noise_suppression))
55
(self.echo_canceller || self.noise_suppression)
56
.then(|| AudioProcessingModule::new(self.echo_canceller, false, false, self.noise_suppression))
57
57
}
58
58
59
59
pub fn gain_module(self) -> Option<AudioProcessingModule> {
@@ -76,7 +76,7 @@ impl MicSettings {
76
76
}
77
77
78
78
pub fn uses_device_track_on(self, windows: bool) -> bool {
79
!windows && !self.music_mode && self.noise_suppression != NoiseSuppression::Off
79
!windows && !self.music_mode && self.noise_suppression == NoiseSuppression::Low
80
80
}
81
81
82
82
pub fn ml_noise_suppression(self) -> bool {
@@ -91,7 +91,7 @@ mod tests {
91
91
#[test]
92
92
fn auto_leaves_noise_to_the_ml_stage_and_keeps_the_rest_of_the_apm() {
93
93
let settings = MicSettings::default();
94
assert!(settings.uses_device_track_on(false));
94
assert!(!settings.uses_device_track_on(false));
95
95
assert!(settings.ml_noise_suppression());
96
96
assert_eq!(
97
97
settings.apm_config(),
@@ -133,7 +133,7 @@ mod tests {
133
133
for music_mode in [false, true] {
134
134
let settings = MicSettings { noise_suppression, music_mode };
135
135
assert!(!settings.uses_device_track_on(true));
136
assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression != NoiseSuppression::Off);
136
assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression == NoiseSuppression::Low);
137
137
}
138
138
}
139
139
}
@@ -52,8 +52,8 @@ impl ApmConfig {52
}52
}53
53
54
pub fn front_module(self) -> Option<AudioProcessingModule> {54
pub fn front_module(self) -> Option<AudioProcessingModule> {55
(self.echo_canceller || self.high_pass_filter || self.noise_suppression)55
(self.echo_canceller || self.noise_suppression)56
.then(|| AudioProcessingModule::new(self.echo_canceller, false, self.high_pass_filter, self.noise_suppression))56
.then(|| AudioProcessingModule::new(self.echo_canceller, false, false, self.noise_suppression))57
}57
}58
58
59
pub fn gain_module(self) -> Option<AudioProcessingModule> {59
pub fn gain_module(self) -> Option<AudioProcessingModule> {@@ -76,7 +76,7 @@ impl MicSettings {76
}76
}77
77
78
pub fn uses_device_track_on(self, windows: bool) -> bool {78
pub fn uses_device_track_on(self, windows: bool) -> bool {79
!windows && !self.music_mode && self.noise_suppression != NoiseSuppression::Off79
!windows && !self.music_mode && self.noise_suppression == NoiseSuppression::Low80
}80
}81
81
82
pub fn ml_noise_suppression(self) -> bool {82
pub fn ml_noise_suppression(self) -> bool {@@ -91,7 +91,7 @@ mod tests {91
#[test]91
#[test]92
fn auto_leaves_noise_to_the_ml_stage_and_keeps_the_rest_of_the_apm() {92
fn auto_leaves_noise_to_the_ml_stage_and_keeps_the_rest_of_the_apm() {93
let settings = MicSettings::default();93
let settings = MicSettings::default();94
assert!(settings.uses_device_track_on(false));94
assert!(!settings.uses_device_track_on(false));95
assert!(settings.ml_noise_suppression());95
assert!(settings.ml_noise_suppression());96
assert_eq!(96
assert_eq!(97
settings.apm_config(),97
settings.apm_config(),@@ -133,7 +133,7 @@ mod tests {133
for music_mode in [false, true] {133
for music_mode in [false, true] {134
let settings = MicSettings { noise_suppression, music_mode };134
let settings = MicSettings { noise_suppression, music_mode };135
assert!(!settings.uses_device_track_on(true));135
assert!(!settings.uses_device_track_on(true));136
assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression != NoiseSuppression::Off);136
assert_eq!(settings.uses_device_track_on(false), !music_mode && noise_suppression == NoiseSuppression::Low);137
}137
}138
}138
}139
}139
}@@ -7,18 +7,21 @@ use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
7
7
use windows::Win32::Media::Audio::{
8
8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
9
9
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,
10
IAudioCaptureClient, IAudioClient, IAudioClient2, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture,
11
eCommunications,
10
AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, IAudioCaptureClient, IAudioClient, IAudioClient2,
11
IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture, eCommunications,
12
12
};
13
13
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};
14
use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize, STGM_READ};
14
use windows::Win32::System::Com::{
15
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, STGM_READ,
16
};
15
17
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
16
use windows::core::{BOOL, HSTRING, Interface};
18
use windows::core::{BOOL, GUID, HSTRING, Interface};
17
19
18
20
use crate::audio::SAMPLE_RATE;
19
21
use crate::capture::Capture;
20
22
use crate::devices::DeviceChoice;
21
23
use crate::error::{Error, Result};
24
use crate::mic_effects::MicEffect;
22
25
use crate::pcm::SampleQueue;
23
26
24
27
const BITS: u16 = 16;
@@ -54,7 +57,7 @@ fn friendly_name(device: &IMMDevice) -> String {
54
57
}
55
58
}
56
59
57
fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient, HANDLE)> {
60
fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient, HANDLE, Vec<MicEffect>)> {
58
61
let block_align = BITS / 8;
59
62
let format = WAVEFORMATEX {
60
63
wFormatTag: PCM_TAG,
@@ -81,11 +84,12 @@ fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient,
81
84
client
82
85
.Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 0, 0, &raw const format, None)
83
86
.map_err(|error| audio_error("initialize microphone", error))?;
87
let effects = apply_effect_policy(&client);
84
88
let event = CreateEventW(None, false, false, None).map_err(|error| audio_error("event", error))?;
85
89
client.SetEventHandle(event).map_err(|error| audio_error("event handle", error))?;
86
90
let capture = client.GetService::<IAudioCaptureClient>().map_err(|error| audio_error("capture service", error))?;
87
91
client.Start().map_err(|error| audio_error("start microphone", error))?;
88
Ok((client, capture, event))
92
Ok((client, capture, event, effects))
89
93
}
90
94
}
91
95
@@ -108,8 +112,8 @@ fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::R
108
112
Ok(())
109
113
}
110
114
111
pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {
112
let (ready_sender, ready) = mpsc::channel::<Result<String>>();
115
pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String, Vec<MicEffect>)> {
116
let (ready_sender, ready) = mpsc::channel::<Result<(String, Vec<MicEffect>)>>();
113
117
let choice = choice.clone();
114
118
let capture = Capture::spawn_thread("mic-communications", move |stop| {
115
119
unsafe {
@@ -117,11 +121,11 @@ pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue
117
121
}
118
122
let started = open_device(&choice).and_then(|device| {
119
123
let name = friendly_name(&device);
120
initialise(&device).map(|(client, capture, event)| (name, client, capture, event))
124
initialise(&device).map(|(client, capture, event, effects)| (name, effects, client, capture, event))
121
125
});
122
126
match started {
123
Ok((name, client, capture, event)) => {
124
let _ = ready_sender.send(Ok(name));
127
Ok((name, effects, client, capture, event)) => {
128
let _ = ready_sender.send(Ok((name, effects)));
125
129
while !stop.load(Ordering::SeqCst) {
126
130
let waited = unsafe { WaitForSingleObject(event, EVENT_WAIT_MS) };
127
131
if waited == WAIT_OBJECT_0 && drain(&capture, &queue).is_err() {
@@ -140,6 +144,54 @@ pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue
140
144
unsafe { CoUninitialize() };
141
145
})
142
146
.map_err(|error| audio_error("microphone thread", error))?;
143
let name = ready.recv().map_err(|_| Error::Audio("microphone thread ended".into()))??;
144
Ok((capture, name))
147
let (name, effects) = ready.recv().map_err(|_| Error::Audio("microphone thread ended".into()))??;
148
Ok((capture, name, effects))
149
}
150
151
/// Switches the Windows effects on this stream to what our chain expects and returns the resulting effect list.
152
fn apply_effect_policy(client: &IAudioClient) -> Vec<MicEffect> {
153
unsafe {
154
let Ok(manager) = client.GetService::<IAudioEffectsManager>() else { return Vec::new() };
155
for effect in list_effects(&manager).unwrap_or_default() {
156
if let Some(enabled) = effect.change() {
157
let state = if enabled { AUDIO_EFFECT_STATE_ON } else { AUDIO_EFFECT_STATE_OFF };
158
let _ = manager.SetAudioEffectState(GUID::from_u128(effect.id), state);
159
}
160
}
161
list_effects(&manager).unwrap_or_default()
162
}
163
}
164
165
fn list_effects(manager: &IAudioEffectsManager) -> Result<Vec<MicEffect>> {
166
unsafe {
167
let mut effects: *mut AUDIO_EFFECT = std::ptr::null_mut();
168
let mut count = 0u32;
169
manager.GetAudioEffects(&mut effects, &mut count).map_err(|error| audio_error("audio effects", error))?;
170
if effects.is_null() {
171
return Ok(Vec::new());
172
}
173
let listed = std::slice::from_raw_parts(effects, count as usize)
174
.iter()
175
.map(|effect| MicEffect { id: effect.id.to_u128(), enabled: effect.state.0 != 0, can_set: effect.canSetState.as_bool() })
176
.collect();
177
CoTaskMemFree(Some(effects.cast_const().cast()));
178
Ok(listed)
179
}
180
}
181
182
/// Opens the microphone the way a call does and lists the Windows effects running on that stream.
183
pub fn probe_effects(choice: &DeviceChoice) -> Result<(String, Vec<MicEffect>)> {
184
unsafe {
185
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
186
}
187
let probed = open_device(choice).and_then(|device| {
188
let (client, _capture, event, effects) = initialise(&device)?;
189
unsafe {
190
let _ = client.Stop();
191
let _ = CloseHandle(event);
192
}
193
Ok((friendly_name(&device), effects))
194
});
195
unsafe { CoUninitialize() };
196
probed
145
197
}
@@ -7,18 +7,21 @@ use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};7
use windows::Win32::Media::Audio::{7
use windows::Win32::Media::Audio::{8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,9
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,9
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDCLNT_STREAMOPTIONS_NONE, AudioCategory_Communications, AudioClientProperties,10
IAudioCaptureClient, IAudioClient, IAudioClient2, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture,10
AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, IAudioCaptureClient, IAudioClient, IAudioClient2,11
eCommunications,11
IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX, eCapture, eCommunications,12
};12
};13
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};13
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};14
use windows::Win32::System::Com::{CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize, STGM_READ};14
use windows::Win32::System::Com::{15
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize, STGM_READ,16
};15
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};17
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};16
use windows::core::{BOOL, HSTRING, Interface};18
use windows::core::{BOOL, GUID, HSTRING, Interface};17
19
18
use crate::audio::SAMPLE_RATE;20
use crate::audio::SAMPLE_RATE;19
use crate::capture::Capture;21
use crate::capture::Capture;20
use crate::devices::DeviceChoice;22
use crate::devices::DeviceChoice;21
use crate::error::{Error, Result};23
use crate::error::{Error, Result};24
use crate::mic_effects::MicEffect;22
use crate::pcm::SampleQueue;25
use crate::pcm::SampleQueue;23
26
24
const BITS: u16 = 16;27
const BITS: u16 = 16;@@ -54,7 +57,7 @@ fn friendly_name(device: &IMMDevice) -> String {54
}57
}55
}58
}56
59
57
fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient, HANDLE)> {60
fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient, HANDLE, Vec<MicEffect>)> {58
let block_align = BITS / 8;61
let block_align = BITS / 8;59
let format = WAVEFORMATEX {62
let format = WAVEFORMATEX {60
wFormatTag: PCM_TAG,63
wFormatTag: PCM_TAG,@@ -81,11 +84,12 @@ fn initialise(device: &IMMDevice) -> Result<(IAudioClient, IAudioCaptureClient,81
client84
client82
.Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 0, 0, &raw const format, None)85
.Initialize(AUDCLNT_SHAREMODE_SHARED, flags, 0, 0, &raw const format, None)83
.map_err(|error| audio_error("initialize microphone", error))?;86
.map_err(|error| audio_error("initialize microphone", error))?;87
let effects = apply_effect_policy(&client);84
let event = CreateEventW(None, false, false, None).map_err(|error| audio_error("event", error))?;88
let event = CreateEventW(None, false, false, None).map_err(|error| audio_error("event", error))?;85
client.SetEventHandle(event).map_err(|error| audio_error("event handle", error))?;89
client.SetEventHandle(event).map_err(|error| audio_error("event handle", error))?;86
let capture = client.GetService::<IAudioCaptureClient>().map_err(|error| audio_error("capture service", error))?;90
let capture = client.GetService::<IAudioCaptureClient>().map_err(|error| audio_error("capture service", error))?;87
client.Start().map_err(|error| audio_error("start microphone", error))?;91
client.Start().map_err(|error| audio_error("start microphone", error))?;88
Ok((client, capture, event))92
Ok((client, capture, event, effects))89
}93
}90
}94
}91
95
@@ -108,8 +112,8 @@ fn drain(capture: &IAudioCaptureClient, queue: &SampleQueue) -> windows::core::R108
Ok(())112
Ok(())109
}113
}110
114
111
pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {115
pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String, Vec<MicEffect>)> {112
let (ready_sender, ready) = mpsc::channel::<Result<String>>();116
let (ready_sender, ready) = mpsc::channel::<Result<(String, Vec<MicEffect>)>>();113
let choice = choice.clone();117
let choice = choice.clone();114
let capture = Capture::spawn_thread("mic-communications", move |stop| {118
let capture = Capture::spawn_thread("mic-communications", move |stop| {115
unsafe {119
unsafe {@@ -117,11 +121,11 @@ pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue117
}121
}118
let started = open_device(&choice).and_then(|device| {122
let started = open_device(&choice).and_then(|device| {119
let name = friendly_name(&device);123
let name = friendly_name(&device);120
initialise(&device).map(|(client, capture, event)| (name, client, capture, event))124
initialise(&device).map(|(client, capture, event, effects)| (name, effects, client, capture, event))121
});125
});122
match started {126
match started {123
Ok((name, client, capture, event)) => {127
Ok((name, effects, client, capture, event)) => {124
let _ = ready_sender.send(Ok(name));128
let _ = ready_sender.send(Ok((name, effects)));125
while !stop.load(Ordering::SeqCst) {129
while !stop.load(Ordering::SeqCst) {126
let waited = unsafe { WaitForSingleObject(event, EVENT_WAIT_MS) };130
let waited = unsafe { WaitForSingleObject(event, EVENT_WAIT_MS) };127
if waited == WAIT_OBJECT_0 && drain(&capture, &queue).is_err() {131
if waited == WAIT_OBJECT_0 && drain(&capture, &queue).is_err() {@@ -140,6 +144,54 @@ pub fn start_communications_microphone(choice: &DeviceChoice, queue: SampleQueue140
unsafe { CoUninitialize() };144
unsafe { CoUninitialize() };141
})145
})142
.map_err(|error| audio_error("microphone thread", error))?;146
.map_err(|error| audio_error("microphone thread", error))?;143
let name = ready.recv().map_err(|_| Error::Audio("microphone thread ended".into()))??;147
let (name, effects) = ready.recv().map_err(|_| Error::Audio("microphone thread ended".into()))??;144
Ok((capture, name))148
Ok((capture, name, effects))149
}150
151
/// Switches the Windows effects on this stream to what our chain expects and returns the resulting effect list.152
fn apply_effect_policy(client: &IAudioClient) -> Vec<MicEffect> {153
unsafe {154
let Ok(manager) = client.GetService::<IAudioEffectsManager>() else { return Vec::new() };155
for effect in list_effects(&manager).unwrap_or_default() {156
if let Some(enabled) = effect.change() {157
let state = if enabled { AUDIO_EFFECT_STATE_ON } else { AUDIO_EFFECT_STATE_OFF };158
let _ = manager.SetAudioEffectState(GUID::from_u128(effect.id), state);159
}160
}161
list_effects(&manager).unwrap_or_default()162
}163
}164
165
fn list_effects(manager: &IAudioEffectsManager) -> Result<Vec<MicEffect>> {166
unsafe {167
let mut effects: *mut AUDIO_EFFECT = std::ptr::null_mut();168
let mut count = 0u32;169
manager.GetAudioEffects(&mut effects, &mut count).map_err(|error| audio_error("audio effects", error))?;170
if effects.is_null() {171
return Ok(Vec::new());172
}173
let listed = std::slice::from_raw_parts(effects, count as usize)174
.iter()175
.map(|effect| MicEffect { id: effect.id.to_u128(), enabled: effect.state.0 != 0, can_set: effect.canSetState.as_bool() })176
.collect();177
CoTaskMemFree(Some(effects.cast_const().cast()));178
Ok(listed)179
}180
}181
182
/// Opens the microphone the way a call does and lists the Windows effects running on that stream.183
pub fn probe_effects(choice: &DeviceChoice) -> Result<(String, Vec<MicEffect>)> {184
unsafe {185
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);186
}187
let probed = open_device(choice).and_then(|device| {188
let (client, _capture, event, effects) = initialise(&device)?;189
unsafe {190
let _ = client.Stop();191
let _ = CloseHandle(event);192
}193
Ok((friendly_name(&device), effects))194
});195
unsafe { CoUninitialize() };196
probed145
}197
}@@ -1,4 +1,3 @@
1
use std::sync::atomic::{AtomicBool, Ordering};
2
1
use std::sync::{Mutex, Once};
3
2
4
3
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
@@ -14,8 +13,6 @@ const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;
14
13
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;
15
14
const WARM_UP_FRAMES: usize = 100;
16
15
17
static ENABLED: AtomicBool = AtomicBool::new(false);
18
static STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());
19
16
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);
20
17
static PREPARE: Once = Once::new();
21
18
@@ -147,20 +144,10 @@ impl Default for NoiseStage {
147
144
}
148
145
}
149
146
150
fn process_capture(channel_index: usize, samples: &mut [f32]) {
151
if !ENABLED.load(Ordering::Relaxed) {
152
return;
153
}
154
let mut stage = STAGE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
155
stage.process(channel_index, samples);
156
}
157
158
147
pub fn apply(settings: MicSettings) {
159
148
if settings.ml_noise_suppression() {
160
149
prepare();
161
150
}
162
webrtc_sys::noise_hook::set_capture_hook(Some(process_capture));
163
ENABLED.store(settings.ml_noise_suppression(), Ordering::Relaxed);
164
151
}
165
152
166
153
#[cfg(test)]
@@ -1,4 +1,3 @@1
use std::sync::atomic::{AtomicBool, Ordering};2
use std::sync::{Mutex, Once};1
use std::sync::{Mutex, Once};3
2
4
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};3
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};@@ -14,8 +13,6 @@ const MAX_LOCAL_SNR_ERB_DB: f32 = 35.0;14
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;13
const MAX_LOCAL_SNR_DF_DB: f32 = 35.0;15
const WARM_UP_FRAMES: usize = 100;14
const WARM_UP_FRAMES: usize = 100;16
15
17
static ENABLED: AtomicBool = AtomicBool::new(false);18
static STAGE: Mutex<NoiseStage> = Mutex::new(NoiseStage::new());19
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);16
static PROTOTYPE: Mutex<Option<DfTract>> = Mutex::new(None);20
static PREPARE: Once = Once::new();17
static PREPARE: Once = Once::new();21
18
@@ -147,20 +144,10 @@ impl Default for NoiseStage {147
}144
}148
}145
}149
146
150
fn process_capture(channel_index: usize, samples: &mut [f32]) {151
if !ENABLED.load(Ordering::Relaxed) {152
return;153
}154
let mut stage = STAGE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());155
stage.process(channel_index, samples);156
}157
158
pub fn apply(settings: MicSettings) {147
pub fn apply(settings: MicSettings) {159
if settings.ml_noise_suppression() {148
if settings.ml_noise_suppression() {160
prepare();149
prepare();161
}150
}162
webrtc_sys::noise_hook::set_capture_hook(Some(process_capture));163
ENABLED.store(settings.ml_noise_suppression(), Ordering::Relaxed);164
}151
}165
152
166
#[cfg(test)]153
#[cfg(test)]@@ -137,6 +137,7 @@ impl SoftwareAudio {
137
137
) -> Result<Self> {
138
138
let mut captures = Vec::new();
139
139
let mut warning = None;
140
let mut processing = plan.processing;
140
141
let mut microphone_source = None;
141
142
let (microphone, computer, loopback) = if mode == AudioMode::Platform {
142
143
let computer_queue = SampleQueue::default();
@@ -152,6 +153,7 @@ impl SoftwareAudio {
152
153
let microphone = match start_microphone(input, microphone_queue.clone()) {
153
154
Ok(started) => {
154
155
microphone_source = Some(started.source);
156
processing.echo_canceller &= !started.os_echo_cancellation;
155
157
captures.push(started.capture);
156
158
FrameSource::Captured(microphone_queue)
157
159
}
@@ -184,7 +186,7 @@ impl SoftwareAudio {
184
186
let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
185
187
let running = Arc::new(AtomicBool::new(true));
186
188
let feeder = Feeder {
187
processing: plan.processing,
189
processing,
188
190
ml_noise: plan.ml_noise,
189
191
source,
190
192
microphone,
@@ -254,17 +256,20 @@ mod tests {
254
256
}
255
257
256
258
#[test]
257
fn call_start_picks_the_path_per_platform_with_default_settings() {
259
fn default_settings_run_the_software_chain_on_both_platforms() {
258
260
let default = MicSettings::default();
259
261
assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
260
assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());
262
assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_some());
263
let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
264
assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
261
265
}
262
266
263
267
#[test]
264
268
fn the_plan_follows_sharing_and_the_mic_choice() {
265
269
let auto = MicSettings::default();
266
270
let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };
267
assert_eq!(SoftwareAudioPlan::wanted_on(false, auto, false, true), None);
271
let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };
272
assert_eq!(SoftwareAudioPlan::wanted_on(false, low, false, true), None);
268
273
assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);
269
274
let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();
270
275
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());
@@ -137,6 +137,7 @@ impl SoftwareAudio {137
) -> Result<Self> {137
) -> Result<Self> {138
let mut captures = Vec::new();138
let mut captures = Vec::new();139
let mut warning = None;139
let mut warning = None;140
let mut processing = plan.processing;140
let mut microphone_source = None;141
let mut microphone_source = None;141
let (microphone, computer, loopback) = if mode == AudioMode::Platform {142
let (microphone, computer, loopback) = if mode == AudioMode::Platform {142
let computer_queue = SampleQueue::default();143
let computer_queue = SampleQueue::default();@@ -152,6 +153,7 @@ impl SoftwareAudio {152
let microphone = match start_microphone(input, microphone_queue.clone()) {153
let microphone = match start_microphone(input, microphone_queue.clone()) {153
Ok(started) => {154
Ok(started) => {154
microphone_source = Some(started.source);155
microphone_source = Some(started.source);156
processing.echo_canceller &= !started.os_echo_cancellation;155
captures.push(started.capture);157
captures.push(started.capture);156
FrameSource::Captured(microphone_queue)158
FrameSource::Captured(microphone_queue)157
}159
}@@ -184,7 +186,7 @@ impl SoftwareAudio {184
let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));186
let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));185
let running = Arc::new(AtomicBool::new(true));187
let running = Arc::new(AtomicBool::new(true));186
let feeder = Feeder {188
let feeder = Feeder {187
processing: plan.processing,189
processing,188
ml_noise: plan.ml_noise,190
ml_noise: plan.ml_noise,189
source,191
source,190
microphone,192
microphone,@@ -254,17 +256,20 @@ mod tests {254
}256
}255
257
256
#[test]258
#[test]257
fn call_start_picks_the_path_per_platform_with_default_settings() {259
fn default_settings_run_the_software_chain_on_both_platforms() {258
let default = MicSettings::default();260
let default = MicSettings::default();259
assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());261
assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());260
assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());262
assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_some());263
let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };264
assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());261
}265
}262
266
263
#[test]267
#[test]264
fn the_plan_follows_sharing_and_the_mic_choice() {268
fn the_plan_follows_sharing_and_the_mic_choice() {265
let auto = MicSettings::default();269
let auto = MicSettings::default();266
let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };270
let off = MicSettings { noise_suppression: NoiseSuppression::Off, music_mode: false };267
assert_eq!(SoftwareAudioPlan::wanted_on(false, auto, false, true), None);271
let low = MicSettings { noise_suppression: NoiseSuppression::Low, music_mode: false };272
assert_eq!(SoftwareAudioPlan::wanted_on(false, low, false, true), None);268
assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);273
assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);269
let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();274
let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();270
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());275
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());@@ -43,15 +43,23 @@ fn named_input(choice: &DeviceChoice) -> Option<Device> {
43
43
pub struct MicrophoneStart {
44
44
pub capture: Capture,
45
45
pub source: String,
46
pub os_echo_cancellation: bool,
46
47
}
47
48
48
49
#[cfg(windows)]
49
50
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
50
51
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {
51
Ok((capture, name)) => Ok(MicrophoneStart { capture, source: format!("wasapi communications ({name})") }),
52
Ok((capture, name, effects)) => {
53
let active: Vec<String> = effects.iter().filter(|effect| effect.enabled).map(|effect| effect.name()).collect();
54
Ok(MicrophoneStart {
55
capture,
56
source: format!("wasapi communications ({name}), windows effects: {}", active.join(", ")),
57
os_echo_cancellation: effects.iter().any(|effect| effect.is_echo_cancellation() && effect.enabled),
58
})
59
}
52
60
Err(error) => {
53
61
let capture = start_cpal_microphone(choice, queue)?;
54
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })
62
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}"), os_echo_cancellation: false })
55
63
}
56
64
}
57
65
}
@@ -59,7 +67,7 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic
59
67
#[cfg(not(windows))]
60
68
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
61
69
let capture = start_cpal_microphone(choice, queue)?;
62
Ok(MicrophoneStart { capture, source: "cpal".into() })
70
Ok(MicrophoneStart { capture, source: "cpal".into(), os_echo_cancellation: false })
63
71
}
64
72
65
73
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
@@ -43,15 +43,23 @@ fn named_input(choice: &DeviceChoice) -> Option<Device> {43
pub struct MicrophoneStart {43
pub struct MicrophoneStart {44
pub capture: Capture,44
pub capture: Capture,45
pub source: String,45
pub source: String,46
pub os_echo_cancellation: bool,46
}47
}47
48
48
#[cfg(windows)]49
#[cfg(windows)]49
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {50
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {50
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {51
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {51
Ok((capture, name)) => Ok(MicrophoneStart { capture, source: format!("wasapi communications ({name})") }),52
Ok((capture, name, effects)) => {53
let active: Vec<String> = effects.iter().filter(|effect| effect.enabled).map(|effect| effect.name()).collect();54
Ok(MicrophoneStart {55
capture,56
source: format!("wasapi communications ({name}), windows effects: {}", active.join(", ")),57
os_echo_cancellation: effects.iter().any(|effect| effect.is_echo_cancellation() && effect.enabled),58
})59
}52
Err(error) => {60
Err(error) => {53
let capture = start_cpal_microphone(choice, queue)?;61
let capture = start_cpal_microphone(choice, queue)?;54
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })62
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}"), os_echo_cancellation: false })55
}63
}56
}64
}57
}65
}@@ -59,7 +67,7 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic59
#[cfg(not(windows))]67
#[cfg(not(windows))]60
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {68
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {61
let capture = start_cpal_microphone(choice, queue)?;69
let capture = start_cpal_microphone(choice, queue)?;62
Ok(MicrophoneStart { capture, source: "cpal".into() })70
Ok(MicrophoneStart { capture, source: "cpal".into(), os_echo_cancellation: false })63
}71
}64
72
65
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {73
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {@@ -0,0 +1,100 @@
1
use crate::audio::SAMPLE_RATE;
2
3
pub const CUTOFF_HZ: f32 = 120.0;
4
const BUTTERWORTH_FOURTH_ORDER_Q: [f32; 2] = [0.541_196_1, 1.306_563];
5
6
#[derive(Debug, Clone, Copy)]
7
struct Biquad {
8
b0: f32,
9
b1: f32,
10
b2: f32,
11
a1: f32,
12
a2: f32,
13
x1: f32,
14
x2: f32,
15
y1: f32,
16
y2: f32,
17
}
18
19
impl Biquad {
20
fn high_pass(cutoff_hz: f32, quality: f32) -> Biquad {
21
let omega = std::f32::consts::TAU * cutoff_hz / SAMPLE_RATE as f32;
22
let alpha = omega.sin() / (2.0 * quality);
23
let cosine = omega.cos();
24
let a0 = 1.0 + alpha;
25
Biquad {
26
b0: (1.0 + cosine) / 2.0 / a0,
27
b1: -(1.0 + cosine) / a0,
28
b2: (1.0 + cosine) / 2.0 / a0,
29
a1: -2.0 * cosine / a0,
30
a2: (1.0 - alpha) / a0,
31
x1: 0.0,
32
x2: 0.0,
33
y1: 0.0,
34
y2: 0.0,
35
}
36
}
37
38
fn process(&mut self, input: f32) -> f32 {
39
let output = self.b0 * input + self.b1 * self.x1 + self.b2 * self.x2 - self.a1 * self.y1 - self.a2 * self.y2;
40
self.x2 = self.x1;
41
self.x1 = input;
42
self.y2 = self.y1;
43
self.y1 = output;
44
output
45
}
46
}
47
48
/// Fourth-order Butterworth high-pass for speech; WebRTC's own high-pass only removes rumble below about 80 Hz.
49
pub struct VoiceHighPass {
50
sections: [Biquad; 2],
51
}
52
53
impl VoiceHighPass {
54
pub fn new() -> VoiceHighPass {
55
VoiceHighPass { sections: BUTTERWORTH_FOURTH_ORDER_Q.map(|quality| Biquad::high_pass(CUTOFF_HZ, quality)) }
56
}
57
58
pub fn process(&mut self, frame: &mut [i16]) {
59
for sample in frame {
60
let filtered = self.sections.iter_mut().fold(f32::from(*sample), |value, section| section.process(value));
61
*sample = filtered.round().clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16;
62
}
63
}
64
}
65
66
impl Default for VoiceHighPass {
67
fn default() -> Self {
68
VoiceHighPass::new()
69
}
70
}
71
72
#[cfg(test)]
73
mod tests {
74
use super::*;
75
use crate::audio::SineGenerator;
76
77
fn gain_db(frequency: f32) -> f32 {
78
let mut filter = VoiceHighPass::new();
79
let mut generator = SineGenerator::new(frequency, 0.5);
80
let (mut input_energy, mut output_energy) = (0.0_f64, 0.0_f64);
81
for frame_index in 0..200 {
82
let input = generator.next_frame();
83
let mut output = input.clone();
84
filter.process(&mut output);
85
if frame_index >= 100 {
86
input_energy += input.iter().map(|sample| f64::from(*sample).powi(2)).sum::<f64>();
87
output_energy += output.iter().map(|sample| f64::from(*sample).powi(2)).sum::<f64>();
88
}
89
}
90
(10.0 * (output_energy / input_energy).log10()) as f32
91
}
92
93
#[test]
94
fn speech_band_passes_and_rumble_is_cut() {
95
assert!(gain_db(1000.0).abs() < 0.2, "1 kHz {}", gain_db(1000.0));
96
assert!(gain_db(200.0) > -1.0, "200 Hz {}", gain_db(200.0));
97
assert!((gain_db(CUTOFF_HZ) + 3.0).abs() < 0.5, "cutoff {}", gain_db(CUTOFF_HZ));
98
assert!(gain_db(60.0) < -20.0, "60 Hz {}", gain_db(60.0));
99
}
100
}
@@ -0,0 +1,100 @@1
use crate::audio::SAMPLE_RATE;2
3
pub const CUTOFF_HZ: f32 = 120.0;4
const BUTTERWORTH_FOURTH_ORDER_Q: [f32; 2] = [0.541_196_1, 1.306_563];5
6
#[derive(Debug, Clone, Copy)]7
struct Biquad {8
b0: f32,9
b1: f32,10
b2: f32,11
a1: f32,12
a2: f32,13
x1: f32,14
x2: f32,15
y1: f32,16
y2: f32,17
}18
19
impl Biquad {20
fn high_pass(cutoff_hz: f32, quality: f32) -> Biquad {21
let omega = std::f32::consts::TAU * cutoff_hz / SAMPLE_RATE as f32;22
let alpha = omega.sin() / (2.0 * quality);23
let cosine = omega.cos();24
let a0 = 1.0 + alpha;25
Biquad {26
b0: (1.0 + cosine) / 2.0 / a0,27
b1: -(1.0 + cosine) / a0,28
b2: (1.0 + cosine) / 2.0 / a0,29
a1: -2.0 * cosine / a0,30
a2: (1.0 - alpha) / a0,31
x1: 0.0,32
x2: 0.0,33
y1: 0.0,34
y2: 0.0,35
}36
}37
38
fn process(&mut self, input: f32) -> f32 {39
let output = self.b0 * input + self.b1 * self.x1 + self.b2 * self.x2 - self.a1 * self.y1 - self.a2 * self.y2;40
self.x2 = self.x1;41
self.x1 = input;42
self.y2 = self.y1;43
self.y1 = output;44
output45
}46
}47
48
/// Fourth-order Butterworth high-pass for speech; WebRTC's own high-pass only removes rumble below about 80 Hz.49
pub struct VoiceHighPass {50
sections: [Biquad; 2],51
}52
53
impl VoiceHighPass {54
pub fn new() -> VoiceHighPass {55
VoiceHighPass { sections: BUTTERWORTH_FOURTH_ORDER_Q.map(|quality| Biquad::high_pass(CUTOFF_HZ, quality)) }56
}57
58
pub fn process(&mut self, frame: &mut [i16]) {59
for sample in frame {60
let filtered = self.sections.iter_mut().fold(f32::from(*sample), |value, section| section.process(value));61
*sample = filtered.round().clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16;62
}63
}64
}65
66
impl Default for VoiceHighPass {67
fn default() -> Self {68
VoiceHighPass::new()69
}70
}71
72
#[cfg(test)]73
mod tests {74
use super::*;75
use crate::audio::SineGenerator;76
77
fn gain_db(frequency: f32) -> f32 {78
let mut filter = VoiceHighPass::new();79
let mut generator = SineGenerator::new(frequency, 0.5);80
let (mut input_energy, mut output_energy) = (0.0_f64, 0.0_f64);81
for frame_index in 0..200 {82
let input = generator.next_frame();83
let mut output = input.clone();84
filter.process(&mut output);85
if frame_index >= 100 {86
input_energy += input.iter().map(|sample| f64::from(*sample).powi(2)).sum::<f64>();87
output_energy += output.iter().map(|sample| f64::from(*sample).powi(2)).sum::<f64>();88
}89
}90
(10.0 * (output_energy / input_energy).log10()) as f3291
}92
93
#[test]94
fn speech_band_passes_and_rumble_is_cut() {95
assert!(gain_db(1000.0).abs() < 0.2, "1 kHz {}", gain_db(1000.0));96
assert!(gain_db(200.0) > -1.0, "200 Hz {}", gain_db(200.0));97
assert!((gain_db(CUTOFF_HZ) + 3.0).abs() < 0.5, "cutoff {}", gain_db(CUTOFF_HZ));98
assert!(gain_db(60.0) < -20.0, "60 Hz {}", gain_db(60.0));99
}100
}