Skip to content

Write HTML. Render video. Built for agents.

fix(render): make WebGL video textures deterministic in headless render (#1403)

James Russod580f2a1d8ff
diff --git a/packages/core/src/runtime/adapters/seek-dispatch.test.ts b/packages/core/src/runtime/adapters/seek-dispatch.test.ts
new file mode 100644
index 0000000000..34a70ebf91
--- /dev/null
+++ b/packages/core/src/runtime/adapters/seek-dispatch.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { dispatchSeekEvent, forceDispatchSeekEvent, resetSeekDispatchState } from "./seek-dispatch";
+
+describe("seek-dispatch", () => {
+ beforeEach(() => {
+ resetSeekDispatchState();
+ });
+
+ it("dispatchSeekEvent fires an hf-seek event with the time", () => {
+ const handler = vi.fn();
+ window.addEventListener("hf-seek", handler);
+ dispatchSeekEvent(2.5);
+ window.removeEventListener("hf-seek", handler);
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect((handler.mock.calls[0][0] as CustomEvent).detail.time).toBe(2.5);
+ });
+
+ it("dispatchSeekEvent dedups consecutive same-time dispatches", () => {
+ const handler = vi.fn();
+ window.addEventListener("hf-seek", handler);
+ dispatchSeekEvent(4);
+ dispatchSeekEvent(4);
+ window.removeEventListener("hf-seek", handler);
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it("forceDispatchSeekEvent re-fires even at the same time (post-injection re-render)", () => {
+ const handler = vi.fn();
+ window.addEventListener("hf-seek", handler);
+ dispatchSeekEvent(6); // GPU adapters' first render at t=6
+ forceDispatchSeekEvent(6); // engine re-render after video injection, same t
+ window.removeEventListener("hf-seek", handler);
+ expect(handler).toHaveBeenCalledTimes(2);
+ expect((handler.mock.calls[1][0] as CustomEvent).detail.time).toBe(6);
+ });
+
+ it("after a force dispatch, the same time still dedups on the normal path", () => {
+ const handler = vi.fn();
+ window.addEventListener("hf-seek", handler);
+ forceDispatchSeekEvent(8);
+ dispatchSeekEvent(8); // deduped — force already recorded t=8
+ window.removeEventListener("hf-seek", handler);
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/runtime/adapters/seek-dispatch.ts b/packages/core/src/runtime/adapters/seek-dispatch.ts
index 6261cc5a27..ad9f0dad8a 100644
--- a/packages/core/src/runtime/adapters/seek-dispatch.ts
+++ b/packages/core/src/runtime/adapters/seek-dispatch.ts
@@ -30,6 +30,25 @@ export function dispatchSeekEvent(time: number): void {
}
}
+/**
+ * Force-dispatch a `"hf-seek"` event even if `time` equals the last dispatched
+ * time, bypassing the dedup guard.
+ *
+ * Needed for the post-video-injection GPU re-render: the engine seeks to time
+ * T (GPU adapters render once, before video frames are injected), then injects
+ * the decoded `__render_frame__` images, then must re-render GPU compositions
+ * at the *same* T so they re-upload textures from the now-present frames. The
+ * normal dedup would swallow that second dispatch.
+ */
+export function forceDispatchSeekEvent(time: number): void {
+ _lastDispatchedTime = time;
+ try {
+ window.dispatchEvent(new CustomEvent("hf-seek", { detail: { time } }));
+ } catch (err) {
+ swallow("runtime.adapters.seek-dispatch.force", err);
+ }
+}
+
/** Reset internal state — used in tests to prevent cross-test contamination. */
export function resetSeekDispatchState(): void {
_lastDispatchedTime = -1;
diff --git a/packages/core/src/runtime/adapters/video-texture-compat.test.ts b/packages/core/src/runtime/adapters/video-texture-compat.test.ts
new file mode 100644
index 0000000000..43dfe3690c
--- /dev/null
+++ b/packages/core/src/runtime/adapters/video-texture-compat.test.ts
@@ -0,0 +1,110 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import { patchWebGLVideoTextureCompat } from "./video-texture-compat";
+
+// Minimal fake WebGL2 context that records the source passed to texImage2D /
+// texSubImage2D, so we can assert the patch substitutes the injected frame.
+class FakeGL2 {
+ lastImageArgs: unknown[] | null = null;
+ lastSubArgs: unknown[] | null = null;
+ texImage2D(...args: unknown[]) {
+ this.lastImageArgs = args;
+ }
+ texSubImage2D(...args: unknown[]) {
+ this.lastSubArgs = args;
+ }
+}
+
+function makeInjectedImage(): HTMLImageElement {
+ const img = document.createElement("img");
+ img.classList.add("__render_frame__");
+ Object.defineProperty(img, "complete", { value: true, configurable: true });
+ Object.defineProperty(img, "naturalWidth", { value: 16, configurable: true });
+ return img;
+}
+
+describe("patchWebGLVideoTextureCompat", () => {
+ let originalGL2: unknown;
+
+ beforeEach(() => {
+ originalGL2 = (globalThis as Record<string, unknown>).WebGL2RenderingContext;
+ (globalThis as Record<string, unknown>).WebGL2RenderingContext = FakeGL2;
+ document.body.innerHTML = "";
+ });
+
+ afterEach(() => {
+ (globalThis as Record<string, unknown>).WebGL2RenderingContext = originalGL2;
+ document.body.innerHTML = "";
+ });
+
+ it("substitutes the decoded __render_frame__ image when uploading a <video>", () => {
+ patchWebGLVideoTextureCompat();
+
+ const video = document.createElement("video");
+ const img = makeInjectedImage();
+ document.body.append(video, img); // img is video.nextElementSibling
+
+ const gl = new FakeGL2();
+ gl.texImage2D(0x0de1, 0, 0x1908, 0x1908, 0x1401, video);
+
+ // Last argument (the source) must be swapped to the injected image.
+ expect(gl.lastImageArgs?.[gl.lastImageArgs.length - 1]).toBe(img);
+ });
+
+ it("leaves the <video> source untouched when no render frame is present (preview)", () => {
+ patchWebGLVideoTextureCompat();
+
+ const video = document.createElement("video");
+ document.body.append(video);
+
+ const gl = new FakeGL2();
+ gl.texImage2D(0x0de1, 0, 0x1908, 0x1908, 0x1401, video);
+
+ expect(gl.lastImageArgs?.[gl.lastImageArgs.length - 1]).toBe(video);
+ });
+
+ it("ignores a render-frame image that is not yet decoded", () => {
+ patchWebGLVideoTextureCompat();
+
+ const video = document.createElement("video");
+ const img = document.createElement("img");
+ img.classList.add("__render_frame__");
+ Object.defineProperty(img, "complete", { value: false, configurable: true });
+ Object.defineProperty(img, "naturalWidth", { value: 0, configurable: true });
+ document.body.append(video, img);
+
+ const gl = new FakeGL2();
+ gl.texImage2D(0x0de1, 0, 0x1908, 0x1908, 0x1401, video);
+
+ expect(gl.lastImageArgs?.[gl.lastImageArgs.length - 1]).toBe(video);
+ });
+
+ it("also patches texSubImage2D", () => {
+ patchWebGLVideoTextureCompat();
+
+ const video = document.createElement("video");
+ const img = makeInjectedImage();
+ document.body.append(video, img);
+
+ const gl = new FakeGL2();
+ gl.texSubImage2D(0x0de1, 0, 0, 0, 0x1908, 0x1401, video);
+
+ expect(gl.lastSubArgs?.[gl.lastSubArgs.length - 1]).toBe(img);
+ });
+
+ it("does not touch numeric/pixel-data overloads (no video source)", () => {
+ patchWebGLVideoTextureCompat();
+
+ const pixels = new Uint8Array([1, 2, 3, 4]);
+ const gl = new FakeGL2();
+ gl.texImage2D(0x0de1, 0, 0x1908, 1, 1, 0, 0x1908, 0x1401, pixels);
+
+ expect(gl.lastImageArgs?.[gl.lastImageArgs.length - 1]).toBe(pixels);
+ });
+
+ it("is idempotent — patching twice does not double-wrap", () => {
+ patchWebGLVideoTextureCompat();
+ const once = FakeGL2.prototype.texImage2D;
+ patchWebGLVideoTextureCompat();
+ expect(FakeGL2.prototype.texImage2D).toBe(once);
+ });
+});
diff --git a/packages/core/src/runtime/adapters/video-texture-compat.ts b/packages/core/src/runtime/adapters/video-texture-compat.ts
index 17bc0b716f..2fdb8f0583 100644
--- a/packages/core/src/runtime/adapters/video-texture-compat.ts
+++ b/packages/core/src/runtime/adapters/video-texture-compat.ts
@@ -1,18 +1,47 @@
/**
- * Patches `GPUQueue.copyExternalImageToTexture` so that video-backed WebGPU
- * effects work in both preview and render mode.
+ * Patches GPU texture-upload paths so that video-backed effects work in both
+ * preview and render mode — for WebGPU (`GPUQueue.copyExternalImageToTexture`)
+ * and WebGL (`texImage2D` / `texSubImage2D`).
*
* During render, the engine's video-frame injector replaces each `<video>`
* with a pre-decoded `<img class="__render_frame__">` sibling. Chrome's
* headless compositor can't supply decoded frames from the native `<video>`
- * element to WebGPU, so `copyExternalImageToTexture({ source: video })`
- * fails with "Browser fails extracting valid resource from external image."
+ * element to the GPU, so uploading a `<video>` directly fails (WebGPU throws
+ * "Browser fails extracting valid resource from external image"; WebGL uploads
+ * a black/stale frame). These patches transparently substitute the decoded
+ * render-frame `<img>` as the upload source. In preview mode (no render-frame
+ * sibling), the original `<video>` path is used unchanged.
+ */
+
+/**
+ * Resolve the decoded render-frame `<img>` for a source `<video>`, if the
+ * engine has injected one and it has decoded pixels. Returns null in preview
+ * mode or before the frame is decoded, so callers fall back to the video.
*
- * This patch checks whether a render-frame `<img>` exists next to the
- * source `<video>`. If it does and has decoded pixels, the patch
- * transparently substitutes it as the copy source. In preview mode (no
- * render-frame sibling), the original video path is used unchanged.
+ * The injector inserts the `<img>` as the video's immediate next sibling and
+ * also gives it the id `__render_frame_<videoId>__`; we check the sibling
+ * first (cheap) and fall back to an id lookup in case a node was inserted
+ * between them.
*/
+function resolveRenderFrameImage(video: HTMLVideoElement): HTMLImageElement | null {
+ const sibling = video.nextElementSibling;
+ if (
+ sibling instanceof HTMLImageElement &&
+ sibling.classList.contains("__render_frame__") &&
+ sibling.complete &&
+ sibling.naturalWidth > 0
+ ) {
+ return sibling;
+ }
+ if (video.id) {
+ const byId = document.getElementById(`__render_frame_${video.id}__`);
+ if (byId instanceof HTMLImageElement && byId.complete && byId.naturalWidth > 0) {
+ return byId;
+ }
+ }
+ return null;
+}
+
export function patchVideoTextureCompat(): void {
const GPUQueueCtor = (globalThis as Record<string, unknown>).GPUQueue as
| { prototype: Record<string, unknown> }
@@ -32,16 +61,51 @@ export function patchVideoTextureCompat(): void {
copySize: unknown,
) {
if (source?.source instanceof HTMLVideoElement) {
- const sibling = source.source.nextElementSibling;
- if (
- sibling instanceof HTMLImageElement &&
- sibling.classList.contains("__render_frame__") &&
- sibling.complete &&
- sibling.naturalWidth > 0
- ) {
- return orig.call(this, { ...source, source: sibling }, destination, copySize);
+ const img = resolveRenderFrameImage(source.source);
+ if (img) {
+ return orig.call(this, { ...source, source: img }, destination, copySize);
}
}
return orig.call(this, source, destination, copySize);
};
}
+
+/**
+ * WebGL analog of {@link patchVideoTextureCompat}. Patches `texImage2D` and
+ * `texSubImage2D` on both `WebGL2RenderingContext` and `WebGLRenderingContext`
+ * so that when a `<video>` is passed as the texture source (the last argument
+ * in the DOM-source overloads), the decoded render-frame `<img>` is uploaded
+ * instead during render. Numeric/`ArrayBufferView` overloads are untouched —
+ * only a trailing `HTMLVideoElement` argument is substituted.
+ */
+export function patchWebGLVideoTextureCompat(): void {
+ const ctors = [
+ (globalThis as Record<string, unknown>).WebGL2RenderingContext,
+ (globalThis as Record<string, unknown>).WebGLRenderingContext,
+ ] as Array<{ prototype: Record<string, unknown> } | undefined>;
+
+ const methods = ["texImage2D", "texSubImage2D"] as const;
+
+ for (const ctor of ctors) {
+ const proto = ctor?.prototype;
+ if (!proto) continue;
+ for (const method of methods) {
+ const orig = proto[method] as ((...args: unknown[]) => unknown) & {
+ __hfVideoPatched?: boolean;
+ };
+ if (typeof orig !== "function" || orig.__hfVideoPatched) continue;
+
+ const patched = function (this: unknown, ...args: unknown[]) {
+ const lastIndex = args.length - 1;
+ const last = args[lastIndex];
+ if (last instanceof HTMLVideoElement) {
+ const img = resolveRenderFrameImage(last);
+ if (img) args[lastIndex] = img;
+ }
+ return orig.apply(this, args);
+ } as ((...args: unknown[]) => unknown) & { __hfVideoPatched?: boolean };
+ patched.__hfVideoPatched = true;
+ proto[method] = patched;
+ }
+ }
+}
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index f7822c7c2c..fdb1e477c6 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -7,7 +7,11 @@ import { createAnimeJsAdapter } from "./adapters/animejs";
import { createLottieAdapter } from "./adapters/lottie";
import { createThreeAdapter } from "./adapters/three";
import { createTypegpuAdapter } from "./adapters/typegpu";
-import { patchVideoTextureCompat } from "./adapters/video-texture-compat";
+import {
+ patchVideoTextureCompat,
+ patchWebGLVideoTextureCompat,
+} from "./adapters/video-texture-compat";
+import { forceDispatchSeekEvent } from "./adapters/seek-dispatch";
import { createWaapiAdapter } from "./adapters/waapi";
import { refreshRuntimeMediaCache, syncRuntimeMedia } from "./media";
import { probeAndCacheElementVolume, type VolumeKeyframe } from "./mediaVolumeEnvelope.js";
@@ -1795,6 +1799,15 @@ export function initSandboxRuntimeModular(): void {
createGsapAdapter({ getTimeline: () => state.capturedTimeline }),
] as RuntimeDeterministicAdapter[];
patchVideoTextureCompat();
+ patchWebGLVideoTextureCompat();
+ // Lets the engine re-render GPU compositions after it injects decoded video
+ // frames, so video-textured WebGL/WebGPU scenes sample the correct frame.
+ window.__hfReseekGpu = (time: number) => {
+ const t = Math.max(0, Number(time) || 0);
+ window.__hfThreeTime = t;
+ window.__hfTypegpuTime = t;
+ forceDispatchSeekEvent(t);
+ };
installRuntimeErrorDiagnostics();
bindMediaMetadataListeners();
runAdapters("discover");
diff --git a/packages/core/src/runtime/window.d.ts b/packages/core/src/runtime/window.d.ts
index fdd920ec1b..439f9c9067 100644
--- a/packages/core/src/runtime/window.d.ts
+++ b/packages/core/src/runtime/window.d.ts
@@ -45,6 +45,13 @@ declare global {
* imperative push signal: `window.addEventListener("hf-seek", e => render(e.detail.time))`.
*/
__hfTypegpuTime?: number;
+ /**
+ * Re-render GPU adapters (Three.js / WebGPU) at the given time, bypassing
+ * the `"hf-seek"` dedup. Called by the engine after injecting decoded
+ * video frames so GPU compositions re-upload their video textures from the
+ * freshly-injected `__render_frame__` images. See `forceDispatchSeekEvent`.
+ */
+ __hfReseekGpu?: (time: number) => void;
__HF_PICKER_API?: HyperframePickerApi;
gsap?: {
timeline: (params?: { paused?: boolean }) => RuntimeTimelineLike;
diff --git a/packages/engine/src/services/videoFrameInjector.test.ts b/packages/engine/src/services/videoFrameInjector.test.ts
index 5a1c793b1c..11caff59b5 100644
--- a/packages/engine/src/services/videoFrameInjector.test.ts
+++ b/packages/engine/src/services/videoFrameInjector.test.ts
@@ -202,7 +202,9 @@ describe("createVideoFrameInjector cache hygiene against page-side skips", () =>
// Pin the contract: when the page returns `[]` (no ids actually
// injected), the cache must not record those frameIndexes, so a follow-
// up call at the same frameIndex still issues an inject.
- const fakePage = {} as Page;
+ // The injector calls page.evaluate after injecting frames (GPU reseek);
+ // stub it so these cache-hygiene cases exercise the real code path.
+ const fakePage = { evaluate: async () => undefined } as unknown as Page;
const hook = createVideoFrameInjector(
fakeTable({ videoId: "pip", framePath: "/p", frameIndex: 5 }),
{
@@ -235,7 +237,9 @@ describe("createVideoFrameInjector cache hygiene against page-side skips", () =>
// record it and a second call at the same frameIndex must short-circuit.
// This pins the happy path so a future refactor can't trade the skip
// bug for a never-cache regression.
- const fakePage = {} as Page;
+ // The injector calls page.evaluate after injecting frames (GPU reseek);
+ // stub it so these cache-hygiene cases exercise the real code path.
+ const fakePage = { evaluate: async () => undefined } as unknown as Page;
const hook = createVideoFrameInjector(
fakeTable({ videoId: "pip", framePath: "/p", frameIndex: 5 }),
{
@@ -251,4 +255,47 @@ describe("createVideoFrameInjector cache hygiene against page-side skips", () =>
// Cache hit — no second inject for the same frameIndex.
expect(injectVideoFramesBatchMock).toHaveBeenCalledTimes(1);
});
+
+ // Regression: WebGL/WebGPU compositions that sample a <video> as a texture
+ // render on `hf-seek` BEFORE frames are injected. After injecting the
+ // decoded frames, the hook must re-render the GPU adapters at the same time
+ // (window.__hfReseekGpu) so they re-upload their textures from the fresh
+ // frames — otherwise the facet flickers / goes black non-deterministically.
+ it("re-renders GPU adapters after injecting frames (post-injection reseek)", async () => {
+ const evaluate = vi.fn(async () => undefined);
+ const page = { evaluate } as unknown as Page;
+ const hook = createVideoFrameInjector(
+ fakeTable({ videoId: "facet", framePath: "/f", frameIndex: 3 }),
+ { frameSrcResolver: inlineResolver },
+ );
+
+ injectVideoFramesBatchMock.mockResolvedValueOnce(["facet"]);
+ await hook!(page, 1.5);
+
+ expect(evaluate).toHaveBeenCalledTimes(1);
+ // Re-render is requested at the same time as the seek.
+ expect(evaluate.mock.calls[0]![1]).toBe(1.5);
+ // The evaluated page function invokes window.__hfReseekGpu(time).
+ const pageFn = evaluate.mock.calls[0]![0] as (t: number) => void;
+ const reseek = vi.fn();
+ (globalThis as unknown as { window?: unknown }).window = { __hfReseekGpu: reseek };
+ pageFn(1.5);
+ delete (globalThis as unknown as { window?: unknown }).window;
+ expect(reseek).toHaveBeenCalledWith(1.5);
+ });
+
+ it("does not reseek GPU when the page injected no frames", async () => {
+ const evaluate = vi.fn(async () => undefined);
+ const page = { evaluate } as unknown as Page;
+ const hook = createVideoFrameInjector(
+ fakeTable({ videoId: "facet", framePath: "/f", frameIndex: 3 }),
+ { frameSrcResolver: inlineResolver },
+ );
+
+ // Page dropped the video (e.g. hidden host) → nothing injected → no reseek.
+ injectVideoFramesBatchMock.mockResolvedValueOnce([]);
+ await hook!(page, 1.5);
+
+ expect(evaluate).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/engine/src/services/videoFrameInjector.ts b/packages/engine/src/services/videoFrameInjector.ts
index d8b9e0e56d..d13c1b6b2e 100644
--- a/packages/engine/src/services/videoFrameInjector.ts
+++ b/packages/engine/src/services/videoFrameInjector.ts
@@ -214,6 +214,17 @@ export function createVideoFrameInjector(
lastInjectedFrameByVideo.set(update.videoId, update.frameIndex);
}
}
+ if (injectedIds.size > 0) {
+ // GPU compositions (WebGL / WebGPU) that sample these videos as
+ // textures already rendered once on the pre-injection seek, reading a
+ // stale/black frame. Now that the decoded `__render_frame__` images are
+ // in the DOM, re-render the GPU adapters at the same time so they
+ // re-upload their video textures from the correct frame. No-op in
+ // compositions without a GPU adapter.
+ await page.evaluate((t: number) => {
+ (window as unknown as { __hfReseekGpu?: (n: number) => void }).__hfReseekGpu?.(t);
+ }, time);
+ }
}
};
}
diff --git a/packages/producer/tests/webgl-video-texture-render-compat/meta.json b/packages/producer/tests/webgl-video-texture-render-compat/meta.json
new file mode 100644
index 0000000000..11dcfd2e49
--- /dev/null
+++ b/packages/producer/tests/webgl-video-texture-render-compat/meta.json
@@ -0,0 +1,13 @@
+{
+ "name": "webgl-video-texture-render-compat",
+ "description": "Regression guard for deterministic WebGL video textures. A WebGL2 canvas samples a <video> as a texture every hf-seek. In headless render, Chrome's compositor can't feed decoded <video> frames to WebGL, so the engine injects a decoded __render_frame__ <img> sibling and the core texImage2D video-texture patch + post-injection GPU reseek must supply the correct frame. Without that fix the rendered facets are black/stale while the preview snapshot shows the video, so render-vs-snapshot PSNR collapses. This fixture fails without the fix and passes with it.",
+ "tags": ["regression", "render-compat", "adapter"],
+ "minPsnr": 30,
+ "maxFrameFailures": 0,
+ "minAudioCorrelation": 0,
+ "maxAudioLagWindows": 1,
+ "renderConfig": {
+ "fps": 30,
+ "workers": 1
+ }
+}
diff --git a/packages/producer/tests/webgl-video-texture-render-compat/output/compiled.html b/packages/producer/tests/webgl-video-texture-render-compat/output/compiled.html
new file mode 100644
index 0000000000..e2d424c515
--- /dev/null
+++ b/packages/producer/tests/webgl-video-texture-render-compat/output/compiled.html
@@ -0,0 +1,106 @@
+<!DOCTYPE html>
+<html>
+ <head><style data-hyperframes-text-rendering="true">html,body,*{text-rendering:geometricPrecision}</style>
+ <style>
+ body {
+ margin: 0;
+ background: #000;
+ }
+ [data-composition-id="webgl-video-texture-test"] {
+ position: relative;
+ overflow: hidden;
+ }
+ #gl {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1280px;
+ height: 720px;
+ }
+ /* Texture-source video: sampled into WebGL only, parked off-canvas. */
+ #vid {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 4px;
+ height: 4px;
+ opacity: 0;
+ z-index: -1;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="root" data-composition-id="webgl-video-texture-test" data-width="1280" data-height="720" data-start="0" data-duration="2">
+ <video id="vid" class="clip" data-start="0" data-duration="2" data-track-index="0" src="clip.mp4" muted playsinline data-end="2" data-has-audio="false"></video>
+ <canvas id="gl"></canvas>
+
+
+ </div>
+ <script>// WebGL2 textured fullscreen triangle sampling the source video element.
+ // The handler uploads that video as a texture on every hf-seek — the
+ // natural author pattern. In headless render, Chrome can't supply decoded
+ // video frames to WebGL, so the core video-texture patch substitutes the
+ // engine's injected, decoded render-frame image, and the post-injection
+ // GPU reseek re-runs this handler. With the fix, render reproduces the
+ // preview snapshot (PSNR high); without it the canvas is black (PSNR
+ // collapses). NB: avoid writing literal tag syntax in comments here — the
+ // compiler's media-attribute injection scans the raw HTML for it.
+ (function () {
+ var canvas = document.getElementById("gl");
+ canvas.width = 1280;
+ canvas.height = 720;
+ var gl = canvas.getContext("webgl2", { preserveDrawingBuffer: true });
+ if (!gl) return;
+
+ var VS =
+ "#version 300 es\n" +
+ "in vec2 p; out vec2 uv;\n" +
+ "void main(){ uv = vec2(p.x*0.5+0.5, 0.5-p.y*0.5); gl_Position = vec4(p,0.0,1.0); }";
+ var FS =
+ "#version 300 es\n" +
+ "precision highp float; in vec2 uv; uniform sampler2D tex; out vec4 c;\n" +
+ "void main(){ c = texture(tex, uv); }";
+
+ function sh(type, src) {
+ var s = gl.createShader(type);
+ gl.shaderSource(s, src);
+ gl.compileShader(s);
+ return s;
+ }
+ var prog = gl.createProgram();
+ gl.attachShader(prog, sh(gl.VERTEX_SHADER, VS));
+ gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FS));
+ gl.linkProgram(prog);
+ gl.useProgram(prog);
+
+ var buf = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
+ var loc = gl.getAttribLocation(prog, "p");
+ gl.enableVertexAttribArray(loc);
+ gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
+
+ var tex = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+
+ var video = document.getElementById("vid");
+
+ function render() {
+ if (video && video.readyState >= 2) {
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, video);
+ }
+ gl.clearColor(0, 0, 0, 1);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ }
+
+ window.addEventListener("hf-seek", function () {
+ render();
+ });
+ render();
+ })();</script></body>
+</html>
diff --git a/packages/producer/tests/webgl-video-texture-render-compat/output/output.mp4 b/packages/producer/tests/webgl-video-texture-render-compat/output/output.mp4
new file mode 100644
index 0000000000..c83b966b69
--- /dev/null
+++ b/packages/producer/tests/webgl-video-texture-render-compat/output/output.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b42f669f775a304b8bd9b5bd09c508a61fa354c950e0fb3081fecc86ff749e06
+size 1075677
diff --git a/packages/producer/tests/webgl-video-texture-render-compat/src/clip.mp4 b/packages/producer/tests/webgl-video-texture-render-compat/src/clip.mp4
new file mode 100644
index 0000000000..b401d99658
--- /dev/null
+++ b/packages/producer/tests/webgl-video-texture-render-compat/src/clip.mp4
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c8571357061d144053774be928e226faf65a35626587c27459a25421d0941ac8
+size 133576
diff --git a/packages/producer/tests/webgl-video-texture-render-compat/src/index.html b/packages/producer/tests/webgl-video-texture-render-compat/src/index.html
new file mode 100644
index 0000000000..8c8edcabac
--- /dev/null
+++ b/packages/producer/tests/webgl-video-texture-render-compat/src/index.html
@@ -0,0 +1,124 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <style>
+ body {
+ margin: 0;
+ background: #000;
+ }
+ [data-composition-id="webgl-video-texture-test"] {
+ position: relative;
+ overflow: hidden;
+ }
+ #gl {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 1280px;
+ height: 720px;
+ }
+ /* Texture-source video: sampled into WebGL only, parked off-canvas. */
+ #vid {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 4px;
+ height: 4px;
+ opacity: 0;
+ z-index: -1;
+ }
+ </style>
+ </head>
+ <body>
+ <div
+ id="root"
+ data-composition-id="webgl-video-texture-test"
+ data-width="1280"
+ data-height="720"
+ data-start="0"
+ data-duration="2"
+ >
+ <video
+ id="vid"
+ class="clip"
+ data-start="0"
+ data-duration="2"
+ data-track-index="0"
+ src="clip.mp4"
+ muted
+ playsinline
+ ></video>
+ <canvas id="gl"></canvas>
+
+ <script>
+ // WebGL2 textured fullscreen triangle sampling the source video element.
+ // The handler uploads that video as a texture on every hf-seek — the
+ // natural author pattern. In headless render, Chrome can't supply decoded
+ // video frames to WebGL, so the core video-texture patch substitutes the
+ // engine's injected, decoded render-frame image, and the post-injection
+ // GPU reseek re-runs this handler. With the fix, render reproduces the
+ // preview snapshot (PSNR high); without it the canvas is black (PSNR
+ // collapses). NB: avoid writing literal tag syntax in comments here — the
+ // compiler's media-attribute injection scans the raw HTML for it.
+ (function () {
+ var canvas = document.getElementById("gl");
+ canvas.width = 1280;
+ canvas.height = 720;
+ var gl = canvas.getContext("webgl2", { preserveDrawingBuffer: true });
+ if (!gl) return;
+
+ var VS =
+ "#version 300 es\n" +
+ "in vec2 p; out vec2 uv;\n" +
+ "void main(){ uv = vec2(p.x*0.5+0.5, 0.5-p.y*0.5); gl_Position = vec4(p,0.0,1.0); }";
+ var FS =
+ "#version 300 es\n" +
+ "precision highp float; in vec2 uv; uniform sampler2D tex; out vec4 c;\n" +
+ "void main(){ c = texture(tex, uv); }";
+
+ function sh(type, src) {
+ var s = gl.createShader(type);
+ gl.shaderSource(s, src);
+ gl.compileShader(s);
+ return s;
+ }
+ var prog = gl.createProgram();
+ gl.attachShader(prog, sh(gl.VERTEX_SHADER, VS));
+ gl.attachShader(prog, sh(gl.FRAGMENT_SHADER, FS));
+ gl.linkProgram(prog);
+ gl.useProgram(prog);
+
+ var buf = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
+ var loc = gl.getAttribLocation(prog, "p");
+ gl.enableVertexAttribArray(loc);
+ gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
+
+ var tex = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+
+ var video = document.getElementById("vid");
+
+ function render() {
+ if (video && video.readyState >= 2) {
+ gl.bindTexture(gl.TEXTURE_2D, tex);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, video);
+ }
+ gl.clearColor(0, 0, 0, 1);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ }
+
+ window.addEventListener("hf-seek", function () {
+ render();
+ });
+ render();
+ })();
+ </script>
+ </div>
+ </body>
+</html>