Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
15 changes: 15 additions & 0 deletions docs/guides/frame-sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,19 @@ Draws are serialized per source. Rapid preview seeks coalesce while a draw is in

Call `unregister()` when replacing a source. Removal of its host or runtime teardown also unregisters it. The callback's `AbortSignal` is aborted, queued work is cancelled, capture waiters are released, and `dispose` runs once. Stop any underlying work in response to the signal or in `dispose`; cancellation cannot forcibly interrupt synchronous JavaScript.

## Media elements

A frame source can supply a timed `<video>` or `<audio>`, for example one decoded with WebCodecs from bytes the page reads itself. The runtime then leaves the element alone: it never loads, preloads, seeks or plays it, and the first-frame asset check does not wait for it. The element needs no `src`.

Two optional members let such a source take part in the Buffering hold, which pauses the film while a clip on screen has no data to play:

- `canPlayAt(sourceTime)`: return `false` while the source cannot play on from that source time. The film holds with Buffering until it returns `true`. Without it, the source never holds the film.
- `received()`: a number that grows while the source still receives data, such as the bytes read so far. As for a media element, the hold gives up 8 seconds after it last grew and the film plays on.

`window.__hf.sourceTimeAt(element, time)` returns the source time the source is asked for at composition time `time`, trims and playback rate included, so the source can read ahead to the clip's last frame.

For a clip with no `data-duration`, the runtime needs the source's length. Return it from `length()` once known, and dispatch a `durationchange` event on the element when it becomes known. A `loop` element's source time wraps at that length, as it does for a media element the runtime plays itself.

A `<video>` a frame source supplies has no picture of its own. Return the picture on screen from `picture()` as `{ canvas, time }`: scripts that draw the video or upload it as a WebGL texture get `canvas`, and the video's `requestVideoFrameCallback` callbacks fire with `time` as `mediaTime`. Add `frame`, the decoded `VideoFrame` the canvas shows, and a colour grade on the video uploads it directly instead of copying the canvas.

Registration does not expose arbitrary scene code as editable keyframes. Manual element edits need stable identities and persistent parameters or overrides. Imported iframe sources also need screenshot capture and an explicit message bridge; this API does not grant access to sandboxed DOM.
9 changes: 9 additions & 0 deletions packages/core/src/compositionReadiness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
settleCompositionReadiness,
settleFirstFrameCompositionReadiness,
} from "./compositionReadiness.js";
import { registerFrameSource } from "./runtime/frameSources.js";
import { createRuntimeStartTimeResolver } from "./runtime/startResolver.js";
import { STUDIO_PREVIEW_MARK_META } from "./studioPreviewMark.js";
import { isRuntimeElementVisibleAt } from "./runtime/timeline.js";
Expand Down Expand Up @@ -87,6 +88,14 @@ describe("scanPendingCompositionAssets", () => {
expect(scan.pendingMedia.map((media) => media.id)).toEqual(["untimed"]);
});

it("leaves out media a frame source supplies", () => {
const doc = docWith('<video id="cam" data-start="0" data-duration="5"></video>');
const dispose = registerFrameSource({ element: doc.getElementById("cam")!, render: () => {} });

expect(scanPendingCompositionAssets(doc, { scope: "first-frame" }).pendingMedia).toEqual([]);
dispose();
});

it("keeps nested timing decisions aligned with the runtime visibility owner", () => {
const doc = docWith(
'<section data-start="30" data-duration="5"><video id="nested" src="later.mp4"></video></section>',
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/compositionReadiness.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { hasFrameSource } from "./runtime/frameSources.js";
import { createRuntimeStartTimeResolver } from "./runtime/startResolver.js";
import { isRuntimeElementVisibleAt } from "./runtime/timeline.js";
import type { RuntimeTimelineLike } from "./runtime/types.js";
Expand Down Expand Up @@ -115,7 +116,7 @@ export function scanPendingCompositionAssets(
runtimeWindow?.__timelines ?? {},
),
)
.filter((el) => el.readyState < HAVE_FUTURE_DATA);
.filter((el) => el.readyState < HAVE_FUTURE_DATA && !hasFrameSource(el));
// 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"))
.filter((img) =>
Expand Down
19 changes: 19 additions & 0 deletions packages/core/src/runtime/colorGrading.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
installAuthoredOpacityCapture,
type RuntimeColorGradingApi,
} from "./colorGrading";
import { registerFrameSource } from "./frameSources";

let lastUniform1f: ReturnType<typeof vi.fn> | null = null;
let lastUniform3f: ReturnType<typeof vi.fn> | null = null;
Expand Down Expand Up @@ -351,6 +352,24 @@ describe("createColorGradingRuntime", () => {
expect(texImage2DCalls.length).toBeGreaterThan(drawsBefore);
});

it("grades the decoded frame a video's frame source hands over", () => {
const video = makeDrawableVideo();
const canvas = Object.assign(document.createElement("canvas"), { width: 640, height: 360 });
// jsdom has no VideoFrame; the grader only passes it to texImage2D.
const frame = {} as unknown as VideoFrame;
const dispose = registerFrameSource({
element: video,
render: () => {},
picture: () => ({ canvas, time: 0, frame }),
});
try {
startRuntimeWithVideo(video);
expect(texImage2DCalls.at(-1)?.at(-1)).toBe(frame);
} finally {
dispose();
}
});

it("keeps graded layers on the committed picture until a preview seek lands", () => {
const { video } = startRuntimeWithVideo();
const drawsBefore = texImage2DCalls.length;
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/runtime/colorGrading.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { swallow } from "./diagnostics";
import { createRecordFilter } from "./mutationRecords";
import { findInjectedRenderFrame } from "./renderFrameSibling";
import { getPausedVideoFrame } from "./pausedVideoFrames";
import { frameSourcePicture } from "./frameSources";
import {
isCanvasElement,
isElementNode,
Expand Down Expand Up @@ -3425,7 +3426,8 @@ type DrawableFrame = {
function drawableFrame(entry: ColorGradingEntry): DrawableFrame | null {
if (document.documentElement.hasAttribute(PREVIEW_SEEK_HOLD_ATTR)) return null;
const source = getDrawableSource(entry.element);
const pixels = source && readablePixels(source, entry);
const pixels =
source && (frameSourcePicture(entry.element)?.frame ?? readablePixels(source, entry));
if (!source || !pixels) {
if (!entry.hasDrawn) entry.canvas.style.display = "none";
return null;
Expand Down
57 changes: 53 additions & 4 deletions packages/core/src/runtime/frameSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,26 @@ import { sourceTimeAt } from "../speedRamp";
import { readElementRateSpec, readMediaStart } from "./playbackRate";
import { registerSeekCompletion } from "./adapters/seek-dispatch";
import { isClipOnScreenAt } from "./clipWindow";
import { isElementNode, isMediaElement, isVideoElement } from "./domRealm";
import { flushPausedVideoCallbacks, stagePausedVideoCallbacks } from "./pausedVideoCallbacks";
import { sourceLengthOf, supplySourceLength } from "./sourceLength";
import type { RuntimeDeterministicAdapter } from "./types";

export interface FrameSource {
element: Element;
ready?: PromiseLike<unknown>;
sourceRange?: { start: number; duration: number; fps: number };
render: (sourceTime: number, signal: AbortSignal) => void | PromiseLike<unknown>;
canPlayAt?: (sourceTime: number) => boolean;
received?: () => number;
length?: () => number | undefined;
picture?: () => { canvas: HTMLCanvasElement; time: number; frame?: VideoFrame } | null;
dispose?: () => void;
}

interface RegisteredSource {
element: Element;
source: FrameSource;
ready: Promise<unknown>;
seek: (time: number) => Promise<void>;
dispose: () => void;
Expand All @@ -23,6 +31,34 @@ const sources = new Map<Element, RegisteredSource>();

export const hasFrameSources = (): boolean => sources.size > 0;

export const hasFrameSource = (element: unknown): boolean =>
isElementNode(element) && sources.has(element);

export const frameSourceReceived = (element: Element): number | undefined =>
sources.get(element)?.source.received?.();

export const frameSourcePicture = (element: Element) =>
sources.get(element)?.source.picture?.() ?? null;

export function frameSourceTimeAt(element: Element, time: number, start: number): number {
const mediaStart = readMediaStart(element);
const target = mediaStart + sourceTimeAt(readElementRateSpec(element), Math.max(0, time - start));
const length = isMediaElement(element) && element.loop ? sourceLengthOf(element) : Number.NaN;
return length > mediaStart && target >= length
? mediaStart + ((target - mediaStart) % (length - mediaStart))
: target;
}

export function frameSourceWaitsAt(
element: Element,
time: number,
start: number,
): boolean | undefined {
const registered = sources.get(element);
if (!registered) return undefined;
return registered.source.canPlayAt?.(frameSourceTimeAt(element, time, start)) === false;
}

/** Bind a frame source to a timed host. Unregister before replacing its source. */
export function registerFrameSource(source: FrameSource): () => void {
if (sources.has(source.element)) throw new Error("This element already has a frame source");
Expand All @@ -46,6 +82,15 @@ export function registerFrameSource(source: FrameSource): () => void {
void ready.catch(() => {});
let pending: number | null = null;
let work: Promise<void> | null = null;
let shownTime: number | null = null;
const showPicture = () => {
const picture = source.picture?.();
if (!picture || picture.time === shownTime || !isVideoElement(source.element)) return;
shownTime = picture.time;
const { width, height } = picture.canvas;
stagePausedVideoCallbacks(source.element, { mediaTime: picture.time, width, height });
flushPausedVideoCallbacks(source.element);
};
const drain = async () => {
let failure: { reason: unknown } | undefined;
try {
Expand All @@ -55,6 +100,7 @@ export function registerFrameSource(source: FrameSource): () => void {
pending = null;
try {
await Promise.race([source.render(time, controller.signal), cancelled]);
showPicture();
} catch (reason) {
failure ??= { reason };
}
Expand All @@ -67,6 +113,7 @@ export function registerFrameSource(source: FrameSource): () => void {
};
const registered: RegisteredSource = {
element: source.element,
source,
ready,
seek(time) {
pending = range
Expand All @@ -80,10 +127,12 @@ export function registerFrameSource(source: FrameSource): () => void {
controller.abort();
pending = null;
sources.delete(source.element);
supplySourceLength(source.element, undefined);
source.dispose?.();
},
};
sources.set(source.element, registered);
supplySourceLength(source.element, source.length);
return registered.dispose;
}

Expand Down Expand Up @@ -138,10 +187,10 @@ export function createFrameSourceAdapter(timing: {
timing.compositionDuration(),
);
if (!onScreen) continue;
const localTime = Math.max(0, time - start);
const sourceTime =
readMediaStart(element) + sourceTimeAt(readElementRateSpec(element), localTime);
registerSeekCompletion(source.seek(sourceTime), "frame-source");
registerSeekCompletion(
source.seek(frameSourceTimeAt(element, time, start)),
"frame-source",
);
}
},
getReadyPromise: () => {
Expand Down
Loading
Loading