BlueGit

ict rusty-teams

Files

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

band_meter.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
band_meter.rs 2.5 KiB Download Raw
1use crate::audio::SAMPLE_RATE;
2
3const SPLIT_HERTZ: f32 = 8000.;
4const QUALITY: f32 = std::f32::consts::FRAC_1_SQRT_2;
5const SILENCE_ENERGY: f64 = 1e6;
6
7pub struct HighBandMeter {
8 coefficients: [f32; 5],
9 history: [f32; 4],
10 total_energy: f64,
11 high_energy: f64,
12}
13
14impl Default for HighBandMeter {
15 fn default() -> Self {
16 let omega = 2. * std::f32::consts::PI * SPLIT_HERTZ / SAMPLE_RATE as f32;
17 let alpha = omega.sin() / (2. * QUALITY);
18 let cosine = omega.cos();
19 let a0 = 1. + alpha;
20 let b0 = (1. + cosine) / 2. / a0;
21 HighBandMeter {
22 coefficients: [
23 b0,
24 -(1. + cosine) / a0,
25 b0,
26 -2. * cosine / a0,
27 (1. - alpha) / a0,
28 ],
29 history: [0.; 4],
30 total_energy: 0.,
31 high_energy: 0.,
32 }
33 }
34}
35
36impl HighBandMeter {
37 pub fn add(&mut self, frame: &[i16]) {
38 let [b0, b1, b2, a1, a2] = self.coefficients;
39 for &sample in frame {
40 let input = f32::from(sample);
41 let [x1, x2, y1, y2] = self.history;
42 let output = b0 * input + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
43 self.history = [input, x1, output, y1];
44 self.total_energy += f64::from(input * input);
45 self.high_energy += f64::from(output * output);
46 }
47 }
48
49 pub fn take_share(&mut self) -> Option<f64> {
50 let share =
51 (self.total_energy > SILENCE_ENERGY).then(|| self.high_energy / self.total_energy);
52 self.total_energy = 0.;
53 self.high_energy = 0.;
54 share
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 fn sine(hertz: f32) -> Vec<i16> {
63 (0..SAMPLE_RATE as usize)
64 .map(|index| {
65 ((2. * std::f32::consts::PI * hertz * index as f32 / SAMPLE_RATE as f32).sin()
66 * 8000.) as i16
67 })
68 .collect()
69 }
70
71 #[test]
72 fn wideband_speech_has_nothing_above_eight_kilohertz() {
73 let mut meter = HighBandMeter::default();
74 meter.add(&sine(1000.));
75 assert!(meter.take_share().unwrap() < 0.01);
76 }
77
78 #[test]
79 fn fullband_content_shows_up_above_eight_kilohertz() {
80 let mut meter = HighBandMeter::default();
81 meter.add(&sine(14000.));
82 assert!(meter.take_share().unwrap() > 0.9);
83 }
84
85 #[test]
86 fn silence_reports_nothing() {
87 let mut meter = HighBandMeter::default();
88 meter.add(&[0; 4800]);
89 assert_eq!(meter.take_share(), None);
90 }
91}