mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(producer): a failed pipelined blend fails its render, not the server (#8775)
* fix(producer): a failed pipelined blend fails its render, not the server The hybrid layered loop kept each in-flight blend+encode as a slot promise and only awaited it when the slot came round again, so a blend, encoder or cancel failure could sit as an unobserved rejection and end the process. Slot promises now hand their failure to the loop, which wakes every worker through the reorder buffer, settles every in-flight blend, and only then fails the render. Page transition entries are checked before use (finite times, string scene ids, a registered shader or none), the transition registry and scene map have no prototype, and the public server attributes any rejection that still escapes a render to that render and fails it, instead of exiting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(producer): report an escaped rejection as the render's failure, not a cancel Aborting with the plain error sent the render down the cancel branch: job status "cancelled" and no failure telemetry. The abort reason is now an EscapedRejectionError, which the orchestrator treats like an audio failure: the render fails with the original message. The server test now runs two renders through a real unobserved rejection and the process handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(producer): trim comments added in the blend-failure fix Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(producer): address review on the blend-failure fix - Bun stage-test mocks of hdrCompositor.js export sanitizeTransitionMeta. - The rejection log carries the stack. - EscapedRejectionError keeps the cause's code/owner/retryable fields. - The hybrid-loop test covers a render that succeeds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
3865262ba3
commit
c890cb38f0
@@ -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);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -349,8 +349,8 @@ export type TransitionFn = (
|
||||
progress: number,
|
||||
) => void;
|
||||
|
||||
/** Registry of all available transitions by name. */
|
||||
export const TRANSITIONS: Record<string, TransitionFn> = {};
|
||||
/** Registry of all available transitions by name; prototype-free, so `constructor` finds nothing. */
|
||||
export const TRANSITIONS: Record<string, TransitionFn> = Object.create(null);
|
||||
|
||||
// ── crossfade ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -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<unknown>) => 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<void>, 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<never>((_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<void>((r) => (finishOther = r)));
|
||||
const leaking = render("req-1", new Promise<void>(() => {}), 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" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<T>(
|
||||
requestId: string,
|
||||
abortController: AbortController,
|
||||
run: (signal: AbortSignal) => Promise<T>,
|
||||
): Promise<T> {
|
||||
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;
|
||||
|
||||
@@ -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>): 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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<string, unknown>) => 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;
|
||||
|
||||
@@ -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<typeof import("@hyperframes/engine")>()),
|
||||
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<typeof import("./captureHdrFrameShared.js")>()),
|
||||
captureTransitionFrameOnWorker: vi.fn(async () => {}),
|
||||
seekInjectAndQueryStacking: vi.fn(async () => ({})),
|
||||
}));
|
||||
vi.mock("../../hdrCompositor.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../../hdrCompositor.js")>()),
|
||||
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<string>(),
|
||||
nativeHdrImageIds: new Set<string>(),
|
||||
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);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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<void> => {
|
||||
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<Promise<void> | 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<void> = (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<void> = (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) {
|
||||
|
||||
@@ -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<string, string[]> = await domSession.page.evaluate(() => {
|
||||
const scenes = document.querySelectorAll(".scene");
|
||||
const map: Record<string, string[]> = {};
|
||||
for (const scene of scenes) {
|
||||
if (!scene.id) continue;
|
||||
const ids = new Set<string>([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<string, string[]> = Object.assign(
|
||||
Object.create(null),
|
||||
await domSession.page.evaluate(() => {
|
||||
const scenes = document.querySelectorAll(".scene");
|
||||
const map: Record<string, string[]> = {};
|
||||
for (const scene of scenes) {
|
||||
if (!scene.id) continue;
|
||||
const ids = new Set<string>([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,
|
||||
|
||||
@@ -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", () => ({
|
||||
|
||||
@@ -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", () => ({
|
||||
|
||||
@@ -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";
|
||||
|
||||
Reference in New Issue
Block a user