Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(player): play and loop a range of a film with range-start and range-end (#4688)
Miguel Ángel840f657028b9
diff --git a/docs/packages/player.mdx b/docs/packages/player.mdxindex add5ce3d89..60d435fadb 100644--- a/docs/packages/player.mdx+++ b/docs/packages/player.mdx@@ -64,6 +64,10 @@ Set `autoplay muted` only when playback should start without a user gesture.| `assets-loading-ui` | `player` or `none` | `player` | `none` hides the loading-assets card; asset events still fire || `low-power-idle` | boolean | false | While paused, check in once a second, not every 80 ms (many-player pages) || `disable-click-to-play` | boolean | false | A click on the player no longer plays or pauses, so the page can handle it |+| `range-start` | number | — | Film second where playback starts, loops back to and parks when paused (`rangeStart`) |+| `range-end` | number | — | Film second the range ends before: it stops or loops on the frame before it (`rangeEnd`) |++`range-start` and `range-end` play the moment [start, end) of the film. The player parks on `range-start` at `ready`, and again when a paused playhead falls outside a new range; `play()` from outside the range starts there. At the end it holds the last frame before `range-end` and fires `ended`, or wraps to `range-start` with `loop`. `currentTime` at `ended` is then inside that frame, not `range-end` itself, so listen for `ended` rather than comparing times. A current runtime stops on that frame itself; video and `__timelines` players stop one clock tick early, predicted from the smaller of their last two steps, and a video in a background tab checks on its own `timeupdate`; an older runtime stops when the player sees its time pass the end. `currentTime` and `duration` stay in film time. A range past the film is cut to its end and an empty or negative one is ignored; both fire `rangeclamped`.Player also accepts `shader-capture-scale` and `shader-loading` for previewingprojects that use shader transitions. These are preview controls, not composition@@ -115,6 +119,7 @@ player.addEventListener("timeupdate", (event) => {| `play` | — | Playback started || `pause` | — | Playback paused || `ended` | — | Playback reached end |+| `rangeclamped` | `{ rangeStart, rangeEnd, duration }` | A range past the film was cut to its end, or an empty one ignored (nulls) || `ratechange` | — | Playback rate changed || `volumechange` | — | Volume or muted state changed || `scenes` | `{ scenes }` | The runtime reported its scene list |diff --git a/packages/core/src/runtime/bridge.test.ts b/packages/core/src/runtime/bridge.test.tsindex 62c0c7d078..37a80205fc 100644--- a/packages/core/src/runtime/bridge.test.ts+++ b/packages/core/src/runtime/bridge.test.ts@@ -18,6 +18,7 @@ function createMockDeps() {onSetColorGrading: vi.fn(),onSetColorGradingCompare: vi.fn(),onSetRootDuration: vi.fn(),+ onSetPlayRange: vi.fn(),onEnablePickMode: vi.fn(),onDisablePickMode: vi.fn(),onSetRuntimeData: vi.fn(),@@ -258,6 +259,17 @@ describe("installRuntimeControlBridge", () => {expect(deps.onSetRootDuration).toHaveBeenCalledWith(18.5);});+ it("dispatches set-play-range with numeric seconds, and null for an open end", () => {+ const deps = createMockDeps();+ const handler = installRuntimeControlBridge(deps);+ handler(makeControlMessage("set-play-range", { startSeconds: "2", endSeconds: 3.5 }));+ handler(makeControlMessage("set-play-range", { startSeconds: null, endSeconds: null }));+ expect(deps.onSetPlayRange.mock.calls).toEqual([+ [2, 3.5],+ [0, null],+ ]);+ });+it("dispatches set-color-grading command with target and grading payload", () => {const deps = createMockDeps();const handler = installRuntimeControlBridge(deps);diff --git a/packages/core/src/runtime/bridge.ts b/packages/core/src/runtime/bridge.tsindex a6dd021123..919836e001 100644--- a/packages/core/src/runtime/bridge.ts+++ b/packages/core/src/runtime/bridge.ts@@ -22,6 +22,7 @@ type BridgeDeps = {onSetPlaybackRate: (rate: number) => void;onSetIdleHeartbeat: (slow: boolean) => void;onSetRootDuration: (durationSeconds: number) => void;+ onSetPlayRange: (startSeconds: number, endSeconds: number | null) => void;onSetColorGrading: (target: HfColorGradingTarget | string | null, grading: unknown) => void;onSetColorGradingCompare: (target: HfColorGradingTarget | string | null,@@ -74,6 +75,11 @@ const CONTROL_HANDLERS = new Map<string, ControlHandler>("set-playback-rate": (data, deps) => deps.onSetPlaybackRate(Number(data.playbackRate ?? 1)),"set-idle-heartbeat": (data, deps) => deps.onSetIdleHeartbeat(Boolean(data.slow)),"set-root-duration": (data, deps) => deps.onSetRootDuration(Number(data.durationSeconds ?? 0)),+ "set-play-range": (data, deps) =>+ deps.onSetPlayRange(+ Number(data.startSeconds ?? 0),+ data.endSeconds == null ? null : Number(data.endSeconds),+ ),"set-color-grading": (data, deps) =>deps.onSetColorGrading(data.target ?? null, data.grading ?? null),"set-color-grading-compare": (data, deps) =>diff --git a/packages/core/src/runtime/clock.test.ts b/packages/core/src/runtime/clock.test.tsindex ddea31687b..fbfad2ec33 100644--- a/packages/core/src/runtime/clock.test.ts+++ b/packages/core/src/runtime/clock.test.ts@@ -199,6 +199,28 @@ describe("TransportClock", () => {expect(clock.getDuration()).toBe(Infinity);});+ it("plays to a range's end, stops on its last frame, and runs to the film end once cleared", () => {+ const { clock, advance } = createClock({ duration: 6 });+ clock.setPlayRange(2, 3, 30);+ clock.seek(2);+ clock.play();+ advance(1500);+ expect(clock.now()).toBe(3);+ expect(clock.reachedEnd()).toBe(true);+ expect(clock.getStopTime()).toBeCloseTo(89 / 30, 9);+ clock.pause();+ clock.seek(clock.getStopTime());+ expect(clock.reachedEnd()).toBe(true);+ expect(clock.getDuration()).toBe(6);+ expect(clock.getPlayStart()).toBe(2);+ clock.setPlayRange(0, null, 30);+ expect(clock.reachedEnd()).toBe(false);+ expect(clock.getStopTime()).toBe(6);+ clock.play();+ advance(5000);+ expect(clock.now()).toBe(6);+ });+it("reachedEnd returns false when no duration set", () => {const { clock, advance } = createClock();clock.play();diff --git a/packages/core/src/runtime/clock.ts b/packages/core/src/runtime/clock.tsindex 1bae66df7c..4d7deabfb3 100644--- a/packages/core/src/runtime/clock.ts+++ b/packages/core/src/runtime/clock.ts@@ -1,5 +1,6 @@import { timeAtSourceTime, type RateSpec } from "../speedRamp.js";import { MEDIA_HARD_SYNC_SECONDS } from "./media.js";+import { playRangeHoldTime } from "./protocol.js";export type TransportClockSnapshot = {time: number;@@ -31,6 +32,9 @@ export class TransportClock {private _playStartMs: number | null = null;private _rate = 1;private _duration = Infinity;+ private _playStart = 0;+ private _playEnd = Infinity;+ private _playHold = Infinity;private _nowMs: () => number;private _audioSource: AudioClockSource | null = null;/** Wall-clock time of the last `now()` read while playing; null while paused. */@@ -64,7 +68,7 @@ export class TransportClock {audioTime = this._elementTimeNeverBehind(this._audioSource);}if (audioTime !== null) {- const t = Number.isFinite(this._duration) ? Math.min(audioTime, this._duration) : audioTime;+ const t = Math.min(audioTime, this.getEnd());this._baseTime = Math.max(0, t);this._playStartMs = this._nowMs();this._lastReadMs = null;@@ -77,7 +81,7 @@ export class TransportClock {this._applyStallCorrection();const elapsed = (this._nowMs() - this._playStartMs) / 1000;const t = this._baseTime + elapsed * this._rate;- this._lastNow = Math.max(0, Number.isFinite(this._duration) ? Math.min(t, this._duration) : t);+ this._lastNow = Math.max(0, Math.min(t, this.getEnd()));return this._lastNow;}@@ -113,7 +117,7 @@ export class TransportClock {play(): boolean {if (this._playStartMs !== null) return false;- if (Number.isFinite(this._duration) && this._baseTime >= this._duration) return false;+ if (this._baseTime >= this.getEnd()) return false;this._playStartMs = this._nowMs();this._lastNow = this._baseTime;// Not a stall: the gap since the clock was last read (possibly a long@@ -174,6 +178,25 @@ export class TransportClock {return this._duration;}+ setPlayRange(start: number, end: number | null, fps: number): void {+ this._playStart = Number.isFinite(start) && start > 0 ? start : 0;+ this._playEnd = end !== null && Number.isFinite(end) && end > this._playStart ? end : Infinity;+ this._playHold = playRangeHoldTime(this._playStart, this._playEnd, fps);+ }++ getPlayStart(): number {+ return this._playStart;+ }++ getEnd(): number {+ return Math.min(this._duration, this._playEnd);+ }++ /** Where a stop parks: the film's end, or a range's last frame, since the moment is [start, end). */+ getStopTime(): number {+ return this._playEnd < this._duration ? this._playHold : this.getEnd();+ }+attachAudioSource(source: AudioClockSource): void {this._audioSource = source;}@@ -218,6 +241,7 @@ export class TransportClock {}reachedEnd(): boolean {- return Number.isFinite(this._duration) && this.now() >= this._duration;+ const time = this.now();+ return time >= this.getEnd() || (this._playStartMs === null && time >= this.getStopTime());}}diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex 408d4064d3..8e9e329eee 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -3710,9 +3710,10 @@ export function initSandboxRuntimeModular(): void {if (dur > 0) {clock.setDuration(dur);if (clock.reachedEnd()) {- clock.seek(0);- state.currentTime = 0;- seekTimelineAndAdapters(0);+ const start = clock.getPlayStart();+ clock.seek(start);+ state.currentTime = start;+ seekTimelineAndAdapters(start);}} else {const rootEl = resolveRootCompositionElement();@@ -4594,21 +4595,19 @@ export function initSandboxRuntimeModular(): void {colorGrading.redrawAnimated();}- // Looping is handled at the player layer (<hyperframes-player>),- // not the runtime. The clock pauses at duration; GSAP's repeat:-1- // is bypassed because we drive tl.totalTime(t) directly. The- // parent observes isPlaying=false at end and re-issues seek(0)+play()- // if its loop attribute is set.+ // The clock stops at its end (GSAP's repeat:-1 is bypassed: we drive+ // tl.totalTime(t) directly); the parent loops by seeking to its range+ // start, or 0, and playing again.if (clock.isPlaying() && clock.reachedEnd()) {webAudio.stopAll();clock.detachAudioSource();clock.pause();state.isPlaying = false;- const dur = clock.getDuration();- if (Number.isFinite(dur)) {- clock.seek(dur);- state.currentTime = dur;- seekTimelineAndAdapters(dur);+ const stop = clock.getStopTime();+ if (Number.isFinite(stop)) {+ clock.seek(stop);+ state.currentTime = stop;+ seekTimelineAndAdapters(stop);}runAdapters("pause");syncMediaForCurrentState(timingRevision);@@ -4890,6 +4889,15 @@ export function initSandboxRuntimeModular(): void {wakeTransport();},onSetRootDuration: growRootDurationLive,+ onSetPlayRange: (startSeconds, endSeconds) => {+ clock.setPlayRange(startSeconds, endSeconds, state.canonicalFps);+ const start = clock.getPlayStart();+ if (clock.isPlaying() && (clock.now() < start || clock.reachedEnd())) {+ transport.seek(start, { keepPlaying: true });+ return;+ }+ postState(true);+ },onSetColorGrading: (target, grading) => {colorGrading.setGrading(target, grading);},@@ -4906,11 +4914,11 @@ export function initSandboxRuntimeModular(): void {clock.detachAudioSource();clock.pause();state.isPlaying = false;- const dur = clock.getDuration();- if (Number.isFinite(dur)) {- clock.seek(dur);- state.currentTime = dur;- seekTimelineAndAdapters(dur);+ const stop = clock.getStopTime();+ if (Number.isFinite(stop)) {+ clock.seek(stop);+ state.currentTime = stop;+ seekTimelineAndAdapters(stop);}runAdapters("pause");syncMediaForCurrentState();diff --git a/packages/core/src/runtime/protocol.ts b/packages/core/src/runtime/protocol.tsindex 653d9f6176..f6a4eccbc2 100644--- a/packages/core/src/runtime/protocol.ts+++ b/packages/core/src/runtime/protocol.ts@@ -6,6 +6,7 @@ export const RUNTIME_PROTOCOL_CAPABILITIES = ["seek-keep-playing","composition-manifest-v1","runtime-data",+ "play-range",] as const;export type RuntimeProtocolFps = {@@ -47,6 +48,10 @@ export function runtimeProtocolFpsFromNumber(value: number): RuntimeProtocolFpsreturn { numerator: numerator / divisor, denominator: denominator / divisor };}+export function playRangeHoldTime(start: number, end: number, fps: number): number {+ return Math.max(start, (Math.ceil(end * fps - 1e-6) - 1) / fps);+}+export function runtimeProtocolFpsToNumber(value: unknown): number | null {if (typeof value !== "object" || value === null) return null;const fps = value as Partial<RuntimeProtocolFps>;diff --git a/packages/core/src/runtime/transportPark.test.ts b/packages/core/src/runtime/transportPark.test.tsindex fa99cd78d4..2a030639d5 100644--- a/packages/core/src/runtime/transportPark.test.ts+++ b/packages/core/src/runtime/transportPark.test.ts@@ -206,6 +206,88 @@ describe("parked transport loop", () => {expect(states.at(-1)).toMatchObject({ isPlaying: false, ended: true, frame: 149 });});+ const setPlayRange = (startSeconds: number | null, endSeconds: number | null) =>+ window.dispatchEvent(+ new MessageEvent("message", {+ source: window.parent,+ data: {+ source: "hf-parent",+ type: "control",+ action: "set-play-range",+ startSeconds,+ endSeconds,+ },+ }),+ );+ const stateMessages = () => posted.filter((m) => m["type"] === "state");++ /** Mounts a 5 s film with clips a [0, 3) and b [3, 5), driven by a mocked clock. */+ const mountRangeFilm = () => {+ let nowMs = 1000;+ vi.spyOn(performance, "now").mockImplementation(() => nowMs);+ mount(+ `<div id="a" data-start="0" data-duration="3"></div><div id="b" data-start="3" data-duration="2"></div>`,+ );+ const timeline = window.__timelines!.main!;+ initSandboxRuntimeModular();+ quiesce();+ const frames: Array<{ time: number; b: string }> = [];+ const step = () => {+ nowMs += 7;+ raf.step(7);+ frames.push({ time: timeline.time(), b: document.getElementById("b")!.style.visibility });+ };+ const playOut = () => {+ window.__player!.play();+ for (let n = 0; n < 1000 && window.__player!.isPlaying(); n += 1) step();+ };+ return { timeline, frames, step, playOut };+ };++ it("stops on a play range's last frame, says it ended, and restarts at the range start only while it is set", () => {+ const { timeline, frames, playOut } = mountRangeFilm();++ setPlayRange(2, 3);+ window.__player!.seek(2);+ for (let wrap = 0; wrap < 3; wrap += 1) playOut();+ expect(stateMessages().at(-1)).toMatchObject({ isPlaying: false, ended: true, frame: 89 });+ expect(stateMessages().at(-1)?.["currentTime"]).toBeCloseTo(89 / 30, 9);+ expect(timeline.time()).toBeCloseTo(89 / 30, 9);+ expect(Math.max(...frames.map((f) => f.time))).toBeLessThan(3);+ expect(frames.every((f) => f.b === "hidden")).toBe(true);+ expect(document.getElementById("a")!.style.visibility).not.toBe("hidden");+ expect(window.__player!.getDuration()).toBe(5);++ const before = stateMessages().length;+ window.__player!.play();+ expect(stateMessages()[before]).toMatchObject({ isPlaying: true, frame: 60 });+ window.__player!.pause();++ setPlayRange(null, null);+ playOut();+ expect(stateMessages().at(-1)).toMatchObject({ isPlaying: false, ended: true, frame: 150 });+ const atFilmEnd = stateMessages().length;+ window.__player!.play();+ expect(stateMessages()[atFilmEnd]).toMatchObject({ isPlaying: true, frame: 0 });+ });++ it("jumps to the range start and keeps playing when a new range leaves the playhead outside", () => {+ const { step } = mountRangeFilm();+ setPlayRange(2, 3);+ window.__player!.seek(2.5);+ window.__player!.play();+ step();+ const before = stateMessages().length;++ setPlayRange(2, 2.4);++ const after = stateMessages().slice(before);+ expect(after.some((m) => m["ended"] === true)).toBe(false);+ expect(after.at(-1)).toMatchObject({ isPlaying: true, currentTime: 2 });+ expect(after.at(-1)?.["capabilities"]).toContain("play-range");+ expect(window.__player!.isPlaying()).toBe(true);+ });+// The render stops at the root's declared length too; a longer animation is cut off.it.each([["3 s, shorter than its animation", "3", 90],diff --git a/packages/core/src/runtime/types.ts b/packages/core/src/runtime/types.tsindex 1ea0823d52..eecdda6ce4 100644--- a/packages/core/src/runtime/types.ts+++ b/packages/core/src/runtime/types.ts@@ -22,6 +22,7 @@ type RuntimeBridgeControlActionBase =| "set-web-audio-media-disabled"| "set-idle-heartbeat"| "set-root-duration"+ | "set-play-range"| "stop-media"| "flash-elements";@@ -34,6 +35,8 @@ type RuntimeBridgeControlMessageBase = {muted?: boolean;volume?: number;durationSeconds?: number;+ startSeconds?: number | null;+ endSeconds?: number | null;disabled?: boolean;slow?: boolean;playbackRate?: number;diff --git a/packages/player/README.md b/packages/player/README.mdindex a38e92605b..329c6e54db 100644--- a/packages/player/README.md+++ b/packages/player/README.md@@ -84,6 +84,10 @@ Show a static image before playback starts:| `assets-loading-ui` | `player \| none` | `player` | `none` never shows the loading-assets card; asset events still fire || `low-power-idle` | boolean | false | While paused, check in once a second, not every 80 ms (many-player pages) || `disable-click-to-play` | boolean | false | A click on the player no longer plays or pauses (host overlays own clicks) |+| `range-start` | number | — | Film second where playback starts, loops back to and parks when paused |+| `range-end` | number | — | Film second the range ends before: it stops or loops on the frame before it |++`range-start` and `range-end` play the moment [start, end) of the film. The player parks on `range-start` at `ready`, and again when a paused playhead falls outside a new range; `play()` from outside the range starts there. At the end it holds the last frame before `range-end` and fires `ended`, or wraps to `range-start` with `loop`. A current runtime stops on that frame itself; video and `__timelines` players stop on their next clock tick and step back to it; an older runtime stops when the player sees its time pass the end. `currentTime` and `duration` stay in film time. A range past the film is cut to its end and an empty or negative one is ignored; both fire `rangeclamped`.### Shader transition previews@@ -149,6 +153,8 @@ player.playbackRate; // number (read/write)player.muted; // boolean (read/write)player.audioLocked; // boolean (read/write) — force-mute + hide volume controlsplayer.loop; // boolean (read/write)+player.rangeStart; // number | null (read/write, mirrors range-start)+player.rangeEnd; // number | null (read/write, mirrors range-end)player.shaderCaptureScale; // number (read/write)player.shaderLoading; // "composition" | "player" | "none" (read/write)@@ -250,6 +256,7 @@ function StudioPreview({ src }: { src: string }) {| `pause` | — | Playback paused || `timeupdate` | `{ currentTime }` | Playback position changed (~10 fps) || `ended` | — | Reached the end (when not looping) |+| `rangeclamped` | `{ rangeStart, rangeEnd, duration }` | The range was cut to the film, or ignored || `error` | `{ message }` (video mode: `{ message, code }`) | Composition or video failed to load || `playbackerror` | `{ source, error }` | The browser blocked playback || `shadertransitionstate` | `{ compositionId, state }` | Shader transition cache/capture progress |diff --git a/packages/player/src/direct-timeline-clock.ts b/packages/player/src/direct-timeline-clock.tsindex da5c45d803..0fd872736b 100644--- a/packages/player/src/direct-timeline-clock.ts+++ b/packages/player/src/direct-timeline-clock.ts@@ -10,6 +10,7 @@import type { DirectTimelineAdapter } from "./timeline-adapters.js";const UI_UPDATE_INTERVAL_MS = 100;+const CURRENT_TIME_ROUNDING_S = 1e-3;export interface ClockCallbacks {/** Called every ~100ms and on completion with the current time. */@@ -24,9 +25,21 @@ export interface ClockCallbacks {onPaused: () => void;}+// A range ending inside the film stops a check early, so the frame past it does not show.+function reachedStop(+ time: number,+ lookAhead: number,+ stop: { end: number; shown: number },+): boolean {+ if (stop.end <= 0) return false;+ const early = stop.shown < stop.end && lookAhead > 0 ? lookAhead + CURRENT_TIME_ROUNDING_S : 0;+ return time + early >= stop.end;+}+export class DirectTimelineClock {private _raf: number | null = null;private _lastUpdateMs = 0;+ private _tick: (() => void) | null = null;constructor(private readonly _callbacks: ClockCallbacks) {}@@ -35,8 +48,12 @@ export class DirectTimelineClock {getCurrentTime: () => number,getDuration: () => number,isPaused: () => boolean,+ getStop: () => { end: number; shown: number },): void {this.stop();+ let lastTime: number | null = null;+ let lastStep = 0;+ let lookAhead = 0;const tick = () => {if (isPaused()) {@@ -53,9 +70,18 @@ export class DirectTimelineClock {}const duration = getDuration();- if (duration > 0) currentTime = Math.min(currentTime, duration);-- const completedPlayback = duration > 0 && currentTime >= duration;+ const stop = getStop();+ if (stop.end > 0) currentTime = Math.min(currentTime, stop.end);++ // The smaller of the last two moves, so one slow frame or a jump does not end the range early.+ const step = lastTime === null ? 0 : currentTime - lastTime;+ if (step !== 0) {+ lookAhead = Math.min(step, lastStep);+ lastStep = step;+ }+ lastTime = currentTime;+ const completedPlayback = reachedStop(currentTime, lookAhead, stop);+ if (completedPlayback) currentTime = stop.shown;const now = performance.now();if (now - this._lastUpdateMs > UI_UPDATE_INTERVAL_MS || completedPlayback) {@@ -70,6 +96,7 @@ export class DirectTimelineClock {}try {timeline.pause();+ if (stop.shown < stop.end) timeline.seek(stop.shown, false);} catch {/* ignore */}@@ -81,9 +108,17 @@ export class DirectTimelineClock {this._raf = requestAnimationFrame(tick);};+ this._tick = tick;this._raf = requestAnimationFrame(tick);}+ /** Runs one check now, for a hidden tab, which runs no animation frames. */+ poll(): void {+ if (this._raf === null || !this._tick) return;+ cancelAnimationFrame(this._raf);+ this._tick();+ }+stop(): void {if (this._raf === null) return;cancelAnimationFrame(this._raf);diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.tsindex c0b0158ad3..ca5a315b28 100644--- a/packages/player/src/hyperframes-player.ts+++ b/packages/player/src/hyperframes-player.ts@@ -5,6 +5,12 @@ import { DirectTimelineClock } from "./direct-timeline-clock.js";import { ParentMediaManager } from "./parent-media.js";import { isRealmHtmlMediaElement } from "./media-element-guards.js";import { handleRuntimeMessage } from "./runtime-message-handler.js";+import {+ isOutsidePlayRange,+ type PlayRange,+ playRangeStopTime,+ resolvePlayRange,+} from "./play-range.js";import {SHADER_CAPTURE_SCALE_ATTR,SHADER_LOADING_ATTR,@@ -47,6 +53,8 @@ const ASSETS_LOADING_ATTR = "assets-loading";const ASSETS_LOADING_UI_ATTR = "assets-loading-ui";const LOW_POWER_IDLE_ATTR = "low-power-idle";const DISABLE_CLICK_TO_PLAY_ATTR = "disable-click-to-play";+const RANGE_START_ATTR = "range-start";+const RANGE_END_ATTR = "range-end";// paint-and-idle now always has a frame to wait on, so the overlay would// flash on every single Play without this debounce. ponytail: 150ms is// unmeasured, retune once there's production data on paint-and-idle timing.@@ -104,6 +112,8 @@ class HyperframesPlayer extends HTMLElement {SHADER_LOADING_ATTR,ASSETS_LOADING_UI_ATTR,LOW_POWER_IDLE_ATTR,+ RANGE_START_ATTR,+ RANGE_END_ATTR,];}@@ -148,6 +158,9 @@ class HyperframesPlayer extends HTMLElement {private _pendingRuntimeData = new Map<string, PendingRuntimeDataDelivery>();private _afterUpdate: Array<() => void> | null = null;private _videoSource: VideoSource | null = null;+ private _runtimeOwnsPlayRange = false;+ private _enteringRange = false;+ private _rangeClampReported = "";constructor() {super();@@ -178,7 +191,7 @@ class HyperframesPlayer extends HTMLElement {},getLoop: () => this.loop,restart: () => {- this.seek(0);+ this.seek(this._playRange()?.start ?? 0);this.play();},onPaused: () => {@@ -338,6 +351,10 @@ class HyperframesPlayer extends HTMLElement {case LOW_POWER_IDLE_ATTR:this._sendControl("set-idle-heartbeat", { slow: val !== null });break;+ case RANGE_START_ATTR:+ case RANGE_END_ATTR:+ this._applyPlayRange(true);+ break;case SHADER_CAPTURE_SCALE_ATTR:case SHADER_LOADING_ATTR:case RUNTIME_SRC_ATTR:@@ -385,8 +402,12 @@ class HyperframesPlayer extends HTMLElement {return this._scenes;}- // fallow-ignore-next-line complexityplay() {+ this._play(true);+ }++ // fallow-ignore-next-line complexity+ private _play(announce: boolean) {if (this._ready && !this._assetsReady) {this._pendingPlay = true;return;@@ -394,7 +415,13 @@ class HyperframesPlayer extends HTMLElement {this._pendingPlay = false;this.posterEl?.remove();this.posterEl = null;- if (this._duration > 0 && this._currentTime >= this._duration) this.seek(0);+ const range = this._ready ? this._playRange() : null;+ if (range) {+ if (isOutsidePlayRange(this._currentTime, range, this._duration, this._runtimeFps)) {+ this.seek(range.start);+ this._enteringRange = true;+ }+ } else if (this._duration > 0 && this._currentTime >= this._duration) this.seek(0);// Must be set before _startParentTickClock so the RAF loop's `_paused`// check doesn't immediately self-terminate on the first callback.this._paused = false;@@ -417,13 +444,14 @@ class HyperframesPlayer extends HTMLElement {}if (this._media.audioOwner === "parent") this._media.playAll();this.controlsApi?.updatePlaying(true);- if (!queuedForReady) this._emit(new Event("play"));+ if (!queuedForReady && announce) this._emit(new Event("play"));if (directTimelineStarted && this._directTimelineAdapter) {this._directTimelineClock.start(this._directTimelineAdapter,() => this._currentTime,() => this._duration,() => this._paused,+ () => this._clockStop(),);}}@@ -688,6 +716,98 @@ class HyperframesPlayer extends HTMLElement {else this.removeAttribute("loop");}+ /** Film time where range playback starts; null (no `range-start`) starts at 0. */+ get rangeStart(): number | null {+ return this._readSeconds(RANGE_START_ATTR);+ }+ set rangeStart(seconds: number | null) {+ this._writeSeconds(RANGE_START_ATTR, seconds);+ }++ /** Film time where range playback ends or loops; null (no `range-end`) plays to the end.+ * When it ends inside the film, `currentTime` at `ended` is inside its last frame, before this. */+ get rangeEnd(): number | null {+ return this._readSeconds(RANGE_END_ATTR);+ }+ set rangeEnd(seconds: number | null) {+ this._writeSeconds(RANGE_END_ATTR, seconds);+ }++ private _readSeconds(name: string): number | null {+ const value = this.getAttribute(name);+ return value === null ? null : Number(value);+ }++ private _writeSeconds(name: string, seconds: number | null): void {+ if (seconds == null) this.removeAttribute(name);+ else this.setAttribute(name, String(seconds));+ }++ private _hasPlayRange(): boolean {+ return this.hasAttribute(RANGE_START_ATTR) || this.hasAttribute(RANGE_END_ATTR);+ }++ private _playRange(): PlayRange | null {+ return resolvePlayRange(this.rangeStart, this.rangeEnd, this._duration).range;+ }++ private _sendPlayRange(range: PlayRange | null): void {+ const endSeconds = range?.end ?? null;+ this._sendControl("set-play-range", { startSeconds: range?.start ?? null, endSeconds });+ }++ /** A new range or duration: the runtime gets the new end and the host hears of a clamp. With+ * `park`, a paused player moves to the start and a playing one outside the range jumps there;+ * a queued play() starts at the range start itself. */+ private _applyPlayRange(park: boolean): void {+ const { range, clamped } = resolvePlayRange(this.rangeStart, this.rangeEnd, this._duration);+ this._sendPlayRange(range);+ if (!this._ready) return;+ this._reportRangeClamp(range, clamped);+ if (range && park && !this._pendingPlay) this._moveIntoPlayRange(range);+ }++ // Once per asked-for range and duration.+ private _reportRangeClamp(range: PlayRange | null, clamped: boolean): void {+ const clampKey = clamped ? `${this.rangeStart},${this.rangeEnd},${this._duration}` : "";+ if (clampKey === this._rangeClampReported) return;+ this._rangeClampReported = clampKey;+ if (!clamped) return;+ const detail = { rangeStart: range?.start ?? null, rangeEnd: range?.end ?? null };+ this._emit(+ new CustomEvent("rangeclamped", { detail: { ...detail, duration: this._duration } }),+ );+ }++ private _moveIntoPlayRange(range: PlayRange): void {+ if (!isOutsidePlayRange(this._currentTime, range, this._duration, this._runtimeFps)) return;+ if (this._paused) this.seek(range.start);+ else this._jumpWhilePlaying(range.start);+ }++ /** A `play-range` runtime jumps by itself and a player clock seeks without pausing; an older+ * runtime is seeked and resumed, with no second `play` event. */+ private _jumpWhilePlaying(time: number): void {+ if (this._directTimelineAdapter) {+ this._directTimelineAdapter.seek(time, false);+ this._currentTime = time;+ } else if (!this._runtimeOwnsPlayRange) {+ this.seek(time);+ this._enteringRange = true;+ this._play(false);+ }+ }++ /** Where the player's own clock stops, and the time it then shows: mid last frame, since a video+ * seeked onto a frame boundary can decode the frame before it. */+ private _clockStop(): { end: number; shown: number } {+ const range = this._playRange();+ const end = range?.end ?? this._duration;+ if (!range) return { end, shown: end };+ const hold = playRangeStopTime(range, this._duration, this._runtimeFps);+ return { end, shown: hold < end ? (hold + end) / 2 : hold };+ }+private _sendControl(action: string, extra: Record<string, unknown> = {}): boolean {try {const frameWindow = this.iframe.contentWindow;@@ -941,6 +1061,10 @@ class HyperframesPlayer extends HTMLElement {onPause: (video) => {if (video.paused && !video.ended && !this._paused) this.pause();},+ // A background tab runs no animation frames; a range's end is checked on timeupdate instead.+ onTimeUpdate: () => {+ if (document.hidden && this._playRange()) this._directTimelineClock.poll();+ },onError: (message, code) => {if (!this._paused) this.pause();this._emit(new CustomEvent("error", { detail: { message, code } }));@@ -1103,8 +1227,10 @@ class HyperframesPlayer extends HTMLElement {duration: this._duration,paused: this._paused,lastUpdateMs: this._lastUpdateMs,+ enteringRange: this._enteringRange,}),- setPlaybackState: ({ currentTime, duration, paused, lastUpdateMs }) => {+ setPlaybackState: ({ currentTime, duration, paused, lastUpdateMs, enteringRange }) => {+ this._enteringRange = enteringRange === true;this._currentTime = currentTime;this._setDuration(duration);this._paused = paused;@@ -1118,6 +1244,7 @@ class HyperframesPlayer extends HTMLElement {onRuntimeReady: () => {this._runtimeBridgeReady = true;this._replayBridgeState();+ if (this._hasPlayRange()) this._sendPlayRange(this._playRange());this._replayRuntimeData();},onRuntimeAssetsReady: () => {@@ -1134,6 +1261,9 @@ class HyperframesPlayer extends HTMLElement {setRuntimeFps: (fps) => {this._runtimeFps = fps;},+ setRuntimeOwnsPlayRange: (owns) => {+ this._runtimeOwnsPlayRange = owns;+ },shouldPromoteMediaAutoplayFallback: () => !this._isSlideshowPlayer(),setScenes: (scenes) => {this._scenes = scenes;@@ -1145,6 +1275,7 @@ class HyperframesPlayer extends HTMLElement {seek: (t) => this.seek(t),play: () => this.play(),getLoop: () => this.loop,+ getPlayRange: () => this._playRange(),media: this._media,});}@@ -1291,6 +1422,8 @@ class HyperframesPlayer extends HTMLElement {}private _releaseDocument(): void {+ this._runtimeOwnsPlayRange = false;+ this._enteringRange = false;this._directTimelineAdapter = null;this._directTimelineClock.stop();this._stopParentTickClock();@@ -1325,13 +1458,17 @@ class HyperframesPlayer extends HTMLElement {this._emit(new CustomEvent("ready", { detail }));// Once ready: covers a size message that never came, and lets a zero-size player warn.this._rescale();+ this._rangeClampReported = "";+ if (this._hasPlayRange()) this._applyPlayRange(true);}/** `ready` carries the first duration; later changes fire `durationchange`. */private _setDuration(duration: number): void {if (duration === this._duration) return;this._duration = duration;- if (this._ready) this._emit(new CustomEvent("durationchange", { detail: { duration } }));+ if (!this._ready) return;+ this._emit(new CustomEvent("durationchange", { detail: { duration } }));+ if (this._hasPlayRange()) this._applyPlayRange(false);}private _setCompositionSize(width: number, height: number): void {diff --git a/packages/player/src/play-range.ts b/packages/player/src/play-range.tsnew file mode 100644index 0000000000..9cf9952fba--- /dev/null+++ b/packages/player/src/play-range.ts@@ -0,0 +1,38 @@+// Range playback: the `range-start` / `range-end` attributes, in film seconds.++import { playRangeHoldTime } from "@hyperframes/core/runtime/protocol";++export interface PlayRange {+ start: number;+ end: number | null;+}++/** The range the player applies for the attributes, and whether it differs from the one asked for:+ * an end past the film is cut to the film's end, and an empty or negative range applies no range. */+export function resolvePlayRange(+ start: number | null,+ end: number | null,+ duration: number,+): { range: PlayRange | null; clamped: boolean } {+ if (start === null && end === null) return { range: null, clamped: false };+ const from = start ?? 0;+ const cut = end !== null && duration > 0 && end > duration;+ const to = cut ? duration : end;+ const limit = to ?? (duration > 0 ? duration : Infinity);+ if (!(from >= 0) || !(limit > from)) return { range: null, clamped: true };+ return { range: { start: from, end: to }, clamped: cut };+}++export function playRangeStopTime(range: PlayRange, duration: number, fps: number): number {+ const end = range.end ?? duration;+ return end < duration ? playRangeHoldTime(range.start, end, fps) : end;+}++export function isOutsidePlayRange(+ time: number,+ range: PlayRange,+ duration: number,+ fps: number,+): boolean {+ return time < range.start || time >= playRangeStopTime(range, duration, fps);+}diff --git a/packages/player/src/playback-state.ts b/packages/player/src/playback-state.tsindex c68a29467c..6d34b03a2d 100644--- a/packages/player/src/playback-state.ts+++ b/packages/player/src/playback-state.ts@@ -7,6 +7,7 @@*/import type { ParentMediaManager } from "./parent-media.js";+import { type PlayRange, playRangeStopTime } from "./play-range.js";const UI_UPDATE_INTERVAL_MS = 100;@@ -15,6 +16,7 @@ export interface PlaybackState {duration: number;paused: boolean;lastUpdateMs: number;+ enteringRange?: boolean;}export interface PlaybackStateCallbacks {@@ -24,6 +26,7 @@ export interface PlaybackStateCallbacks {seek: (t: number) => void;play: () => void;getLoop: () => boolean;+ getPlayRange?: () => PlayRange | null;media: ParentMediaManager;}@@ -32,6 +35,7 @@ type RuntimeStateData = {isPlaying: boolean;currentTime?: number;ended?: boolean;+ ownsRange?: boolean;};/** The runtime's exact time when it sends one (older runtimes send only the whole frame). */@@ -49,6 +53,55 @@ function isAtEnd(data: RuntimeStateData, time: number, duration: number): booleareturn time >= duration;}+type PlayBounds = {+ start: number;+ shownAtEnd: number;+ atEnd: boolean;+ stopRuntime: boolean;+ entering: boolean;+};++/** A `play-range` runtime says when a range ended. For an older one the player reads the time,+ * and after it jumps into the range only from a state inside it, never a stale one. */+function playBounds(+ data: RuntimeStateData,+ time: number,+ current: PlaybackState,+ playing: boolean,+ range: PlayRange | null | undefined,+ fps: number,+): PlayBounds {+ const { duration } = current;+ if (!range) {+ const atEnd = isAtEnd(data, time, duration);+ return { start: 0, shownAtEnd: duration, atEnd, stopRuntime: false, entering: false };+ }+ if (data.ownsRange) {+ const atEnd = playing && data.ended === true && !data.isPlaying;+ return { start: range.start, shownAtEnd: time, atEnd, stopRuntime: false, entering: false };+ }+ return olderRuntimeBounds(data, time, current, playing, range, fps);+}++function olderRuntimeBounds(+ data: RuntimeStateData,+ time: number,+ current: PlaybackState,+ playing: boolean,+ range: PlayRange,+ fps: number,+): PlayBounds {+ const end = range.end ?? current.duration;+ const entering = current.enteringRange === true && (time < range.start || time >= end);+ return {+ start: range.start,+ shownAtEnd: playRangeStopTime(range, current.duration, fps),+ atEnd: playing && !entering && isAtEnd(data, time, end),+ stopRuntime: data.isPlaying,+ entering,+ };+}+/*** Process a `state` message from the runtime and return the next state.* Side effects (controls updates, events, media mirroring) are fired through@@ -61,23 +114,26 @@ export function applyRuntimeStateMessage(callbacks: PlaybackStateCallbacks,): PlaybackState {const rawTime = runtimeTime(data, fps);- const atEnd = isAtEnd(data, rawTime, current.duration);- const clampedTime = current.duration > 0 ? Math.min(rawTime, current.duration) : rawTime;- const currentTime = atEnd ? current.duration : clampedTime;const wasPlaying = !current.paused;+ const playing = wasPlaying || data.isPlaying;+ const range = callbacks.getPlayRange?.();+ const bounds = playBounds(data, rawTime, current, playing, range, fps);+ const { atEnd, start: loopStart } = bounds;+ const clampedTime = current.duration > 0 ? Math.min(rawTime, current.duration) : rawTime;+ const currentTime = atEnd ? bounds.shownAtEnd : clampedTime;const nextPaused = !data.isPlaying;- const completedPlayback = atEnd && (wasPlaying || data.isPlaying);+ const completedPlayback = atEnd && playing;if (completedPlayback && callbacks.getLoop()) {if (callbacks.media.audioOwner === "parent") callbacks.media.pauseAll();- callbacks.seek(0);+ callbacks.seek(loopStart);callbacks.play();// play() sets paused=false; reflect that in the returned state so the// caller's destructure doesn't overwrite it with the stale nextPaused value.- return { ...current, currentTime: 0, paused: false };+ return { ...current, currentTime: loopStart, paused: false, enteringRange: true };}- const next: PlaybackState = { ...current, currentTime, paused: nextPaused };+ const next = { ...current, currentTime, paused: nextPaused, enteringRange: bounds.entering };if (callbacks.media.audioOwner === "parent") {if (wasPlaying && nextPaused) {@@ -98,6 +154,8 @@ export function applyRuntimeStateMessage(}if (completedPlayback) {+ // A runtime without play-range plays on past the range: stop it on the last frame inside.+ if (bounds.stopRuntime) callbacks.seek(currentTime);if (callbacks.media.audioOwner === "parent") callbacks.media.pauseAll();next.paused = true;callbacks.updateControlsPlaying(false);diff --git a/packages/player/src/range-playback.test.ts b/packages/player/src/range-playback.test.tsnew file mode 100644index 0000000000..51aa05d841--- /dev/null+++ b/packages/player/src/range-playback.test.ts@@ -0,0 +1,486 @@+import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";+import { runtimeProtocolMetadata } from "@hyperframes/core/runtime/protocol";++type Player = HTMLElement & {+ play: () => void;+ pause: () => void;+ seek: (t: number) => void;+ currentTime: number;+ duration: number;+ paused: boolean;+ loop: boolean;+ rangeStart: number | null;+ rangeEnd: number | null;+ iframe: HTMLIFrameElement;+ _assetsReady: boolean;+ _onMessage: (event: MessageEvent) => void;+ _onProbeReady: (result: unknown) => void;+};++// The last frame inside a range ending at 3 s at 30 fps, and the middle of it.+const HOLD_AT_3 = 89 / 30;+const MID_LAST_AT_3 = 89.5 / 30;++let player: Player;+let events: string[];++function createPlayer(attrs: Record<string, string> = {}): Player {+ const el = document.createElement("hyperframes-player") as Player;+ for (const [name, value] of Object.entries(attrs)) el.setAttribute(name, value);+ events = [];+ for (const type of ["ready", "ended", "rangeclamped", "durationchange", "play"]) {+ el.addEventListener(type, (event) => {+ const detail = (event as CustomEvent).detail;+ const shown = type === "rangeclamped" ? ` ${JSON.stringify(detail)}` : "";+ events.push(`${type}@${Number(el.currentTime.toFixed(3))}${shown}`);+ });+ }+ return el;+}++const ranEvents = () => events.filter((e) => !e.startsWith("play@"));++describe("HyperframesPlayer range playback: composition", () => {+ let postSpy: MockInstance<typeof window.postMessage>;+ // A runtime that advertises `play-range` (the current one), or an older one that does not.+ let protocol: Record<string, unknown>;++ const send = (data: Record<string, unknown>) =>+ player._onMessage(+ new MessageEvent("message", {+ source: window,+ data: { source: "hf-preview", ...protocol, ...data },+ }),+ );+ const timeline = (seconds: number) =>+ send({+ type: "timeline",+ durationInFrames: seconds * 30,+ durationSeconds: seconds,+ scenes: [],+ });+ const state = (currentTime: number, isPlaying: boolean, ended = false) =>+ send({ type: "state", frame: Math.round(currentTime * 30), currentTime, isPlaying, ended });+ const controls = (action: string) =>+ postSpy.mock.calls+ .map((call) => call[0] as Record<string, unknown>)+ .filter((data) => data?.type === "control" && data.action === action);+ const seeks = () => controls("seek").map((data) => data.timeSeconds as number);+ const sentRanges = () =>+ controls("set-play-range").map((data) => [data.startSeconds, data.endSeconds]);++ function mount(attrs: Record<string, string> = {}, seconds = 6) {+ player = createPlayer(attrs);+ Object.defineProperty(player.iframe, "contentWindow", {+ configurable: true,+ get: () => window,+ });+ document.body.appendChild(player);+ timeline(seconds);+ player._assetsReady = true;+ }++ beforeEach(async () => {+ await import("./hyperframes-player.js");+ postSpy = vi.spyOn(window, "postMessage").mockImplementation(() => undefined);+ protocol = { ...runtimeProtocolMetadata(30) };+ });++ afterEach(() => {+ document.body.innerHTML = "";+ vi.restoreAllMocks();+ });++ it("parks on range-start at ready and hands the range to the runtime once", () => {+ mount({ "range-start": "2", "range-end": "3" });++ expect(events).toEqual(["ready@2"]);+ expect(seeks()).toEqual([2]);+ expect(sentRanges()).toEqual([[2, 3]]);+ expect(player.paused).toBe(true);+ });++ it("starts a play from outside the range at range-start, and leaves a parked seek alone", () => {+ mount({ "range-start": "2", "range-end": "3" });++ player.seek(5);+ state(5, false, true);+ expect(player.currentTime).toBe(5);+ expect(ranEvents()).toEqual(["ready@2"]);+ player.play();+ expect(seeks()).toEqual([2, 5, 2]);+ expect(player.currentTime).toBe(2);++ player.seek(1);+ player.play();+ expect(seeks().at(-1)).toBe(2);++ player.seek(2.5);+ player.play();+ expect(seeks().at(-1)).toBe(2.5);+ });++ it("ends on the range's last frame when the runtime reports its end there", () => {+ mount({ "range-start": "2", "range-end": "3" });+ player.play();++ state(HOLD_AT_3, false, true);++ expect(ranEvents()).toEqual(["ready@2", "[email protected]"]);+ expect(player.paused).toBe(true);+ expect(player.currentTime).toBe(HOLD_AT_3);+ player.play();+ expect(seeks().at(-1)).toBe(2);+ });++ it("wraps to range-start and keeps playing with loop", () => {+ mount({ "range-start": "2", "range-end": "3", loop: "" });+ player.play();++ state(HOLD_AT_3, false, true);++ expect(seeks()).toEqual([2, 2]);+ expect(player.paused).toBe(false);+ expect(player.currentTime).toBe(2);+ expect(ranEvents()).toEqual(["ready@2"]);+ });++ it("stops an older runtime that plays past the end on the last frame inside, or wraps it", () => {+ protocol = {};+ mount({ "range-start": "2", "range-end": "3" });+ player.play();+ state(3.03, true);+ expect(ranEvents()).toEqual(["ready@2", "[email protected]"]);+ expect(seeks().at(-1)).toBe(HOLD_AT_3);+ expect(player.currentTime).toBe(HOLD_AT_3);+ expect(player.paused).toBe(true);++ player.loop = true;+ player.play();+ state(2.1, true);+ state(3.03, true);+ expect(seeks().slice(-2)).toEqual([2, 2]);+ expect(player.paused).toBe(false);+ });++ for (const runtime of ["a play-range runtime", "an older runtime"]) {+ it(`keeps playing from range-start with ${runtime} when a new end leaves the playhead past it`, () => {+ if (runtime === "an older runtime") protocol = {};+ mount({ "range-start": "2", "range-end": "3" });+ player.play();+ state(2.5, true);+ const seeksBefore = seeks().length;+ const eventsBefore = events.length;++ player.rangeEnd = 2.4;+ state(2.53, true);+ state(2.54, true, true);+ state(2, true);++ expect(events.slice(eventsBefore)).toEqual([]);+ expect(player.paused).toBe(false);+ expect(player.currentTime).toBe(2);+ expect(sentRanges().at(-1)).toEqual([2, 2.4]);+ // A play-range runtime jumps by itself; for an older one the player seeks.+ expect(seeks().slice(seeksBefore)).toEqual(runtime === "an older runtime" ? [2] : []);++ // Past the new end: an older runtime is read from its time, a current one says so.+ if (runtime === "an older runtime") state(2.41, true);+ else state(71 / 30, false, true);+ expect(ranEvents().at(-1)).toBe("[email protected]");+ });+ }++ it("clamps a range past the film to its end and says so once", () => {+ mount({ "range-start": "2", "range-end": "10", loop: "" });+ timeline(6);++ expect(events).toEqual([+ "ready@2",+ 'rangeclamped@2 {"rangeStart":2,"rangeEnd":6,"duration":6}',+ ]);+ expect(sentRanges().at(-1)).toEqual([2, 6]);+ player.play();+ state(6, false, true);+ expect(seeks().at(-1)).toBe(2);+ });++ it("clamps when a later duration makes the range exceed the film", () => {+ mount({ "range-start": "2", "range-end": "5" });+ expect(events).toEqual(["ready@2"]);++ timeline(4);++ expect(events).toEqual([+ "ready@2",+ "durationchange@2",+ 'rangeclamped@2 {"rangeStart":2,"rangeEnd":4,"duration":4}',+ ]);+ expect(sentRanges().at(-1)).toEqual([2, 4]);+ });++ it("plays an empty or negative range as if unset, and says so once", () => {+ mount({ "range-start": "3", "range-end": "2", loop: "" });+ timeline(6);++ expect(events).toEqual([+ "ready@0",+ 'rangeclamped@0 {"rangeStart":null,"rangeEnd":null,"duration":6}',+ ]);+ expect(seeks()).toEqual([]);+ expect(sentRanges().at(-1)).toEqual([null, null]);+ player.play();+ state(6, false, true);+ expect(seeks()).toEqual([0]);++ player.rangeStart = -1;+ expect(events.at(-1)).toBe('rangeclamped@0 {"rangeStart":null,"rangeEnd":null,"duration":6}');+ expect(events.filter((e) => e.startsWith("rangeclamped"))).toHaveLength(2);+ });++ it("re-parks a paused player on a new range's start only when the playhead falls outside it", () => {+ mount({ "range-start": "2", "range-end": "3" });++ player.rangeEnd = 5;+ expect(seeks()).toEqual([2]);+ player.rangeStart = 4;+ expect(seeks()).toEqual([2, 4]);+ player.seek(4.5);+ player.rangeEnd = 4.8;+ expect(seeks().at(-1)).toBe(4.5);+ expect(player.currentTime).toBe(4.5);+ player.rangeEnd = 4.2;+ expect(seeks().at(-1)).toBe(4);+ expect(player.paused).toBe(true);+ expect(sentRanges().at(-1)).toEqual([4, 4.2]);+ });++ it("clears the range in the runtime when both attributes go", () => {+ mount({ "range-start": "2", "range-end": "3" });++ player.removeAttribute("range-start");+ player.removeAttribute("range-end");++ expect(sentRanges().at(-1)).toEqual([null, null]);+ });++ it("reflects range-start and range-end as rangeStart and rangeEnd both ways", () => {+ player = createPlayer();+ expect([player.rangeStart, player.rangeEnd]).toEqual([null, null]);++ player.rangeStart = 1.5;+ player.setAttribute("range-end", "4");+ expect(player.getAttribute("range-start")).toBe("1.5");+ expect(player.rangeEnd).toBe(4);++ player.rangeStart = null;+ player.rangeEnd = undefined as unknown as null;+ expect(player.hasAttribute("range-start")).toBe(false);+ expect(player.hasAttribute("range-end")).toBe(false);+ expect([player.rangeStart, player.rangeEnd]).toEqual([null, null]);+ });++ // Pins the existing whole-film behaviour: no range attribute, no new message, loop from 0.+ it("changes nothing for a player without range attributes", () => {+ mount({ loop: "" });+ send({ type: "ready" });+ player.play();+ state(6, false, true);++ expect([player.rangeStart, player.rangeEnd]).toEqual([null, null]);+ expect(sentRanges()).toEqual([]);+ expect(seeks()).toEqual([0]);+ expect(ranEvents()).toEqual(["ready@0"]);+ });+});++describe("HyperframesPlayer range playback: video and direct timelines", () => {+ let frames: FrameRequestCallback[];+ let playSpy: MockInstance<HTMLMediaElement["play"]>;++ function setMedia(video: HTMLMediaElement, props: Record<string, unknown>) {+ for (const [name, value] of Object.entries(props)) {+ Object.defineProperty(video, name, { configurable: true, writable: true, value });+ }+ }++ function loadVideo(range: Record<string, string>): HTMLVideoElement {+ player = createPlayer({ type: "video/mp4", src: "https://cdn.example.com/film.mp4", ...range });+ document.body.appendChild(player);+ const video = player.shadowRoot!.querySelector("video")!;+ setMedia(video, { duration: 6, videoWidth: 640, videoHeight: 360 });+ video.dispatchEvent(new Event("loadedmetadata"));+ return video;+ }++ function flushFrame() {+ const frame = frames.shift();+ if (!frame) throw new Error("no animation frame queued");+ frame(performance.now());+ }++ beforeEach(async () => {+ await import("./hyperframes-player.js");+ playSpy = vi+ .spyOn(HTMLMediaElement.prototype, "play")+ .mockImplementation(function (this: HTMLMediaElement) {+ setMedia(this, { paused: false });+ return Promise.resolve();+ });+ vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(+ function (this: HTMLMediaElement) {+ setMedia(this, { paused: true });+ },+ );+ vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(() => undefined);+ frames = [];+ vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {+ frames.push(callback);+ return frames.length;+ });+ });++ afterEach(() => {+ document.body.innerHTML = "";+ vi.restoreAllMocks();+ });++ it("parks, stops on the last frame inside, wraps with loop and reports a clamp for a video", () => {+ const video = loadVideo({ "range-start": "2", "range-end": "3" });+ expect(video.currentTime).toBe(2);+ expect(ranEvents()).toEqual(["ready@2"]);++ player.play();+ setMedia(video, { currentTime: 3.01 });+ flushFrame();+ expect(ranEvents()).toEqual(["ready@2", "[email protected]"]);+ expect(video.currentTime).toBeCloseTo(MID_LAST_AT_3, 9);+ expect(player.currentTime).toBeCloseTo(MID_LAST_AT_3, 9);+ expect(player.paused).toBe(true);++ player.loop = true;+ player.play();+ expect(video.currentTime).toBe(2);+ setMedia(video, { currentTime: 3.02 });+ flushFrame();+ expect(video.currentTime).toBe(2);+ expect(playSpy).toHaveBeenCalledTimes(3);+ expect(player.paused).toBe(false);++ const plays = events.filter((e) => e.startsWith("play@")).length;+ player.rangeEnd = 2.5;+ setMedia(video, { currentTime: 2.7 });+ player.rangeStart = 2.1;+ expect(video.currentTime).toBe(2.1);+ expect(player.paused).toBe(false);+ expect(events.filter((e) => e.startsWith("play@"))).toHaveLength(plays);++ setMedia(video, { duration: 2.4 });+ video.dispatchEvent(new Event("durationchange"));+ expect(events.at(-1)).toBe('[email protected] {"rangeStart":2.1,"rangeEnd":2.4,"duration":2.4}');+ });++ it("stops a check early at a range end inside the film, not after one slow frame or at the film's end", () => {+ const video = loadVideo({ "range-end": "3" });++ player.play();+ for (const currentTime of [2.6, 2.617, 2.817, 2.834]) {+ setMedia(video, { currentTime });+ flushFrame();+ }+ expect(player.paused).toBe(false);+ for (const currentTime of [2.95, 2.99]) {+ setMedia(video, { currentTime });+ flushFrame();+ }+ expect(ranEvents()).toEqual(["ready@0", "[email protected]"]);++ player.removeAttribute("range-end");+ player.seek(5.9);+ player.play();+ for (const currentTime of [5.91, 5.95, 5.99, 5.9995]) {+ setMedia(video, { currentTime });+ flushFrame();+ }+ expect(player.paused).toBe(false);+ });++ it("checks a video's range end on its timeupdate while the tab is hidden", () => {+ const video = loadVideo({ "range-end": "3" });++ player.play();+ setMedia(video, { currentTime: 3.01 });+ video.dispatchEvent(new Event("timeupdate"));+ expect(player.paused).toBe(false);++ Object.defineProperty(document, "hidden", { configurable: true, value: true });+ try {+ video.dispatchEvent(new Event("timeupdate"));+ } finally {+ delete (document as { hidden?: boolean }).hidden;+ }+ expect(ranEvents()).toEqual(["ready@0", "[email protected]"]);+ });++ it("stops a check early when the video's time moves once per frame and is rounded down", () => {+ const video = loadVideo({ "range-end": "3" });+ player.play();+ for (const currentTime of [2.9, 2.9, 2.933333, 2.933333, 2.966666]) {+ setMedia(video, { currentTime });+ flushFrame();+ }+ expect(ranEvents()).toEqual(["ready@0", "[email protected]"]);+ });++ it("leaves a video without a range to animation frames while the tab is hidden", () => {+ const video = loadVideo({});+ player.play();+ setMedia(video, { currentTime: 6 });+ Object.defineProperty(document, "hidden", { configurable: true, value: true });+ try {+ video.dispatchEvent(new Event("timeupdate"));+ } finally {+ delete (document as { hidden?: boolean }).hidden;+ }+ expect(ranEvents()).toEqual(["ready@0"]);+ expect(player.paused).toBe(false);+ });++ it("parks, stops on the last frame inside and wraps a same-origin __timelines composition", () => {+ let time = 0;+ const tl = {+ duration: () => 6,+ time: () => time,+ seek: vi.fn((t: number) => void (time = t)),+ play: vi.fn(),+ pause: vi.fn(),+ };+ player = createPlayer({ "range-start": "2", "range-end": "3" });+ Object.defineProperty(player.iframe, "contentWindow", {+ configurable: true,+ get: () => ({ __timelines: { main: tl }, postMessage: vi.fn() }),+ });+ document.body.appendChild(player);+ player._onProbeReady({+ duration: 6,+ adapter: { kind: "direct-timeline", timeline: tl, getDuration: () => 6 },+ compositionSize: null,+ });+ player._assetsReady = true;+ expect(tl.seek).toHaveBeenLastCalledWith(2, false);++ player.play();+ time = 3.02;+ flushFrame();+ expect(ranEvents()).toEqual(["ready@2", "[email protected]"]);+ expect(time).toBeCloseTo(MID_LAST_AT_3, 9);++ player.loop = true;+ player.play();+ time = 3.02;+ flushFrame();+ expect(tl.seek).toHaveBeenLastCalledWith(2, false);+ expect(tl.seek).not.toHaveBeenCalledWith(0, false);+ expect(player.paused).toBe(false);+ });+});diff --git a/packages/player/src/runtime-message-handler.ts b/packages/player/src/runtime-message-handler.tsindex 45b477e272..3d73ec072a 100644--- a/packages/player/src/runtime-message-handler.ts+++ b/packages/player/src/runtime-message-handler.ts@@ -49,6 +49,7 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks {* same-origin composition probe cannot inspect CDN iframes. */onRuntimeTimelineReady: (duration: number, assetsReady: boolean | undefined) => void;setRuntimeFps?: (fps: number) => void;+ setRuntimeOwnsPlayRange?: (owns: boolean) => void;/** Called with the scene list whenever a "timeline" message is received. */setScenes: (scenes: SceneRecord[]) => void;/** Return false to ignore the iframe runtime's audible-media autoplay fallback.@@ -76,6 +77,9 @@ export function handleRuntimeMessage(return;}callbacks.setRuntimeFps?.(protocol.fps);+ const ownsPlayRange =+ protocol.status === "supported" && protocol.metadata.capabilities.includes("play-range");+ callbacks.setRuntimeOwnsPlayRange?.(ownsPlayRange);if (data["type"] === "shader-transition-state") {const state: ShaderTransitionState =@@ -119,6 +123,7 @@ export function handleRuntimeMessage(currentTime: data["currentTime"] as number | undefined,ended: typeof data["ended"] === "boolean" ? data["ended"] : undefined,isPlaying: !!data["isPlaying"],+ ownsRange: ownsPlayRange,},protocol.fps,callbacks.getPlaybackState(),diff --git a/packages/player/src/video-source.ts b/packages/player/src/video-source.tsindex 0d39ce844c..108134136e 100644--- a/packages/player/src/video-source.ts+++ b/packages/player/src/video-source.ts@@ -13,6 +13,7 @@ export interface VideoSourceCallbacks {onResize: (video: HTMLVideoElement) => void;onPlay: (video: HTMLVideoElement) => void;onPause: (video: HTMLVideoElement) => void;+ onTimeUpdate: () => void;onError: (message: string, code: number | null) => void;onPlayRejected: (error: unknown) => void;}@@ -36,6 +37,7 @@ export function createVideoSource(callbacks: VideoSourceCallbacks): VideoSourcevideo.addEventListener("resize", () => callbacks.onResize(video), { signal });video.addEventListener("play", () => callbacks.onPlay(video), { signal });video.addEventListener("pause", () => callbacks.onPause(video), { signal });+ video.addEventListener("timeupdate", () => callbacks.onTimeUpdate(), { signal });video.addEventListener("error",() =>diff --git a/packages/studio/src/player/lib/runtimeProtocol.test.ts b/packages/studio/src/player/lib/runtimeProtocol.test.tsindex 6a13501def..3ec66f79fc 100644--- a/packages/studio/src/player/lib/runtimeProtocol.test.ts+++ b/packages/studio/src/player/lib/runtimeProtocol.test.ts@@ -20,6 +20,7 @@ describe("Studio runtime protocol", () => {"seek-keep-playing","composition-manifest-v1","runtime-data",+ "play-range",],fps: { numerator: 60, denominator: 1 },timeSeconds: 1.25,