8000 perf(editor): cache waveform pyramid on open — 9.8s→10ms for longform by johannboehme · Pull Request #62 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
187 changes: 187 additions & 0 deletions frontend/src/editor/editor-load.bench.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/**
* Editor-load pipeline benchmark — real Chromium.
*
* Measures the per-stage cost of everything the editor does between "open a
* job" and "timeline interactive", at realistic master-audio durations. The
* point is to find where the "Loading editor…" wait actually goes — not the
* JS bundle, not the file read, but the per-sample processing.
*
* Stages (all run on the decoded 22050 Hz mono PCM the editor works with):
* decode WAV → mono PCM (floor; compressed sources cost more)
* pyramid buildPeakPyramidAsync (waveform peaks)
* pyramid$ getOrComputePyramid → getCachedPyramid (warm IDB read)
* analysis getOrComputeAnalysis (tempo/beats/onsets worker)
* loudness buildLoudnessEnvelope (sidechain envelope)
*
* Not a pass/fail gate — it logs a table. Read the console output.
*/
import { describe, it } from "vitest";
import { decodeAudioToMonoPcm } from "../local/codec";
import { buildPeakPyramidAsync } from "../local/waveform/build-pyramid-async";
import {
getCachedPyramid,
getOrComputePyramid,
} from "../local/waveform/pyramid-cache";
import { buildLoudnessEnvelope } from "./fx/audio-envelope";
import { getOrComputeAnalysis } from "../local/render/audio-analysis";

const SR = 22050;

/** Music-ish mono PCM: a tonal bed + a transient every 0.5 s so the
* onset/tempo analysis has real structure to chew on (silence would
* short-circuit the beat tracker and under-report its cost). */
function makePcm(durationS: number, sampleRate: number): Float32Array {
const n = Math.floor(durationS * sampleRate);
const pcm = new Float32Array(n);
const beatPeriod = Math.floor(sampleRate * 0.5); // 120 BPM
for (let i = 0; i < n; i++) {
const t = i / sampleRate;
let s = 0.18 * Math.sin(2 * Math.PI * 110 * t);
s += 0.12 * Math.sin(2 * Math.PI * 220 * t);
const intoBeat = i % beatPeriod;
if (intoBeat < sampleRate * 0.04) {
const env = 1 - intoBeat / (sampleRate * 0.04);
s += 0.5 * env * Math.sin(2 * Math.PI * 60 * t);
}
pcm[i] = Math.max(-1, Math.min(1, s));
}
return pcm;
}

/** 16-bit mono WAV blob from PCM (so the decode path has real bytes). */
function pcmToWav(pcm: Float32Array, sampleRate: number): Blob {
const dataLen = pcm.length * 2;
const buf = new ArrayBuffer(44 + dataLen);
const dv = new DataView(buf);
dv.setUint32(0, 0x52494646, false);
dv.setUint32(4, 36 + dataLen, true);
dv.setUint32(8, 0x57415645, false);
dv.setUint32(12, 0x666d7420, false);
dv.setUint32(16, 16, true);
dv.setUint16(20, 1, true);
dv.setUint16(22, 1, true);
dv.setUint32(24, sampleRate, true);
dv.setUint32(28, sampleRate * 2, true);
dv.setUint16(32, 2, true);
dv.setUint16(34, 16, true);
dv.setUint32(36, 0x64617461, false);
dv.setUint32(40, dataLen, true);
let off = 44;
for (let i = 0; i < pcm.length; i++) {
const s = pcm[i];
dv.setInt16(off, s < 0 ? s * 0x8000 : s * 0x7fff, true);
off += 2;
}
return new Blob([buf], { type: "audio/wav" });
}

async function time<T>(fn: () => Promise<T> | T): Promise<{ ms: number; out: T }> {
const t0 = performance.now();
const out = await fn();
return { ms: performance.now() - t0, out };
}

const f = (ms: number) => `${ms.toFixed(0).padStart(6)} ms`;

describe("editor-load pipeline benchmark", () => {
// 1 / 4 / 15 min cover a single-take clip up to a long-form set.
const DURATIONS = [60, 240, 900];

it(
"measures per-stage cost across audio durations",
async () => {
const rows: string[] = [];
rows.push(
`dur samples decode(WAV) pyramid pyramid$(warm) loudness analysis`,
);

for (const durationS of DURATIONS) {
const pcm = makePcm(durationS, SR);
const wav = pcmToWav(pcm, SR);
const jobId = `bench-${durationS}-${pcm.length}`;

const decode = await time(() => decodeAudioToMonoPcm(wav, SR));
const decoded = decode.out;

const pyramid = await time(() =>
buildPeakPyramidAsync(decoded.pcm.slice(), decoded.sampleRate, {
baseSamplesPerBucket: 64,
}),
);

// Warm path: persist once, then measure the cached read the editor
// would now hit instead of rebuilding.
await getOrComputePyramid(jobId, decoded.pcm.slice(), decoded.sampleRate);
const pyramidWarm = await time(() =>
getCachedPyramid(jobId, decoded.sampleRate),
);

const loudness = await time(() =>
buildLoudnessEnvelope(decoded.pcm.slice(), decoded.sampleRate),
);

let analysisMs = NaN;
try {
const analysis = await time(() =>
getOrComputeAnalysis(
`${jobId}-an`,
decoded.pcm.slice(),
decoded.sampleRate,
),
);
analysisMs = analysis.ms;
} catch (e) {
rows.push(` analysis failed @${durationS}s: ${String(e)}`);
}

rows.push(
`${`${durationS}s`.padStart(4)} ${`${pcm.length}`.padStart(9)} ` +
`${f(decode.ms)} ${f(pyramid.ms)} ${f(pyramidWarm.ms)} ` +
`${f(loudness.ms)} ${f(analysisMs)}`,
);
}

// eslint-disable-next-line no-console
console.log("\n========== EDITOR LOAD PIPELINE BENCHMARK ==========\n" +
rows.join("\n") +
"\n====================================================\n");
},
120_000,
);

// Real compressed sources go through WebCodecs (or ffmpeg.wasm fallback) —
// a different cost class than the WAV floor above. The fixtures are short,
// so we report ms-per-second-of-audio to extrapolate to a full track.
it(
"measures compressed-source decode (AAC / MP3) per second of audio",
async () => {
const out: string[] = [];
for (const name of ["studio-aac.m4a", "studio-mp3.mp3"]) {
try {
const blob = await fetch(`/__test_fixtures__/${name}`).then((r) =>
r.blob(),
);
// First call includes the streaming-module dynamic import (cold).
const cold = await time(() => decodeAudioToMonoPcm(blob, SR));
const warm = await time(() => decodeAudioToMonoPcm(blob, SR));
const durS = cold.out.pcm.length / cold.out.sampleRate;
const perSecCold = cold.ms / durS;
out.push(
`${name.padEnd(16)} bytes=${blob.size} audio=${durS.toFixed(1)}s ` +
`cold=${cold.ms.toFixed(0)}ms warm=${warm.ms.toFixed(0)}ms ` +
`→ ${perSecCold.toFixed(1)} ms/s ` +
`(extrapolated 240s≈${(perSecCold * 240).toFixed(0)}ms, ` +
`900s≈${(perSecCold * 900).toFixed(0)}ms)`,
);
} catch (e) {
out.push(`${name}: FAILED — ${String(e)}`);
}
}
// eslint-disable-next-line no-console
console.log("\n========== COMPRESSED DECODE ==========\n" +
out.join("\n") +
"\n=======================================\n");
},
120_000,
);
});
115 changes: 115 additions & 0 deletions frontend/src/editor/load-master-audio.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { describe, it, expect, vi } from "vitest";
import { loadMasterAudio, type LoadMasterAudioDeps } from "./load-master-audio";
import type { PeakPyramid } from "../local/waveform/peak-pyramid";

/** Minimal pyramid stand-in — only the fields the loader reads. */
function fakePyramid(durationS: number, sampleRate = 22050): PeakPyramid {
return { version: 1, sampleRate, durationS } as unknown as PeakPyramid;
}

function decoded(sampleRate = 22050) {
return { pcm: new Float32Array([0.1, -0.2, 0.3]), sampleRate };
}

function makeDeps(over: Partial<LoadMasterAudioDeps> = {}): LoadMasterAudioDeps {
return {
getCachedPyramid: vi.fn(async () => undefined),
decode: vi.fn(async () => decoded()),
buildPyramid: vi.fn(async (_id, _pcm, sr) => fakePyramid(7, sr)),
...over,
};
}

describe("loadMasterAudio", () => {
it("uses the cached pyramid's duration WITHOUT decoding (the fast path)", async () => {
const cached = fakePyramid(123.4);
const deps = makeDeps({ getCachedPyramid: vi.fn(async () => cached) });

const out = await loadMasterAudio("job-1", 22050, deps);

expect(out.wave?.duration).toBe(123.4);
expect(out.wave?.pyramid).toBe(cached);
// The whole point: no decode and no rebuild gate the result.
expect(deps.decode).not.toHaveBeenCalled();
expect(deps.buildPyramid).not.toHaveBeenCalled();
});

it("queries the cache with the requested sample rate", async () => {
const getCachedPyramid = vi.fn(async () => fakePyramid(10));
await loadMasterAudio("job-1", 48000, makeDeps({ getCachedPyramid }));
expect(getCachedPyramid).toHaveBeenCalledWith("job-1", 48000);
});

it("getPcm() lazily decodes at most once on the fast path", async () => {
const decode = vi.fn(async () => decoded());
const out = await loadMasterAudio(
"job-1",
22050,
makeDeps({ getCachedPyramid: vi.fn(async () => fakePyramid(5)), decode }),
);

expect(decode).not.toHaveBeenCalled(); // not yet — deferred
const a = await out.getPcm();
const b = await out.getPcm();
expect(decode).toHaveBeenCalledTimes(1); // memoized
expect(a).toBe(b);
expect(a?.pcm.length).toBe(3);
});

it("on cache miss: decodes, builds+persists the pyramid, derives duration from it", async () => {
const buildPyramid = vi.fn(async (_id, _pcm, sr) => fakePyramid(88, sr));
const decode = vi.fn(async () => decoded(22050));
const out = await loadMasterAudio(
"job-1",
22050,
makeDeps({ getCachedPyramid: vi.fn(async () => undefined), decode, buildPyramid }),
);

expect(out.wave?.duration).toBe(88);
expect(decode).toHaveBeenCalledTimes(1);
expect(buildPyramid).toHaveBeenCalledWith("job-1", expect.any(Float32Array), 22050);
});

it("on cache miss: getPcm() reuses the cold-path decode (no second decode)", async () => {
const decode = vi.fn(async () => decoded());
const out = await loadMasterAudio(
"job-1",
22050,
makeDeps({ getCachedPyramid: vi.fn(async () => undefined), decode }),
);
const pcm = await out.getPcm();
expect(decode).toHaveBeenCalledTimes(1);
expect(pcm?.pcm.length).toBe(3);
});

it("returns wave=null (graceful) when decode fails on the cold path", async () => {
const out = await loadMasterAudio(
"job-1",
22050,
makeDeps({
getCachedPyramid: vi.fn(async () => undefined),
decode: vi.fn(async () => {
throw new Error("no audio");
}),
}),
);
expect(out.wave).toBeNull();
expect(await out.getPcm()).toBeNull();
});

it("treats a cache read error as a miss and falls back to decode", async () => {
const buildPyramid = vi.fn(async (_id, _pcm, sr) => fakePyramid(33, sr));
const out = await loadMasterAudio(
"job-1",
22050,
makeDeps({
getCachedPyramid: vi.fn(async () => {
throw new Error("idb down");
}),
buildPyramid,
}),
);
expect(out.wave?.duration).toBe(33);
expect(buildPyramid).toHaveBeenCalledTimes(1);
});
});
91 changes: 91 additions & 0 deletions frontend/src/editor/load-master-audio.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import type { PeakPyramid } from "../local/waveform/peak-pyramid";

export interface MasterAudioWave {
pyramid: PeakPyramid;
duration: number;
}

export interface DecodedPcm {
pcm: Float32Array;
sampleRate: number;
}

export interface LoadMasterAudioDeps {
/** Read the persisted peak-pyramid from IDB (pre-warmed by the sync step). */
getCachedPyramid: (
jobId: string,
sampleRate: number,
) => Promise<PeakPyramid | undefined>;
/** Decode the master audio to mono PCM. Expensive (1–3 s) — runs at most once. */
decode: () => Promise<DecodedPcm>;
/** Build the pyramid from decoded PCM and persist it for the next open. */
buildPyramid: (
jobId: string,
pcm: Float32Array,
sampleRate: number,
) => Promise<PeakPyramid>;
}

export interface LoadedMasterAudio {
/** Waveform for the timeline, or null if the audio couldn't be prepared. */
wave: MasterAudioWave | null;
/**
* Lazily provide the decoded PCM — needed only for audio-analysis on a cache
* miss and for the sidechain loudness envelope, never for first paint.
* Memoized: decodes at most once, and reuses the decode already done on the
* cache-miss path rather than decoding twice.
*/
getPcm: () => Promise<DecodedPcm | null>;
}

/**
* Prepare the master waveform for the editor, decode-free when possible.
*
* The sync step persists the peak-pyramid, and the pyramid carries the true
* master-audio duration (`durationS = samples / sampleRate`). When that cache
* is warm we hand the timeline its waveform — and `loadJob` its duration —
* without decoding a single sample. The decode (1–3 s) then only happens
* lazily, in the background, for the sidechain loudness envelope.
*
* On a cold/un-synced job there is no cached pyramid, so we must decode to
* learn the real duration and build the pyramid (which `buildPyramid` also
* persists, so the next open is fast). That decoded PCM is reused by
* `getPcm()` rather than decoded a second time.
*
* Note the duration always traces back to a real decode — never to the job's
* `durationS`, which is the lead-cam *video* length, not the master audio.
*/
export async function loadMasterAudio(
jobId: string,
sampleRate: number,
deps: LoadMasterAudioDeps,
): Promise<LoadedMasterAudio> {
// Memoized PCM provider: a single decode shared by every consumer.
let pcmPromise: Promise<DecodedPcm | null> | null = null;
const getPcm = (): Promise<DecodedPcm | null> => {
if (!pcmPromise) pcmPromise = deps.decode().catch(() => null);
return pcmPromise;
};

const cached = await deps
.getCachedPyramid(jobId, sampleRate)
.catch(() => undefined);
if (cached) {
return { wave: { pyramid: cached, duration: cached.durationS }, getPcm };
}

// Cold path: decode (via the memoized provider so it isn't repeated) to
// learn the real duration, then build + persist the pyramid.
const decodedPcm = await getPcm();
if (!decodedPcm) return { wave: null, getPcm };
try {
const pyramid = await deps.buildPyramid(
jobId,
decodedPcm.pcm,
decodedPcm.sampleRate,
);
return { wave: { pyramid, duration: pyramid.durationS }, getPcm };
} catch {
return { wave: null, getPcm };
}
}
Loading
Loading
0