diff --git a/packages/producer/src/services/htmlCompiler.test.ts b/packages/producer/src/services/htmlCompiler.test.ts index a25b2ccfccf..8237dbeee6e 100644 --- a/packages/producer/src/services/htmlCompiler.test.ts +++ b/packages/producer/src/services/htmlCompiler.test.ts @@ -18,6 +18,7 @@ import { detectRenderModeHints, detectShaderTransitionUsage, detectThreeDTransformUsage, + detectWebGlUsage, discoverMediaFromBrowser, discoverAudioVolumeAutomationFromTimeline, discoverVideoVisibilityFromTimeline, @@ -1085,6 +1086,73 @@ describe("detectThreeDTransformUsage", () => { }); }); +describe("detectWebGlUsage", () => { + it("detects getContext('webgl') and getContext('webgl2')", () => { + expect(detectWebGlUsage('')).toBe(true); + expect(detectWebGlUsage("")).toBe(true); + expect( + detectWebGlUsage(''), + ).toBe(true); + }); + + it("detects WebGPU contexts and attributes", () => { + expect(detectWebGlUsage('')).toBe( + true, + ); + expect(detectWebGlUsage('
')).toBe(true); + }); + + it("detects Three.js references and renderer constructors", () => { + expect(detectWebGlUsage("")).toBe( + true, + ); + expect(detectWebGlUsage("")).toBe(true); + expect( + detectWebGlUsage( + "", + ), + ).toBe(true); + expect(detectWebGlUsage("")).toBe(true); + }); + + it("detects Babylon.js and PixiJS", () => { + expect( + detectWebGlUsage(""), + ).toBe(true); + expect(detectWebGlUsage("")).toBe(true); + }); + + it("detects framework CDN scripts", () => { + expect( + detectWebGlUsage( + '', + ), + ).toBe(true); + expect(detectWebGlUsage('')).toBe(true); + expect( + detectWebGlUsage( + '', + ), + ).toBe(true); + }); + + it("detects hyperframes adapter hooks", () => { + expect(detectWebGlUsage("")).toBe(true); + expect(detectWebGlUsage("")).toBe(true); + expect(detectWebGlUsage("")).toBe(true); + }); + + it("does not false-positive on 2d canvas or standard HTML", () => { + expect(detectWebGlUsage('')).toBe(false); + expect(detectWebGlUsage('

Title

Description

')).toBe( + false, + ); + expect(detectWebGlUsage('')).toBe( + false, + ); + }); +}); + describe("detectAncestorBackgroundImage", () => { const wrap = (headCss: string, bodyAttrs = "", inner = "") => `` + diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index 9b892a49b44..e56d2d8bb12 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -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"; @@ -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|]*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; @@ -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( @@ -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 @@ -2255,6 +2277,7 @@ export async function compileForRender( usesThreeDTransforms, usesMixBlendMode, hasAncestorBackgroundImage, + usesWebGl, }; } diff --git a/packages/producer/src/services/render/stages/compileStage.test.ts b/packages/producer/src/services/render/stages/compileStage.test.ts index 245124eac48..a74fe162259 100644 --- a/packages/producer/src/services/render/stages/compileStage.test.ts +++ b/packages/producer/src/services/render/stages/compileStage.test.ts @@ -276,6 +276,67 @@ describe("runCompileStage — master bus", () => { }); }); +const WEBGL_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; diff --git a/packages/producer/src/services/render/stages/compileStage.ts b/packages/producer/src/services/render/stages/compileStage.ts index a4a4b013093..ac4680098bc 100644 --- a/packages/producer/src/services/render/stages/compileStage.ts +++ b/packages/producer/src/services/render/stages/compileStage.ts @@ -286,6 +286,26 @@ export async function runCompileStage(input: CompileStageInput): Promise { 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); }); @@ -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)", () => { @@ -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); }); diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts index d1f9160c740..32b1f0e63ec 100644 --- a/packages/producer/src/services/renderOrchestrator.ts +++ b/packages/producer/src/services/renderOrchestrator.ts @@ -2740,6 +2740,25 @@ export function shouldDiscardProbeSessionForPageSideCompositing(args: { return args.hasProbeSession && args.usePageSideCompositing; } +/** + * True when a composition uses WebGL / accelerated canvas (either through + * runtime adapters or static compile analysis) and the R&D bypass flags + * are not active. Used to gate drawElement and block priority inversion + * so WebGL renders preserve multi-worker screenshot parallelism (#5604). + */ +export function isWebGlRouteActive(args: { + hasWebGlAdapter?: boolean; + usesWebGl?: boolean; + env?: Readonly>; +}): boolean { + if (!args.hasWebGlAdapter && !args.usesWebGl) return false; + const env = args.env ?? process.env; + if (env.HF_FAST_CAPTURE_WEBGL === "true" || env.HF_FAST_CAPTURE_CSSFX === "true") { + return false; + } + return true; +} + /** * Main render pipeline */ @@ -3079,8 +3098,7 @@ async function executeRenderPipeline(input: { // `cfg.forceScreenshot` directly. let captureForceScreenshot = compileResult.forceScreenshot; // drawElement release telemetry: why default DE disengaged (if it did), - // whether self-verify fell back, and the drain-side counters. - const deCompileGate = compileResult.deCompileGate; + let deCompileGate = compileResult.deCompileGate; // Seed with the CONFIG-TIME refusal, if there was one. The clamp further // down only runs `if (cfg.useDrawElement && ...)`, so a render that never // became a drawElement candidate at all could never acquire a reason — @@ -3651,8 +3669,33 @@ async function executeRenderPipeline(input: { // correlated populations, hardware). A plain before/after cannot // attribute a fleet perf shift to this change; this can. const deShortBandRoute = process.env.HF_DE_SHORT_BAND_ROUTE === "true"; - // "Would ANY multi-worker resolution be inverted?" — if workers resolve - // to 1 naturally the outcome is identical either way. + const hasWebGlAdapter = adaptersUsed.some( + (a) => a === "three" || a === "typegpu" || a === "mapbox" || a === "maplibre", + ); + // Runtime WebGL adapter gate: adaptersUsed comes from the compilation phase + // and reflects Three.js/TypeGPU/Mapbox/MapLibre adapter hooks resolved at + // runtime — a superset of what the static regex in compileStage catches. + // When triggered, disable drawElement and set the "webgl" gate label so + // downstream DE eligibility checks and telemetry see the gate. + const webGlGateActive = isWebGlRouteActive({ + hasWebGlAdapter, + usesWebGl: compiled.usesWebGl, + }); + if (cfg.useDrawElement && webGlGateActive && hasWebGlAdapter) { + cfg.useDrawElement = false; + deCompileGate = deCompileGate ?? "webgl"; + // The probe session already initialized in drawElement mode (canvas + // injected); it must not be reused by the unverified path. + if (probeSession && probeSession.captureMode === "drawelement") { + lastBrowserConsole = probeSession.browserConsoleBuffer; + await closeCaptureSession(probeSession); + probeSession = null; + } + if (cfg.pageSideCompositingAutoDisabled) { + cfg.enablePageSideCompositing = true; + cfg.pageSideCompositingAutoDisabled = false; + } + } const WOULD_RESOLVE_MULTI_WORKER = 2; const deInversionArgs = { workerCount: WOULD_RESOLVE_MULTI_WORKER, @@ -3664,7 +3707,7 @@ async function executeRenderPipeline(input: { totalFrames, minFrames: deSingleMinFrames, singleWorkerStreamingOk: shouldUseStreamingEncode(cfg, outputFormat, 1, job.duration), - layeredOrEffectRoute: hasHdrContent || compiled.hasShaderTransitions, + layeredOrEffectRoute: hasHdrContent || compiled.hasShaderTransitions || webGlGateActive, supersampling: deviceScaleFactor !== 1, probeDeGated: isProbeDeGated(probeSession), experimentalParallelDeOptIn: @@ -3754,7 +3797,7 @@ async function executeRenderPipeline(input: { outputFormat, totalFrames, minFrames: deParallelMinFrames, - layeredOrEffectRoute: hasHdrContent || compiled.hasShaderTransitions, + layeredOrEffectRoute: hasHdrContent || compiled.hasShaderTransitions || webGlGateActive, supersampling: deviceScaleFactor !== 1, probeDeGated: isProbeDeGated(probeSession), experimentalParallelDeOptIn: