@hyperframes/core 0.9.95 → 0.9.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/audibleVideo.d.ts +10 -0
  2. package/dist/audibleVideo.js +37 -0
  3. package/dist/generated/runtime-inline.js +1 -1
  4. package/dist/hyperframe.runtime.iife.js +67 -67
  5. package/dist/index.d.ts +1 -1
  6. package/dist/runtime/adapters/seek-dispatch.d.ts +40 -0
  7. package/dist/runtime/adapters/seek-dispatch.js +164 -0
  8. package/dist/runtime/assetUrl.d.ts +6 -0
  9. package/dist/runtime/assetUrl.js +8 -0
  10. package/dist/runtime/audioFx.d.ts +77 -0
  11. package/dist/runtime/audioFx.js +277 -0
  12. package/dist/runtime/bridge.d.ts +6 -0
  13. package/dist/runtime/bridge.js +20 -0
  14. package/dist/runtime/decodesFirst.d.ts +4 -0
  15. package/dist/runtime/decodesFirst.js +14 -0
  16. package/dist/runtime/editing/gsapSnapshot.js +12 -3
  17. package/dist/runtime/editing/gsapSnapshotLimits.d.ts +5 -3
  18. package/dist/runtime/editing/gsapSnapshotLimits.js +5 -3
  19. package/dist/runtime/editing/textCaret.d.ts +14 -0
  20. package/dist/runtime/editing/textCaret.js +98 -0
  21. package/dist/runtime/editing/textEdit.d.ts +8 -0
  22. package/dist/runtime/editing/textEdit.js +67 -10
  23. package/dist/runtime/editingPort.d.ts +3 -2
  24. package/dist/runtime/editingPort.js +2 -1
  25. package/dist/runtime/media.d.ts +113 -0
  26. package/dist/runtime/media.js +820 -0
  27. package/dist/runtime/mediaLoadFailure.d.ts +8 -0
  28. package/dist/runtime/mediaLoadFailure.js +58 -0
  29. package/dist/runtime/mediaProxy.d.ts +91 -0
  30. package/dist/runtime/mediaProxy.js +803 -0
  31. package/dist/runtime/playbackHealth.d.ts +31 -0
  32. package/dist/runtime/playbackHealth.js +137 -0
  33. package/dist/runtime/preloadMedia.d.ts +16 -0
  34. package/dist/runtime/preloadMedia.js +266 -0
  35. package/dist/runtime/previewCopies.d.ts +13 -0
  36. package/dist/runtime/previewCopies.js +80 -0
  37. package/dist/runtime/proxyWait.d.ts +3 -0
  38. package/dist/runtime/proxyWait.js +51 -0
  39. package/dist/runtime/runtimeLoad.d.ts +3 -0
  40. package/dist/runtime/runtimeLoad.js +13 -0
  41. package/dist/runtime/state.d.ts +7 -0
  42. package/dist/runtime/state.js +3 -0
  43. package/dist/runtime/timedClipHide.d.ts +12 -0
  44. package/dist/runtime/timedClipHide.js +94 -0
  45. package/dist/runtime/types.d.ts +29 -18
  46. package/dist/runtime/webAudioTransport.d.ts +243 -0
  47. package/dist/runtime/webAudioTransport.js +1176 -0
  48. package/dist/safePath.js +20 -11
  49. package/dist/terminalText.d.ts +1 -0
  50. package/dist/terminalText.js +17 -0
  51. package/package.json +12 -4
@@ -0,0 +1,31 @@
1
+ import type { PlaybackHeldBy } from "./types.js";
2
+ /** What counts as a choppy preview; every number of the rule lives here. */
3
+ export declare const PLAYBACK_HEALTH: {
4
+ readonly windowSeconds: 3;
5
+ readonly choppyShare: 0.25;
6
+ readonly warmupSeconds: 1;
7
+ readonly reportEveryMs: 1000;
8
+ };
9
+ export type PlaybackHealthInput = {
10
+ nowMs: number;
11
+ filmTime: number;
12
+ fps: number;
13
+ rate: number;
14
+ playing: boolean;
15
+ hidden: boolean;
16
+ /** A playing video is waiting for data. */
17
+ waiting: boolean;
18
+ heldBy?: PlaybackHeldBy | null;
19
+ frozen?: boolean;
20
+ clock: "audio" | "webaudio" | "monotonic";
21
+ /** Anything that changes how heavy a frame is to draw (window size, zoom). */
22
+ layoutKey: string;
23
+ };
24
+ export declare function watchMediaFetches(doc: Document): () => void;
25
+ export declare function heldByMedia(el: HTMLMediaElement, nowMs: number): PlaybackHeldBy;
26
+ /** The host re-sends its scale on every resize; only a different scale restarts the window. */
27
+ export declare function noteDisplayScale(scale: number): void;
28
+ /** Restarts the window after something that stalls playback for reasons unrelated to the level. */
29
+ export declare function restartPlaybackHealth(): void;
30
+ /** One call per runtime tick: counts frames drawn against frames due while the film plays. */
31
+ export declare function notePlaybackFrame(input: PlaybackHealthInput): void;
@@ -0,0 +1,137 @@
1
+ import { postRuntimeMessage } from "./bridge.js";
2
+ /** What counts as a choppy preview; every number of the rule lives here. */
3
+ export const PLAYBACK_HEALTH = {
4
+ windowSeconds: 3,
5
+ choppyShare: 0.25,
6
+ warmupSeconds: 1,
7
+ reportEveryMs: 1000,
8
+ };
9
+ const FORWARD_JUMP_SECONDS = 0.5;
10
+ let samples = [];
11
+ let last = null;
12
+ let warmEndMs = 0;
13
+ let key = "";
14
+ let posted = false;
15
+ let postedAtMs = 0;
16
+ let clockSource = "monotonic";
17
+ const fetchStartedAt = new WeakMap();
18
+ export function watchMediaFetches(doc) {
19
+ const onStart = (event) => {
20
+ if (event.target)
21
+ fetchStartedAt.set(event.target, performance.now());
22
+ };
23
+ doc.addEventListener("loadstart", onStart, true);
24
+ return () => doc.removeEventListener("loadstart", onStart, true);
25
+ }
26
+ const resourceFetchStart = (src) => performance.getEntriesByName(src).at(-1)?.startTime;
27
+ export function heldByMedia(el, nowMs) {
28
+ const started = fetchStartedAt.get(el) ?? (el.currentSrc ? resourceFetchStart(el.currentSrc) : undefined);
29
+ return {
30
+ kind: el.tagName === "VIDEO" ? "video" : "audio",
31
+ readyState: el.readyState,
32
+ networkState: el.networkState,
33
+ fetchMs: started === undefined ? null : Math.round(nowMs - started),
34
+ };
35
+ }
36
+ function post(health) {
37
+ postRuntimeMessage({ source: "hf-preview", type: "preview-health", health });
38
+ }
39
+ function clear() {
40
+ samples = [];
41
+ last = null;
42
+ if (posted)
43
+ post(null);
44
+ posted = false;
45
+ postedAtMs = 0;
46
+ }
47
+ let displayScale = null;
48
+ /** The host re-sends its scale on every resize; only a different scale restarts the window. */
49
+ export function noteDisplayScale(scale) {
50
+ if (scale === displayScale)
51
+ return;
52
+ displayScale = scale;
53
+ clear();
54
+ }
55
+ /** Restarts the window after something that stalls playback for reasons unrelated to the level. */
56
+ export function restartPlaybackHealth() {
57
+ clear();
58
+ }
59
+ function measure(nowMs, fps, rate) {
60
+ const windowMs = PLAYBACK_HEALTH.windowSeconds * 1000;
61
+ while (samples[0] && samples[0].atMs < nowMs - windowMs)
62
+ samples.shift();
63
+ const first = samples[0];
64
+ if (!first)
65
+ return;
66
+ const spanMs = nowMs - (first.atMs - first.gapMs);
67
+ if (spanMs < windowMs || nowMs - postedAtMs < PLAYBACK_HEALTH.reportEveryMs)
68
+ return;
69
+ const drawn = samples.filter((sample) => sample.drawn).length;
70
+ const due = (spanMs / 1000) * fps * rate;
71
+ const skipped = due > 0 ? 1 - Math.min(drawn, due) / due : 0;
72
+ const waitingMs = samples.reduce((sum, s) => sum + (s.waiting ? s.gapMs : 0), 0);
73
+ const frozenMs = samples.reduce((sum, s) => sum + (s.frozen ? s.gapMs : 0), 0);
74
+ const droppedShare = Math.max(skipped, waitingMs / spanMs);
75
+ let heldBy = null;
76
+ for (const sample of samples)
77
+ heldBy = sample.heldBy ?? heldBy;
78
+ const gaps = samples.map((sample) => sample.gapMs).sort((a, b) => a - b);
79
+ const gapAt = (share) => Math.round(gaps[Math.ceil(share * gaps.length) - 1] ?? 0);
80
+ posted = true;
81
+ postedAtMs = nowMs;
82
+ post({
83
+ droppedShare: Math.round(droppedShare * 1000) / 1000,
84
+ seconds: Math.round(spanMs / 100) / 10,
85
+ choppy: droppedShare >= PLAYBACK_HEALTH.choppyShare,
86
+ fps: Math.round((drawn / (spanMs / 1000)) * 10) / 10,
87
+ worstFrameMs: Math.round(Math.max(...samples.map((sample) => sample.gapMs))),
88
+ skippedShare: Math.round(skipped * 1000) / 1000,
89
+ waitingShare: Math.round((waitingMs / spanMs) * 1000) / 1000,
90
+ frozenShare: Math.round((frozenMs / spanMs) * 1000) / 1000,
91
+ gapP50Ms: gapAt(0.5),
92
+ gapP95Ms: gapAt(0.95),
93
+ clockSource,
94
+ heldBy,
95
+ mode: "play",
96
+ });
97
+ }
98
+ /** One call per runtime tick: counts frames drawn against frames due while the film plays. */
99
+ export function notePlaybackFrame(input) {
100
+ const { nowMs, filmTime, fps, rate } = input;
101
+ const nextKey = `${fps}|${rate}|${input.layoutKey}`;
102
+ if (!input.playing || input.hidden) {
103
+ clear();
104
+ return;
105
+ }
106
+ if (nextKey !== key) {
107
+ key = nextKey;
108
+ clear();
109
+ }
110
+ const frame = Math.floor(filmTime * fps + 1e-6);
111
+ const previous = last;
112
+ last = { ms: nowMs, film: filmTime, frame };
113
+ if (!previous) {
114
+ warmEndMs = nowMs + PLAYBACK_HEALTH.warmupSeconds * 1000;
115
+ return;
116
+ }
117
+ const gapMs = nowMs - previous.ms;
118
+ const expected = previous.film + (gapMs / 1000) * rate;
119
+ if (filmTime < previous.film || filmTime > expected + FORWARD_JUMP_SECONDS) {
120
+ clear();
121
+ last = { ms: nowMs, film: filmTime, frame };
122
+ warmEndMs = nowMs + PLAYBACK_HEALTH.warmupSeconds * 1000;
123
+ return;
124
+ }
125
+ if (nowMs < warmEndMs)
126
+ return;
127
+ clockSource = input.clock;
128
+ samples.push({
129
+ atMs: nowMs,
130
+ gapMs,
131
+ drawn: frame !== previous.frame,
132
+ waiting: input.waiting,
133
+ frozen: input.frozen === true,
134
+ heldBy: input.heldBy ?? null,
135
+ });
136
+ measure(nowMs, fps, rate);
137
+ }
@@ -0,0 +1,16 @@
1
+ type PreloadableMedia = Pick<HTMLMediaElement, "id" | "tagName" | "getAttribute" | "querySelectorAll" | "preload" | "readyState" | "networkState" | "error" | "load">;
2
+ export declare function isRenderFrameVideo(media: Pick<Element, "getAttribute" | "id" | "tagName">): boolean;
3
+ export declare function preloadMedia(media: PreloadableMedia): void;
4
+ export declare function prefetchMedia(media: PreloadableMedia): void;
5
+ export declare function prepareUpcomingMedia(media: HTMLMediaElement, isUpcoming: () => boolean): void;
6
+ /** Ends a fetch in flight for good, which preload none alone does not. */
7
+ export declare function stopMediaDownload(media: HTMLMediaElement): void;
8
+ export declare function releaseMedia(media: HTMLMediaElement, whenBuffered?: boolean): void;
9
+ export declare function lengthIsAuthored(media: Element): boolean;
10
+ export declare function isLongSource(el: Element): boolean;
11
+ export declare function bytesOfSource(src: string): Promise<number | null>;
12
+ export declare function giveBackWhenDue(el: HTMLMediaElement): void;
13
+ /** Preview only: later clips parse at preload none, as Chromium ignores a none set mid-fetch.
14
+ * One watcher per page: a runtime evaluated again replaces the last one's. */
15
+ export declare function deferMediaUntilDue(): void;
16
+ export {};
@@ -0,0 +1,266 @@
1
+ import { parseStrictFiniteTimingNumber, readMediaStart } from "./playbackRate.js";
2
+ import { authoredSrcOf, holdsWhenIdle, isHeldUntilDue, recordOpenedAtInPoint, unproxiedSrc, heldForCopy, } from "./proxySrc.js";
3
+ import { createRuntimeStartTimeResolver } from "./startResolver.js";
4
+ import { readMediaRenderId } from "./renderFrameSibling.js";
5
+ import { defersMedia } from "./timedClipHide.js";
6
+ import { capturePageIn, inPlayerFrame, servedToStudio } from "../studioPreviewMark.js";
7
+ import { swallow } from "./diagnostics.js";
8
+ import { runtimeLoad } from "./runtimeLoad.js";
9
+ import { isChromium, isWebKit, mediaElementTime } from "./mediaClock.js";
10
+ import { setRuntimePreload } from "./runtimeAttributes.js";
11
+ const MEDIA_EDGE_SECONDS = 0.1;
12
+ const loadedFor = new WeakMap();
13
+ const sourceList = (media) => [
14
+ media.getAttribute("src"),
15
+ ...[...media.querySelectorAll("source")].map((el) => el.getAttribute("src")),
16
+ ].join(" ");
17
+ function loadOncePerList(media, preload) {
18
+ const list = sourceList(media);
19
+ const last = loadedFor.get(media);
20
+ const ended = media.error !== null || media.networkState === 3;
21
+ const covered = last?.list === list && (last.preload === "auto" || preload === "metadata");
22
+ if (covered && !ended)
23
+ return;
24
+ loadedFor.set(media, { list, preload });
25
+ runtimeLoad(media);
26
+ }
27
+ export function isRenderFrameVideo(media) {
28
+ const ids = window
29
+ .__HF_RENDER_FRAME_VIDEO_IDS;
30
+ return media.tagName === "VIDEO" && ids?.includes(readMediaRenderId(media) ?? "") === true;
31
+ }
32
+ export function preloadMedia(media) {
33
+ if (isRenderFrameVideo(media))
34
+ return;
35
+ if (media.preload !== "auto")
36
+ setRuntimePreload(media, "auto");
37
+ // load() resets an in-flight video fetch, discarding its selected resource and buffered data.
38
+ const videoAlreadyLoading = media.tagName === "VIDEO" && media.networkState === 2;
39
+ if (media.readyState < 3 && !videoAlreadyLoading)
40
+ loadOncePerList(media, "auto");
41
+ }
42
+ export function prefetchMedia(media) {
43
+ if (!isChromium())
44
+ return preloadMedia(media);
45
+ if (isRenderFrameVideo(media))
46
+ return;
47
+ if (media.preload !== "metadata")
48
+ setRuntimePreload(media, "metadata");
49
+ if (media.readyState === 0 && media.networkState !== 2)
50
+ loadOncePerList(media, "metadata");
51
+ }
52
+ const pendingPlaybackStart = new WeakMap();
53
+ function cancelPlaybackStart(media) {
54
+ pendingPlaybackStart.get(media)?.();
55
+ }
56
+ export function prepareUpcomingMedia(media, isUpcoming) {
57
+ cancelPlaybackStart(media);
58
+ if (isRenderFrameVideo(media))
59
+ return;
60
+ const prepare = () => {
61
+ if (!media.isConnected || !media.paused || media.seeking || !isUpcoming())
62
+ return;
63
+ const start = readMediaStart(media);
64
+ if (Math.abs(media.currentTime - start) <= 0.02)
65
+ return;
66
+ try {
67
+ media.currentTime = mediaElementTime(start);
68
+ }
69
+ catch (error) {
70
+ swallow("runtime.preload.playbackStart", error);
71
+ }
72
+ };
73
+ if (media.readyState > 0) {
74
+ prepare();
75
+ return;
76
+ }
77
+ const cancel = () => {
78
+ media.removeEventListener("loadedmetadata", loaded);
79
+ media.removeEventListener("error", cancel);
80
+ media.removeEventListener("abort", cancel);
81
+ pendingPlaybackStart.delete(media);
82
+ };
83
+ const loaded = () => {
84
+ cancel();
85
+ prepare();
86
+ };
87
+ pendingPlaybackStart.set(media, cancel);
88
+ media.addEventListener("loadedmetadata", loaded);
89
+ media.addEventListener("error", cancel);
90
+ media.addEventListener("abort", cancel);
91
+ }
92
+ /** Ends a fetch in flight for good, which preload none alone does not. */
93
+ export function stopMediaDownload(media) {
94
+ cancelPlaybackStart(media);
95
+ loadedFor.delete(media);
96
+ for (const source of media.querySelectorAll("source"))
97
+ source.remove();
98
+ media.removeAttribute("src");
99
+ runtimeLoad(media);
100
+ }
101
+ function wholeFileBuffered(media) {
102
+ const { buffered, duration } = media;
103
+ return (Number.isFinite(duration) &&
104
+ duration > 0 &&
105
+ buffered.length === 1 &&
106
+ buffered.start(0) <= MEDIA_EDGE_SECONDS &&
107
+ buffered.end(0) >= duration - MEDIA_EDGE_SECONDS);
108
+ }
109
+ export function releaseMedia(media, whenBuffered = false) {
110
+ if (media.querySelector("source") || (!whenBuffered && wholeFileBuffered(media)))
111
+ return;
112
+ if (holdsWhenIdle(media))
113
+ return holdUntilDue(media);
114
+ const src = media.getAttribute("src");
115
+ if (src === null || servedToStudio(document)) {
116
+ stopMediaDownload(media);
117
+ if (src !== null)
118
+ media.setAttribute("src", src);
119
+ return;
120
+ }
121
+ cancelPlaybackStart(media);
122
+ loadedFor.delete(media);
123
+ media.removeAttribute("src");
124
+ media.setAttribute("src", src);
125
+ }
126
+ export function lengthIsAuthored(media) {
127
+ return parseStrictFiniteTimingNumber(media.getAttribute("data-duration")) != null;
128
+ }
129
+ const LONG_SOURCE_BYTES = 32 * 1024 * 1024;
130
+ const sourceBytes = new Map();
131
+ const knownBytes = new Map();
132
+ export function isLongSource(el) {
133
+ const src = unproxiedSrc(el);
134
+ if (!src)
135
+ return false;
136
+ try {
137
+ return (knownBytes.get(new URL(src, document.baseURI).href) ?? 0) >= LONG_SOURCE_BYTES;
138
+ }
139
+ catch {
140
+ return false;
141
+ }
142
+ }
143
+ export function bytesOfSource(src) {
144
+ let url;
145
+ try {
146
+ url = new URL(src, document.baseURI).href;
147
+ }
148
+ catch {
149
+ return Promise.resolve(null);
150
+ }
151
+ const known = sourceBytes.get(url);
152
+ if (known)
153
+ return known;
154
+ const asked = (async () => {
155
+ const abort = new AbortController();
156
+ try {
157
+ const response = await fetch(url, { headers: { Range: "bytes=0-0" }, signal: abort.signal });
158
+ const total = /\/(\d+)$/.exec(response.headers.get("content-range") ?? "")?.[1] ??
159
+ (response.status === 200 ? response.headers.get("content-length") : null);
160
+ if (total === null)
161
+ return null;
162
+ knownBytes.set(url, Number(total));
163
+ return Number(total);
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ finally {
169
+ abort.abort();
170
+ }
171
+ })();
172
+ sourceBytes.set(url, asked);
173
+ return asked;
174
+ }
175
+ function openAtInPoint(el) {
176
+ const src = el.getAttribute("src");
177
+ const start = readMediaStart(el);
178
+ // Only the player: Studio copies and saves what it reads from the page, and must never see the fragment.
179
+ if (!inPlayerFrame(document) || !src || src.includes("#") || el.loop)
180
+ return;
181
+ if (el.querySelector("source"))
182
+ return;
183
+ if (!(start > 0))
184
+ return;
185
+ const written = `${src}#t=${start}`;
186
+ recordOpenedAtInPoint(el, src, written);
187
+ el.setAttribute("src", written);
188
+ }
189
+ // WebKit opens the file for any clip that has a src, whatever its preload: a later clip of a long file has none.
190
+ function holdUntilDue(el) {
191
+ const authored = unproxiedSrc(el);
192
+ if (authored === null)
193
+ return;
194
+ recordOpenedAtInPoint(el, authored, null, true);
195
+ stopMediaDownload(el);
196
+ }
197
+ export function giveBackWhenDue(el) {
198
+ if (!isHeldUntilDue(el) || heldForCopy.has(el))
199
+ return;
200
+ const authored = authoredSrcOf(el);
201
+ const start = readMediaStart(el);
202
+ const written = start > 0 ? `${authored}#t=${start}` : authored;
203
+ recordOpenedAtInPoint(el, authored, written);
204
+ el.setAttribute("src", written);
205
+ }
206
+ // One WebKit began reading at parse opens at its in-point instead: its metadata then costs little.
207
+ const holdable = (el, src) => el.preload === "none" &&
208
+ el.networkState !== 2 &&
209
+ !src.includes("#") &&
210
+ !el.loop &&
211
+ !el.querySelector("source");
212
+ function openLongSourceAtInPoint(el, later, opened, notLong) {
213
+ const src = el.getAttribute("src");
214
+ if (!isWebKit() || !inPlayerFrame(document) || !src)
215
+ return notLong?.();
216
+ void bytesOfSource(src).then((bytes) => {
217
+ if (bytes === null || bytes < LONG_SOURCE_BYTES)
218
+ return notLong?.();
219
+ if (el.getAttribute("src") !== src || !el.paused || el.seeking)
220
+ return;
221
+ if (later && holdable(el, src))
222
+ return holdUntilDue(el);
223
+ openAtInPoint(el);
224
+ opened();
225
+ });
226
+ }
227
+ /** Preview only: later clips parse at preload none, as Chromium ignores a none set mid-fetch.
228
+ * One watcher per page: a runtime evaluated again replaces the last one's. */
229
+ export function deferMediaUntilDue() {
230
+ const win = window;
231
+ win.__hfMediaDeferral?.disconnect();
232
+ win.__hfMediaDeferral = undefined;
233
+ if (!defersMedia())
234
+ return;
235
+ const defer = (el, startInFilm, parsedEarly = false) => {
236
+ const start = parseStrictFiniteTimingNumber(el.getAttribute("data-start"));
237
+ if (start == null || (!lengthIsAuthored(el) && !capturePageIn(document)))
238
+ return;
239
+ const media = el;
240
+ const authoredPreload = media.preload;
241
+ const later = startInFilm(el) > 0;
242
+ if (later)
243
+ setRuntimePreload(media, "none");
244
+ const restore = () => setRuntimePreload(media, authoredPreload);
245
+ openLongSourceAtInPoint(media, later, restore, later && parsedEarly ? restore : undefined);
246
+ };
247
+ win.__hfMediaDeferral = new MutationObserver((records) => {
248
+ const startInFilm = createRuntimeStartTimeResolver({}).resolveMediaStartForElement;
249
+ for (const record of records)
250
+ for (const node of record.addedNodes) {
251
+ if (node.nodeType !== 1)
252
+ continue;
253
+ const el = node;
254
+ if (el.matches("video, audio"))
255
+ defer(el, startInFilm);
256
+ for (const media of el.querySelectorAll("video, audio"))
257
+ defer(media, startInFilm);
258
+ }
259
+ });
260
+ win.__hfMediaDeferral.observe(document.documentElement, { childList: true, subtree: true });
261
+ if (isWebKit()) {
262
+ const startInFilm = createRuntimeStartTimeResolver({}).resolveMediaStartForElement;
263
+ for (const media of document.querySelectorAll("video, audio"))
264
+ defer(media, startInFilm, true);
265
+ }
266
+ }
@@ -0,0 +1,13 @@
1
+ type CopyState = {
2
+ state: "making" | "ready" | "failed";
3
+ progress: number | null;
4
+ light: boolean;
5
+ };
6
+ /** Starts counting the lighter copies wanted at a level; at full quality none are wanted. */
7
+ export declare function setCopyReportingLevel(level: number): void;
8
+ export declare function resetCopyReporting(): void;
9
+ export declare function noteCopy(el: HTMLMediaElement, state: CopyState["state"], progress?: number | null, light?: boolean): void;
10
+ export declare function failedCopyElements(): HTMLMediaElement[];
11
+ /** True when every lighter copy wanted at this level is ready; true when none are wanted. */
12
+ export declare function copiesReady(): boolean;
13
+ export {};
@@ -0,0 +1,80 @@
1
+ import { wallClearTimeout, wallSetTimeout } from "./wallClock.js";
2
+ import { postRuntimeMessage } from "./bridge.js";
3
+ const REPORT_EVERY_MS = 1000;
4
+ const copies = new Map();
5
+ let reporting = false;
6
+ let reportedAny = false;
7
+ let timer;
8
+ let dirtyWhileWaiting = false;
9
+ function report() {
10
+ for (const el of copies.keys())
11
+ if (!el.isConnected)
12
+ copies.delete(el);
13
+ const states = [...copies.values()];
14
+ const wanted = states.length > 0;
15
+ if (!wanted && !reportedAny)
16
+ return false;
17
+ reportedAny = wanted;
18
+ const made = states.reduce((sum, copy) => sum + (copy.state === "ready" ? 1 : (copy.progress ?? 0)), 0);
19
+ postRuntimeMessage({
20
+ source: "hf-preview",
21
+ type: "preview-copies",
22
+ copies: wanted
23
+ ? {
24
+ total: states.length,
25
+ ready: states.filter((copy) => copy.state === "ready").length,
26
+ failed: states.filter((copy) => copy.state === "failed").length,
27
+ progress: made / states.length,
28
+ error: states.some((copy) => copy.state === "failed") ? "failed" : null,
29
+ }
30
+ : null,
31
+ });
32
+ return true;
33
+ }
34
+ function scheduleReport() {
35
+ if (timer !== undefined) {
36
+ dirtyWhileWaiting = true;
37
+ return;
38
+ }
39
+ if (!report())
40
+ return;
41
+ timer = wallSetTimeout(() => {
42
+ timer = undefined;
43
+ if (dirtyWhileWaiting) {
44
+ dirtyWhileWaiting = false;
45
+ scheduleReport();
46
+ }
47
+ }, REPORT_EVERY_MS);
48
+ }
49
+ /** Starts counting the lighter copies wanted at a level; at full quality none are wanted. */
50
+ export function setCopyReportingLevel(level) {
51
+ for (const [el, copy] of copies)
52
+ if (copy.light)
53
+ copies.delete(el);
54
+ reporting = level < 1;
55
+ wallClearTimeout(timer);
56
+ timer = undefined;
57
+ dirtyWhileWaiting = false;
58
+ scheduleReport();
59
+ }
60
+ export function resetCopyReporting() {
61
+ copies.clear();
62
+ wallClearTimeout(timer);
63
+ timer = undefined;
64
+ reporting = false;
65
+ reportedAny = false;
66
+ dirtyWhileWaiting = false;
67
+ }
68
+ export function noteCopy(el, state, progress = null, light = true) {
69
+ if (light && !reporting)
70
+ return;
71
+ copies.set(el, { state, progress, light });
72
+ scheduleReport();
73
+ }
74
+ export function failedCopyElements() {
75
+ return [...copies].filter(([, copy]) => copy.state === "failed").map(([el]) => el);
76
+ }
77
+ /** True when every lighter copy wanted at this level is ready; true when none are wanted. */
78
+ export function copiesReady() {
79
+ return [...copies.values()].every((copy) => !copy.light || copy.state === "ready");
80
+ }
@@ -0,0 +1,3 @@
1
+ /** Asks for one byte of a `?hf-proxy=` URL until it is served, after each Retry-After: while the
2
+ * server answers 202 (copy being made) or 503 (queue full), after up to 3 failed asks; a throw is not served. */
3
+ export declare function waitForServedProxy(href: string, live: () => boolean, onProgress?: (fraction: number) => void, atPlayhead?: () => boolean, background?: boolean, onAsk?: () => void): Promise<boolean>;
@@ -0,0 +1,51 @@
1
+ import { wallSetTimeout } from "./wallClock.js";
2
+ import { capturePageIn } from "../studioPreviewMark.js";
3
+ import { PREVIEW_PROXY_PRIORITY_HEADER, PREVIEW_PROXY_PROGRESS_HEADER, PREVIEW_PROXY_RETRY_PARAM, } from "../previewProxyBox.js";
4
+ const MAX_FAILED_ASKS = 3;
5
+ function withoutRetryFlag(href) {
6
+ const url = new URL(href, document.baseURI);
7
+ url.searchParams.delete(PREVIEW_PROXY_RETRY_PARAM);
8
+ return url.href;
9
+ }
10
+ function askHeaders(atPlayhead, background, onAsk) {
11
+ onAsk?.();
12
+ const headers = { Range: "bytes=0-0" };
13
+ if (atPlayhead)
14
+ headers[PREVIEW_PROXY_PRIORITY_HEADER] = "1";
15
+ else if (background)
16
+ headers[PREVIEW_PROXY_PRIORITY_HEADER] = "0";
17
+ return headers;
18
+ }
19
+ function reportProgress(res, onProgress) {
20
+ const reached = res?.status === 202 ? res.headers.get(PREVIEW_PROXY_PROGRESS_HEADER) : null;
21
+ if (reached !== null && Number.isFinite(Number(reached))) {
22
+ onProgress?.(Math.min(1, Math.max(0, Number(reached))));
23
+ }
24
+ }
25
+ /** Asks for one byte of a `?hf-proxy=` URL until it is served, after each Retry-After: while the
26
+ * server answers 202 (copy being made) or 503 (queue full), after up to 3 failed asks; a throw is not served. */
27
+ export async function waitForServedProxy(href, live, onProgress, atPlayhead = () => false, background = false, onAsk) {
28
+ let failed = 0;
29
+ let ask = href;
30
+ const onUnwatchedCapturePage = capturePageIn(document);
31
+ try {
32
+ while (live()) {
33
+ const headers = askHeaders(!onUnwatchedCapturePage && atPlayhead(), background || onUnwatchedCapturePage, onAsk);
34
+ const res = await fetch(ask, { headers, cache: "no-store" }).catch(() => null);
35
+ ask = withoutRetryFlag(href);
36
+ void res?.body?.cancel().catch(() => { });
37
+ const pending = res?.status === 202 || res?.status === 503;
38
+ reportProgress(res, onProgress);
39
+ if (!pending && res?.ok)
40
+ return true;
41
+ if (!pending && ++failed > MAX_FAILED_ASKS)
42
+ return false;
43
+ const seconds = Math.min(Number(res?.headers.get("Retry-After")) || 2, 30);
44
+ await new Promise((resolveWait) => wallSetTimeout(resolveWait, seconds * 1000));
45
+ }
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ return false;
51
+ }
@@ -0,0 +1,3 @@
1
+ /** Every load() the runtime makes goes through here, so the sealed CORS handling can tell it from the composition's. */
2
+ export declare function runtimeLoad(media: Pick<HTMLMediaElement, "load">): void;
3
+ export declare const loadedByRuntime: (media: object) => boolean;
@@ -0,0 +1,13 @@
1
+ let loading = null;
2
+ /** Every load() the runtime makes goes through here, so the sealed CORS handling can tell it from the composition's. */
3
+ export function runtimeLoad(media) {
4
+ const outer = loading;
5
+ loading = media;
6
+ try {
7
+ media.load();
8
+ }
9
+ finally {
10
+ loading = outer;
11
+ }
12
+ }
13
+ export const loadedByRuntime = (media) => loading === media;
@@ -33,6 +33,13 @@ export type RuntimeState = {
33
33
  webAudioMediaDisabled: boolean;
34
34
  /** Latch: the first refusal starts `media-autoplay-blocked`, which then follows the media list. */
35
35
  mediaAutoplayBlockedPosted: boolean;
36
+ parentCopiesPosted: boolean;
37
+ parentAudioClips: ReadonlySet<string>;
38
+ parentAudioClock: {
39
+ time: number;
40
+ rate: number;
41
+ at: number;
42
+ } | null;
36
43
  /**
37
44
  * One-shot flag: force a hard media sync on the next tick. Set on
38
45
  * play/pause/seek/rate transitions to immediately correct any
@@ -11,6 +11,9 @@ export function createRuntimeState() {
11
11
  nativeMediaSyncDisabled: false,
12
12
  webAudioMediaDisabled: false,
13
13
  mediaAutoplayBlockedPosted: false,
14
+ parentCopiesPosted: false,
15
+ parentAudioClips: new Set(),
16
+ parentAudioClock: null,
14
17
  mediaForceSyncNextTick: false,
15
18
  playbackRate: 1,
16
19
  bridgeLastPostedFrame: -1,
@@ -0,0 +1,12 @@
1
+ import { CLIP_HIDDEN_ATTR } from "./clipReveal.js";
2
+ export { CLIP_HIDDEN_ATTR };
3
+ export declare const SKIPPED_CLIP = "[data-start]:not(video, audio, img, [data-hf-upcoming], [data-hf-autostamped])[data-hf-clip-hidden]";
4
+ export declare function showHiddenClips(only?: (el: HTMLElement) => boolean): () => void;
5
+ export declare function showClips(hidden: Array<Element & ElementCSSInlineStyle>): () => void;
6
+ export declare function defersMedia(): boolean;
7
+ /** True in Studio's preview, where hidden clips' images are neither fetched nor decoded until due. */
8
+ export declare function skipsHiddenImages(): boolean;
9
+ export declare function hideTimedClipsUntilFirstPass(): void;
10
+ /** True when this call lifted the rule; callers then re-register what skipped hidden elements (grading). */
11
+ export declare function revealTimedClipsAfterFirstPass(): boolean;
12
+ export declare function keepInlineHideRulesForOlderShaders(): void;