Skip to content

Commit 3ea2f90

Browse files
perf(runtime): reuse one timing resolver per pass and derive duration only when the composition changes (#3824)
* perf(runtime): reuse one timing resolver per synchronous pass `createRuntimeStartTimeResolver` memoizes element start and duration lookups in WeakMaps, but `resolveStartForElement` and `resolveDurationForElement` each constructed a brand-new resolver per call and discarded it. The caches never served a second lookup, so a single pass re-walked the composition ancestry of every element, and per-seek work scaled with total timeline content rather than with what changed. `withTimingResolver(fn)` installs one resolver for the duration of a synchronous callback and restores the previous one in a `finally`, so a throw cannot leak the scope. Callers outside a scope keep today's construct-per-call behaviour unchanged. Three separate scopes, deliberately not one: - the media-cache build in `syncMediaForCurrentState` - the body of `syncTimedElementVisibility` - the media scan in `resolveMediaWindowDurationSeconds` They must stay separate. `syncRuntimeMedia` calls `el.load()` on the seek-past-buffered-range retry, which synchronously resets `el.duration` to NaN, and `resolveDurationForElement` reads `element.duration`. A cache spanning that write would serve the pre-`load()` duration to a post-`load()` read. Splitting at the write makes the staleness unrepresentable instead of merely handled. The third scope sits on `resolveMediaWindowDurationSeconds` rather than its caller `getSafeTimelineDurationSeconds`, which would look like the tidier boundary: that caller also invokes author-supplied `timeline.duration()` and third-party adapter `getInferredDurationSeconds()`, and foreign code inside a cache scope can mutate the DOM between two resolves. Resolver constructions per seek plus transport tick go from 15 per media element to a flat 4, and self time in `resolveStartForElementInternal` falls about 70% on a 79-video composition. * perf(runtime): derive composition duration only when the composition changes The runtime re-derived the composition's total duration on every animation frame. transportTick called getSafeTimelineDurationSeconds unconditionally, and deriving it scans every media element in the document and walks each one's composition ancestry to resolve an absolute start and duration. That value is a function of the composition, not of the playhead, so a paused editor with nothing happening recomputed the same answer ~60 times a second. On a 91-media-element composition the media scan ran 1.05 times per frame while the editor sat idle and untouched. Derive it once and reuse it until an input could have changed. The inputs, and the signal that catches each: - timing attributes edited (live editing, variables re-applied, the runtime's own autostamping) -> MutationObserver with an attribute filter - timed elements added or removed, including nested compositions that mount asynchronously after init -> the same observer, childList+subtree - media metadata arriving, or el.load() resetting duration to NaN, neither of which mutates the DOM -> capture-phase media event listeners - a timeline registered or lengthened in window.__timelines, a plain object nothing can observe -> a registry signature compared on read Observer records are delivered in a microtask, so the queue is drained on read as well; otherwise an edit read back in the same synchronous block, the ordinary live-editing case, would be served the pre-edit value. The render path does not read the cache at all. Capture depends on the exact duration and a frame rendered against a wrong one cannot be recovered, so it pays the full derivation on every frame exactly as before. Measured on the 91-media-element composition, idle and untouched: media scans per frame 1.05 -> 0.05. Across 100 single-frame seeks: 2.28 -> 0.11 per seek, so seeking does not invalidate the cache either. The residual is a separate per-20-tick caller in timeline.ts, untouched here.
1 parent 0665249 commit 3ea2f90

3 files changed

Lines changed: 679 additions & 75 deletions

File tree

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

Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3674,3 +3674,270 @@ describe("initSandboxRuntimeModular", () => {
36743674
});
36753675
});
36763676
});
3677+
3678+
/**
3679+
* The derived duration floor is a function of the composition, not of the
3680+
* playhead — yet transportTick asked for it on every animation frame, which
3681+
* made a paused, untouched editor scan every media element ~60 times a second.
3682+
*
3683+
* These tests pin the two halves of that change: the derivation must happen a
3684+
* FIXED number of times regardless of how many frames elapse, and every input
3685+
* that can change the answer must still force a fresh one.
3686+
*
3687+
* The probe is `[data-composition-id][data-start]`, which `init.ts` queries in
3688+
* exactly one place: `resolveAuthoredCompositionDurationFloorSeconds`, reached
3689+
* only from a real derivation. Counting it needs no production test hook, and
3690+
* it cannot be satisfied by a derivation that was skipped.
3691+
*/
3692+
describe("derived duration floor recomputation", () => {
3693+
const DERIVATION_PROBE_SELECTOR = "[data-composition-id][data-start]";
3694+
const originalRequestAnimationFrame = window.requestAnimationFrame;
3695+
const originalCancelAnimationFrame = window.cancelAnimationFrame;
3696+
3697+
let raf: ReturnType<typeof createManualRaf>;
3698+
let derivations: number;
3699+
3700+
/**
3701+
* Registers a short root timeline as well as the markup. transportTick only
3702+
* syncs the clock duration when a timeline is BOUND, so a fixture without
3703+
* one never reaches the per-frame call these tests are about — it would make
3704+
* the invariance assertion pass for the wrong reason. The timeline is
3705+
* deliberately shorter than every media window here so the derived floor,
3706+
* not the timeline, is what the assertions read.
3707+
*/
3708+
const mountComposition = (bodyHtml: string) => {
3709+
document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-start="0">${bodyHtml}</div>`;
3710+
window.__timelines = { main: createMockTimeline(1) };
3711+
};
3712+
3713+
const setNativeDuration = (media: HTMLMediaElement, seconds: number) => {
3714+
Object.defineProperty(media, "duration", { value: seconds, configurable: true });
3715+
};
3716+
3717+
/** Drive the transport for `frames` animation frames and report the duration it settled on. */
3718+
const runFrames = (frames: number): number => {
3719+
for (let frame = 0; frame < frames; frame += 1) raf.step(16);
3720+
return window.__player!.getDuration();
3721+
};
3722+
3723+
beforeEach(() => {
3724+
resetRuntimeDataForTests();
3725+
document.body.innerHTML = "";
3726+
(globalThis as typeof globalThis & { CSS?: { escape?: (value: string) => string } }).CSS ??= {};
3727+
globalThis.CSS.escape ??= (value: string) => value;
3728+
raf = createManualRaf();
3729+
window.requestAnimationFrame = raf.requestAnimationFrame as typeof window.requestAnimationFrame;
3730+
window.cancelAnimationFrame = raf.cancelAnimationFrame as typeof window.cancelAnimationFrame;
3731+
derivations = 0;
3732+
const originalQuerySelectorAll = Element.prototype.querySelectorAll;
3733+
vi.spyOn(Element.prototype, "querySelectorAll").mockImplementation(function (
3734+
this: Element,
3735+
selector: string,
3736+
) {
3737+
if (selector === DERIVATION_PROBE_SELECTOR) derivations += 1;
3738+
return originalQuerySelectorAll.call(this, selector);
3739+
} as typeof Element.prototype.querySelectorAll);
3740+
window.__timelines = {};
3741+
});
3742+
3743+
afterEach(() => {
3744+
window.__hfRuntimeTeardown?.();
3745+
resetRuntimeDataForTests();
3746+
document.body.innerHTML = "";
3747+
window.__timelines = {} as Record<string, RuntimeTimelineLike>;
3748+
delete window.__player;
3749+
delete window.__playerReady;
3750+
delete window.__renderReady;
3751+
vi.restoreAllMocks();
3752+
window.requestAnimationFrame = originalRequestAnimationFrame;
3753+
window.cancelAnimationFrame = originalCancelAnimationFrame;
3754+
});
3755+
3756+
describe("invariance across frames", () => {
3757+
/**
3758+
* The load-bearing assertion, and it is INVARIANCE, not a threshold: a
3759+
* threshold ("fewer than 10 derivations") passes on a small fixture and
3760+
* still degrades linearly in production. Quadrupling the frame count must
3761+
* not change the derivation count at all.
3762+
*/
3763+
it("derives the duration floor a fixed number of times however many frames elapse", () => {
3764+
mountComposition(`<video data-start="0"></video>`);
3765+
setNativeDuration(document.querySelector("video")!, 10);
3766+
initSandboxRuntimeModular();
3767+
3768+
const afterStartup = derivations;
3769+
expect(runFrames(25)).toBe(10);
3770+
const afterShortRun = derivations - afterStartup;
3771+
3772+
expect(runFrames(100)).toBe(10);
3773+
const afterLongRun = derivations - afterStartup - afterShortRun;
3774+
3775+
// Four times the frames, the same amount of work. Before the cache both
3776+
// numbers tracked the frame count (25 and 100).
3777+
expect(afterShortRun).toBe(afterLongRun);
3778+
expect(afterShortRun).toBe(0);
3779+
});
3780+
3781+
it("does not re-derive for a DOM change that cannot affect the duration", () => {
3782+
mountComposition(`<video data-start="0"></video>`);
3783+
setNativeDuration(document.querySelector("video")!, 10);
3784+
initSandboxRuntimeModular();
3785+
runFrames(2);
3786+
3787+
const before = derivations;
3788+
// A class and an inline transform are what an animating composition
3789+
// writes on every frame. Treating those as duration inputs would make
3790+
// the cache useless during playback.
3791+
document.querySelector("video")!.classList.add("is-visible");
3792+
document.querySelector("video")!.setAttribute("style", "opacity: 0.5");
3793+
3794+
expect(runFrames(5)).toBe(10);
3795+
expect(derivations).toBe(before);
3796+
});
3797+
});
3798+
3799+
describe("invalidation, one test per input that can change the answer", () => {
3800+
/**
3801+
* Media metadata is the input with no DOM footprint at all: `duration`
3802+
* goes from NaN to a number on the element itself. Both halves are visible
3803+
* here — the silent property change is served STALE (proving the cache is
3804+
* real), and the event that always accompanies it in a browser makes it
3805+
* fresh (proving the invalidation is real).
3806+
*/
3807+
it("serves a stale duration for a silent metadata change and a fresh one once the event fires", () => {
3808+
mountComposition(`<video data-start="0"></video>`);
3809+
const video = document.querySelector("video")!;
3810+
setNativeDuration(video, 10);
3811+
initSandboxRuntimeModular();
3812+
expect(runFrames(2)).toBe(10);
3813+
3814+
// Half one: the input changed, nothing signalled it, the cache answers.
3815+
setNativeDuration(video, 30);
3816+
expect(runFrames(2)).toBe(10);
3817+
3818+
// Half two: the signal a real browser emits alongside that change.
3819+
video.dispatchEvent(new Event("durationchange"));
3820+
expect(runFrames(1)).toBe(30);
3821+
});
3822+
3823+
it("re-derives when el.load() resets duration to NaN", () => {
3824+
mountComposition(`<video data-start="0"></video>`);
3825+
const video = document.querySelector("video")!;
3826+
setNativeDuration(video, 10);
3827+
initSandboxRuntimeModular();
3828+
expect(runFrames(2)).toBe(10);
3829+
3830+
// What load() does: duration back to NaN, announced by `emptied`.
3831+
setNativeDuration(video, Number.NaN);
3832+
expect(runFrames(2)).toBe(10);
3833+
video.dispatchEvent(new Event("emptied"));
3834+
const before = derivations;
3835+
runFrames(1);
3836+
expect(derivations).toBeGreaterThan(before);
3837+
});
3838+
3839+
it("re-derives when a timing attribute is edited", () => {
3840+
mountComposition(`<video data-start="0"></video>`);
3841+
setNativeDuration(document.querySelector("video")!, 10);
3842+
initSandboxRuntimeModular();
3843+
expect(runFrames(2)).toBe(10);
3844+
3845+
document.querySelector("video")!.setAttribute("data-duration", "25");
3846+
expect(runFrames(1)).toBe(25);
3847+
});
3848+
3849+
it("re-derives when a clip is moved later on the timeline", () => {
3850+
mountComposition(`<video data-start="0" data-duration="10"></video>`);
3851+
initSandboxRuntimeModular();
3852+
expect(runFrames(2)).toBe(10);
3853+
3854+
document.querySelector("video")!.setAttribute("data-start", "5");
3855+
expect(runFrames(1)).toBe(15);
3856+
});
3857+
3858+
it("re-derives when a timed element is added after init", () => {
3859+
mountComposition(`<video data-start="0" data-duration="10"></video>`);
3860+
initSandboxRuntimeModular();
3861+
expect(runFrames(2)).toBe(10);
3862+
3863+
// Nested compositions mount asynchronously, well after init — this is
3864+
// the ordinary case, not an edge case.
3865+
const late = document.createElement("audio");
3866+
late.setAttribute("data-start", "20");
3867+
late.setAttribute("data-duration", "5");
3868+
document.querySelector("[data-composition-id]")!.append(late);
3869+
3870+
expect(runFrames(1)).toBe(25);
3871+
});
3872+
3873+
it("re-derives when a timed element is removed", () => {
3874+
mountComposition(
3875+
`<video data-start="0" data-duration="10"></video>` +
3876+
`<audio id="tail" data-start="20" data-duration="5"></audio>`,
3877+
);
3878+
initSandboxRuntimeModular();
3879+
expect(runFrames(2)).toBe(25);
3880+
3881+
document.querySelector("#tail")!.remove();
3882+
expect(runFrames(1)).toBe(10);
3883+
});
3884+
3885+
/**
3886+
* `window.__timelines` is a plain object. No MutationObserver and no event
3887+
* can see a composition script registering into it or lengthening what it
3888+
* already registered, so the cache compares a signature of the registry on
3889+
* every read. Nothing else in the invalidation set could catch this.
3890+
*/
3891+
it("re-derives when a nested composition's registered timeline grows", () => {
3892+
mountComposition(`<div data-composition-id="scene" data-start="0" data-duration="10"></div>`);
3893+
window.__timelines = { ...window.__timelines, scene: createMockTimeline(10) };
3894+
initSandboxRuntimeModular();
3895+
expect(runFrames(2)).toBe(10);
3896+
3897+
window.__timelines = { ...window.__timelines, scene: createMockTimeline(40) };
3898+
const before = derivations;
3899+
runFrames(1);
3900+
expect(derivations).toBeGreaterThan(before);
3901+
});
3902+
3903+
/**
3904+
* MutationObserver records are delivered in a microtask. A caller that
3905+
* edits a timing attribute and reads the duration back in the same
3906+
* synchronous block — which is exactly what the Studio's live editing does
3907+
* — would be handed the pre-edit value if the cache waited for the
3908+
* callback. It drains the queue on read instead.
3909+
*/
3910+
it("reflects an edit read back in the same synchronous block", () => {
3911+
mountComposition(`<video data-start="0" data-duration="10"></video>`);
3912+
initSandboxRuntimeModular();
3913+
expect(runFrames(2)).toBe(10);
3914+
3915+
// No await, no microtask checkpoint between the write and the read.
3916+
document.querySelector("video")!.setAttribute("data-duration", "42");
3917+
expect(runFrames(1)).toBe(42);
3918+
});
3919+
});
3920+
3921+
/**
3922+
* The render path depends on the exact duration and a frame captured against
3923+
* a wrong one cannot be recovered, so it does not read the cache at all —
3924+
* the same silent metadata change that is deliberately served stale to the
3925+
* editor must be seen immediately here.
3926+
*/
3927+
it("never serves a cached duration once render capture has started", () => {
3928+
mountComposition(`<video data-start="0"></video>`);
3929+
const video = document.querySelector("video")!;
3930+
setNativeDuration(video, 10);
3931+
initSandboxRuntimeModular();
3932+
expect(runFrames(2)).toBe(10);
3933+
3934+
window.__player!.renderSeek(0);
3935+
setNativeDuration(video, 30);
3936+
// No `durationchange` dispatched, and the editor would still answer 10.
3937+
expect(runFrames(1)).toBe(30);
3938+
3939+
const before = derivations;
3940+
runFrames(3);
3941+
expect(derivations).toBeGreaterThan(before);
3942+
});
3943+
});

0 commit comments

Comments
 (0)