fix(calling): laptop mic speech no longer cut, AGC2 before and after DeepFilterNet
- DeepFilterNet dropped quiet laptop-mic speech (-40 dBFS) as noise: a lift AGC2 (start +10 dB) now runs before it - DeepFilterNet takes about 6 dB off reverberant speech: an output AGC2 (+3 dB fixed, limiter) restores the level after it - create_gain_apm in vendored webrtc-sys gives each AGC2 its own settings; create_apm is back to upstream - AEC3 runs again next to the Windows echo canceller, so residual echo is gone before the gain lifts it - stage dumps add 0-far-end; stages are now raw, echo-highpass, gain, noise-gain Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -1197,6 +1197,7 @@ dependencies = [
1197
1197
"chatsvc",
1198
1198
"chrono",
1199
1199
"cpal",
1200
"cxx",
1200
1201
"deep_filter",
1201
1202
"flate2",
1202
1203
"futures-util",
@@ -1197,6 +1197,7 @@ dependencies = [1197
"chatsvc",1197
"chatsvc",1198
"chrono",1198
"chrono",1199
"cpal",1199
"cpal",1200
"cxx",1200
"deep_filter",1201
"deep_filter",1201
"flate2",1202
"flate2",1202
"futures-util",1203
"futures-util",@@ -14,6 +14,7 @@ flate2 = "1"
14
14
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }
15
15
futures-util.workspace = true
16
16
libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }
17
cxx = "1"
17
18
deep_filter = { path = "../../vendor/deep_filter" }
18
19
ndarray = "0.17"
19
20
nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }
@@ -14,6 +14,7 @@ flate2 = "1"14
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }14
image = { version = "0.25", default-features = false, features = ["jpeg", "png"] }15
futures-util.workspace = true15
futures-util.workspace = true16
libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }16
libwebrtc = { version = "=0.3.51", features = ["glib-main-loop"] }17
cxx = "1"17
deep_filter = { path = "../../vendor/deep_filter" }18
deep_filter = { path = "../../vendor/deep_filter" }18
ndarray = "0.17"19
ndarray = "0.17"19
nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }20
nokhwa = { version = "0.10", default-features = false, features = ["input-native"] }@@ -0,0 +1,55 @@
1
use cxx::UniquePtr;
2
use webrtc_sys::apm::ffi::{AudioProcessingModule, create_gain_apm};
3
4
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
5
6
const LIFT_INITIAL_GAIN_DB: f32 = 10.0;
7
const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 10.0;
8
const OUTPUT_FIXED_GAIN_DB: f32 = 3.0;
9
const OUTPUT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;
10
11
/// One AGC2 (adaptive digital gain, then fixed gain, then its -1 dBFS limiter) on 10 ms mono frames.
12
pub struct GainStage {
13
module: UniquePtr<AudioProcessingModule>,
14
}
15
16
impl GainStage {
17
/// Before DeepFilterNet: brings a quiet laptop mic up fast, settles near AGC2's own -22 dBFS.
18
pub fn lift() -> GainStage {
19
GainStage { module: create_gain_apm(LIFT_INITIAL_GAIN_DB, 0.0, LIFT_GAIN_CHANGE_DB_PER_SECOND) }
20
}
21
22
/// Last stage: +6 dB on top of AGC2's target puts speech near -16 dBFS like Teams.
23
pub fn output() -> GainStage {
24
GainStage { module: create_gain_apm(0.0, OUTPUT_FIXED_GAIN_DB, OUTPUT_GAIN_CHANGE_DB_PER_SECOND) }
25
}
26
27
pub fn process(&mut self, frame: &mut [i16]) {
28
if frame.len() != FRAME_SAMPLES || self.module.is_null() {
29
return;
30
}
31
let length = frame.len();
32
let pointer = frame.as_mut_ptr();
33
unsafe {
34
self.module.pin_mut().process_stream(pointer, length, pointer, length, SAMPLE_RATE as i32, 1);
35
}
36
}
37
}
38
39
#[cfg(test)]
40
mod tests {
41
use super::*;
42
43
fn rms_dbfs(samples: &[i16]) -> f32 {
44
let mean_square = samples.iter().map(|sample| f32::from(*sample).powi(2)).sum::<f32>() / samples.len() as f32;
45
10.0 * (mean_square / 32768.0_f32.powi(2)).log10()
46
}
47
48
#[test]
49
fn other_frame_lengths_pass_through() {
50
let mut stage = GainStage::lift();
51
let mut frame = vec![1000i16; 160];
52
stage.process(&mut frame);
53
assert_eq!(rms_dbfs(&frame), rms_dbfs(&[1000i16; 160]));
54
}
55
}
@@ -0,0 +1,55 @@1
use cxx::UniquePtr;2
use webrtc_sys::apm::ffi::{AudioProcessingModule, create_gain_apm};3
4
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};5
6
const LIFT_INITIAL_GAIN_DB: f32 = 10.0;7
const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 10.0;8
const OUTPUT_FIXED_GAIN_DB: f32 = 3.0;9
const OUTPUT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;10
11
/// One AGC2 (adaptive digital gain, then fixed gain, then its -1 dBFS limiter) on 10 ms mono frames.12
pub struct GainStage {13
module: UniquePtr<AudioProcessingModule>,14
}15
16
impl GainStage {17
/// Before DeepFilterNet: brings a quiet laptop mic up fast, settles near AGC2's own -22 dBFS.18
pub fn lift() -> GainStage {19
GainStage { module: create_gain_apm(LIFT_INITIAL_GAIN_DB, 0.0, LIFT_GAIN_CHANGE_DB_PER_SECOND) }20
}21
22
/// Last stage: +6 dB on top of AGC2's target puts speech near -16 dBFS like Teams.23
pub fn output() -> GainStage {24
GainStage { module: create_gain_apm(0.0, OUTPUT_FIXED_GAIN_DB, OUTPUT_GAIN_CHANGE_DB_PER_SECOND) }25
}26
27
pub fn process(&mut self, frame: &mut [i16]) {28
if frame.len() != FRAME_SAMPLES || self.module.is_null() {29
return;30
}31
let length = frame.len();32
let pointer = frame.as_mut_ptr();33
unsafe {34
self.module.pin_mut().process_stream(pointer, length, pointer, length, SAMPLE_RATE as i32, 1);35
}36
}37
}38
39
#[cfg(test)]40
mod tests {41
use super::*;42
43
fn rms_dbfs(samples: &[i16]) -> f32 {44
let mean_square = samples.iter().map(|sample| f32::from(*sample).powi(2)).sum::<f32>() / samples.len() as f32;45
10.0 * (mean_square / 32768.0_f32.powi(2)).log10()46
}47
48
#[test]49
fn other_frame_lengths_pass_through() {50
let mut stage = GainStage::lift();51
let mut frame = vec![1000i16; 160];52
stage.process(&mut frame);53
assert_eq!(rms_dbfs(&frame), rms_dbfs(&[1000i16; 160]));54
}55
}@@ -34,6 +34,7 @@ pub mod meeting;
34
34
pub mod meeting_options;
35
35
pub mod mic_processing;
36
36
pub mod mixer;
37
pub mod gain_stage;
37
38
pub mod mic_chain;
38
39
pub mod mic_effects;
39
40
pub mod noise_stage;
@@ -34,6 +34,7 @@ pub mod meeting;34
pub mod meeting_options;34
pub mod meeting_options;35
pub mod mic_processing;35
pub mod mic_processing;36
pub mod mixer;36
pub mod mixer;37
pub mod gain_stage;37
pub mod mic_chain;38
pub mod mic_chain;38
pub mod mic_effects;39
pub mod mic_effects;39
pub mod noise_stage;40
pub mod noise_stage;@@ -1,17 +1,20 @@
1
1
use libwebrtc::native::apm::AudioProcessingModule;
2
2
3
3
use crate::audio::SAMPLE_RATE;
4
use crate::gain_stage::GainStage;
4
5
use crate::mic_processing::ApmConfig;
5
6
use crate::noise_stage::NoiseStage;
6
7
use crate::voice_high_pass::VoiceHighPass;
7
8
use crate::wav_dump::StageDumps;
8
9
9
/// Voice high-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.
10
/// DeepFilterNet drops quiet laptop-mic speech as noise and takes about 6 dB off reverberant speech,
11
/// so one AGC2 brings the level up before it and a second one restores the level after it.
10
12
pub struct MicChain {
11
13
high_pass: Option<VoiceHighPass>,
12
14
front: Option<AudioProcessingModule>,
13
15
ml_noise: Option<NoiseStage>,
14
gain: Option<AudioProcessingModule>,
16
lift: Option<GainStage>,
17
output_gain: Option<GainStage>,
15
18
dumps: Option<StageDumps>,
16
19
}
17
20
@@ -24,34 +27,39 @@ impl MicChain {
24
27
high_pass: processing.high_pass_filter.then(VoiceHighPass::new),
25
28
front: processing.front_module(),
26
29
ml_noise: ml_noise.then(NoiseStage::new),
27
gain: processing.gain_module(),
30
lift: (processing.gain_controller && ml_noise).then(GainStage::lift),
31
output_gain: processing.gain_controller.then(GainStage::output),
28
32
dumps,
29
33
}
30
34
}
31
35
32
36
pub fn process_far_end(&mut self, frame: &mut [i16]) {
37
self.dump(0, frame);
33
38
if let Some(front) = self.front.as_mut() {
34
39
let _ = front.process_reverse_stream(frame, SAMPLE_RATE as i32, 1);
35
40
}
36
41
}
37
42
38
43
pub fn process(&mut self, frame: &mut [i16]) {
39
self.dump(0, frame);
44
self.dump(1, frame);
40
45
if let Some(high_pass) = self.high_pass.as_mut() {
41
46
high_pass.process(frame);
42
47
}
43
48
if let Some(front) = self.front.as_mut() {
44
49
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);
45
50
}
46
self.dump(1, frame);
51
self.dump(2, frame);
52
if let Some(lift) = self.lift.as_mut() {
53
lift.process(frame);
54
}
55
self.dump(3, frame);
47
56
if let Some(noise_stage) = self.ml_noise.as_mut() {
48
57
noise_stage.process_pcm(0, frame);
49
58
}
50
self.dump(2, frame);
51
if let Some(gain) = self.gain.as_mut() {
52
let _ = gain.process_stream(frame, SAMPLE_RATE as i32, 1);
59
if let Some(output_gain) = self.output_gain.as_mut() {
60
output_gain.process(frame);
53
61
}
54
self.dump(3, frame);
62
self.dump(4, frame);
55
63
}
56
64
57
65
fn dump(&mut self, stage_index: usize, frame: &[i16]) {
@@ -1,17 +1,20 @@1
use libwebrtc::native::apm::AudioProcessingModule;1
use libwebrtc::native::apm::AudioProcessingModule;2
2
3
use crate::audio::SAMPLE_RATE;3
use crate::audio::SAMPLE_RATE;4
use crate::gain_stage::GainStage;4
use crate::mic_processing::ApmConfig;5
use crate::mic_processing::ApmConfig;5
use crate::noise_stage::NoiseStage;6
use crate::noise_stage::NoiseStage;6
use crate::voice_high_pass::VoiceHighPass;7
use crate::voice_high_pass::VoiceHighPass;7
use crate::wav_dump::StageDumps;8
use crate::wav_dump::StageDumps;8
9
9
/// Voice high-pass and echo first, then DeepFilterNet, then AGC2 with its limiter, so the gain follows the cleaned voice.10
/// DeepFilterNet drops quiet laptop-mic speech as noise and takes about 6 dB off reverberant speech,11
/// so one AGC2 brings the level up before it and a second one restores the level after it.10
pub struct MicChain {12
pub struct MicChain {11
high_pass: Option<VoiceHighPass>,13
high_pass: Option<VoiceHighPass>,12
front: Option<AudioProcessingModule>,14
front: Option<AudioProcessingModule>,13
ml_noise: Option<NoiseStage>,15
ml_noise: Option<NoiseStage>,14
gain: Option<AudioProcessingModule>,16
lift: Option<GainStage>,17
output_gain: Option<GainStage>,15
dumps: Option<StageDumps>,18
dumps: Option<StageDumps>,16
}19
}17
20
@@ -24,34 +27,39 @@ impl MicChain {24
high_pass: processing.high_pass_filter.then(VoiceHighPass::new),27
high_pass: processing.high_pass_filter.then(VoiceHighPass::new),25
front: processing.front_module(),28
front: processing.front_module(),26
ml_noise: ml_noise.then(NoiseStage::new),29
ml_noise: ml_noise.then(NoiseStage::new),27
gain: processing.gain_module(),30
lift: (processing.gain_controller && ml_noise).then(GainStage::lift),31
output_gain: processing.gain_controller.then(GainStage::output),28
dumps,32
dumps,29
}33
}30
}34
}31
35
32
pub fn process_far_end(&mut self, frame: &mut [i16]) {36
pub fn process_far_end(&mut self, frame: &mut [i16]) {37
self.dump(0, frame);33
if let Some(front) = self.front.as_mut() {38
if let Some(front) = self.front.as_mut() {34
let _ = front.process_reverse_stream(frame, SAMPLE_RATE as i32, 1);39
let _ = front.process_reverse_stream(frame, SAMPLE_RATE as i32, 1);35
}40
}36
}41
}37
42
38
pub fn process(&mut self, frame: &mut [i16]) {43
pub fn process(&mut self, frame: &mut [i16]) {39
self.dump(0, frame);44
self.dump(1, frame);40
if let Some(high_pass) = self.high_pass.as_mut() {45
if let Some(high_pass) = self.high_pass.as_mut() {41
high_pass.process(frame);46
high_pass.process(frame);42
}47
}43
if let Some(front) = self.front.as_mut() {48
if let Some(front) = self.front.as_mut() {44
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);49
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);45
}50
}46
self.dump(1, frame);51
self.dump(2, frame);52
if let Some(lift) = self.lift.as_mut() {53
lift.process(frame);54
}55
self.dump(3, frame);47
if let Some(noise_stage) = self.ml_noise.as_mut() {56
if let Some(noise_stage) = self.ml_noise.as_mut() {48
noise_stage.process_pcm(0, frame);57
noise_stage.process_pcm(0, frame);49
}58
}50
self.dump(2, frame);59
if let Some(output_gain) = self.output_gain.as_mut() {51
if let Some(gain) = self.gain.as_mut() {60
output_gain.process(frame);52
let _ = gain.process_stream(frame, SAMPLE_RATE as i32, 1);53
}61
}54
self.dump(3, frame);62
self.dump(4, frame);55
}63
}56
64
57
fn dump(&mut self, stage_index: usize, frame: &[i16]) {65
fn dump(&mut self, stage_index: usize, frame: &[i16]) {@@ -10,10 +10,6 @@ impl MicEffect {
10
10
effect_name(self.id)
11
11
}
12
12
13
pub fn is_echo_cancellation(&self) -> bool {
14
known_prefix(self.id) == Some(ECHO_CANCELLATION)
15
}
16
17
13
/// The state to switch to, when it differs from the current one and Windows lets us change it.
18
14
pub fn change(&self) -> Option<bool> {
19
15
wanted_state(self.id).filter(|wanted| self.can_set && *wanted != self.enabled)
@@ -55,11 +51,12 @@ fn known_prefix(guid: u128) -> Option<u32> {
55
51
}
56
52
57
53
/// 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.
54
/// The Windows echo canceller stays: it has the exact speaker signal; AEC3 after it removes the rest before AGC2 lifts it.
59
55
pub fn wanted_state(guid: u128) -> Option<bool> {
60
56
match known_prefix(guid)? {
61
57
NOISE_SUPPRESSION | DEEP_NOISE_SUPPRESSION | GAIN_CONTROL | RANGE_COMPRESSION => Some(false),
62
58
BEAMFORMING => Some(true),
59
ECHO_CANCELLATION => None,
63
60
_ => None,
64
61
}
65
62
}
@@ -85,7 +82,7 @@ mod tests {
85
82
assert_eq!(wanted_state(guid(ECHO_CANCELLATION)), None);
86
83
assert_eq!(wanted_state(0x1234), None);
87
84
let echo = MicEffect { id: guid(ECHO_CANCELLATION), enabled: true, can_set: true };
88
assert!(echo.is_echo_cancellation() && echo.change().is_none());
85
assert!(echo.change().is_none());
89
86
let deep_noise = MicEffect { id: guid(DEEP_NOISE_SUPPRESSION), enabled: true, can_set: true };
90
87
assert_eq!(deep_noise.change(), Some(false));
91
88
assert_eq!(MicEffect { can_set: false, ..deep_noise }.change(), None);
@@ -10,10 +10,6 @@ impl MicEffect {10
effect_name(self.id)10
effect_name(self.id)11
}11
}12
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.13
/// 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> {14
pub fn change(&self) -> Option<bool> {19
wanted_state(self.id).filter(|wanted| self.can_set && *wanted != self.enabled)15
wanted_state(self.id).filter(|wanted| self.can_set && *wanted != self.enabled)@@ -55,11 +51,12 @@ fn known_prefix(guid: u128) -> Option<u32> {55
}51
}56
52
57
/// DeepFilterNet and AGC2 replace the Windows noise, gain and compression stages, stacking them muffles speech.53
/// 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.54
/// The Windows echo canceller stays: it has the exact speaker signal; AEC3 after it removes the rest before AGC2 lifts it.59
pub fn wanted_state(guid: u128) -> Option<bool> {55
pub fn wanted_state(guid: u128) -> Option<bool> {60
match known_prefix(guid)? {56
match known_prefix(guid)? {61
NOISE_SUPPRESSION | DEEP_NOISE_SUPPRESSION | GAIN_CONTROL | RANGE_COMPRESSION => Some(false),57
NOISE_SUPPRESSION | DEEP_NOISE_SUPPRESSION | GAIN_CONTROL | RANGE_COMPRESSION => Some(false),62
BEAMFORMING => Some(true),58
BEAMFORMING => Some(true),59
ECHO_CANCELLATION => None,63
_ => None,60
_ => None,64
}61
}65
}62
}@@ -85,7 +82,7 @@ mod tests {85
assert_eq!(wanted_state(guid(ECHO_CANCELLATION)), None);82
assert_eq!(wanted_state(guid(ECHO_CANCELLATION)), None);86
assert_eq!(wanted_state(0x1234), None);83
assert_eq!(wanted_state(0x1234), None);87
let echo = MicEffect { id: guid(ECHO_CANCELLATION), enabled: true, can_set: true };84
let echo = MicEffect { id: guid(ECHO_CANCELLATION), enabled: true, can_set: true };88
assert!(echo.is_echo_cancellation() && echo.change().is_none());85
assert!(echo.change().is_none());89
let deep_noise = MicEffect { id: guid(DEEP_NOISE_SUPPRESSION), enabled: true, can_set: true };86
let deep_noise = MicEffect { id: guid(DEEP_NOISE_SUPPRESSION), enabled: true, can_set: true };90
assert_eq!(deep_noise.change(), Some(false));87
assert_eq!(deep_noise.change(), Some(false));91
assert_eq!(MicEffect { can_set: false, ..deep_noise }.change(), None);88
assert_eq!(MicEffect { can_set: false, ..deep_noise }.change(), None);@@ -56,9 +56,6 @@ impl ApmConfig {
56
56
.then(|| AudioProcessingModule::new(self.echo_canceller, false, false, self.noise_suppression))
57
57
}
58
58
59
pub fn gain_module(self) -> Option<AudioProcessingModule> {
60
self.gain_controller.then(|| AudioProcessingModule::new(false, true, false, false))
61
}
62
59
}
63
60
64
61
impl MicSettings {
@@ -110,16 +107,6 @@ mod tests {
110
107
);
111
108
}
112
109
113
#[test]
114
fn gain_runs_in_its_own_module_after_the_front_stages() {
115
let config = MicSettings::default().apm_config();
116
assert!(config.front_module().is_some());
117
assert!(config.gain_module().is_some());
118
let music = MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.apm_config();
119
assert!(music.front_module().is_some());
120
assert!(music.gain_module().is_none());
121
}
122
123
110
#[test]
124
111
fn only_auto_outside_music_mode_runs_the_ml_stage() {
125
112
assert!(MicSettings::default().ml_noise_suppression());
@@ -144,7 +131,6 @@ mod tests {
144
131
assert!(!settings.uses_device_track());
145
132
assert!(settings.apm_config().is_passthrough());
146
133
assert!(settings.apm_config().front_module().is_none());
147
assert!(settings.apm_config().gain_module().is_none());
148
134
}
149
135
150
136
#[test]
@@ -56,9 +56,6 @@ impl ApmConfig {56
.then(|| AudioProcessingModule::new(self.echo_canceller, false, false, 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> {60
self.gain_controller.then(|| AudioProcessingModule::new(false, true, false, false))61
}62
}59
}63
60
64
impl MicSettings {61
impl MicSettings {@@ -110,16 +107,6 @@ mod tests {110
);107
);111
}108
}112
109
113
#[test]114
fn gain_runs_in_its_own_module_after_the_front_stages() {115
let config = MicSettings::default().apm_config();116
assert!(config.front_module().is_some());117
assert!(config.gain_module().is_some());118
let music = MicSettings { noise_suppression: NoiseSuppression::Auto, music_mode: true }.apm_config();119
assert!(music.front_module().is_some());120
assert!(music.gain_module().is_none());121
}122
123
#[test]110
#[test]124
fn only_auto_outside_music_mode_runs_the_ml_stage() {111
fn only_auto_outside_music_mode_runs_the_ml_stage() {125
assert!(MicSettings::default().ml_noise_suppression());112
assert!(MicSettings::default().ml_noise_suppression());@@ -144,7 +131,6 @@ mod tests {144
assert!(!settings.uses_device_track());131
assert!(!settings.uses_device_track());145
assert!(settings.apm_config().is_passthrough());132
assert!(settings.apm_config().is_passthrough());146
assert!(settings.apm_config().front_module().is_none());133
assert!(settings.apm_config().front_module().is_none());147
assert!(settings.apm_config().gain_module().is_none());148
}134
}149
135
150
#[test]136
#[test]@@ -137,7 +137,6 @@ 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;
141
140
let mut microphone_source = None;
142
141
let (microphone, computer, loopback) = if mode == AudioMode::Platform {
143
142
let computer_queue = SampleQueue::default();
@@ -153,7 +152,6 @@ impl SoftwareAudio {
153
152
let microphone = match start_microphone(input, microphone_queue.clone()) {
154
153
Ok(started) => {
155
154
microphone_source = Some(started.source);
156
processing.echo_canceller &= !started.os_echo_cancellation;
157
155
captures.push(started.capture);
158
156
FrameSource::Captured(microphone_queue)
159
157
}
@@ -186,7 +184,7 @@ impl SoftwareAudio {
186
184
let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));
187
185
let running = Arc::new(AtomicBool::new(true));
188
186
let feeder = Feeder {
189
processing,
187
processing: plan.processing,
190
188
ml_noise: plan.ml_noise,
191
189
source,
192
190
microphone,
@@ -137,7 +137,6 @@ 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;141
let mut microphone_source = None;140
let mut microphone_source = None;142
let (microphone, computer, loopback) = if mode == AudioMode::Platform {141
let (microphone, computer, loopback) = if mode == AudioMode::Platform {143
let computer_queue = SampleQueue::default();142
let computer_queue = SampleQueue::default();@@ -153,7 +152,6 @@ impl SoftwareAudio {153
let microphone = match start_microphone(input, microphone_queue.clone()) {152
let microphone = match start_microphone(input, microphone_queue.clone()) {154
Ok(started) => {153
Ok(started) => {155
microphone_source = Some(started.source);154
microphone_source = Some(started.source);156
processing.echo_canceller &= !started.os_echo_cancellation;157
captures.push(started.capture);155
captures.push(started.capture);158
FrameSource::Captured(microphone_queue)156
FrameSource::Captured(microphone_queue)159
}157
}@@ -186,7 +184,7 @@ impl SoftwareAudio {186
let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));184
let microphone_muted = Arc::new(AtomicBool::new(microphone_muted));187
let running = Arc::new(AtomicBool::new(true));185
let running = Arc::new(AtomicBool::new(true));188
let feeder = Feeder {186
let feeder = Feeder {189
processing,187
processing: plan.processing,190
ml_noise: plan.ml_noise,188
ml_noise: plan.ml_noise,191
source,189
source,192
microphone,190
microphone,@@ -43,7 +43,6 @@ 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,
47
46
}
48
47
49
48
#[cfg(windows)]
@@ -54,12 +53,11 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic
54
53
Ok(MicrophoneStart {
55
54
capture,
56
55
source: format!("wasapi communications ({name}), windows effects: {}", active.join(", ")),
57
os_echo_cancellation: effects.iter().any(|effect| effect.is_echo_cancellation() && effect.enabled),
58
56
})
59
57
}
60
58
Err(error) => {
61
59
let capture = start_cpal_microphone(choice, queue)?;
62
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}"), os_echo_cancellation: false })
60
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })
63
61
}
64
62
}
65
63
}
@@ -67,7 +65,7 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic
67
65
#[cfg(not(windows))]
68
66
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
69
67
let capture = start_cpal_microphone(choice, queue)?;
70
Ok(MicrophoneStart { capture, source: "cpal".into(), os_echo_cancellation: false })
68
Ok(MicrophoneStart { capture, source: "cpal".into() })
71
69
}
72
70
73
71
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
@@ -43,7 +43,6 @@ 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,47
}46
}48
47
49
#[cfg(windows)]48
#[cfg(windows)]@@ -54,12 +53,11 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic54
Ok(MicrophoneStart {53
Ok(MicrophoneStart {55
capture,54
capture,56
source: format!("wasapi communications ({name}), windows effects: {}", active.join(", ")),55
source: format!("wasapi communications ({name}), windows effects: {}", active.join(", ")),57
os_echo_cancellation: effects.iter().any(|effect| effect.is_echo_cancellation() && effect.enabled),58
})56
})59
}57
}60
Err(error) => {58
Err(error) => {61
let capture = start_cpal_microphone(choice, queue)?;59
let capture = start_cpal_microphone(choice, queue)?;62
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}"), os_echo_cancellation: false })60
Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })63
}61
}64
}62
}65
}63
}@@ -67,7 +65,7 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic67
#[cfg(not(windows))]65
#[cfg(not(windows))]68
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {66
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {69
let capture = start_cpal_microphone(choice, queue)?;67
let capture = start_cpal_microphone(choice, queue)?;70
Ok(MicrophoneStart { capture, source: "cpal".into(), os_echo_cancellation: false })68
Ok(MicrophoneStart { capture, source: "cpal".into() })71
}69
}72
70
73
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {71
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {@@ -66,7 +66,7 @@ pub struct StageDumps {
66
66
}
67
67
68
68
impl StageDumps {
69
pub const STAGES: [&str; 4] = ["1-raw", "2-echo-highpass", "3-noise", "4-gain"];
69
pub const STAGES: [&str; 5] = ["0-far-end", "1-raw", "2-echo-highpass", "3-gain", "4-noise-gain"];
70
70
71
71
pub fn from_env() -> Option<StageDumps> {
72
72
let directory = PathBuf::from(std::env::var_os(AUDIO_DUMP_ENV)?);
@@ -113,11 +113,11 @@ mod tests {
113
113
fn every_stage_gets_its_own_file() {
114
114
let directory = tempfile::tempdir().unwrap();
115
115
let mut dumps = StageDumps::create(directory.path()).unwrap();
116
dumps.write(3, &[5]);
116
dumps.write(4, &[5]);
117
117
drop(dumps);
118
118
let names: Vec<String> =
119
119
std::fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().into_string().unwrap()).collect();
120
120
assert_eq!(names.len(), StageDumps::STAGES.len());
121
assert!(names.iter().any(|name| name.ends_with("4-gain.wav")));
121
assert!(names.iter().any(|name| name.ends_with("4-noise-gain.wav")));
122
122
}
123
123
}
@@ -66,7 +66,7 @@ pub struct StageDumps {66
}66
}67
67
68
impl StageDumps {68
impl StageDumps {69
pub const STAGES: [&str; 4] = ["1-raw", "2-echo-highpass", "3-noise", "4-gain"];69
pub const STAGES: [&str; 5] = ["0-far-end", "1-raw", "2-echo-highpass", "3-gain", "4-noise-gain"];70
70
71
pub fn from_env() -> Option<StageDumps> {71
pub fn from_env() -> Option<StageDumps> {72
let directory = PathBuf::from(std::env::var_os(AUDIO_DUMP_ENV)?);72
let directory = PathBuf::from(std::env::var_os(AUDIO_DUMP_ENV)?);@@ -113,11 +113,11 @@ mod tests {113
fn every_stage_gets_its_own_file() {113
fn every_stage_gets_its_own_file() {114
let directory = tempfile::tempdir().unwrap();114
let directory = tempfile::tempdir().unwrap();115
let mut dumps = StageDumps::create(directory.path()).unwrap();115
let mut dumps = StageDumps::create(directory.path()).unwrap();116
dumps.write(3, &[5]);116
dumps.write(4, &[5]);117
drop(dumps);117
drop(dumps);118
let names: Vec<String> =118
let names: Vec<String> =119
std::fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().into_string().unwrap()).collect();119
std::fs::read_dir(directory.path()).unwrap().map(|entry| entry.unwrap().file_name().into_string().unwrap()).collect();120
assert_eq!(names.len(), StageDumps::STAGES.len());120
assert_eq!(names.len(), StageDumps::STAGES.len());121
assert!(names.iter().any(|name| name.ends_with("4-gain.wav")));121
assert!(names.iter().any(|name| name.ends_with("4-noise-gain.wav")));122
}122
}123
}123
}@@ -37,9 +37,6 @@ struct AudioProcessingConfig {
37
37
config.echo_canceller.enabled = echo_canceller_enabled;
38
38
config.gain_controller2.enabled = gain_controller_enabled;
39
39
config.gain_controller2.adaptive_digital.enabled = gain_controller_enabled;
40
// Speech settles near -16 dBFS like Teams instead of AGC2's -22 dBFS; the limiter after the fixed gain keeps peaks below -1 dBFS.
41
config.gain_controller2.adaptive_digital.initial_gain_db = 0.0f;
42
config.gain_controller2.fixed_digital.gain_db = gain_controller_enabled ? 6.0f : 0.0f;
43
40
config.high_pass_filter.enabled = high_pass_filter_enabled;
44
41
config.noise_suppression.enabled = noise_suppression_enabled;
45
42
return config;
@@ -49,6 +46,7 @@ struct AudioProcessingConfig {
49
46
class AudioProcessingModule {
50
47
public:
51
48
AudioProcessingModule(const AudioProcessingConfig& config);
49
AudioProcessingModule(const webrtc::AudioProcessing::Config& config);
52
50
53
51
int process_stream(const int16_t* src,
54
52
size_t src_len,
@@ -76,4 +74,8 @@ std::unique_ptr<AudioProcessingModule> create_apm(
76
74
bool high_pass_filter_enabled,
77
75
bool noise_suppression_enabled);
78
76
77
std::unique_ptr<AudioProcessingModule> create_gain_apm(float initial_gain_db,
78
float fixed_gain_db,
79
float max_gain_change_db_per_second);
80
79
81
} // namespace livekit_ffi
@@ -37,9 +37,6 @@ struct AudioProcessingConfig {37
config.echo_canceller.enabled = echo_canceller_enabled;37
config.echo_canceller.enabled = echo_canceller_enabled;38
config.gain_controller2.enabled = gain_controller_enabled;38
config.gain_controller2.enabled = gain_controller_enabled;39
config.gain_controller2.adaptive_digital.enabled = gain_controller_enabled;39
config.gain_controller2.adaptive_digital.enabled = gain_controller_enabled;40
// Speech settles near -16 dBFS like Teams instead of AGC2's -22 dBFS; the limiter after the fixed gain keeps peaks below -1 dBFS.41
config.gain_controller2.adaptive_digital.initial_gain_db = 0.0f;42
config.gain_controller2.fixed_digital.gain_db = gain_controller_enabled ? 6.0f : 0.0f;43
config.high_pass_filter.enabled = high_pass_filter_enabled;40
config.high_pass_filter.enabled = high_pass_filter_enabled;44
config.noise_suppression.enabled = noise_suppression_enabled;41
config.noise_suppression.enabled = noise_suppression_enabled;45
return config;42
return config;@@ -49,6 +46,7 @@ struct AudioProcessingConfig {49
class AudioProcessingModule {46
class AudioProcessingModule {50
public:47
public:51
AudioProcessingModule(const AudioProcessingConfig& config);48
AudioProcessingModule(const AudioProcessingConfig& config);49
AudioProcessingModule(const webrtc::AudioProcessing::Config& config);52
50
53
int process_stream(const int16_t* src,51
int process_stream(const int16_t* src,54
size_t src_len,52
size_t src_len,@@ -76,4 +74,8 @@ std::unique_ptr<AudioProcessingModule> create_apm(76
bool high_pass_filter_enabled,74
bool high_pass_filter_enabled,77
bool noise_suppression_enabled);75
bool noise_suppression_enabled);78
76
77
std::unique_ptr<AudioProcessingModule> create_gain_apm(float initial_gain_db,78
float fixed_gain_db,79
float max_gain_change_db_per_second);80
79
} // namespace livekit_ffi81
} // namespace livekit_ffi@@ -25,11 +25,15 @@
25
25
namespace livekit_ffi {
26
26
27
27
AudioProcessingModule::AudioProcessingModule(
28
const AudioProcessingConfig& config) {
28
const AudioProcessingConfig& config)
29
: AudioProcessingModule(config.ToWebrtcConfig()) {}
30
31
AudioProcessingModule::AudioProcessingModule(
32
const webrtc::AudioProcessing::Config& config) {
29
33
apm_ = webrtc::BuiltinAudioProcessingBuilder()
30
34
.Build(webrtc::CreateEnvironment());
31
35
32
apm_->ApplyConfig(config.ToWebrtcConfig());
36
apm_->ApplyConfig(config);
33
37
apm_->Initialize();
34
38
}
35
39
@@ -70,4 +74,18 @@ std::unique_ptr<AudioProcessingModule> create_apm(
70
74
return std::make_unique<AudioProcessingModule>(config);
71
75
}
72
76
77
std::unique_ptr<AudioProcessingModule> create_gain_apm(
78
float initial_gain_db,
79
float fixed_gain_db,
80
float max_gain_change_db_per_second) {
81
webrtc::AudioProcessing::Config config;
82
config.gain_controller2.enabled = true;
83
config.gain_controller2.adaptive_digital.enabled = true;
84
config.gain_controller2.adaptive_digital.initial_gain_db = initial_gain_db;
85
config.gain_controller2.adaptive_digital.max_gain_change_db_per_second =
86
max_gain_change_db_per_second;
87
config.gain_controller2.fixed_digital.gain_db = fixed_gain_db;
88
return std::make_unique<AudioProcessingModule>(config);
89
}
90
73
91
} // namespace livekit_ffi
@@ -25,11 +25,15 @@25
namespace livekit_ffi {25
namespace livekit_ffi {26
26
27
AudioProcessingModule::AudioProcessingModule(27
AudioProcessingModule::AudioProcessingModule(28
const AudioProcessingConfig& config) {28
const AudioProcessingConfig& config)29
: AudioProcessingModule(config.ToWebrtcConfig()) {}30
31
AudioProcessingModule::AudioProcessingModule(32
const webrtc::AudioProcessing::Config& config) {29
apm_ = webrtc::BuiltinAudioProcessingBuilder()33
apm_ = webrtc::BuiltinAudioProcessingBuilder()30
.Build(webrtc::CreateEnvironment());34
.Build(webrtc::CreateEnvironment());31
35
32
apm_->ApplyConfig(config.ToWebrtcConfig());36
apm_->ApplyConfig(config);33
apm_->Initialize();37
apm_->Initialize();34
}38
}35
39
@@ -70,4 +74,18 @@ std::unique_ptr<AudioProcessingModule> create_apm(70
return std::make_unique<AudioProcessingModule>(config);74
return std::make_unique<AudioProcessingModule>(config);71
}75
}72
76
77
std::unique_ptr<AudioProcessingModule> create_gain_apm(78
float initial_gain_db,79
float fixed_gain_db,80
float max_gain_change_db_per_second) {81
webrtc::AudioProcessing::Config config;82
config.gain_controller2.enabled = true;83
config.gain_controller2.adaptive_digital.enabled = true;84
config.gain_controller2.adaptive_digital.initial_gain_db = initial_gain_db;85
config.gain_controller2.adaptive_digital.max_gain_change_db_per_second =86
max_gain_change_db_per_second;87
config.gain_controller2.fixed_digital.gain_db = fixed_gain_db;88
return std::make_unique<AudioProcessingModule>(config);89
}90
73
} // namespace livekit_ffi91
} // namespace livekit_ffi@@ -49,6 +49,12 @@ pub mod ffi {
49
49
high_pass_filter_enabled: bool,
50
50
noise_suppression_enabled: bool,
51
51
) -> UniquePtr<AudioProcessingModule>;
52
53
fn create_gain_apm(
54
initial_gain_db: f32,
55
fixed_gain_db: f32,
56
max_gain_change_db_per_second: f32,
57
) -> UniquePtr<AudioProcessingModule>;
52
58
}
53
59
}
54
60
@@ -49,6 +49,12 @@ pub mod ffi {49
high_pass_filter_enabled: bool,49
high_pass_filter_enabled: bool,50
noise_suppression_enabled: bool,50
noise_suppression_enabled: bool,51
) -> UniquePtr<AudioProcessingModule>;51
) -> UniquePtr<AudioProcessingModule>;52
53
fn create_gain_apm(54
initial_gain_db: f32,55
fixed_gain_db: f32,56
max_gain_change_db_per_second: f32,57
) -> UniquePtr<AudioProcessingModule>;52
}58
}53
}59
}54
60