From cd48c4962fd7f804f87fdd3eb74b26bbdc3ad4f8 Mon Sep 17 00:00:00 2001 From: Chris Laupama <42254688+chrislaupama@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:30:43 +0000 Subject: [PATCH 1/2] Add the expanded Spectrum window with 2D, 3D waterfall and Split views --- crates/dstudio-app/src/analyzer_views.rs | 11 + crates/dstudio-app/src/device_window.rs | 167 ++++++++- .../dstudio-app/src/device_window_spectrum.rs | 348 ++++++++++++++++++ crates/dstudio-app/src/main.rs | 15 +- 4 files changed, 537 insertions(+), 4 deletions(-) create mode 100644 crates/dstudio-app/src/device_window_spectrum.rs diff --git a/crates/dstudio-app/src/analyzer_views.rs b/crates/dstudio-app/src/analyzer_views.rs index ef616972..ed267fa9 100644 --- a/crates/dstudio-app/src/analyzer_views.rs +++ b/crates/dstudio-app/src/analyzer_views.rs @@ -65,6 +65,8 @@ const TRACE_FRAMES: usize = 256; const TRACE_WINDOW: f32 = 4.0; const TRACE_RANGE_CT: f32 = 120.0; const BANDS: usize = 256; +/// Bands of a Spectrum frame (log spaced 20 Hz..20 kHz). +pub(crate) const SPECTRUM_BANDS: usize = BANDS; const FLOOR_DB: f32 = -120.0; const SUCCESS: Color = Color::from_rgb_u8(0x4c, 0xaf, 0x50); /// Spectrum stroke colours by Color Scheme. @@ -76,6 +78,10 @@ const PALETTE: [Color; 6] = [ Color::from_rgb_u8(0x7e, 0xc8, 0xe8), Color::from_rgb_u8(0xc8, 0xd0, 0xdc), ]; +/// A Spectrum's curve colour for its Color Scheme choice. +pub(crate) fn spectrum_color(scheme: usize) -> Color { + PALETTE[scheme.min(PALETTE.len() - 1)] +} const NOTES: [&str; 12] = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]; #[derive(Debug, Clone, Copy)] @@ -483,6 +489,11 @@ impl Controller { canvas(FIELD_X * Z, FIELD_Y * Z, w, h, body_y, "Pitch", String::new(), [Vec::new(), layers, over], Vec::new()) } + /// A Spectrum card's newest frame: (analyser sequence, shown curve, peak hold), dB per band. + pub(crate) fn spectrum_frame(&self, id: DeviceId) -> Option<(u64, &[f32], &[f32])> { + self.devices.panel.analyzers.spectra.get(&id).map(|s| (s.seq, s.shown.as_slice(), s.peak.as_slice())) + } + fn tuner_canvas(&self, d: &Device, def: &'static DeviceDef, w_pt: f32, accent: Color) -> PanelCanvas { self.tuner_canvas_at(d, def, w_pt, TUNER_BOTTOM - FIELD_Y, Z, accent) } diff --git a/crates/dstudio-app/src/device_window.rs b/crates/dstudio-app/src/device_window.rs index 2d3b3b81..6bfa7f75 100644 --- a/crates/dstudio-app/src/device_window.rs +++ b/crates/dstudio-app/src/device_window.rs @@ -89,6 +89,8 @@ pub(crate) const ACT_MB_BAND: i32 = 13; pub(crate) const ACT_VIEW: i32 = 14; /// Delay: the repeat-EQ band the rack edits (value: 0..6). pub(crate) const ACT_DELAY_BAND: i32 = 15; +/// Spectrum: clear the window's history. +pub(crate) const ACT_SPEC_RESET: i32 = 16; const PILL_GHOST: i32 = 6; /// Character Mod's Mode parameter of each circuit (Ensemble has none). const CM_MODES: [Option<&str>; 11] = dstudio_core::builtin::character_mod::MODE_PARAMS; @@ -126,7 +128,7 @@ pub(crate) fn has_window(def: &DeviceDef) -> bool { def.id, "auto-filter" | "channeleq" | "character-eq" | "transient-shaper" | "multiband-compressor" | "delay" | "reverb" | "echo" ) || is_wave_window(def) - || matches!(def.id, "utility" | "widener" | "tuner") + || matches!(def.id, "utility" | "widener" | "tuner" | "spectrum") || def.id == "bitcrusher" || is_field_window(def) || is_dynamics_window(def) @@ -190,6 +192,8 @@ pub(crate) fn kit(def: &DeviceDef) -> Kit { // Utility: three cards and no display; the meters run the window's height. "utility" => Kit { w: 1200.0, display: (INSET, 52.0, 1042.0, 630.0), plot: (0.0, 0.0, 0.0, 0.0), narrow: true, meters_h: 0.0 }, // Stereo Widener: the field over the correlation lane. + // Spectrum: the analyser across the display, one Level meter beside it. + "spectrum" => Kit { w: 1200.0, display: (INSET, 52.0, 1108.0, 514.0), plot: (36.0, 32.0, 42.0, 34.0), narrow: true, meters_h: 0.0 }, // Tuner: the bar across a tall display, one In meter beside it. "tuner" => Kit { w: 1200.0, display: (INSET, 52.0, 1108.0, 550.0), plot: (0.0, 0.0, 0.0, 0.0), narrow: true, meters_h: 0.0 }, // Its meters run down past the card, as the Bit Crusher's. @@ -245,6 +249,8 @@ pub(crate) struct WinUi { epoch: Option, /// Stereo Widener: input and output correlation of the open windows. pub(crate) corr: HashMap>, + /// Spectrum: the frames each open window keeps for its 3D and Split views. + pub(crate) spec: HashMap, } /// Which signal a window's analyser shows. @@ -658,6 +664,7 @@ impl Controller { _ if is_wave_window(def) => self.wave_window_canvas(d, def, &k, accent), _ if def.id == "bitcrusher" => self.crush_window_canvas(d, def, &k, accent), _ if def.id == "widener" => self.widener_window_canvas(d, def, &k, accent), + _ if def.id == "spectrum" => self.spectrum_window_canvas(d, def, &k, accent), // The card's tuner at twice its scale, its bar across the middle of the display. _ if def.id == "tuner" => { PanelCanvas { well: false, ..self.tuner_canvas_at(d, def, k.display.2 / 2.0, TUNER_WIN_H, 2.0 * Z, accent) } @@ -681,13 +688,17 @@ impl Controller { "utility" => self.utility_window(d, def, &mut b), "widener" => self.widener_window(d, def, &mut b, dy + dh + 12.0), "tuner" => self.tuner_window(d, def, &mut b, dy + dh + 14.0), + "spectrum" => self.spectrum_window(d, def, &mut b, dy + dh + 12.0), _ => self.field_window(d, def, &mut b, dy + dh + 12.0), }; let (mut meters, ticks, mut ticks_x) = self.window_meters(d.id, &k); - // The Tuner meters its input only. - if def.id == "tuner" { + // The Tuner meters its input only; the Spectrum its level. + if matches!(def.id, "tuner" | "spectrum") { meters.truncate(1); ticks_x = meters[0].x / Z + 38.0; + if def.id == "spectrum" { + meters[0].label = s("Level"); + } } Some(WinView { visible: true, @@ -784,6 +795,21 @@ impl Controller { self.devices.wins.meters.retain(|id, _| open.contains(id)); self.devices.wins.history.retain(|id, _| open.contains(id)); self.devices.wins.corr.retain(|id, _| open.contains(id)); + self.devices.wins.spec.retain(|id, _| open.contains(id)); + for &id in &open { + let Some(d) = self.project().device(id) else { continue }; + let Some(def) = dstudio_core::builtin::def_of(d).filter(|def| def.id == "spectrum") else { continue }; + if self.devices.wins.held.contains(&id) { + continue; + } + let depth = def.param("history_depth").map_or(3, |p| self.panel_value(d, def, p).round() as usize); + let depth = crate::device_window_spectrum::DEPTHS[depth.min(crate::device_window_spectrum::DEPTHS.len() - 1)]; + let Some((seq, shown, _)) = self.spectrum_frame(id) else { continue }; + let shown = shown.to_vec(); + if self.devices.wins.spec.entry(id).or_default().take(seq, &shown, depth) { + self.ui_dirty = true; + } + } let epoch = *self.devices.wins.epoch.get_or_insert(now); let t = now.duration_since(epoch).as_secs_f64(); let mut out = Vec::new(); @@ -1650,6 +1676,91 @@ impl Controller { 700.0 } + /// A picker in the header after its name, right-aligned at `right`; returns the left. + #[allow(clippy::too_many_arguments)] + fn header_picker(&self, d: &Device, def: &'static DeviceDef, b: &mut Builder, id: &str, name: &str, right: f32, inert: bool) -> f32 { + let label = def.param(id).map_or_else(String::new, |p| p.format(self.panel_value(d, def, p))); + let pw = pill_w(&label) + 14.0; + let p = b.pill(PILL_PICKER, def.index_of(id).map_or(-1, |i| i as i32), 0, right - pw / 2.0, 9.5, 0.0, &label, false); + p.inert = inert; + let lw = crate::text_measure::value_width(name) * 1.15 + 6.0; + let ink = if inert { 0x59 } else { 0xb3 }; + b.texts.push(PanelText { + x: (right - pw - 8.0 - lw) * Z, + y: 13.5 * Z, + w: lw * Z, + h: 16.0 * Z, + text: s(name), + color: Color::from_argb_u8(ink, 0xe5, 0xe5, 0xe8), + size: 12.0 * Z, + weight: 600, + align: 2, + }); + right - pw - 8.0 - lw + } + + /// Spectrum: header (View pills, Reset and Hold view, History and Color), the analyser + /// in the display (the Split view's spectrogram in a well of its own below the 2D + /// part), and one card: FFT, Window, Channel | Slope, Ceiling, Range | Smoothing, + /// Averaging, Peak Hold, Decay. + fn spectrum_window(&self, d: &Device, def: &'static DeviceDef, b: &mut Builder, y: f32) -> f32 { + let val = |id: &str| def.param(id).map_or(0.0, |p| self.panel_value(d, def, p)); + let idx = |id: &str| def.index_of(id).map_or(-1, |i| i as i32); + let label = |id: &str| def.param(id).map_or_else(String::new, |p| p.format(self.panel_value(d, def, p))); + let mode = val("display_mode").round() as i32; + let mut x = self.header_choice(d, def, b, "display_mode", b.w - INSET); + x = Self::header_rule(b, x); + let rw = pill_w("Reset") + 4.0; + b.pill(PILL_GHOST, ACT_SPEC_RESET, 0, x - rw, 10.5, rw, "Reset", false); + x -= rw + 10.0 + 77.5; + b.pill(PILL_GHOST_LATCH, ACT_HOLD, 0, x, 10.5, 77.5, "Hold view", self.win_held(d.id)); + x = Self::header_rule(b, x); + x = self.header_picker(d, def, b, "history_depth", "History", x, mode == crate::device_window_spectrum::MODE_2D); + self.header_picker(d, def, b, "color_scheme", "Color", x - 24.0, false); + // Split: the 2D part in the display, the spectrogram in its own well below. + if mode == crate::device_window_spectrum::MODE_SPLIT { + let k = kit(def); + if let Some(bx) = b.boxes.iter_mut().find(|bx| bx.kind == BOX_DISPLAY) { + bx.h = (k.plot.1 + crate::device_window_spectrum::SPLIT_GRAM_Y - 16.0) * Z; + } + } + let row = Row::main(y); + self.win_card( + d, + def, + b, + row, + vec![ + ( + vec![ + Item::Picker(idx("fft_size"), label("fft_size"), "FFT", 104.0, false), + Item::Picker(idx("window"), label("window"), "Window", 104.0, false), + Item::Picker(idx("channel_mode"), label("channel_mode"), "Channel", 104.0, false), + ], + 0.0, + ), + ( + vec![ + Item::Knob("slope", "Slope", 2, 70.0, false), + Item::Knob("db_ceiling", "Ceiling", 2, 70.0, false), + Item::Knob("db_range", "Range", 2, 70.0, false), + ], + 4.0, + ), + ( + vec![ + Item::Knob("smoothing", "Smoothing", 1, 76.0, false), + Item::Knob("averaging", "Averaging", 1, 76.0, false), + Item::Picker(idx("peak_hold"), label("peak_hold"), "Peak Hold", 90.0, false), + Item::Knob("decay", "Decay", 1, 70.0, false), + ], + 4.0, + ), + ], + ); + row.y + row.h + 16.0 + } + /// Tuner: a short card: Tuning and Reference, then Mute Output. fn tuner_window(&self, d: &Device, def: &'static DeviceDef, b: &mut Builder, y: f32) -> f32 { let idx = |id: &str| def.index_of(id).map_or(-1, |i| i as i32); @@ -2696,6 +2807,9 @@ impl Controller { let span = crate::device_window_dynamics::SPANS[value.clamp(0, 2) as usize]; self.devices.wins.span.insert(device, span); } + (ACT_SPEC_RESET, _) => { + self.devices.wins.spec.remove(&device); + } (ACT_HOLD, _) => { if !self.devices.wins.held.remove(&device) { self.devices.wins.held.insert(device); @@ -3262,6 +3376,44 @@ mod tests { } } + /// Spectrum: three views from one history; Reset clears it, Hold view stops taking + /// frames, the History picker is inert in 2D. + #[test] + fn spectrum_window_draws_each_view_from_its_history() { + use slint::Model; + let (mut c, did, def) = controller_with("spectrum"); + assert!(has_window(def)); + let idx = |p: &str| def.index_of(p).unwrap() as i32; + let v = view(&c, did, def); + assert!((v.w / Z - 1200.0).abs() < 0.5 && (v.h / Z - 700.0).abs() < 0.5, "{} x {}", v.w / Z, v.h / Z); + assert_eq!(v.meters.row_count(), 1); + assert_eq!(v.meters.row_data(0).unwrap().label, "Level"); + for p in ["fft_size", "window", "channel_mode", "peak_hold", "color_scheme", "history_depth"] { + assert!(v.pills.iter().any(|q| q.param == idx(p)), "{p}"); + } + assert_eq!(v.pills.iter().filter(|q| q.param == idx("display_mode")).count(), 3); + let empty_3d = v.display.paths.row_count(); + let h = c.devices.wins.spec.entry(did).or_default(); + for i in 1..=200u64 { + let f: Vec = (0..crate::analyzer_views::SPECTRUM_BANDS).map(|b| -30.0 - (b as f32 * 0.2) - (i % 7) as f32).collect(); + h.take(i, &f, 128); + } + assert_eq!(h.frames.len(), 128); + let full_3d = view(&c, did, def).display.paths.row_count(); + assert!(full_3d >= empty_3d + 2 * 40, "{empty_3d} -> {full_3d}"); + c.execute(Command::SetDeviceParam { device: did, param: "display_mode".into(), value: 2.0 }); + let split = view(&c, did, def); + let well = split.boxes.iter().find(|b| b.kind == BOX_DISPLAY).unwrap(); + assert!(well.h / Z < 300.0, "{}", well.h / Z); + assert!(split.display.paths.row_count() > 4); + c.execute(Command::SetDeviceParam { device: did, param: "display_mode".into(), value: 0.0 }); + let flat = view(&c, did, def); + assert!(flat.pills.iter().any(|q| q.param == idx("history_depth") && q.inert)); + assert!(flat.display.texts.iter().any(|t| t.text.starts_with("Tilt"))); + c.win_action(did, ACT_SPEC_RESET, 0); + assert!(c.win_spec_history(did).is_none()); + } + /// A full ten-second history draws as one line per series, however many samples it holds. #[test] fn dynamics_history_draws_once_per_series() { @@ -3300,12 +3452,21 @@ mod tests { "utility", "widener", "tuner", + "spectrum", ] { let (mut c, did, def) = controller_with(id); let h: std::collections::VecDeque<_> = (0..630).map(|i| (i as f64 / 60.0, -12.0 + (i as f32 * 0.1).sin() * 6.0, -18.0, -6.0)).collect(); c.devices.wins.history.insert(did, h); c.devices.wins.epoch = Some(Instant::now() - std::time::Duration::from_millis(10_500)); + if id == "spectrum" { + let h = c.devices.wins.spec.entry(did).or_default(); + for i in 1..=128u64 { + let f: Vec = + (0..crate::analyzer_views::SPECTRUM_BANDS).map(|b| -20.0 - b as f32 * 0.25 - (i % 9) as f32).collect(); + h.take(i, &f, 128); + } + } let d = c.project().device(did).unwrap().clone(); let t0 = std::time::Instant::now(); for _ in 0..n { diff --git a/crates/dstudio-app/src/device_window_spectrum.rs b/crates/dstudio-app/src/device_window_spectrum.rs new file mode 100644 index 00000000..f9de1178 --- /dev/null +++ b/crates/dstudio-app/src/device_window_spectrum.rs @@ -0,0 +1,348 @@ +//! Spectrum's expanded window display, in its three views. 2D: the analyser curve and its +//! peak hold over a dB ladder (Ceiling down by Range) and a log Hz axis, with the tilt +//! guide. 3D: the frames of the history as a waterfall receding from the front. Split: +//! the 2D picture over a spectrogram of the history (newest row at the top). The window +//! keeps up to History Depth frames while it is open; Hold view stops taking them. + +use crate::PanelCanvas; +use crate::analyzer_views::{SPECTRUM_BANDS, spectrum_color}; +use crate::controller::Controller; +use crate::device_canvas::{dashed, fill, path, rgba, stroke, text, white}; +use crate::device_panel::Z; +use crate::device_window::Kit; +use crate::{PanelPath, PanelText}; +use dstudio_core::builtin::DeviceDef; +use dstudio_core::{Device, DeviceId}; +use slint::{Color, ModelRc, VecModel}; +use std::collections::VecDeque; +use std::fmt::Write; +use std::rc::Rc; + +fn model(v: Vec) -> ModelRc { + ModelRc::from(Rc::new(VecModel::from(v))) +} + +/// History Depth choices (frames). +pub(crate) const DEPTHS: [usize; 6] = [32, 64, 96, 128, 192, 256]; +/// Display modes. +pub(crate) const MODE_2D: i32 = 0; +pub(crate) const MODE_3D: i32 = 1; +pub(crate) const MODE_SPLIT: i32 = 2; +/// Split: height of the 2D part (pt from the plot top) and where the spectrogram starts. +const SPLIT_2D_H: f32 = 242.0; +pub(crate) const SPLIT_GRAM_Y: f32 = 278.0; +/// Most waterfall lines and spectrogram rows drawn, and points / columns per row. +const MAX_LINES: usize = 40; +const MAX_ROWS: usize = 64; +const COLS: usize = 96; +/// Spectrogram ink steps. +const STEPS: usize = 8; +const HZ_TICKS: [(f32, &str); 9] = [ + (50.0, "50"), + (100.0, "100"), + (200.0, "200"), + (500.0, "500"), + (1000.0, "1k"), + (2000.0, "2k"), + (5000.0, "5k"), + (10000.0, "10k"), + (20000.0, "20k"), +]; + +/// The frames a Spectrum window keeps: the last analyser sequence taken and the shown +/// curves, newest last. +#[derive(Debug, Default, Clone)] +pub(crate) struct SpecHistory { + pub seq: u64, + pub frames: VecDeque>, +} + +impl SpecHistory { + /// Takes a new frame (once per analyser sequence), keeping at most `depth`. + pub(crate) fn take(&mut self, seq: u64, frame: &[f32], depth: usize) -> bool { + if seq == 0 || seq == self.seq || frame.is_empty() { + return false; + } + self.seq = seq; + self.frames.push_back(frame.to_vec()); + while self.frames.len() > depth.max(1) { + self.frames.pop_front(); + } + true + } +} + +/// x (0..1) of band `i` on the 20 Hz..20 kHz log axis. +fn band_t(i: usize) -> f32 { + (i as f32 + 0.5) / SPECTRUM_BANDS as f32 +} + +/// `n` values sampled evenly from a frame (the loudest band of each span). +fn decimate(frame: &[f32], n: usize) -> Vec { + let len = frame.len().max(1); + (0..n) + .map(|k| { + let (a, b) = (k * len / n, ((k + 1) * len / n).max(k * len / n + 1).min(len)); + frame[a.min(len - 1)..b].iter().copied().fold(f32::MIN, f32::max) + }) + .collect() +} + +/// "−12.3 dB", or a dash when nothing is above the floor. +fn peak_text(db: Option) -> String { + match db { + Some(v) if v > -119.0 => { + if v < 0.0 { + format!("\u{2212}{:.1} dB", -v) + } else { + format!("{v:.1} dB") + } + } + _ => "\u{2013}".into(), + } +} + +impl Controller { + pub(crate) fn win_spec_history(&self, id: DeviceId) -> Option<&SpecHistory> { + self.devices.wins.spec.get(&id) + } + + pub(crate) fn spectrum_window_canvas(&self, d: &Device, def: &'static DeviceDef, k: &Kit, _accent: Color) -> PanelCanvas { + let v = |id: &str, dflt: f32| def.param(id).map_or(dflt, |p| self.panel_value(d, def, p)); + let (_, _, dw, dh) = k.display; + let (pl, pt, pr, pb) = k.plot; + let (pw, ph) = ((dw - pl - pr) * Z, (dh - pt - pb) * Z); + let mode = v("display_mode", 1.0).round() as i32; + let (ceiling, range, slope) = (v("db_ceiling", 0.0), v("db_range", 90.0).max(1.0), v("slope", 4.5)); + let color = spectrum_color(v("color_scheme", 0.0).round() as usize); + let dim = white(0.32); + let mut paths: Vec = Vec::new(); + let mut texts: Vec = Vec::new(); + let frame = self.spectrum_frame(d.id); + let history = self.win_spec_history(d.id); + + // Caption: the loudest peak and the transport; the tilt on the right. + let cy = -(pt - 18.0) * Z; + let peak = frame.and_then(|(_, _, p)| p.iter().copied().reduce(f32::max)); + texts.push(text(0.0, cy, 60.0 * Z, "Peak", white(0.55), 12.0 * Z, 0)); + let mut x = (crate::text_measure::value_width("Peak") + 12.0) * Z; + let pk = peak_text(peak); + texts.push(text(x, cy, 100.0 * Z, pk.clone(), color, 12.0 * Z, 0)); + x += (crate::text_measure::value_width(&pk) + 16.0) * Z; + if !self.project_playing() { + texts.push(text(x, cy, 80.0 * Z, "stopped", dim, 10.0 * Z, 0)); + } + let tilt = format!("Tilt {}{:.1} dB/oct", if slope < 0.0 { "\u{2212}" } else { "+" }, slope.abs()); + texts.push(text(pw, cy, 160.0 * Z, tilt, dim, 10.0 * Z, 2)); + + if mode == MODE_3D { + Self::spectrum_waterfall(history, pw, ph, ceiling, range, color, &mut paths); + } else { + let h2 = if mode == MODE_SPLIT { SPLIT_2D_H * Z } else { ph }; + Self::spectrum_2d(frame, pw, h2, ceiling, range, slope, color, &mut paths, &mut texts); + if mode == MODE_SPLIT { + let (gx, gy) = (-pl * Z, SPLIT_GRAM_Y * Z); + let (gw, gh) = (dw * Z, ph + pb * Z - gy); + paths.push(fill(format!("M{gx:.1} {gy:.1} h{gw:.1} v{gh:.1} h{:.1} Z", -gw), Color::from_rgb_u8(0, 0, 0))); + Self::spectrogram(history, gx, gy, gw, gh, ceiling, range, color, &mut paths); + } + } + PanelCanvas { + visible: true, + w: pw, + h: ph, + paths: model(paths), + texts: model(texts), + label: "Spectrum".into(), + ..Default::default() + } + } + + /// The 2D picture `w` x `h`: grid, ladder, axis, tilt guide, peak hold and curve. + #[allow(clippy::too_many_arguments)] + fn spectrum_2d( + frame: Option<(u64, &[f32], &[f32])>, + w: f32, + h: f32, + ceiling: f32, + range: f32, + slope: f32, + color: Color, + paths: &mut Vec, + texts: &mut Vec, + ) { + let dim = white(0.32); + let x_of = |hz: f32| (hz / 20.0).ln() / 1000f32.ln() * w; + let y_of = |db: f32| ((ceiling - db) / range).clamp(-0.01, 1.01) * h; + let (mut grid, mut strong) = (String::new(), String::new()); + for (hz, label) in HZ_TICKS { + let x = x_of(hz).round() + 0.5; + let _ = write!(if hz == 1000.0 { &mut strong } else { &mut grid }, "M{x:.1} 0 V{h:.1} "); + texts.push(text(x, h + 10.0 * Z, 40.0 * Z, label, dim, 10.0 * Z, if hz >= 20000.0 { 2 } else { 1 })); + } + texts.push(text(-6.0 * Z, h + 10.0 * Z, 40.0 * Z, "dBFS", dim, 10.0 * Z, 2)); + texts.push(text(w + 30.0 * Z, h + 10.0 * Z, 30.0 * Z, "Hz", dim, 10.0 * Z, 2)); + let step = if range >= 72.0 { + 12.0 + } else if range >= 36.0 { + 6.0 + } else { + 3.0 + }; + let mut db = (ceiling / step).floor() * step; + while db > ceiling - range + 0.1 { + let y = y_of(db).round() + 0.5; + let _ = write!(grid, "M0 {y:.1} H{w:.1} "); + let label = if db < 0.0 { format!("\u{2212}{:.0}", -db) } else { format!("{db:.0}") }; + texts.push(text(-8.0 * Z, y_of(db), 40.0 * Z, label, dim, 10.0 * Z, 2)); + db -= step; + } + let _ = write!(grid, "M0 {h:.1} H{w:.1} M{w:.1} 0 V{h:.1}"); + paths.push(stroke(grid, white(0.05), 1.0)); + paths.push(stroke(strong, white(0.14), 1.0)); + let guide = |hz: f32| h / 2.0 - slope * (hz / 1000.0).log2() * h / range; + paths.push(stroke(dashed(&[(0.0, guide(20.0)), (w, guide(20000.0))], 3.0 * Z, 4.0 * Z), white(0.22), 1.0)); + let Some((_, shown, peak)) = frame else { return }; + let pts = |v: &[f32]| -> Vec<(f32, f32)> { v.iter().enumerate().map(|(i, db)| (band_t(i) * w, y_of(*db))).collect() }; + if peak.iter().any(|db| *db > -119.99) { + paths.push(stroke(path(&pts(peak)), rgba(color, 0.35), 1.0)); + } + if shown.iter().any(|db| *db > -119.99) { + let p = pts(shown); + let line = path(&p); + paths.push(PanelPath { fill2: rgba(color, 0.04), ..fill(format!("{line} L{w:.1} {h:.1} L0 {h:.1} Z"), rgba(color, 0.5)) }); + paths.push(stroke(line, rgba(color, 0.95), 1.25 * Z)); + } + } + + /// The waterfall: up to MAX_LINES frames from the back (oldest, raised and narrowed) + /// to the front (newest), each filled with the display so it hides those behind it. + #[allow(clippy::too_many_arguments)] + fn spectrum_waterfall( + history: Option<&SpecHistory>, + w: f32, + h: f32, + ceiling: f32, + range: f32, + color: Color, + paths: &mut Vec, + ) { + let depth = 0.38 * h; + let amp = 0.55 * h; + let inset = 0.1 * w; + let base = |k: f32| h - k * depth; + let span = |k: f32| (k * inset, w - k * inset); + // The floor: its outline and a few depth lines. + let (bl, br) = span(1.0); + let mut floor = format!("M0 {h:.1} L{w:.1} {h:.1} L{br:.1} {b:.1} L{bl:.1} {b:.1} Z ", b = base(1.0)); + for i in 1..4 { + let k = i as f32 / 4.0; + let (l, r) = span(k); + let _ = write!(floor, "M{l:.1} {y:.1} H{r:.1} ", y = base(k)); + } + paths.push(stroke(floor, white(0.08), 1.0)); + let Some(hist) = history.filter(|h| !h.frames.is_empty()) else { return }; + let n = hist.frames.len(); + let lines = n.min(MAX_LINES); + let bg = Color::from_rgb_u8(0x14, 0x15, 0x17); + for li in 0..lines { + // Oldest first: li = 0 is the back. + let fi = if lines == 1 { n - 1 } else { li * (n - 1) / (lines - 1) }; + let k = 1.0 - fi as f32 / (n.max(2) - 1) as f32; + let k = if n == 1 { 0.0 } else { k }; + let (l, r) = span(k); + let y0 = base(k); + let a = amp * (1.0 - 0.35 * k); + let vals = decimate(&hist.frames[fi], COLS); + let pts: Vec<(f32, f32)> = vals + .iter() + .enumerate() + .map(|(c, db)| { + let t = ((db - (ceiling - range)) / range).clamp(0.0, 1.0); + (l + (r - l) * (c as f32 + 0.5) / COLS as f32, y0 - t * a) + }) + .collect(); + let line = path(&pts); + paths.push(fill(format!("{line} L{:.1} {y0:.1} L{:.1} {y0:.1} Z", pts[pts.len() - 1].0, pts[0].0), bg)); + paths.push(stroke(line, rgba(color, 0.25 + 0.7 * (1.0 - k)), if k < 0.01 { 1.25 * Z } else { 1.0 })); + } + } + + /// The spectrogram: one row per frame (newest at the top), its level in STEPS inks. + #[allow(clippy::too_many_arguments)] + fn spectrogram( + history: Option<&SpecHistory>, + x0: f32, + y0: f32, + w: f32, + h: f32, + ceiling: f32, + range: f32, + color: Color, + paths: &mut Vec, + ) { + let Some(hist) = history.filter(|h| !h.frames.is_empty()) else { return }; + let n = hist.frames.len(); + let rows = n.min(MAX_ROWS); + let rh = h / rows as f32; + let cw = w / COLS as f32; + let mut inks: Vec = vec![String::new(); STEPS]; + for ri in 0..rows { + // Row 0 (top) is the newest. + let fi = n - 1 - ri * n / rows; + let vals = decimate(&hist.frames[fi], COLS); + let y = y0 + ri as f32 * rh; + let mut c = 0; + while c < COLS { + let step = |db: f32| ((((db - (ceiling - range)) / range).clamp(0.0, 1.0)) * STEPS as f32) as usize; + let s = step(vals[c]).min(STEPS); + let mut e = c + 1; + while e < COLS && step(vals[e]).min(STEPS) == s { + e += 1; + } + if s > 0 { + let _ = write!( + inks[s - 1], + "M{:.1} {y:.1} h{:.1} v{rh:.1} h{:.1} Z ", + x0 + c as f32 * cw, + (e - c) as f32 * cw, + -((e - c) as f32 * cw) + ); + } + c = e; + } + } + for (i, ink) in inks.into_iter().enumerate() { + if !ink.is_empty() { + paths.push(fill(ink, rgba(color, (i + 1) as f32 / STEPS as f32))); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn history_takes_each_sequence_once_and_keeps_the_depth() { + let mut h = SpecHistory::default(); + assert!(h.take(1, &[0.0; 4], 2)); + assert!(!h.take(1, &[1.0; 4], 2)); + assert!(h.take(2, &[2.0; 4], 2)); + assert!(h.take(3, &[3.0; 4], 2)); + assert_eq!(h.frames.len(), 2); + assert_eq!(h.frames[0][0], 2.0); + assert!(!h.take(0, &[4.0; 4], 2)); + } + + #[test] + fn decimate_keeps_the_loudest_band_of_each_span() { + let f: Vec = (0..256).map(|i| if i == 37 { 0.0 } else { -60.0 }).collect(); + let d = decimate(&f, 96); + assert_eq!(d.len(), 96); + assert_eq!(d.iter().filter(|v| **v == 0.0).count(), 1); + assert_eq!(peak_text(Some(-12.34)), "\u{2212}12.3 dB"); + assert_eq!(peak_text(None), "\u{2013}"); + } +} diff --git a/crates/dstudio-app/src/main.rs b/crates/dstudio-app/src/main.rs index 6108cb8f..45c5a7c9 100644 --- a/crates/dstudio-app/src/main.rs +++ b/crates/dstudio-app/src/main.rs @@ -59,6 +59,7 @@ mod device_window_dynamics; mod device_window_fields; mod device_window_multiband; mod device_window_shaper; +mod device_window_spectrum; mod device_window_wave; mod device_window_widener; mod devices; @@ -252,6 +253,8 @@ struct Args { track_rename_review: bool, /// reference-: that device alone in an audio track's chain (an instrument on an instrument track). device_state: Option<&'static str>, + /// A parameter the device-window review sets first (review-window-spectrum-2d / -split). + window_param: Option<(&'static str, f32)>, /// window-: as reference-, with the device's window open. device_window: bool, /// review-window-: a test signal runs through the device so its window's meters and @@ -677,6 +680,13 @@ fn parse_args() -> Result { a.device_state = s.strip_prefix("window-").and_then(dstudio_core::builtin::find).map(|d| d.id); a.device_window = true; } + st @ ("review-window-spectrum-2d" | "review-window-spectrum-split") => { + a.reference_default = true; + a.device_state = Some("spectrum"); + a.device_window = true; + a.window_signal = true; + a.window_param = Some(("display_mode", if st.ends_with("2d") { 0.0 } else { 2.0 })); + } s if s.strip_prefix("review-window-").and_then(dstudio_core::builtin::find).is_some() => { a.reference_default = true; a.device_state = s.strip_prefix("review-window-").and_then(dstudio_core::builtin::find).map(|d| d.id); @@ -741,7 +751,7 @@ fn parse_args() -> Result { } s => { return Err(format!( - "unknown state {s} (supported: reference-default, reference-mixer, reference-assistant, reference-midi-clip, reference-pianoroll, reference-synth, reference-input-menu, reference-settings-audio, reference-devices-effects, reference-automation, reference-live, review-automation, review-automation-picker, review-recording, review-midi-recording, review-settings-midi, review-shortcuts, review-shortcuts-recording, review-shortcuts-unmapped, review-shortcuts-tracks, review-shortcuts-notes, review-shortcuts-transpose, review-shortcuts-strip, review-shortcuts-zoom, review-shortcuts-move, review-shortcuts-mouse, review-shortcuts-preset-menu, review-shortcuts-logic, review-device-chain, review-devices-minimap, review-returns, review-returns-strip, review-returns-empty, review-returns-options, review-snap-menu, review-count-in-menu, review-clip-takes, review-track-menu, review-track-drag, review-clip-selection, review-transport-sig, review-transport-key, review-track-rename, review-audio-loop-drag, review-pr-zoom, review-pr-typing, review-pr-reverse, review-pr-velocity, reference- e.g. reference-compressor, window- and review-window- (expanded window, review- with a test signal), reference-lfo, reference-chain, review-settings-plugins, review-strip-trim, review-plugin-folders, review-analyzers, review-assistant-)" + "unknown state {s} (supported: reference-default, reference-mixer, reference-assistant, reference-midi-clip, reference-pianoroll, reference-synth, reference-input-menu, reference-settings-audio, reference-devices-effects, reference-automation, reference-live, review-automation, review-automation-picker, review-recording, review-midi-recording, review-settings-midi, review-shortcuts, review-shortcuts-recording, review-shortcuts-unmapped, review-shortcuts-tracks, review-shortcuts-notes, review-shortcuts-transpose, review-shortcuts-strip, review-shortcuts-zoom, review-shortcuts-move, review-shortcuts-mouse, review-shortcuts-preset-menu, review-shortcuts-logic, review-device-chain, review-devices-minimap, review-returns, review-returns-strip, review-returns-empty, review-returns-options, review-snap-menu, review-count-in-menu, review-clip-takes, review-track-menu, review-track-drag, review-clip-selection, review-transport-sig, review-transport-key, review-track-rename, review-audio-loop-drag, review-pr-zoom, review-pr-typing, review-pr-reverse, review-pr-velocity, reference- e.g. reference-compressor, window- and review-window- (expanded window, review- with a test signal), review-window-spectrum-<2d|split>, reference-lfo, reference-chain, review-settings-plugins, review-strip-trim, review-plugin-folders, review-analyzers, review-assistant-)" )); } }, @@ -2373,6 +2383,9 @@ fn run() -> Result<(), Box> { if args.device_window && let Some(d) = c.project().track(t).and_then(|t| t.devices.last()).map(|d| d.id) { + if let Some((param, value)) = args.window_param { + c.execute(dstudio_core::Command::SetDeviceParam { device: d, param: param.into(), value }); + } c.device_window(d); } if args.window_signal { From b42de8ed26959e10cc48ca94d39469390f3de48c Mon Sep 17 00:00:00 2001 From: Chris Laupama <42254688+chrislaupama@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:13:01 +0000 Subject: [PATCH 2/2] Place Spectrum history at its age; write curve coordinates without the float formatter The waterfall and spectrogram lay frames out by the History depth, so a history still filling up starts at the front (3D) or grows down from the top (Split). The waterfall draws up to 32 lines. path() and the spectrogram write one-decimal coordinates with an integer writer, which makes curve drawing in every expanded window about three times cheaper. The review signal polls the analyser and pre-rolls Spectrum long enough to fill its history. Docs updated. --- CHANGELOG.md | 4 + README.md | 3 +- crates/dstudio-app/src/device_canvas.rs | 47 ++++++++++- crates/dstudio-app/src/device_window.rs | 2 +- .../dstudio-app/src/device_window_spectrum.rs | 79 ++++++++++++++----- crates/dstudio-app/src/main.rs | 7 +- docs/devices.md | 8 +- 7 files changed, 122 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed20728e..4ff3e28f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,3 +62,7 @@ Nothing has been released yet. The first release, 0.1.0, will cover what is on ` field over frequency above a correlation lane that plots the input and output correlation of the last six seconds). The engine measures a built-in device's stereo correlation while its window is open (`se_builtin_correlation`). - An expanded window for Tuner: the card's tuner at twice its size across the display, with its input meter. +- An expanded window for Spectrum with three views: 2D (the spectrum, its peak hold and the slope guide on a dB + ladder), 3D (a waterfall of the last 32 to 256 frames) and Split (the spectrum over a spectrogram), with Hold view, + Reset, History and Color in its top bar and every analyser setting in one card. Curve drawing in every expanded + window is about three times cheaper (coordinates are written without the float formatter). diff --git a/README.md b/README.md index 3e472611..b76d87f7 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,8 @@ gain it applied, and Multiband Compressor, whose window draws each band's level, axis with draggable crossovers, and Delay, Echo and Reverb, whose window draws the card's echo train, tail picture or repeat EQ at full size with every control in a row below, Distortion, Tape Saturation and Soft Clipper, whose window draws the transfer curve beside a sine through the device, Bit Crusher, whose window draws one crushed cycle, Utility, and Stereo Widener, whose window draws the stereo -field over a live correlation lane, and Tuner; the other devices open their card in a window for now. +field over a live correlation lane, Tuner, and Spectrum, whose window shows the spectrum flat, as a 3D waterfall of its +history, or split over a spectrogram; the other devices open their card in a window for now. [docs/devices.md](docs/devices.md) explains how they work and how to add one. | Kind | Devices | diff --git a/crates/dstudio-app/src/device_canvas.rs b/crates/dstudio-app/src/device_canvas.rs index 8b7590f3..10efd08a 100644 --- a/crates/dstudio-app/src/device_canvas.rs +++ b/crates/dstudio-app/src/device_canvas.rs @@ -153,14 +153,46 @@ impl Plot { } pub(crate) fn path(pts: &[(f32, f32)]) -> String { - use std::fmt::Write; let mut out = String::with_capacity(pts.len() * 16); for (i, (x, y)) in pts.iter().enumerate() { - let _ = write!(out, "{}{x:.1} {y:.1}", if i == 0 { "M" } else { " L" }); + out.push_str(if i == 0 { "M" } else { " L" }); + push_tenths(&mut out, *x); + out.push(' '); + push_tenths(&mut out, *y); } out } +/// Appends `v` to one decimal, as `{:.1}` would, without the float formatter: windows +/// rebuild every frame and their curves hold thousands of coordinates. +pub(crate) fn push_tenths(out: &mut String, v: f32) { + let t = (v * 10.0).round(); + if !t.is_finite() || t.abs() > 1.0e9 { + use std::fmt::Write; + let _ = write!(out, "{v:.1}"); + return; + } + let t = t as i64; + if t < 0 { + out.push('-'); + } + let a = t.unsigned_abs(); + let mut buf = [0u8; 20]; + let mut i = buf.len(); + let mut w = a / 10; + loop { + i -= 1; + buf[i] = b'0' + (w % 10) as u8; + w /= 10; + if w == 0 { + break; + } + } + out.push_str(std::str::from_utf8(&buf[i..]).unwrap_or("0")); + out.push('.'); + out.push((b'0' + (a % 10) as u8) as char); +} + /// Closed area between a curve and the horizontal line at `base`. fn area(pts: &[(f32, f32)], base: f32) -> String { // A flat area has nothing to fill (and a zero-height fill leaves rendering fringes). @@ -1593,6 +1625,17 @@ impl Controller { mod tests { use super::*; + #[test] + fn tenths_match_the_float_formatter() { + for v in [0.0f32, 0.04, 0.06, -0.06, 1.25, -3.75, 12.34, 999.95, -1234.56, 0.5, 7.0] { + let mut s = String::new(); + push_tenths(&mut s, v); + let want = format!("{:.1}", (v * 10.0).round() / 10.0); + assert_eq!(s, want, "{v}"); + } + assert_eq!(path(&[(1.0, 2.0), (-3.5, 4.25)]), "M1.0 2.0 L-3.5 4.3"); + } + #[test] fn plot_maps_log_frequency_and_db() { let p = Plot { w: 400.0, h: 200.0, top_db: 24.0, bottom_db: -24.0, axis: 0.0, park: 19.0 * Z }; diff --git a/crates/dstudio-app/src/device_window.rs b/crates/dstudio-app/src/device_window.rs index 6bfa7f75..441bfcef 100644 --- a/crates/dstudio-app/src/device_window.rs +++ b/crates/dstudio-app/src/device_window.rs @@ -3400,7 +3400,7 @@ mod tests { } assert_eq!(h.frames.len(), 128); let full_3d = view(&c, did, def).display.paths.row_count(); - assert!(full_3d >= empty_3d + 2 * 40, "{empty_3d} -> {full_3d}"); + assert!(full_3d >= empty_3d + 2 * 32, "{empty_3d} -> {full_3d}"); c.execute(Command::SetDeviceParam { device: did, param: "display_mode".into(), value: 2.0 }); let split = view(&c, did, def); let well = split.boxes.iter().find(|b| b.kind == BOX_DISPLAY).unwrap(); diff --git a/crates/dstudio-app/src/device_window_spectrum.rs b/crates/dstudio-app/src/device_window_spectrum.rs index f9de1178..9134f312 100644 --- a/crates/dstudio-app/src/device_window_spectrum.rs +++ b/crates/dstudio-app/src/device_window_spectrum.rs @@ -7,7 +7,7 @@ use crate::PanelCanvas; use crate::analyzer_views::{SPECTRUM_BANDS, spectrum_color}; use crate::controller::Controller; -use crate::device_canvas::{dashed, fill, path, rgba, stroke, text, white}; +use crate::device_canvas::{dashed, fill, path, push_tenths, rgba, stroke, text, white}; use crate::device_panel::Z; use crate::device_window::Kit; use crate::{PanelPath, PanelText}; @@ -32,7 +32,7 @@ pub(crate) const MODE_SPLIT: i32 = 2; const SPLIT_2D_H: f32 = 242.0; pub(crate) const SPLIT_GRAM_Y: f32 = 278.0; /// Most waterfall lines and spectrogram rows drawn, and points / columns per row. -const MAX_LINES: usize = 40; +const MAX_LINES: usize = 32; const MAX_ROWS: usize = 64; const COLS: usize = 96; /// Spectrogram ink steps. @@ -120,6 +120,7 @@ impl Controller { let mut texts: Vec = Vec::new(); let frame = self.spectrum_frame(d.id); let history = self.win_spec_history(d.id); + let depth = DEPTHS[(v("history_depth", 3.0).round().max(0.0) as usize).min(DEPTHS.len() - 1)]; // Caption: the loudest peak and the transport; the tilt on the right. let cy = -(pt - 18.0) * Z; @@ -136,7 +137,7 @@ impl Controller { texts.push(text(pw, cy, 160.0 * Z, tilt, dim, 10.0 * Z, 2)); if mode == MODE_3D { - Self::spectrum_waterfall(history, pw, ph, ceiling, range, color, &mut paths); + Self::spectrum_waterfall(history, depth, pw, ph, ceiling, range, color, &mut paths); } else { let h2 = if mode == MODE_SPLIT { SPLIT_2D_H * Z } else { ph }; Self::spectrum_2d(frame, pw, h2, ceiling, range, slope, color, &mut paths, &mut texts); @@ -144,7 +145,7 @@ impl Controller { let (gx, gy) = (-pl * Z, SPLIT_GRAM_Y * Z); let (gw, gh) = (dw * Z, ph + pb * Z - gy); paths.push(fill(format!("M{gx:.1} {gy:.1} h{gw:.1} v{gh:.1} h{:.1} Z", -gw), Color::from_rgb_u8(0, 0, 0))); - Self::spectrogram(history, gx, gy, gw, gh, ceiling, range, color, &mut paths); + Self::spectrogram(history, depth, gx, gy, gw, gh, ceiling, range, color, &mut paths); } } PanelCanvas { @@ -218,8 +219,10 @@ impl Controller { /// The waterfall: up to MAX_LINES frames from the back (oldest, raised and narrowed) /// to the front (newest), each filled with the display so it hides those behind it. #[allow(clippy::too_many_arguments)] + #[allow(clippy::too_many_arguments)] fn spectrum_waterfall( history: Option<&SpecHistory>, + depth_frames: usize, w: f32, h: f32, ceiling: f32, @@ -242,14 +245,18 @@ impl Controller { } paths.push(stroke(floor, white(0.08), 1.0)); let Some(hist) = history.filter(|h| !h.frames.is_empty()) else { return }; + // Lines sit at their age on the floor: the back is the oldest frame the history keeps, + // so a history still filling up starts at the front. let n = hist.frames.len(); - let lines = n.min(MAX_LINES); + let full = depth_frames.max(n).max(2); + let stride = full.div_ceil(MAX_LINES); + let lines = n.div_ceil(stride); let bg = Color::from_rgb_u8(0x14, 0x15, 0x17); - for li in 0..lines { - // Oldest first: li = 0 is the back. - let fi = if lines == 1 { n - 1 } else { li * (n - 1) / (lines - 1) }; - let k = 1.0 - fi as f32 / (n.max(2) - 1) as f32; - let k = if n == 1 { 0.0 } else { k }; + for li in (0..lines).rev() { + // Oldest first: the largest age is drawn first, at the back. + let age = li * stride; + let fi = n - 1 - age; + let k = age as f32 / (full - 1) as f32; let (l, r) = span(k); let y0 = base(k); let a = amp * (1.0 - 0.35 * k); @@ -272,6 +279,7 @@ impl Controller { #[allow(clippy::too_many_arguments)] fn spectrogram( history: Option<&SpecHistory>, + depth_frames: usize, x0: f32, y0: f32, w: f32, @@ -282,14 +290,17 @@ impl Controller { paths: &mut Vec, ) { let Some(hist) = history.filter(|h| !h.frames.is_empty()) else { return }; + // Rows are sized for the whole history, so one still filling up grows down from the top. let n = hist.frames.len(); - let rows = n.min(MAX_ROWS); - let rh = h / rows as f32; + let full = depth_frames.max(n).max(1); + let stride = full.div_ceil(MAX_ROWS); + let rh = h / full.div_ceil(stride) as f32; + let rows = n.div_ceil(stride); let cw = w / COLS as f32; let mut inks: Vec = vec![String::new(); STEPS]; for ri in 0..rows { // Row 0 (top) is the newest. - let fi = n - 1 - ri * n / rows; + let fi = n - 1 - ri * stride; let vals = decimate(&hist.frames[fi], COLS); let y = y0 + ri as f32 * rh; let mut c = 0; @@ -301,13 +312,18 @@ impl Controller { e += 1; } if s > 0 { - let _ = write!( - inks[s - 1], - "M{:.1} {y:.1} h{:.1} v{rh:.1} h{:.1} Z ", - x0 + c as f32 * cw, - (e - c) as f32 * cw, - -((e - c) as f32 * cw) - ); + let (o, rw) = (&mut inks[s - 1], (e - c) as f32 * cw); + o.push('M'); + push_tenths(o, x0 + c as f32 * cw); + o.push(' '); + push_tenths(o, y); + o.push_str(" h"); + push_tenths(o, rw); + o.push_str(" v"); + push_tenths(o, rh); + o.push_str(" h"); + push_tenths(o, -rw); + o.push_str(" Z "); } c = e; } @@ -336,6 +352,29 @@ mod tests { assert!(!h.take(0, &[4.0; 4], 2)); } + /// A history still filling up keeps its rows and lines at their age: the spectrogram + /// grows down from the top and the waterfall starts at the front. + #[test] + fn a_short_history_sits_at_its_age() { + let mut h = SpecHistory::default(); + for i in 1..=3u64 { + h.take(i, &[-10.0; 256], 64); + } + let mut paths = Vec::new(); + Controller::spectrogram(Some(&h), 64, 0.0, 0.0, 96.0, 64.0, 0.0, 90.0, Color::from_rgb_u8(255, 0, 0), &mut paths); + let ys: Vec = paths + .iter() + .flat_map(|p| p.commands.split('M').skip(1).map(|r| r.split_whitespace().nth(1).unwrap().parse::().unwrap())) + .collect(); + assert!(!ys.is_empty() && ys.iter().all(|y| *y < 3.5), "{ys:?}"); + let mut lines = Vec::new(); + Controller::spectrum_waterfall(Some(&h), 32, 400.0, 200.0, 0.0, 90.0, Color::from_rgb_u8(255, 0, 0), &mut lines); + // Floor, then a fill and a stroke per line; every line sits near the front edge. + assert_eq!(lines.len(), 1 + 2 * 3); + let first_x: f32 = lines[1].commands[1..].split_whitespace().next().unwrap().parse().unwrap(); + assert!(first_x < 5.0, "the oldest of three frames is drawn at the front, not the back: {first_x}"); + } + #[test] fn decimate_keeps_the_loudest_band_of_each_span() { let f: Vec = (0..256).map(|i| if i == 37 { 0.0 } else { -60.0 }).collect(); diff --git a/crates/dstudio-app/src/main.rs b/crates/dstudio-app/src/main.rs index 45c5a7c9..7bc3d174 100644 --- a/crates/dstudio-app/src/main.rs +++ b/crates/dstudio-app/src/main.rs @@ -1376,6 +1376,7 @@ impl WindowSignal { c.set_status(format!("review-window: {e}"), 10); return; } + c.panel_poll_views_at(at); c.poll_window_meters_at(at); } } @@ -2396,8 +2397,10 @@ fn run() -> Result<(), Box> { c.execute(dstudio_core::Command::SetTrackMonitor { track: t, monitor: true }); c.set_track_input(t, Some(dstudio_core::InputSource { channel: 0, stereo: false })); let mut sig = WindowSignal::default(); - let mut at = Instant::now() - Duration::from_millis(990); - for _ in 0..33 { + // Spectrum renders long enough to fill its window's 128-frame history. + let pre = if id == "spectrum" { 160 } else { 33 }; + let mut at = Instant::now() - Duration::from_millis(30 * pre as u64); + for _ in 0..pre { sig.step(&mut c, at); at += Duration::from_millis(30); } diff --git a/docs/devices.md b/docs/devices.md index ea8ed5e4..4a0dd5b4 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -67,7 +67,7 @@ flowchart LR Flanger, Phaser, Ring Mod and Character Mod; and the dynamics family: Compressor, Limiter, Gate, Glue Compressor, Character Compressor and Mastering Limiter; Transient Shaper; Multiband Compressor; Delay, Echo and Reverb; Distortion, Tape Saturation, - Soft Clipper and Bit Crusher; Utility, Stereo Widener and Tuner), otherwise the card itself in a window. A + Soft Clipper and Bit Crusher; Utility, Stereo Widener, Tuner and Spectrum), otherwise the card itself in a window. A window is a face 960 pt wide (Ring Mod 860): a top bar (power, presets, the device's header pills), a large display (the card's canvas drawn at window size with its axis and legend), In / Out meters, and rows of controls laid out with the same @@ -128,7 +128,11 @@ flowchart LR `se_builtin_correlation` (`Engine::builtin_correlation`): while metering is on the audio thread sums L·R, L² and R² of the input and the output of each block, and each poll takes them as a correlation per side (2 where a side - was silent). The + was silent). The Spectrum window (src/device_window_spectrum.rs) keeps + its own history of analyser frames (`SpecHistory`, as deep as the History + picker, frozen by Hold view, cleared by Reset) and draws it as a waterfall + (up to 32 lines) or a spectrogram (up to 64 rows), each frame placed at its + age so a history still filling up starts at the front. The meters read `se_builtin_set_metering` / `se_builtin_levels` (`Engine::builtin_levels(id, &mut [f32; 4])`): while a window is open the audio thread keeps the input and output peak of each block, and the app