From 55895aedb5e709ca7f5a674eb60c572e25178df9 Mon Sep 17 00:00:00 2001 From: Chris Laupama <42254688+chrislaupama@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:57:53 +0000 Subject: [PATCH] Add expanded windows for Compressor, Limiter, Gate and Glue Compressor --- CHANGELOG.md | 3 + README.md | 5 +- crates/dstudio-app/src/device_panel.rs | 2 +- crates/dstudio-app/src/device_window.rs | 280 ++++++++++- .../dstudio-app/src/device_window_dynamics.rs | 456 ++++++++++++++++++ crates/dstudio-app/src/main.rs | 1 + docs/devices.md | 13 +- 7 files changed, 753 insertions(+), 7 deletions(-) create mode 100644 crates/dstudio-app/src/device_window_dynamics.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e6320fc..ebedbedf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,3 +37,6 @@ Nothing has been released yet. The first release, 0.1.0, will cover what is on ` - An expanded window for Character Mod: the circuit's motion in its own unit (delay, sweep, gain or pan) with the band it travels and a legend, the circuit and LFO controls on one card, and a rack card with Input, the circuit's artifacts, Depth-M and Depth-S, Seed (click for the next take), Mono and Output. +- Expanded windows for Compressor, Limiter, Gate and Glue Compressor: the last 1, 4 or 10 seconds of input, output and + gain reduction (Hold view freezes it) under a threshold or ceiling line you can drag, a transfer curve with the live + operating point beside the main controls, In and Out meters and every control laid out in rows. diff --git a/README.md b/README.md index 71f45b65..e65086d3 100644 --- a/README.md +++ b/README.md @@ -123,8 +123,9 @@ Device comes with 44 devices of its own. Each one is a single declarative defini factory presets) that the model, undo, saving, automation, engine and panel all derive from, with a C++ DSP kernel behind it. Auto Filter, Channel EQ and Character EQ also open an expanded window with a large display and live analyser, In and Out meters and every control laid out in rows, and so do Tremolo, Auto-Panner, Chorus, Flanger, Phaser, -Ring Mod and Character Mod, whose window plots their motion or response with a time or frequency axis and a legend; the other devices -open their card in a window for now. +Ring Mod and Character Mod, whose window plots their motion or response with a time or frequency axis and a legend, and +Compressor, Limiter, Gate and Glue Compressor, whose window scrolls the last 1, 4 or 10 seconds of input, output and gain +reduction under a draggable threshold, beside a transfer curve; 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_panel.rs b/crates/dstudio-app/src/device_panel.rs index c3c9f449..3b43e44c 100644 --- a/crates/dstudio-app/src/device_panel.rs +++ b/crates/dstudio-app/src/device_panel.rs @@ -441,7 +441,7 @@ pub fn soft_knee_gr(x: f32, threshold: f32, ratio: f32, knee: f32) -> f32 { /// Static transfer curve (output dB for input dB) of a knob face, the input /// level the axis is laid out around and the span its knee highlight covers. /// None for \`Face::Transfer\`, whose curve the device computes. -fn face_law(face: Face, num: impl Fn(&str) -> f32) -> Option<(Box f32>, f32, (f32, f32))> { +pub(crate) fn face_law(face: Face, num: impl Fn(&str) -> f32) -> Option<(Box f32>, f32, (f32, f32))> { Some(match face { Face::SoftKneeCurve { threshold, ratio, knee } => { let (t, r, k) = (num(threshold), num(ratio), num(knee).max(0.0)); diff --git a/crates/dstudio-app/src/device_window.rs b/crates/dstudio-app/src/device_window.rs index da4c0941..f8acfdb5 100644 --- a/crates/dstudio-app/src/device_window.rs +++ b/crates/dstudio-app/src/device_window.rs @@ -77,6 +77,8 @@ pub(crate) const ACT_ANALYZER: i32 = 7; pub(crate) const ACT_HOLD: i32 = 8; /// Character Mod: play the next take (seed). pub(crate) const ACT_SEED: i32 = 9; +/// Dynamics windows: the history's length (value: index into 1 s, 4 s, 10 s). +pub(crate) const ACT_SPAN: i32 = 10; 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; @@ -88,7 +90,12 @@ pub(crate) const MENU_ANALYZER: i32 = -4; /// Devices with an expanded window. pub(crate) fn has_window(def: &DeviceDef) -> bool { - matches!(def.id, "auto-filter" | "channeleq" | "character-eq") || is_field_window(def) + matches!(def.id, "auto-filter" | "channeleq" | "character-eq") || is_field_window(def) || is_dynamics_window(def) +} + +/// Windows of the level-history family (src/device_window_dynamics.rs). +fn is_dynamics_window(def: &DeviceDef) -> bool { + crate::device_window_dynamics::spec(def.id).is_some() } /// Windows of the plotted-field family (motion and response pictures). @@ -127,6 +134,9 @@ pub(crate) fn kit(def: &DeviceDef) -> Kit { "phaser" => field_kit(WIN_W, 374.0, 56.0, 44.0), "ring-mod" => field_kit(860.0, 254.0, 40.0, 29.0), "character-mod" => field_kit(WIN_W, 222.0, 60.0, 44.0), + // The level-history family: the plot's ladder in a 52 pt column, the caption band above. + "compressor" | "limiter" | "gate" => field_kit(WIN_W, 394.0, 52.0, 6.0), + "glue-compressor" => field_kit(WIN_W, 282.0, 52.0, 6.0), _ => eq(56.0, 394.0), } } @@ -156,6 +166,11 @@ pub(crate) struct WinUi { /// Analyser frames of open windows. spectra: HashMap, clock: Option, + /// Level histories of the open dynamics windows, and the window each shows (s). + history: HashMap>, + span: HashMap, + /// Start of the histories' clock. + epoch: Option, } /// Which signal a window's analyser shows. @@ -541,6 +556,7 @@ impl Controller { Some(View::Eq(v)) => self.eq_window_field(d, def, v, accent), Some(View::Custom("auto-filter")) => self.auto_filter_window_field(d, def, accent), Some(View::Field(f)) => self.field_window_canvas(d, def, f, &k, accent), + _ if is_dynamics_window(def) => self.dynamics_window_canvas(d, def, &k, accent), _ => PanelCanvas::default(), }; display.x = (dx + k.plot.0) * Z; @@ -549,6 +565,7 @@ impl Controller { "auto-filter" => self.auto_filter_window(d, def, &mut b), "channeleq" => self.channel_eq_window(d, def, &mut b), "character-eq" => self.character_eq_window(d, def, &mut b), + _ if is_dynamics_window(def) => self.dynamics_window(d, def, &mut b, dy + dh + 12.0), _ => self.field_window(d, def, &mut b, dy + dh + 12.0), }; let (meters, ticks, ticks_x) = self.window_meters(d.id, &k); @@ -644,6 +661,31 @@ impl Controller { .filter(|id| self.project().device(*id).and_then(dstudio_core::builtin::def_of).is_some_and(has_window)) .collect(); self.devices.wins.meters.retain(|id, _| open.contains(id)); + self.devices.wins.history.retain(|id, _| open.contains(id)); + let epoch = *self.devices.wins.epoch.get_or_insert(now); + let t = now.duration_since(epoch).as_secs_f64(); + let mut out = Vec::new(); + for &id in &open { + let Some(sp) = self + .project() + .device(id) + .and_then(dstudio_core::builtin::def_of) + .and_then(|def| crate::device_window_dynamics::spec(def.id)) + else { + continue; + }; + if self.devices.wins.held.contains(&id) { + continue; + } + let (i, o, g) = match self.engine.builtin_readouts(id.0, &mut out) { + Ok(()) if out.len() >= 3 => (out[0], out[1], out[2].min(0.0)), + _ => (-120.0, -120.0, 0.0), + }; + let h = self.devices.wins.history.entry(id).or_default(); + if crate::device_window_dynamics::push(h, (t, i, o, g), sp.bottom) { + self.ui_dirty = true; + } + } self.devices.wins.spectra.retain(|id, _| open.contains(id)); let mut frame = Vec::new(); for &id in &open { @@ -1037,6 +1079,170 @@ impl Controller { rack.y + rack.h + 16.0 } + // ------------------------------------------------------------ Dynamics family + + pub(crate) fn win_span(&self, id: DeviceId, sp: &crate::device_window_dynamics::DynSpec) -> f32 { + self.devices.wins.span.get(&id).copied().unwrap_or(sp.span) + } + + pub(crate) fn win_held(&self, id: DeviceId) -> bool { + self.devices.wins.held.contains(&id) + } + + pub(crate) fn win_history(&self, id: DeviceId) -> Option<&std::collections::VecDeque> { + self.devices.wins.history.get(&id) + } + + /// The histories' clock now (s). + pub(crate) fn win_now(&self) -> f64 { + self.devices.wins.epoch.map_or(0.0, |e| Instant::now().duration_since(e).as_secs_f64()) + } + + pub(crate) fn project_playing(&self) -> bool { + self.engine.transport().playing + } + + /// Header and control cards of a level-history window: the window lengths (and the + /// Compressor's Hold view and style), then the device's controls with its transfer square. + fn dynamics_window(&self, d: &Device, def: &'static DeviceDef, b: &mut Builder, y: f32) -> f32 { + let Some(sp) = crate::device_window_dynamics::spec(def.id) else { return y }; + 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); + // Header, from the right: the style pills, Hold view, then the window lengths. + let span = self.win_span(d.id, &sp); + let mut x = b.w - INSET; + if def.id == "compressor" { + let style = val("style").round() as i32; + let items: Vec<(String, bool, i32)> = ["Clean", "Opto", "Punch", "Smooth"] + .iter() + .enumerate() + .map(|(i, l)| (l.to_string(), style == i as i32, i as i32)) + .collect(); + let w = Builder::row_w(&["Clean", "Opto", "Punch", "Smooth"], 8.0); + x -= w; + b.pill_row(PILL_CHOICE, idx("style"), x, 7.5, &items, 8.0, true); + b.rect(BOX_HEADER_RULE, x - 17.0, 11.5, 1.0, 20.0); + x -= 34.0 + 77.5; + b.pill(PILL_GHOST_LATCH, ACT_HOLD, 0, x, 10.5, 77.5, "Hold view", self.win_held(d.id)); + b.rect(BOX_HEADER_RULE, x - 17.0, 11.5, 1.0, 20.0); + x -= 34.0; + } + let widths = [33.2, 36.1, 40.8]; + x -= widths.iter().sum::() + 2.0 * 8.0; + for (i, (s, w)) in crate::device_window_dynamics::SPANS.iter().zip(widths).enumerate() { + b.pill(PILL_GHOST, ACT_SPAN, i as i32, x, 10.5, w, &format!("{s:.0}s"), (span - s).abs() < 1e-3); + x += w + 8.0; + } + + let sidechain = || { + let source = match d.sidechain { + None => "None".to_string(), + Some(t) => self.project().track(t).map_or_else(|| "Removed".to_string(), |t| t.name.clone()), + }; + Item::Picker(-1, source, "Sidechain", 112.0, false) + }; + let square = Item::Blank(86.0); + let row = Row::main(y); + let clusters: Vec<(Vec, f32)> = match def.id { + "compressor" => vec![ + (vec![Item::Knob("threshold", "Threshold", 2, 70.0, false), Item::Knob("ratio", "Ratio", 2, 70.0, false)], 10.0), + ( + vec![ + Item::Knob("attack", "Attack", 1, 52.0, false), + Item::Knob("release", "Release", 1, 52.0, false), + Item::Knob("knee", "Knee", 1, 52.0, false), + Item::Knob("makeup_gain", "Gain", 1, 52.0, false), + Item::Knob("mix", "Mix", 1, 52.0, false), + ], + 10.0, + ), + (vec![sidechain(), Item::Knob("sidechain_gain", "Sidechain Gain", 1, 82.0, d.sidechain.is_none())], 10.0), + (vec![square], 10.0), + (vec![Item::Knob("output_gain", "Output", 1, 52.0, false)], 10.0), + ], + "limiter" => vec![ + (vec![Item::Knob("input_gain", "Input", 1, 64.0, false)], 14.0), + (vec![Item::Knob("ceiling", "Ceiling", 2, 70.0, false), Item::Knob("release", "Release", 1, 64.0, false)], 14.0), + (vec![Item::Knob("lookahead", "Lookahead", 1, 64.0, false), Item::Toggle("true_peak", "True Peak", false)], 14.0), + (vec![square], 14.0), + (vec![Item::Knob("mix", "Mix", 1, 64.0, false), Item::Knob("output_gain", "Output", 1, 64.0, false)], 14.0), + ], + "gate" => vec![ + (vec![Item::Knob("threshold", "Threshold", 2, 70.0, false), Item::Knob("ratio", "Ratio", 1, 64.0, false)], 14.0), + ( + vec![ + Item::Knob("attack", "Attack", 1, 64.0, false), + Item::Knob("hold", "Hold", 1, 64.0, false), + Item::Knob("release", "Release", 1, 64.0, false), + ], + 14.0, + ), + (vec![square], 14.0), + ( + vec![ + Item::Knob("lookahead", "Lookahead", 1, 64.0, false), + Item::Knob("sidechain_hpf", "Sidechain HPF", 1, 82.0, false), + ], + 14.0, + ), + (vec![Item::Knob("mix", "Mix", 1, 64.0, false)], 14.0), + ], + _ => { + // The unit is in the column's name: the pills carry the numbers alone. + let pills = |id: &'static str| -> Vec<(&'static str, f32)> { + def.param(id).map_or_else(Vec::new, |p| { + p.choices.iter().enumerate().map(|(i, c)| (c.split(' ').next().unwrap_or(c), i as f32)).collect() + }) + }; + vec![ + (vec![Item::Knob("threshold", "Threshold", 2, 64.0, false), Item::Pills("ratio", pills("ratio"), "Ratio", 125.0)], 9.0), + (vec![square], 9.0), + ( + vec![ + Item::Pills("attack", pills("attack"), "Attack (ms)", 248.0), + Item::Pills("release", pills("release"), "Release (s)", 207.0), + ], + 9.0, + ), + ] + } + }; + // The square's column: find it to place the transfer canvas. + let widths: Vec = clusters + .iter() + .map(|(items, gap)| items.iter().map(Item::width).sum::() + gap * (items.len().saturating_sub(1)) as f32) + .collect(); + let sq_at = clusters.iter().position(|(items, _)| items.len() == 1 && matches!(items[0], Item::Blank(w) if w == 86.0)); + self.win_card(d, def, b, row, clusters); + if let Some(i) = sq_at { + let (xs, _) = gutter(INSET, b.w - 2.0 * INSET, &widths); + let mut sq = self.dynamics_square(d, def, accent_of(b)); + sq.x = (xs[i] + 4.0) * Z; + sq.y = (row.top() + 4.0) * Z; + b.square = sq; + } + if def.id != "glue-compressor" { + return row.y + row.h + 16.0; + } + let pills = |id: &'static str| -> Vec<(&'static str, f32)> { + def.param(id).map_or_else(Vec::new, |p| p.choices.iter().enumerate().map(|(i, c)| (*c, i as f32)).collect()) + }; + let rack = Row::rack(row.y + row.h + 12.0); + self.win_card( + d, + def, + b, + rack, + vec![ + (vec![sidechain(), Item::Pills("sc_hpf", pills("sc_hpf"), "SC HPF (Hz)", 207.0)], 9.0), + (vec![Item::Knob("range", "Range", 1, 52.0, false), Item::Knob("makeup", "Makeup", 1, 52.0, false)], 9.0), + (vec![Item::Knob("color", "Color", 1, 52.0, false), Item::Knob("mix", "Mix", 1, 52.0, false)], 9.0), + (vec![Item::Knob("output_gain", "Output", 1, 52.0, false)], 9.0), + ], + ); + rack.y + rack.h + 16.0 + } + // ------------------------------------------------------------ EQs /// Band pills of an EQ header: the selected band lit, bands out of the chain dimmed. @@ -1361,6 +1567,10 @@ impl Controller { let next = p.min + (cur + step).rem_euclid(span) as f32; self.panel_commit(Command::SetDeviceParam { device, param: p.id.into(), value: next }); } + (ACT_SPAN, _) => { + let span = crate::device_window_dynamics::SPANS[value.clamp(0, 2) as usize]; + self.devices.wins.span.insert(device, span); + } (ACT_HOLD, _) => { if !self.devices.wins.held.remove(&device) { self.devices.wins.held.insert(device); @@ -1553,6 +1763,72 @@ mod tests { } } + /// The dynamics windows: the level display with its threshold grip, a transfer square, + /// every control once inside the face, and span pills that pick the history window. + #[test] + fn dynamics_windows_show_levels_and_every_control() { + use slint::Model; + for id in ["compressor", "limiter", "gate", "glue-compressor"] { + let (mut c, did, def) = controller_with(id); + assert!(has_window(def), "{id}"); + let v = view(&c, did, def); + assert!(v.display.visible && v.display.zones.row_count() == 1, "{id}: threshold drag"); + assert!(v.square.visible && v.square.paths.row_count() > 0, "{id}: transfer square"); + let mut params = std::collections::HashSet::new(); + for k in v.knobs.iter() { + assert!(k.x >= 0.0 && k.x <= v.w && k.y > 0.0 && k.y < v.h, "{id}: {} outside", k.label); + assert!(params.insert(k.param), "{id}: {} shown twice", k.label); + } + let lit = |c: &Controller| { + view(c, did, def).pills.iter().filter(|p| p.param == ACT_SPAN && p.active).map(|p| p.label.to_string()).collect::>() + }; + c.win_action(did, ACT_SPAN, 0); + assert_eq!(lit(&c), ["1s"], "{id}"); + c.win_action(did, ACT_SPAN, 2); + assert_eq!(lit(&c), ["10s"], "{id}"); + } + } + + /// A full ten-second history draws as one line per series, however many samples it holds. + #[test] + fn dynamics_history_draws_once_per_series() { + use slint::Model; + let (mut c, did, def) = controller_with("compressor"); + let empty = view(&c, did, def).display.paths.row_count(); + let h: std::collections::VecDeque<_> = (0..600).map(|i| (i as f64 / 60.0, -12.0, -18.0, -6.0)).collect(); + c.devices.wins.history.insert(did, h); + c.devices.wins.epoch = Some(Instant::now() - std::time::Duration::from_secs(10)); + let full = view(&c, did, def).display.paths.row_count(); + assert!(full > empty && full < empty + 12, "{empty} -> {full}"); + } + + /// Cost of rebuilding a dynamics window with a full history, against its card + /// (`cargo test -p dstudio-app --release bench_dynamics_windows -- --ignored --nocapture`). + #[test] + #[ignore] + fn bench_dynamics_windows() { + let n = 500; + for id in ["compressor", "limiter", "gate", "glue-compressor"] { + 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)); + let d = c.project().device(did).unwrap().clone(); + let t0 = std::time::Instant::now(); + for _ in 0..n { + std::hint::black_box(c.builtin_card(&d, def)); + } + let card = t0.elapsed().as_secs_f64() * 1e6 / n as f64; + let t0 = std::time::Instant::now(); + for _ in 0..n { + std::hint::black_box(view(&c, did, def)); + } + let win = t0.elapsed().as_secs_f64() * 1e6 / n as f64; + println!("{id:<15} card {card:7.1} us window {win:7.1} us"); + } + } + /// Character Mod: two cards; the rack drops the artifacts a circuit lacks, and the /// Seed pill plays the next take, wrapping at the end. #[test] @@ -1596,7 +1872,7 @@ mod tests { assert!(seen[1].iter().any(|n| n == "Threshold"), "{:?}", seen[1]); assert!(seen[4].iter().any(|n| n == "Amount"), "{:?}", seen[4]); // A device without a window keeps its card. - let (c, did, def) = controller_with("compressor"); + let (c, did, def) = controller_with("device-rack"); assert!(!has_window(def)); let d = c.project().device(did).unwrap().clone(); assert!(c.window_view(&d, def, Color::from_rgb_u8(0, 0, 0)).is_none()); diff --git a/crates/dstudio-app/src/device_window_dynamics.rs b/crates/dstudio-app/src/device_window_dynamics.rs new file mode 100644 index 00000000..7f088f91 --- /dev/null +++ b/crates/dstudio-app/src/device_window_dynamics.rs @@ -0,0 +1,456 @@ +//! Expanded windows of the level-history family (Compressor, Limiter, Gate, Glue +//! Compressor): the scrolling display and its transfer square. +//! +//! The display stacks two views on one time axis: a gain-reduction lane (0 to +//! -18 dB, its caption reading the reduction now and its peak over the window) +//! and the level plot under it (input, the reduction band down to the level +//! before makeup, output, and the threshold or ceiling as a dashed line with a +//! grip pill at the oldest edge, which drags it). One px/dB serves both views. +//! The history is the window's own (src/device_window.rs polls in, out and +//! gain reduction while the window is open) and spans 1, 4 or 10 seconds. + +use crate::controller::Controller; +use crate::device_canvas::{MUTE_TEXT, fill, rgba, stroke, text, white}; +use crate::device_panel::Z; +use crate::device_window::Kit; +use crate::{PanelCanvas, PanelGrip, PanelPath, PanelText, PanelZone}; +use dstudio_core::Device; +use dstudio_core::builtin::DeviceDef; +use slint::{Color, ModelRc, SharedString, VecModel}; +use std::collections::VecDeque; +use std::rc::Rc; + +fn model(v: Vec) -> ModelRc { + ModelRc::from(Rc::new(VecModel::from(v))) +} + +/// One history sample: (seconds, input dB, output dB, gain reduction dB <= 0). +pub(crate) type Sample = (f64, f32, f32, f32); + +/// The longest window (s); older samples are dropped. +pub(crate) const SPAN_MAX: f64 = 10.5; +/// Window lengths offered in the header (s). +pub(crate) const SPANS: [f32; 3] = [1.0, 4.0, 10.0]; + +/// Display constants (reference points). +const PAD: f32 = 6.0; +const CAP_H: f32 = 19.0; +const LANE_GAP: f32 = 20.0; +const TIME_H: f32 = 38.0; +const GR_FLOOR: f32 = -18.0; +const LANE_R: f32 = 4.0; +/// A sample at the floor (or within this of it) is silence: no ink. +const FLOOR_EPS: f32 = 0.3; + +/// The family's per-device picture. +pub(crate) struct DynSpec { + /// Level plot range (dB) and its ladder step. + pub top: f32, + pub bottom: f32, + pub step: f32, + /// The dashed line's parameter and its pill name. + pub line: &'static str, + pub line_name: &'static str, + /// The trace before makeup (Compressor's Gain) drawn and listed. + pub pre_gain: bool, + /// Detector entry in the legend (dimmed while nothing feeds it). + pub detector: bool, + /// Default window (s). + pub span: f32, +} + +pub(crate) fn spec(id: &str) -> Option { + let s = |top, bottom, step, line, line_name, pre_gain, detector, span| DynSpec { + top, + bottom, + step, + line, + line_name, + pre_gain, + detector, + span, + }; + Some(match id { + "compressor" => s(0.0, -36.0, 6.0, "threshold", "Threshold", true, true, 10.0), + "limiter" => s(12.0, -30.0, 6.0, "ceiling", "Ceiling", false, false, 4.0), + "gate" => s(12.0, -60.0, 12.0, "threshold", "Threshold", false, false, 4.0), + "glue-compressor" => s(0.0, -48.0, 6.0, "threshold", "Threshold", false, true, 4.0), + _ => return None, + }) +} + +/// The lane and plot geometry of a display h pt high (plot-local, reference points): +/// (lane height, plot top, plot height, px per dB). +pub(crate) fn geometry(sp: &DynSpec, display_h: f32) -> (f32, f32, f32, f32) { + let avail = display_h - PAD * 2.0 - CAP_H - LANE_GAP - TIME_H; + let per_db = avail / (-GR_FLOOR + (sp.top - sp.bottom)); + let lane = per_db * -GR_FLOOR; + (lane, lane + LANE_GAP, per_db * (sp.top - sp.bottom), per_db) +} + +/// A gain-reduction amount as the caption reads it: "0.0", "−3.2". +fn gr_text(gr: f32) -> String { + if gr < -0.05 { format!("\u{2212}{:.1}", -gr) } else { "0.0".into() } +} + +fn db_rung(db: f32) -> String { + if db > 0.5 { + format!("+{db:.0}") + } else if db < -0.5 { + format!("\u{2212}{:.0}", -db) + } else { + "0".into() + } +} + +/// Polylines through the points whose value clears the floor; a run below it is silence. +fn runs(pts: &[(f32, f32, bool)]) -> String { + let mut out = String::new(); + let mut open = false; + for (x, y, audible) in pts { + if *audible { + out.push_str(&format!("{}{x:.1} {y:.1} ", if open { "L" } else { "M" })); + open = true; + } else { + open = false; + } + } + out +} + +impl Controller { + /// The display of a level-history window. + pub(crate) fn dynamics_window_canvas(&self, d: &Device, def: &'static DeviceDef, k: &Kit, accent: Color) -> PanelCanvas { + let Some(sp) = spec(def.id) else { return PanelCanvas::default() }; + let (_, _, dw, dh) = k.display; + let (l, _, r, _) = k.plot; + let pw = (dw - l - r) * Z; + let (lane_h, plot_t, plot_h, per_db) = geometry(&sp, dh); + let (lane_h, plot_t, plot_h) = (lane_h * Z, plot_t * Z, plot_h * Z); + let span = self.win_span(d.id, &sp); + let held = self.win_held(d.id); + let hist = self.win_history(d.id); + let now = self.win_now(); + let mut paths: Vec = Vec::new(); + let mut texts: Vec = Vec::new(); + + let db_y = |db: f32| plot_t + ((sp.top - db) / (sp.top - sp.bottom)).clamp(0.0, 1.0) * plot_h; + let gr_y = |gr: f32| (gr / GR_FLOOR).clamp(0.0, 1.0) * lane_h; + let grid = if span <= 1.0 { + 0.25 + } else if span <= 4.0 { + 1.0 + } else { + 2.0 + }; + let at = hist.and_then(|h| h.back().map(|s| s.0)).filter(|_| held).unwrap_or(now); + let x_of = |t: f64| ((1.0 - (at - t) as f32 / span) * pw).clamp(0.0, pw); + // Samples inside the window, about one per 2 px. + let pts: Vec = hist + .map(|h| { + let from = at - span as f64; + let mut v: Vec = Vec::new(); + let mut last_x = f32::MIN; + for s in h.iter().filter(|s| s.0 >= from - 0.05) { + let x = x_of(s.0); + if x - last_x >= 2.0 * Z || v.is_empty() { + v.push(*s); + last_x = x; + } else if let Some(p) = v.last_mut() { + // Keep the deepest reduction and the loudest levels of a merged column. + *p = (s.0, p.1.max(s.1), p.2.max(s.2), p.3.min(s.3)); + } + } + v + }) + .unwrap_or_default(); + let gr_now = pts.last().map_or(0.0, |s| s.3); + let gr_peak = pts.iter().map(|s| s.3).fold(0.0f32, f32::min); + + // Caption: the reduction now, then its peak over the window. + let base = -(CAP_H - 6.0) * Z; + let label = "Gain Reduction"; + texts.push(PanelText { weight: 700, ..text(2.0 * Z, base, 120.0 * Z, label, MUTE_TEXT, 12.0 * Z, 0) }); + let vx = 2.0 * Z + (crate::text_measure::value_width(label) * 1.2 + 12.0) * Z; + let value = format!("{} dB", gr_text(gr_now)); + texts.push(text(vx, base - 0.3 * Z, 80.0 * Z, value.clone(), white(0.92), 13.0 * Z, 0)); + let px = vx + (crate::text_measure::value_width(&value) * 1.3 + 12.0) * Z; + texts.push(text(px, base, 80.0 * Z, format!("Peak {}", gr_text(gr_peak)), white(0.55), 11.0 * Z, 0)); + + // The lane: a light box, time rules, the reduction filled down from its top edge. + let r = LANE_R * Z; + let lane_box = format!( + "M{r:.1} 0 L{:.1} 0 Q{pw:.1} 0 {pw:.1} {r:.1} L{pw:.1} {:.1} Q{pw:.1} {lane_h:.1} {:.1} {lane_h:.1} L{r:.1} {lane_h:.1} Q0 {lane_h:.1} 0 {:.1} L0 {r:.1} Q0 0 {r:.1} 0 Z", + pw - r, + lane_h - r, + pw - r, + lane_h - r + ); + paths.push(fill(lane_box.clone(), white(0.035))); + let mut sec = grid; + while sec < span - 1e-3 { + let x = ((1.0 - sec / span) * pw).round() + 0.5; + paths.push(stroke(format!("M{x:.1} 0 L{x:.1} {lane_h:.1}"), white(0.04), 1.0)); + sec += grid; + } + for g in [6.0, 12.0] { + let y = gr_y(-g).round() + 0.5; + paths.push(stroke(format!("M0 {y:.1} L{pw:.1} {y:.1}"), white(0.05), 1.0)); + } + for g in [0.0f32, 6.0, 12.0, 18.0] { + texts.push(text(-8.0 * Z, gr_y(-g), 40.0 * Z, db_rung(-g), white(0.3), 11.0 * Z, 2)); + } + if pts.len() > 1 { + let line: Vec<(f32, f32)> = pts.iter().map(|s| (x_of(s.0), gr_y(s.3))).collect(); + let mut area = format!("M{:.1} 0 ", line[0].0); + for (x, y) in &line { + area.push_str(&format!("L{x:.1} {y:.1} ")); + } + area.push_str(&format!("L{:.1} 0 Z", line[line.len() - 1].0)); + paths.push(fill(area, rgba(accent, 0.55))); + paths.push(stroke(crate::device_canvas::path(&line), accent, 1.25 * Z)); + } + paths.push(stroke(lane_box, white(0.06), 1.0)); + + // The level plot: time rules, the ladder, then the traces. + let mut sec = grid; + while sec < span - 1e-3 { + let x = ((1.0 - sec / span) * pw).round() + 0.5; + paths.push(stroke(format!("M{x:.1} {plot_t:.1} L{x:.1} {:.1}", plot_t + plot_h), white(0.05), 1.0)); + sec += grid; + } + let mut db = sp.top; + while db >= sp.bottom - 1e-3 { + let y = db_y(db).round() + 0.5; + let strong = db.abs() < 1e-3; + paths.push(stroke(format!("M0 {y:.1} L{pw:.1} {y:.1}"), white(if strong { 0.13 } else { 0.05 }), 1.0)); + texts.push(text(-8.0 * Z, db_y(db), 40.0 * Z, db_rung(db), white(0.3), 11.0 * Z, 2)); + db -= sp.step; + } + texts.push(text(-8.0 * Z, plot_t + plot_h + 9.0 * Z, 40.0 * Z, "dBFS", white(0.3), 9.0 * Z, 2)); + let audible = |db: f32| db > sp.bottom + FLOOR_EPS; + let trace = |f: &dyn Fn(&Sample) -> f32| -> String { + runs(&pts.iter().map(|s| (x_of(s.0), db_y(f(s)), audible(f(s)))).collect::>()) + }; + let pre = |s: &Sample| s.1 + s.3; + paths.push(stroke(trace(&|s| s.1), white(0.55), 1.0)); + // The band between input and the level before makeup is the reduction. + if pts.iter().any(|s| s.3 < -0.1 && audible(s.1)) { + let mut band = String::new(); + for (i, s) in pts.iter().enumerate() { + band.push_str(&format!("{}{:.1} {:.1} ", if i == 0 { "M" } else { "L" }, x_of(s.0), db_y(s.1))); + } + for s in pts.iter().rev() { + band.push_str(&format!("L{:.1} {:.1} ", x_of(s.0), db_y(pre(s)))); + } + band.push('Z'); + paths.push(fill(band, rgba(accent, 0.22))); + } + paths.push(stroke(trace(&|s| s.1), rgba(accent, 0.85), 1.25 * Z)); + if sp.pre_gain { + paths.push(stroke(trace(&pre), rgba(accent, 0.75), 1.0)); + } + let out = trace(&|s| s.2); + paths.push(stroke(out.clone(), Color::from_argb_u8(140, 0, 0, 0), 3.5 * Z)); + paths.push(stroke(out, white(1.0), 1.75 * Z)); + + // Time axis: one label per rule, the window's start at the left, its state at the right. + let ty = plot_t + plot_h + 11.0 * Z; + let mut sec = grid; + while sec < span - 1e-3 { + let x = (1.0 - sec / span) * pw; + if pw - x >= 24.0 * Z { + let label = if sec.fract() > 1e-3 { format!("\u{2212}{sec:.2}s") } else { format!("\u{2212}{sec:.0}s") }; + texts.push(text(x, ty, 60.0 * Z, label, white(0.5), 9.0 * Z, 1)); + } + sec += grid; + } + texts.push(text(0.0, ty, 60.0 * Z, format!("\u{2212}{span:.0}s"), white(0.5), 9.0 * Z, 0)); + let state = if held { + "held" + } else if self.project_playing() { + "now" + } else { + "stopped" + }; + texts.push(text(pw, ty, 60.0 * Z, state, white(0.5), 9.0 * Z, 2)); + + // Legend: every series drawn, the detector dimmed while nothing feeds it. + let ly = plot_t + plot_h + 31.0 * Z; + let (glyph, gap, entry) = (14.0 * Z, 6.0 * Z, 16.0 * Z); + let sidechain = d.sidechain.is_some(); + let thresh_ink = Color::from_argb_u8(140, 200, 198, 188); + let detector_ink = Color::from_argb_u8(115, 200, 198, 188); + let mut entries: Vec<(&str, u8)> = vec![("Input", 0), ("Output", 1)]; + if sp.pre_gain { + entries.push(("Pre-Gain", 2)); + } + entries.push(("Reduction", 3)); + if sp.detector && def.id == "compressor" { + entries.push(("Detector", 4)); + } + entries.push((sp.line_name, 5)); + if sp.detector && def.id != "compressor" { + entries.push(("Detector", 4)); + } + let mut x = 0.0; + for (name, kind) in entries { + let dim = kind == 4 && !sidechain; + let a = if dim { 0.35 } else { 1.0 }; + let line = format!("M{x:.1} {ly:.1} L{:.1} {ly:.1}", x + glyph); + match kind { + 0 => paths.push(stroke(line, white(0.55), 1.0)), + 1 => paths.push(stroke(line, white(1.0), 1.75 * Z)), + 2 => paths.push(stroke(line, rgba(accent, 0.75), 1.0)), + 3 => paths + .push(fill(format!("M{x:.1} {:.1} h{glyph:.1} v{:.1} h{:.1} Z", ly - 4.0 * Z, 8.0 * Z, -glyph), rgba(accent, 0.32))), + 4 => paths.push(stroke( + crate::device_canvas::dashed(&[(x, ly), (x + glyph, ly)], 2.0 * Z, 3.0 * Z), + rgba(detector_ink, 0.45 * a), + 1.0, + )), + _ => paths.push(stroke(crate::device_canvas::dashed(&[(x, ly), (x + glyph, ly)], 6.0 * Z, 5.0 * Z), thresh_ink, 1.5 * Z)), + } + let w = crate::text_measure::value_width(name) * 0.9 * Z; + texts.push(text(x + glyph + gap, ly, w + 10.0 * Z, name, white(0.7 * a), 9.0 * Z, 0)); + x += glyph + gap + w + entry; + } + + // Now: one marker down both views at the right edge. + let nx = pw - 0.5; + paths.push(stroke( + format!("M{:.1} 0 Q{nx:.1} 0 {nx:.1} {r:.1} L{nx:.1} {:.1}", nx - r, plot_t + plot_h), + rgba(accent, 0.6), + 1.5 * Z, + )); + if held { + paths.push(stroke( + format!("M0.5 {:.1} h{:.1} v{:.1} h{:.1} Z", plot_t + 0.5, pw - 1.0, plot_h - 1.0, -(pw - 1.0)), + rgba(accent, 0.8), + 1.0, + )); + texts.push(text(pw - 8.0 * Z - 60.0 * Z, plot_t + 12.0 * Z, 60.0 * Z, "Held", accent, 9.0 * Z, 2)); + } + + // The dashed line and its grip pill at the oldest edge; dragging the band moves it. + let p = def.param(sp.line); + let v = p.map_or(0.0, |p| self.panel_value(d, def, p)); + let ly = db_y(v.clamp(sp.bottom, sp.top)).round() + 0.5; + paths.push(stroke(crate::device_canvas::dashed(&[(0.0, ly), (pw, ly)], 6.0 * Z, 5.0 * Z), thresh_ink, 1.5 * Z)); + let value: SharedString = p.map_or_else(String::new, |p| def.text(d, p, v)).into(); + let grips = vec![PanelGrip { x: 6.0 * Z, y: ly, anchor: 0, label: sp.line_name.into(), value, hot: false, plain: false }]; + let index = def.index_of(sp.line).map_or(-1, |i| i as i32); + let range = p.map_or(1.0, |p| (p.max - p.min).max(1e-3)); + let zone = PanelZone { + x: 0.0, + y: ly - 8.0 * Z, + w: pw, + h: 16.0 * Z, + param_x: -1, + param_y: index, + rate_x: 0.0, + rate_y: 1.0 / (per_db * Z * range), + }; + PanelCanvas { + visible: true, + w: pw, + h: plot_t + plot_h + TIME_H * Z, + paths: model(paths), + texts: model(texts), + grips: model(grips), + zones: model(vec![zone]), + label: label.into(), + value: value_of(&pts).into(), + ..Default::default() + } + } + + /// The transfer square (78 pt): the curve over -48..0 dB in and out, the wedge it cuts + /// from the unity line, the knee lit, the threshold dotted and the live input as a dot. + pub(crate) fn dynamics_square(&self, d: &Device, def: &'static DeviceDef, accent: Color) -> PanelCanvas { + const RANGE: f32 = 48.0; + let size = 78.0 * Z; + let (m, s) = (2.0 * Z, 74.0 * Z); + let in_x = |db: f32| m + (1.0 - db / -RANGE) * s; + let out_y = |db: f32| m + (db / -RANGE).clamp(0.0, 1.0) * s; + let num = |id: &str| def.param(id).map_or(0.0, |p| self.panel_value(d, def, p)); + let face = def.layout.faces.first().map(|f| f.1); + let Some((law, at, knee)) = face.and_then(|f| crate::device_panel::face_law(f, num)) else { return PanelCanvas::default() }; + let mut paths = Vec::new(); + for i in 1..4 { + let q = m + i as f32 / 4.0 * s; + paths.push(stroke(format!("M{m:.1} {q:.1} L{:.1} {q:.1} M{q:.1} {m:.1} L{q:.1} {:.1}", m + s, m + s), white(0.05), 1.0)); + } + let tx = in_x(at.max(-RANGE)); + paths.push(stroke(crate::device_canvas::dashed(&[(tx, m), (tx, m + s)], 1.0 * Z, 3.0 * Z), white(0.2), 1.0)); + let curve: Vec<(f32, f32)> = + (0..=100).map(|i| -RANGE + i as f32 / 100.0 * RANGE).map(|x| (in_x(x), out_y(law(x).max(-RANGE)))).collect(); + let mut wedge = crate::device_canvas::path(&curve); + wedge.push_str(&format!(" L{:.1} {m:.1} L{m:.1} {:.1} Z", m + s, m + s)); + paths.push(fill(wedge, rgba(accent, 0.28))); + paths.push(stroke(format!("M{m:.1} {:.1} L{:.1} {m:.1}", m + s, m + s), rgba(accent, 0.7), 1.0)); + paths.push(stroke(crate::device_canvas::path(&curve), white(0.92), 1.75 * Z)); + if knee.1 - knee.0 > 0.5 { + let bend: Vec<(f32, f32)> = (0..=24) + .map(|i| (knee.0 + (knee.1 - knee.0) * i as f32 / 24.0).max(-RANGE)) + .map(|x| (in_x(x), out_y(law(x).max(-RANGE)))) + .collect(); + paths.push(stroke(crate::device_canvas::path(&bend), rgba(accent, 0.95), 2.5 * Z)); + } + let live_in = self.win_history(d.id).and_then(|h| h.back()).map_or(-RANGE, |s| s.1).clamp(-RANGE, 0.0); + let (dx, dy) = + ((in_x(live_in)).clamp(m + 4.0 * Z, m + s - 4.0 * Z), out_y(law(live_in).max(-RANGE)).clamp(m + 4.0 * Z, m + s - 4.0 * Z)); + let rr = 4.0 * Z; + let dot = format!("M{:.2} {dy:.2} a{rr:.2} {rr:.2} 0 1 0 {:.2} 0 a{rr:.2} {rr:.2} 0 1 0 {:.2} 0 Z", dx - rr, 2.0 * rr, -2.0 * rr); + paths.push(PanelPath { width: 1.5 * Z, stroke: Color::from_rgb_u8(0x16, 0x18, 0x1a), ..fill(dot, white(1.0)) }); + PanelCanvas { visible: true, w: size, h: size, paths: model(paths), ..Default::default() } + } +} + +/// The accessible value of the display: the reduction now. +fn value_of(pts: &[Sample]) -> String { + format!("{} dB", gr_text(pts.last().map_or(0.0, |s| s.3))) +} + +/// Push a sample, dropping those older than the longest window. Returns whether the +/// picture changed (a silent history that stays silent does not). +pub(crate) fn push(h: &mut VecDeque, s: Sample, floor: f32) -> bool { + let silent = |s: &Sample| s.1 <= floor && s.2 <= floor && s.3 > -0.05; + while h.front().is_some_and(|f| s.0 - f.0 > SPAN_MAX) { + h.pop_front(); + } + let quiet = silent(&s) && h.iter().all(silent); + h.push_back(s); + !quiet +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn one_px_per_db_serves_lane_and_plot() { + let sp = spec("compressor").unwrap(); + let (lane, plot_t, plot_h, per_db) = geometry(&sp, 394.0); + assert!((lane - 101.7).abs() < 0.2, "{lane}"); + assert!((plot_h - 203.3).abs() < 0.2, "{plot_h}"); + assert!((plot_t - lane - 20.0).abs() < 1e-3); + assert!((lane / 18.0 - per_db).abs() < 1e-4 && (plot_h / 36.0 - per_db).abs() < 1e-4); + assert!(spec("gate").is_some_and(|s| s.bottom == -60.0 && s.step == 12.0)); + assert!(spec("chorus").is_none()); + } + + #[test] + fn history_keeps_ten_seconds_and_rests_in_silence() { + let mut h = VecDeque::new(); + assert!(!push(&mut h, (0.0, -120.0, -120.0, 0.0), -36.0), "silence draws nothing new"); + assert!(push(&mut h, (0.1, -12.0, -14.0, -3.0), -36.0)); + for i in 0..200 { + push(&mut h, (0.2 + i as f64 * 0.1, -12.0, -14.0, -3.0), -36.0); + } + assert!(h.back().unwrap().0 - h.front().unwrap().0 <= SPAN_MAX + 1e-9); + assert_eq!(gr_text(-3.04), "\u{2212}3.0"); + assert_eq!(gr_text(-0.01), "0.0"); + assert_eq!(runs(&[(0.0, 1.0, true), (1.0, 1.0, true), (2.0, 5.0, false), (3.0, 1.0, true)]), "M0.0 1.0 L1.0 1.0 M3.0 1.0 "); + } +} diff --git a/crates/dstudio-app/src/main.rs b/crates/dstudio-app/src/main.rs index 009414e8..88855a1e 100644 --- a/crates/dstudio-app/src/main.rs +++ b/crates/dstudio-app/src/main.rs @@ -55,6 +55,7 @@ mod device_mod; mod device_panel; mod device_views; mod device_window; +mod device_window_dynamics; mod device_window_fields; mod devices; mod devminimap; diff --git a/docs/devices.md b/docs/devices.md index 51b007d0..645b311c 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -64,7 +64,8 @@ flowchart LR expanded window (`device_window.rs`, `ui/device_window.slint`) when the device has one (`device_window::has_window`; Auto Filter, Channel EQ, Character EQ and the plotted-field family: Tremolo, Auto-Panner, Chorus, - Flanger, Phaser, Ring Mod and Character Mod), otherwise the card itself in a window. A + Flanger, Phaser, Ring Mod and Character Mod; and the dynamics family: + Compressor, Limiter, Gate and Glue Compressor), 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 @@ -75,7 +76,15 @@ flowchart LR series; dragging the plot moves the card field's two parameters. Character Mod's picture reads in its circuit's own unit (ms delay, Hz sweep, dB gain or pan) with the band its series travel, and its rack card drops the artifacts - a circuit lacks; its Seed pill plays the next take (`ACT_SEED`). The + a circuit lacks; its Seed pill plays the next take (`ACT_SEED`). A dynamics + window's display (`device_window_dynamics.rs`) is a level history: each + meter poll appends the device's input, output and gain reduction + (`builtin_readouts`) to a ring of the last 10.5 s, and the display draws the + span the header pills pick (1, 4 or 10 s, `ACT_SPAN`) as a gain-reduction lane + over a dBFS level plot, one pixel per dB in both, with the threshold (or + ceiling) as a dashed line you drag. Hold view freezes the history. Each + device's first card carries a transfer square: the static curve of the + card's law over −48..0 dB with the knee and the live operating point. 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