@hyperframes/core 0.9.94 → 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 (61) hide show
  1. package/dist/atomicFile.js +14 -9
  2. package/dist/audibleVideo.d.ts +10 -0
  3. package/dist/audibleVideo.js +37 -0
  4. package/dist/compiler/htmlBundler.js +2 -0
  5. package/dist/compiler/index.d.ts +1 -0
  6. package/dist/compiler/index.js +1 -0
  7. package/dist/compiler/inlineSubCompositions.js +2 -1
  8. package/dist/compositionSource.d.ts +1 -0
  9. package/dist/compositionSource.js +22 -1
  10. package/dist/generated/runtime-inline.js +1 -1
  11. package/dist/hyperframe.runtime.iife.js +67 -67
  12. package/dist/index.d.ts +1 -1
  13. package/dist/runtime/adapters/seek-dispatch.d.ts +40 -0
  14. package/dist/runtime/adapters/seek-dispatch.js +164 -0
  15. package/dist/runtime/assetUrl.d.ts +6 -0
  16. package/dist/runtime/assetUrl.js +8 -0
  17. package/dist/runtime/audioFx.d.ts +77 -0
  18. package/dist/runtime/audioFx.js +277 -0
  19. package/dist/runtime/bridge.d.ts +6 -0
  20. package/dist/runtime/bridge.js +20 -0
  21. package/dist/runtime/decodesFirst.d.ts +4 -0
  22. package/dist/runtime/decodesFirst.js +14 -0
  23. package/dist/runtime/drawnBox.d.ts +29 -0
  24. package/dist/runtime/drawnBox.js +100 -0
  25. package/dist/runtime/editingDraft.d.ts +0 -11
  26. package/dist/runtime/editingDraft.js +1 -61
  27. package/dist/runtime/editingElement.js +3 -3
  28. package/dist/runtime/editingGestureStart.d.ts +2 -6
  29. package/dist/runtime/editingGestureStart.js +1 -40
  30. package/dist/runtime/editingHandles.d.ts +4 -0
  31. package/dist/runtime/editingHandles.js +9 -0
  32. package/dist/runtime/editingPort.d.ts +5 -0
  33. package/dist/runtime/editingPort.js +5 -1
  34. package/dist/runtime/media.d.ts +113 -0
  35. package/dist/runtime/media.js +820 -0
  36. package/dist/runtime/mediaLoadFailure.d.ts +8 -0
  37. package/dist/runtime/mediaLoadFailure.js +58 -0
  38. package/dist/runtime/mediaProxy.d.ts +91 -0
  39. package/dist/runtime/mediaProxy.js +803 -0
  40. package/dist/runtime/playbackHealth.d.ts +31 -0
  41. package/dist/runtime/playbackHealth.js +137 -0
  42. package/dist/runtime/preloadMedia.d.ts +16 -0
  43. package/dist/runtime/preloadMedia.js +266 -0
  44. package/dist/runtime/previewCopies.d.ts +13 -0
  45. package/dist/runtime/previewCopies.js +80 -0
  46. package/dist/runtime/proxyWait.d.ts +3 -0
  47. package/dist/runtime/proxyWait.js +51 -0
  48. package/dist/runtime/runtimeLoad.d.ts +3 -0
  49. package/dist/runtime/runtimeLoad.js +13 -0
  50. package/dist/runtime/state.d.ts +7 -0
  51. package/dist/runtime/state.js +3 -0
  52. package/dist/runtime/timedClipHide.d.ts +12 -0
  53. package/dist/runtime/timedClipHide.js +94 -0
  54. package/dist/runtime/types.d.ts +29 -18
  55. package/dist/runtime/webAudioTransport.d.ts +241 -0
  56. package/dist/runtime/webAudioTransport.js +1162 -0
  57. package/dist/safePath.d.ts +2 -0
  58. package/dist/safePath.js +41 -13
  59. package/dist/studioPreviewMark.js +2 -4
  60. package/dist/utils/inlineTextStyleRead.js +2 -4
  61. package/package.json +16 -4
@@ -0,0 +1,820 @@
1
+ import { sourceLengthOf } from "./sourceLength.js";
2
+ import { wallClearTimeout, wallSetTimeout } from "./wallClock.js";
3
+ import { runtimeLoad } from "./runtimeLoad.js";
4
+ import { swallow } from "./diagnostics.js";
5
+ import { isClipVisibleAt, isInClipWindow } from "./clipWindow.js";
6
+ import { isWebKit, mediaElementTime, startsSoundOnlyInsideATap } from "./mediaClock.js";
7
+ import { sameInstant } from "../clipFacts.js";
8
+ import { interpolateVolumeGain } from "./mediaVolumeEnvelope.js";
9
+ import { elementVolumeLaneGain } from "./audioAutomationVolume.js";
10
+ import { fadeGain, NO_FADES, readElementFades } from "../audioFade.js";
11
+ import { readElementPlaybackRate, readElementRateSpec, readMediaStart } from "./playbackRate.js";
12
+ import { rateAt, sourceTimeAt, timeAtSourceTime } from "../speedRamp.js";
13
+ import { clampAudioGain, clipGain, gainTimesLane } from "../audioGain.js";
14
+ import { isMemberGroupHidden } from "../audioGroups.js";
15
+ import { findInjectedRenderFrame } from "./renderFrameSibling.js";
16
+ import { ownsPausedVideoTime } from "./pausedVideoFrames.js";
17
+ import { isRenderFrameVideo } from "./preloadMedia.js";
18
+ import { registerSeekCompletion } from "./adapters/seek-dispatch.js";
19
+ import { cutToHostSlots, wrapLoopedSourceTime } from "../mediaTiming.js";
20
+ import { forgetSteering, markMediaRestarted, isSteering, MEDIA_HARD_SYNC_SECONDS, MEDIA_SYNC_TOLERANCE_SECONDS, steerMedia, } from "./mediaSteer.js";
21
+ import { setRuntimePreload } from "./runtimeAttributes.js";
22
+ export { MEDIA_HARD_SYNC_SECONDS, MEDIA_SYNC_TOLERANCE_SECONDS } from "./mediaSteer.js";
23
+ export { readElementPlaybackRate, readElementRateSpec, resolveNaturalMediaTimelineDuration, } from "./playbackRate.js";
24
+ export function readElementPlaybackStart(el) {
25
+ return readMediaStart(el);
26
+ }
27
+ const HOLD_END_EVENTS = ["seeked", "loadeddata", "error", "emptied", "abort"];
28
+ export const HOLD_CAP_MS = 5000;
29
+ const WEBKIT_STUCK_AUDIO_SECONDS = 1;
30
+ // A playing WebKit audio element that has not moved for this long is frozen, not starting (it starts ~150 ms late).
31
+ const WEBKIT_FROZEN_AUDIO_SECONDS = 0.4;
32
+ const lastMoved = new WeakMap();
33
+ function frozenAudioFor(el, ct, now) {
34
+ const m = lastMoved.get(el);
35
+ if (!m || m.ct !== ct || el.paused || el.seeking || el.readyState < 3) {
36
+ lastMoved.set(el, { ct, at: now });
37
+ return 0;
38
+ }
39
+ return now - m.at;
40
+ }
41
+ // Where a video held on its tail was last sent, and where the browser put it: a browser lands a seek to the end
42
+ // short of it, so asking again for the same time each tick would seek every frame.
43
+ const heldTailSeekedTo = new WeakMap();
44
+ const HELD_TAIL_MOVED_SECONDS = 0.05;
45
+ const releaseHeldVideo = new WeakMap();
46
+ // A seeking video still paints its previous frame, and one still fetching its first data paints none (its seek
47
+ // waits for metadata without setting `seeking`); frame captures wait on the barrier until it lands. The 5 s cap is
48
+ // the only end for a stalled source (`suspend` also fires between range requests); capture phase catches <source>.
49
+ function holdSeekBarrierUntilVideoLands(el) {
50
+ const loading = el.readyState < el.HAVE_CURRENT_DATA &&
51
+ el.networkState === el.NETWORK_LOADING &&
52
+ !window.__HF_EXPORT_RENDER_SEEK_CONFIG;
53
+ if (el.tagName !== "VIDEO" || !(el.seeking || loading) || findInjectedRenderFrame(el))
54
+ return;
55
+ releaseHeldVideo.get(el)?.();
56
+ registerSeekCompletion(new Promise((resolve) => {
57
+ const done = (event) => {
58
+ if (event?.type === "loadeddata" && el.seeking)
59
+ return;
60
+ wallClearTimeout(cap);
61
+ for (const type of HOLD_END_EVENTS)
62
+ el.removeEventListener(type, done, true);
63
+ if (releaseHeldVideo.get(el) === done)
64
+ releaseHeldVideo.delete(el);
65
+ resolve();
66
+ };
67
+ const cap = wallSetTimeout(done, HOLD_CAP_MS);
68
+ for (const type of HOLD_END_EVENTS)
69
+ el.addEventListener(type, done, true);
70
+ releaseHeldVideo.set(el, done);
71
+ }), "video-frame");
72
+ }
73
+ /**
74
+ * Resolve a media element's timeline window without conflating a video's
75
+ * authored display slot with the amount of source left to decode.
76
+ *
77
+ * An explicit video slot may outlive its source and hold the final frame; a loop fills its slot.
78
+ * Other audio remains source-bounded because it has no visual hold state.
79
+ */
80
+ export function resolveRuntimeMediaClipDuration(params) {
81
+ const fillsSlot = params.isVideo || params.loops;
82
+ const mediaDuration = fillsSlot
83
+ ? (params.explicitDuration ?? params.sourceDuration)
84
+ : params.sourceDuration;
85
+ const candidates = (fillsSlot
86
+ ? [mediaDuration, params.hostRemaining]
87
+ : [mediaDuration, params.hostRemaining, params.explicitDuration]).filter((value) => value != null && Number.isFinite(value) && value >= 0);
88
+ return candidates.length > 0 ? Math.min(...candidates) : null;
89
+ }
90
+ export function refreshRuntimeMediaCache(params) {
91
+ const mediaEls = params?.elements ??
92
+ Array.from(document.querySelectorAll("video, audio"));
93
+ const timedMediaEls = params?.shouldIncludeElement
94
+ ? mediaEls.filter((el) => params.shouldIncludeElement?.(el))
95
+ : mediaEls.filter((el) => el.hasAttribute("data-start"));
96
+ const mediaClips = [];
97
+ const videoClips = [];
98
+ let maxMediaEnd = 0;
99
+ for (const el of timedMediaEls) {
100
+ let start = params?.resolveStartSeconds
101
+ ? params.resolveStartSeconds(el)
102
+ : Number.parseFloat(el.dataset.start ?? "0");
103
+ if (!Number.isFinite(start))
104
+ continue;
105
+ const mediaStart = readElementPlaybackStart(el);
106
+ const playbackRate = readElementPlaybackRate(el);
107
+ const rate = readElementRateSpec(el);
108
+ const loop = el.loop;
109
+ const length = sourceLengthOf(el);
110
+ const sourceDuration = Number.isFinite(length) && length > 0 ? length : null;
111
+ let duration = params?.resolveDurationSeconds?.(el) ?? Number.parseFloat(el.dataset.duration ?? "");
112
+ if ((!Number.isFinite(duration) || duration < 0) && sourceDuration != null) {
113
+ // Effective duration accounts for playback rate:
114
+ // at 0.5x, a 10s source plays for 20s on the timeline
115
+ duration = Math.max(0, timeAtSourceTime(rate, sourceDuration - mediaStart));
116
+ }
117
+ const hasKnownDuration = Number.isFinite(duration) && duration >= 0;
118
+ let end = hasKnownDuration ? start + duration : Number.POSITIVE_INFINITY;
119
+ const origin = start;
120
+ const kept = cutToHostSlots({ start, end }, params?.resolveHostSlots?.(el) ?? []);
121
+ if (kept.start !== start || kept.end !== end) {
122
+ ({ start, end } = kept);
123
+ duration = end - start;
124
+ }
125
+ const volumeRaw = Number.parseFloat(el.dataset.volume ?? "");
126
+ const clip = {
127
+ el,
128
+ start,
129
+ origin,
130
+ mediaStart,
131
+ duration: Number.isFinite(end) ? duration : Number.POSITIVE_INFINITY,
132
+ end,
133
+ volume: Number.isFinite(volumeRaw) ? volumeRaw : null,
134
+ playbackRate,
135
+ rate,
136
+ loop,
137
+ sourceDuration,
138
+ fades: readElementFades(el),
139
+ };
140
+ mediaClips.push(clip);
141
+ if (el.tagName === "VIDEO")
142
+ videoClips.push(clip);
143
+ if (Number.isFinite(end))
144
+ maxMediaEnd = Math.max(maxMediaEnd, end);
145
+ }
146
+ return { timedMediaEls, mediaClips, videoClips, maxMediaEnd };
147
+ }
148
+ // Per-element timeline→media offset from the previous tick. Used to tell a
149
+ // gradual drift (initial buffer catch-up, where offset grows ~16ms/tick) from
150
+ // a scrub (where offset jumps in one tick). Cleared when a clip becomes
151
+ // inactive so the next activation gets a hard resync on its first tick.
152
+ const lastOffset = new WeakMap();
153
+ // Desired source time from the previous active tick. Unlike `forceSync`, which
154
+ // also covers play/pause and rate changes, a decrease here identifies an actual
155
+ // backward transport seek within an audio clip.
156
+ const lastRelativeTime = new WeakMap();
157
+ const strictDriftSamples = new WeakMap();
158
+ // Elements that had a seek past their buffered range (common with streaming
159
+ // MP3 where preload="metadata" only fetches the first few seconds). After
160
+ // setting preload="auto" and calling load(), we mark the element so subsequent
161
+ // ticks don't restart the fetch in a loop while the browser downloads data.
162
+ // Cleared when the clip leaves its active window.
163
+ const seekLoadRetried = new WeakSet();
164
+ // Elements whose play() is in flight. The sync runs on a 50 ms poll and with
165
+ // a 1–2 s buffer that would fire 20–40 spurious play() calls per element —
166
+ // noise in devtools and, worse, each `.catch(() => {})` would swallow a real
167
+ // AbortError / NotAllowedError that should surface. Cleared on the `playing`
168
+ // event (actual playback started) or on `pause`/`error` (state ended).
169
+ const playRequested = new WeakSet();
170
+ const startedEarly = new WeakSet();
171
+ function markPlayRequested(el) {
172
+ noteFirstPlayAsk(el);
173
+ if (playRequested.has(el))
174
+ return;
175
+ playRequested.add(el);
176
+ const clear = () => playRequested.delete(el);
177
+ el.addEventListener("playing", clear, { once: true });
178
+ el.addEventListener("pause", clear, { once: true });
179
+ el.addEventListener("error", clear, { once: true });
180
+ }
181
+ // iOS refuses an unmuted start ~5 s after the tap unless that element played inside a tap: play-then-pause
182
+ // each idle unmuted one from the tap's own call stack. Authored-muted clips start freely and stay deferred.
183
+ export function primeMediaForLaterStarts(els) {
184
+ if (!startsSoundOnlyInsideATap())
185
+ return;
186
+ for (const el of els) {
187
+ if (el.defaultMuted || !el.paused || playRequested.has(el) || isUnplayable(el))
188
+ continue;
189
+ el.play().catch(() => { });
190
+ el.pause();
191
+ }
192
+ }
193
+ // HTMLMediaElement.NETWORK_NO_SOURCE — no usable source (404 / unsupported).
194
+ const MEDIA_NETWORK_NO_SOURCE = 3;
195
+ const MEDIA_NETWORK_IDLE = 1;
196
+ const MEDIA_NETWORK_LOADING = 2;
197
+ const MEDIA_HAVE_NOTHING = 0;
198
+ const MEDIA_HAVE_METADATA = 1;
199
+ const STOPPED_AT_METADATA_MS = 5000;
200
+ const firstPlayAskedAt = new WeakMap();
201
+ const watchedForFirstFrame = new WeakSet();
202
+ const warnedSkipped = new WeakSet();
203
+ const receivedBytes = new WeakSet();
204
+ const sourceOf = (el) => el.currentSrc || el.src;
205
+ function noteFirstPlayAsk(el) {
206
+ if (!watchedForFirstFrame.has(el)) {
207
+ watchedForFirstFrame.add(el);
208
+ el.addEventListener("loadeddata", () => firstPlayAskedAt.set(el, null));
209
+ el.addEventListener("emptied", () => (firstPlayAskedAt.delete(el), receivedBytes.delete(el)));
210
+ el.addEventListener("progress", () => receivedBytes.add(el));
211
+ }
212
+ if (!firstPlayAskedAt.has(el)) {
213
+ firstPlayAskedAt.set(el, el.readyState > MEDIA_HAVE_METADATA ? null : performance.now());
214
+ }
215
+ }
216
+ // Safari can leave a video "loading" with no request ever sent; a slow fetch still delivers bytes (progress).
217
+ function stallSinceFirstAsk(el) {
218
+ const askedAt = firstPlayAskedAt.get(el);
219
+ if (askedAt == null || performance.now() - askedAt < STOPPED_AT_METADATA_MS)
220
+ return null;
221
+ if (el.readyState === MEDIA_HAVE_METADATA && el.networkState === MEDIA_NETWORK_IDLE)
222
+ return "after its header";
223
+ if (el.readyState === MEDIA_HAVE_NOTHING &&
224
+ el.networkState === MEDIA_NETWORK_LOADING &&
225
+ !receivedBytes.has(el))
226
+ return "never started";
227
+ return null;
228
+ }
229
+ const SKIP_REASON = {
230
+ "after its header": "the browser stopped loading it after its header",
231
+ "never started": "the browser never started loading it",
232
+ };
233
+ // Errored, sourceless, or stalled since first asked to play: it can't play, and re-issuing play()
234
+ // every tick just floods rejections. Skip it until its state changes (src reload).
235
+ export function isUnplayable(el) {
236
+ if (el.error != null || el.networkState === MEDIA_NETWORK_NO_SOURCE)
237
+ return true;
238
+ const stall = stallSinceFirstAsk(el);
239
+ if (!stall)
240
+ return false;
241
+ if (!warnedSkipped.has(el)) {
242
+ warnedSkipped.add(el);
243
+ console.warn(`[hyperframes] skipping "${sourceOf(el)}": ${SKIP_REASON[stall]}; the rest plays`);
244
+ }
245
+ return true;
246
+ }
247
+ const lastRuntimeAppliedVolume = new WeakMap();
248
+ function clampVolume(volume) {
249
+ if (!Number.isFinite(volume))
250
+ return 1;
251
+ return Math.max(0, Math.min(1, volume));
252
+ }
253
+ /**
254
+ * Drop every per-source sync baseline tracked for `el` — offset drift
255
+ * samples, the seek-past-buffered-range retry latch, and the last
256
+ * runtime-applied volume — so the next `syncRuntimeMedia` tick treats it as
257
+ * a first tick (hard resync, fresh drift baseline) instead of comparing
258
+ * against state computed for a different file. Used both when a clip leaves
259
+ * its active window (below) and by the runtime's proxy-swap helper
260
+ * (mediaProxy.ts) right after an in-place `src` swap, which points the same
261
+ * element at a different file without ever leaving its active window.
262
+ */
263
+ export function evictMediaSyncState(el) {
264
+ heldTailSeekedTo.delete(el);
265
+ lastMoved.delete(el);
266
+ lastOffset.delete(el);
267
+ lastRelativeTime.delete(el);
268
+ strictDriftSamples.delete(el);
269
+ seekLoadRetried.delete(el);
270
+ lastRuntimeAppliedVolume.delete(el);
271
+ forgetSteering(el);
272
+ heldAhead.delete(el);
273
+ forgetOutPoint(el);
274
+ videoStarts.delete(el);
275
+ }
276
+ /** Whether the clip is inside its window at the playhead right now: the sync tick keeps its time while it is. */
277
+ export function isActiveAtPlayhead(el) {
278
+ return lastRelativeTime.has(el);
279
+ }
280
+ /** The source time the clip shows at the playhead, while it is inside its window. */
281
+ export function sourceTimeAtPlayhead(el) {
282
+ return lastRelativeTime.get(el);
283
+ }
284
+ /** Test-only seam: whether any per-source sync state is still tracked for `el`. */
285
+ export function hasMediaSyncStateForTest(el) {
286
+ return (lastOffset.has(el) ||
287
+ lastRelativeTime.has(el) ||
288
+ strictDriftSamples.has(el) ||
289
+ seekLoadRetried.has(el) ||
290
+ lastRuntimeAppliedVolume.has(el) ||
291
+ isSteering(el));
292
+ }
293
+ export const MEDIA_PRESEEK_SECONDS = 1.5;
294
+ export function mediaSourceTimeAt(clip, timeSeconds) {
295
+ const elapsed = Math.max(0, Math.min(timeSeconds, clip.end) - (clip.origin ?? clip.start));
296
+ const target = clip.mediaStart + sourceTimeAt(clip.rate ?? clip.playbackRate, elapsed);
297
+ if (clip.sourceDuration == null)
298
+ return target;
299
+ if (clip.loop)
300
+ return wrapLoopedSourceTime(target, clip.mediaStart, clip.sourceDuration);
301
+ // A non-loop video past its source holds the last frame.
302
+ if (!clip.loop && clip.el.tagName === "VIDEO")
303
+ return Math.min(target, clip.sourceDuration);
304
+ return target;
305
+ }
306
+ function prepareUpcomingMedia(clip, time, playing, rate) {
307
+ const { el } = clip;
308
+ const dueIn = clip.start - time;
309
+ if (!playing ||
310
+ dueIn <= 0 ||
311
+ dueIn > MEDIA_PRESEEK_SECONDS * rate ||
312
+ !el.paused ||
313
+ el.seeking ||
314
+ el.readyState < el.HAVE_METADATA ||
315
+ findInjectedRenderFrame(el) ||
316
+ ("__HF_EXPORT_RENDER_SEEK_CONFIG" in window && window.__HF_EXPORT_RENDER_SEEK_CONFIG))
317
+ return;
318
+ const target = mediaSourceTimeAt(clip, clip.start);
319
+ if (!Number.isFinite(target) || target < 0 || Math.abs(el.currentTime - target) <= 0.001)
320
+ return;
321
+ try {
322
+ // A trimmed clip seeked as it opens shows no frame and plays late, then is seeked again while it sounds.
323
+ // Hidden preparation must not hold the visible-frame seek barrier.
324
+ el.currentTime = mediaElementTime(target);
325
+ }
326
+ catch (err) {
327
+ swallow("runtime.media.preseek", err);
328
+ }
329
+ }
330
+ // Chromium refuses a slower playbackRate (NotSupportedError).
331
+ const MIN_NATIVE_PLAYBACK_RATE = 1 / 16;
332
+ // A video this far ahead of the playhead, or at its out-point, is held until the playhead reaches it:
333
+ // steering a lead of a few hundred ms takes seconds and shows frames past the cut.
334
+ const VIDEO_LEAD_HOLD_SECONDS = 0.1;
335
+ const heldAhead = new WeakSet();
336
+ // Where a browser reports presented frames, a video nearing its out-point is paused on the last
337
+ // frame before it, so a cut shows every frame up to the out-point and none past it.
338
+ const OUT_POINT_WATCH_SECONDS = 0.5;
339
+ const outPointWatch = new WeakMap();
340
+ const heldAtOutPoint = new WeakMap();
341
+ const lastFrameBefore = new WeakMap();
342
+ const reportsFrames = (el) => typeof el.requestVideoFrameCallback === "function";
343
+ function watchOutPoint(el, outPoint) {
344
+ if (outPointWatch.get(el) === outPoint)
345
+ return;
346
+ outPointWatch.set(el, outPoint);
347
+ let previous = null;
348
+ let shortestStep = Number.POSITIVE_INFINITY;
349
+ let longestStep = 0;
350
+ const onFrame = (_now, frame) => {
351
+ if (outPointWatch.get(el) !== outPoint)
352
+ return;
353
+ if (el.paused) {
354
+ outPointWatch.delete(el);
355
+ return;
356
+ }
357
+ // A seek between two frames is not a frame step; a dropped frame or an uneven cadence is a longer one.
358
+ const gap = previous === null ? Number.NaN : frame.mediaTime - previous;
359
+ if (gap > 0 && gap < VIDEO_LEAD_HOLD_SECONDS) {
360
+ shortestStep = Math.min(shortestStep, gap);
361
+ longestStep = Math.max(longestStep, gap);
362
+ const framesLeft = Math.floor((outPoint - 0.001 - frame.mediaTime) / shortestStep);
363
+ lastFrameBefore.set(el, { outPoint, at: frame.mediaTime + framesLeft * shortestStep });
364
+ }
365
+ previous = frame.mediaTime;
366
+ if (frame.mediaTime + (longestStep || MEDIA_SYNC_TOLERANCE_SECONDS) < outPoint - 0.001) {
367
+ el.requestVideoFrameCallback(onFrame);
368
+ return;
369
+ }
370
+ outPointWatch.delete(el);
371
+ heldAtOutPoint.set(el, outPoint);
372
+ heldAhead.add(el);
373
+ el.pause();
374
+ };
375
+ el.requestVideoFrameCallback(onFrame);
376
+ }
377
+ function forgetOutPoint(el) {
378
+ outPointWatch.delete(el);
379
+ heldAtOutPoint.delete(el);
380
+ lastFrameBefore.delete(el);
381
+ }
382
+ /** Where a watched video is held: on the last frame before its out-point once its cadence is known. */
383
+ function outPointHoldTime(el, outPoint, watched) {
384
+ if (!watched)
385
+ return outPoint - MEDIA_SYNC_TOLERANCE_SECONDS;
386
+ const last = lastFrameBefore.get(el);
387
+ return last?.outPoint === outPoint ? last.at : outPoint;
388
+ }
389
+ // A muted video runs on its audio track, which starts after play(): an upcoming one starts early by the learned delay.
390
+ let videoStartLatency = null;
391
+ const videoStarts = new WeakMap();
392
+ let playheadWasRunning = false;
393
+ export function resetVideoStartLatency() {
394
+ videoStartLatency = null;
395
+ playheadWasRunning = false;
396
+ }
397
+ /** A quarter second in: its lag plus how early it started, capped at 0.1 s. */
398
+ function learnVideoStartLatency(el, time, offset, rate) {
399
+ const start = videoStarts.get(el);
400
+ if (!start || time < start.at)
401
+ return;
402
+ videoStarts.delete(el);
403
+ const sample = ((offset - start.offset) / rate + start.lead) * start.weight;
404
+ const averaged = videoStartLatency === null ? sample : (videoStartLatency + sample) / 2;
405
+ videoStartLatency = Math.min(0.1, Math.max(0, averaged));
406
+ }
407
+ /** A muted video takes its clock from its audio track, whose late start stalls the picture after a cut. */
408
+ function dropSilentAudioTrack(el) {
409
+ if (el.tagName !== "VIDEO" || !el.defaultMuted)
410
+ return;
411
+ const tracks = el.audioTracks;
412
+ for (const track of Array.from(tracks ?? []))
413
+ track.enabled = false;
414
+ }
415
+ // fallow-ignore-next-line complexity
416
+ export function syncRuntimeMedia(params) {
417
+ const forceMuteAll = !!(params.outputMuted || params.userMuted);
418
+ const startWeight = playheadWasRunning ? 1 : 0.5;
419
+ playheadWasRunning = params.playing && params.clockAdvancing !== false;
420
+ for (const clip of params.clips) {
421
+ const { el } = clip;
422
+ if (!el.isConnected)
423
+ continue;
424
+ dropSilentAudioTrack(el);
425
+ const clipRate = clip.rate ?? clip.playbackRate;
426
+ const origin = clip.origin ?? clip.start;
427
+ const isNonLoopVideo = el.tagName === "VIDEO" && !clip.loop;
428
+ const inWindow = isInClipWindow(params.timeSeconds, clip.start, clip.end);
429
+ const dueIn = clip.start - params.timeSeconds;
430
+ const cueAhead = el.tagName === "AUDIO"
431
+ ? (params.cueAheadSeconds ?? 0)
432
+ : params.playing && videoStartLatency !== null
433
+ ? videoStartLatency * params.playbackRate + (params.cueAheadSeconds ?? 0) / 2
434
+ : 0;
435
+ const startsEarly = !inWindow &&
436
+ dueIn > 0 &&
437
+ dueIn * Math.max(1, rateAt(clipRate, clip.start - origin)) <=
438
+ Math.max(cueAhead, startedEarly.has(el) ? MEDIA_SYNC_TOLERANCE_SECONDS : 0);
439
+ if (startsEarly)
440
+ startedEarly.add(el);
441
+ else
442
+ startedEarly.delete(el);
443
+ // A video that runs to the composition end stays the visible frame at and past it, so it
444
+ // is held on the frame it shows at its own end rather than left on a stale one.
445
+ const isTerminalVideo = isNonLoopVideo &&
446
+ !inWindow &&
447
+ (params.timeSeconds >= clip.end || sameInstant(params.timeSeconds, clip.end)) &&
448
+ isClipVisibleAt(params.timeSeconds, clip.start, clip.end, params.getCompositionDuration());
449
+ const relTime = mediaSourceTimeAt(clip, params.timeSeconds - (params.clockAhead?.(el) ?? 0));
450
+ const isHeldVideoTail = isTerminalVideo ||
451
+ (isNonLoopVideo && clip.sourceDuration != null && relTime >= clip.sourceDuration && inWindow);
452
+ const previousRelativeTime = lastRelativeTime.get(el);
453
+ const audioReenteredAfterBackwardSeek = el.tagName === "AUDIO" &&
454
+ (previousRelativeTime === undefined || relTime < previousRelativeTime - 0.04);
455
+ const canSeekEndedMediaBackward = !clip.loop &&
456
+ clip.sourceDuration != null &&
457
+ relTime >= clip.mediaStart &&
458
+ relTime < clip.sourceDuration &&
459
+ (isNonLoopVideo || audioReenteredAfterBackwardSeek);
460
+ // Ended media can re-enter playable source after a backward timeline seek
461
+ // without depending on the browser having reset `ended` first. Audio needs
462
+ // a fresh activation or a measured backward transport seek so ordinary EOF
463
+ // and non-seek force-sync transitions cannot replay its tail. A non-loop
464
+ // video additionally remains an active visual through
465
+ // its authored window, with tail seeks clamped to the final frame.
466
+ const isActive = (inWindow || isTerminalVideo || startsEarly) &&
467
+ relTime >= 0 &&
468
+ (!el.ended || clip.loop || isHeldVideoTail || canSeekEndedMediaBackward);
469
+ if (isActive) {
470
+ lastRelativeTime.set(el, relTime);
471
+ const userVol = clampVolume(params.userVolume ?? 1);
472
+ const fallbackAuthorVolume = clampAudioGain(clip.volume ?? 1);
473
+ const previousRuntimeVolume = lastRuntimeAppliedVolume.get(el);
474
+ const currentElementVolume = clampVolume(el.volume);
475
+ let authorVolume;
476
+ // An explicit volume lane, times `data-volume`, sets the level. Checked before the probed
477
+ // keyframes because the two would otherwise fight, and it is the one the
478
+ // author drew — `lint` warns when a track carries both.
479
+ // Clip-local, NOT `relTime`. A lane's `t` is "seconds from the start of
480
+ // the clip" (see HfAutomationPoint), and the render honours that: the wav
481
+ // is already cut with `-ss mediaStart`, so its t=0 IS the clip's start.
482
+ // `relTime` is MEDIA time — it carries mediaStart, scales by playbackRate
483
+ // and wraps on a loop — so feeding it here played the envelope at a
484
+ // different position than it renders, or ran it off the end entirely on a
485
+ // trimmed clip. The FX lanes on this same feature use clip-local elapsed;
486
+ // there is one time base, and this is it.
487
+ const laneGain = elementVolumeLaneGain(el, params.timeSeconds - origin);
488
+ const routed = params.isWebAudioRouted?.(el) === true;
489
+ const tweened = laneGain === null && (clip.volumeKeyframes?.length ?? 0) > 0;
490
+ const preFxGain = routed ? clipGain(fallbackAuthorVolume, tweened) : 1;
491
+ if (laneGain !== null) {
492
+ authorVolume = routed ? 1 : gainTimesLane(fallbackAuthorVolume, laneGain);
493
+ }
494
+ else if (clip.volumeKeyframes && clip.volumeKeyframes.length > 0) {
495
+ // Keyframes probed from the GSAP timeline — same source as the renderer.
496
+ // Use the interpolated envelope value directly; no need to track GSAP changes.
497
+ // Index by elapsed time on the TIMELINE since the clip began, which is what
498
+ // a normalised envelope is keyed by (and what the renderer's PCM baker uses).
499
+ // `relTime` is a position inside the media SOURCE — it carries `mediaStart`
500
+ // and the playback rate — so it only coincides with the envelope's time base
501
+ // for an untrimmed clip playing at 1x from t=0.
502
+ const elapsedInClip = params.timeSeconds - origin;
503
+ authorVolume = clampAudioGain(interpolateVolumeGain(clip.volumeKeyframes, elapsedInClip));
504
+ }
505
+ else if (routed) {
506
+ authorVolume = 1;
507
+ }
508
+ else if (previousRuntimeVolume === undefined) {
509
+ // First tick this clip is active. The transport has already seeked GSAP
510
+ // to the current time (seekTimelineAndAdapters runs before syncRuntimeMedia),
511
+ // so el.volume reflects the animated value — trust it rather than falling
512
+ // back to data-volume, which would clobber the GSAP-seeked position.
513
+ //
514
+ // Except above unity. `el.volume` is spec-bound to [0,1], so it cannot
515
+ // represent an authored boost, and reading it back can only lose the
516
+ // gain. Without this, a boosted clip opened at 0 dB for one tick and
517
+ // then jumped once the unchanged-since-last-tick branch below took over
518
+ // — audible, and invisible to any test that ticks more than once.
519
+ authorVolume = fallbackAuthorVolume > 1 ? fallbackAuthorVolume : currentElementVolume;
520
+ }
521
+ else if (Math.abs(currentElementVolume - previousRuntimeVolume) > 0.0001) {
522
+ // GSAP (or user code) changed el.volume between ticks — track it.
523
+ //
524
+ // Unity-capped on purpose, and it is not a hole in the ceiling: this
525
+ // reads back through `el.volume`, which the spec pins to [0,1], so it
526
+ // cannot observe an above-unity value however wide the clamp gets. A
527
+ // clip whose volume is actually animated takes the probed-keyframes
528
+ // branch above, which carries the authored gain unclamped; this branch
529
+ // is the fallback for elements no probe ran on.
530
+ authorVolume = currentElementVolume;
531
+ }
532
+ else {
533
+ // Volume unchanged since last tick — use data-volume as the baseline.
534
+ authorVolume = fallbackAuthorVolume;
535
+ }
536
+ // Clip-local fade on top of the resolved level, matching render's afade-after-volume.
537
+ const unfadedVolume = authorVolume;
538
+ const fades = clip.fades ?? NO_FADES;
539
+ if (fades.fadeIn > 0 || fades.fadeOut > 0) {
540
+ authorVolume *= fadeGain(params.timeSeconds - origin, clip.duration + clip.start - origin, fades);
541
+ }
542
+ // A data-hidden ancestor is silent in the export (audioMixer.ts drops
543
+ // it), so preview matches. Folded into the per-tick volume, not
544
+ // el.muted (RULES trap: el.muted is the transport's ownership flag).
545
+ // Two independent ways to be silent, and the second is not an ancestor
546
+ // question: membership lives on the MEMBER's `data-audio-group`, so a
547
+ // muted BUS is invisible to `closest()`. The render drops such members
548
+ // (`memberGroupHidden`), so without this the export was silent where the
549
+ // fallback played at full level.
550
+ const silencedByHidden = el.closest("[data-hidden]") !== null || isMemberGroupHidden(el.ownerDocument, el);
551
+ const effectiveVolume = silencedByHidden ? 0 : clampVolume(authorVolume * userVol);
552
+ if (Math.abs(el.volume - effectiveVolume) > 1e-6)
553
+ el.volume = effectiveVolume;
554
+ lastRuntimeAppliedVolume.set(el, effectiveVolume);
555
+ if (unfadedVolume === authorVolume)
556
+ params.onElementVolume?.(el, effectiveVolume, authorVolume, preFxGain);
557
+ else
558
+ params.onElementVolume?.(el, effectiveVolume, authorVolume, preFxGain, unfadedVolume);
559
+ // Mute only when force-muted or the transport owns this element; an unclaimed
560
+ // track stays audible via the HTMLMedia fallback.
561
+ if ((forceMuteAll || params.isWebAudioOwned?.(el)) && !el.muted)
562
+ el.muted = true;
563
+ // Ensure full preload for every active media element. Streaming
564
+ // formats (MP3) may arrive with preload="metadata", which only
565
+ // buffers the first few seconds and causes seeks to silently fail
566
+ // past the buffered range. Setting this on every tick is cheap
567
+ // (no-op when already "auto") and catches elements whose preload
568
+ // was overridden after init.ts set it.
569
+ if (el.preload !== "auto" && !isRenderFrameVideo(el))
570
+ setRuntimePreload(el, "auto");
571
+ if (!params.playing && ownsPausedVideoTime(el)) {
572
+ if (!el.paused)
573
+ el.pause();
574
+ continue;
575
+ }
576
+ // Per-element rate × global transport rate
577
+ const baseRate = rateAt(clipRate, params.timeSeconds - origin) * params.playbackRate;
578
+ // Too slow for the browser to play: kept paused and stepped onto the playhead by seeks.
579
+ const playing = params.playing && baseRate >= MIN_NATIVE_PLAYBACK_RATE;
580
+ // Drift correction — three tiers:
581
+ //
582
+ // 1. Hard sync (0.5s): first tick, timeline jumps (scrub), catastrophic
583
+ // drift (>3s). Unconditional seek — accepts brief rebuffer cost.
584
+ // Forcing el.currentTime every frame causes audible seek hiccups
585
+ // (readyState drops briefly), so we only hard-seek when necessary.
586
+ //
587
+ // 2. Strict sync (40ms, 2 consecutive samples): catches accumulated
588
+ // drift from pause/play toggling or browser media pipeline latency.
589
+ // Offset-stabilization guard (4ms/tick) prevents false corrections
590
+ // during initial buffering where offset grows naturally.
591
+ //
592
+ // 3. Force sync (20ms): on play/pause/seek/rate transitions, correct
593
+ // any drift >20ms immediately via the forceSync one-shot flag.
594
+ //
595
+ // The first tick a clip is active has no previous offset to compare —
596
+ // treated as hard resync so sub-compositions with non-zero mediaStart
597
+ // land on the right frame.
598
+ const STRICT_REQUIRED_SAMPLES = 2;
599
+ const currentElTime = el.currentTime || 0;
600
+ const nativeLoopLap = clip.loop &&
601
+ clip.mediaStart === 0 &&
602
+ clip.sourceDuration != null &&
603
+ params.playing &&
604
+ !el.paused
605
+ ? clip.sourceDuration
606
+ : 0;
607
+ const offsetWithLaps = relTime - currentElTime;
608
+ const offset = nativeLoopLap > 0
609
+ ? offsetWithLaps - Math.round(offsetWithLaps / nativeLoopLap) * nativeLoopLap
610
+ : offsetWithLaps;
611
+ const drift = Math.abs(offset);
612
+ const prevOffset = lastOffset.get(el);
613
+ lastOffset.set(el, offset);
614
+ const firstTickOfClip = prevOffset === undefined;
615
+ const offsetJumped = !firstTickOfClip && Math.abs(offset - prevOffset) > 0.5;
616
+ const webkitAudio = el.tagName === "AUDIO" && isWebKit();
617
+ const frozenFor = webkitAudio ? frozenAudioFor(el, currentElTime, params.timeSeconds) : 0;
618
+ const catastrophicDrift = drift > (webkitAudio ? WEBKIT_STUCK_AUDIO_SECONDS : 3) ||
619
+ frozenFor >= WEBKIT_FROZEN_AUDIO_SECONDS;
620
+ // A short audio clip can leave its native element paused just before EOF.
621
+ // When the timeline re-enters the clip, rewind stale forward state at the
622
+ // strict threshold; do not force cold audio forward while it buffers.
623
+ const staleAudioOnFirstTick = el.tagName === "AUDIO" &&
624
+ firstTickOfClip &&
625
+ currentElTime - relTime > MEDIA_SYNC_TOLERANCE_SECONDS;
626
+ const hardSync = (isHeldVideoTail && drift > 0.001) ||
627
+ (el.ended && canSeekEndedMediaBackward && drift > 0.001) ||
628
+ staleAudioOnFirstTick ||
629
+ (drift > MEDIA_HARD_SYNC_SECONDS && (firstTickOfClip || offsetJumped || catastrophicDrift));
630
+ // Seeking playing media resets a video's decoder (a ~150ms freeze that loops into a
631
+ // seek→freeze→drift→seek stutter) and jumps sounding audio (a click). So playing media skips
632
+ // strict and force sync and is steered by rate; hard sync (>0.5s) and audio past its steer
633
+ // limit seek. A paused transport pauses it below, so a seek that pauses mid-playback lands it.
634
+ if (el.tagName === "VIDEO" && !isHeldVideoTail) {
635
+ const outPoint = mediaSourceTimeAt(clip, clip.end);
636
+ const watched = reportsFrames(el);
637
+ if (watched &&
638
+ playing &&
639
+ !clip.loop &&
640
+ !el.paused &&
641
+ outPoint - currentElTime <= OUT_POINT_WATCH_SECONDS * baseRate)
642
+ watchOutPoint(el, outPoint);
643
+ const atOutPoint = heldAtOutPoint.get(el) === outPoint;
644
+ // A loop's playhead wraps before its element, so its offset jumps by a lap: steering owns loops.
645
+ const ahead = !clip.loop &&
646
+ (offset < -VIDEO_LEAD_HOLD_SECONDS ||
647
+ atOutPoint ||
648
+ currentElTime >= outPointHoldTime(el, outPoint, watched));
649
+ if (!playing || (!ahead && offset >= -MEDIA_SYNC_TOLERANCE_SECONDS))
650
+ heldAhead.delete(el);
651
+ else if (ahead && (!el.paused || atOutPoint)) {
652
+ heldAhead.add(el);
653
+ if (!el.paused)
654
+ el.pause();
655
+ }
656
+ }
657
+ const holdingAhead = heldAhead.has(el);
658
+ const isPlayingMedia = !el.paused && playing;
659
+ if (isPlayingMedia)
660
+ learnVideoStartLatency(el, params.timeSeconds, offset, baseRate);
661
+ // Only apply strict sync when offset has stabilized (not growing).
662
+ // During initial buffering, offset grows ~16ms/tick as the timeline
663
+ // advances while media stays at 0. Accumulated drift from pause/play
664
+ // toggling shows up as a stable, non-zero offset (delta near 0).
665
+ const heldBelowFloor = params.playing && !playing;
666
+ const offsetStabilized = heldBelowFloor || (prevOffset !== undefined && Math.abs(offset - prevOffset) < 0.004);
667
+ let strictSync = false;
668
+ if (!isPlayingMedia &&
669
+ !params.keepLateMedia &&
670
+ !holdingAhead &&
671
+ !hardSync &&
672
+ !firstTickOfClip &&
673
+ offsetStabilized &&
674
+ drift > MEDIA_SYNC_TOLERANCE_SECONDS) {
675
+ const samples = (strictDriftSamples.get(el) ?? 0) + 1;
676
+ strictDriftSamples.set(el, samples);
677
+ if (samples >= STRICT_REQUIRED_SAMPLES) {
678
+ strictSync = true;
679
+ strictDriftSamples.set(el, 0);
680
+ }
681
+ }
682
+ else if (drift <= MEDIA_SYNC_TOLERANCE_SECONDS) {
683
+ strictDriftSamples.set(el, 0);
684
+ }
685
+ const forceSync = !isPlayingMedia && !holdingAhead && params.forceSync && drift > 0.02;
686
+ const steered = isPlayingMedia && !hardSync ? steerMedia(el, offset, baseRate, offsetStabilized) : null;
687
+ const steerSeeks = steered?.seek === true;
688
+ const dipped = steerSeeks && params.seekUnderDip?.(el, relTime) === true;
689
+ try {
690
+ // A hard sync lands the element on the playhead, so its pre-seek offset says nothing.
691
+ if (!steered)
692
+ forgetSteering(el);
693
+ const rate = Math.max(MIN_NATIVE_PLAYBACK_RATE, steered?.rate ?? baseRate);
694
+ // Some engines read a rate back at lower precision; an equal-enough rate is not rewritten.
695
+ if (Math.abs(el.playbackRate - rate) > 1e-6)
696
+ el.playbackRate = rate;
697
+ }
698
+ catch (err) {
699
+ // ignore unsupported playbackRate
700
+ swallow("runtime.media.site1", err);
701
+ }
702
+ const heldTail = heldTailSeekedTo.get(el);
703
+ // Only while playing: a paused pass (a seek, a render's prepare) always lands the frame it asks for.
704
+ const tailSettled = isHeldVideoTail &&
705
+ params.playing &&
706
+ heldTail?.target === relTime &&
707
+ Math.abs(el.currentTime - heldTail.landed) < HELD_TAIL_MOVED_SECONDS;
708
+ if (!tailSettled && (hardSync || strictSync || forceSync || (steerSeeks && !dipped))) {
709
+ // Skip the per-tick seek (and the `el.load()` drift-recovery retry
710
+ // below) for `<video>` elements that have a sibling
711
+ // `<img id="__render_frame_<id>__">`. The sibling is created only
712
+ // by the producer's frame-injection pipeline during render — its
713
+ // presence means the visual is painted from the `<img>` and the
714
+ // `<video>` is `visibility: hidden`. Audio is mixed by ffmpeg from
715
+ // source files in `runAudioStage`, never via Chrome's in-browser
716
+ // audio path. So the `<video>`'s `currentTime` has no observable
717
+ // effect during render, and the per-tick set just kicks Chrome's
718
+ // media pipeline for nothing. Preview is unaffected (the sibling
719
+ // only exists during render).
720
+ const skipForInjectedVideo = el.tagName === "VIDEO" && !!findInjectedRenderFrame(el);
721
+ if (!skipForInjectedVideo) {
722
+ try {
723
+ el.currentTime = mediaElementTime(relTime);
724
+ }
725
+ catch (err) {
726
+ swallow("runtime.media.site2", err);
727
+ }
728
+ if (isHeldVideoTail)
729
+ heldTailSeekedTo.set(el, { target: relTime, landed: el.currentTime });
730
+ else
731
+ heldTailSeekedTo.delete(el);
732
+ if (Math.abs(el.currentTime - relTime) > 0.5 && !seekLoadRetried.has(el)) {
733
+ seekLoadRetried.add(el);
734
+ runtimeLoad(el);
735
+ try {
736
+ el.currentTime = mediaElementTime(relTime);
737
+ }
738
+ catch (err) {
739
+ swallow("runtime.media.site3", err);
740
+ }
741
+ }
742
+ holdSeekBarrierUntilVideoLands(el);
743
+ markMediaRestarted(el);
744
+ }
745
+ playRequested.delete(el);
746
+ heldAhead.delete(el);
747
+ forgetOutPoint(el);
748
+ videoStarts.delete(el);
749
+ }
750
+ else if (!playing) {
751
+ holdSeekBarrierUntilVideoLands(el);
752
+ }
753
+ if (isHeldVideoTail) {
754
+ if (!el.paused)
755
+ el.pause();
756
+ }
757
+ else if (playing &&
758
+ !heldAhead.has(el) &&
759
+ params.clockAdvancing !== false &&
760
+ el.paused &&
761
+ !playRequested.has(el) &&
762
+ !isUnplayable(el)) {
763
+ // `HTMLMediaElement.play()` is spec'd to queue playback and resolve
764
+ // once enough data is buffered, so we can unconditionally call it —
765
+ // no need to gate on `readyState` or defer to a `canplay` listener.
766
+ //
767
+ // The old `readyState < HAVE_FUTURE_DATA` branch called `el.load()`
768
+ // inside the listener, which *aborts* the in-flight fetch that
769
+ // `bindMediaMetadataListeners` already started at init time and
770
+ // restarts from zero. On slow networks this delayed playback by
771
+ // seconds. The canplay listener was also racey — the event could
772
+ // fire between `load()` and `addEventListener` attachment, wedging
773
+ // the element waiting for a callback that never came.
774
+ markPlayRequested(el);
775
+ markMediaRestarted(el);
776
+ if (isNonLoopVideo)
777
+ videoStarts.set(el, {
778
+ weight: startWeight,
779
+ offset: relTime - (el.currentTime || 0),
780
+ lead: Math.max(0, clip.start - params.timeSeconds) / params.playbackRate,
781
+ at: Math.max(params.timeSeconds, clip.start) + 0.25 * params.playbackRate,
782
+ });
783
+ void el.play().catch((err) => {
784
+ // If play() rejects — e.g. autoplay blocked, element removed
785
+ // mid-flight — drop the in-flight flag so a future sync tick can
786
+ // retry rather than getting stuck waiting for `playing`/`pause`.
787
+ playRequested.delete(el);
788
+ // `NotAllowedError` is the autoplay-gating browser response when
789
+ // the iframe has no user activation. Signal the parent exactly
790
+ // once so it can promote to parent-frame audio proxies. Retries
791
+ // here would be pointless — nothing the runtime does fixes it.
792
+ const name = err && typeof err === "object" && "name" in err
793
+ ? String(err.name ?? "")
794
+ : "";
795
+ if (name === "NotAllowedError") {
796
+ firstPlayAskedAt.delete(el);
797
+ params.onAutoplayBlocked?.();
798
+ }
799
+ });
800
+ }
801
+ else if (!playing && !el.paused) {
802
+ el.pause();
803
+ }
804
+ continue;
805
+ }
806
+ // Drop drift state when the element is not playable. If native audio EOF
807
+ // arrived slightly before the authored boundary, preserve only its desired
808
+ // source time while the transport remains inside that boundary. Otherwise
809
+ // the next poll would mistake the cleared baseline for a fresh activation
810
+ // and replay the tail. A real backward seek still decreases relTime, and a
811
+ // true outside-window transition clears every baseline as before.
812
+ const remainsInsideAuthoredWindow = isInClipWindow(params.timeSeconds, clip.start, clip.end);
813
+ evictMediaSyncState(el);
814
+ if (remainsInsideAuthoredWindow)
815
+ lastRelativeTime.set(el, relTime);
816
+ if (!el.paused)
817
+ el.pause();
818
+ prepareUpcomingMedia(clip, params.timeSeconds, params.playing, params.playbackRate);
819
+ }
820
+ }