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