Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
perf(runtime): reuse one timing resolver per pass and derive duration only when the composition changes (#3824)
Miguel Ángel3ea2f909e15e
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 7a8991ac6f..536b536a34 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -3674,3 +3674,270 @@ describe("initSandboxRuntimeModular", () => {});});});++/**+ * The derived duration floor is a function of the composition, not of the+ * playhead — yet transportTick asked for it on every animation frame, which+ * made a paused, untouched editor scan every media element ~60 times a second.+ *+ * These tests pin the two halves of that change: the derivation must happen a+ * FIXED number of times regardless of how many frames elapse, and every input+ * that can change the answer must still force a fresh one.+ *+ * The probe is `[data-composition-id][data-start]`, which `init.ts` queries in+ * exactly one place: `resolveAuthoredCompositionDurationFloorSeconds`, reached+ * only from a real derivation. Counting it needs no production test hook, and+ * it cannot be satisfied by a derivation that was skipped.+ */+describe("derived duration floor recomputation", () => {+ const DERIVATION_PROBE_SELECTOR = "[data-composition-id][data-start]";+ const originalRequestAnimationFrame = window.requestAnimationFrame;+ const originalCancelAnimationFrame = window.cancelAnimationFrame;++ let raf: ReturnType<typeof createManualRaf>;+ let derivations: number;++ /**+ * Registers a short root timeline as well as the markup. transportTick only+ * syncs the clock duration when a timeline is BOUND, so a fixture without+ * one never reaches the per-frame call these tests are about — it would make+ * the invariance assertion pass for the wrong reason. The timeline is+ * deliberately shorter than every media window here so the derived floor,+ * not the timeline, is what the assertions read.+ */+ const mountComposition = (bodyHtml: string) => {+ document.body.innerHTML = `<div data-composition-id="main" data-root="true" data-start="0">${bodyHtml}</div>`;+ window.__timelines = { main: createMockTimeline(1) };+ };++ const setNativeDuration = (media: HTMLMediaElement, seconds: number) => {+ Object.defineProperty(media, "duration", { value: seconds, configurable: true });+ };++ /** Drive the transport for `frames` animation frames and report the duration it settled on. */+ const runFrames = (frames: number): number => {+ for (let frame = 0; frame < frames; frame += 1) raf.step(16);+ return window.__player!.getDuration();+ };++ beforeEach(() => {+ resetRuntimeDataForTests();+ document.body.innerHTML = "";+ (globalThis as typeof globalThis & { CSS?: { escape?: (value: string) => string } }).CSS ??= {};+ globalThis.CSS.escape ??= (value: string) => value;+ raf = createManualRaf();+ window.requestAnimationFrame = raf.requestAnimationFrame as typeof window.requestAnimationFrame;+ window.cancelAnimationFrame = raf.cancelAnimationFrame as typeof window.cancelAnimationFrame;+ derivations = 0;+ const originalQuerySelectorAll = Element.prototype.querySelectorAll;+ vi.spyOn(Element.prototype, "querySelectorAll").mockImplementation(function (+ this: Element,+ selector: string,+ ) {+ if (selector === DERIVATION_PROBE_SELECTOR) derivations += 1;+ return originalQuerySelectorAll.call(this, selector);+ } as typeof Element.prototype.querySelectorAll);+ window.__timelines = {};+ });++ afterEach(() => {+ window.__hfRuntimeTeardown?.();+ resetRuntimeDataForTests();+ document.body.innerHTML = "";+ window.__timelines = {} as Record<string, RuntimeTimelineLike>;+ delete window.__player;+ delete window.__playerReady;+ delete window.__renderReady;+ vi.restoreAllMocks();+ window.requestAnimationFrame = originalRequestAnimationFrame;+ window.cancelAnimationFrame = originalCancelAnimationFrame;+ });++ describe("invariance across frames", () => {+ /**+ * The load-bearing assertion, and it is INVARIANCE, not a threshold: a+ * threshold ("fewer than 10 derivations") passes on a small fixture and+ * still degrades linearly in production. Quadrupling the frame count must+ * not change the derivation count at all.+ */+ it("derives the duration floor a fixed number of times however many frames elapse", () => {+ mountComposition(`<video data-start="0"></video>`);+ setNativeDuration(document.querySelector("video")!, 10);+ initSandboxRuntimeModular();++ const afterStartup = derivations;+ expect(runFrames(25)).toBe(10);+ const afterShortRun = derivations - afterStartup;++ expect(runFrames(100)).toBe(10);+ const afterLongRun = derivations - afterStartup - afterShortRun;++ // Four times the frames, the same amount of work. Before the cache both+ // numbers tracked the frame count (25 and 100).+ expect(afterShortRun).toBe(afterLongRun);+ expect(afterShortRun).toBe(0);+ });++ it("does not re-derive for a DOM change that cannot affect the duration", () => {+ mountComposition(`<video data-start="0"></video>`);+ setNativeDuration(document.querySelector("video")!, 10);+ initSandboxRuntimeModular();+ runFrames(2);++ const before = derivations;+ // A class and an inline transform are what an animating composition+ // writes on every frame. Treating those as duration inputs would make+ // the cache useless during playback.+ document.querySelector("video")!.classList.add("is-visible");+ document.querySelector("video")!.setAttribute("style", "opacity: 0.5");++ expect(runFrames(5)).toBe(10);+ expect(derivations).toBe(before);+ });+ });++ describe("invalidation, one test per input that can change the answer", () => {+ /**+ * Media metadata is the input with no DOM footprint at all: `duration`+ * goes from NaN to a number on the element itself. Both halves are visible+ * here — the silent property change is served STALE (proving the cache is+ * real), and the event that always accompanies it in a browser makes it+ * fresh (proving the invalidation is real).+ */+ it("serves a stale duration for a silent metadata change and a fresh one once the event fires", () => {+ mountComposition(`<video data-start="0"></video>`);+ const video = document.querySelector("video")!;+ setNativeDuration(video, 10);+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ // Half one: the input changed, nothing signalled it, the cache answers.+ setNativeDuration(video, 30);+ expect(runFrames(2)).toBe(10);++ // Half two: the signal a real browser emits alongside that change.+ video.dispatchEvent(new Event("durationchange"));+ expect(runFrames(1)).toBe(30);+ });++ it("re-derives when el.load() resets duration to NaN", () => {+ mountComposition(`<video data-start="0"></video>`);+ const video = document.querySelector("video")!;+ setNativeDuration(video, 10);+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ // What load() does: duration back to NaN, announced by `emptied`.+ setNativeDuration(video, Number.NaN);+ expect(runFrames(2)).toBe(10);+ video.dispatchEvent(new Event("emptied"));+ const before = derivations;+ runFrames(1);+ expect(derivations).toBeGreaterThan(before);+ });++ it("re-derives when a timing attribute is edited", () => {+ mountComposition(`<video data-start="0"></video>`);+ setNativeDuration(document.querySelector("video")!, 10);+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ document.querySelector("video")!.setAttribute("data-duration", "25");+ expect(runFrames(1)).toBe(25);+ });++ it("re-derives when a clip is moved later on the timeline", () => {+ mountComposition(`<video data-start="0" data-duration="10"></video>`);+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ document.querySelector("video")!.setAttribute("data-start", "5");+ expect(runFrames(1)).toBe(15);+ });++ it("re-derives when a timed element is added after init", () => {+ mountComposition(`<video data-start="0" data-duration="10"></video>`);+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ // Nested compositions mount asynchronously, well after init — this is+ // the ordinary case, not an edge case.+ const late = document.createElement("audio");+ late.setAttribute("data-start", "20");+ late.setAttribute("data-duration", "5");+ document.querySelector("[data-composition-id]")!.append(late);++ expect(runFrames(1)).toBe(25);+ });++ it("re-derives when a timed element is removed", () => {+ mountComposition(+ `<video data-start="0" data-duration="10"></video>` ++ `<audio id="tail" data-start="20" data-duration="5"></audio>`,+ );+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(25);++ document.querySelector("#tail")!.remove();+ expect(runFrames(1)).toBe(10);+ });++ /**+ * `window.__timelines` is a plain object. No MutationObserver and no event+ * can see a composition script registering into it or lengthening what it+ * already registered, so the cache compares a signature of the registry on+ * every read. Nothing else in the invalidation set could catch this.+ */+ it("re-derives when a nested composition's registered timeline grows", () => {+ mountComposition(`<div data-composition-id="scene" data-start="0" data-duration="10"></div>`);+ window.__timelines = { ...window.__timelines, scene: createMockTimeline(10) };+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ window.__timelines = { ...window.__timelines, scene: createMockTimeline(40) };+ const before = derivations;+ runFrames(1);+ expect(derivations).toBeGreaterThan(before);+ });++ /**+ * MutationObserver records are delivered in a microtask. A caller that+ * edits a timing attribute and reads the duration back in the same+ * synchronous block — which is exactly what the Studio's live editing does+ * — would be handed the pre-edit value if the cache waited for the+ * callback. It drains the queue on read instead.+ */+ it("reflects an edit read back in the same synchronous block", () => {+ mountComposition(`<video data-start="0" data-duration="10"></video>`);+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ // No await, no microtask checkpoint between the write and the read.+ document.querySelector("video")!.setAttribute("data-duration", "42");+ expect(runFrames(1)).toBe(42);+ });+ });++ /**+ * The render path depends on the exact duration and a frame captured against+ * a wrong one cannot be recovered, so it does not read the cache at all —+ * the same silent metadata change that is deliberately served stale to the+ * editor must be seen immediately here.+ */+ it("never serves a cached duration once render capture has started", () => {+ mountComposition(`<video data-start="0"></video>`);+ const video = document.querySelector("video")!;+ setNativeDuration(video, 10);+ initSandboxRuntimeModular();+ expect(runFrames(2)).toBe(10);++ window.__player!.renderSeek(0);+ setNativeDuration(video, 30);+ // No `durationchange` dispatched, and the editor would still answer 10.+ expect(runFrames(1)).toBe(30);++ const before = derivations;+ runFrames(3);+ expect(derivations).toBeGreaterThan(before);+ });+});diff --git a/packages/core/src/runtime/init.timingResolver.test.ts b/packages/core/src/runtime/init.timingResolver.test.tsnew file mode 100644index 0000000000..e5f5df483a--- /dev/null+++ b/packages/core/src/runtime/init.timingResolver.test.ts@@ -0,0 +1,161 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { RuntimeTimelineLike } from "./types";++const resolverSpy = vi.hoisted(() => ({ constructions: 0 }));+const mediaSpy = vi.hoisted(() => ({ beforeSync: null as null | (() => void) }));++vi.mock("./startResolver", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./startResolver")>();+ return {+ ...actual,+ createRuntimeStartTimeResolver: (+ params: Parameters<typeof actual.createRuntimeStartTimeResolver>[0],+ ) => {+ resolverSpy.constructions += 1;+ return actual.createRuntimeStartTimeResolver(params);+ },+ };+});++vi.mock("./media", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./media")>();+ return {+ ...actual,+ syncRuntimeMedia: (params: Parameters<typeof actual.syncRuntimeMedia>[0]) => {+ mediaSpy.beforeSync?.();+ return actual.syncRuntimeMedia(params);+ },+ };+});++const { initSandboxRuntimeModular } = await import("./init");++function createMockTimeline(duration: number): RuntimeTimelineLike {+ const state = { time: 0, paused: true };+ return {+ play: () => {+ state.paused = false;+ },+ pause: () => {+ state.paused = true;+ },+ seek: (time?: number) => (time === undefined ? state.time : (state.time = time)),+ totalTime: (time?: number) => (time === undefined ? state.time : (state.time = time)),+ time: () => state.time,+ duration: () => duration,+ add: () => {},+ paused: (value?: boolean) =>+ typeof value === "boolean" ? (state.paused = value) : state.paused,+ timeScale: () => {},+ set: () => {},+ getChildren: () => [],+ };+}++/** jsdom leaves `duration` as NaN; a writable getter also lets a test mimic the+ * `el.load()` reset `syncRuntimeMedia` performs on the seek-retry path. */+function stubDuration(el: HTMLMediaElement, initial: number): { set: (next: number) => void } {+ let value = initial;+ Object.defineProperty(el, "duration", { get: () => value, configurable: true });+ return { set: (next: number) => (value = next) };+}++describe("runtime timing resolver scoping", () => {+ const originalRequestAnimationFrame = window.requestAnimationFrame;+ const originalCancelAnimationFrame = window.cancelAnimationFrame;++ beforeEach(() => {+ document.body.innerHTML = "";+ (globalThis as typeof globalThis & { CSS?: { escape?: (value: string) => string } }).CSS ??= {};+ globalThis.CSS.escape ??= (value: string) => value;+ window.requestAnimationFrame = ((callback: FrameRequestCallback) => {+ callback(0);+ return 1;+ }) as typeof window.requestAnimationFrame;+ window.cancelAnimationFrame = (() => {}) as typeof window.cancelAnimationFrame;+ resolverSpy.constructions = 0;+ mediaSpy.beforeSync = null;+ });++ afterEach(() => {+ window.requestAnimationFrame = originalRequestAnimationFrame;+ window.cancelAnimationFrame = originalCancelAnimationFrame;+ mediaSpy.beforeSync = null;+ delete window.__player;+ delete window.__playerReady;+ });++ /** One seek plus one transport tick: between them they drive all three+ * scopes (media cache, visibility pass, media-window duration scan). */+ const passWithMediaCount = (count: number): number => {+ const frames: FrameRequestCallback[] = [];+ window.requestAnimationFrame = ((callback: FrameRequestCallback) => {+ frames.push(callback);+ return frames.length;+ }) as typeof window.requestAnimationFrame;+ const flushFrame = () => frames.splice(0, frames.length).forEach((callback) => callback(0));++ const clips = Array.from(+ { length: count },+ (_, i) => `<video id="clip${i}" data-start="${i}" data-duration="1"></video>`,+ ).join("");+ document.body.innerHTML = `<div data-composition-id="main" data-root="true">${clips}</div>`;+ for (const video of document.querySelectorAll("video")) {+ stubDuration(video as HTMLVideoElement, 1);+ }+ window.__timelines = { main: createMockTimeline(count) };+ initSandboxRuntimeModular();+ // Let the runtime bind its timeline, so the tick below takes the+ // duration-resolution branch rather than short-circuiting.+ flushFrame();++ resolverSpy.constructions = 0;+ window.__player?.renderSeek(0.5);+ flushFrame();+ return resolverSpy.constructions;+ };++ // Non-vacuity: this is the whole point of the change. Every resolver carries+ // WeakMap caches, so building one per call means a seek re-walks the ancestor+ // chain of every element. Before the fix this count grew with media count+ // (~7 constructions per media element); after it, it is flat.+ it("builds a constant number of timing resolvers per seek, not one per element", () => {+ const few = passWithMediaCount(2);+ const many = passWithMediaCount(12);++ expect(many).toBe(few);+ // A ceiling, so a future caller that reintroduces per-element construction+ // inside a scope fails here even if it happens to be element-count-flat.+ expect(many).toBeLessThanOrEqual(6);+ });++ // The two scopes exist because `syncRuntimeMedia` can call `el.load()` on its+ // seek-past-buffered-range retry, which synchronously resets `el.duration`.+ // One scope spanning the media pass would serve the pre-`load()` duration to+ // the visibility pass that runs after it.+ it("resolves a post-load() duration in the visibility pass, not the cached pre-load() one", () => {+ document.body.innerHTML =+ `<div data-composition-id="main" data-root="true">` ++ // `lead`'s duration is read (and cached) while the media cache is built,+ // because `follower`'s start is expressed relative to it.+ `<video id="lead" data-start="0"></video>` ++ `<audio id="follower" data-start="lead + 0" data-duration="1"></audio>` ++ `</div>`;+ const lead = document.querySelector<HTMLVideoElement>("#lead")!;+ const follower = document.querySelector<HTMLAudioElement>("#follower")!;+ const leadDuration = stubDuration(lead, 10);+ stubDuration(follower, 1);+ window.__timelines = {};+ initSandboxRuntimeModular();++ // Stands in for the `el.load()` the seek-retry performs: the source turns+ // out to be shorter than the metadata first reported.+ mediaSpy.beforeSync = () => leadDuration.set(2);++ window.__player?.renderSeek(2.5);++ // Fresh read => follower starts at 2 and is on screen at 2.5.+ // Stale cache => follower starts at 10 and is hidden.+ expect(follower.style.visibility).toBe("visible");+ });+});diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex cd35eda018..658c227559 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -645,34 +645,63 @@ export function initSandboxRuntimeModular(): void {}};- const resolveStartForElement = (- element: Element,- fallback = 0,- opts?: { includeAuthoredTimingAttrs?: boolean },- ): number => {- const resolver = createRuntimeStartTimeResolver({+ const createTimingResolver = (includeAuthoredTimingAttrs: boolean) =>+ createRuntimeStartTimeResolver({timelineRegistry: (window.__timelines ?? {}) as Record<string,RuntimeTimelineLike | undefined>,- includeAuthoredTimingAttrs: opts?.includeAuthoredTimingAttrs ?? true,+ includeAuthoredTimingAttrs,});- return resolver.resolveStartForElement(element, fallback);++ // `createRuntimeStartTimeResolver` memoizes starts and durations in WeakMaps,+ // but a resolver built per call throws those caches away before the second+ // lookup ever happens, so one pass re-walks every ancestor chain once per+ // element. `withTimingResolver` installs ONE resolver for the duration of a+ // synchronous callback; every resolve inside shares its caches.+ //+ // NEVER widen these into a single scope spanning a whole media pass.+ // `syncRuntimeMedia` calls `el.load()` on the seek-past-buffered-range retry+ // (media.ts), which synchronously resets `el.duration` to NaN, and+ // `resolveDurationForElement` reads `element.duration` (startResolver.ts). A+ // cache living across `refreshRuntimeMediaCache` -> `syncRuntimeMedia` ->+ // `syncTimedElementVisibility` would serve the pre-`load()` duration to a+ // post-`load()` read. Two scopes with the write in between is what makes that+ // impossible. Do not merge them.+ let activeTimingResolver: ReturnType<typeof createTimingResolver> | null = null;++ const withTimingResolver = <T>(fn: () => T): T => {+ const previous = activeTimingResolver;+ activeTimingResolver = createTimingResolver(true);+ try {+ return fn();+ } finally {+ activeTimingResolver = previous;+ }};+ // The installed resolver carries authored timing attrs; a caller that opts+ // out gets its own, exactly as before.+ const timingResolverFor = (includeAuthoredTimingAttrs: boolean) =>+ includeAuthoredTimingAttrs && activeTimingResolver+ ? activeTimingResolver+ : createTimingResolver(includeAuthoredTimingAttrs);++ const resolveStartForElement = (+ element: Element,+ fallback = 0,+ opts?: { includeAuthoredTimingAttrs?: boolean },+ ): number =>+ timingResolverFor(opts?.includeAuthoredTimingAttrs ?? true).resolveStartForElement(+ element,+ fallback,+ );+const resolveDurationForElement = (element: Element,opts?: { includeAuthoredTimingAttrs?: boolean },- ): number | null => {- const resolver = createRuntimeStartTimeResolver({- timelineRegistry: (window.__timelines ?? {}) as Record<- string,- RuntimeTimelineLike | undefined- >,- includeAuthoredTimingAttrs: opts?.includeAuthoredTimingAttrs ?? true,- });- return resolver.resolveDurationForElement(element);- };+ ): number | null =>+ timingResolverFor(opts?.includeAuthoredTimingAttrs ?? true).resolveDurationForElement(element);const resolveMediaCompositionContext = (element: Element) => {const compositionRoot = element.closest("[data-composition-id]");@@ -814,20 +843,35 @@ export function initSandboxRuntimeModular(): void {return null;};+ // Scope 3 of 3 (see `withTimingResolver`). Every media element resolves its+ // composition ancestry here, and this runs on every transport tick via+ // `getSafeTimelineDurationSeconds`, so it is the heaviest consumer of the+ // per-call resolvers.+ //+ // The scope sits HERE and not on `getSafeTimelineDurationSeconds`, which+ // would look like the tidier boundary: that function also calls+ // `timeline.duration()` (author-supplied GSAP) and every adapter's+ // `getInferredDurationSeconds()` (third-party runtimes). Foreign code inside+ // a cache scope can touch the DOM between two resolves. This loop is DOM+ // reads only, so nothing can change under it.const resolveMediaWindowDurationSeconds = (): number | null => {const mediaNodes = Array.from(document.querySelectorAll("video[data-start], audio[data-start]"),) as HTMLMediaElement[];+ // Checked before the scope opens: a composition with no timed media runs+ // this every tick, and it should not pay for a resolver it never uses.if (mediaNodes.length === 0) return null;- let maxWindowEndSeconds = 0;- for (const node of mediaNodes) {- const start = resolveAbsoluteMediaStartSeconds(node);- if (!Number.isFinite(start)) continue;- const duration = resolveMediaElementDurationSeconds(node);- if (duration == null || duration <= MIN_VALID_TIMELINE_DURATION_SECONDS) continue;- maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);- }- return maxWindowEndSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxWindowEndSeconds : null;+ return withTimingResolver(() => {+ let maxWindowEndSeconds = 0;+ for (const node of mediaNodes) {+ const start = resolveAbsoluteMediaStartSeconds(node);+ if (!Number.isFinite(start)) continue;+ const duration = resolveMediaElementDurationSeconds(node);+ if (duration == null || duration <= MIN_VALID_TIMELINE_DURATION_SECONDS) continue;+ maxWindowEndSeconds = Math.max(maxWindowEndSeconds, Math.max(0, start) + duration);+ }+ return maxWindowEndSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxWindowEndSeconds : null;+ });};const resolveAuthoredCompositionDurationFloorSeconds = (): number | null => {@@ -911,13 +955,140 @@ export function initSandboxRuntimeModular(): void {return maxSeconds > MIN_VALID_TIMELINE_DURATION_SECONDS ? maxSeconds : null;};+ // Flips true on the first renderSeek call — the render/producer capture+ // protocol's signal that it has started deterministically driving frames.+ // One-way for this page lifetime; every producer render gets a fresh runtime.+ // See scheduleMetadataDurationHydration for why this gates the async+ // metadata rebind off once set, and resolveDurationFloors for why the+ // derived-duration cache is bypassed entirely once it is set.+ let renderCaptureSeekStarted = false;++ // The media and authored-composition duration floors are derived from the+ // DOM and the timeline registry — never from the playhead — so they change+ // only when the composition changes. transportTick asks for them on EVERY+ // animation frame, and deriving them scans every media element and walks+ // each one's composition ancestry, which is the largest single cost of a+ // paused, untouched editor. Derive once and reuse until an input changes.+ //+ // Every input that can change the answer, and the signal that catches it:+ // - timing attributes edited (Studio live editing, variables re-applied,+ // the runtime's own autostamping) -> MutationObserver, attribute filter below+ // - media or timed elements added/removed (nested compositions mount+ // asynchronously, well after init) -> MutationObserver, childList + subtree+ // - media metadata arriving or being reset (`el.load()` puts `duration`+ // back to NaN) — no DOM mutation at all -> capture-phase media events below+ // - a timeline registered, or an existing one's duration changing, in+ // `window.__timelines` (a plain object, not observable) -> registry+ // signature compared on read+ // The bias is deliberate: a redundant derivation is a missed optimisation,+ // a missed one is a wrong duration.+ type DurationFloors = { media: number | null; authoredComposition: number | null };+ const DURATION_FLOOR_INPUT_ATTRIBUTES = [+ "data-start",+ "data-duration",+ "data-end",+ "data-composition-id",+ "data-composition-src",+ "data-composition-file",+ "data-root",+ "data-hf-authored-duration",+ "data-hf-authored-end",+ "data-hf-auto-start",+ MEDIA_START_BASIS_ATTR,+ "data-playback-rate",+ "data-playback-start",+ "data-media-start",+ // `data-start` may be an expression referencing another element by id, and+ // a media element's `duration` follows its source.+ "id",+ "src",+ ];+ const DURATION_FLOOR_MEDIA_EVENTS = ["loadedmetadata", "durationchange", "emptied"] as const;+ let durationFloorsCache: DurationFloors | null = null;+ let durationFloorsRegistrySignature: string | null = null;+ let durationFloorsObserver: MutationObserver | null = null;++ const invalidateDurationFloors = () => {+ durationFloorsCache = null;+ };++ const deriveDurationFloors = (): DurationFloors => ({+ media: resolveMediaDurationFloorSeconds(),+ authoredComposition: resolveAuthoredCompositionDurationFloorSeconds(),+ });++ const readTimelineRegistrySignature = (): string => {+ const timelines = (window.__timelines ?? {}) as Record<string, RuntimeTimelineLike | undefined>;+ let signature = "";+ for (const timelineId of Object.keys(timelines)) {+ const timeline = timelines[timelineId];+ if (!timeline) continue;+ signature += `${timelineId}=${getTimelineDurationSeconds(timeline) ?? "?"};`;+ }+ return signature;+ };++ const watchDurationFloorInputs = () => {+ if (durationFloorsObserver || typeof MutationObserver === "undefined") return;+ durationFloorsObserver = new MutationObserver(invalidateDurationFloors);+ durationFloorsObserver.observe(document.documentElement, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: DURATION_FLOOR_INPUT_ATTRIBUTES,+ });+ // Media duration changes are published as events, not DOM mutations, and+ // they do not bubble — so listen in the capture phase, which reaches every+ // media element including ones added long after this binds.+ for (const eventType of DURATION_FLOOR_MEDIA_EVENTS) {+ document.addEventListener(eventType, invalidateDurationFloors, true);+ }+ runtimeCleanupCallbacks.push(() => {+ durationFloorsObserver?.disconnect();+ durationFloorsObserver = null;+ invalidateDurationFloors();+ for (const eventType of DURATION_FLOOR_MEDIA_EVENTS) {+ document.removeEventListener(eventType, invalidateDurationFloors, true);+ }+ });+ };++ const resolveDurationFloors = (): DurationFloors => {+ // The render path never reads a cached floor. Capture depends on the exact+ // duration and a frame that rendered against a wrong one cannot be+ // recovered, so it pays the full derivation on every frame exactly as+ // before — a correct slow render beats a fast wrong one.+ if (renderCaptureSeekStarted) return deriveDurationFloors();+ watchDurationFloorInputs();+ // MutationObserver records are delivered in a microtask, so a caller that+ // edits a timing attribute and reads the duration back in the SAME+ // synchronous block would otherwise be served the pre-edit value. Draining+ // the queue here makes the cache correct within a task, not just across+ // tasks. Taking the records suppresses the callback for them, which is+ // exactly equivalent since the callback only marks the cache stale.+ if (durationFloorsObserver && durationFloorsObserver.takeRecords().length > 0) {+ invalidateDurationFloors();+ }+ const registrySignature = readTimelineRegistrySignature();+ if (durationFloorsCache && registrySignature === durationFloorsRegistrySignature) {+ return durationFloorsCache;+ }+ durationFloorsRegistrySignature = registrySignature;+ durationFloorsCache = deriveDurationFloors();+ return durationFloorsCache;+ };+const getSafeTimelineDurationSeconds = (timeline: RuntimeTimelineLike | null,fallback = 0,): number => {const timelineDuration = getTimelineDurationSeconds(timeline);- const mediaFloor = resolveMediaDurationFloorSeconds();- const authoredCompositionFloor = resolveAuthoredCompositionDurationFloorSeconds();+ const { media: mediaFloor, authoredComposition: authoredCompositionFloor } =+ resolveDurationFloors();+ // Deliberately NOT cached: adapters infer their duration from live+ // animation objects (CSS/WAAPI/Lottie), which can change without any DOM+ // mutation or media event to observe. It is also a short loop over the+ // registered adapters, not a document scan.const adapterFloor = resolveAdapterDurationFloorSeconds();const durationFloor = Math.max(mediaFloor ?? 0,@@ -969,9 +1140,10 @@ export function initSandboxRuntimeModular(): void {timelineRegistry: timelines,includeAuthoredTimingAttrs: true,});- const mediaDurationFloorSeconds = resolveMediaDurationFloorSeconds();- const authoredCompositionDurationFloorSeconds =- resolveAuthoredCompositionDurationFloorSeconds();+ const {+ media: mediaDurationFloorSeconds,+ authoredComposition: authoredCompositionDurationFloorSeconds,+ } = resolveDurationFloors();const durationFloorSeconds =Math.max(mediaDurationFloorSeconds ?? 0, authoredCompositionDurationFloorSeconds ?? 0) ||null;@@ -1810,12 +1982,6 @@ export function initSandboxRuntimeModular(): void {let metadataRebindDebounceTimerId: number | null = null;let metadataRebindApplied = false;- // Flips true on the first renderSeek call — the render/producer capture- // protocol's signal that it has started deterministically driving frames.- // One-way for this page lifetime; every producer render gets a fresh runtime.- // See scheduleMetadataDurationHydration for why this gates the async- // metadata rebind off once set.- let renderCaptureSeekStarted = false;const metadataBoundMedia = new Set<HTMLMediaElement>();const volumeKeyframeCache = new WeakMap<HTMLMediaElement, VolumeKeyframe[]>();@@ -2086,10 +2252,7 @@ export function initSandboxRuntimeModular(): void {}};- const syncTimedElementVisibility = (- currentTime: number,- visibilityNodes: Element[] = Array.from(document.querySelectorAll("[data-start]")),- ) => {+ const applyTimedElementVisibility = (currentTime: number, visibilityNodes: Element[]) => {const rootComp = resolveRootCompositionElement();for (const rawNode of visibilityNodes) {if (!(rawNode instanceof HTMLElement)) continue;@@ -2160,41 +2323,54 @@ export function initSandboxRuntimeModular(): void {syncAudioGroupMute();};+ // Scope 2 of 3 (see `withTimingResolver`). One resolver for the whole+ // visibility pass: every node costs 2 x (1 + ancestor depth) resolves, and+ // ancestor chains are shared between siblings. Nothing in this body calls+ // `el.load()` or awaits, so no duration can change under the cache.+ const syncTimedElementVisibility = (+ currentTime: number,+ visibilityNodes: Element[] = Array.from(document.querySelectorAll("[data-start]")),+ ) => withTimingResolver(() => applyTimedElementVisibility(currentTime, visibilityNodes));+const syncMediaForCurrentState = () => {- const cache = refreshRuntimeMediaCache({- shouldIncludeElement: (element) =>- element.hasAttribute("data-start") ||- Boolean(resolveMediaCompositionContext(element).compositionRoot),- resolveStartSeconds: (element) => {- return resolveAbsoluteMediaStartSeconds(element);- },- resolveDurationSeconds: (element) => {- const context = resolveMediaCompositionContext(element);- const start = resolveAbsoluteMediaStartSeconds(element);- const hostRemaining =- context.inheritedStart != null &&- context.inheritedDuration != null &&- context.inheritedDuration > 0- ? Math.max(0, context.inheritedStart + context.inheritedDuration - start)+ // Scope 1 of 3 (see `withTimingResolver`). Closes before `syncRuntimeMedia`,+ // which may call `el.load()` and invalidate every cached duration.+ const cache = withTimingResolver(() =>+ refreshRuntimeMediaCache({+ shouldIncludeElement: (element) =>+ element.hasAttribute("data-start") ||+ Boolean(resolveMediaCompositionContext(element).compositionRoot),+ resolveStartSeconds: (element) => {+ return resolveAbsoluteMediaStartSeconds(element);+ },+ resolveDurationSeconds: (element) => {+ const context = resolveMediaCompositionContext(element);+ const start = resolveAbsoluteMediaStartSeconds(element);+ const hostRemaining =+ context.inheritedStart != null &&+ context.inheritedDuration != null &&+ context.inheritedDuration > 0+ ? Math.max(0, context.inheritedStart + context.inheritedDuration - start)+ : null;+ const sourceDuration = Number.isFinite(element.duration)+ ? resolveNaturalMediaTimelineDuration(element, element.duration): null;- const sourceDuration = Number.isFinite(element.duration)- ? resolveNaturalMediaTimelineDuration(element, element.duration)- : null;- // The element's own data-duration is an explicit clip-length trim- // (the studio writes it when you drag the clip edge). It must bound- // playback so a trimmed track stops at its edge instead of running on- // to the source-file or host-composition end. Absent → no cap (an- // untrimmed clip plays its natural source length).- const ownDuration = parseStrictFiniteTimingNumber(element.dataset.duration);- const explicitDuration = ownDuration != null && ownDuration > 0 ? ownDuration : null;- return resolveRuntimeMediaClipDuration({- isVideo: element.tagName === "VIDEO",- sourceDuration,- hostRemaining,- explicitDuration,- });- },- });+ // The element's own data-duration is an explicit clip-length trim+ // (the studio writes it when you drag the clip edge). It must bound+ // playback so a trimmed track stops at its edge instead of running on+ // to the source-file or host-composition end. Absent → no cap (an+ // untrimmed clip plays its natural source length).+ const ownDuration = parseStrictFiniteTimingNumber(element.dataset.duration);+ const explicitDuration = ownDuration != null && ownDuration > 0 ? ownDuration : null;+ return resolveRuntimeMediaClipDuration({+ isVideo: element.tagName === "VIDEO",+ sourceDuration,+ hostRemaining,+ explicitDuration,+ });+ },+ }),+ );// Attach probed volume keyframes to clips so syncRuntimeMedia can use the// same envelope the renderer uses instead of tracking GSAP-change diffs.for (const clip of cache.mediaClips) {