diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 096845f..17d5bd9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -481,6 +481,9 @@ rodio source │ v audio analyzer ──> normalized features + scope samples + │ (PCM history, channel levels) + v +display meter ───> third-octave spectrum, L/R levels, peak hold │ v Rhai render(input) @@ -499,6 +502,36 @@ script implements `render(input)` and returns declarative commands such as clear, cell, line, rectangle, trace, and text. Scripts never receive the ratatui frame or audio engine directly. +Protocol v3 adds what front-panel displays need: a third-octave spectrum +(31 bands, 20 Hz to 20 kHz, nominal ISO labels with exact base-2 edges that +partition the FFT bins) with per-band peak hold, left/right RMS and held +sample peaks, the RMS of the side signal (L - R) / 2 and a +stereo/mono decision made on loud windows, the analyzed sample rate, and track, queue and transport +details (format, bit depth, bitrate, track number, queue position, repeat, +shuffle, source), and the local wall-clock time. The audio thread only appends mono samples to a lock-free +ring and accumulates per-window channel levels; the FFT (an ~85 ms window +whose length follows the sample rate) and all ballistics run when the UI +takes a snapshot, under a mutex the audio thread never touches. Ballistics +are time-based (fast attack, steady fall, hold then fall): they advance with +the clock rather than per snapshot. Audio arrives in device-callback bursts, +so a snapshot that sees no new samples reuses the last measurement; only when +the PCM write counter stays still for longer than a few callbacks (pause, +stop) does the meter fall to the floor instead of freezing. In the control +role, and briefly when a track starts, the host passes an empty analysis, so +the meter reads zero. Meter values report the decoded signal on a fixed dBFS +scale and are therefore not scaled by the output volume, unlike the v2 +energy features. Scripts choose their own display range within that scale. + +v3 also lets a script keep state: `render` may return +`#{ commands, state }`, and the host passes `state` back with `dt` and a frame +counter on the next frame. State lives in the host's script runtime, is reset +whenever the script is recompiled or the visualizer is opened, and is subject +to the same sandbox size limits as any other value. Thin drawing comes from braille `dots` and `line` +commands in a 2 x 4 dot grid per cell (dots merge with braille already in the +cell; lines are clipped to the area first, so far endpoints cost nothing) and +from optional bold/dim/italic/underline/reversed attributes, which each +command sets for its cells rather than adding to what was drawn before. + This command boundary is intentional: - scripts remain independent of Rust UI internals; @@ -538,8 +571,8 @@ is not a plugin mechanism for accessing the library, network, or player controls. Fullscreen execution currently happens synchronously during UI drawing, with a fresh -Rhai scope for each frame; scripts should derive motion from time and the -already-smoothed audio features rather than rely on retained mutable state. +Rhai scope for each frame; retained state is limited to the explicit `state` +value described above, and motion should still be derived from time and `dt`. The 50 ms animation timer gives a nominal 20 FPS cadence (other events can also trigger redraws). Operation limits are not wall-clock deadlines. The host also checks the script modification time during drawing, so slow script diff --git a/CHANGELOG.md b/CHANGELOG.md index e28198b..438cff4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,54 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.5.1] - 2026-11-22 + +### Added + +- "VFD panel" visualization: a vacuum-fluorescent hi-fi front panel with + thin segment digits, a stereo peak level meter (bars or needle VU meters), + a 25-band analyzer with three levels of glow, a nonlinear scale and peak + hold, a peak frequency readout with hold, tone fans, a signal path + schematic with a travelling pulse (source, format, volume, sample rate, + stereo or mono, and the output level in dBFS), the transport word in segment letters, + mode lamps (REPEAT, SHUFFLE, source, LOUDNESS, MUTE, SEARCH, OVER), a tape + counter and a dot-matrix title line (Latin and Cyrillic). Effects: a + power-on segment test, a counter "search" on track changes, static on + track and source changes, a source block that relights with its new + value, colours that fade into unlit phosphor on pause, a night dimmer, a + slow filament "breath", slightly uneven digit brightness and a standby + clock when nothing is loaded. Display modes "full", "spectrum", + "minimal" and "deck" switch with Shift+M or can be pinned with + `DISPLAY_MODE()` at the top of the script, like the palettes ("classic", + "green", "amber", "ice"); a mode that does not fit the window steps down. + A switch looks like hardware: the time and L/R meters stay lit, the other + sections go dark and light up one by one, and a row of mode lamps shows + the choice for a moment. The analyzer's display range follows the + loudness of the music (the measurements stay absolute), and deck mode has + AMS, NR, AUTO REVERSE and REW/FF lamps with a counter that races during a + seek. Bars settle with a little inertia, the analyzer's + tint runs from warm amber in the bass to light yellow in the treble, peak + marks fall with a little gravity after their hold, and the transport word + uses 14-segment letters with faint unlit segments. +- `Shift+M` in the fullscreen visualizer switches its display mode; the + choice is saved in `visualizations.toml`. +- Visualization protocol v3: a real third-octave spectrum (31 bands) with + peak hold, left/right RMS and held peaks, the side-signal level + (`level_side`, the floor for mono) and `channel_mode` ("stereo" or + "mono"), the sample rate, and track, + queue and transport details in the script input; `render` may return + `#{ commands, state }` to keep state between frames (with `dt` and + `frame`); new braille `dots` and `line` commands for thin drawing; bold, + dim, italic, underline and reversed attributes on any command. v2 scripts + keep working unchanged. Scripts also get the local time as + `clock_hour`, `clock_minute`, `clock_second` and `clock_millis`, and the + display mode as `mode`, a counter each script takes modulo its own number + of modes. + +### Fixed + +- The visualization clock shows local time instead of UTC. + ## [0.5.0] - 2026-11-20 ### Added @@ -212,6 +260,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Music-directory validation and migration now reject overlapping changes, resolve canonical paths, and produce Windows-portable managed filenames. -[Unreleased]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.8...HEAD +[Unreleased]: https://gt.hexor.cy/Furumi/furumi-tui/compare/v0.5.1...HEAD +[0.5.1]: https://gt.hexor.cy/Furumi/furumi-tui/compare/v0.5.0...v0.5.1 [0.2.8]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.7...v0.2.8 [0.2.5]: https://gt.hexor.cy/ab/furumi_tui/compare/v0.2.4...v0.2.5 diff --git a/Cargo.lock b/Cargo.lock index f680970..b7cb10c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1715,11 +1715,12 @@ dependencies = [ [[package]] name = "furumi_tui" -version = "0.5.0" +version = "0.5.1" dependencies = [ "anyhow", "base64", "blake3", + "chrono", "core-foundation 0.10.1", "crokey", "crossterm", diff --git a/Cargo.toml b/Cargo.toml index 6f2c6f6..b8099bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "furumi_tui" -version = "0.5.0" +version = "0.5.1" edition = "2024" rust-version = "1.97" description = "A federated P2P player for personal music libraries" @@ -23,6 +23,8 @@ object = { version = "0.36", default-features = false, features = ["read", "std" anyhow = "1.0.102" blake3 = "1" +# Local wall-clock time for visualizations (the clock and its hour/minute). +chrono = { version = "0.4.45", default-features = false, features = ["clock"] } crokey = "1.4.0" crossterm = { version = "0.29.0", features = ["event-stream"] } directories = "6.0.0" diff --git a/README.md b/README.md index f5a997c..d326d4a 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,10 @@ context-aware bindings, and user-defined rebinding through TOML. Built-in audio visualizations, OS media controls, gapless queue playback, and local library management are included. Visualizations are runtime-loadable Rhai scripts executed in a resource-limited sandbox, so they can be added or edited -without rebuilding the player. +without rebuilding the player. The bundled "VFD panel" preset draws a hi-fi +front panel from a real third-octave spectrum and stereo level meter; scripts +can use the same spectrum, levels, track details, thin braille lines and +per-frame state. Optional similarity search calculates versioned embeddings for local tracks in the background and keeps them in SQLite. It works offline; after a separate diff --git a/src/app/action.rs b/src/app/action.rs index 4f7b70f..85255f3 100644 --- a/src/app/action.rs +++ b/src/app/action.rs @@ -32,6 +32,7 @@ pub enum Action { ToggleShuffle, CycleRepeat, ToggleVisualizer, + CycleVisualizerMode, ToggleLike, ToggleTrackSelection, OpenTrackInfo, @@ -129,6 +130,7 @@ impl Action { | Action::ToggleShuffle | Action::CycleRepeat | Action::ToggleVisualizer + | Action::CycleVisualizerMode | Action::OpenConnectedDevices | Action::OpenListenHistory => Category::Playback, Action::QueueAddNext @@ -228,6 +230,7 @@ impl Action { Action::ToggleShuffle => "Toggle shuffle".into(), Action::CycleRepeat => "Cycle repeat mode".into(), Action::ToggleVisualizer => "Toggle fullscreen visualizer".into(), + Action::CycleVisualizerMode => "Next visualizer display mode".into(), Action::ToggleLike => "Like / unlike".into(), Action::ToggleTrackSelection => "Track line selection".into(), Action::OpenTrackInfo => "Track info".into(), diff --git a/src/app/update.rs b/src/app/update.rs index 32599c3..11e5dcb 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -389,6 +389,18 @@ pub fn update(state: &mut AppState, action: Action) -> Option { } None } + Action::CycleVisualizerMode => { + if state.visualizer.active { + if let Err(err) = state.visualizer.cycle_mode() { + // the fullscreen visualizer hides the status line + tracing::warn!(error = %format!("{err:#}"), "saving the visualizer mode failed"); + state.status_message = Some(format!("visualization settings: {err:#}")); + } + } else { + state.status_message = Some("open the visualizer first (Shift+L)".into()); + } + None + } Action::Select => select_current(state), Action::Back if state.visualizer.active => { state.visualizer.close(); diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index a3e3a16..e7b0d84 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -776,6 +776,20 @@ fn visualizer_requires_current_track() { ); } +#[test] +fn visualizer_mode_needs_an_open_visualizer() { + let mut state = AppState::default(); + let mode = state.visualizer.config.mode; + + assert_eq!(update(&mut state, Action::CycleVisualizerMode), None); + + assert_eq!(state.visualizer.config.mode, mode); + assert_eq!( + state.status_message.as_deref(), + Some("open the visualizer first (Shift+L)") + ); +} + #[test] fn visualizer_toggles_and_back_closes_it() { let mut state = AppState::default(); diff --git a/src/config/default_keymap.toml b/src/config/default_keymap.toml index d544b68..f15e334 100644 --- a/src/config/default_keymap.toml +++ b/src/config/default_keymap.toml @@ -223,6 +223,10 @@ command = "CycleRepeat" key_sequence = "shift-l" command = "ToggleVisualizer" +[[keymaps]] +key_sequence = "shift-m" +command = "CycleVisualizerMode" + [[keymaps]] key_sequence = "shift-h" command = "OpenListenHistory" diff --git a/src/config/keymap.rs b/src/config/keymap.rs index 569bcc9..2265dba 100644 --- a/src/config/keymap.rs +++ b/src/config/keymap.rs @@ -584,6 +584,11 @@ mod tests { km.resolve(shift_l, KeyContext::Library), KeyResolution::Action(Action::ToggleVisualizer) ); + let shift_m = KeyCombination::new(KeyCode::Char('M'), KeyModifiers::SHIFT); + assert_eq!( + km.resolve(shift_m, KeyContext::Library), + KeyResolution::Action(Action::CycleVisualizerMode) + ); } #[test] diff --git a/src/player/analyzer.rs b/src/player/analyzer.rs index e2c9163..f6a7649 100644 --- a/src/player/analyzer.rs +++ b/src/player/analyzer.rs @@ -1,10 +1,12 @@ -use std::sync::Arc; use std::sync::atomic::{AtomicI16, AtomicU32, AtomicU64, AtomicUsize, Ordering}; -use std::time::Duration; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use rodio::source::SeekError; use rodio::{ChannelCount, Sample, SampleRate, Source}; +use super::spectrum::{Meter, PCM_SAMPLES, StereoReading}; + const LEVEL_SCALE: f32 = 1_000_000.0; const SCOPE_SAMPLES: usize = 256; const SCOPE_SAMPLE_SCALE: f32 = i16::MAX as f32; @@ -20,6 +22,26 @@ pub struct AudioAnalysisSnapshot { pub treble: f64, pub beat: f64, pub scope: Vec, + /// Third-octave band levels (see `spectrum::BAND_CENTERS_HZ`), 0.0..1.0 + /// over `spectrum::FLOOR_DB`..0 dBFS, with analyzer ballistics. + pub spectrum: Vec, + /// Per-band peak-hold markers on the same scale as `spectrum`. + pub spectrum_peaks: Vec, + /// Left/right RMS levels and held sample peaks on the same dB scale. + /// Mono sources report the same value for both channels. + pub level_l: f64, + pub level_r: f64, + pub peak_l: f64, + pub peak_r: f64, + /// RMS of the side signal (L - R) / 2 on the same scale: the floor for + /// mono sources and for stereo files that carry the same signal twice. + pub level_side: f64, + /// Whether the channels carry different signals: decided on loud windows + /// only (side within 30 dB of the louder channel), `None` until then. + pub stereo: Option, + /// Sample rate of the analyzed stream in Hz (0 when nothing has played + /// since the player last stopped). + pub sample_rate: u32, } #[derive(Debug)] @@ -32,6 +54,20 @@ pub struct AnalyzerShared { beat: AtomicU32, scope_write: AtomicUsize, scope: Box<[AtomicI16]>, + /// Full-rate mono history for the spectrum; written by the audio thread. + pcm_write: AtomicUsize, + pcm: Box<[AtomicI16]>, + sample_rate: AtomicU32, + /// Per-window channel levels (linear, `LEVEL_SCALE`). Peaks accumulate + /// with `fetch_max` until the meter consumes them. + rms_l: AtomicU32, + rms_r: AtomicU32, + rms_side: AtomicU32, + peak_l: AtomicU32, + peak_r: AtomicU32, + /// Ballistics and FFT state. Only snapshot readers (the UI side) lock it; + /// the audio thread never does. + meter: Mutex, } impl Default for AnalyzerShared { @@ -44,14 +80,27 @@ impl Default for AnalyzerShared { treble: AtomicU32::new(0), beat: AtomicU32::new(0), scope_write: AtomicUsize::new(0), - scope: (0..SCOPE_SAMPLES) - .map(|_| AtomicI16::new(0)) - .collect::>() - .into_boxed_slice(), + scope: atomic_ring(SCOPE_SAMPLES), + pcm_write: AtomicUsize::new(0), + pcm: atomic_ring(PCM_SAMPLES), + sample_rate: AtomicU32::new(0), + rms_l: AtomicU32::new(0), + rms_r: AtomicU32::new(0), + rms_side: AtomicU32::new(0), + peak_l: AtomicU32::new(0), + peak_r: AtomicU32::new(0), + meter: Mutex::new(Meter::default()), } } } +fn atomic_ring(len: usize) -> Box<[AtomicI16]> { + (0..len) + .map(|_| AtomicI16::new(0)) + .collect::>() + .into_boxed_slice() +} + impl AnalyzerShared { pub fn clear(&self) { self.energy.store(0, Ordering::Relaxed); @@ -63,10 +112,37 @@ impl AnalyzerShared { for sample in self.scope.iter() { sample.store(0, Ordering::Relaxed); } + self.pcm_write.store(0, Ordering::Relaxed); + for sample in self.pcm.iter() { + sample.store(0, Ordering::Relaxed); + } + for level in [ + &self.rms_l, + &self.rms_r, + &self.rms_side, + &self.peak_l, + &self.peak_r, + ] { + level.store(0, Ordering::Relaxed); + } self.sequence.store(0, Ordering::Relaxed); } + /// Like [`Self::clear`], and also forgets the sample rate: nothing is + /// loaded any more. + pub fn reset(&self) { + self.clear(); + self.sample_rate.store(0, Ordering::Relaxed); + } + pub fn snapshot(&self) -> AudioAnalysisSnapshot { + self.snapshot_at(Instant::now()) + } + + /// Like [`Self::snapshot`] with an explicit clock, so meter ballistics are + /// deterministic in tests. Ballistics are time-based: how often callers + /// read does not change how fast bars rise or fall. + pub fn snapshot_at(&self, now: Instant) -> AudioAnalysisSnapshot { let write = self.scope_write.load(Ordering::Relaxed); let len = self.scope.len().max(1); let scope = (0..self.scope.len()) @@ -76,6 +152,25 @@ impl AnalyzerShared { }) .collect(); + let sample_rate = self.sample_rate.load(Ordering::Relaxed); + let pcm_write = self.pcm_write.load(Ordering::Relaxed); + let stereo = StereoReading { + rms_l: load_norm(&self.rms_l) as f32, + rms_r: load_norm(&self.rms_r) as f32, + rms_side: load_norm(&self.rms_side) as f32, + peak_l: f64::from(self.peak_l.swap(0, Ordering::Relaxed)) as f32 / LEVEL_SCALE, + peak_r: f64::from(self.peak_r.swap(0, Ordering::Relaxed)) as f32 / LEVEL_SCALE, + }; + let reading = { + let mut meter = self + .meter + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + meter.update(now, pcm_write, sample_rate, stereo, |out| { + self.copy_pcm(pcm_write, out) + }) + }; + AudioAnalysisSnapshot { sequence: self.sequence.load(Ordering::Relaxed), energy: load_norm(&self.energy), @@ -84,6 +179,31 @@ impl AnalyzerShared { treble: load_norm(&self.treble), beat: load_norm(&self.beat), scope, + spectrum: reading.spectrum, + spectrum_peaks: reading.spectrum_peaks, + level_l: reading.level_l, + level_r: reading.level_r, + peak_l: reading.peak_l, + peak_r: reading.peak_r, + level_side: reading.level_side, + stereo: reading.stereo, + sample_rate, + } + } + + /// Copies the newest `out.len()` mono samples, oldest first. Slots not + /// written since the last clear read as silence. + fn copy_pcm(&self, write: usize, out: &mut [f32]) { + let len = self.pcm.len(); + let count = out.len().min(len); + let start = write.wrapping_sub(count); + for (offset, slot) in out.iter_mut().enumerate() { + *slot = if offset < count && write >= count - offset { + let index = start.wrapping_add(offset) % len; + f32::from(self.pcm[index].load(Ordering::Relaxed)) / SCOPE_SAMPLE_SCALE + } else { + 0.0 + }; } } @@ -96,6 +216,22 @@ impl AnalyzerShared { self.sequence.fetch_add(1, Ordering::Relaxed); } + fn push_pcm(&self, sample: f32) { + let index = self.pcm_write.fetch_add(1, Ordering::Relaxed) % self.pcm.len(); + let value = (sample.clamp(-1.0, 1.0) * SCOPE_SAMPLE_SCALE).round() as i16; + self.pcm[index].store(value, Ordering::Relaxed); + } + + fn store_channels(&self, sample_rate: f32, rms: [f32; 3], peak: [f32; 2]) { + self.sample_rate + .store(sample_rate.round() as u32, Ordering::Relaxed); + store_norm(&self.rms_l, rms[0]); + store_norm(&self.rms_r, rms[1]); + store_norm(&self.rms_side, rms[2]); + self.peak_l.fetch_max(norm_bits(peak[0]), Ordering::Relaxed); + self.peak_r.fetch_max(norm_bits(peak[1]), Ordering::Relaxed); + } + fn push_scope(&self, sample: f32) { let index = self.scope_write.fetch_add(1, Ordering::Relaxed) % self.scope.len(); let value = (sample.clamp(-1.0, 1.0) * SCOPE_SAMPLE_SCALE).round() as i16; @@ -181,6 +317,12 @@ struct AnalyzerState { mid_alpha: f32, channel_index: usize, frame_sum: f32, + /// Left/right of the current frame (mono feeds both). + frame_lr: [f32; 2], + channel_sq: [f32; 2], + /// Sum of squared side samples (L - R) / 2 in the current window. + side_sq: f32, + channel_peak: [f32; 2], frame_count: usize, window_frames: usize, scope_counter: usize, @@ -208,6 +350,10 @@ impl AnalyzerState { mid_alpha: 0.0, channel_index: 0, frame_sum: 0.0, + frame_lr: [0.0; 2], + channel_sq: [0.0; 2], + side_sq: 0.0, + channel_peak: [0.0; 2], frame_count: 0, window_frames: 0, scope_counter: 0, @@ -252,6 +398,10 @@ impl AnalyzerState { fn reset_filters(&mut self) { self.channel_index = 0; self.frame_sum = 0.0; + self.frame_lr = [0.0; 2]; + self.channel_sq = [0.0; 2]; + self.side_sq = 0.0; + self.channel_peak = [0.0; 2]; self.frame_count = 0; self.scope_counter = 0; self.low_bass = 0.0; @@ -275,10 +425,23 @@ impl AnalyzerState { 0.0 }; self.frame_sum += sample; + // First channel is left, second right; extra channels only feed mono. + if self.channel_index < 2 { + self.frame_lr[self.channel_index] = sample; + } self.channel_index += 1; if self.channel_index < self.channels { return; } + if self.channels == 1 { + self.frame_lr[1] = self.frame_lr[0]; + } + for (channel, value) in self.frame_lr.iter().enumerate() { + self.channel_sq[channel] += value * value; + self.channel_peak[channel] = self.channel_peak[channel].max(value.abs()); + } + let side = (self.frame_lr[0] - self.frame_lr[1]) * 0.5; + self.side_sq += side * side; let mono = self.frame_sum / self.channels as f32; self.channel_index = 0; @@ -299,6 +462,7 @@ impl AnalyzerState { self.mid_sq += mid * mid; self.treble_sq += treble * treble; self.frame_count += 1; + shared.push_pcm(sample); self.scope_counter += 1; if self.scope_counter >= self.scope_stride { @@ -339,10 +503,23 @@ impl AnalyzerState { self.smooth_beat, ); + shared.store_channels( + self.sample_rate, + [ + (self.channel_sq[0] / frames).sqrt(), + (self.channel_sq[1] / frames).sqrt(), + (self.side_sq / frames).sqrt(), + ], + self.channel_peak, + ); + self.full_sq = 0.0; self.bass_sq = 0.0; self.mid_sq = 0.0; self.treble_sq = 0.0; + self.channel_sq = [0.0; 2]; + self.side_sq = 0.0; + self.channel_peak = [0.0; 2]; self.frame_count = 0; } } @@ -361,10 +538,11 @@ fn smooth_level(previous: f32, next: f32, attack: f32, release: f32) -> f32 { } fn store_norm(target: &AtomicU32, value: f32) { - target.store( - (value.clamp(0.0, 1.0) * LEVEL_SCALE).round() as u32, - Ordering::Relaxed, - ); + target.store(norm_bits(value), Ordering::Relaxed); +} + +fn norm_bits(value: f32) -> u32 { + (value.clamp(0.0, 1.0) * LEVEL_SCALE).round() as u32 } fn load_norm(source: &AtomicU32) -> f64 { @@ -384,19 +562,24 @@ mod tests { impl TestSource { fn sine(frames: usize, channels: u16, sample_rate: u32, frequency: f32) -> Self { - let channels_count = channels.max(1); - let mut samples = Vec::with_capacity(frames * usize::from(channels_count)); + let gains = vec![1.0; usize::from(channels.max(1))]; + Self::sine_gains(frames, sample_rate, frequency, &gains) + } + + /// A sine with a gain per channel (one entry per channel). + fn sine_gains(frames: usize, sample_rate: u32, frequency: f32, gains: &[f32]) -> Self { + let mut samples = Vec::with_capacity(frames * gains.len()); for frame in 0..frames { let time = frame as f32 / sample_rate as f32; let sample = (std::f32::consts::TAU * frequency * time).sin() * 0.5; - for _ in 0..channels_count { - samples.push(sample as Sample); + for gain in gains { + samples.push((sample * gain) as Sample); } } Self { samples, cursor: 0, - channels: ChannelCount::new(channels_count).unwrap(), + channels: ChannelCount::new(u16::try_from(gains.len()).unwrap()).unwrap(), sample_rate: SampleRate::new(sample_rate).unwrap(), } } @@ -452,4 +635,71 @@ mod tests { assert!(snapshot.bass > 0.0); assert!(snapshot.scope.iter().any(|sample| sample.abs() > 0.001)); } + + #[test] + fn analyzed_source_feeds_the_spectrum_and_channel_meters() { + let shared = Arc::new(AnalyzerShared::default()); + let source = TestSource::sine(48_000, 2, 48_000, 1_000.0); + let analyzed = AnalyzedSource::new(source, Arc::clone(&shared)); + + for _ in analyzed {} + + let snapshot = shared.snapshot(); + assert_eq!(snapshot.sample_rate, 48_000); + let bands = crate::player::BAND_CENTERS_HZ; + let at_1k = bands.iter().position(|hz| *hz == 1_000.0).unwrap(); + let loudest = snapshot + .spectrum + .iter() + .enumerate() + .max_by(|left, right| left.1.total_cmp(right.1)) + .map(|(index, _)| index); + assert_eq!(loudest, Some(at_1k)); + assert!(snapshot.level_l > 0.5 && (snapshot.level_l - snapshot.level_r).abs() < 1e-6); + // the same signal in both channels has no side component + assert_eq!(snapshot.level_side, 0.0); + assert_eq!(snapshot.stereo, Some(false)); + assert!(snapshot.peak_l >= snapshot.level_l); + } + + #[test] + fn analyzed_source_measures_the_side_signal() { + let measure = |gains: &[f32]| { + let shared = Arc::new(AnalyzerShared::default()); + let source = TestSource::sine_gains(48_000, 48_000, 1_000.0, gains); + for _ in AnalyzedSource::new(source, Arc::clone(&shared)) {} + shared.snapshot() + }; + // R = -L: the side signal (L - R) / 2 equals L + let opposite = measure(&[1.0, -1.0]); + assert!(opposite.level_side > 0.5); + assert!((opposite.level_side - opposite.level_l).abs() < 1e-3); + assert_eq!(opposite.stereo, Some(true)); + // mono duplicates L into R + let mono = measure(&[1.0]); + assert_eq!(mono.level_side, 0.0); + assert_eq!(mono.stereo, Some(false)); + // a third channel only feeds the mono sum + let surround = measure(&[1.0, 0.0, 1.0]); + assert!(surround.level_side > 0.0 && surround.level_side < surround.level_l); + } + + #[test] + fn pcm_history_reads_newest_samples_and_silence_before_the_first() { + let shared = AnalyzerShared::default(); + for value in [0.25_f32, 0.5, -0.5] { + shared.push_pcm(value); + } + let mut out = [1.0_f32; 5]; + shared.copy_pcm(shared.pcm_write.load(Ordering::Relaxed), &mut out); + let rounded: Vec = out + .iter() + .map(|value| (value * 4.0).round() / 4.0) + .collect(); + assert_eq!(rounded, [0.0, 0.0, 0.25, 0.5, -0.5]); + + shared.clear(); + shared.copy_pcm(shared.pcm_write.load(Ordering::Relaxed), &mut out); + assert!(out.iter().all(|value| *value == 0.0)); + } } diff --git a/src/player/mod.rs b/src/player/mod.rs index 2f9c7bd..06763a0 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -6,6 +6,7 @@ mod analyzer; mod opus; +mod spectrum; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -15,6 +16,7 @@ use std::time::Duration; use rodio::{Decoder, DeviceSinkBuilder, Player, Source, stream::MixerDeviceSink}; pub use analyzer::AudioAnalysisSnapshot; +pub use spectrum::{BAND_CENTERS_HZ, FLOOR_DB}; pub trait TrackReadSeek: std::io::Read + std::io::Seek + Send + Sync {} @@ -453,7 +455,7 @@ fn handle( if let Some(out) = output.take() { out.player.stop(); } - shared.analysis.clear(); + shared.analysis.reset(); playing.track_loaded = false; playing.base = Duration::ZERO; } diff --git a/src/player/spectrum.rs b/src/player/spectrum.rs new file mode 100644 index 0000000..7d86f61 --- /dev/null +++ b/src/player/spectrum.rs @@ -0,0 +1,650 @@ +//! Display meter for visualizations: a third-octave spectrum and stereo levels +//! with analyzer ballistics (fast attack, steady fall, peak hold). +//! +//! The audio thread only writes samples and per-window channel levels into +//! `AnalyzerShared`; the FFT and all smoothing run here, on the reader side, +//! when a snapshot is taken. Ballistics are time-based: rises and falls +//! advance with the clock, not with the number of snapshots. + +use std::sync::Arc; +use std::time::Instant; + +use rustfft::num_complex::Complex; +use rustfft::{Fft, FftPlanner}; + +/// Mono samples kept for the spectrum: enough for an ~85 ms window at +/// 192 kHz. The FFT uses the newest `fft_len(rate)` of them. +pub const PCM_SAMPLES: usize = 16_384; + +/// Bottom of the display scale: values are normalized from `FLOOR_DB`..0 dBFS +/// to 0.0..1.0, so a full-scale sine reads 1.0. +pub const FLOOR_DB: f32 = -60.0; + +/// Nominal ISO third-octave band centres (Hz), 20 Hz .. 20 kHz. These are +/// labels; band edges come from the exact base-2 centres (see `exact_center`) +/// so neighbouring bands meet without gaps or overlaps. +pub const BAND_CENTERS_HZ: [f32; 31] = [ + 20.0, 25.0, 31.5, 40.0, 50.0, 63.0, 80.0, 100.0, 125.0, 160.0, 200.0, 250.0, 315.0, 400.0, + 500.0, 630.0, 800.0, 1_000.0, 1_250.0, 1_600.0, 2_000.0, 2_500.0, 3_150.0, 4_000.0, 5_000.0, + 6_300.0, 8_000.0, 10_000.0, 12_500.0, 16_000.0, 20_000.0, +]; + +const BANDS: usize = BAND_CENTERS_HZ.len(); +/// Index of the 1 kHz band. +const KHZ_BAND: i32 = 17; +const MIN_FFT: usize = 4096; +const BAND_ATTACK_SECS: f32 = 0.025; +const BAND_FALL_DB_PER_SEC: f32 = 36.0; +const PEAK_HOLD_SECS: f32 = 1.2; +const PEAK_FALL_DB_PER_SEC: f32 = 18.0; +const LEVEL_ATTACK_SECS: f32 = 0.05; +const LEVEL_RELEASE_SECS: f32 = 0.3; +/// A window counts as stereo when its side signal (L - R) / 2 is no more +/// than this far below the louder channel: lossy coding of a mono recording +/// leaves a side signal far below that, real stereo mixes sit well above it. +const STEREO_SIDE_DB: f32 = -30.0; +/// Only windows this far above the floor decide; quieter ones keep the last +/// decision, since their side signal is lost in the floor. +const STEREO_DECIDE_ABOVE_FLOOR_DB: f32 = 30.0; + +/// Longest step applied at once; a stalled reader must not fast-forward a +/// whole second of decay in one frame. +const MAX_STEP_SECS: f32 = 0.25; +/// Audio arrives in device-callback bursts (rodio uses ~46 ms buffers), so a +/// snapshot may see no new samples while playback runs. Only a longer stall +/// (pause, stop) counts as silence. +const STALL_SECS: f32 = 0.15; + +/// FFT length for a sample rate: ~85 ms of audio, a power of two. +fn fft_len(sample_rate: u32) -> usize { + (sample_rate as usize * MIN_FFT / 48_000) + .next_power_of_two() + .clamp(MIN_FFT, PCM_SAMPLES) +} + +/// Exact base-2 third-octave centre of band `index` (1 kHz at index 17). +fn exact_center(index: usize) -> f32 { + 1_000.0 * 2f32.powf((index as i32 - KHZ_BAND) as f32 / 3.0) +} + +/// Linear channel levels of the latest analysis window. +#[derive(Debug, Clone, Copy, Default)] +pub struct StereoReading { + pub rms_l: f32, + pub rms_r: f32, + /// RMS of the side signal (L - R) / 2. + pub rms_side: f32, + /// Highest sample peaks since the previous reading. + pub peak_l: f32, + pub peak_r: f32, +} + +#[derive(Debug, Clone, Default)] +pub struct MeterReading { + pub spectrum: Vec, + pub spectrum_peaks: Vec, + pub level_l: f64, + pub level_r: f64, + pub peak_l: f64, + pub peak_r: f64, + pub level_side: f64, + /// Whether the two channels carry different signals (see + /// `STEREO_SIDE_DB`); `None` until a loud enough window was measured. + pub stereo: Option, +} + +struct Hold { + db: f32, + age: f32, +} + +impl Hold { + fn new() -> Self { + Self { + db: FLOOR_DB, + age: 0.0, + } + } + + fn update(&mut self, value_db: f32, dt: f32) { + if value_db >= self.db { + self.db = value_db; + self.age = 0.0; + return; + } + self.age += dt; + if self.age > PEAK_HOLD_SECS { + self.db = (self.db - PEAK_FALL_DB_PER_SEC * dt).max(value_db); + } + } +} + +/// FFT plan, window and band bin ranges for one sample rate. +struct Analysis { + sample_rate: u32, + fft: Arc>, + window: Vec, + /// Sum of squared window weights, for power normalization. + window_power: f32, + pcm: Vec, + buffer: Vec>, + scratch: Vec>, + /// Inclusive bin range per band; `None` above Nyquist. + bins: [Option<(usize, usize)>; BANDS], +} + +impl Analysis { + fn new(sample_rate: u32) -> Self { + let len = fft_len(sample_rate); + let fft = FftPlanner::::new().plan_fft_forward(len); + let scratch = vec![Complex::default(); fft.get_inplace_scratch_len()]; + let window: Vec = (0..len) + .map(|index| { + let phase = std::f32::consts::TAU * index as f32 / len as f32; + 0.5 - 0.5 * phase.cos() + }) + .collect(); + let window_power = window.iter().map(|weight| weight * weight).sum(); + Self { + sample_rate, + fft, + window, + window_power, + pcm: vec![0.0; len], + buffer: vec![Complex::default(); len], + scratch, + bins: band_bins(sample_rate, len), + } + } + + /// Band power in dBFS (a full-scale sine reads 0 dB in its band). The + /// caller has filled `pcm`. + fn band_targets(&mut self) -> [f32; BANDS] { + for ((slot, sample), weight) in self.buffer.iter_mut().zip(&self.pcm).zip(&self.window) { + *slot = Complex::new(sample * weight, 0.0); + } + self.fft + .process_with_scratch(&mut self.buffer, &mut self.scratch); + // One-sided power per bin, normalized so the bins of a sine sum to + // its mean square (A^2 / 2); doubled below so the sine reads 0 dB. + let scale = 2.0 / (self.buffer.len() as f32 * self.window_power); + let mut out = [FLOOR_DB; BANDS]; + for (slot, range) in out.iter_mut().zip(self.bins) { + if let Some((first, last)) = range { + let power: f32 = self.buffer[first..=last] + .iter() + .map(|bin| bin.norm_sqr() * scale) + .sum(); + *slot = to_db_power(2.0 * power); + } + } + out + } +} + +/// Partitions the FFT bins between the bands: each bin belongs to exactly one +/// band, from the first bin at or above the band's lower edge up to the bin +/// before the next band starts. A band narrower than one bin (deep bass at +/// short windows) reads the bin that contains its centre, which it then shares +/// with its neighbour. +fn band_bins(sample_rate: u32, len: usize) -> [Option<(usize, usize)>; BANDS] { + let bin_hz = sample_rate as f32 / len as f32; + let last_bin = len / 2 - 1; + let nyquist = sample_rate as f32 / 2.0; + let edge = 2f32.powf(1.0 / 6.0); + let first_bin = |index: usize| ((exact_center(index) / edge / bin_hz).ceil() as usize).max(1); + std::array::from_fn(|index| { + let low = exact_center(index) / edge; + if low >= nyquist { + return None; + } + let first = first_bin(index); + let last = if index + 1 < BANDS { + first_bin(index + 1).saturating_sub(1) + } else { + ((exact_center(index) * edge / bin_hz).floor() as usize).max(first) + } + .min(last_bin); + if first <= last { + Some((first, last)) + } else { + let center = ((exact_center(index) / bin_hz).round() as usize).clamp(1, last_bin); + Some((center, center)) + } + }) +} + +pub struct Meter { + analysis: Option, + bands_db: [f32; BANDS], + band_peaks: [Hold; BANDS], + /// Left, right and side RMS levels. + level_db: [f32; 3], + level_peaks: [Hold; 2], + last_update: Option, + last_write: usize, + /// When the PCM counter last moved, and what that audio measured; reused + /// between device callbacks until `STALL_SECS` pass. + last_fresh: Option, + held_targets: [f32; BANDS], + held_rms: [f32; 3], + /// Last stereo decision; kept through silence, pauses and stalls. + stereo: Option, +} + +impl std::fmt::Debug for Meter { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Meter") + .field("bands_db", &self.bands_db) + .field("level_db", &self.level_db) + .finish_non_exhaustive() + } +} + +impl Default for Meter { + fn default() -> Self { + Self { + analysis: None, + bands_db: [FLOOR_DB; BANDS], + band_peaks: std::array::from_fn(|_| Hold::new()), + level_db: [FLOOR_DB; 3], + level_peaks: std::array::from_fn(|_| Hold::new()), + last_update: None, + last_write: 0, + last_fresh: None, + held_targets: [FLOOR_DB; BANDS], + held_rms: [0.0; 3], + stereo: None, + } + } +} + +impl Meter { + /// Advances the meter to `now`. `write` is the analyzer's PCM write + /// counter: while it keeps moving the newest audio is measured; once it + /// has not moved for `STALL_SECS` (paused, stopped) the meter is fed + /// silence and falls instead of freezing. `fill_pcm` copies the newest + /// `out.len()` mono samples, oldest first. + pub fn update( + &mut self, + now: Instant, + write: usize, + sample_rate: u32, + stereo: StereoReading, + fill_pcm: impl FnOnce(&mut [f32]), + ) -> MeterReading { + let dt = self + .last_update + .map(|last| now.saturating_duration_since(last).as_secs_f32()) + .unwrap_or(MAX_STEP_SECS) + .min(MAX_STEP_SECS); + self.last_update = Some(now); + let fresh = write != self.last_write; + self.last_write = write; + + let (targets, rms, peaks) = if fresh && sample_rate > 0 { + if self + .analysis + .as_ref() + .is_none_or(|analysis| analysis.sample_rate != sample_rate) + { + self.analysis = Some(Analysis::new(sample_rate)); + } + let analysis = self.analysis.as_mut().expect("analysis was just set"); + fill_pcm(&mut analysis.pcm); + self.held_targets = analysis.band_targets(); + self.held_rms = [stereo.rms_l, stereo.rms_r, stereo.rms_side]; + // decided on the raw window, before ballistics: smoothed levels + // converge on the floor together and would read as stereo + let loud = stereo.rms_l.max(stereo.rms_r); + if to_db(loud) > FLOOR_DB + STEREO_DECIDE_ABOVE_FLOOR_DB { + self.stereo = Some(to_db(stereo.rms_side) > to_db(loud) + STEREO_SIDE_DB); + } + self.last_fresh = Some(now); + ( + self.held_targets, + self.held_rms, + [stereo.peak_l, stereo.peak_r], + ) + } else if self + .last_fresh + .is_some_and(|last| now.saturating_duration_since(last).as_secs_f32() <= STALL_SECS) + { + (self.held_targets, self.held_rms, [0.0; 2]) + } else { + ([FLOOR_DB; BANDS], [0.0; 3], [0.0; 2]) + }; + + for ((current, target), peak) in self + .bands_db + .iter_mut() + .zip(targets) + .zip(self.band_peaks.iter_mut()) + { + *current = follow_band(*current, target, dt); + peak.update(*current, dt); + } + for (level, value) in self.level_db.iter_mut().zip(rms) { + *level = follow_level(*level, to_db(value), dt); + } + for (hold, value) in self.level_peaks.iter_mut().zip(peaks) { + hold.update(to_db(value), dt); + } + + MeterReading { + spectrum: self.bands_db.iter().map(|db| normalize(*db)).collect(), + spectrum_peaks: self + .band_peaks + .iter() + .map(|hold| normalize(hold.db)) + .collect(), + level_l: normalize(self.level_db[0]), + level_r: normalize(self.level_db[1]), + peak_l: normalize(self.level_peaks[0].db), + peak_r: normalize(self.level_peaks[1].db), + level_side: normalize(self.level_db[2]), + stereo: self.stereo, + } + } +} + +fn follow_band(current: f32, target: f32, dt: f32) -> f32 { + if target > current { + current + (target - current) * (1.0 - (-dt / BAND_ATTACK_SECS).exp()) + } else { + (current - BAND_FALL_DB_PER_SEC * dt).max(target) + } +} + +fn follow_level(current: f32, target: f32, dt: f32) -> f32 { + let tau = if target > current { + LEVEL_ATTACK_SECS + } else { + LEVEL_RELEASE_SECS + }; + current + (target - current) * (1.0 - (-dt / tau).exp()) +} + +fn to_db(amplitude: f32) -> f32 { + if amplitude <= 0.0 || !amplitude.is_finite() { + FLOOR_DB + } else { + (20.0 * amplitude.log10()).max(FLOOR_DB) + } +} + +fn to_db_power(power: f32) -> f32 { + if power <= 0.0 || !power.is_finite() { + FLOOR_DB + } else { + (10.0 * power.log10()).max(FLOOR_DB) + } +} + +fn normalize(db: f32) -> f64 { + f64::from(((db - FLOOR_DB) / -FLOOR_DB).clamp(0.0, 1.0)) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use super::*; + + fn sine(frequency: f32, amplitude: f32, sample_rate: u32, len: usize) -> Vec { + (0..len) + .map(|index| { + let time = index as f32 / sample_rate as f32; + amplitude * (std::f32::consts::TAU * frequency * time).sin() + }) + .collect() + } + + fn band(center: f32) -> usize { + BAND_CENTERS_HZ + .iter() + .position(|value| *value == center) + .unwrap() + } + + /// Feeds a steady tone for `steps` snapshots 50 ms apart. + fn settle(meter: &mut Meter, frequency: f32, sample_rate: u32, steps: u64) -> MeterReading { + let samples = sine(frequency, 0.5, sample_rate, PCM_SAMPLES); + let start = Instant::now(); + let mut reading = MeterReading::default(); + for step in 1..=steps { + reading = meter.update( + start + Duration::from_millis(50 * step), + step as usize, + sample_rate, + StereoReading::default(), + |out| out.copy_from_slice(&samples[..out.len()]), + ); + } + reading + } + + fn band_powers_db(frequency: f32, sample_rate: u32) -> [f32; BANDS] { + let mut analysis = Analysis::new(sample_rate); + let len = analysis.pcm.len(); + analysis + .pcm + .copy_from_slice(&sine(frequency, 1.0, sample_rate, len)); + analysis.band_targets() + } + + #[test] + fn a_sine_lights_its_own_third_octave_band() { + let reading = settle(&mut Meter::default(), 1_000.0, 48_000, 10); + let at_1k = reading.spectrum[band(1_000.0)]; + // -6 dBFS on a 60 dB scale reads 0.9. + assert!((at_1k - 0.9).abs() < 0.03, "1 kHz band read {at_1k}"); + assert!(reading.spectrum[band(250.0)] < 0.2); + assert!(reading.spectrum[band(4_000.0)] < 0.2); + assert!(reading.spectrum_peaks[band(1_000.0)] >= at_1k); + } + + #[test] + fn bands_cover_the_axis_without_gaps_or_double_counting() { + for sample_rate in [44_100, 48_000, 96_000] { + // Up to just below the top band's upper edge (~22.4 kHz) or + // Nyquist; 1/24-octave steps also land right on band edges. + let top = (sample_rate as f32 / 2.0 * 0.85).min(exact_center(BANDS - 1) * 1.1); + let mut frequency = 80.0_f32; + while frequency < top { + let powers = band_powers_db(frequency, sample_rate); + let loudest = powers.iter().copied().fold(FLOOR_DB, f32::max); + let total: f32 = powers + .iter() + .filter(|db| **db > FLOOR_DB) + .map(|db| 10f32.powf(db / 10.0)) + .sum(); + assert!( + (-3.5..=0.5).contains(&loudest), + "{frequency} Hz at {sample_rate}: loudest band {loudest} dB" + ); + let total_db = 10.0 * total.log10(); + assert!( + total_db.abs() < 0.5, + "{frequency} Hz at {sample_rate}: bands sum to {total_db} dB" + ); + frequency *= 2f32.powf(1.0 / 24.0); + } + } + } + + #[test] + fn deep_bass_reads_at_every_sample_rate() { + for sample_rate in [44_100, 48_000, 96_000, 192_000] { + let powers = band_powers_db(31.5, sample_rate); + assert!( + powers[band(31.5)] > -3.0, + "31.5 Hz at {sample_rate}: {} dB", + powers[band(31.5)] + ); + assert!(powers[band(1_000.0)] < -40.0); + } + // Bands above Nyquist stay at the floor. + assert_eq!(band_powers_db(1_000.0, 32_000)[band(20_000.0)], FLOOR_DB); + } + + #[test] + fn callback_gaps_keep_the_meter_steady_but_a_stall_falls() { + let mut meter = Meter::default(); + let samples = sine(1_000.0, 0.5, 48_000, PCM_SAMPLES); + let tone = StereoReading { + rms_l: 0.35, + rms_r: 0.35, + rms_side: 0.0, + peak_l: 0.5, + peak_r: 0.5, + }; + let start = Instant::now(); + let mut write = 0; + let mut steady = MeterReading::default(); + for step in 1..=40u64 { + // Every third snapshot lands between two device callbacks. + if step % 3 != 0 { + write += 1; + } + let reading = meter.update( + start + Duration::from_millis(50 * step), + write, + 48_000, + tone, + |out| out.copy_from_slice(&samples[..out.len()]), + ); + if step > 20 { + assert!( + (reading.level_l - steady.level_l).abs() < 0.02 || step == 21, + "level jumped at step {step}" + ); + assert!( + (reading.spectrum[band(1_000.0)] - 0.9).abs() < 0.03, + "band jumped at step {step}" + ); + } + steady = reading; + } + + // The counter stops for longer than a callback gap: paused. + let index = band(1_000.0); + let paused_at = start + Duration::from_millis(2_000); + let first = meter.update(paused_at, write, 48_000, tone, |_| {}); + let later = meter.update( + paused_at + Duration::from_millis(500), + write, + 48_000, + tone, + |_| {}, + ); + assert!(later.spectrum[index] < first.spectrum[index]); + assert!(later.level_l < first.level_l); + // The peak marker holds for 1.2 s before it falls too. + assert!((later.spectrum_peaks[index] - 0.9).abs() < 0.03); + let mut reading = later; + for step in 1..=20u64 { + reading = meter.update( + paused_at + Duration::from_millis(500 + 250 * step), + write, + 48_000, + tone, + |_| {}, + ); + } + assert_eq!(reading.spectrum[index], 0.0); + assert!(reading.spectrum_peaks[index] < 0.5); + } + + #[test] + fn channel_levels_follow_rms_and_hold_peaks() { + let mut meter = Meter::default(); + let start = Instant::now(); + let loud_left = StereoReading { + rms_l: 0.5, + rms_r: 0.05, + rms_side: 0.2, + peak_l: 0.9, + peak_r: 0.1, + }; + let mut reading = MeterReading::default(); + for step in 1..=20 { + reading = meter.update( + start + Duration::from_millis(50 * step), + step as usize, + 48_000, + loud_left, + |out| out.fill(0.0), + ); + } + assert!(reading.level_l > reading.level_r); + assert!((reading.level_l - normalize(to_db(0.5))).abs() < 0.02); + assert!((reading.peak_l - normalize(to_db(0.9))).abs() < 0.01); + assert!(reading.peak_l >= reading.level_l); + assert!((reading.level_side - normalize(to_db(0.2))).abs() < 0.02); + assert_eq!(reading.stereo, Some(true)); + } + + #[test] + fn stereo_is_decided_on_loud_windows_and_kept_through_silence() { + let mut meter = Meter::default(); + let start = Instant::now(); + let mut read = |step: u64, stereo: StereoReading| { + meter.update( + start + Duration::from_millis(50 * step), + step as usize, + 48_000, + stereo, + |out| out.fill(0.0), + ) + }; + let quiet = StereoReading { + rms_l: 0.0005, + rms_r: 0.0001, + rms_side: 0.0002, + ..StereoReading::default() + }; + assert_eq!(read(1, quiet).stereo, None); + let near_mono = StereoReading { + rms_l: 0.3, + rms_r: 0.3, + rms_side: 0.003, + ..StereoReading::default() + }; + assert_eq!(read(2, near_mono).stereo, Some(false)); + // silence and then a stall keep the decision + assert_eq!(read(3, StereoReading::default()).stereo, Some(false)); + let wide = StereoReading { + rms_side: 0.1, + ..near_mono + }; + assert_eq!(read(4, wide).stereo, Some(true)); + let later = meter.update( + start + Duration::from_secs(5), + 4, + 48_000, + StereoReading::default(), + |out| out.fill(0.0), + ); + assert_eq!(later.stereo, Some(true)); + } + + #[test] + fn silence_and_unknown_rate_read_the_floor() { + let mut meter = Meter::default(); + let reading = meter.update(Instant::now(), 1, 0, StereoReading::default(), |_| {}); + assert!(reading.spectrum.iter().all(|value| *value == 0.0)); + assert_eq!(reading.level_l, 0.0); + assert_eq!(reading.level_side, 0.0); + assert_eq!(reading.spectrum.len(), BAND_CENTERS_HZ.len()); + } + + #[test] + fn fft_length_tracks_the_sample_rate() { + assert_eq!(fft_len(44_100), 4096); + assert_eq!(fft_len(48_000), 4096); + assert_eq!(fft_len(96_000), 8192); + assert_eq!(fft_len(192_000), 16_384); + assert_eq!(fft_len(0), 4096); + } +} diff --git a/src/visualizations/vfd_panel.rhai b/src/visualizations/vfd_panel.rhai new file mode 100644 index 0000000..0a2843c --- /dev/null +++ b/src/visualizations/vfd_panel.rhai @@ -0,0 +1,1653 @@ +// name: VFD panel +// protocol: furumi-visualizer-v3 +// bundle-version: 8 +// +// A hi-fi front panel in the style of a vacuum fluorescent display: thin +// segment digits, a peak level meter (bars or needles), a third-octave +// analyzer with three levels of glow and peak hold, a peak frequency readout +// with hold, tone fans, a signal path schematic, the transport word, mode +// lamps and a dot-matrix title line. Everything is drawn thin (eighth blocks, +// braille dots and box-drawing slashes for the 14-segment diagonals); only +// level bars are thicker. +// +// Typography: numbers (time, frequency, volume) in 7-segment digits, the +// transport word (PLAY / PAUSE / STOP) in 14-segment letters with faint unlit +// segments, +// the title in a 5x7 dot matrix, service labels in plain thin text, mode lamps +// as a label over a short bar. +// +// Effects, most of them keeping a little state between frames: +// power-on segment test, counter "search" on track changes, OVER lamp with +// hold, blinking pause point, slightly uneven digit brightness (an aged +// tube), a slow filament "breath", phosphor that glows brighter only where a +// column is loud, a dimmer at night, colours that fade into unlit phosphor +// on pause, a source block that goes dark and relights with its new value, +// a short burst of static when the track or source changes, a pulse that +// now and then travels the signal path, LOUDNESS / MUTE / SEARCH lamps, a +// running tape counter, and a standby clock with a sweep every minute when +// nothing is loaded. +// +// Options: edit the functions below. +fn PALETTE() { "classic" } // "classic" | "green" | "amber" | "ice" +fn METER_STYLE() { "bars" } // "bars" | "needles" +fn NIGHT_DIMMER() { true } // dim the panel from 22:00 to 07:00 +fn DISPLAY_MODE() { "auto" } // "auto" | "full" | "spectrum" | "minimal" | "deck" +// full everything: meters, analyzer, tone, signal path, transport +// spectrum a taller analyzer; the lower modules shrink to one line +// minimal time, title, L/R meter and the analyzer, no signal path +// deck a cassette deck: large counter, tape counter, wide L/R meters +// auto Shift+M in the visualizer steps through full, spectrum, +// minimal and deck; a fixed value pins one of them +// A display mode that does not fit the window steps down: full -> spectrum +// -> minimal -> compact. On a change the panel switches like hardware: the +// time and L/R meters stay lit, the other sections go dark and light up one +// after another. +fn DECK_LAMPS() { true } // AMS / NR / AUTO REVERSE / REW-FF lamps in deck mode +// +// Script entry point: +// fn render(input) -> Array (stateless) +// fn render(input) -> #{ commands: Array, state: Map } +// +// Input fields (v2): +// width, height terminal size in cells +// time, position, progress animation time and playback progress +// volume, paused player state +// energy, bass, mid, treble smoothed bands 0.0..1.0 (scaled by volume) +// beat transient pulse estimate 0.0..1.0 +// seed stable per-track number 0.0..1.0 +// samples recent mono waveform -1.0..1.0 +// show_clock, clock user setting and local clock text +// track_title, track_artist metadata strings +// Added in v3: +// spectrum, spectrum_peaks 31 third-octave bands (spectrum_hz: 20 Hz .. +// 20 kHz), 0.0..1.0 over spectrum_floor_db..0 +// dBFS, with analyzer fall and peak hold +// level_l, level_r channel RMS on the same scale +// level_side RMS of (L - R) / 2 on the same scale: the +// floor when both channels carry one signal +// channel_mode "stereo" or "mono" (decided on loud +// passages, kept through silence), "" unknown +// peak_l, peak_r held channel sample peaks on the same scale +// sample_rate analyzed sample rate in Hz (0 = none) +// duration, track_number, disc_number, year, release_title +// audio_format, audio_bitrate, audio_sample_rate, audio_bit_depth +// source "local", "federated", "podcast" or "" +// playing a track is loaded and not paused +// queue_index, queue_length 1-based position (0 = none) and length +// shuffle, repeat bool and "off" / "one" / "all" +// clock_hour, clock_minute, clock_second, clock_millis local time +// mode display mode counter (Shift+M), use modulo +// dt, frame seconds since the last frame, frame count +// state what the last frame returned as `state` +// (empty when the visualizer opens or the +// script changes) +// +// Draw commands (v3 adds dots, line and text attributes): +// #{ op: "clear", bg } +// #{ op: "cell" | "text" | "hline" | "vline" | "rect" | "trace", ... } +// #{ op: "dots", points: [x0, y0, x1, y1, ...], fg } braille dots; a cell +// is 2 x 4 dots +// #{ op: "line", x0, y0, x1, y1, fg } thin braille line +// bold / dim / italic / underline / reversed: true on any command +// +// The file is yours to edit; a newer Furumi only replaces it while it still +// carries an older "bundle-version" line. + +// ---------- helpers ---------- + +fn clamp(v, lo, hi) { if v < lo { lo } else if v > hi { hi } else { v } } +fn mn(a, b) { if a < b { a } else { b } } +fn mx(a, b) { if a > b { a } else { b } } +fn frac(x) { x - x.floor() } + +fn rgb(r, g, b) { + to_int(clamp(r, 0, 255)) * 65536 + to_int(clamp(g, 0, 255)) * 256 + to_int(clamp(b, 0, 255)) +} + +fn scale(c, f) { + rgb(to_float((c >> 16) & 255) * f, to_float((c >> 8) & 255) * f, to_float(c & 255) * f) +} + +// Blend toward white by `t` (0..1). +fn whiten(c, t) { + let r = to_float((c >> 16) & 255); let g = to_float((c >> 8) & 255); let b = to_float(c & 255); + rgb(r + (255.0 - r) * t, g + (255.0 - g) * t, b + (255.0 - b) * t) +} + +// Blend two colours: t = 0 gives a, 1 gives b. +fn mixc(a, b, t) { + let ar = to_float((a >> 16) & 255); let ag = to_float((a >> 8) & 255); let ab = to_float(a & 255); + let br = to_float((b >> 16) & 255); let bg = to_float((b >> 8) & 255); let bb = to_float(b & 255); + rgb(ar + (br - ar) * t, ag + (bg - ag) * t, ab + (bb - ab) * t) +} + +fn pad2(n) { if n < 10 { "0" + n } else { "" + n } } +fn pad4(n) { let s = "" + n; while s.len() < 4 { s = "0" + s; } s } + +fn get(input, key, fallback) { if key in input { input[key] } else { fallback } } + +// Called in method style (cmds.txt(...)) so commands append in place. +// Negative coordinates are dropped: Furumi rejects them. +fn txt(x, y, s, fg) { + if x >= 0 && y >= 0 && s != "" { + this.push(#{ op: "text", x: x, y: y, text: s, fg: fg, bg: 0 }); + } +} +fn hl(x, y, w, ch, fg) { + if x >= 0 && y >= 0 && w > 0 && fg >= 0 { this.push(#{ op: "hline", x: x, y: y, w: w, ch: ch, fg: fg, bg: 0 }); } +} +fn vl(x, y, h, ch, fg) { + if x >= 0 && y >= 0 && h > 0 && fg >= 0 { this.push(#{ op: "vline", x: x, y: y, h: h, ch: ch, fg: fg, bg: 0 }); } +} +fn fill(x, y, w, h, ch, fg) { + if x >= 0 && y >= 0 && w > 0 && h > 0 { + this.push(#{ op: "rect", x: x, y: y, w: w, h: h, ch: ch, fg: fg, bg: 0 }); + } +} +// Braille line in dot coordinates (2 dots per cell across, 4 down). +fn ln(x0, y0, x1, y1, fg) { + if x0 >= 0 && y0 >= 0 && x1 >= 0 && y1 >= 0 { + this.push(#{ op: "line", x0: x0, y0: y0, x1: x1, y1: y1, fg: fg, bg: 0 }); + } +} +fn dots(points, fg) { + if points.len() > 1 { this.push(#{ op: "dots", points: points, fg: fg, bg: 0 }); } +} + +// ---------- palette and brightness ---------- +// Four colour zones like the filters over a real VFD: text, analyzer, +// auxiliary (tone / signal path / transport) and warnings. Each frame the +// zones get one brightness: night dimmer x filament breath (plus a boost during +// the power-on test). Loud analyzer columns glow brighter on their own, and +// pause fades lit colours into unlit phosphor. + +fn zone_bases() { + switch PALETTE() { + "green" => [rgb(120, 255, 214), rgb(120, 255, 214), rgb(120, 255, 214), rgb(255, 72, 52)], + "amber" => [rgb(255, 184, 52), rgb(255, 176, 36), rgb(255, 184, 52), rgb(255, 64, 40)], + "ice" => [rgb(214, 236, 255), rgb(150, 206, 255), rgb(120, 196, 255), rgb(255, 86, 86)], + _ => [rgb(232, 244, 240), rgb(255, 176, 36), rgb(84, 234, 216), rgb(255, 58, 38)] + } +} + +fn night(input) { + let h = get(input, "clock_hour", 12); + NIGHT_DIMMER() && (h >= 22 || h < 7) +} + +// An unlit, desaturated phosphor tone of `c`: what a segment looks like when +// the grid voltage drops. `t` blends towards it (0 = lit colour). +fn phosphor(c, t) { + let r = to_float((c >> 16) & 255); let g = to_float((c >> 8) & 255); let b = to_float(c & 255); + let l = (0.3 * r + 0.59 * g + 0.11 * b) * 0.45; + rgb(r + (l * 0.92 - r) * t, g + (l - g) * t, b + (l * 0.96 - b) * t) +} + +fn glow(c, b, fade) { phosphor(scale(c, b), fade) } + +// `boost` brightens the whole panel (power-on test); `fade` (0..1) moves the +// lit colours towards unlit phosphor (pause, stop). +fn make_palette(input, boost, fade) { + let z = zone_bases(); + let dim = if night(input) { 0.72 } else { 1.0 }; + let breath = 0.955 + 0.045 * sin(input.time * 0.9); + let b = clamp(dim * breath + boost, 0.3, 1.15); + let amber = glow(z[1], b, fade); + // the analyzer's tint runs from warm amber in the bass to light yellow + // in the treble, a small shift that keeps the panel one colour + let warm_base = if PALETTE() == "classic" || PALETTE() == "amber" { mixc(z[1], rgb(255, 120, 16), 0.3) } else { scale(z[1], 0.9) }; + #{ + white: glow(z[0], b, fade), white_mid: glow(z[0], 0.6 * b, fade), white_ghost: scale(z[0], 0.095), + amber: amber, amber_low: glow(z[1], 0.68 * b, fade), amber_hot: whiten(amber, 0.5), + peak: whiten(amber, 0.8), amber_ghost: scale(z[1], 0.17), amber_text: glow(z[1], 0.8 * b, fade), + amber_rule: scale(z[1], 0.3), + amber_warm: glow(warm_base, b, fade), amber_light: glow(whiten(z[1], 0.32), b, fade), + red: glow(z[3], b, fade * 0.6), red_mid: glow(z[3], 0.34 * b, fade * 0.6), red_ghost: scale(z[3], 0.18), + cyan: glow(z[2], b, fade), cyan_mid: glow(z[2], 0.55 * b, fade), cyan_hot: whiten(glow(z[2], b, fade), 0.6), + cyan_line: glow(z[2], 0.4 * b, fade), + cyan_ghost: scale(z[2], 0.13), + // unlit segments of the thin digits: fainter than the analyzer's, + // so a lit digit never reads as an 8 + white_seg: scale(z[0], 0.055), amber_seg: scale(z[1], 0.075), cyan_seg: scale(z[2], 0.07), + // unlit lamps: visible without being read as lit, the same at night + lamp_off: scale(z[0], 0.17), red_lamp_off: scale(z[3], 0.26), + amber_lamp_off: scale(z[1], 0.22), cyan_lamp_off: scale(z[2], 0.2), + noise: scale(z[0], 0.32 * b) + } +} + +// ---------- thin segment font ---------- +// Segments are thin lines on cell edges, all about equally thick: horizontals +// are eighth blocks ("▁", 1/8 of the cell height) along the bottom of a row, +// verticals are quarter blocks ("▎", 1/4 of the narrower cell width) along +// the left edge of the first and the last column. A cell holds one stroke, +// so where a horizontal would share the left column with a vertical (middle +// and bottom bars) the vertical keeps the cell and the bar starts one column +// later: a small joint gap like on a real segment display. A glyph is cw cells +// wide and 2*rh+1 rows tall. It covers digits and the few letters in +// seg_mask; the transport word uses the 14-segment letters below (seg14_*). + +fn seg_mask(ch) { + let s = switch ch { + "0" => "abcdef", "1" => "bc", "2" => "abged", "3" => "abgcd", + "4" => "fgbc", "5" => "afgcd", "S" => "afgcd", "6" => "afgedc", + "7" => "abc", "8" => "abcdefg", "9" => "abcdfg", "P" => "abefg", + "L" => "def", "A" => "abcefg", "U" => "bcdef", "E" => "adefg", + "O" => "abcdef", "H" => "bcefg", "C" => "adef", "r" => "eg", "n" => "ceg", + "d" => "bcdeg", "-" => "g", _ => "" + }; + let m = 0; + for c in s.chars() { + m = m | switch c { 'a' => 1, 'b' => 2, 'c' => 4, 'd' => 8, 'e' => 16, 'f' => 32, 'g' => 64, _ => 0 }; + } + m +} + +fn pick(mask, bit, on, off) { if (mask & bit) != 0 { on } else { off } } + +fn seg(x, y, mask, cw, rh, on, off) { + let inner = mx(cw - 2, 1); + this.hl(x, y, cw - 1, "▁", pick(mask, 1, on, off)); + this.vl(x, y + 1, rh, "▎", pick(mask, 32, on, off)); + this.vl(x + cw - 1, y + 1, rh, "▎", pick(mask, 2, on, off)); + this.hl(x + 1, y + rh, inner, "▁", pick(mask, 64, on, off)); + this.vl(x, y + rh + 1, rh, "▎", pick(mask, 16, on, off)); + this.vl(x + cw - 1, y + rh + 1, rh, "▎", pick(mask, 4, on, off)); + this.hl(x + 1, y + 2 * rh, inner, "▁", pick(mask, 8, on, off)); +} + +// ---------- 14-segment letters (transport word) ---------- +// A fixed 7 x 5 cell glyph: the outline as in the 7-segment font, a middle +// bar split in two halves (g1, g2), centre strokes above and below (i, l) and +// four diagonals drawn with box-drawing slashes, two cells each. Unlit +// segments glow faintly, like the counter's. Lit strokes are drawn last, so a +// lit stroke wins a cell it shares with an unlit one. + +fn seg14_mask(ch) { + let s = switch ch { + "P" => "a b f e g1 g2", "L" => "f e d", "A" => "a b c e f g1 g2", + "Y" => "h j l", "U" => "b c d e f", "S" => "a f g1 g2 c d", + "E" => "a f e d g1", "T" => "a i l", "O" => "a b c d e f", _ => "" + }; + let m = 0; + for part in s.split(" ") { + m = m | switch part { + "a" => 1, "b" => 2, "c" => 4, "d" => 8, "e" => 16, "f" => 32, + "g1" => 64, "g2" => 128, "h" => 256, "i" => 512, "j" => 1024, + "k" => 2048, "l" => 4096, "m" => 8192, _ => 0 + }; + } + m +} + +fn seg14_stroke(x, y, bit, fg) { + switch bit { + 1 => this.hl(x, y, 6, "▁", fg), + 2 => this.vl(x + 6, y + 1, 2, "▎", fg), + 4 => this.vl(x + 6, y + 3, 2, "▎", fg), + 8 => this.hl(x + 1, y + 4, 5, "▁", fg), + 16 => this.vl(x, y + 3, 2, "▎", fg), + 32 => this.vl(x, y + 1, 2, "▎", fg), + 64 => this.hl(x + 1, y + 2, 2, "▁", fg), + 128 => this.hl(x + 4, y + 2, 2, "▁", fg), + 256 => { this.txt(x + 1, y + 1, "╲", fg); this.txt(x + 2, y + 2, "╲", fg); }, + 512 => this.vl(x + 3, y + 1, 2, "▎", fg), + 1024 => { this.txt(x + 4, y + 1, "╱", fg); this.txt(x + 3, y + 2, "╱", fg); }, + 2048 => { this.txt(x + 2, y + 3, "╱", fg); this.txt(x + 1, y + 4, "╱", fg); }, + 4096 => this.vl(x + 3, y + 3, 2, "▎", fg), + 8192 => { this.txt(x + 3, y + 3, "╲", fg); this.txt(x + 4, y + 4, "╲", fg); }, + _ => () + } +} + +// Draws a word in 14-segment letters; returns the x after it. +fn seg14_text(x, y, s, on, off) { + let cx = x; + // unlit diagonals last, so the faint X of a 14-segment display stays whole + // (unlit straight strokes give up the cells they share with it) + let off_bits = [1, 2, 4, 8, 16, 32, 64, 128, 512, 4096, 256, 1024, 2048, 8192]; + let bits = [256, 1024, 2048, 8192, 1, 2, 4, 8, 16, 32, 64, 128, 512, 4096]; + for ch in s.chars() { + let mask = seg14_mask("" + ch); + for b in off_bits { if (mask & b) == 0 { this.seg14_stroke(cx, y, b, off); } } + for b in bits { if (mask & b) != 0 { this.seg14_stroke(cx, y, b, on); } } + cx += 8; + } + cx +} + +// An aged tube: every digit position is a little brighter or dimmer. +fn wear(x) { 0.84 + 0.16 * frac(abs(sin(to_float(x) * 12.9898)) * 43758.5453) } + +// Text in the segment font. "." is a point, " " a blank digit. `point_on` +// lets the caller blink points. Returns the x after the last glyph. +fn seg_text(x, y, s, cw, rh, on, off, point_on) { + let cx = x; + for ch in s.chars() { + if ch == '.' { + this.txt(cx, y + 2 * rh, "▖", if point_on { scale(on, wear(cx)) } else { off }); + cx += 2; + } else { + if ch != ' ' { this.seg(cx, y, seg_mask("" + ch), cw, rh, scale(on, wear(cx)), off); } + cx += cw + 1; + } + } + cx +} + +// ---------- measurements ---------- + +// Normalized meter value -> dBFS. +fn dbfs(input, v) { get(input, "spectrum_floor_db", -60.0) * (1.0 - v) } + +// Display curve of the analyzer: a 42 dB window per third-octave band that +// ends at `top` dBFS, raised to a power so quiet passages sit lower and loud +// ones reach the top. `top` follows the music (see update_range): the window +// moves, the measurements do not. +fn band_display(input, v, top) { + // the window never reaches below the analyzer floor: silence stays dark + let lo = mx(top - 42.0, get(input, "spectrum_floor_db", -60.0)); + let lin = clamp((dbfs(input, v) - lo) / (top - lo), 0.0, 1.0); + if lin <= 0.0 { 0.0 } else { pow(lin, 1.3) } +} + +// Top of the analyzer window: rises at once with the loudest band, falls +// slowly (4 dB/s), and stays within -26..-6 dBFS, so quiet music fills more +// of the analyzer and loud music does not pin it to the top. +fn update_range(st, input, dt) { + let s = get(input, "spectrum", []); + let loudest = -60.0; + for i in 5..30 { if i < s.len() { loudest = mx(loudest, dbfs(input, s[i])); } } + if !("agc" in st) { st.agc = -14.0; } + st.agc = if loudest > st.agc { loudest } else { st.agc - 4.0 * dt }; + st.top_db = clamp(st.agc + 4.0, -26.0, -6.0); + st +} + +// The 25 panel bands 63 Hz .. 16 kHz are spectrum entries 5..29. +fn panel_bands(input, top) { + let s = get(input, "spectrum", []); + let p = get(input, "spectrum_peaks", []); + let out = []; + for i in 5..30 { + let v = if i < s.len() { s[i] } else { 0.0 }; + let pk = if i < p.len() { p[i] } else { 0.0 }; + out.push([band_display(input, v, top), band_display(input, pk, top)]); + } + out +} + +fn band_label(i) { + switch i { 0 => "63", 4 => "160", 8 => "400", 12 => "1k", 16 => "2.5k", 20 => "6.3k", 24 => "16k", _ => "·" } +} + +fn band_hz(i) { + let hz = [63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, + 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500, 16000]; + hz[clamp(i, 0, 24)] +} + +// Deck peak meter scale: 0 on the scale is -10 dBFS; the first mark is the +// host floor (-60 dBFS). +fn meter_pos(db) { + let marks = [-50.0, -20.0, -15.0, -10.0, -7.0, -5.0, -3.0, -1.0, 0.0, 1.0, 3.0, 5.0, 8.0]; + let d = db + 10.0; + if d <= marks[0] { return 0.0; } + for i in 1..marks.len() { + if d <= marks[i] { + return to_float(i - 1) + (d - marks[i - 1]) / (marks[i] - marks[i - 1]); + } + } + to_float(marks.len() - 1) +} + +// Tape counter: counts take-up reel turns, so it runs a little slower as +// the reel fills. +fn tape_counter(position) { + to_int(sqrt(mx(position, 0.0) * 30.0 + 400.0) * 20.0 - 400.0) % 10000 +} + +// ---------- panels ---------- + +fn draw_counter(input, st, x, y, cw, rh) { + let p = st.pal; + let secs = clamp(to_int(input.position), 0, 99 * 60 + 59); + let text = "" + (secs / 60) + "." + pad2(secs % 60); + if st.spin > 0.0 { + // track change: digits "search" like an AMS counter + let f = input.frame; + text = "" + (f % 10) + "." + ((f * 7) % 10) + "" + ((f * 3) % 10); + } + let lit = if input.paused { p.white_mid } else { p.white }; + let off = if st.boot > 0.0 { lit } else { p.white_seg }; + let blink = !input.paused || (to_int(input.time * 2.0) % 2 == 0); + let end = this.seg_text(x, y, text, cw, rh, lit, off, blink); + let n = get(input, "track_number", 0); + let q = get(input, "queue_index", 0); + let tn = if n > 0 { n } else { q }; + let ts = if tn <= 0 { "-" } else if tn > 99 { "--" } else { "" + tn }; + let te = this.seg_text(end + 3, y, ts, cw, rh, lit, off, false); + this.txt(x, y + 2 * rh + 2, "TIME", p.white_mid); + this.txt(end + 3, y + 2 * rh + 2, "TRACK", p.white_mid); + te +} + +// Width kept for the counter so the meter never moves: "88.88" and a +// two-digit track number. +fn counter_width() { 29 + 3 + 13 } + +fn draw_meter(input, st, x, y, w) { + let p = st.pal; + let labels = ["-∞", "-20", "-15", "-10", "-7", "-5", "-3", "-1", "0", "+1", "+3", "+5", "+8"]; + let n = 12.0; + this.txt(x + 4, y, "PEAK LEVEL METER", p.white); + this.txt(x + w - 4, y, "0VU", p.white); + this.txt(x + w - 4, y + 1, "▔▔▔", p.white_mid); + let bx = x + 3; + let mw = w - 4; + let hot = to_int(8.0 / n * to_float(mw)); + let rows = [["L", get(input, "level_l", 0.0), get(input, "peak_l", 0.0), y + 2], + ["R", get(input, "level_r", 0.0), get(input, "peak_r", 0.0), y + 4]]; + for r in rows { + this.txt(x, r[3], r[0], p.white); + this.hl(bx, r[3], hot, "▃", if st.boot > 0.0 { p.white_mid } else { p.white_ghost }); + // the red zone glows at a middle level even when unlit, so it reads as a zone + this.hl(bx + hot, r[3], mw - hot, "▃", if st.boot > 0.0 { p.red } else { p.red_mid }); + let cells = if r[1] > 0.0 { clamp(to_int(meter_pos(dbfs(input, r[1])) / n * to_float(mw) + 0.5), 0, mw) } else { 0 }; + this.hl(bx, r[3], mn(cells, hot), "▃", p.white); + if cells > hot { this.hl(bx + hot, r[3], cells - hot, "▃", p.red); } + if r[2] > 0.0 { + // a two-cell peak mark, brighter than the bar + let pk = clamp(to_int(meter_pos(dbfs(input, r[2])) / n * to_float(mw)), 1, mw - 1); + this.hl(bx + pk - 1, r[3], 2, "▃", if pk >= hot { whiten(p.red, 0.25) } else { whiten(p.white, 0.3) }); + } + } + this.txt(x, y + 3, "dB", p.white); + // labels that would touch the previous one are left out on narrow meters + let free = bx; + for k in 0..13 { + let lx = bx + to_int(to_float(k) / n * to_float(mw - 2)) - if k == 0 { 0 } else { 1 }; + if lx >= free && (k == 12 || lx + labels[k].len() < bx + mw) { + this.txt(lx, y + 3, labels[k], if k >= 8 { p.red } else { p.white }); + free = lx + labels[k].len() + 1; + } + } +} + +// Two needle VU meters drawn with braille: an arc scale with a red zone, +// ticks at the deck marks and a needle on the RMS level. +fn draw_needles(input, st, x, y, w) { + let p = st.pal; + this.txt(x + 4, y, "VU METER", p.white); + this.txt(x + w - 4, y, "0VU", p.white); + let mw = (w - 4) / 2; + let chans = [["L", get(input, "level_l", 0.0), get(input, "peak_l", 0.0)], + ["R", get(input, "level_r", 0.0), get(input, "peak_r", 0.0)]]; + for k in 0..2 { + let left = x + k * (mw + 4); + let wd = mw * 2; // meter width in dots + let top = (y + 1) * 4 + 1; // arc top in dots + let bottom = (y + 5) * 4 + 3; // last dot row of the face + let r = to_float(wd / 2 - 2) / 0.7071; // radius for a +/-45 degree arc + let cx = to_float(left * 2 + wd / 2); + let cy = to_float(top) + r; // pivot below the face + let arc = []; let red_arc = []; let ticks = []; + let steps = mx(wd, 8); + for i in 0..=steps { + let pos = to_float(i) / to_float(steps) * 12.0; + let a = (pos / 12.0 * 90.0 - 45.0) * 0.0174533; + let px = to_int(cx + r * sin(a)); let py = to_int(cy - r * cos(a)); + if pos >= 8.0 { red_arc.push(px); red_arc.push(py); } else { arc.push(px); arc.push(py); } + } + for m in [0.0, 1.0, 3.0, 5.0, 8.0, 10.0, 12.0] { + let a = (m / 12.0 * 90.0 - 45.0) * 0.0174533; + let tx = to_int(cx + (r + 2.0) * sin(a)); let ty = to_int(cy - (r + 2.0) * cos(a)); + // keep the label row free + if ty >= (y + 1) * 4 { ticks.push(tx); ticks.push(ty); } + } + this.dots(arc, if st.boot > 0.0 { p.white } else { p.white_mid }); + this.dots(red_arc, p.red); + this.dots(ticks, p.white); + let level = if chans[k][1] > 0.0 { meter_pos(dbfs(input, chans[k][1])) } else { 0.0 }; + if st.boot > 0.0 { level = 12.0 * (1.0 - st.boot / 0.9); } + let a = (level / 12.0 * 90.0 - 45.0) * 0.0174533; + let tip_x = cx + (r - 1.0) * sin(a); let tip_y = cy - (r - 1.0) * cos(a); + // stop the needle at the bottom of the face instead of the pivot + let rb = (cy - to_float(bottom)) / cos(a); + let foot_x = cx + rb * sin(a); + this.ln(to_int(tip_x), to_int(tip_y), to_int(foot_x), bottom, if level >= 8.0 { p.red } else { p.white }); + this.txt(left, y + 5, chans[k][0], p.white); + let peak_on = chans[k][2] > 0.0 && meter_pos(dbfs(input, chans[k][2])) >= 8.0; + this.txt(left + mw - 4, y + 5, "PEAK", if peak_on || st.boot > 0.0 { p.red } else { p.red_lamp_off }); + } +} + +// Red lamps like a deck's tape-type indicators, here for the loudest range; +// below them the OVER lamp and the tape counter. +fn draw_lamps(input, st, bands, x, y) { + let p = st.pal; + let sums = [0.0, 0.0, 0.0]; + for i in 0..bands.len() { + let g = if i < 7 { 0 } else if i < 17 { 1 } else { 2 }; + sums[g] += bands[i][0]; + } + let avg = [sums[0] / 7.0, sums[1] / 10.0, sums[2] / 8.0]; + let best = 0; + if avg[1] > avg[best] { best = 1; } + if avg[2] > avg[best] { best = 2; } + let names = ["LOW", "MID", "HIGH"]; + let cx = x; + for i in 0..3 { + let on = st.boot > 0.0 || (i == best && avg[best] > 0.05); + this.txt(cx, y, names[i], if on { p.red } else { p.red_lamp_off }); + this.hl(cx, y + 1, names[i].len(), "▔", if on { p.red } else { p.red_lamp_off }); + cx += names[i].len() + 3; + } + let over = st.boot > 0.0 || st.over > 0.0; + this.txt(x, y + 3, "OVER", if over { p.red } else { p.red_lamp_off }); + this.txt(x, y + 5, "CNT", p.white_mid); + this.txt(x + 4, y + 5, if st.boot > 0.0 { "8888" } else { pad4(tape_counter(input.position)) }, p.white); +} + +// A mode lamp: the label with a short indicator bar under it. +fn lamp(x, y, label, on, lit, ghost) { + let fg = if on { lit } else { ghost }; + this.txt(x, y, label, fg); + this.hl(x, y + 1, label.len(), "▔", fg); + x + label.len() + 3 +} + +fn draw_status_row(input, st, x, y, w) { + let p = st.pal; + let boot = st.boot > 0.0; + let repeat = get(input, "repeat", "off"); + let source = get(input, "source", ""); + let vol = to_int(input.volume * 100.0 + 0.5); + let cx = x; + cx = this.lamp(cx, y, "REPEAT", boot || repeat != "off", p.white, p.lamp_off); + if repeat == "one" || boot { this.txt(cx - 2, y, "1", p.white); } + cx = this.lamp(cx, y, "SHUFFLE", boot || get(input, "shuffle", false), p.white, p.lamp_off); + cx = this.lamp(cx, y, "LOCAL", boot || source == "local", p.white, p.lamp_off); + cx = this.lamp(cx, y, "FED", boot || source == "federated", p.white, p.lamp_off); + cx = this.lamp(cx, y, "PODCAST", boot || source == "podcast", p.white, p.lamp_off); + cx += 2; + // automatic modes: loudness at low volume, mute at zero, search on seeks + cx = this.lamp(cx, y, "LOUDNESS", boot || (vol > 0 && vol <= 30), p.white, p.lamp_off); + cx = this.lamp(cx, y, "MUTE", boot || vol == 0, p.red, p.red_lamp_off); + let blink = to_int(input.time * 6.0) % 2 == 0; + this.lamp(cx, y, "SEARCH", boot || (st.search > 0.0 && blink), p.white, p.lamp_off); + + // format badge, like a noise-reduction lamp with its boxed letter + let fmt = get(input, "audio_format", "").to_upper(); + let depth = get(input, "audio_bit_depth", 0); + let badge = if fmt == "" { "PCM" } else { fmt }; + let kbps = get(input, "audio_bitrate", 0); + let box_ = if depth > 0 { "" + depth + "BIT" } else if kbps > 0 { "" + kbps + "K" } else { "--" }; + let bx = x + w - badge.len() - box_.len() - 4; + if bx > cx + 6 { + this.txt(bx, y, badge, if fmt != "" || boot { p.white } else { p.lamp_off }); + this.txt(bx + badge.len() + 2, y, "[" + box_ + "]", p.white); + } +} + +// Dot-matrix title line: 5x7 glyphs in braille (3 cells x 2 rows each), +// scrolling smoothly by dots when it is too long. +fn draw_matrix_title(input, st, x, y, w, label) { + let p = st.pal; + if w <= 3 { return; } + let text = label.to_upper(); + let chars = []; + for c in text.chars() { + // combining marks, zero-width characters and variation selectors + // have no cell of their own + let u = to_int(c); + if (u >= 0x300 && u <= 0x36F) || (u >= 0x1AB0 && u <= 0x1AFF) || (u >= 0x1DC0 && u <= 0x1DFF) + || (u >= 0x20D0 && u <= 0x20FF) || (u >= 0x200B && u <= 0x200F) || (u >= 0xFE00 && u <= 0xFE0F) { + continue; + } + chars.push(c); + } + let count = chars.len(); + let x0 = x * 2; let wd = w * 2; let y0 = y * 4; + let total = count * 6; + let gap = 24; + let off = if total <= wd { 0 } else { to_int(input.time * 14.0) % (total + gap) }; + let pts = []; + // during the gap between loops `i` stays at the end of the text + let i = mn(off / 6, count); + let px = x0 + i * 6 - off; + // two passes over the text so the loop joins seamlessly + let pass = 0; + while px < x0 + wd && pass < 2 { + if i >= count { + if total <= wd { break; } + px += gap; i = 0; pass += 1; + continue; + } + let glyph = dm_glyph(chars[i]); + for row in 0..7 { + let bits = glyph[row]; + if bits == 0 { continue; } + for col in 0..5 { + if (bits & (16 >> col)) != 0 { + let dx = px + col; + if dx >= x0 && dx < x0 + wd { pts.push(dx); pts.push(y0 + row); } + } + } + } + px += 6; i += 1; + } + this.dots(pts, p.white); +} + +fn title_label(input) { + if input.track_artist != "" && input.track_title != "" { + input.track_artist + " — " + input.track_title + } else if input.track_title != "" { input.track_title } else { "NO DISC" } +} + +// Segment analyzer: thin dashes stacked per band, a dark gap between bands. +// Three levels of glow: lit segments (dimmer at the foot of a column, the top +// one nearly white), unlit segments that stay visible but faint, and a light +// peak-hold mark above the column. Louder columns burn brighter on their own +// instead of the whole panel brightening. +fn draw_analyzer(input, st, bands, x, y, bw, h) { + let p = st.pal; + let n = bands.len(); + let bar = mx(bw - 1, 1); + let right = x + 2 + n * bw; + let scale_fg = p.amber_ghost + rgb(30, 22, 3); + let red_row = y + h / 5; + let free = x + 1; + let r = 0; + while r < h { + let fg = if y + r == red_row { p.red } else { scale_fg }; + this.txt(x, y + r, "·", fg); + this.txt(right, y + r, "·", fg); + r += 1; + } + let boot = st.boot > 0.0; + for i in 0..n { + let bx = x + 2 + i * bw; + let v = if boot { 1.0 } else { bands[i][0] }; + let lit = clamp(to_int(v * to_float(h) + 0.5), 0, h); + let g = if boot { 1.0 } else { 0.78 + 0.34 * v }; + let t = to_float(i) / to_float(mx(n - 1, 1)); + let col = if t < 0.5 { mixc(p.amber_warm, p.amber, t * 2.0) } else { mixc(p.amber, p.amber_light, (t - 0.5) * 2.0) }; + if lit < h { this.fill(bx, y, bar, h - lit, "▂", p.amber_ghost); } + if lit > 0 { + let low = to_int(to_float(lit) * 0.45); + if low > 0 { this.fill(bx, y + h - low, bar, low, "▂", scale(col, 0.68 * g)); } + let body = lit - low - 1; + if body > 0 { this.fill(bx, y + h - lit + 1, bar, body, "▂", scale(col, g)); } + this.hl(bx, y + h - lit, bar, "▂", p.amber_hot); + } + let cap = clamp(to_int(bands[i][1] * to_float(h) + 0.5), 0, h); + if cap > lit && !boot { this.hl(bx, y + h - cap, bar, "▂", p.peak); } + let label = band_label(i); + // narrow bars: keep only the dot halfway between two frequencies, so + // dots never push the frequencies out + if label != "·" || bar >= 2 || i % 4 == 2 { + let lx = mx(bx + (bar - label.len()) / 2, x + 1); + if lx >= free { + this.txt(lx, y + h + 1, label, p.amber_text); + free = lx + label.len() + 1; + } + } + } + right +} + +// Peak frequency as one measuring module with a fixed vertical structure: +// caption and HOLD lamp, the value, a rule, then the sample rate. The value +// is held (HOLD lit) while the loudest band is weaker than the held one. +fn draw_measure(input, st, x, y, w) { + let p = st.pal; + let boot = st.boot > 0.0; + let live = boot || st.hold_v > 0.05; + let holding = !boot && live && st.hold_i != st.best_i; + this.txt(x, y, "PEAK FREQUENCY", p.amber_text); + this.txt(x + w - 4, y, "HOLD", if holding || boot { p.amber } else { p.amber_lamp_off }); + let hz = band_hz(st.hold_i); + let digits = ""; let unit = ""; + if hz < 1000 { digits = "" + hz; unit = "Hz"; } + else if hz < 10000 { digits = "" + (hz / 1000) + "." + ((hz % 1000) / 100); unit = "kHz"; } + else { digits = "" + (hz / 1000); unit = "kHz"; } + if !live { digits = "--"; } + let off = if boot { p.amber } else { p.amber_seg }; + let end = this.seg_text(x, y + 2, digits, 6, 2, p.amber, off, true); + this.txt(end + 1, y + 6, unit, if live { p.amber_text } else { p.amber_ghost }); + this.hl(x, y + 8, w, "▁", p.amber_rule); + let sr = get(input, "sample_rate", 0); + let srt = if sr > 0 { "" + (sr / 1000) + "." + ((sr % 1000) / 100) + " kHz" } else { "--" }; + this.txt(x, y + 10, "RATE", p.amber_text); + this.txt(x + w - srt.len(), y + 10, srt, p.amber); +} + +// Height of the measuring module. +fn measure_height() { 11 } + +// Bass / treble fans as thin stepped strokes: each range's line runs from its +// level at the edge (+10 .. -10) into the flat 0 line in the middle; only the +// line that matches the current balance against the mids is drawn. +fn draw_fans(input, st, bands, x, y, w) { + let p = st.pal; + let lo = (bands[1][0] + bands[2][0] + bands[3][0] + bands[4][0]) / 4.0; + let mid = (bands[10][0] + bands[11][0] + bands[12][0] + bands[13][0]) / 4.0; + let hi = (bands[19][0] + bands[20][0] + bands[21][0] + bands[22][0]) / 4.0; + let bass_line = clamp(to_int(2.0 - (lo - mid) * 6.0 + 0.5), 0, 4); + let treble_line = clamp(to_int(2.0 - (hi - mid) * 6.0 + 0.5), 0, 4); + + this.txt(x, y, "BASS", p.cyan); + this.txt(x + w - 6, y, "TREBLE", p.cyan); + let gy = y + 1; + let gh = 4; // rows for +10 .. -10 + this.txt(x, gy, "+10", p.cyan_mid); + this.txt(x, gy + gh / 2, " 0", p.cyan_mid); + this.txt(x, gy + gh - 1, "-10", p.cyan_mid); + let gx = x + 4; + let gw = w - 4; + // three thin strokes per row: top "▔", middle "─", bottom "▁" + let levels = 3 * gh - 1; + let zero = levels / 2; + let ramp = gw * 3 / 10; + let lines = [[bass_line, 0, 1], [treble_line, gw - 1, -1]]; + for l in lines { + let start = l[0] * levels / 4; + for c in 0..ramp { + let t = to_float(c) / to_float(mx(ramp - 1, 1)); + let lv = to_int(to_float(start) + (to_float(zero) - to_float(start)) * t + 0.5); + let ch = switch lv % 3 { 0 => "▔", 1 => "─", _ => "▁" }; + this.txt(gx + l[1] + l[2] * c, gy + lv / 3, ch, p.cyan); + } + } + let flat = switch zero % 3 { 0 => "▔", 1 => "─", _ => "▁" }; + this.hl(gx + ramp, gy + zero / 3, gw - 2 * ramp, flat, p.cyan_mid); +} + +fn draw_balance(input, st, x, y, w) { + let p = st.pal; + let l = get(input, "level_l", 0.0); + let r = get(input, "level_r", 0.0); + let bal = if l + r > 0.01 { (r - l) / (l + r) } else { 0.0 }; + this.txt(x, y, "L", p.cyan); + this.txt(x + w - 1, y, "R", p.cyan); + let mid = x + w / 2; + this.txt(mid - 3, y, "BALANCE", p.cyan); + let d = x + 2; + while d < mid - 4 { this.txt(d, y, "·", p.cyan_mid); d += 2; } + d = mid + 5; + while d < x + w - 2 { this.txt(d, y, "·", p.cyan_mid); d += 2; } + // a bright centre mark, and the marker as two thin vertical segments + this.txt(mid, y + 1, "▎", p.cyan_mid); + let pos = clamp(mid + to_int(bal * to_float(w / 2 - 2) * 4.0), x + 2, x + w - 4); + this.txt(pos, y + 1, "▎", p.cyan_hot); + this.txt(pos + 1, y + 1, "▎", p.cyan_hot); +} + +// A framed box: "▁" above, "▔" below, "▎" sides on the left edges of the +// first column and of the column after the label, so the frame lines are all +// equally thin and every corner meets. Returns the column after its right +// side. 3 rows tall, the label on row y+1. +fn sbox(x, y, label, fg) { + let w = label.len() + 4; + this.hl(x, y, w, "▁", fg); + this.txt(x, y + 1, "▎", fg); + this.txt(x + 2, y + 1, label, fg); + this.txt(x + w, y + 1, "▎", fg); + this.hl(x, y + 2, w, "▔", fg); + x + w + 1 +} + +fn sbox_width(label) { label.len() + 5 } + +// What leaves the player, for the lower row of the signal path: the held +// output peak in dBFS after the volume stage (the analyzer measures before +// it; the player's gain is volume cubed, 60 * log10(volume) dB), refreshed +// four times a second like a hardware readout, +// and whether the two channels differ (STEREO) or carry the same signal +// (MONO), from the host's channel_mode. Stereo in the last second keeps +// STEREO, so a near-mono moment in a stereo track does not flip it. +fn update_output(st, input, hot, dt) { + if !("out_t" in st) { st.out_t = 0.0; st.out_db = -99; st.stereo_t = 0.0; st.chan = ""; } + st.out_t -= dt; + if st.out_t <= 0.0 { + st.out_t = 0.25; + let vol = input.volume; + // -99 means silent; a live level is clamped to the readout's -60 + st.out_db = if hot > 0.0 && vol > 0.0 { + mx(to_int(dbfs(input, hot) + 60.0 * ln(vol) / ln(10.0) - 0.5), -60) + } else { -99 }; + } + st.stereo_t -= dt; + let mode = get(input, "channel_mode", ""); + if mode == "stereo" { st.stereo_t = 1.0; } + if mode != "" { st.chan = if st.stereo_t > 0.0 { "STEREO" } else { "MONO" }; } + st +} + +// Labels of the lower row, from the volume stage to the output: sample rate, +// channels, output level. Short forms for narrow panels. +fn output_labels(input, st, short) { + let sr = get(input, "sample_rate", 0); + if sr <= 0 { sr = get(input, "audio_sample_rate", 0); } + let khz = if sr > 0 { "" + (sr / 1000) + "." + ((sr % 1000) / 100) } else { "--" }; + let chan = if "chan" in st && st.chan != "" { st.chan } else { "--" }; + let live = get(input, "playing", false) && "out_db" in st && st.out_db > -99; + let db = if live { "" + st.out_db } else { "--" }; + while db.len() < 3 { db = " " + db; } + if short { + [khz + "K", if chan == "STEREO" { "ST" } else if chan == "MONO" { "MO" } else { "--" }, db + "DB"] + } else { + [khz + " KHZ", chan, "OUT " + db + " DB"] + } +} + +// Signal path drawn as a schematic: boxes on a bus line that runs along their +// bottom edges, nodes between them, and a wire from the end of the upper row +// down to the lower row. Every box is a live value: source, format and +// volume above; sample rate, channels and output level below. The active path +// is lit; now and then a bright pulse travels along it to the output. +fn draw_schematic(input, st, x, y, w) { + let p = st.pal; + let playing = get(input, "playing", !input.paused && input.track_title != ""); + let lit = playing || st.boot > 0.0; + let on = if lit { p.cyan } else { p.cyan_mid }; + // lines and wires stay quiet; boxes and nodes carry the light + let bus = if lit { p.cyan_line } else { p.cyan_ghost }; + let fmt = get(input, "audio_format", "").to_upper(); + let vol = to_int(input.volume * 100.0 + 0.5); + let src = switch get(input, "source", "") { "federated" => "NETWORK", "podcast" => "PODCAST", _ => "LIBRARY" }; + let mid = if fmt == "" { "DECODE" } else { fmt }; + let vol_label = "VOL " + vol; + + // upper row: source, decoder, volume; the wire leaves at column xr + let top = [src, mid, vol_label]; + let tw = 0; + for l in top { tw += sbox_width(l); } + let xr = x + w - 2; + let gap = clamp((w - 2 - tw) / 2, 2, 12); + let bus_y = y + 2; + this.hl(x, bus_y, xr - x, "▔", bus); + let cx = x; + for k in 0..3 { + let fg = on; + // a new source goes dark for a moment, then lights with its value + if k == 0 && st.src_flash > 0.25 { fg = p.cyan_ghost; } + let next = this.sbox(cx, y, top[k], fg); + if k < 2 { this.txt(next + (gap - 1) / 2, bus_y, "▀", on); } + cx = next + gap - 1; + } + + // the wire down to the lower bus + let ty = y + 4; + let low_y = ty + 2; + this.vl(xr, bus_y, low_y - bus_y, "▎", bus); + + // lower row, right-aligned and read right to left: sample rate, channels, + // output level (red near full scale) + // the form follows the widest values, so live readings do not switch it + let widest = sbox_width("192.0 KHZ") + sbox_width("STEREO") + sbox_width("OUT -60 DB"); + let labels = output_labels(input, st, widest + 4 > xr - x); + let bw_ = 0; + for l in labels { bw_ += sbox_width(l); } + let bottom = [labels[2], labels[1], labels[0]]; + let hot_out = lit && "out_db" in st && st.out_db >= -1; + let gap2 = clamp((xr - x - bw_) / 3, 2, 12); + let start = xr - 1 - bw_ - 2 * (gap2 - 1); + this.hl(start, low_y, xr - start, "▔", bus); + let cx2 = start; + for k in 0..3 { + let next = this.sbox(cx2, ty, bottom[k], if k == 0 && hot_out { p.red } else { on }); + if k < 2 { this.txt(next + (gap2 - 1) / 2, low_y, "▀", on); } + cx2 = next + gap2 - 1; + } + + // the pulse: every 7 s it runs once along bus, wire and lower bus + if playing && st.boot <= 0.0 { + let phase = (input.time % 7.0) / 2.2; + if phase < 1.0 { + let n1 = xr - x; let n2 = low_y - bus_y; let n3 = xr - start; + let total = n1 + n2 + n3; + let at = to_int(phase * to_float(total)); + for tail in 0..3 { + let k = at - tail; + if k < 0 { continue; } + let fg = if tail == 0 { p.cyan_hot } else { p.cyan }; + if k < n1 { this.txt(x + k, bus_y, "▔", fg); } + else if k < n1 + n2 { this.txt(xr, bus_y + (k - n1), "▎", fg); } + else if k < total { this.txt(xr - 1 - (k - n1 - n2), low_y, "▔", fg); } + } + } + } + + let state = if !playing { if input.track_title == "" { "STANDBY" } else { "PAUSED" } } + else if vol == 0 { "MUTE" } else { "ACTIVE" }; + this.txt(x, y + 8, "SIGNAL PATH / " + state, p.cyan_mid); +} + +// The transport module: the word in 14-segment letters, then one row of +// captions and one row of equally tall digits under them, aligned to the +// module's edges: track number (with the queue length) on the left, the +// STEREO lamp in the middle, volume on the right. +fn draw_transport(input, st, x, y) { + let p = st.pal; + let word = if input.track_title == "" { "STOP" } else if input.paused { "PAUSE" } else { "PLAY" }; + let boot = st.boot > 0.0; + let off = if boot { p.cyan } else { p.cyan_seg }; + this.seg14_text(x, y, word, p.cyan, off); + let w = transport_width(); + let ly = y + 6; + let caption = whiten(p.cyan_mid, 0.25); + // the same detection as the signal path (see update_output) + let stereo = "chan" in st && st.chan == "STEREO" && get(input, "playing", false); + this.txt(x, ly, "TRACK", caption); + this.txt(x + 15, ly, "STEREO", if stereo || boot { p.cyan } else { p.cyan_lamp_off }); + this.txt(x + w - 7, ly, "VOLUME", caption); + let q = get(input, "queue_index", 0); + let qn = get(input, "queue_length", 0); + let qs = if q <= 0 || q > 99 { "--" } else { pad2(q) }; + let end = this.seg_text(x, ly + 1, qs, 5, 1, p.cyan, off, false); + this.txt(end + 1, ly + 3, "OF " + (if qn > 999 { "1K+" } else { "" + qn }), caption); + // volume digits end where the module ends, "%" on their baseline + let vs = "" + to_int(input.volume * 100.0 + 0.5); + let vx = x + w - 3 - (vs.len() * 6 - 1); + this.seg_text(vx, ly + 1, vs, 5, 1, p.cyan, off, false); + this.txt(x + w - 2, ly + 3, "%", caption); +} + +// "PAUSE" in the segment letters is the widest transport word. +fn transport_width() { 40 } + +// Static on the display for a moment after the track or source changes. +fn draw_noise(input, st) { + if st.noise <= 0.0 { return; } + let W = input.width; let H = input.height; + // capped so a huge terminal stays far below the operation limit + let count = mn(to_int(to_float(W * H) * 0.35 * clamp(st.noise / 0.35, 0.0, 1.0)), 6000); + let f = input.frame % 9973; + let pts = []; + for i in 0..count { + let a = (i * 7919 + f * 104729 + 13) % 1000003; + let b = (i * 15485863 % 999983 + f * 32452843 % 999979) % 1000033; + pts.push(a % (W * 2)); pts.push(b % (H * 4)); + } + this.dots(pts, st.pal.noise); +} + +// ---------- state ---------- + +fn advance_state(input) { + let st = input.state; + // a track is its title, queue slot and seed together, so two songs with + // the same title still count as a change + let key = input.track_title + "|" + get(input, "queue_index", 0) + "|" + input.seed; + if !("boot" in st) || !("key" in st) { + st = #{ boot: 0.9, spin: 0.0, over: 0.0, noise: 0.0, search: 0.0, src_flash: 0.0, + fade: 0.0, hold_i: 0, hold_v: 0.0, hold_t: 0.0, best_i: 0, + key: key, source: get(input, "source", ""), last_pos: input.position }; + } + if !("fade" in st) { st.fade = 0.0; st.src_flash = 0.0; st.hold_i = 0; st.hold_v = 0.0; st.hold_t = 0.0; st.best_i = 0; } + let dt = get(input, "dt", 0.05); + st.boot -= dt; st.spin -= dt; st.over -= dt; st.noise -= dt; st.search -= dt; st.src_flash -= dt; + // lit colours fade into unlit phosphor while paused (the standby clock + // stays lit) + let target = if input.paused && input.track_title != "" { 1.0 } else { 0.0 }; + st.fade = if target > st.fade { mn(st.fade + dt / 0.8, target) } else { mx(st.fade - dt / 0.3, target) }; + let source = get(input, "source", ""); + if st.key != key { + st.key = key; + if input.track_title != "" { st.spin = 0.6; } + st.noise = 0.35; + } else if input.track_title != "" { + let expected = st.last_pos + if input.paused { 0.0 } else { dt }; + if input.position < 1.0 && st.last_pos > 1.5 { + // the same track again (repeat one, "previous" restart) + st.spin = 0.6; + } else if abs(input.position - expected) > 1.5 { + // a jump that playback alone cannot explain is a seek + st.search = 0.8; + st.seek_dir = if input.position > expected { 1 } else { -1 }; + } + } + if st.source != source { st.source = source; st.noise = 0.35; st.src_flash = 0.5; } + st.last_pos = input.position; + let hot = mx(get(input, "peak_l", 0.0), get(input, "peak_r", 0.0)); + if dbfs(input, hot) > -0.5 && hot > 0.0 { st.over = 1.0; } + st = update_output(st, input, hot, dt); + // the panel brightens while the power-on test runs + st.pal = make_palette(input, if st.boot > 0.0 { 0.1 } else { 0.0 }, if st.boot > 0.0 { 0.0 } else { st.fade }); + st +} + +// Peak-frequency hold: the readout keeps the strongest band for a moment, and +// a new band takes over when it is at least as loud as the held one has +// decayed to. +fn update_hold(st, bands, dt) { + let best = 0; + for i in 1..bands.len() { if bands[i][0] > bands[best][0] { best = i; } } + st.best_i = best; + st.hold_t -= dt; + st.hold_v -= 0.35 * dt; + if bands[best][0] >= st.hold_v || st.hold_t <= 0.0 { + st.hold_i = best; + st.hold_v = bands[best][0]; + st.hold_t = 1.2; + } + st +} + +// ---------- layouts ---------- + +fn draw_top_band(input, st, bands, x0, y, cw) { + let lamps_w = 18; + this.draw_counter(input, st, x0, y, 6, 2); + let meter_x = x0 + counter_width() + 4; + let meter_w = x0 + cw - lamps_w - 4 - meter_x; + if METER_STYLE() == "needles" { + this.draw_needles(input, st, meter_x, y, meter_w); + } else { + this.draw_meter(input, st, meter_x, y, meter_w); + } + // the lamp block is not shared between modes: it relights with section 1 + this.draw_lamps(input, section(st, 1), bands, x0 + cw - lamps_w + 2, y); +} + +fn draw_title_rows(input, st, x0, y, cw) { + this.draw_status_row(input, st, x0, y, cw); + this.txt(x0, y + 2, "▸", st.pal.white_mid); + this.draw_matrix_title(input, st, x0 + 2, y + 2, cw - 2, title_label(input)); +} + +// FULL PANEL: meters, analyzer with its measuring module, tone, signal path +// and transport. +fn render_full(input, st, bands) { + let cmds = []; + let p = st.pal; + let W = input.width; + let H = input.height; + let cw = mn(W - 4, 170); + let x0 = (W - cw) / 2; + + // row 0 stays free for the optional clock + let top = if input.show_clock { 1 } else { 0 }; + let spec_h = clamp(H - top - 30, 8, 16); + // top band 7, status and title 4, analyzer spec_h + 2 labels, lower block 10 + let used = 7 + 4 + spec_h + 2 + 10; + let gap = clamp((H - top - used) / 3, 0, 2); + let y = clamp((H - used - gap * 3 - top) / 2 + top, top, 3); + + cmds.draw_top_band(input, st, bands, x0, y, cw); + y += 7 + gap; + cmds.draw_title_rows(input, section(st, 1), x0, y, cw); + + y += 4 + gap; + let module_w = 26; + let bw = clamp((cw - module_w - 8) / 25, 3, 5); + let right = cmds.draw_analyzer(input, section(st, 2), bands, x0, y, bw, spec_h); + let mx_ = right + mx((x0 + cw - right - module_w) / 2, 3); + cmds.draw_measure(input, section(st, 3), mx_, y + mx((spec_h + 2 - measure_height()) / 2, 0), mn(module_w, x0 + cw - mx_)); + + y += spec_h + 2 + gap; + cmds.draw_balance(input, section(st, 4), x0, y, 28); + cmds.draw_fans(input, section(st, 4), bands, x0, y + 3, 28); + let tr_w = transport_width(); + let sx = x0 + 32; + let sw = cw - 32 - tr_w - 4; + cmds.draw_schematic(input, section(st, 5), sx, y, sw); + cmds.draw_transport(input, section(st, 6), x0 + cw - tr_w, y); + + if input.show_clock { cmds.txt(W - input.clock.len() - 1, 0, input.clock, p.white_mid); } + cmds +} + +// One-line summary of transport and signal path for the compact modes. +fn draw_strip(input, st, x, y, w) { + let p = st.pal; + let word = if input.track_title == "" { "STOP" } else if input.paused { "PAUSE" } else { "PLAY" }; + let q = get(input, "queue_index", 0); + let qn = get(input, "queue_length", 0); + let vol = to_int(input.volume * 100.0 + 0.5); + let fmt = get(input, "audio_format", "").to_upper(); + let src = switch get(input, "source", "") { "federated" => "NETWORK", "podcast" => "PODCAST", _ => "LIBRARY" }; + let cx = x; + this.txt(cx, y, word, p.cyan); cx += word.len() + 3; + let ts = "TRACK " + (if q > 999 { "999+" } else { "" + q }) + "/" + (if qn > 999 { "999+" } else { "" + qn }); + this.txt(cx, y, ts, p.cyan_mid); cx += ts.len() + 3; + let vs = "VOL " + vol + "%"; + this.txt(cx, y, vs, p.cyan_mid); cx += vs.len() + 3; + let out = output_labels(input, st, true); + let path = src + " › " + (if fmt == "" { "DECODE" } else { fmt }) + " › " + out[0] + " › " + out[1] + " › OUT " + out[2]; + if cx + path.len() < x + w { this.txt(cx, y, path, p.cyan_mid); } +} + +// SPECTRUM FOCUS: the analyzer takes the height; the lower modules shrink to +// one line. +fn render_spectrum(input, st, bands) { + let cmds = []; + let p = st.pal; + let W = input.width; + let H = input.height; + let cw = mn(W - 4, 170); + let x0 = (W - cw) / 2; + let top = if input.show_clock { 1 } else { 0 }; + // the analyzer is tall but capped, and the panel is centred vertically + let spec_h = clamp(H - top - 17, 6, 18); + let y = top + mx((H - top - (13 + spec_h + 4)) / 2, 0); + cmds.draw_top_band(input, st, bands, x0, y, cw); + y += 8; + cmds.draw_title_rows(input, section(st, 1), x0, y, cw); + y += 5; + let module_w = 26; + let bw = clamp((cw - module_w - 8) / 25, 2, 5); + let right = cmds.draw_analyzer(input, section(st, 2), bands, x0, y, bw, spec_h); + let mx_ = right + mx((x0 + cw - right - module_w) / 2, 3); + if mx_ + module_w <= x0 + cw && spec_h + 2 >= measure_height() { + cmds.draw_measure(input, section(st, 3), mx_, y + (spec_h + 2 - measure_height()) / 2, module_w); + } + cmds.draw_strip(input, section(st, 4), x0, y + spec_h + 3, cw); + if input.show_clock { cmds.txt(W - input.clock.len() - 1, 0, input.clock, p.white_mid); } + cmds +} + +// TAPE DECK: a large counter, the tape counter and wide L/R meters, with a +// small analyzer underneath. +fn render_tape(input, st, bands) { + let cmds = []; + let p = st.pal; + let W = input.width; + let H = input.height; + let cw = mn(W - 4, 170); + let x0 = (W - cw) / 2; + let cw0 = mn(W - 4, 170); + // big digits only where the widest counter, track and tape counter still + // end before the lamps + let big = H >= 36 && cw0 >= 116; + let rh = if big { 4 } else { 2 }; + let dw = if big { 9 } else { 6 }; + // centre the whole deck vertically + let spec_h = clamp(H - (2 * rh + 4) - 6 - 5 - 6, 3, 10); + let content = (2 * rh + 4) + 6 + 5 + spec_h + 4; + let y = clamp((H - content) / 2, if input.show_clock { 1 } else { 0 }, 6); + cmds.draw_counter(input, st, x0, y, dw, rh); + // tape counter in segment digits at a fixed place after the widest + // counter ("88.88" and a two-digit track), and the lamps on the right + let cx = x0 + (6 * dw + 11) + 6; + let off = if st.boot > 0.0 { p.white } else { p.white_seg }; + // during a seek the counter races like a deck winding the tape + let counter = if st.boot > 0.0 { "8888" } + else if st.search > 0.0 { pad4((tape_counter(input.position) + input.frame * 37) % 10000) } + else { pad4(tape_counter(input.position)) }; + // the tape counter belongs to the deck section and relights with it + let tp = section(st, 1).pal; + cmds.seg_text(cx, y, counter, 6, 2, tp.white, off, false); + cmds.txt(cx, y + 6, "TAPE COUNTER", tp.white_mid); + let lamps_x = x0 + cw - 16; + cmds.draw_lamps(input, section(st, 1), bands, lamps_x, y); + if DECK_LAMPS() && lamps_x - (cx + 28) >= 18 { + cmds.draw_deck_lamps(input, section(st, 1), cx + 31, y); + } + y += 2 * rh + 4; + if METER_STYLE() == "needles" { cmds.draw_needles(input, st, x0, y, cw); } else { cmds.draw_meter(input, st, x0, y, cw); } + y += 6; + cmds.draw_title_rows(input, section(st, 2), x0, y, cw); + y += 5; + let bw = clamp((cw - 4) / 25, 2, 6); + cmds.draw_analyzer(input, section(st, 3), bands, x0, y, bw, spec_h); + if y + spec_h + 3 < H { cmds.draw_strip(input, section(st, 4), x0, y + spec_h + 3, cw); } + if input.show_clock { cmds.txt(W - input.clock.len() - 1, 0, input.clock, p.white_mid); } + cmds +} + +// Cassette deck lamps: AMS lights while the counter searches on a track +// change, NR [B] while playing (decorative), AUTO REVERSE with repeat all, +// and REW / FF in the direction of a seek. +fn draw_deck_lamps(input, st, x, y) { + let p = st.pal; + let boot = st.boot > 0.0; + let playing = get(input, "playing", false); + let blink = to_int(input.time * 6.0) % 2 == 0; + this.lamp(x, y, "AMS", boot || (st.spin > 0.0 && blink), p.white, p.lamp_off); + let nx = this.lamp(x + 6, y, "NR", boot || playing, p.white, p.lamp_off); + this.txt(nx - 2, y, "[B]", if boot || playing { p.white } else { p.lamp_off }); + this.lamp(x, y + 2, "AUTO REVERSE", boot || get(input, "repeat", "off") == "all", p.white, p.lamp_off); + let dir = if "seek_dir" in st { st.seek_dir } else { 0 }; + let seeking = st.search > 0.0; + this.lamp(x, y + 4, "<< REW", boot || (seeking && dir < 0), p.white, p.lamp_off); + this.lamp(x + 9, y + 4, "FF >>", boot || (seeking && dir > 0), p.white, p.lamp_off); +} + +// MINIMAL: time, the L/R meter, the title and a tall analyzer with its +// measuring module; no lamps, tone, signal path or transport. +fn render_minimal(input, st, bands) { + let cmds = []; + let p = st.pal; + let W = input.width; + let H = input.height; + // a narrower composition keeps its balance on wide screens + let cw = mn(W - 4, 132); + let x0 = (W - cw) / 2; + let top = if input.show_clock { 1 } else { 0 }; + // the analyzer is capped, so a tall window centres the panel instead + let spec_h = clamp(H - top - 14, 6, 22); + let y = top + mx((H - top - (13 + spec_h)) / 2, 0); + cmds.draw_counter(input, st, x0, y, 6, 2); + let meter_x = x0 + counter_width() + 4; + let meter_w = x0 + cw - meter_x; + if METER_STYLE() == "needles" { + cmds.draw_needles(input, st, meter_x, y, meter_w); + } else { + cmds.draw_meter(input, st, meter_x, y, meter_w); + } + y += 8; + let ts = section(st, 1); + cmds.txt(x0, y, "▸", ts.pal.white_mid); + cmds.draw_matrix_title(input, ts, x0 + 2, y, cw - 2, title_label(input)); + y += 3; + let module_w = 26; + let bw = clamp((cw - module_w - 8) / 25, 2, 5); + let right = cmds.draw_analyzer(input, section(st, 2), bands, x0, y, bw, spec_h); + let mx_ = right + mx((x0 + cw - right - module_w) / 2, 3); + if mx_ + module_w <= x0 + cw && spec_h + 2 >= measure_height() { + cmds.draw_measure(input, section(st, 3), mx_, y + (spec_h + 2 - measure_height()) / 2, module_w); + } + if input.show_clock { cmds.txt(W - input.clock.len() - 1, 0, input.clock, p.white_mid); } + cmds +} + +fn render_compact(input, st, bands) { + let cmds = []; + let p = st.pal; + let W = input.width; + let H = input.height; + let top = 0; + let clock_w = if input.show_clock { input.clock.len() + 2 } else { 0 }; + if H >= 18 { + let end = cmds.draw_counter(input, st, 1, 0, 6, 2); + cmds.draw_matrix_title(input, st, end + 3, 2, W - end - 4, title_label(input)); + top = 8; + if input.show_clock { + // top right when the counter leaves room, else the free row + // above the analyzer + let cy = if end + clock_w <= W - 1 { 0 } else { 7 }; + cmds.txt(W - input.clock.len() - 1, cy, input.clock, p.white_mid); + } + } else { + cmds.draw_matrix_title(input, st, 1, 0, W - 2 - clock_w, title_label(input)); + top = 3; + if input.show_clock { cmds.txt(W - input.clock.len() - 1, 0, input.clock, p.white_mid); } + } + let spec_h = mn(H - top - 2, 14); + let bw = clamp((W - 4) / 25, 2, 5); + if spec_h >= 3 { cmds.draw_analyzer(input, st, bands, 0, top, bw, spec_h); } + cmds +} + +// Nothing loaded: a large clock with a blinking colon; at the top of every +// minute a brightness sweep runs across the digits. +fn render_standby(input, st) { + let cmds = []; + let p = st.pal; + let W = input.width; + let H = input.height; + let h = get(input, "clock_hour", 0); + let m = get(input, "clock_minute", 0); + let s = get(input, "clock_second", 0); + if W < 42 || H < 10 { return render_compact(input, st, panel_bands(input, -8.0)); } + let big = W >= 70 && H >= 20; + let cw = if big { 9 } else { 6 }; + let rh = if big { 4 } else { 2 }; + let digits = pad2(h) + pad2(m); + let width = 4 * (cw + 1) + 3; + let x = mx((W - width - 10) / 2, 0); + let y = mx((H - (2 * rh + 1) - 6) / 2, 0); + let ms = get(input, "clock_millis", 0); + let sweep = if s < 2 { (to_float(s) + to_float(ms) / 1000.0) * 3.0 - 0.5 } else { -10.0 }; + let cx = x; + for i in 0..4 { + if i == 2 { + let colon = if s % 2 == 0 { p.white } else { p.white_ghost }; + cmds.colon(cx, y, rh, colon); + cx += 3; + } + let boost = clamp(1.0 - abs(to_float(i) - sweep), 0.0, 1.0); + let on = whiten(p.white, 0.55 * boost); + cmds.seg_text(cx, y, digits.sub_string(i, 1), cw, rh, on, p.white_seg, false); + cx += cw + 1; + } + cmds.seg_text(cx + 1, y + 2 * rh - 2, pad2(s), if big { 5 } else { 4 }, 1, p.white_mid, p.white_seg, false); + let ly = y + 2 * rh + 2; + cmds.txt(x, ly, "STANDBY", p.red); + cmds.txt(x + 10, ly, if night(input) { "DIMMER" } else { "" }, p.white_mid); + if W >= 40 { + cmds.draw_matrix_title(input, st, x, ly + 2, mn(W - x - 2, width + 10), "FURUMI · NO DISC"); + } + cmds +} + +// The colon of the standby clock: two small squares between the hour and +// minute digits. +fn colon(x, y, rh, fg) { + this.txt(x + 1, y + rh - 1, "▪", fg); + this.txt(x + 1, y + rh + 1, "▪", fg); +} + +// Mode switch like a hardware display: section 0 (time, L/R meters) stays +// lit; the other sections are dark for a moment, then light up one after +// another with a brief overshoot as each comes on. +fn section(st, k) { + if k == 0 || !("mode_t" in st) { return st; } + let t = st.mode_t; + let on_at = 0.12 + to_float(k) * 0.11; + if t >= on_at + 0.08 { return st; } + let s2 = st; + let p = st.pal; + let keys = ["white", "white_mid", "amber", "amber_low", "amber_hot", "peak", "amber_text", + "amber_warm", "amber_light", "red", "red_mid", "cyan", "cyan_mid", "cyan_hot", "cyan_line"]; + if t < on_at { + let ghost = #{ white: p.white_ghost, white_mid: p.white_ghost, amber: p.amber_ghost, + amber_low: p.amber_ghost, amber_hot: p.amber_ghost, peak: p.amber_ghost, + amber_text: p.amber_ghost, amber_warm: p.amber_ghost, amber_light: p.amber_ghost, + red: p.red_ghost, red_mid: p.red_ghost, cyan: p.cyan_ghost, cyan_mid: p.cyan_ghost, + cyan_hot: p.cyan_ghost, cyan_line: p.cyan_ghost }; + for key in keys { p[key] = ghost[key]; } + // unlit lamps and rules go down with them, so nothing reads as lit + p.lamp_off = p.white_ghost; + p.red_lamp_off = p.red_ghost; + p.amber_lamp_off = p.amber_ghost; + p.cyan_lamp_off = p.cyan_ghost; + p.amber_rule = p.amber_ghost; + } else { + for key in keys { p[key] = whiten(p[key], 0.35); } + } + s2.pal = p; + s2 +} + +// Smallest screens for each composition (full needs a row more with the +// clock). +fn full_height(input) { if input.show_clock { 35 } else { 34 } } + +fn mode_fits(mode, input) { + let W = input.width; let H = input.height; + switch mode { + "full" => W >= 120 && H >= full_height(input), + "spectrum" => W >= 100 && H >= 26, + "minimal" => W >= 80 && H >= 20, + "deck" => W >= 100 && H >= 30, + _ => true + } +} + +fn mode_names() { ["full", "spectrum", "minimal", "deck"] } + +// The display mode: Shift+M picks it unless DISPLAY_MODE() pins one; a mode +// that does not fit the window steps down. Earlier names still work. +fn pick_mode(input) { + let mode = DISPLAY_MODE(); + mode = switch mode { "classic" => "full", "focus" => "spectrum", "tape" => "deck", _ => mode }; + if mode == "auto" { + let names = mode_names(); + mode = names[get(input, "mode", 0) % names.len()]; + } + if mode == "deck" && !mode_fits("deck", input) { mode = "spectrum"; } + if mode == "full" && !mode_fits("full", input) { mode = "spectrum"; } + if mode == "spectrum" && !mode_fits("spectrum", input) { mode = "minimal"; } + if mode == "minimal" && !mode_fits("minimal", input) { mode = "compact"; } + mode +} + +// Bar inertia: a column follows a rise at once, but when the energy drops it +// starts falling slowly and gathers speed, like a real display settling. The +// peak marks have their own physics: a hold, then a fall that accelerates. +fn update_inertia(st, bands, dt) { + let n = bands.len(); + let bars = if "bars" in st { st.bars } else { [] }; + let vel = if "vel" in st { st.vel } else { [] }; + if bars.len() != n { bars = []; vel = []; for i in 0..n { bars.push(0.0); vel.push(0.0); } } + // peak marks: held for a moment, then they start falling slowly and + // speed up, like a light object under gravity + let caps = if "caps" in st { st.caps } else { [] }; + let cap_vel = if "cap_vel" in st { st.cap_vel } else { [] }; + let cap_hold = if "cap_hold" in st { st.cap_hold } else { [] }; + if caps.len() != n { + caps = []; cap_vel = []; cap_hold = []; + for i in 0..n { caps.push(0.0); cap_vel.push(0.0); cap_hold.push(0.0); } + } + let out = []; + for i in 0..n { + let v = bands[i][0]; + if v >= bars[i] { + bars[i] = v; vel[i] = 0.0; + } else { + vel[i] = vel[i] + 2.4 * dt; + bars[i] = mx(v, bars[i] - vel[i] * dt); + } + if bars[i] >= caps[i] { + caps[i] = bars[i]; cap_vel[i] = 0.0; cap_hold[i] = 0.9; + } else if cap_hold[i] > 0.0 { + cap_hold[i] = cap_hold[i] - dt; + } else { + cap_vel[i] = cap_vel[i] + 1.6 * dt; + caps[i] = mx(bars[i], caps[i] - cap_vel[i] * dt); + } + out.push([bars[i], caps[i]]); + } + st.bars = bars; st.vel = vel; + st.caps = caps; st.cap_vel = cap_vel; st.cap_hold = cap_hold; + st.shown = out; + st +} + +// For two seconds after Shift+M, a row of mode lamps along the bottom edge. +fn draw_mode_lamps(input, st, mode) { + let p = st.pal; + let names = ["FULL", "SPECTRUM", "MINIMAL", "DECK"]; + let keys = mode_names(); + let total = 9; + for n in names { total += n.len() + 3; } + let x = mx((input.width - total) / 2, 0); + let y = input.height - 2; + this.fill(x - 1, y, total + 2, 2, " ", 0); + this.txt(x, y, "DISPLAY", p.white_mid); + let cx = x + 9; + for k in 0..names.len() { + cx = this.lamp(cx, y, names[k], keys[k] == mode, p.white, p.lamp_off); + } +} + +fn render(input) { + let st = advance_state(input); + let dt = get(input, "dt", 0.05); + st = update_range(st, input, dt); + let raw = panel_bands(input, st.top_db); + st = update_hold(st, raw, dt); + st = update_inertia(st, raw, dt); + let bands = st.shown; + // the mode lamps light up for a moment on every Shift+M; the sections + // switch over (mode_t, see section) only when the layout really changes, + // not for a pinned DISPLAY_MODE() or a fallback to the same layout + let mode = pick_mode(input); + let mode_in = get(input, "mode", 0); + if !("mode_seen" in st) { st.mode_seen = mode_in; st.mode_flash = 0.0; st.mode_shown = mode; } + st.mode_flash -= dt; + if "mode_t" in st { + st.mode_t += dt; + if st.mode_t > 1.5 { st.remove("mode_t"); } + } + if st.mode_seen != mode_in { + st.mode_seen = mode_in; + st.mode_flash = 2.0; + if st.mode_shown != mode { st.mode_t = 0.0; } + } + st.mode_shown = mode; + let cmds = [#{ op: "clear", bg: 0 }]; + let W = input.width; let H = input.height; + if W >= 20 && H >= 6 { + cmds.draw_noise(input, st); + let body = if input.track_title == "" && st.boot <= 0.0 { + render_standby(input, st) + } else { + switch mode { + "full" => render_full(input, st, bands), + "spectrum" => render_spectrum(input, st, bands), + "minimal" => render_minimal(input, st, bands), + "deck" => render_tape(input, st, bands), + _ => render_compact(input, st, bands) + } + }; + for c in body { cmds.push(c); } + if st.mode_flash > 0.0 && mode != "compact" && W >= 60 && H >= 8 { cmds.draw_mode_lamps(input, st, mode); } + } + #{ commands: cmds, state: st } +} + +// ---------- dot-matrix font ---------- + +// 5x7 dot-matrix glyphs, one int per row with bit 4 as the leftmost dot. +// Latin, digits, common punctuation and Cyrillic; anything else is a box. +fn dm_glyph(c) { + switch c { + 'A' => [14, 17, 17, 31, 17, 17, 17], + 'B' => [30, 17, 17, 30, 17, 17, 30], + 'C' => [14, 17, 16, 16, 16, 17, 14], + 'D' => [30, 17, 17, 17, 17, 17, 30], + 'E' => [31, 16, 16, 30, 16, 16, 31], + 'F' => [31, 16, 16, 30, 16, 16, 16], + 'G' => [14, 17, 16, 23, 17, 17, 15], + 'H' => [17, 17, 17, 31, 17, 17, 17], + 'I' => [14, 4, 4, 4, 4, 4, 14], + 'J' => [7, 2, 2, 2, 2, 18, 12], + 'K' => [17, 18, 20, 24, 20, 18, 17], + 'L' => [16, 16, 16, 16, 16, 16, 31], + 'M' => [17, 27, 21, 21, 17, 17, 17], + 'N' => [17, 17, 25, 21, 19, 17, 17], + 'O' => [14, 17, 17, 17, 17, 17, 14], + 'P' => [30, 17, 17, 30, 16, 16, 16], + 'Q' => [14, 17, 17, 17, 21, 18, 13], + 'R' => [30, 17, 17, 30, 20, 18, 17], + 'S' => [15, 16, 16, 14, 1, 1, 30], + 'T' => [31, 4, 4, 4, 4, 4, 4], + 'U' => [17, 17, 17, 17, 17, 17, 14], + 'V' => [17, 17, 17, 17, 17, 10, 4], + 'W' => [17, 17, 17, 21, 21, 21, 10], + 'X' => [17, 17, 10, 4, 10, 17, 17], + 'Y' => [17, 17, 10, 4, 4, 4, 4], + 'Z' => [31, 1, 2, 4, 8, 16, 31], + '0' => [14, 17, 19, 21, 25, 17, 14], + '1' => [4, 12, 4, 4, 4, 4, 14], + '2' => [14, 17, 1, 2, 4, 8, 31], + '3' => [31, 2, 4, 2, 1, 17, 14], + '4' => [2, 6, 10, 18, 31, 2, 2], + '5' => [31, 16, 30, 1, 1, 17, 14], + '6' => [6, 8, 16, 30, 17, 17, 14], + '7' => [31, 1, 2, 4, 8, 8, 8], + '8' => [14, 17, 17, 14, 17, 17, 14], + '9' => [14, 17, 17, 15, 1, 2, 12], + ' ' => [0, 0, 0, 0, 0, 0, 0], + '.' => [0, 0, 0, 0, 0, 12, 12], + ',' => [0, 0, 0, 0, 12, 4, 8], + ':' => [0, 12, 12, 0, 12, 12, 0], + ';' => [0, 12, 12, 0, 12, 4, 8], + '-' => [0, 0, 0, 31, 0, 0, 0], + '—' => [0, 0, 0, 31, 0, 0, 0], + '–' => [0, 0, 0, 31, 0, 0, 0], + '\'' => [12, 4, 8, 0, 0, 0, 0], + '’' => [12, 4, 8, 0, 0, 0, 0], + '`' => [12, 4, 8, 0, 0, 0, 0], + '"' => [10, 10, 10, 0, 0, 0, 0], + '«' => [10, 10, 10, 0, 0, 0, 0], + '»' => [10, 10, 10, 0, 0, 0, 0], + '“' => [10, 10, 10, 0, 0, 0, 0], + '”' => [10, 10, 10, 0, 0, 0, 0], + '!' => [4, 4, 4, 4, 4, 0, 4], + '?' => [14, 17, 1, 2, 4, 0, 4], + '&' => [12, 18, 20, 8, 21, 18, 13], + '/' => [0, 1, 2, 4, 8, 16, 0], + '(' => [2, 4, 8, 8, 8, 4, 2], + ')' => [8, 4, 2, 2, 2, 4, 8], + '[' => [14, 8, 8, 8, 8, 8, 14], + ']' => [14, 2, 2, 2, 2, 2, 14], + '+' => [0, 4, 4, 31, 4, 4, 0], + '#' => [10, 10, 31, 10, 31, 10, 10], + '*' => [0, 4, 21, 14, 21, 4, 0], + '_' => [0, 0, 0, 0, 0, 0, 31], + '·' => [0, 0, 0, 4, 0, 0, 0], + '•' => [0, 0, 0, 4, 0, 0, 0], + '…' => [0, 0, 0, 0, 0, 0, 21], + '%' => [24, 25, 2, 4, 8, 19, 3], + '=' => [0, 0, 31, 0, 31, 0, 0], + '@' => [14, 17, 1, 13, 21, 21, 14], + '$' => [4, 15, 20, 14, 5, 30, 4], + 'А' => [14, 17, 17, 31, 17, 17, 17], + 'В' => [30, 17, 17, 30, 17, 17, 30], + 'Е' => [31, 16, 16, 30, 16, 16, 31], + 'К' => [17, 18, 20, 24, 20, 18, 17], + 'М' => [17, 27, 21, 21, 17, 17, 17], + 'Н' => [17, 17, 17, 31, 17, 17, 17], + 'О' => [14, 17, 17, 17, 17, 17, 14], + 'Р' => [30, 17, 17, 30, 16, 16, 16], + 'С' => [14, 17, 16, 16, 16, 17, 14], + 'Т' => [31, 4, 4, 4, 4, 4, 4], + 'Х' => [17, 17, 10, 4, 10, 17, 17], + 'З' => [31, 2, 4, 2, 1, 17, 14], + 'Ё' => [10, 0, 31, 16, 30, 16, 31], + 'Б' => [31, 16, 16, 30, 17, 17, 30], + 'Г' => [31, 16, 16, 16, 16, 16, 16], + 'Д' => [6, 10, 10, 10, 10, 31, 17], + 'Ж' => [21, 21, 14, 4, 14, 21, 21], + 'И' => [17, 17, 19, 21, 25, 17, 17], + 'Й' => [10, 4, 17, 19, 21, 25, 17], + 'Л' => [7, 9, 9, 9, 9, 9, 17], + 'П' => [31, 17, 17, 17, 17, 17, 17], + 'У' => [17, 17, 17, 15, 1, 17, 14], + 'Ф' => [4, 14, 21, 21, 21, 14, 4], + 'Ц' => [18, 18, 18, 18, 18, 31, 1], + 'Ч' => [17, 17, 17, 15, 1, 1, 1], + 'Ш' => [21, 21, 21, 21, 21, 21, 31], + 'Щ' => [21, 21, 21, 21, 21, 31, 1], + 'Ъ' => [24, 8, 8, 14, 9, 9, 14], + 'Ы' => [17, 17, 17, 25, 21, 21, 25], + 'Ь' => [16, 16, 16, 30, 17, 17, 30], + 'Э' => [14, 17, 1, 7, 1, 17, 14], + 'Ю' => [18, 21, 21, 29, 21, 21, 18], + 'Я' => [15, 17, 17, 15, 5, 9, 17], + 'І' => [14, 4, 4, 4, 4, 4, 14], + 'Ї' => [10, 0, 14, 4, 4, 4, 14], + 'Є' => [14, 17, 16, 30, 16, 17, 14], + 'Ґ' => [1, 31, 16, 16, 16, 16, 16], + 'Ў' => [10, 4, 17, 15, 1, 17, 14], + 'À' => [14, 17, 17, 31, 17, 17, 17], + 'Á' => [14, 17, 17, 31, 17, 17, 17], + 'Â' => [14, 17, 17, 31, 17, 17, 17], + 'Ä' => [14, 17, 17, 31, 17, 17, 17], + 'Ã' => [14, 17, 17, 31, 17, 17, 17], + 'Å' => [14, 17, 17, 31, 17, 17, 17], + 'Ç' => [14, 17, 16, 16, 16, 17, 14], + 'È' => [31, 16, 16, 30, 16, 16, 31], + 'É' => [31, 16, 16, 30, 16, 16, 31], + 'Ê' => [31, 16, 16, 30, 16, 16, 31], + 'Ë' => [31, 16, 16, 30, 16, 16, 31], + 'Ì' => [14, 4, 4, 4, 4, 4, 14], + 'Í' => [14, 4, 4, 4, 4, 4, 14], + 'Î' => [14, 4, 4, 4, 4, 4, 14], + 'Ï' => [14, 4, 4, 4, 4, 4, 14], + 'Ñ' => [17, 17, 25, 21, 19, 17, 17], + 'Ò' => [14, 17, 17, 17, 17, 17, 14], + 'Ó' => [14, 17, 17, 17, 17, 17, 14], + 'Ô' => [14, 17, 17, 17, 17, 17, 14], + 'Ö' => [14, 17, 17, 17, 17, 17, 14], + 'Õ' => [14, 17, 17, 17, 17, 17, 14], + 'Ø' => [14, 17, 17, 17, 17, 17, 14], + 'Ù' => [17, 17, 17, 17, 17, 17, 14], + 'Ú' => [17, 17, 17, 17, 17, 17, 14], + 'Û' => [17, 17, 17, 17, 17, 17, 14], + 'Ü' => [17, 17, 17, 17, 17, 17, 14], + 'Ý' => [17, 17, 10, 4, 4, 4, 4], + 'Ÿ' => [17, 17, 10, 4, 4, 4, 4], + 'Œ' => [14, 17, 17, 17, 17, 17, 14], + 'Æ' => [14, 17, 17, 31, 17, 17, 17], + 'ß' => [15, 16, 16, 14, 1, 1, 30], + _ => [31, 17, 17, 17, 17, 17, 31] + } +} diff --git a/src/visualizer.rs b/src/visualizer.rs index ef0fefa..adc569b 100644 --- a/src/visualizer.rs +++ b/src/visualizer.rs @@ -15,7 +15,7 @@ use ratatui::buffer::Buffer; pub mod status; use ratatui::layout::Rect; -use ratatui::style::{Color, Style}; +use ratatui::style::{Color, Modifier, Style}; use ratatui::widgets::{Clear, Paragraph}; use rhai::{AST, Array, Dynamic, Engine, FLOAT, INT, Map, Scope}; use serde::{Deserialize, Serialize}; @@ -54,6 +54,13 @@ const BUNDLED_SCRIPTS: &[BundledScript] = &[ version: 6, source: include_str!("visualizations/morphing_cube.rhai"), }, + BundledScript { + id: "vfd_panel", + file_name: "vfd_panel.rhai", + display_name: "VFD panel", + version: 8, + source: include_str!("visualizations/vfd_panel.rhai"), + }, ]; #[derive(Debug, Clone)] @@ -69,6 +76,10 @@ pub struct VisualizerConfig { pub selected: String, #[serde(default)] pub show_clock: bool, + /// Display mode the script interprets (`input.mode`), cycled with + /// `CycleVisualizerMode` while the visualizer is open. + #[serde(default)] + pub mode: u32, } impl Default for VisualizerConfig { @@ -76,6 +87,7 @@ impl Default for VisualizerConfig { Self { selected: default_script_id(), show_clock: false, + mode: 0, } } } @@ -118,6 +130,12 @@ impl VisualizerState { pub fn open(&mut self) { self.active = true; self.started_at = Some(Instant::now()); + // Every opening is a new session for the script: empty state, frame + // 0 and dt 0, just as `time` restarts. + self.runtime + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .reset_session(); } pub fn close(&mut self) { @@ -179,6 +197,13 @@ impl VisualizerState { self.save_config() } + /// Moves to the next display mode; scripts take it modulo their own + /// number of modes. + pub fn cycle_mode(&mut self) -> Result<()> { + self.config.mode = self.config.mode.wrapping_add(1); + self.save_config() + } + pub fn toggle_clock(&mut self) -> Result<()> { self.config.show_clock = !self.config.show_clock; self.save_config() @@ -335,7 +360,16 @@ fn input_map_with_features(area: Rect, state: &AppState, features: AudioFeatures "show_clock".into(), state.visualizer.config.show_clock.into(), ); - input.insert("clock".into(), clock_label().into()); + let (hour, minute, second, millis) = clock_now(); + input.insert( + "clock".into(), + format!("{hour:02}:{minute:02}:{second:02}").into(), + ); + insert_int(&mut input, "clock_hour", i64::from(hour)); + insert_int(&mut input, "clock_minute", i64::from(minute)); + insert_int(&mut input, "clock_second", i64::from(second)); + insert_int(&mut input, "clock_millis", i64::from(millis)); + insert_int(&mut input, "mode", i64::from(state.visualizer.config.mode)); let (title, artist) = state .player .current @@ -344,9 +378,143 @@ fn input_map_with_features(area: Rect, state: &AppState, features: AudioFeatures .unwrap_or_else(|| ("".to_string(), "".to_string())); input.insert("track_title".into(), title.into()); input.insert("track_artist".into(), artist.into()); + insert_meter(&mut input, &state.player.audio_analysis); + insert_track_details(&mut input, state); input } +/// Analyzer meter fields (protocol v3). They report the decoded signal as a +/// level meter would, so unlike `energy`/`bass`/... they are not scaled by +/// the output volume; while paused or stopped they fall on their own. +fn insert_meter(input: &mut Map, analysis: &crate::player::AudioAnalysisSnapshot) { + let floats = |values: &[f64]| -> Dynamic { + values + .iter() + .map(|value| Dynamic::from_float(*value as FLOAT)) + .collect::() + .into() + }; + let bands = crate::player::BAND_CENTERS_HZ.len(); + let spectrum = if analysis.spectrum.len() == bands { + analysis.spectrum.clone() + } else { + vec![0.0; bands] + }; + let peaks = if analysis.spectrum_peaks.len() == bands { + analysis.spectrum_peaks.clone() + } else { + vec![0.0; bands] + }; + input.insert("spectrum".into(), floats(&spectrum)); + input.insert("spectrum_peaks".into(), floats(&peaks)); + input.insert( + "spectrum_hz".into(), + floats( + &crate::player::BAND_CENTERS_HZ + .iter() + .map(|hz| f64::from(*hz)) + .collect::>(), + ), + ); + insert_float( + input, + "spectrum_floor_db", + f64::from(crate::player::FLOOR_DB), + ); + insert_float(input, "level_l", analysis.level_l); + insert_float(input, "level_r", analysis.level_r); + insert_float(input, "peak_l", analysis.peak_l); + insert_float(input, "peak_r", analysis.peak_r); + insert_float(input, "level_side", analysis.level_side); + let channel_mode = match analysis.stereo { + Some(true) => "stereo", + Some(false) => "mono", + None => "", + }; + input.insert("channel_mode".into(), channel_mode.into()); + insert_int(input, "sample_rate", i64::from(analysis.sample_rate)); +} + +/// Track, queue and transport details for front-panel style displays. +/// Unknown numbers are 0 and unknown strings empty. +fn insert_track_details(input: &mut Map, state: &AppState) { + let player = &state.player; + let track = player.current.as_ref(); + let number = |value: Option| i64::from(value.unwrap_or(0).max(0)); + insert_float( + input, + "duration", + track.map_or(0.0, |track| track.duration_seconds.max(0.0)), + ); + insert_int( + input, + "track_number", + number(track.and_then(|t| t.track_number)), + ); + insert_int( + input, + "disc_number", + number(track.and_then(|t| t.disc_number)), + ); + insert_int(input, "year", number(track.and_then(|t| t.release_year))); + input.insert( + "release_title".into(), + track + .map_or_else(String::new, |t| t.release_title.clone()) + .into(), + ); + input.insert( + "audio_format".into(), + track + .and_then(|t| t.audio_format.clone()) + .unwrap_or_default() + .into(), + ); + insert_int( + input, + "audio_bitrate", + number(track.and_then(|t| t.audio_bitrate)), + ); + insert_int( + input, + "audio_sample_rate", + number(track.and_then(|t| t.audio_sample_rate)), + ); + insert_int( + input, + "audio_bit_depth", + number(track.and_then(|t| t.audio_bit_depth)), + ); + let source = match track { + None => "", + Some(track) if track.is_podcast() => "podcast", + Some(track) if track.fed.is_some() => "federated", + Some(_) => "local", + }; + input.insert("source".into(), source.into()); + input.insert( + "playing".into(), + (player.playing && track.is_some() && !player.paused).into(), + ); + let (index, length) = if track.is_some() && !player.queue.is_empty() { + ( + i64::try_from(player.queue_pos + 1).unwrap_or(i64::MAX), + i64::try_from(player.queue.len()).unwrap_or(i64::MAX), + ) + } else { + (0, i64::try_from(player.queue.len()).unwrap_or(i64::MAX)) + }; + insert_int(input, "queue_index", index); + insert_int(input, "queue_length", length); + input.insert("shuffle".into(), player.shuffle.into()); + let repeat = match player.repeat { + crate::app::state::RepeatMode::Off => "off", + crate::app::state::RepeatMode::One => "one", + crate::app::state::RepeatMode::All => "all", + }; + input.insert("repeat".into(), repeat.into()); +} + fn features_from_state(state: &AppState, scale_output: bool) -> AudioFeatures { let elapsed_secs = state .visualizer @@ -432,8 +600,18 @@ struct ScriptRuntime { cached_path: Option, cached_modified: Option, ast: Option, + /// Value the script returned as `state`, handed back as `input.state` on + /// the next frame. Reset whenever the script is (re)loaded and whenever + /// the visualizer opens. + script_state: Dynamic, + last_render: Option, + frame: u64, } +/// Longest `input.dt` a script sees, so a long pause does not make one frame +/// jump a whole animation. +const MAX_FRAME_DT_SECS: f64 = 1.0; + impl Default for ScriptRuntime { fn default() -> Self { let mut engine = Engine::new(); @@ -464,21 +642,66 @@ impl Default for ScriptRuntime { cached_path: None, cached_modified: None, ast: None, + script_state: Dynamic::UNIT, + last_render: None, + frame: 0, } } } impl ScriptRuntime { - fn render(&mut self, path: &Path, input: Map) -> std::result::Result, String> { + /// Runs the script's `render(input)`. A script returns either an array of + /// draw commands, or `#{ commands: [...], state: ... }` to keep `state` + /// for the next frame (`input.state`, an empty map at first). + fn render( + &mut self, + path: &Path, + mut input: Map, + ) -> std::result::Result, String> { self.load(path)?; let Some(ast) = &self.ast else { return Err("script did not compile".to_string()); }; + let now = Instant::now(); + let dt = self.last_render.map_or(0.0, |last| { + now.saturating_duration_since(last) + .as_secs_f64() + .min(MAX_FRAME_DT_SECS) + }); + self.last_render = Some(now); + insert_float(&mut input, "dt", dt); + insert_int( + &mut input, + "frame", + i64::try_from(self.frame).unwrap_or(i64::MAX), + ); + self.frame = self.frame.wrapping_add(1); + let state = if self.script_state.is_unit() { + Dynamic::from_map(Map::new()) + } else { + self.script_state.clone() + }; + input.insert("state".into(), state); + let mut scope = Scope::new(); - let output = self + let returned = self .engine - .call_fn::(&mut scope, ast, "render", (input,)) + .call_fn::(&mut scope, ast, "render", (input,)) .map_err(|err| err.to_string())?; + let output = if returned.is_array() { + returned.cast::() + } else if let Some(mut map) = returned.try_cast::() { + let commands = map + .remove("commands") + .and_then(|value| value.try_cast::()) + .ok_or_else(|| "render returned a map without a commands array".to_string())?; + if let Some(state) = map.remove("state") { + self.script_state = state; + } + commands + } else { + return Err("render must return an array or #{ commands, state }".to_string()); + }; let mut commands = Vec::with_capacity(output.len()); for (index, value) in output.into_iter().enumerate() { commands.push( @@ -508,8 +731,16 @@ impl ScriptRuntime { self.cached_path = Some(path.to_path_buf()); self.cached_modified = modified; self.ast = Some(ast); + self.reset_session(); Ok(()) } + + /// Forgets the script's retained state and frame clock. + fn reset_session(&mut self) { + self.script_state = Dynamic::UNIT; + self.frame = 0; + self.last_render = None; + } } #[derive(Debug, Clone)] @@ -523,6 +754,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, HLine { x: u16, @@ -531,6 +763,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, VLine { x: u16, @@ -539,6 +772,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, Rect { x: u16, @@ -548,6 +782,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, Trace { x: u16, @@ -557,6 +792,7 @@ enum DrawCommand { fg: Color, line_fg: Color, bg: Color, + mods: Modifier, }, Text { x: u16, @@ -564,6 +800,26 @@ enum DrawCommand { text: String, fg: Color, bg: Color, + mods: Modifier, + }, + /// Braille dots: each cell holds 2 x 4 dots, so `points` are in dot + /// coordinates (x 0..2*width, y 0..4*height). Dots merge with braille + /// already drawn in the same cell. + Dots { + points: Vec<(u16, u16)>, + fg: Color, + bg: Color, + mods: Modifier, + }, + /// A thin straight line of braille dots between two dot coordinates. + Line { + x0: u16, + y0: u16, + x1: u16, + y1: u16, + fg: Color, + bg: Color, + mods: Modifier, }, } @@ -577,6 +833,7 @@ impl DrawCommand { .ok_or_else(|| "missing op".to_string())?; let fg = map_color(&map, "fg").unwrap_or(Color::White); let bg = map_color(&map, "bg").unwrap_or(Color::Black); + let mods = map_modifiers(&map); match op.as_str() { "clear" => Ok(DrawCommand::Clear { bg }), "cell" => Ok(DrawCommand::Cell { @@ -585,6 +842,7 @@ impl DrawCommand { ch: map_string(&map, "ch").unwrap_or_else(|| " ".to_string()), fg, bg, + mods, }), "hline" => Ok(DrawCommand::HLine { x: map_u16(&map, "x").ok_or_else(|| "hline.x must be an integer".to_string())?, @@ -593,6 +851,7 @@ impl DrawCommand { ch: map_string(&map, "ch").unwrap_or_else(|| " ".to_string()), fg, bg, + mods, }), "vline" => Ok(DrawCommand::VLine { x: map_u16(&map, "x").ok_or_else(|| "vline.x must be an integer".to_string())?, @@ -601,6 +860,7 @@ impl DrawCommand { ch: map_string(&map, "ch").unwrap_or_else(|| " ".to_string()), fg, bg, + mods, }), "rect" => Ok(DrawCommand::Rect { x: map_u16(&map, "x").ok_or_else(|| "rect.x must be an integer".to_string())?, @@ -610,6 +870,7 @@ impl DrawCommand { ch: map_string(&map, "ch").unwrap_or_else(|| " ".to_string()), fg, bg, + mods, }), "trace" => Ok(DrawCommand::Trace { x: map_u16(&map, "x").unwrap_or(0), @@ -620,6 +881,7 @@ impl DrawCommand { fg, line_fg: map_color(&map, "line_fg").unwrap_or(fg), bg, + mods, }), "text" => Ok(DrawCommand::Text { x: map_u16(&map, "x").ok_or_else(|| "text.x must be an integer".to_string())?, @@ -627,6 +889,34 @@ impl DrawCommand { text: map_string(&map, "text").unwrap_or_default(), fg, bg, + mods, + }), + "dots" => { + let flat = map_u16_array(&map, "points") + .ok_or_else(|| "dots.points must be an integer array".to_string())?; + if flat.len() % 2 != 0 { + return Err("dots.points must hold x, y pairs".to_string()); + } + Ok(DrawCommand::Dots { + points: flat + .as_chunks::<2>() + .0 + .iter() + .map(|[x, y]| (*x, *y)) + .collect(), + fg, + bg, + mods, + }) + } + "line" => Ok(DrawCommand::Line { + x0: map_u16(&map, "x0").ok_or_else(|| "line.x0 must be an integer".to_string())?, + y0: map_u16(&map, "y0").ok_or_else(|| "line.y0 must be an integer".to_string())?, + x1: map_u16(&map, "x1").ok_or_else(|| "line.x1 must be an integer".to_string())?, + y1: map_u16(&map, "y1").ok_or_else(|| "line.y1 must be an integer".to_string())?, + fg, + bg, + mods, }), _ => Err(format!("unknown op {op:?}")), } @@ -638,11 +928,32 @@ fn render_commands(frame: &mut Frame, area: Rect, commands: &[DrawCommand]) { } fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCommand]) { + // Each command sets the cell's whole attribute set, so a plain command + // drawn over a bold or dim one does not inherit its attributes. + let styled = |fg: Color, bg: Color, mods: Modifier| { + Style::new() + .fg(fg) + .bg(bg) + .add_modifier(mods) + .remove_modifier(Modifier::all().difference(mods)) + }; for command in commands { match command { - DrawCommand::Clear { bg } => fill_rect(buffer, area, " ", Style::new().bg(*bg)), - DrawCommand::Cell { x, y, ch, fg, bg } => { - write_cell(buffer, area, *x, *y, ch, Style::new().fg(*fg).bg(*bg)); + DrawCommand::Clear { bg } => fill_rect( + buffer, + area, + " ", + Style::new().bg(*bg).remove_modifier(Modifier::all()), + ), + DrawCommand::Cell { + x, + y, + ch, + fg, + bg, + mods, + } => { + write_cell(buffer, area, *x, *y, ch, styled(*fg, *bg, *mods)); } DrawCommand::HLine { x, @@ -651,8 +962,9 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo ch, fg, bg, + mods, } => { - let style = Style::new().fg(*fg).bg(*bg); + let style = styled(*fg, *bg, *mods); for offset in 0..(*w).min(area.width.saturating_sub(*x)) { write_cell(buffer, area, x.saturating_add(offset), *y, ch, style); } @@ -664,8 +976,9 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo ch, fg, bg, + mods, } => { - let style = Style::new().fg(*fg).bg(*bg); + let style = styled(*fg, *bg, *mods); for offset in 0..(*h).min(area.height.saturating_sub(*y)) { write_cell(buffer, area, *x, y.saturating_add(offset), ch, style); } @@ -678,8 +991,9 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo ch, fg, bg, + mods, } => { - let style = Style::new().fg(*fg).bg(*bg); + let style = styled(*fg, *bg, *mods); for row in 0..(*h).min(area.height.saturating_sub(*y)) { for col in 0..(*w).min(area.width.saturating_sub(*x)) { write_cell( @@ -701,9 +1015,10 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo fg, line_fg, bg, + mods, } => { - let line_style = Style::new().fg(*line_fg).bg(*bg); - let point_style = Style::new().fg(*fg).bg(*bg); + let line_style = styled(*line_fg, *bg, *mods); + let point_style = styled(*fg, *bg, *mods); let mut previous_y: Option = None; for (index, y) in ys .iter() @@ -726,7 +1041,14 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo previous_y = Some(y); } } - DrawCommand::Text { x, y, text, fg, bg } => { + DrawCommand::Text { + x, + y, + text, + fg, + bg, + mods, + } => { for (offset, ch) in text .chars() .take(usize::from(area.width.saturating_sub(*x))) @@ -741,14 +1063,139 @@ fn render_commands_to_buffer(buffer: &mut Buffer, area: Rect, commands: &[DrawCo x.saturating_add(offset), *y, &ch.to_string(), - Style::new().fg(*fg).bg(*bg), + styled(*fg, *bg, *mods), ); } } + DrawCommand::Dots { + points, + fg, + bg, + mods, + } => { + let style = styled(*fg, *bg, *mods); + for (dot_x, dot_y) in points { + plot_dot(buffer, area, *dot_x, *dot_y, style); + } + } + DrawCommand::Line { + x0, + y0, + x1, + y1, + fg, + bg, + mods, + } => { + let style = styled(*fg, *bg, *mods); + draw_dot_line(buffer, area, (*x0, *y0), (*x1, *y1), style); + } } } } +/// Braille dot bits by (row, column) inside a cell. +const BRAILLE_BITS: [[u32; 2]; 4] = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]]; +const BRAILLE_BASE: u32 = 0x2800; + +fn plot_dot(buffer: &mut Buffer, area: Rect, dot_x: u16, dot_y: u16, style: Style) { + let (x, y) = (dot_x / 2, dot_y / 4); + if x >= area.width || y >= area.height { + return; + } + let bit = BRAILLE_BITS[usize::from(dot_y % 4)][usize::from(dot_x % 2)]; + let Some(cell) = buffer.cell_mut((area.x.saturating_add(x), area.y.saturating_add(y))) else { + return; + }; + let existing = cell + .symbol() + .chars() + .next() + .map(u32::from) + .filter(|code| (BRAILLE_BASE..=BRAILLE_BASE + 0xff).contains(code)) + .map_or(0, |code| code - BRAILLE_BASE); + let symbol = char::from_u32(BRAILLE_BASE + (existing | bit)).unwrap_or(' '); + cell.set_symbol(&symbol.to_string()).set_style(style); +} + +/// Bresenham between two dot coordinates. The segment is first clipped to the +/// area's dot grid, so the work is bounded by the area, not by how far away a +/// script puts the endpoints. +fn draw_dot_line(buffer: &mut Buffer, area: Rect, from: (u16, u16), to: (u16, u16), style: Style) { + let max_x = f64::from(area.width) * 2.0 - 1.0; + let max_y = f64::from(area.height) * 4.0 - 1.0; + if max_x < 0.0 || max_y < 0.0 { + return; + } + let Some(((x0, y0), (x1, y1))) = clip_segment( + (f64::from(from.0), f64::from(from.1)), + (f64::from(to.0), f64::from(to.1)), + max_x, + max_y, + ) else { + return; + }; + let (mut x, mut y) = (x0.round() as i32, y0.round() as i32); + let (x1, y1) = (x1.round() as i32, y1.round() as i32); + let dx = (x1 - x).abs(); + let dy = -(y1 - y).abs(); + let step_x = if x < x1 { 1 } else { -1 }; + let step_y = if y < y1 { 1 } else { -1 }; + let mut error = dx + dy; + loop { + if let (Ok(dot_x), Ok(dot_y)) = (u16::try_from(x), u16::try_from(y)) { + plot_dot(buffer, area, dot_x, dot_y, style); + } + if x == x1 && y == y1 { + break; + } + let doubled = 2 * error; + if doubled >= dy { + error += dy; + x += step_x; + } + if doubled <= dx { + error += dx; + y += step_y; + } + } +} + +/// Liang-Barsky clip of a segment to `[0, max_x] x [0, max_y]`. +fn clip_segment( + from: (f64, f64), + to: (f64, f64), + max_x: f64, + max_y: f64, +) -> Option<((f64, f64), (f64, f64))> { + let (dx, dy) = (to.0 - from.0, to.1 - from.1); + let (mut enter, mut leave) = (0.0_f64, 1.0_f64); + for (p, q) in [ + (-dx, from.0), + (dx, max_x - from.0), + (-dy, from.1), + (dy, max_y - from.1), + ] { + if p == 0.0 { + if q < 0.0 { + return None; + } + } else { + let t = q / p; + if p < 0.0 { + enter = enter.max(t); + } else { + leave = leave.min(t); + } + } + } + if enter > leave { + return None; + } + let at = |t: f64| (from.0 + dx * t, from.1 + dy * t); + Some((at(enter), at(leave))) +} + fn fill_rect(buffer: &mut Buffer, area: Rect, symbol: &'static str, style: Style) { for y in area.y..area.y + area.height { for x in area.x..area.x + area.width { @@ -793,6 +1240,30 @@ fn map_u16_array(map: &Map, key: &str) -> Option> { .collect() } +/// Optional text attributes on any command: `bold`, `dim`, `italic`, +/// `underline`, `reversed` (booleans). Terminals render bold as a heavier or +/// brighter glyph and dim as a fainter one. +fn map_modifiers(map: &Map) -> Modifier { + let flag = |key: &str| { + map.get(key) + .and_then(|value| value.clone().try_cast::()) + .unwrap_or(false) + }; + let mut mods = Modifier::empty(); + for (key, modifier) in [ + ("bold", Modifier::BOLD), + ("dim", Modifier::DIM), + ("italic", Modifier::ITALIC), + ("underline", Modifier::UNDERLINED), + ("reversed", Modifier::REVERSED), + ] { + if flag(key) { + mods |= modifier; + } + } + mods +} + fn map_color(map: &Map, key: &str) -> Option { let value = map.get(key)?; if let Some(rgb) = value.clone().try_cast::() { @@ -832,16 +1303,16 @@ fn insert_float(map: &mut Map, key: &str, value: f64) { map.insert(key.into(), Dynamic::from_float(value as FLOAT)); } -fn clock_label() -> String { - let secs = SystemTime::now() - .duration_since(SystemTime::UNIX_EPOCH) - .map(|duration| duration.as_secs()) - .unwrap_or(0); - format!( - "{:02}:{:02}:{:02}", - secs / 3600 % 24, - secs / 60 % 60, - secs % 60 +/// Local wall-clock time as (hour, minute, second, millisecond), read once +/// so all clock inputs of a frame agree. +fn clock_now() -> (u32, u32, u32, u32) { + use chrono::Timelike as _; + let now = chrono::Local::now(); + ( + now.hour(), + now.minute(), + now.second(), + now.timestamp_subsec_millis().min(999), ) } @@ -971,6 +1442,8 @@ mod tests { input.insert("clock".into(), "12:34:56".into()); input.insert("track_title".into(), "track".into()); input.insert("track_artist".into(), "artist".into()); + insert_meter(&mut input, &crate::player::AudioAnalysisSnapshot::default()); + insert_track_details(&mut input, &AppState::default()); input } @@ -1312,4 +1785,486 @@ mod tests { } } } + + fn script_file(name: &str, source: &str) -> PathBuf { + let path = + std::env::temp_dir().join(format!("furumi-test-{}-{name}.rhai", std::process::id())); + std::fs::write(&path, source).unwrap(); + path + } + + fn rendered_text(commands: &[DrawCommand]) -> String { + commands + .iter() + .filter_map(|command| match command { + DrawCommand::Text { text, .. } => Some(text.clone()), + _ => None, + }) + .collect() + } + + #[test] + fn script_state_round_trips_and_resets_on_reload() { + let source = r#" + fn render(input) { + let n = if "n" in input.state { input.state.n } else { 0 }; + #{ + commands: [#{ op: "text", x: 0, y: 0, text: "" + n + "/" + input.frame }], + state: #{ n: n + 1 } + } + } + "#; + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), source).unwrap(); + let base = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000); + file.as_file() + .set_times(std::fs::FileTimes::new().set_modified(base)) + .unwrap(); + let mut runtime = ScriptRuntime::default(); + let mut last = Vec::new(); + for _ in 0..3 { + last = runtime.render(file.path(), test_input()).unwrap(); + } + assert_eq!(rendered_text(&last), "2/2"); + + // An edited script starts from an empty state again. + std::fs::write(file.path(), format!("{source}\n// edited")).unwrap(); + file.as_file() + .set_times( + std::fs::FileTimes::new().set_modified(base + std::time::Duration::from_secs(10)), + ) + .unwrap(); + let reloaded = runtime.render(file.path(), test_input()).unwrap(); + assert_eq!(rendered_text(&reloaded), "0/0"); + + // So does reopening the visualizer. + runtime.render(file.path(), test_input()).unwrap(); + runtime.reset_session(); + let reopened = runtime.render(file.path(), test_input()).unwrap(); + assert_eq!(rendered_text(&reopened), "0/0"); + } + + #[test] + fn map_results_need_a_commands_array() { + let path = script_file("no-commands", "fn render(input) { #{ state: 1 } }"); + let err = ScriptRuntime::default() + .render(&path, test_input()) + .unwrap_err(); + let _ = std::fs::remove_file(&path); + assert!(err.contains("commands"), "{err}"); + } + + #[test] + fn dots_and_lines_merge_into_braille_cells() { + let commands = [ + DrawCommand::from_dynamic(Dynamic::from_map( + [ + ("op".into(), "line".into()), + ("x0".into(), Dynamic::from_int(0)), + ("y0".into(), Dynamic::from_int(0)), + ("x1".into(), Dynamic::from_int(3)), + ("y1".into(), Dynamic::from_int(0)), + ] + .into_iter() + .collect(), + )) + .unwrap(), + DrawCommand::from_dynamic(Dynamic::from_map( + [ + ("op".into(), "dots".into()), + ( + "points".into(), + vec![Dynamic::from_int(0), Dynamic::from_int(3)].into(), + ), + ("fg".into(), Dynamic::from_int(0x33ffee)), + ] + .into_iter() + .collect(), + )) + .unwrap(), + ]; + let area = Rect::new(0, 0, 3, 1); + let mut buffer = Buffer::empty(area); + render_commands_to_buffer(&mut buffer, area, &commands); + // Cell 0 holds dots (0,0), (1,0) and (0,3); cell 1 holds (2,0), (3,0). + assert_eq!(buffer[(0, 0)].symbol(), "\u{2849}"); + assert_eq!(buffer[(1, 0)].symbol(), "\u{2809}"); + assert_eq!(buffer[(0, 0)].fg, Color::Rgb(0x33, 0xff, 0xee)); + assert_eq!(buffer[(2, 0)].symbol(), " "); + } + + #[test] + fn odd_dot_lists_and_off_screen_lines_are_handled() { + let odd = Dynamic::from_map( + [ + ("op".into(), "dots".into()), + ("points".into(), vec![Dynamic::from_int(1)].into()), + ] + .into_iter() + .collect(), + ); + assert!(DrawCommand::from_dynamic(odd).is_err()); + + let area = Rect::new(0, 0, 2, 1); + let mut buffer = Buffer::empty(area); + let line = DrawCommand::Line { + x0: 0, + y0: 0, + x1: 400, + y1: 900, + fg: Color::White, + bg: Color::Black, + mods: Modifier::empty(), + }; + render_commands_to_buffer(&mut buffer, area, &[line]); + assert_eq!(buffer[(0, 0)].symbol().chars().count(), 1); + } + + #[test] + fn far_line_endpoints_are_clipped_to_the_area() { + let area = Rect::new(0, 0, 4, 2); + let line = |x0, y0, x1, y1| DrawCommand::Line { + x0, + y0, + x1, + y1, + fg: Color::White, + bg: Color::Black, + mods: Modifier::empty(), + }; + let mut far = Buffer::empty(area); + let started = Instant::now(); + render_commands_to_buffer( + &mut far, + area, + &[ + line(0, 0, u16::MAX, u16::MAX), + line(u16::MAX, 0, u16::MAX, u16::MAX), + ], + ); + assert!(started.elapsed() < std::time::Duration::from_millis(50)); + // Same dots as the line drawn only to the area's last dot. + let mut near = Buffer::empty(area); + render_commands_to_buffer(&mut near, area, &[line(0, 0, 7, 7)]); + assert_eq!(far, near); + } + + #[test] + fn attributes_do_not_leak_into_later_commands() { + let text = |bold: bool| { + DrawCommand::from_dynamic(Dynamic::from_map( + [ + ("op".into(), "text".into()), + ("x".into(), Dynamic::from_int(0)), + ("y".into(), Dynamic::from_int(0)), + ("text".into(), "A".into()), + ("bold".into(), bold.into()), + ("reversed".into(), bold.into()), + ] + .into_iter() + .collect(), + )) + .unwrap() + }; + let area = Rect::new(0, 0, 1, 1); + let mut buffer = Buffer::empty(area); + render_commands_to_buffer(&mut buffer, area, &[text(true), text(false)]); + assert!(buffer[(0, 0)].modifier.is_empty()); + render_commands_to_buffer( + &mut buffer, + area, + &[text(true), DrawCommand::Clear { bg: Color::Black }], + ); + assert!(buffer[(0, 0)].modifier.is_empty()); + } + + #[test] + fn vfd_panel_renders_in_bounds_for_many_situations() { + let script = BUNDLED_SCRIPTS + .iter() + .find(|script| script.id == "vfd_panel") + .unwrap(); + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), script.source).unwrap(); + let sizes = [ + (20, 6), + (40, 12), + (80, 24), + (119, 33), + (120, 34), + (160, 45), + (300, 90), + ]; + let variants: [(&str, i64, &str, i64, f64); 4] = [ + ("", 0, "", 0, 0.0), + ( + "A very long title that keeps going for a while — on and on", + 3, + "local", + 128, + 1.0, + ), + ("Episode", 1, "podcast", 1500, 0.0), + ("Remote", 2, "federated", 7, 0.55), + ]; + for (width, height) in sizes { + for (title, number, source, queue, volume) in variants { + let mut runtime = ScriptRuntime::default(); + for frame in 0..3 { + let mut input = test_input(); + insert_int(&mut input, "width", width); + insert_int(&mut input, "height", height); + input.insert("track_title".into(), title.into()); + input.insert("source".into(), source.into()); + insert_int(&mut input, "track_number", number * 41); + insert_int(&mut input, "queue_index", number); + insert_int(&mut input, "queue_length", queue); + insert_float(&mut input, "volume", volume); + insert_float(&mut input, "position", 600.0 + f64::from(frame) * 7.0); + input.insert("paused".into(), (frame == 1).into()); + let commands = runtime + .render(file.path(), input) + .unwrap_or_else(|err| panic!("{width}x{height} {title:?}: {err}")); + let area = Rect::new(0, 0, width as u16, height as u16); + let mut buffer = Buffer::empty(area); + render_commands_to_buffer(&mut buffer, area, &commands); + // nothing is laid out past the bottom of the frame + for command in &commands { + let bottom = match command { + DrawCommand::Text { y, .. } + | DrawCommand::Cell { y, .. } + | DrawCommand::HLine { y, .. } => Some(*y), + DrawCommand::VLine { y, h, .. } | DrawCommand::Rect { y, h, .. } => { + Some(y + h.saturating_sub(1)) + } + _ => None, + }; + if let Some(bottom) = bottom { + assert!( + i64::from(bottom) < height, + "{width}x{height} {title:?}: drawn at row {bottom}" + ); + } + } + } + } + } + } + + #[test] + fn vfd_panel_options_standby_and_effects_render() { + let base = BUNDLED_SCRIPTS + .iter() + .find(|script| script.id == "vfd_panel") + .unwrap() + .source; + let variants = [ + base.to_string(), + base.replacen( + r#"fn METER_STYLE() { "bars" }"#, + r#"fn METER_STYLE() { "needles" }"#, + 1, + ), + base.replacen( + r#"fn PALETTE() { "classic" }"#, + r#"fn PALETTE() { "green" }"#, + 1, + ), + base.replacen( + r#"fn PALETTE() { "classic" }"#, + r#"fn PALETTE() { "ice" }"#, + 1, + ), + base.replacen( + r#"fn DISPLAY_MODE() { "auto" }"#, + r#"fn DISPLAY_MODE() { "deck" }"#, + 1, + ), + base.replacen( + r#"fn DISPLAY_MODE() { "auto" }"#, + r#"fn DISPLAY_MODE() { "minimal" }"#, + 1, + ), + ]; + assert_ne!(variants[0], variants[1]); + assert_ne!(variants[0], variants[2]); + for source in variants { + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), &source).unwrap(); + for (width, height) in [ + (30, 8), + (80, 24), + (100, 30), + (110, 40), + (160, 45), + (240, 70), + ] { + for title in ["", "Даже не думай — Ёлка", "Track"] { + let mut runtime = ScriptRuntime::default(); + // Past the power-on test, with static and a seek pending. + let state: Map = [ + ("boot".into(), Dynamic::from_float(-1.0)), + ("spin".into(), Dynamic::from_float(0.3)), + ("over".into(), Dynamic::from_float(0.5)), + ("noise".into(), Dynamic::from_float(0.2)), + ("search".into(), Dynamic::from_float(0.4)), + ("key".into(), "another track".into()), + ("source".into(), "local".into()), + ("last_pos".into(), Dynamic::from_float(5.0)), + ] + .into_iter() + .collect(); + runtime.load(file.path()).unwrap(); + runtime.script_state = Dynamic::from_map(state); + let mut input = test_input(); + insert_int(&mut input, "width", width); + insert_int(&mut input, "height", height); + input.insert("track_title".into(), title.into()); + insert_float(&mut input, "volume", 0.2); + insert_int(&mut input, "clock_hour", 23); + insert_int(&mut input, "clock_second", 1); + let commands = runtime + .render(file.path(), input) + .unwrap_or_else(|err| panic!("{width}x{height} {title:?}: {err}")); + let area = Rect::new(0, 0, width as u16, height as u16); + let mut buffer = Buffer::empty(area); + render_commands_to_buffer(&mut buffer, area, &commands); + if title.is_empty() && width >= 80 { + let text = rendered_text(&commands); + assert!( + text.contains("STANDBY"), + "{width}x{height}: no standby clock" + ); + } + } + } + } + } + + #[test] + fn vfd_panel_clock_keeps_clear_of_the_lamps() { + let script = BUNDLED_SCRIPTS + .iter() + .find(|script| script.id == "vfd_panel") + .unwrap(); + let file = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(file.path(), script.source).unwrap(); + for (width, height) in [(120, 34), (160, 34), (180, 40)] { + let mut runtime = ScriptRuntime::default(); + runtime.load(file.path()).unwrap(); + runtime.script_state = Dynamic::from_map( + [("boot".into(), Dynamic::from_float(-1.0))] + .into_iter() + .collect(), + ); + let mut input = test_input(); + insert_int(&mut input, "width", width); + insert_int(&mut input, "height", height); + let commands = runtime.render(file.path(), input).unwrap(); + let area = Rect::new(0, 0, width as u16, height as u16); + let mut buffer = Buffer::empty(area); + render_commands_to_buffer(&mut buffer, area, &commands); + let rows: Vec = (0..area.height) + .map(|y| { + (0..area.width) + .map(|x| buffer[(x, y)].symbol().to_string()) + .collect() + }) + .collect(); + assert!(rows[0].contains("12:34:56"), "{width}x{height}: clock"); + assert!( + rows.iter().any(|row| row.contains("HIGH")), + "{width}x{height}: lamps overdrawn" + ); + } + } + + #[test] + fn text_modifiers_reach_the_buffer() { + let command = DrawCommand::from_dynamic(Dynamic::from_map( + [ + ("op".into(), "text".into()), + ("x".into(), Dynamic::from_int(0)), + ("y".into(), Dynamic::from_int(0)), + ("text".into(), "A".into()), + ("bold".into(), true.into()), + ("dim".into(), false.into()), + ] + .into_iter() + .collect(), + )) + .unwrap(); + let area = Rect::new(0, 0, 1, 1); + let mut buffer = Buffer::empty(area); + render_commands_to_buffer(&mut buffer, area, &[command]); + assert!(buffer[(0, 0)].modifier.contains(Modifier::BOLD)); + assert!(!buffer[(0, 0)].modifier.contains(Modifier::DIM)); + } + + #[test] + fn meter_and_track_details_reach_scripts() { + let mut state = AppState::default(); + let track = crate::library::models::TrackItem { + id: 7, + title: "Even Flow".into(), + track_number: Some(3), + disc_number: Some(1), + duration_seconds: 293.0, + artists: vec![], + featured_artists: vec![], + release_id: 1, + release_title: "Ten".into(), + release_year: Some(1991), + cover_path: None, + file_path: "/music/even-flow.flac".into(), + content_id: None, + audio_format: Some("flac".into()), + audio_bitrate: Some(900), + audio_sample_rate: Some(44_100), + audio_bit_depth: Some(16), + file_size_bytes: None, + play_count: 0, + fed: None, + podcast: None, + }; + state.player.queue = vec![track.clone(), track.clone()]; + state.player.queue_pos = 1; + state.player.current = Some(track); + state.player.playing = true; + state.player.audio_analysis.spectrum = vec![0.5; crate::player::BAND_CENTERS_HZ.len()]; + state.player.audio_analysis.level_l = 0.25; + state.player.audio_analysis.level_side = 0.125; + state.player.audio_analysis.stereo = Some(true); + state.player.audio_analysis.sample_rate = 44_100; + + let input = input_map(Rect::new(0, 0, 80, 24), &state); + let int = |key: &str| input[key].as_int().unwrap(); + let float = |key: &str| input[key].as_float().unwrap(); + let text = |key: &str| input[key].clone().into_string().unwrap(); + assert_eq!(int("queue_index"), 2); + assert_eq!(int("queue_length"), 2); + assert_eq!(int("track_number"), 3); + assert_eq!(int("year"), 1991); + assert_eq!(int("audio_bitrate"), 900); + assert_eq!(int("sample_rate"), 44_100); + assert_eq!(text("source"), "local"); + assert_eq!(text("repeat"), "off"); + assert_eq!(text("audio_format"), "flac"); + assert!(input["playing"].as_bool().unwrap()); + assert_eq!(float("level_l"), 0.25); + assert_eq!(float("level_side"), 0.125); + assert_eq!(text("channel_mode"), "stereo"); + assert_eq!(float("spectrum_floor_db"), -60.0); + let spectrum = input["spectrum"].clone().into_array().unwrap(); + let hz = input["spectrum_hz"].clone().into_array().unwrap(); + assert_eq!(spectrum.len(), hz.len()); + assert_eq!(spectrum[0].as_float().unwrap(), 0.5); + + // Without analysis the arrays keep their length and read silence. + let empty = input_map(Rect::new(0, 0, 80, 24), &AppState::default()); + let peaks = empty["spectrum_peaks"].clone().into_array().unwrap(); + assert_eq!(peaks.len(), crate::player::BAND_CENTERS_HZ.len()); + assert_eq!(empty["source"].clone().into_string().unwrap(), ""); + assert_eq!(empty["queue_index"].as_int().unwrap(), 0); + } } diff --git a/src/visualizer/status.rs b/src/visualizer/status.rs index f678bb9..604aa55 100644 --- a/src/visualizer/status.rs +++ b/src/visualizer/status.rs @@ -495,15 +495,16 @@ mod tests { #[test] fn loud_recordings_use_multiple_heights_instead_of_a_solid_row() { - let file = tempfile::NamedTempFile::new().unwrap(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("braille.rhai"); let mut runtime = ScriptRuntime::default(); - std::fs::write(file.path(), LEGACY_SOURCE).unwrap(); - let old = prepare(&mut runtime, file.path(), input(64, 1.0), 64).unwrap(); + std::fs::write(&path, LEGACY_SOURCE).unwrap(); + let old = prepare(&mut runtime, &path, input(64, 1.0), 64).unwrap(); assert!(old.content.iter().all(|cell| cell.symbol() == "⣿")); - install_script_at(file.path()).unwrap(); + install_script_at(&path).unwrap(); // A fresh runtime also models a restart installing the new default. let mut runtime = ScriptRuntime::default(); - let new = prepare(&mut runtime, file.path(), input(64, 1.0), 64).unwrap(); + let new = prepare(&mut runtime, &path, input(64, 1.0), 64).unwrap(); let symbols: std::collections::HashSet<_> = new.content.iter().map(|cell| cell.symbol()).collect(); assert!(symbols.len() >= 4, "{symbols:?}"); @@ -524,23 +525,24 @@ mod tests { .collect::() .into(), ); - let silent = prepare(&mut runtime, file.path(), silence, 64).unwrap(); + let silent = prepare(&mut runtime, &path, silence, 64).unwrap(); assert!(silent.content.iter().all(|cell| cell.symbol() == "⠀")); } #[test] fn only_the_untouched_previous_default_is_upgraded() { - let file = tempfile::NamedTempFile::new().unwrap(); - std::fs::write(file.path(), LEGACY_SOURCE).unwrap(); - install_script_at(file.path()).unwrap(); - assert_eq!(std::fs::read_to_string(file.path()).unwrap(), SOURCE); - install_script_at(file.path()).unwrap(); - assert_eq!(std::fs::read_to_string(file.path()).unwrap(), SOURCE); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("braille.rhai"); + std::fs::write(&path, LEGACY_SOURCE).unwrap(); + install_script_at(&path).unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), SOURCE); + install_script_at(&path).unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), SOURCE); for stock in [LEGACY_SOURCE, SOURCE] { let custom = format!("{stock}\n// user customization\n"); - std::fs::write(file.path(), &custom).unwrap(); - install_script_at(file.path()).unwrap(); - assert_eq!(std::fs::read_to_string(file.path()).unwrap(), custom); + std::fs::write(&path, &custom).unwrap(); + install_script_at(&path).unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), custom); } }