Skip to content

Build your personal knowledge base with Trilium Notes

client/audio player: add a basic audio spectrum visualization

Adorian Doran02a1797619fc
diff --git a/apps/client/src/widgets/type_widgets/file/Audio.tsx b/apps/client/src/widgets/type_widgets/file/Audio.tsx
index 07b8eb7da9..fb2d5e2a87 100644
--- a/apps/client/src/widgets/type_widgets/file/Audio.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Audio.tsx
@@ -7,6 +7,7 @@ import { getUrlForDownload } from "../../../services/open";
import Icon from "../../react/Icon";
import NoItems from "../../react/NoItems";
import { loadWaveform } from "./audio_waveform";
+import { AudioVisualizer } from "./AudioVisualizer";
import { MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";
import { WaveformSeekBar } from "./WaveformSeekBar";
@@ -56,7 +57,8 @@ export default function AudioPreview({ note, noteContext, isVisible = true }: {
onEmptied={syncPlaying}
onError={onError}
/>
- <div className="audio-preview-icon-wrapper">
+ <div className="audio-preview-visualization-wrapper">
+ <AudioVisualizer mediaRef={audioRef} isPlaying={playing} />
<Icon icon="bx bx-music" className="audio-preview-icon" />
</div>
<div className="media-preview-controls">
diff --git a/apps/client/src/widgets/type_widgets/file/AudioVisualizer.css b/apps/client/src/widgets/type_widgets/file/AudioVisualizer.css
new file mode 100644
index 0000000000..24cb05fc4c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/AudioVisualizer.css
@@ -0,0 +1,31 @@
+.audio-preview-visualization-wrapper {
+ /* Gradient endpoints — tune to taste. Read by the canvas renderer via getComputedStyle. */
+ --audio-visualizer-low-color: rgb(206, 206, 206);
+ --audio-visualizer-high-color: black;
+
+ flex-grow: 1;
+ min-height: 0;
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ .audio-preview-icon {
+ /* Same size/position as before; layered above the canvas. */
+ font-size: 8em;
+ opacity: 0.6;
+ position: relative;
+ z-index: 1;
+ }
+
+ .audio-visualizer-canvas {
+ /* Bottom half of the wrapper, full width, behind the icon and ignoring pointer input. */
+ position: absolute;
+ left: 0;
+ bottom: 0;
+ width: 100%;
+ height: 50%;
+ z-index: 0;
+ pointer-events: none;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/file/AudioVisualizer.tsx b/apps/client/src/widgets/type_widgets/file/AudioVisualizer.tsx
new file mode 100644
index 0000000000..90c48965cd
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/AudioVisualizer.tsx
@@ -0,0 +1,155 @@
+import "./AudioVisualizer.css";
+
+import { RefObject } from "preact";
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+import { useTriliumEvent } from "../../react/hooks";
+import { buildRowColors, cellIntensity, computeColumnAmplitudes, computeGrid, hasMotion, resizePreserving, smoothAmplitudes, type VisualizerGrid } from "./audio_visualizer";
+import { resolveCssColor } from "./css_color";
+import { useAudioAnalyser } from "./useAudioAnalyser";
+
+/** Cell geometry, in CSS pixels. The grid fits as many of these as the canvas allows. */
+const CELL_SIZE = 8;
+const CELL_GAP = 2;
+/** Slice of the spectrum spread across the bars — broad (not voice-specific). The very top bins are usually
+ * silent, so the top quarter is dropped to keep the bars lively. */
+const LO_FRACTION = 0;
+const HI_FRACTION = 0.75;
+/** rAF easing: fast attack, slower release, for a snappy but smooth meter. */
+const RISE = 0.5;
+const FALL = 0.15;
+
+const DEFAULT_LOW_COLOR = "rgb(0, 0, 0)";
+const DEFAULT_HIGH_COLOR = "rgb(136, 136, 136)";
+
+/**
+ * Realtime frequency visualizer: a bottom-aligned grid of square cells where each column is a frequency bar that
+ * lights up from the bottom and each cell takes a single colour from a low→high vertical gradient. Runs an rAF
+ * loop only while playing (and briefly after, to animate the decay); when not playing every column rests at zero.
+ */
+export function AudioVisualizer({ mediaRef, isPlaying }: { mediaRef: RefObject<HTMLAudioElement>; isPlaying: boolean }) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const getFrequencyData = useAudioAnalyser(mediaRef);
+ const [ size, setSize ] = useState({ width: 0, height: 0 });
+ const [ colors, setColors ] = useState({ low: DEFAULT_LOW_COLOR, high: DEFAULT_HIGH_COLOR });
+
+ // The render loop reads the latest props/state through refs so it never has to be torn down and restarted.
+ const isPlayingRef = useRef(isPlaying);
+ isPlayingRef.current = isPlaying;
+ const sizeRef = useRef(size);
+ sizeRef.current = size;
+ const colorsRef = useRef(colors);
+ colorsRef.current = colors;
+ // Reused per-frame buffers (per column / per row) so the loop allocates nothing once warm.
+ const displayRef = useRef<Float32Array>(new Float32Array(0));
+ const targetRef = useRef<Float32Array>(new Float32Array(0));
+ const rowColorsRef = useRef<{ rows: number; low: string; high: string; colors: string[] }>({ rows: -1, low: "", high: "", colors: [] });
+ const rafRef = useRef(0);
+
+ // Track the canvas' CSS size so the loop can render at device-pixel resolution and re-lay-out the grid.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ const observer = new ResizeObserver(() => setSize({ width: canvas.clientWidth, height: canvas.clientHeight }));
+ observer.observe(canvas);
+ setSize({ width: canvas.clientWidth, height: canvas.clientHeight });
+ return () => observer.disconnect();
+ }, []);
+
+ // Resolve the theme's gradient colours once on mount and on any theme change (cached; never read per frame).
+ const refreshColors = useCallback(() => {
+ const host = canvasRef.current?.parentElement ?? canvasRef.current;
+ if (!host) return;
+ setColors({
+ low: resolveCssColor(host, "--audio-visualizer-low-color", DEFAULT_LOW_COLOR),
+ high: resolveCssColor(host, "--audio-visualizer-high-color", DEFAULT_HIGH_COLOR)
+ });
+ }, []);
+ useEffect(refreshColors, [ refreshColors ]);
+ useTriliumEvent("themeChanged", refreshColors);
+
+ const renderFrame = useCallback(() => {
+ const canvas = canvasRef.current;
+ const { width, height } = sizeRef.current;
+ const ctx = canvas?.getContext("2d");
+ if (!canvas || !ctx || width <= 0 || height <= 0) {
+ rafRef.current = 0;
+ return;
+ }
+
+ const dpr = window.devicePixelRatio || 1;
+ if (canvas.width !== Math.round(width * dpr) || canvas.height !== Math.round(height * dpr)) {
+ canvas.width = Math.round(width * dpr);
+ canvas.height = Math.round(height * dpr);
+ }
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+
+ const grid = computeGrid(width, height, CELL_SIZE, CELL_GAP);
+ // Keep the per-column buffers sized to the grid, preserving values across resizes to avoid a jump.
+ if (displayRef.current.length !== grid.cols) {
+ displayRef.current = resizePreserving(displayRef.current, grid.cols);
+ targetRef.current = new Float32Array(grid.cols);
+ }
+ // Rebuild the cached row gradient only when the rows or colours actually change.
+ const cache = rowColorsRef.current;
+ if (cache.rows !== grid.rows || cache.low !== colorsRef.current.low || cache.high !== colorsRef.current.high) {
+ rowColorsRef.current = {
+ rows: grid.rows,
+ low: colorsRef.current.low,
+ high: colorsRef.current.high,
+ colors: buildRowColors(colorsRef.current.low, colorsRef.current.high, grid.rows)
+ };
+ }
+
+ const spectrum = isPlayingRef.current ? getFrequencyData() : null;
+ const targets = spectrum ? computeColumnAmplitudes(spectrum, targetRef.current, LO_FRACTION, HI_FRACTION) : null;
+ smoothAmplitudes(displayRef.current, targets, RISE, FALL);
+
+ drawGrid(ctx, width, height, grid, displayRef.current, rowColorsRef.current.colors);
+
+ // Keep animating while playing, or while bars are still settling toward zero after a pause.
+ rafRef.current = isPlayingRef.current || hasMotion(displayRef.current) ? requestAnimationFrame(renderFrame) : 0;
+ }, [ getFrequencyData ]);
+
+ // Start the loop when playback starts; it self-terminates once paused and fully decayed.
+ useEffect(() => {
+ if (isPlaying && rafRef.current === 0) {
+ rafRef.current = requestAnimationFrame(renderFrame);
+ }
+ }, [ isPlaying, renderFrame ]);
+
+ // While idle (loop stopped), redraw a single frame on size/colour changes so a resize doesn't leave a
+ // stretched/stale canvas. When playing, the running loop already picks these up each frame.
+ useEffect(() => {
+ if (rafRef.current === 0) {
+ renderFrame();
+ }
+ }, [ size, colors, renderFrame ]);
+
+ useEffect(() => () => {
+ if (rafRef.current) {
+ cancelAnimationFrame(rafRef.current);
+ }
+ }, []);
+
+ return <canvas ref={canvasRef} class="audio-visualizer-canvas" aria-hidden="true" />;
+}
+
+function drawGrid(ctx: CanvasRenderingContext2D, width: number, height: number, grid: VisualizerGrid, amplitudes: Float32Array, rowColors: string[]) {
+ ctx.clearRect(0, 0, width, height);
+ const { cols, rows, offsetX } = grid;
+ const stride = CELL_SIZE + CELL_GAP;
+ // Iterate row-by-row so the (per-row) fill colour is set once rather than per cell; each cell's alpha is its
+ // intensity, fading the leading cell between off and on.
+ for (let r = 0; r < rows; r++) {
+ ctx.fillStyle = rowColors[r];
+ const y = height - CELL_SIZE - r * stride;
+ for (let c = 0; c < cols; c++) {
+ const intensity = cellIntensity(amplitudes[c], rows, r);
+ if (intensity <= 0) continue;
+ ctx.globalAlpha = intensity;
+ ctx.fillRect(offsetX + c * stride, y, CELL_SIZE, CELL_SIZE);
+ }
+ }
+ ctx.globalAlpha = 1;
+}
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.css b/apps/client/src/widgets/type_widgets/file/MediaPlayer.css
index 2564f45325..7840b3d5ec 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.css
+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.css
@@ -99,13 +99,4 @@
height: 100%;
display: flex;
flex-direction: column;
-
- .audio-preview-icon-wrapper {
- flex-grow: 1;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 8em;
- opacity: 0.6;
- }
}
diff --git a/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx
index 7b545aceed..1a3a4fa88b 100644
--- a/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx
+++ b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n";
import { useTriliumEvent } from "../../react/hooks";
+import { resolveCssColor } from "./css_color";
import { formatTime } from "./MediaPlayer";
/** Below this normalized amplitude a bucket is considered silence and painted with the silence color. */
@@ -224,23 +225,10 @@ interface WaveformColors {
const DEFAULT_COLORS: WaveformColors = { played: "#4caf9d", unplayed: "#5a5a5a", silence: "#333333" };
function readColors(canvas: HTMLCanvasElement): WaveformColors {
+ const host = canvas.parentElement ?? canvas;
return {
- played: resolveColor(canvas, "--waveform-played-color", DEFAULT_COLORS.played),
- unplayed: resolveColor(canvas, "--waveform-unplayed-color", DEFAULT_COLORS.unplayed),
- silence: resolveColor(canvas, "--waveform-silence-color", DEFAULT_COLORS.silence)
+ played: resolveCssColor(host, "--waveform-played-color", DEFAULT_COLORS.played),
+ unplayed: resolveCssColor(host, "--waveform-unplayed-color", DEFAULT_COLORS.unplayed),
+ silence: resolveCssColor(host, "--waveform-silence-color", DEFAULT_COLORS.silence)
};
}
-
-/** Resolve a CSS custom property to a concrete color, even when the theme defines it through nested `var()`
- * references (which `getPropertyValue` returns unresolved). A throwaway element inherits the canvas' cascade,
- * so the browser's style engine substitutes the variables; we read back the computed `color`. */
-function resolveColor(canvas: HTMLCanvasElement, name: string, fallback: string): string {
- const host = canvas.parentElement ?? canvas;
- const probe = document.createElement("span");
- probe.style.color = `var(${name}, ${fallback})`;
- probe.style.display = "none";
- host.appendChild(probe);
- const resolved = getComputedStyle(probe).color;
- host.removeChild(probe);
- return resolved || fallback;
-}
diff --git a/apps/client/src/widgets/type_widgets/file/audio_visualizer.spec.ts b/apps/client/src/widgets/type_widgets/file/audio_visualizer.spec.ts
new file mode 100644
index 0000000000..4fa266829c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/audio_visualizer.spec.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+
+import { buildRowColors, cellIntensity, computeColumnAmplitudes, computeGrid, hasMotion, parseRgb, resizePreserving, smoothAmplitudes } from "./audio_visualizer";
+
+describe("computeGrid", () => {
+ it("fits as many cells as the size allows and centres horizontally", () => {
+ // stride = 21 + 4 = 25. Width 100 → floor((100+4)/25) = 4 cols; grid spans 4*25-4 = 96, centred → 2px.
+ const grid = computeGrid(100, 50, 21, 4);
+ expect(grid.cols).toBe(4);
+ expect(grid.rows).toBe(2); // floor((50+4)/25) = 2
+ expect(grid.offsetX).toBeCloseTo(2);
+ });
+
+ it("returns an empty grid for non-positive sizes", () => {
+ expect(computeGrid(0, 0, 21, 4)).toEqual({ cols: 0, rows: 0, offsetX: 0 });
+ expect(computeGrid(10, 10, 0, 0)).toEqual({ cols: 0, rows: 0, offsetX: 0 });
+ });
+});
+
+describe("parseRgb", () => {
+ it("parses rgb()/rgba() and hex forms", () => {
+ expect(parseRgb("rgb(10, 20, 30)")).toEqual([ 10, 20, 30 ]);
+ expect(parseRgb("rgba(255, 128, 0, 0.5)")).toEqual([ 255, 128, 0 ]);
+ expect(parseRgb("#ff8800")).toEqual([ 255, 136, 0 ]);
+ expect(parseRgb("#abc")).toEqual([ 170, 187, 204 ]);
+ });
+
+ it("clamps out-of-range channels and falls back to black on garbage", () => {
+ expect(parseRgb("rgb(300, -5, 999)")).toEqual([ 255, 0, 255 ]);
+ expect(parseRgb("not-a-color")).toEqual([ 0, 0, 0 ]);
+ });
+});
+
+describe("buildRowColors", () => {
+ it("interpolates from the low colour at the bottom to the high colour at the top", () => {
+ const colors = buildRowColors("rgb(0, 0, 0)", "rgb(200, 200, 200)", 3);
+ expect(colors).toHaveLength(3);
+ expect(colors[0]).toBe("rgb(0, 0, 0)"); // bottom = low
+ expect(colors[1]).toBe("rgb(100, 100, 100)"); // midpoint
+ expect(colors[2]).toBe("rgb(200, 200, 200)"); // top = high
+ });
+
+ it("handles the single-row and empty cases", () => {
+ expect(buildRowColors("rgb(10, 10, 10)", "rgb(90, 90, 90)", 1)).toEqual([ "rgb(10, 10, 10)" ]);
+ expect(buildRowColors("rgb(0, 0, 0)", "rgb(1, 1, 1)", 0)).toEqual([]);
+ });
+});
+
+describe("computeColumnAmplitudes", () => {
+ it("downsamples to one normalized peak per column over the selected window", () => {
+ // 8 bins; full window; 2 columns → first column = max(bins 0..3), second = max(bins 4..7).
+ const freq = new Uint8Array([ 0, 51, 0, 0, 0, 0, 255, 0 ]);
+ const out = computeColumnAmplitudes(freq, new Float32Array(2), 0, 1);
+ expect(out[0]).toBeCloseTo(51 / 255);
+ expect(out[1]).toBeCloseTo(1);
+ });
+
+ it("restricts to the [loFraction, hiFraction] slice of the spectrum", () => {
+ // Energy only in the top half; with a window of the bottom half it reads as silent.
+ const freq = new Uint8Array([ 0, 0, 0, 0, 200, 200, 200, 200 ]);
+ const out = computeColumnAmplitudes(freq, new Float32Array(1), 0, 0.5);
+ expect(out[0]).toBe(0);
+ });
+
+ it("guards empty input", () => {
+ expect(Array.from(computeColumnAmplitudes(new Uint8Array(0), new Float32Array(3), 0, 1))).toEqual([ 0, 0, 0 ]);
+ });
+});
+
+describe("smoothAmplitudes", () => {
+ it("rises fast and falls slow toward the target", () => {
+ const current = new Float32Array([ 0, 1 ]);
+ smoothAmplitudes(current, new Float32Array([ 1, 0 ]), 0.5, 0.1);
+ expect(current[0]).toBeCloseTo(0.5); // rose by rise factor
+ expect(current[1]).toBeCloseTo(0.9); // fell by fall factor
+ });
+
+ it("decays to exactly zero when the target is null (paused)", () => {
+ const current = new Float32Array([ 0.5 ]);
+ for (let i = 0; i < 200; i++) smoothAmplitudes(current, null, 0.5, 0.2);
+ expect(current[0]).toBe(0);
+ expect(hasMotion(current)).toBe(false);
+ });
+});
+
+describe("cellIntensity", () => {
+ it("saturates cells inside the bar and fades the leading one", () => {
+ // amplitude 0.35 over 10 rows → fill 3.5: rows 0-2 fully on, row 3 half-lit, rows 4+ off.
+ expect(cellIntensity(0.35, 10, 0)).toBe(1);
+ expect(cellIntensity(0.35, 10, 2)).toBe(1);
+ expect(cellIntensity(0.35, 10, 3)).toBeCloseTo(0.5);
+ expect(cellIntensity(0.35, 10, 4)).toBe(0);
+ });
+
+ it("is zero for a silent column", () => {
+ expect(cellIntensity(0, 10, 0)).toBe(0);
+ });
+});
+
+describe("resizePreserving", () => {
+ it("preserves overlapping values when growing or shrinking", () => {
+ // Float32-exact values so the round-trip through Float32Array compares exactly.
+ const grown = resizePreserving(new Float32Array([ 0.5, 0.25 ]), 4);
+ expect(Array.from(grown)).toEqual([ 0.5, 0.25, 0, 0 ]);
+ const shrunk = resizePreserving(new Float32Array([ 0.5, 0.25, 0.75 ]), 2);
+ expect(Array.from(shrunk)).toEqual([ 0.5, 0.25 ]);
+ });
+
+ it("returns the same array when the length is unchanged", () => {
+ const arr = new Float32Array([ 1, 2 ]);
+ expect(resizePreserving(arr, 2)).toBe(arr);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/file/audio_visualizer.ts b/apps/client/src/widgets/type_widgets/file/audio_visualizer.ts
new file mode 100644
index 0000000000..e0eac9dbfe
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/audio_visualizer.ts
@@ -0,0 +1,154 @@
+/**
+ * Pure geometry/colour/amplitude helpers for the audio sound-bar visualizer.
+ *
+ * The visualizer draws a grid of square cells: each column is a frequency bar that lights up from the bottom,
+ * and a cell's colour is a gradient between a "low" colour (bottom row) and a "high" colour (top row). The
+ * canvas adapter ({@link ../AudioVisualizer}) owns the rAF loop, canvas and analyser; everything here is pure
+ * and synchronous so it can be unit-tested without a DOM or the Web Audio API.
+ */
+
+export interface VisualizerGrid {
+ /** Number of columns (frequency bars) that fit the width. */
+ cols: number;
+ /** Number of cell rows that fit the height. */
+ rows: number;
+ /** Left padding, in CSS pixels, that horizontally centres the grid in the available width. */
+ offsetX: number;
+}
+
+/** Lay out a grid of `cellSize` squares separated by `gap`, as many as fit, centred horizontally. Rows are
+ * drawn bottom-up by the renderer, so any leftover height sits above the grid. */
+export function computeGrid(width: number, height: number, cellSize: number, gap: number): VisualizerGrid {
+ const stride = cellSize + gap;
+ if (stride <= 0) {
+ return { cols: 0, rows: 0, offsetX: 0 };
+ }
+ // n cells span n*cellSize + (n-1)*gap = n*stride - gap, which must fit the extent.
+ const cols = Math.max(0, Math.floor((width + gap) / stride));
+ const rows = Math.max(0, Math.floor((height + gap) / stride));
+ const gridWidth = cols > 0 ? cols * stride - gap : 0;
+ return { cols, rows, offsetX: Math.max(0, (width - gridWidth) / 2) };
+}
+
+/** Parse a CSS colour into [r, g, b]. Handles the `rgb()/rgba()` form that getComputedStyle returns, plus
+ * `#rgb`/`#rrggbb` for literal fallbacks. Unknown input yields black. */
+export function parseRgb(color: string): [number, number, number] {
+ const fn = color.match(/rgba?\(([^)]+)\)/i);
+ if (fn) {
+ const parts = fn[1].split(",").map((p) => parseFloat(p.trim()));
+ return [ clampByte(parts[0]), clampByte(parts[1]), clampByte(parts[2]) ];
+ }
+ const hex = color.trim().replace(/^#/, "");
+ if (hex.length === 3) {
+ return [ parseHex(hex[0] + hex[0]), parseHex(hex[1] + hex[1]), parseHex(hex[2] + hex[2]) ];
+ }
+ if (hex.length >= 6) {
+ return [ parseHex(hex.slice(0, 2)), parseHex(hex.slice(2, 4)), parseHex(hex.slice(4, 6)) ];
+ }
+ return [ 0, 0, 0 ];
+}
+
+/** Precompute one colour per row, interpolating from `lowColor` (row 0, bottom) to `highColor` (top row). The
+ * renderer reuses this so it never parses/interpolates colours per cell per frame. */
+export function buildRowColors(lowColor: string, highColor: string, rows: number): string[] {
+ if (rows <= 0) {
+ return [];
+ }
+ const low = parseRgb(lowColor);
+ const high = parseRgb(highColor);
+ const colors = new Array<string>(rows);
+ for (let r = 0; r < rows; r++) {
+ const t = rows > 1 ? r / (rows - 1) : 0;
+ const red = Math.round(low[0] + (high[0] - low[0]) * t);
+ const green = Math.round(low[1] + (high[1] - low[1]) * t);
+ const blue = Math.round(low[2] + (high[2] - low[2]) * t);
+ colors[r] = `rgb(${red}, ${green}, ${blue})`;
+ }
+ return colors;
+}
+
+/**
+ * Reduce a frequency spectrum to one 0..1 amplitude per column, writing into `out` (reused frame to frame). The
+ * `[loFraction, hiFraction]` window selects the slice of the spectrum to spread across the bars — broad by
+ * default rather than voice-specific. Each column takes the loudest bin in its slice so transients aren't
+ * averaged away.
+ */
+export function computeColumnAmplitudes(freqData: Uint8Array, out: Float32Array, loFraction: number, hiFraction: number): Float32Array {
+ const cols = out.length;
+ const n = freqData.length;
+ if (cols === 0 || n === 0) {
+ out.fill(0);
+ return out;
+ }
+ const lo = Math.max(0, Math.min(n - 1, Math.floor(n * loFraction)));
+ const hi = Math.min(n, Math.max(lo + 1, Math.floor(n * hiFraction)));
+ const span = hi - lo;
+ for (let c = 0; c < cols; c++) {
+ const start = lo + Math.floor((c / cols) * span);
+ const end = Math.max(start + 1, lo + Math.floor(((c + 1) / cols) * span));
+ let peak = 0;
+ for (let i = start; i < end && i < n; i++) {
+ if (freqData[i] > peak) peak = freqData[i];
+ }
+ out[c] = peak / 255;
+ }
+ return out;
+}
+
+/** Ease each displayed amplitude toward its target in place: a fast `rise` on attack, slower `fall` on release
+ * (VU-meter feel). `target` null means decay toward zero (paused). Snaps when within epsilon so a release
+ * actually reaches 0 (letting the render loop stop) instead of asymptoting forever. */
+export function smoothAmplitudes(current: Float32Array, target: Float32Array | null, rise: number, fall: number): void {
+ for (let c = 0; c < current.length; c++) {
+ const t = target ? target[c] : 0;
+ const cur = current[c];
+ const next = cur + (t - cur) * (t > cur ? rise : fall);
+ current[c] = Math.abs(t - next) < 0.001 ? t : next;
+ }
+}
+
+/**
+ * How "on" a cell is, 0..1, for a column's 0..1 amplitude — the fill level `amplitude*rows` minus the cell's
+ * row index, clamped. Cells fully within the bar return 1, cells above it 0, and the single leading cell a
+ * fraction. Drawn as the cell's alpha, this fades the leading cell between off and on as the bar's (eased)
+ * height sweeps across it, instead of cells popping on/off.
+ */
+export function cellIntensity(amplitude: number, rows: number, row: number): number {
+ const fill = amplitude * rows - row;
+ return fill <= 0 ? 0 : fill >= 1 ? 1 : fill;
+}
+
+/** Resize a per-column buffer to `length`, preserving overlapping values so a resize doesn't reset the bars. */
+export function resizePreserving(arr: Float32Array, length: number): Float32Array {
+ if (arr.length === length) {
+ return arr;
+ }
+ const next = new Float32Array(length);
+ next.set(arr.subarray(0, Math.min(arr.length, length)));
+ return next;
+}
+
+/** Whether any bar is still above the resting threshold — i.e. the render loop must keep animating the decay. */
+export function hasMotion(current: Float32Array): boolean {
+ for (let i = 0; i < current.length; i++) {
+ if (current[i] > 0.001) {
+ return true;
+ }
+ }
+ return false;
+}
+
+function clampByte(value: number): number {
+ if (!Number.isFinite(value)) {
+ return 0;
+ }
+ return Math.max(0, Math.min(255, Math.round(value)));
+}
+
+function parseHex(pair: string): number {
+ // Reject anything that isn't exactly two hex digits (e.g. "-c", which parseInt would read as -12).
+ if (!/^[0-9a-f]{2}$/i.test(pair)) {
+ return 0;
+ }
+ return parseInt(pair, 16);
+}
diff --git a/apps/client/src/widgets/type_widgets/file/css_color.ts b/apps/client/src/widgets/type_widgets/file/css_color.ts
new file mode 100644
index 0000000000..8817ddcffb
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/css_color.ts
@@ -0,0 +1,17 @@
+/**
+ * Resolve a CSS custom property to a concrete `rgb(...)` colour for canvas rendering.
+ *
+ * `getComputedStyle().getPropertyValue("--x")` returns the value unresolved when a theme defines it through
+ * nested `var()` references. Instead we attach a throwaway probe element that inherits `host`'s cascade and set
+ * its `color` to `var(--name, fallback)`; the browser's style engine substitutes the variables, and we read back
+ * the computed `color`. Falls back to `fallback` if the property is unset or the runtime returns nothing.
+ */
+export function resolveCssColor(host: HTMLElement, name: string, fallback: string): string {
+ const probe = document.createElement("span");
+ probe.style.color = `var(${name}, ${fallback})`;
+ probe.style.display = "none";
+ host.appendChild(probe);
+ const resolved = getComputedStyle(probe).color;
+ host.removeChild(probe);
+ return resolved || fallback;
+}
diff --git a/apps/client/src/widgets/type_widgets/file/useAudioAnalyser.ts b/apps/client/src/widgets/type_widgets/file/useAudioAnalyser.ts
new file mode 100644
index 0000000000..ce7532e648
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/file/useAudioAnalyser.ts
@@ -0,0 +1,80 @@
+import { RefObject } from "preact";
+import { useCallback, useEffect } from "preact/hooks";
+
+interface AnalyserBundle {
+ context: AudioContext;
+ analyser: AnalyserNode;
+ data: Uint8Array<ArrayBuffer>;
+}
+
+/**
+ * One AudioContext/analyser graph per media element. `createMediaElementSource` may be called only once per
+ * element, and the element is reused across notes, so the graph is built once and cached for the element's
+ * lifetime (a `null` entry records a failed/unsupported attempt so we don't retry it).
+ */
+const analyserCache = new WeakMap<HTMLMediaElement, AnalyserBundle | null>();
+
+const FFT_SIZE = 2048;
+const SMOOTHING = 0.8;
+
+/**
+ * Taps a media element's audio for frequency analysis and returns a getter for the current byte spectrum (or
+ * null before the graph exists / when unsupported). The graph is built lazily on first `play` — both because an
+ * AudioContext needs a user gesture to start, and because routing the element through the context means it only
+ * outputs while the context runs, so we resume it then.
+ *
+ * Caveat: once tapped, the element's audio flows through the AudioContext. On the desktop custom protocol the
+ * element is cross-origin, so the tap is blocked (tainted) — audio still plays, the spectrum just reads zero.
+ */
+export function useAudioAnalyser(mediaRef: RefObject<HTMLMediaElement>): () => Uint8Array | null {
+ useEffect(() => {
+ const media = mediaRef.current;
+ if (!media) return;
+ const onPlay = () => {
+ const bundle = ensureAnalyser(media);
+ if (bundle && bundle.context.state === "suspended") {
+ void bundle.context.resume();
+ }
+ };
+ media.addEventListener("play", onPlay);
+ return () => media.removeEventListener("play", onPlay);
+ }, [ mediaRef ]);
+
+ return useCallback(() => {
+ const media = mediaRef.current;
+ if (!media) return null;
+ const bundle = analyserCache.get(media);
+ if (!bundle) return null;
+ bundle.analyser.getByteFrequencyData(bundle.data);
+ return bundle.data;
+ }, [ mediaRef ]);
+}
+
+function ensureAnalyser(media: HTMLMediaElement): AnalyserBundle | null {
+ const cached = analyserCache.get(media);
+ if (cached !== undefined) {
+ return cached; // already built, or a recorded failure we shouldn't retry
+ }
+
+ const AudioContextCtor = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
+ if (!AudioContextCtor) {
+ analyserCache.set(media, null);
+ return null;
+ }
+ try {
+ const context = new AudioContextCtor();
+ const source = context.createMediaElementSource(media);
+ const analyser = context.createAnalyser();
+ analyser.fftSize = FFT_SIZE;
+ analyser.smoothingTimeConstant = SMOOTHING;
+ source.connect(analyser);
+ analyser.connect(context.destination);
+ const bundle: AnalyserBundle = { context, analyser, data: new Uint8Array(analyser.frequencyBinCount) };
+ analyserCache.set(media, bundle);
+ return bundle;
+ } catch {
+ // createMediaElementSource throws when the element's source is cross-origin/tainted; record the failure.
+ analyserCache.set(media, null);
+ return null;
+ }
+}