Skip to content

Write HTML. Render video. Built for agents.

feat(engine): sub-frame multi-sample motion blur, capture-level accumulation (#4019)

miga-heygen0a1c6f5a457c
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 778586d941..835a038dcb 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -269,6 +269,7 @@ export {
export {
MEDIA_VISUAL_STYLE_PROPERTIES,
copyMediaVisualStyles,
+ quantizeSeekTime,
quantizeTimeToFrame,
type MediaVisualStyleProperty,
} from "./inline-scripts/parityContract";
diff --git a/packages/core/src/inline-scripts/parityContract.ts b/packages/core/src/inline-scripts/parityContract.ts
index 21ba002a85..d7b8ed8b72 100644
--- a/packages/core/src/inline-scripts/parityContract.ts
+++ b/packages/core/src/inline-scripts/parityContract.ts
@@ -34,22 +34,52 @@ export type MediaVisualStyleProperty = (typeof MEDIA_VISUAL_STYLE_PROPERTIES)[nu
const FRAME_BOUNDARY_EPSILON = 1e-3;
+function safeFps(fps: number): number {
+ return Number.isFinite(fps) && fps > 0 ? fps : 30;
+}
+
+function safeTime(timeSeconds: number): number {
+ return Number.isFinite(timeSeconds) && timeSeconds > 0 ? timeSeconds : 0;
+}
+
export function quantizeTimeToFrame(timeSeconds: number, fps: number): number {
- const safeFps = Number.isFinite(fps) && fps > 0 ? fps : 30;
- const safeTime = Number.isFinite(timeSeconds) && timeSeconds > 0 ? timeSeconds : 0;
- const frameIndex = Math.floor(safeTime * safeFps + 1e-9);
- return frameIndex / safeFps;
+ const grid = safeFps(fps);
+ const frameIndex = Math.floor(safeTime(timeSeconds) * grid + 1e-9);
+ return frameIndex / grid;
+}
+
+/**
+ * The grid a deterministic render seek lands on.
+ *
+ * With no `subFrameDivisions` this is the output frame grid, unchanged. Sub-frame
+ * sampling (motion blur) passes an integer subdivision count, which can only refine
+ * the output grid, never move a frame-time instant off it.
+ *
+ * The finer grid rounds where the frame grid floors. A sub-frame time makes a float
+ * round trip (the caller builds `ticks / (fps * divisions)`, this recomputes
+ * `time * fps * divisions`), and past a few million ticks that error exceeds the
+ * floor epsilon, which would silently drop a sample one tick early.
+ */
+export function quantizeSeekTime(
+ timeSeconds: number,
+ fps: number,
+ subFrameDivisions?: number,
+): number {
+ const divisions = Number.isInteger(subFrameDivisions) ? (subFrameDivisions as number) : 1;
+ if (divisions <= 1) return quantizeTimeToFrame(timeSeconds, fps);
+ const grid = safeFps(fps) * divisions;
+ return Math.round(safeTime(timeSeconds) * grid) / grid;
}
/** Snap decimal noise near a frame boundary without moving genuinely fractional timing. */
export function snapTimeToFrameBoundary(timeSeconds: number, fps: number): number {
- const safeFps = Number.isFinite(fps) && fps > 0 ? fps : 30;
- const safeTime = Number.isFinite(timeSeconds) && timeSeconds > 0 ? timeSeconds : 0;
- const framePosition = safeTime * safeFps;
+ const grid = safeFps(fps);
+ const time = safeTime(timeSeconds);
+ const framePosition = time * grid;
const nearestFrame = Math.round(framePosition);
return Math.abs(framePosition - nearestFrame) <= FRAME_BOUNDARY_EPSILON
- ? nearestFrame / safeFps
- : safeTime;
+ ? nearestFrame / grid
+ : time;
}
export function copyMediaVisualStyles(
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index 66f141cece..d5de489bd5 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -54,7 +54,11 @@ import {
isMemberGroupHidden,
} from "../audioGroups";
import { clampNativeMediaVolume } from "../audioGain";
-import { quantizeTimeToFrame, snapTimeToFrameBoundary } from "../inline-scripts/parityContract";
+import {
+ quantizeSeekTime,
+ quantizeTimeToFrame,
+ snapTimeToFrameBoundary,
+} from "../inline-scripts/parityContract";
import { createManualEditGestureWatch } from "./manualEditGestureWatch";
import type {
RuntimeDeterministicAdapter,
@@ -3030,9 +3034,10 @@ export function initSandboxRuntimeModular(): void {
},
renderSeek: (timeSeconds, options) => {
renderCaptureSeekStarted = true;
- const quantized = quantizeTimeToFrame(
+ const quantized = quantizeSeekTime(
Math.max(0, Number(timeSeconds) || 0),
state.canonicalFps,
+ options?.subFrameDivisions,
);
webAudio.stopAll();
clock.detachAudioSource();
diff --git a/packages/core/src/runtime/player.test.ts b/packages/core/src/runtime/player.test.ts
index 377efb7b64..fde3b30e61 100644
--- a/packages/core/src/runtime/player.test.ts
+++ b/packages/core/src/runtime/player.test.ts
@@ -652,3 +652,69 @@ describe("createRuntimePlayer", () => {
});
});
});
+
+describe("renderSeek sub-frame grid (issue #4010 motion blur)", () => {
+ // The 16 sample times of one frame at the After Effects defaults (180 degree shutter,
+ // phase -90): offsets -0.234375 .. +0.234375 frames on the engine's 4096-tick grid.
+ const SUB_FRAME_DIVISIONS = 4096;
+ const sampleTimes = (frameIndex: number, fps: number, samples: number): number[] => {
+ const grid = fps * SUB_FRAME_DIVISIONS;
+ return Array.from({ length: samples }, (_, k) => {
+ const offsetFrames = -0.25 + ((k + 0.5) / samples) * 0.5;
+ const ticks =
+ frameIndex * SUB_FRAME_DIVISIONS + Math.round(offsetFrames * SUB_FRAME_DIVISIONS);
+ return ticks / grid;
+ });
+ };
+
+ it("keeps 16 sub-frame sample times distinct instead of flooring them onto frame 10", () => {
+ const timeline = createMockTimeline();
+ const player = createRuntimePlayer(createMockDeps(timeline));
+
+ const landed = sampleTimes(10, 30, 16).map((t) => {
+ player.renderSeek(t, { suppressEvents: true, subFrameDivisions: SUB_FRAME_DIVISIONS });
+ return timeline.time();
+ });
+
+ // Without the finer grid every sample floors onto frame 10 and the averaged frame is
+ // byte-identical to the unblurred one, which reads as "the feature does nothing".
+ expect(new Set(landed).size).toBe(16);
+ expect(landed).toEqual([...landed].sort((a, b) => a - b));
+ // The window straddles the frame instant: first sample before it, last after.
+ expect(landed[0]).toBeLessThan(10 / 30);
+ expect(landed[15]).toBeGreaterThan(10 / 30);
+ });
+
+ it("recovers the intended tick exactly on a long composition", () => {
+ const timeline = createMockTimeline();
+ const player = createRuntimePlayer(createMockDeps(timeline));
+ // Frame 18000 is 10 minutes in at 30fps, where the tick count is large enough that a
+ // floor with a 1e-9 epsilon can land a tick early on the float round trip.
+ const expected = sampleTimes(18000, 30, 16);
+
+ const landed = expected.map((t) => {
+ player.renderSeek(t, { suppressEvents: true, subFrameDivisions: SUB_FRAME_DIVISIONS });
+ return timeline.time();
+ });
+
+ expect(landed).toEqual(expected);
+ });
+
+ it("still floors onto the output frame grid when no subdivision is asked for", () => {
+ const timeline = createMockTimeline();
+ const player = createRuntimePlayer(createMockDeps(timeline));
+
+ player.renderSeek(10 / 30 + 0.017, {});
+
+ expect(timeline.time()).toBe(10 / 30);
+ });
+
+ it("suppresses timeline events on a sub-frame sample seek", () => {
+ const timeline = createMockTimeline();
+ const player = createRuntimePlayer(createMockDeps(timeline));
+
+ player.renderSeek(10 / 30, { suppressEvents: true, subFrameDivisions: SUB_FRAME_DIVISIONS });
+
+ expect(timeline.totalTime).toHaveBeenCalledWith(10 / 30, true);
+ });
+});
diff --git a/packages/core/src/runtime/player.ts b/packages/core/src/runtime/player.ts
index 9af28afc73..7217dcea47 100644
--- a/packages/core/src/runtime/player.ts
+++ b/packages/core/src/runtime/player.ts
@@ -1,5 +1,5 @@
import type { RuntimePlayer, RuntimeSeekOptions, RuntimeTimelineLike } from "./types";
-import { quantizeTimeToFrame } from "../inline-scripts/parityContract";
+import { quantizeSeekTime } from "../inline-scripts/parityContract";
import { swallow } from "./diagnostics";
/**
@@ -89,7 +89,7 @@ function seekTimelineDeterministically(
canonicalFps: number,
options?: RuntimeSeekOptions,
): number {
- const quantized = quantizeTimeToFrame(timeSeconds, canonicalFps);
+ const quantized = quantizeSeekTime(timeSeconds, canonicalFps, options?.subFrameDivisions);
const suppressEvents = options?.suppressEvents === true;
safeVoid(timeline, "pause");
if (typeof timeline.totalTime === "function") {
@@ -248,7 +248,11 @@ export function createRuntimePlayer(deps: PlayerDeps): RuntimePlayer {
activateSiblingTimelines(deps.getTimelineRegistry?.(), timeline);
return seekTimelineDeterministically(timeline, timeSeconds, canonicalFps, options);
})()
- : quantizeTimeToFrame(Math.max(0, Number(timeSeconds) || 0), canonicalFps);
+ : quantizeSeekTime(
+ Math.max(0, Number(timeSeconds) || 0),
+ canonicalFps,
+ options?.subFrameDivisions,
+ );
deps.onDeterministicSeek(quantized, options);
deps.setIsPlaying(false);
deps.onSyncMedia(quantized, false);
diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.ts
index edfd520508..221b5a660c 100644
--- a/packages/core/src/runtime/types.ts
+++ b/packages/core/src/runtime/types.ts
@@ -257,6 +257,12 @@ export type RuntimePlayer = {
export type RuntimeSeekOptions = {
suppressEvents?: boolean;
+ /**
+ * Subdivide the output frame grid this render seek quantizes onto. Integer >= 1;
+ * 1 (or absent) is the output frame grid. Motion-blur sub-frame sampling passes the
+ * engine's sub-frame tick count so a fractional sample time survives quantization.
+ */
+ subFrameDivisions?: number;
};
export type RuntimeTimelineChildLike = {
diff --git a/packages/engine/src/services/frameCapture-motionBlur.test.ts b/packages/engine/src/services/frameCapture-motionBlur.test.ts
new file mode 100644
index 0000000000..b1f335429a
--- /dev/null
+++ b/packages/engine/src/services/frameCapture-motionBlur.test.ts
@@ -0,0 +1,225 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import {
+ captureFrame,
+ captureFrameToBuffer,
+ resolveSessionMotionBlur,
+ type CaptureSession,
+} from "./frameCapture.js";
+import { mkdtempSync } from "fs";
+import { tmpdir } from "os";
+import { join } from "path";
+import { resolveMotionBlurPlan } from "./motionBlur.js";
+import { decodePng, encodePng } from "../utils/alphaBlit.js";
+import { pageScreenshotCapture } from "./screenshotService.js";
+
+vi.mock("./screenshotService.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./screenshotService.js")>()),
+ pageScreenshotCapture: vi.fn(),
+}));
+
+/**
+ * The accumulation pass drives the real page-side seek callback, so the fake page runs
+ * each `page.evaluate` argument against a stubbed `window` / `document` instead of
+ * recording that a call happened. What lands in `seeks` is therefore what a browser's
+ * `window.__hf.seek` would have received.
+ */
+interface RecordedSeek {
+ time: number;
+ suppressEvents?: boolean;
+ subFrameDivisions?: number;
+}
+
+function installPageGlobals(seeks: RecordedSeek[]): void {
+ const root = globalThis as Record<string, unknown>;
+ root.window = {
+ __hf: {
+ seek: (time: number, options?: { suppressEvents?: boolean; subFrameDivisions?: number }) => {
+ seeks.push({ time, ...options });
+ },
+ },
+ };
+ root.document = { querySelectorAll: () => [] };
+}
+
+const WIDTH = 2;
+const HEIGHT = 1;
+
+function solidPng(value: number): Buffer {
+ const rgba = new Uint8Array(WIDTH * HEIGHT * 4);
+ for (let i = 0; i < rgba.length; i += 4) {
+ rgba[i] = value;
+ rgba[i + 1] = value;
+ rgba[i + 2] = value;
+ rgba[i + 3] = 255;
+ }
+ return encodePng(WIDTH, HEIGHT, rgba);
+}
+
+function makeSession(overrides: Partial<CaptureSession> = {}): CaptureSession {
+ return {
+ page: {
+ evaluate: async (fn: unknown, ...args: unknown[]) =>
+ typeof fn === "function" ? (fn as (...a: unknown[]) => unknown)(...args) : undefined,
+ },
+ options: { fps: { num: 30, den: 1 }, format: "png", width: WIDTH, height: HEIGHT },
+ captureMode: "screenshot",
+ isInitialized: true,
+ onBeforeCapture: null,
+ capturePerf: {
+ frames: 0,
+ seekMs: 0,
+ beforeCaptureMs: 0,
+ screenshotMs: 0,
+ totalMs: 0,
+ frameMs: [],
+ },
+ motionBlur: resolveMotionBlurPlan({}) ?? undefined,
+ ...overrides,
+ } as unknown as CaptureSession;
+}
+
+let seeks: RecordedSeek[];
+
+beforeEach(() => {
+ seeks = [];
+ installPageGlobals(seeks);
+ // Sample n is captured as the flat grey 16n, so the average over the default 16
+ // samples is the mean of 0, 16, ... 240, which is 120.
+ let sample = 0;
+ vi.mocked(pageScreenshotCapture).mockImplementation(async () => solidPng(16 * sample++));
+});
+
+afterEach(() => {
+ vi.mocked(pageScreenshotCapture).mockReset();
+ const root = globalThis as Record<string, unknown>;
+ delete root.window;
+ delete root.document;
+});
+
+describe("sub-frame accumulation reaches the page with distinct sample times", () => {
+ it("seeks 16 distinct sub-frame times, all on the finer grid", async () => {
+ await captureFrameToBuffer(makeSession(), 10, 10 / 30);
+
+ const samples = seeks.filter((s) => s.subFrameDivisions !== undefined);
+ expect(samples).toHaveLength(16);
+ expect(new Set(samples.map((s) => s.time)).size).toBe(16);
+ expect(samples.every((s) => s.subFrameDivisions === 4096)).toBe(true);
+ // Frame 10 at 30fps is tick 40960; the window spans 960 ticks either side.
+ expect(samples[0]?.time).toBe(40000 / 122880);
+ expect(samples[15]?.time).toBe(41920 / 122880);
+ });
+
+ it("fires exactly one eventful seek per frame, at the frame time", async () => {
+ await captureFrameToBuffer(makeSession(), 10, 10 / 30);
+
+ const eventful = seeks.filter((s) => s.suppressEvents !== true);
+ expect(eventful).toHaveLength(1);
+ expect(eventful[0]?.time).toBe(10 / 30);
+ // It comes first, so a composition's own callbacks fire on the same interval they
+ // would with motion blur off, before the playhead moves inside the shutter window.
+ expect(seeks[0]).toBe(eventful[0]);
+ });
+
+ it("restores the playhead to the frame time so the next frame's callbacks are not skipped", async () => {
+ await captureFrameToBuffer(makeSession(), 10, 10 / 30);
+
+ const last = seeks[seeks.length - 1];
+ expect(last?.time).toBe(10 / 30);
+ expect(last?.suppressEvents).toBe(true);
+ expect(seeks).toHaveLength(18);
+ });
+
+ it("averages the captured samples into the output frame", async () => {
+ const result = await captureFrameToBuffer(makeSession(), 10, 10 / 30);
+
+ const decoded = decodePng(result.buffer);
+ expect(decoded.width).toBe(WIDTH);
+ expect([...decoded.data.slice(0, 4)]).toEqual([120, 120, 120, 255]);
+ });
+
+ it("reports the frame time, not the last sample time", async () => {
+ const outputDir = mkdtempSync(join(tmpdir(), "hf-motion-blur-"));
+ const result = await captureFrame(makeSession({ outputDir }), 10, 10 / 30);
+
+ expect(result.time).toBe(10 / 30);
+ expect(result.path).toBe(join(outputDir, "frame_000010.png"));
+ });
+
+ it("captures once per frame with motion blur off", async () => {
+ await captureFrameToBuffer(makeSession({ motionBlur: undefined }), 10, 10 / 30);
+
+ expect(vi.mocked(pageScreenshotCapture)).toHaveBeenCalledTimes(1);
+ expect(seeks).toHaveLength(1);
+ expect(seeks[0]).toEqual({ time: 10 / 30 });
+ });
+});
+
+describe("accumulation composes with static-frame dedup", () => {
+ it("pays nothing on a static frame instead of capturing K samples of the same instant", async () => {
+ const anchor = solidPng(42);
+ const session = makeSession({
+ staticFrames: new Set([11]),
+ lastFrameBuffer: anchor,
+ lastFrameAbsoluteIndex: 10,
+ });
+
+ const result = await captureFrameToBuffer(session, 11, 11 / 30);
+
+ expect(result.buffer).toBe(anchor);
+ expect(vi.mocked(pageScreenshotCapture)).not.toHaveBeenCalled();
+ expect(seeks).toHaveLength(0);
+ expect(session.staticDedupCount).toBe(1);
+ });
+
+ it("pays K captures on a moving frame", async () => {
+ const session = makeSession({
+ staticFrames: new Set([11]),
+ lastFrameBuffer: solidPng(42),
+ lastFrameAbsoluteIndex: 10,
+ });
+
+ await captureFrameToBuffer(session, 12, 12 / 30);
+
+ expect(vi.mocked(pageScreenshotCapture)).toHaveBeenCalledTimes(16);
+ });
+});
+
+describe("resolveSessionMotionBlur rejects what accumulation cannot render", () => {
+ const withOptions = (overrides: Partial<CaptureSession>): CaptureSession =>
+ makeSession({
+ options: {
+ fps: { num: 30, den: 1 },
+ format: "png",
+ width: WIDTH,
+ height: HEIGHT,
+ motionBlur: {},
+ },
+ ...overrides,
+ } as Partial<CaptureSession>);
+
+ it("is off when the composition did not ask for it", () => {
+ expect(resolveSessionMotionBlur(makeSession())).toBeUndefined();
+ });
+
+ it("resolves a plan for a screenshot-mode PNG session", () => {
+ expect(resolveSessionMotionBlur(withOptions({}))?.sampleTickOffsets).toHaveLength(16);
+ });
+
+ it("rejects a capture mode whose sampling is not implemented yet", () => {
+ expect(() => resolveSessionMotionBlur(withOptions({ captureMode: "beginframe" }))).toThrow(
+ /screenshot capture mode/,
+ );
+ });
+
+ it("rejects a lossy output format", () => {
+ const session = withOptions({});
+ session.options.format = "jpeg";
+ expect(() => resolveSessionMotionBlur(session)).toThrow(/format "png"/);
+ });
+
+ it("rejects injected video frames, which cannot follow a sub-frame seek", () => {
+ expect(() =>
+ resolveSessionMotionBlur(withOptions({ onBeforeCapture: async () => {} })),
+ ).toThrow(/video/);
+ });
+});
diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts
index 9c66f065ba..eff6b50331 100644
--- a/packages/engine/src/services/frameCapture.ts
+++ b/packages/engine/src/services/frameCapture.ts
@@ -12,6 +12,7 @@ import { type Browser, type Page, type Viewport, type ConsoleMessage } from "pup
import { existsSync, mkdirSync, writeFileSync } from "fs";
import { join } from "path";
import {
+ quantizeSeekTime,
quantizeTimeToFrame,
fpsToNumber,
resolveAuthoredTimingWindow,
@@ -19,6 +20,13 @@ import {
} from "@hyperframes/core";
import { DrawElementCaptureError } from "./drawElementCaptureError.js";
+import { encodePng } from "../utils/alphaBlit.js";
+import {
+ MotionBlurAccumulator,
+ motionBlurSampleTimes,
+ resolveMotionBlurPlan,
+ type MotionBlurPlan,
+} from "./motionBlur.js";
// ── Extracted modules ───────────────────────────────────────────────────────
import {
@@ -63,6 +71,7 @@ import type {
CaptureBufferResult,
CapturePerfSummary,
CaptureWarning,
+ HfSeekOptions,
SubTimelineWaitOutcome,
} from "../types.js";
import { cloneCaptureWarnings } from "./captureWarning.js";
@@ -97,6 +106,13 @@ export interface CaptureSession {
lastFrameAbsoluteIndex?: number;
/** Count of frames served from a reused buffer (dedup telemetry). */
staticDedupCount?: number;
+ /**
+ * Resolved sub-frame motion-blur plan, or undefined when off. Set once by
+ * `resolveSessionMotionBlur` at the end of initialization, where the capture mode has
+ * settled, so an unsupported combination fails before the first frame rather than
+ * silently rendering unblurred.
+ */
+ motionBlur?: MotionBlurPlan;
// ── Static-dedup observability (set by armStaticDedup; surfaced via
// getCapturePerfSummary → RenderPerfSummary → the render_complete event) ──
// `armed` derives from the verified staticFrames set. Predicted count is stored
@@ -2496,6 +2512,8 @@ export async function initializeSession(session: CaptureSession): Promise<void>
const commitCdp = await getCdpSession(page);
await commitCdp.send("HeadlessExperimental.beginFrame", preparedBeginFrameTimeline.commitParams);
+ session.motionBlur = resolveSessionMotionBlur(session);
+
session.isInitialized = true;
}
@@ -2547,10 +2565,36 @@ export async function waitForPendingSeekCompletion(page: Pick<Page, "evaluate">)
});
}
+/**
+ * Seek the page timeline and report whether a page-side composite is pending.
+ *
+ * The page's `seek()` owns all framework-specific stepping (GSAP, CSS animations, WAAPI);
+ * the options object reaches it untouched through the producer's `__hf.seek` bridge.
+ * Seek and pending-flag read share one round trip.
+ */
+async function seekPageTimeline(
+ page: Page,
+ time: number,
+ seekOptions: HfSeekOptions | undefined,
+): Promise<boolean> {
+ return page.evaluate(
+ (t: number, opts: HfSeekOptions | undefined) => {
+ if (window.__hf && typeof window.__hf.seek === "function") {
+ window.__hf.seek(t, opts);
+ }
+ return !!(window as unknown as { __hf_page_composite_pending?: boolean })
+ .__hf_page_composite_pending;
+ },
+ time,
+ seekOptions,
+ );
+}
+
async function prepareFrameForCapture(
session: CaptureSession,
frameIndex: number,
time: number,
+ seekOptions?: HfSeekOptions,
): Promise<{
quantizedTime: number;
seekMs: number;
@@ -2562,19 +2606,14 @@ async function prepareFrameForCapture(
throw new Error("[FrameCapture] Session not initialized");
}
- const quantizedTime = quantizeTimeToFrame(time, fpsToNumber(options.fps));
+ const quantizedTime = quantizeSeekTime(
+ time,
+ fpsToNumber(options.fps),
+ seekOptions?.subFrameDivisions,
+ );
const seekStart = Date.now();
- // Seek via the __hf protocol. The page's seek() implementation handles
- // all framework-specific logic (GSAP stepping, CSS animation sync, etc.)
- // Seek + check page-side composite pending flag in one round-trip.
- const hasPendingComposite = await page.evaluate((t: number) => {
- if (window.__hf && typeof window.__hf.seek === "function") {
- window.__hf.seek(t);
- }
- return !!(window as unknown as { __hf_page_composite_pending?: boolean })
- .__hf_page_composite_pending;
- }, quantizedTime);
+ const hasPendingComposite = await seekPageTimeline(page, quantizedTime, seekOptions);
await decodeDynamicCssBackgroundImages(page);
@@ -3568,12 +3607,199 @@ export async function withFrameDeadline<T>(
}
}
+/**
+ * Resolve the session's motion-blur plan, rejecting combinations the accumulation pass
+ * cannot render correctly instead of silently producing an unblurred frame.
+ *
+ * Called once initialization has settled the capture mode. `format: "png"` is required
+ * because samples are averaged pixel by pixel: JPEG samples would be averaged after
+ * lossy quantization and the blended frame is re-encoded as PNG. `<video>` content is
+ * out of scope because it is supplied by the before-capture frame-injection hook rather
+ * than by the timeline seek, so it cannot follow a sub-frame time.
+ */
+export function resolveSessionMotionBlur(session: CaptureSession): MotionBlurPlan | undefined {
+ const plan = resolveMotionBlurPlan(session.options.motionBlur);
+ if (!plan) return undefined;
+ if (session.captureMode !== "screenshot") {
+ throw new Error(
+ `[MotionBlur] sub-frame motion blur requires screenshot capture mode, got "${session.captureMode}"`,
+ );
+ }
+ if (session.options.format !== "png") {
+ throw new Error(
+ `[MotionBlur] sub-frame motion blur requires format "png", got "${session.options.format ?? "jpeg"}"`,
+ );
+ }
+ if (session.onBeforeCapture) {
+ throw new Error(
+ "[MotionBlur] sub-frame motion blur cannot run with injected video frames: video content is extracted per output frame and does not follow a sub-frame seek",
+ );
+ }
+ return plan;
+}
+
+/** Frame timings shared by the single-capture and accumulation paths. */
+interface CapturedSurface {
+ buffer: Buffer;
+ quantizedTime: number;
+ seekMs: number;
+ beforeCaptureMs: number;
+ screenshotMs: number;
+}
+
+/** Seek to `time` and capture one surface with the session's capture mode. */
+async function captureFrameSurface(
+ session: CaptureSession,
+ frameIndex: number,
+ time: number,
+ seekOptions?: HfSeekOptions,
+): Promise<CapturedSurface> {
+ const { page, options } = session;
+ const { quantizedTime, seekMs, beforeCaptureMs } = await prepareFrameForCapture(
+ session,
+ frameIndex,
+ time,
+ seekOptions,
+ );
+
+ const screenshotStart = Date.now();
+ let screenshotBuffer: Buffer;
+
+ if (session.captureMode === "beginframe") {
+ const frameTimeTicks = session.beginFrameTimeTicks + frameIndex * session.beginFrameIntervalMs;
+ const result = await beginFrameCapture(
+ page,
+ options,
+ frameTimeTicks,
+ session.beginFrameIntervalMs,
+ );
+ if (result.hasDamage) session.beginFrameHasDamageCount++;
+ else session.beginFrameNoDamageCount++;
+ screenshotBuffer = result.buffer;
+ } else if (
+ session.captureMode === "drawelement" &&
+ session.clipBoundaryFrames?.has(frameIndex) &&
+ process.env.HF_FAST_CAPTURE_BOUNDARY_SS === "true"
+ ) {
+ throw new DrawElementCaptureError(
+ frameIndex,
+ "boundary screenshot requested on an injected canvas page",
+ );
+ } else if (session.captureMode === "drawelement") {
+ // Advance compositor state via BeginFrame when available (Linux headless-shell);
+ // on macOS the compositor advances naturally without BeginFrame.
+ if (session.beginFrameTimeTicks > 0) {
+ const client = await getCdpSession(page);
+ await client.send("HeadlessExperimental.beginFrame", {
+ frameTimeTicks: session.beginFrameTimeTicks + frameIndex * session.beginFrameIntervalMs,
+ interval: session.beginFrameIntervalMs,
+ noDisplayUpdates: false,
+ // no screenshot param — we capture via canvas
+ });
+ }
+ try {
+ screenshotBuffer = await captureDrawElementFrame(
+ page,
+ options.width,
+ options.height,
+ options.format ?? "jpeg",
+ options.quality ?? 80,
+ // Paint-event sync only without BeginFrame (macOS / screenshot-launched):
+ // under BeginFrame control the per-frame beginFrame above already painted
+ // a fresh snapshot, and no further paint would arrive during a wait.
+ session.beginFrameTimeTicks === 0,
+ );
+ // A tiny JPEG may be a dropped paint record. Never screenshot this page:
+ // its injected canvas can still hold the preceding frame's bitmap.
+ // Restart on a fresh screenshot page even if this was a simple valid frame.
+ if ((options.format ?? "jpeg") !== "png" && process.env.HF_FORCE_DRAWELEMENT !== "1") {
+ const sizes = (session.deFrameSizes ??= []);
+ const sorted = sizes.length >= 12 ? [...sizes].sort((a, b) => a - b) : null;
+ const median = sorted ? (sorted[sorted.length >> 1] ?? 0) : 0;
+ const floor = Math.max(20000, median * 0.12);
+ if (screenshotBuffer.length < floor) {
+ throw new DrawElementCaptureError(
+ frameIndex,
+ `suspect small frame (${screenshotBuffer.length}B < ${Math.round(floor)}B)`,
+ );
+ } else {
+ if (sizes.length >= 60) sizes.shift();
+ sizes.push(screenshotBuffer.length);
+ }
+ }
+ } catch (err) {
+ // Missing paint records/canvas state require a new screenshot page.
+ if (isRecoverableDrawElementError(err)) {
+ session.deNcprFallbacks = (session.deNcprFallbacks ?? 0) + 1;
+ const reason = isCanvasNotInitializedError(err)
+ ? "drawElement canvas not initialized"
+ : "No cached paint record";
+ throw new DrawElementCaptureError(frameIndex, reason, err);
+ } else {
+ throw err;
+ }
+ }
+ } else {
+ screenshotBuffer = await pageScreenshotCapture(page, options);
+ }
+
+ const screenshotMs = Date.now() - screenshotStart;
+
+ return { buffer: screenshotBuffer, quantizedTime, seekMs, beforeCaptureMs, screenshotMs };
+}
+
+/**
+ * Capture one output frame as the average of `plan.samplesPerFrame` sub-frame captures.
+ *
+ * Callback invariant: exactly one eventful seek per output frame, at the frame time,
+ * arriving from the previous frame's time. Every sample seek suppresses events and the
+ * playhead is restored to the frame time afterwards, so a composition's own
+ * onUpdate/onComplete fire on the same interval boundaries as a render with blur off.
+ */
+async function captureAccumulatedFrame(
+ session: CaptureSession,
+ frameIndex: number,
+ absFrameIndex: number,
+ plan: MotionBlurPlan,
+): Promise<CapturedSurface> {
+ const fps = fpsToNumber(session.options.fps);
+ const frameTime = quantizeSeekTime(absFrameIndex / fps, fps);
+
+ const eventfulSeekStart = Date.now();
+ await seekPageTimeline(session.page, frameTime, undefined);
+ const totals = { seekMs: Date.now() - eventfulSeekStart, beforeCaptureMs: 0, screenshotMs: 0 };
+
+ const sampleSeek: HfSeekOptions = {
+ suppressEvents: true,
+ subFrameDivisions: plan.subFrameDivisions,
+ };
+ const accumulator = new MotionBlurAccumulator(plan.blend);
+ for (const sampleTime of motionBlurSampleTimes(plan, absFrameIndex, fps)) {
+ const sample = await captureFrameSurface(session, frameIndex, sampleTime, sampleSeek);
+ totals.seekMs += sample.seekMs;
+ totals.beforeCaptureMs += sample.beforeCaptureMs;
+ totals.screenshotMs += sample.screenshotMs;
+ accumulator.add(sample.buffer);
+ }
+
+ const restoreSeekStart = Date.now();
+ await seekPageTimeline(session.page, frameTime, { suppressEvents: true });
+ totals.seekMs += Date.now() - restoreSeekStart;
+
+ const blended = accumulator.finish();
+ return {
+ buffer: encodePng(blended.width, blended.height, blended.data),
+ quantizedTime: frameTime,
+ ...totals,
+ };
+}
+
async function captureFrameCore(
session: CaptureSession,
frameIndex: number,
time: number,
): Promise<{ buffer: Buffer; quantizedTime: number; captureTimeMs: number }> {
- const { page, options } = session;
+ const { options } = session;
const startTime = Date.now();
// Static-frame dedup: this frame is byte-identical to its predecessor (predicted +
@@ -3606,95 +3832,12 @@ async function captureFrameCore(
}
try {
- const { quantizedTime, seekMs, beforeCaptureMs } = await prepareFrameForCapture(
- session,
- frameIndex,
- time,
- );
-
- const screenshotStart = Date.now();
- let screenshotBuffer: Buffer;
-
- if (session.captureMode === "beginframe") {
- const frameTimeTicks =
- session.beginFrameTimeTicks + frameIndex * session.beginFrameIntervalMs;
- const result = await beginFrameCapture(
- page,
- options,
- frameTimeTicks,
- session.beginFrameIntervalMs,
- );
- if (result.hasDamage) session.beginFrameHasDamageCount++;
- else session.beginFrameNoDamageCount++;
- screenshotBuffer = result.buffer;
- } else if (
- session.captureMode === "drawelement" &&
- session.clipBoundaryFrames?.has(frameIndex) &&
- process.env.HF_FAST_CAPTURE_BOUNDARY_SS === "true"
- ) {
- throw new DrawElementCaptureError(
- frameIndex,
- "boundary screenshot requested on an injected canvas page",
- );
- } else if (session.captureMode === "drawelement") {
- // Advance compositor state via BeginFrame when available (Linux headless-shell);
- // on macOS the compositor advances naturally without BeginFrame.
- if (session.beginFrameTimeTicks > 0) {
- const client = await getCdpSession(page);
- await client.send("HeadlessExperimental.beginFrame", {
- frameTimeTicks: session.beginFrameTimeTicks + frameIndex * session.beginFrameIntervalMs,
- interval: session.beginFrameIntervalMs,
- noDisplayUpdates: false,
- // no screenshot param — we capture via canvas
- });
- }
- try {
- screenshotBuffer = await captureDrawElementFrame(
- page,
- options.width,
- options.height,
- options.format ?? "jpeg",
- options.quality ?? 80,
- // Paint-event sync only without BeginFrame (macOS / screenshot-launched):
- // under BeginFrame control the per-frame beginFrame above already painted
- // a fresh snapshot, and no further paint would arrive during a wait.
- session.beginFrameTimeTicks === 0,
- );
- // A tiny JPEG may be a dropped paint record. Never screenshot this page:
- // its injected canvas can still hold the preceding frame's bitmap.
- // Restart on a fresh screenshot page even if this was a simple valid frame.
- if ((options.format ?? "jpeg") !== "png" && process.env.HF_FORCE_DRAWELEMENT !== "1") {
- const sizes = (session.deFrameSizes ??= []);
- const sorted = sizes.length >= 12 ? [...sizes].sort((a, b) => a - b) : null;
- const median = sorted ? (sorted[sorted.length >> 1] ?? 0) : 0;
- const floor = Math.max(20000, median * 0.12);
- if (screenshotBuffer.length < floor) {
- throw new DrawElementCaptureError(
- frameIndex,
- `suspect small frame (${screenshotBuffer.length}B < ${Math.round(floor)}B)`,
- );
- } else {
- if (sizes.length >= 60) sizes.shift();
- sizes.push(screenshotBuffer.length);
- }
- }
- } catch (err) {
- // Missing paint records/canvas state require a new screenshot page.
- if (isRecoverableDrawElementError(err)) {
- session.deNcprFallbacks = (session.deNcprFallbacks ?? 0) + 1;
- const reason = isCanvasNotInitializedError(err)
- ? "drawElement canvas not initialized"
- : "No cached paint record";
- throw new DrawElementCaptureError(frameIndex, reason, err);
- } else {
- throw err;
- }
- }
- } else {
- screenshotBuffer = await pageScreenshotCapture(page, options);
- }
-
- const screenshotMs = Date.now() - screenshotStart;
+ const plan = session.motionBlur;
+ // One capture per frame, or `plan.samplesPerFrame` captures averaged into one. Both
+ // report the same timings, so perf accounting and the dedup anchor stay shared.
+ const { buffer, quantizedTime, seekMs, beforeCaptureMs, screenshotMs } = plan
+ ? await captureAccumulatedFrame(session, frameIndex, absFrameIndex, plan)
+ : await captureFrameSurface(session, frameIndex, time);
const captureTimeMs = Date.now() - startTime;
session.capturePerf.frames += 1;
@@ -3706,11 +3849,11 @@ async function captureFrameCore(
// Retain this freshly-captured buffer so the following static frames can reuse it.
if (session.staticFrames) {
- session.lastFrameBuffer = screenshotBuffer;
+ session.lastFrameBuffer = buffer;
session.lastFrameAbsoluteIndex = absFrameIndex;
}
- return { buffer: screenshotBuffer, quantizedTime, captureTimeMs };
+ return { buffer, quantizedTime, captureTimeMs };
} catch (captureError) {
if (session.isInitialized) {
await captureFrameErrorDiagnostics(
@@ -3809,6 +3952,13 @@ export async function captureFrameToBuffer(
* - macOS hardware GPU path (syncToPaintEvent=true, beginFrameTimeTicks=0).
* BeginFrame (Linux) uses the standard synchronous path unchanged.
*/
+/**
+ * Worker-encode path, gated to drawElement capture. It does not route through
+ * `captureFrameCore` and so has no accumulation branch; that is safe only because
+ * `resolveSessionMotionBlur` rejects every capture mode except screenshot, which makes
+ * this function unreachable with motion blur on. Widening the supported capture modes
+ * means handling accumulation here too.
+ */
export async function captureFrameToBufferPipelined(
session: CaptureSession,
frameIndex: number,
diff --git a/packages/engine/src/services/motionBlur.test.ts b/packages/engine/src/services/motionBlur.test.ts
new file mode 100644
index 0000000000..b262899f11
--- /dev/null
+++ b/packages/engine/src/services/motionBlur.test.ts
@@ -0,0 +1,158 @@
+import { describe, it, expect } from "vitest";
+import {
+ MAX_SAMPLES_PER_FRAME,
+ MotionBlurAccumulator,
+ motionBlurSampleTimes,
+ resolveMotionBlurPlan,
+ type MotionBlurBlendSpace,
+} from "./motionBlur.js";
+import { encodePng } from "../utils/alphaBlit.js";
+
+const solid = (count: number, r: number, g: number, b: number, a = 255): Uint8Array => {
+ const out = new Uint8Array(count * 4);
+ for (let i = 0; i < count * 4; i += 4) {
+ out[i] = r;
+ out[i + 1] = g;
+ out[i + 2] = b;
+ out[i + 3] = a;
+ }
+ return out;
+};
+
+/** Average `samples` as the capture path does, one decoded PNG at a time. */
+const average = (
+ samples: readonly Uint8Array[],
+ blend: MotionBlurBlendSpace,
+ width = 1,
+): { width: number; height: number; data: Uint8Array } => {
+ const accumulator = new MotionBlurAccumulator(blend);
+ for (const sample of samples) {
+ accumulator.add(encodePng(width, sample.length / 4 / width, sample));
+ }
+ return accumulator.finish();
+};
+
+describe("resolveMotionBlurPlan", () => {
+ it("is off when no options are given", () => {
+ expect(resolveMotionBlurPlan(undefined)).toBeNull();
+ });
+
+ it("defaults to After Effects: 16 samples, 180 degree shutter, phase -90, sRGB", () => {
+ const plan = resolveMotionBlurPlan({});
+ expect(plan).not.toBeNull();
+ expect(plan?.sampleTickOffsets).toHaveLength(16);
+ expect(plan?.blend).toBe("srgb");
+ // 180 degrees at phase -90 is a window of a quarter frame either side of the instant.
+ expect(plan?.sampleTickOffsets[0]).toBe(-960);
+ expect(plan?.sampleTickOffsets[15]).toBe(960);
+ });
+
+ it("places the default samples symmetrically across a quarter frame either side", () => {
+ // From the shutter formula, by hand: offset_k = (-90/360 + ((k+0.5)/16) * 180/360)
+ // frames, so k=0 is -0.234375 and k=15 is +0.234375. At 4096 ticks per frame that
+ // is exactly -960 and +960, with 128 ticks between neighbours.
+ const plan = resolveMotionBlurPlan({});
+ expect(plan?.subFrameDivisions).toBe(4096);
+ expect(plan?.sampleTickOffsets[0]).toBe(-960);
+ expect(plan?.sampleTickOffsets[15]).toBe(960);
+ expect(plan?.sampleTickOffsets).toHaveLength(16);
+ const gaps = plan?.sampleTickOffsets
+ .slice(1)
+ .map((t, i) => t - (plan.sampleTickOffsets[i] as number));
+ expect(new Set(gaps)).toEqual(new Set([128]));
+ });
+
+ it("clamps the sample count to 1..64 and ignores non-finite input", () => {
+ expect(resolveMotionBlurPlan({ samplesPerFrame: 200 })?.sampleTickOffsets).toHaveLength(
+ MAX_SAMPLES_PER_FRAME,
+ );
+ expect(resolveMotionBlurPlan({ samplesPerFrame: 0 })?.sampleTickOffsets).toHaveLength(1);
+ expect(resolveMotionBlurPlan({ samplesPerFrame: Number.NaN })?.sampleTickOffsets).toHaveLength(
+ 16,
+ );
+ });
+
+ it("follows the shutter window when the angle and phase are changed", () => {
+ // The AD5 measurement of the real After Effects export: a window one frame either
+ // side of t, which is shutterAngle 720 at phase -360.
+ const plan = resolveMotionBlurPlan({ shutterAngle: 720, shutterPhase: -360 });
+ expect(plan?.sampleTickOffsets[0]).toBe(Math.round((-1 + 1 / 16) * 4096));
+ expect(plan?.sampleTickOffsets[15]).toBe(Math.round((1 - 1 / 16) * 4096));
+ });
+});
+
+describe("motionBlurSampleTimes", () => {
+ it("returns ascending distinct sub-frame times around the frame instant", () => {
+ const plan = resolveMotionBlurPlan({});
+ if (!plan) throw new Error("plan");
+ const times = motionBlurSampleTimes(plan, 10, 30);
+
+ // Frame 10 at 30fps is tick 40960 on the 122880-tick-per-second grid; the first
+ // sample sits 960 ticks earlier and the last 960 later.
+ expect(times[0]).toBe(40000 / 122880);
+ expect(times[15]).toBe(41920 / 122880);
+ expect(new Set(times).size).toBe(16);
+ expect(times[0]).toBeLessThan(10 / 30);
+ expect(times[15]).toBeGreaterThan(10 / 30);
+ });
+
+ it("clamps samples before the composition start to zero", () => {
+ const plan = resolveMotionBlurPlan({});
+ if (!plan) throw new Error("plan");
+ const times = motionBlurSampleTimes(plan, 0, 30);
+
+ expect(times[0]).toBe(0);
+ expect(times[15]).toBe(960 / 122880);
+ });
+});
+
+describe("MotionBlurAccumulator", () => {
+ it("averages opaque samples channel by channel in sRGB", () => {
+ const blended = average([solid(2, 0, 10, 100), solid(2, 255, 30, 100)], "srgb", 2);
+ // Independent: (0+255)/2 = 127.5 -> 128, (10+30)/2 = 20, (100+100)/2 = 100.
+ expect([...blended.data.slice(0, 4)]).toEqual([128, 20, 100, 255]);
+ });
+
+ it("averages in linear light when asked, which lands well above the sRGB mean", () => {
+ const blended = average([solid(1, 0, 64, 0), solid(1, 255, 192, 0)], "linear");
+ // Independent (sRGB EOTF, mean, inverse EOTF): 0 with 255 -> 188, 64 with 192 -> 146.
+ expect([...blended.data.slice(0, 4)]).toEqual([188, 146, 0, 255]);
+ });
+
+ it("returns a single sample unchanged", () => {
+ expect([...average([solid(1, 7, 8, 9)], "srgb").data]).toEqual([7, 8, 9, 255]);
+ });
+
+ it("gives a transparent sample no colour weight and averages the alpha", () => {
+ const blended = average([solid(1, 200, 0, 0, 255), solid(1, 0, 0, 0, 0)], "srgb");
+ // The transparent sample contributes no colour, so the visible colour survives at
+ // full strength while coverage halves.
+ expect([...blended.data.slice(0, 4)]).toEqual([200, 0, 0, 128]);
+ });
+
+ it("rejects a sample whose geometry disagrees rather than blending garbage", () => {
+ const accumulator = new MotionBlurAccumulator("srgb");
+ accumulator.add(encodePng(2, 1, solid(2, 0, 0, 0)));
+ expect(() => accumulator.add(encodePng(1, 2, solid(2, 0, 0, 0)))).toThrow(/geometry mismatch/);
+ });
+
+ it("refuses to finish with no samples rather than returning an empty frame", () => {
+ expect(() => new MotionBlurAccumulator("srgb").finish()).toThrow(/no samples/);
+ });
+
+ it("holds precision across the full 64-sample maximum", () => {
+ // Independent: the mean of 0, 4, 8 ... 252 is 126.
+ const samples = Array.from({ length: 64 }, (_, k) => solid(1, 4 * k, 4 * k, 4 * k));
+ expect([...average(samples, "srgb").data]).toEqual([126, 126, 126, 255]);
+ });
+});
+
+describe("MotionBlurAccumulator geometry", () => {
+ it("reports the decoded sample geometry", () => {
+ const blended = average([solid(2, 0, 0, 0), solid(2, 100, 200, 40)], "srgb", 2);
+
+ expect(blended.width).toBe(2);
+ expect(blended.height).toBe(1);
+ expect([...blended.data.slice(0, 4)]).toEqual([50, 100, 20, 255]);
+ });
+});
diff --git a/packages/engine/src/services/motionBlur.ts b/packages/engine/src/services/motionBlur.ts
new file mode 100644
index 0000000000..d38dbe8f91
--- /dev/null
+++ b/packages/engine/src/services/motionBlur.ts
@@ -0,0 +1,208 @@
+/**
+ * Sub-frame multi-sample motion blur (issue #4010).
+ *
+ * For each output frame the capture path seeks the timeline to K sub-frame times spread
+ * across the shutter window, captures each, and averages them. Unlike the catalog
+ * component, which stacks offset copies of an element and can only integrate
+ * translation, re-rendering at each sample integrates whatever the composition actually
+ * does inside the window: rotation, scale, opacity, filters, child animation.
+ *
+ * Shutter window, the After Effects model, in frames rather than seconds so the sample
+ * offsets are frame-rate independent:
+ *
+ * shutterTime = shutterAngle / 360 / fps
+ * windowStart = t + shutterPhase / 360 / fps
+ * sample k at windowStart + (k + 0.5) / N * shutterTime
+ */
+
+import { decodePng, srgbByteToLinear } from "../utils/alphaBlit.js";
+
+/** Caller-facing options. Presence of the object is the opt-in; there is no enabled flag. */
+export interface MotionBlurOptions {
+ /** Sub-frame captures averaged into one output frame. Default 16, clamped to 1..64. */
+ samplesPerFrame?: number;
+ /** Shutter window width in degrees of one frame. Default 180, AE's default. */
+ shutterAngle?: number;
+ /** Window offset in degrees. Default -90, which centres the window on the frame time. */
+ shutterPhase?: number;
+ /**
+ * Working space for the average. Default "srgb", matching After Effects' non-linearised
+ * 8-bpc working space and the catalog component. "linear" is physically correct light
+ * integration and diverges from both on high-contrast edges.
+ */
+ blend?: MotionBlurBlendSpace;
+}
+
+export type MotionBlurBlendSpace = "srgb" | "linear";
+
+/**
+ * A resolved plan. Only `resolveMotionBlurPlan` produces one, so every field is already
+ * clamped and the sample offsets are integers on a fixed sub-frame tick grid.
+ */
+export interface MotionBlurPlan {
+ readonly blend: MotionBlurBlendSpace;
+ /**
+ * Sub-frame ticks per output frame. The seek grid is `fps * subFrameDivisions`, which
+ * contains the output frame grid, so the frame-time instant never moves.
+ */
+ readonly subFrameDivisions: number;
+ /** Tick offsets from the frame instant, ascending. Integers, so every host agrees. */
+ readonly sampleTickOffsets: readonly number[];
+}
+
+export const MAX_SAMPLES_PER_FRAME = 64;
+
+const DEFAULT_SAMPLES_PER_FRAME = 16;
+const DEFAULT_SHUTTER_ANGLE = 180;
+const DEFAULT_SHUTTER_PHASE = -90;
+
+/**
+ * Ticks per output frame on the seek grid. Fine enough that the rounding error on a
+ * sample time is under 1/8192 of a frame, coarse enough to stay exactly representable.
+ */
+const SUB_FRAME_DIVISIONS = 4096;
+
+function finiteOr(value: number | undefined, fallback: number): number {
+ return Number.isFinite(value) ? (value as number) : fallback;
+}
+
+/** Resolve caller options into a plan, or null when motion blur is off. */
+export function resolveMotionBlurPlan(
+ options: MotionBlurOptions | undefined,
+): MotionBlurPlan | null {
+ if (!options) return null;
+
+ const samplesPerFrame = Math.min(
+ MAX_SAMPLES_PER_FRAME,
+ Math.max(1, Math.round(finiteOr(options.samplesPerFrame, DEFAULT_SAMPLES_PER_FRAME))),
+ );
+ const shutterAngle = finiteOr(options.shutterAngle, DEFAULT_SHUTTER_ANGLE);
+ const shutterPhase = finiteOr(options.shutterPhase, DEFAULT_SHUTTER_PHASE);
+ const blend: MotionBlurBlendSpace = options.blend === "linear" ? "linear" : "srgb";
+
+ const windowStartFrames = shutterPhase / 360;
+ const shutterFrames = shutterAngle / 360;
+ const sampleTickOffsets: number[] = [];
+ for (let k = 0; k < samplesPerFrame; k++) {
+ const offsetFrames = windowStartFrames + ((k + 0.5) / samplesPerFrame) * shutterFrames;
+ sampleTickOffsets.push(Math.round(offsetFrames * SUB_FRAME_DIVISIONS));
+ }
+
+ return { blend, subFrameDivisions: SUB_FRAME_DIVISIONS, sampleTickOffsets };
+}
+
+/**
+ * Absolute seek times for one output frame, in ascending order.
+ *
+ * Built from integer ticks rather than by adding floats to `frameIndex / fps`, so the
+ * page-side quantizer recovers the intended tick exactly on every host. Times before the
+ * composition start clamp to 0, which is what After Effects does at the first frame.
+ */
+export function motionBlurSampleTimes(
+ plan: MotionBlurPlan,
+ frameIndex: number,
+ fps: number,
+): number[] {
+ const grid = fps * plan.subFrameDivisions;
+ const frameTicks = frameIndex * plan.subFrameDivisions;
+ return plan.sampleTickOffsets.map((offset) => Math.max(0, frameTicks + offset) / grid);
+}
+
+const SRGB_TO_LINEAR = (() => {
+ const lut = new Float64Array(256);
+ for (let i = 0; i < 256; i++) lut[i] = srgbByteToLinear(i);
+ return lut;
+})();
+
+/**
+ * Identity table for the sRGB working space, so the accumulate loop is one shape for both
+ * spaces instead of two near-copies. Measured on a 1920x1080 frame at 16 samples, reading
+ * this table costs nothing against using the byte directly: the two variants time within
+ * each other's run-to-run noise.
+ */
+const SRGB_PASSTHROUGH = (() => {
+ const lut = new Float64Array(256);
+ for (let i = 0; i < 256; i++) lut[i] = i;
+ return lut;
+})();
+
+function linearToByte(value: number): number {
+ const c = value <= 0.0031308 ? value * 12.92 : 1.055 * Math.pow(value, 1 / 2.4) - 0.055;
+ return clampByte(c * 255);
+}
+
+function clampByte(value: number): number {
+ return Math.min(255, Math.max(0, Math.round(value)));
+}
+
+/**
+ * Running average of the sub-frame captures for one output frame.
+ *
+ * Samples are folded in as they arrive rather than held until the end, so peak memory is
+ * one accumulator plus one decoded sample regardless of K. Holding all K decoded frames
+ * would be (K + 1) * 8.3 MB at 1080p, which is 141 MB at the default 16 samples and
+ * 540 MB at the 64 maximum, thrown away and rebuilt on every frame of the render.
+ *
+ * Colour is summed premultiplied by alpha and un-premultiplied at the end, so a sample
+ * that is transparent at a pixel contributes no colour there. On opaque frames, the
+ * common case, that reduces to a plain mean.
+ */
+export class MotionBlurAccumulator {
+ private readonly toWorking: Float64Array;
+ private readonly fromWorking: (value: number) => number;
+ /** Premultiplied r, g, b and alpha sums per pixel. Null until the first sample sets the size. */
+ private sums: Float32Array | null = null;
+ private width = 0;
+ private height = 0;
+ private count = 0;
+
+ constructor(blend: MotionBlurBlendSpace) {
+ this.toWorking = blend === "linear" ? SRGB_TO_LINEAR : SRGB_PASSTHROUGH;
+ this.fromWorking = blend === "linear" ? linearToByte : clampByte;
+ }
+
+ /** Fold one captured sample PNG into the running average. */
+ add(png: Buffer): void {
+ const { width, height, data } = decodePng(png);
+ if (!this.sums) {
+ this.width = width;
+ this.height = height;
+ // float32 holds a 64-sample premultiplied sum (max 16320) far more precisely than
+ // the 1/255 quantum the result is rounded to.
+ this.sums = new Float32Array(width * height * 4);
+ } else if (width !== this.width || height !== this.height) {
+ throw new Error(
+ `MotionBlurAccumulator: sample geometry mismatch (${width}x${height} vs ${this.width}x${this.height})`,
+ );
+ }
+
+ const sums = this.sums;
+ const toWorking = this.toWorking;
+ for (let i = 0; i < sums.length; i += 4) {
+ const alpha = (data[i + 3] as number) / 255;
+ sums[i] = (sums[i] as number) + (toWorking[data[i] as number] as number) * alpha;
+ sums[i + 1] = (sums[i + 1] as number) + (toWorking[data[i + 1] as number] as number) * alpha;
+ sums[i + 2] = (sums[i + 2] as number) + (toWorking[data[i + 2] as number] as number) * alpha;
+ sums[i + 3] = (sums[i + 3] as number) + alpha;
+ }
+ this.count += 1;
+ }
+
+ /** Un-premultiply and encode the average. Throws if no sample was ever added. */
+ finish(): { width: number; height: number; data: Uint8Array } {
+ const sums = this.sums;
+ if (!sums) throw new Error("MotionBlurAccumulator: no samples");
+
+ const out = new Uint8Array(sums.length);
+ for (let i = 0; i < sums.length; i += 4) {
+ const alphaSum = sums[i + 3] as number;
+ out[i + 3] = clampByte((alphaSum / this.count) * 255);
+ if (alphaSum === 0) continue;
+ const scale = 1 / alphaSum;
+ out[i] = this.fromWorking((sums[i] as number) * scale);
+ out[i + 1] = this.fromWorking((sums[i + 1] as number) * scale);
+ out[i + 2] = this.fromWorking((sums[i + 2] as number) * scale);
+ }
+ return { width: this.width, height: this.height, data: out };
+ }
+}
diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.ts
index bd5214d860..f0844d0853 100644
--- a/packages/engine/src/types.ts
+++ b/packages/engine/src/types.ts
@@ -5,6 +5,7 @@
* as video must expose `window.__hf` implementing the HfProtocol interface.
*/
import type { Fps } from "@hyperframes/core";
+import type { MotionBlurOptions } from "./services/motionBlur.js";
/**
* Outcome of waiting for a sub-composition's GSAP timelines to register.
@@ -96,11 +97,23 @@ export interface HfTransitionMeta {
* GSAP, Framer Motion, CSS animations, Three.js — anything works as long
* as `seek()` produces deterministic visual output for a given time.
*/
+/**
+ * Per-seek controls the page honours. Both default off, which is an ordinary frame seek.
+ *
+ * `suppressEvents` stops a composition's own timeline callbacks from firing, and
+ * `subFrameDivisions` refines the grid the page quantizes onto so a fractional time is
+ * not floored back onto the output frame. Motion-blur sampling sets both.
+ */
+export interface HfSeekOptions {
+ suppressEvents?: boolean;
+ subFrameDivisions?: number;
+}
+
export interface HfProtocol {
/** Total duration of the composition in seconds */
duration: number;
/** Seek to a specific time. Must produce deterministic visual output. */
- seek(time: number): void;
+ seek(time: number, options?: HfSeekOptions): void;
/** Optional: media elements the engine should handle */
media?: HfMediaElement[];
/** Optional: shader transition metadata, populated by @hyperframes/shader-transitions */
@@ -130,6 +143,12 @@ export interface CaptureOptions {
fps: Fps;
format?: "jpeg" | "png";
quality?: number;
+ /**
+ * Opt into sub-frame multi-sample motion blur (issue #4010). Absent means off and the
+ * capture path is byte-identical to a render without it. Requires `format: "png"` and
+ * screenshot capture mode; see `services/motionBlur.ts`.
+ */
+ motionBlur?: MotionBlurOptions;
deviceScaleFactor?: number;
/**
* Opt into Chrome's capture-beyond-viewport screenshot path. Leave undefined
diff --git a/packages/engine/src/utils/alphaBlit.ts b/packages/engine/src/utils/alphaBlit.ts
index e8bf2e0eed..6b585eb653 100644
--- a/packages/engine/src/utils/alphaBlit.ts
+++ b/packages/engine/src/utils/alphaBlit.ts
@@ -5,7 +5,8 @@
* Uses only Node.js built-ins (zlib) — no additional dependencies.
*/
-import { inflateSync } from "zlib";
+import { deflateSync, inflateSync } from "zlib";
+import { chunkCrc32 } from "./crc32.js";
// ── PNG decoder ───────────────────────────────────────────────────────────────
@@ -181,6 +182,56 @@ export function decodePng(buf: Buffer): { width: number; height: number; data: U
return { width, height, data: output };
}
+// ── PNG encoder ──────────────────────────────────────────────────
+
+/**
+ * Intermediate frames are read once by the encoder and deleted, so encode speed matters
+ * and compression ratio does not. Measured on a 1920x1080 frame: level 1 takes 214 ms for
+ * 4.14 MiB against level 6's 293 ms for 3.98 MiB.
+ */
+const PNG_DEFLATE_LEVEL = 1;
+
+function pngChunk(type: string, body: Buffer): Buffer {
+ const header = Buffer.alloc(8);
+ header.writeUInt32BE(body.length, 0);
+ header.write(type, 4, "ascii");
+ const trailer = Buffer.alloc(4);
+ trailer.writeUInt32BE(chunkCrc32(type, body), 0);
+ return Buffer.concat([header, body, trailer]);
+}
+
+/**
+ * Encode 8-bit RGBA pixels as a PNG, the inverse of `decodePng`.
+ *
+ * Byte-identical for identical pixels: every scanline takes filter 0 and zlib runs at a
+ * fixed level, so a render that samples the same instant twice produces the same file.
+ */
+export function encodePng(width: number, height: number, rgba: Uint8Array): Buffer {
+ const expected = width * height * 4;
+ if (rgba.length !== expected) {
+ throw new Error(
+ `encodePng: expected ${expected} bytes for ${width}x${height}, got ${rgba.length}`,
+ );
+ }
+ const stride = width * 4;
+ const filtered = Buffer.alloc((stride + 1) * height);
+ for (let y = 0; y < height; y++) {
+ filtered[y * (stride + 1)] = 0;
+ filtered.set(rgba.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(width, 0);
+ ihdr.writeUInt32BE(height, 4);
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 6; // colour type RGBA
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ pngChunk("IHDR", ihdr),
+ pngChunk("IDAT", deflateSync(filtered, { level: PNG_DEFLATE_LEVEL })),
+ pngChunk("IEND", Buffer.alloc(0)),
+ ]);
+}
+
// ── 16-bit PNG decoder ────────────────────────────────────────────────────────
/**
@@ -249,6 +300,12 @@ export function decodePngToRgb48le(buf: Buffer): { width: number; height: number
* bt2020). For neutral/near-neutral content (text, UI) the gamut difference
* is negligible.
*/
+/** sRGB EOTF: an 8-bit signal value to linear light, 0 to 1 relative to SDR white. */
+export function srgbByteToLinear(value: number): number {
+ const v = value / 255;
+ return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
+}
+
function buildSrgbToSignalLut(transfer: "hlg" | "pq" | "srgb"): Uint16Array {
const lut = new Uint16Array(256);
@@ -272,9 +329,7 @@ function buildSrgbToSignalLut(transfer: "hlg" | "pq" | "srgb"): Uint16Array {
continue;
}
- // sRGB EOTF: signal → linear (range 0–1, relative to SDR white)
- const v = i / 255;
- const linear = v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
+ const linear = srgbByteToLinear(i);
let signal: number;
if (transfer === "hlg") {
diff --git a/packages/engine/src/utils/crc32.ts b/packages/engine/src/utils/crc32.ts
new file mode 100644
index 0000000000..42c6798ccc
--- /dev/null
+++ b/packages/engine/src/utils/crc32.ts
@@ -0,0 +1,36 @@
+/**
+ * PNG chunk CRC32, shared by the encoder and the metadata reader.
+ *
+ * node:zlib's crc32 is native and takes a running seed, so the chunk type and the chunk
+ * data can be CRC'd in sequence without concatenating them into a throwaway buffer:
+ * ~210 ms to ~1.3 ms on a 12 MiB PNG.
+ *
+ * It landed in Node 22.2.0, and this repo declares `"node": ">=22"` with a major-only
+ * runtime gate, so 22.0 and 22.1 are still supported. A NAMED import of a missing export
+ * throws at module evaluation, i.e. the importing module would fail to load at all on
+ * those, long before any PNG is touched, so the namespace import plus the capability
+ * check below is deliberate. Raising the floor to 22.2.0 instead would be a user-facing
+ * support change.
+ */
+import * as zlib from "node:zlib";
+
+const nativeCrc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : undefined;
+
+/** Bit-at-a-time fallback for Node 22.0/22.1. Correct, just slower. */
+function crc32Fallback(data: Buffer, seed: number): number {
+ let crc = seed ^ 0xffffffff;
+ for (let i = 0; i < data.length; i++) {
+ crc ^= data[i] ?? 0;
+ for (let bit = 0; bit < 8; bit++) {
+ const mask = -(crc & 1);
+ crc = (crc >>> 1) ^ (0xedb88320 & mask);
+ }
+ }
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+export function chunkCrc32(chunkType: string, chunkData: Buffer): number {
+ const typeBytes = Buffer.from(chunkType, "ascii");
+ if (nativeCrc32) return nativeCrc32(chunkData, nativeCrc32(typeBytes));
+ return crc32Fallback(chunkData, crc32Fallback(typeBytes, 0));
+}
diff --git a/packages/engine/src/utils/ffprobe.ts b/packages/engine/src/utils/ffprobe.ts
index c4358494e1..54b5f004cd 100644
--- a/packages/engine/src/utils/ffprobe.ts
+++ b/packages/engine/src/utils/ffprobe.ts
@@ -1,7 +1,7 @@
// fallow-ignore-file code-duplication complexity
import { spawn } from "child_process";
import { createReadStream, readFileSync, statSync } from "fs";
-import * as zlib from "node:zlib";
+import { chunkCrc32 } from "./crc32.js";
import { StringDecoder } from "node:string_decoder";
import { basename } from "path";
import { redactTelemetryString } from "@hyperframes/core";
@@ -468,38 +468,6 @@ export async function probeMediaProfile(
}
}
-// node:zlib's crc32 is native and takes a running seed, so the chunk type and
-// the chunk data can be CRC'd in sequence without concatenating them into a
-// throwaway buffer: ~210 ms -> ~1.3 ms on a 12 MiB PNG.
-//
-// It landed in Node 22.2.0, and this repo declares `"node": ">=22"` with a
-// major-only runtime gate, so 22.0 and 22.1 are still supported. A NAMED
-// import of a missing export throws at module evaluation — i.e. `ffprobe.ts`
-// would fail to load at all on those, long before any PNG is parsed — so the
-// namespace import plus this capability check is deliberate. Raising the
-// floor to 22.2.0 instead would be a user-facing support change, which does
-// not belong in a PNG bug fix.
-const nativeCrc32 = typeof zlib.crc32 === "function" ? zlib.crc32 : undefined;
-
-/** Bit-at-a-time fallback for Node 22.0/22.1. Correct, just slower. */
-function crc32Fallback(data: Buffer, seed: number): number {
- let crc = seed ^ 0xffffffff;
- for (let i = 0; i < data.length; i++) {
- crc ^= data[i] ?? 0;
- for (let bit = 0; bit < 8; bit++) {
- const mask = -(crc & 1);
- crc = (crc >>> 1) ^ (0xedb88320 & mask);
- }
- }
- return (crc ^ 0xffffffff) >>> 0;
-}
-
-function chunkCrc32(chunkType: string, chunkData: Buffer): number {
- const typeBytes = Buffer.from(chunkType, "ascii");
- if (nativeCrc32) return nativeCrc32(chunkData, nativeCrc32(typeBytes));
- return crc32Fallback(chunkData, crc32Fallback(typeBytes, 0));
-}
-
export function extractPngMetadataFromBuffer(buf: Buffer): StillImageMetadata | null {
if (
buf.length < 8 ||
diff --git a/packages/parsers/src/types.ts b/packages/parsers/src/types.ts
index f402726c2b..d6588ae977 100644
--- a/packages/parsers/src/types.ts
+++ b/packages/parsers/src/types.ts
@@ -437,7 +437,10 @@ export interface PlayerAPI {
ensureTimeline(): void;
enableRenderMode(): void;
disableRenderMode(): void;
- renderSeek(time: number, options?: { suppressEvents?: boolean }): void;
+ renderSeek(
+ time: number,
+ options?: { suppressEvents?: boolean; subFrameDivisions?: number },
+ ): void;
getElementVisibility(elementId: string): { visible: boolean; opacity?: number };
getVisibleElements(): Array<{ id: string; tagName: string; start: number; end: number }>;
getRenderState(): {