import { Show, createEffect, createMemo } from "solid-js"; import { player } from "../lib/player"; import { TICK_MS } from "../lib/player/store"; import { wavePath, type TrackPeaks, type WaveformTuning } from "../lib/player/peaks"; /** * The transport row, drawn as the track. * * There is no hairline any more. What used to be a 2 px rule with a caret on it is now a thousand bars * mirrored about the same horizontal axis that rule sat on, so the row says what it always said — *here is * where you are, along this track* — and also what the track is made of. The bars go up and down from the * middle, which is the axis the thumb used to ride and the only line the row has. * * It is the row's drawing rather than a picture under it: the slider is still the control, still underneath * and still what a drag reaches, still carrying the `--pb-fill` this is drawn from — one computation of "how * far along", three readers, because two derivations of that number would agree almost always and "almost * always" is the failure worth designing out. So this is `aria-hidden`, `pointer-events: none`, out of the * tab order: the waveform is what you read while you drag, not another thing to drag. * * The played part is the same path drawn again in the accent and cut to the position with a `clip-path`; the * caret is the boundary stated as a line, which is the version that survives a chorus where the bars either * side of it are the same height. * * Same artifact as everything else (`store.peaks()`), same `wavePath`, same level rules, and the path stops * at `filled` — a bar standing where the pass has not been would be a claim about audio nobody has read, so * a fold in progress arrives as the silhouette growing from the left. */ /** * How many bars the row draws — a count the drawing asks for, not one derived from its width. * * Fixed on purpose. A width-driven budget is the right model for a raster that cannot show more columns than * it has pixels, and it was the old row's; here the point is the *reading*, and a fixed count makes the row * the same picture on a phone and on an ultrawide, which is what you want from a shape you might be * recognising a passage by. It stays a knob through the one that already exists: `barsPerPx` is applied to * this budget, so `waveformTuning({ barsPerPx: 2 })` asks for two thousand bars and `{ barsPerPx: 0 }` * draws every bucket the fold measured. * * 1000 closed rectangles is 4000 segments, drawn as one `` rather than 1000 elements. Both numbers * have history here: the row's first version had 144 elements and cost a 252 ms task per arrival, and the * unbudgeted `bars` shape cost 94,932 segments and 4,501 ms of GPU process * (`docs/research/player-waveform.md`). A thousand is two orders of magnitude under the second and one * element rather than a hundred and forty-four. */ const WAVE_BARS = 1000; /** The viewBox height, in the path's own units. CSS decides the real height. */ const WAVE_UNITS = 20; /** * How long the bars take to grow in, and how. Outward and decelerating: the row should look like it is * arriving rather than like it is being wound up. * * Short on purpose. The row is under a transport, not a hero image, and the arrival matters most while the * first audio is starting — an animation that outlasts the user's glance is the one the last design was * criticised for. */ /** Whether two renderings of the row are the same drawing — see the `equals` on the memo below. */ const sameDrawing = (a: Drawing | null, b: Drawing | null) => a?.d === b?.d && a?.id === b?.id && a?.idle === b?.idle && a?.viewBox === b?.viewBox; /** * Whether two tunings ask for the same drawing. * * A key-by-key compare over everything except the knobs the path cannot see. `loopEdge` is the loop * region's treatment — brackets, caps, ticks — and it rides on the same persisted bag as the drawing * knobs because there is one waveform setting and two readers of it; a press of it used to rebuild a * thousand-bar path that came out byte-identical (`WASTED_RECOMPUTE`, five in a second in the knob * test alone). * * An ignore list rather than a pick, and deliberately: a key nobody thought to name takes part in the * comparison, so the failure mode of `wavePath` one day reading a new knob is one rebuild too many * rather than a row that stopped redrawing. * * Every field is a primitive or absent, so `Object.is` per key is the whole comparison and there is * nothing deeper to walk. */ const LOOK_ONLY: (keyof WaveformTuning)[] = ["loopEdge"]; const sameTuning = (a: WaveformTuning, b: WaveformTuning): boolean => { const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set; for (const key of keys) { if (LOOK_ONLY.includes(key)) continue; if (!Object.is(a[key], b[key])) return false; } return true; }; const GROW_MS = 220; const GROW_EASE = "cubic-bezier(0.22, 0.8, 0.28, 1)"; /** * The row before there is a track: the same drawing machinery, with nothing measured in it. * * An empty bar used to be an empty row, which made the arrival impossible to see — the grow played on a row * that had only just appeared, at the moment the listener was looking at the artwork instead. So the row * exists from the start, holding a placeholder silhouette small enough that a real track arriving is * unmistakably *more*, and the grow plays twice where it used to play once: once into the placeholder, and * again into the track. * * The line it must not cross is the one the whole feature is built on — never draw ink where nobody has * listened — and the discriminator is drawn to that line rather than to "no bytes": the placeholder shows * whenever there is *no measurement*, and a measurement of nothing is still a measurement, so a track that * folds out silent draws a blank row and not a waiting motif. Placeholder means "nothing has been read yet"; * blank means "it was read, and there is nothing there". Conflating them would let a silent track borrow the * look of an unbuilt one, which is the same category of error as drawing bars past the fold. * * That is a revision, and the reason for it is worth keeping: the first version keyed the placeholder to * "no bytes", which looked right in the component and flickered in the app — bytes arrive a moment before the * fold's first report, so the row blanked and came back on every load, and a row that blinks while a track * decodes is worse than either choice on its own. Loading is not silence, and now the row says so. * * It is a placeholder rather than a fake waveform in two other ways too: it is drawn in a dimmer ink (see * `[data-idle]` in `App.css`), and it has no played layer and no caret, because with no track there is no * position to state and an accent line at bucket zero would be claiming one. */ const IDLE_BUCKETS = WAVE_BARS; /** What the row renders: one path, the measurement it came from, and whether that measurement is a wait. */ interface Drawing { d: string; id: string; idle: boolean; viewBox: string; } /** * The placeholder's shape, as a real artifact. * * Not a hand-written path string: building a `TrackPeaks` and running it through `wavePath` means the idle * row honours the same `shape`, `barRatio`, `minBar` and point budget as a real one, so the transition from * placeholder to track is a change of heights in one drawing rather than a swap between two drawings. The * levels are deterministic from the bucket index — a motif, not noise — because a row that reshuffled itself * on every re-render would be the pulsing row all over again, and because "reproducible" is what makes the * test below able to assert *this* shape rather than merely *a* shape. * * The amplitudes sit near −25 dBFS, which under the shipped `floorDb`/`curve` lands at roughly a fifth of the * row: short enough to read as waiting, tall enough to see the grow. */ const IDLE_PEAKS: TrackPeaks = (() => { const values = new Int16Array(IDLE_BUCKETS * 2); for (let b = 0; b < IDLE_BUCKETS; b++) { const slow = Math.sin((b / IDLE_BUCKETS) * Math.PI * 2 * 2.5); const fine = Math.sin(b * 0.083 + 1.7); const q15 = Math.round((0.055 + 0.017 * slow + 0.008 * fine) * 32767); values[b * 2] = -q15; values[b * 2 + 1] = q15; } return { id: "idle", format: "idle", seconds: IDLE_BUCKETS, sampleRate: 44100, rate: 1, buckets: IDLE_BUCKETS, filled: IDLE_BUCKETS, channels: 2, stride: 1, values, ms: 0, fold: "idle", }; })(); export const WaveformRow = (props: { fill: string }) => { const store = player(); /** * The drawing's two inputs, each stopped by its own equality gate. * * They used to be read straight inside `drawing` below, and that made the expensive memo depend on * whatever those reads depend on rather than on what the drawing depends on. `peaks()` reads which * track is current, so pressing `n` invalidated a thousand-bar path build — eight of them in a * second, all eight producing the same path (`WASTED_RECOMPUTE`, ~2 ms each, discarded by the gate * below); and `waveformTuning()` hands back a fresh object on every write, so a knob nudged to the * value it already had rebuilt it too. * * So the cheap reads live here, where their own equality can stop the invalidation, and the path * build below only runs when a *drawing* input moved: `Object.is` is enough for the artifact (the * fold republishes by reference, and a re-fold arrives as a new object with a new `values` array), * while the tuning needs `sameTuning`, which knows the difference between a knob that redraws and * one that only re-looks. */ const measured = createMemo( () => { const peaks = store.peaks(); return peaks && peaks.buckets > 0 && peaks.filled > 0 ? peaks : null; }, { name: "pb-wave-measured" }, ); const tuning = createMemo(() => store.waveformTuning(), { name: "pb-wave-tuning", equals: sameTuning, }); const drawing = createMemo( () => { // "Measured nothing yet" — no artifact, or an artifact the pass has not reached into. The placeholder's // whole meaning, so it is one condition rather than two ("no bytes" and "no artifact") that have to // agree — and both of them mean the same thing to the listener, which is the only reader that matters. const measuredArtifact = measured(); if (!measuredArtifact) { const d = wavePath(IDLE_PEAKS, { ...tuning(), // Not normalised to itself: `normalize: "track"` would scale the placeholder up to full height and // throw away the whole reason the levels are where they are — it is a motif, not a master to be // measured against. normalize: "none", height: WAVE_UNITS, widthPx: WAVE_BARS, to: IDLE_PEAKS.filled, }); return d ? { d, id: IDLE_PEAKS.id, idle: true, viewBox: `0 0 ${IDLE_PEAKS.buckets} ${WAVE_UNITS}`, } : null; } // The ink stops where the measurement does. Not decoration that can be filled in later: a bar // standing where the pass has not been is a claim about audio nobody has read. const filled = Math.min(measuredArtifact.filled, measuredArtifact.buckets); const d = wavePath(measuredArtifact, { ...tuning(), // The shape is the knob's, so `envelope`, `bars` and `blocks` are all one keystroke away; the // default is the mirrored bars, which is what a waveform over an axis looks like. `blocks` remains // for anyone who wants the silhouette stood on a floor instead. height: WAVE_UNITS, widthPx: WAVE_BARS, to: filled, }); if (!d) return null; // measured something, and all of it silence: nothing to draw // The id rides along so the arrival can be recognised as *a different measurement* rather than as a // new path string: the fold reports many times per track, and a grow that restarted on every slice // would be a row that pulses while it fills. return { d, id: measuredArtifact.id, idle: false, viewBox: `0 0 ${measuredArtifact.buckets} ${WAVE_UNITS}`, }; }, { name: "pb-wave", // Content equality, because the memo builds a fresh object on every run and the fields *are* the // output: when all four are the same there is nothing for a subscriber to do. Without this the row // tripped `UNSTABLE_MEMO_OUTPUT` — the equality gate never closes, so the `Show` and the grow effect // re-run on every upstream change, which for a row that re-renders as the fold reports is every slice. // Safe in a way a generic shallow compare is not: `d` is a string, so a real change to the drawing is // never mistaken for equality. equals: sameDrawing, }, ); // How long the playhead glides between position samples — one tick, except when the change it is being // asked to draw was a *seek*. // // The glide is justified by arithmetic: the clock advances linearly, so interpolating one sample across the // interval before the next lands on the truth. A seek voids the premise — pressing `4` means *be at 40 %*, // not *watch the caret travel to 40 %* — so the row asks the store whether the change it is about to draw // came from a will rather than from playback, and draws that one as a jump. Half a tick is the window: the // seek's own repaint lands inside it, and the next sample, ~250 ms later, is by then a tick and glides. // // It has to depend on the position itself, which is why the fill is read here at all: the memo is asked // "how should *this* change be drawn", and a memo that did not read it would sit on whatever answer the // last seek gave and stop gliding for the rest of the track. const smooth = createMemo(() => { const at = Number(props.fill); if (!Number.isFinite(at)) return `${TICK_MS}ms`; // nothing to glide to: draw it where it is const sinceSeek = (globalThis.performance?.now() ?? Date.now()) - store.lastSeekAt(); return sinceSeek <= TICK_MS / 2 ? "0ms" : `${TICK_MS}ms`; }); /** The row's element, once the `Show` has made it. The grow is played on this, and nothing else. */ let row: HTMLSpanElement | undefined; /** Which measurement has already been played in, so a re-publish is not an arrival. */ let grown = ""; // The view is built before the effect below is created, and that ordering is load-bearing rather than // stylistic: the effect needs the element `Show` creates, and Solid runs effects in creation order. A // `createEffect` declared up here would run first, find `row` still undefined on the arrival that matters, // and the row would silently never grow. const view = ( {(s) => ( /* Two layers of one path, the second cut to the playhead by a `clip-path` reading `--pb-fill` — the same contract the row's two hairlines used to hold between themselves, so the mechanism is unchanged and only what it separates has moved. The cost per position tick is the clip and nothing else: the path is built once per measurement and `position` moving does not touch it. Measured on the row, redrawing the shape per tick was ~3 ms of main thread a frame on a throttled CPU; moving a clip is free by comparison. A `clip-path` rather than a mask, which was also measured: masks put Blink onto the compositor with a surface of their own and cost more than the thing they were cutting. */ // `--pb-tick` is the cadence the position arrives on, from the code that sets it: the played layer // and the caret glide across exactly one interval, linearly, which is why a 4 Hz clock reads as // motion — see the `.pb-wave-played` rule in App.css for the arithmetic, and `TICK_MS` for why the // stylesheet is not allowed to guess at this number. )} ); // The bars grow into their final form when a measurement lands: one composited `scaleY` on the row, from // the axis the bars are mirrored about, over a fifth of a second. It is an animation on *one element* — // the drawing is not touched, no path is rebuilt, no height is interpolated — which is the whole reason it // is affordable here and was not in the row's first version, where the same idea meant 144 animated paths // and a 252 ms task per arrival (`docs/research/player-waveform.md`). What it costs is one call to // `animate` per track, and that is measured rather than assumed: `npm run perf:wave:playhead`. // // Deliberately keyed on the measurement rather than on the path: the fold reports a slice at a time, and // restarting the grow on each report would make the row pulse while it fills — the exact failure the old // lane design had to be argued out of. createEffect(drawing, (s) => { if (!s || !row) return; if (grown === s.id) return; grown = s.id; // An element that grows is motion; motion is what `prefers-reduced-motion` asks out. The row simply // appears, which is what it did before this existed. if (globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return; // jsdom has no Web Animations; the guard is also the honest answer for any engine without it. row.animate?.([{ transform: "scaleY(0)" }, { transform: "scaleY(1)" }], { duration: GROW_MS, easing: GROW_EASE, fill: "none", }); }); return view; }; export default WaveformRow;