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 @@
1 [workspace]1 [workspace]
2 resolver = "2"2 resolver = "2"
3-members = ["crates/client", "crates/common", "crates/pixel", "crates/server"]3+members = ["crates/client", "crates/common", "crates/pixel", "crates/spectrum", "crates/server"]
4 4
5 [profile.dev]5 [profile.dev]
6 debug = "line-tables-only"6 debug = "line-tables-only"
@@ -11,6 +11,12 @@ opt-level = 3
11 [profile.dev.package.pixel]11 [profile.dev.package.pixel]
12 opt-level = 312 opt-level = 3
13 13
14+[profile.dev.package.spectrum]
15+opt-level = 3
16+
17+[profile.dev.package.rustfft]
18+opt-level = 3
19+
14 [profile.harness]20 [profile.harness]
15 inherits = "dev"21 inherits = "dev"
16 opt-level = 322 opt-level = 3
@@ -30,6 +36,7 @@ unsafe_code = "forbid"
30 [workspace.dependencies]36 [workspace.dependencies]
31 common = { path = "crates/common" }37 common = { path = "crates/common" }
32 pixel = { path = "crates/pixel" }38 pixel = { path = "crates/pixel" }
39+spectrum = { path = "crates/spectrum" }
33 tokio = { version = "1.54.1", features = ["full"] }40 tokio = { version = "1.54.1", features = ["full"] }
34 bitcode = "0.6.9"41 bitcode = "0.6.9"
35 quinn = { version = "0.11.12", default-features = false, features = [42 quinn = { version = "0.11.12", default-features = false, features = [
crates/client/Cargo.tomlmodified+1 -0
@@ -6,6 +6,7 @@ edition = "2024"
6 [dependencies]6 [dependencies]
7 common.workspace = true7 common.workspace = true
8 pixel.workspace = true8 pixel.workspace = true
9+spectrum.workspace = true
9 reed-solomon-simd = "3.1.0"10 reed-solomon-simd = "3.1.0"
10 tokio.workspace = true11 tokio.workspace = true
11 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }12 quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
crates/client/src/gui/chat.rsmodified+1 -1
@@ -256,7 +256,7 @@ pub struct Chat {
256 const RING_LIMIT: usize = 15;256 const RING_LIMIT: usize = 15;
257 const RING_INTERVAL: Duration = Duration::from_secs(2);257 const RING_INTERVAL: Duration = Duration::from_secs(2);
258 const VOICE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1);258 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);
260 const DEFAULT_USER_VOLUME: f32 = 100.0;260 const DEFAULT_USER_VOLUME: f32 = 100.0;
261 261
262 pub struct UserVolume {262 pub struct UserVolume {
crates/client/src/gui/wave.rsmodified+12 -22
@@ -4,37 +4,32 @@ use gpui_kit::{Div, Hsla, ParentElement, Styled, div, px};
4 4
5 use crate::network::Levels;5 use crate::network::Levels;
6 6
7-pub const BARS: usize = 16;7+const DECAY: f32 = 0.82;
8-const SILENT_BARS: usize = 2;8+const GONE: f32 = 0.02;
9-const DECAY: f32 = 0.985;
10-const PEAK_FLOOR: f32 = 0.02;
11-const CURVE: f32 = 0.7;
12 const AUDIBLE: f32 = 0.1;9 const AUDIBLE: f32 = 0.1;
13 const BAR_WIDTH: f32 = 2.;10 const BAR_WIDTH: f32 = 2.;
14 const MIN_BAR: f32 = 1.5;11 const MIN_BAR: f32 = 1.5;
15 12
16 pub struct Wave {13 pub struct Wave {
17 bars: VecDeque<f32>,14 bars: VecDeque<f32>,
18- peak: f32,
19 }15 }
20 16
21 impl Wave {17 impl Wave {
22 fn new() -> Self {18 fn new() -> Self {
23 Self {19 Self {
24- bars: VecDeque::from(vec![0.0; BARS]),20+ bars: VecDeque::from(vec![0.0; spectrum::BANDS]),
25- peak: PEAK_FLOOR,
26 }21 }
27 }22 }
28 23
29- fn push(&mut self, level: f32) {24+ fn push(&mut self, bands: &[f32]) {
30- self.peak = (self.peak * DECAY).max(level).max(PEAK_FLOOR);25+ for (index, bar) in self.bars.iter_mut().enumerate() {
31- self.bars.pop_front();26+ let band = bands.get(index).copied().unwrap_or(0.0);
32- self.bars27+ *bar = band.max(*bar * DECAY);
33- .push_back((level / self.peak).clamp(0.0, 1.0).powf(CURVE));28+ }
34 }29 }
35 30
36 fn silent(&self) -> bool {31 fn silent(&self) -> bool {
37- self.bars.iter().all(|bar| *bar == 0.0)32+ self.bars.iter().all(|bar| *bar < GONE)
38 }33 }
39 }34 }
40 35
@@ -49,14 +44,9 @@ fn advance(waves: &mut HashMap<String, Wave>, levels: Vec<(String, Vec<f32>)>) -
49 let mut levels: HashMap<String, Vec<f32>> = levels.into_iter().collect();44 let mut levels: HashMap<String, Vec<f32>> = levels.into_iter().collect();
50 let ids: HashSet<String> = waves.keys().chain(levels.keys()).cloned().collect();45 let ids: HashSet<String> = waves.keys().chain(levels.keys()).cloned().collect();
51 for id in ids {46 for id in ids {
52- let incoming = levels47+ let bands = levels.remove(&id).unwrap_or_default();
53- .remove(&id)
54- .filter(|incoming| !incoming.is_empty())
55- .unwrap_or_else(|| vec![0.0; SILENT_BARS]);
56 let wave = waves.entry(id.clone()).or_insert_with(Wave::new);48 let wave = waves.entry(id.clone()).or_insert_with(Wave::new);
57- for level in incoming {49+ wave.push(&bands);
58- wave.push(level);
59- }
60 if wave.silent() {50 if wave.silent() {
61 waves.remove(&id);51 waves.remove(&id);
62 }52 }
@@ -96,7 +86,7 @@ impl Waves {
96 pub fn share(&self, id: &str) -> Option<&VecDeque<f32>> {86 pub fn share(&self, id: &str) -> Option<&VecDeque<f32>> {
97 self.share87 self.share
98 .get(id)88 .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))
100 .map(|wave| &wave.bars)90 .map(|wave| &wave.bars)
101 }91 }
102 }92 }
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};
2 3
3-pub const LEVEL_CAPACITY: usize = 32;4+use common::constant::VOICE_SAMPLE_RATE;
5+use spectrum::{Analyzer, WINDOW};
4 6
5 pub fn rms(samples: &[f32]) -> f32 {7 pub fn rms(samples: &[f32]) -> f32 {
6 if samples.is_empty() {8 if samples.is_empty() {
@@ -9,23 +11,57 @@ pub fn rms(samples: &[f32]) -> f32 {
9 (samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32).sqrt()11 (samples.iter().map(|sample| sample * sample).sum::<f32>() / samples.len() as f32).sqrt()
10 }12 }
11 13
12-pub fn push_level(levels: &mut Vec<f32>, level: f32) {14+fn analyzer() -> &'static Analyzer {
13- if levels.len() >= LEVEL_CAPACITY {15+ static ANALYZER: OnceLock<Analyzer> = OnceLock::new();
14- levels.remove(0);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())
15 }50 }
16- levels.push(level);
17 }51 }
18 52
19 #[derive(Debug, Clone, Default)]53 #[derive(Debug, Clone, Default)]
20-pub struct Meter(Arc<Mutex<Vec<f32>>>);54+pub struct Meter(Arc<Mutex<Spectrum>>);
21 55
22 impl Meter {56 impl Meter {
23- pub fn record(&self, samples: &[f32]) {57+ pub fn record(&self, samples: &[f32], channels: usize) {
24- let mut levels = self.0.lock().unwrap_or_else(PoisonError::into_inner);58+ self.0
25- push_level(&mut levels, rms(samples));59+ .lock()
60+ .unwrap_or_else(PoisonError::into_inner)
61+ .record(samples, channels);
26 }62 }
27 63
28 pub fn take(&self) -> Vec<f32> {64 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()
30 }66 }
31 }67 }
crates/client/src/share/session.rsmodified+2 -2
@@ -417,7 +417,7 @@ fn encode_audio(
417 for sample in pcm.iter_mut() {417 for sample in pcm.iter_mut() {
418 *sample = samples.pop().unwrap_or(0.0);418 *sample = samples.pop().unwrap_or(0.0);
419 }419 }
420- meter.record(&pcm);420+ meter.record(&pcm, SHARE_AUDIO_CHANNELS);
421 let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else {421 let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else {
422 continue;422 continue;
423 };423 };
@@ -790,7 +790,7 @@ fn flush(
790 if now - due > LATE_MS {790 if now - due > LATE_MS {
791 continue;791 continue;
792 }792 }
793- meter.record(&samples);793+ meter.record(&samples, SHARE_AUDIO_CHANNELS);
794 for sample in samples {794 for sample in samples {
795 let _ = ring.push(sample * gain);795 let _ = ring.push(sample * gain);
796 }796 }
crates/client/src/voice/engine.rsmodified+9 -11
@@ -12,7 +12,7 @@ use common::{
12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};12 use ec_opus::{Application, Bandwidth, Decoder, Encoder};
13 13
14 use crate::{14 use crate::{
15- media::meter::{push_level, rms},15+ media::meter::{Spectrum, rms},
16 settings::{Activation, Profile},16 settings::{Activation, Profile},
17 };17 };
18 18
@@ -78,7 +78,7 @@ struct Speaker {
78 previous_transit: Option<f32>,78 previous_transit: Option<f32>,
79 jitter_ms: f32,79 jitter_ms: f32,
80 highest: u32,80 highest: u32,
81- levels: Vec<f32>,81+ spectrum: Spectrum,
82 }82 }
83 83
84 #[derive(Debug, Clone, Copy, Default)]84 #[derive(Debug, Clone, Copy, Default)]
@@ -105,7 +105,7 @@ impl Speaker {
105 previous_transit: None,105 previous_transit: None,
106 jitter_ms: 0.0,106 jitter_ms: 0.0,
107 highest: sequence.wrapping_sub(1),107 highest: sequence.wrapping_sub(1),
108- levels: Vec::new(),108+ spectrum: Spectrum::default(),
109 }109 }
110 }110 }
111 111
@@ -157,7 +157,7 @@ impl Speaker {
157 self.previous_transit = None;157 self.previous_transit = None;
158 return;158 return;
159 };159 };
160- push_level(&mut self.levels, rms(&frame));160+ self.spectrum.record(&frame, 1);
161 self.pending.extend(frame);161 self.pending.extend(frame);
162 }162 }
163 *sample += self.pending.pop_front().unwrap_or(0.0) * gain;163 *sample += self.pending.pop_front().unwrap_or(0.0) * gain;
@@ -180,7 +180,7 @@ pub struct Engine {
180 hangover: u32,180 hangover: u32,
181 sending: bool,181 sending: bool,
182 level_db: f32,182 level_db: f32,
183- sent_levels: Vec<f32>,183+ sent: Spectrum,
184 volumes: HashMap<String, f32>,184 volumes: HashMap<String, f32>,
185 speakers: HashMap<String, Speaker>,185 speakers: HashMap<String, Speaker>,
186 sent_bytes: usize,186 sent_bytes: usize,
@@ -213,7 +213,7 @@ impl Engine {
213 hangover: 0,213 hangover: 0,
214 sending: false,214 sending: false,
215 level_db: SILENT_DB,215 level_db: SILENT_DB,
216- sent_levels: Vec::new(),216+ sent: Spectrum::default(),
217 volumes: HashMap::new(),217 volumes: HashMap::new(),
218 speakers: HashMap::new(),218 speakers: HashMap::new(),
219 sent_bytes: 0,219 sent_bytes: 0,
@@ -253,7 +253,7 @@ impl Engine {
253 }253 }
254 254
255 if speaking {255 if speaking {
256- push_level(&mut self.sent_levels, loud);256+ self.sent.record(frame, 1);
257 }257 }
258 let mut samples = *frame;258 let mut samples = *frame;
259 if speaking && !was_sending {259 if speaking && !was_sending {
@@ -304,9 +304,7 @@ impl Engine {
304 }304 }
305 speaker.last_heard = now;305 speaker.last_heard = now;
306 if payload.is_empty() {306 if payload.is_empty() {
307- for level in std::mem::take(&mut self.sent_levels) {307+ speaker.spectrum.absorb(&mut self.sent);
308- push_level(&mut speaker.levels, level);
309- }
310 return;308 return;
311 }309 }
312 if sequence < speaker.next {310 if sequence < speaker.next {
@@ -357,7 +355,7 @@ impl Engine {
357 self.speakers355 self.speakers
358 .iter_mut()356 .iter_mut()
359 .filter(|(_, speaker)| now.duration_since(speaker.last_heard) <= SPEAKING_WINDOW)357 .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()))
361 .collect()359 .collect()
362 }360 }
363 361
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+}