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
33 changes: 33 additions & 0 deletions packages/engine/src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,34 @@ describe("resolveConfig", () => {
expect(config.forceScreenshot).toBe(false);
});

it("PRODUCER_FORCE_SCREENSHOT=auto leaves BeginFrame on and marks the per-page choice", () => {
setEnv("PRODUCER_BROWSER_GPU_MODE", "software");
setEnv("PRODUCER_FORCE_SCREENSHOT", "auto");
const config = resolveConfig();
expect(config.forceScreenshot).toBe(false);
expect(config.forceScreenshotExplicitlyOptedOut).toBe(true);
expect(config.screenshotForAcceleratedCanvas).toBe(true);
});

it("unset, true and false never mark the per-page choice", () => {
setEnv("PRODUCER_BROWSER_GPU_MODE", "software");
const resolved = [undefined, "true", "false"].map((value) => {
if (value === undefined) unsetEnv("PRODUCER_FORCE_SCREENSHOT");
else setEnv("PRODUCER_FORCE_SCREENSHOT", value);
const config = resolveConfig();
return [
config.forceScreenshot,
config.forceScreenshotExplicitlyOptedOut,
config.screenshotForAcceleratedCanvas,
];
});
expect(resolved).toEqual([
[true, undefined, undefined],
[true, undefined, undefined],
[false, true, undefined],
]);
});

it("explicit programmatic opt-out is honored on software", () => {
setEnv("PRODUCER_BROWSER_GPU_MODE", "software");
unsetEnv("PRODUCER_FORCE_SCREENSHOT");
Expand Down Expand Up @@ -555,6 +583,11 @@ describe("resolveConfig", () => {
}
});

it("treats PRODUCER_FORCE_SCREENSHOT=auto as an opt-out on software", () => {
const env = { PRODUCER_FORCE_SCREENSHOT: "auto" } as NodeJS.ProcessEnv;
expect(shouldClampToScreenshotForConcreteGpu("software", false, env)).toBe(false);
});

it("honors the programmatic opt-out via opts.programmaticOptOut on software", () => {
// The auto→software probe path is what this really guards: `resolveConfig`
// sets `forceScreenshotExplicitlyOptedOut = true` when the caller passed
Expand Down
29 changes: 25 additions & 4 deletions packages/engine/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,12 @@ export interface EngineConfig {
* the runtime probe fires). Not intended to be set by callers.
*/
forceScreenshotExplicitlyOptedOut?: boolean;
/**
* INTERNAL. Set to `true` by `resolveConfig` for `PRODUCER_FORCE_SCREENSHOT=auto`:
* capture as with `false`, except that a page holding a WebGL or WebGPU canvas is
* captured by screenshot when the browser's GL is software. Not intended to be set by callers.
*/
screenshotForAcceleratedCanvas?: boolean;
/** How long a BeginFrame capture may take to draw its first frame before the render retries by screenshot. */
beginFrameFirstFrameDeadlineMs?: number;
/**
Expand Down Expand Up @@ -351,6 +357,7 @@ const OPTIONAL_ENGINE_CONFIG_FIELDS = [
"expectedChromiumMajor",
"pageSideCompositingAutoDisabled",
"forceScreenshotExplicitlyOptedOut",
"screenshotForAcceleratedCanvas",
"beginFrameFirstFrameDeadlineMs",
"streamingEncodeAutoDisabledOnWin32Compound",
"runtimeManifestPath",
Expand Down Expand Up @@ -542,6 +549,7 @@ function validateOptionalEngineConfigFields(config: Record<string, unknown>): vo
for (const field of [
"pageSideCompositingAutoDisabled",
"forceScreenshotExplicitlyOptedOut",
"screenshotForAcceleratedCanvas",
"streamingEncodeAutoDisabledOnWin32Compound",
] as const) {
if (config[field] !== undefined && typeof config[field] !== "boolean") {
Expand Down Expand Up @@ -1057,8 +1065,7 @@ export function resolveConfig(overrides?: Partial<EngineConfig>): EngineConfig {
// on top:
//
// 1. Linux + software (SwiftShader host): kicks the browser off BeginFrame,
// which stalls the compositor on shader-heavy frames under CPU raster
// (same motivation as the closed PR #822).
// which stalls the compositor on shader-heavy frames under CPU raster.
// 2. Observability truth: `renderOrchestrator`'s reported `captureMode`
// field is derived from `cfg.forceScreenshot ? "screenshot" : "beginframe"`
// — without this clamp it misreports `"beginframe"` for the actual
Expand All @@ -1073,8 +1080,11 @@ export function resolveConfig(overrides?: Partial<EngineConfig>): EngineConfig {
//
// Explicit opt-out (env or programmatic override) is honored so BeginFrame-
// on-software debugging remains possible.
// `auto` opts out the same way as `false`; the per-page choice is made once the page is open.
Object.assign(merged, autoCaptureFields(env("PRODUCER_FORCE_SCREENSHOT")));
const explicitForceScreenshotOptOut =
env("PRODUCER_FORCE_SCREENSHOT") === "false" || overrides?.forceScreenshot === false;
optsOutOfSoftwareScreenshot(env("PRODUCER_FORCE_SCREENSHOT")) ||
overrides?.forceScreenshot === false;
// Persist provenance so the concrete-resolved-GPU helper can honor the
// programmatic opt-out too — at that point `forceScreenshot === false` is
// otherwise ambiguous between default and explicit opt-out.
Expand Down Expand Up @@ -1157,6 +1167,17 @@ export function resolveConfig(overrides?: Partial<EngineConfig>): EngineConfig {
};
}

/** The `PRODUCER_FORCE_SCREENSHOT` values that keep BeginFrame capture on software GL. */
function optsOutOfSoftwareScreenshot(requested: string | undefined): boolean {
return requested === "false" || requested === "auto";
}

function autoCaptureFields(
requested: string | undefined,
): Pick<EngineConfig, "screenshotForAcceleratedCanvas"> {
return requested === "auto" ? { screenshotForAcceleratedCanvas: true } : {};
}

/**
* Runtime-resolved companion to the software-GPU screenshot clamp in
* `resolveConfig`. Returns `true` iff callers should treat this render as
Expand Down Expand Up @@ -1186,7 +1207,7 @@ export function shouldClampToScreenshotForConcreteGpu(
if (currentForceScreenshot) return false;
if (resolvedGpuMode !== "software") return false;
if (opts.programmaticOptOut) return false;
return env["PRODUCER_FORCE_SCREENSHOT"] !== "false";
return !optsOutOfSoftwareScreenshot(env["PRODUCER_FORCE_SCREENSHOT"]);
}

/**
Expand Down
54 changes: 53 additions & 1 deletion packages/producer/src/services/distributed/plan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { basename, join } from "node:path";
import {
applyConcreteGpuScreenshotClamp,
_setDownloadFetchForTests,
Expand All @@ -36,6 +36,7 @@ import {
getFfmpegBinary,
getFfprobeBinary,
encodeAac,
resolveHeadlessShellPath,
} from "@hyperframes/engine";
import { recomputePlanHashFromPlanDir } from "../render/stages/freezePlan.js";
import { defaultLogger } from "../../logger.js";
Expand Down Expand Up @@ -608,6 +609,57 @@ describe("plan() and page motion blur (R19)", () => {
}, 60_000);
});

describe("plan() and PRODUCER_FORCE_SCREENSHOT=auto", () => {
const WEBGL_CANVAS =
'<canvas id="gl" width="32" height="32"></canvas>' +
'<script>document.getElementById("gl").getContext("webgl");</script>';

const planLockedCapture = async (html: string, name: string, requested: string | undefined) => {
const dir = join(runRoot, name);
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "index.html"), html, "utf-8");
const planDir = join(runRoot, `${name}-plan`);
const previous = process.env.PRODUCER_FORCE_SCREENSHOT;
if (requested === undefined) delete process.env.PRODUCER_FORCE_SCREENSHOT;
else process.env.PRODUCER_FORCE_SCREENSHOT = requested;
try {
await plan(dir, { fps: 30, width: 320, height: 240, format: "mp4" }, planDir);
} finally {
if (previous === undefined) delete process.env.PRODUCER_FORCE_SCREENSHOT;
else process.env.PRODUCER_FORCE_SCREENSHOT = previous;
}
const meta = JSON.parse(readFileSync(join(planDir, "meta", "encoder.json"), "utf-8"));
return { captureMode: meta.captureMode ?? null, forceScreenshot: meta.forceScreenshot ?? null };
};

// BeginFrame capture exists only on Linux, so only there is there a choice to lock.
it.skipIf(process.platform !== "linux")(
"locks screenshot capture for every chunk when the page has a WebGL canvas",
async () => {
// Only chrome-headless-shell has BeginFrame; any other browser plans the same for every page.
if (!basename(resolveHeadlessShellPath() ?? "").startsWith("chrome-headless-shell")) {
console.warn("[plan.test] skipping the auto capture lock test: no chrome-headless-shell");
return;
}
const webgl = FIXTURE_HTML.replace("</body>", `${WEBGL_CANVAS}</body>`);
expect(webgl).not.toBe(FIXTURE_HTML);
expect(await planLockedCapture(webgl, "auto-webgl", "auto")).toEqual({
captureMode: "screenshot",
forceScreenshot: true,
});
expect(await planLockedCapture(FIXTURE_HTML, "auto-plain", "auto")).toEqual({
captureMode: "beginframe",
forceScreenshot: false,
});
expect(await planLockedCapture(webgl, "false-webgl", "false")).toEqual({
captureMode: "beginframe",
forceScreenshot: false,
});
},
120_000,
);
});

describe("buildChunkSlices", () => {
it("produces consecutive non-overlapping ranges covering all frames", () => {
const slices = buildChunkSlices(700, 3, 240);
Expand Down
1 change: 1 addition & 0 deletions packages/producer/src/services/distributed/plan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1428,6 +1428,7 @@ async function compilePlanComposition(
assertNotAborted();
logPlanStage(log, "reference_background", stageStarted);
}
if (probeResult.acceleratedCanvasScreenshot) forceScreenshot = true;
compiled = probeResult.compiled;
job.strictVariablesChecked = probeResult.strictVariablesChecked;
job.duration = probeResult.duration;
Expand Down
89 changes: 89 additions & 0 deletions packages/producer/src/services/render/stages/probeStage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1877,6 +1877,95 @@ describe("runProbeStage — transient browser error retry (#1687)", () => {
expect(result.beginFrameStalled).toBe(true);
});

async function runAutoCaptureMode(input: {
pageHasAcceleratedCanvas: boolean;
cfg?: Record<string, unknown>;
stageForceScreenshot?: boolean;
}) {
resetRetryMocks();
capturedCfgs.length = 0;
let canvasChecks = 0;
pageEvaluateHandler = async (fn) => {
if (String(fn).includes("__hfAcceleratedCanvases")) {
canvasChecks += 1;
return input.pageHasAcceleratedCanvas;
}
return {
timelineKeys: [],
hfDuration: 5,
gsapLoaded: false,
totalDurationMs: 5000,
__hf: {},
};
};
const { runProbeStage } = await import("./probeStage.js");
const probeInput = makeProbeInput({
cfgForceScreenshot: input.stageForceScreenshot ?? false,
stageForceScreenshot: input.stageForceScreenshot ?? false,
});
Object.assign(probeInput.cfg, { screenshotForAcceleratedCanvas: true }, input.cfg);
const result = await runProbeStage(probeInput);
return { result, canvasChecks };
}

it("auto capture mode switches to screenshot for a WebGL or WebGPU canvas on software GL", async () => {
const { result } = await runAutoCaptureMode({ pageHasAcceleratedCanvas: true });

expect(result.acceleratedCanvasScreenshot).toBe(true);
expect(result.beginFrameStalled).toBe(false);
expect(createSessionCallCount).toBe(2);
expect(closedSessions).toEqual([createdSessions[0]]);
expect(capturedCfgs[0]).toMatchObject({ forceScreenshot: false });
expect(capturedCfgs[1]).toMatchObject({ forceScreenshot: true });
expect(result.probeSession).toBe(createdSessions[1]);
expect(durationProbeSessions).toEqual([createdSessions[1]]);
});

it("auto capture mode keeps BeginFrame when the page has no WebGL or WebGPU canvas", async () => {
const { result, canvasChecks } = await runAutoCaptureMode({ pageHasAcceleratedCanvas: false });

expect(canvasChecks).toBe(1);
expect(result.acceleratedCanvasScreenshot).toBe(false);
expect(createSessionCallCount).toBe(1);
expect(capturedCfgs[0]).toMatchObject({ forceScreenshot: false });
expect(result.probeSession?.launchCaptureMode).toBe("beginframe");
});

it("auto capture mode keeps BeginFrame on hardware GL even with a WebGL canvas", async () => {
const { result, canvasChecks } = await runAutoCaptureMode({
pageHasAcceleratedCanvas: true,
cfg: { browserGpuMode: "hardware" },
});

expect(canvasChecks).toBe(0);
expect(result.acceleratedCanvasScreenshot).toBe(false);
expect(createSessionCallCount).toBe(1);
expect(result.probeSession?.launchCaptureMode).toBe("beginframe");
});

it("without the auto value a WebGL canvas on software GL is never looked for", async () => {
const { result, canvasChecks } = await runAutoCaptureMode({
pageHasAcceleratedCanvas: true,
cfg: { screenshotForAcceleratedCanvas: undefined },
});

expect(canvasChecks).toBe(0);
expect(result.acceleratedCanvasScreenshot).toBe(false);
expect(createSessionCallCount).toBe(1);
expect(result.probeSession?.launchCaptureMode).toBe("beginframe");
});

it("auto capture mode does not look at the page when screenshot is already chosen", async () => {
const { result, canvasChecks } = await runAutoCaptureMode({
pageHasAcceleratedCanvas: true,
stageForceScreenshot: true,
});

expect(canvasChecks).toBe(0);
expect(result.acceleratedCanvasScreenshot).toBe(false);
expect(createSessionCallCount).toBe(1);
});

it("retries once on a transient 'Navigating frame was detached' error and succeeds", async () => {
await runWithTransientInitializeError("Navigating frame was detached");
});
Expand Down
Loading
Loading