/** * The seek row, outside the app — for measuring its entrance and for looking at it. * * Everything geometry-related here is the app's own code (`barHeights`/`wavePath`, imported from * `/src/lib/player/peaks.ts` over the dev server) and the CSS is copied verbatim from `App.css`, so * what is rasterized and what is screenshotted here is what ships. Only the *peaks* are invented: a * synthetic envelope with loud and quiet sections, transients, a hole of silence and a fade, because * the interesting input is a shape with structure rather than noise, and because it has to be * reproducible for two runs to be comparable. * * Two doors: * * - `bench.run(name)` mounts one variant and samples rAF spacing while its entrance runs — that is * `dt`, which is what a listener feels. The driver adds `Performance.getMetrics` deltas around it, * which is what the renderer was charged. * - `?still=1&shape=bars&zoom=3` paints one settled row and stops, for a screenshot. Most of what * "looks bad" is not measurable, and the only honest way to argue about it is to look. * * `bench.block()` answers the compositor question: it jams the main thread mid-sweep so the caller can * screenshot through the jam — pixels that keep changing while script is stuck in a loop were never * that thread's to produce. */ import { barHeights, wavePath, sweepOf } from "/src/lib/player/peaks.ts"; /** The lane count the row used to be cut into. Kept here because `ship` has to mean *shipped*. */ const WAVE_LANES = 48; /** The row's viewBox height, matching `WAVE_UNITS` in `WaveformRow.tsx`. */ /** The row as the app lays it out: ~1400 CSS px wide, 20 tall, four minutes at 20 buckets/s. */ const ROW_PX = 1400; const WAVE_UNITS = 20; /** The row's bar budget, mirroring `WAVE_BARS` in `WaveformRow.tsx`. */ const WAVE_BARS = 1000; const SECONDS = 240; /** The app's current defaults, so that `?still=1` screenshots what ships. */ const TUNING = { normalize: "none", floorDb: -42, curve: 1.8, barRatio: 0.55, minBar: 0.6, shape: "envelope", barsPerPx: 1, sweepMs: 1400, height: WAVE_UNITS, widthPx: ROW_PX, }; /** What the row used to ship with, spelled out so the baselines below stay honest as defaults move. */ const SHIPPED = { barsPerPx: 4, curve: 1 }; /** A shape with sections, so thinning and staggering have something to be wrong about. */ function synthPeaks(seconds = SECONDS, rate = 20) { const buckets = Math.round(seconds * rate); const values = new Int16Array(buckets * 2); let s = 12345; const rnd = () => (s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff; for (let b = 0; b < buckets; b++) { const t = b / buckets; const section = t < 0.08 ? 0.12 : t < 0.3 ? 0.5 : t < 0.55 ? 0.86 : t < 0.62 ? 0.03 : t < 0.9 ? 0.7 : 0.3; const beat = Math.pow(Math.max(0, Math.sin(t * seconds * Math.PI * 2)), 6) * 0.35; const fade = t > 0.94 ? (1 - t) / 0.06 : 1; const a = Math.min(1, (section + beat) * fade * (0.75 + rnd() * 0.5)); const peak = Math.round(a * 32767); values[b * 2] = -peak; values[b * 2 + 1] = peak; } return { id: "bench", format: "flac", seconds, sampleRate: 44100, rate, buckets, filled: buckets, channels: 2, stride: 4, values, ms: 7, fold: "20/32/16/4/0", }; } const PEAKS = synthPeaks(); const SWEEP = sweepOf(TUNING); const svgNS = "http://www.w3.org/2000/svg"; const svgEl = (n, attrs = {}) => { const e = document.createElementNS(svgNS, n); for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v); return e; }; const span = (cls, style = {}) => { const e = document.createElement("span"); e.className = cls; for (const [k, v] of Object.entries(style)) { // `Object.assign(el.style, …)` silently drops custom properties — and a row whose `--pb-fill` never // landed renders as if the playhead were at zero, which is a screenshot of nothing. if (k.startsWith("--")) e.style.setProperty(k, String(v)); else e.style[k] = v; } return e; }; /** * The row, built the way `PlayerBar` builds it. * * `layers` names which of the three drawings to put up; `lanes` whether the animated partition rides * in each of them. Both are knobs here because the shipped row turned both up to the maximum at once, * and the only way to price each is to be able to turn it down on its own. */ /** * What ships today: one path, mirrored about the row's own axis, drawn twice and cut to the playhead. * * Kept as its own builder rather than another flag on `row()` because `row()` grew around the design that * had 144 lanes and three layers, and every knob it exposes is a lever on that. This one has two: how many * bars, and where the playhead is. */ function waveNowRow(cfg) { const wrap = span("pb-seek-wrap"); const d = wavePath(PEAKS, { ...TUNING, height: WAVE_UNITS, widthPx: cfg.strip || WAVE_BARS, barsPerPx: 1, }); const wave = span("pb-wave"); const layer = (cls) => { const svg = svgEl("svg", { class: "pb-wave-svg", viewBox: `0 0 ${PEAKS.buckets} ${WAVE_UNITS}`, preserveAspectRatio: "none", }); svg.appendChild(svgEl("path", { class: `pb-wave-path${cls}`, d })); return svg; }; wave.appendChild(layer("")); const played = span("pb-wave-played", { "--pb-fill": String(cfg.fill) }); played.appendChild(layer(" pb-wave-path--played")); wave.appendChild(played); wave.appendChild(span("pb-wave-caret", { "--pb-fill": String(cfg.fill) })); wrap.appendChild(wave); if (cfg.marks && cfg.region) { const marks = span("pb-marks"); const region = span("pb-loop-region"); region.style.setProperty("--pb-loop-start", String(cfg.region[0])); region.style.setProperty("--pb-loop-width", String(cfg.region[1] - cfg.region[0])); if (cfg.edge) region.dataset.edge = cfg.edge; if (cfg.tint !== undefined) region.style.setProperty("--pb-region-tint", `${cfg.tint}%`); if (cfg.detected) region.dataset.origin = "detected"; marks.appendChild(region); wrap.appendChild(marks); } // The row names the treatment too, because `bar` needs a lane out of the row's own height. Kept in step // with `PlayerBar.tsx`, which puts the same attribute on the same wrap for the same reason. if (cfg.edge) wrap.dataset.loopEdge = cfg.edge; return wrap; } function row(opts = {}) { const tuning = { ...TUNING, ...(opts.tuning ?? {}) }; if (opts.now) return waveNowRow({ marks: true, fill: 0.42, region: [0.4, 0.62], ...opts }); const cfg = { layers: ["unplayed", "loop", "played"], lanes: true, animate: true, fill: 0.42, region: [0.4, 0.62], ...opts, }; const bars = gammaCurve(barHeights(PEAKS, tuning), opts.gamma); const settled = wavePath(PEAKS, { ...tuning, bars }); const laneList = cfg.lanes ? lanePaths(tuning, bars) : []; const wrap = span("pb-seek-wrap"); const wave = span("pb-wave"); if (cfg.lanes && cfg.animate) { // The shipped row's own contract with the fold: the reveal edge is a transition the component // re-times on every report, so the sweep needs it to be the thing being measured too. wave.style.setProperty("--pb-wave", "1"); wave.style.setProperty("--pb-wave-ms", "120ms"); } if (cfg.layers.includes("unplayed")) wave.appendChild(layer(settled, cfg, laneList, "")); if (cfg.layers.includes("loop")) { const loop = layer(settled, cfg, laneList, "pb-wave-loop"); loop.style.setProperty("--pb-loop-start", String(cfg.region[0])); loop.style.setProperty("--pb-loop-end", String(cfg.region[1])); if (cfg.detected) loop.dataset.origin = "detected"; wave.appendChild(loop); } if (cfg.layers.includes("played")) { const played = span("pb-wave-played", { "--pb-fill": String(cfg.fill) }); played.appendChild(layer(settled, cfg, laneList, "")); wave.appendChild(played); } wrap.appendChild(wave); if (cfg.marks && cfg.region) { const marks = span("pb-marks"); const region = span("pb-loop-region"); region.style.setProperty("--pb-loop-start", String(cfg.region[0])); region.style.setProperty("--pb-loop-width", String(cfg.region[1] - cfg.region[0])); if (cfg.waved) region.dataset.waved = "true"; if (cfg.edge) region.dataset.edge = cfg.edge; if (cfg.tint !== undefined) region.style.setProperty("--pb-region-tint", `${cfg.tint}%`); if (cfg.edgeW) region.style.setProperty("--pb-edge-w", `${cfg.edgeW}px`); if (cfg.detected) region.dataset.origin = "detected"; marks.appendChild(region); if (cfg.caret !== undefined) { const caret = span("pb-loop-caret"); caret.style.setProperty("--pb-loop-at", String(cfg.caret)); marks.appendChild(caret); } wrap.appendChild(marks); } // …and on the row, where the lane the rail is drawn in is sized from. See `waveNowRow`. if (cfg.edge) wrap.dataset.loopEdge = cfg.edge; const slider = document.createElement("input"); slider.type = "range"; slider.className = "pb-seek"; slider.min = "0"; slider.max = String(PEAKS.seconds); slider.value = String(PEAKS.seconds * cfg.fill); slider.style.setProperty("--pb-fill", String(cfg.fill)); slider.style.pointerEvents = "none"; wrap.appendChild(slider); return wrap; } /** The shipped lane partition: `WAVE_LANES` runs of buckets, each one element, staggered by place. */ function lanePaths(tuning, bars) { const width = Math.max(1, Math.ceil(PEAKS.buckets / WAVE_LANES)); const out = []; for (let i = 0; i * width < PEAKS.buckets; i++) { const from = i * width; const to = Math.min(from + width, PEAKS.buckets); const d = wavePath(PEAKS, { ...tuning, bars, from, to }); out.push({ d, delay: Math.round((from / PEAKS.buckets) * (SWEEP.sweepMs / 2)), grow: SWEEP.growMs, }); } return out; } /** * The height curve, applied to the app's own bars before they reach the path builder. * * `barHeights` maps decibels linearly between the floor and full scale, which spends the top third of * the row on the range music actually lives in (−12…0 dBFS is 71…100% of the row) — so a verse and a * chorus differ by three pixels and the loud half of every track is a slab. A power above one hands * that range back: the quiet tail still reaches zero, and the loud half of the row stops being flat. */ function gammaCurve(bars, gamma) { if (!gamma || gamma === 1) return bars; const out = new Float32Array(bars.length); for (let i = 0; i < bars.length; i++) out[i] = Math.pow(bars[i], gamma); return out; } /** One ``: the settled path, plus the animated lanes over it when the variant wants them. */ function layer(settled, cfg, laneList, cls) { const svg = svgEl("svg", { class: `pb-wave-svg ${cls}`.trim(), viewBox: `0 0 ${PEAKS.buckets} ${WAVE_UNITS}`, preserveAspectRatio: "none", }); svg.appendChild(svgEl("path", { class: "pb-wave-path", d: settled })); if (cfg.lanes && cfg.animate) for (const l of laneList) { if (!l.d) continue; const p = svgEl("path", { class: "pb-wave-fresh", d: l.d }); p.style.animationDelay = `${l.delay}ms`; p.style.animationDuration = `${l.grow}ms`; svg.appendChild(p); } return svg; } /** * The variants, each a statement about where the entrance's cost comes from. * * `paths` and `animated` are reported beside the timings because they are different axes: the shipped * row is heavy on both at once, and "how many elements" is not the same question as "how much ink". */ const variants = { /** What ships: three copies of the drawing, the lanes animated in all three. */ ship(tuning, set) { const t = { ...tuning, ...SHIPPED, ...set }; const wrap = row({ tuning: t }); return { node: wrap, paths: 3 * (1 + live(t).length), animated: 3 * live(t).length }; }, /** One copy of the drawing with its lanes: prices the two clipped duplicates. */ single(tuning, set) { const t = { ...tuning, ...SHIPPED, ...set }; const wrap = row({ tuning: t, layers: ["unplayed"] }); return { node: wrap, paths: 1 + live(t).length, animated: live(t).length }; }, /** * Three copies of one path at the *old* ink (4 points per CSS pixel, linear dB) and nothing animating — * the floor the lane entrance had to be worth, before the point budget existed. `flat` below is the same * question asked of the ink the row actually wears. */ static3(tuning, set) { return { node: row({ tuning: { ...tuning, ...SHIPPED, ...set }, animate: false }), paths: 3, animated: 0, }; }, /** * **The row that ships**: three copies of one path at the shipped defaults — one point per CSS pixel, * `curve` 1.8 — with nothing animating. It is `now` with the two wrapper animations taken off it, which * is the comparison that ended the entrance: the animations were free beside the drawing, and a drawing * the listener pays for either way is not worth an entrance that costs anything at all. Measured here * rather than asserted in a commit message, because that is how the claim got made in the first place. */ flat(tuning, set) { return { node: row({ tuning: { ...tuning, ...set }, lanes: false, animate: false }), paths: 3, animated: 0, }; }, /** * The row's second entrance: one path per layer at one point per CSS pixel, and two animations on the * wrapper — the reveal edge and the rise — rather than a lane of path per slice per layer. This is what * the table in `docs/research/player-waveform.md` measured as `now`; the row that ships today is `flat`, * which is this drawing with the animations taken off it. */ now(tuning) { const wrap = row({ tuning, lanes: false }); const wave = wrap.querySelector(".pb-wave"); wave.style.setProperty("--pb-wave", "1"); wave.animate([{ clipPath: "inset(0 100% 0 0)" }, { clipPath: "inset(0 0% 0 0)" }], { duration: SWEEP.revealMs, easing: "linear", fill: "none", }); wave.animate([{ transform: "scaleY(0)" }, { transform: "scaleY(1)" }], { duration: SWEEP.growMs, easing: "cubic-bezier(0.22, 0.75, 0.3, 1)", fill: "none", }); return { node: wrap, paths: 3, animated: 2 }; }, /** `now` with the old four-points-per-pixel budget: prices the budget on its own. */ nowAt4(tuning) { return { node: row({ tuning: { ...tuning, barsPerPx: 4 }, lanes: false }), paths: 3, animated: 0, }; }, /** One static path, and the whole entrance is one transform on the outer ``. */ grow(tuning) { const wrap = row({ tuning, layers: ["unplayed"], lanes: false }); wrap.querySelector("svg").animate([{ transform: "scaleY(0)" }, { transform: "scaleY(1)" }], { duration: SWEEP.growMs, easing: "cubic-bezier(0.25, 0.6, 0.25, 1)", fill: "both", }); return { node: wrap, paths: 1, animated: 1 }; }, /** One animated element sweeping a `` across the row: the sweep without a per-lane element. */ maskSweep(tuning) { const wrap = row({ tuning, layers: ["unplayed"], lanes: false }); const svg = wrap.querySelector("svg"); const defs = svgEl("defs"); const mask = svgEl("mask", { id: "sweep", maskUnits: "userSpaceOnUse", x: 0, y: 0, width: PEAKS.buckets, height: WAVE_UNITS, }); const rect = svgEl("rect", { x: -PEAKS.buckets, y: 0, width: PEAKS.buckets, height: WAVE_UNITS, fill: "#fff", }); rect.animate( [{ transform: "translateX(0px)" }, { transform: `translateX(${PEAKS.buckets}px)` }], { duration: SWEEP.sweepMs, easing: "linear", fill: "both" }, ); mask.appendChild(rect); defs.appendChild(mask); svg.insertBefore(defs, svg.firstChild); svg.querySelector("path").setAttribute("mask", "url(#sweep)"); return { node: wrap, paths: 1, animated: 1 }; }, }; const laneCache = new Map(); function live(tuning) { const key = JSON.stringify([ tuning.shape, tuning.barsPerPx, tuning.barRatio, tuning.minBar, tuning.floorDb, ]); if (!laneCache.has(key)) laneCache.set( key, lanePaths(tuning, barHeights(PEAKS, tuning)).filter((l) => l.d), ); return laneCache.get(key); } /** Frame spacing over `ms`, with the long tasks that landed inside it. */ function frames(ms) { return new Promise((done) => { const dt = []; const long = []; let obs; if (typeof PerformanceObserver !== "undefined") { try { obs = new PerformanceObserver((l) => { for (const e of l.getEntries()) long.push(Math.round(e.duration)); }); obs.observe({ entryTypes: ["longtask"] }); } catch { obs = undefined; } } let last = performance.now(); const t0 = last; const tick = () => { const now = performance.now(); dt.push(now - last); last = now; if (now - t0 < ms) requestAnimationFrame(tick); else { obs?.disconnect(); done({ dt, long, span: now - t0 }); } }; requestAnimationFrame(tick); }); } const pct = (xs, p) => { const a = [...xs].sort((x, y) => x - y); return a.length ? a[Math.min(a.length - 1, Math.floor(p * a.length))] : 0; }; async function run(name, opts = {}) { const tuning = { ...TUNING, ...(opts.tuning ?? {}) }; const stage = document.getElementById("stage"); stage.replaceChildren(); const built = variants[name](tuning, opts.tuning ?? {}); const t0 = performance.now(); stage.appendChild(built.node); // Two frames: the first is layout plus the first paint of the new subtree, which is the mount cost. const f0 = await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); const mount = f0 - t0; const sample = await frames(Math.max(400, SWEEP.sweepMs)); const dts = sample.dt.slice(2); // the two frames straddling the mount are not the sweep // Read the path data out *before* the stage is cleared: after it every `d` is gone, and the row that // reports "0 kB of path" is the row that was measured rather than the row that was cheap. const kb = [...stage.querySelectorAll("path")].reduce( (a, p) => a + (p.getAttribute("d") || "").length, 0, ); stage.replaceChildren(); return { variant: name, ...built, mountMs: +mount.toFixed(1), frames: dts.length, fps: +(1000 / (dts.reduce((a, b) => a + b, 0) / Math.max(1, dts.length))).toFixed(1), dtP50: +pct(dts, 0.5).toFixed(2), dtP95: +pct(dts, 0.95).toFixed(2), dtMax: +Math.max(0, ...dts).toFixed(1), over20: dts.filter((d) => d > 20).length, over50: dts.filter((d) => d > 50).length, longTasks: sample.long, pathKb: Math.round(kb / 1024), perFrameMs: +(dts.reduce((a, b) => a + b, 0) / Math.max(1, dts.length)).toFixed(2), }; } /** * Is it on the compositor? Jam the main thread for `ms`, and let the caller screenshot through it. */ async function block(name, opts = {}) { const tuning = { ...TUNING, ...(opts.tuning ?? {}) }; const stage = document.getElementById("stage"); stage.replaceChildren(); stage.appendChild(variants[name](tuning).node); await new Promise((r) => requestAnimationFrame(r)); const ms = opts.ms ?? 600; const start = performance.now(); const t = stage.querySelector("path"); const before = t ? getComputedStyle(t).transform : ""; while (performance.now() < start + ms) { /* spin: no rAF, no style, no paint can run on this thread */ } return { variant: name, blockedMs: Math.round(performance.now() - start), runningAnimations: document.getAnimations().filter((a) => a.playState === "running").length, transformBefore: before, transformAfter: t ? getComputedStyle(t).transform : "", paths: stage.querySelectorAll("path").length, }; } /** `?still=1` paints one settled row and stops, for the screenshot script and for the human eye. */ function stillFromUrl() { const q = new URLSearchParams(location.search); if (q.get("still") !== "1") return; const num = (k, d) => (q.has(k) ? Number(q.get(k)) : d); const tuning = { ...TUNING, shape: q.get("shape") ?? TUNING.shape, barsPerPx: num("bpp", TUNING.barsPerPx), curve: num("curve", TUNING.curve), floorDb: num("floor", TUNING.floorDb), barRatio: num("ratio", TUNING.barRatio), minBar: num("min", TUNING.minBar), height: num("units", TUNING.height), }; const zoom = num("zoom", 1); const region = q.has("region") ? q.get("region").split(",").map(Number) : [0.4, 0.62]; const built = row({ tuning, gamma: num("gamma", 1), fill: num("fill", 0.42), region, marks: q.get("marks") === "1", edge: q.get("edge") ?? undefined, edgeW: q.has("edgeW") ? num("edgeW", 2) : undefined, waved: q.get("waved") === "1", caret: q.has("caret") ? num("caret", 0.7) : undefined, detected: q.get("detected") === "1", layers: (q.get("layers") ?? "unplayed,loop,played").split(","), strip: q.has("strip") ? num("strip", 1000) : 0, now: q.get("now") === "1", tint: q.has("tint") ? num("tint", 20) : undefined, animate: false, }); const label = document.createElement("p"); label.className = "row-label"; label.textContent = q.get("label") ?? ""; const box = document.createElement("div"); box.style.width = `${ROW_PX * zoom}px`; box.style.height = `${20 * zoom}px`; built.style.width = "100%"; built.style.height = "100%"; box.appendChild(built); document.getElementById("stage").append(label, box); document.body.style.paddingBottom = "24px"; } stillFromUrl(); /** * The row's grow, played on the strip's own row — the same keyframes, easing and origin as * `WaveformRow.tsx`, because the cost question is about that animation and not about a lookalike. */ globalThis.growRow = ({ ms = 220 } = {}) => { const row = document.querySelector(".pb-wave"); if (!row) return { animated: false }; row.animate([{ transform: "scaleY(0)" }, { transform: "scaleY(1)" }], { duration: ms, easing: "cubic-bezier(0.22, 0.8, 0.28, 1)", fill: "none", }); return { animated: true }; }; /** Jam the main thread, so a screenshot taken through the jam answers who was moving the pixels. */ globalThis.jamMainThread = (ms) => { // The window is marked, because a probe that cannot show the thread was actually stuck has measured // nothing: rAF timestamps either side of it are what turn "pixels moved" into "the compositor moved them". const start = performance.now(); const end = start + ms; while (performance.now() < end) { /* nothing else is allowed to run, which is the point */ } globalThis.__jam = { start, end }; return ms; }; globalThis.bench = { variants: Object.keys(variants), run, block, row, peaks: PEAKS, tuning: TUNING, }; console.log("[bench] ready", Object.keys(variants).join(", "));