| 1 | use std::{collections::VecDeque, time::Duration}; |
| 2 | |
| 3 | use instant::Instant; |
| 4 | |
| 5 | /// How much audio one level covers, and so how often the waveform takes a |
| 6 | /// step: about the pace of a syllable, so the bars follow speech without |
| 7 | /// racing past. |
| 8 | pub(super) const LEVEL_INTERVAL: Duration = Duration::from_millis(80); |
| 9 | |
| 10 | /// How many recent levels are kept: enough to fill a wide waveform (about |
| 11 | /// twenty seconds of audio). |
| 12 | pub(super) const LEVEL_HISTORY: usize = 256; |
| 13 | |
| 14 | /// How far behind the newest level the waveform's playhead runs, in levels. |
| 15 | /// Levels arrive in uneven bursts as the audio device hands over its buffers. |
| 16 | /// Between two arrivals the playhead advances a whole level, so it must run |
| 17 | /// more than one level behind to never catch up with the newest bar; the rest |
| 18 | /// absorbs late and bunched buffers. The bars then scroll at an even pace and |
| 19 | /// each new one slides in from past the trailing edge (about 140 ms later |
| 20 | /// than the sound). |
| 21 | const PLAYHEAD_LAG: f64 = 1.75; |
| 22 | |
| 23 | /// How much of each level's arrival error the playhead's phase corrects: |
| 24 | /// small enough that one late buffer does not jerk the waveform. |
| 25 | const PLAYHEAD_PHASE_GAIN: f64 = 0.1; |
| 26 | |
| 27 | /// How much each arrival error adjusts the playhead's pace, in seconds per |
| 28 | /// level per second of error, so it settles on the pace levels actually |
| 29 | /// arrive at (a device running slow or a timer firing late) instead of |
| 30 | /// drifting away from them. |
| 31 | const PLAYHEAD_PACE_GAIN: f64 = 0.01; |
| 32 | |
| 33 | /// How far ahead of the playhead levels may pile up before the waveform shows |
| 34 | /// them anyway, in levels. |
| 35 | const PLAYHEAD_MAX_LEAD: f32 = 3.; |
| 36 | |
| 37 | /// Raw levels below this are background noise and read as silence, so a quiet |
| 38 | /// room shows a calm baseline instead of flickering bars. |
| 39 | const NOISE_FLOOR: f32 = 0.06; |
| 40 | |
| 41 | /// How far a level moves toward a louder reading per step: almost at once, so |
| 42 | /// peaks pop. |
| 43 | const ATTACK: f32 = 0.85; |
| 44 | |
| 45 | /// How far a level moves toward a quieter reading per step: slowly, so bars |
| 46 | /// fall back smoothly. |
| 47 | const RELEASE: f32 = 0.3; |
| 48 | |
| 49 | /// Turns a stream of PCM into smoothed input levels, one per |
| 50 | /// [`LEVEL_INTERVAL`] of audio, carrying partial intervals across pushes. |
| 51 | pub(super) struct LevelMeter { |
| 52 | /// Samples per level: [`LEVEL_INTERVAL`] at the stream's rate and channels. |
| 53 | window: usize, |
| 54 | sum: f64, |
| 55 | count: usize, |
| 56 | smoothed: f32, |
| 57 | levels: VecDeque<f32>, |
| 58 | /// Levels recorded since the reset, including those dropped from history. |
| 59 | recorded: u64, |
| 60 | /// When level zero would have arrived on the playhead's even clock; `None` |
| 61 | /// until the first level. |
| 62 | anchor: Option<Instant>, |
| 63 | /// The playhead's pace in seconds per level: [`LEVEL_INTERVAL`], tuned to |
| 64 | /// how fast levels actually arrive. |
| 65 | pace: f64, |
| 66 | } |
| 67 | |
| 68 | impl LevelMeter { |
| 69 | pub(super) fn new() -> Self { |
| 70 | Self { |
| 71 | window: window_for(16_000, 1), |
| 72 | sum: 0., |
| 73 | count: 0, |
| 74 | smoothed: 0., |
| 75 | levels: VecDeque::with_capacity(LEVEL_HISTORY), |
| 76 | recorded: 0, |
| 77 | anchor: None, |
| 78 | pace: LEVEL_INTERVAL.as_secs_f64(), |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /// Clear the history and measure a stream of `sample_rate` × `channels`. |
| 83 | pub(super) fn reset(&mut self, sample_rate: u32, channels: u16) { |
| 84 | *self = Self { |
| 85 | window: window_for(sample_rate, channels), |
| 86 | ..Self::new() |
| 87 | }; |
| 88 | } |
| 89 | |
| 90 | /// Measure `samples`; returns whether a new level was recorded. |
| 91 | pub(super) fn push(&mut self, samples: &[i16]) -> bool { |
| 92 | self.push_at(samples, Instant::now()) |
| 93 | } |
| 94 | |
| 95 | /// [`Self::push`] with the time the samples arrived. |
| 96 | pub(super) fn push_at(&mut self, samples: &[i16], now: Instant) -> bool { |
| 97 | let mut recorded = false; |
| 98 | for &sample in samples { |
| 99 | let sample = sample as f64 / i16::MAX as f64; |
| 100 | self.sum += sample * sample; |
| 101 | self.count += 1; |
| 102 | if self.count == self.window { |
| 103 | let raw = gate(level_of_rms((self.sum / self.count as f64).sqrt())); |
| 104 | self.smoothed = smooth(self.smoothed, raw); |
| 105 | if self.levels.len() == LEVEL_HISTORY { |
| 106 | self.levels.pop_front(); |
| 107 | } |
| 108 | self.levels.push_back(self.smoothed); |
| 109 | self.sum = 0.; |
| 110 | self.count = 0; |
| 111 | self.recorded += 1; |
| 112 | self.align_playhead(now); |
| 113 | recorded = true; |
| 114 | } |
| 115 | } |
| 116 | recorded |
| 117 | } |
| 118 | |
| 119 | /// Nudge the playhead's clock toward the arrival of the level just |
| 120 | /// recorded: its pace toward the pace levels arrive at, its phase toward |
| 121 | /// this arrival. Changing the pace keeps the playhead where it is, so the |
| 122 | /// waveform never jumps. |
| 123 | fn align_playhead(&mut self, now: Instant) { |
| 124 | let Some(anchor) = self.anchor else { |
| 125 | // The first level arrives on time by definition. |
| 126 | self.anchor = now.checked_sub(LEVEL_INTERVAL); |
| 127 | return; |
| 128 | }; |
| 129 | let error = signed_secs(now, anchor) - self.recorded as f64 * self.pace; |
| 130 | let interval = LEVEL_INTERVAL.as_secs_f64(); |
| 131 | let pace = (self.pace + error * PLAYHEAD_PACE_GAIN).clamp(interval / 2., interval * 2.); |
| 132 | // Re-anchor so the playhead's position at `now` is unchanged by the new pace. |
| 133 | let elapsed_levels = signed_secs(now, anchor) / self.pace; |
| 134 | let anchor = shift_instant(now, -elapsed_levels * pace); |
| 135 | self.pace = pace; |
| 136 | self.anchor = Some(shift_instant(anchor, error * PLAYHEAD_PHASE_GAIN)); |
| 137 | } |
| 138 | |
| 139 | /// Where the waveform should draw the newest level at `now`, in levels past |
| 140 | /// the trailing edge (0.0 at the edge, positive further out). The playhead |
| 141 | /// advances at an even pace of about one level per [`LEVEL_INTERVAL`], |
| 142 | /// behind the newest level; `None` before the first level. |
| 143 | pub(super) fn lead_at(&self, now: Instant) -> Option<f32> { |
| 144 | let anchor = self.anchor?; |
| 145 | let playhead = signed_secs(now, anchor) / self.pace - PLAYHEAD_LAG; |
| 146 | let lead = (self.recorded as f64 - playhead) as f32; |
| 147 | // Never draw past the newest level, and never fall so far behind that a |
| 148 | // burst of levels stays hidden. |
| 149 | Some(lead.clamp(0., PLAYHEAD_MAX_LEAD)) |
| 150 | } |
| 151 | |
| 152 | pub(super) fn levels(&self) -> impl ExactSizeIterator<Item = f32> + '_ { |
| 153 | self.levels.iter().copied() |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /// `later - earlier` in seconds, negative when `later` is earlier. |
| 158 | fn signed_secs(later: Instant, earlier: Instant) -> f64 { |
| 159 | match later.checked_duration_since(earlier) { |
| 160 | Some(elapsed) => elapsed.as_secs_f64(), |
| 161 | None => -earlier.duration_since(later).as_secs_f64(), |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// `instant` moved by `secs`, forward when positive. |
| 166 | fn shift_instant(instant: Instant, secs: f64) -> Instant { |
| 167 | let by = Duration::from_secs_f64(secs.abs()); |
| 168 | if secs >= 0. { |
| 169 | instant + by |
| 170 | } else { |
| 171 | instant.checked_sub(by).unwrap_or(instant) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | fn window_for(sample_rate: u32, channels: u16) -> usize { |
| 176 | let per_second = sample_rate as u128 * channels.max(1) as u128; |
| 177 | ((per_second * LEVEL_INTERVAL.as_millis() / 1_000) as usize).max(1) |
| 178 | } |
| 179 | |
| 180 | /// The loudness of an RMS amplitude in `0.0..=1.0`, mapping -50 dBFS..0 dBFS |
| 181 | /// linearly so that normal speech fills most of the range. |
| 182 | pub(super) fn level_of_rms(rms: f64) -> f32 { |
| 183 | if rms <= 0. { |
| 184 | return 0.; |
| 185 | } |
| 186 | let db = 20. * rms.log10(); |
| 187 | ((db + 50.) / 50.).clamp(0., 1.) as f32 |
| 188 | } |
| 189 | |
| 190 | fn gate(level: f32) -> f32 { |
| 191 | if level < NOISE_FLOOR { 0. } else { level } |
| 192 | } |
| 193 | |
| 194 | /// One step of fast-attack, slow-release smoothing from `previous` toward `raw`. |
| 195 | pub(super) fn smooth(previous: f32, raw: f32) -> f32 { |
| 196 | let rate = if raw > previous { ATTACK } else { RELEASE }; |
| 197 | previous + (raw - previous) * rate |
| 198 | } |
| 199 | |
| 200 | #[cfg(test)] |
| 201 | mod tests { |
| 202 | use super::*; |
| 203 | |
| 204 | fn tone(amplitude: i16, len: usize) -> Vec<i16> { |
| 205 | (0..len) |
| 206 | .map(|ix| if ix % 2 == 0 { amplitude } else { -amplitude }) |
| 207 | .collect() |
| 208 | } |
| 209 | |
| 210 | #[test] |
| 211 | fn one_level_per_interval_across_pushes() { |
| 212 | let mut meter = LevelMeter::new(); |
| 213 | meter.reset(16_000, 1); |
| 214 | // Two and a half levels' worth of audio in uneven pushes. |
| 215 | let window = window_for(16_000, 1); |
| 216 | assert!(!meter.push(&tone(1_000, window / 3))); |
| 217 | assert!(meter.push(&tone(1_000, window))); |
| 218 | assert!(meter.push(&tone(1_000, window + window / 6))); |
| 219 | assert_eq!(meter.levels().len(), 2); |
| 220 | assert!(meter.lead_at(Instant::now()).is_some()); |
| 221 | } |
| 222 | |
| 223 | #[test] |
| 224 | fn the_window_follows_the_stream_format() { |
| 225 | // 80 ms of 16 kHz mono, and of 48 kHz stereo. |
| 226 | assert_eq!(window_for(16_000, 1), 1_280); |
| 227 | assert_eq!(window_for(48_000, 2), 7_680); |
| 228 | } |
| 229 | |
| 230 | #[test] |
| 231 | fn peaks_rise_fast_and_fall_slowly() { |
| 232 | let up = smooth(0., 1.); |
| 233 | assert!(up >= 0.85); |
| 234 | let down = smooth(1., 0.); |
| 235 | assert!(down >= 0.65, "{down}"); |
| 236 | assert!(smooth(down, 0.) < down); |
| 237 | } |
| 238 | |
| 239 | #[test] |
| 240 | fn background_noise_reads_as_silence() { |
| 241 | let mut meter = LevelMeter::new(); |
| 242 | meter.reset(16_000, 1); |
| 243 | // -60 dBFS: below the -50 dB floor of the scale. |
| 244 | meter.push(&tone(32, window_for(16_000, 1))); |
| 245 | assert_eq!(meter.levels().next(), Some(0.)); |
| 246 | } |
| 247 | |
| 248 | #[test] |
| 249 | fn level_maps_decibels_to_the_unit_range() { |
| 250 | assert_eq!(level_of_rms(0.), 0.); |
| 251 | assert_eq!(level_of_rms(1.), 1.); |
| 252 | // -20 dBFS sits at 0.6 on the -50..0 dB scale. |
| 253 | assert!((level_of_rms(0.1) - 0.6).abs() < 0.01); |
| 254 | } |
| 255 | |
| 256 | #[test] |
| 257 | fn history_is_bounded() { |
| 258 | let mut meter = LevelMeter::new(); |
| 259 | meter.reset(16_000, 1); |
| 260 | meter.push(&tone(8_000, window_for(16_000, 1) * (LEVEL_HISTORY + 10))); |
| 261 | assert_eq!(meter.levels().len(), LEVEL_HISTORY); |
| 262 | } |
| 263 | |
| 264 | fn level_at(meter: &mut LevelMeter, at: Instant) { |
| 265 | let window = window_for(16_000, 1); |
| 266 | assert!(meter.push_at(&tone(1_000, window), at)); |
| 267 | } |
| 268 | |
| 269 | #[test] |
| 270 | fn the_playhead_moves_at_an_even_pace_between_levels() { |
| 271 | let mut meter = LevelMeter::new(); |
| 272 | meter.reset(16_000, 1); |
| 273 | let start = Instant::now(); |
| 274 | level_at(&mut meter, start); |
| 275 | // Right after a level the newest bar sits past the trailing edge, then |
| 276 | // slides toward it at one level per interval. |
| 277 | let lead = |ms: u64| meter.lead_at(start + Duration::from_millis(ms)).unwrap(); |
| 278 | assert!((lead(0) - 1.75).abs() < 1e-3, "{}", lead(0)); |
| 279 | assert!((lead(40) - 1.25).abs() < 1e-3, "{}", lead(40)); |
| 280 | assert!((lead(80) - 0.75).abs() < 1e-3, "{}", lead(80)); |
| 281 | // Long after the audio stopped arriving, the newest bar rests at the edge. |
| 282 | assert_eq!(lead(1_000), 0.); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn uneven_arrivals_do_not_jerk_the_playhead() { |
| 287 | let mut meter = LevelMeter::new(); |
| 288 | meter.reset(16_000, 1); |
| 289 | let start = Instant::now(); |
| 290 | level_at(&mut meter, start); |
| 291 | // The second level arrives 20 ms early: the playhead barely moves with |
| 292 | // it; the bars stay put and the new one waits further out. |
| 293 | let before = meter.lead_at(start + Duration::from_millis(60)).unwrap(); |
| 294 | level_at(&mut meter, start + Duration::from_millis(60)); |
| 295 | let after = meter.lead_at(start + Duration::from_millis(60)).unwrap(); |
| 296 | assert!((after - before - 1.).abs() < 0.05, "{before} → {after}"); |
| 297 | } |
| 298 | |
| 299 | #[test] |
| 300 | fn the_playhead_settles_on_the_pace_levels_arrive_at() { |
| 301 | for interval_ms in [72u64, 92] { |
| 302 | let mut meter = LevelMeter::new(); |
| 303 | meter.reset(16_000, 1); |
| 304 | let start = Instant::now(); |
| 305 | // Levels 10 % fast, then 15 % slow, as a late timer or a slow device would. |
| 306 | for ix in 0..300u64 { |
| 307 | level_at(&mut meter, start + Duration::from_millis(ix * interval_ms)); |
| 308 | } |
| 309 | let last = start + Duration::from_millis(299 * interval_ms); |
| 310 | let half = Duration::from_millis(interval_ms / 2); |
| 311 | // The newest bar arrives the usual lag behind the playhead and is |
| 312 | // still out past the edge half an interval later: the waveform |
| 313 | // neither runs ahead and stalls nor falls behind. |
| 314 | let at_arrival = meter.lead_at(last).unwrap(); |
| 315 | let between = meter.lead_at(last + half).unwrap(); |
| 316 | assert!( |
| 317 | (at_arrival - 1.75).abs() < 0.1, |
| 318 | "{interval_ms} ms: {at_arrival}" |
| 319 | ); |
| 320 | assert!((between - 1.25).abs() < 0.1, "{interval_ms} ms: {between}"); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn nothing_leads_before_the_first_level() { |
| 326 | let mut meter = LevelMeter::new(); |
| 327 | meter.reset(16_000, 1); |
| 328 | assert_eq!(meter.lead_at(Instant::now()), None); |
| 329 | } |
| 330 | } |