diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 096845f..9394ed3 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,35 @@ 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 analyzed sample rate, and track, queue and transport +details (format, bit depth, bitrate, track number, queue position, repeat, +shuffle, source). 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 +570,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..33e411f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- "VFD panel" visualization: a vacuum-fluorescent hi-fi front panel with + thin segment digits, a stereo peak level meter, a 25-band analyzer with + peak hold, tone fans, a routing diagram and transport lamps, plus a + power-on segment test, a counter "search" on track changes and an OVER + lamp. +- Visualization protocol v3: a real third-octave spectrum (31 bands) with + peak hold, left/right RMS and held peaks, 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. + ## [0.5.0] - 2026-11-20 ### Added 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/visualizations/vfd_panel.rhai b/src/visualizations/vfd_panel.rhai new file mode 100644 index 0000000..e293214 --- /dev/null +++ b/src/visualizations/vfd_panel.rhai @@ -0,0 +1,636 @@ +// name: VFD panel +// protocol: furumi-visualizer-v3 +// bundle-version: 1 +// +// A hi-fi front panel in the style of a vacuum fluorescent display: thin +// segment digits, a stereo peak level meter, a third-octave analyzer with +// peak hold, tone fans, a routing diagram and transport lamps. Everything is +// drawn thin (eighth blocks and braille dots); only level bars are thicker. +// +// It uses the v3 inputs (see below) and keeps a little state between frames +// for its effects: a power-on segment test, a "search" spin of the counter on +// track changes, an OVER lamp that holds and a blinking pause point. +// +// 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 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 +// 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" +// 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 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 pad2(n) { if n < 10 { "0" + n } else { "" + n } } + +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 { 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 { 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 }); + } +} + +// ---------- palette (lit / ghost of unlit segments) ---------- + +fn white() { rgb(232, 244, 240) } +fn white_mid() { rgb(140, 152, 150) } +fn white_ghost() { rgb(22, 27, 27) } +fn amber() { rgb(255, 176, 36) } +fn amber_hot() { rgb(255, 224, 130) } +fn amber_ghost() { rgb(40, 25, 6) } +fn amber_text() { rgb(208, 138, 28) } +fn red() { rgb(255, 58, 38) } +fn red_ghost() { rgb(46, 11, 8) } +fn cyan() { rgb(84, 234, 216) } +fn cyan_mid() { rgb(44, 146, 136) } +fn cyan_ghost() { rgb(8, 32, 30) } + +// ---------- thin segment font ---------- +// Segments are eighth-block lines on cell edges: horizontals "▁" at the +// bottom of a row, verticals "▕" / "▏" on the inner edges of the outer +// columns. A glyph is cw cells wide and 2*rh+1 rows tall. + +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", "Y" => "bcdfg", "U" => "bcdef", + "E" => "adefg", "t" => "defg", "o" => "cdeg", "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 = cw - 2; + this.hl(x + 1, y, inner, "▁", 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)); +} + +// 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 { on } else { off }); + cx += 2; + } else { + if ch != ' ' { this.seg(cx, y, seg_mask("" + ch), cw, rh, on, off); } + cx += cw + 1; + } + } + cx +} + +fn seg_width(s, cw) { + let w = 0; + for ch in s.chars() { if ch == '.' { w += 2; } else { w += cw + 1; } } + w - 1 +} + +// ---------- measurements ---------- + +// Normalized meter value -> dBFS. +fn dbfs(input, v) { get(input, "spectrum_floor_db", -60.0) * (1.0 - v) } + +// Display range of the analyzer: ordinary music sits around -45..-15 dBFS +// per third-octave band; the panel shows -50..-10 dBFS. +fn band_display(input, v) { clamp((dbfs(input, v) + 50.0) / 40.0, 0.0, 1.0) } + +// The 25 panel bands 63 Hz .. 16 kHz are spectrum entries 5..29. +fn panel_bands(input) { + 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), band_display(input, pk)]); + } + 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)] +} + +// ---------- panels ---------- + +fn draw_counter(input, st, x, y) { + 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 { white_mid() } else { white() }; + let off = if st.boot > 0.0 { lit } else { white_ghost() }; + let blink = !input.paused || (to_int(input.time * 2.0) % 2 == 0); + let end = this.seg_text(x, y, text, 6, 2, 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, 6, 2, lit, off, false); + this.txt(x, y + 6, "TIME", white_mid()); + this.txt(end + 3, y + 6, "TRACK", 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 } + +// Deck peak meter scale: 0 on the scale is -10 dBFS. +fn meter_pos(db) { + // The first mark is the host floor (-60 dBFS) on this scale. + 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) +} + +fn draw_meter(input, st, x, y, w) { + 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", white()); + this.txt(x + w - 4, y, "0VU", white()); + this.txt(x + w - 4, y + 1, "▔▔▔", 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], white()); + let ghost = if st.boot > 0.0 { white_mid() } else { white_ghost() }; + this.hl(bx, r[3], hot, "▃", ghost); + this.hl(bx + hot, r[3], mw - hot, "▃", if st.boot > 0.0 { red() } else { red_ghost() }); + 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), "▃", white()); + if cells > hot { this.hl(bx + hot, r[3], cells - hot, "▃", red()); } + if r[2] > 0.0 { + let pk = clamp(to_int(meter_pos(dbfs(input, r[2])) / n * to_float(mw)), 0, mw - 1); + this.txt(bx + pk, r[3], "▃", if pk >= hot { red() } else { white() }); + } + } + this.txt(x, y + 3, "dB", 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 { red() } else { white() }); + free = lx + labels[k].len() + 1; + } + } +} + +// Red lamps like a deck's tape-type indicators, here for the loudest range. +fn draw_lamps(input, st, bands, x, y) { + 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 { red() } else { red_ghost() }); + this.hl(cx, y + 1, names[i].len(), "▔", if on { red() } else { red_ghost() }); + cx += names[i].len() + 3; + } + let over = st.boot > 0.0 || st.over > 0.0; + this.txt(x, y + 3, "OVER", if over { red() } else { red_ghost() }); +} + +fn lamp(x, y, label, on, lit, ghost) { + this.txt(x, y, label, if on { lit } else { ghost }); + x + label.len() + 3 +} + +fn draw_status_row(input, st, x, y, w) { + let boot = st.boot > 0.0; + let repeat = get(input, "repeat", "off"); + let source = get(input, "source", ""); + let cx = x; + cx = this.lamp(cx, y, "REPEAT", boot || repeat != "off", white(), white_ghost()); + if repeat == "one" || boot { this.txt(cx - 2, y, "1", white()); } + cx = this.lamp(cx, y, "SHUFFLE", boot || get(input, "shuffle", false), white(), white_ghost()); + cx = this.lamp(cx, y, "LOCAL", boot || source == "local", white(), white_ghost()); + cx = this.lamp(cx, y, "FED", boot || source == "federated", white(), white_ghost()); + cx = this.lamp(cx, y, "PODCAST", boot || source == "podcast", white(), white_ghost()); + + // 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 bx = x + w - badge.len() - 8; + this.txt(bx, y, badge, if fmt != "" || boot { white() } else { white_ghost() }); + let kbps = get(input, "audio_bitrate", 0); + let box_ = if depth > 0 { "" + depth + "BIT" } else if kbps > 0 { "" + kbps + "K" } else { "--" }; + this.txt(bx + badge.len() + 2, y, "[" + box_ + "]", white()); +} + +fn draw_title(input, x, y, w) { + if w <= 4 { return; } + let label = if input.track_artist != "" && input.track_title != "" { + input.track_artist + " — " + input.track_title + } else if input.track_title != "" { input.track_title } else { "NO DISC" }; + label = label.to_upper(); + if label.len() <= w { + this.txt(x, y, label, white()); + } else { + let loop_ = label + " · "; + let off = to_int(input.time * 4.0) % loop_.len(); + this.txt(x, y, (loop_ + loop_).sub_string(off, w), white()); + } +} + +// Segment analyzer: thin dashes stacked per band, a dark gap between bands. +fn draw_analyzer(input, st, bands, x, y, bw, h) { + let n = bands.len(); + let bar = mx(bw - 1, 1); + let right = x + 2 + n * bw; + let scale = amber_ghost() + rgb(40, 30, 4); + let red_row = y + h / 5; + let free = x + 1; + let r = 0; + while r < h { + let fg = if y + r == red_row { red() } else { scale }; + this.txt(x, y + r, "·", fg); + this.txt(right, y + r, "·", fg); + r += 1; + } + for i in 0..n { + let bx = x + 2 + i * bw; + let v = if st.boot > 0.0 { 1.0 } else { bands[i][0] }; + let lit = clamp(to_int(v * to_float(h) + 0.5), 0, h); + if lit < h { this.fill(bx, y, bar, h - lit, "▂", amber_ghost()); } + if lit > 1 { this.fill(bx, y + h - lit + 1, bar, lit - 1, "▂", amber()); } + if lit > 0 { this.hl(bx, y + h - lit, bar, "▂", amber_hot()); } + let cap = clamp(to_int(bands[i][1] * to_float(h) + 0.5), 0, h); + if cap > lit && st.boot <= 0.0 { this.hl(bx, y + h - cap, bar, "▂", amber_hot()); } + let label = band_label(i); + let lx = mx(bx + (bar - label.len()) / 2, x + 1); + if lx >= free { + this.txt(lx, y + h + 1, label, amber_text()); + free = lx + label.len() + 1; + } + } + right +} + +fn draw_readout(input, st, bands, x, y) { + let best = 0; + for i in 1..bands.len() { if bands[i][0] > bands[best][0] { best = i; } } + let live = st.boot > 0.0 || bands[best][0] > 0.08; + let hz = band_hz(best); + 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 on = amber(); + let off = if st.boot > 0.0 { amber() } else { amber_ghost() }; + let end = this.seg_text(x, y, digits, 6, 2, on, off, true); + this.txt(end + 1, y + 4, unit, if live { amber() } else { amber_ghost() }); + this.txt(x, y + 7, "PEAK BAND", amber_text()); + this.txt(x + 12, y + 7, "HOLD", amber()); + let sr = get(input, "sample_rate", 0); + let srt = if sr > 0 { "" + (sr / 1000) + "." + ((sr % 1000) / 100) + "k" } else { "--" }; + this.txt(x, y + 9, "RATE", amber_text()); + this.txt(x + 5, y + 9, "[" + srt + "]", amber()); +} + +// Bass / treble fans: thin lines converging on the 0 line; the line closest +// to the current balance of that range against the mids is lit. +fn draw_fans(input, bands, x, y, w) { + 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", cyan()); + this.txt(x + w - 6, y, "TREBLE", cyan()); + let gy = y + 1; + let gh = 4; // rows: +10 .. -10 + this.txt(x, gy, "+10", cyan_mid()); + this.txt(x, gy + 2, " 0", cyan_mid()); + this.txt(x, gy + gh - 1, "-10", cyan_mid()); + let X0 = (x + 4) * 2; + let W = (w - 4) * 2; + let Y0 = gy * 4 + 1; + let H = gh * 4 - 3; + let ymid = Y0 + H / 2; + let half = W / 2; + for i in 0..5 { + let yy = Y0 + i * H / 4; + let bass_fg = if i == bass_line { cyan() } else { cyan_ghost() }; + let treble_fg = if i == treble_line { cyan() } else { cyan_ghost() }; + this.ln(X0, yy, X0 + half * 6 / 10, ymid, bass_fg); + this.ln(X0 + W - 1, yy, X0 + W - 1 - half * 6 / 10, ymid, treble_fg); + } + this.ln(X0 + half * 6 / 10, ymid, X0 + W - 1 - half * 6 / 10, ymid, cyan()); +} + +fn draw_balance(input, x, y, w) { + 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", cyan()); + this.txt(x + w - 1, y, "R", cyan()); + let mid = x + w / 2; + this.txt(mid - 3, y, "BALANCE", cyan()); + let d = x + 2; + while d < mid - 4 { this.txt(d, y, "·", cyan_mid()); d += 2; } + d = mid + 5; + while d < x + w - 2 { this.txt(d, y, "·", cyan_mid()); d += 2; } + let pos = clamp(mid + to_int(bal * to_float(w / 2 - 2) * 4.0), x + 2, x + w - 3); + this.txt(pos, y + 1, "▮", cyan()); +} + +// Small speaker icon (box and cone) in braille, one cell wide plus the cone. +fn speaker(x, y, fg) { + let X = x * 2; let Y = y * 4; + this.ln(X, Y + 1, X, Y + 3, fg); + this.ln(X + 1, Y + 1, X + 1, Y + 3, fg); + this.ln(X + 1, Y + 1, X + 3, Y, fg); + this.ln(X + 1, Y + 3, X + 3, Y + 4, fg); + this.ln(X + 3, Y, X + 3, Y + 4, fg); +} + +// Thin box around a label: "▁" above, "▔" below, "▕" / "▏" at the sides. +// Returns the x after the box. The box is 3 rows tall, the label on row y+1. +fn tbox(x, y, label, fg) { + let w = label.len() + 4; + this.hl(x + 1, y, w - 2, "▁", fg); + this.txt(x, y + 1, "▕", fg); + this.txt(x + 2, y + 1, label, fg); + this.txt(x + w - 1, y + 1, "▏", fg); + this.hl(x + 1, y + 2, w - 2, "▔", fg); + x + w +} + +fn draw_routing(input, st, x, y) { + let playing = get(input, "playing", !input.paused && input.track_title != ""); + let lit = playing || st.boot > 0.0; + let on = if lit { cyan() } else { cyan_mid() }; + let dim = if lit { cyan_mid() } else { 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" }; + + // source -> decoder -> volume + let x1 = this.tbox(x, y, src, on); + this.hl(x1, y + 1, 3, "─", dim); + let x2 = this.tbox(x1 + 3, y, if fmt == "" { "DECODE" } else { fmt }, on); + this.hl(x2, y + 1, 3, "─", dim); + let x3 = this.tbox(x2 + 3, y, "VOL " + vol, on); + + // volume -> tone -> amplifier -> speakers A / B + let ty = y + 4; + let drop_x = x3 - 3; + this.vl(drop_x, y + 3, ty - y - 2, "▏", dim); + this.hl(x + 24, ty + 1, drop_x - x - 24, "─", dim); + this.txt(drop_x, ty + 1, "┘", dim); + let tone_end = this.tbox(x + 16, ty, "TONE", on); + this.hl(tone_end, ty + 1, x + 24 - tone_end, "─", dim); + + // amplifier: a thin braille triangle pointing at the speakers + let AX = (x + 6) * 2; let AY = (ty + 1) * 4 + 2; + this.ln(AX, AY, AX + 16, AY - 6, on); + this.ln(AX, AY, AX + 16, AY + 6, on); + this.ln(AX + 16, AY - 6, AX + 16, AY + 6, on); + this.txt(x + 10, ty + 1, "AMP", on); + this.hl(x + 15, ty + 1, 1, "─", dim); + this.speaker(x, ty, on); + this.txt(x + 3, ty, "A", on); + this.speaker(x, ty + 2, dim); + this.txt(x + 3, ty + 2, "B", dim); + this.ln((x + 2) * 2, ty * 4 + 2, AX, AY, dim); + this.ln((x + 2) * 2, (ty + 2) * 4 + 2, AX, AY, dim); + x3 +} + +fn draw_transport(input, st, x, y) { + let word = if input.track_title == "" { "StoP" } else if input.paused { "PAUSE" } else { "PLAY" }; + let off = if st.boot > 0.0 { cyan() } else { cyan_ghost() }; + this.seg_text(x, y, word, 6, 2, cyan(), off, false); + let ly = y + 6; + let stereo = get(input, "level_l", 0.0) > 0.0 && (get(input, "level_l", 0.0) - get(input, "level_r", 0.0)).abs() > 0.001; + this.txt(x, ly, "TRACK", cyan_mid()); + this.txt(x + 11, ly, "STEREO", if stereo || st.boot > 0.0 { cyan() } else { cyan_ghost() }); + this.txt(x + transport_width() - 5, ly, "VOL", cyan_mid()); + let q = get(input, "queue_index", 0); + let qn = get(input, "queue_length", 0); + let qs = if q <= 0 { "-" } else if q > 99 { "--" } else { "" + q }; + let end = this.seg_text(x, ly + 1, qs, 4, 1, cyan(), off, false); + this.txt(end + 1, ly + 2, "/" + (if qn > 99 { "99+" } else { "" + qn }), cyan_mid()); + // volume right-aligned to the block's edge, "%" in the last column + let vs = "" + to_int(input.volume * 100.0 + 0.5); + let vx = x + transport_width() - 2 - (vs.len() * 5 - 1) - 1; + this.seg_text(vx, ly + 1, vs, 4, 1, cyan(), off, false); + this.txt(x + transport_width() - 2, ly + 2, "%", cyan()); +} + +// "PAUSE" in the segment font is the widest transport word. +fn transport_width() { 35 } + +// ---------- state ---------- + +fn advance_state(input) { + let st = input.state; + if !("boot" in st) { st = #{ boot: 0.9, spin: 0.0, over: 0.0, title: input.track_title }; } + let dt = get(input, "dt", 0.05); + st.boot = st.boot - dt; + st.spin = st.spin - dt; + st.over = st.over - dt; + if st.title != input.track_title { + st.title = input.track_title; + if input.track_title != "" { st.spin = 0.6; } + } + 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 +} + +// ---------- layouts ---------- + +fn render_full(input, st) { + let cmds = []; + let W = input.width; + let H = input.height; + let cw = mn(W - 4, 170); + let x0 = (W - cw) / 2; + let bands = panel_bands(input); + + let spec_h = clamp(H - 27, 8, 14); + let used = 7 + 1 + spec_h + 2 + 9; + let gap = clamp((H - used) / 5, 1, 2); + let y = clamp((H - used - gap * 4) / 2, 0, 3); + + let lamps_w = 18; + cmds.draw_counter(input, st, x0, y); + let meter_x = x0 + counter_width() + 4; + cmds.draw_meter(input, st, meter_x, y, x0 + cw - lamps_w - 4 - meter_x); + cmds.draw_lamps(input, st, bands, x0 + cw - lamps_w + 2, y); + + y += 7 + gap; + cmds.draw_status_row(input, st, x0, y, cw); + y += 1; + cmds.txt(x0, y, "▸", white_mid()); + cmds.draw_title(input, x0 + 2, y, cw - 2); + + y += 1 + gap; + let readout_w = 30; + let bw = clamp((cw - readout_w - 6) / 25, 3, 5); + let right = cmds.draw_analyzer(input, st, bands, x0, y, bw, spec_h); + let rx = right + mx((x0 + cw - right - 22) / 2, 3); + cmds.draw_readout(input, st, bands, rx, y + mx((spec_h - 10) / 2, 0)); + + y += spec_h + 2 + gap; + cmds.draw_balance(input, x0, y, 28); + cmds.draw_fans(input, bands, x0, y + 3, 28); + let routing_w = 40; + let tr_w = transport_width(); + let rx2 = x0 + 32 + mx((cw - 32 - routing_w - tr_w) / 2, 0); + cmds.draw_routing(input, st, rx2, y); + cmds.draw_transport(input, st, x0 + cw - tr_w, y); + + if input.show_clock { cmds.txt(W - input.clock.len() - 1, 0, input.clock, white_mid()); } + cmds +} + +fn render_compact(input, st) { + let cmds = []; + let W = input.width; + let H = input.height; + let bands = panel_bands(input); + 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); + cmds.draw_title(input, end + 3, 2, W - end - 4); + 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, white_mid()); + } + } else { + cmds.draw_title(input, 1, 0, W - 2 - clock_w); + top = 2; + if input.show_clock { cmds.txt(W - input.clock.len() - 1, 0, input.clock, 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 +} + +fn render(input) { + let st = advance_state(input); + let cmds = [#{ op: "clear", bg: 0 }]; + if input.width >= 20 && input.height >= 6 { + let body = if input.width >= 120 && input.height >= 34 { render_full(input, st) } else { render_compact(input, st) }; + for c in body { cmds.push(c); } + } + #{ commands: cmds, state: st } +} diff --git a/src/visualizer.rs b/src/visualizer.rs index ef0fefa..1feb68b 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: 1, + source: include_str!("visualizations/vfd_panel.rhai"), + }, ]; #[derive(Debug, Clone)] @@ -118,6 +125,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) { @@ -344,9 +357,136 @@ 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_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 +572,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 +614,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 +703,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 +726,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, HLine { x: u16, @@ -531,6 +735,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, VLine { x: u16, @@ -539,6 +744,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, Rect { x: u16, @@ -548,6 +754,7 @@ enum DrawCommand { ch: String, fg: Color, bg: Color, + mods: Modifier, }, Trace { x: u16, @@ -557,6 +764,7 @@ enum DrawCommand { fg: Color, line_fg: Color, bg: Color, + mods: Modifier, }, Text { x: u16, @@ -564,6 +772,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 +805,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 +814,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 +823,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 +832,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 +842,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 +853,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 +861,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 +900,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 +934,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 +948,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 +963,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 +987,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 +1013,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 +1035,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 +1212,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::() { @@ -971,6 +1414,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 +1757,336 @@ 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); + } + } + } + } + + #[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.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("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); + } }