diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index a95c26d4df..3628f51b73 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -2121,9 +2121,9 @@ How it uses the machine, and when it gives up: | Flag | Default | Description | | -------------------------------------------------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | | `--workers, -w` | auto | 1–24 workers. Each is a separate Chrome, roughly 256 MB. Auto weighs cores, memory, frame count, and cost. N is a ceiling: a render drawElement can capture still uses one worker. | -| `--low-memory-mode` / `--no-low-memory-mode` | auto at 8 GB RAM or less | Safe profile: one worker, screenshot capture, no calibration. See the note below. | +| `--low-memory-mode` / `--no-low-memory-mode` | auto at 8 GB RAM or less | Safe profile: one worker, screenshot capture, no worker calibration. See the note below. | | `--gpu` | off | Hardware FFmpeg encoding (NVENC, VideoToolbox, AMF, VAAPI, QSV) | -| `--browser-gpu` / `--no-browser-gpu` | auto locally, off in Docker | Host GPU for Chrome and WebGL capture, or software rendering. Auto probes WebGL once and falls back. When calibration finds the GPU slow, auto also times software capture and renders in software if it is faster. | +| `--browser-gpu` / `--no-browser-gpu` | auto locally, off in Docker | Host GPU for Chrome and WebGL capture, or software rendering. Auto probes WebGL once and falls back. When calibration finds the GPU slow, auto also times software capture and renders in software if it is faster. `render` measures this once per machine, GPU driver and HyperFrames version (even with `--workers`), keeps the answer in `gpu-choice.json` under `HYPERFRAMES_CONFIG_DIR`, and reuses it. | | `--page-side-compositing` / `--no-page-side-compositing` | on | Page-side WebGL for SDR shader transitions in mp4, hls and gif, ~6× faster. webm and mov use the layered path; gif always uses page-side WebGL, even with `--no-page-side-compositing`. | | `--experimental-fast-capture` | on where it can engage | Chrome's draw-element capture, ~2× faster; falls back to screenshots on its own. Env: `PRODUCER_EXPERIMENTAL_FAST_CAPTURE`. | | `--frames-cache-dir` | `/hyperframes-extract-cache-` | Where extracted source frames cache. `off`, `none`, `false`, or `0` disables it. `doctor` reports the live value. | @@ -2943,7 +2943,7 @@ hyperframes auth logout --yes # no prompt | `HYPERFRAMES_API_KEY` | Alias for `HEYGEN_API_KEY`. | | `HEYGEN_ACCESS_TOKEN` | OAuth token from a host app; used first, never refreshed. | | `HEYGEN_API_URL` | API base URL (default `https://api.heygen.com`). | -| `HYPERFRAMES_CONFIG_DIR` | Settings root: credentials, telemetry and update settings, project links (default `~/.hyperframes`). | +| `HYPERFRAMES_CONFIG_DIR` | Settings root: credentials, telemetry and update settings, project links, the measured GPU choice (default `~/.hyperframes`). | | `HYPERFRAMES_ENV` | `prod` (default) or `dev`; `dev` uses a separate credential directory. Hosts and the OAuth client id come from `HEYGEN_API_URL` and `HYPERFRAMES_OAUTH_*`. | | `HYPERFRAMES_OAUTH_CLIENT_ID` | Override the selected public OAuth client. | diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index 0ece708611..43fb37494e 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { spawn } from "node:child_process"; import { VERSION } from "../version.js"; +import { hyperframesConfigDir } from "../utils/configDir.js"; const producerState = vi.hoisted(() => ({ createdJobs: [] as Array>, @@ -1068,6 +1069,12 @@ describe("renderLocal browser GPU config", () => { ]); }); + // Auto mode reuses the GPU choice measured on this machine, kept with the CLI's other state. + const AUTO_GPU_CHOICE = { + gpuChoiceFile: hyperframesConfigDir("gpu-choice.json"), + hyperframesVersion: VERSION, + }; + it("forwards browserGpuMode='auto' into producer config (probe-then-choose)", async () => { await renderLocal(PROJECT_DIR, "/tmp/out.mp4", { fps: { num: 30, den: 1 }, @@ -1081,6 +1088,7 @@ describe("renderLocal browser GPU config", () => { expect(producerState.resolveConfigCalls).toContainEqual({ browserGpuMode: "auto", + ...AUTO_GPU_CHOICE, forceScreenshot: false, beginFrameFirstFrameDeadlineMs: 20_000, }); @@ -1103,7 +1111,10 @@ describe("renderLocal browser GPU config", () => { hdrMode: "auto", quiet: true, }); - expect(producerState.resolveConfigCalls).toContainEqual({ browserGpuMode: "auto" }); + expect(producerState.resolveConfigCalls).toContainEqual({ + browserGpuMode: "auto", + ...AUTO_GPU_CHOICE, + }); expect(producerState.resolveConfigCalls[0]).not.toHaveProperty("forceScreenshot"); } finally { if (prev === undefined) delete process.env.PRODUCER_FORCE_SCREENSHOT; @@ -1123,7 +1134,10 @@ describe("renderLocal browser GPU config", () => { outputResolution: "landscape", }); - expect(producerState.resolveConfigCalls).toContainEqual({ browserGpuMode: "auto" }); + expect(producerState.resolveConfigCalls).toContainEqual({ + browserGpuMode: "auto", + ...AUTO_GPU_CHOICE, + }); expect(producerState.resolveConfigCalls[0]).not.toHaveProperty("forceScreenshot"); expect(producerState.resolveConfigCalls[0]).not.toHaveProperty( "beginFrameFirstFrameDeadlineMs", diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index db6d8dc198..61881b8421 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -115,6 +115,7 @@ import { } from "../telemetry/renderCpu.js"; import { bytesToMb } from "../telemetry/system.js"; import { VERSION } from "../version.js"; +import { hyperframesConfigDir } from "../utils/configDir.js"; import { afterCleanRender, afterRevert, @@ -1222,6 +1223,10 @@ async function executeLocalRender( const engineConfig = producer.resolveConfig({ browserGpuMode: options.browserGpuMode ?? "software", + ...(options.browserGpuMode === "auto" && { + gpuChoiceFile: hyperframesConfigDir("gpu-choice.json"), + hyperframesVersion: VERSION, + }), // Local auto opts out of the software-GPU screenshot clamp, and a BeginFrame that draws no first frame // retries by screenshot. Docker and --no-browser-gpu request software; --resolution supersamples via screenshot. ...(options.browserGpuMode === "auto" && diff --git a/packages/engine/src/config.ts b/packages/engine/src/config.ts index 3be2901591..5d41a752e8 100644 --- a/packages/engine/src/config.ts +++ b/packages/engine/src/config.ts @@ -41,6 +41,10 @@ export interface EngineConfig { // ── Browser ────────────────────────────────────────────────────────── chromePath?: string; + /** Where auto GPU mode keeps the GPU-or-software choice it measured on this machine; unset measures per render. */ + gpuChoiceFile?: string; + /** The HyperFrames version; a stored GPU choice is reused only by the version that measured it. */ + hyperframesVersion?: string; disableGpu: boolean; /** * Chrome/WebGL rendering backend. @@ -351,6 +355,8 @@ const OPTIONAL_ENGINE_CONFIG_FIELDS = [ "streamingEncodeAutoDisabledOnWin32Compound", "runtimeManifestPath", "extractCacheDir", + "gpuChoiceFile", + "hyperframesVersion", ] as const; const BOOLEAN_ENGINE_CONFIG_FIELDS = [ @@ -516,7 +522,13 @@ function validateEngineConfigHdr(config: Record): void { } function validateOptionalEngineConfigFields(config: Record): void { - for (const field of ["chromePath", "runtimeManifestPath", "extractCacheDir"] as const) { + for (const field of [ + "chromePath", + "runtimeManifestPath", + "extractCacheDir", + "gpuChoiceFile", + "hyperframesVersion", + ] as const) { if ( config[field] !== undefined && (typeof config[field] !== "string" || config[field].length === 0) diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index e24e4eb46b..e25b00b9b6 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -103,6 +103,7 @@ export { closeBrowserPool, resolveHeadlessShellPath, resolveBrowserGpuMode, + probedHardwareGpu, buildChromeArgs, compositionRequiresWebGpu, assertWebGpuAdapterAvailable, diff --git a/packages/engine/src/services/browserManager.ts b/packages/engine/src/services/browserManager.ts index 9d986963f3..82dfcb6c35 100644 --- a/packages/engine/src/services/browserManager.ts +++ b/packages/engine/src/services/browserManager.ts @@ -80,6 +80,7 @@ interface WebGlProbeInfo { hasWebGL: boolean; vendor: string; renderer: string; + driver?: string; } export const SOFTWARE_WEBGL_RENDERER_TOKENS: readonly string[] = [ @@ -146,8 +147,12 @@ async function probeHardwareWebGlInfo( ? options.probeLifecycle.launch(ppt, launchOptions) : ppt.launch(launchOptions); }); + const browser = probeBrowser; return await rejectAfter( - readWebGlInfo(probeBrowser), + readWebGlInfo(browser).then(async (info) => ({ + ...info, + driver: await readGpuDriver(browser), + })), GPU_PROBE_TIMEOUT_MS, `GPU probe page did not answer within ${GPU_PROBE_TIMEOUT_MS}ms`, ); @@ -189,6 +194,18 @@ async function readWebGlInfo(browser: Browser): Promise { }); } +async function readGpuDriver(browser: Browser): Promise { + try { + const cdp = await browser.target().createCDPSession(); + const { gpu } = await cdp.send("SystemInfo.getInfo"); + const device = gpu.devices[0]; + return device ? `${device.driverVendor} ${device.driverVersion}`.trim() : ""; + } catch { + // expected: a Chrome build without SystemInfo; the GPU's name still identifies it + return ""; + } +} + export type AcquiredBrowser = BrowserLease; const CACHED_HEADLESS_SHELL_EXECUTABLES: Readonly< @@ -548,6 +565,7 @@ interface GpuProbeOutcome { wslAccess?: string[]; /** Under WSL, Chrome reached the GPU only without WSLg's WAYLAND_DISPLAY. */ withoutWaylandDisplay?: boolean; + gpu?: string; } /** @@ -617,7 +635,7 @@ async function probeAutoBrowserGpuMode(options: GpuProbeOptions): Promise): NodeJS.Proc return env; } +export async function probedHardwareGpu(): Promise { + const outcome = await _autoBrowserGpuModeCache; + return outcome?.mode === "hardware" ? outcome.gpu || undefined : undefined; +} + /** True when a `resolvedMode` render must launch without WAYLAND_DISPLAY to reach the GPU. */ export async function captureWithoutWaylandDisplay( resolvedMode: "software" | "hardware", diff --git a/packages/producer/src/services/render/captureCost.autoGpu.test.ts b/packages/producer/src/services/render/captureCost.autoGpu.test.ts index ed801b7303..097f226d51 100644 --- a/packages/producer/src/services/render/captureCost.autoGpu.test.ts +++ b/packages/producer/src/services/render/captureCost.autoGpu.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { estimateMeasuredCaptureCostMultiplier, pickAutoGpuModeFromCalibration, + settleAutoGpuChoice, shouldCalibrateSoftwareGpu, } from "./captureCost.js"; @@ -77,3 +78,24 @@ describe("pickAutoGpuModeFromCalibration", () => { expect(pickAutoGpuModeFromCalibration(hardware, undefined)).toBe("hardware"); }); }); + +describe("settleAutoGpuChoice", () => { + const failed = { multiplier: 8, reasons: ["calibration-failed"] }; + + it("settles hardware without timing software when the GPU path is not slow", () => { + expect(settleAutoGpuChoice(measured(200, 220, 250, 300, 310), undefined)).toBe("hardware"); + }); + + it("settles whichever measured faster when the GPU path is slow", () => { + const slow = measured(1400, 1500, 1550, 1600, 1678); + expect(settleAutoGpuChoice(slow, measured(150, 160, 170, 180, 190))).toBe("software"); + expect(settleAutoGpuChoice(slow, measured(2000, 2100, 2200, 2300, 2400))).toBe("hardware"); + }); + + it("settles nothing when a calibration it needs measured nothing", () => { + expect(settleAutoGpuChoice(undefined, undefined)).toBeUndefined(); + expect(settleAutoGpuChoice(failed, undefined)).toBeUndefined(); + expect(settleAutoGpuChoice(measured(1400, 1500, 1550, 1600, 1678), failed)).toBeUndefined(); + expect(settleAutoGpuChoice(measured(1400, 1500, 1550, 1600, 1678), undefined)).toBeUndefined(); + }); +}); diff --git a/packages/producer/src/services/render/captureCost.ts b/packages/producer/src/services/render/captureCost.ts index 5e5e53ef09..7660e8f16d 100644 --- a/packages/producer/src/services/render/captureCost.ts +++ b/packages/producer/src/services/render/captureCost.ts @@ -265,13 +265,22 @@ export function shouldCalibrateSoftwareGpu( ); } +export function settleAutoGpuChoice( + hardware: CaptureCostEstimate | undefined, + software: CaptureCostEstimate | undefined, +): "software" | "hardware" | undefined { + if (hardware?.p95Ms === undefined) return undefined; + if (hardware.multiplier <= 1) return "hardware"; + if (software?.p95Ms === undefined) return undefined; + return software.p95Ms < hardware.p95Ms ? "software" : "hardware"; +} + /** Auto mode keeps the hardware GPU unless software measured strictly faster. */ export function pickAutoGpuModeFromCalibration( hardware: CaptureCostEstimate, software: CaptureCostEstimate | undefined, ): "software" | "hardware" { - if (hardware.p95Ms === undefined || software?.p95Ms === undefined) return "hardware"; - return software.p95Ms < hardware.p95Ms ? "software" : "hardware"; + return settleAutoGpuChoice(hardware, software) ?? "hardware"; } export function selectCaptureCalibrationFrames(totalFrames: number): number[] { diff --git a/packages/producer/src/services/render/gpuChoice.test.ts b/packages/producer/src/services/render/gpuChoice.test.ts new file mode 100644 index 0000000000..9717f233dc --- /dev/null +++ b/packages/producer/src/services/render/gpuChoice.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { gpuChoiceStore, readGpuChoice, writeGpuChoice } from "./gpuChoice.js"; + +const dirs: string[] = []; +afterEach(() => { + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); +const fileIn = () => { + const dir = mkdtempSync(join(tmpdir(), "hf-gpu-choice-")); + dirs.push(dir); + return join(dir, "state", "gpu-choice.json"); +}; +const cfg = (file: string, version = "1.2.3") => ({ + gpuChoiceFile: file, + hyperframesVersion: version, +}); +const GPU = "ANGLE (AMD, AMD Radeon(TM) 840M Graphics Direct3D11) | AMD 32.0.21025.10016"; + +describe("gpuChoiceStore", () => { + it("keys the choice by version and GPU", () => { + expect(gpuChoiceStore(cfg("/x/gpu-choice.json"), GPU)).toEqual({ + file: "/x/gpu-choice.json", + key: `1.2.3 | ${GPU}`, + }); + }); + + it("has no store without a file, a version or a probed GPU", () => { + expect(gpuChoiceStore({ hyperframesVersion: "1.2.3" }, GPU)).toBeUndefined(); + expect(gpuChoiceStore({ gpuChoiceFile: "/x/gpu-choice.json" }, GPU)).toBeUndefined(); + expect(gpuChoiceStore(cfg("/x/gpu-choice.json"), undefined)).toBeUndefined(); + }); +}); + +describe("readGpuChoice / writeGpuChoice", () => { + it("reads back what was written for the same key, creating the folder", () => { + const store = gpuChoiceStore(cfg(fileIn()), GPU)!; + writeGpuChoice(store, "software", { hardwareP95Ms: 1678, softwareP95Ms: 90 }); + expect(readGpuChoice(store)).toBe("software"); + expect(JSON.parse(readFileSync(store.file, "utf8"))).toMatchObject({ + key: store.key, + mode: "software", + hardwareP95Ms: 1678, + softwareP95Ms: 90, + }); + }); + + it("measures again when the version, GPU or driver changed", () => { + const file = fileIn(); + writeGpuChoice(gpuChoiceStore(cfg(file), GPU)!, "software", {}); + expect(readGpuChoice(gpuChoiceStore(cfg(file, "1.2.4"), GPU)!)).toBeUndefined(); + expect(readGpuChoice(gpuChoiceStore(cfg(file), `${GPU}.1`)!)).toBeUndefined(); + }); + + it("measures again when there is no file or it is not a choice", () => { + const store = gpuChoiceStore(cfg(fileIn()), GPU)!; + expect(readGpuChoice(store)).toBeUndefined(); + writeGpuChoice(store, "hardware", {}); + writeFileSync(store.file, "{not json"); + expect(readGpuChoice(store)).toBeUndefined(); + writeFileSync(store.file, JSON.stringify({ key: store.key, mode: "fast" })); + expect(readGpuChoice(store)).toBeUndefined(); + }); +}); diff --git a/packages/producer/src/services/render/gpuChoice.ts b/packages/producer/src/services/render/gpuChoice.ts new file mode 100644 index 0000000000..a4674f64f6 --- /dev/null +++ b/packages/producer/src/services/render/gpuChoice.ts @@ -0,0 +1,45 @@ +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; +import type { EngineConfig } from "@hyperframes/engine"; + +export type GpuChoice = "software" | "hardware"; + +/** Where this machine's measured GPU choice lives, and the key it is valid for. */ +export interface GpuChoiceStore { + file: string; + key: string; +} + +/** A store only when the caller gave a file and version and the probe reached a hardware GPU. */ +export function gpuChoiceStore( + cfg: Pick, + gpu: string | undefined, +): GpuChoiceStore | undefined { + if (!cfg.gpuChoiceFile || !cfg.hyperframesVersion || !gpu) return undefined; + return { file: cfg.gpuChoiceFile, key: `${cfg.hyperframesVersion} | ${gpu}` }; +} + +/** The stored choice when it was measured for this key; undefined means measure. */ +export function readGpuChoice(store: GpuChoiceStore): GpuChoice | undefined { + let record: { key?: unknown; mode?: unknown }; + try { + record = JSON.parse(readFileSync(store.file, "utf8")) as typeof record; + } catch { + // expected: no file yet, or one this version cannot read; both mean measure again + return undefined; + } + if (record?.key !== store.key) return undefined; + return record.mode === "software" || record.mode === "hardware" ? record.mode : undefined; +} + +export function writeGpuChoice( + store: GpuChoiceStore, + mode: GpuChoice, + measured: { hardwareP95Ms?: number; softwareP95Ms?: number }, +): void { + mkdirSync(dirname(store.file), { recursive: true }); + const temp = `${store.file}.${process.pid}.tmp`; + const record = { key: store.key, mode, ...measured, measuredAt: new Date().toISOString() }; + writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`); + renameSync(temp, store.file); +} diff --git a/packages/producer/src/services/renderOrchestrator.autoGpu.test.ts b/packages/producer/src/services/renderOrchestrator.autoGpu.test.ts index 7b83189cc6..971c9318b1 100644 --- a/packages/producer/src/services/renderOrchestrator.autoGpu.test.ts +++ b/packages/producer/src/services/renderOrchestrator.autoGpu.test.ts @@ -1,5 +1,5 @@ -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { resolveConfig, type EngineConfig } from "@hyperframes/engine"; @@ -18,6 +18,7 @@ const { state, CAPTURE_REACHED } = vi.hoisted(() => ({ sizedWith: [] as (number | undefined)[], hardwareP95Ms: 1678, softwareP95Ms: 90, + gpu: "AMD Radeon 840M | AMD 32.0" as string | undefined, }, CAPTURE_REACHED: "capture reached", })); @@ -31,6 +32,7 @@ vi.mock("@hyperframes/engine", async (importOriginal) => ({ ...(await importOriginal()), assertConfiguredFfmpegBinariesExist: () => {}, resolveBrowserGpuMode: async (mode: string) => (mode === "software" ? "software" : "hardware"), + probedHardwareGpu: async () => state.gpu, resolveHeadlessShellPath: () => "/opt/chrome-headless-shell", createCaptureSession: async () => ({ browserConsoleBuffer: [], options: {} }), initializeSession: async () => {}, @@ -139,6 +141,7 @@ beforeEach(() => { state.sizedWith = []; state.hardwareP95Ms = 1678; state.softwareP95Ms = 90; + state.gpu = "AMD Radeon 840M | AMD 32.0"; vi.stubEnv("HF_SEGMENTED_CAPTURE", "false"); }); afterEach(() => { @@ -146,15 +149,20 @@ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); -function render(browserGpuMode: EngineConfig["browserGpuMode"]): Promise { +function render( + browserGpuMode: EngineConfig["browserGpuMode"], + opts: { workers?: number; gpuChoiceFile?: string; hyperframesVersion?: string } = {}, +): Promise { const root = mkdtempSync(join(tmpdir(), "hf-auto-gpu-")); dirs.push(root); writeFileSync(join(root, "index.html"), "
"); + const { workers, ...store } = opts; const job = createRenderJob({ fps: 30, quality: "standard", hdrMode: "force-sdr", - producerConfig: resolveConfig({ browserGpuMode, lowMemoryMode: false }), + ...(workers !== undefined && { workers }), + producerConfig: resolveConfig({ browserGpuMode, lowMemoryMode: false, ...store }), logger: { info() {}, warn() {}, error() {}, debug() {} }, }); return executeRenderJob(job, root, join(root, "output.mp4")); @@ -181,3 +189,80 @@ it("never times software for an explicit hardware request", async () => { expect(state.sizedWith).toEqual([1678]); expect(state.captureGpuModes).toEqual(["hardware"]); }); + +describe("with a GPU choice file", () => { + const choiceFile = () => { + const dir = mkdtempSync(join(tmpdir(), "hf-gpu-choice-")); + dirs.push(dir); + return join(dir, "gpu-choice.json"); + }; + const reset = () => { + state.calibratedModes = []; + state.captureGpuModes = []; + state.sizedWith = []; + }; + + it("measures once with a given worker count, then reuses the choice without calibrating", async () => { + const gpuChoiceFile = choiceFile(); + const opts = { workers: 3, gpuChoiceFile, hyperframesVersion: "1.2.3" }; + await expect(render("auto", opts)).rejects.toThrow(CAPTURE_REACHED); + expect(state.calibratedModes).toEqual(["auto", "software"]); + expect(state.sizedWith).toEqual([undefined]); + expect(state.captureGpuModes).toEqual(["software"]); + expect(JSON.parse(readFileSync(gpuChoiceFile, "utf8"))).toMatchObject({ mode: "software" }); + + reset(); + await expect(render("auto", opts)).rejects.toThrow(CAPTURE_REACHED); + expect(state.calibratedModes).toEqual([]); + expect(state.captureGpuModes).toEqual(["software"]); + }); + + it("keeps a stored hardware choice without timing software", async () => { + const gpuChoiceFile = choiceFile(); + const opts = { gpuChoiceFile, hyperframesVersion: "1.2.3" }; + state.softwareP95Ms = 2400; + await expect(render("auto", opts)).rejects.toThrow(CAPTURE_REACHED); + expect(JSON.parse(readFileSync(gpuChoiceFile, "utf8"))).toMatchObject({ mode: "hardware" }); + + reset(); + state.softwareP95Ms = 90; + await expect(render("auto", opts)).rejects.toThrow(CAPTURE_REACHED); + expect(state.calibratedModes).toEqual(["auto"]); + expect(state.captureGpuModes).toEqual(["auto"]); + }); + + it("measures again when the GPU or the version changed", async () => { + const gpuChoiceFile = choiceFile(); + await expect( + render("auto", { workers: 3, gpuChoiceFile, hyperframesVersion: "1.2.3" }), + ).rejects.toThrow(CAPTURE_REACHED); + + reset(); + state.gpu = "AMD Radeon 840M | AMD 33.0"; + await expect( + render("auto", { workers: 3, gpuChoiceFile, hyperframesVersion: "1.2.3" }), + ).rejects.toThrow(CAPTURE_REACHED); + expect(state.calibratedModes).toEqual(["auto", "software"]); + + reset(); + await expect( + render("auto", { workers: 3, gpuChoiceFile, hyperframesVersion: "1.2.4" }), + ).rejects.toThrow(CAPTURE_REACHED); + expect(state.calibratedModes).toEqual(["auto", "software"]); + }); + + it("neither measures nor stores without a file, so a given worker count stays uncalibrated", async () => { + await expect(render("auto", { workers: 3 })).rejects.toThrow(CAPTURE_REACHED); + expect(state.calibratedModes).toEqual([]); + expect(state.captureGpuModes).toEqual(["auto"]); + }); + + it("neither measures nor stores for an explicit GPU request", async () => { + const gpuChoiceFile = choiceFile(); + await expect( + render("hardware", { workers: 3, gpuChoiceFile, hyperframesVersion: "1.2.3" }), + ).rejects.toThrow(CAPTURE_REACHED); + expect(state.calibratedModes).toEqual([]); + expect(existsSync(gpuChoiceFile)).toBe(false); + }); +}); diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts index 4728636ab8..b1c34453f5 100644 --- a/packages/producer/src/services/renderOrchestrator.ts +++ b/packages/producer/src/services/renderOrchestrator.ts @@ -101,6 +101,7 @@ import { type WorkerSizing, type StaticVerificationOutcome, resolveBrowserGpuMode, + probedHardwareGpu, resolveHeadlessShellPath, compositionRequiresWebGpu, applyConcreteGpuScreenshotClamp, @@ -231,9 +232,11 @@ import { resolveRenderWorkerCount, pickAutoGpuModeFromCalibration, runCaptureCalibration, + settleAutoGpuChoice, selectCaptureCalibrationFrames, shouldCalibrateSoftwareGpu, } from "./render/captureCost.js"; +import { gpuChoiceStore, readGpuChoice, writeGpuChoice } from "./render/gpuChoice.js"; import { computeCompositionObservabilityHash, RenderObservabilityRecorder, @@ -3868,6 +3871,26 @@ async function executeRenderPipeline(input: { chromePath: resolveHeadlessShellPath(cfg), browserTimeout: cfg.browserTimeout, }); + // The probe browser runs on the GPU auto mode first chose; a switch to software must not reuse it. + const closeProbeSession = async (): Promise => { + if (!probeSession) return; + lastBrowserConsole = probeSession.browserConsoleBuffer; + await closeCaptureSession(probeSession).catch(() => {}); + probeSession = null; + }; + const gpuStore = + cfg.browserGpuMode === "auto" && resolvedBrowserGpuMode === "hardware" + ? gpuChoiceStore(cfg, await probedHardwareGpu()) + : undefined; + const storedGpuChoice = gpuStore && readGpuChoice(gpuStore); + if (gpuStore && storedGpuChoice === "software") { + log.info("[Render] Auto GPU mode: rendering in software, as measured on this machine.", { + file: gpuStore.file, + }); + cfg.browserGpuMode = "software"; + resolvedBrowserGpuMode = "software"; + await closeProbeSession(); + } startingFrameCapture(); // Apply the software-GPU→screenshot clamp to the AUTHORITATIVE local // `captureForceScreenshot` (not just the observability copy) so all @@ -4343,14 +4366,16 @@ async function executeRenderPipeline(input: { }, }); - if ( + const sizeByCalibration = job.config.workers === undefined && totalFrames >= 60 && !htmlInCanvasDetected && !cfg.lowMemoryMode && !deInversionEligible && - !deParallelRouterEligible - ) { + !deParallelRouterEligible; + // A machine with no stored GPU choice measures it once, even when the worker count is given. + const measureGpuChoice = gpuStore !== undefined && storedGpuChoice === undefined; + if (sizeByCalibration || measureGpuChoice) { updateJobStatus(job, "rendering", "Measuring capture speed", 25, onProgress, { code: "start_browsers", }); @@ -4397,6 +4422,7 @@ async function executeRenderPipeline(input: { }); probeSession = result.probeSession; if ( + storedGpuChoice === undefined && shouldCalibrateSoftwareGpu( cfg.browserGpuMode, resolvedBrowserGpuMode, @@ -4423,7 +4449,7 @@ async function executeRenderPipeline(input: { calibrationFrames?.release(); } startingFrameCapture(); - captureCalibration = outcome.calibration; + if (sizeByCalibration) captureCalibration = outcome.calibration; calibrationEvaluateTimedOut = outcome.calibrationEvaluateTimedOut; captureForceScreenshot = outcome.forceScreenshot; updateCaptureObservability({ forceScreenshot: captureForceScreenshot }); @@ -4447,19 +4473,33 @@ async function executeRenderPipeline(input: { ); cfg.browserGpuMode = "software"; resolvedBrowserGpuMode = "software"; - captureCalibration = softwareOutcome.calibration; + if (sizeByCalibration) captureCalibration = softwareOutcome.calibration; captureForceScreenshot = softwareOutcome.forceScreenshot; - // The probe browser runs on the hardware GPU; the capture stage opens its own. - if (probeSession) { - lastBrowserConsole = probeSession.browserConsoleBuffer; - await closeCaptureSession(probeSession).catch(() => {}); - probeSession = null; - } + await closeProbeSession(); updateCaptureObservability({ browserGpuMode: resolvedBrowserGpuMode, forceScreenshot: captureForceScreenshot, }); } + const settledGpuChoice = measureGpuChoice + ? settleAutoGpuChoice(outcome.calibration?.estimate, softwareOutcome?.calibration?.estimate) + : undefined; + if (gpuStore && settledGpuChoice) { + try { + writeGpuChoice(gpuStore, settledGpuChoice, { + hardwareP95Ms: outcome.calibration?.estimate.p95Ms, + softwareP95Ms: softwareOutcome?.calibration?.estimate.p95Ms, + }); + } catch (error) { + log.warn( + "[Render] Could not save the measured GPU choice; the next render measures again.", + { + file: gpuStore.file, + error: error instanceof Error ? error.message : String(error), + }, + ); + } + } observability.checkpoint("capture_calibration", "resolved", { forceScreenshot: captureForceScreenshot, browserGpuMode: resolvedBrowserGpuMode,