Skip to content

Write HTML. Render video. Built for agents.

fix(player): gate play on real composition readiness, not just duration (#4054)

Miguel Ángel72b223d57f5b
diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json
index b4f48daf36..d69cac3b59 100644
--- a/packages/core/package-subpaths.json
+++ b/packages/core/package-subpaths.json
@@ -56,6 +56,12 @@
"types": "./dist/mediaTiming.d.ts",
"environments": ["browser", "bun", "node"]
},
+ "./composition-readiness": {
+ "source": "./src/compositionReadiness.ts",
+ "runtime": "./dist/compositionReadiness.js",
+ "types": "./dist/compositionReadiness.d.ts",
+ "environments": ["browser", "bun", "node"]
+ },
"./editing": {
"source": "./src/editing/affordances.ts",
"runtime": "./dist/editing/affordances.js",
diff --git a/packages/core/package.json b/packages/core/package.json
index e3e8d99e8a..767a7ab412 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -70,6 +70,12 @@
"import": "./src/mediaTiming.ts",
"types": "./src/mediaTiming.ts"
},
+ "./composition-readiness": {
+ "bun": "./src/compositionReadiness.ts",
+ "node": "./dist/compositionReadiness.js",
+ "import": "./src/compositionReadiness.ts",
+ "types": "./src/compositionReadiness.ts"
+ },
"./editing": {
"bun": "./src/editing/affordances.ts",
"node": "./dist/editing/affordances.js",
@@ -434,6 +440,10 @@
"import": "./dist/mediaTiming.js",
"types": "./dist/mediaTiming.d.ts"
},
+ "./composition-readiness": {
+ "import": "./dist/compositionReadiness.js",
+ "types": "./dist/compositionReadiness.d.ts"
+ },
"./editing": {
"import": "./dist/editing/affordances.js",
"types": "./dist/editing/affordances.d.ts"
diff --git a/packages/core/src/compositionReadiness.test.ts b/packages/core/src/compositionReadiness.test.ts
new file mode 100644
index 0000000000..6dc1e5ffd6
--- /dev/null
+++ b/packages/core/src/compositionReadiness.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it, vi } from "vitest";
+import {
+ mediaReadinessInput,
+ scanPendingCompositionAssets,
+ settleCompositionReadiness,
+} from "./compositionReadiness.js";
+
+function docWith(bodyHtml: string): Document {
+ const doc = document.implementation.createHTMLDocument("");
+ doc.body.innerHTML = bodyHtml;
+ return doc;
+}
+
+describe("scanPendingCompositionAssets", () => {
+ it("reports nothing pending for an empty document", () => {
+ const scan = scanPendingCompositionAssets(docWith(""));
+ expect(scan).toEqual({ pendingMedia: [], pendingImages: [], fontsLoading: false });
+ });
+
+ it("finds a not-yet-decoded image as pending", () => {
+ const scan = scanPendingCompositionAssets(docWith('<img src="a.png">'));
+ expect(scan.pendingImages).toHaveLength(1);
+ });
+});
+
+describe("mediaReadinessInput", () => {
+ it("returns null when there is nothing to wait on", () => {
+ expect(mediaReadinessInput(docWith(""))).toBeNull();
+ });
+});
+
+describe("settleCompositionReadiness", () => {
+ it("calls back synchronously, before returning, when nothing is pending", () => {
+ let calledSync = false;
+ settleCompositionReadiness(docWith(""), () => {
+ calledSync = true;
+ });
+ // If this ever ran via a microtask instead, calledSync would still be
+ // false right here — a caller that plays/enables playback immediately
+ // after this call would see stale state, which is the exact regression
+ // this test guards against.
+ expect(calledSync).toBe(true);
+ });
+
+ it("calls back asynchronously when something is pending", () => {
+ const doc = docWith('<img src="a.png">');
+ const img = doc.querySelector("img")!;
+ Object.defineProperty(img, "complete", { value: false });
+ img.decode = vi.fn().mockResolvedValue(undefined);
+
+ let calledSync = false;
+ settleCompositionReadiness(doc, () => {
+ calledSync = true;
+ });
+ expect(calledSync).toBe(false);
+ });
+
+ it("waits for a pending image to decode before settling", async () => {
+ const doc = docWith('<img src="a.png">');
+ const img = doc.querySelector("img")!;
+ Object.defineProperty(img, "complete", { value: false });
+ img.decode = vi.fn().mockResolvedValue(undefined);
+
+ const result = await new Promise((resolve) => settleCompositionReadiness(doc, resolve));
+ expect(result).toEqual({ timedOut: false });
+ expect(img.decode).toHaveBeenCalled();
+ });
+
+ it("times out rather than waiting forever on a stuck asset", async () => {
+ vi.useFakeTimers();
+ const doc = docWith('<img src="a.png">');
+ const img = doc.querySelector("img")!;
+ Object.defineProperty(img, "complete", { value: false });
+ img.decode = () => new Promise<void>(() => {}); // never resolves
+
+ const pending = new Promise((resolve) =>
+ settleCompositionReadiness(doc, resolve, { timeoutMs: 1000 }),
+ );
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(pending).resolves.toEqual({ timedOut: true });
+ vi.useRealTimers();
+ });
+});
diff --git a/packages/core/src/compositionReadiness.ts b/packages/core/src/compositionReadiness.ts
new file mode 100644
index 0000000000..0798689ed4
--- /dev/null
+++ b/packages/core/src/compositionReadiness.ts
@@ -0,0 +1,109 @@
+/** A composition is "ready" once every declared input settles, not just once
+ * its duration is known. Each input returns null (nothing to wait on) or a
+ * promise that resolves once it settles. */
+export type CompositionReadinessInput = (doc: Document) => Promise<void> | null;
+
+export interface PendingCompositionAssets {
+ pendingMedia: HTMLMediaElement[];
+ pendingImages: HTMLImageElement[];
+ fontsLoading: boolean;
+}
+
+// HTMLMediaElement.HAVE_FUTURE_DATA per spec, used as a literal because not
+// every DOM implementation defines the named static (e.g. happy-dom leaves
+// it undefined).
+const HAVE_FUTURE_DATA = 3;
+
+// `doc` is a foreign (same-origin) iframe document, so its elements belong to
+// that iframe's own realm — instanceof checks against this window's globals
+// would silently reject every one of them. Resolve the class from the node's
+// own defaultView first.
+export function isRealmElement(node: Node): node is Element {
+ const view = node.ownerDocument?.defaultView;
+ if (view && node instanceof view.Element) return true;
+ return node instanceof Element;
+}
+
+export function isRealmHtmlMediaElement(node: Node): node is HTMLMediaElement {
+ if (!isRealmElement(node)) return false;
+ if (node.tagName !== "AUDIO" && node.tagName !== "VIDEO") return false;
+ const view = node.ownerDocument?.defaultView;
+ if (view && node instanceof view.HTMLMediaElement) return true;
+ return node instanceof HTMLMediaElement;
+}
+
+/** One DOM pass for every declared-media asset not yet ready. */
+export function scanPendingCompositionAssets(doc: Document): PendingCompositionAssets {
+ const pendingMedia = Array.from(doc.querySelectorAll("video, audio"))
+ .filter(isRealmHtmlMediaElement)
+ .filter((el) => el.readyState < HAVE_FUTURE_DATA);
+ const pendingImages = Array.from(doc.querySelectorAll("img")).filter((img) => !img.complete);
+ const fontsLoading = doc.fonts?.status === "loading";
+ return { pendingMedia, pendingImages, fontsLoading };
+}
+
+function collectPendingCompositionAssets(
+ doc: Document,
+ { pendingMedia, pendingImages, fontsLoading }: PendingCompositionAssets,
+): Promise<void> {
+ const mediaReady = pendingMedia.map(
+ (el) =>
+ new Promise<void>((resolve) => {
+ const onSettled = () => {
+ el.removeEventListener("canplay", onSettled);
+ el.removeEventListener("error", onSettled);
+ resolve();
+ };
+ el.addEventListener("canplay", onSettled);
+ el.addEventListener("error", onSettled);
+ }),
+ );
+ const imagesReady = pendingImages.map((img) =>
+ img.decode ? img.decode().catch(() => {}) : Promise.resolve(),
+ );
+ const fontsReady = fontsLoading && doc.fonts ? doc.fonts.ready.then(() => {}) : Promise.resolve();
+ return Promise.all([...mediaReady, ...imagesReady, fontsReady]).then(() => {});
+}
+
+/** Declared-media readiness input: waits on the composition's own video,
+ * audio, image and font-face loads. */
+export function mediaReadinessInput(doc: Document): Promise<void> | null {
+ const scan = scanPendingCompositionAssets(doc);
+ if (scan.pendingMedia.length === 0 && scan.pendingImages.length === 0 && !scan.fontsLoading) {
+ return null;
+ }
+ return collectPendingCompositionAssets(doc, scan);
+}
+
+const DEFAULT_TIMEOUT_MS = 8_000;
+
+export interface CompositionReadinessResult {
+ timedOut: boolean;
+}
+
+/** Invokes `onSettled` once every input settles, or the timeout elapses.
+ * Calls back synchronously, before returning, when nothing is pending — a
+ * caller that plays right after this call sees the decision already
+ * applied, same as before this gate existed. */
+export function settleCompositionReadiness(
+ doc: Document,
+ onSettled: (result: CompositionReadinessResult) => void,
+ opts: { inputs?: CompositionReadinessInput[]; timeoutMs?: number } = {},
+): void {
+ const inputs = opts.inputs ?? [mediaReadinessInput];
+ const pending = inputs.map((input) => input(doc)).filter((p): p is Promise<void> => p !== null);
+ if (pending.length === 0) {
+ onSettled({ timedOut: false });
+ return;
+ }
+
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
+ let timeoutId: ReturnType<typeof setTimeout>;
+ const timeout = new Promise<"timed-out">((resolve) => {
+ timeoutId = setTimeout(() => resolve("timed-out"), timeoutMs);
+ });
+ Promise.race([Promise.all(pending).then(() => "done" as const), timeout]).then((result) => {
+ clearTimeout(timeoutId);
+ onSettled({ timedOut: result === "timed-out" });
+ });
+}
diff --git a/packages/player/src/hyperframes-player.test.ts b/packages/player/src/hyperframes-player.test.ts
index bac3a3e0c1..ebd81e6278 100644
--- a/packages/player/src/hyperframes-player.test.ts
+++ b/packages/player/src/hyperframes-player.test.ts
@@ -2761,3 +2761,282 @@ describe("HyperframesPlayer retained runtime data", () => {
expect(applied[0]?.detail).toEqual({ channel: "captions", requestId: requests[1] });
});
});
+
+describe("HyperframesPlayer asset-ready gate", () => {
+ type PlayerInternal = HTMLElement & {
+ iframe: HTMLIFrameElement;
+ _ready: boolean;
+ _pendingPlay: boolean;
+ _paused: boolean;
+ assetsReady: boolean;
+ _waitForAssetsReady(doc: Document | null): void;
+ _onIframeLoad(): void;
+ play(): void;
+ pause(): void;
+ seek(timeInSeconds: number): void;
+ };
+
+ beforeEach(async () => {
+ await import("./hyperframes-player.js");
+ });
+
+ // A bare iframe fires its own async `load` a few ms after append, which
+ // resets _assetsReady — await it first so it can't land mid-test.
+ async function createConnectedPlayer(): Promise<PlayerInternal> {
+ const player = document.createElement("hyperframes-player") as PlayerInternal;
+ document.body.appendChild(player);
+ await new Promise<void>((resolve) => {
+ player.iframe.addEventListener("load", () => resolve(), { once: true });
+ });
+ player._ready = true;
+ return player;
+ }
+
+ // A composition doc with one video stuck at readyState 0 — the shared
+ // "something is still loading" fixture for the defer/timeout tests below.
+ function createStalledVideoDoc(): { doc: Document; video: HTMLVideoElement } {
+ const doc = document.implementation.createHTMLDocument("composition");
+ const video = doc.createElement("video");
+ Object.defineProperty(video, "readyState", { value: 0, configurable: true });
+ doc.body.appendChild(video);
+ return { doc, video };
+ }
+
+ it("settles immediately for a cross-origin composition (doc === null)", async () => {
+ const player = await createConnectedPlayer();
+
+ player._waitForAssetsReady(null);
+
+ expect(player.assetsReady).toBe(true);
+ expect(player.hasAttribute("assets-loading")).toBe(false);
+
+ player.remove();
+ });
+
+ it("defers play() until a pending video settles, then plays and clears the overlay attribute", async () => {
+ const player = await createConnectedPlayer();
+
+ const { doc, video } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, doc);
+
+ const playSpy = vi.fn();
+ player.addEventListener("play", playSpy);
+
+ player._waitForAssetsReady(doc);
+ expect(player.assetsReady).toBe(false);
+ expect(player.hasAttribute("assets-loading")).toBe(true);
+
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+ expect(playSpy).not.toHaveBeenCalled();
+
+ video.dispatchEvent(new Event("canplay"));
+ // A macrotask flush drains the whole promise chain regardless of its
+ // depth (resolved media promise -> Promise.all -> Promise.race -> settle).
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(player.assetsReady).toBe(true);
+ expect(player.hasAttribute("assets-loading")).toBe(false);
+ expect(player._pendingPlay).toBe(false);
+ expect(playSpy).toHaveBeenCalledTimes(1);
+
+ player.remove();
+ });
+
+ it("cancels a queued play if the user pauses while assets are still buffering", async () => {
+ const player = await createConnectedPlayer();
+
+ const { doc, video } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, doc);
+
+ const playSpy = vi.fn();
+ player.addEventListener("play", playSpy);
+
+ player._waitForAssetsReady(doc);
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+
+ player.pause();
+ expect(player._pendingPlay).toBe(false);
+ expect(player._paused).toBe(true);
+
+ video.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(player.assetsReady).toBe(true);
+ expect(player._pendingPlay).toBe(false);
+ expect(player._paused).toBe(true);
+ expect(playSpy).not.toHaveBeenCalled();
+
+ player.remove();
+ });
+
+ it("cancels a queued play if the user seeks while assets are still buffering", async () => {
+ const player = await createConnectedPlayer();
+
+ const { doc, video } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, doc);
+
+ const playSpy = vi.fn();
+ player.addEventListener("play", playSpy);
+
+ player._waitForAssetsReady(doc);
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+
+ player.seek(1.5);
+ expect(player._pendingPlay).toBe(false);
+
+ video.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(player.assetsReady).toBe(true);
+ expect(player._pendingPlay).toBe(false);
+ expect(playSpy).not.toHaveBeenCalled();
+
+ player.remove();
+ });
+
+ it("settles a play() called twice while buffering into exactly one playback start (pre-existing idempotency, not the pause/seek cancel)", async () => {
+ const player = await createConnectedPlayer();
+
+ const { doc, video } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, doc);
+
+ const playSpy = vi.fn();
+ player.addEventListener("play", playSpy);
+
+ player._waitForAssetsReady(doc);
+ player.play();
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+
+ video.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(player.assetsReady).toBe(true);
+ expect(player._pendingPlay).toBe(false);
+ // Two queued play() calls settle into exactly one playback start, never two.
+ expect(playSpy).toHaveBeenCalledTimes(1);
+
+ player.remove();
+ });
+
+ it("plays anyway once the 8s timeout elapses for an asset that never settles", async () => {
+ // Real timers for the initial (blank) iframe load, then switch to fake
+ // timers so the 8s asset-ready timeout can be advanced instantly.
+ const player = await createConnectedPlayer();
+ vi.useFakeTimers();
+ try {
+ const { doc } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, doc);
+
+ player._waitForAssetsReady(doc);
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+
+ await vi.advanceTimersByTimeAsync(8_000);
+
+ expect(player.assetsReady).toBe(true);
+ expect(player._pendingPlay).toBe(false);
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(warnSpy.mock.calls[0]?.[0]).toContain("assets-loading timed out");
+
+ player.remove();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("ignores a superseded wait's settle after a composition swap mid-wait", async () => {
+ const player = await createConnectedPlayer();
+
+ const { doc: docA, video: videoA } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, docA);
+ player._waitForAssetsReady(docA);
+
+ // Simulates a src/srcdoc swap arriving while A's wait is still in flight,
+ // then B's own ready handler firing (which is what real navigation does:
+ // _onIframeLoad clears _ready, the new composition's ready handler sets
+ // it again before calling _waitForAssetsReady).
+ player._onIframeLoad();
+ player._ready = true;
+ const { doc: docB, video: videoB } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, docB);
+ player._waitForAssetsReady(docB);
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+
+ const playSpy = vi.fn();
+ player.addEventListener("play", playSpy);
+
+ videoA.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ // A's stale settle must not mark B ready or play it — B's own video is
+ // still stuck.
+ expect(player.assetsReady).toBe(false);
+ expect(player._pendingPlay).toBe(true);
+ expect(playSpy).not.toHaveBeenCalled();
+
+ videoB.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(player.assetsReady).toBe(true);
+ expect(player._pendingPlay).toBe(false);
+ expect(playSpy).toHaveBeenCalledTimes(1);
+
+ player.remove();
+ });
+
+ it("does not resume play() after disconnect once a pending wait settles late", async () => {
+ const player = await createConnectedPlayer();
+
+ const { doc, video } = createStalledVideoDoc();
+ stubIframeContentDocument(player.iframe, doc);
+ player._waitForAssetsReady(doc);
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+
+ const playSpy = vi.fn();
+ player.addEventListener("play", playSpy);
+
+ player.remove();
+ video.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(playSpy).not.toHaveBeenCalled();
+ });
+
+ it("dispatches 'play' exactly once for a call made before the probe resolves", async () => {
+ const player = await createConnectedPlayer();
+ player._ready = false;
+
+ const playSpy = vi.fn();
+ player.addEventListener("play", playSpy);
+
+ player.play();
+ expect(player._pendingPlay).toBe(true);
+ expect(playSpy).not.toHaveBeenCalled();
+
+ (
+ player as unknown as {
+ _onProbeReady: (r: {
+ duration: number;
+ adapter: { kind: string; getDuration: () => number };
+ compositionSize: null;
+ }) => void;
+ }
+ )._onProbeReady({
+ duration: 5,
+ adapter: { kind: "runtime", getDuration: () => 5 },
+ compositionSize: null,
+ });
+
+ expect(playSpy).toHaveBeenCalledTimes(1);
+
+ player.remove();
+ });
+});
diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts
index 2dd0bf4593..868b88b9e0 100644
--- a/packages/player/src/hyperframes-player.ts
+++ b/packages/player/src/hyperframes-player.ts
@@ -20,6 +20,10 @@ import { ShaderLoaderState } from "./shader-loader-state.js";
import { PLAYER_STYLES } from "./styles.js";
import { type DirectTimelineAdapter } from "./timeline-adapters.js";
import { runtimeProtocolMetadata } from "@hyperframes/core/runtime/protocol";
+import {
+ scanPendingCompositionAssets,
+ settleCompositionReadiness,
+} from "@hyperframes/core/composition-readiness";
// Playback-rate bounds mirror the runtime clamp in
// packages/core/src/runtime/init.ts (applyPlaybackRate) and media.ts so the
@@ -32,6 +36,11 @@ const MIN_PLAYBACK_RATE = 0.1;
const MAX_PLAYBACK_RATE = 5;
const SANDBOX_ORIGIN_ATTR = "sandbox-origin";
const RUNTIME_DATA_DELIVERY_TIMEOUT_MS = 10_000;
+// Bounds how long the player waits for a same-origin composition's media,
+// images and fonts before playing anyway — a stuck asset must not block
+// playback forever.
+const ASSETS_READY_TIMEOUT_MS = 8_000;
+const ASSETS_LOADING_ATTR = "assets-loading";
export type ColorGradingTarget =
| string
@@ -95,6 +104,9 @@ class HyperframesPlayer extends HTMLElement {
private probe: CompositionProbe;
private _ready = false;
+ private _assetsReady = false;
+ private _pendingPlay = false;
+ private _assetsGeneration = 0;
private _currentTime = 0;
private _duration = 0;
private _paused = true;
@@ -212,6 +224,7 @@ class HyperframesPlayer extends HTMLElement {
this.controlsApi = null;
this._paused = true;
this._ready = false;
+ this._invalidateAssetsWait();
this._runtimeBridgeReady = false;
this._rejectAllRuntimeDataDeliveries("Player disconnected before runtime data was applied");
}
@@ -227,6 +240,7 @@ class HyperframesPlayer extends HTMLElement {
if (!this.isConnected) break;
if (val) {
this._ready = false;
+ this._invalidateAssetsWait();
this._runtimeBridgeReady = false;
this._rejectAllRuntimeDataDeliveries(
"Composition navigated before runtime data was applied",
@@ -237,6 +251,7 @@ class HyperframesPlayer extends HTMLElement {
case "srcdoc":
if (!this.isConnected) break;
this._ready = false;
+ this._invalidateAssetsWait();
this._runtimeBridgeReady = false;
this._rejectAllRuntimeDataDeliveries(
"Composition navigated before runtime data was applied",
@@ -317,6 +332,7 @@ class HyperframesPlayer extends HTMLElement {
private _reloadForSandboxOriginPolicy(): void {
this._ready = false;
+ this._invalidateAssetsWait();
this._runtimeBridgeReady = false;
this._rejectAllRuntimeDataDeliveries("Sandbox policy changed before runtime data was applied");
const srcdoc = this.getAttribute("srcdoc");
@@ -343,7 +359,13 @@ class HyperframesPlayer extends HTMLElement {
return this._scenes;
}
+ // fallow-ignore-next-line complexity
play() {
+ if (this._ready && !this._assetsReady) {
+ this._pendingPlay = true;
+ return;
+ }
+ this._pendingPlay = false;
this.posterEl?.remove();
this.posterEl = null;
if (this._duration > 0 && this._currentTime >= this._duration) this.seek(0);
@@ -351,19 +373,25 @@ class HyperframesPlayer extends HTMLElement {
// check doesn't immediately self-terminate on the first callback.
this._paused = false;
const directTimelineStarted = this._tryDirectTimelinePlay();
+ // Set when the probe hasn't resolved yet: retried from _onProbeReady /
+ // _onRuntimeTimelineReady once ready, which is the call that actually
+ // starts playback — this premature call must not ALSO dispatch "play"
+ // for what hasn't started, or a host listener sees it fire twice.
+ let queuedForReady = false;
if (!directTimelineStarted) {
this._sendControl("play");
// Only start the parent tick clock once the composition is ready and
// confirmed on the runtime bridge path (not the direct-timeline path).
- // Guards against firing ticks into an uninitialized iframe when play()
- // is called before the probe has resolved.
if (this._ready && !this._directTimelineAdapter) {
this._startParentTickClock();
+ } else if (!this._ready) {
+ this._pendingPlay = true;
+ queuedForReady = true;
}
}
if (this._media.audioOwner === "parent") this._media.playAll();
this.controlsApi?.updatePlaying(true);
- this.dispatchEvent(new Event("play"));
+ if (!queuedForReady) this.dispatchEvent(new Event("play"));
if (directTimelineStarted && this._directTimelineAdapter) {
this._directTimelineClock.start(
this._directTimelineAdapter,
@@ -375,6 +403,10 @@ class HyperframesPlayer extends HTMLElement {
}
pause() {
+ // A play queued while assets were still buffering must not survive an
+ // explicit user pause — otherwise it fires once assets settle, seconds
+ // after the user stopped playback.
+ this._pendingPlay = false;
if (!this._tryDirectTimelinePause()) this._sendControl("pause");
this._directTimelineClock.stop();
this._stopParentTickClock();
@@ -391,6 +423,10 @@ class HyperframesPlayer extends HTMLElement {
}
seek(timeInSeconds: number) {
+ // seek()'s own contract is that it lands paused, so a play still queued
+ // from the asset-buffering window is cancelled here too — same reason as
+ // pause() above.
+ this._pendingPlay = false;
if (!this._trySyncSeek(timeInSeconds) && !this._tryDirectTimelineSeek(timeInSeconds)) {
this._sendControl("seek", {
timeSeconds: timeInSeconds,
@@ -483,6 +519,13 @@ class HyperframesPlayer extends HTMLElement {
return this._ready;
}
+ /** True once the composition's media, images and fonts have loaded (or the
+ * 8s wait timed out) — mirrors the `assetsready` event. Always true for
+ * cross-origin compositions, which the player has no DOM access to wait on. */
+ get assetsReady() {
+ return this._assetsReady;
+ }
+
get playbackRate() {
return clampPlaybackRate(parseFloat(this.getAttribute("playback-rate") || "1"));
}
@@ -788,6 +831,7 @@ class HyperframesPlayer extends HTMLElement {
// replaced, where it can only end in a delivery timeout rather than the immediate,
// explanatory rejection the caller gets from every other navigating path.
this._ready = false;
+ this._invalidateAssetsWait();
this._runtimeBridgeReady = false;
this._rejectAllRuntimeDataDeliveries("Shader options changed before runtime data was applied");
if (getShaderModeFromElement(this) !== "player") this.shaderLoader.reset();
@@ -947,7 +991,8 @@ class HyperframesPlayer extends HTMLElement {
this._replayBridgeState();
this._setIframeMediaMuted(this.muted);
- if (this.hasAttribute("autoplay")) this.play();
+ this._waitForAssetsReady(doc);
+ if (this.hasAttribute("autoplay") || this._pendingPlay) this.play();
}
private _onProbeReady({ duration, adapter, compositionSize }: ProbeResult) {
@@ -961,14 +1006,78 @@ class HyperframesPlayer extends HTMLElement {
this._compositionHeight = compositionSize.height;
this._rescale();
}
- try {
- const doc = this.iframe.contentDocument;
- if (doc) this._media.setupFromIframe(doc);
- } catch {
- /* cross-origin */
- }
+ const doc = this._getSameOriginIframeDocument();
+ if (doc) this._media.setupFromIframe(doc);
this._setIframeMediaMuted(this.muted);
- if (this.hasAttribute("autoplay")) this.play();
+ this._waitForAssetsReady(doc);
+ if (this.hasAttribute("autoplay") || this._pendingPlay) this.play();
+ }
+
+ /** Gates play() on composition readiness (media/images/fonts), bounded by
+ * ASSETS_READY_TIMEOUT_MS; settles synchronously when nothing is pending. */
+ private _waitForAssetsReady(doc: Document | null): void {
+ this._assetsReady = false;
+ // Invalidates any earlier wait still in flight (a composition swap, or
+ // disconnect, mid-wait) — its eventual settle checks this and no-ops
+ // rather than resolving a since-superseded generation.
+ const generation = ++this._assetsGeneration;
+ if (!doc) {
+ this._settleAssetsReady(generation);
+ return;
+ }
+ settleCompositionReadiness(
+ doc,
+ ({ timedOut }) => {
+ if (generation !== this._assetsGeneration) return;
+ if (timedOut) this._warnStuckAssets(doc);
+ this._settleAssetsReady(generation);
+ },
+ { timeoutMs: ASSETS_READY_TIMEOUT_MS },
+ );
+ // settleCompositionReadiness calls back synchronously when nothing was
+ // pending, so _assetsReady is already true here in the common case — the
+ // loading overlay only shows for the genuinely-waiting case.
+ if (!this._assetsReady) {
+ this.setAttribute(ASSETS_LOADING_ATTR, "");
+ this.shaderLoader.showAssetsLoading();
+ }
+ }
+
+ /** Timeout diagnostic. Re-scans (rather than reusing the original scan)
+ * since some assets may have resolved in the 8s since. */
+ private _warnStuckAssets(doc: Document): void {
+ const { pendingMedia, pendingImages, fontsLoading } = scanPendingCompositionAssets(doc);
+ console.warn(
+ `[hyperframes-player] assets-loading timed out after ${ASSETS_READY_TIMEOUT_MS}ms — playing anyway`,
+ {
+ stuckMedia: pendingMedia.map(
+ (el) => el.currentSrc || el.getAttribute("src") || `<${el.tagName.toLowerCase()}>`,
+ ),
+ stuckImages: pendingImages.map(
+ (img) => img.currentSrc || img.getAttribute("src") || "<img>",
+ ),
+ fontsLoading,
+ },
+ );
+ }
+
+ private _settleAssetsReady(generation: number): void {
+ if (generation !== this._assetsGeneration || this._assetsReady) return;
+ this._assetsReady = true;
+ this.removeAttribute(ASSETS_LOADING_ATTR);
+ this.shaderLoader.hide();
+ this.dispatchEvent(new Event("assetsready"));
+ if (this._pendingPlay) this.play();
+ }
+
+ /** Abandons any in-flight asset wait — every `_ready = false` site calls
+ * this first, so a stale wait's settle can't apply to what comes next. */
+ private _invalidateAssetsWait(): void {
+ this._assetsReady = false;
+ this._pendingPlay = false;
+ this._assetsGeneration++;
+ this.removeAttribute(ASSETS_LOADING_ATTR);
+ this.shaderLoader.hide();
}
private _rescale() {
@@ -1005,6 +1114,7 @@ class HyperframesPlayer extends HTMLElement {
this._directTimelineAdapter = null;
this._directTimelineClock.stop();
this._stopParentTickClock();
+ this._invalidateAssetsWait();
this.shaderLoader.reset();
this._media.resetForIframeLoad();
this.probe.start();
diff --git a/packages/player/src/media-element-guards.ts b/packages/player/src/media-element-guards.ts
index 5e9867f45d..93036de995 100644
--- a/packages/player/src/media-element-guards.ts
+++ b/packages/player/src/media-element-guards.ts
@@ -1,14 +1 @@
-export function isRealmElement(node: Node): node is Element {
- const view = node.ownerDocument?.defaultView;
- if (view && node instanceof view.Element) return true;
- return node instanceof Element;
-}
-
-export function isRealmHtmlMediaElement(node: Node): node is HTMLMediaElement {
- if (!isRealmElement(node)) return false;
- if (node.tagName !== "AUDIO" && node.tagName !== "VIDEO") return false;
-
- const view = node.ownerDocument?.defaultView;
- if (view && node instanceof view.HTMLMediaElement) return true;
- return node instanceof HTMLMediaElement;
-}
+export { isRealmElement, isRealmHtmlMediaElement } from "@hyperframes/core/composition-readiness";
diff --git a/packages/player/src/shader-loader-state.ts b/packages/player/src/shader-loader-state.ts
index de9cb199d7..558575e332 100644
--- a/packages/player/src/shader-loader-state.ts
+++ b/packages/player/src/shader-loader-state.ts
@@ -54,6 +54,7 @@ export class ShaderLoaderState {
this._el.frameRow.style.visibility = "hidden";
}
+ // fallow-ignore-next-line unused-class-member, complexity
update(status: ShaderTransitionState, loadingMode: string): void {
if (loadingMode !== "player") {
this.reset();
@@ -63,6 +64,9 @@ export class ShaderLoaderState {
this.hide();
return;
}
+ // showAssetsLoading() may have left "Loading assets" here for a prior
+ // show; this path owns the label whenever it's the one drawing the panel.
+ this._el.root.setAttribute("aria-label", "Preparing scene transitions");
const progress =
typeof status.progress === "number" && Number.isFinite(status.progress) ? status.progress : 0;
@@ -86,6 +90,7 @@ export class ShaderLoaderState {
this._el.fill.style.transform = `scaleX(${ratio})`;
+ // fallow-ignore-next-line code-duplication
this._el.transitionValue.textContent =
status.currentTransition !== undefined && status.transitionTotal !== undefined
? `${status.currentTransition}/${status.transitionTotal}`
@@ -111,6 +116,17 @@ export class ShaderLoaderState {
this.show();
}
+ /** Second reason to show the same overlay — reuses the shader-transition
+ * panel's DOM rather than drawing a second one. */
+ showAssetsLoading(): void {
+ this.reset();
+ this._el.title.textContent = "Loading assets";
+ this._el.detail.textContent = "Waiting for images, video and fonts to finish loading.";
+ this._el.root.setAttribute("aria-label", "Loading assets");
+ this.show();
+ }
+
+ // fallow-ignore-next-line unused-class-member
get hideTimeout(): ReturnType<typeof setTimeout> | null {
return this._hideTimeout;
}
diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.ts b/packages/studio/src/player/hooks/useTimelinePlayer.ts
index 7fb883fadb..7794be1b04 100644
--- a/packages/studio/src/player/hooks/useTimelinePlayer.ts
+++ b/packages/studio/src/player/hooks/useTimelinePlayer.ts
@@ -45,6 +45,7 @@ import { shouldResumeForwardPlaybackAfterSeek, shouldStopAfterSeek } from "../li
import { applyPreviewVariablesToUrl } from "../../hooks/previewVariablesStore";
import { createPreviewMessageHandler } from "./previewMessageRouter";
import { timelineElementsChanged } from "./timelinePlayerSync";
+import { safeContentDocument } from "./timelineSyncHydration";
export function useTimelinePlayer() {
const iframeRef = useRef<HTMLIFrameElement | null>(null);
@@ -60,7 +61,7 @@ export function useTimelinePlayer() {
const staticSeekAdapterRef = useRef<StaticSeekCacheEntry | null>(null);
const staticSeekWarnedRef = useRef(false);
- const { setIsPlaying, setCurrentTime, setDuration, setTimelineReady, setElements } =
+ const { setIsPlaying, setCurrentTime, setDuration, requestTimelineReady, setElements } =
usePlayerStore.getState();
// The fixture lease belongs at this shared synchronization boundary so every
@@ -101,7 +102,11 @@ export function useTimelinePlayer() {
setDuration(nextDuration ?? 0);
}
if (!state.timelineReady) {
- setTimelineReady(true);
+ // Same gate as initializeAdapter's own readiness wait: this is the
+ // message-based fallback for compositions that report their duration
+ // via clip manifest rather than the direct adapter, and it must not
+ // enable Play any earlier than that path does.
+ requestTimelineReady(safeContentDocument(iframeRef.current));
}
// Asynchronously enrich media elements still missing sourceDuration
@@ -120,7 +125,7 @@ export function useTimelinePlayer() {
},
);
},
- [setElements, setTimelineReady, setDuration],
+ [setElements, requestTimelineReady, setDuration],
);
// Pre-existing dispatcher complexity — surfaced by this PR's line shifts, not new logic.
@@ -425,7 +430,7 @@ export function useTimelinePlayer() {
syncTimelineElements,
setDuration,
setCurrentTime,
- setTimelineReady,
+ requestTimelineReady,
setIsPlaying,
attachIframeShortcutListeners,
applyPreviewAudioState,
diff --git a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts
index f5b26dd496..31e6b76617 100644
--- a/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts
+++ b/packages/studio/src/player/hooks/useTimelineSyncCallbacks.ts
@@ -42,7 +42,7 @@ interface UseTimelineSyncCallbacksParams {
syncTimelineElements: (elements: TimelineElement[], nextDuration?: number) => void;
setDuration: (v: number) => void;
setCurrentTime: (v: number) => void;
- setTimelineReady: (v: boolean) => void;
+ requestTimelineReady: (doc: Document | null) => void;
setIsPlaying: (v: boolean) => void;
attachIframeShortcutListeners: () => void;
applyPreviewAudioState: () => void;
@@ -106,7 +106,7 @@ export function useTimelineSyncCallbacks({
syncTimelineElements,
setDuration,
setCurrentTime,
- setTimelineReady,
+ requestTimelineReady,
setIsPlaying,
attachIframeShortcutListeners,
applyPreviewAudioState,
@@ -204,7 +204,10 @@ export function useTimelineSyncCallbacks({
syncAdapterDuration(adapter, setDuration);
setCurrentTime(startTime);
if (!isRefreshingRef.current) {
- setTimelineReady(true);
+ // Enables Play from actual play-readiness, not just a known duration —
+ // a click before this resolves used to start the timeline with media,
+ // images or fonts still loading and never recover.
+ requestTimelineReady(safeContentDocument(iframeRef.current));
}
isRefreshingRef.current = false;
setIsPlaying(false);
@@ -223,7 +226,7 @@ export function useTimelineSyncCallbacks({
getAdapter,
setDuration,
setCurrentTime,
- setTimelineReady,
+ requestTimelineReady,
setIsPlaying,
processTimelineMessage,
enrichMissingCompositions,
diff --git a/packages/studio/src/player/store/playerStore.test.ts b/packages/studio/src/player/store/playerStore.test.ts
index 951468d1c9..0b9ffff79e 100644
--- a/packages/studio/src/player/store/playerStore.test.ts
+++ b/packages/studio/src/player/store/playerStore.test.ts
@@ -1,3 +1,4 @@
+// @vitest-environment happy-dom
import { describe, it, expect, beforeEach, vi } from "vitest";
import { usePlayerStore, liveTime, type TimelineElement } from "./playerStore";
@@ -322,6 +323,47 @@ describe("usePlayerStore", () => {
});
});
+ describe("requestTimelineReady", () => {
+ function stalledVideoDoc(): { doc: Document; video: HTMLVideoElement } {
+ const doc = document.implementation.createHTMLDocument("composition");
+ const video = doc.createElement("video");
+ Object.defineProperty(video, "readyState", { value: 0, configurable: true });
+ doc.body.appendChild(video);
+ return { doc, video };
+ }
+
+ it("resolves timelineReady once the doc's media settles", async () => {
+ const { doc, video } = stalledVideoDoc();
+ usePlayerStore.getState().requestTimelineReady(doc);
+ expect(usePlayerStore.getState().timelineReady).toBe(false);
+
+ video.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(usePlayerStore.getState().timelineReady).toBe(true);
+ });
+
+ it("a stale wait from a project switched away from never marks the new project ready", async () => {
+ // beginTimelineSession no-ops when projectId is unchanged, so pin a
+ // known starting project first rather than relying on reset()'s
+ // leftover timelineProjectId from whatever test ran before this one.
+ usePlayerStore.getState().beginTimelineSession("readiness-test-project-a");
+ const { doc: docA, video: videoA } = stalledVideoDoc();
+ usePlayerStore.getState().requestTimelineReady(docA);
+
+ // Switches projects mid-wait — beginTimelineSession resets timelineReady
+ // to false for project B, whose own media has not been checked at all.
+ usePlayerStore.getState().beginTimelineSession("readiness-test-project-b");
+ expect(usePlayerStore.getState().timelineReady).toBe(false);
+
+ // A's wait settles late; it must not resolve into B's readiness.
+ videoA.dispatchEvent(new Event("canplay"));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(usePlayerStore.getState().timelineReady).toBe(false);
+ });
+ });
+
describe("setElements", () => {
it("sets the elements array", () => {
const elements: TimelineElement[] = [
diff --git a/packages/studio/src/player/store/playerStore.ts b/packages/studio/src/player/store/playerStore.ts
index 2543214695..2fd2b802ba 100644
--- a/packages/studio/src/player/store/playerStore.ts
+++ b/packages/studio/src/player/store/playerStore.ts
@@ -19,6 +19,7 @@ import {
import { createEditingModeSlice, type EditingModeSlice } from "./editingModeSlice";
import { createTimelineFocusRequest, type TimelineFocusRequest } from "./timelineFocusState";
import { createThumbnailSlice, type ThumbnailSlice } from "./thumbnailSlice";
+import { createPlaybackReadinessSlice, resetPlaybackReadinessState } from "./readinessSlice";
export type { KeyframeCacheEntry } from "./keyframeSlice";
export { liveTime } from "./liveTime";
@@ -54,12 +55,15 @@ function resolveElementSelection(
};
}
-interface PlayerState
- extends KeyframeSlice, AutomationSelectionSlice, ThumbnailSlice, EditingModeSlice {
+type PlayerStoreSlices = KeyframeSlice &
+ AutomationSelectionSlice &
+ ThumbnailSlice &
+ EditingModeSlice &
+ ReturnType<typeof createPlaybackReadinessSlice>;
+interface PlayerState extends PlayerStoreSlices {
isPlaying: boolean;
currentTime: number;
duration: number;
- timelineReady: boolean;
/** Increments exactly once when the Studio switches to a different project. */
timelineSessionEpoch: number;
/** Project owning the current timeline session; null outside a project-scoped reset. */
@@ -129,7 +133,6 @@ interface PlayerState
setAudioMuted: (muted: boolean) => void;
setAudioVolume: (volume: number) => void;
setLoopEnabled: (enabled: boolean) => void;
- setTimelineReady: (ready: boolean) => void;
setBeatDragging: (dragging: boolean) => void;
setElements: (elements: TimelineElement[]) => void;
setSelectedElementId: (id: string | null, options?: SelectElementOptions) => void;
@@ -260,7 +263,7 @@ export function createTimelineResetState() {
isPlaying: false,
currentTime: 0,
duration: 0,
- timelineReady: false,
+ ...resetPlaybackReadinessState(),
beatDragging: false,
elements: [],
selectedElementId: null,
@@ -304,7 +307,6 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
isPlaying: false,
currentTime: 0,
duration: 0,
- timelineReady: false,
timelineSessionEpoch: 0,
timelineProjectId: null,
beatDragging: false,
@@ -333,6 +335,7 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
...createAutomationSelectionSlice(set),
...createEditingModeSlice(set),
+ ...createPlaybackReadinessSlice(set),
activeKeyframePct: null,
setActiveKeyframePct: (pct) => set({ activeKeyframePct: pct }),
@@ -521,7 +524,6 @@ export const usePlayerStore = create<PlayerState>((set, get) => ({
bumpZEditVersion: () => set((state) => ({ zEditVersion: state.zEditVersion + 1 })),
setCurrentTime: (time) => set({ currentTime: Number.isFinite(time) ? time : 0 }),
setDuration: (duration) => set({ duration: Number.isFinite(duration) ? duration : 0 }),
- setTimelineReady: (ready) => set({ timelineReady: ready }),
setBeatDragging: (dragging) => set({ beatDragging: dragging }),
setElements: (elements) => set({ elements }),
// A genuine single selection: always collapse the set to just this element. User
diff --git a/packages/studio/src/player/store/readinessSlice.ts b/packages/studio/src/player/store/readinessSlice.ts
new file mode 100644
index 0000000000..ddaba6c129
--- /dev/null
+++ b/packages/studio/src/player/store/readinessSlice.ts
@@ -0,0 +1,42 @@
+/** Gates `timelineReady` on the composition's declared readiness inputs
+ * (media, for now) instead of just a known duration. The generation counter
+ * is module-scope, not store state: it guards an in-flight settlement, not
+ * something a component reads, so bumping it shouldn't trigger a render. */
+import type { StoreApi } from "zustand";
+import { settleCompositionReadiness } from "@hyperframes/core/composition-readiness";
+
+export interface PlaybackReadinessSlice {
+ timelineReady: boolean;
+ setTimelineReady: (ready: boolean) => void;
+ /** Sets timelineReady once doc's readiness inputs settle, or immediately
+ * if doc is null. A wait a later call supersedes never wins the race. */
+ requestTimelineReady: (doc: Document | null) => void;
+}
+
+let timelineReadyGeneration = 0;
+
+/** For a full timeline reset: bumps the generation so any requestTimelineReady
+ * wait in flight can never resolve into what replaced it. */
+export function resetPlaybackReadinessState(): Pick<PlaybackReadinessSlice, "timelineReady"> {
+ timelineReadyGeneration++;
+ return { timelineReady: false };
+}
+
+export function createPlaybackReadinessSlice(
+ set: StoreApi<PlaybackReadinessSlice>["setState"],
+): PlaybackReadinessSlice {
+ return {
+ timelineReady: false,
+ setTimelineReady: (ready) => {
+ timelineReadyGeneration++;
+ set({ timelineReady: ready });
+ },
+ requestTimelineReady: (doc) => {
+ const generation = ++timelineReadyGeneration;
+ if (!doc) return set({ timelineReady: true });
+ settleCompositionReadiness(doc, () => {
+ if (generation === timelineReadyGeneration) set({ timelineReady: true });
+ });
+ },
+ };
+}