8000 Demo project: fix broken render + long-form session demo by johannboehme · Pull Request #148 · 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
29 changes: 28 additions & 1 deletion frontend/src/core/render/webgpu-backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* (echtes GPU-Device, Chromium via Playwright).
*/
import { afterEach, describe, expect, it, vi } from "vitest";
import { WebGPUBackend } from "./webgpu-backend";
import { WebGPUBackend, imageSourceDims } from "./webgpu-backend";
import {
getCapabilities,
initCapabilities,
Expand Down Expand Up @@ -193,3 +193,30 @@ describe("WebGPUBackend — device.lost handling (issue #115)", () => {
expect(getCapabilities().webgpu).toBe(true);
});
});

describe("imageSourceDims — worker-safe image source measurement", () => {
afterEach(() => {
vi.unstubAllGlobals();
});

it("measures an HTMLImageElement via naturalWidth/naturalHeight", () => {
const img = document.createElement("img");
Object.defineProperty(img, "naturalWidth", { value: 320 });
Object.defineProperty(img, "naturalHeight", { value: 240 });
expect(imageSourceDims(img)).toEqual({ w: 320, h: 240 });
});

it("measures an ImageBitmap-like source via width/height", () => {
const bitmapLike = { width: 64, height: 48 } as ImageBitmap;
expect(imageSourceDims(bitmapLike)).toEqual({ w: 64, h: 48 });
});

it("does not throw in a worker-like scope without HTMLImageElement (demo-render regression)", () => {
// The render worker has no DOM globals — a bare `instanceof
// HTMLImageElement` throws a ReferenceError there and killed every
// export whose frame loop hit the test-pattern/image path.
vi.stubGlobal("HTMLImageElement", undefined);
const bitmapLike = { width: 8, height: 8 } as ImageBitmap;
expect(imageSourceDims(bitmapLike)).toEqual({ w: 8, h: 8 });
});
});
29 changes: 21 additions & 8 deletions frontend/src/core/render/webgpu-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@ type AnyCanvas = HTMLCanvasElement | OffscreenCanvas;
* canvas without renegotiation. */
const CANVAS_FORMAT: GPUTextureFormat = "bgra8unorm";

/** Pixel dimensions of an image layer source. HTMLImageElement is probed
* via `typeof` first — the render worker has no DOM globals, and a bare
* `instanceof HTMLImageElement` is a ReferenceError there (it killed
* every export whose frame loop hit the test-pattern/image path). */
export function imageSourceDims(
bitmap: ImageBitmap | HTMLImageElement,
): { w: number; h: number } {
if (
typeof HTMLImageElement !== "undefined" &&
bitmap instanceof HTMLImageElement
) {
return { w: bitmap.naturalWidth, h: bitmap.naturalHeight };
}
return { w: bitmap.width, h: bitmap.height };
}

export class WebGPUBackend implements CompositorBackend {
readonly id = "webgpu" as const;

Expand Down Expand Up @@ -707,16 +723,13 @@ export class WebGPUBackend implements CompositorBackend {
let srcW: number;
let srcH: number;
switch (src.kind) {
case "image":
case "image": {
imageSource = src.bitmap;
if (src.bitmap instanceof HTMLImageElement) {
srcW = src.bitmap.naturalWidth;
srcH = src.bitmap.naturalHeight;
} else {
srcW = src.bitmap.width;
srcH = src.bitmap.height;
}
const dims = imageSourceDims(src.bitmap);
srcW = dims.w;
srcH = dims.h;
break;
}
case "video":
// Runtime-supplied fallback wins over a not-yet-ready <video>
// — hides the black flash during seek/wrap.
Expand Down
82 changes: 82 additions & 0 deletions frontend/src/local/demo/demo-longform.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { describe, it, expect } from "vitest";
import { createDemoJob } from "./demo-project";
import { DEMO_SESSION, buildDemoSessionScore } from "./demo-song";
import { useOpsStore } from "../ops-store";
import { jobsDb, deleteJob } from "../jobs";
import { isVideoAsset } from "../../storage/jobs-db";

/** Wait until the sync op for `jobId` clears (success) or errors. */
function waitForSyncDone(jobId: string, timeoutMs = 240_000): Promise<void> {
return new Promise((resolve, reject) => {
const start = Date.now();
const tick = () => {
const op = useOpsStore.getState().ops[jobId]?.sync;
if (op?.error) {
reject(new Error(`Sync failed: ${op.error}`));
return;
}
if (!op) {
resolve();
return;
}
if (Date.now() - start > timeoutMs) {
reject(new Error(`Sync timed out at stage ${op.stage}`));
return;
}
setTimeout(tick, 250);
};
tick();
});
}

describe("long-form demo (end-to-end through sync + chunk detection)", () => {
it(
"detects the session's sections as chunks with one global tempo",
async () => {
const jobId = await createDemoJob({ mode: "longform" });
try {
await waitForSyncDone(jobId);

const job = await jobsDb.getJob(jobId);
expect(job).not.toBeNull();
expect(job!.mode).toBe("longform");
expect(job!.title).toBe("Demo session · long-form");

// Both cams prepped with real sync offsets.
const cams = (job!.videos ?? []).filter(isVideoAsset);
expect(cams).toHaveLength(2);
for (const cam of cams) {
expect(cam.sync).toBeDefined();
expect(cam.framesPath).toBeTruthy();
}

// Chunk detection found the session's loud sections — one chunk
// per synthesized section, boundaries within a couple hundred ms
// (10 Hz envelope + bar-snap tolerance).
const { sections } = buildDemoSessionScore(DEMO_SESSION);
const chunks = job!.chunks ?? [];
expect(chunks).toHaveLength(sections.length);
for (const [i, section] of sections.entries()) {
expect(
Math.abs(chunks[i].startMs - section.startS * 1000),
`chunk ${i} start`,
).toBeLessThan(400);
// End may be bar-snapped backwards from the raw silence edge,
// so allow up to a bar (~2.2 s) early but not late.
expect(chunks[i].endMs).toBeGreaterThan(section.startS * 1000 + 2000);
expect(chunks[i].endMs).toBeLessThan(section.endS * 1000 + 400);
}

// ONE tempo: global BPM aggregated from the chunks ≈ 112.
expect(job!.bpm).toBeDefined();
expect(Math.abs(job!.bpm!.value - DEMO_SESSION.bpm)).toBeLessThan(3);

// Triage phase gating: no arrangement yet — the user curates it.
expect(job!.arrangement).toBeUndefined();
} finally {
await deleteJob(jobId).catch(() => undefined);
}
},
300_000,
);
});
32 changes: 31 additions & 1 deletion frontend/src/local/demo/demo-project.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import {
createDemoJob,
type DemoProgress,
} from "./demo-project";
import { DEMO_SONG, songDurationS } from "./demo-song";
import {
DEMO_SONG,
DEMO_SESSION,
sessionDurationS,
songDurationS,
} from "./demo-song";
import type { Capabilities } from "../../core/capabilities";
import { createJob } from "../jobs";
import { synthesizeDemoVideo } from "./demo-video";
Expand Down Expand Up @@ -110,6 +115,31 @@ describe("createDemoJob", () => {
}
});

it("longform mode: session song, sections forwarded, job mode longform", async () => {
await createDemoJob({ mode: "longform" });

const dur = sessionDurationS(DEMO_SESSION);
for (const [i, spec] of DEMO_CAM_SPECS.entries()) {
const call = vi.mocked(synthesizeDemoVideo).mock.calls[i][0];
expect(call.durationS).toBeCloseTo(dur - spec.songStartS, 6);
expect(call.songPcm.length).toBe(Math.round(dur * DEMO_SESSION.sampleRate));
// Silence gaps drive the cams' tacet visuals.
expect(call.sections).toHaveLength(DEMO_SESSION.sections.length);
}

const [, , options] = vi.mocked(createJob).mock.calls[0];
expect(options).toMatchObject({
title: "Demo session · long-form",
mode: "longform",
});
});

it("direct mode does not pass sections (visuals always active)", async () => {
await createDemoJob();
const call = vi.mocked(synthesizeDemoVideo).mock.calls[0][0];
expect(call.sections).toBeUndefined();
});

it("reports progress stages in order: song → cams → job", async () => {
const stages: DemoProgress[] = [];
await createDemoJob({ onProgress: (p) => stages.push(p) });
Expand Down
50 changes: 41 additions & 9 deletions frontend/src/local/demo/demo-project.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
/**
* One-click demo project: synthesizes a small song plus two "cam"
* videos entirely in the browser (no bundled media, no downloads) and
* feeds them through the NORMAL `createJob` path, so the user lands in
* the same sync → editor flow their own footage would take.
* One-click demo project: synthesizes a song plus two "cam" videos
* entirely in the browser (no bundled media, no downloads) and feeds
* them through the NORMAL `createJob` path, so the user lands in the
* same flow their own footage would take. Two flavours:
*
* direct — a compact 17 s song; sync → editor → render.
* longform — a ~48 s session with silent gaps and different beat
* styles at one tempo; sync → triage → arrange → editor
* → render, the full long-form workflow.
*
* Cam B starts one bar into the song — the sync stage has a real
* offset to find, exactly like a phone that started recording late.
Expand All @@ -11,7 +16,16 @@
import type { Capabilities } from "../../core/capabilities";
import type { PickedAsset } from "../asset-source";
import { createJob } from "../jobs";
import { DEMO_SONG, renderDemoSongPcm, songDurationS, beatDurationS } from "./demo-song";
import {
DEMO_SONG,
DEMO_SESSION,
buildDemoSessionScore,
renderDemoSongPcm,
renderDemoSessionPcm,
songDurationS,
beatDurationS,
type DemoSessionSectionSpan,
} from "./demo-song";
import { encodeWavPcm16 } from "./wav-encode";
import { synthesizeDemoVideo } from "./demo-video";

Expand Down Expand Up @@ -64,8 +78,14 @@ export interface DemoProgress {
detail: string;
}

/** Which workflow the demo project walks. Mirrors `JobMode`. */
export type DemoMode = "direct" | "longform";

export interface CreateDemoJobOptions {
onProgress?: (p: DemoProgress) => void;
/** `direct` (default): 17 s song → editor. `longform`: ~48 s session
* with silent gaps + varied beats → triage → arrange → editor. */
mode?: DemoMode;
}

/**
Expand All @@ -77,16 +97,27 @@ export async function createDemoJob(
opts: CreateDemoJobOptions = {},
): Promise<string> {
const ?? (() => {});
const mode = opts.mode ?? "direct";

onProgress({ stage: "song", detail: "song" });
const songPcm = renderDemoSongPcm(DEMO_SONG);
let songPcm: Float32Array;
let durS: number;
let sections: DemoSessionSectionSpan[] | undefined;
if (mode === "longform") {
const score = buildDemoSessionScore(DEMO_SESSION);
songPcm = renderDemoSessionPcm(DEMO_SESSION);
durS = score.durationS;
sections = score.sections;
} else {
songPcm = renderDemoSongPcm(DEMO_SONG);
durS = songDurationS(DEMO_SONG);
}
const wav = encodeWavPcm16(songPcm, 1, DEMO_SONG.sampleRate);
const audioPick: PickedAsset = {
file: new File([wav], "demo-song.wav", { type: "audio/wav" }),
handle: null,
};

const durS = songDurationS(DEMO_SONG);
const videoPicks: PickedAsset[] = [];
for (const spec of DEMO_CAM_SPECS) {
onProgress({ stage: "cam", detail: spec.label });
Expand All @@ -96,13 +127,14 @@ export async function createDemoJob(
songPcm,
sampleRate: DEMO_SONG.sampleRate,
bpm: DEMO_SONG.bpm,
sections,
});
videoPicks.push({ file, handle: null });
}

onProgress({ stage: "job", detail: "job" });
return await createJob(videoPicks, audioPick, {
title: "Demo session",
mode: "direct",
title: mode === "longform" ? "Demo session · long-form" : "Demo session",
mode,
});
}
63 changes: 63 additions & 0 deletions frontend/src/local/demo/demo-render.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, it, expect } from "vitest";
import { createDemoJob } from "./demo-project";
import { useOpsStore } from "../ops-store";
import { runEditRender, deleteJob } from "../jobs";
import { opfs } from "../../storage/opfs";
import { demuxVideoTrack } from "../codec/webcodecs/demux";
import { songDurationS, DEMO_SONG } from "./demo-song";

/** Wait until the sync op for `jobId` clears (success) or errors. */
function waitForSyncDone(jobId: string, timeoutMs = 180_000): Promise<void> {
return new Promise((resolve, reject) => {
const start = Date.now();
const tick = () => {
const op = useOpsStore.getState().ops[jobId]?.sync;
if (op?.error) {
reject(new Error(`Sync failed: ${op.error}`));
return;
}
if (!op) {
resolve();
return;
}
if (Date.now() - start > timeoutMs) {
reject(new Error(`Sync timed out at stage ${op.stage}`));
return;
}
setTimeout(tick, 250);
};
tick();
});
}

describe("demo project render (end-to-end through the real pipeline)", () => {
it(
"renders the demo job to a playable MP4 of roughly song length",
async () => {
const jobId = await createDemoJob();
try {
await waitForSyncDone(jobId);

// Same call the editor's Export button makes, with the defaults a
// user gets when they hit Export without touching anything.
await runEditRender(jobId, { segments: [], overlays: [] });

const op = useOpsStore.getState().ops[jobId]?.render;
expect(op?.error).toBeUndefined();
expect(op?.done).toBe(true);

const out = await opfs.readFile(`jobs/${jobId}/output.mp4`);
expect(out.size).toBeGreaterThan(50_000);

const reparsed = await demuxVideoTrack(out);
expect(reparsed).not.toBeNull();
const expectS = songDurationS(DEMO_SONG);
expect(reparsed!.info.durationS).toBeGreaterThan(expectS - 1.5);
expect(reparsed!.info.durationS).toBeLessThan(expectS + 1.5);
} finally {
await deleteJob(jobId).catch(() => undefined);
}
},
300_000,
);
});
Loading
Loading
0