Skip to main content

vector_calls/
gate.rs

1//! A voice Channel's member sends only while speaking (CORD-07 ยง8); the rest of the
2//! time a muted frame keeps their liveness count moving at a fraction of the bytes.
3
4use crate::FRAME_MS;
5
6/// The level counted as speech, on the meters' -60 dBFS to 0 scale: the stage's
7/// speaking ring lights at the same.
8pub const SPEECH_LEVEL: f32 = 0.15;
9/// How long sending goes on after speech stops, so word endings and short pauses stay whole.
10pub const SPEECH_HANGOVER_MS: u32 = 400;
11
12#[derive(Default)]
13pub struct SpeechGate {
14    hang: u32,
15}
16
17impl SpeechGate {
18    /// Once per frame, with its level: whether it goes out as audio. The first frame at
19    /// speech level opens the gate.
20    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}