BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / mic_chain.rs

mic_chain.rs

mic_chain.rs 3.0 KiB Download Raw
1use libwebrtc::native::apm::AudioProcessingModule;
2
3use crate::audio::SAMPLE_RATE;
4use crate::gain_stage::GainStage;
5use crate::mic_processing::ApmConfig;
6use crate::noise_stage::NoiseStage;
7use crate::voice_high_pass::VoiceHighPass;
8use crate::wav_dump::StageDumps;
9
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.
12pub struct MicChain {
13 high_pass: Option<VoiceHighPass>,
14 front: Option<AudioProcessingModule>,
15 ml_noise: Option<NoiseStage>,
16 lift: Option<GainStage>,
17 output_gain: Option<GainStage>,
18 dumps: Option<StageDumps>,
19}
20
21impl MicChain {
22 pub fn new(processing: ApmConfig, ml_noise: bool, dumps: Option<StageDumps>) -> MicChain {
23 if ml_noise {
24 crate::noise_stage::prepare();
25 }
26 MicChain {
27 high_pass: processing.high_pass_filter.then(VoiceHighPass::new),
28 front: processing.front_module(),
29 ml_noise: ml_noise.then(NoiseStage::new),
30 lift: (processing.gain_controller && ml_noise).then(GainStage::lift),
31 output_gain: processing.gain_controller.then(GainStage::output),
32 dumps,
33 }
34 }
35
36 pub fn process_far_end(&mut self, frame: &mut [i16]) {
37 self.dump(0, frame);
38 if let Some(front) = self.front.as_mut() {
39 let _ = front.process_reverse_stream(frame, SAMPLE_RATE as i32, 1);
40 }
41 }
42
43 pub fn process(&mut self, frame: &mut [i16]) {
44 self.dump(1, frame);
45 if let Some(high_pass) = self.high_pass.as_mut() {
46 high_pass.process(frame);
47 }
48 if let Some(front) = self.front.as_mut() {
49 let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);
50 }
51 self.dump(2, frame);
52 if let Some(lift) = self.lift.as_mut() {
53 lift.process(frame);
54 }
55 self.dump(3, frame);
56 if let Some(noise_stage) = self.ml_noise.as_mut() {
57 noise_stage.process_pcm(0, frame);
58 }
59 if let Some(output_gain) = self.output_gain.as_mut() {
60 output_gain.process(frame);
61 }
62 self.dump(4, frame);
63 }
64
65 fn dump(&mut self, stage_index: usize, frame: &[i16]) {
66 if let Some(dumps) = self.dumps.as_mut() {
67 dumps.write(stage_index, frame);
68 }
69 }
70}
71
72#[cfg(test)]
73mod tests {
74 use super::*;
75 use crate::audio::SineGenerator;
76 use crate::mic_processing::MicSettings;
77
78 #[test]
79 fn off_leaves_the_frame_untouched() {
80 let off = MicSettings { noise_suppression: crate::mic_processing::NoiseSuppression::Off, music_mode: false };
81 let mut chain = MicChain::new(off.apm_config(), off.ml_noise_suppression(), None);
82 let mut generator = SineGenerator::new(300.0, 0.2);
83 let original = generator.next_frame();
84 let mut frame = original.clone();
85 chain.process(&mut frame);
86 assert_eq!(frame, original);
87 }
88}