Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
9e85e20
perf(core): the preview loads only the media on screen or due next
miguel-heygen Sep 28, 2026
133208d
perf(core): a far clip in the preview stays unloaded until it comes due
miguel-heygen Sep 28, 2026
50310be
fix(core): a far preview clip makes no request before it comes due
miguel-heygen Sep 28, 2026
2798968
perf(core): a playing clip loads the next clip on its track
miguel-heygen Sep 28, 2026
d3a1d05
chore(core): say in one line why the preview parses later clips at pr…
miguel-heygen Sep 28, 2026
c5caff0
fix(core): the Studio timeline stops waiting on clips the preview lef…
miguel-heygen Sep 28, 2026
11071f7
chore: merge origin/main (a0c72ad64) into the preview preload branch
miguel-heygen Sep 28, 2026
217fc93
fix(core): a clip leaving the preview window closes its fetch on a sl…
miguel-heygen Sep 28, 2026
1f9eaeb
refactor(core): name the authored-length check for what it reads
miguel-heygen Sep 28, 2026
df3d160
fix(player): a clip the preview stops preloading drops its parent-fra…
miguel-heygen Sep 29, 2026
6dadc46
chore(player): keep the proxy adoption note in one place
miguel-heygen Sep 29, 2026
36926eb
perf(studio): pause timeline thumbnails while playing preview media w…
miguel-heygen Sep 29, 2026
de8b11d
Revert "perf(studio): pause timeline thumbnails while playing preview…
miguel-heygen Sep 29, 2026
11ccdfe
Merge remote-tracking branch 'origin/main' into perf/runtime-preload-…
miguel-heygen Sep 29, 2026
3df726e
fix(core): preview keeps loop-start clips loaded and drops arms a jum…
miguel-heygen Sep 29, 2026
0ee8586
fix(core): a loop wrap also keeps the loop-in clip's next clip loaded
miguel-heygen Sep 29, 2026
286efb9
fix(core): the preview leaves clips on <source> children out of its r…
miguel-heygen Sep 29, 2026
cc0b4a6
style(core): drop a release comment the commit message already carries
miguel-heygen Sep 29, 2026
55fa648
chore: merge origin/main (6d00d94b4) into the preview preload branch
miguel-heygen Sep 29, 2026
cf01282
fix(core): arm a nested clip timed in root seconds by its real start
miguel-heygen Sep 29, 2026
3a35ffd
fix(core): keep a clip loaded for a step back across its end in the p…
miguel-heygen Sep 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/core/src/compositionReadiness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
settleFirstFrameCompositionReadiness,
} from "./compositionReadiness.js";
import { createRuntimeStartTimeResolver } from "./runtime/startResolver.js";
import { STUDIO_PREVIEW_MARK_META } from "./studioPreviewMark.js";
import { isRuntimeElementVisibleAt } from "./runtime/timeline.js";

function docWith(bodyHtml: string): Document {
Expand Down Expand Up @@ -179,6 +180,23 @@ describe("mediaReadinessInput", () => {
await expect(pending).resolves.toBeUndefined();
});

it("waits on a later clip in Studio's preview only once the runtime has set it to buffer", () => {
const html =
'<video id="deferred" data-start="30" data-duration="5" preload="none" src="a.mp4"></video>' +
'<video id="untrimmed" data-start="30" preload="metadata" src="b.mp4"></video>' +
'<video id="due" data-start="30" data-duration="5" preload="auto" src="c.mp4"></video>';
const preview = docWith(html);
preview.head
.appendChild(preview.createElement("meta"))
.setAttribute("name", STUDIO_PREVIEW_MARK_META);
const plain = docWith(html);
const ids = (doc: Document) =>
scanPendingCompositionAssets(doc, { scope: "all" }).pendingMedia.map((el) => el.id);

expect(ids(preview)).toEqual(["due"]);
expect(ids(plain)).toEqual(["deferred", "untrimmed", "due"]);
});

it("waits on a later scene's image in the full scan unless it is lazy", () => {
const doc = docWith(
'<div data-start="30" data-duration="5"><img id="later" src="later.png">' +
Expand Down
12 changes: 11 additions & 1 deletion packages/core/src/compositionReadiness.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createRuntimeStartTimeResolver } from "./runtime/startResolver.js";
import { isRuntimeElementVisibleAt } from "./runtime/timeline.js";
import type { RuntimeTimelineLike } from "./runtime/types.js";
import { STUDIO_PREVIEW_MARK_META } from "./studioPreviewMark.js";

/** 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
Expand Down Expand Up @@ -103,9 +104,18 @@ export function scanPendingCompositionAssets(
timelineRegistry: runtimeWindow?.__timelines,
includeAuthoredTimingAttrs: true,
});
// Studio's preview buffers a clip off the first frame only once it comes due, as with a lazy image.
const defersMedia = doc.querySelector(`meta[name="${STUDIO_PREVIEW_MARK_META}"]`) !== null;
const pendingMedia = Array.from(doc.querySelectorAll("video, audio"))
.filter(isRealmHtmlMediaElement)
.filter((el) => shouldIncludeAsset(el, scope, resolver, runtimeWindow?.__timelines ?? {}))
.filter((el) =>
shouldIncludeAsset(
el,
defersMedia && el.preload !== "auto" ? FIRST_FRAME_READINESS_SCOPE : scope,
resolver,
runtimeWindow?.__timelines ?? {},
),
)
.filter((el) => el.readyState < HAVE_FUTURE_DATA);
// A lazy image off the first frame loads only once shown, so no scope can wait on it.
const pendingImages = Array.from(doc.querySelectorAll("img"))
Expand Down
325 changes: 325 additions & 0 deletions packages/core/src/runtime/entry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,331 @@ describe("runtime entry", () => {
expect(document.querySelectorAll("style[data-hf-first-pass-hide]")).toHaveLength(0);
});

describe("media preload window", () => {
const loads: HTMLMediaElement[] = [];
const spyLoad = () => {
loads.length = 0;
vi.spyOn(HTMLMediaElement.prototype, "load").mockImplementation(
function (this: HTMLMediaElement) {
loads.push(this);
},
);
};
const loadsOf = (...els: HTMLMediaElement[]) =>
els.map((el) => loads.filter((loaded) => loaded === el).length);
const videos = (root: HTMLElement, ...starts: string[]) =>
starts.map((start) => timed(root, "video", start));
const armed = (...els: HTMLMediaElement[]) => els.map((el) => el.preload === "auto");
afterEach(() => vi.restoreAllMocks());

it("loads a preview's media only on screen or due within the look-ahead, and frees what the playhead left", async () => {
spyLoad();
servePreview();
const [now, soon, later] = videos(mountRoot(), "0", "1.5", "9");

await evaluateRuntime();
expect(armed(now, soon, later)).toEqual([true, true, false]);
expect(later.preload).toBe("none");
expect(loadsOf(now, soon, later)).toEqual([1, 1, 0]);

now.setAttribute("src", "now.mp4");
const srcWrites = new MutationObserver(() => {});
srcWrites.observe(now, { attributeFilter: ["src"] });
window.__player?.seek(7.6);
expect(armed(now, soon, later)).toEqual([false, false, true]);
// The two that left are reloaded empty with src dropped for the reload, ending any fetch in flight.
expect([now.preload, soon.preload]).toEqual(["none", "none"]);
expect(loadsOf(now, soon, later)).toEqual([2, 2, 1]);
expect(srcWrites.takeRecords()).toHaveLength(2);
expect(now.getAttribute("src")).toBe("now.mp4");
});

it("loads a clip with no authored length as a render does, so no reload drops its duration", async () => {
spyLoad();
servePreview();
const [untrimmed, later] = videos(mountRoot(), "0", "8");
untrimmed.removeAttribute("data-duration");
later.removeAttribute("data-duration");
Object.defineProperty(untrimmed, "readyState", { value: 1 });
Object.defineProperty(untrimmed, "duration", { value: 2 });

await evaluateRuntime();
window.__player?.seek(3.6);
window.__player?.seek(0.5);
window.__player?.seek(7.5);
expect(armed(untrimmed, later)).toEqual([true, true]);
expect(loadsOf(untrimmed, later)).toEqual([1, 1]);
});

it("arms a clip a far jump lands on without reloading it under the seek", async () => {
spyLoad();
servePreview();
const [now, later] = videos(mountRoot(), "0", "8");

await evaluateRuntime();
const beforeJump = loadsOf(later)[0];
window.__player?.seek(8.4);
expect(armed(now, later)).toEqual([false, true]);
expect(loadsOf(later)).toEqual([beforeJump]);
});

// jsdom's media elements cannot play; the runtime only needs play() to settle.
const stubPlayback = () => {
vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue(undefined);
vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {});
};
const tracks = (root: HTMLElement) => {
stubPlayback();
const [now, next, afterNext, otherTrack] = videos(root, "0", "4", "7", "3");
otherTrack.setAttribute("data-track-index", "2");
return { now, next, afterNext, otherTrack };
};

it("arms the next clip on a clip's track when it starts playing, and nothing else", async () => {
spyLoad();
servePreview();
const { next, afterNext, otherTrack } = tracks(mountRoot());

await evaluateRuntime();
window.__player?.play();
expect(armed(next, afterNext, otherTrack)).toEqual([true, false, false]);
expect(loadsOf(next, afterNext, otherTrack)).toEqual([1, 0, 0]);
});

it("arms nothing ahead of a paused playhead, and keeps what it armed through a pause", async () => {
spyLoad();
servePreview();
const { next, afterNext } = tracks(mountRoot());

await evaluateRuntime();
window.__player?.seek(0.5);
expect(armed(next)).toEqual([false]);
window.__player?.play();
window.__player?.pause();
expect(armed(next, afterNext)).toEqual([true, false]);
expect(loadsOf(next)).toEqual([1]);
});

it("holds a clip past the look-ahead edge a scrub crosses, and frees it once well clear", async () => {
spyLoad();
servePreview();
const [, later] = videos(mountRoot(), "0", "5");

await evaluateRuntime();
window.__player?.seek(3.5);
window.__player?.seek(2.5);
window.__player?.seek(3.5);
expect(armed(later)).toEqual([true]);
expect(loadsOf(later)).toEqual([1]);
window.__player?.seek(0.5);
expect(armed(later)).toEqual([false]);
});

it("keeps the clip a step back across a cut returns to loaded", async () => {
spyLoad();
servePreview();
const [outgoing, incoming] = videos(mountRoot(), "0", "2");

await evaluateRuntime();
window.__player?.seek(2.1);
expect(armed(outgoing, incoming)).toEqual([true, true]);
window.__player?.seek(1.9);
expect(armed(outgoing)).toEqual([true]);
expect(loadsOf(outgoing)).toEqual([1]);
});

it("arms a clip behind a playhead shuttling back before the playhead reaches it", async () => {
spyLoad();
servePreview();
const [earlier, current] = videos(mountRoot(), "0", "2");
current.setAttribute("data-duration", "6");

await evaluateRuntime();
window.__player?.seek(6.5);
expect(armed(earlier)).toEqual([false]);
let armedAt: number | undefined;
for (let tenths = 45; tenths >= 20 && armedAt === undefined; tenths--) {
window.__player?.seek(tenths / 10);
if (armed(earlier)[0]) armedAt = tenths / 10;
}
// Within the 2 s look-ahead of its end, as a clip ahead is armed within 2 s of its start.
expect(armedAt).toBe(4);
});

it("still frees a clip that ended well behind the playhead", async () => {
spyLoad();
servePreview();
const [earlier, current] = videos(mountRoot(), "0", "2");
current.setAttribute("data-duration", "6");

await evaluateRuntime();
window.__player?.seek(2.1);
window.__player?.seek(5.9);
expect(armed(earlier)).toEqual([true]);
expect(loadsOf(earlier)).toEqual([1]);
window.__player?.seek(6.1);
expect(armed(earlier)).toEqual([false]);
expect(earlier.preload).toBe("none");
expect(loadsOf(earlier)).toEqual([2]);
});

it("drops an arm once the clip that set it leaves the screen, as a jump while playing does", async () => {
spyLoad();
servePreview();
const { next } = tracks(mountRoot());
window.__timelines = { main: pausedTimeline(20) };

await evaluateRuntime();
window.__player?.play();
window.__player?.seek(10.5, { keepPlaying: true });
expect(armed(next)).toEqual([false]);
});

it("stops holding a clip it armed once that clip has played", async () => {
spyLoad();
servePreview();
const { next } = tracks(mountRoot());
window.__timelines = { main: pausedTimeline(20) };

await evaluateRuntime();
window.__player?.play();
window.__player?.seek(4.5, { keepPlaying: true });
window.__player?.seek(10.5, { keepPlaying: true });
expect(armed(next)).toEqual([false]);
});

it("arms a clip that starts exactly where the playing one ends", async () => {
spyLoad();
servePreview();
stubPlayback();
// 1.1 + 2.2 is 3.3000000000000003: back to back only within the boundary tolerance.
const [first, second] = videos(mountRoot(), "1.1", "3.3");
first.setAttribute("data-duration", "2.2");

await evaluateRuntime();
window.__player?.seek(1.2);
window.__player?.play();
expect(armed(second)).toEqual([true]);
});

it("arms the next clip only in the same host and on an authored track", async () => {
spyLoad();
servePreview();
stubPlayback();
const root = mountRoot();
const [now] = videos(root, "0");
const host = timed(root, "div", "0");
host.setAttribute("data-composition-id", "inner");
host.setAttribute("data-duration", "10");
const [otherHost] = videos(host, "4");
const [untracked, untrackedNext] = videos(root, "0", "4");
for (const el of [untracked, untrackedNext]) el.removeAttribute("data-track-index");
now.setAttribute("data-track-index", "1");

await evaluateRuntime();
window.__player?.play();
expect(armed(otherHost, untrackedNext)).toEqual([false, false]);
});

it("arms a short nested clip whose start is already root time before it is due", async () => {
spyLoad();
servePreview();
const host = timed(mountRoot(), "div", "5");
host.setAttribute("data-composition-id", "inner");
host.setAttribute("data-duration", "5");
const [clip] = videos(host, "6");
clip.setAttribute("data-hf-media-start-basis", "global");
clip.setAttribute("data-duration", "0.4");

await evaluateRuntime();
window.__player?.seek(4.5);
expect(armed(clip)).toEqual([true]);
});

it("keeps the clips due at the loop start loaded while the loop plays", async () => {
spyLoad();
servePreview();
const { now, next, afterNext } = tracks(mountRoot());
window.__timelines = { main: pausedTimeline(20) };

await evaluateRuntime();
window.__hf?.setLoopStart?.(0);
window.__player?.play();
window.__player?.seek(19.5, { keepPlaying: true });
expect(armed(now, next, afterNext)).toEqual([true, true, false]);
expect(loadsOf(now, next)).toEqual([1, 1]);
window.__hf?.setLoopStart?.(null);
window.__player?.seek(19.6, { keepPlaying: true });
expect(armed(now)).toEqual([false]);
});

it("holds the loop start only while playing, and for a loop start that is a time", async () => {
spyLoad();
servePreview();
const { now } = tracks(mountRoot());

await evaluateRuntime();
window.__hf?.setLoopStart?.(0);
window.__player?.play();
window.__player?.seek(9.5, { keepPlaying: true });
window.__player?.pause();
expect(armed(now)).toEqual([false]);
window.__hf?.setLoopStart?.(-1);
window.__player?.play();
expect(armed(now)).toEqual([false]);
});

it("never arms a next clip with no authored length, so it is not reloaded", async () => {
spyLoad();
servePreview();
const { next } = tracks(mountRoot());
next.removeAttribute("data-duration");

await evaluateRuntime();
const atBind = loadsOf(next)[0];
window.__player?.play();
expect(loadsOf(next)).toEqual([atBind]);
});

it("keeps an armed next clip through a window pass that finds it outside the look-ahead", async () => {
spyLoad();
servePreview();
const { next } = tracks(mountRoot());

await evaluateRuntime();
window.__player?.play();
window.__player?.seek(0.5, { keepPlaying: true });
expect(armed(next)).toEqual([true]);
expect(loadsOf(next)).toEqual([1]);
});

it("gives each parsed clip after the first frame preload none before it can fetch", async () => {
servePreview();
const root = mountRoot();
timed(root, "div", "0");
await evaluateRuntime();
const [first, later] = videos(root, "0", "5");
const untrimmed = timed(root, "audio", "5");
untrimmed.removeAttribute("data-duration");
await Promise.resolve();
expect([first.preload, later.preload, untrimmed.preload]).toEqual(["", "none", ""]);
});

it("keeps a render loading every media element at bind", async () => {
spyLoad();
const [now, soon, later] = videos(mountRoot(), "0", "1.5", "5");

await evaluateRuntime();
window.__player?.seek(3.6);
expect(armed(now, soon, later)).toEqual([true, true, true]);
expect(loadsOf(now, soon, later)).toEqual([1, 1, 1]);
const parsedLater = timed(document.body, "video", "5");
await Promise.resolve();
expect(parsedLater.preload).not.toBe("none");
expect((window as { __hfMediaDeferral?: unknown }).__hfMediaDeferral).toBeUndefined();
});
});

it("grades media inside a clip once the first pass shows the clip, with no seek", async () => {
const getContext = vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
const scene = timed(mountRoot(), "div", "0");
Expand Down
Loading
Loading