| 1 | pub const SPEAKING_THRESHOLD: f32 = 0.02; |
| 2 | pub const SPEAKING_HOLD_TICKS: u32 = 2; |
| 3 | |
| 4 | #[derive(Debug, Clone)] |
| 5 | pub struct SpeakingDetector { |
| 6 | threshold: f32, |
| 7 | hold_ticks: u32, |
| 8 | remaining: u32, |
| 9 | } |
| 10 | |
| 11 | impl Default for SpeakingDetector { |
| 12 | fn default() -> Self { |
| 13 | SpeakingDetector::new(SPEAKING_THRESHOLD, SPEAKING_HOLD_TICKS) |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | impl SpeakingDetector { |
| 18 | pub fn new(threshold: f32, hold_ticks: u32) -> Self { |
| 19 | SpeakingDetector { |
| 20 | threshold, |
| 21 | hold_ticks, |
| 22 | remaining: 0, |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | pub fn update(&mut self, level: f32) -> bool { |
| 27 | if level > self.threshold { |
| 28 | self.remaining = self.hold_ticks; |
| 29 | return true; |
| 30 | } |
| 31 | if self.remaining > 0 { |
| 32 | self.remaining -= 1; |
| 33 | return true; |
| 34 | } |
| 35 | false |
| 36 | } |
| 37 | |
| 38 | pub fn reset(&mut self) { |
| 39 | self.remaining = 0; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | #[cfg(test)] |
| 44 | mod tests { |
| 45 | use super::*; |
| 46 | |
| 47 | #[test] |
| 48 | fn level_above_the_threshold_is_speaking() { |
| 49 | let mut detector = SpeakingDetector::new(0.05, 0); |
| 50 | assert!(!detector.update(0.05)); |
| 51 | assert!(detector.update(0.06)); |
| 52 | assert!(!detector.update(0.0)); |
| 53 | } |
| 54 | |
| 55 | #[test] |
| 56 | fn hold_keeps_the_ring_through_short_pauses() { |
| 57 | let mut detector = SpeakingDetector::new(0.05, 2); |
| 58 | assert!(detector.update(0.5)); |
| 59 | assert!(detector.update(0.0)); |
| 60 | assert!(detector.update(0.0)); |
| 61 | assert!(!detector.update(0.0)); |
| 62 | assert!(detector.update(0.5)); |
| 63 | } |
| 64 | |
| 65 | #[test] |
| 66 | fn reset_clears_the_hold() { |
| 67 | let mut detector = SpeakingDetector::new(0.05, 3); |
| 68 | detector.update(0.5); |
| 69 | detector.reset(); |
| 70 | assert!(!detector.update(0.0)); |
| 71 | } |
| 72 | } |