Skip to content

Commit d83f276

Browse files
perf(studio): films with thousands of timed clips stop re-reading every clip each frame (#6805)
* perf(studio): films with thousands of timed clips stop re-reading every clip each frame * perf(studio): drop the added comment lines the ratchet counts
1 parent b93c01c commit d83f276

5 files changed

Lines changed: 113 additions & 12 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// @vitest-environment happy-dom
2+
3+
import { afterEach, expect, it, vi } from "vitest";
4+
import { initSandboxRuntimeModular } from "./init";
5+
import { createMockTimeline, resetRuntimeFixtureDom } from "./runtimeSeekFixture.test-helpers";
6+
7+
afterEach(() => {
8+
window.__hfRuntimeTeardown?.();
9+
vi.restoreAllMocks();
10+
resetRuntimeFixtureDom();
11+
});
12+
13+
it("reads a far clip's start once while playing, not on every frame", () => {
14+
resetRuntimeFixtureDom();
15+
let now = 0;
16+
let id = 0;
17+
const callbacks = new Map<number, FrameRequestCallback>();
18+
vi.spyOn(performance, "now").mockImplementation(() => now);
19+
vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
20+
callbacks.set(++id, callback);
21+
return id;
22+
});
23+
vi.spyOn(window, "cancelAnimationFrame").mockImplementation((key) => {
24+
callbacks.delete(key);
25+
});
26+
const step = (frames: number) => {
27+
for (let i = 0; i < frames; i++) {
28+
now += 33;
29+
const pending = [...callbacks.values()];
30+
callbacks.clear();
31+
for (const callback of pending) callback(now);
32+
}
33+
};
34+
const words = Array.from(
35+
{ length: 300 },
36+
(_, i) => `<span id="w${i}" class="clip" data-start="${5 + i * 0.1}" data-duration="1"></span>`,
37+
);
38+
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-duration="60">${words.join("")}</div>`;
39+
window.__timelines = { main: createMockTimeline(60) };
40+
initSandboxRuntimeModular();
41+
const player = window.__player!;
42+
const far = document.getElementById("w299")!;
43+
const startReads = vi.fn();
44+
const getAttribute = far.getAttribute.bind(far);
45+
far.getAttribute = (name: string) => {
46+
if (name === "data-start") startReads();
47+
return getAttribute(name);
48+
};
49+
50+
player.play();
51+
step(5);
52+
const afterWarmUp = startReads.mock.calls.length;
53+
step(60);
54+
55+
expect(player.isPlaying()).toBe(true);
56+
expect(startReads.mock.calls.length - afterWarmUp).toBe(0);
57+
});

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2948,12 +2948,23 @@ export function initSandboxRuntimeModular(): void {
29482948
// A clip's first visible style pass is slow; playing, each hidden clip gets it once just before its start.
29492949
const clipsNeverStyledVisible = new Set<StylableElement>();
29502950
const clipsStyledVisible = new WeakSet<Element>();
2951-
const styleClipsDueVisibleOnce = (t: number) => {
2951+
let neverStyledStarts = { revision: -1, starts: new Map<StylableElement, number>() };
2952+
const neverStyledStart = (el: StylableElement, revision: number): number => {
2953+
if (neverStyledStarts.revision !== revision)
2954+
neverStyledStarts = { revision, starts: new Map() };
2955+
let start = neverStyledStarts.starts.get(el);
2956+
if (start === undefined) {
2957+
start = resolveStartForElement(el, Number.NaN);
2958+
neverStyledStarts.starts.set(el, start);
2959+
}
2960+
return start;
2961+
};
2962+
const styleClipsDueVisibleOnce = (t: number, revision: number) => {
29522963
if (clipsNeverStyledVisible.size === 0 || !clock.isPlaying()) return;
29532964
const clips: StylableElement[] = [];
29542965
for (const el of clipsNeverStyledVisible) {
2955-
const start = resolveStartForElement(el, Number.NaN);
2956-
if (el.isConnected && el.hasAttribute(CLIP_HIDDEN_ATTR) && !(start <= t + LOOKAHEAD_SECONDS))
2966+
const start = neverStyledStart(el, revision);
2967+
if (!(start <= t + LOOKAHEAD_SECONDS) && el.isConnected && el.hasAttribute(CLIP_HIDDEN_ATTR))
29572968
continue;
29582969
clipsNeverStyledVisible.delete(el);
29592970
if (el.isConnected && el.hasAttribute(CLIP_HIDDEN_ATTR) && start > t) clips.push(el);
@@ -5290,7 +5301,7 @@ export function initSandboxRuntimeModular(): void {
52905301
const revision = opts?.revision ?? readCompositionTimingRevision();
52915302
if (revision !== tweensRenderedThrough.revision)
52925303
tweensRenderedThrough = { revision, time: Number.NEGATIVE_INFINITY };
5293-
styleClipsDueVisibleOnce(t);
5304+
styleClipsDueVisibleOnce(t, revision);
52945305
const firstRenders = t > tweensRenderedThrough.time;
52955306
// Only clips holding a tween that renders for the first time on this seek need their authored style read.
52965307
const firstRendered =

‎packages/studio/src/player/hooks/timelineDomBinding.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,24 @@ describe("live DOM manifest hydration", () => {
167167
expect(findTimelineDomNodeForClip(doc, clip({ start: 9 }), 0)?.id).toBe("stable");
168168
});
169169
});
170+
171+
describe("selector occurrence indexes while hydrating many clips", () => {
172+
it("queries the document once for a class many clips share, not once per clip", () => {
173+
const count = 200;
174+
const spans = Array.from(
175+
{ length: count },
176+
(_, i) =>
177+
`<span class="clip w" data-start="${i}" data-duration="1" data-track-index="0"></span>`,
178+
).join("");
179+
const doc = documentWith(spans);
180+
const query = vi.spyOn(doc, "querySelectorAll");
181+
const clips = Array.from({ length: count }, (_, i) => clip({ tagName: "span", start: i }));
182+
183+
const elements = buildTimelineElementsFromClips(clips, doc);
184+
185+
expect(elements).toHaveLength(count);
186+
expect(query.mock.calls.filter(([selector]) => selector === ".w").length).toBeLessThanOrEqual(
187+
1,
188+
);
189+
});
190+
});

‎packages/studio/src/player/hooks/timelineSyncHydration.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
* an argument, so each is callable — and readable — on its own.
1010
*/
1111

12+
import { withSelectorIndexPass } from "../../utils/sourceScopedSelectorIndex";
1213
import { createTimelineDomNodeResolver, findClipElementById } from "../lib/timelineElementHelpers";
1314
import { usePlayerStore } from "../store/playerStore";
1415
import type { TimelineElement, DomClipChild, SubCompositionHostState } from "../store/playerStore";
@@ -214,15 +215,17 @@ export function buildTimelineElementsFromClips(
214215
iframeDoc: Document | null,
215216
): TimelineElement[] {
216217
const resolveHost = iframeDoc ? createTimelineDomNodeResolver(iframeDoc) : null;
217-
return clips.map((clip, index) => {
218-
const hostEl = resolveHost?.(clip, index) ?? null;
219-
return createTimelineElementFromManifestClip({
220-
clip,
221-
fallbackIndex: index,
222-
doc: iframeDoc,
223-
hostEl,
218+
const build = () =>
219+
clips.map((clip, index) => {
220+
const hostEl = resolveHost?.(clip, index) ?? null;
221+
return createTimelineElementFromManifestClip({
222+
clip,
223+
fallbackIndex: index,
224+
doc: iframeDoc,
225+
hostEl,
226+
});
224227
});
225-
});
228+
return iframeDoc ? withSelectorIndexPass(iframeDoc, build) : build();
226229
}
227230

228231
/**

‎packages/studio/src/player/lib/timelineDOM.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import type { TimelineElement } from "../store/playerStore";
1212
import type { ClipManifestClip, IframeWindow, TimelineLike } from "./playbackTypes";
13+
import { withSelectorIndexPass } from "../../utils/sourceScopedSelectorIndex";
1314
import { resolveCssStackingContextId } from "@hyperframes/core/runtime/stacking-context";
1415
import { readClipTiming } from "@hyperframes/core/composition-contract";
1516
import { readMasterFxChain } from "@hyperframes/core/audio-groups";
@@ -234,6 +235,14 @@ export function parseTimelineFromDOM(
234235
doc: Document,
235236
rootDuration: number,
236237
timelines?: Readonly<Record<string, TimelineLike>>,
238+
): TimelineElement[] {
239+
return withSelectorIndexPass(doc, () => scanTimelineFromDOM(doc, rootDuration, timelines));
240+
}
241+
242+
function scanTimelineFromDOM(
243+
doc: Document,
244+
rootDuration: number,
245+
timelines?: Readonly<Record<string, TimelineLike>>,
237246
): TimelineElement[] {
238247
const rootComp = doc.querySelector("[data-composition-id]");
239248
const nodes = doc.querySelectorAll("[data-start]");

0 commit comments

Comments
 (0)