@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,1162 @@
1
+ import { wallClearTimeout, wallSetTimeout } from "./wallClock.js";
2
+ import { attachElementFxChain, readElementAutomation, scheduleVolume, } from "./audioFx.js";
3
+ import { clearParamLane } from "../audio/audioFxAutomation.js";
4
+ import { audioGroupOf, readAudioGroupVolume, resolveGroupElement, resolveMasterBusElement, } from "../audioGroups.js";
5
+ import { swallow } from "./diagnostics.js";
6
+ import { reportMediaLoadFailure } from "./mediaLoadFailure.js";
7
+ import { createLevelTap } from "./levelTap.js";
8
+ import { clampAudioGain } from "../audioGain.js";
9
+ import { getDebugSurface } from "./globals.js";
10
+ import { readElementPlaybackRate, readElementRateSpec } from "./media.js";
11
+ import { rateAt, sourceTimeAt, timeAtSourceTime } from "../speedRamp.js";
12
+ import { classifyWebAudioMediaRoute, reportWebAudioMediaRoute } from "./webAudioRoute.js";
13
+ import { assetUrl } from "./assetUrl.js";
14
+ import { mediaElementTime } from "./mediaClock.js";
15
+ import { sourceLengthOf } from "./sourceLength.js";
16
+ import { clampFadesToDuration, fadeGain, readElementFades } from "../audioFade.js";
17
+ import { AudioTooLong, assertDecodeFits, unreadFits } from "../audioDecode.js";
18
+ const MASTER_FX_ATTRS = { automation: null };
19
+ function normalizeRate(rate) {
20
+ if (!Number.isFinite(rate) || rate <= 0)
21
+ return 1;
22
+ return rate;
23
+ }
24
+ /**
25
+ * The render puts every track volume through `clampVolume`, which is
26
+ * `clampAudioGain` — ceiling MAX_AUDIO_GAIN (+12 dB, ~3.98), not unity. Preview
27
+ * has to agree or the two diverge on exactly the attribute this bus exists to
28
+ * honour: an authored `<hf-audio-group data-volume="2">` previewed at 1.0 and
29
+ * exported at 2.0, up to 6 dB quieter in the audition than in the file, and
30
+ * 12 dB at the ceiling. Preview was also self-inconsistent — the same
31
+ * parameter's automation lane is bounded by `VOLUME_RANGE.max`, which IS
32
+ * MAX_AUDIO_GAIN, so an envelope could reach 3.98 where the static fader could
33
+ * not pass 1.0. `clampAudioGain` still floors at 0, so a negative value cannot
34
+ * invert polarity in preview while rendering silent. Compositions are
35
+ * hand-authorable, so out-of-range values do not need a slider to be reachable.
36
+ */
37
+ function clampGroupVolume(volume) {
38
+ return clampAudioGain(volume);
39
+ }
40
+ /**
41
+ * Breadcrumb for the per-element-mute handoff: the transport just claimed a track
42
+ * that was audibly playing through the HTMLMedia fallback. Quiet unless
43
+ * `__hfDebug` — a hook for diagnosing the race if it ever regresses.
44
+ */
45
+ function logFallbackHandoff(el, priorMuted) {
46
+ if (priorMuted || el.paused || !getDebugSurface().__hfDebug)
47
+ return;
48
+ // eslint-disable-next-line no-console -- intentional debug surface
49
+ console.debug("[hyperframes] webAudioTransport claimed fallback-playing element:", el.currentSrc || el.getAttribute("src") || "");
50
+ }
51
+ /**
52
+ * Start a buffer source, bounding it to the clip's authored window
53
+ * (`data-duration`) so a trimmed clip stops at its edge instead of running the
54
+ * buffer to the source file's natural end. `remaining`, the third `start()` arg,
55
+ * is the rest of the clip from the offset in buffer seconds. An infinite
56
+ * `clipDuration` plays unbounded (legacy behavior).
57
+ *
58
+ * Returns false when the playhead is already past the clip end (nothing to
59
+ * play); the caller should discard the source.
60
+ */
61
+ function startBoundedSource(node, opts) {
62
+ const { elapsed, mediaStart, scheduledAt, globalRate, mediaRate, clipDuration, headCut } = opts;
63
+ const hasBound = Number.isFinite(clipDuration) && clipDuration > 0;
64
+ const from = Math.max(elapsed, headCut, 0);
65
+ const remaining = (clipDuration - from) * mediaRate;
66
+ if (hasBound && remaining <= 0)
67
+ return false;
68
+ const when = from > elapsed ? scheduledAt + (from - elapsed) / globalRate : 0;
69
+ let offset = from * mediaRate + mediaStart;
70
+ if (node.loop)
71
+ offset = node.loopStart + ((offset - node.loopStart) % (node.loopEnd - node.loopStart));
72
+ if (hasBound)
73
+ node.start(when, offset, remaining);
74
+ else
75
+ node.start(when, offset);
76
+ return true;
77
+ }
78
+ /**
79
+ * The clip's `data-fade-in` / `data-fade-out` booked on their own gain on the audio clock, from where the clip starts
80
+ * sounding (`from`, clip seconds). A per-tick volume write is 50 ms apart, coarser than a fade: stepped, the clip
81
+ * starts and stops at full level and clicks at every cut. Null when the clip has no fade, or a fade-out with no end
82
+ * to book it against, which the per-tick volume keeps.
83
+ */
84
+ function bookedFades(ctx, el, timing, from, clipDuration) {
85
+ const fades = clampFadesToDuration(readElementFades(el), clipDuration);
86
+ if (fades.fadeIn <= 0 && fades.fadeOut <= 0)
87
+ return null;
88
+ if (fades.fadeOut > 0 && !Number.isFinite(clipDuration))
89
+ return null;
90
+ const node = ctx.createGain();
91
+ const gain = node.gain;
92
+ const level = (clipSeconds) => fadeGain(clipSeconds, clipDuration, fades);
93
+ const book = (t) => {
94
+ const start = Math.max(from, t.elapsed);
95
+ const at = (clipSeconds) => t.scheduledAt + Math.max(0, clipSeconds - t.elapsed) / t.rate;
96
+ gain.value = level(start);
97
+ gain.setValueAtTime(level(start), at(start));
98
+ if (fades.fadeIn > start)
99
+ gain.linearRampToValueAtTime(level(fades.fadeIn), at(fades.fadeIn));
100
+ if (fades.fadeOut > 0) {
101
+ const hold = clipDuration - fades.fadeOut;
102
+ if (hold > start && hold > fades.fadeIn)
103
+ gain.setValueAtTime(level(hold), at(hold));
104
+ gain.linearRampToValueAtTime(0, at(clipDuration));
105
+ }
106
+ };
107
+ book(timing);
108
+ return {
109
+ node,
110
+ rebook: (t) => {
111
+ gain.cancelScheduledValues(0);
112
+ book(t);
113
+ },
114
+ };
115
+ }
116
+ // Clip gain, FX, then the volume lane on its own gain ahead of `gainNode` (all but the lane
117
+ // rewritten every tick); the FX handle re-aims the lane on rate changes and edits.
118
+ function attachClipStages(ctx, el, source, gainNode, timing, span) {
119
+ const laneNode = ctx.createGain();
120
+ laneNode.connect(gainNode);
121
+ const clipGainNode = ctx.createGain();
122
+ const fades = bookedFades(ctx, el, timing, span.from, span.clipDuration);
123
+ if (fades)
124
+ source.connect(fades.node);
125
+ (fades?.node ?? source).connect(clipGainNode);
126
+ const fx = attachElementFxChain(ctx, el, clipGainNode, laneNode, timing, undefined, {
127
+ param: laneNode.gain,
128
+ gain: () => readAudioGroupVolume(el),
129
+ gainAhead: true,
130
+ });
131
+ return { fx, laneNode, clipGainNode, fades };
132
+ }
133
+ function isBufferSource(source) {
134
+ return source.sourceKind === "buffer";
135
+ }
136
+ const decodeKey = (el) => {
137
+ const src = el.currentSrc || el.getAttribute("src");
138
+ if (!src)
139
+ return null;
140
+ try {
141
+ const url = new URL(assetUrl(src));
142
+ url.hash = "";
143
+ return url.href;
144
+ }
145
+ catch {
146
+ return src;
147
+ }
148
+ };
149
+ const DIP_SECONDS = 0.015;
150
+ /** A dipped seek comes back up when the element lands, or when it can no longer land. */
151
+ const DIP_END_EVENTS = ["seeked", "error", "emptied", "abort"];
152
+ /** Where a routed element starts sounding or jumps; a pause needs nothing, no audio flows until `playing`. */
153
+ const FOLLOWED_EVENTS = ["playing", "seeked", "ratechange"];
154
+ // A pause to scrub or a reschedule mid-play keeps the output awake; a real idle lets it sleep.
155
+ const IDLE_SUSPEND_MS = 10000;
156
+ const SHORT_DECODE_SECONDS = 0.25;
157
+ const DECODE_BUDGET_BYTES = 256 * 1024 * 1024;
158
+ const ASSUMED_CHANNELS = 2;
159
+ const BYTES_PER_SAMPLE = 4;
160
+ export class WebAudioTransport {
161
+ /** Request options for every decode fetch, over `cache: "no-store"`. */
162
+ _fetchInit;
163
+ _busDocument;
164
+ _givenContext;
165
+ _ctx = null;
166
+ _bufferCache = new Map();
167
+ _decoding = new Map();
168
+ _pendingDecodeBytes = new Map();
169
+ _failedSrcs = new Set();
170
+ _mediaElementSources = new WeakMap();
171
+ _handedOver = new Set();
172
+ _activeSources = [];
173
+ _masterGain = null;
174
+ /** Where the master bus chain lands; the program meter taps here. */
175
+ _busOut = null;
176
+ /** The chain on the composition root, built on first schedule and kept for the session. */
177
+ _master = null;
178
+ /** Preview volume and mute. Downstream of `_masterGain`; meters tap the program. */
179
+ _monitorGain = null;
180
+ _masterVolume = 1;
181
+ _masterMuted = false;
182
+ // One shared bus per group id, lazily built the first time a member of that
183
+ // group is scheduled. Lives for the session (mirrors `_masterGain`'s own
184
+ // lifecycle) rather than being torn down on every `stopAll()`, so replaying
185
+ // a group does not rebuild its chain; only `destroy()` disposes these.
186
+ _groups = new Map();
187
+ // Level taps exist only between `startMetering()` and `stopMetering()`.
188
+ _metering = false;
189
+ _masterTap = null;
190
+ _groupTaps = new Map();
191
+ // Composition-time reference frame: at AudioContext time `_rateAnchorCtx`,
192
+ // composition time was `_rateAnchorComp`, and time has been advancing at
193
+ // `_rate` composition-seconds per wallclock-second since.
194
+ _rateAnchorCtx = 0;
195
+ _rateAnchorComp = 0;
196
+ _rate = 1;
197
+ _paused = true;
198
+ _playGeneration = 0;
199
+ // A running context renders silence nonstop, so a paused transport keeps it
200
+ // suspended unless a captured track is sounding on the idle route (scrub).
201
+ _playingCaptured = new Set();
202
+ _suspendPending = false;
203
+ _restTimer = null;
204
+ async init() {
205
+ return this.open();
206
+ }
207
+ /** `context`: one the caller opened inside a tap, which Safari only lets sound when made there. */
208
+ constructor(opts = {}) {
209
+ this._fetchInit = opts.fetchInit ?? {};
210
+ this._busDocument = opts.busDocument;
211
+ this._givenContext = opts.context ?? null;
212
+ }
213
+ /** Builds the context on the calling thread: on Windows that opens the audio device and can block seconds. */
214
+ open() {
215
+ if (this._ctx)
216
+ return true;
217
+ try {
218
+ this._ctx = this._givenContext ?? new AudioContext();
219
+ this._givenContext = null;
220
+ this._ctx.onstatechange = () => this.rest();
221
+ this._masterGain = this._ctx.createGain();
222
+ this._busOut = this._ctx.createGain();
223
+ this._monitorGain = this._ctx.createGain();
224
+ this._masterGain.connect(this._busOut);
225
+ this._busOut.connect(this._monitorGain);
226
+ this._monitorGain.connect(this._ctx.destination);
227
+ this.applyMasterGain();
228
+ if (this._metering)
229
+ this.attachMasterTap();
230
+ return true;
231
+ }
232
+ catch {
233
+ return false;
234
+ }
235
+ }
236
+ async wake() {
237
+ if (!this._ctx || (this._ctx.state === "running" && !this._suspendPending))
238
+ return;
239
+ this._suspendPending = false;
240
+ await this._ctx.resume();
241
+ }
242
+ rest() {
243
+ if (this._restTimer !== null)
244
+ wallClearTimeout(this._restTimer);
245
+ this._restTimer = null;
246
+ if (!this._ctx || this._ctx.state !== "running" || this._suspendPending)
247
+ return;
248
+ this._restTimer = wallSetTimeout(() => {
249
+ this._restTimer = null;
250
+ this.suspendIfIdle();
251
+ }, IDLE_SUSPEND_MS);
252
+ }
253
+ suspendIfIdle() {
254
+ // `paused` is the truth; the load algorithm clears it without a "pause" event.
255
+ for (const el of this._playingCaptured)
256
+ if (el.paused)
257
+ this._playingCaptured.delete(el);
258
+ if (!this._ctx || !this._paused || this._suspendPending || this._playingCaptured.size > 0)
259
+ return;
260
+ this._suspendPending = true;
261
+ this._ctx.suspend().catch((err) => {
262
+ this._suspendPending = false;
263
+ swallow("webAudioTransport.suspend", err);
264
+ });
265
+ }
266
+ get context() {
267
+ return this._ctx;
268
+ }
269
+ getTime() {
270
+ if (!this._ctx || this._paused)
271
+ return -1;
272
+ return this._rateAnchorComp + (this._ctx.currentTime - this._rateAnchorCtx) * this._rate;
273
+ }
274
+ /** Drops decoded audio no listed element still points at. A playing source holds its own buffer. */
275
+ releaseDecodedExcept(els) {
276
+ const live = new Set(els.map(decodeKey));
277
+ for (const src of [...this._bufferCache.keys()]) {
278
+ if (!live.has(src))
279
+ this._bufferCache.delete(src);
280
+ }
281
+ }
282
+ /** One fetch and decode per source at a time: a play and a seek scheduling together share it. */
283
+ decodeAudioElement(el) {
284
+ const src = decodeKey(el);
285
+ if (!src)
286
+ return Promise.resolve(null);
287
+ const pending = this._decoding.get(src);
288
+ if (pending)
289
+ return pending;
290
+ this._pendingDecodeBytes.set(src, this.estimateDecodedBytes(el.duration));
291
+ const decoding = this.fetchAndDecode(src, el).finally(() => {
292
+ this._decoding.delete(src);
293
+ this._pendingDecodeBytes.delete(src);
294
+ });
295
+ this._decoding.set(src, decoding);
296
+ return decoding;
297
+ }
298
+ fitsDecodeBudget(el) {
299
+ const src = decodeKey(el);
300
+ if (!src)
301
+ return false;
302
+ if (this._bufferCache.has(src) || this._decoding.has(src))
303
+ return true;
304
+ if (!Number.isFinite(el.duration))
305
+ return false;
306
+ return this.decodedBytes() + this.estimateDecodedBytes(el.duration) <= DECODE_BUDGET_BYTES;
307
+ }
308
+ estimateDecodedBytes(seconds) {
309
+ const rate = this._ctx?.sampleRate ?? 48000;
310
+ if (!Number.isFinite(seconds))
311
+ return 0;
312
+ return seconds * rate * ASSUMED_CHANNELS * BYTES_PER_SAMPLE;
313
+ }
314
+ decodedBytes() {
315
+ let bytes = 0;
316
+ for (const buffer of this._bufferCache.values())
317
+ bytes += buffer.length * buffer.numberOfChannels * BYTES_PER_SAMPLE;
318
+ for (const pending of this._pendingDecodeBytes.values())
319
+ bytes += pending;
320
+ return bytes;
321
+ }
322
+ /** Whether its length was read, for a source that has not failed for good and is not too long to decode. */
323
+ async mayDecode(src, el) {
324
+ if (this._failedSrcs.has(src))
325
+ return null;
326
+ try {
327
+ return await assertDecodeFits(src, el.duration);
328
+ }
329
+ catch (err) {
330
+ if (!(err instanceof AudioTooLong))
331
+ throw err;
332
+ this._failedSrcs.add(src);
333
+ return null;
334
+ }
335
+ }
336
+ // Fetch the bytes. A network error or non-OK status (e.g. a 404 for an
337
+ // asset that simply has not been uploaded yet) is TRANSIENT — return null
338
+ // WITHOUT blacklisting, so the next play/seek generation retries once the
339
+ // asset becomes available.
340
+ async fetchBytes(src, el) {
341
+ try {
342
+ // `no-store`: a retry must actually re-request the asset — not replay a
343
+ // cached 404/stale response from the failed attempt that we chose not to
344
+ // blacklist.
345
+ const response = await fetch(src, { cache: "no-store", ...this._fetchInit });
346
+ if (!response.ok) {
347
+ swallow("webAudioTransport.fetch", new Error(`${response.status} ${src}`));
348
+ reportMediaLoadFailure(el, "fetch", response.status);
349
+ return null;
350
+ }
351
+ return await response.arrayBuffer();
352
+ }
353
+ catch (err) {
354
+ swallow("webAudioTransport.fetch", err);
355
+ reportMediaLoadFailure(el, "fetch", null);
356
+ return null;
357
+ }
358
+ }
359
+ async fetchAndDecode(src, el) {
360
+ if (this._bufferCache.has(src))
361
+ return this._bufferCache.get(src);
362
+ if (!this._ctx)
363
+ return null;
364
+ const length = await this.mayDecode(src, el);
365
+ if (!length)
366
+ return null;
367
+ const arrayBuffer = await this.fetchBytes(src, el);
368
+ if (!arrayBuffer)
369
+ return null;
370
+ // A source whose length can't be read and whose bytes could pass the budget plays through its element.
371
+ if (length === "unread" && !unreadFits(arrayBuffer.byteLength)) {
372
+ this._failedSrcs.add(src);
373
+ return null;
374
+ }
375
+ return this.decode(src, el, arrayBuffer);
376
+ }
377
+ // A decode failure means the bytes themselves are unusable (corrupt or an
378
+ // unsupported codec) — that IS permanent, so blacklist to avoid re-decoding
379
+ // the same bad payload on every generation.
380
+ async decode(src, el, arrayBuffer) {
381
+ if (!this._ctx)
382
+ return null;
383
+ try {
384
+ const audioBuffer = await this._ctx.decodeAudioData(arrayBuffer);
385
+ // A file whose container timescale disagrees with its stream decodes short; its element plays it whole.
386
+ if (Number.isFinite(el.duration) &&
387
+ el.duration - audioBuffer.duration > SHORT_DECODE_SECONDS) {
388
+ this._failedSrcs.add(src);
389
+ return null;
390
+ }
391
+ this._bufferCache.set(src, audioBuffer);
392
+ return audioBuffer;
393
+ }
394
+ catch (err) {
395
+ this._failedSrcs.add(src);
396
+ swallow("webAudioTransport.decode", err);
397
+ reportMediaLoadFailure(el, "decode", null, arrayBuffer.byteLength);
398
+ return null;
399
+ }
400
+ }
401
+ startGeneration() {
402
+ this._playGeneration += 1;
403
+ return this._playGeneration;
404
+ }
405
+ currentGeneration() {
406
+ return this._playGeneration;
407
+ }
408
+ /**
409
+ * The element's cached MediaElementAudioSourceNode, building it on first use
410
+ * — or `null` when this element must not be captured at all.
411
+ *
412
+ * That second outcome is the whole point. `createMediaElementSource` cannot
413
+ * report that it produced a silent node: over a CORS-cross-origin resource
414
+ * the Web Audio spec asks the node for SILENCE rather than an exception, so
415
+ * the caller's `try/catch` never fires and the composition plays through
416
+ * with no audio and no error (#3458). The call also permanently reroutes the
417
+ * element away from its native output, so the question has to be settled
418
+ * before it, and there is no undo afterwards.
419
+ *
420
+ * `init.ts` routes on the same verdict before ever calling in, and
421
+ * `AudioRow.tsx`'s standalone preview player classifies over its own
422
+ * throwaway `AudioContext` before its own `createMediaElementSource` call —
423
+ * this method is A enforcement point, not THE enforcement point; every
424
+ * caller that can reach `createMediaElementSource` is expected to classify
425
+ * first. What this method DOES own is the cache below: `_mediaElementSources`
426
+ * is keyed by element identity, not by asset, so a cache hit alone says
427
+ * nothing about the element's CURRENT resource. Reclassifying on every call
428
+ * — cache hit included — means a `src` mutation an outer caller missed (a
429
+ * pooled element swapped from a same-origin clip to a cross-origin one
430
+ * without going through a fresh generation) can't leave a stale
431
+ * `web-audio` verdict silently attached to the new resource.
432
+ */
433
+ acquireMediaElementSource(el) {
434
+ const cached = this._mediaElementSources.get(el);
435
+ if (cached) {
436
+ // The node itself doesn't change identity on a src swap, but its
437
+ // eligibility can: the Web Audio spec's tainted-origin check runs
438
+ // against the element's CURRENT underlying resource, not the one that
439
+ // was current when the node was built. A same-origin-to-cross-origin
440
+ // mutation on this element would otherwise keep returning the old
441
+ // (now-silent) node forever — `destroy()` was the only thing that ever
442
+ // cleared this cache, so a long-lived element that changed sources
443
+ // stayed silenced for the rest of the session (the R2 finding this
444
+ // block exists to close). The node is still a one-way door — it can't
445
+ // be un-created, and the element's native output is gone either way —
446
+ // so disconnecting it just stops it feeding a graph that no longer
447
+ // matches the asset; the caller falls back to the decode-only path.
448
+ const route = classifyWebAudioMediaRoute(el);
449
+ if (route.kind !== "web-audio") {
450
+ try {
451
+ cached.disconnect();
452
+ }
453
+ catch {
454
+ // Already torn down.
455
+ }
456
+ this._mediaElementSources.delete(el);
457
+ reportWebAudioMediaRoute(el, route);
458
+ return null;
459
+ }
460
+ return cached;
461
+ }
462
+ if (!this._ctx)
463
+ return null;
464
+ const route = classifyWebAudioMediaRoute(el);
465
+ if (route.kind !== "web-audio") {
466
+ reportWebAudioMediaRoute(el, route);
467
+ return null;
468
+ }
469
+ const sourceNode = this._ctx.createMediaElementSource(el);
470
+ this._mediaElementSources.set(el, sourceNode);
471
+ if (!el.paused)
472
+ this._playingCaptured.add(el);
473
+ el.addEventListener("play", () => {
474
+ this._playingCaptured.add(el);
475
+ void this.wake();
476
+ });
477
+ const stopped = () => {
478
+ this._playingCaptured.delete(el);
479
+ this.rest();
480
+ };
481
+ el.addEventListener("pause", stopped);
482
+ el.addEventListener("emptied", stopped);
483
+ return sourceNode;
484
+ }
485
+ /**
486
+ * Route the browser's pitch-preserving HTMLMediaElement transport through the
487
+ * same FX, automation, element-gain, and master graph used by final audio.
488
+ * The media element remains the source-time/rate owner; Web Audio is strictly
489
+ * downstream and therefore never resamples it for Studio global speed.
490
+ */
491
+ async scheduleMediaElementPlayback(el, compositionStart, mediaStart, compositionTime, volume, generation, rate = 1, clipDuration = Number.POSITIVE_INFINITY) {
492
+ if (!this._ctx || !this._masterGain)
493
+ return null;
494
+ if (generation !== this._playGeneration)
495
+ return null;
496
+ try {
497
+ await this.wake();
498
+ if (generation !== this._playGeneration)
499
+ return null;
500
+ const sourceNode = this.acquireMediaElementSource(el);
501
+ if (!sourceNode)
502
+ return null;
503
+ sourceNode.disconnect();
504
+ const safeRate = normalizeRate(rate);
505
+ const gainNode = this._ctx.createGain();
506
+ gainNode.gain.value = volume;
507
+ const scheduledAt = this._ctx.currentTime;
508
+ const elapsed = compositionTime - compositionStart;
509
+ const timing = { scheduledAt, elapsed, rate: safeRate };
510
+ // The group bus, not master, for a member — same as the decoded-buffer
511
+ // path. This transport is the PRIMARY one for audio (the decode path is
512
+ // its fallback), so routing it at master would have left every grouped
513
+ // track bypassing the bus whose whole premise is that a group is one
514
+ // signal.
515
+ gainNode.connect(this.resolveDestination(el, scheduledAt, compositionTime, safeRate) ?? this._masterGain);
516
+ const dipNode = this._ctx.createGain();
517
+ sourceNode.connect(dipNode);
518
+ const { fx, laneNode, clipGainNode, fades } = attachClipStages(this._ctx, el, dipNode, gainNode, timing, { from: Math.max(elapsed, 0), clipDuration });
519
+ this._rate = safeRate;
520
+ this._rateAnchorCtx = scheduledAt;
521
+ this._rateAnchorComp = compositionTime;
522
+ const scheduled = {
523
+ fx,
524
+ fades,
525
+ dipNode,
526
+ el,
527
+ sourceNode,
528
+ sourceKind: "media-element",
529
+ gainNode,
530
+ laneNode,
531
+ clipGainNode,
532
+ compositionStart,
533
+ mediaStart,
534
+ scheduledAt,
535
+ priorMuted: el.muted,
536
+ priorVolume: el.volume,
537
+ mediaPlaybackRate: readElementPlaybackRate(el),
538
+ bounded: false,
539
+ unfollow: this.followElement(el, compositionStart, mediaStart, fx, fades),
540
+ };
541
+ // Chrome applies HTMLMediaElement.volume before MediaElementAudioSource.
542
+ // Keep that upstream stage at unity so the existing downstream gain is
543
+ // the single owner of author × user volume and automation.
544
+ el.volume = 1;
545
+ this._activeSources.push(scheduled);
546
+ this._paused = false;
547
+ return scheduled;
548
+ }
549
+ catch (err) {
550
+ swallow("webAudioTransport.mediaElementSource", err);
551
+ return null;
552
+ }
553
+ }
554
+ /**
555
+ * A routed element keeps its own time: it starts late, is seeked and is steered by rate. Its lane and fades were
556
+ * booked against the context clock, so each time it starts or moves they are re-aimed at where it actually is.
557
+ */
558
+ followElement(el, compositionStart, mediaStart, fx, fades) {
559
+ const retime = () => {
560
+ if (el.paused || !this._ctx)
561
+ return;
562
+ const spec = readElementRateSpec(el);
563
+ let source = el.currentTime - mediaStart;
564
+ const loopLength = el.duration - mediaStart;
565
+ // A looping element's position wraps: it is on the pass nearest where the transport expects it.
566
+ if (el.loop && loopLength > 0) {
567
+ const expected = sourceTimeAt(spec, this.getTime() - compositionStart);
568
+ source += Math.round((expected - source) / loopLength) * loopLength;
569
+ }
570
+ const elapsed = timeAtSourceTime(spec, source);
571
+ const rate = el.playbackRate / rateAt(spec, elapsed);
572
+ // Stopped at rate 0, or with no position yet: no audio moves, so there is nothing to aim at.
573
+ if (!(rate > 0) || !Number.isFinite(elapsed))
574
+ return;
575
+ const timing = { scheduledAt: this._ctx.currentTime, elapsed, rate };
576
+ fx?.retime(timing);
577
+ fades?.rebook(timing);
578
+ };
579
+ for (const type of FOLLOWED_EVENTS)
580
+ el.addEventListener(type, retime);
581
+ return () => {
582
+ for (const type of FOLLOWED_EVENTS)
583
+ el.removeEventListener(type, retime);
584
+ };
585
+ }
586
+ /**
587
+ * Seek a sounding routed element under a short gain dip: down, seek, and back up once it has landed, so the jump
588
+ * is neither a click nor a tempo change. False when the element is not routed and has no dip to hide it under.
589
+ */
590
+ seekUnderDip(el, target) {
591
+ const source = this._activeSources.find((s) => s.el === el && s.sourceKind === "media-element");
592
+ const ctx = this._ctx;
593
+ if (!ctx || !source?.dipNode)
594
+ return false;
595
+ if (source.dipping)
596
+ return true;
597
+ source.dipping = true;
598
+ const gain = source.dipNode.gain;
599
+ const ramp = (to) => {
600
+ const now = ctx.currentTime;
601
+ gain.cancelScheduledValues(now);
602
+ gain.setValueAtTime(gain.value, now);
603
+ gain.linearRampToValueAtTime(to, now + DIP_SECONDS);
604
+ };
605
+ const rise = () => {
606
+ for (const type of DIP_END_EVENTS)
607
+ el.removeEventListener(type, rise);
608
+ source.dipping = false;
609
+ ramp(1);
610
+ };
611
+ ramp(0);
612
+ wallSetTimeout(() => {
613
+ // A stop or a new pass in the meantime owns the element now.
614
+ if (!this._activeSources.includes(source))
615
+ return;
616
+ for (const type of DIP_END_EVENTS)
617
+ el.addEventListener(type, rise);
618
+ try {
619
+ // Where the element would be by now had it been on time.
620
+ el.currentTime = mediaElementTime(target + DIP_SECONDS * el.playbackRate);
621
+ }
622
+ catch (err) {
623
+ swallow("webAudioTransport.seekUnderDip", err);
624
+ rise();
625
+ }
626
+ }, DIP_SECONDS * 1000);
627
+ return true;
628
+ }
629
+ /**
630
+ * The gain a grouped member's signal should land on, building it on first
631
+ * use. A group's clock is COMPOSITION time (design doc §1.3) — it has no
632
+ * `data-start`, and a missing start parses as 0, which is exactly
633
+ * composition time — so its chain and volume lane are scheduled once here
634
+ * against that zero-offset timing, not the member's own clip-local timing.
635
+ * A group id with no matching `<hf-audio-group>` element still gets a bus
636
+ * (flat, no chain) so a hand-authored `data-audio-group` degrades to a
637
+ * plain sum rather than losing the member's audio.
638
+ */
639
+ groupInput(groupId, doc, timing) {
640
+ const existing = this._groups.get(groupId);
641
+ if (existing) {
642
+ // The bus outlives `stopAll()` on purpose, so a replay or a seek reuses
643
+ // this graph — but its envelopes were committed to the FIRST pass's
644
+ // absolute context times. Left alone they hold their last value forever,
645
+ // which for a fade-out is silence for the rest of the session. Re-anchor
646
+ // once per play generation, not once per member scheduled.
647
+ if (existing.generation !== this._playGeneration) {
648
+ // Stamped only on success, and isolated: this runs inside
649
+ // `schedulePlayback`, whose catch turns any throw into `return null` —
650
+ // i.e. a bus problem would silently drop the MEMBER from the pass. And
651
+ // stamping first would consume the generation, so no later member of
652
+ // the same group would retry and the bus would keep the previous pass's
653
+ // envelopes: finding 11 unfixed on exactly the pass that failed.
654
+ try {
655
+ existing.reanchor(timing);
656
+ existing.generation = this._playGeneration;
657
+ }
658
+ catch (err) {
659
+ swallow("webAudioTransport.groupReanchor", err);
660
+ }
661
+ }
662
+ return existing.input;
663
+ }
664
+ if (!this._ctx || !this._masterGain)
665
+ return null;
666
+ const input = this._ctx.createGain();
667
+ // Stable point the FX chain (or, when there's none, the dry passthrough —
668
+ // see `attachElementFxChain`'s `detach()`) always lands on before master,
669
+ // regardless of whether a chain is attached/detached/rebuilt later. The
670
+ // mute gain splices in BEFORE `output`, between the FX chain and here.
671
+ const output = this._ctx.createGain();
672
+ output.connect(this._masterGain);
673
+ // Tag-checked, and re-resolved on every reanchor below rather than frozen:
674
+ // a bus whose element does not exist yet (studio group creation, or a
675
+ // sub-composition that loads later) kept the `getAttribute: () => null`
676
+ // stub for the whole session, so its fader, chain and mute never reached
677
+ // preview while the export honoured all three.
678
+ const resolveEl = () => resolveGroupElement(doc, groupId);
679
+ const groupEl = resolveEl();
680
+ const muteGain = this._ctx.createGain();
681
+ muteGain.gain.value = groupEl?.hasAttribute("data-hidden") ? 0 : 1;
682
+ muteGain.connect(output);
683
+ // The group's fader, POST-FX: `data-volume` is the static position and the
684
+ // volume lane, scaled by it, rides it, which is where a DAW puts it and the
685
+ // order the render bakes it in. Scheduling it
686
+ // on `input` instead put the fader ahead of the effects, so any nonlinear
687
+ // group effect — a compressor, the Giant preset — previewed differently
688
+ // than it rendered.
689
+ const fader = this._ctx.createGain();
690
+ fader.gain.value = clampGroupVolume(readAudioGroupVolume(groupEl));
691
+ fader.connect(muteGain);
692
+ const faderLane = {
693
+ param: fader.gain,
694
+ gain: () => readAudioGroupVolume(resolveEl()),
695
+ };
696
+ const fx = attachElementFxChain(this._ctx, groupEl ?? { getAttribute: () => null }, input, fader, timing, undefined, groupEl ? faderLane : undefined);
697
+ this._groups.set(groupId, {
698
+ input,
699
+ output,
700
+ isPresent: () => resolveEl() !== null,
701
+ fader,
702
+ muteGain,
703
+ fx,
704
+ generation: this._playGeneration,
705
+ reanchor: (at) => {
706
+ // Cleared BEFORE the value write, and unconditionally: a scheduled envelope
707
+ // outranks a `.value` write, so a deleted lane's ramps would keep the param.
708
+ clearParamLane([{ param: fader.gain }]);
709
+ // Re-resolved, not the element captured at build time — see `resolveEl`.
710
+ const live = resolveEl();
711
+ fader.gain.value = clampGroupVolume(readAudioGroupVolume(live));
712
+ muteGain.gain.value = live?.hasAttribute("data-hidden") ? 0 : 1;
713
+ fx?.reanchor(at);
714
+ // The handle books the fader from the element the bus was built with.
715
+ if (live && live !== groupEl)
716
+ scheduleVolume(faderLane, readElementAutomation(live), at);
717
+ },
718
+ dispose: () => {
719
+ try {
720
+ fx?.dispose();
721
+ input.disconnect();
722
+ fader.disconnect();
723
+ muteGain.disconnect();
724
+ output.disconnect();
725
+ }
726
+ catch {
727
+ // Already torn down.
728
+ }
729
+ },
730
+ });
731
+ this.attachGroupTap(groupId, output);
732
+ return input;
733
+ }
734
+ startMetering() {
735
+ this._metering = true;
736
+ this.attachMasterTap();
737
+ for (const [id, group] of this._groups)
738
+ this.attachGroupTap(id, group.output);
739
+ }
740
+ stopMetering() {
741
+ this._metering = false;
742
+ this._masterTap?.dispose();
743
+ this._masterTap = null;
744
+ for (const tap of this._groupTaps.values())
745
+ tap.dispose();
746
+ this._groupTaps.clear();
747
+ }
748
+ readLevels() {
749
+ const groups = {};
750
+ for (const [id, tap] of this._groupTaps) {
751
+ if (this._groups.get(id)?.isPresent())
752
+ groups[id] = tap.read();
753
+ }
754
+ return { master: this._masterTap?.read() ?? { l: 0, r: 0 }, groups };
755
+ }
756
+ attachMasterTap() {
757
+ if (this._ctx && this._masterGain && !this._masterTap) {
758
+ this._masterTap = createLevelTap(this._ctx, this._busOut ?? this._masterGain);
759
+ }
760
+ }
761
+ attachGroupTap(id, output) {
762
+ if (this._metering && this._ctx && !this._groupTaps.has(id)) {
763
+ this._groupTaps.set(id, createLevelTap(this._ctx, output));
764
+ }
765
+ }
766
+ /**
767
+ * Group mute, preview side — a separate gain from `input`'s volume fader
768
+ * so a mute toggle never fights `scheduleVolume`'s ramps on the
769
+ * same param (the same hazard the design doc flags for §2.1). A no-op
770
+ * until the group has an active member: at that point `groupInput` reads
771
+ * the element's own `data-hidden` for its initial value, so there is
772
+ * nothing to catch up on here.
773
+ */
774
+ setGroupMuted(groupId, muted) {
775
+ const group = this._groups.get(groupId);
776
+ if (!group)
777
+ return;
778
+ try {
779
+ group.muteGain.gain.value = muted ? 0 : 1;
780
+ }
781
+ catch (err) {
782
+ swallow("webAudioTransport.setGroupMuted", err);
783
+ }
784
+ }
785
+ /**
786
+ * The master bus chain, between the sum of every clip and group and the monitor.
787
+ * A seek re-anchors it once per play generation; no root yet is retried next schedule.
788
+ */
789
+ ensureMasterBus(doc, timing) {
790
+ if (!this._ctx || !this._masterGain || !this._busOut)
791
+ return;
792
+ if (this._master) {
793
+ if (this._master.generation === this._playGeneration)
794
+ return;
795
+ try {
796
+ this._master.fx?.reanchor(timing);
797
+ this._master.generation = this._playGeneration;
798
+ }
799
+ catch (err) {
800
+ swallow("webAudioTransport.masterReanchor", err);
801
+ }
802
+ return;
803
+ }
804
+ const root = resolveMasterBusElement(doc);
805
+ if (!root)
806
+ return;
807
+ this._masterGain.disconnect(this._busOut);
808
+ const fx = attachElementFxChain(this._ctx, root, this._masterGain, this._busOut, timing, MASTER_FX_ATTRS);
809
+ this._master = { fx, generation: this._playGeneration };
810
+ }
811
+ /** Master, unless `el` belongs to a group — then that group's bus (built on
812
+ * first use, per `groupInput`). */
813
+ resolveDestination(el, scheduledAt, compositionTime, safeRate) {
814
+ if (!this._masterGain)
815
+ return null;
816
+ const groupTiming = { scheduledAt, elapsed: compositionTime, rate: safeRate };
817
+ const doc = this._busDocument === undefined ? el.ownerDocument : this._busDocument;
818
+ if (!doc)
819
+ return this._masterGain;
820
+ this.ensureMasterBus(doc, groupTiming);
821
+ const groupId = audioGroupOf(el);
822
+ if (!groupId)
823
+ return this._masterGain;
824
+ return this.groupInput(groupId, doc, groupTiming) ?? this._masterGain;
825
+ }
826
+ /**
827
+ * The graph goes with it. Splicing alone left the FX handle alive and then
828
+ * UNREACHABLE — `stopAll()` disposes by walking `_activeSources`, which the
829
+ * splice just emptied of this entry. Every clip that finished naturally
830
+ * leaked its MutationObserver for the session, and each one still answered
831
+ * later `data-fx-chain` edits by rebuilding a whole graph (impulse response,
832
+ * chorus/phaser oscillators started and never stopped) around a dead
833
+ * source. Not disposed when the index is already -1: `stopAll()` has
834
+ * already done it, and `stop()` is what fired this event.
835
+ */
836
+ handleSourceEnded(sourceNode, scheduled, el, priorMuted) {
837
+ const idx = this._activeSources.indexOf(scheduled);
838
+ if (idx === -1)
839
+ return;
840
+ this._activeSources.splice(idx, 1);
841
+ el.muted = priorMuted;
842
+ try {
843
+ sourceNode.disconnect();
844
+ scheduled.fx?.dispose();
845
+ scheduled.fades?.node.disconnect();
846
+ scheduled.clipGainNode.disconnect();
847
+ scheduled.laneNode.disconnect();
848
+ scheduled.gainNode.disconnect();
849
+ }
850
+ catch {
851
+ // Already torn down.
852
+ }
853
+ if (this._activeSources.length === 0)
854
+ this._paused = true;
855
+ }
856
+ // Pre-existing size (110 lines before this diff, which shrank it to under
857
+ // 95 via two extractions — see `handleSourceEnded`/`resolveDestination`);
858
+ // the remainder is inherently sequential graph-wiring, not a nested
859
+ // decision tree, and further splitting would cost more readability than it
860
+ // buys. Same call the B2 step took on `TimelineLogicalRow`.
861
+ // fallow-ignore-next-line complexity
862
+ async schedulePlayback(el, buffer, compositionStart, mediaStart, readCompositionTime, volume, generation, rate = 1, clipDuration = Number.POSITIVE_INFINITY, windowStart = compositionStart) {
863
+ if (!this._ctx || !this._masterGain)
864
+ return null;
865
+ if (generation !== this._playGeneration)
866
+ return null;
867
+ try {
868
+ await this.wake();
869
+ if (generation !== this._playGeneration)
870
+ return null;
871
+ // Read after the wake: the clock kept running while the context resumed.
872
+ const compositionTime = readCompositionTime();
873
+ const safeRate = normalizeRate(rate);
874
+ const mediaRate = readElementPlaybackRate(el);
875
+ const sourceRate = safeRate * mediaRate;
876
+ const sourceNode = this._ctx.createBufferSource();
877
+ sourceNode.buffer = buffer;
878
+ sourceNode.playbackRate.value = sourceRate;
879
+ const sourceLength = sourceLengthOf(el);
880
+ const loopEnd = Number.isFinite(sourceLength) ? sourceLength : buffer.duration;
881
+ if (el.loop && loopEnd > mediaStart) {
882
+ sourceNode.loop = true;
883
+ sourceNode.loopStart = mediaStart;
884
+ sourceNode.loopEnd = loopEnd;
885
+ }
886
+ const gainNode = this._ctx.createGain();
887
+ gainNode.gain.value = volume;
888
+ const elapsed = compositionTime - compositionStart;
889
+ const scheduledAt = this._ctx.currentTime;
890
+ const timing = { scheduledAt, elapsed, rate: safeRate };
891
+ // Splice the element's FX chain between the decoded source and its gain,
892
+ // so effects see the raw signal and volume automation rides on their
893
+ // output — the same order the offline render uses. Preview and render run
894
+ // the identical graph builders, so what is heard here is what is written.
895
+ gainNode.connect(this.resolveDestination(el, scheduledAt, compositionTime, safeRate) ?? this._masterGain);
896
+ const headCut = windowStart - compositionStart;
897
+ const { fx, laneNode, clipGainNode, fades } = attachClipStages(this._ctx, el, sourceNode, gainNode, timing, { from: Math.max(elapsed, headCut, 0), clipDuration });
898
+ this._rate = safeRate;
899
+ this._rateAnchorCtx = scheduledAt;
900
+ this._rateAnchorComp = compositionTime;
901
+ if (!startBoundedSource(sourceNode, {
902
+ elapsed,
903
+ mediaStart,
904
+ scheduledAt,
905
+ globalRate: safeRate,
906
+ mediaRate,
907
+ clipDuration,
908
+ headCut,
909
+ })) {
910
+ // Playhead already past the clip end — discard the nodes we built.
911
+ sourceNode.disconnect();
912
+ fx?.dispose();
913
+ fades?.node.disconnect();
914
+ clipGainNode.disconnect();
915
+ laneNode.disconnect();
916
+ gainNode.disconnect();
917
+ return null;
918
+ }
919
+ const priorMuted = el.muted;
920
+ el.muted = true;
921
+ logFallbackHandoff(el, priorMuted);
922
+ const scheduled = {
923
+ fx,
924
+ fades,
925
+ el,
926
+ sourceNode,
927
+ sourceKind: "buffer",
928
+ gainNode,
929
+ laneNode,
930
+ clipGainNode,
931
+ compositionStart,
932
+ mediaStart,
933
+ scheduledAt,
934
+ priorMuted,
935
+ priorVolume: el.volume,
936
+ mediaPlaybackRate: mediaRate,
937
+ bounded: Number.isFinite(clipDuration) && clipDuration > 0,
938
+ };
939
+ this._activeSources.push(scheduled);
940
+ this._paused = false;
941
+ sourceNode.addEventListener("ended", () => this.handleSourceEnded(sourceNode, scheduled, el, priorMuted));
942
+ return scheduled;
943
+ }
944
+ catch (err) {
945
+ swallow("webAudioTransport.schedule", err);
946
+ return null;
947
+ }
948
+ }
949
+ /** Drops the routed element's source once a decoded buffer plays in its place; it stays silent until a stop. */
950
+ releaseRouted(el) {
951
+ const routed = this._activeSources.find((s) => s.el === el && s.sourceKind === "media-element");
952
+ if (!routed)
953
+ return;
954
+ this._activeSources.splice(this._activeSources.indexOf(routed), 1);
955
+ this.dispose(routed, false);
956
+ this._handedOver.add(el);
957
+ }
958
+ /** A decoded buffer plays what an element carried: it cannot hold pitch through a speed change. */
959
+ hasHandedOverSources() {
960
+ return this._activeSources.some((s) => isBufferSource(s) && this._handedOver.has(s.el));
961
+ }
962
+ /**
963
+ * Rebases the composition-time reference frame before swapping rate so
964
+ * `getTime()` stays continuous across the change. Sources scheduled to
965
+ * start in the future keep their original wallclock start time — callers
966
+ * that need rate-correct future starts should `stopAll()` and reschedule.
967
+ *
968
+ * Each decoded source's FX automation is re-aimed too. Lanes are committed to
969
+ * absolute context times when the source is scheduled, so bumping only
970
+ * `playbackRate` left every automated parameter running its original plan
971
+ * over audio moving at a different speed. The `stopAll()`+reschedule recovery
972
+ * in the runtime is no help here: it only fires for bounded sources, and a
973
+ * project-level music bed with no `data-duration` is unbounded, so it never
974
+ * recovered at all.
975
+ */
976
+ setRate(rate) {
977
+ const safeRate = normalizeRate(rate);
978
+ if (safeRate === this._rate)
979
+ return false;
980
+ if (this._ctx && !this._paused) {
981
+ this._rateAnchorComp = this.getTime();
982
+ this._rateAnchorCtx = this._ctx.currentTime;
983
+ }
984
+ this._rate = safeRate;
985
+ // A routed element is not touched: its rate change re-aims its own lane and fades (`followElement`).
986
+ for (const source of this._activeSources) {
987
+ if (!isBufferSource(source))
988
+ continue;
989
+ try {
990
+ source.sourceNode.playbackRate.value = safeRate * source.mediaPlaybackRate;
991
+ source.fx?.setRate(safeRate);
992
+ if (this._ctx && !this._paused)
993
+ source.fades?.rebook({
994
+ scheduledAt: this._ctx.currentTime,
995
+ elapsed: this.getTime() - source.compositionStart,
996
+ rate: safeRate,
997
+ });
998
+ }
999
+ catch (err) {
1000
+ swallow("webAudioTransport.setRate", err);
1001
+ }
1002
+ }
1003
+ this.setBusRate(safeRate);
1004
+ return true;
1005
+ }
1006
+ // Group buses and the master bus are not in `_activeSources` — they outlive it — so
1007
+ // their FX automation needs re-aiming too, or a rate change leaves their envelopes
1008
+ // running the old plan over audio at the new speed.
1009
+ setBusRate(rate) {
1010
+ const buses = [...this._groups.values(), ...(this._master ? [this._master] : [])];
1011
+ for (const bus of buses) {
1012
+ try {
1013
+ bus.fx?.setRate(rate);
1014
+ }
1015
+ catch (err) {
1016
+ swallow("webAudioTransport.setRate.bus", err);
1017
+ }
1018
+ }
1019
+ }
1020
+ // A bounded source's wall-clock duration was baked into start()'s duration
1021
+ // arg at its original rate; a later rate change can't rescale it in place, so
1022
+ // the caller must stopAll()+reschedule to keep trimmed clips ending on time.
1023
+ hasBoundedActiveSources() {
1024
+ return this._activeSources.some((s) => isBufferSource(s) && s.bounded);
1025
+ }
1026
+ stopAll() {
1027
+ for (const source of this._activeSources)
1028
+ this.dispose(source);
1029
+ this._activeSources = [];
1030
+ this.reconnectHandedOver();
1031
+ this._paused = true;
1032
+ this._playGeneration += 1;
1033
+ this.rest();
1034
+ }
1035
+ reconnectHandedOver() {
1036
+ for (const el of this._handedOver) {
1037
+ try {
1038
+ if (this._ctx)
1039
+ this._mediaElementSources.get(el)?.connect(this._ctx.destination);
1040
+ }
1041
+ catch (err) {
1042
+ swallow("webAudioTransport.reconnectHandedOver", err);
1043
+ }
1044
+ }
1045
+ this._handedOver.clear();
1046
+ }
1047
+ /** Stops what plays from media gone from the page, without sending it to the destination as a stop does. */
1048
+ releaseDetached() {
1049
+ this._activeSources = this._activeSources.filter((source) => {
1050
+ if (source.el.isConnected)
1051
+ return true;
1052
+ this.dispose(source, false);
1053
+ return false;
1054
+ });
1055
+ }
1056
+ dispose(source, keepsSounding = true) {
1057
+ source.unfollow?.();
1058
+ try {
1059
+ if (isBufferSource(source))
1060
+ source.sourceNode.stop();
1061
+ source.sourceNode.disconnect();
1062
+ source.fx?.dispose();
1063
+ source.fades?.node.disconnect();
1064
+ source.dipNode?.disconnect();
1065
+ source.clipGainNode.disconnect();
1066
+ source.laneNode.disconnect();
1067
+ source.gainNode.disconnect();
1068
+ }
1069
+ catch {
1070
+ // already stopped
1071
+ }
1072
+ if (isBufferSource(source))
1073
+ source.el.muted = source.priorMuted;
1074
+ else {
1075
+ source.el.volume = source.priorVolume;
1076
+ // Captured, it has no native output; outside a play it sounds through the destination.
1077
+ if (this._ctx && keepsSounding)
1078
+ source.sourceNode.connect(this._ctx.destination);
1079
+ }
1080
+ }
1081
+ setVolume(volume) {
1082
+ this._masterVolume = Math.max(0, Math.min(1, volume));
1083
+ this.applyMasterGain();
1084
+ }
1085
+ /**
1086
+ * The per-element gain carries the clip's AUTHOR gain, which reaches
1087
+ * MAX_AUDIO_GAIN — so it is clamped against that ceiling, not the spec's
1088
+ * [0,1]. `setVolume` above is the opposite case and stays spec-clamped: the
1089
+ * user's master volume is a fader, not a gain.
1090
+ *
1091
+ * Clamping this one at unity capped every static above-unity `data-volume` on
1092
+ * the preview path while the render honoured it — the exact preview/render
1093
+ * divergence this ceiling exists to close. Automation lanes hid it, because
1094
+ * they schedule ramps onto the param directly and never pass through here.
1095
+ */
1096
+ setElementVolume(el, volume, clipGain = 1, unfadedVolume = volume) {
1097
+ for (const source of this._activeSources) {
1098
+ if (source.el !== el)
1099
+ continue;
1100
+ try {
1101
+ if (source.sourceKind === "media-element")
1102
+ source.el.volume = 1;
1103
+ source.gainNode.gain.value = clampAudioGain(source.fades ? unfadedVolume : volume);
1104
+ source.clipGainNode.gain.value = clampAudioGain(clipGain);
1105
+ }
1106
+ catch (err) {
1107
+ swallow("webAudioTransport.setElementVolume", err);
1108
+ }
1109
+ }
1110
+ }
1111
+ setMuted(muted) {
1112
+ this._masterMuted = muted;
1113
+ this.applyMasterGain();
1114
+ }
1115
+ applyMasterGain() {
1116
+ if (this._monitorGain)
1117
+ this._monitorGain.gain.value = this._masterMuted ? 0 : this._masterVolume;
1118
+ }
1119
+ ownsClock() {
1120
+ return !this._paused && this._activeSources.some(isBufferSource);
1121
+ }
1122
+ /** Whether the transport currently plays THIS element (the runtime mutes it to
1123
+ * avoid double audio; an unclaimed track stays audible). */
1124
+ ownsElement(el) {
1125
+ return !this._paused && this._activeSources.some((s) => s.el === el && isBufferSource(s));
1126
+ }
1127
+ /** Whether this element's native signal currently flows through the WebAudio graph. */
1128
+ routesElement(el) {
1129
+ return !this._paused && this._activeSources.some((source) => source.el === el);
1130
+ }
1131
+ destroy() {
1132
+ this.stopAll();
1133
+ this.stopMetering();
1134
+ for (const group of this._groups.values())
1135
+ group.dispose();
1136
+ this._groups.clear();
1137
+ this._master?.fx?.dispose();
1138
+ this._master = null;
1139
+ this._bufferCache.clear();
1140
+ this._failedSrcs.clear();
1141
+ this._mediaElementSources = new WeakMap();
1142
+ this._playingCaptured.clear();
1143
+ this._suspendPending = false;
1144
+ if (this._restTimer !== null)
1145
+ wallClearTimeout(this._restTimer);
1146
+ this._restTimer = null;
1147
+ if (this._ctx) {
1148
+ try {
1149
+ void this._ctx.close();
1150
+ }
1151
+ catch {
1152
+ // ignore
1153
+ }
1154
+ }
1155
+ this._ctx = null;
1156
+ this._masterGain = null;
1157
+ this._busOut = null;
1158
+ this._monitorGain = null;
1159
+ this._masterVolume = 1;
1160
+ this._masterMuted = false;
1161
+ }
1162
+ }