Skip to content
32 changes: 32 additions & 0 deletions packages/core/src/runtime/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,38 @@ Attribute selectors with a declared namespace prefix (`@namespace xl url(...)` p
in runtime and compiled output alike. Compiled CSS text leaves them as authored, so these
selectors need JavaScript; with scripts disabled they match only unrenamed values.

## Hold rules

A held clip has no `src`, so it downloads and decodes nothing, while readers still see its file
(`unproxiedSrc`). Each row is the one place that takes or ends that hold; a change to any of them
updates this table.

| Hold | Taken by | Ended by | While held |
| ------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------- |
| Until due | `preloadMedia.ts` `holdUntilDue`: a long idle source | `giveBackWhenDue`: the clip is due, unless a copy hold has it | nothing loads |
| For a copy | `mediaProxy.ts` `holdForCopy`: the copy job, for a file too large for the shown box | `decideFileTurn` or `endCopyHold`, see below | frame captures wait for the copy (5 s cap); stills below |
| For a capture still | `holdForCaptureStill`: a one-shot capture page | never: the file is not decoded there | `standInCaptureStill` sets the server's frame as poster each pass |

For a copy:

- **Its own file, for one clip.** `decideFileTurn` gives the one held clip on screen its file back
while its copy is made, so at most one oversized file decodes. It takes the file back once the clip
leaves the screen while that copy is still coming. Never on a capture page, and never for a file
deeper than 8 bits that the browser cannot decode.
- **The job that owns it.** A copy job owns the clip while `src` is the value it started from. With
no `src`, a held clip belongs only to the job for the source it holds, and an unheld one only to a
job that also started with no `src`.
- **End of the job.** `endCopyHold`: a served copy loads in place of the file. Any other ending gives
the file back, except to a clip that was held until due, which stays held until it is due. A job
whose clip now holds another source leaves that hold alone.
- **Still.** Only the owning job puts up a still, and a lighter copy's job only for a clip held when
its copy began: the server's frame at the playhead, as the poster, asked for on the tick the clip
comes on screen and at each copy poll. A page's own poster is never replaced. The still stays up
while its own copy loads, and the job takes it down when that load ends (`loadeddata`, `error`,
`abort`, `emptied`) or the job ends without a copy.
- **Swap.** Any source swap (`loadProxy`) shows the frame it had as poster until the new file has
a frame (`holdShownFrame`), then restores the page's poster.

## Build

```bash
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/runtime/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ import {
isRenderMode,
maybeProxyProactively,
standInCaptureStill,
showStillWhenDue,
decideFileTurn,
describeVideoSources,
levelsWithLighterCopies,
Expand Down Expand Up @@ -3636,7 +3637,10 @@ export function initSandboxRuntimeModular(): void {
currentTime,
loadsAhead && dueAtLoopStart(rawNode, visibleAt),
);
if (isMediaElement(rawNode)) standInCaptureStill(rawNode, isVisibleNow);
if (isMediaElement(rawNode)) {
standInCaptureStill(rawNode, isVisibleNow);
showStillWhenDue(rawNode, isVisibleNow);
}
if (!isMediaElement(rawNode) && !isImageElement(rawNode)) decidedTimedClip = true;
if (isVideoElement(rawNode) || isImageElement(rawNode)) {
colorGradingRuntime?.setSourceVisibility(rawNode, isVisibleNow);
Expand Down
157 changes: 156 additions & 1 deletion packages/core/src/runtime/mediaProxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ import {
swapToProxy,
type MediaCodecMapEntry,
} from "./mediaProxy";
import { createMockTimeline } from "./runtimeSeekFixture.test-helpers";
import { deriveCodecMapKey } from "./mediaSourceLookup";
import { escapeCssString } from "./editingElement";
import type { PreviewSourceFacts } from "../previewProxyBox";
import { recordOpenedAtInPoint, unproxiedSrc } from "./proxySrc";

vi.mock("./bridge", () => ({
vi.mock("./bridge", async (importOriginal) => ({
...(await importOriginal<typeof import("./bridge")>()),
postRuntimeMessage: vi.fn(),
}));

Expand Down Expand Up @@ -104,11 +106,26 @@ function postersAtLoad(el: HTMLVideoElement) {
return posters;
}

/** jsdom's FileReader finishes on the real event loop; this one finishes within a fake clock's step. */
class StepReader {
result: string | null = null;
error: DOMException | null = null;
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
readAsDataURL(blob: Blob) {
void blob.arrayBuffer().then((bytes) => {
this.result = `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}`;
this.onload?.();
});
}
}

beforeEach(() => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response("x", { status: 206 })),
);
vi.stubGlobal("FileReader", StepReader);
});

// Each runtime a test loads fresh keeps its own copy reporting: reset every one, or a late report reaches a later test.
Expand Down Expand Up @@ -1917,6 +1934,144 @@ describe("preview quality: lighter copies of heavy files", () => {
]);
});

// fails without the fix: the still went up only at the copy's next poll, 2 s (5 s with the queue full) after the
// clip came on screen, so a held clip showed nothing until then.
it("puts its still up on the tick it comes on screen, not at the copy's next poll", async () => {
const { el, showStillWhenDue } = await waitingForItsCopy(making);
const media = await import("./media");
showStillWhenDue(el, true);
expect(el.hasAttribute("poster")).toBe(false);
const clip = {
el,
start: 0,
mediaStart: 4,
duration: 10,
end: 10,
volume: null,
playbackRate: 1,
};
media.syncRuntimeMedia({
clips: [{ ...clip, loop: false, sourceDuration: null }],
...{ timeSeconds: 1, playing: false, playbackRate: 1, getCompositionDuration: () => 0 },
});
showStillWhenDue(el, false);
expect(el.hasAttribute("poster")).toBe(false);
showStillWhenDue(el, true);
expect(
new URL(el.getAttribute("poster")!, document.baseURI).searchParams.get("hf-proxy-still"),
).toBe("5.0");
});

/** A held clip inside its window in a sealed frame, each still's answer left to the test. */
async function sealedHeld() {
vi.useFakeTimers();
vi.stubGlobal("origin", "null");
const answers: Array<(res: Response) => void> = [];
let made = false;
vi.stubGlobal(
"fetch",
vi.fn((url: string) => {
if (String(url).includes("hf-proxy-still"))
return new Promise<Response>((answer) => answers.push(answer));
if (!String(url).includes("hf-proxy") || made)
return Promise.resolve(new Response("x", { status: 206 }));
return Promise.resolve(making());
}),
);
const staged = await stage({ "/video.mp4": HEAVY, "/b.mp4": HEAVY });
const el = staged.video();
staged.maybeProxyProactively(el);
await vi.advanceTimersByTimeAsync(0);
const media = await import("./media");
const clip = { el, start: 0, mediaStart: 4, duration: 10, end: 10, volume: null };
media.syncRuntimeMedia({
clips: [{ ...clip, playbackRate: 1, loop: false, sourceDuration: null }],
...{ timeSeconds: 1, playing: false, playbackRate: 1, getCompositionDuration: () => 0 },
});
return { ...staged, el, answers, finish: () => (made = true) };
}

// fails without the fix: a job whose clip got a new source still asked for, and put up, its old source's still.
it("asks no still for a copy job whose clip has a new source", async () => {
const { el, showStillWhenDue, answers } = await sealedHeld();
el.setAttribute("src", "/other.mp4");
showStillWhenDue(el, true);
expect([answers.length, el.getAttribute("poster")]).toEqual([0, null]);
});

// fails without the fix: a sealed still answered after the clip got a new source went up as its poster.
it("puts up no sealed still that answers after the clip got a new source", async () => {
const { el, showStillWhenDue, answers } = await sealedHeld();
showStillWhenDue(el, true);
el.setAttribute("src", "/other.mp4");
answers[0]!(jpegStill());
await vi.advanceTimersByTimeAsync(10);
expect(el.getAttribute("poster")).toBeNull();
});

// fails without the fix: the old job's cleanup cleared the new job's pending still, so the clip stayed blank.
it("keeps a replacement copy's pending still through the old copy's cleanup", async () => {
const { el, showStillWhenDue, swapToProxy, answers } = await sealedHeld();
showStillWhenDue(el, true);
el.setAttribute("src", "/b.mp4");
swapToProxy(el, null, "light", HEAVY);
await vi.advanceTimersByTimeAsync(0);
showStillWhenDue(el, true);
await vi.advanceTimersByTimeAsync(2_000);
answers.at(-1)!(jpegStill());
await vi.advanceTimersByTimeAsync(10);
expect([answers.length, el.getAttribute("poster")]).toEqual([2, JPEG_STILL]);
});

// fails without the fix: a sealed still answered once its own copy was loading, before the copy drew, was dropped.
it("puts up a sealed still that answers while its own copy loads, and takes it down once the copy draws", async () => {
const { el, showStillWhenDue, answers, finish } = await sealedHeld();
showStillWhenDue(el, true);
finish();
await vi.advanceTimersByTimeAsync(2_000);
expect(el.getAttribute("src")).toContain("hf-proxy");
answers[0]!(jpegStill());
await vi.advanceTimersByTimeAsync(10);
expect(el.getAttribute("poster")).toBe(JPEG_STILL);
el.dispatchEvent(new Event("loadeddata"));
await vi.advanceTimersByTimeAsync(0);
expect(el.getAttribute("poster")).toBeNull();
});

// fails without the fix: a job started on a held clip with no src matched a new source held with no src, and
// loaded its old copy over the new one.
it("loads no copy from a job started on a held clip once the clip holds a new source", async () => {
const { el, swapToProxy, finish } = await sealedHeld();
expect(el.getAttribute("src")).toBeNull();
swapToProxy(el, null, "light", HEAVY);
await vi.advanceTimersByTimeAsync(0);
el.setAttribute("src", "/b.mp4");
swapToProxy(el, null, "light", HEAVY);
await vi.advanceTimersByTimeAsync(0);
finish();
await vi.advanceTimersByTimeAsync(2_000);
expect(new URL(el.getAttribute("src")!, document.baseURI).pathname).toBe("/b.mp4");
});

// fails without the fix: the runtime's pass never asked, so a paused seek onto a held clip showed nothing until
// the copy's next poll.
it("puts its still up on a paused seek into its window, through the runtime's own pass", async () => {
const { el } = await waitingForItsCopy(making);
const root = document.createElement("div");
Object.assign(root.dataset, { compositionId: "main", root: "true", duration: "10" });
Object.assign(el.dataset, { start: "0", duration: "10", mediaStart: "4" });
document.body.append(root);
root.append(el);
window.__timelines = { main: createMockTimeline(10) };
const { initSandboxRuntimeModular } = await import("./init");
initSandboxRuntimeModular();
expect(el.hasAttribute("poster")).toBe(false);
window.__player!.seek(1);
expect(
new URL(el.getAttribute("poster")!, document.baseURI).searchParams.get("hf-proxy-still"),
).toBe("5.0");
});

async function twoHeldOnScreen(facts: PreviewSourceFacts = HEAVY) {
vi.useFakeTimers();
let made = false;
Expand Down
Loading
Loading