diff --git a/packages/engine/src/utils/shaderTransitions.test.ts b/packages/engine/src/utils/shaderTransitions.test.ts index 0d8ecc4ba3..dfc1829a04 100644 --- a/packages/engine/src/utils/shaderTransitions.test.ts +++ b/packages/engine/src/utils/shaderTransitions.test.ts @@ -736,3 +736,12 @@ describe("convertTransfer", () => { expect(buf.readUInt16LE(0)).not.toBe(before); }); }); + +describe("TRANSITIONS lookup", () => { + it.each(["constructor", "toString", "__proto__", "hasOwnProperty"])( + "finds no transition for the inherited name %s", + (name) => { + expect(TRANSITIONS[name] ?? crossfade).toBe(crossfade); + }, + ); +}); diff --git a/packages/engine/src/utils/shaderTransitions.ts b/packages/engine/src/utils/shaderTransitions.ts index 6a20d64557..0524eaede5 100644 --- a/packages/engine/src/utils/shaderTransitions.ts +++ b/packages/engine/src/utils/shaderTransitions.ts @@ -349,8 +349,8 @@ export type TransitionFn = ( progress: number, ) => void; -/** Registry of all available transitions by name. */ -export const TRANSITIONS: Record = {}; +/** Registry of all available transitions by name; prototype-free, so `constructor` finds nothing. */ +export const TRANSITIONS: Record = Object.create(null); // ── crossfade ───────────────────────────────────────────────────────────────── diff --git a/packages/producer/src/server.escapedRejection.test.ts b/packages/producer/src/server.escapedRejection.test.ts new file mode 100644 index 0000000000..f523182c82 --- /dev/null +++ b/packages/producer/src/server.escapedRejection.test.ts @@ -0,0 +1,62 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { EscapedRejectionError } from "./services/renderOrchestrator.js"; +import { onEscapedRejection, runInRenderScope } from "./server.js"; + +const testLog = () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }); +type RejectionListener = (reason: unknown, promise: Promise) => void; + +describe("a rejection nobody handled during a render", () => { + const log = testLog(); + let runnerListeners: RejectionListener[] = []; + const handler: RejectionListener = (reason) => onEscapedRejection(reason, log); + beforeEach(() => { + // Stand in for the server: only its handler hears rejections during the test. + runnerListeners = process.listeners("unhandledRejection"); + process.removeAllListeners("unhandledRejection"); + process.on("unhandledRejection", handler); + }); + afterEach(() => { + process.off("unhandledRejection", handler); + for (const listener of runnerListeners) process.on("unhandledRejection", listener); + }); + + // A render that runs until it is aborted or told to finish, like the pipeline does. + const render = (requestId: string, finish: Promise, leak = false) => + runInRenderScope(requestId, new AbortController(), async (signal) => { + await new Promise((r) => setTimeout(r, 0)); + // Work this render started, whose failure nobody handles. + if (leak) void Promise.reject(new Error("lost blend")); + await Promise.race([ + finish, + new Promise((_resolve, reject) => + signal.addEventListener("abort", () => reject(signal.reason)), + ), + ]); + return requestId; + }); + + it("fails only the render it came from, with its own error, and logs that render", async () => { + let finishOther = () => {}; + const other = render("req-2", new Promise((r) => (finishOther = r))); + const leaking = render("req-1", new Promise(() => {}), true); + + const failure = await leaking.catch((err: unknown) => err); + expect(failure).toBeInstanceOf(EscapedRejectionError); + expect(failure).toMatchObject({ message: "lost blend" }); + expect(log.error).toHaveBeenCalledWith( + "Unhandled promise rejection", + expect.objectContaining({ requestId: "req-1", error: "lost blend" }), + ); + + finishOther(); + await expect(other).resolves.toBe("req-2"); + }); + + it("outside any render is logged and does not throw", () => { + expect(() => onEscapedRejection("stray", log)).not.toThrow(); + expect(log.error).toHaveBeenCalledWith( + "Unhandled promise rejection", + expect.objectContaining({ requestId: null, error: "stray" }), + ); + }); +}); diff --git a/packages/producer/src/server.ts b/packages/producer/src/server.ts index 7b300d1c68..c246ded599 100644 --- a/packages/producer/src/server.ts +++ b/packages/producer/src/server.ts @@ -33,6 +33,7 @@ import { rmSync, createReadStream, } from "node:fs"; +import { AsyncLocalStorage } from "node:async_hooks"; import { basename, resolve, dirname, join } from "node:path"; import { homedir, tmpdir } from "node:os"; import { parseArgs } from "node:util"; @@ -50,6 +51,7 @@ import { isSafePath } from "@hyperframes/core/safe-path"; import { foreignWritablePath } from "@hyperframes/core/cache-dir"; import { RenderCancelledError, + EscapedRejectionError, createRenderJob, executeRenderJob, resolveRenderDebugDir, @@ -1018,11 +1020,14 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle }); try { - await executeRenderJob( - job, - input.projectDir, - absoluteOutputPath, - createBlockingProgressReporter(log, requestId), + await runInRenderScope(requestId, new AbortController(), (signal) => + executeRenderJob( + job, + input.projectDir, + absoluteOutputPath, + createBlockingProgressReporter(log, requestId), + signal, + ), ); const fileSize = outputFileSize(absoluteOutputPath); @@ -1129,12 +1134,8 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle const release = await renderSemaphore.acquire(); try { - await executeRenderJob( - job, - input.projectDir, - absoluteOutputPath, - reportProgress, - abortController.signal, + await runInRenderScope(requestId, abortController, (signal) => + executeRenderJob(job, input.projectDir, absoluteOutputPath, reportProgress, signal), ).finally(release); clearInterval(keepalive); @@ -1340,6 +1341,29 @@ export function createProducerApp(options: HandlerOptions = {}): Hono { return app; } +const renderScope = new AsyncLocalStorage<{ requestId: string; fail: (err: Error) => void }>(); + +/** Runs a render so a rejection nobody handled inside it fails that render only. */ +export function runInRenderScope( + requestId: string, + abortController: AbortController, + run: (signal: AbortSignal) => Promise, +): Promise { + const fail = (err: Error) => abortController.abort(new EscapedRejectionError(err)); + return renderScope.run({ requestId, fail }, () => run(abortController.signal)); +} + +export function onEscapedRejection(reason: unknown, log: ProducerLogger): void { + const err = reason instanceof Error ? reason : new Error(String(reason)); + const scope = renderScope.getStore(); + log.error("Unhandled promise rejection", { + requestId: scope?.requestId ?? null, + error: err.message, + stack: err.stack, + }); + scope?.fail(err); +} + // --------------------------------------------------------------------------- // Standalone server // --------------------------------------------------------------------------- @@ -1448,6 +1472,7 @@ export function startServer(options: ServerOptions = {}) { } process.on("SIGTERM", () => shutdown("SIGTERM")); + process.on("unhandledRejection", (reason) => onEscapedRejection(reason, log)); process.on("SIGINT", () => shutdown("SIGINT")); return server; diff --git a/packages/producer/src/services/hdrCompositor.test.ts b/packages/producer/src/services/hdrCompositor.test.ts index f08d45b39d..ee2b86d51a 100644 --- a/packages/producer/src/services/hdrCompositor.test.ts +++ b/packages/producer/src/services/hdrCompositor.test.ts @@ -1,9 +1,13 @@ import { mkdtempSync, openSync, closeSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import type { ElementStackingInfo } from "@hyperframes/engine"; -import { blitHdrVideoLayer, selectDomLayerShowIds } from "./hdrCompositor.js"; +import { + blitHdrVideoLayer, + sanitizeTransitionMeta, + selectDomLayerShowIds, +} from "./hdrCompositor.js"; function makeEl(id: string, overrides?: Partial): ElementStackingInfo { return { @@ -158,3 +162,26 @@ describe("blitHdrVideoLayer", () => { ).rejects.toThrow("HDR frame extraction failed"); }); }); + +describe("sanitizeTransitionMeta", () => { + it("keeps well-formed entries, drops malformed ones, and keeps only registered shaders", () => { + const warn = vi.fn(); + const good = { time: 1, duration: 0.5, ease: "power2", fromScene: "a", toScene: "b" }; + const kept = sanitizeTransitionMeta( + [ + { ...good, shader: "crossfade" }, + { ...good, shader: "constructor" }, + { ...good, shader: "not-a-shader" }, + { ...good, shader: 7 }, + { ...good, time: Number.NaN }, + { ...good, duration: "1" }, + { ...good, fromScene: 3 }, + null, + "x", + ], + warn, + ); + expect(kept).toEqual([{ ...good, shader: "crossfade" }, good, good, good]); + expect(sanitizeTransitionMeta({ length: 1 }, warn)).toEqual([]); + }); +}); diff --git a/packages/producer/src/services/hdrCompositor.ts b/packages/producer/src/services/hdrCompositor.ts index 1e17dfefe8..b0a5e5b320 100644 --- a/packages/producer/src/services/hdrCompositor.ts +++ b/packages/producer/src/services/hdrCompositor.ts @@ -20,6 +20,7 @@ import { type HdrTransfer, type ElementStackingInfo, type HfTransitionMeta, + TRANSITIONS, captureAlphaPng, applyDomLayerMask, removeDomLayerMask, @@ -92,6 +93,49 @@ function resolveBlitOpacity(opacity: number): number | undefined { */ export type HdrTransitionMeta = HfTransitionMeta; +const isTime = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v) && v >= 0; + +/** + * The page's `window.__hf.transitions`, kept only where it is well formed: + * finite non-negative `time` and `duration` and string scene ids. A `shader` + * that is not a string or not a registered transition is dropped, which gives + * the crossfade the layered path already uses for a transition with no shader. + */ +export function sanitizeTransitionMeta( + raw: unknown, + warn: (message: string, meta: Record) => void, +): HdrTransitionMeta[] { + if (!Array.isArray(raw)) return []; + const kept: HdrTransitionMeta[] = []; + for (const [index, entry] of raw.entries()) { + if ( + typeof entry !== "object" || + entry === null || + !isTime(entry.time) || + !isTime(entry.duration) || + typeof entry.fromScene !== "string" || + typeof entry.toScene !== "string" + ) { + warn("[Render] Ignoring malformed shader transition entry", { index }); + continue; + } + const { shader } = entry; + const known = typeof shader === "string" && Object.hasOwn(TRANSITIONS, shader); + if (shader !== undefined && !known) { + warn("[Render] Unknown shader transition; using crossfade", { index }); + } + kept.push({ + time: entry.time, + duration: entry.duration, + ease: typeof entry.ease === "string" ? entry.ease : "", + fromScene: entry.fromScene, + toScene: entry.toScene, + ...(known ? { shader } : {}), + }); + } + return kept; +} + /** Pre-computed frame range for an active transition. */ export interface TransitionRange extends HdrTransitionMeta { startFrame: number; diff --git a/packages/producer/src/services/render/stages/captureHdrHybridLoop.test.ts b/packages/producer/src/services/render/stages/captureHdrHybridLoop.test.ts new file mode 100644 index 0000000000..ab0220df1d --- /dev/null +++ b/packages/producer/src/services/render/stages/captureHdrHybridLoop.test.ts @@ -0,0 +1,156 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { ShaderBlendRequest } from "../../shaderTransitionWorkerPool.js"; +import { type HybridLoopInput, runHybridLayeredFrameLoop } from "./captureHdrHybridLoop.js"; + +vi.mock("@hyperframes/engine", async (importOriginal) => ({ + ...(await importOriginal()), + createCaptureSession: vi.fn(async () => ({ page: {} })), + initializeSession: vi.fn(async () => {}), + initTransparentBackground: vi.fn(async () => {}), + closeCaptureSession: vi.fn(async () => {}), +})); +vi.mock("./captureHdrFrameShared.js", async (importOriginal) => ({ + ...(await importOriginal()), + captureTransitionFrameOnWorker: vi.fn(async () => {}), + seekInjectAndQueryStacking: vi.fn(async () => ({})), +})); +vi.mock("../../hdrCompositor.js", async (importOriginal) => ({ + ...(await importOriginal()), + compositeHdrFrame: vi.fn(async () => {}), +})); + +let blendsInFlight = 0; +let blendsInFlightAtTerminate: number | undefined; +let failBlend = (_call: number) => false; +let blendCalls = 0; +const pool = { + size: 2, + run: vi.fn(async (req: ShaderBlendRequest) => { + const call = ++blendCalls; + blendsInFlight++; + try { + await new Promise((r) => setTimeout(r, 5)); + if (failBlend(call)) throw new Error("blend failed"); + return { bufferA: req.bufferA, bufferB: req.bufferB, output: req.output }; + } finally { + blendsInFlight--; + } + }), + terminate: vi.fn(async () => { + blendsInFlightAtTerminate = blendsInFlight; + }), +}; +vi.mock("../../shaderTransitionWorkerPool.js", () => ({ + createShaderTransitionWorkerPool: vi.fn(async () => pool), +})); + +function loopInput(overrides: { + writeFrame?: (frame: number) => boolean; + assertNotAborted?: () => void; +}): HybridLoopInput { + const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + let frame = 0; + const input = { + job: { config: { fps: { num: 30, den: 1 } }, totalFrames: 16, framesRendered: 0 }, + cfg: {}, + log, + framesDir: "/tmp/unused", + width: 1, + height: 1, + totalFrames: 16, + nativeHdrIds: new Set(), + nativeHdrImageIds: new Set(), + hdrCompositeCtx: {}, + hdrPerf: undefined, + hdrEncoder: { + writeFrame: async () => (overrides.writeFrame ?? (() => true))(frame++), + getExitError: () => "encoder exited", + }, + domSession: { page: {} }, + fileServer: { url: "http://127.0.0.1:0" }, + buildCaptureOptions: () => ({}), + createRenderVideoFrameInjector: () => undefined, + transitionRanges: [ + { + time: 0, + duration: 0.5, + shader: "crossfade", + ease: "", + fromScene: "a", + toScene: "b", + startFrame: 2, + endFrame: 13, + }, + ], + sceneElements: { a: ["a"], b: ["b"] }, + compositeTransfer: "srgb", + hdrTargetTransfer: undefined, + workerCount: 2, + debugDumpEnabled: false, + debugDumpDir: null, + assertNotAborted: overrides.assertNotAborted ?? (() => {}), + }; + // The loop only touches the fields above; the rest of each type is not needed here. + return input as unknown as HybridLoopInput; +} + +describe("runHybridLayeredFrameLoop failures with 2 workers", () => { + const escaped: unknown[] = []; + const onUnhandled = (reason: unknown) => escaped.push(reason); + beforeEach(() => { + escaped.length = 0; + blendCalls = 0; + blendsInFlight = 0; + blendsInFlightAtTerminate = undefined; + failBlend = () => false; + process.on("unhandledRejection", onUnhandled); + }); + afterEach(() => { + process.off("unhandledRejection", onUnhandled); + }); + + it("writes every frame and settles every blend when nothing fails", async () => { + const input = loopInput({}); + await runHybridLayeredFrameLoop(input); + expect(input.job.framesRendered).toBe(16); + expect(blendsInFlightAtTerminate).toBe(0); + expect(escaped).toEqual([]); + }); + + let aborts = 0; + it.each([ + { + name: "a blend fails", + setup: () => { + failBlend = (call) => call === 2; + return loopInput({}); + }, + error: /blend failed/, + }, + { + name: "the encoder exits", + setup: () => loopInput({ writeFrame: (frame) => frame < 5 }), + error: /Streaming encoder exited/, + }, + { + name: "the render is cancelled mid-transition", + setup: () => { + aborts = 0; + return loopInput({ + assertNotAborted: () => { + if (++aborts === 9) throw new Error("render cancelled"); + }, + }); + }, + error: /render cancelled/, + }, + ])( + "$name: the loop fails with it, settles every blend, and leaves no rejection unobserved", + async ({ setup, error }) => { + await expect(runHybridLayeredFrameLoop(setup())).rejects.toThrow(error); + await new Promise((r) => setTimeout(r, 50)); + expect(escaped).toEqual([]); + expect(blendsInFlightAtTerminate).toBe(0); + }, + ); +}); diff --git a/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts b/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts index 8d5dd272b3..b6ff579739 100644 --- a/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts +++ b/packages/producer/src/services/render/stages/captureHdrHybridLoop.ts @@ -180,6 +180,17 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise const workerRanges = distributeLayeredHybridFrameRanges(totalFrames, activeWorkerCount); let framesWritten = 0; const reorderBuffer = createFrameReorderBuffer(0, totalFrames); + // The first failure on any worker stops the loop and wakes every worker + // parked on the reorder buffer for a frame that will never be written. + let failure: Error | null = null; + const fail = (err: unknown): void => { + if (failure) return; + failure = err instanceof Error ? err : new Error(String(err)); + reorderBuffer.abort(failure); + }; + const throwIfFailed = (): void => { + if (failure) throw failure; + }; const writeEncoded = async (frameIdx: number, buf: Buffer): Promise => { await reorderBuffer.waitForFrame(frameIdx); @@ -210,132 +221,133 @@ export async function runHybridLayeredFrameLoop(input: HybridLoopInput): Promise // promise is non-null; before reusing the slot for a new capture we // await it so the buffer triple is free + the encoder has seen the // earlier frame (writeEncoded gates ordering via the reorder buffer). + // Slot promises never reject; their failure goes to `fail`. const ringInFlight: Array | null> = ring ? ring.map(() => null) : []; let nextRingIdx = 0; - for (let i = range.start; i < range.end; i++) { - assertNotAborted(); - const time = (i * job.config.fps.den) / job.config.fps.num; - const activeTransition = transitionFramesSet.has(i) - ? transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame) - : undefined; - if (activeTransition && ring) { - // Pick the next ring slot. If it's still in flight from an earlier - // capture, await it to drain before reusing its buffer triple. - const slot = nextRingIdx; - nextRingIdx = (nextRingIdx + 1) % TRANSITION_RING_DEPTH; - const prev = ringInFlight[slot]; - if (prev) await prev; - const buffers = ring[slot]; - if (!buffers) continue; - // CAPTURE on the DOM worker (this thread). Fills bufferA/bufferB - // synchronously w.r.t. this loop — DOM work can't be pipelined - // because the per-worker browser session is single-threaded. - await captureTransitionFrameOnWorker({ - session, - frameIdx: i, - time, - transition: activeTransition, - buffers, - nativeHdrIds, - nativeHdrImageIds, - sceneElements, - hdrCompositeCtx, - width, - height, - compositeTransfer, - hdrTargetTransfer, - hdrPerf, - log, - }); - const progress = - activeTransition.endFrame === activeTransition.startFrame - ? 1 - : (i - activeTransition.startFrame) / - (activeTransition.endFrame - activeTransition.startFrame); - // BLEND + ENCODE without awaiting. The promise drains back into - // `ringInFlight[slot]`; the next iteration that picks `slot` - // awaits it. The encoder reorder buffer fences ordering so out- - // of-order blend completion is fine. - const frameIdx = i; - // When the @hyperframes/shader-transitions composition omits the - // shader on a transition entry, it requests a CSS crossfade. The - // engine-side path uses applyFallbackTransition() on the page; the - // producer's Node-side layered pipeline runs the equivalent here - // by routing the blend through `crossfade`. - const shaderName = activeTransition.shader; - const dispatch: Promise = (async () => { - if (poolRef && shaderName) { - const blendStart = Date.now(); - const result = await poolRef.run({ - shader: shaderName, - bufferA: buffers.bufferA, - bufferB: buffers.bufferB, - output: buffers.output, - width, - height, - progress, - }); - buffers.bufferA = result.bufferA; - buffers.bufferB = result.bufferB; - buffers.output = result.output; - addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart); - } else { - const transitionFn: TransitionFn = shaderName - ? (TRANSITIONS[shaderName] ?? crossfade) - : crossfade; - const blendStart = Date.now(); - transitionFn( - buffers.bufferA, - buffers.bufferB, - buffers.output, - width, - height, - progress, - ); - addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart); - } - await writeEncoded(frameIdx, buffers.output); - })(); - // Catch on a separate handle so an unhandled-rejection can't fire - // if no one awaits this slot before the worker exits. The error - // is re-thrown on the next await (slot reuse OR end-of-task drain). - ringInFlight[slot] = dispatch.catch((err: unknown) => { - throw err instanceof Error ? err : new Error(String(err)); - }); - } else { - const stackingInfo = await seekInjectAndQueryStacking( - session.page, - time, - session.onBeforeCapture, - nativeHdrIds, - hdrPerf, - "frameSeekMs", - "frameInjectMs", - "stackingQueryMs", - ); - canvas.fill(0); - // Rebind ctx to this worker's session for per-layer captures - const wctx: HdrCompositeContext = { ...hdrCompositeCtx, domSession: session }; - await timeHdrPhaseAsync(hdrPerf, "normalCompositeMs", () => - compositeHdrFrame(wctx, canvas, time, stackingInfo, undefined, i), - ); - if (debugDumpEnabled && debugDumpDir && i % 30 === 0) { - writeFileExclusiveSync( - join(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`), - canvas, + try { + for (let i = range.start; i < range.end; i++) { + throwIfFailed(); + assertNotAborted(); + const time = (i * job.config.fps.den) / job.config.fps.num; + const activeTransition = transitionFramesSet.has(i) + ? transitionRanges.find((t) => i >= t.startFrame && i <= t.endFrame) + : undefined; + if (activeTransition && ring) { + // Pick the next ring slot. If it's still in flight from an earlier + // capture, await it to drain before reusing its buffer triple. + const slot = nextRingIdx; + nextRingIdx = (nextRingIdx + 1) % TRANSITION_RING_DEPTH; + const prev = ringInFlight[slot]; + if (prev) await prev; + throwIfFailed(); + const buffers = ring[slot]; + if (!buffers) continue; + // CAPTURE on the DOM worker (this thread). Fills bufferA/bufferB + // synchronously w.r.t. this loop — DOM work can't be pipelined + // because the per-worker browser session is single-threaded. + await captureTransitionFrameOnWorker({ + session, + frameIdx: i, + time, + transition: activeTransition, + buffers, + nativeHdrIds, + nativeHdrImageIds, + sceneElements, + hdrCompositeCtx, + width, + height, + compositeTransfer, + hdrTargetTransfer, + hdrPerf, + log, + }); + const progress = + activeTransition.endFrame === activeTransition.startFrame + ? 1 + : (i - activeTransition.startFrame) / + (activeTransition.endFrame - activeTransition.startFrame); + // BLEND + ENCODE without awaiting. The promise drains back into + // `ringInFlight[slot]`; the next iteration that picks `slot` + // awaits it. The encoder reorder buffer fences ordering so out- + // of-order blend completion is fine. + const frameIdx = i; + // When the @hyperframes/shader-transitions composition omits the + // shader on a transition entry, it requests a CSS crossfade. The + // engine-side path uses applyFallbackTransition() on the page; the + // producer's Node-side layered pipeline runs the equivalent here + // by routing the blend through `crossfade`. + const shaderName = activeTransition.shader; + const dispatch: Promise = (async () => { + if (poolRef && shaderName) { + const blendStart = Date.now(); + const result = await poolRef.run({ + shader: shaderName, + bufferA: buffers.bufferA, + bufferB: buffers.bufferB, + output: buffers.output, + width, + height, + progress, + }); + buffers.bufferA = result.bufferA; + buffers.bufferB = result.bufferB; + buffers.output = result.output; + addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart); + } else { + const transitionFn: TransitionFn = shaderName + ? (TRANSITIONS[shaderName] ?? crossfade) + : crossfade; + const blendStart = Date.now(); + transitionFn( + buffers.bufferA, + buffers.bufferB, + buffers.output, + width, + height, + progress, + ); + addHdrTiming(hdrPerf, "transitionCompositeMs", blendStart); + } + await writeEncoded(frameIdx, buffers.output); + })(); + ringInFlight[slot] = dispatch.then(() => undefined, fail); + } else { + const stackingInfo = await seekInjectAndQueryStacking( + session.page, + time, + session.onBeforeCapture, + nativeHdrIds, + hdrPerf, + "frameSeekMs", + "frameInjectMs", + "stackingQueryMs", ); + canvas.fill(0); + // Rebind ctx to this worker's session for per-layer captures + const wctx: HdrCompositeContext = { ...hdrCompositeCtx, domSession: session }; + await timeHdrPhaseAsync(hdrPerf, "normalCompositeMs", () => + compositeHdrFrame(wctx, canvas, time, stackingInfo, undefined, i), + ); + if (debugDumpEnabled && debugDumpDir && i % 30 === 0) { + writeFileExclusiveSync( + join(debugDumpDir, `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`), + canvas, + ); + } + await writeEncoded(i, canvas); } - await writeEncoded(i, canvas); } + } catch (err) { + fail(err); + } finally { + await Promise.all(ringInFlight); } - // Drain any pipelined blends still in flight on this worker before - // returning. If any rejected, the rejection bubbles here so - // `Promise.all` over `workerTaskOf` sees the failure. - for (const pending of ringInFlight) { - if (pending) await pending; - } + throwIfFailed(); }; - await Promise.all(sessions.map((_, w) => workerTaskOf(w))); + // allSettled: every worker's ring settles before the pool is terminated. + await Promise.allSettled(sessions.map((_, w) => workerTaskOf(w))); + throwIfFailed(); await reorderBuffer.waitForAllDone(); } finally { for (const s of workerSessions) { diff --git a/packages/producer/src/services/render/stages/captureHdrStage.ts b/packages/producer/src/services/render/stages/captureHdrStage.ts index 8e6ffc8a4a..1392f7e407 100644 --- a/packages/producer/src/services/render/stages/captureHdrStage.ts +++ b/packages/producer/src/services/render/stages/captureHdrStage.ts @@ -61,6 +61,7 @@ import { type HdrVideoFrameSource, type TransitionRange, resolveCompositeTransfer, + sanitizeTransitionMeta, } from "../../hdrCompositor.js"; import { type HdrPerfCollector, createHdrPerfCollector } from "../hdrPerf.js"; import type { HdrDiagnostics, ProgressCallback, RenderJob } from "../../renderOrchestrator.js"; @@ -231,23 +232,27 @@ export async function runCaptureHdrStage( await initTransparentBackground(domSession.page, { clearCompositionRoot: true }); // ── Scene detection for shader transitions ────────────────────────── - const transitionMeta: HdrTransitionMeta[] = await domSession.page.evaluate(() => { - return window.__hf?.transitions ?? []; - }); - const sceneElements: Record = await domSession.page.evaluate(() => { - const scenes = document.querySelectorAll(".scene"); - const map: Record = {}; - for (const scene of scenes) { - if (!scene.id) continue; - const ids = new Set([scene.id]); - const els = scene.querySelectorAll("[id]"); - for (const el of els) { - if (el.id) ids.add(el.id); + const transitionMeta: HdrTransitionMeta[] = sanitizeTransitionMeta( + await domSession.page.evaluate((): unknown => window.__hf?.transitions ?? []), + (message, meta) => log.warn(message, meta), + ); + const sceneElements: Record = Object.assign( + Object.create(null), + await domSession.page.evaluate(() => { + const scenes = document.querySelectorAll(".scene"); + const map: Record = {}; + for (const scene of scenes) { + if (!scene.id) continue; + const ids = new Set([scene.id]); + const els = scene.querySelectorAll("[id]"); + for (const el of els) { + if (el.id) ids.add(el.id); + } + map[scene.id] = Array.from(ids); } - map[scene.id] = Array.from(ids); - } - return map; - }); + return map; + }), + ); const fpsDecimal = fpsToNumber(job.config.fps); const transitionRanges: TransitionRange[] = transitionMeta.map((t) => ({ ...t, diff --git a/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts b/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts index bd81a1adeb..f54f97a520 100644 --- a/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts +++ b/packages/producer/src/services/render/stages/captureSegmentedStage.test.ts @@ -176,6 +176,7 @@ mock.module("../../renderOrchestrator.js", () => ({ mock.module("../../hdrCompositor.js", () => ({ closeHdrVideoFrameSource: () => {}, resolveCompositeTransfer: () => "srgb", + sanitizeTransitionMeta: (raw: unknown) => (Array.isArray(raw) ? raw : []), })); mock.module("./captureHdrResources.js", () => ({ diff --git a/packages/producer/src/services/render/stages/captureStreamingStage.test.ts b/packages/producer/src/services/render/stages/captureStreamingStage.test.ts index ba13edbea3..5c5ddc3e84 100644 --- a/packages/producer/src/services/render/stages/captureStreamingStage.test.ts +++ b/packages/producer/src/services/render/stages/captureStreamingStage.test.ts @@ -389,6 +389,7 @@ mock.module("../../renderOrchestrator.js", () => ({ mock.module("../../hdrCompositor.js", () => ({ closeHdrVideoFrameSource: () => {}, resolveCompositeTransfer: () => "srgb", + sanitizeTransitionMeta: (raw: unknown) => (Array.isArray(raw) ? raw : []), })); mock.module("./captureHdrResources.js", () => ({ diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts index 2d76f9acea..90dbf61ec1 100644 --- a/packages/producer/src/services/renderOrchestrator.ts +++ b/packages/producer/src/services/renderOrchestrator.ts @@ -949,6 +949,18 @@ export class RenderCancelledError extends Error { } } +/** + * Aborts a render because a promise rejection nobody handled came from it. The + * render fails with the original error; it is not reported as a cancel. + */ +export class EscapedRejectionError extends Error { + constructor(cause: Error) { + super(cause.message, { cause }); + Object.assign(this, cause); + this.name = cause.name; + } +} + export function createRenderFileLogger( logPath: string, base: ProducerLogger = defaultLogger, @@ -5943,13 +5955,16 @@ async function executeRenderPipeline(input: { framesRendered: job.framesRendered ?? 0, error: caught, }); + const escapedRejection = + executionSignal.reason instanceof EscapedRejectionError ? executionSignal.reason : undefined; const error = surfaceScriptFailure( - tooSlowError ?? audioFailure ?? pageNeverReady ?? caught, + tooSlowError ?? audioFailure ?? escapedRejection ?? pageNeverReady ?? caught, job, ); if ( !tooSlowError && !audioFailure && + !escapedRejection && (error instanceof RenderCancelledError || executionSignal.aborted) ) { job.error = error instanceof Error ? error.message : "render_cancelled";