1use crate::FRAME_MS;
5
6pub const SPEECH_LEVEL: f32 = 0.15;
9pub const SPEECH_HANGOVER_MS: u32 = 400;
11
12#[derive(Default)]
13pub struct SpeechGate {
14 hang: u32,
15}
16
17impl SpeechGate {
18 pub fn open(&mut self, level: f32) -> bool {
21 if level > SPEECH_LEVEL {
22 self.hang = SPEECH_HANGOVER_MS / FRAME_MS;
23 } else {
24 self.hang = self.hang.saturating_sub(1);
25 }
26 self.hang > 0
27 }
28}
29
30#[cfg(test)]
31mod tests {
32 use super::*;
33
34 #[test]
35 fn speech_opens_the_gate_at_once_and_a_hangover_closes_it() {
36 let mut gate = SpeechGate::default();
37 assert!(!gate.open(0.0), "silence sends nothing");
38 assert!(!gate.open(SPEECH_LEVEL), "the threshold itself is not speech");
39 assert!(gate.open(0.4), "the first loud frame goes out");
40 for _ in 1..SPEECH_HANGOVER_MS / FRAME_MS {
41 assert!(gate.open(0.0), "a pause shorter than the hangover keeps sending");
42 }
43 assert!(!gate.open(0.0), "the hangover ends");
44 assert!(gate.open(0.3), "speech again reopens it");
45 }
46}