8000 fix(preview): WebGL2 double-flip on preferFallback bitmap upload by johannboehme · Pull Request #45 · 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
70 changes: 70 additions & 0 deletions frontend/src/editor/render/preview-runtime.test.ts
Original 8000 file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,76 @@ describe("PreviewRuntime — last-good-frame cache (hides black flash on seek/wr
});
});

describe("PreviewRuntime — extended snapshot scope (hot-covering cams)", () => {
// The lastGoodFrame snapshot is captured for every cam whose pill
// covers the playhead, not just the active layer. That way a cam
// about to be cut to (e.g. via a cut that's coming up in 50ms) has
// a fresh bitmap ready when its <video> kicks off the seek; the
// existing `inRange && !ready && cached` fallback then bridges the
// 1–3 decode frames seamlessly without a black flash.

function multiCamSnapshot(activeCamId: string): EditorStoreSnapshot {
// Two video clips with overlapping pills at timelineT=0.5; cuts
// pick the active cam by the rule "latest cut <= arrT wins".
const base = snapshot({ clips: [videoClip("a"), videoClip("b")] });
return { ...base, cuts: [{ atTimeS: 0, camId: activeCamId }] };
}

it("refreshes lastGoodFrame for non-active hot covering cams", async () => {
// Without this, the very first cam-switch from A → B has no cached
// snapshot for B and the latch can't substitute anything. With this
// the snapshot pipeline keeps every hot covering cam fresh so a
// valid fallback is always within 100ms of being current.
const createBitmapFromVideo = vi.fn(
async (_el: HTMLVideoElement) =>
({ close: vi.fn() }) as unknown as ImageBitmap,
);
const backend = makeBackend();
const pool = makePool();
const elA = makeFakeVideoEl({ readyState: 4, seeking: false });
const elB = makeFakeVideoEl({ readyState: 4, seeking: false });
(pool as unknown as { _add: (id: string, el?: HTMLVideoElement) => void })._add(
"a",
elA,
);
(pool as unknown as { _add: (id: string, el?: HTMLVideoElement) => void })._add(
"b",
elB,
);
const snap: { value: EditorStoreSnapshot } = {
value: multiCamSnapshot("a"),
};
const canvas = document.createElement("canvas");
const rt = new PreviewRuntime({
canvas,
cams: { a: { videoUrl: "a.mp4" }, b: { videoUrl: "b.mp4" } },
capabilities: { webgl2: false, webgpu: false },
cssW: 100,
cssH: 50,
dpr: 1,
initialScale: 1,
createBackendFn: vi.fn(async () => backend),
createPool: () => pool,
raf: () => 0,
cancelRaf: () => undefined,
readSnapshot: () => snap.value,
readPlayback: () => ({ currentTime: 0.5, timelineT: 0.5, isPlaying: false }),
createBitmapFromVideo,
});
await rt.init();
rt.tick();
await Promise.resolve();
await Promise.resolve();
// Both A (active) and B (hot covering, not active) should have been
// snapshotted — otherwise the cam-switch latch can't substitute.
const calledEls = createBitmapFromVideo.mock.calls.map(
(c: [HTMLVideoElement]) => c[0],
);
expect(calledEls).toContain(elA);
expect(calledEls).toContain(elB);
});
});

describe("PreviewRuntime — setCams (live + Media flow)", () => {
it("forwards a newly-added cam URL to the pool on the next tick", async () => {
// Repro for the bug where adding a video to an already-running editor
Expand Down
39 changes: 23 additions & 16 deletions frontend/src/editor/render/preview-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ export class PreviewRuntime {
this.backend.drawFrame(descriptor, sources);
const drawMs = this.opts.now() - t0;

this.maybeRefreshSnapshots(descriptor.layers, targets);
this.maybeRefreshSnapshots(targets);

// Feed the adaptive scaler. Only react when the backend itself is
// straining — visualizers/overlays/store reads are out of scope.
Expand Down Expand Up @@ -458,34 +458,35 @@ export class PreviewRuntime {
}

/** After a successful drawFrame, capture the live `<video>` of every
* active layer that's currently in-range and ready. Per-layer
* throttle keeps this cheap: most ticks hit the fast path
* (`now() - lastSnapshotMs < 100ms` → noop). The held bitmap is what
* `buildSourcesMap` substitutes during seeks/wraps. */
* HOT COVERING cam — not just the active layer. Per-layer throttle
* keeps this cheap (`now() - lastSnapshotMs < 100ms` → noop). The
* held bitmap is what `buildSourcesMap` substitutes during seeks
* and wraps. Iterating targets (which hot-keep populates with every
* covering pill's cam) means a cam that isn't currently active but
* is about to be cut to via a cut still has a fresh fallback ready
* for the seek-in-progress window before its first decoded frame
* lands. Image clips have entries in `targets` too but the pool
* returns null for them, so they're filtered naturally. */
private maybeRefreshSnapshots(
layers: ReadonlyArray<{ layerId: string; source: { kind: string } }>,
targets: ReadonlyMap<string, PoolSyncTarget>,
): void {
if (!this.pool) return;
let now: number | null = null;
for (const layer of layers) {
if (layer.source.kind !== "video") continue;
if (this.snapshotInFlight.has(layer.layerId)) continue;
const existing = this.lastGoodFrames.get(layer.layerId);
for (const [layerId, target] of targets) {
if (this.snapshotInFlight.has(layerId)) continue;
const existing = this.lastGoodFrames.get(layerId);
if (now === null) now = this.opts.now();
if (existing && now - existing.lastSnapshotMs < SNAPSHOT_THROTTLE_MS) {
continue;
}
const el = this.pool.getElement(layer.layerId);
const el = this.pool.getElement(layerId);
if (!el) continue;
if (el.seeking || el.readyState < READY_HAVE_CURRENT_DATA) continue;
const target = targets.get(layer.layerId);
if (!target || !this.pool.isSourceInRange(layer.layerId, target.sourceT)) {
if (!this.pool.isSourceInRange(layerId, target.sourceT)) {
continue;
}

this.snapshotInFlight.add(layer.layerId);
const layerId = layer.layerId;
this.snapshotInFlight.add(layerId);
void this.opts
.createBitmapFromVideo(el)
.then((bm) => {
Expand Down Expand Up @@ -655,7 +656,13 @@ async function defaultLoadBitmap(url: string): Promise<ImageBitmap> {
async function defaultCreateBitmapFromVideo(
el: HTMLVideoElement,
): Promise<ImageBitmap> {
return createImageBitmap(el);
// `imageOrientation: "from-image"` forces a deterministic Y-convention
// for the snapshot across browser/driver combos. Without it the
// default is "browser-defined" for HTMLVideoElement, which on some
// GPU drivers produces bitmaps that don't match the live <video>
// upload path's Y-orientation — visible as a flipped fallback frame
// when the cam-switch guard substitutes the snapshot.
return createImageBitmap(el, { imageOrientation: "from-image" });
}

function collectVideoCams(clips: readonly Clip[], cams: ClipUrlMap): VideoCam[] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,64 @@ describe("WebGL2Backend vs Canvas2DBackend — video source orientation parity",
const topMatchesBot = colorDist(c2dBot, glTop);
expect(topMatchesTop).toBeLessThan(topMatchesBot);
}, 15000);

it("WebGL2 fallback-bitmap render keeps the same orientation as live <video>", async () => {
// Regression: when the runtime hands a `preferFallback=true` source
// with a cached ImageBitmap (the seek-bridging path), the WebGL2
// backend uploads the bitmap, NOT the <video>. ImageBitmaps honour
// UNPACK_FLIP_Y_WEBGL=true and arrive already flipped — if the
// shader's u_srcFlipY is still 1 (because src.kind === "video"),
// the second flip in the fragment shader produces an upside-down
// frame. This was visible at every pill / cam transition in the
// editor preview during the seek-fallback window.
const cachedBitmap = await createImageBitmap(videoEl);

// First render: live <video> path (no fallback).
const live = document.createElement("canvas");
const liveBackend = new WebGL2Backend();
await liveBackend.init(live, { pixelW: W, pixelH: H });
liveBackend.drawFrame(
descriptor(),
new Map([["v", { kind: "video", element: videoEl }]]),
);
const liveGl = live.getContext("webgl2")!;
const liveTop = readWebGLPixel(liveGl, W / 2, 8);
const liveBot = readWebGLPixel(liveGl, W / 2, H - 8);

// Second render: preferFallback=true, same video frame as the cache.
const fb = document.createElement("canvas");
const fbBackend = new WebGL2Backend();
await fbBackend.init(fb, { pixelW: W, pixelH: H });
fbBackend.drawFrame(
descriptor(),
new Map([
[
"v",
{
kind: "video",
element: videoEl,
fallback: cachedBitmap,
preferFallback: true,
},
],
]),
);
const fbGl = fb.getContext("webgl2")!;
const fbTop = readWebGLPixel(fbGl, W / 2, 8);
const fbBot = readWebGLPixel(fbGl, W / 2, H - 8);

liveBackend.dispose();
fbBackend.dispose();
cachedBitmap.close();

// eslint-disable-next-line no-console
console.log("liveTop", liveTop, "liveBot", liveBot, "fbTop", fbTop, "fbBot", fbBot);

// The fallback render must keep the SAME orientation as the live
// render. If srcFlipY is wrong for the bitmap path, fbTop matches
// liveBot (and vice versa) — a clear inversion signature.
const topMatchesTop = colorDist(liveTop, fbTop);
const topMatchesBot = colorDist(liveBot, fbTop);
expect(topMatchesTop).toBeLessThan(topMatchesBot);
}, 15000);
});
18 changes: 13 additions & 5 deletions frontend/src/editor/render/webgl2-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,11 +228,19 @@ export class WebGL2Backend implements CompositorBackend {
gl.uniformMatrix2fv(this.layerLocs.uvMat, false, uvMatrixCM(layer));
// HTMLVideoElement / VideoFrame uploads ignore UNPACK_FLIP_Y_WEBGL
// on Chrome's hardware path, so we compensate at sample time.
// ImageBitmap honours the flag — flip stays at 0 there.
gl.uniform1f(
this.layerLocs.srcFlipY,
src.kind === "video" || src.kind === "videoframe" ? 1 : 0,
);
// ImageBitmap honours the flag — flip stays at 0 there. Critical
// edge: `kind === "video"` with `preferFallback` set uploads the
// CACHED ImageBitmap, NOT the <video> element. That bitmap
// honours UNPACK_FLIP_Y_WEBGL like any other ImageBitmap, so
// srcFlipY MUST be 0 here — otherwise the shader flips again,
// and the user sees a single upside-down frame at every pill /
// cam transition while the seek-fallback bridges the decode gap.
const usingFallbackBitmap =
src.kind === "video" && src.preferFallback && src.fallback != null;
const needsShaderFlip =
(src.kind === "video" && !usingFallbackBitmap) ||
src.kind === "videoframe";
gl.uniform1f(this.layerLocs.srcFlipY, needsShaderFlip ? 1 : 0);
this.quad.draw();
}

Expand Down
Loading
0