Skip to content

Commit 2be8a62

Browse files
fix(engine): stop compositing phantom duplicates on captureBeyondViewport (#2607)
* fix(core): stop the async media-metadata rebind once render capture starts seeking scheduleMetadataDurationHydration re-resolves and can swap the captured GSAP timeline off a debounced loadedmetadata/durationchange event, fully uncoordinated with the producer's own per-frame renderSeek calls. When a full-length <video>'s metadata resolves after capture has already begun (slow I/O, Docker), this races the deterministic BeginFrame capture loop and can reflow sub-composition state mid-render, producing phase-offset duplicate content in captured frames (#2550). Render-mode duration correction already happens deterministically during the probe stage before capture starts, so once renderSeek has been called once there is nothing left for this self-correction to do — gate it off for the rest of the session. * fix(core): scope the metadata-rebind guard to actual render/export pages renderSeek isn't capture-exclusive — Studio's own preview iframe falls back to it for compositions whose timeline overhangs every native adapter's duration. Gating the HF#2550 fix on renderCaptureSeekStarted alone silently disabled the metadata-driven duration self-correction for that live-scrub case too, where it's still needed. Require the render/ export page signal (window.__HF_EXPORT_RENDER_SEEK_CONFIG, set only by the producer's fileServer.ts) alongside it, and add a regression test covering the Studio-preview case. * fix(engine): stop requesting beyond-viewport capture for video comps that don't need it Root-caused HF#2550 by reproducing the reporter's public repro end-to-end (not just the timeline-rebind mechanism from the earlier commits in this branch) on native Linux: instrumented the actual DOM state during a real capture session and confirmed the sub-composition never double-mounts — getBoundingClientRect and the timeline's own local time both match the single, correct DOM tree throughout. The phantom second copy only exists in the captured screenshot pixels. Bisected it to captureBeyondViewport: resolveVideoCaptureBeyondViewport (#1094's tall-portrait fix) forces `Page.captureScreenshot`'s beyond-viewport path on for any render with a native <video>, regardless of whether the page's content actually overflows the declared capture height. On SwiftShader that beyond-viewport path can composite a stale, vertically offset paint of the page alongside the fresh one for content that fits entirely within the viewport — producing exactly the reported phase-offset duplicate. Disabling captureBeyondViewport (repro's video still present) eliminates the duplicate outright; re-enabling it reproduces the duplicate byte-for-byte, isolating it as the actual cause. Adds pageContentExceedsCaptureHeight, a ground-truth measurement of the page's actual scrollHeight against the requested capture height, and wires it into initializeSession to downgrade captureBeyondViewport back to false once the page is settled and it's confirmed unnecessary — the "reliable clip predictor" the original #1094 fix's ponytail comment flagged as missing. This keeps #1094's fix intact for content that genuinely overflows while closing the SwiftShader ghosting hazard for the (common) case of video that fits inside its own viewport. * test(producer): add HF#2550 video+sub-composition regression fixture Checks in the reporter's confirmed real-world reproduction (media regenerated via ffmpeg testsrc2, matching their public repro repo) as a regression fixture, with a golden baseline rendered against the fix. Verified end-to-end via the project's own Docker regression harness: - Rendering this fixture with the fix produces the golden baseline (clean, single flowchart instance, captureBeyondViewport correctly downgraded). - Direct CLI renders (not through this harness) against unpatched code reproduce the reported phantom-duplicate artifact reliably (10/10). Caveat documented in meta.json: the underlying bug is timing-dependent. Two harness runs against unpatched code, using this same fixture, did not reproduce the artifact (0/2) — the harness's in-process render path apparently doesn't hit the same race window a direct CLI process does on this host. This fixture is a best-effort regression guard and a preserved real-world repro, not the sole protection — the deterministic guard is packages/engine/src/services/screenshotService.test.ts's pageContentExceedsCaptureHeight unit tests, which exercise the actual fix logic directly. Also adds an .gitattributes LFS rule for this fixture's source index.html (744 KB — carries the real project's embedded base64 assets, over the largefiles hook's 500 KB non-LFS limit). * fix: route HF#2550 fixture binaries through LFS (were committed raw) filter.lfs.clean/smudge were locally configured as a no-op "cat" in this repo's shared .git/config, silently disabling LFS filtering for every worktree. The previous commit's large binaries (output.mp4, compiled.html, source index.html, source video) landed as raw blobs instead of LFS pointers as a result. Ran `git lfs install --local --force` to restore the correct filter commands, then re-staged the affected files so they commit as proper LFS pointers. * fix(engine): address capture viewport review feedback
1 parent 8bfc676 commit 2be8a62

15 files changed

Lines changed: 1100 additions & 6 deletions

File tree

‎.gitattributes‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ packages/producer/tests/**/*.webm filter=lfs diff=lfs merge=lfs -text
1717
packages/producer/tests/**/*.png filter=lfs diff=lfs merge=lfs -text
1818
packages/producer/tests/**/output/compiled.html filter=lfs diff=lfs merge=lfs -text
1919

20+
# HF#2550 fixture's source index.html carries the real-world project's
21+
# embedded base64 assets (744 KB) — over the largefiles hook's 500 KB
22+
# non-LFS limit. Scoped to this one file, not a broad tests/**/*.html
23+
# pattern, since every other fixture's source HTML is small plain git.
24+
packages/producer/tests/hf2550-video-subcomposition-ghost/src/index.html filter=lfs diff=lfs merge=lfs -text
25+
2026
# ONNX models must ALWAYS use LFS regardless of location: a 31 MB ppmattingv2
2127
# model was once committed raw into skills/ then deleted — but a raw commit
2228
# lives in history forever. No path in the repo legitimately ships a raw .onnx.

‎packages/core/src/runtime/init.test.ts‎

Lines changed: 119 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,18 @@ function createMockTimeline(duration: number): RuntimeTimelineLike {
3737

3838
function createPaddableMockTimeline(duration: number): RuntimeTimelineLike {
3939
const timeline = createMockTimeline(duration) as RuntimeTimelineLike & {
40-
to: (_target: object, vars: { duration: number }, position: number) => void;
40+
to: (_target: object, vars: { duration: number }, position?: number) => void;
4141
};
4242
const baseDuration = timeline.duration;
4343
let paddedDuration = baseDuration();
4444
timeline.duration = () => paddedDuration;
45+
// Mirrors GSAP: an omitted position appends sequentially at the current end.
4546
timeline.to = (_target, vars, position) => {
46-
paddedDuration = Math.max(paddedDuration, position + Math.max(0, Number(vars.duration) || 0));
47+
const resolvedPosition = position ?? paddedDuration;
48+
paddedDuration = Math.max(
49+
paddedDuration,
50+
resolvedPosition + Math.max(0, Number(vars.duration) || 0),
51+
);
4752
};
4853
return timeline;
4954
}
@@ -1391,6 +1396,118 @@ describe("initSandboxRuntimeModular", () => {
13911396
},
13921397
);
13931398

1399+
it("ignores the async media-metadata duration rebind once render capture has started seeking frames (regression HF#2550)", async () => {
1400+
const root = document.createElement("div");
1401+
root.setAttribute("data-composition-id", "main");
1402+
root.setAttribute("data-root", "true");
1403+
root.setAttribute("data-start", "0");
1404+
root.setAttribute("data-width", "1920");
1405+
root.setAttribute("data-height", "1080");
1406+
document.body.appendChild(root);
1407+
1408+
const video = document.createElement("video");
1409+
video.setAttribute("data-start", "0");
1410+
document.body.appendChild(video);
1411+
1412+
// A root timeline with no usable duration yet — mirrors a composition
1413+
// whose length is derived from a full-length <video> that hasn't reported
1414+
// its metadata. window.gsap is needed because resolveRootTimelineFromDocument
1415+
// builds a fresh duration-floor wrapper timeline via gsap.timeline().
1416+
(
1417+
window as unknown as {
1418+
gsap?: { timeline: () => ReturnType<typeof createPaddableMockTimeline> };
1419+
}
1420+
).gsap = {
1421+
timeline: () => createPaddableMockTimeline(0),
1422+
};
1423+
window.__timelines = { main: createMockTimeline(0) };
1424+
// Only a real producer render/export page sets this (fileServer.ts's
1425+
// pre-head script) — required alongside renderCaptureSeekStarted so the
1426+
// gate doesn't also disable Studio's own preview-iframe rebind.
1427+
window.__HF_EXPORT_RENDER_SEEK_CONFIG = { fps: 30, fpsSource: "default" };
1428+
1429+
const postMessageSpy = vi.spyOn(window, "postMessage");
1430+
1431+
try {
1432+
initSandboxRuntimeModular();
1433+
1434+
// The render/producer capture protocol has claimed the timeline and is
1435+
// now driving frames deterministically (mirrors the engine's
1436+
// window.__hf.seek(t) -> player.renderSeek(t) bridge).
1437+
window.__player?.renderSeek(0);
1438+
1439+
// Let the runtime's own deferred re-bind attempt (init.ts's
1440+
// `setTimeout(() => maybePublishRenderReady(), 0)`, unrelated to media
1441+
// metadata) settle first, so only the metadata path below is under test.
1442+
await new Promise((resolve) => setTimeout(resolve, 10));
1443+
1444+
// Video metadata resolves late — after capture has started, the exact
1445+
// HF#2550 race (Docker/slow-I/O environments hit this; fast native
1446+
// environments resolve metadata before capture begins and never do).
1447+
Object.defineProperty(video, "duration", { value: 12, configurable: true });
1448+
video.dispatchEvent(new Event("loadedmetadata"));
1449+
1450+
// Clears init.ts's internal METADATA_REBIND_DEBOUNCE_MS (100ms, not exported).
1451+
await new Promise((resolve) => setTimeout(resolve, 150));
1452+
1453+
const rebindMessages = postMessageSpy.mock.calls
1454+
.map(([message]) => message as { code?: string } | undefined)
1455+
.filter((message) => message?.code === "timeline_rebind_after_media_metadata");
1456+
expect(rebindMessages).toHaveLength(0);
1457+
} finally {
1458+
delete (window as { gsap?: unknown }).gsap;
1459+
}
1460+
});
1461+
1462+
it("still applies the media-metadata duration rebind after renderSeek in Studio preview (no export render-seek config)", async () => {
1463+
const root = document.createElement("div");
1464+
root.setAttribute("data-composition-id", "main");
1465+
root.setAttribute("data-root", "true");
1466+
root.setAttribute("data-start", "0");
1467+
root.setAttribute("data-width", "1920");
1468+
root.setAttribute("data-height", "1080");
1469+
document.body.appendChild(root);
1470+
1471+
const video = document.createElement("video");
1472+
video.setAttribute("data-start", "0");
1473+
document.body.appendChild(video);
1474+
1475+
(
1476+
window as unknown as {
1477+
gsap?: { timeline: () => ReturnType<typeof createPaddableMockTimeline> };
1478+
}
1479+
).gsap = {
1480+
timeline: () => createPaddableMockTimeline(0),
1481+
};
1482+
window.__timelines = { main: createMockTimeline(0) };
1483+
// No window.__HF_EXPORT_RENDER_SEEK_CONFIG here — Studio's preview iframe
1484+
// never sets it, and useTimelinePlayer's overhang fallback drives
1485+
// renderSeek there too. The rebind must still fire for this case.
1486+
1487+
const postMessageSpy = vi.spyOn(window, "postMessage");
1488+
1489+
try {
1490+
initSandboxRuntimeModular();
1491+
1492+
window.__player?.renderSeek(0);
1493+
1494+
await new Promise((resolve) => setTimeout(resolve, 10));
1495+
1496+
Object.defineProperty(video, "duration", { value: 12, configurable: true });
1497+
video.dispatchEvent(new Event("loadedmetadata"));
1498+
1499+
// Clears init.ts's internal METADATA_REBIND_DEBOUNCE_MS (100ms, not exported).
1500+
await new Promise((resolve) => setTimeout(resolve, 150));
1501+
1502+
const rebindMessages = postMessageSpy.mock.calls
1503+
.map(([message]) => message as { code?: string } | undefined)
1504+
.filter((message) => message?.code === "timeline_rebind_after_media_metadata");
1505+
expect(rebindMessages).toHaveLength(1);
1506+
} finally {
1507+
delete (window as { gsap?: unknown }).gsap;
1508+
}
1509+
});
1510+
13941511
it("sets __renderReady only after timeline is bound, not at __playerReady time", async () => {
13951512
const root = document.createElement("div");
13961513
root.setAttribute("data-composition-id", "main");

‎packages/core/src/runtime/init.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1593,6 +1593,12 @@ export function initSandboxRuntimeModular(): void {
15931593

15941594
let metadataRebindDebounceTimerId: number | null = null;
15951595
let metadataRebindApplied = false;
1596+
// Flips true on the first renderSeek call — the render/producer capture
1597+
// protocol's signal that it has started deterministically driving frames.
1598+
// One-way for this page lifetime; every producer render gets a fresh runtime.
1599+
// See scheduleMetadataDurationHydration for why this gates the async
1600+
// metadata rebind off once set.
1601+
let renderCaptureSeekStarted = false;
15961602
const metadataBoundMedia = new Set<HTMLMediaElement>();
15971603
const volumeKeyframeCache = new WeakMap<HTMLMediaElement, VolumeKeyframe[]>();
15981604

@@ -1604,6 +1610,23 @@ export function initSandboxRuntimeModular(): void {
16041610
metadataRebindDebounceTimerId = window.setTimeout(() => {
16051611
if (state.tornDown) return;
16061612
metadataRebindDebounceTimerId = null;
1613+
// The render/producer capture protocol drives frames deterministically
1614+
// via renderSeek — once it has claimed the timeline, an async
1615+
// loadedmetadata/durationchange rebind racing that loop is exactly the
1616+
// "double composite" hazard from HF#2550: this handler runs off its own
1617+
// debounced browser-side timer, uncoordinated with the capture loop's
1618+
// own seeks, so a rebind mid-capture can reflow the DOM between one
1619+
// BeginFrame call and the next. Render-mode duration correction has
1620+
// already happened deterministically during the probe stage before
1621+
// capture starts, so once frames are being driven there is nothing left
1622+
// for this self-correction to usefully do.
1623+
//
1624+
// renderSeek is also the entrypoint Studio's own preview iframe falls
1625+
// back to for overhanging timelines (useTimelinePlayer), so gate on
1626+
// both signals — renderCaptureSeekStarted alone would silently disable
1627+
// this self-correction for a live Studio scrub too, where duration
1628+
// hasn't been pre-resolved by a probe stage and still needs it.
1629+
if (renderCaptureSeekStarted && window.__HF_EXPORT_RENDER_SEEK_CONFIG) return;
16071630
const resolution = resolveRootTimelineFromDocument();
16081631
if (!resolution.timeline) return;
16091632
const hasResolvedMediaFloor = isUsableTimelineDuration(
@@ -2254,6 +2277,7 @@ export function initSandboxRuntimeModular(): void {
22542277
postState(true);
22552278
},
22562279
renderSeek: (timeSeconds, options) => {
2280+
renderCaptureSeekStarted = true;
22572281
const quantized = quantizeTimeToFrame(
22582282
Math.max(0, Number(timeSeconds) || 0),
22592283
state.canonicalFps,

‎packages/engine/src/services/frameCapture.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
beginFrameCapture,
2929
ensureRenderFrameSiblings,
3030
getCdpSession,
31+
pageContentExceedsCaptureHeight,
3132
pageScreenshotCapture,
3233
initTransparentBackground,
3334
shouldDefaultCaptureBeyondViewport,
@@ -2004,6 +2005,23 @@ export async function initializeSession(session: CaptureSession): Promise<void>
20042005

20052006
await recordSessionInitTelemetry(session, initStart);
20062007

2008+
// Ground-truth-check the upstream captureBeyondViewport request (see
2009+
// pageContentExceedsCaptureHeight) now that the page is fully settled —
2010+
// downgrade it when the page doesn't actually overflow the requested
2011+
// capture height, since the beyond-viewport CDP path is otherwise pure
2012+
// downside (HF#2550: phantom duplicate content on SwiftShader) for
2013+
// content it was never needed for.
2014+
if (session.options.captureBeyondViewport) {
2015+
const needsBeyondViewport = await pageContentExceedsCaptureHeight(
2016+
page,
2017+
session.options.height,
2018+
);
2019+
if (!needsBeyondViewport) {
2020+
session.options.captureBeyondViewport = false;
2021+
logInitPhase("captureBeyondViewport downgraded: page content fits the capture viewport");
2022+
}
2023+
}
2024+
20072025
// drawElement or transparent-background init — runs after page is fully ready.
20082026
await initDrawElementOrTransparentBackground(session, page, logInitPhase);
20092027

‎packages/engine/src/services/screenshotService.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { parseHTML } from "linkedom";
55
import { type Page } from "puppeteer-core";
66
import {
77
pageScreenshotCapture,
8+
pageContentExceedsCaptureHeight,
89
cdpSessionCache,
910
ensureRenderFrameSiblings,
1011
applyDomLayerMask,
@@ -143,6 +144,37 @@ describe("shouldDefaultCaptureBeyondViewport", () => {
143144
});
144145
});
145146

147+
describe("pageContentExceedsCaptureHeight", () => {
148+
function makeFakePageWithScrollHeight(scrollHeight: number): Page {
149+
return { evaluate: vi.fn().mockResolvedValue(scrollHeight) } as unknown as Page;
150+
}
151+
152+
it("is false when the page fits exactly within the requested height", async () => {
153+
const page = makeFakePageWithScrollHeight(1920);
154+
await expect(pageContentExceedsCaptureHeight(page, 1920)).resolves.toBe(false);
155+
});
156+
157+
it("tolerates subpixel rounding just past the requested height", async () => {
158+
const page = makeFakePageWithScrollHeight(1920.5);
159+
await expect(pageContentExceedsCaptureHeight(page, 1920)).resolves.toBe(false);
160+
});
161+
162+
it("tolerates exactly one CSS pixel past the requested height", async () => {
163+
const page = makeFakePageWithScrollHeight(1921);
164+
await expect(pageContentExceedsCaptureHeight(page, 1920)).resolves.toBe(false);
165+
});
166+
167+
it("detects content just beyond the rounding tolerance", async () => {
168+
const page = makeFakePageWithScrollHeight(1922);
169+
await expect(pageContentExceedsCaptureHeight(page, 1920)).resolves.toBe(true);
170+
});
171+
172+
it("is true when the page genuinely overflows the requested height", async () => {
173+
const page = makeFakePageWithScrollHeight(2007);
174+
await expect(pageContentExceedsCaptureHeight(page, 1920)).resolves.toBe(true);
175+
});
176+
});
177+
146178
describe("injectVideoFramesBatch replacement layout", () => {
147179
it("does not copy opposing inset constraints onto the injected frame image", async () => {
148180
const { window, document } = parseHTML(

‎packages/engine/src/services/screenshotService.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,30 @@ export async function beginFrameCapture(
182182
};
183183
}
184184

185+
/**
186+
* True if the page's actual rendered content is taller than the requested
187+
* capture height. `captureBeyondViewport` exists for exactly one reason
188+
* (#1094): a native `<video>` surface whose content genuinely overflows the
189+
* viewport-bound capture path clips its bottom edge to black. A video that
190+
* fits entirely inside its composition's declared viewport doesn't have that
191+
* problem — ground-truth measurement beats the coarser "has a video, so
192+
* always request beyond-viewport" heuristic, which also unnecessarily routes
193+
* every video render through a CDP capture path prone to producing phantom
194+
* duplicate content on SwiftShader (#2550).
195+
*
196+
* Callers measure once after page settle. Hyperframes compositions have a
197+
* fixed-height, overflow-clipped render surface; timeline animation may move
198+
* pixels within that surface but must not grow document flow during capture.
199+
*/
200+
export async function pageContentExceedsCaptureHeight(
201+
page: Page,
202+
requestedHeight: number,
203+
): Promise<boolean> {
204+
const scrollHeight = await page.evaluate(() => document.documentElement.scrollHeight);
205+
// Small tolerance for subpixel layout rounding, not a real overflow signal.
206+
return scrollHeight > requestedHeight + 1;
207+
}
208+
185209
/**
186210
* Capture a screenshot using standard Page.captureScreenshot CDP call.
187211
* Fallback for environments where BeginFrame is unavailable (macOS, Windows).

‎packages/producer/src/services/render/captureBeyondViewport.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@
1212
* over the software perf optimization: enable beyond-viewport for any render
1313
* that has a native video surface, regardless of GPU mode.
1414
*
15-
* ponytail: blanket-on for video. If the software re-raster tax proves
16-
* significant on the distributed fleet, narrow it back to comps whose content
17-
* actually reaches the bottom edge — but that needs a reliable clip predictor
18-
* first, and a black band is unshippable in the meantime.
15+
* This is a candidate, not a final decision: the engine downgrades it back to
16+
* `false` once the page is loaded and `pageContentExceedsCaptureHeight`
17+
* (screenshotService.ts) measures that the content doesn't actually overflow
18+
* the requested capture height — the "reliable clip predictor" this used to
19+
* lack. That measurement matters beyond the software re-raster tax: on
20+
* SwiftShader, requesting beyond-viewport for content that doesn't need it
21+
* can produce phantom duplicate content in the captured frame (HF#2550).
1922
*/
2023
export function resolveVideoCaptureBeyondViewport(videoCount: number): boolean | undefined {
2124
if (videoCount <= 0) return undefined;
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"name": "HF#2550: video + sub-composition phantom duplicate on captureBeyondViewport",
3+
"description": "Regression for HF#2550: a full-length <video> forced captureBeyondViewport on for every render (resolveVideoCaptureBeyondViewport), regardless of whether the page actually needed it. On SwiftShader, requesting beyond-viewport capture for content that fits entirely within the viewport could composite a stale, vertically-offset paint of the page alongside the fresh one — visible here as a phantom second copy of the flowchart-vertical sub-composition around t=11.3-14.3s. Fixed by pageContentExceedsCaptureHeight downgrading captureBeyondViewport back to false once the page is confirmed not to overflow the requested capture height. Caveat: the underlying bug is timing-dependent — it reproduced reliably (10/10) via a direct CLI render on the same host, but did NOT reproduce (0/2) when run through this harness's in-process mode on unpatched code. Keep this fixture as documentation of a confirmed real-world repro and a best-effort guard, not the sole regression protection — packages/engine/src/services/screenshotService.test.ts's pageContentExceedsCaptureHeight tests are the deterministic guard for the actual fix logic.",
4+
"tags": ["video", "sub-composition", "regression", "slow"],
5+
"minPsnr": 30,
6+
"maxFrameFailures": 0,
7+
"minAudioCorrelation": 0,
8+
"maxAudioLagWindows": 1,
9+
"renderConfig": {
10+
"fps": 30,
11+
"workers": 1
12+
}
13+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
version https://git-lfs.github.com/spec/v1
2+
oid sha256:26bfa531f6a7b4a31ad6e99e838f743b552d3b3c7c461a7c3f7b9c85d02d27cf
3+
size 1129788
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
version https://git-lfs.github.com/spec/v1
2+
oid sha256:697405f1eaa0f52dbe265d4c2a7674d70d18a05072a14921ded5c3237d377d1c
3+
size 67061526

0 commit comments

Comments
 (0)