Skip to content

Commit e93934a

Browse files
refactor(spectrum): inline single-use helpers
Signed-off-by: Maika Namuo <httpworldview@gmail.com>
1 parent 9cd94e4 commit e93934a

3 files changed

Lines changed: 74 additions & 149 deletions

File tree

‎src/visuals/spectrum/processor.rs‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,8 @@ impl SpectrumProcessor {
173173
let floor = self.config.floor_db;
174174
self.snapshot.floor_db = floor;
175175
for db in self.snapshot.traces.iter_mut().flatten() {
176-
reset_to_floor(db, bins, floor);
176+
db.clear();
177+
db.resize(bins, floor);
177178
}
178179
self.reset_smoothing();
179180
}
@@ -318,8 +319,6 @@ impl SpectrumProcessor {
318319
if self.fft.is_none() {
319320
return;
320321
}
321-
let averaging_mode_changed =
322-
std::mem::discriminant(&old.averaging) != std::mem::discriminant(&config.averaging);
323322
if old.fft_size != config.fft_size || old.window != config.window {
324323
self.rebuild_fft();
325324
} else if old.sample_rate != config.sample_rate
@@ -328,7 +327,9 @@ impl SpectrumProcessor {
328327
|| old.secondary_source != config.secondary_source
329328
{
330329
self.reset_buffers();
331-
} else if averaging_mode_changed {
330+
} else if std::mem::discriminant(&old.averaging)
331+
!= std::mem::discriminant(&config.averaging)
332+
{
332333
self.reset_level_buffers();
333334
} else if old.floor_db != config.floor_db {
334335
self.reset_smoothing();
@@ -409,11 +410,6 @@ impl SpectrumLevelBuffers {
409410
}
410411
}
411412

412-
fn reset_to_floor(buf: &mut Vec<f32>, bins: usize, floor: f32) {
413-
buf.clear();
414-
buf.resize(bins, floor);
415-
}
416-
417413
pub(super) fn a_weight(freq_hz: f32) -> f32 {
418414
const C1: f64 = 20.598_997 * 20.598_997;
419415
const C2: f64 = 107.652_65 * 107.652_65;
@@ -424,13 +420,10 @@ pub(super) fn a_weight(freq_hz: f32) -> f32 {
424420
return f32::NEG_INFINITY;
425421
}
426422

427-
let f = freq_hz as f64;
423+
let f = f64::from(freq_hz);
428424
let f2 = f * f;
429-
let numerator = C4 * f2 * f2;
430425
let denom = (f2 + C1) * ((f2 + C2) * (f2 + C3)).sqrt() * (f2 + C4);
431-
432-
let ra = numerator / denom;
433-
(20.0 * ra.log10() + 2.0) as f32
426+
(20.0 * (C4 * f2 * f2 / denom).log10() + 2.0) as f32
434427
}
435428

436429
#[cfg(test)]

‎src/visuals/spectrum/render.rs‎

Lines changed: 33 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -96,10 +96,6 @@ impl SpectrumParams {
9696
let clip = ClipTransform::from_bounds(bounds);
9797

9898
let has_primary = self.normalized_points.len() >= MIN_TRACE_POINTS;
99-
if !has_primary && self.secondary_points.len() < MIN_TRACE_POINTS {
100-
return;
101-
}
102-
10399
if has_primary && self.display_mode == SpectrumDisplayMode::Bar {
104100
self.build_bar_vertices(&mut scratch.instances, clip, bounds);
105101
} else {
@@ -140,36 +136,38 @@ impl SpectrumParams {
140136
vertices.reserve(segments(&self.normalized_points) * 2 + segments(&self.secondary_points));
141137
let baseline = bounds.y + bounds.height;
142138
let project = |out: &mut Vec<(f32, f32)>, normalized: &[[f32; 2]]| {
143-
let visible = normalized.len() >= MIN_TRACE_POINTS;
144-
if visible {
145-
out.extend(
146-
normalized
147-
.iter()
148-
.map(|&p| normalized_to_cartesian(bounds, p)),
149-
);
150-
decimate_line(out, pixel_budget);
151-
}
152-
visible
153-
};
154-
155-
let has_primary = project(points, &self.normalized_points);
156-
if has_primary {
157-
self.push_highlight_columns(vertices, clip, baseline, bounds.height, points);
158-
}
159-
160-
if project(points2, &self.secondary_points) {
161-
extend_aa_line_list(
162-
vertices,
163-
points2,
164-
SECONDARY_LINE_THICKNESS,
165-
self.secondary_line_color,
166-
clip,
139+
out.extend(
140+
normalized
141+
.iter()
142+
.map(|&p| normalized_to_cartesian(bounds, p)),
167143
);
168-
}
144+
decimate_line(out, pixel_budget);
145+
};
146+
project(points, &self.normalized_points);
147+
project(points2, &self.secondary_points);
169148

170-
if has_primary {
171-
extend_aa_line_list(vertices, points, LINE_THICKNESS, self.line_color, clip);
149+
for seg in points.windows(2) {
150+
let c0 = self.ramp_color((baseline - seg[0].1) / bounds.height);
151+
let c1 = self.ramp_color((baseline - seg[1].1) / bounds.height);
152+
if c0[3] > 0.0 || c1[3] > 0.0 {
153+
vertices.push(baseline_segment_instance(
154+
seg[0],
155+
seg[1],
156+
baseline,
157+
clip,
158+
[c0, c1],
159+
false,
160+
));
161+
}
172162
}
163+
extend_aa_line_list(
164+
vertices,
165+
points2,
166+
SECONDARY_LINE_THICKNESS,
167+
self.secondary_line_color,
168+
clip,
169+
);
170+
extend_aa_line_list(vertices, points, LINE_THICKNESS, self.line_color, clip);
173171
}
174172

175173
fn build_bar_vertices(
@@ -192,10 +190,7 @@ impl SpectrumParams {
192190

193191
verts.reserve(bar_count * if secondary.is_some() { 2 } else { 1 });
194192
for i in 0..bar_count {
195-
let (t0, t1) = (
196-
i as f32 / bar_count as f32,
197-
(i + 1) as f32 / bar_count as f32,
198-
);
193+
let [t0, t1] = [i, i + 1].map(|edge| edge as f32 / bar_count as f32);
199194
let amp = sample_max(&self.normalized_points, t0, t1);
200195
let x0 = bounds.x + i as f32 * unit + offset;
201196
let x1 = x0 + bar_w;
@@ -228,30 +223,6 @@ impl SpectrumParams {
228223
}
229224
}
230225

231-
fn push_highlight_columns(
232-
&self,
233-
vertices: &mut Vec<SdfInstance>,
234-
clip: ClipTransform,
235-
baseline: f32,
236-
height: f32,
237-
positions: &[(f32, f32)],
238-
) {
239-
for seg in positions.windows(2) {
240-
let c0 = self.ramp_color((baseline - seg[0].1) / height);
241-
let c1 = self.ramp_color((baseline - seg[1].1) / height);
242-
if c0[3] > 0.0 || c1[3] > 0.0 {
243-
vertices.push(baseline_segment_instance(
244-
seg[0],
245-
seg[1],
246-
baseline,
247-
clip,
248-
[c0, c1],
249-
false,
250-
));
251-
}
252-
}
253-
}
254-
255226
fn ramp_color(&self, amp: f32) -> [f32; 4] {
256227
let (lo, hi, f) = ramp_segment(&self.stop_positions, &self.stop_spreads, amp);
257228
let [a, b] = [self.ramp[lo], self.ramp[hi]];
@@ -275,14 +246,10 @@ fn sample_max(pts: &[[f32; 2]], t0: f32, t1: f32) -> f32 {
275246
}
276247

277248
fn sample_lerp_at(pts: &[[f32; 2]], t: f32, index: usize) -> f32 {
278-
if index == 0 {
279-
return pts[0][1];
280-
}
281-
if index >= pts.len() {
282-
return pts[pts.len() - 1][1];
249+
if index == 0 || index >= pts.len() {
250+
return pts[index.min(pts.len() - 1)][1];
283251
}
284-
let a = pts[index - 1];
285-
let b = pts[index];
252+
let [a, b] = [pts[index - 1], pts[index]];
286253
lerp(a[1], b[1], (t - a[0]) / (b[0] - a[0]).max(1e-6))
287254
}
288255

‎src/visuals/spectrum/state.rs‎

Lines changed: 34 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -59,18 +59,6 @@ struct GridLayoutKey {
5959
}
6060
type SharedPoints = Arc<Vec<[f32; 2]>>;
6161
static EMPTY_POINTS: LazyLock<SharedPoints> = LazyLock::new(|| Arc::new(Vec::new()));
62-
fn rebuild_points(
63-
points: &mut SharedPoints,
64-
capacity: usize,
65-
build: impl FnOnce(&mut Vec<[f32; 2]>),
66-
) {
67-
if Arc::strong_count(points) != 1 || points.capacity() != capacity {
68-
*points = Arc::new(Vec::with_capacity(capacity));
69-
}
70-
let points = Arc::get_mut(points).expect("unshared spectrum geometry");
71-
points.clear();
72-
build(points);
73-
}
7462

7563
crate::macros::default_struct! {
7664
pub(crate) struct SpectrumState {
@@ -146,17 +134,20 @@ impl SpectrumState {
146134
*points = Arc::clone(&EMPTY_POINTS);
147135
continue;
148136
};
149-
rebuild_points(points, self.x_cache.len(), |points| {
150-
build_single_points_into(
151-
points,
152-
style,
153-
min_f,
154-
max_f,
155-
snap,
156-
trace_db(&snap.traces[trace], weighting),
157-
&self.x_cache,
158-
);
159-
});
137+
if Arc::strong_count(points) != 1 || points.capacity() != self.x_cache.len() {
138+
*points = Arc::new(Vec::with_capacity(self.x_cache.len()));
139+
}
140+
let points = Arc::get_mut(points).expect("unshared spectrum geometry");
141+
points.clear();
142+
build_single_points_into(
143+
points,
144+
style,
145+
min_f,
146+
max_f,
147+
snap,
148+
trace_db(&snap.traces[trace], weighting),
149+
&self.x_cache,
150+
);
160151
}
161152
let peak = primary_trace
162153
.filter(|_| style.show_peak_label)
@@ -354,23 +345,20 @@ impl SpectrumState {
354345
}
355346

356347
fn peak(&self) -> Option<&PeakLabel> {
357-
self.peak.as_ref().filter(|_| {
358-
self.style.show_peak_label
359-
&& self.style.source != Channel::None
360-
&& self.points[0].len() >= MIN_TRACE_POINTS
361-
})
348+
self.peak
349+
.as_ref()
350+
.filter(|_| self.points[0].len() >= MIN_TRACE_POINTS)
362351
}
363352

364353
pub(in crate::visuals) fn ignores_audio(&self) -> bool {
365354
[self.style.source, self.style.secondary_source] == [Channel::None; 2]
366355
}
367356

368357
pub(in crate::visuals) fn is_quiescent(&self) -> bool {
369-
let quiet = [self.style.source, self.style.secondary_source]
370-
.into_iter()
371-
.zip(&self.points)
372-
.filter(|(source, _)| *source != Channel::None)
373-
.all(|(_, points)| points.iter().all(|point| point[1] == 0.0));
358+
let quiet = self
359+
.points
360+
.iter()
361+
.all(|points| points.iter().all(|point| point[1] == 0.0));
374362
self.ignores_audio() || (self.effective_range.is_some() && self.peak.is_none() && quiet)
375363
}
376364

@@ -474,11 +462,8 @@ crate::visuals::visualization_widget!(Spectrum, SpectrumState, |this, r, th, b|
474462

475463
fn value_at(bins: &[f32], mags: &[f32], f: f32) -> f32 {
476464
let i = bins.partition_point(|&bin| bin < f);
477-
if i == 0 {
478-
return mags[0];
479-
}
480-
if i >= bins.len() {
481-
return mags[bins.len() - 1];
465+
if i == 0 || i >= bins.len() {
466+
return mags[i.min(bins.len() - 1)];
482467
}
483468
lerp(
484469
mags[i - 1],
@@ -700,27 +685,16 @@ mod tests {
700685
manager.ingest_samples(&vec![0.0; settings.fft_size], format);
701686
settings.floor_db = -140.0;
702687
manager.apply_config(VisualConfig::Spectrum(settings));
703-
let state = state.borrow();
704-
assert!(
705-
state
706-
.points
707-
.iter()
708-
.all(|points| points.iter().all(|point| point[1] == 0.0))
709-
);
710-
assert!(state.peak.is_none());
688+
assert!(state.borrow().is_quiescent());
711689
}
712690

713691
#[test]
714692
fn theme_colors_invalidate_cached_geometry_without_audio_update() {
715693
let mut state = SpectrumState::default();
716694
state.points[0] = Arc::new(vec![[0.0, 0.0], [1.0, 1.0]]);
717695
let bounds = Rectangle::new(Point::ORIGIN, Size::new(100.0, 50.0));
718-
let dark = state
719-
.visual_params(bounds, &iced::Theme::Dark, None)
720-
.unwrap();
721-
let light = state
722-
.visual_params(bounds, &iced::Theme::Light, None)
723-
.unwrap();
696+
let [dark, light] = [iced::Theme::Dark, iced::Theme::Light]
697+
.map(|theme| state.visual_params(bounds, &theme, None).unwrap());
724698
assert_eq!(dark.geometry.revision, light.geometry.revision);
725699
assert_ne!(dark.line_color, light.line_color);
726700
assert_ne!(dark.geometry_fingerprint(), light.geometry_fingerprint());
@@ -885,15 +859,12 @@ fn build_single_points_into(
885859
) {
886860
let bins = &snap.frequency_bins;
887861
let inv_dr = (MAX_DB - style.floor_db).max(EPSILON).recip();
888-
let y = |m: f32| {
889-
if m <= snap.floor_db {
862+
let mut push = |x, m: f32| {
863+
let y = if m <= snap.floor_db {
890864
0.0
891865
} else {
892866
((m - style.floor_db) * inv_dr).clamp(0.0, 1.0)
893-
}
894-
};
895-
let mut push = |x, m| {
896-
let y = y(m);
867+
};
897868
if y.is_finite() {
898869
out.push([if style.reverse_frequency { 1.0 - x } else { x }, y]);
899870
}
@@ -1048,7 +1019,6 @@ fn draw_peak(
10481019
peak_color: Color,
10491020
) {
10501021
let theme_palette = th.extended_palette();
1051-
let [(title_pos, title_bounds), (detail_pos, detail_bounds)] = layout.text_layouts;
10521022
fill_bordered_rect(
10531023
r,
10541024
layout.rect,
@@ -1060,16 +1030,11 @@ fn draw_peak(
10601030
},
10611031
true,
10621032
);
1063-
r.fill_paragraph(
1064-
&peak.text[0],
1065-
title_pos,
1033+
let colors = [
10661034
with_alpha(theme_palette.background.base.text, peak.opacity),
1067-
Rectangle::new(title_pos, title_bounds),
1068-
);
1069-
r.fill_paragraph(
1070-
&peak.text[1],
1071-
detail_pos,
10721035
with_alpha(theme_palette.secondary.weak.text, 0.84 * peak.opacity),
1073-
Rectangle::new(detail_pos, detail_bounds),
1074-
);
1036+
];
1037+
for ((text, (pos, size)), color) in peak.text.iter().zip(layout.text_layouts).zip(colors) {
1038+
r.fill_paragraph(text, pos, color, Rectangle::new(pos, size));
1039+
}
10751040
}

0 commit comments

Comments
 (0)