forge
Explore
Log in

Don't you dare go Hollow

Draw voice and stream audio as a live frequency spectrum

Browse files at this commit

d8f98cf90aa0d727dbc3232734c2b7b1a86b2affAhmet Kaan GümüşParent: ebf01d5
  • ui
    • draw voice and stream audio as a live frequency spectrum
Show full message
💄 ui: draw voice and stream audio as a live frequency spectrum
Cargo.tomlmodified+8 -1
@@ -1,6 +1,6 @@
11 [workspace]
22 resolver = "2"
3-members = ["crates/client", "crates/common", "crates/pixel", "crates/server"]
3+members = ["crates/client", "crates/common", "crates/pixel", "crates/spectrum", "crates/server"]
44
55 [profile.dev]
66 debug = "line-tables-only"
@@ -11,6 +11,12 @@ opt-level = 3
1111 [profile.dev.package.pixel]
1212 opt-level = 3
1313
14+[profile.dev.package.spectrum]
15+opt-level = 3
16+
17+[profile.dev.package.rustfft]
18+opt-level = 3
19+
1420 [profile.harness]
1521 inherits = "dev"
1622 opt-level = 3
@@ -30,6 +36,7 @@ unsafe_code = "forbid"
3036 [workspace.dependencies]
3137 common = { path = "crates/common" }
3238 pixel = { path = "crates/pixel" }
39+spectrum = { path = "crates/spectrum" }
3340 tokio = { version = "1.54.1", features = ["full"] }
3441 bitcode = "0.6.9"
3542 quinn = { version = "0.11.12", default-features = false, features = [
crates/client/Cargo.tomlmodified+1 -0
@@ -6,6 +6,7 @@ edition = "2024"
66 [dependencies]
77 common.workspace = true
88 pixel.workspace = true
9+spectrum.workspace = true
910 reed-solomon-simd = "3.1.0"
1011 tokio.workspace = true
1112 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
crates/client/src/gui/chat.rsmodified+1 -1
@@ -256,7 +256,7 @@ pub struct Chat {
256256 const RING_LIMIT: usize = 15;
257257 const RING_INTERVAL: Duration = Duration::from_secs(2);
258258 const VOICE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1);
259-const WAVE_INTERVAL: Duration = Duration::from_millis(50);
259+const WAVE_INTERVAL: Duration = Duration::from_millis(33);
260260 const DEFAULT_USER_VOLUME: f32 = 100.0;
261261
262262 pub struct UserVolume {
crates/client/src/gui/wave.rsmodified+12 -22
@@ -4,37 +4,32 @@ use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px};
44
55 use crate::network::Levels;
66
7-pub const BARS: usize = 16;
8-const SILENT_BARS: usize = 2;
9-const DECAY: f32 = 0.985;
10-const PEAK_FLOOR: f32 = 0.02;
11-const CURVE: f32 = 0.7;
7+const DECAY: f32 = 0.82;
8+const GONE: f32 = 0.02;
129 const AUDIBLE: f32 = 0.1;
1310 const BAR_WIDTH: f32 = 2.;
1411 const MIN_BAR: f32 = 1.5;
1512
1613 pub struct Wave {
1714 bars: VecDeque<f32>,
18- peak: f32,
1915 }
2016
2117 impl Wave {
2218 fn new() -> Self {
2319 Self {
24- bars: VecDeque::from(vec![0.0; BARS]),
25- peak: PEAK_FLOOR,
20+ bars: VecDeque::from(vec![0.0; spectrum::BANDS]),
2621 }
2722 }
2823
29- fn push(&mut self, level: f32) {
30- self.peak = (self.peak * DECAY).max(level).max(PEAK_FLOOR);
31- self.bars.pop_front();
32- self.bars
33- .push_back((level / self.peak).clamp(0.0, 1.0).powf(CURVE));
24+ fn push(&mut self, bands: &[f32]) {
25+ for (index, bar) in self.bars.iter_mut().enumerate() {
26+ let band = bands.get(index).copied().unwrap_or(0.0);
27+ *bar = band.max(*bar * DECAY);
28+ }
3429 }
3530
3631 fn silent(&self) -> bool {
37- self.bars.iter().all(|bar| *bar == 0.0)
32+ self.bars.iter().all(|bar| *bar < GONE)
3833 }
3934 }
4035
@@ -49,14 +44,9 @@ fn advance(waves: &mut HashMap<String, Wave>, levels: Vec<(String, Vec<f32>)>) -
4944 let mut levels: HashMap<String, Vec<f32>> = levels.into_iter().collect();
5045 let ids: HashSet<String> = waves.keys().chain(levels.keys()).cloned().collect();
5146 for id in ids {
52- let incoming = levels
53- .remove(&id)
54- .filter(|incoming| !incoming.is_empty())
55- .unwrap_or_else(|| vec![0.0; SILENT_BARS]);
47+ let bands = levels.remove(&id).unwrap_or_default();
5648 let wave = waves.entry(id.clone()).or_insert_with(Wave::new);
57- for level in incoming {
58- wave.push(level);
59- }
49+ wave.push(&bands);
6050 if wave.silent() {
6151 waves.remove(&id);
6252 }
@@ -96,7 +86,7 @@ impl Waves {
9686 pub fn share(&self, id: &str) -> Option<&VecDeque<f32>> {
9787 self.share
9888 .get(id)
99- .filter(|wave| wave.peak > PEAK_FLOOR || wave.bars.iter().any(|bar| *bar >= AUDIBLE))
89+ .filter(|wave| wave.bars.iter().any(|bar| *bar >= AUDIBLE))
10090 .map(|wave| &wave.bars)
10191 }
10292 }
crates/client/src/media/meter.rsmodified+47 -11
@@ -1,6 +1,8 @@
1-use std::sync::{Arc, Mutex, PoisonError};
1+use std::collections::VecDeque;
2+use std::sync::{Arc, Mutex, OnceLock, PoisonError};
23
3-pub const LEVEL_CAPACITY: usize = 32;
4+use common::constant::VOICE_SAMPLE_RATE;
5+use spectrum::{Analyzer, WINDOW};
46
57 pub fn rms(samples: &[f32]) -> f32 {
68 if samples.is_empty() {
@@ -9,23 +11,57 @@ pub fn rms(samples: &[f32]) -> f32 {
911 (samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32).sqrt()
1012 }
1113
12-pub fn push_level(levels: &mut Vec<f32>, level: f32) {
13- if levels.len() >= LEVEL_CAPACITY {
14- levels.remove(0);
14+fn analyzer() -> &'static Analyzer {
15+ static ANALYZER: OnceLock<Analyzer> = OnceLock::new();
16+ ANALYZER.get_or_init(|| Analyzer::new(VOICE_SAMPLE_RATE))
17+}
18+
19+#[derive(Debug, Default)]
20+pub struct Spectrum {
21+ samples: VecDeque<f32>,
22+ fresh: bool,
23+}
24+
25+impl Spectrum {
26+ pub fn record(&mut self, samples: &[f32], channels: usize) {
27+ for frame in samples.chunks(channels) {
28+ if self.samples.len() >= WINDOW {
29+ self.samples.pop_front();
30+ }
31+ self.samples
32+ .push_back(frame.iter().sum::<f32>() / frame.len() as f32);
33+ }
34+ self.fresh = true;
35+ }
36+
37+ pub fn absorb(&mut self, other: &mut Spectrum) {
38+ if other.fresh {
39+ let samples: Vec<f32> = other.samples.iter().copied().collect();
40+ self.record(&samples, 1);
41+ other.fresh = false;
42+ }
43+ }
44+
45+ pub fn take(&mut self) -> Vec<f32> {
46+ if !std::mem::take(&mut self.fresh) {
47+ return Vec::new();
48+ }
49+ analyzer().bands(self.samples.make_contiguous())
1550 }
16- levels.push(level);
1751 }
1852
1953 #[derive(Debug, Clone, Default)]
20-pub struct Meter(Arc<Mutex<Vec<f32>>>);
54+pub struct Meter(Arc<Mutex<Spectrum>>);
2155
2256 impl Meter {
23- pub fn record(&self, samples: &[f32]) {
24- let mut levels = self.0.lock().unwrap_or_else(PoisonError::into_inner);
25- push_level(&mut levels, rms(samples));
57+ pub fn record(&self, samples: &[f32], channels: usize) {
58+ self.0
59+ .lock()
60+ .unwrap_or_else(PoisonError::into_inner)
61+ .record(samples, channels);
2662 }
2763
2864 pub fn take(&self) -> Vec<f32> {
29- std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner))
65+ self.0.lock().unwrap_or_else(PoisonError::into_inner).take()
3066 }
3167 }
crates/client/src/share/session.rsmodified+2 -2
@@ -417,7 +417,7 @@ fn encode_audio(
417417 for sample in pcm.iter_mut() {
418418 *sample = samples.pop().unwrap_or(0.0);
419419 }
420- meter.record(&pcm);
420+ meter.record(&pcm, SHARE_AUDIO_CHANNELS);
421421 let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else {
422422 continue;
423423 };
@@ -790,7 +790,7 @@ fn flush(
790790 if now - due > LATE_MS {
791791 continue;
792792 }
793- meter.record(&samples);
793+ meter.record(&samples, SHARE_AUDIO_CHANNELS);
794794 for sample in samples {
795795 let _ = ring.push(sample * gain);
796796 }
crates/client/src/voice/engine.rsmodified+9 -11
@@ -12,7 +12,7 @@ use common::{
1212 use ec_opus::{Application, Bandwidth, Decoder, Encoder};
1313
1414 use crate::{
15- media::meter::{push_level, rms},
15+ media::meter::{Spectrum, rms},
1616 settings::{Activation, Profile},
1717 };
1818
@@ -78,7 +78,7 @@ struct Speaker {
7878 previous_transit: Option<f32>,
7979 jitter_ms: f32,
8080 highest: u32,
81- levels: Vec<f32>,
81+ spectrum: Spectrum,
8282 }
8383
8484 #[derive(Debug, Clone, Copy, Default)]
@@ -105,7 +105,7 @@ impl Speaker {
105105 previous_transit: None,
106106 jitter_ms: 0.0,
107107 highest: sequence.wrapping_sub(1),
108- levels: Vec::new(),
108+ spectrum: Spectrum::default(),
109109 }
110110 }
111111
@@ -157,7 +157,7 @@ impl Speaker {
157157 self.previous_transit = None;
158158 return;
159159 };
160- push_level(&mut self.levels, rms(&frame));
160+ self.spectrum.record(&frame, 1);
161161 self.pending.extend(frame);
162162 }
163163 *sample += self.pending.pop_front().unwrap_or(0.0) * gain;
@@ -180,7 +180,7 @@ pub struct Engine {
180180 hangover: u32,
181181 sending: bool,
182182 level_db: f32,
183- sent_levels: Vec<f32>,
183+ sent: Spectrum,
184184 volumes: HashMap<String, f32>,
185185 speakers: HashMap<String, Speaker>,
186186 sent_bytes: usize,
@@ -213,7 +213,7 @@ impl Engine {
213213 hangover: 0,
214214 sending: false,
215215 level_db: SILENT_DB,
216- sent_levels: Vec::new(),
216+ sent: Spectrum::default(),
217217 volumes: HashMap::new(),
218218 speakers: HashMap::new(),
219219 sent_bytes: 0,
@@ -253,7 +253,7 @@ impl Engine {
253253 }
254254
255255 if speaking {
256- push_level(&mut self.sent_levels, loud);
256+ self.sent.record(frame, 1);
257257 }
258258 let mut samples = *frame;
259259 if speaking && !was_sending {
@@ -304,9 +304,7 @@ impl Engine {
304304 }
305305 speaker.last_heard = now;
306306 if payload.is_empty() {
307- for level in std::mem::take(&mut self.sent_levels) {
308- push_level(&mut speaker.levels, level);
309- }
307+ speaker.spectrum.absorb(&mut self.sent);
310308 return;
311309 }
312310 if sequence < speaker.next {
@@ -357,7 +355,7 @@ impl Engine {
357355 self.speakers
358356 .iter_mut()
359357 .filter(|(_, speaker)| now.duration_since(speaker.last_heard) <= SPEAKING_WINDOW)
360- .map(|(user_id, speaker)| (user_id.clone(), std::mem::take(&mut speaker.levels)))
358+ .map(|(user_id, speaker)| (user_id.clone(), speaker.spectrum.take()))
361359 .collect()
362360 }
363361
crates/spectrum/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "spectrum"
3+version = "0.1.0"
4+edition = "2024"
5+
6+[dependencies]
7+rustfft = "6.4.1"
8+
9+[lints]
10+workspace = true
crates/spectrum/src/lib.rsadded+85 -0
@@ -0,0 +1,85 @@
1+use std::f32::consts::PI;
2+use std::sync::Arc;
3+
4+use rustfft::{Fft, FftPlanner, num_complex::Complex};
5+
6+pub const BANDS: usize = 24;
7+pub const WINDOW: usize = 1024;
8+const LOW_HZ: f32 = 80.0;
9+const HIGH_HZ: f32 = 8000.0;
10+const FLOOR_DB: f32 = -60.0;
11+const CEIL_DB: f32 = -12.0;
12+
13+pub struct Analyzer {
14+ fft: Arc<dyn Fft<f32>>,
15+ hann: Vec<f32>,
16+ gain: f32,
17+ edges: Vec<usize>,
18+}
19+
20+impl Analyzer {
21+ pub fn new(sample_rate: u32) -> Self {
22+ let hann: Vec<f32> = (0..WINDOW)
23+ .map(|i| 0.5 - 0.5 * (2.0 * PI * i as f32 / WINDOW as f32).cos())
24+ .collect();
25+ let gain = 2.0 / hann.iter().sum::<f32>();
26+ let bin = |hz: f32| (hz * WINDOW as f32 / sample_rate as f32) as usize;
27+ let mut edges = Vec::with_capacity(BANDS + 1);
28+ for band in 0..=BANDS {
29+ let hz = LOW_HZ * (HIGH_HZ / LOW_HZ).powf(band as f32 / BANDS as f32);
30+ let previous = edges.last().map_or(0, |edge| edge + 1);
31+ edges.push(bin(hz).max(previous).min(WINDOW / 2));
32+ }
33+ Self {
34+ fft: FftPlanner::new().plan_fft_forward(WINDOW),
35+ hann,
36+ gain,
37+ edges,
38+ }
39+ }
40+
41+ pub fn bands(&self, samples: &[f32]) -> Vec<f32> {
42+ let offset = WINDOW.saturating_sub(samples.len());
43+ let mut buffer = vec![Complex::default(); WINDOW];
44+ for (index, sample) in samples.iter().rev().take(WINDOW).enumerate() {
45+ let at = WINDOW - 1 - index;
46+ if at >= offset {
47+ buffer[at].re = sample * self.hann[at];
48+ }
49+ }
50+ self.fft.process(&mut buffer);
51+ self.edges
52+ .windows(2)
53+ .map(|edge| {
54+ let peak = buffer[edge[0]..edge[1].max(edge[0] + 1)]
55+ .iter()
56+ .map(|value| value.norm() * self.gain)
57+ .fold(0.0, f32::max);
58+ let db = 20.0 * peak.max(1e-6).log10();
59+ ((db - FLOOR_DB) / (CEIL_DB - FLOOR_DB)).clamp(0.0, 1.0)
60+ })
61+ .collect()
62+ }
63+}
64+
65+#[cfg(test)]
66+mod tests {
67+ use super::*;
68+
69+ #[test]
70+ fn tone_lights_its_band() {
71+ let analyzer = Analyzer::new(48000);
72+ let tone: Vec<f32> = (0..WINDOW)
73+ .map(|i| 0.5 * (2.0 * PI * 1000.0 * i as f32 / 48000.0).sin())
74+ .collect();
75+ let bands = analyzer.bands(&tone);
76+ let loudest = bands
77+ .iter()
78+ .enumerate()
79+ .max_by(|a, b| a.1.total_cmp(b.1))
80+ .map(|(index, _)| index)
81+ .unwrap_or_default();
82+ assert!(bands[loudest] > 0.8);
83+ assert!(bands[0] < 0.2 && bands[BANDS - 1] < 0.2);
84+ }
85+}