Skip to content

Write HTML. Render video. Built for agents.

feat(hdr): layered HDR compositing, shader transitions, and HDR image support (#268)

Vance Ingalls99a903be2f52
diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx
index 1463cc0f4f..82192cbfaa 100644
--- a/docs/packages/cli.mdx
+++ b/docs/packages/cli.mdx
@@ -465,14 +465,15 @@ This is suppressed in CI environments, non-TTY shells, and when `HYPERFRAMES_NO_
| `--output` | path | `renders/<name>.mp4` | Output file path |
| `--format` | mp4, webm, mov | mp4 | Output format (WebM/MOV render with transparency) |
| `--fps` | 24, 30, 60 | 30 | Frames per second |
- | `--quality` | draft, standard, high | standard | Encoding quality preset |
- | `--crf` | 0–51 | — | Override CRF (lower = higher quality). Cannot combine with `--video-bitrate` |
- | `--video-bitrate` | e.g. `10M`, `5000k` | — | Target bitrate encoding. Cannot combine with `--crf` |
+ | `--quality` | draft, standard, high | standard | Encoding quality preset (drives CRF/bitrate) |
+ | `--hdr` | — | off | HDR output (H.265 10-bit, BT.2020 HLG/PQ). MP4 only |
| `--workers` | 1-8 | 4 | Parallel render workers |
| `--gpu` | — | off | GPU encoding (NVENC, VideoToolbox, VAAPI) |
| `--docker` | — | off | Use Docker for [deterministic rendering](/concepts/determinism) |
| `--quiet` | — | off | Suppress verbose output |
+ CRF and target bitrate are now driven by `--quality`. For programmatic renders, `RenderConfig.crf` and `RenderConfig.videoBitrate` still accept overrides.
+
#### WebM with Transparency
Use `--format webm` to render compositions with a transparent background. This produces VP9 video with alpha channel in a WebM container — the standard format for overlayable video.
diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts
index 265c82fd00..cec618b4db 100644
--- a/packages/cli/src/commands/render.ts
+++ b/packages/cli/src/commands/render.ts
@@ -7,10 +7,9 @@ export const examples: Example[] = [
["Render transparent overlay (ProRes)", "hyperframes render --format mov --output overlay.mov"],
["Render transparent WebM overlay", "hyperframes render --format webm --output overlay.webm"],
["High quality at 60fps", "hyperframes render --fps 60 --quality high --output hd.mp4"],
- ["Custom CRF for maximum quality", "hyperframes render --crf 15 --output pristine.mp4"],
- ["Target bitrate encoding", "hyperframes render --video-bitrate 10M --output hq.mp4"],
["Deterministic render via Docker", "hyperframes render --docker --output deterministic.mp4"],
["Parallel rendering with 6 workers", "hyperframes render --workers 6 --output fast.mp4"],
+ ["HDR output (H.265 10-bit)", "hyperframes render --hdr --output hdr-output.mp4"],
];
import { cpus, freemem, tmpdir } from "node:os";
import { resolve, dirname, join, basename } from "node:path";
@@ -81,19 +80,10 @@ export default defineCommand({
description: "Use Docker for deterministic render",
default: false,
},
- crf: {
- type: "string",
- description:
- "CRF (Constant Rate Factor) for the video encoder. " +
- "Lower = higher quality / larger file. Range: 0–51 for H.264. " +
- "Overrides the quality preset CRF. Cannot be used with --video-bitrate.",
- },
- "video-bitrate": {
- type: "string",
- description:
- "Target video bitrate (e.g. '10M', '5000k'). " +
- "Uses bitrate-based encoding instead of CRF. " +
- "Cannot be used with --crf.",
+ hdr: {
+ type: "boolean",
+ description: "Enable HDR: probe sources for PQ/HLG, output H.265 10-bit BT.2020",
+ default: false,
},
gpu: { type: "boolean", description: "Use GPU encoding", default: false },
quiet: {
@@ -144,36 +134,6 @@ export default defineCommand({
}
const format = formatRaw as "mp4" | "webm" | "mov";
- // ── Validate CRF / video-bitrate ────────────────────────────────────
- let crf: number | undefined;
- let videoBitrate: string | undefined;
- if (args.crf != null && args["video-bitrate"] != null) {
- errorBox(
- "Conflicting options",
- "--crf and --video-bitrate cannot be used together. Choose one.",
- );
- process.exit(1);
- }
- if (args.crf != null) {
- const parsed = parseInt(args.crf, 10);
- if (isNaN(parsed) || parsed < 0 || parsed > 51) {
- errorBox("Invalid CRF", `Got "${args.crf}". Must be a number between 0 and 51.`);
- process.exit(1);
- }
- crf = parsed;
- }
- if (args["video-bitrate"] != null) {
- const raw = args["video-bitrate"];
- if (!/^\d+(\.\d+)?[kKM]$/.test(raw)) {
- errorBox(
- "Invalid video bitrate",
- `Got "${raw}". Must be a number followed by k, K, or M (e.g. "10M", "5000k", "1.5M").`,
- );
- process.exit(1);
- }
- videoBitrate = raw;
- }
-
// ── Validate workers ──────────────────────────────────────────────────
let workers: number | undefined;
if (args.workers != null && args.workers !== "auto") {
@@ -231,12 +191,7 @@ export default defineCommand({
c.accent(project.name) +
c.dim(" \u2192 " + outputPath),
);
- const encodeLabel = videoBitrate
- ? `bitrate ${videoBitrate}`
- : crf != null
- ? `crf ${crf}`
- : quality;
- console.log(c.dim(" " + fps + "fps \u00B7 " + encodeLabel + " \u00B7 " + workerLabel));
+ console.log(c.dim(" " + fps + "fps \u00B7 " + quality + " \u00B7 " + workerLabel));
console.log("");
}
@@ -316,9 +271,8 @@ export default defineCommand({
format,
workers: workerCount,
gpu: useGpu,
+ hdr: args.hdr ?? false,
quiet,
- crf,
- videoBitrate,
});
} else {
await renderLocal(project.dir, outputPath, {
@@ -327,10 +281,9 @@ export default defineCommand({
format,
workers: workerCount,
gpu: useGpu,
+ hdr: args.hdr ?? false,
quiet,
browserPath,
- crf,
- videoBitrate,
});
}
},
@@ -342,10 +295,9 @@ interface RenderOptions {
format: "mp4" | "webm" | "mov";
workers: number;
gpu: boolean;
+ hdr: boolean;
quiet: boolean;
browserPath?: string;
- crf?: number;
- videoBitrate?: string;
}
const DOCKER_IMAGE_PREFIX = "hyperframes-renderer";
@@ -480,8 +432,6 @@ async function renderDocker(
String(options.workers),
...(options.quiet ? ["--quiet"] : []),
...(options.gpu ? ["--gpu"] : []),
- ...(options.crf != null ? ["--crf", String(options.crf)] : []),
- ...(options.videoBitrate ? ["--video-bitrate", options.videoBitrate] : []),
];
if (!options.quiet) {
@@ -543,8 +493,7 @@ async function renderLocal(
format: options.format,
workers: options.workers,
useGpu: options.gpu,
- crf: options.crf,
- videoBitrate: options.videoBitrate,
+ hdr: options.hdr,
});
const onProgress = options.quiet
diff --git a/packages/core/src/lint/rules/media.ts b/packages/core/src/lint/rules/media.ts
index 782b5ca2d1..e67b1e9558 100644
--- a/packages/core/src/lint/rules/media.ts
+++ b/packages/core/src/lint/rules/media.ts
@@ -82,6 +82,8 @@ export const mediaRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> =
const timedTagPositions: Array<{ name: string; start: number; id?: string }> = [];
for (const tag of tags) {
if (tag.name === "video" || tag.name === "audio") continue;
+ // Skip the composition root — it uses data-start as a playback anchor, not as a clip timer
+ if (readAttr(tag.raw, "data-composition-id")) continue;
if (readAttr(tag.raw, "data-start")) {
timedTagPositions.push({
name: tag.name,
diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts
index 741c42efd4..5cb608fd94 100644
--- a/packages/engine/src/index.ts
+++ b/packages/engine/src/index.ts
@@ -34,6 +34,7 @@
export type {
HfProtocol,
HfMediaElement,
+ HfTransitionMeta,
CaptureOptions,
CaptureResult,
CaptureBufferResult,
@@ -79,6 +80,9 @@ export {
cdpSessionCache,
initTransparentBackground,
captureAlphaPng,
+ applyDomLayerMask,
+ removeDomLayerMask,
+ DOM_LAYER_MASK_STYLE_ID,
type BeginFrameResult,
} from "./services/screenshotService.js";
@@ -155,6 +159,7 @@ export {
} from "./utils/ffprobe.js";
export { downloadToTemp, isHttpUrl } from "./utils/urlDownloader.js";
+export { runFfmpeg, type RunFfmpegOptions, type RunFfmpegResult } from "./utils/runFfmpeg.js";
export {
decodePng,
@@ -164,10 +169,22 @@ export {
blitRgb48leAffine,
parseTransformMatrix,
getSrgbToHdrLut,
+ roundedRectAlpha,
} from "./utils/alphaBlit.js";
export { groupIntoLayers, type CompositeLayer } from "./utils/layerCompositor.js";
+// ── Shader transitions ────────────────────────────────────────────────────────
+export {
+ type TransitionFn,
+ TRANSITIONS,
+ crossfade,
+ sampleRgb48le,
+ hdrToLinear,
+ linearToHdr,
+ convertTransfer,
+} from "./utils/shaderTransitions.js";
+
export {
initHdrReadback,
uploadAndReadbackHdrFrame,
diff --git a/packages/engine/src/services/screenshotService.ts b/packages/engine/src/services/screenshotService.ts
index 038df11f59..7ba30a232a 100644
--- a/packages/engine/src/services/screenshotService.ts
+++ b/packages/engine/src/services/screenshotService.ts
@@ -181,12 +181,34 @@ export async function captureScreenshotWithAlpha(
* Only use on sessions that are exclusively dedicated to transparent capture
* (e.g., the HDR two-pass DOM layer session) — the background will stay
* transparent for the lifetime of the session.
+ *
+ * NOTE on the injected stylesheet: `Emulation.setDefaultBackgroundColorOverride`
+ * only replaces the *default* page background. Compositions almost always set
+ * `body { background: ... }` and `#root { background: ... }`, which paint over
+ * the override and ruin alpha capture for layered HDR compositing — the
+ * composition root's full-frame background paints across the entire viewport
+ * and wipes out HDR content captured beneath it.
+ *
+ * We force `html`, `body`, and any element marked as a composition root
+ * (`[data-composition-id]`) to transparent. In HDR layered compositing the HDR
+ * video itself is the backdrop, so DOM layers must only contribute their
+ * foreground UI pixels — never a page-spanning solid backdrop.
*/
+export const TRANSPARENT_BG_STYLE_ID = "__hf_transparent_bg__";
+
export async function initTransparentBackground(page: Page): Promise<void> {
const client = await getCdpSession(page);
await client.send("Emulation.setDefaultBackgroundColorOverride", {
color: { r: 0, g: 0, b: 0, a: 0 },
});
+ await page.evaluate((styleId: string) => {
+ if (document.getElementById(styleId)) return;
+ const style = document.createElement("style");
+ style.id = styleId;
+ style.textContent =
+ "html,body,[data-composition-id]{background:transparent !important;background-color:transparent !important;background-image:none !important;}";
+ document.head.appendChild(style);
+ }, TRANSPARENT_BG_STYLE_ID);
}
/**
@@ -209,6 +231,135 @@ export async function captureAlphaPng(page: Page, width: number, height: number)
return Buffer.from(result.data, "base64");
}
+/**
+ * Stylesheet ID used by applyDomLayerMask / removeDomLayerMask. Exposed so
+ * tests can assert presence/absence of the mask between captures.
+ */
+export const DOM_LAYER_MASK_STYLE_ID = "__hf_dom_layer_mask__";
+
+/**
+ * Mask the DOM so a single layer screenshot captures ONLY the layer's pixels.
+ *
+ * The HDR layered compositor walks z-ordered layers and blits each one over a
+ * shared canvas. DOM layers are full-page screenshots — a naive screenshot
+ * captures every painted pixel on the page, which means root background +
+ * static overlays + sibling-scene content all overwrite previously composited
+ * HDR content beneath. The mask narrows each screenshot to the elements that
+ * actually belong to this layer.
+ *
+ * Strategy:
+ *
+ * 1. Inject a stylesheet that hides every body descendant
+ * (`body * { visibility: hidden !important }`) and re-shows the layer's
+ * elements (and their descendants and their injected `__render_frame_*`
+ * siblings) via `visibility: visible !important`. CSS `visibility: visible`
+ * on a descendant overrides an ancestor's `visibility: hidden`, so deep
+ * layer elements remain visible even though intermediate parents are
+ * hidden by the mass-hide rule.
+ * 2. Inline-hide each `extraHideId` (and its `__render_frame_*` sibling) with
+ * `visibility: hidden !important`. Inline `!important` beats stylesheet
+ * `!important`, so this overrides the show rule for elements that fall
+ * under a show selector but should NOT paint — typically other-layer
+ * elements that are descendants of a container layer (for example HDR
+ * videos and other-layer SDR videos are descendants of `#root` when we
+ * capture the root DOM layer).
+ *
+ * Only `visibility` is set on extraHideIds — never `opacity`. CSS opacity is
+ * multiplicative through the descendant chain and a descendant cannot escape
+ * an ancestor's `opacity: 0`. If `#root` is in `extraHideIds` and we set
+ * `opacity: 0` on it, every descendant — including `#vid-5-b` and its
+ * `__render_frame_vid-5-b__` IMG — becomes invisible even with
+ * `visibility: visible !important`. `visibility` does NOT have this problem:
+ * a descendant with `visibility: visible` overrides an ancestor's
+ * `visibility: hidden`.
+ *
+ * Layout is preserved (visibility doesn't trigger reflow), so border-radius
+ * clipping, overflow:hidden, and absolute positioning continue to apply to
+ * the visible layer elements. Opacity is also preserved — an ancestor at
+ * `opacity: 0` (e.g. an inactive scene during a transition) still
+ * propagates to its descendants, which is the desired behavior during
+ * cross-scene blends.
+ *
+ * Idempotent across calls: an existing mask stylesheet is removed before a
+ * new one is installed, so consecutive `applyDomLayerMask` invocations leave
+ * exactly one stylesheet attached.
+ */
+export async function applyDomLayerMask(
+ page: Page,
+ showIds: string[],
+ extraHideIds: string[],
+): Promise<void> {
+ await page.evaluate(
+ (args: { show: string[]; hide: string[]; styleId: string }) => {
+ const existing = document.getElementById(args.styleId);
+ if (existing) existing.remove();
+
+ const showSelectors: string[] = [];
+ for (const id of args.show) {
+ const escaped = CSS.escape(id);
+ showSelectors.push(`#${escaped}`, `#${escaped} *`);
+ const renderEscaped = CSS.escape(`__render_frame_${id}__`);
+ showSelectors.push(`#${renderEscaped}`, `#${renderEscaped} *`);
+ }
+
+ const massHideRule = "body *{visibility:hidden !important;}";
+ const showRule =
+ showSelectors.length === 0
+ ? ""
+ : `${showSelectors.join(",")}{visibility:visible !important;}`;
+
+ const style = document.createElement("style");
+ style.id = args.styleId;
+ style.textContent = `${massHideRule}\n${showRule}`;
+ document.head.appendChild(style);
+
+ for (const id of args.hide) {
+ const el = document.getElementById(id);
+ if (el) {
+ el.style.setProperty("visibility", "hidden", "important");
+ }
+ const img = document.getElementById(`__render_frame_${id}__`);
+ if (img) {
+ img.style.setProperty("visibility", "hidden", "important");
+ }
+ }
+ },
+ { show: showIds, hide: extraHideIds, styleId: DOM_LAYER_MASK_STYLE_ID },
+ );
+}
+
+/**
+ * Tear down the mask installed by applyDomLayerMask.
+ *
+ * Removes the mask stylesheet and clears the inline `visibility` properties
+ * set on `extraHideIds` (and their `__render_frame_*` siblings).
+ *
+ * IMPORTANT: We do NOT strip inline `opacity` here. applyDomLayerMask only
+ * ever sets `visibility` (never `opacity`), so any inline opacity present on
+ * a wrapper was put there by user animation code (typically GSAP) and must
+ * survive across per-layer captures. GSAP's seek with suppress-events does
+ * not re-apply tweens when the timeline is already at the target time, so if
+ * we strip opacity here and then seek to the same time for the next layer,
+ * GSAP won't put it back and the wrapper will render fully opaque.
+ */
+export async function removeDomLayerMask(page: Page, extraHideIds: string[]): Promise<void> {
+ await page.evaluate(
+ (args: { hide: string[]; styleId: string }) => {
+ const style = document.getElementById(args.styleId);
+ if (style) style.remove();
+ for (const id of args.hide) {
+ const el = document.getElementById(id);
+ if (el) {
+ el.style.removeProperty("visibility");
+ }
+ const img = document.getElementById(`__render_frame_${id}__`);
+ if (img) img.style.removeProperty("visibility");
+ }
+ },
+ { hide: extraHideIds, styleId: DOM_LAYER_MASK_STYLE_ID },
+ );
+}
+
export async function injectVideoFramesBatch(
page: Page,
updates: Array<{ videoId: string; dataUri: string }>,
@@ -224,6 +375,16 @@ export async function injectVideoFramesBatch(
let img = video.nextElementSibling as HTMLImageElement | null;
const isNewImage = !img || !img.classList.contains("__render_frame__");
const computedStyle = window.getComputedStyle(video);
+ // GSAP seeks re-apply tween values during an active tween, but do not
+ // re-apply tweens that have already completed. After an opacity fade-in
+ // finishes, GSAP's last set value is overwritten on subsequent frames
+ // by the `opacity: 0 !important` we apply at the bottom of this
+ // function to hide the native <video>. That leaves `computedOpacity`
+ // stuck at 0 even though the user's intent is opacity 1 (the tween's
+ // end state). The `|| 1` fallback treats computedOpacity === 0 as a
+ // hidden-native-video artifact and recovers opacity 1, matching the
+ // final on-screen state for the vast majority of compositions.
+ // For active tweens in the [0,1] exclusive range this is a no-op.
const computedOpacity = parseFloat(computedStyle.opacity) || 1;
const sourceIsStatic = !computedStyle.position || computedStyle.position === "static";
@@ -260,6 +421,14 @@ export async function injectVideoFramesBatch(
img.style.zIndex = computedStyle.zIndex;
for (const property of visualProperties) {
+ // Opacity is handled explicitly via `computedOpacity` below — copying
+ // via the generic loop would race against the opacity:0 hide applied
+ // to the <video> at the end of this function. GSAP may animate
+ // opacity either on a wrapper (the <img> inherits via the stacking
+ // context) or directly on the <video> (we must copy it to the <img>
+ // since they are siblings). Reading computedStyle.opacity before
+ // hiding the <video> handles both cases correctly.
+ if (property === "opacity") continue;
if (
sourceIsStatic &&
(property === "top" ||
diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.ts
index a27c77f70a..df4a0e5366 100644
--- a/packages/engine/src/types.ts
+++ b/packages/engine/src/types.ts
@@ -31,6 +31,29 @@ export interface HfMediaElement {
hasAudio?: boolean;
}
+/**
+ * Metadata for a shader transition between two scenes.
+ *
+ * Compositions using @hyperframes/shader-transitions populate
+ * `window.__hf.transitions` with one entry per transition so the
+ * producer can pre-compute scene ranges, capture per-scene buffers,
+ * and apply the transition in HDR-aware compositing.
+ */
+export interface HfTransitionMeta {
+ /** Time the transition starts (seconds) */
+ time: number;
+ /** Transition duration (seconds) */
+ duration: number;
+ /** Shader identifier (e.g. "fade", "wipe") */
+ shader: string;
+ /** GSAP easing string (e.g. "power2.inOut") */
+ ease: string;
+ /** Scene id the transition starts from */
+ fromScene: string;
+ /** Scene id the transition ends on */
+ toScene: string;
+}
+
/**
* The seek protocol. The only contract between the engine and a page.
*
@@ -42,6 +65,15 @@ export interface HfMediaElement {
* GSAP, Framer Motion, CSS animations, Three.js — anything works as long
* as `seek()` produces deterministic visual output for a given time.
*/
+export interface HfTransitionMeta {
+ time: number;
+ duration: number;
+ shader: string;
+ ease: string;
+ fromScene: string;
+ toScene: string;
+}
+
export interface HfProtocol {
/** Total duration of the composition in seconds */
duration: number;
@@ -49,6 +81,8 @@ export interface HfProtocol {
seek(time: number): void;
/** Optional: media elements the engine should handle */
media?: HfMediaElement[];
+ /** Optional: shader transition metadata, populated by @hyperframes/shader-transitions */
+ transitions?: HfTransitionMeta[];
}
// ── Capture Types ──────────────────────────────────────────────────────────────
diff --git a/packages/engine/src/utils/shaderTransitions.test.ts b/packages/engine/src/utils/shaderTransitions.test.ts
new file mode 100644
index 0000000000..bb5eaaa438
--- /dev/null
+++ b/packages/engine/src/utils/shaderTransitions.test.ts
@@ -0,0 +1,674 @@
+import { describe, expect, it } from "vitest";
+import {
+ sampleRgb48le,
+ mix16,
+ clamp16,
+ smoothstep,
+ hash,
+ vnoise,
+ fbm,
+ crossfade,
+ flashThroughWhite,
+ hdrToLinear,
+ linearToHdr,
+ convertTransfer,
+ TRANSITIONS,
+ type TransitionFn,
+} from "./shaderTransitions.js";
+
+// ── sampleRgb48le ─────────────────────────────────────────────────────────────
+
+describe("sampleRgb48le", () => {
+ it("samples center pixel of a uniform 1x1 buffer", () => {
+ const buf = Buffer.alloc(6);
+ buf.writeUInt16LE(10000, 0); // R
+ buf.writeUInt16LE(20000, 2); // G
+ buf.writeUInt16LE(30000, 4); // B
+ const [r, g, b] = sampleRgb48le(buf, 0.5, 0.5, 1, 1);
+ expect(r).toBe(10000);
+ expect(g).toBe(20000);
+ expect(b).toBe(30000);
+ });
+
+ it("clamps out-of-bounds UV below 0 to first pixel", () => {
+ const buf = Buffer.alloc(6);
+ buf.writeUInt16LE(5000, 0);
+ buf.writeUInt16LE(6000, 2);
+ buf.writeUInt16LE(7000, 4);
+ const [r, g, b] = sampleRgb48le(buf, -0.5, -0.5, 1, 1);
+ expect(r).toBe(5000);
+ expect(g).toBe(6000);
+ expect(b).toBe(7000);
+ });
+
+ it("clamps out-of-bounds UV above 1 to last pixel", () => {
+ const buf = Buffer.alloc(6);
+ buf.writeUInt16LE(5000, 0);
+ buf.writeUInt16LE(6000, 2);
+ buf.writeUInt16LE(7000, 4);
+ const [r, g, b] = sampleRgb48le(buf, 1.5, 1.5, 1, 1);
+ expect(r).toBe(5000);
+ expect(g).toBe(6000);
+ expect(b).toBe(7000);
+ });
+
+ it("bilinearly interpolates between two horizontally adjacent pixels", () => {
+ // 2x1 buffer: pixel 0 = (0,0,0), pixel 1 = (65534,65534,65534)
+ const buf = Buffer.alloc(12);
+ buf.writeUInt16LE(0, 0);
+ buf.writeUInt16LE(0, 2);
+ buf.writeUInt16LE(0, 4);
+ buf.writeUInt16LE(65534, 6);
+ buf.writeUInt16LE(65534, 8);
+ buf.writeUInt16LE(65534, 10);
+ // u=0.5, w=2 → x = 0.5*(2-1) = 0.5 → equal blend of pixels 0 and 1
+ const [r, g, b] = sampleRgb48le(buf, 0.5, 0, 2, 1);
+ expect(r).toBe(32767);
+ expect(g).toBe(32767);
+ expect(b).toBe(32767);
+ });
+
+ it("samples from exact pixel 0 at u=0", () => {
+ const buf = Buffer.alloc(12);
+ buf.writeUInt16LE(1000, 0);
+ buf.writeUInt16LE(2000, 2);
+ buf.writeUInt16LE(3000, 4);
+ buf.writeUInt16LE(60000, 6);
+ buf.writeUInt16LE(60000, 8);
+ buf.writeUInt16LE(60000, 10);
+ const [r, g, b] = sampleRgb48le(buf, 0, 0, 2, 1);
+ expect(r).toBe(1000);
+ expect(g).toBe(2000);
+ expect(b).toBe(3000);
+ });
+
+ // ── Wider coverage for the perf-migration follow-up ────────────────────────
+ // These pin down sub-pixel sampling semantics so a future Uint16Array
+ // implementation can swap in and verify byte-equivalent output.
+
+ it("bilinearly interpolates between two vertically adjacent pixels", () => {
+ // 1x2 buffer: row 0 = (0,0,0), row 1 = (40000,40000,40000)
+ const buf = Buffer.alloc(12);
+ buf.writeUInt16LE(0, 0);
+ buf.writeUInt16LE(0, 2);
+ buf.writeUInt16LE(0, 4);
+ buf.writeUInt16LE(40000, 6);
+ buf.writeUInt16LE(40000, 8);
+ buf.writeUInt16LE(40000, 10);
+ const [r, g, b] = sampleRgb48le(buf, 0, 0.5, 1, 2);
+ expect(r).toBe(20000);
+ expect(g).toBe(20000);
+ expect(b).toBe(20000);
+ });
+
+ it("bilinearly interpolates the centroid of a 2x2 block", () => {
+ // Layout (R channel only, others mirror):
+ // (1000) (5000)
+ // (3000) (7000)
+ // Centroid (u=v=0.5) → average of all four = 4000
+ const buf = Buffer.alloc(24);
+ const corners = [1000, 5000, 3000, 7000];
+ for (let i = 0; i < 4; i++) {
+ const off = i * 6;
+ buf.writeUInt16LE(corners[i] ?? 0, off);
+ buf.writeUInt16LE(corners[i] ?? 0, off + 2);
+ buf.writeUInt16LE(corners[i] ?? 0, off + 4);
+ }
+ const [r, g, b] = sampleRgb48le(buf, 0.5, 0.5, 2, 2);
+ expect(r).toBe(4000);
+ expect(g).toBe(4000);
+ expect(b).toBe(4000);
+ });
+
+ it("does not bleed channels — R, G, B sampled independently", () => {
+ // 2x1 buffer with distinct per-channel gradients.
+ // pixel 0: R=1000 G=20000 B=50000
+ // pixel 1: R=9000 G=30000 B=60000
+ const buf = Buffer.alloc(12);
+ buf.writeUInt16LE(1000, 0);
+ buf.writeUInt16LE(20000, 2);
+ buf.writeUInt16LE(50000, 4);
+ buf.writeUInt16LE(9000, 6);
+ buf.writeUInt16LE(30000, 8);
+ buf.writeUInt16LE(60000, 10);
+ const [r, g, b] = sampleRgb48le(buf, 0.5, 0, 2, 1);
+ expect(r).toBe(5000);
+ expect(g).toBe(25000);
+ expect(b).toBe(55000);
+ });
+
+ it("samples last pixel exactly when u=v=1 (no overflow past the edge)", () => {
+ // 2x2 buffer where (1,1) corner has a unique value the first three pixels
+ // do not. If sampleRgb48le tried to read off-edge, the result would mix in
+ // out-of-bounds garbage.
+ const buf = Buffer.alloc(24);
+ const fill = [10, 20, 30, 65000];
+ for (let i = 0; i < 4; i++) {
+ const off = i * 6;
+ buf.writeUInt16LE(fill[i] ?? 0, off);
+ buf.writeUInt16LE(fill[i] ?? 0, off + 2);
+ buf.writeUInt16LE(fill[i] ?? 0, off + 4);
+ }
+ const [r, g, b] = sampleRgb48le(buf, 1, 1, 2, 2);
+ expect(r).toBe(65000);
+ expect(g).toBe(65000);
+ expect(b).toBe(65000);
+ });
+
+ it("respects asymmetric off-center UV weights", () => {
+ // 2x1 buffer, R-only differentiation: pixel 0 = 0, pixel 1 = 10000
+ // u=0.25 → x = 0.25 * (2 - 1) = 0.25
+ // weight on pixel 0 = 0.75, weight on pixel 1 = 0.25
+ // expected R = round(0 * 0.75 + 10000 * 0.25) = 2500
+ const buf = Buffer.alloc(12);
+ buf.writeUInt16LE(0, 0);
+ buf.writeUInt16LE(0, 2);
+ buf.writeUInt16LE(0, 4);
+ buf.writeUInt16LE(10000, 6);
+ buf.writeUInt16LE(10000, 8);
+ buf.writeUInt16LE(10000, 10);
+ const [r, g, b] = sampleRgb48le(buf, 0.25, 0, 2, 1);
+ expect(r).toBe(2500);
+ expect(g).toBe(2500);
+ expect(b).toBe(2500);
+ });
+
+ it("preserves max 16-bit values without clipping or rollover", () => {
+ // Verify the 65535 ceiling round-trips through bilinear weights without
+ // losing precision. A naïve 32-bit accumulator would still be fine here,
+ // but a future packed-Uint16 implementation must be checked for overflow
+ // in intermediate sums.
+ const buf = Buffer.alloc(24);
+ for (let i = 0; i < 4; i++) {
+ const off = i * 6;
+ buf.writeUInt16LE(65535, off);
+ buf.writeUInt16LE(65535, off + 2);
+ buf.writeUInt16LE(65535, off + 4);
+ }
+ const [r, g, b] = sampleRgb48le(buf, 0.5, 0.5, 2, 2);
+ expect(r).toBe(65535);
+ expect(g).toBe(65535);
+ expect(b).toBe(65535);
+ });
+
+ it("works on a large 256x256 canvas with sub-pixel UV", () => {
+ // Sanity check that buffer offset math scales — exercises the (y * w + x) * 6
+ // indexing on a non-trivial stride.
+ const w = 256;
+ const h = 256;
+ const buf = Buffer.alloc(w * h * 6);
+ // Diagonal gradient in R: pixel (x, y).R = x
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const off = (y * w + x) * 6;
+ buf.writeUInt16LE(x, off);
+ }
+ }
+ // u = 0.5 → sx = 0.5 * (w - 1) = 127.5 → R should be ≈ 127.5 → rounds to 128
+ const [r] = sampleRgb48le(buf, 0.5, 0.5, w, h);
+ expect(r).toBe(128);
+ });
+
+ it("handles 1x1 source with arbitrary UV (no x1=x0 division by zero)", () => {
+ // x0+1 gets clamped back to w-1=0, so x0 == x1. The weights still sum to 1
+ // and the result must equal the single pixel value.
+ const buf = Buffer.alloc(6);
+ buf.writeUInt16LE(12345, 0);
+ buf.writeUInt16LE(23456, 2);
+ buf.writeUInt16LE(34567, 4);
+ for (const [u, v] of [
+ [0, 0],
+ [0.5, 0.5],
+ [1, 1],
+ [0.7, 0.3],
+ ] as const) {
+ const [r, g, b] = sampleRgb48le(buf, u, v, 1, 1);
+ expect(r).toBe(12345);
+ expect(g).toBe(23456);
+ expect(b).toBe(34567);
+ }
+ });
+});
+
+// ── mix16 ─────────────────────────────────────────────────────────────────────
+
+describe("mix16", () => {
+ it("returns a at t=0", () => {
+ expect(mix16(1000, 60000, 0)).toBe(1000);
+ });
+
+ it("returns b at t=1", () => {
+ expect(mix16(1000, 60000, 1)).toBe(60000);
+ });
+
+ it("returns midpoint at t=0.5", () => {
+ expect(mix16(0, 60000, 0.5)).toBe(30000);
+ });
+
+ it("returns rounded result for non-integer midpoints", () => {
+ // 0 * 0.5 + 1 * 0.5 = 0.5 → rounds to 1
+ expect(mix16(0, 1, 0.5)).toBe(1);
+ });
+});
+
+// ── clamp16 ───────────────────────────────────────────────────────────────────
+
+describe("clamp16", () => {
+ it("clamps negative to 0", () => {
+ expect(clamp16(-100)).toBe(0);
+ });
+
+ it("clamps overflow to 65535", () => {
+ expect(clamp16(70000)).toBe(65535);
+ });
+
+ it("passes normal values through", () => {
+ expect(clamp16(32768)).toBe(32768);
+ });
+
+ it("passes boundary values through", () => {
+ expect(clamp16(0)).toBe(0);
+ expect(clamp16(65535)).toBe(65535);
+ });
+});
+
+// ── smoothstep ────────────────────────────────────────────────────────────────
+
+describe("smoothstep", () => {
+ it("returns 0 when x <= edge0", () => {
+ expect(smoothstep(0.2, 0.8, 0.1)).toBe(0);
+ expect(smoothstep(0.2, 0.8, 0.2)).toBe(0);
+ });
+
+ it("returns 1 when x >= edge1", () => {
+ expect(smoothstep(0.2, 0.8, 0.9)).toBe(1);
+ expect(smoothstep(0.2, 0.8, 0.8)).toBe(1);
+ });
+
+ it("returns ~0.5 at midpoint between edge0 and edge1", () => {
+ // t = (0.5 - 0.2) / (0.8 - 0.2) = 0.5; hermite(0.5) = 0.5*0.5*(3-2*0.5) = 0.5
+ expect(smoothstep(0.2, 0.8, 0.5)).toBeCloseTo(0.5, 10);
+ });
+
+ it("is monotonically increasing", () => {
+ const vals = [0.3, 0.4, 0.5, 0.6, 0.7].map((x) => smoothstep(0.2, 0.8, x));
+ for (let i = 1; i < vals.length; i++) {
+ expect(vals[i]).toBeGreaterThan(vals[i - 1] ?? 0);
+ }
+ });
+});
+
+// ── hash ──────────────────────────────────────────────────────────────────────
+
+describe("hash", () => {
+ it("returns a value in [0, 1)", () => {
+ const h = hash(1.5, 2.7);
+ expect(h).toBeGreaterThanOrEqual(0);
+ expect(h).toBeLessThan(1);
+ });
+
+ it("is deterministic for the same inputs", () => {
+ expect(hash(3.14, 2.71)).toBe(hash(3.14, 2.71));
+ });
+
+ it("returns different values for different inputs", () => {
+ expect(hash(0, 0)).not.toBe(hash(1, 0));
+ expect(hash(0, 0)).not.toBe(hash(0, 1));
+ });
+
+ it("returns values in [0,1) for integer grid points", () => {
+ for (let i = 0; i < 5; i++) {
+ for (let j = 0; j < 5; j++) {
+ const h = hash(i, j);
+ expect(h).toBeGreaterThanOrEqual(0);
+ expect(h).toBeLessThan(1);
+ }
+ }
+ });
+});
+
+// ── vnoise ────────────────────────────────────────────────────────────────────
+
+describe("vnoise", () => {
+ it("returns a value in [0, 1]", () => {
+ const v = vnoise(1.5, 2.3);
+ expect(v).toBeGreaterThanOrEqual(0);
+ expect(v).toBeLessThanOrEqual(1);
+ });
+
+ it("is deterministic for the same inputs", () => {
+ expect(vnoise(3.14, 2.71)).toBe(vnoise(3.14, 2.71));
+ });
+
+ it("returns [0,1] range over a grid", () => {
+ for (let i = 0; i < 4; i++) {
+ for (let j = 0; j < 4; j++) {
+ const v = vnoise(i * 0.7, j * 0.7);
+ expect(v).toBeGreaterThanOrEqual(0);
+ expect(v).toBeLessThanOrEqual(1);
+ }
+ }
+ });
+
+ it("produces variation across the domain (not constant)", () => {
+ const values = new Set([
+ vnoise(0, 0),
+ vnoise(1, 0),
+ vnoise(0, 1),
+ vnoise(1, 1),
+ vnoise(0.5, 0.5),
+ ]);
+ // At least 2 distinct values among 5 samples
+ expect(values.size).toBeGreaterThan(1);
+ });
+});
+
+// ── fbm ───────────────────────────────────────────────────────────────────────
+
+describe("fbm", () => {
+ it("is deterministic for the same inputs", () => {
+ expect(fbm(1.5, 2.3)).toBe(fbm(1.5, 2.3));
+ });
+
+ it("returns consistent known values", () => {
+ const v0 = fbm(0, 0);
+ const v1 = fbm(1, 0);
+ const v2 = fbm(0, 1);
+ // All should be finite numbers (not NaN/Infinity)
+ expect(Number.isFinite(v0)).toBe(true);
+ expect(Number.isFinite(v1)).toBe(true);
+ expect(Number.isFinite(v2)).toBe(true);
+ // Should produce different values for different inputs
+ expect(v0).not.toBe(v1);
+ expect(v0).not.toBe(v2);
+ });
+
+ it("produces values in a reasonable range", () => {
+ // fbm sums 5 octaves of vnoise (0–1) with amplitudes 0.5,0.25,0.125,0.0625,0.03125
+ // max possible ≈ 0.96875; values should be positive
+ const v = fbm(2.5, 3.7);
+ expect(v).toBeGreaterThan(0);
+ expect(v).toBeLessThan(1.1);
+ });
+});
+
+// ── transition helpers ────────────────────────────────────────────────────────
+
+function makeBuffer(w: number, h: number, r: number, g: number, b: number): Buffer {
+ const buf = Buffer.alloc(w * h * 6);
+ for (let i = 0; i < w * h; i++) {
+ buf.writeUInt16LE(r, i * 6);
+ buf.writeUInt16LE(g, i * 6 + 2);
+ buf.writeUInt16LE(b, i * 6 + 4);
+ }
+ return buf;
+}
+
+function runTransition(
+ fn: TransitionFn,
+ w: number,
+ h: number,
+ fR: number,
+ fG: number,
+ fB: number,
+ tR: number,
+ tG: number,
+ tB: number,
+ progress: number,
+): Buffer {
+ const from = makeBuffer(w, h, fR, fG, fB);
+ const to = makeBuffer(w, h, tR, tG, tB);
+ const out = Buffer.alloc(w * h * 6);
+ fn(from, to, out, w, h, progress);
+ return out;
+}
+
+// ── crossfade ─────────────────────────────────────────────────────────────────
+
+describe("crossfade", () => {
+ it("at progress=0 output equals from", () => {
+ const out = runTransition(crossfade, 2, 2, 10000, 20000, 30000, 50000, 55000, 60000, 0);
+ for (let i = 0; i < 4; i++) {
+ expect(out.readUInt16LE(i * 6)).toBe(10000);
+ expect(out.readUInt16LE(i * 6 + 2)).toBe(20000);
+ expect(out.readUInt16LE(i * 6 + 4)).toBe(30000);
+ }
+ });
+
+ it("at progress=1 output equals to", () => {
+ const out = runTransition(crossfade, 2, 2, 10000, 20000, 30000, 50000, 55000, 60000, 1);
+ for (let i = 0; i < 4; i++) {
+ expect(out.readUInt16LE(i * 6)).toBe(50000);
+ expect(out.readUInt16LE(i * 6 + 2)).toBe(55000);
+ expect(out.readUInt16LE(i * 6 + 4)).toBe(60000);
+ }
+ });
+
+ it("at progress=0.5 output is midpoint of from and to", () => {
+ const out = runTransition(crossfade, 1, 1, 0, 0, 0, 60000, 60000, 60000, 0.5);
+ expect(out.readUInt16LE(0)).toBe(30000);
+ expect(out.readUInt16LE(2)).toBe(30000);
+ expect(out.readUInt16LE(4)).toBe(30000);
+ });
+
+ it("is registered in TRANSITIONS", () => {
+ expect(TRANSITIONS["crossfade"]).toBe(crossfade);
+ });
+});
+
+// ── flashThroughWhite ─────────────────────────────────────────────────────────
+
+describe("flashThroughWhite", () => {
+ it("at progress=0 output approximates from", () => {
+ // toWhite = smoothstep(0,0.45,0) = 0, fromWhite = 1-smoothstep(0.5,1,0) = 1,
+ // blend = smoothstep(0.35,0.65,0) = 0 → output = fromC = from (untouched)
+ const out = runTransition(flashThroughWhite, 1, 1, 10000, 20000, 30000, 50000, 55000, 60000, 0);
+ expect(out.readUInt16LE(0)).toBe(10000);
+ expect(out.readUInt16LE(2)).toBe(20000);
+ expect(out.readUInt16LE(4)).toBe(30000);
+ });
+
+ it("at progress≈0.45 all channels are near white (>50000)", () => {
+ // toWhite = smoothstep(0,0.45,0.45) = 1 → fromC = white
+ // fromWhite = 1-smoothstep(0.5,1,0.45) = 1 → toC = white
+ // both inputs to blend are white → output is white
+ const out = runTransition(
+ flashThroughWhite,
+ 1,
+ 1,
+ 10000,
+ 20000,
+ 30000,
+ 50000,
+ 55000,
+ 60000,
+ 0.45,
+ );
+ expect(out.readUInt16LE(0)).toBeGreaterThan(50000);
+ expect(out.readUInt16LE(2)).toBeGreaterThan(50000);
+ expect(out.readUInt16LE(4)).toBeGreaterThan(50000);
+ });
+
+ it("at progress=1 output approximates to", () => {
+ // toWhite = smoothstep(0,0.45,1) = 1, fromWhite = 1-smoothstep(0.5,1,1) = 0,
+ // blend = smoothstep(0.35,0.65,1) = 1 → output = toC = to (untouched)
+ const out = runTransition(flashThroughWhite, 1, 1, 10000, 20000, 30000, 50000, 55000, 60000, 1);
+ expect(out.readUInt16LE(0)).toBe(50000);
+ expect(out.readUInt16LE(2)).toBe(55000);
+ expect(out.readUInt16LE(4)).toBe(60000);
+ });
+
+ it("is registered in TRANSITIONS", () => {
+ expect(TRANSITIONS["flash-through-white"]).toBe(flashThroughWhite);
+ });
+});
+
+// ── all transitions smoke test ────────────────────────────────────────────────
+
+const ALL_SHADERS = [
+ "crossfade",
+ "flash-through-white",
+ "chromatic-split",
+ "sdf-iris",
+ "whip-pan",
+ "cinematic-zoom",
+ "gravitational-lens",
+ "glitch",
+ "ripple-waves",
+ "swirl-vortex",
+ "thermal-distortion",
+ "domain-warp",
+ "ridged-burn",
+ "cross-warp-morph",
+ "light-leak",
+];
+
+// Pixel offset selector for the "at progress=0, center pixel ≈ from" test.
+// Most transitions use the center pixel (4*8+4). Two shaders require a
+// different test pixel because their design does not produce `from` at the
+// center when p=0:
+// sdf-iris: the iris reveal shows `to` inside and `from` outside.
+// At any p>0 the center is inside → shows `to`. We use
+// a corner pixel (row 0, col 0) that stays outside the
+// iris until p is large.
+// gravitational-lens: at p=0 the horizon mask is 0 at center (dist=0),
+// producing black. A corner pixel (dist≈0.7) has
+// horizon > 0 and shows a lensed version of `from`.
+const P0_PIXEL: Record<string, number> = {
+ "sdf-iris": 0 * 6, // top-left corner: always outside iris at p=0
+ "gravitational-lens": (0 * 8 + 0) * 6, // top-left corner: non-zero dist
+};
+
+describe("all transitions smoke test", () => {
+ for (const name of ALL_SHADERS) {
+ describe(name, () => {
+ it("exists in registry", () => {
+ expect(TRANSITIONS[name]).toBeDefined();
+ });
+ it("at progress=0, center pixel ≈ from", () => {
+ const from = makeBuffer(8, 8, 40000, 30000, 20000);
+ const to = makeBuffer(8, 8, 10000, 10000, 10000);
+ const out = Buffer.alloc(8 * 8 * 6);
+ const fn = TRANSITIONS[name];
+ expect(fn).toBeDefined();
+ fn?.(from, to, out, 8, 8, 0);
+ const o = P0_PIXEL[name] ?? (4 * 8 + 4) * 6;
+ // At progress=0 the result should be the `from` pixel (R=40000).
+ // The midpoint between from (40000) and to (10000) is 25000, so a
+ // tighter threshold catches transitions that are halfway-blended
+ // when they should be fully on the `from` side.
+ expect(out.readUInt16LE(o)).toBeGreaterThan(35000);
+ });
+ it("at progress=1, center pixel ≈ to", () => {
+ const from = makeBuffer(8, 8, 40000, 30000, 20000);
+ const to = makeBuffer(8, 8, 10000, 10000, 10000);
+ const out = Buffer.alloc(8 * 8 * 6);
+ const fn = TRANSITIONS[name];
+ expect(fn).toBeDefined();
+ fn?.(from, to, out, 8, 8, 1);
+ const o = (4 * 8 + 4) * 6;
+ // At progress=1 the result should be the `to` pixel (R=10000).
+ // Tighter than the previous halfway midpoint (25000) so that any
+ // transition that is still half-blended will fail.
+ expect(out.readUInt16LE(o)).toBeLessThan(15000);
+ });
+ });
+ }
+});
+
+// ── hdrToLinear / linearToHdr roundtrip ────────────────────────────────────
+
+describe("hdrToLinear / linearToHdr", () => {
+ for (const transfer of ["pq", "hlg"] as const) {
+ describe(transfer, () => {
+ it("roundtrip preserves mid-to-high values", () => {
+ // PQ concentrates precision in the dark range — linearizing then
+ // re-quantizing at 16-bit loses bits for values below ~16000.
+ // HLG squares small inputs, similar effect. Test the mid-to-high
+ // range where roundtrip error is bounded.
+ const values = [16384, 32768, 50000, 65535];
+ const buf = Buffer.alloc(values.length * 2);
+ for (let i = 0; i < values.length; i++) {
+ buf.writeUInt16LE(values[i] ?? 0, i * 2);
+ }
+ const original = Buffer.from(buf);
+ hdrToLinear(buf, transfer);
+ linearToHdr(buf, transfer);
+ for (let i = 0; i < values.length; i++) {
+ const got = buf.readUInt16LE(i * 2);
+ const want = original.readUInt16LE(i * 2);
+ expect(Math.abs(got - want)).toBeLessThanOrEqual(30);
+ }
+ });
+
+ it("zero maps to zero", () => {
+ const buf = Buffer.alloc(2);
+ buf.writeUInt16LE(0, 0);
+ hdrToLinear(buf, transfer);
+ expect(buf.readUInt16LE(0)).toBe(0);
+ });
+
+ it("65535 maps to 65535", () => {
+ const buf = Buffer.alloc(2);
+ buf.writeUInt16LE(65535, 0);
+ hdrToLinear(buf, transfer);
+ linearToHdr(buf, transfer);
+ expect(buf.readUInt16LE(0)).toBe(65535);
+ });
+
+ it("hdrToLinear produces monotonically increasing output", () => {
+ const steps = [0, 1000, 5000, 10000, 20000, 40000, 65535];
+ const buf = Buffer.alloc(steps.length * 2);
+ for (let i = 0; i < steps.length; i++) {
+ buf.writeUInt16LE(steps[i] ?? 0, i * 2);
+ }
+ hdrToLinear(buf, transfer);
+ let prev = 0;
+ for (let i = 0; i < steps.length; i++) {
+ const val = buf.readUInt16LE(i * 2);
+ expect(val).toBeGreaterThanOrEqual(prev);
+ prev = val;
+ }
+ });
+ });
+ }
+});
+
+// ── convertTransfer (HLG↔PQ) ─────────────────────────────────────────────
+
+describe("convertTransfer", () => {
+ it("no-op when from === to", () => {
+ const buf = Buffer.alloc(6);
+ buf.writeUInt16LE(32768, 0);
+ buf.writeUInt16LE(16384, 2);
+ buf.writeUInt16LE(8192, 4);
+ const original = Buffer.from(buf);
+ convertTransfer(buf, "pq", "pq");
+ expect(buf.equals(original)).toBe(true);
+ });
+
+ it("hlg→pq→hlg roundtrip preserves mid-high values", () => {
+ const values = [16384, 32768, 50000, 65535];
+ const buf = Buffer.alloc(values.length * 2);
+ for (let i = 0; i < values.length; i++) {
+ buf.writeUInt16LE(values[i] ?? 0, i * 2);
+ }
+ const original = Buffer.from(buf);
+ convertTransfer(buf, "hlg", "pq");
+ expect(buf.equals(original)).toBe(false);
+ convertTransfer(buf, "pq", "hlg");
+ for (let i = 0; i < values.length; i++) {
+ const got = buf.readUInt16LE(i * 2);
+ const want = original.readUInt16LE(i * 2);
+ expect(Math.abs(got - want)).toBeLessThanOrEqual(30);
+ }
+ });
+
+ it("hlg→pq produces different values", () => {
+ const buf = Buffer.alloc(2);
+ buf.writeUInt16LE(32768, 0);
+ const before = buf.readUInt16LE(0);
+ convertTransfer(buf, "hlg", "pq");
+ expect(buf.readUInt16LE(0)).not.toBe(before);
+ });
+});
diff --git a/packages/engine/src/utils/shaderTransitions.ts b/packages/engine/src/utils/shaderTransitions.ts
new file mode 100644
index 0000000000..6a20d64557
--- /dev/null
+++ b/packages/engine/src/utils/shaderTransitions.ts
@@ -0,0 +1,1130 @@
+/**
+ * Shader Transition Math Utilities
+ *
+ * Sampling helpers and math primitives for rgb48le shader transitions.
+ * Functions are ported from GLSL to operate on 16-bit little-endian pixel
+ * buffers (6 bytes per pixel: R, G, B each stored as UInt16LE).
+ */
+
+// ── PQ linearization ─────────────────────────────────────────────────────────
+// Shader transitions were ported from sRGB GLSL where pixel values distribute
+// linearly across the visible range. In PQ space, dark content clusters near
+// zero, causing UV-warping shaders to produce black artifacts. Converting to
+// linear light before the shader and back to PQ after gives correct results.
+
+const PQ_M1 = 0.1593017578125;
+const PQ_M2 = 78.84375;
+const PQ_C1 = 0.8359375;
+const PQ_C2 = 18.8515625;
+const PQ_C3 = 18.6875;
+
+/** PQ EOTF: decode PQ signal (0-1) → linear light (0-1, normalized to 10000 nits). */
+function pqEotf(signal: number): number {
+ const sp = Math.pow(Math.max(0, signal), 1 / PQ_M2);
+ const num = Math.max(sp - PQ_C1, 0);
+ const den = PQ_C2 - PQ_C3 * sp;
+ return den > 0 ? Math.pow(num / den, 1 / PQ_M1) : 0;
+}
+
+/** PQ OETF: encode linear light (0-1) → PQ signal (0-1). */
+function pqOetf(linear: number): number {
+ const lp = Math.pow(Math.max(0, linear), PQ_M1);
+ return Math.pow((PQ_C1 + PQ_C2 * lp) / (1 + PQ_C3 * lp), PQ_M2);
+}
+
+/** HLG OETF inverse: decode HLG signal (0-1) → linear scene light (0-1). */
+function hlgEotf(signal: number): number {
+ const a = 0.17883277;
+ const b = 1 - 4 * a;
+ const c = 0.5 - a * Math.log(4 * a);
+ if (signal <= 0.5) {
+ return (signal * signal) / 3;
+ }
+ return (Math.exp((signal - c) / a) + b) / 12;
+}
+
+/** HLG OETF: encode linear scene light (0-1) → HLG signal (0-1). */
+function hlgOetf(linear: number): number {
+ const a = 0.17883277;
+ const b = 1 - 4 * a;
+ const c = 0.5 - a * Math.log(4 * a);
+ if (linear <= 1 / 12) {
+ return Math.sqrt(3 * linear);
+ }
+ return a * Math.log(12 * linear - b) + c;
+}
+
+// ── Precomputed LUTs for fast HDR↔linear conversion ─────────────────────────
+// 65536-entry lookup tables eliminate per-pixel Math.pow calls. Built once on
+// first use, then reused for all subsequent conversions. At 4K (8.3M pixels ×
+// 3 channels × 3 buffers), this turns ~75M Math.pow calls per transition frame
+// into 75M array lookups — ~100× faster.
+
+function buildLut(fn: (v: number) => number): Uint16Array {
+ const lut = new Uint16Array(65536);
+ for (let i = 0; i < 65536; i++) {
+ lut[i] = Math.round(fn(i / 65535) * 65535);
+ }
+ return lut;
+}
+
+let pqToLinearLut: Uint16Array | null = null;
+let linearToPqLut: Uint16Array | null = null;
+let hlgToLinearLut: Uint16Array | null = null;
+let linearToHlgLut: Uint16Array | null = null;
+
+function getPqToLinearLut(): Uint16Array {
+ if (!pqToLinearLut) pqToLinearLut = buildLut(pqEotf);
+ return pqToLinearLut;
+}
+function getLinearToPqLut(): Uint16Array {
+ if (!linearToPqLut) linearToPqLut = buildLut(pqOetf);
+ return linearToPqLut;
+}
+function getHlgToLinearLut(): Uint16Array {
+ if (!hlgToLinearLut) hlgToLinearLut = buildLut(hlgEotf);
+ return hlgToLinearLut;
+}
+function getLinearToHlgLut(): Uint16Array {
+ if (!linearToHlgLut) linearToHlgLut = buildLut(hlgOetf);
+ return linearToHlgLut;
+}
+
+/**
+ * Convert an rgb48le buffer from HDR signal space to linear light, in-place.
+ * Uses precomputed 65536-entry LUT for O(1) per-sample conversion.
+ * @param transfer "pq" or "hlg"
+ */
+export function hdrToLinear(buf: Buffer, transfer: "pq" | "hlg"): void {
+ const lut = transfer === "pq" ? getPqToLinearLut() : getHlgToLinearLut();
+ const len = buf.length / 2;
+ for (let i = 0; i < len; i++) {
+ const off = i * 2;
+ buf.writeUInt16LE(lut[buf.readUInt16LE(off)] ?? 0, off);
+ }
+}
+
+/**
+ * Convert an rgb48le buffer from linear light back to HDR signal space, in-place.
+ * Uses precomputed 65536-entry LUT for O(1) per-sample conversion.
+ * @param transfer "pq" or "hlg"
+ */
+export function linearToHdr(buf: Buffer, transfer: "pq" | "hlg"): void {
+ const lut = transfer === "pq" ? getLinearToPqLut() : getLinearToHlgLut();
+ const len = buf.length / 2;
+ for (let i = 0; i < len; i++) {
+ const off = i * 2;
+ buf.writeUInt16LE(lut[buf.readUInt16LE(off)] ?? 0, off);
+ }
+}
+
+// ── Cross-transfer conversion (HLG↔PQ) ──────────────────────────────────────
+// HLG is scene-referred, PQ is display-referred. Converting between them
+// requires the OOTF (Optical-Optical Transfer Function) which maps scene
+// light to display light. Per BT.2100, the HLG OOTF for a reference
+// display at Lw nits is: Y_display = Lw * Y_scene^gamma, where
+// gamma = 1.2 * 1.111^(log2(Lw/1000)). At 1000 nits: gamma = 1.2.
+//
+// The per-channel approximation (applying gamma per-channel rather than
+// on luminance Y) introduces slight color shifts but avoids a full
+// colorimetric conversion with BT.2020 luma coefficients.
+
+const HLG_OOTF_LW = 1000; // reference display peak luminance (nits)
+const HLG_OOTF_GAMMA = 1.2 * Math.pow(1.111, Math.log2(HLG_OOTF_LW / 1000));
+
+/** HLG scene light → PQ display light (per-channel, normalized to 10000 nits) */
+function hlgSceneToPqDisplay(sceneLinear: number): number {
+ const displayNits = HLG_OOTF_LW * Math.pow(Math.max(0, sceneLinear), HLG_OOTF_GAMMA);
+ return displayNits / 10000; // PQ is normalized to 10000 nits
+}
+
+/** PQ display light → HLG scene light (inverse OOTF) */
+function pqDisplayToHlgScene(displayNormalized: number): number {
+ const displayNits = displayNormalized * 10000;
+ return Math.pow(Math.max(0, displayNits / HLG_OOTF_LW), 1 / HLG_OOTF_GAMMA);
+}
+
+let hlgToPqLut: Uint16Array | null = null;
+let pqToHlgLut: Uint16Array | null = null;
+
+function getHlgToPqLut(): Uint16Array {
+ // HLG signal → scene linear (EOTF) → display linear (OOTF) → PQ signal (OETF)
+ if (!hlgToPqLut) hlgToPqLut = buildLut((v) => pqOetf(hlgSceneToPqDisplay(hlgEotf(v))));
+ return hlgToPqLut;
+}
+function getPqToHlgLut(): Uint16Array {
+ // PQ signal → display linear (EOTF) → scene linear (inverse OOTF) → HLG signal (OETF)
+ if (!pqToHlgLut) pqToHlgLut = buildLut((v) => hlgOetf(pqDisplayToHlgScene(pqEotf(v))));
+ return pqToHlgLut;
+}
+
+/**
+ * Convert an rgb48le buffer between HDR transfer functions, in-place.
+ * Uses a composite 65536-entry LUT (source EOTF → linear → target OETF)
+ * for O(1) per-sample conversion. No-op if from === to.
+ */
+export function convertTransfer(buf: Buffer, from: "pq" | "hlg", to: "pq" | "hlg"): void {
+ if (from === to) return;
+ const lut = from === "hlg" ? getHlgToPqLut() : getPqToHlgLut();
+ const len = buf.length / 2;
+ for (let i = 0; i < len; i++) {
+ const off = i * 2;
+ buf.writeUInt16LE(lut[buf.readUInt16LE(off)] ?? 0, off);
+ }
+}
+
+// ── Buffer sampling ───────────────────────────────────────────────────────────
+
+/**
+ * Sample an rgb48le buffer at floating-point UV coordinates (0–1 range, clamped).
+ * Uses bilinear interpolation between the 4 nearest pixels, equivalent to
+ * GLSL `texture2D` with clamp-to-edge wrapping.
+ *
+ * @param buf rgb48le buffer — w * h * 6 bytes
+ * @param u Horizontal coordinate in [0, 1]
+ * @param v Vertical coordinate in [0, 1]
+ * @param w Image width in pixels
+ * @param h Image height in pixels
+ * @returns [r, g, b] as 16-bit values (0–65535)
+ */
+export function sampleRgb48le(
+ buf: Buffer,
+ u: number,
+ v: number,
+ w: number,
+ h: number,
+): [number, number, number] {
+ // Clamp UV to [0, 1] then map to pixel coordinates
+ const uc = Math.max(0, Math.min(1, u));
+ const vc = Math.max(0, Math.min(1, v));
+
+ const sx = uc * (w - 1);
+ const sy = vc * (h - 1);
+
+ const x0 = Math.floor(sx);
+ const y0 = Math.floor(sy);
+ const x1 = Math.min(x0 + 1, w - 1);
+ const y1 = Math.min(y0 + 1, h - 1);
+
+ const fx = sx - x0;
+ const fy = sy - y0;
+
+ const w00 = (1 - fx) * (1 - fy);
+ const w10 = fx * (1 - fy);
+ const w01 = (1 - fx) * fy;
+ const w11 = fx * fy;
+
+ const off00 = (y0 * w + x0) * 6;
+ const off10 = (y0 * w + x1) * 6;
+ const off01 = (y1 * w + x0) * 6;
+ const off11 = (y1 * w + x1) * 6;
+
+ const r = Math.round(
+ buf.readUInt16LE(off00) * w00 +
+ buf.readUInt16LE(off10) * w10 +
+ buf.readUInt16LE(off01) * w01 +
+ buf.readUInt16LE(off11) * w11,
+ );
+ const g = Math.round(
+ buf.readUInt16LE(off00 + 2) * w00 +
+ buf.readUInt16LE(off10 + 2) * w10 +
+ buf.readUInt16LE(off01 + 2) * w01 +
+ buf.readUInt16LE(off11 + 2) * w11,
+ );
+ const b = Math.round(
+ buf.readUInt16LE(off00 + 4) * w00 +
+ buf.readUInt16LE(off10 + 4) * w10 +
+ buf.readUInt16LE(off01 + 4) * w01 +
+ buf.readUInt16LE(off11 + 4) * w11,
+ );
+
+ return [r, g, b];
+}
+
+// ── 16-bit math primitives ────────────────────────────────────────────────────
+
+/**
+ * Linear interpolate two 16-bit values. Equivalent to GLSL `mix(a, b, t)`.
+ */
+export function mix16(a: number, b: number, t: number): number {
+ return Math.round(a * (1 - t) + b * t);
+}
+
+/**
+ * Clamp a value to the 16-bit unsigned range [0, 65535].
+ */
+export function clamp16(v: number): number {
+ return Math.max(0, Math.min(65535, v));
+}
+
+// ── GLSL math ports ───────────────────────────────────────────────────────────
+
+/**
+ * Hermite interpolation from GLSL `smoothstep(edge0, edge1, x)`.
+ * Returns 0 for x ≤ edge0, 1 for x ≥ edge1, and a smooth S-curve between.
+ */
+export function smoothstep(edge0: number, edge1: number, x: number): number {
+ const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
+ return t * t * (3 - 2 * t);
+}
+
+/**
+ * Deterministic pseudo-random value in [0, 1).
+ * Port of the GLSL idiom: `fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453)`.
+ */
+export function hash(x: number, y: number): number {
+ return (((Math.sin(x * 127.1 + y * 311.7) * 43758.5453) % 1) + 1) % 1;
+}
+
+/**
+ * Value noise with C2-continuous quintic interpolation.
+ * Samples `hash()` at the 4 surrounding integer grid corners and blends
+ * using the quintic fade f = f³(f(6f − 15) + 10).
+ *
+ * Returns a value in [0, 1].
+ */
+export function vnoise(px: number, py: number): number {
+ const ix = Math.floor(px);
+ const iy = Math.floor(py);
+
+ // Fractional part
+ let fx = px - ix;
+ let fy = py - iy;
+
+ // Quintic C2 interpolation weights
+ fx = fx * fx * fx * (fx * (fx * 6 - 15) + 10);
+ fy = fy * fy * fy * (fy * (fy * 6 - 15) + 10);
+
+ const h00 = hash(ix, iy);
+ const h10 = hash(ix + 1, iy);
+ const h01 = hash(ix, iy + 1);
+ const h11 = hash(ix + 1, iy + 1);
+
+ // Bilinear blend
+ return h00 * (1 - fx) * (1 - fy) + h10 * fx * (1 - fy) + h01 * (1 - fx) * fy + h11 * fx * fy;
+}
+
+// Rotation matrix constants from GLSL: mat2(0.8, 0.6, -0.6, 0.8)
+// Applies to [px, py]: px' = 0.8*px - 0.6*py, py' = 0.6*px + 0.8*py
+const ROT_A = 0.8;
+const ROT_B = 0.6;
+
+/**
+ * Fractal Brownian motion — 5-octave accumulation of value noise.
+ *
+ * Each octave: accumulate `amplitude * vnoise(p)`, rotate p by 36.87°,
+ * scale by 2.02, halve the amplitude. Matching the GLSL convention of
+ * `mat2(0.8, 0.6, -0.6, 0.8)` for the rotation.
+ */
+export function fbm(px: number, py: number): number {
+ let value = 0;
+ let amplitude = 0.5;
+ let x = px;
+ let y = py;
+
+ for (let i = 0; i < 5; i++) {
+ value += amplitude * vnoise(x, y);
+
+ // Rotate by mat2(0.8, 0.6, -0.6, 0.8)
+ const nx = ROT_A * x - ROT_B * y;
+ const ny = ROT_B * x + ROT_A * y;
+ x = nx * 2.02;
+ y = ny * 2.02;
+
+ amplitude *= 0.5;
+ }
+
+ return value;
+}
+
+// ── Transition types and registry ─────────────────────────────────────────────
+
+/** A transition function that blends two rgb48le buffers into an output buffer. */
+export type TransitionFn = (
+ from: Buffer,
+ to: Buffer,
+ output: Buffer,
+ width: number,
+ height: number,
+ progress: number,
+) => void;
+
+/** Registry of all available transitions by name. */
+export const TRANSITIONS: Record<string, TransitionFn> = {};
+
+// ── crossfade ─────────────────────────────────────────────────────────────────
+
+/**
+ * Simple linear blend between two frames. Equivalent to GLSL `mix(from, to, progress)`.
+ */
+export const crossfade: TransitionFn = (from, to, out, w, h, p) => {
+ const inv = 1 - p;
+ for (let i = 0; i < w * h; i++) {
+ const o = i * 6;
+ out.writeUInt16LE(Math.round(from.readUInt16LE(o) * inv + to.readUInt16LE(o) * p), o);
+ out.writeUInt16LE(
+ Math.round(from.readUInt16LE(o + 2) * inv + to.readUInt16LE(o + 2) * p),
+ o + 2,
+ );
+ out.writeUInt16LE(
+ Math.round(from.readUInt16LE(o + 4) * inv + to.readUInt16LE(o + 4) * p),
+ o + 4,
+ );
+ }
+};
+TRANSITIONS["crossfade"] = crossfade;
+
+// ── flashThroughWhite ─────────────────────────────────────────────────────────
+
+/**
+ * Flash-through-white transition: the outgoing scene brightens to white while
+ * the incoming scene emerges from white, creating a bright flash at the midpoint.
+ *
+ * Port of the GLSL flash-through-white shader.
+ */
+export const flashThroughWhite: TransitionFn = (from, to, out, w, h, p) => {
+ const toWhite = smoothstep(0, 0.45, p); // outgoing brightens toward white
+ const fromWhite = 1 - smoothstep(0.5, 1, p); // incoming starts from white
+ const blend = smoothstep(0.35, 0.65, p); // crossfade between the two
+
+ for (let i = 0; i < w * h; i++) {
+ const o = i * 6;
+ const fromR = mix16(from.readUInt16LE(o), 65535, toWhite);
+ const fromG = mix16(from.readUInt16LE(o + 2), 65535, toWhite);
+ const fromB = mix16(from.readUInt16LE(o + 4), 65535, toWhite);
+
+ const toR = mix16(to.readUInt16LE(o), 65535, fromWhite);
+ const toG = mix16(to.readUInt16LE(o + 2), 65535, fromWhite);
+ const toB = mix16(to.readUInt16LE(o + 4), 65535, fromWhite);
+
+ out.writeUInt16LE(mix16(fromR, toR, blend), o);
+ out.writeUInt16LE(mix16(fromG, toG, blend), o + 2);
+ out.writeUInt16LE(mix16(fromB, toB, blend), o + 4);
+ }
+};
+TRANSITIONS["flash-through-white"] = flashThroughWhite;
+
+// ── chromatic-split ───────────────────────────────────────────────────────────
+
+/**
+ * RGB channel offset transition. Each channel is sampled at a different UV
+ * offset, spreading apart as progress increases (outgoing) and converging
+ * as progress approaches 1 (incoming). Port of the GLSL chromatic-split shader.
+ */
+export const chromaticSplit: TransitionFn = (from, to, out, w, h, p) => {
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ // Center-relative UV for offset direction
+ const cx = ux - 0.5;
+ const cy = uy - 0.5;
+
+ const fromShift = p * 0.06;
+ const fr = sampleRgb48le(from, ux + cx * fromShift, uy + cy * fromShift, w, h)[0];
+ const fg = sampleRgb48le(from, ux, uy, w, h)[1];
+ const fb = sampleRgb48le(from, ux - cx * fromShift, uy - cy * fromShift, w, h)[2];
+
+ const toShift = (1 - p) * 0.06;
+ const tr = sampleRgb48le(to, ux - cx * toShift, uy - cy * toShift, w, h)[0];
+ const tg = sampleRgb48le(to, ux, uy, w, h)[1];
+ const tb = sampleRgb48le(to, ux + cx * toShift, uy + cy * toShift, w, h)[2];
+
+ out.writeUInt16LE(clamp16(mix16(fr, tr, p)), o);
+ out.writeUInt16LE(clamp16(mix16(fg, tg, p)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(fb, tb, p)), o + 4);
+ }
+};
+TRANSITIONS["chromatic-split"] = chromaticSplit;
+
+// ── sdf-iris ──────────────────────────────────────────────────────────────────
+
+/**
+ * Circular iris reveal. A sharp edge expands from the center while golden
+ * glow rings ripple outward at the boundary. Port of the GLSL sdf-iris shader.
+ */
+export const sdfIris: TransitionFn = (from, to, out, w, h, p) => {
+ // Accent colors for glow rings (16-bit scale)
+ const accentBright = [65535, 55000, 35000] as const;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ // Aspect-corrected distance from center
+ const ax = (ux - 0.5) * (w / h);
+ const ay = uy - 0.5;
+ const d = Math.sqrt(ax * ax + ay * ay);
+
+ const radius = p * 1.2;
+ const fw = 0.003;
+ const edge = smoothstep(radius + fw, radius - fw, d);
+
+ // Three glow rings at different radii and falloff speeds
+ const ring1 = Math.exp(-Math.abs(d - radius) * 25);
+ const ring2 = Math.exp(-Math.abs(d - radius + 0.04) * 20) * 0.5;
+ const ring3 = Math.exp(-Math.abs(d - radius + 0.08) * 15) * 0.25;
+ const glow = (ring1 + ring2 + ring3) * p * (1 - p) * 4;
+
+ const [fromR, fromG, fromB] = sampleRgb48le(from, ux, uy, w, h);
+ const [toR, toG, toB] = sampleRgb48le(to, ux, uy, w, h);
+
+ out.writeUInt16LE(clamp16(mix16(fromR, toR, edge) + accentBright[0] * glow * 0.6), o);
+ out.writeUInt16LE(clamp16(mix16(fromG, toG, edge) + accentBright[1] * glow * 0.6), o + 2);
+ out.writeUInt16LE(clamp16(mix16(fromB, toB, edge) + accentBright[2] * glow * 0.6), o + 4);
+ }
+};
+TRANSITIONS["sdf-iris"] = sdfIris;
+
+// ── glitch ────────────────────────────────────────────────────────────────────
+
+/**
+ * Deterministic PRNG matching the GLSL `rand` in the glitch shader.
+ * Uses different constants than `hash` — do NOT substitute.
+ */
+function glitchRand(x: number, y: number): number {
+ return (((Math.sin(x * 12.9898 + y * 78.233) * 43758.5453) % 1) + 1) % 1;
+}
+
+/**
+ * Block displacement + scanlines + RGB channel split. Intensity peaks at the
+ * midpoint (p=0.5) and decays at both ends. Port of the GLSL glitch shader.
+ */
+export const glitch: TransitionFn = (from, to, out, w, h, p) => {
+ const intensity = p * (1 - p) * 4;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ // Horizontal line displacement
+ const lineY = Math.floor(uy * 60) / 60;
+ const lineDisp = (glitchRand(lineY, Math.floor(p * 17)) - 0.5) * 0.18 * intensity;
+
+ // Block displacement
+ const blockX = Math.floor(ux * 12);
+ const blockY = Math.floor(uy * 8);
+ const progressStep = Math.floor(p * 11);
+ const br = glitchRand(blockX + progressStep, blockY + progressStep);
+ const ba = (br >= 0.83 ? 1 : 0) * intensity;
+ const bdx = (glitchRand(blockX * 2.1, blockY * 2.1) - 0.5) * 0.35 * ba;
+ const bdy = (glitchRand(blockX * 3.7, blockY * 3.7) - 0.5) * 0.35 * ba;
+
+ const uvx = Math.max(0, Math.min(1, ux + lineDisp + bdx));
+ const uvy = Math.max(0, Math.min(1, uy + bdy));
+
+ // RGB channel split on displaced UV
+ const shift = intensity * 0.035;
+ const r = sampleRgb48le(from, uvx + shift, uvy, w, h)[0];
+ const g = sampleRgb48le(from, uvx, uvy, w, h)[1];
+ const b = sampleRgb48le(from, uvx - shift, uvy, w, h)[2];
+
+ // Normalize to 0-1 for scanline, flicker, and crush operations
+ let cr = r / 65535;
+ let cg = g / 65535;
+ let cb = b / 65535;
+
+ // Scanline darkening: darken rows where fract(uy * h * 0.5) > 0.5
+ const scanline = (((uy * h * 0.5) % 1) + 1) % 1 >= 0.5 ? 0.05 * intensity : 0;
+ cr -= scanline;
+ cg -= scanline;
+ cb -= scanline;
+
+ // Brightness flicker
+ const flicker = 1 + (glitchRand(Math.floor(p * 23), 0) - 0.5) * 0.3 * intensity;
+ cr *= flicker;
+ cg *= flicker;
+ cb *= flicker;
+
+ // Color crush (posterize)
+ const levels = 256 - (256 - 8) * (intensity * 0.5);
+ cr = Math.floor(cr * levels) / levels;
+ cg = Math.floor(cg * levels) / levels;
+ cb = Math.floor(cb * levels) / levels;
+
+ // Scale back to 16-bit and mix with `to` by progress
+ const [toR, toG, toB] = sampleRgb48le(to, ux, uy, w, h);
+ out.writeUInt16LE(clamp16(mix16(Math.round(cr * 65535), toR, p)), o);
+ out.writeUInt16LE(clamp16(mix16(Math.round(cg * 65535), toG, p)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(Math.round(cb * 65535), toB, p)), o + 4);
+ }
+};
+TRANSITIONS["glitch"] = glitch;
+
+// ── light-leak ────────────────────────────────────────────────────────────────
+
+/**
+ * ACES filmic tonemap. Input and output in 0-1 normalized range.
+ * Formula: (x * (2.51x + 0.03)) / (x * (2.43x + 0.59) + 0.14)
+ */
+function aces(x: number): number {
+ return Math.max(0, Math.min(1, (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14)));
+}
+
+/**
+ * Warm lens-flare from the upper-right corner. The incoming scene burns through
+ * an overexposed flash, tonemapped with ACES and crossfaded with the outgoing
+ * scene. Port of the GLSL light-leak shader.
+ */
+export const lightLeak: TransitionFn = (from, to, out, w, h, p) => {
+ // Normalized accent colors (0-1 range for ACES pipeline)
+ const accent = [50000 / 65535, 25000 / 65535, 5000 / 65535] as const;
+ const accentBright = [65535 / 65535, 55000 / 65535, 35000 / 65535] as const;
+
+ // Light source position
+ const lpx = 1.3;
+ const lpy = -0.2;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const dx = ux - lpx;
+ const dy = uy - lpy;
+ const dist = Math.sqrt(dx * dx + dy * dy);
+
+ const leak = Math.max(0, Math.min(1, Math.exp(-dist * 1.8) * p * 4));
+
+ // Warm color: mix accent with accent_bright based on distance
+ const warmR = accent[0] + (accentBright[0] - accent[0]) * dist * 0.7;
+ const warmG = accent[1] + (accentBright[1] - accent[1]) * dist * 0.7;
+ const warmB = accent[2] + (accentBright[2] - accent[2]) * dist * 0.7;
+
+ // Lens flare streak
+ const flare = Math.exp(-Math.abs(uy - (-0.2 + ux * 0.3)) * 15) * leak * 0.3;
+
+ const [fr, fg, fb] = sampleRgb48le(from, ux, uy, w, h);
+ const fromR = fr / 65535;
+ const fromG = fg / 65535;
+ const fromB = fb / 65535;
+
+ // Overexpose and tonemap
+ const overR = aces(fromR + warmR * leak * 3 + accentBright[0] * flare);
+ const overG = aces(fromG + warmG * leak * 3 + accentBright[1] * flare);
+ const overB = aces(fromB + warmB * leak * 3 + accentBright[2] * flare);
+
+ // Mix overexposed → to by smoothstepped progress
+ const [toR, toG, toB] = sampleRgb48le(to, ux, uy, w, h);
+ const blend = smoothstep(0.15, 0.85, p);
+
+ out.writeUInt16LE(clamp16(mix16(Math.round(overR * 65535), toR, blend)), o);
+ out.writeUInt16LE(clamp16(mix16(Math.round(overG * 65535), toG, blend)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(Math.round(overB * 65535), toB, blend)), o + 4);
+ }
+};
+TRANSITIONS["light-leak"] = lightLeak;
+
+// ── cross-warp-morph ──────────────────────────────────────────────────────────
+
+/**
+ * FBM displacement warp. Both frames are warped in opposite directions by a
+ * fractal noise field, then blended by a noise-threshold mask that sweeps
+ * across the screen as progress advances. Port of the GLSL cross-warp-morph shader.
+ */
+export const crossWarpMorph: TransitionFn = (from, to, out, w, h, p) => {
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const dispX = fbm(ux * 3, uy * 3) - 0.5;
+ const dispY = fbm(ux * 3 + 7.3, uy * 3 + 3.7) - 0.5;
+
+ const fromUx = Math.max(0, Math.min(1, ux + dispX * p * 0.5));
+ const fromUy = Math.max(0, Math.min(1, uy + dispY * p * 0.5));
+ const toUx = Math.max(0, Math.min(1, ux - dispX * (1 - p) * 0.5));
+ const toUy = Math.max(0, Math.min(1, uy - dispY * (1 - p) * 0.5));
+
+ const [fromR, fromG, fromB] = sampleRgb48le(from, fromUx, fromUy, w, h);
+ const [toR, toG, toB] = sampleRgb48le(to, toUx, toUy, w, h);
+
+ const n = fbm(ux * 4 + 3.1, uy * 4 + 1.7);
+ const blend = smoothstep(0.4, 0.6, n + p * 1.2 - 0.6);
+
+ out.writeUInt16LE(clamp16(mix16(fromR, toR, blend)), o);
+ out.writeUInt16LE(clamp16(mix16(fromG, toG, blend)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(fromB, toB, blend)), o + 4);
+ }
+};
+TRANSITIONS["cross-warp-morph"] = crossWarpMorph;
+
+// ── whip-pan ──────────────────────────────────────────────────────────────────
+
+/**
+ * Horizontal motion blur. The outgoing frame is sampled with offsets shifted
+ * right (by progress*1.5) and the incoming frame is sampled with offsets shifted
+ * left (by (1-progress)*1.5). Each direction uses 10 samples averaged together.
+ * Port of the GLSL whip-pan shader.
+ */
+export const whipPan: TransitionFn = (from, to, out, w, h, p) => {
+ const fromOff = p * 1.5;
+ const toOff = (1 - p) * 1.5;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ let fromR = 0,
+ fromG = 0,
+ fromB = 0;
+ for (let s = 0; s < 10; s++) {
+ const f = s / 10;
+ const fuv = Math.max(0, Math.min(1, ux + fromOff + p * 0.08 * f));
+ const [r, g, b] = sampleRgb48le(from, fuv, uy, w, h);
+ fromR += r;
+ fromG += g;
+ fromB += b;
+ }
+ fromR /= 10;
+ fromG /= 10;
+ fromB /= 10;
+
+ let toR = 0,
+ toG = 0,
+ toB = 0;
+ for (let s = 0; s < 10; s++) {
+ const f = s / 10;
+ const tuv = Math.max(0, Math.min(1, ux - toOff - (1 - p) * 0.08 * f));
+ const [r, g, b] = sampleRgb48le(to, tuv, uy, w, h);
+ toR += r;
+ toG += g;
+ toB += b;
+ }
+ toR /= 10;
+ toG /= 10;
+ toB /= 10;
+
+ out.writeUInt16LE(clamp16(mix16(Math.round(fromR), Math.round(toR), p)), o);
+ out.writeUInt16LE(clamp16(mix16(Math.round(fromG), Math.round(toG), p)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(Math.round(fromB), Math.round(toB), p)), o + 4);
+ }
+};
+TRANSITIONS["whip-pan"] = whipPan;
+
+// ── cinematic-zoom ────────────────────────────────────────────────────────────
+
+/**
+ * Radial zoom blur with chromatic aberration. Both frames are blurred along a
+ * radial direction from center using 12 samples. R/G/B channels use slightly
+ * different zoom factors (1.06, 1.0, 0.94) for chromatic aberration. The
+ * outgoing frame zooms inward while the incoming zooms outward.
+ * Port of the GLSL cinematic-zoom shader.
+ */
+export const cinematicZoom: TransitionFn = (from, to, out, w, h, p) => {
+ const fromS = p * 0.08;
+ const toS = (1 - p) * 0.06;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const dx = ux - 0.5;
+ const dy = uy - 0.5;
+
+ let fr = 0,
+ fg = 0,
+ fb = 0;
+ for (let s = 0; s < 12; s++) {
+ const f = s / 12;
+ const rr = sampleRgb48le(
+ from,
+ ux - dx * fromS * 1.06 * f,
+ uy - dy * fromS * 1.06 * f,
+ w,
+ h,
+ )[0];
+ const gg = sampleRgb48le(from, ux - dx * fromS * f, uy - dy * fromS * f, w, h)[1];
+ const bb = sampleRgb48le(
+ from,
+ ux - dx * fromS * 0.94 * f,
+ uy - dy * fromS * 0.94 * f,
+ w,
+ h,
+ )[2];
+ fr += rr;
+ fg += gg;
+ fb += bb;
+ }
+ fr /= 12;
+ fg /= 12;
+ fb /= 12;
+
+ let tr = 0,
+ tg = 0,
+ tb = 0;
+ for (let s = 0; s < 12; s++) {
+ const f = s / 12;
+ const rr = sampleRgb48le(to, ux + dx * toS * 1.06 * f, uy + dy * toS * 1.06 * f, w, h)[0];
+ const gg = sampleRgb48le(to, ux + dx * toS * f, uy + dy * toS * f, w, h)[1];
+ const bb = sampleRgb48le(to, ux + dx * toS * 0.94 * f, uy + dy * toS * 0.94 * f, w, h)[2];
+ tr += rr;
+ tg += gg;
+ tb += bb;
+ }
+ tr /= 12;
+ tg /= 12;
+ tb /= 12;
+
+ out.writeUInt16LE(clamp16(mix16(Math.round(fr), Math.round(tr), p)), o);
+ out.writeUInt16LE(clamp16(mix16(Math.round(fg), Math.round(tg), p)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(Math.round(fb), Math.round(tb), p)), o + 4);
+ }
+};
+TRANSITIONS["cinematic-zoom"] = cinematicZoom;
+
+// ── gravitational-lens ────────────────────────────────────────────────────────
+
+/**
+ * Radial warp toward center simulating a gravitational lens effect. The
+ * outgoing frame is warped with chromatic separation, masked by a horizon
+ * that depends on distance from center. Mixed to the incoming frame using
+ * smoothstep(0.3, 0.9, progress). Port of the GLSL gravitational-lens shader.
+ */
+export const gravitationalLens: TransitionFn = (from, to, out, w, h, p) => {
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const uvx = ux - 0.5;
+ const uvy = uy - 0.5;
+ const dist = Math.sqrt(uvx * uvx + uvy * uvy);
+
+ const pull = p * 2;
+ const warpStr = (pull * 0.3) / (dist + 0.1);
+
+ const warpedX = Math.max(0, Math.min(1, ux - uvx * warpStr));
+ const warpedY = Math.max(0, Math.min(1, uy - uvy * warpStr));
+
+ const [, ag] = sampleRgb48le(from, warpedX, warpedY, w, h);
+
+ const horizon = smoothstep(0, 0.3, dist / (1 - p * 0.85 + 0.001));
+ const shift = (pull * 0.02) / (dist + 0.2);
+
+ const rSampX = Math.max(0, Math.min(1, ux - uvx * (warpStr + shift)));
+ const rSampY = Math.max(0, Math.min(1, uy - uvy * (warpStr + shift)));
+ const bSampX = Math.max(0, Math.min(1, ux - uvx * (warpStr - shift)));
+ const bSampY = Math.max(0, Math.min(1, uy - uvy * (warpStr - shift)));
+
+ const ar = sampleRgb48le(from, rSampX, rSampY, w, h)[0];
+ const ab = sampleRgb48le(from, bSampX, bSampY, w, h)[2];
+
+ const lensedR = Math.round(ar * horizon);
+ const lensedG = Math.round(ag * horizon);
+ const lensedB = Math.round(ab * horizon);
+
+ const [toR, toG, toB] = sampleRgb48le(to, ux, uy, w, h);
+ const blend = smoothstep(0.3, 0.9, p);
+
+ out.writeUInt16LE(clamp16(mix16(lensedR, toR, blend)), o);
+ out.writeUInt16LE(clamp16(mix16(lensedG, toG, blend)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(lensedB, toB, blend)), o + 4);
+ }
+};
+TRANSITIONS["gravitational-lens"] = gravitationalLens;
+
+// ── ripple-waves ──────────────────────────────────────────────────────────────
+
+/**
+ * Concentric wave distortion. Exponential wave functions create rings radiating
+ * outward from center. Both frames are distorted — the outgoing with progress-
+ * scaled amplitude, the incoming with (1-progress)-scaled amplitude. A warm
+ * accent tint highlights wave peaks. Port of the GLSL ripple-waves shader.
+ */
+export const rippleWaves: TransitionFn = (from, to, out, w, h, p) => {
+ // Accent bright color (16-bit)
+ const accentBright = [65535, 55000, 35000] as const;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const uvx = ux - 0.5;
+ const uvy = uy - 0.5;
+ const dist = Math.sqrt(uvx * uvx + uvy * uvy);
+
+ // Normalize direction from center, offset by small amount to avoid div-by-zero
+ const nux = uvx + 0.001;
+ const nuy = uvy + 0.001;
+ const nlen = Math.sqrt(nux * nux + nuy * nuy);
+ const dirx = nux / nlen;
+ const diry = nuy / nlen;
+
+ // From frame: waves moving outward (positive phase)
+ const fromAmp = p * 0.04;
+ const fw1 = Math.exp(Math.sin(dist * 25 - p * 12) - 1);
+ const fw2 = Math.exp(Math.sin(dist * 50 - p * 18) - 1) * 0.5;
+ const fromUx = Math.max(0, Math.min(1, ux + dirx * (fw1 + fw2) * fromAmp));
+ const fromUy = Math.max(0, Math.min(1, uy + diry * (fw1 + fw2) * fromAmp));
+
+ // To frame: waves moving inward (reversed phase)
+ const toAmp = (1 - p) * 0.04;
+ const tw1 = Math.exp(Math.sin(dist * 25 + p * 12) - 1);
+ const tw2 = Math.exp(Math.sin(dist * 50 + p * 18) - 1) * 0.5;
+ const toUx = Math.max(0, Math.min(1, ux - dirx * (tw1 + tw2) * toAmp));
+ const toUy = Math.max(0, Math.min(1, uy - diry * (tw1 + tw2) * toAmp));
+
+ const [fromR, fromG, fromB] = sampleRgb48le(from, fromUx, fromUy, w, h);
+ const [toR, toG, toB] = sampleRgb48le(to, toUx, toUy, w, h);
+
+ const peak = fw1 * p;
+ const tintR = accentBright[0] * peak * 0.1;
+ const tintG = accentBright[1] * peak * 0.1;
+ const tintB = accentBright[2] * peak * 0.1;
+
+ out.writeUInt16LE(clamp16(mix16(Math.round(fromR + tintR), toR, p)), o);
+ out.writeUInt16LE(clamp16(mix16(Math.round(fromG + tintG), toG, p)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(Math.round(fromB + tintB), toB, p)), o + 4);
+ }
+};
+TRANSITIONS["ripple-waves"] = rippleWaves;
+
+// ── swirl-vortex ──────────────────────────────────────────────────────────────
+
+/**
+ * Rotational UV warp. The outgoing frame is rotated clockwise and the incoming
+ * counter-clockwise. Rotation angle depends on distance from center and FBM
+ * warp noise. Port of the GLSL swirl-vortex shader.
+ */
+export const swirlVortex: TransitionFn = (from, to, out, w, h, p) => {
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const uvx = ux - 0.5;
+ const uvy = uy - 0.5;
+ const dist = Math.sqrt(uvx * uvx + uvy * uvy);
+
+ const warp = fbm(ux * 4, uy * 4) * 0.5;
+
+ const fromAng = p * (1 - dist) * 10 + warp * p * 3;
+ const fs = Math.sin(fromAng);
+ const fc = Math.cos(fromAng);
+ const fromUx = Math.max(0, Math.min(1, uvx * fc - uvy * fs + 0.5));
+ const fromUy = Math.max(0, Math.min(1, uvx * fs + uvy * fc + 0.5));
+
+ const toAng = -(1 - p) * (1 - dist) * 10 - warp * (1 - p) * 3;
+ const ts = Math.sin(toAng);
+ const tc = Math.cos(toAng);
+ const toUx = Math.max(0, Math.min(1, uvx * tc - uvy * ts + 0.5));
+ const toUy = Math.max(0, Math.min(1, uvx * ts + uvy * tc + 0.5));
+
+ const [fromR, fromG, fromB] = sampleRgb48le(from, fromUx, fromUy, w, h);
+ const [toR, toG, toB] = sampleRgb48le(to, toUx, toUy, w, h);
+
+ out.writeUInt16LE(clamp16(mix16(fromR, toR, p)), o);
+ out.writeUInt16LE(clamp16(mix16(fromG, toG, p)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(fromB, toB, p)), o + 4);
+ }
+};
+TRANSITIONS["swirl-vortex"] = swirlVortex;
+
+// ── thermal-distortion ────────────────────────────────────────────────────────
+
+/**
+ * Heat shimmer effect. Horizontal displacement based on a sin wave modulated by
+ * FBM noise, fading toward the top of the screen. Both frames are displaced
+ * independently, and a warm haze overlay fades as progress advances.
+ * Port of the GLSL thermal-distortion shader.
+ */
+export const thermalDistortion: TransitionFn = (from, to, out, w, h, p) => {
+ // Accent bright color (16-bit)
+ const accentBright = [65535, 55000, 35000] as const;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const heat = p * 1.5;
+ const yFade = smoothstep(1, 0, uy);
+
+ // From frame shimmer: fbm(uv*6) modulates sin wave
+ const shimmer = Math.sin(uy * 40 + fbm(ux * 6, uy * 6) * 8) * fbm(ux * 3 + 0, uy * 3 + p * 2);
+ const dispX = shimmer * heat * 0.03 * yFade;
+ const fromUx = Math.max(0, Math.min(1, ux + dispX));
+ const [fromR, fromG, fromB] = sampleRgb48le(from, fromUx, uy, w, h);
+
+ // To frame shimmer: different FBM seed (offset by 3)
+ const invShimmer =
+ Math.sin(uy * 40 + fbm(ux * 6 + 3, uy * 6 + 3) * 8) * fbm(ux * 3 + 3, uy * 3 + p * 2);
+ const dispX2 = invShimmer * (1 - p) * 0.03 * yFade;
+ const toUx = Math.max(0, Math.min(1, ux + dispX2));
+ const [toR, toG, toB] = sampleRgb48le(to, toUx, uy, w, h);
+
+ const haze = heat * yFade * 0.15 * (1 - p);
+
+ out.writeUInt16LE(clamp16(mix16(fromR, toR, p) + Math.round(accentBright[0] * haze)), o);
+ out.writeUInt16LE(clamp16(mix16(fromG, toG, p) + Math.round(accentBright[1] * haze)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(fromB, toB, p) + Math.round(accentBright[2] * haze)), o + 4);
+ }
+};
+TRANSITIONS["thermal-distortion"] = thermalDistortion;
+
+// ── domain-warp ───────────────────────────────────────────────────────────────
+
+/**
+ * FBM-driven UV warp with edge glow. Computes two layers of FBM (q and r) to
+ * derive a warp direction. Both frames are displaced in opposite directions.
+ * An edge-detection glow appears at the transition boundary.
+ * Port of the GLSL domain-warp shader. Note: mix(B, A, e) ordering — e=1 shows A (from).
+ */
+export const domainWarp: TransitionFn = (from, to, out, w, h, p) => {
+ // Accent colors (16-bit)
+ const accentDark = [25000, 8000, 2000] as const;
+ const accentBright = [65535, 55000, 35000] as const;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ // Two-layer domain warp: q, then r
+ const qx = fbm(ux * 3, uy * 3);
+ const qy = fbm(ux * 3 + 5.2, uy * 3 + 1.3);
+ const rx = fbm(ux * 3 + qx * 4 + 1.7, uy * 3 + qy * 4 + 9.2);
+ const ry = fbm(ux * 3 + qx * 4 + 8.3, uy * 3 + qy * 4 + 2.8);
+
+ const n = fbm(ux * 3 + rx * 2, uy * 3 + ry * 2);
+ const warpDirX = (qx - 0.5) * 0.4;
+ const warpDirY = (qy - 0.5) * 0.4;
+
+ const aUx = Math.max(0, Math.min(1, ux + warpDirX * p));
+ const aUy = Math.max(0, Math.min(1, uy + warpDirY * p));
+ const bUx = Math.max(0, Math.min(1, ux - warpDirX * (1 - p)));
+ const bUy = Math.max(0, Math.min(1, uy - warpDirY * (1 - p)));
+
+ const [aR, aG, aB] = sampleRgb48le(from, aUx, aUy, w, h);
+ const [bR, bG, bB] = sampleRgb48le(to, bUx, bUy, w, h);
+
+ // e=1 → show A (from), e=0 → show B (to): mix(B, A, e)
+ const e = smoothstep(p - 0.08, p + 0.08, n);
+
+ const ed = Math.abs(n - p);
+ // step(1, p) = p >= 1 ? 1 : 0 → suppress glow at p=1
+ const pStep = p >= 1 ? 1 : 0;
+ const em = smoothstep(0.1, 0, ed) * (1 - pStep);
+
+ // Edge color: mix accent_dark → accent_bright based on edge proximity
+ const ecBlend = smoothstep(0, 0.1, ed);
+ const ecR = accentDark[0] + (accentBright[0] - accentDark[0]) * (1 - ecBlend);
+ const ecG = accentDark[1] + (accentBright[1] - accentDark[1]) * (1 - ecBlend);
+ const ecB = accentDark[2] + (accentBright[2] - accentDark[2]) * (1 - ecBlend);
+
+ // mix(B, A, e) + edge glow
+ out.writeUInt16LE(clamp16(mix16(bR, aR, e) + Math.round(ecR * em * 2)), o);
+ out.writeUInt16LE(clamp16(mix16(bG, aG, e) + Math.round(ecG * em * 2)), o + 2);
+ out.writeUInt16LE(clamp16(mix16(bB, aB, e) + Math.round(ecB * em * 2)), o + 4);
+ }
+};
+TRANSITIONS["domain-warp"] = domainWarp;
+
+// ── ridged-burn ───────────────────────────────────────────────────────────────
+
+/**
+ * Ridged noise threshold transition with heat glow and sparks. Uses a custom
+ * ridged noise function (5 octaves of abs(vnoise*2 - 1)) to create a
+ * burning-paper effect. Accent colors glow at the burn boundary. Sparks
+ * appear from high-frequency noise.
+ * Port of the GLSL ridged-burn shader. Note: mix(B, A, e) ordering — e=1 shows A (from).
+ */
+
+/**
+ * Ridged noise: 5 octaves of abs(vnoise*2 - 1) with the same rotation and
+ * scaling as fbm. Returns values in [0, ~0.97].
+ */
+function ridged(px: number, py: number): number {
+ let value = 0;
+ let amplitude = 0.5;
+ let x = px;
+ let y = py;
+
+ for (let i = 0; i < 5; i++) {
+ value += amplitude * Math.abs(vnoise(x, y) * 2 - 1);
+
+ const nx = ROT_A * x - ROT_B * y;
+ const ny = ROT_B * x + ROT_A * y;
+ x = nx * 2.02;
+ y = ny * 2.02;
+
+ amplitude *= 0.5;
+ }
+
+ return value;
+}
+
+export const ridgedBurn: TransitionFn = (from, to, out, w, h, p) => {
+ // Accent colors (16-bit)
+ const accent = [50000, 25000, 5000] as const;
+ const accentDark = [25000, 8000, 2000] as const;
+ const accentBright = [65535, 55000, 35000] as const;
+
+ for (let i = 0; i < w * h; i++) {
+ const ux = (i % w) / w;
+ const uy = Math.floor(i / w) / h;
+ const o = i * 6;
+
+ const [aR, aG, aB] = sampleRgb48le(from, ux, uy, w, h);
+ const [bR, bG, bB] = sampleRgb48le(to, ux, uy, w, h);
+
+ const n = ridged(ux * 4, uy * 4);
+
+ // e=1 → show A (from), e=0 → show B (to): mix(B, A, e)
+ const e = smoothstep(p - 0.04, p + 0.04, n);
+
+ const heat = smoothstep(0.12, 0, Math.abs(n - p));
+ // step(1, p) = p >= 1 ? 1 : 0 → suppress glow at p=1
+ const pStep = p >= 1 ? 1 : 0;
+ const heatMasked = heat * (1 - pStep);
+
+ // Burn color gradient: dark → accent → accent_bright → white
+ let burnR = accentDark[0] + (accent[0] - accentDark[0]) * smoothstep(0, 0.25, heatMasked);
+ let burnG = accentDark[1] + (accent[1] - accentDark[1]) * smoothstep(0, 0.25, heatMasked);
+ let burnB = accentDark[2] + (accent[2] - accentDark[2]) * smoothstep(0, 0.25, heatMasked);
+ const blend2 = smoothstep(0.25, 0.5, heatMasked);
+ burnR = burnR + (accentBright[0] - burnR) * blend2;
+ burnG = burnG + (accentBright[1] - burnG) * blend2;
+ burnB = burnB + (accentBright[2] - burnB) * blend2;
+ const blend3 = smoothstep(0.5, 1, heatMasked);
+ burnR = burnR + (65535 - burnR) * blend3;
+ burnG = burnG + (65535 - burnG) * blend3;
+ burnB = burnB + (65535 - burnB) * blend3;
+
+ // Sparks: high-frequency noise above threshold
+ const sparks = (vnoise(ux * 80, uy * 80) >= 0.92 ? 1 : 0) * heatMasked * 3;
+
+ out.writeUInt16LE(
+ clamp16(
+ mix16(bR, aR, e) +
+ Math.round(burnR * heatMasked * 3.5) +
+ Math.round(accentBright[0] * sparks),
+ ),
+ o,
+ );
+ out.writeUInt16LE(
+ clamp16(
+ mix16(bG, aG, e) +
+ Math.round(burnG * heatMasked * 3.5) +
+ Math.round(accentBright[1] * sparks),
+ ),
+ o + 2,
+ );
+ out.writeUInt16LE(
+ clamp16(
+ mix16(bB, aB, e) +
+ Math.round(burnB * heatMasked * 3.5) +
+ Math.round(accentBright[2] * sparks),
+ ),
+ o + 4,
+ );
+ }
+};
+TRANSITIONS["ridged-burn"] = ridgedBurn;
diff --git a/packages/engine/src/utils/uint16-alignment-audit.test.ts b/packages/engine/src/utils/uint16-alignment-audit.test.ts
new file mode 100644
index 0000000000..e43ec89634
--- /dev/null
+++ b/packages/engine/src/utils/uint16-alignment-audit.test.ts
@@ -0,0 +1,125 @@
+/**
+ * Audit test: Uint16Array vs Buffer.read/writeUInt16LE alignment.
+ *
+ * Captures the migration hazard documented in the HDR follow-up plan:
+ * "Uint16Array over readUInt16LE / writeUInt16LE — ~105 touch points in the
+ * hot path with an alignment-correctness concern (odd byteOffset on sliced
+ * Buffers throws)."
+ *
+ * The hot path in `alphaBlit.ts` and `shaderTransitions.ts` reads/writes 16-bit
+ * channels via `Buffer.readUInt16LE` / `Buffer.writeUInt16LE`. Those methods
+ * accept arbitrary byte offsets — odd offsets are fine. A future perf PR may
+ * migrate to `Uint16Array` views for ~2× throughput, but `Uint16Array` requires
+ * 2-byte alignment of the underlying ArrayBuffer offset. If the source `Buffer`
+ * was sliced from a parent at an odd byte offset, constructing a `Uint16Array`
+ * view directly will throw `RangeError`.
+ *
+ * These tests pin down the contract so the migration PR can:
+ * 1. Verify the migration is safe (current sub-buffers always start at even
+ * byte offsets) — see `rgb48le row stride` test.
+ * 2. Provide a reference safe-wrap pattern when alignment is not guaranteed.
+ */
+import { describe, expect, it } from "vitest";
+
+describe("Uint16 alignment audit", () => {
+ describe("Buffer.read/writeUInt16LE — current API", () => {
+ it("accepts odd byte offsets without throwing", () => {
+ const buf = Buffer.alloc(8);
+ buf.writeUInt16LE(0xabcd, 1);
+ expect(buf.readUInt16LE(1)).toBe(0xabcd);
+ buf.writeUInt16LE(0x1234, 3);
+ expect(buf.readUInt16LE(3)).toBe(0x1234);
+ });
+
+ it("preserves values across non-aligned slice round-trips", () => {
+ const buf = Buffer.alloc(10);
+ buf.writeUInt16LE(0xdead, 1);
+ buf.writeUInt16LE(0xbeef, 5);
+ const sub = buf.subarray(1);
+ expect(sub.readUInt16LE(0)).toBe(0xdead);
+ expect(sub.readUInt16LE(4)).toBe(0xbeef);
+ });
+ });
+
+ describe("Uint16Array — migration hazard", () => {
+ it("throws RangeError when byteOffset is odd", () => {
+ const ab = new ArrayBuffer(8);
+ expect(() => new Uint16Array(ab, 1, 2)).toThrow(RangeError);
+ expect(() => new Uint16Array(ab, 3, 1)).toThrow(RangeError);
+ });
+
+ it("succeeds when byteOffset is even", () => {
+ const ab = new ArrayBuffer(8);
+ expect(() => new Uint16Array(ab, 0, 4)).not.toThrow();
+ expect(() => new Uint16Array(ab, 2, 3)).not.toThrow();
+ });
+
+ it("a Buffer sliced at an odd offset cannot back a Uint16Array view directly", () => {
+ const parent = Buffer.alloc(8);
+ const odd = parent.subarray(1);
+ expect(odd.byteOffset % 2).toBe(1);
+ expect(
+ () => new Uint16Array(odd.buffer, odd.byteOffset, Math.floor(odd.byteLength / 2)),
+ ).toThrow(RangeError);
+ });
+
+ it("safe-wrap pattern: copy to a fresh aligned Buffer when offset is odd", () => {
+ const parent = Buffer.alloc(8);
+ parent.writeUInt16LE(0xfeed, 1);
+ const odd = parent.subarray(1, 3);
+
+ // Pattern the migration PR should use when alignment is not guaranteed:
+ // realign by copying into a freshly allocated Buffer (always page-aligned).
+ const aligned = odd.byteOffset % 2 === 0 ? odd : Buffer.from(odd);
+ expect(aligned.byteOffset % 2).toBe(0);
+ const view = new Uint16Array(
+ aligned.buffer,
+ aligned.byteOffset,
+ Math.floor(aligned.byteLength / 2),
+ );
+ expect(view[0]).toBe(0xfeed);
+ });
+ });
+
+ describe("HDR canvas/row alignment invariants", () => {
+ it("rgb48le canvas row strides are always even-byte multiples", () => {
+ // A row of an rgb48le canvas is `width * 6` bytes (3 channels × 2 bytes).
+ // For any width, the row stride is even, so per-row subarrays inherit
+ // even byte offsets when sliced from a Buffer whose byteOffset is also
+ // even (true for `Buffer.alloc(N)`, which is fresh-allocator-aligned).
+ for (const width of [1, 7, 33, 256, 1920]) {
+ const stride = width * 6;
+ expect(stride % 2).toBe(0);
+ }
+ });
+
+ it("Buffer.alloc canvases produce subarrays with even byte offsets", () => {
+ // This is the invariant the alphaBlit hot path relies on: as long as the
+ // working canvas is built with `Buffer.alloc(width * height * 6)`, each
+ // row subarray (`canvas.subarray(y * stride, (y + 1) * stride)`) starts
+ // at an even byte offset, so a future Uint16Array migration is safe
+ // without any realignment copy.
+ const width = 17; // odd width; stride = 102 (still even)
+ const height = 4;
+ const canvas = Buffer.alloc(width * height * 6);
+ const stride = width * 6;
+ for (let y = 0; y < height; y++) {
+ const row = canvas.subarray(y * stride, (y + 1) * stride);
+ expect(row.byteOffset % 2).toBe(0);
+ }
+ });
+
+ it("a 3-byte rgb24 stride would NOT be alignment-safe (counter-example)", () => {
+ // Documents why the rgb48le format is migration-friendly: an rgba8 or
+ // rgb24 canvas with odd width produces sub-buffers at odd byte offsets.
+ // If a future PR wants to use Uint16Array views, it must keep the data
+ // in an even-stride format (rgb48le ✓) or pay for a realignment copy.
+ const width = 3;
+ const height = 2;
+ const rgb24 = Buffer.alloc(width * height * 3); // stride = 9, odd!
+ const stride = width * 3;
+ const row1 = rgb24.subarray(stride, stride * 2);
+ expect(row1.byteOffset % 2).toBe(1);
+ });
+ });
+});
diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts
index 4f6c169490..c8db0e86be 100644
--- a/packages/producer/src/services/renderOrchestrator.ts
+++ b/packages/producer/src/services/renderOrchestrator.ts
@@ -32,6 +32,7 @@ import {
type VideoElement,
FrameLookupTable,
type HdrTransfer,
+ detectTransfer,
createCaptureSession,
initializeSession,
closeCaptureSession,
@@ -58,18 +59,26 @@ import {
type StreamingEncoder,
analyzeCompositionHdr,
isHdrColorSpace,
+ runFfmpeg,
extractVideoMetadata,
initTransparentBackground,
captureAlphaPng,
+ applyDomLayerMask,
+ removeDomLayerMask,
decodePng,
decodePngToRgb48le,
blitRgba8OverRgb48le,
blitRgb48leRegion,
- hideVideoElements,
- showVideoElements,
queryElementStacking,
groupIntoLayers,
blitRgb48leAffine,
+ parseTransformMatrix,
+ TRANSITIONS,
+ crossfade,
+ convertTransfer,
+ type TransitionFn,
+ type ElementStackingInfo,
+ type HfTransitionMeta,
} from "@hyperframes/engine";
import { join, dirname, resolve } from "path";
import { randomUUID } from "crypto";
@@ -136,6 +145,19 @@ function getMaxFrameIndex(frameDir: string): number {
return max;
}
+/**
+ * Metadata for a shader transition between two scenes, extracted from
+ * `window.__hf.transitions`. Re-exported from the engine so the producer
+ * shares the contract with composition runtime code.
+ */
+type HdrTransitionMeta = HfTransitionMeta;
+
+/** Pre-computed frame range for an active transition. */
+interface TransitionRange extends HdrTransitionMeta {
+ startFrame: number;
+ endFrame: number;
+}
+
export type RenderStatus =
| "queued"
| "preprocessing"
@@ -164,6 +186,8 @@ export interface RenderConfig {
crf?: number;
/** Target video bitrate (e.g. "10M"). Mutually exclusive with `crf`. */
videoBitrate?: string;
+ /** Enable HDR color space probing on video/image sources. */
+ hdr?: boolean;
}
export interface RenderPerfSummary {
@@ -360,6 +384,99 @@ export function applyRenderModeHints(
});
}
+/**
+ * Blit a single HDR video layer onto an rgb48le canvas.
+ *
+ * Shared between the normal-frame compositing path (compositeToBuffer)
+ * and the transition dual-scene compositing loop to avoid duplicating
+ * the frame lookup, fallback, decode, transform, and blit logic.
+ */
+function blitHdrVideoLayer(
+ canvas: Buffer,
+ el: ElementStackingInfo,
+ time: number,
+ fps: number,
+ hdrFrameDirs: Map<string, string>,
+ hdrStartTimes: Map<string, number>,
+ width: number,
+ height: number,
+ log?: ProducerLogger,
+ sourceTransfer?: HdrTransfer,
+ targetTransfer?: HdrTransfer,
+): void {
+ const frameDir = hdrFrameDirs.get(el.id);
+ const startTime = hdrStartTimes.get(el.id);
+ if (!frameDir || startTime === undefined) {
+ return;
+ }
+
+ // Frame index within the video (1-based for FFmpeg image2 output).
+ // Clamp against the highest extracted frame in the directory so that when
+ // the composition outlives the source clip we freeze on the last frame
+ // (matching Chrome's <video> behavior) without issuing an O(N) iterative
+ // existsSync sweep per requested time.
+ const videoFrameIndex = Math.round((time - startTime) * fps) + 1;
+ if (videoFrameIndex < 1) return;
+ const maxIndex = getMaxFrameIndex(frameDir);
+ const effectiveIndex = maxIndex > 0 ? Math.min(videoFrameIndex, maxIndex) : videoFrameIndex;
+ const framePath = join(frameDir, `frame_${String(effectiveIndex).padStart(4, "0")}.png`);
+
+ if (!existsSync(framePath)) {
+ return;
+ }
+
+ try {
+ const { data: hdrRgb, width: srcW, height: srcH } = decodePngToRgb48le(readFileSync(framePath));
+
+ // Convert between HDR transfer functions if source doesn't match output
+ if (sourceTransfer && targetTransfer && sourceTransfer !== targetTransfer) {
+ convertTransfer(hdrRgb, sourceTransfer, targetTransfer);
+ }
+
+ const viewportMatrix = parseTransformMatrix(el.transform);
+
+ // Pass border-radius for rounded-corner masking (only when non-zero)
+ const br = el.borderRadius;
+ const hasBorderRadius = br[0] > 0 || br[1] > 0 || br[2] > 0 || br[3] > 0;
+ const borderRadiusParam = hasBorderRadius ? br : undefined;
+
+ if (viewportMatrix) {
+ // Use the full viewport transform (handles scale, rotation, translate)
+ blitRgb48leAffine(
+ canvas,
+ hdrRgb,
+ viewportMatrix,
+ srcW,
+ srcH,
+ width,
+ height,
+ el.opacity < 0.999 ? el.opacity : undefined,
+ borderRadiusParam,
+ );
+ } else {
+ // No transform — identity position, use fast region blit
+ blitRgb48leRegion(
+ canvas,
+ hdrRgb,
+ el.x,
+ el.y,
+ srcW,
+ srcH,
+ width,
+ height,
+ el.opacity < 0.999 ? el.opacity : undefined,
+ borderRadiusParam,
+ );
+ }
+ } catch (err) {
+ if (log) {
+ log.debug(`HDR blit failed for ${el.id}`, {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+}
+
export function createRenderJob(config: RenderConfig): RenderJob {
return {
id: randomUUID(),
@@ -700,6 +817,7 @@ export async function executeRenderJob(
job.duration = composition.duration;
job.totalFrames = Math.ceil(composition.duration * job.config.fps);
+ const totalFrames = job.totalFrames;
if (job.duration <= 0) {
// Gather diagnostics to help users understand why the render would produce a black video.
@@ -777,9 +895,11 @@ export async function executeRenderJob(
// Probe ORIGINAL color spaces before extraction (which may convert SDR→HDR).
// This is needed to identify which videos are natively HDR vs converted-SDR
- // for the two-pass compositing path.
+ // for the two-pass compositing path. Gated by --hdr flag to avoid ffprobe
+ // overhead on SDR-only compositions.
const nativeHdrVideoIds = new Set<string>();
- if (composition.videos.length > 0) {
+ const videoTransfers = new Map<string, HdrTransfer>();
+ if (job.config.hdr && composition.videos.length > 0) {
await Promise.all(
composition.videos.map(async (v) => {
let videoPath = v.src;
@@ -793,6 +913,7 @@ export async function executeRenderJob(
const meta = await extractVideoMetadata(videoPath);
if (isHdrColorSpace(meta.colorSpace)) {
nativeHdrVideoIds.add(v.id);
+ videoTransfers.set(v.id, detectTransfer(meta.colorSpace));
}
}),
);
@@ -839,17 +960,24 @@ export async function executeRenderJob(
}
// ── HDR auto-detection ──────────────────────────────────────────────
- // If any extracted video source has an HDR color space, the output
- // automatically uses H.265 10-bit with the dominant transfer (PQ if any
- // PQ source is present, otherwise HLG). No flag needed.
+ // When --hdr is set, analyze extracted video metadata AND probed images
+ // for HDR color spaces. If found, output uses H.265 10-bit with the
+ // dominant transfer (PQ if any PQ source is present, otherwise HLG).
let effectiveHdr: { transfer: HdrTransfer } | undefined;
- if (frameLookup) {
+ if (job.config.hdr && frameLookup) {
const colorSpaces = (extractionResult?.extracted ?? []).map((ext) => ext.metadata.colorSpace);
const info = analyzeCompositionHdr(colorSpaces);
if (info.hasHdr && info.dominantTransfer) {
effectiveHdr = { transfer: info.dominantTransfer };
}
}
+ // Also detect HDR from probed images (no extraction result for images)
+ if (job.config.hdr && !effectiveHdr && nativeHdrVideoIds.size > 0) {
+ const firstTransfer = videoTransfers.values().next().value;
+ if (firstTransfer) {
+ effectiveHdr = { transfer: firstTransfer };
+ }
+ }
if (effectiveHdr && outputFormat !== "mp4") {
log.info(`[Render] HDR source detected but format is ${outputFormat} — using SDR`);
effectiveHdr = undefined;
@@ -912,7 +1040,7 @@ export async function executeRenderJob(
quality: needsAlpha ? undefined : job.config.quality === "draft" ? 80 : 95,
};
- const workerCount = calculateOptimalWorkers(job.totalFrames!, job.config.workers, cfg);
+ const workerCount = calculateOptimalWorkers(totalFrames, job.config.workers, cfg);
const FORMAT_EXT: Record<string, string> = { mp4: ".mp4", webm: ".webm", mov: ".mov" };
const videoExt = FORMAT_EXT[outputFormat] ?? ".mp4";
@@ -920,8 +1048,8 @@ export async function executeRenderJob(
// Only use the HDR encoder preset when there's HDR video to pass through.
// For SDR-only compositions, --hdr is a no-op — H.265 10-bit causes browser
// color management issues (orange shift) with no quality benefit.
- const hasHdrVideo = effectiveHdr && composition.videos.length > 0 && frameLookup;
- const encoderHdr = hasHdrVideo ? effectiveHdr : undefined;
+ const hasHdrContent = effectiveHdr && nativeHdrVideoIds.size > 0;
+ const encoderHdr = hasHdrContent ? effectiveHdr : undefined;
const preset = getEncoderPreset(job.config.quality, outputFormat, encoderHdr);
job.framesRendered = 0;
@@ -931,7 +1059,7 @@ export async function executeRenderJob(
// composite bottom-to-top in Node.js memory. HDR layers use native
// pre-extracted HLG pixels; DOM layers use Chrome alpha screenshots
// with sRGB→HLG conversion. Video position/opacity applied via queried bounds.
- if (hasHdrVideo) {
+ if (hasHdrContent) {
log.info("[Render] HDR layered composite: z-ordered DOM + native HLG video layers");
// Use NATIVE HDR IDs (probed before SDR→HDR conversion) so only originally-HDR
@@ -955,10 +1083,12 @@ export async function executeRenderJob(
// Launch headless Chrome for DOM capture.
// Pass the video frame injector so SDR videos are rendered correctly in Chrome.
- // HDR videos get injected too but are hidden via hideVideoElements before the
- // DOM screenshot — only the native FFmpeg-extracted HLG frames are used for HDR.
+ // HDR videos get injected too but are masked out via applyDomLayerMask
+ // before each DOM screenshot — only the native FFmpeg-extracted HLG
+ // frames are used for HDR pixels.
+ if (!fileServer) throw new Error("fileServer must be initialized before HDR compositing");
const domSession = await createCaptureSession(
- fileServer!.url,
+ fileServer.url,
framesDir,
captureOptions,
createVideoFrameInjector(frameLookup),
@@ -972,6 +1102,44 @@ export async function executeRenderJob(
// captureAlphaPng() per frame skips the per-frame CDP set/reset overhead.
await initTransparentBackground(domSession.page);
+ // ── Scene detection for shader transitions ──────────────────────────
+ // Query the browser for transition metadata written by @hyperframes/shader-transitions
+ // (window.__hf.transitions) and discover which elements belong to each scene.
+ const transitionMeta: HdrTransitionMeta[] = await domSession.page.evaluate(() => {
+ return window.__hf?.transitions ?? [];
+ });
+
+ // Contract: compositions using window.__hf.transitions must wrap each
+ // scene's elements in a <div class="scene" id="sceneName"> where the id
+ // matches the fromScene/toScene values declared in the transition metadata.
+ const sceneElements: Record<string, string[]> = await domSession.page.evaluate(() => {
+ const scenes = document.querySelectorAll(".scene");
+ const map: Record<string, string[]> = {};
+ for (const scene of scenes) {
+ const els = scene.querySelectorAll("[data-start]");
+ map[scene.id] = Array.from(els).map((e) => e.id);
+ }
+ return map;
+ });
+
+ const transitionRanges: TransitionRange[] = transitionMeta.map((t) => ({
+ ...t,
+ startFrame: Math.floor(t.time * job.config.fps),
+ endFrame: Math.ceil((t.time + t.duration) * job.config.fps),
+ }));
+
+ if (transitionRanges.length > 0) {
+ log.info("[Render] Detected shader transitions for HDR compositing", {
+ count: transitionRanges.length,
+ transitions: transitionRanges.map((t) => ({
+ shader: t.shader,
+ from: t.fromScene,
+ to: t.toScene,
+ frames: `${t.startFrame}-${t.endFrame}`,
+ })),
+ });
+ }
+
// Spawn HDR streaming encoder accepting raw rgb48le composited frames
const hdrEncoder = await spawnStreamingEncoder(
videoOnlyPath,
@@ -991,23 +1159,41 @@ export async function executeRenderJob(
);
assertNotAborted();
- const { execSync } = await import("child_process");
-
- // ── Query initial element bounds for HDR extraction dimensions ──────
+ // ── Query element bounds for HDR extraction dimensions ────────────
// Extract at each HDR video's display dimensions (not composition dimensions)
- // so the source stride matches the blit dimensions. Without this, a 1200x900
- // video element would have stride mismatch against a 1920x1080 extraction.
- await domSession.page.evaluate((t: number) => {
- if (window.__hf && typeof window.__hf.seek === "function") window.__hf.seek(t);
- }, 0);
- if (domSession.onBeforeCapture) {
- await domSession.onBeforeCapture(domSession.page, 0);
- }
- const initialStacking = await queryElementStacking(domSession.page, nativeHdrVideoIds);
+ // so the source stride matches the blit dimensions. Elements that aren't
+ // visible at t=0 (e.g., data-start > 0) need to be queried at their own
+ // start time so their layout dimensions are available.
const hdrExtractionDims = new Map<string, { width: number; height: number }>();
- for (const el of initialStacking) {
- if (el.isHdr && el.width > 0 && el.height > 0) {
- hdrExtractionDims.set(el.id, { width: el.width, height: el.height });
+ const hdrVideoStartTimes = new Map<string, number>();
+ for (const v of composition.videos) {
+ if (hdrVideoIds.includes(v.id)) {
+ hdrVideoStartTimes.set(v.id, v.start);
+ }
+ }
+
+ // Collect unique start times to minimize seek operations
+ const uniqueStartTimes = [...new Set(hdrVideoStartTimes.values())].sort((a, b) => a - b);
+ for (const seekTime of uniqueStartTimes) {
+ await domSession.page.evaluate((t: number) => {
+ if (window.__hf && typeof window.__hf.seek === "function") window.__hf.seek(t);
+ }, seekTime);
+ if (domSession.onBeforeCapture) {
+ await domSession.onBeforeCapture(domSession.page, seekTime);
+ }
+ const stacking = await queryElementStacking(domSession.page, nativeHdrVideoIds);
+ for (const el of stacking) {
+ // Use layout dimensions (offsetWidth/offsetHeight) for extraction — these
+ // are unaffected by CSS transforms (GSAP scale/rotation). getBoundingClientRect
+ // returns the transformed bounding box which can be wrong for extraction.
+ if (
+ el.isHdr &&
+ el.layoutWidth > 0 &&
+ el.layoutHeight > 0 &&
+ !hdrExtractionDims.has(el.id)
+ ) {
+ hdrExtractionDims.set(el.id, { width: el.layoutWidth, height: el.layoutHeight });
+ }
}
}
@@ -1020,22 +1206,35 @@ export async function executeRenderJob(
mkdirSync(frameDir, { recursive: true });
const duration = video.end - video.start;
const dims = hdrExtractionDims.get(videoId) ?? { width, height };
- try {
- execSync(
- `ffmpeg -ss ${video.mediaStart} -i "${srcPath}" -t ${duration} -r ${job.config.fps} ` +
- `-vf "scale=${dims.width}:${dims.height}:force_original_aspect_ratio=increase,crop=${dims.width}:${dims.height}" ` +
- `-pix_fmt rgb48le -c:v png "${join(frameDir, "frame_%04d.png")}"`,
- { maxBuffer: 1024 * 1024, stdio: ["pipe", "pipe", "pipe"] },
- );
- } catch (err) {
+ const ffmpegArgs = [
+ "-ss",
+ String(video.mediaStart),
+ "-i",
+ srcPath,
+ "-t",
+ String(duration),
+ "-r",
+ String(job.config.fps),
+ "-vf",
+ `scale=${dims.width}:${dims.height}:force_original_aspect_ratio=increase,crop=${dims.width}:${dims.height}`,
+ "-pix_fmt",
+ "rgb48le",
+ "-c:v",
+ "png",
+ "-y",
+ join(frameDir, "frame_%04d.png"),
+ ];
+ const result = await runFfmpeg(ffmpegArgs, { signal: abortSignal });
+ if (!result.success) {
log.warn("HDR frame pre-extraction failed; loop will fill with black", {
videoId,
srcPath,
- error: err instanceof Error ? err.message : String(err),
+ stderr: result.stderr.slice(-400),
});
}
hdrFrameDirs.set(videoId, frameDir);
}
+
assertNotAborted();
try {
@@ -1043,7 +1242,234 @@ export async function executeRenderJob(
// We call it manually since the HDR loop doesn't use captureFrame().
const beforeCaptureHook = domSession.onBeforeCapture;
- for (let i = 0; i < job.totalFrames!; i++) {
+ // Track which HDR video frame directories have been cleaned up.
+ // Once a video's last frame has been used (time > video.end), its
+ // extraction directory is deleted to free disk space. This prevents
+ // disk exhaustion on compositions with many HDR videos.
+ const cleanedUpVideos = new Set<string>();
+ // Build a map of video end times for quick lookup
+ const hdrVideoEndTimes = new Map<string, number>();
+ for (const v of composition.videos) {
+ if (hdrFrameDirs.has(v.id)) {
+ hdrVideoEndTimes.set(v.id, v.end);
+ }
+ }
+
+ // ── compositeToBuffer: layer compositing helper ────────────────────
+ // Extracted so the transition path can composite each scene independently.
+ // Closes over domSession, hdrFrameDirs, composition, nativeHdrVideoIds, etc.
+ //
+ // @param canvas - Pre-allocated rgb48le buffer (width * height * 6 bytes)
+ // @param time - Seek time in seconds
+ // @param fullStacking - Complete stacking info for ALL elements (used for hideIds)
+ // @param elementFilter - When set, only composite elements whose IDs are in this set.
+ // When undefined, all elements are included (non-transition frame).
+ // @param debugFrameIndex - Frame index used to label diagnostic dumps. -1 disables
+ // per-layer dumps even when KEEP_TEMP=1 (for warmup calls).
+ const debugDumpEnabled = process.env.KEEP_TEMP === "1";
+ const debugDumpDir = debugDumpEnabled ? join(framesDir, "debug-composite") : null;
+ if (debugDumpDir && !existsSync(debugDumpDir)) {
+ mkdirSync(debugDumpDir, { recursive: true });
+ }
+ function countNonZeroAlpha(rgba: Uint8Array): number {
+ let n = 0;
+ for (let p = 3; p < rgba.length; p += 4) {
+ if (rgba[p] !== 0) n++;
+ }
+ return n;
+ }
+ function countNonZeroRgb48(buf: Uint8Array): number {
+ let n = 0;
+ for (let p = 0; p < buf.length; p += 6) {
+ if (buf[p] !== 0 || buf[p + 1] !== 0 || buf[p + 2] !== 0) n++;
+ }
+ return n;
+ }
+ async function compositeToBuffer(
+ canvas: Buffer,
+ time: number,
+ fullStacking: ElementStackingInfo[],
+ elementFilter?: Set<string>,
+ debugFrameIndex: number = -1,
+ ): Promise<void> {
+ // Filter stacking info when rendering a single scene
+ const filteredStacking = elementFilter
+ ? fullStacking.filter((e) => elementFilter.has(e.id))
+ : fullStacking;
+
+ // Group filtered elements into z-ordered layers
+ const layers = groupIntoLayers(filteredStacking);
+
+ const shouldLog = debugDumpEnabled && debugFrameIndex >= 0;
+ if (shouldLog) {
+ log.info("[diag] compositeToBuffer plan", {
+ frame: debugFrameIndex,
+ time: time.toFixed(3),
+ filterSize: elementFilter?.size,
+ fullStackingCount: fullStacking.length,
+ filteredCount: filteredStacking.length,
+ layerCount: layers.length,
+ layers: layers.map((l) =>
+ l.type === "hdr"
+ ? {
+ type: "hdr",
+ id: l.element.id,
+ z: l.element.zIndex,
+ visible: l.element.visible,
+ opacity: l.element.opacity,
+ bounds: `${Math.round(l.element.x)},${Math.round(l.element.y)} ${Math.round(l.element.width)}x${Math.round(l.element.height)}`,
+ }
+ : { type: "dom", ids: l.elementIds },
+ ),
+ });
+ }
+
+ // Composite layers bottom-to-top
+ for (let layerIdx = 0; layerIdx < layers.length; layerIdx++) {
+ const layer = layers[layerIdx]!;
+ if (layer.type === "hdr") {
+ const before = shouldLog ? countNonZeroRgb48(canvas) : 0;
+ blitHdrVideoLayer(
+ canvas,
+ layer.element,
+ time,
+ job.config.fps,
+ hdrFrameDirs,
+ hdrVideoStartTimes,
+ width,
+ height,
+ log,
+ videoTransfers.get(layer.element.id),
+ effectiveHdr?.transfer,
+ );
+ if (shouldLog) {
+ const after = countNonZeroRgb48(canvas);
+ const frameDir = hdrFrameDirs.get(layer.element.id);
+ const startTime = hdrVideoStartTimes.get(layer.element.id) ?? 0;
+ const localTime = time - startTime;
+ const frameNum = Math.floor(localTime * job.config.fps) + 1;
+ const expectedFrame = frameDir
+ ? join(frameDir, `frame_${String(frameNum).padStart(4, "0")}.png`)
+ : null;
+ log.info("[diag] hdr layer blit", {
+ frame: debugFrameIndex,
+ layerIdx,
+ id: layer.element.id,
+ pixelsAdded: after - before,
+ totalNonZero: after,
+ startTime,
+ localTime: localTime.toFixed(3),
+ hdrFrameNum: frameNum,
+ expectedFrame,
+ expectedFrameExists: expectedFrame ? existsSync(expectedFrame) : false,
+ });
+ }
+ } else {
+ // DOM layer: capture only elements in this layer.
+ //
+ // Each layer gets a fresh seek + inject cycle to guarantee correct
+ // visibility state — avoids fragile interactions between the frame
+ // injector, applyDomLayerMask, removeDomLayerMask, and GSAP re-seek.
+ //
+ // The mask:
+ // - mass-hides every body descendant via stylesheet
+ // - re-shows the layer's elements (and their descendants and
+ // their injected `__render_frame_*` siblings) so deep-nested
+ // content stays visible even though intermediate ancestors
+ // are hidden
+ // - inline-hides every other data-start element so they don't
+ // paint when they happen to be descendants of a layer element
+ // (most importantly: HDR videos and other-layer SDR videos
+ // that live inside `#root` when capturing the root DOM layer)
+ //
+ // Without the mask, every DOM screenshot captures the full page
+ // (root background, sibling scenes' static content, the painted
+ // border/box-shadow of cards, etc.) and the resulting opaque
+ // pixels overwrite previously composited HDR content beneath.
+ const allElementIds = fullStacking.map((e) => e.id);
+ const layerIds = new Set(layer.elementIds);
+ const hideIds = allElementIds.filter((id) => !layerIds.has(id));
+
+ // 1. Seek GSAP to restore all animated properties from clean state
+ await domSession.page.evaluate((t: number) => {
+ if (window.__hf && typeof window.__hf.seek === "function") window.__hf.seek(t);
+ }, time);
+
+ // 2. Run frame injector to set correct SDR video visibility
+ if (beforeCaptureHook) {
+ await beforeCaptureHook(domSession.page, time);
+ }
+
+ // 3. Install the mask (mass-hide stylesheet + inline-hide non-layer ids)
+ await applyDomLayerMask(domSession.page, layer.elementIds, hideIds);
+
+ // 4. Screenshot
+ const domPng = await captureAlphaPng(domSession.page, width, height);
+
+ // 5. Tear down the mask
+ await removeDomLayerMask(domSession.page, hideIds);
+
+ try {
+ const { data: domRgba } = decodePng(domPng);
+ // Invariant: this branch is only reached when HDR output is active.
+ if (!effectiveHdr) {
+ throw new Error(
+ "Invariant violation: effectiveHdr is undefined inside HDR layer branch",
+ );
+ }
+ const before = shouldLog ? countNonZeroRgb48(canvas) : 0;
+ const alphaPixels = shouldLog ? countNonZeroAlpha(domRgba) : 0;
+ blitRgba8OverRgb48le(domRgba, canvas, width, height, effectiveHdr.transfer);
+ if (shouldLog && debugDumpDir) {
+ const after = countNonZeroRgb48(canvas);
+ const dumpName = `frame_${String(debugFrameIndex).padStart(4, "0")}_layer_${String(layerIdx).padStart(2, "0")}_dom.png`;
+ const dumpPath = join(debugDumpDir, dumpName);
+ writeFileSync(dumpPath, domPng);
+ log.info("[diag] dom layer blit", {
+ frame: debugFrameIndex,
+ layerIdx,
+ layerIds: layer.elementIds,
+ hideCount: hideIds.length,
+ pngBytes: domPng.length,
+ alphaPixels,
+ pixelsAdded: after - before,
+ totalNonZero: after,
+ dumpPath,
+ });
+ }
+ } catch (err) {
+ log.warn("DOM layer decode/blit failed; skipping overlay", {
+ layerIds: layer.elementIds,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ }
+
+ if (shouldLog && debugDumpDir) {
+ const finalNonZero = countNonZeroRgb48(canvas);
+ log.info("[diag] compositeToBuffer end", {
+ frame: debugFrameIndex,
+ finalNonZeroPixels: finalNonZero,
+ totalPixels: width * height,
+ coverage: ((finalNonZero / (width * height)) * 100).toFixed(1) + "%",
+ });
+ }
+ }
+
+ // ── Pre-allocate transition buffers ─────────────────────────────────
+ // Each buffer is width * height * 6 bytes (~37 MB at 1080p). Reused
+ // across frames to avoid per-frame allocation in the hot loop.
+ const bufSize = width * height * 6;
+ const hasTransitions = transitionRanges.length > 0;
+ const transBufferA = hasTransitions ? Buffer.alloc(bufSize) : null;
+ const transBufferB = hasTransitions ? Buffer.alloc(bufSize) : null;
+ const transOutput = hasTransitions ? Buffer.alloc(bufSize) : null;
+ // Pre-allocate the normal-frame canvas too — reused via .fill(0) each iteration
+ // to avoid ~37 MB allocation per frame in the hot loop.
+ const normalCanvas = Buffer.alloc(bufSize);
+
+ for (let i = 0; i < totalFrames; i++) {
assertNotAborted();
const time = i / job.config.fps;
@@ -1060,147 +1486,164 @@ export async function executeRenderJob(
// Query ALL timed elements for z-order analysis
const stackingInfo = await queryElementStacking(domSession.page, nativeHdrVideoIds);
- // Group into z-ordered layers
- const layers = groupIntoLayers(stackingInfo);
+ // Find active transition for this frame (if any)
+ const activeTransition = transitionRanges.find(
+ (t) => i >= t.startFrame && i <= t.endFrame,
+ );
if (i % 30 === 0) {
const hdrEl = stackingInfo.find((e) => e.isHdr);
- const hdrInLayers = layers.some((l) => l.type === "hdr");
log.debug("[Render] HDR layer composite frame", {
frame: i,
time: time.toFixed(2),
hdrElement: hdrEl
? { z: hdrEl.zIndex, visible: hdrEl.visible, width: hdrEl.width }
: null,
- hdrLayerPresent: hdrInLayers,
- layerCount: layers.length,
+ stackingCount: stackingInfo.length,
+ activeTransition: activeTransition?.shader,
});
}
- // Start with a black canvas
- const canvas = Buffer.alloc(width * height * 6);
-
- // Composite layers bottom-to-top
- for (const layer of layers) {
- if (layer.type === "hdr") {
- const el = layer.element;
- const frameDir = hdrFrameDirs.get(el.id);
- const video = composition.videos.find((v) => v.id === el.id);
- if (!frameDir || !video) continue;
-
- // Frame index within the video (1-based for FFmpeg image2 output).
- // Clamp against the highest extracted frame in the directory to
- // avoid issuing an existsSync per requested time when the
- // composition outlives the source clip. If the requested frame
- // is past the end of the source, fall back to the last available
- // frame (freeze on last frame, matching Chrome's <video> behavior).
- const videoFrameIndex = Math.round((time - video.start) * job.config.fps) + 1;
- const maxIndex = getMaxFrameIndex(frameDir);
- const effectiveIndex =
- videoFrameIndex >= 1
- ? maxIndex > 0
- ? Math.min(videoFrameIndex, maxIndex)
- : videoFrameIndex
- : 0;
- const framePath =
- effectiveIndex >= 1
- ? join(frameDir, `frame_${String(effectiveIndex).padStart(4, "0")}.png`)
- : null;
+ if (activeTransition && transBufferA && transBufferB && transOutput) {
+ // ── Transition frame: dual-scene compositing ──────────────────
+ const progress =
+ activeTransition.endFrame === activeTransition.startFrame
+ ? 1
+ : (i - activeTransition.startFrame) /
+ (activeTransition.endFrame - activeTransition.startFrame);
+
+ // Resolve scene element IDs
+ const sceneAIds = new Set(sceneElements[activeTransition.fromScene] ?? []);
+ const sceneBIds = new Set(sceneElements[activeTransition.toScene] ?? []);
+
+ // Zero-fill scene buffers (transition function writes every output pixel)
+ transBufferA.fill(0);
+ transBufferB.fill(0);
+
+ for (const [sceneBuf, sceneIds] of [
+ [transBufferA, sceneAIds],
+ [transBufferB, sceneBIds],
+ ] as const) {
+ // Fresh state: seek + inject
+ await domSession.page.evaluate((t: number) => {
+ if (window.__hf && typeof window.__hf.seek === "function") window.__hf.seek(t);
+ }, time);
+ if (beforeCaptureHook) {
+ await beforeCaptureHook(domSession.page, time);
+ }
- if (framePath !== null && existsSync(framePath)) {
- try {
- const {
- data: hdrRgb,
- width: srcW,
- height: srcH,
- } = decodePngToRgb48le(readFileSync(framePath));
-
- // Derive the effective transform from the bounding rect.
- // getBoundingClientRect() already reflects all ancestor transforms
- // (GSAP sets transforms on wrapper divs, not video elements).
- const scaleX = el.width / srcW;
- const scaleY = el.height / srcH;
- const needsAffine = Math.abs(scaleX - 1) > 0.001 || Math.abs(scaleY - 1) > 0.001;
-
- if (needsAffine) {
- // Element bounds differ from extraction dimensions — scale via affine blit
- blitRgb48leAffine(
- canvas,
- hdrRgb,
- [scaleX, 0, 0, scaleY, el.x, el.y],
- srcW,
- srcH,
- width,
- height,
- el.opacity < 0.999 ? el.opacity : undefined,
- );
- } else {
- // Same dimensions — fast path with row copy
- blitRgb48leRegion(
- canvas,
- hdrRgb,
- el.x,
- el.y,
- srcW,
- srcH,
- width,
- height,
- el.opacity < 0.999 ? el.opacity : undefined,
- );
- }
- } catch (err) {
- log.warn("HDR layer decode/blit failed; skipping layer for frame", {
- frameIndex: i,
- videoId: el.id,
- framePath,
- error: err instanceof Error ? err.message : String(err),
- });
- }
+ // Blit all HDR videos/images for this scene
+ for (const el of stackingInfo) {
+ if (!el.isHdr || !sceneIds.has(el.id)) continue;
+ blitHdrVideoLayer(
+ sceneBuf as Buffer,
+ el,
+ time,
+ job.config.fps,
+ hdrFrameDirs,
+ hdrVideoStartTimes,
+ width,
+ height,
+ log,
+ videoTransfers.get(el.id),
+ effectiveHdr?.transfer,
+ );
}
- } else {
- // DOM layer: hide elements NOT in this layer + all HDR videos.
- // All elements (including invisible SDR videos) are in the stacking
- // info so their injected <img> replacements get hidden from other layers.
- const allElementIds = stackingInfo.map((e) => e.id);
- const layerIds = new Set(layer.elementIds);
- const hideIds = allElementIds.filter(
- (id) => !layerIds.has(id) || nativeHdrVideoIds.has(id),
- );
- await hideVideoElements(domSession.page, hideIds);
+ // Single DOM screenshot: mask the page so only this scene's DOM
+ // elements paint. Same masking strategy as the per-layer DOM
+ // branch — see applyDomLayerMask for details. Native HDR videos
+ // are always inline-hidden so their fallback poster/black frame
+ // doesn't bleed into the DOM overlay (HDR pixels are blitted
+ // separately by blitHdrVideoLayer above).
+ const showIds = Array.from(sceneIds);
+ const hideIds = stackingInfo
+ .map((e) => e.id)
+ .filter((id) => !sceneIds.has(id) || nativeHdrVideoIds.has(id));
+ await applyDomLayerMask(domSession.page, showIds, hideIds);
const domPng = await captureAlphaPng(domSession.page, width, height);
- await showVideoElements(domSession.page, hideIds);
-
- // Re-seek GSAP to restore animated properties (opacity, transforms)
- // that showVideoElements clobbered via removeProperty.
- await domSession.page.evaluate((t: number) => {
- if (window.__hf && typeof window.__hf.seek === "function") window.__hf.seek(t);
- }, time);
+ await removeDomLayerMask(domSession.page, hideIds);
try {
const { data: domRgba } = decodePng(domPng);
- // Invariant: `hasHdrVideo` requires `effectiveHdr` to be set (see line ~870).
+ // Invariant: `hasHdrVideo` requires `effectiveHdr` to be set (see line ~919).
if (!effectiveHdr) {
throw new Error(
"Invariant violation: effectiveHdr is undefined inside hasHdrVideo branch",
);
}
- blitRgba8OverRgb48le(domRgba, canvas, width, height, effectiveHdr.transfer);
+ blitRgba8OverRgb48le(
+ domRgba,
+ sceneBuf as Buffer,
+ width,
+ height,
+ effectiveHdr.transfer,
+ );
} catch (err) {
- log.warn("DOM layer decode/blit failed; skipping overlay for frame", {
+ log.warn("DOM layer decode/blit failed; skipping overlay for transition scene", {
frameIndex: i,
- layerIds: layer.elementIds,
+ sceneIds: Array.from(sceneIds),
error: err instanceof Error ? err.message : String(err),
});
}
}
+
+ // Apply shader transition blend directly in PQ/HLG signal space.
+ // Linearization was attempted but destroys dark PQ content — values below
+ // PQ ~5000 quantize to zero in 16-bit linear, wiping out the bottom portion
+ // of dark video content. PQ space is perceptual and works well enough
+ // for shader math since the shaders were designed for perceptual (sRGB) space.
+ const transitionFn: TransitionFn = TRANSITIONS[activeTransition.shader] ?? crossfade;
+ transitionFn(transBufferA, transBufferB, transOutput, width, height, progress);
+
+ hdrEncoder.writeFrame(transOutput);
+ } else {
+ // ── Normal frame: full layer composite (no transition) ─────────
+ normalCanvas.fill(0);
+ await compositeToBuffer(normalCanvas, time, stackingInfo, undefined, i);
+ if (debugDumpEnabled && debugDumpDir && i % 30 === 0) {
+ const previewPath = join(
+ debugDumpDir,
+ `frame_${String(i).padStart(4, "0")}_final_rgb48le.bin`,
+ );
+ writeFileSync(previewPath, normalCanvas);
+ }
+ hdrEncoder.writeFrame(normalCanvas);
}
- hdrEncoder.writeFrame(canvas);
+ // Clean up HDR frame directories for videos that have ended.
+ // Frees disk space during long renders with many HDR videos.
+ // Skip when KEEP_TEMP=1 so we can inspect intermediate state.
+ if (process.env.KEEP_TEMP !== "1") {
+ for (const [videoId, endTime] of hdrVideoEndTimes) {
+ if (time > endTime && !cleanedUpVideos.has(videoId)) {
+ // Also check no active transition references this video's scene
+ const stillNeeded =
+ activeTransition &&
+ (sceneElements[activeTransition.fromScene]?.includes(videoId) ||
+ sceneElements[activeTransition.toScene]?.includes(videoId));
+ if (!stillNeeded) {
+ const frameDir = hdrFrameDirs.get(videoId);
+ if (frameDir) {
+ try {
+ rmSync(frameDir, { recursive: true, force: true });
+ } catch (err) {
+ log.warn("Failed to clean up HDR frame directory", {
+ videoId,
+ frameDir,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ cleanedUpVideos.add(videoId);
+ }
+ }
+ }
+ }
job.framesRendered = i + 1;
- if ((i + 1) % 10 === 0 || i + 1 === job.totalFrames!) {
- const frameProgress = (i + 1) / job.totalFrames!;
+ if ((i + 1) % 10 === 0 || i + 1 === totalFrames) {
+ const frameProgress = (i + 1) / totalFrames;
updateJobStatus(
job,
"rendering",
@@ -1251,7 +1694,7 @@ export async function executeRenderJob(
if (enableStreamingEncode && streamingEncoder) {
// ── Streaming capture + encode (Stage 4 absorbs Stage 5) ──────────
- const reorderBuffer = createFrameReorderBuffer(0, job.totalFrames!);
+ const reorderBuffer = createFrameReorderBuffer(0, totalFrames);
const currentEncoder = streamingEncoder;
if (workerCount > 1) {
@@ -1323,7 +1766,7 @@ export async function executeRenderJob(
assertNotAborted();
lastBrowserConsole = session.browserConsoleBuffer;
- for (let i = 0; i < job.totalFrames!; i++) {
+ for (let i = 0; i < totalFrames; i++) {
assertNotAborted();
const time = i / job.config.fps;
const { buffer } = await captureFrameToBuffer(session, i, time);
@@ -1332,7 +1775,7 @@ export async function executeRenderJob(
reorderBuffer.advanceTo(i + 1);
job.framesRendered = i + 1;
- const frameProgress = (i + 1) / job.totalFrames!;
+ const frameProgress = (i + 1) / totalFrames;
const progress = 25 + frameProgress * 55;
updateJobStatus(
@@ -1546,15 +1989,13 @@ export async function executeRenderJob(
chunkedEncode: enableChunkedEncode,
chunkSizeFrames: enableChunkedEncode ? chunkedEncodeSize : null,
compositionDurationSeconds: composition.duration,
- totalFrames: job.totalFrames!,
+ totalFrames: totalFrames,
resolution: { width, height },
videoCount: composition.videos.length,
audioCount: composition.audios.length,
stages: perfStages,
captureAvgMs:
- job.totalFrames! > 0
- ? Math.round((perfStages.captureMs ?? 0) / job.totalFrames!)
- : undefined,
+ totalFrames > 0 ? Math.round((perfStages.captureMs ?? 0) / totalFrames) : undefined,
};
job.perfSummary = perfSummary;
if (job.config.debug) {
@@ -1575,6 +2016,8 @@ export async function executeRenderJob(
const debugOutput = join(workDir, `output${videoExt}`);
copyFileSync(outputPath, debugOutput);
}
+ } else if (process.env.KEEP_TEMP === "1") {
+ log.info("KEEP_TEMP=1 — leaving workDir on disk for inspection", { workDir });
} else {
await safeCleanup(
"remove workDir",
diff --git a/packages/shader-transitions/src/hyper-shader.ts b/packages/shader-transitions/src/hyper-shader.ts
index 6d3b30e0e0..1fc8aafe11 100644
--- a/packages/shader-transitions/src/hyper-shader.ts
+++ b/packages/shader-transitions/src/hyper-shader.ts
@@ -83,6 +83,59 @@ function deriveAccentColors(hex: string): AccentColors {
export function init(config: HyperShaderConfig): GsapTimeline {
const { bgColor, scenes, transitions } = config;
+ if (scenes.length !== transitions.length + 1) {
+ throw new Error(
+ `[HyperShader] init(): expected scenes.length === transitions.length + 1, got scenes=${scenes.length}, transitions=${transitions.length}`,
+ );
+ }
+
+ // Verify each scene id resolves to an element with the `.scene` class.
+ // Capture and compositing later assume both — without this guard the
+ // texture map gets stale ids and transitions silently no-op.
+ if (typeof document !== "undefined") {
+ const missing: string[] = [];
+ const notScene: string[] = [];
+ for (const id of scenes) {
+ const el = document.getElementById(id);
+ if (!el) {
+ missing.push(id);
+ } else if (!el.classList.contains("scene")) {
+ notScene.push(id);
+ }
+ }
+ if (missing.length > 0) {
+ throw new Error(`[HyperShader] init(): scene ids not found in DOM: ${missing.join(", ")}`);
+ }
+ if (notScene.length > 0) {
+ throw new Error(
+ `[HyperShader] init(): elements found but missing .scene class: ${notScene.join(", ")}`,
+ );
+ }
+ }
+
+ interface HfTransitionMeta {
+ time: number;
+ duration: number;
+ shader: string;
+ ease: string;
+ fromScene: string;
+ toScene: string;
+ }
+ type HfWindowWrite = { __hf?: { transitions?: HfTransitionMeta[] } };
+ if (typeof window !== "undefined") {
+ const hfWin = window as unknown as HfWindowWrite;
+ if (hfWin.__hf) {
+ hfWin.__hf.transitions = transitions.map((t: TransitionConfig, i: number) => ({
+ time: t.time,
+ duration: t.duration ?? 1,
+ shader: t.shader,
+ ease: t.ease ?? "none",
+ fromScene: scenes[i] ?? "",
+ toScene: scenes[i + 1] ?? "",
+ }));
+ }
+ }
+
const accentColors: AccentColors = config.accentColor
? deriveAccentColors(config.accentColor)
: { accent: [1, 0.6, 0.2], dark: [0.4, 0.15, 0], bright: [1, 0.85, 0.5] };