@hyperframes/core 0.9.95 → 0.9.96

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 (39) 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/media.d.ts +113 -0
  17. package/dist/runtime/media.js +820 -0
  18. package/dist/runtime/mediaLoadFailure.d.ts +8 -0
  19. package/dist/runtime/mediaLoadFailure.js +58 -0
  20. package/dist/runtime/mediaProxy.d.ts +91 -0
  21. package/dist/runtime/mediaProxy.js +803 -0
  22. package/dist/runtime/playbackHealth.d.ts +31 -0
  23. package/dist/runtime/playbackHealth.js +137 -0
  24. package/dist/runtime/preloadMedia.d.ts +16 -0
  25. package/dist/runtime/preloadMedia.js +266 -0
  26. package/dist/runtime/previewCopies.d.ts +13 -0
  27. package/dist/runtime/previewCopies.js +80 -0
  28. package/dist/runtime/proxyWait.d.ts +3 -0
  29. package/dist/runtime/proxyWait.js +51 -0
  30. package/dist/runtime/runtimeLoad.d.ts +3 -0
  31. package/dist/runtime/runtimeLoad.js +13 -0
  32. package/dist/runtime/state.d.ts +7 -0
  33. package/dist/runtime/state.js +3 -0
  34. package/dist/runtime/timedClipHide.d.ts +12 -0
  35. package/dist/runtime/timedClipHide.js +94 -0
  36. package/dist/runtime/types.d.ts +29 -18
  37. package/dist/runtime/webAudioTransport.d.ts +241 -0
  38. package/dist/runtime/webAudioTransport.js +1162 -0
  39. package/package.json +12 -4
@@ -0,0 +1,803 @@
1
+ import { wallClearInterval, wallSetInterval, wallSetTimeout } from "./wallClock.js";
2
+ import { runtimeLoad } from "./runtimeLoad.js";
3
+ import { postRuntimeMessage } from "./bridge.js";
4
+ import { swallow } from "./diagnostics.js";
5
+ import { evictMediaSyncState, HOLD_CAP_MS, isActiveAtPlayhead, sourceTimeAtPlayhead, } from "./media.js";
6
+ import { findInjectedRenderFrame } from "./renderFrameSibling.js";
7
+ import { isVideoElement } from "./domRealm.js";
8
+ import { currentSrcValue, deriveCodecMapKey, lookupCodecMapEntry, sourceFactsOf, sourceFactsOfSrc, } from "./mediaSourceLookup.js";
9
+ import { naturalVideoSize } from "../mediaDisplaySize.js";
10
+ import { escapeCssString } from "./editingElement.js";
11
+ import { authoredSrcOf, heldForCopy, heldPosters, inPointOf, recordOpenedAtInPoint, swappedElements, unproxiedSrc, } from "./proxySrc.js";
12
+ import { giveBackWhenDue, stopMediaDownload } from "./preloadMedia.js";
13
+ import { restartPlaybackHealth } from "./playbackHealth.js";
14
+ import { failedCopyElements, noteCopy, setCopyReportingLevel } from "./previewCopies.js";
15
+ import { waitForServedProxy } from "./proxyWait.js";
16
+ import { registerSeekCompletion } from "./adapters/seek-dispatch.js";
17
+ import { formatPreviewProxyBox, isHeavyForPreview, isOversizedForPreview, isPreviewQuality, PREVIEW_QUALITY_LEVELS, PREVIEW_PROXY_BOX_PARAM, PREVIEW_PROXY_LIGHT_PARAM, PREVIEW_PROXY_RETRY_PARAM, PREVIEW_PROXY_STILL_PARAM, quantizePreviewProxyBox, scalePreviewProxyBox, wantsLighterCopy, } from "../previewProxyBox.js";
18
+ import { CAPTURE_STILL_ATTR, capturePageIn, captureStillsIn, PREVIEW_FILE_SIZE_ATTR, } from "../studioPreviewMark.js";
19
+ const PROXY_QUERY_PARAM = "hf-proxy";
20
+ /** Fired whenever an element is swapped to its authoring proxy (any trigger). */
21
+ const DIAGNOSTIC_FALLBACK_CODE = "runtime_media_proxy_fallback";
22
+ /** Fired when the runtime detects an undecodable video but cannot (or already
23
+ * did) proxy it — a remote asset, or the proxy URL itself failing. */
24
+ const DIAGNOSTIC_UNAVAILABLE_CODE = "runtime_media_proxy_unavailable";
25
+ // `swappedElements` gates every trigger, so a second undecodable-video signal never re-swaps.
26
+ // Elements that already got the "can't help you" diagnostic (cross-origin,
27
+ // or the proxy itself failing) — one-shot per element, independent of
28
+ // `swappedElements` so the proxy-failed case (which fires AFTER a real swap)
29
+ // still gets its own single diagnostic.
30
+ const unavailableDiagnosedElements = new WeakSet();
31
+ // Elements whose swap has started, with the src it started for. Until the copy is served they
32
+ // keep that src, so nothing that reads it (timeline, player mirror) loads a copy still being made.
33
+ const proxyRequested = new WeakMap();
34
+ // Below 1, heavy files get lighter copies at the shown box times this level; at 1, files oversized for their box.
35
+ let previewQuality = 1;
36
+ // Elements whose next ask for a copy tells the server to forget its failure first.
37
+ const retryNext = new WeakSet();
38
+ // How large the host shows this document, in its CSS pixels per ours (player fit x page zoom).
39
+ // A top-level page shows itself at 1; a framed one waits for its host to say.
40
+ let displayScale = window.parent === window ? 1 : null;
41
+ let displayScaleArrived = () => { };
42
+ const displayScaleKnown = new Promise((arrived) => (displayScaleArrived = arrived));
43
+ // A host that never says (an older player) gets the source-size copy after this wait.
44
+ const DISPLAY_SCALE_WAIT_MS = 1000;
45
+ const boxedElements = new Map();
46
+ // The larger copy each element waits for; a newer ask replaces it and the older wait stops.
47
+ const pendingUpgrades = new WeakMap();
48
+ function shownScale() {
49
+ if (displayScale !== null)
50
+ return Promise.resolve(displayScale);
51
+ return Promise.race([
52
+ displayScaleKnown.then(() => displayScale),
53
+ new Promise((give) => wallSetTimeout(() => give(null), DISPLAY_SCALE_WAIT_MS)),
54
+ ]);
55
+ }
56
+ /** The video's box in device pixels, at least the stage so a later zoom or a clip still hidden fits. */
57
+ function shownBox(el, scale) {
58
+ // These show the file at its own size when it fits, so a smaller copy would show smaller.
59
+ if (["none", "scale-down"].includes(getComputedStyle(el).objectFit))
60
+ return null;
61
+ const rect = el.getBoundingClientRect();
62
+ const stage = document.documentElement;
63
+ const pixels = scale * (window.devicePixelRatio || 1);
64
+ return quantizePreviewProxyBox(Math.max(rect.width, stage.clientWidth) * pixels, Math.max(rect.height, stage.clientHeight) * pixels);
65
+ }
66
+ /** The host reports how large it shows this document; copies too small for it are replaced. */
67
+ export function setProxyDisplayScale(scale) {
68
+ if (!(scale > 0) || !Number.isFinite(scale))
69
+ return;
70
+ displayScale = scale;
71
+ displayScaleArrived();
72
+ for (const el of boxedElements.keys())
73
+ keepSized(el, scale);
74
+ }
75
+ function codecEntryOf(el) {
76
+ const map = window.__HF_MEDIA_CODEC_MAP__;
77
+ const key = deriveCodecMapKey(el);
78
+ return map && key !== null ? lookupCodecMapEntry(key, map) : null;
79
+ }
80
+ // fallow-ignore-next-line complexity
81
+ function keepSized(el, scale) {
82
+ const copy = boxedElements.get(el);
83
+ if (!copy)
84
+ return;
85
+ if (!el.isConnected || el.getAttribute("src") !== copy.href) {
86
+ boxedElements.delete(el);
87
+ return;
88
+ }
89
+ const shown = shownBox(el, scale);
90
+ const lowered = previewQuality < 1;
91
+ const needed = shown && lowered ? scalePreviewProxyBox(shown, previewQuality) : shown;
92
+ if (lowered && !needed)
93
+ return;
94
+ if (needed && copy.light && lightCopyNoLongerNeeded(el, needed)) {
95
+ return restoreOriginal(el);
96
+ }
97
+ if (boxCovers(copy.box, needed, lowered))
98
+ return dropUnneededCopy(el);
99
+ requestBox(el, copy, lowered || !needed ? needed : growOnly(needed, copy.box));
100
+ }
101
+ function dropUnneededCopy(el) {
102
+ if (pendingUpgrades.delete(el))
103
+ noteCopy(el, "ready");
104
+ }
105
+ function lightCopyNoLongerNeeded(el, needed) {
106
+ const facts = sourceFactsOf(el);
107
+ return facts !== null && !wantsLighterCopy(facts, needed, previewQuality);
108
+ }
109
+ function boxCovers(current, needed, exact) {
110
+ if (exact)
111
+ return needed?.width === current.width && needed.height === current.height;
112
+ return needed !== null && needed.width <= current.width && needed.height <= current.height;
113
+ }
114
+ function growOnly(needed, current) {
115
+ return {
116
+ width: Math.max(needed.width, current.width),
117
+ height: Math.max(needed.height, current.height),
118
+ };
119
+ }
120
+ function requestBox(el, copy, box) {
121
+ const href = appendProxyParam(copy.originalSrc, copy.variant, box, copy.light, retryNext.delete(el));
122
+ if (pendingUpgrades.get(el) === href)
123
+ return;
124
+ pendingUpgrades.set(el, href);
125
+ const wanted = () => pendingUpgrades.get(el) === href && el.isConnected && el.getAttribute("src") === copy.href;
126
+ noteCopy(el, "making", null, copy.light);
127
+ void waitForServedProxy(href, wanted, (fraction) => wanted() && noteCopy(el, "making", fraction, copy.light), () => isActiveAtPlayhead(el)).then((served) => {
128
+ if (wanted())
129
+ noteCopy(el, served ? "ready" : "failed", null, copy.light);
130
+ if (served && wanted())
131
+ loadProxy(el, href, copy.originalSrc, copy.variant, box, copy.light);
132
+ if (pendingUpgrades.get(el) === href)
133
+ pendingUpgrades.delete(el);
134
+ });
135
+ }
136
+ /** Puts a video that only got a lighter copy back on its original. */
137
+ function restoreOriginal(el) {
138
+ const original = swappedElements.get(el) ?? null;
139
+ for (const state of [boxedElements, pendingUpgrades, proxyRequested, swappedElements]) {
140
+ state.delete(el);
141
+ }
142
+ evictMediaSyncState(el);
143
+ restartPlaybackHealth();
144
+ if (original === null) {
145
+ // No file loads, so no event would ever let a held still go.
146
+ letGoOfStill.get(el)?.();
147
+ el.removeAttribute("src");
148
+ }
149
+ else {
150
+ holdShownFrame(el);
151
+ el.setAttribute("src", original);
152
+ }
153
+ runtimeLoad(el);
154
+ }
155
+ // Wide enough to stand in for the picture for the moment a swap takes; small enough to encode in a few ms.
156
+ const HELD_STILL_WIDTH = 640;
157
+ const HAVE_CURRENT_DATA = 2;
158
+ // The new file can draw (and is not seeking), or it failed and holding would freeze the picture.
159
+ const RELEASE_EVENTS = ["loadeddata", "seeked", "error"];
160
+ const letGoOfStill = new WeakMap();
161
+ /** A swapped source empties the video until the new file decodes, which shows black. Until then it shows a still
162
+ * of the frame it had, as its poster. */
163
+ function holdShownFrame(el) {
164
+ if (!isVideoElement(el) || heldPosters.has(el))
165
+ return;
166
+ const still = stillOf(el);
167
+ if (!still)
168
+ return;
169
+ heldPosters.set(el, { poster: el.getAttribute("poster"), since: performance.now() });
170
+ el.setAttribute("poster", still);
171
+ const letGo = () => {
172
+ for (const type of RELEASE_EVENTS)
173
+ el.removeEventListener(type, release);
174
+ letGoOfStill.delete(el);
175
+ const authored = heldPosters.get(el)?.poster ?? null;
176
+ heldPosters.delete(el);
177
+ if (authored === null)
178
+ el.removeAttribute("poster");
179
+ else
180
+ el.setAttribute("poster", authored);
181
+ };
182
+ const release = (event) => {
183
+ if (event.type === "error" || (el.readyState >= HAVE_CURRENT_DATA && !el.seeking))
184
+ letGo();
185
+ };
186
+ for (const type of RELEASE_EVENTS)
187
+ el.addEventListener(type, release);
188
+ letGoOfStill.set(el, letGo);
189
+ }
190
+ /** The frame the video shows, as a JPEG data URL; null with no frame yet or one the page may not read. */
191
+ function stillOf(el) {
192
+ if (el.readyState < HAVE_CURRENT_DATA || !el.videoWidth || !el.videoHeight)
193
+ return null;
194
+ const scale = Math.min(1, HELD_STILL_WIDTH / el.videoWidth);
195
+ const canvas = document.createElement("canvas");
196
+ canvas.width = Math.max(1, Math.round(el.videoWidth * scale));
197
+ canvas.height = Math.max(1, Math.round(el.videoHeight * scale));
198
+ try {
199
+ const context = canvas.getContext("2d");
200
+ if (!context)
201
+ return null;
202
+ context.drawImage(el, 0, 0, canvas.width, canvas.height);
203
+ return canvas.toDataURL("image/jpeg", 0.85);
204
+ }
205
+ catch {
206
+ // A cross-origin frame taints the canvas: the swap goes ahead with nothing held.
207
+ return null;
208
+ }
209
+ }
210
+ function loadProxy(el, href, originalSrc, variant, box, light = false) {
211
+ if (box)
212
+ boxedElements.set(el, { originalSrc, variant, href, box, light });
213
+ else
214
+ boxedElements.delete(el);
215
+ // Sync state measured on the previous file would read the new file's buffering as drift.
216
+ evictMediaSyncState(el);
217
+ restartPlaybackHealth();
218
+ holdShownFrame(el);
219
+ keepFileSize(el, href, originalSrc);
220
+ el.src = href;
221
+ runtimeLoad(el);
222
+ }
223
+ // Each size this page pinned, keyed by mark and copy address, so a video given any other file is sized as before.
224
+ // ponytail: rules are never removed; at most one per copy and size this page asked for.
225
+ let copySizes = null;
226
+ const sizeRules = new Set();
227
+ const pinnedSizes = new WeakMap();
228
+ // Read before a hold or a still lays the box out instead of the file.
229
+ const sizedBeforeCopy = new WeakMap();
230
+ const isCopyAddress = (src) => /[?&]hf-proxy=/.test(src ?? "");
231
+ /** While a smaller copy plays, a video the film leaves unsized keeps the size its file gave it. */
232
+ function keepFileSize(el, href, originalSrc) {
233
+ const decided = sizedBeforeCopy.get(el);
234
+ sizedBeforeCopy.delete(el);
235
+ const size = isVideoElement(el) && (decided ?? sizedByItsFile(el)) ? fileSizeOf(el, originalSrc) : null;
236
+ if (!size) {
237
+ pinnedSizes.delete(el);
238
+ el.removeAttribute(PREVIEW_FILE_SIZE_ATTR);
239
+ return;
240
+ }
241
+ const mark = `${size.width}x${size.height}`;
242
+ pinnedSizes.set(el, { href, mark });
243
+ el.setAttribute(PREVIEW_FILE_SIZE_ATTR, mark);
244
+ const rule = `:where(video[${PREVIEW_FILE_SIZE_ATTR}="${mark}"][src="${escapeCssString(href)}"]) ` +
245
+ `{ width: ${size.width}px; height: ${size.height}px; flex-shrink: 0; }`;
246
+ if (sizeRules.has(rule))
247
+ return;
248
+ sizeRules.add(rule);
249
+ copySizes ??= document.createElement("style");
250
+ copySizes.textContent += `${rule}\n`;
251
+ if (!copySizes.isConnected)
252
+ document.head.appendChild(copySizes);
253
+ }
254
+ /** The film leaves the video's size to its file: its content box is the file's own size (300x150 with none). */
255
+ function sizedByItsFile(el) {
256
+ if (pinnedSizes.get(el)?.href === el.getAttribute("src"))
257
+ return true;
258
+ if (el.getClientRects().length === 0)
259
+ return false;
260
+ const style = getComputedStyle(el);
261
+ const px = (value) => parseFloat(value) || 0;
262
+ const width = el.clientWidth - px(style.paddingLeft) - px(style.paddingRight);
263
+ const height = el.clientHeight - px(style.paddingTop) - px(style.paddingBottom);
264
+ const [own, ownHeight] = el.videoWidth ? [el.videoWidth, el.videoHeight] : [300, 150];
265
+ return Math.abs(width - own) < 1 && Math.abs(height - ownHeight) < 1;
266
+ }
267
+ /** The video's box at its file's size: the original's decoded size when it has one, else its facts. */
268
+ function fileSizeOf(el, originalSrc) {
269
+ const pinned = pinnedSizes.get(el);
270
+ if (pinned?.href === el.getAttribute("src")) {
271
+ const [width = 0, height = 0] = pinned.mark.split("x").map(Number);
272
+ return { width, height };
273
+ }
274
+ if (!isCopyAddress(el.getAttribute("src")) && el.videoWidth > 0) {
275
+ return withBoxEdges(el, { width: el.videoWidth, height: el.videoHeight });
276
+ }
277
+ const facts = sourceFactsOfSrc(originalSrc);
278
+ return facts && withBoxEdges(el, naturalVideoSize(facts));
279
+ }
280
+ /** A border-box video's size with its padding and border added, so its content box stays `size`. */
281
+ function withBoxEdges(el, size) {
282
+ const style = getComputedStyle(el);
283
+ if (style.boxSizing !== "border-box")
284
+ return size;
285
+ const px = (...values) => values.reduce((sum, value) => sum + (parseFloat(value) || 0), 0);
286
+ return {
287
+ width: size.width +
288
+ px(style.paddingLeft, style.paddingRight, style.borderLeftWidth, style.borderRightWidth),
289
+ height: size.height +
290
+ px(style.paddingTop, style.paddingBottom, style.borderTopWidth, style.borderBottomWidth),
291
+ };
292
+ }
293
+ /**
294
+ * Render mode never proxies: the codec map arrives by injection (not a
295
+ * fetch, so determinism holds) but render always decodes the original via
296
+ * FFmpeg frame extraction, never a browser-side element. Mirrors the two
297
+ * render-mode signals already used elsewhere in the runtime — the global
298
+ * export-seek config (init.ts) and the per-element `__render_frame_<id>__`
299
+ * sibling image the producer's frame-injection pipeline creates during
300
+ * render (the same check `syncRuntimeMedia`'s `skipForInjectedVideo` makes
301
+ * in media.ts).
302
+ */
303
+ export function isRenderMode(el) {
304
+ if (window.__HF_EXPORT_RENDER_SEEK_CONFIG)
305
+ return true;
306
+ return isVideoElement(el) && !!findInjectedRenderFrame(el);
307
+ }
308
+ const stills = new WeakSet();
309
+ /** While a file the browser cannot play is being copied, its own frame at the playhead stands in as the poster. */
310
+ function showStill(el, originalSrc, variant, box, light) {
311
+ const at = sourceTimeAtPlayhead(el);
312
+ if (at === undefined || stills.has(el) || el.hasAttribute("poster"))
313
+ return;
314
+ const url = new URL(appendProxyParam(originalSrc, variant, box, light), document.baseURI);
315
+ url.searchParams.set(PREVIEW_PROXY_STILL_PARAM, at.toFixed(1));
316
+ stills.add(el);
317
+ el.setAttribute("poster", url.href);
318
+ }
319
+ function dropStill(el) {
320
+ if (stills.delete(el))
321
+ el.removeAttribute("poster");
322
+ }
323
+ function appendProxyParam(src, variant, box, light = false, retry = false) {
324
+ const url = new URL(src, document.baseURI);
325
+ url.searchParams.set(PROXY_QUERY_PARAM, variant);
326
+ if (box)
327
+ url.searchParams.set(PREVIEW_PROXY_BOX_PARAM, formatPreviewProxyBox(box));
328
+ if (light && box)
329
+ url.searchParams.set(PREVIEW_PROXY_LIGHT_PARAM, "1");
330
+ if (retry)
331
+ url.searchParams.set(PREVIEW_PROXY_RETRY_PARAM, "1");
332
+ return url.href;
333
+ }
334
+ const UNAVAILABLE_NOTES = {
335
+ cross_origin: "video reports zero decodable width but its source is cross-origin; no local proxy can be served for it",
336
+ proxy_playback_failed: "the authoring proxy itself failed to decode; render output is unaffected",
337
+ browser_safe_codec: "the file errored but its codec is browser-decodable; a proxy cannot help (the file itself is likely corrupt)",
338
+ invalid_source_url: "the media source URL is malformed and cannot be proxied",
339
+ };
340
+ function emitUnavailableDiagnostic(el, reason, asset) {
341
+ if (unavailableDiagnosedElements.has(el))
342
+ return;
343
+ unavailableDiagnosedElements.add(el);
344
+ const note = UNAVAILABLE_NOTES[reason];
345
+ const details = {
346
+ asset,
347
+ codecName: null,
348
+ reason,
349
+ note,
350
+ };
351
+ postRuntimeMessage({
352
+ source: "hf-preview",
353
+ type: "diagnostic",
354
+ code: DIAGNOSTIC_UNAVAILABLE_CODE,
355
+ details,
356
+ });
357
+ // Mirrors swapToProxy's fallback line: the stable diagnostic code is in the
358
+ // text so checkBrowser.ts's console scraper can match a token, not prose.
359
+ console.info(`[hyperframes] ${DIAGNOSTIC_UNAVAILABLE_CODE}: "${asset}" (${reason}): ${note}`);
360
+ }
361
+ /** Holds `el` with no src while its copy is made (readers still see its file); false with no src to hold. */
362
+ function holdForCopy(el, holdsCaptures = true) {
363
+ const authored = unproxiedSrc(el);
364
+ if (authored === null)
365
+ return false;
366
+ heldForCopy.set(el, inPointOf(el));
367
+ recordOpenedAtInPoint(el, authored, null);
368
+ stopMediaDownload(el);
369
+ if (!holdsCaptures)
370
+ return true;
371
+ holdFrameCaptures(new Promise((landed) => {
372
+ el.addEventListener("loadeddata", landed, { once: true });
373
+ el.addEventListener("error", landed, { once: true });
374
+ }));
375
+ return true;
376
+ }
377
+ // A file deeper than 8 bits plays only where the browser names its codec at that depth; elsewhere it stays held.
378
+ const DEEP_CODEC_MIME = {
379
+ h264: 'video/mp4; codecs="avc1.6E0028"',
380
+ hevc: 'video/mp4; codecs="hvc1.2.4.L120.B0"',
381
+ vp9: 'video/webm; codecs="vp09.02.10.10"',
382
+ av1: 'video/mp4; codecs="av01.0.08M.10"',
383
+ };
384
+ function decodesItsFile(el, file) {
385
+ const facts = sourceFactsOfSrc(file);
386
+ if (!facts || facts.bitDepth <= 8)
387
+ return true;
388
+ const mime = facts.codec === undefined ? undefined : DEEP_CODEC_MIME[facts.codec];
389
+ return mime !== undefined && el.canPlayType(mime) !== "";
390
+ }
391
+ let playingItsFile = null;
392
+ const copyStillComing = (el) => el.isConnected && !swappedElements.has(el) && proxyRequested.has(el);
393
+ /** Each media tick re-decides a clip whose copy is still being made: the one on screen plays its own file, and every
394
+ * other, one that played its file and left the screen included, is held, so at most one oversized file decodes. */
395
+ export function decideFileTurn(el, onScreen) {
396
+ if (el === playingItsFile && !(onScreen && copyStillComing(el))) {
397
+ playingItsFile = null;
398
+ if (copyStillComing(el))
399
+ holdForCopy(el);
400
+ }
401
+ if (playingItsFile && !playingItsFile.isConnected)
402
+ playingItsFile = null;
403
+ if (!onScreen || playingItsFile || !heldForCopy.has(el) || el.getAttribute("src") !== null)
404
+ return;
405
+ if (captureStills.has(el))
406
+ return; // a capture page shows the server's still, never decodes the original
407
+ const before = heldForCopy.get(el);
408
+ const src = before ? before.written : authoredSrcOf(el);
409
+ if (src === null || !decodesItsFile(el, src))
410
+ return;
411
+ playingItsFile = el;
412
+ heldForCopy.delete(el);
413
+ recordOpenedAtInPoint(el, before?.authored ?? src, src, before?.holdsWhenIdle);
414
+ el.setAttribute("src", src);
415
+ }
416
+ /** Without a copy (`giveBack` set), a clip held until due stays held; any other gets its src back as the runtime's. */
417
+ function endCopyHold(el, giveBack) {
418
+ if (!heldForCopy.has(el))
419
+ return;
420
+ const before = heldForCopy.get(el);
421
+ heldForCopy.delete(el);
422
+ if (giveBack === null || el.getAttribute("src") !== null)
423
+ return;
424
+ const src = before ? before.written : giveBack;
425
+ recordOpenedAtInPoint(el, before?.authored ?? giveBack, src, before?.holdsWhenIdle);
426
+ if (src !== null)
427
+ el.setAttribute("src", src);
428
+ }
429
+ function holdFrameCaptures(until) {
430
+ registerSeekCompletion(Promise.race([until, new Promise((cap) => wallSetTimeout(cap, HOLD_CAP_MS))]), "video-frame");
431
+ }
432
+ // fallow-ignore-next-line complexity
433
+ async function makeCopy(el, job, scale) {
434
+ const { originalSrc, originalAttr, variant, lightFacts, level, live } = job;
435
+ // Asked once the shown size is known, so the copy is made at that size and only once.
436
+ const shown = scale === null ? null : shownBox(el, scale);
437
+ const box = shown && level < 1 ? scalePreviewProxyBox(shown, level) : shown;
438
+ if (lightFacts && !(box && wantsLighterCopy(lightFacts, box, level))) {
439
+ if (proxyRequested.get(el) === originalAttr)
440
+ proxyRequested.delete(el);
441
+ return;
442
+ }
443
+ if (isVideoElement(el))
444
+ sizedBeforeCopy.set(el, sizedByItsFile(el));
445
+ const held = lightFacts && box && isOversizedForPreview(lightFacts, box) && holdForCopy(el);
446
+ const proxiedSrc = appendProxyParam(originalSrc, variant, box, lightFacts !== undefined, retryNext.delete(el));
447
+ const light = lightFacts !== undefined;
448
+ noteCopy(el, "making", null, light);
449
+ const served = await waitForServedProxy(proxiedSrc, live, (fraction) => noteCopy(el, "making", fraction, light), () => isActiveAtPlayhead(el), false, light && !held ? undefined : () => showStill(el, originalSrc, variant, box, light));
450
+ const wanted = live();
451
+ if (!served || !wanted)
452
+ sizedBeforeCopy.delete(el);
453
+ if (held)
454
+ endCopyHold(el, served && wanted ? null : originalAttr);
455
+ if (!wanted) {
456
+ dropStill(el);
457
+ if (proxyRequested.get(el) === originalAttr)
458
+ proxyRequested.delete(el);
459
+ if (lightFacts && el.isConnected && el.getAttribute("src") === originalAttr) {
460
+ applyPreviewQuality(el);
461
+ }
462
+ return;
463
+ }
464
+ if (!served) {
465
+ dropStill(el);
466
+ noteCopy(el, "failed", null, light);
467
+ emitUnavailableDiagnostic(el, "proxy_playback_failed", originalSrc);
468
+ return;
469
+ }
470
+ noteCopy(el, "ready", null, light);
471
+ swappedElements.set(el, held ? originalAttr : unproxiedSrc(el));
472
+ loadProxy(el, proxiedSrc, originalSrc, variant, box, lightFacts !== undefined);
473
+ // The shown size may have grown while this copy was being made.
474
+ if (displayScale !== null)
475
+ keepSized(el, displayScale);
476
+ return new Promise((landed) => {
477
+ el.addEventListener("loadeddata", landed, { once: true });
478
+ el.addEventListener("error", landed, { once: true });
479
+ }).then(() => dropStill(el));
480
+ }
481
+ /**
482
+ * Swap `el` to its alpha-aware proxy URL, evict stale per-source sync state, and
483
+ * emit the one-time diagnostic + console line. Safe to call from any of the
484
+ * three triggers (proactive/reactive/tertiary); a no-op if already swapped.
485
+ */
486
+ function copyVariant(entry) {
487
+ if (!entry)
488
+ return "auto";
489
+ return entry.hasAlpha ? "vp8" : "h264";
490
+ }
491
+ export function swapToProxy(el, entry = null, trigger = "reactive", lightFacts) {
492
+ if (swappedElements.has(el))
493
+ return;
494
+ giveBackWhenDue(el);
495
+ if (proxyRequested.has(el) && proxyRequested.get(el) === el.getAttribute("src"))
496
+ return;
497
+ const originalSrc = currentSrcValue(el);
498
+ const variant = copyVariant(entry);
499
+ try {
500
+ new URL(originalSrc, document.baseURI);
501
+ }
502
+ catch (err) {
503
+ swallow("runtime.mediaProxy.swap", err);
504
+ emitUnavailableDiagnostic(el, "invalid_source_url", originalSrc);
505
+ return;
506
+ }
507
+ const originalAttr = el.getAttribute("src");
508
+ proxyRequested.set(el, originalAttr);
509
+ const level = previewQuality;
510
+ // A lighter copy waits for no level but its own; a copy the file cannot play without finishes at any level.
511
+ const live = () => el.isConnected &&
512
+ (el.getAttribute("src") === originalAttr ||
513
+ (heldForCopy.has(el) && el.getAttribute("src") === null)) &&
514
+ (!lightFacts || previewQuality === level);
515
+ const job = { originalSrc, originalAttr, variant, lightFacts, level, live };
516
+ const swap = shownScale().then((scale) => makeCopy(el, job, scale));
517
+ if (lightFacts)
518
+ return;
519
+ // A frame capture holds for the copy as it held for a loading video before, up to the same cap.
520
+ holdFrameCaptures(swap);
521
+ const codecName = entry?.codecName ?? null;
522
+ const details = {
523
+ asset: originalSrc,
524
+ codecName,
525
+ trigger,
526
+ note: "render output is unaffected; only this preview element was swapped to an authoring proxy",
527
+ };
528
+ postRuntimeMessage({
529
+ source: "hf-preview",
530
+ type: "diagnostic",
531
+ code: DIAGNOSTIC_FALLBACK_CODE,
532
+ details,
533
+ });
534
+ // The diagnostic code doubles as the stable token check's console scraper
535
+ // matches on (packages/cli/src/utils/checkBrowser.ts); keep it in the text.
536
+ console.info(`[hyperframes] ${DIAGNOSTIC_FALLBACK_CODE}: "${originalSrc}" uses a codec (${codecName ?? "unknown"}) this browser can't decode; ` +
537
+ "auto-swapped to an authoring proxy for this preview only. Render output is unaffected.");
538
+ }
539
+ /**
540
+ * Proactive trigger: consult the codec map before an element's first
541
+ * `load()` and swap ahead of time when the browser is known-unlikely to
542
+ * decode it, avoiding an error flash. `<audio>` is never proxied (per the
543
+ * plan's KTD — an HEVC container's AAC track demuxes fine regardless of the
544
+ * browser's video codec support).
545
+ */
546
+ export function maybeProxyProactively(el) {
547
+ if (isRenderMode(el))
548
+ return;
549
+ if (!isVideoElement(el))
550
+ return;
551
+ if (swappedElements.has(el))
552
+ return;
553
+ const entry = codecEntryOf(el);
554
+ const canPlay = entry?.representativeMime ? el.canPlayType(entry.representativeMime) : "";
555
+ const playable = canPlay === "probably" || canPlay === "maybe";
556
+ if (entry?.browserHostile && !playable)
557
+ swapToProxy(el, entry, "proactive");
558
+ else
559
+ lightenIfHeavy(el, entry);
560
+ }
561
+ function lightenIfHeavy(el, entry) {
562
+ if (swappedElements.has(el) || proxyRequested.has(el))
563
+ return;
564
+ if (capturePageIn(document))
565
+ return holdForCaptureStill(el);
566
+ const facts = sourceFactsOf(el);
567
+ if (facts)
568
+ swapToProxy(el, entry, "light", facts);
569
+ }
570
+ // Each held clip's own poster, given back with its file; and the one still ask whose answer counts.
571
+ const captureStills = new WeakMap();
572
+ const stillAsks = new WeakMap();
573
+ /** At least twice the pixels it is drawn at (#7723's rule), and opaque: a JPEG still has no alpha. */
574
+ function stillStandsIn(el) {
575
+ const facts = isVideoElement(el) ? sourceFactsOf(el) : null;
576
+ if (!facts || facts.hasAlpha || codecEntryOf(el)?.hasAlpha)
577
+ return false;
578
+ const box = shownBox(el, 1);
579
+ return box !== null && isOversizedForPreview(facts, box);
580
+ }
581
+ /** On a one-shot capture, such a file is never decoded. */
582
+ function holdForCaptureStill(el) {
583
+ const poster = el.getAttribute("poster");
584
+ if (captureStillsIn(document) && stillStandsIn(el) && holdForCopy(el, false))
585
+ captureStills.set(el, poster);
586
+ }
587
+ /** Each media pass: such a clip on screen shows the server's frame at the playhead; a capture waits for it. */
588
+ export function standInCaptureStill(el, onScreen) {
589
+ const file = onScreen && captureStills.has(el) ? unproxiedSrc(el) : null;
590
+ const at = file === null ? undefined : sourceTimeAtPlayhead(el);
591
+ if (file === null || at === undefined)
592
+ return;
593
+ const url = new URL(appendProxyParam(file, copyVariant(codecEntryOf(el)), shownBox(el, 1), true), document.baseURI);
594
+ url.searchParams.set(PREVIEW_PROXY_STILL_PARAM, at.toFixed(3));
595
+ if (el.getAttribute("poster") === url.href)
596
+ return;
597
+ el.setAttribute("poster", url.href);
598
+ el.removeAttribute(CAPTURE_STILL_ATTR);
599
+ const drawn = new Image();
600
+ stillAsks.set(el, drawn);
601
+ // The page may set its own poster meanwhile: an answer acts only on the poster its own ask put there.
602
+ const ours = () => stillAsks.get(el) === drawn && el.getAttribute("poster") === url.href;
603
+ holdFrameCaptures(new Promise((landed) => {
604
+ drawn.onload = () => {
605
+ if (ours())
606
+ el.setAttribute(CAPTURE_STILL_ATTR, "");
607
+ landed();
608
+ };
609
+ drawn.onerror = () => {
610
+ if (ours())
611
+ decodeItsFile(el, file);
612
+ landed();
613
+ };
614
+ }));
615
+ drawn.src = url.href;
616
+ }
617
+ /** A frame the server could not cut: the clip decodes its own file, as on any capture page, and the capture waits. */
618
+ function decodeItsFile(el, file) {
619
+ const poster = captureStills.get(el);
620
+ captureStills.delete(el);
621
+ el.removeAttribute(CAPTURE_STILL_ATTR);
622
+ if (poster)
623
+ el.setAttribute("poster", poster);
624
+ else
625
+ el.removeAttribute("poster");
626
+ holdFrameCaptures(new Promise((landed) => {
627
+ el.addEventListener("loadeddata", landed, { once: true });
628
+ el.addEventListener("error", landed, { once: true });
629
+ }));
630
+ endCopyHold(el, file);
631
+ }
632
+ function applyPreviewQuality(el) {
633
+ if (isRenderMode(el) || !isVideoElement(el))
634
+ return;
635
+ if (boxedElements.has(el) && displayScale !== null)
636
+ return keepSized(el, displayScale);
637
+ lightenIfHeavy(el, codecEntryOf(el));
638
+ }
639
+ /** The host's preview quality: below 1, heavy videos play lighter copies at the shown box times the level. */
640
+ export function setPreviewQuality(level) {
641
+ if (!isPreviewQuality(level) || level === previewQuality)
642
+ return;
643
+ previewQuality = level;
644
+ setCopyReportingLevel(level);
645
+ restartPlaybackHealth();
646
+ for (const el of document.querySelectorAll("video"))
647
+ applyPreviewQuality(el);
648
+ }
649
+ /** The lower levels at which at least one video would get a lighter copy, by the same rule that makes them. */
650
+ export function levelsWithLighterCopies() {
651
+ if (displayScale === null)
652
+ return [];
653
+ const sized = [...document.querySelectorAll("video")].flatMap((el) => {
654
+ const facts = sourceFactsOf(el);
655
+ const shown = facts && shownBox(el, displayScale ?? 1);
656
+ return facts && shown ? [{ facts, shown }] : [];
657
+ });
658
+ return PREVIEW_QUALITY_LEVELS.filter((level) => level < 1 &&
659
+ sized.some(({ facts, shown }) => isHeavyForPreview(facts, scalePreviewProxyBox(shown, level))));
660
+ }
661
+ const COPY_AHEAD_CHECK_MS = 2000;
662
+ const COPY_AHEAD_LEVEL = 0.5;
663
+ let copiesAheadTimer = null;
664
+ let makingCopyAhead = false;
665
+ const copiesAheadDone = new Set();
666
+ function copyAheadBox(el, isShown) {
667
+ if (displayScale === null || !isShown(el) || swappedElements.has(el))
668
+ return null;
669
+ const shown = shownBox(el, displayScale);
670
+ return shown && scalePreviewProxyBox(shown, COPY_AHEAD_LEVEL);
671
+ }
672
+ /** The 1/2 copy of a clip on screen that is heavy at that size, not yet made. */
673
+ function nextCopyAhead(isShown) {
674
+ if (previewQuality < 1)
675
+ return null;
676
+ for (const el of document.querySelectorAll("video")) {
677
+ const facts = sourceFactsOf(el);
678
+ const box = facts && copyAheadBox(el, isShown);
679
+ if (!facts || !box || !isHeavyForPreview(facts, box))
680
+ continue;
681
+ const variant = copyVariant(codecEntryOf(el));
682
+ const href = appendProxyParam(currentSrcValue(el), variant, box, true, false);
683
+ if (!copiesAheadDone.has(href))
684
+ return href;
685
+ }
686
+ return null;
687
+ }
688
+ /** While on, makes those copies one at a time, starting none while `isBusy`. Off by default. */
689
+ export function setCopiesAhead(on, isBusy, isShown = isActiveAtPlayhead) {
690
+ if (copiesAheadTimer !== null)
691
+ wallClearInterval(copiesAheadTimer);
692
+ copiesAheadTimer = null;
693
+ if (!on)
694
+ return;
695
+ const live = () => copiesAheadTimer !== null && !isBusy();
696
+ const check = () => {
697
+ if (makingCopyAhead || isBusy())
698
+ return;
699
+ const href = nextCopyAhead(isShown);
700
+ if (href === null)
701
+ return;
702
+ makingCopyAhead = true;
703
+ void waitForServedProxy(href, live, undefined, undefined, true).then((served) => {
704
+ makingCopyAhead = false;
705
+ if (served || live())
706
+ copiesAheadDone.add(href);
707
+ });
708
+ };
709
+ copiesAheadTimer = wallSetInterval(check, COPY_AHEAD_CHECK_MS);
710
+ check();
711
+ }
712
+ /** The video files the composition plays, grouped by what they are, never by name. */
713
+ export function describeVideoSources() {
714
+ const groups = new Map();
715
+ for (const el of document.querySelectorAll("video")) {
716
+ const key = deriveCodecMapKey(el);
717
+ const map = window.__HF_MEDIA_CODEC_MAP__;
718
+ const { width = 0, height = 0, bitDepth = 0, codec: probed } = sourceFactsOf(el) ?? {};
719
+ const hostile = map && key !== null ? lookupCodecMapEntry(key, map)?.codecName : undefined;
720
+ const codec = probed ?? hostile ?? "unknown";
721
+ const id = `${codec}|${width}|${height}|${bitDepth}`;
722
+ const group = groups.get(id) ?? { codec, width, height, bitDepth, count: 0 };
723
+ group.count += 1;
724
+ groups.set(id, group);
725
+ }
726
+ return [...groups.values()];
727
+ }
728
+ /** Asks again for the copies that failed, telling the server to forget why they did. */
729
+ export function retryPreviewCopies() {
730
+ for (const el of failedCopyElements()) {
731
+ retryNext.add(el);
732
+ proxyRequested.delete(el);
733
+ pendingUpgrades.delete(el);
734
+ const map = window.__HF_MEDIA_CODEC_MAP__;
735
+ const key = deriveCodecMapKey(el);
736
+ const entry = map && key !== null ? lookupCodecMapEntry(key, map) : null;
737
+ if (boxedElements.has(el) && displayScale !== null)
738
+ keepSized(el, displayScale);
739
+ else if (entry?.browserHostile)
740
+ swapToProxy(el, entry, "reactive");
741
+ else
742
+ lightenIfHeavy(el, entry);
743
+ }
744
+ }
745
+ /**
746
+ * Reactive trigger (the primary catch-all per the plan's KTD): a `<video>`
747
+ * reporting `videoWidth === 0` at `loadedmetadata` has an undecodable (or
748
+ * absent) video track — the common case for an HEVC+AAC file, which fires
749
+ * no error event because the AAC track satisfies the demuxer. Swaps once
750
+ * per element; if the element is already on its proxy src, the proxy
751
+ * itself is the one failing, so this only emits the failure diagnostic.
752
+ *
753
+ * No map, no swaps: the codec map global is only injected on surfaces where
754
+ * auto-proxying is enabled and served, so its absence means a `?hf-proxy=`
755
+ * request would 404 — never swap there. When the map is present but has no
756
+ * entry for this key, swapping stays allowed (unlisted-asset rescue). A
757
+ * mapped alpha entries select the VP8/WebM proxy variant.
758
+ */
759
+ export function handleMetadataForProxy(el) {
760
+ if (isRenderMode(el))
761
+ return;
762
+ if (!isVideoElement(el))
763
+ return;
764
+ if (el.videoWidth !== 0)
765
+ return;
766
+ swapOrDiagnose(el, "reactive");
767
+ }
768
+ /**
769
+ * Tertiary trigger: the `error` event, for the rarer zero-decodable-stream
770
+ * file (video-only hostile codec) where the demuxer has nothing to satisfy
771
+ * it and `loadedmetadata` never fires. Same guards and once-per-element
772
+ * behavior as the reactive path, plus one extra skip: an entry the scan
773
+ * mapped as browser-SAFE that still errors is a corrupt-but-safe file — an
774
+ * proxy of a broken source can't help, so only diagnose.
775
+ */
776
+ export function handleErrorForProxy(el) {
777
+ if (isRenderMode(el))
778
+ return;
779
+ if (!isVideoElement(el))
780
+ return;
781
+ swapOrDiagnose(el, "tertiary");
782
+ }
783
+ function swapOrDiagnose(el, trigger) {
784
+ const src = currentSrcValue(el);
785
+ if (swappedElements.has(el)) {
786
+ emitUnavailableDiagnostic(el, "proxy_playback_failed", src);
787
+ return;
788
+ }
789
+ const map = window.__HF_MEDIA_CODEC_MAP__;
790
+ if (!map)
791
+ return;
792
+ const key = deriveCodecMapKey(el);
793
+ if (key === null) {
794
+ emitUnavailableDiagnostic(el, "cross_origin", src);
795
+ return;
796
+ }
797
+ const entry = lookupCodecMapEntry(key, map);
798
+ if (entry && !entry.browserHostile) {
799
+ emitUnavailableDiagnostic(el, "browser_safe_codec", src);
800
+ return;
801
+ }
802
+ swapToProxy(el, entry, trigger);
803
+ }