Skip to content
Closed
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
68 changes: 68 additions & 0 deletions packages/producer/src/services/htmlCompiler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
detectRenderModeHints,
detectShaderTransitionUsage,
detectThreeDTransformUsage,
detectWebGlUsage,
discoverMediaFromBrowser,
discoverAudioVolumeAutomationFromTimeline,
discoverVideoVisibilityFromTimeline,
Expand Down Expand Up @@ -1085,6 +1086,73 @@ describe("detectThreeDTransformUsage", () => {
});
});

describe("detectWebGlUsage", () => {
it("detects getContext('webgl') and getContext('webgl2')", () => {
expect(detectWebGlUsage('<script>const gl = canvas.getContext("webgl");</script>')).toBe(true);
expect(detectWebGlUsage("<script>const gl = canvas.getContext('webgl2');</script>")).toBe(true);
expect(
detectWebGlUsage('<script>const gl = canvas.getContext("experimental-webgl");</script>'),
).toBe(true);
});

it("detects WebGPU contexts and attributes", () => {
expect(detectWebGlUsage('<script>const context = canvas.getContext("webgpu");</script>')).toBe(
true,
);
expect(detectWebGlUsage('<div data-requires-webgpu id="render"></div>')).toBe(true);
});

it("detects Three.js references and renderer constructors", () => {
expect(detectWebGlUsage("<script>const renderer = new THREE.WebGLRenderer();</script>")).toBe(
true,
);
expect(detectWebGlUsage("<script>const scene = new THREE.Scene();</script>")).toBe(true);
expect(
detectWebGlUsage(
"<script>const cam = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);</script>",
),
).toBe(true);
expect(detectWebGlUsage("<script>if (window.THREE) { init(); }</script>")).toBe(true);
});

it("detects Babylon.js and PixiJS", () => {
expect(
detectWebGlUsage("<script>const engine = new BABYLON.Engine(canvas, true);</script>"),
).toBe(true);
expect(detectWebGlUsage("<script>const app = new PIXI.Application();</script>")).toBe(true);
});

it("detects framework CDN scripts", () => {
expect(
detectWebGlUsage(
'<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>',
),
).toBe(true);
expect(detectWebGlUsage('<script src="https://cdn.example.com/pixi.js"></script>')).toBe(true);
expect(
detectWebGlUsage(
'<script src="https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js"></script>',
),
).toBe(true);
});

it("detects hyperframes adapter hooks", () => {
expect(detectWebGlUsage("<script>window.__hfTypegpuTime = 0;</script>")).toBe(true);
expect(detectWebGlUsage("<script>window.__hfMapbox = map;</script>")).toBe(true);
expect(detectWebGlUsage("<script>window.__hfMaplibre = map;</script>")).toBe(true);
});

it("does not false-positive on 2d canvas or standard HTML", () => {
expect(detectWebGlUsage('<script>const ctx = canvas.getContext("2d");</script>')).toBe(false);
expect(detectWebGlUsage('<div class="hero"><h1>Title</h1><p>Description</p></div>')).toBe(
false,
);
expect(detectWebGlUsage('<script>gsap.to(".box", { x: 100, duration: 1 });</script>')).toBe(
false,
);
});
});

describe("detectAncestorBackgroundImage", () => {
const wrap = (headCss: string, bodyAttrs = "", inner = "") =>
`<!doctype html><html><head><style>${headCss}</style></head><body${bodyAttrs ? ` ${bodyAttrs}` : ""}>` +
Expand Down
23 changes: 23 additions & 0 deletions packages/producer/src/services/htmlCompiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ export interface CompiledComposition {
usesMixBlendMode: boolean;
/** Ancestors of the composition root carry a background-image (gradient/url). */
hasAncestorBackgroundImage: boolean;
/** Composition exercises WebGL / WebGPU accelerated canvas contexts. */
usesWebGl: boolean;
}

const INFERRED_MEDIA_DURATION_ATTR = "data-hf-inferred-duration";
Expand Down Expand Up @@ -412,6 +414,22 @@ function detectMixBlendModeUsage(html: string): boolean {
return MIX_BLEND_MODE_PATTERN.test(html);
}

/**
* Signals that the composition exercises WebGL or WebGPU contexts.
* drawElementImage cannot faithfully capture accelerated canvases — they freeze
* under seek-based capture or drop texture presentations, triggering the
* engine's `webgl-context` init-time risk gate. Detecting WebGL statically
* allows the orchestrator to route to the platform baseline (screenshot)
* across parallel workers up front instead of falling into the single-worker
* inversion.
*/
const WEBGL_USAGE_PATTERN =
/\.getContext\s*\(\s*["'](?:webgl2?|experimental-webgl|webgpu)["']|\b(?:THREE\.)?WebGL(?:1|2)?Renderer\b|\bWebGL2?RenderingContext\b|\bdata-requires-webgpu\b|\b__hfTypegpuTime\b|\b__hfMapbox\b|\b__hfMaplibre\b|\bwindow\.THREE\b|\bTHREE\.(?:Scene|PerspectiveCamera|OrthographicCamera|DefaultLoadingManager)\b|\b(?:new\s+)?BABYLON\.Engine\b|\b(?:new\s+)?PIXI\.(?:Application|Renderer)\b|<script[^>]*src=["'][^"']*(?:three|pixi|babylon|mapbox-gl|maplibre-gl)(?:[.-]min)?\.js/i;

export function detectWebGlUsage(html: string): boolean {
return WEBGL_USAGE_PATTERN.test(html);
}

/** A background declaration whose value paints an image (gradient or url). */
const BACKGROUND_IMAGE_DECL_PATTERN =
/(?:^|;|\{)\s*background(?:-image)?\s*:[^;}]*(?:\bgradient\s*\(|url\s*\()/i;
Expand Down Expand Up @@ -2076,6 +2094,7 @@ export async function compileForRender(
const usesThreeDTransforms = detectThreeDTransformUsage(sanitizedHtml);
const usesMixBlendMode = detectMixBlendModeUsage(sanitizedHtml);
const hasAncestorBackgroundImage = detectAncestorBackgroundImage(sanitizedHtml);
let usesWebGl = detectWebGlUsage(sanitizedHtml);

const normalizedFontHtml = normalizeSystemFontPrimaryFamilies(
injectTextRenderingRule(
Expand All @@ -2092,6 +2111,9 @@ export async function compileForRender(

// CDN scripts are inlined after coalescing so they stay separate from the merged inline runs.
const assembledHtml = await inlineExternalScripts(coalescedHtml);
if (!usesWebGl && detectWebGlUsage(assembledHtml)) {
usesWebGl = true;
}

// Inject studio position seek re-apply script when positions are baked into HTML.
// GSAP overwrites the `translate` CSS property on every frame seek; this script
Expand Down Expand Up @@ -2255,6 +2277,7 @@ export async function compileForRender(
usesThreeDTransforms,
usesMixBlendMode,
hasAncestorBackgroundImage,
usesWebGl,
};
}

Expand Down
61 changes: 61 additions & 0 deletions packages/producer/src/services/render/stages/compileStage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,67 @@ describe("runCompileStage — master bus", () => {
});
});

const WEBGL_HTML = `<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<div data-composition-id="root" data-width="1920" data-height="1080" data-duration="1">
<canvas id="c"></canvas>
<script>
const gl = document.getElementById("c").getContext("webgl");
</script>
</div>
</body>
</html>`;

describe("runCompileStage — drawElement WebGL gate", () => {
it("gates drawElement when composition uses WebGL", async () => {
const fixture = setupFixture(WEBGL_HTML);
try {
const cfg = createCfg({ useDrawElement: true });
const result = await runCompileStage({
projectDir: join(fixture.workDir, "project"),
workDir: fixture.workDir,
htmlPath: fixture.htmlPath,
entryFile: "index.html",
job: createJob(),
cfg,
needsAlpha: false,
log: noopLog,
assertNotAborted: () => {},
});
expect(result.compiled.usesWebGl).toBe(true);
expect(result.deCompileGate).toBe("webgl");
expect(cfg.useDrawElement).toBe(false);
} finally {
fixture.cleanup();
}
});

it("does not gate drawElement on standard non-WebGL HTML", async () => {
const fixture = setupFixture(PLAIN_HTML);
try {
const cfg = createCfg({ useDrawElement: true });
const result = await runCompileStage({
projectDir: join(fixture.workDir, "project"),
workDir: fixture.workDir,
htmlPath: fixture.htmlPath,
entryFile: "index.html",
job: createJob(),
cfg,
needsAlpha: false,
log: noopLog,
assertNotAborted: () => {},
});
expect(result.compiled.usesWebGl).toBe(false);
expect(result.deCompileGate).toBeUndefined();
expect(cfg.useDrawElement).toBe(true);
} finally {
fixture.cleanup();
}
});
});

describe("runCompileStage — font fetch cancellation", () => {
let fixture: CompileFixture | null = null;

Expand Down
20 changes: 20 additions & 0 deletions packages/producer/src/services/render/stages/compileStage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,26 @@ export async function runCompileStage(input: CompileStageInput): Promise<Compile
"so page-side compositing stays available.",
);
}
// WebGL / accelerated canvas gate: drawElementImage cannot faithfully capture
// accelerated canvases (they freeze under seek-based capture or drop texture
// swaps, triggering the engine's `webgl-context` init-time risk gate).
// When a composition uses WebGL, disable drawElementImage so the render uses
// the platform's baseline route (screenshot) across parallel workers instead
// of collapsing to a single worker under the DE priority inversion.
// HF_FAST_CAPTURE_WEBGL=true or HF_FAST_CAPTURE_CSSFX=true bypasses for R&D.
if (
cfg.useDrawElement &&
process.env.HF_FAST_CAPTURE_WEBGL !== "true" &&
process.env.HF_FAST_CAPTURE_CSSFX !== "true" &&
compiled.usesWebGl
) {
cfg.useDrawElement = false;
deCompileGate = "webgl";
log.info(
"[Render] Fast capture: composition uses WebGL / accelerated canvas, so disabling drawElementImage " +
"for this render. Capture uses the platform's baseline route.",
);
}
// Whenever a compile-time gate cleared useDrawElement, restore page-side
// compositing — but ONLY when resolveConfig auto-disabled it because
// drawElement was going to run. An explicit enablePageSideCompositing:false
Expand Down
63 changes: 63 additions & 0 deletions packages/producer/src/services/renderOrchestrator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
scanElementTags,
envInt,
isDeParallelRouterEnabled,
isWebGlRouteActive,
mergeWorkerInitObservability,
resolveCompositionElementCount,
detectAdaptersStatic,
Expand Down Expand Up @@ -2778,6 +2779,9 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
it("requires drawElement to be enabled and ungated", () => {
expect(shouldPreferSingleWorkerDrawElement({ ...eligible, useDrawElement: false })).toBe(false);
expect(shouldPreferSingleWorkerDrawElement({ ...eligible, deCompileGate: "3d" })).toBe(false);
expect(shouldPreferSingleWorkerDrawElement({ ...eligible, deCompileGate: "webgl" })).toBe(
false,
);
expect(shouldPreferSingleWorkerDrawElement({ ...eligible, forceScreenshot: true })).toBe(false);
});

Expand All @@ -2791,6 +2795,64 @@ describe("shouldPreferSingleWorkerDrawElement (DE priority inversion)", () => {
it("is a no-op when workers already resolved to 1", () => {
expect(shouldPreferSingleWorkerDrawElement({ ...eligible, workerCount: 1 })).toBe(false);
});

it("does not invert a WebGL composition of >= 900 frames to one worker (#5604)", () => {
// Compositions of >= 900 frames with WebGL must not invert to a single worker.
// They are routed via layeredOrEffectRoute (from isWebGlRouteActive) or deCompileGate,
// preserving multi-worker screenshot parallelism.
const webGlComp = {
...eligible,
totalFrames: 900,
layeredOrEffectRoute: isWebGlRouteActive({ usesWebGl: true }),
};
expect(webGlComp.layeredOrEffectRoute).toBe(true);
expect(shouldPreferSingleWorkerDrawElement(webGlComp)).toBe(false);

// Also blocks when caught via runtime WebGL adapter hooks:
const adapterComp = {
...eligible,
totalFrames: 900,
layeredOrEffectRoute: isWebGlRouteActive({ hasWebGlAdapter: true }),
};
expect(adapterComp.layeredOrEffectRoute).toBe(true);
expect(shouldPreferSingleWorkerDrawElement(adapterComp)).toBe(false);

// Bypass via HF_FAST_CAPTURE_WEBGL=true restores the old routing:
const bypassed = isWebGlRouteActive({
usesWebGl: true,
env: { HF_FAST_CAPTURE_WEBGL: "true" },
});
expect(bypassed).toBe(false);
expect(
shouldPreferSingleWorkerDrawElement({
...eligible,
totalFrames: 900,
layeredOrEffectRoute: bypassed,
}),
).toBe(true);
});
});

describe("isWebGlRouteActive", () => {
it("returns true when usesWebGl or hasWebGlAdapter is set and bypasses are not active", () => {
expect(isWebGlRouteActive({ usesWebGl: true, env: {} })).toBe(true);
expect(isWebGlRouteActive({ hasWebGlAdapter: true, env: {} })).toBe(true);
expect(isWebGlRouteActive({ usesWebGl: true, hasWebGlAdapter: true, env: {} })).toBe(true);
});

it("returns false when neither usesWebGl nor hasWebGlAdapter is set", () => {
expect(isWebGlRouteActive({ usesWebGl: false, hasWebGlAdapter: false, env: {} })).toBe(false);
expect(isWebGlRouteActive({ env: {} })).toBe(false);
});

it("returns false when bypassed by HF_FAST_CAPTURE_WEBGL=true or HF_FAST_CAPTURE_CSSFX=true", () => {
expect(isWebGlRouteActive({ usesWebGl: true, env: { HF_FAST_CAPTURE_WEBGL: "true" } })).toBe(
false,
);
expect(
isWebGlRouteActive({ hasWebGlAdapter: true, env: { HF_FAST_CAPTURE_CSSFX: "true" } }),
).toBe(false);
});
});

describe("resolveInversionRetryPlan (self-verify retry rollback)", () => {
Expand Down Expand Up @@ -2986,6 +3048,7 @@ describe("shouldPreferParallelDrawElement (DE parallel router)", () => {
it("requires drawElement to be enabled and ungated", () => {
expect(shouldPreferParallelDrawElement({ ...eligible, useDrawElement: false })).toBe(false);
expect(shouldPreferParallelDrawElement({ ...eligible, deCompileGate: "3d" })).toBe(false);
expect(shouldPreferParallelDrawElement({ ...eligible, deCompileGate: "webgl" })).toBe(false);
expect(shouldPreferParallelDrawElement({ ...eligible, forceScreenshot: true })).toBe(false);
});

Expand Down
Loading