BlueGit

ict rusty-teams

Files

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

mic_chain.rs

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