fix(producer): auto GPU mode renders in software when software captures faster (#8785)

* fix(producer): auto GPU mode renders in software when software captures faster

On a Windows laptop with an AMD Radeon 840M, auto mode picked the hardware
GPU, calibration measured screenshot capture at ~1.6 s/frame p95, and the
render dropped to 1 worker: a 10 s clip took 5m27s. Software WebGL
captured the same frames at ~0.28 s/frame on 5 workers.

When auto mode resolved to hardware and calibration measured it slow, time
software too and keep whichever is faster. Explicit --browser-gpu and
--no-browser-gpu are unchanged.

* test(producer): pin the auto GPU switch to software and document it

The orchestrator test drives a render in auto mode with a slow hardware
calibration and a faster software one, and checks that capture gets
browserGpuMode software and worker sizing uses the software estimate.
The CLI docs say auto can now switch to software after calibration.
This commit is contained in:
Miguel Ángel
2026-11-25 00:43:02 +00:00
committed by GitHub
parent 886e5d4f43
commit c5ed60fc83
5 changed files with 362 additions and 18 deletions
+1 -1
View File
@@ -2123,7 +2123,7 @@ How it uses the machine, and when it gives up:
| `--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. |
| `--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. |
| `--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. |
| `--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` | `<tmpdir>/hyperframes-extract-cache-<uid>` | Where extracted source frames cache. `off`, `none`, `false`, or `0` disables it. `doctor` reports the live value. |
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import {
estimateMeasuredCaptureCostMultiplier,
pickAutoGpuModeFromCalibration,
shouldCalibrateSoftwareGpu,
} from "./captureCost.js";
const measured = (...ms: number[]) =>
estimateMeasuredCaptureCostMultiplier(
ms.map((captureTimeMs, frameIndex) => ({ frameIndex, captureTimeMs })),
);
describe("shouldCalibrateSoftwareGpu", () => {
const slowHardware = measured(1400, 1500, 1550, 1600, 1678);
it("measures software when auto mode picked a hardware GPU that calibrated slow", () => {
expect(shouldCalibrateSoftwareGpu("auto", "hardware", slowHardware)).toBe(true);
});
it("leaves an explicit GPU choice alone", () => {
expect(shouldCalibrateSoftwareGpu("hardware", "hardware", slowHardware)).toBe(false);
});
it("does nothing when auto already picked software", () => {
expect(shouldCalibrateSoftwareGpu("auto", "software", slowHardware)).toBe(false);
});
it("does nothing when the hardware path calibrated at baseline cost", () => {
expect(shouldCalibrateSoftwareGpu("auto", "hardware", measured(200, 220, 250, 300, 310))).toBe(
false,
);
});
it("does nothing when calibration failed and measured no frames", () => {
expect(
shouldCalibrateSoftwareGpu("auto", "hardware", {
multiplier: 8,
reasons: ["calibration-failed"],
}),
).toBe(false);
});
});
describe("pickAutoGpuModeFromCalibration", () => {
it("picks software when it captures faster than the hardware GPU (AMD Radeon 840M, D3D11)", () => {
expect(
pickAutoGpuModeFromCalibration(
measured(1400, 1500, 1550, 1600, 1678),
measured(150, 160, 170, 180, 190),
),
).toBe("software");
});
it("keeps hardware when it captures faster than software", () => {
expect(
pickAutoGpuModeFromCalibration(
measured(700, 720, 750, 760, 800),
measured(2000, 2100, 2200, 2300, 2400),
),
).toBe("hardware");
});
it("keeps hardware on a tie", () => {
expect(
pickAutoGpuModeFromCalibration(
measured(900, 900, 900, 900, 900),
measured(900, 900, 900, 900, 900),
),
).toBe("hardware");
});
it("keeps hardware when software calibration failed or did not run", () => {
const hardware = measured(1400, 1500, 1550, 1600, 1678);
expect(
pickAutoGpuModeFromCalibration(hardware, { multiplier: 8, reasons: ["calibration-failed"] }),
).toBe("hardware");
expect(pickAutoGpuModeFromCalibration(hardware, undefined)).toBe("hardware");
});
});
@@ -250,6 +250,30 @@ export function estimateMeasuredCaptureCostMultiplier(
};
}
/** Auto mode chose the hardware GPU and calibration measured it slow: worth timing software too. */
export function shouldCalibrateSoftwareGpu(
requestedMode: EngineConfig["browserGpuMode"],
resolvedMode: "software" | "hardware",
hardware: CaptureCostEstimate | undefined,
): boolean {
return (
requestedMode === "auto" &&
resolvedMode === "hardware" &&
hardware !== undefined &&
hardware.multiplier > 1 &&
hardware.p95Ms !== undefined
);
}
/** 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";
}
export function selectCaptureCalibrationFrames(totalFrames: number): number[] {
if (totalFrames <= 0) return [];
const lastFrame = totalFrames - 1;
@@ -0,0 +1,183 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { resolveConfig, type EngineConfig } from "@hyperframes/engine";
import {
estimateMeasuredCaptureCostMultiplier,
type CaptureCostEstimate,
} from "./render/captureCost.js";
import { createRenderJob, executeRenderJob } from "./renderOrchestrator.js";
// Entry: executeRenderJob in auto GPU mode with the probe resolving to hardware and calibration
// scripted per GPU mode. The capture stage records what it was given and ends the render there.
const { state, CAPTURE_REACHED } = vi.hoisted(() => ({
state: {
calibratedModes: [] as string[],
captureGpuModes: [] as string[],
sizedWith: [] as (number | undefined)[],
hardwareP95Ms: 1678,
softwareP95Ms: 90,
},
CAPTURE_REACHED: "capture reached",
}));
const estimate = (p95Ms: number): CaptureCostEstimate =>
estimateMeasuredCaptureCostMultiplier(
[0, 1, 2, 3, 4].map((frameIndex) => ({ frameIndex, captureTimeMs: p95Ms })),
);
vi.mock("@hyperframes/engine", async (importOriginal) => ({
...(await importOriginal<typeof import("@hyperframes/engine")>()),
assertConfiguredFfmpegBinariesExist: () => {},
resolveBrowserGpuMode: async (mode: string) => (mode === "software" ? "software" : "hardware"),
resolveHeadlessShellPath: () => "/opt/chrome-headless-shell",
createCaptureSession: async () => ({ browserConsoleBuffer: [], options: {} }),
initializeSession: async () => {},
closeCaptureSession: async () => {},
}));
vi.mock("./fileServer.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./fileServer.js")>()),
createFileServer: async () => ({
url: "http://127.0.0.1:1",
port: 1,
close: () => {},
addPreHeadScript: () => {},
}),
}));
vi.mock("./render/stages/compileStage.js", () => ({
runCompileStage: async () => ({
compiled: {
html: "<div></div>",
renderModeHints: { reasons: [] },
hasShaderTransitions: false,
unresolvedCompositions: [],
},
composition: { width: 320, height: 180, duration: 4, videos: [], images: [], audios: [] },
deviceScaleFactor: 1,
outputWidth: 320,
outputHeight: 180,
compileOnlyMs: 0,
forceScreenshot: true,
}),
}));
vi.mock("./render/stages/probeStage.js", () => ({
runProbeStage: async ({ compiled }: { compiled: object }) => ({
compiled,
fileServer: null,
probeSession: null,
lastBrowserConsole: [],
duration: 4,
totalFrames: 120,
browserProbeMs: 0,
}),
}));
vi.mock("./render/stages/extractVideosStage.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./render/stages/extractVideosStage.js")>()),
runExtractVideosStage: async () => ({
extractionResult: null,
frameLookup: null,
videoReadinessSkipIds: new Set<string>(),
videoMetadataHints: new Map(),
nativeHdrVideoIds: new Set<string>(),
videoTransfers: new Map(),
nativeHdrImageIds: new Set<string>(),
imageTransfers: new Map(),
hdrImageSrcPaths: new Map(),
imageColorSpaces: [],
videoExtractMs: 0,
failureToEnforce: undefined,
}),
}));
vi.mock("./render/stages/audioStage.js", () => ({
runAudioStage: async () => ({ audioOutputPath: undefined, hasAudio: false, audioProcessMs: 0 }),
}));
vi.mock("./render/captureCost.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./render/captureCost.js")>()),
resolveRenderWorkerCount: (
_frames: number,
_workers: number | undefined,
_cfg: EngineConfig,
_compiled: unknown,
_log: unknown,
measured?: CaptureCostEstimate,
) => {
state.sizedWith.push(measured?.p95Ms);
return 1;
},
runCaptureCalibration: async (input: {
cfg: EngineConfig;
forceScreenshot: boolean;
probeSession: unknown;
}) => {
state.calibratedModes.push(input.cfg.browserGpuMode);
const software = input.cfg.browserGpuMode === "software";
return {
calibration: {
estimate: estimate(software ? state.softwareP95Ms : state.hardwareP95Ms),
samples: [],
},
forceScreenshot: input.forceScreenshot,
probeSession: input.probeSession,
lastBrowserConsole: [],
calibrationEvaluateTimedOut: false,
};
},
}));
vi.mock("./render/stages/captureStreamingStage.js", async (importOriginal) => ({
...(await importOriginal<typeof import("./render/stages/captureStreamingStage.js")>()),
runCaptureStreamingStage: async (input: { cfg: EngineConfig }) => {
state.captureGpuModes.push(input.cfg.browserGpuMode);
throw new Error(CAPTURE_REACHED);
},
}));
const dirs: string[] = [];
beforeEach(() => {
state.calibratedModes = [];
state.captureGpuModes = [];
state.sizedWith = [];
state.hardwareP95Ms = 1678;
state.softwareP95Ms = 90;
vi.stubEnv("HF_SEGMENTED_CAPTURE", "false");
});
afterEach(() => {
vi.unstubAllEnvs();
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
function render(browserGpuMode: EngineConfig["browserGpuMode"]): Promise<void> {
const root = mkdtempSync(join(tmpdir(), "hf-auto-gpu-"));
dirs.push(root);
writeFileSync(join(root, "index.html"), "<div></div>");
const job = createRenderJob({
fps: 30,
quality: "standard",
hdrMode: "force-sdr",
producerConfig: resolveConfig({ browserGpuMode, lowMemoryMode: false }),
logger: { info() {}, warn() {}, error() {}, debug() {} },
});
return executeRenderJob(job, root, join(root, "output.mp4"));
}
it("captures in software, sized by the software calibration, when auto mode's hardware GPU calibrates slower", async () => {
await expect(render("auto")).rejects.toThrow(CAPTURE_REACHED);
expect(state.calibratedModes).toEqual(["auto", "software"]);
expect(state.sizedWith).toEqual([90]);
expect(state.captureGpuModes).toEqual(["software"]);
});
it("keeps the hardware GPU when software calibrates slower", async () => {
state.softwareP95Ms = 2400;
await expect(render("auto")).rejects.toThrow(CAPTURE_REACHED);
expect(state.calibratedModes).toEqual(["auto", "software"]);
expect(state.sizedWith).toEqual([1678]);
expect(state.captureGpuModes).toEqual(["auto"]);
});
it("never times software for an explicit hardware request", async () => {
await expect(render("hardware")).rejects.toThrow(CAPTURE_REACHED);
expect(state.calibratedModes).toEqual(["hardware"]);
expect(state.sizedWith).toEqual([1678]);
expect(state.captureGpuModes).toEqual(["hardware"]);
});
@@ -229,8 +229,10 @@ import {
type CaptureCostEstimate,
buildHeapAdvisoryWarning,
resolveRenderWorkerCount,
pickAutoGpuModeFromCalibration,
runCaptureCalibration,
selectCaptureCalibrationFrames,
shouldCalibrateSoftwareGpu,
} from "./render/captureCost.js";
import {
computeCompositionObservabilityHash,
@@ -3862,7 +3864,7 @@ async function executeRenderPipeline(input: {
updateJobStatus(job, "rendering", "Checking browser GPU", 25, onProgress, {
code: "start_browsers",
});
const resolvedBrowserGpuMode = await resolveBrowserGpuMode(cfg.browserGpuMode, {
let resolvedBrowserGpuMode = await resolveBrowserGpuMode(cfg.browserGpuMode, {
chromePath: resolveHeadlessShellPath(cfg),
browserTimeout: cfg.browserTimeout,
});
@@ -4361,6 +4363,18 @@ async function executeRenderPipeline(input: {
)
: undefined;
let outcome: Awaited<ReturnType<typeof runCaptureCalibration>>;
let softwareOutcome: Awaited<ReturnType<typeof runCaptureCalibration>> | undefined;
const calibrationInput = {
fileServer: activeFileServer,
log,
job,
totalFrames,
buildCaptureOptions: buildPrepCaptureOptions,
createRenderVideoFrameInjector: calibrationFrames
? calibrationFrames.injector
: createRenderVideoFrameInjector,
assertNotAborted,
};
try {
outcome = await observeRenderStage(
observability,
@@ -4373,22 +4387,36 @@ async function executeRenderPipeline(input: {
// ts=1784019503.
stagePhase: "calibrating",
}),
() =>
runCaptureCalibration({
async () => {
const result = await runCaptureCalibration({
...calibrationInput,
cfg: calibrationCaptureConfig(cfg),
fileServer: activeFileServer,
workDir,
log,
job,
totalFrames,
forceScreenshot: captureForceScreenshot,
probeSession,
buildCaptureOptions: buildPrepCaptureOptions,
createRenderVideoFrameInjector: calibrationFrames
? calibrationFrames.injector
: createRenderVideoFrameInjector,
assertNotAborted,
}),
});
probeSession = result.probeSession;
if (
shouldCalibrateSoftwareGpu(
cfg.browserGpuMode,
resolvedBrowserGpuMode,
result.calibration?.estimate,
)
) {
softwareOutcome = await runCaptureCalibration({
...calibrationInput,
cfg: calibrationCaptureConfig({ ...cfg, browserGpuMode: "software" }),
workDir: join(workDir, "software-gpu"),
forceScreenshot: applyConcreteGpuScreenshotClamp(
captureForceScreenshot,
"software",
cfg,
),
probeSession: null,
});
}
return result;
},
{ heartbeatMessage: "browser calibrating (frames not started)" },
);
} finally {
@@ -4399,15 +4427,45 @@ async function executeRenderPipeline(input: {
calibrationEvaluateTimedOut = outcome.calibrationEvaluateTimedOut;
captureForceScreenshot = outcome.forceScreenshot;
updateCaptureObservability({ forceScreenshot: captureForceScreenshot });
probeSession = outcome.probeSession;
if (outcome.lastBrowserConsole.length > 0) {
lastBrowserConsole = outcome.lastBrowserConsole;
}
if (
softwareOutcome &&
outcome.calibration &&
pickAutoGpuModeFromCalibration(
outcome.calibration.estimate,
softwareOutcome.calibration?.estimate,
) === "software"
) {
log.warn(
"[Render] Auto GPU mode: software capture measured faster than the hardware GPU, rendering in software.",
{
hardwareP95Ms: outcome.calibration.estimate.p95Ms,
softwareP95Ms: softwareOutcome.calibration?.estimate.p95Ms,
},
);
cfg.browserGpuMode = "software";
resolvedBrowserGpuMode = "software";
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;
}
updateCaptureObservability({
browserGpuMode: resolvedBrowserGpuMode,
forceScreenshot: captureForceScreenshot,
});
}
observability.checkpoint("capture_calibration", "resolved", {
forceScreenshot: captureForceScreenshot,
multiplier: outcome.calibration?.estimate.multiplier ?? null,
p95Ms: outcome.calibration?.estimate.p95Ms ?? null,
medianMs: outcome.calibration?.estimate.medianMs ?? null,
browserGpuMode: resolvedBrowserGpuMode,
multiplier: captureCalibration?.estimate.multiplier ?? null,
p95Ms: captureCalibration?.estimate.p95Ms ?? null,
medianMs: captureCalibration?.estimate.medianMs ?? null,
});
} else {
observability.checkpoint("capture_calibration", "skipped", {