@avoid.quest/audio 0.0.0-stage → 0.1.0

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 (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +70 -2
  3. package/dist/effects/index.d.ts +266 -0
  4. package/dist/effects/index.js +744 -0
  5. package/dist/effects/index.js.map +1 -0
  6. package/dist/errors-BT9HxDLn.js +74 -0
  7. package/dist/errors-BT9HxDLn.js.map +1 -0
  8. package/dist/errors-ChTQFwuZ.d.ts +53 -0
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.js +3 -0
  11. package/dist/midi/index.d.ts +162 -0
  12. package/dist/midi/index.js +338 -0
  13. package/dist/midi/index.js.map +1 -0
  14. package/dist/playback/index.d.ts +349 -0
  15. package/dist/playback/index.js +1372 -0
  16. package/dist/playback/index.js.map +1 -0
  17. package/dist/queue/index.d.ts +144 -0
  18. package/dist/queue/index.js +1062 -0
  19. package/dist/queue/index.js.map +1 -0
  20. package/dist/recognize/index.d.ts +161 -0
  21. package/dist/recognize/index.js +2816 -0
  22. package/dist/recognize/index.js.map +1 -0
  23. package/dist/routing/index.d.ts +140 -0
  24. package/dist/routing/index.js +678 -0
  25. package/dist/routing/index.js.map +1 -0
  26. package/dist/sync/index.d.ts +282 -0
  27. package/dist/sync/index.js +1103 -0
  28. package/dist/sync/index.js.map +1 -0
  29. package/dist/worklet-loader-BvEW0oVO.d.ts +44 -0
  30. package/dist/worklet-loader-S7R8ZAmP.js +175 -0
  31. package/dist/worklet-loader-S7R8ZAmP.js.map +1 -0
  32. package/dist/worklets/couch-live.d.ts +1 -0
  33. package/dist/worklets/couch-live.js +365 -0
  34. package/dist/worklets/couch-live.js.map +1 -0
  35. package/dist/worklets/meter.d.ts +7 -0
  36. package/dist/worklets/meter.js +80 -0
  37. package/dist/worklets/meter.js.map +1 -0
  38. package/package.json +109 -4
@@ -0,0 +1,1372 @@
1
+ import { Context, Duration, Effect, Fiber, Layer, Option, Schedule, Scope } from "effect";
2
+ import { a as AudioPlaybackError, l as AudioUnsupportedError, n as AudioDecodeError, t as AudioCaptureError } from "../errors-BT9HxDLn.js";
3
+ // src/playback/audio-context.ts
4
+ var AudioContextService = class extends Context.Service()("@avoid.quest/audio/AudioContextService") {};
5
+ /**
6
+ * Computes browser-aware `AudioContextOptions`:
7
+ * - Mobile uses a 128-frame latency hint (`128 / 48_000`) to avoid glitches.
8
+ * - Firefox omits forced `sampleRate` because forcing 48 kHz breaks some device drivers.
9
+ */
10
+ function createAudioContextOptions(options = {}) {
11
+ const sampleRate = options.sampleRate ?? 48e3;
12
+ const latencyHint = options.isMobile ? 128 / sampleRate : 0;
13
+ if (options.isFirefox) return { latencyHint };
14
+ return {
15
+ latencyHint,
16
+ sampleRate
17
+ };
18
+ }
19
+ /**
20
+ * Normalizes Safari/iOS `"interrupted"` state to `"suspended"`.
21
+ */
22
+ function normalizeAudioContextState(state) {
23
+ if (state === "running" || state === "closed") return state;
24
+ return "suspended";
25
+ }
26
+ function snapshotAudioContext(context) {
27
+ const extended = context;
28
+ return {
29
+ baseLatency: typeof context.baseLatency === "number" ? context.baseLatency : void 0,
30
+ currentTime: context.currentTime,
31
+ outputLatency: typeof extended.outputLatency === "number" ? extended.outputLatency : void 0,
32
+ sampleRate: context.sampleRate,
33
+ state: normalizeAudioContextState(context.state)
34
+ };
35
+ }
36
+ const pendingResumes = /* @__PURE__ */ new WeakMap();
37
+ function resumeContextDeduplicated(context) {
38
+ const existing = pendingResumes.get(context);
39
+ if (existing) return existing;
40
+ let promise;
41
+ try {
42
+ promise = Promise.resolve(context.resume()).finally(() => {
43
+ pendingResumes.delete(context);
44
+ });
45
+ } catch (error) {
46
+ return Promise.reject(error);
47
+ }
48
+ pendingResumes.set(context, promise);
49
+ return promise;
50
+ }
51
+ /**
52
+ * Deduplicates concurrent `AudioContext.resume()` calls and normalizes iOS `"interrupted"` state.
53
+ */
54
+ function ensureAudioContextRunning(context) {
55
+ return Effect.tryPromise({
56
+ catch: (error) => new AudioPlaybackError({
57
+ cause: String(error),
58
+ code: "CONTEXT_RESUME_FAILED",
59
+ message: `Failed to resume AudioContext: ${String(error)}`,
60
+ recoverable: true
61
+ }),
62
+ try: async () => {
63
+ const normalized = normalizeAudioContextState(context.state);
64
+ if (normalized === "running") return;
65
+ if (normalized === "closed") throw new Error("AudioContext is closed.");
66
+ await resumeContextDeduplicated(context);
67
+ }
68
+ });
69
+ }
70
+ const GESTURE_EVENTS = [
71
+ "touchstart",
72
+ "touchend",
73
+ "click",
74
+ "keydown"
75
+ ];
76
+ function noopCleanup() {}
77
+ /**
78
+ * Attaches persistent passive user-gesture listeners to unlock a suspended
79
+ * `AudioContext` (including iOS Safari, where `touchstart` or early gestures
80
+ * may resolve without transitioning `state` to `"running"`). Listeners remain
81
+ * active across gestures until `context.state === "running"` (or `"closed"`),
82
+ * or until the returned cleanup callback is invoked.
83
+ */
84
+ function attachGestureUnlock(context, target = globalThis.window === void 0 ? void 0 : globalThis.window) {
85
+ if (!target) return noopCleanup;
86
+ const initialState = normalizeAudioContextState(context.state);
87
+ if (initialState === "running" || initialState === "closed") return noopCleanup;
88
+ const supportsStateChange = typeof context.addEventListener === "function" && typeof context.removeEventListener === "function";
89
+ let cleaned = false;
90
+ const isTerminalState = () => {
91
+ const normalized = normalizeAudioContextState(context.state);
92
+ return normalized === "running" || normalized === "closed";
93
+ };
94
+ const cleanup = () => {
95
+ if (cleaned) return;
96
+ cleaned = true;
97
+ for (const eventName of GESTURE_EVENTS) target.removeEventListener(eventName, onGesture);
98
+ if (supportsStateChange) context.removeEventListener("statechange", onStateChange);
99
+ };
100
+ const onStateChange = () => {
101
+ if (isTerminalState()) cleanup();
102
+ };
103
+ const onGesture = () => {
104
+ if (cleaned) return;
105
+ if (isTerminalState()) {
106
+ cleanup();
107
+ return;
108
+ }
109
+ let resumePromise;
110
+ try {
111
+ resumePromise = Promise.resolve(context.resume());
112
+ } catch {
113
+ return;
114
+ }
115
+ resumePromise.then(() => {
116
+ if (!cleaned && isTerminalState()) cleanup();
117
+ return true;
118
+ }).catch(() => false);
119
+ };
120
+ for (const eventName of GESTURE_EVENTS) target.addEventListener(eventName, onGesture, { passive: true });
121
+ if (supportsStateChange) context.addEventListener("statechange", onStateChange);
122
+ return cleanup;
123
+ }
124
+ function resolveDefaultAudioContextCtor() {
125
+ const globalWithWebkit = globalThis;
126
+ return globalWithWebkit.AudioContext ?? globalWithWebkit.webkitAudioContext;
127
+ }
128
+ function closeContextSafely(context) {
129
+ return Effect.tryPromise({
130
+ catch: () => "CLOSE_FAILED",
131
+ try: async () => {
132
+ if (normalizeAudioContextState(context.state) === "closed") return;
133
+ if (typeof context.close === "function") await context.close();
134
+ }
135
+ }).pipe(Effect.catch(() => Effect.void));
136
+ }
137
+ /**
138
+ * Acquires a `Scope`-managed `AudioContextHandle`, optionally attaching
139
+ * user-gesture unlock listeners and releasing listeners + closing owned
140
+ * `AudioContext` instances when the `Scope` closes.
141
+ */
142
+ function acquireAudioContext(options = {}) {
143
+ const shouldCloseOnRelease = options.closeOnRelease ?? options.context === void 0;
144
+ return Effect.acquireRelease(Effect.suspend(() => {
145
+ let { context } = options;
146
+ if (!context) {
147
+ const ctxOptions = createAudioContextOptions(options);
148
+ if (options.createContext) context = options.createContext(ctxOptions);
149
+ else {
150
+ const Ctor = resolveDefaultAudioContextCtor();
151
+ if (typeof Ctor !== "function") return Effect.fail(new AudioUnsupportedError({
152
+ feature: "AudioContext",
153
+ message: "AudioContext is not supported in this environment."
154
+ }));
155
+ context = new Ctor(ctxOptions);
156
+ }
157
+ }
158
+ const detachUnlock = options.unlockOnGesture ?? true ? attachGestureUnlock(context, options.unlockTarget) : noopCleanup;
159
+ const resolvedContext = context;
160
+ const close = () => Effect.sync(() => {
161
+ detachUnlock();
162
+ }).pipe(Effect.andThen(closeContextSafely(resolvedContext)));
163
+ return Effect.succeed({
164
+ close,
165
+ context: resolvedContext,
166
+ detachUnlock,
167
+ ensureRunning: () => ensureAudioContextRunning(resolvedContext),
168
+ getSnapshot: () => snapshotAudioContext(resolvedContext)
169
+ });
170
+ }), (resource) => Effect.sync(() => {
171
+ resource.detachUnlock();
172
+ }).pipe(Effect.andThen(shouldCloseOnRelease ? closeContextSafely(resource.context) : Effect.void))).pipe(Effect.map(({ close, context, ensureRunning, getSnapshot }) => ({
173
+ close,
174
+ context,
175
+ ensureRunning,
176
+ getSnapshot
177
+ })));
178
+ }
179
+ /**
180
+ * Builds a scoped Effect v4 `Layer` providing `AudioContextService`.
181
+ */
182
+ function makeAudioContextLayer(options = {}) {
183
+ return Layer.effect(AudioContextService, acquireAudioContext(options));
184
+ }
185
+ // src/playback/input-capture.ts
186
+ function stopAllTracks(stream) {
187
+ for (const track of stream.getTracks()) track.stop();
188
+ }
189
+ function defaultNavigatorMediaDevices() {
190
+ return globalThis.navigator === void 0 ? void 0 : globalThis.navigator.mediaDevices;
191
+ }
192
+ function createAbortError(message) {
193
+ return new AudioCaptureError({
194
+ cancelled: true,
195
+ code: "ABORTED",
196
+ message
197
+ });
198
+ }
199
+ function mapCaptureError(error, fallbackCode, prefix) {
200
+ if (error instanceof AudioCaptureError) return error;
201
+ const errName = error instanceof Error ? error.name : "";
202
+ return new AudioCaptureError({
203
+ cancelled: errName === "NotAllowedError" || errName === "AbortError",
204
+ code: errName || fallbackCode,
205
+ message: `${prefix}: ${String(error)}`
206
+ });
207
+ }
208
+ /**
209
+ * Acquires a `MediaStream` from `getUserMedia` / `getDisplayMedia` while racing
210
+ * against both the Effect fiber `AbortSignal` and an optional caller `AbortSignal`.
211
+ * If cancelled while the browser prompt/request is still pending, any
212
+ * `MediaStreamTrack`s returned upon eventual resolution are immediately stopped
213
+ * so microphone/capture handles never leak.
214
+ */
215
+ function acquireStreamWithAbort(requestStream, userSignal, abortMessage, fallbackCode, errorPrefix) {
216
+ return Effect.callback((resume, effectSignal) => {
217
+ const isAborted = () => effectSignal.aborted || userSignal?.aborted === true;
218
+ if (isAborted()) {
219
+ resume(Effect.fail(createAbortError(abortMessage)));
220
+ return;
221
+ }
222
+ let settled = false;
223
+ let streamPromise;
224
+ try {
225
+ streamPromise = requestStream();
226
+ } catch (error) {
227
+ resume(Effect.fail(mapCaptureError(error, fallbackCode, errorPrefix)));
228
+ return;
229
+ }
230
+ const cleanupListeners = () => {
231
+ effectSignal.removeEventListener("abort", onAbort);
232
+ userSignal?.removeEventListener("abort", onAbort);
233
+ };
234
+ const stopLateStream = async () => {
235
+ try {
236
+ stopAllTracks(await streamPromise);
237
+ } catch {}
238
+ };
239
+ const onAbort = () => {
240
+ if (settled) return;
241
+ settled = true;
242
+ cleanupListeners();
243
+ stopLateStream();
244
+ resume(Effect.fail(createAbortError(abortMessage)));
245
+ };
246
+ effectSignal.addEventListener("abort", onAbort, { once: true });
247
+ userSignal?.addEventListener("abort", onAbort, { once: true });
248
+ const awaitResolution = async () => {
249
+ try {
250
+ const stream = await streamPromise;
251
+ if (settled || isAborted()) {
252
+ settled = true;
253
+ cleanupListeners();
254
+ stopAllTracks(stream);
255
+ resume(Effect.fail(createAbortError(abortMessage)));
256
+ return;
257
+ }
258
+ settled = true;
259
+ cleanupListeners();
260
+ resume(Effect.succeed(stream));
261
+ } catch (error) {
262
+ if (settled) return;
263
+ settled = true;
264
+ cleanupListeners();
265
+ resume(Effect.fail(mapCaptureError(error, fallbackCode, errorPrefix)));
266
+ }
267
+ };
268
+ awaitResolution();
269
+ return Effect.sync(() => {
270
+ onAbort();
271
+ });
272
+ });
273
+ }
274
+ /**
275
+ * Requests browser tab audio via `getDisplayMedia` with Chromium self-capture
276
+ * exclusion hints, abort/cancellation cleanup, and a feedback-loop guard
277
+ * verifying `displaySurface === "browser"` and at least one live audio track.
278
+ */
279
+ function requestDisplayAudio(options = {}) {
280
+ return Effect.gen(function* () {
281
+ const devices = options.mediaDevices ?? defaultNavigatorMediaDevices();
282
+ if (!devices || typeof devices.getDisplayMedia !== "function") return yield* Effect.fail(new AudioCaptureError({
283
+ code: "UNSUPPORTED",
284
+ message: "getDisplayMedia is not available in this environment."
285
+ }));
286
+ const constraints = {
287
+ audio: {
288
+ autoGainControl: false,
289
+ echoCancellation: false,
290
+ noiseSuppression: false,
291
+ restrictOwnAudio: true,
292
+ suppressLocalAudioPlayback: true
293
+ },
294
+ monitorTypeSurfaces: "exclude",
295
+ selfBrowserSurface: "exclude",
296
+ surfaceSwitching: "exclude",
297
+ systemAudio: "exclude",
298
+ video: {
299
+ displaySurface: "browser",
300
+ frameRate: 1
301
+ },
302
+ windowAudio: "exclude"
303
+ };
304
+ const stream = yield* acquireStreamWithAbort(() => devices.getDisplayMedia(constraints), options.signal, "Display audio capture was cancelled.", "DISPLAY_AUDIO_FAILED", "Display audio capture failed");
305
+ const requireTab = options.requireBrowserTab ?? true;
306
+ if (stream.getAudioTracks().filter((track) => track.readyState === "live").length === 0) {
307
+ stopAllTracks(stream);
308
+ return yield* Effect.fail(new AudioCaptureError({
309
+ code: "NO_AUDIO_TRACK",
310
+ message: "Selected display surface did not provide an audio track."
311
+ }));
312
+ }
313
+ if (requireTab) {
314
+ const [videoTrack] = stream.getVideoTracks();
315
+ const settings = videoTrack?.getSettings();
316
+ if (settings?.displaySurface !== void 0 && settings.displaySurface !== "browser") {
317
+ stopAllTracks(stream);
318
+ return yield* Effect.fail(new AudioCaptureError({
319
+ code: "INVALID_SURFACE",
320
+ message: `Expected browser tab surface, got "${settings.displaySurface}".`
321
+ }));
322
+ }
323
+ }
324
+ return stream;
325
+ });
326
+ }
327
+ function resolveInputStreamEffect(options) {
328
+ const abortMessage = "Input capture was cancelled.";
329
+ if (options.signal?.aborted) return Effect.fail(createAbortError(abortMessage));
330
+ if (options.stream) return Effect.succeed(options.stream);
331
+ const devices = options.mediaDevices ?? defaultNavigatorMediaDevices();
332
+ if (!devices || typeof devices.getUserMedia !== "function") return Effect.fail(new AudioCaptureError({
333
+ code: "UNSUPPORTED",
334
+ message: "getUserMedia is not available in this environment."
335
+ }));
336
+ const audioConstraints = {
337
+ autoGainControl: false,
338
+ channelCount: { ideal: options.channelCount ?? 2 },
339
+ echoCancellation: false,
340
+ noiseSuppression: false,
341
+ ...options.deviceId ? { deviceId: { exact: options.deviceId } } : {}
342
+ };
343
+ return acquireStreamWithAbort(() => devices.getUserMedia({
344
+ audio: audioConstraints,
345
+ video: false
346
+ }), options.signal, abortMessage, "INPUT_CAPTURE_FAILED", "Input capture failed");
347
+ }
348
+ function wireChannelRouting(context, sourceNode, outputNode, detectedChannels, outputChannelCount, selection) {
349
+ const isDefaultStereo = detectedChannels <= 2 && selection?.left === 0 && selection?.right === 1;
350
+ if (selection === void 0 || isDefaultStereo) {
351
+ sourceNode.connect(outputNode);
352
+ return {};
353
+ }
354
+ const splitCount = Math.max(2, detectedChannels, selection.left + 1, selection.right + 1);
355
+ const splitter = context.createChannelSplitter(splitCount);
356
+ const merger = context.createChannelMerger(outputChannelCount);
357
+ sourceNode.connect(splitter);
358
+ splitter.connect(merger, selection.left, 0);
359
+ if (outputChannelCount === 2) splitter.connect(merger, selection.right, 1);
360
+ merger.connect(outputNode);
361
+ return {
362
+ merger,
363
+ splitter
364
+ };
365
+ }
366
+ function buildCaptureGraph(context, stream, options) {
367
+ const audioTracks = stream.getAudioTracks().filter((track) => track.readyState === "live");
368
+ if (audioTracks.length === 0) throw new AudioCaptureError({
369
+ code: "NO_AUDIO_TRACK",
370
+ message: "Stream does not contain a live audio track."
371
+ });
372
+ const sourceNode = context.createMediaStreamSource(stream);
373
+ const outputNode = context.createGain();
374
+ const detectedChannels = audioTracks[0]?.getSettings().channelCount ?? options.channelCount ?? 2;
375
+ const selection = options.channelSelection;
376
+ const outputChannelCount = detectedChannels === 1 || selection !== void 0 && selection.left === selection.right ? 1 : 2;
377
+ outputNode.channelCount = outputChannelCount;
378
+ outputNode.channelCountMode = "explicit";
379
+ const { splitter, merger } = wireChannelRouting(context, sourceNode, outputNode, detectedChannels, outputChannelCount, selection);
380
+ let stopped = false;
381
+ const onTrackEnded = () => {
382
+ stop();
383
+ options.onEnded?.();
384
+ };
385
+ const stop = () => {
386
+ if (stopped) return;
387
+ stopped = true;
388
+ for (const track of stream.getAudioTracks()) track.removeEventListener("ended", onTrackEnded);
389
+ sourceNode.disconnect();
390
+ splitter?.disconnect();
391
+ merger?.disconnect();
392
+ outputNode.disconnect();
393
+ stopAllTracks(stream);
394
+ };
395
+ for (const track of stream.getAudioTracks()) track.addEventListener("ended", onTrackEnded, { once: true });
396
+ return {
397
+ outputChannelCount,
398
+ outputNode,
399
+ sourceNode,
400
+ stop,
401
+ stream
402
+ };
403
+ }
404
+ /**
405
+ * Acquires a live audio input (`getUserMedia` or a pre-acquired `MediaStream`),
406
+ * wires optional channel selection routing into an output `GainNode`, supports
407
+ * `AbortSignal` and `Scope`/fiber cancellation without leaking pending
408
+ * `MediaStreamTrack`s, and automatically stops tracks + disconnects nodes when
409
+ * the Effect `Scope` closes.
410
+ */
411
+ function acquireInputCapture(context, options = {}) {
412
+ return Effect.gen(function* () {
413
+ const scope = yield* Scope.Scope;
414
+ return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
415
+ const stream = yield* restore(resolveInputStreamEffect(options));
416
+ const capture = yield* Effect.try({
417
+ catch: (setupError) => {
418
+ stopAllTracks(stream);
419
+ return mapCaptureError(setupError, "INPUT_CAPTURE_FAILED", "Input capture failed");
420
+ },
421
+ try: () => {
422
+ if (options.signal?.aborted) throw createAbortError("Input capture was cancelled.");
423
+ return buildCaptureGraph(context, stream, options);
424
+ }
425
+ });
426
+ yield* Scope.addFinalizer(scope, Effect.sync(() => {
427
+ capture.stop();
428
+ }));
429
+ return capture;
430
+ }));
431
+ });
432
+ }
433
+ // src/playback/media-engine.ts
434
+ const MIN_PLAYBACK_RATE = .5;
435
+ const MAX_PLAYBACK_RATE = 2;
436
+ const DEFAULT_MEDIA_READY_TIMEOUT_MS = 2e4;
437
+ const DEFAULT_STALL_WATCHDOG_MS = 6e3;
438
+ const DEFAULT_MAX_RECOVERY_DELAY_MS = 3e4;
439
+ /**
440
+ * Clamps playback speed into the supported `[0.5, 2.0]` range.
441
+ */
442
+ function clampPlaybackRate(rate) {
443
+ if (!Number.isFinite(rate)) return 1;
444
+ return Math.max(MIN_PLAYBACK_RATE, Math.min(2, rate));
445
+ }
446
+ /**
447
+ * Sets pitch preservation on an `HTMLMediaElement`, including Safari < 17 `webkitPreservesPitch`.
448
+ */
449
+ function applyPreservesPitch(element, preserve) {
450
+ const extended = element;
451
+ if ("preservesPitch" in extended) extended.preservesPitch = preserve;
452
+ if ("webkitPreservesPitch" in extended) extended.webkitPreservesPitch = preserve;
453
+ return preserve;
454
+ }
455
+ /**
456
+ * Detects `.m3u8` HLS streams, checking one level deep inside `?url=` proxy params.
457
+ */
458
+ function isHlsUrl(url, depth = 0) {
459
+ try {
460
+ const parsed = new URL(url, "https://placeholder.invalid");
461
+ if (parsed.pathname.toLowerCase().endsWith(".m3u8")) return true;
462
+ if (depth < 1) {
463
+ const nested = parsed.searchParams.get("url");
464
+ if (nested !== null) return isHlsUrl(nested, depth + 1);
465
+ }
466
+ return false;
467
+ } catch {
468
+ return url.toLowerCase().includes(".m3u8");
469
+ }
470
+ }
471
+ /**
472
+ * Returns true for Safari / Apple WebKit browsers (excluding Chrome/Edge/Firefox).
473
+ */
474
+ function isWebKitBrowser(userAgent = globalThis.navigator === void 0 ? void 0 : globalThis.navigator.userAgent) {
475
+ if (!userAgent) return false;
476
+ const hasSafari = /safari/iu.test(userAgent);
477
+ const isChromiumOrFirefox = /chrome|chromium|crios|fxios|edg|opr/iu.test(userAgent);
478
+ return hasSafari && !isChromiumOrFirefox;
479
+ }
480
+ /**
481
+ * Uses native HLS only on Safari/WebKit with `application/vnd.apple.mpegurl` support.
482
+ * Chrome stays on `hls.js` because native Chrome HLS rejects certain MP3/AAC segments.
483
+ */
484
+ function shouldUseNativeHls(element, allowNativeHls = true, userAgent) {
485
+ if (!allowNativeHls) return false;
486
+ if (!isWebKitBrowser(userAgent)) return false;
487
+ const support = element.canPlayType("application/vnd.apple.mpegurl");
488
+ return support === "probably" || support === "maybe";
489
+ }
490
+ /**
491
+ * Exponential backoff delay calculation matching Radio's recovery schedule:
492
+ * `0ms` for attempt `<= 0`, then `1s, 2s, 4s, 8s, 16s, 30s` cap.
493
+ */
494
+ function computeStallBackoffMs(attempt, baseDelayMs = 1e3, maxDelayMs = DEFAULT_MAX_RECOVERY_DELAY_MS) {
495
+ if (attempt <= 0) return 0;
496
+ return Math.min(baseDelayMs * 2 ** Math.min(attempt - 1, 10), maxDelayMs);
497
+ }
498
+ /**
499
+ * Builds an Effect v4 `Schedule` for bounded exponential stall/disconnect recovery.
500
+ */
501
+ function createStallRecoverySchedule(config = {}) {
502
+ const baseDelayMs = config.baseDelayMs ?? 1e3;
503
+ const maxDelayMs = config.maxDelayMs ?? 3e4;
504
+ const maxAttempts = config.maxAttempts ?? 5;
505
+ return Schedule.recurs(maxAttempts).pipe(Schedule.modifyDelay(({ attempt }) => Effect.succeed(Duration.millis(computeStallBackoffMs(attempt, baseDelayMs, maxDelayMs)))));
506
+ }
507
+ function hasElementEventTarget(element) {
508
+ return typeof element.addEventListener === "function" && typeof element.removeEventListener === "function";
509
+ }
510
+ /**
511
+ * Creates a `Scope`-managed media/HLS playback engine supporting both
512
+ * `HTMLAudioElement` and `HTMLVideoElement` with lazy dynamic `import("hls.js")`,
513
+ * Safari native HLS detection, speed `0.5–2.0` + `preservesPitch`, URL renewal
514
+ * reload, media-ready timeout & stall watchdog, and Effect `Schedule` stall recovery.
515
+ */
516
+ function createMediaEngine(options) {
517
+ return Effect.gen(function* () {
518
+ const scope = yield* Scope.Scope;
519
+ const { element } = options;
520
+ const mediaReadyTimeoutMs = options.mediaReadyTimeoutMs ?? 2e4;
521
+ const stallWatchdogMs = options.stallWatchdogMs ?? 6e3;
522
+ const recoverySchedule = createStallRecoverySchedule(options.stallRecovery);
523
+ const loadHlsModule = options.loadHls ?? (() => import("hls.js"));
524
+ let hlsInstance;
525
+ let currentUrl;
526
+ let mode = "idle";
527
+ let playbackRate = clampPlaybackRate(element.playbackRate || 1);
528
+ let preservesPitch = true;
529
+ let mediaRecoveryAttempted = false;
530
+ let disposed = false;
531
+ let loadGeneration = 0;
532
+ let pendingSeekCleanup;
533
+ let readyWatchdogTimer;
534
+ let readyWatchdogCleanup;
535
+ let stallWatchdogTimer;
536
+ let lastProgressTime = element.currentTime;
537
+ let hlsRecoveryStep;
538
+ let hlsRecoveryFiber;
539
+ let stallRecoveryStep;
540
+ let stallRecoveryFiber;
541
+ let cancelPendingReadyWait;
542
+ const clearPendingReadyWait = () => {
543
+ cancelPendingReadyWait?.();
544
+ cancelPendingReadyWait = void 0;
545
+ };
546
+ const clearPendingSeek = () => {
547
+ pendingSeekCleanup?.();
548
+ pendingSeekCleanup = void 0;
549
+ };
550
+ const clearReadyWatchdog = () => {
551
+ if (readyWatchdogTimer !== void 0) {
552
+ clearTimeout(readyWatchdogTimer);
553
+ readyWatchdogTimer = void 0;
554
+ }
555
+ readyWatchdogCleanup?.();
556
+ readyWatchdogCleanup = void 0;
557
+ };
558
+ const clearStallWatchdog = () => {
559
+ if (stallWatchdogTimer !== void 0) {
560
+ clearTimeout(stallWatchdogTimer);
561
+ stallWatchdogTimer = void 0;
562
+ }
563
+ };
564
+ const stopHlsRecovery = () => {
565
+ if (hlsRecoveryFiber) {
566
+ hlsRecoveryFiber.interruptUnsafe();
567
+ hlsRecoveryFiber = void 0;
568
+ }
569
+ hlsRecoveryStep = void 0;
570
+ };
571
+ const stopStallRecovery = () => {
572
+ clearStallWatchdog();
573
+ if (stallRecoveryFiber) {
574
+ stallRecoveryFiber.interruptUnsafe();
575
+ stallRecoveryFiber = void 0;
576
+ }
577
+ stallRecoveryStep = void 0;
578
+ };
579
+ const destroyHls = () => {
580
+ stopHlsRecovery();
581
+ if (hlsInstance) {
582
+ hlsInstance.destroy();
583
+ hlsInstance = void 0;
584
+ }
585
+ };
586
+ const applySeekPosition = (seconds) => {
587
+ if (!Number.isFinite(seconds) || seconds < 0) return;
588
+ try {
589
+ element.currentTime = seconds;
590
+ } catch {}
591
+ };
592
+ /**
593
+ * Applies initial `startPositionSeconds` AFTER `element.load()` / metadata settles
594
+ * so `element.load()` never resets `currentTime` back to `0`.
595
+ */
596
+ const scheduleInitialSeek = (seconds) => {
597
+ clearPendingSeek();
598
+ if (seconds === void 0 || !Number.isFinite(seconds) || seconds <= 0) return;
599
+ if (typeof element.readyState === "number" && element.readyState >= 1 || !hasElementEventTarget(element)) {
600
+ applySeekPosition(seconds);
601
+ return;
602
+ }
603
+ const onReady = () => {
604
+ clearPendingSeek();
605
+ if (!disposed) applySeekPosition(seconds);
606
+ };
607
+ const onError = () => {
608
+ clearPendingSeek();
609
+ };
610
+ element.addEventListener("loadedmetadata", onReady, { once: true });
611
+ element.addEventListener("error", onError, { once: true });
612
+ pendingSeekCleanup = () => {
613
+ element.removeEventListener("loadedmetadata", onReady);
614
+ element.removeEventListener("error", onError);
615
+ };
616
+ };
617
+ const armReadyWatchdog = (timeoutMs, generation) => {
618
+ clearReadyWatchdog();
619
+ if (disposed || timeoutMs <= 0 || !hasElementEventTarget(element) || typeof element.readyState === "number" && element.readyState >= 1) return;
620
+ const onMediaReady = () => {
621
+ clearReadyWatchdog();
622
+ };
623
+ const onMediaError = () => {
624
+ clearReadyWatchdog();
625
+ if (disposed || generation !== loadGeneration) return;
626
+ options.onStreamError?.(element.currentTime, new AudioPlaybackError({
627
+ code: "MEDIA_LOAD_ERROR",
628
+ message: "Media element emitted an error before becoming ready.",
629
+ recoverable: true
630
+ }));
631
+ };
632
+ element.addEventListener("loadedmetadata", onMediaReady, { once: true });
633
+ element.addEventListener("canplay", onMediaReady, { once: true });
634
+ element.addEventListener("playing", onMediaReady, { once: true });
635
+ element.addEventListener("error", onMediaError, { once: true });
636
+ readyWatchdogCleanup = () => {
637
+ element.removeEventListener("loadedmetadata", onMediaReady);
638
+ element.removeEventListener("canplay", onMediaReady);
639
+ element.removeEventListener("playing", onMediaReady);
640
+ element.removeEventListener("error", onMediaError);
641
+ };
642
+ readyWatchdogTimer = setTimeout(() => {
643
+ clearReadyWatchdog();
644
+ if (disposed || generation !== loadGeneration) return;
645
+ if (typeof element.readyState === "number" && element.readyState >= 1) return;
646
+ options.onStreamError?.(element.currentTime, new AudioPlaybackError({
647
+ code: "MEDIA_READY_TIMEOUT",
648
+ message: `Media did not become ready within ${timeoutMs} ms.`,
649
+ recoverable: true
650
+ }));
651
+ }, timeoutMs);
652
+ };
653
+ const waitForReadyEffect = (timeoutMs, generation, hls, manifestEvent) => {
654
+ if (disposed || generation !== loadGeneration) return Effect.fail(new AudioPlaybackError({
655
+ code: "MEDIA_LOAD_SUPERSEDED",
656
+ message: "Media load was superseded before becoming ready.",
657
+ recoverable: true
658
+ }));
659
+ if (typeof element.readyState === "number" && element.readyState >= 1 || !hasElementEventTarget(element)) return Effect.void;
660
+ return Effect.callback((resume) => {
661
+ let settled = false;
662
+ const cleanup = () => {
663
+ element.removeEventListener("loadedmetadata", onReady);
664
+ element.removeEventListener("canplay", onReady);
665
+ element.removeEventListener("error", onError);
666
+ if (hls && manifestEvent) hls.off(manifestEvent, onReady);
667
+ if (cancelPendingReadyWait === onSuperseded) cancelPendingReadyWait = void 0;
668
+ };
669
+ const onSuperseded = () => {
670
+ if (settled) return;
671
+ settled = true;
672
+ cleanup();
673
+ resume(Effect.fail(new AudioPlaybackError({
674
+ code: "MEDIA_LOAD_SUPERSEDED",
675
+ message: "Media load was superseded before becoming ready.",
676
+ recoverable: true
677
+ })));
678
+ };
679
+ const onReady = () => {
680
+ if (settled) return;
681
+ if (disposed || generation !== loadGeneration) {
682
+ onSuperseded();
683
+ return;
684
+ }
685
+ settled = true;
686
+ cleanup();
687
+ resume(Effect.void);
688
+ };
689
+ const onError = () => {
690
+ if (settled) return;
691
+ if (disposed || generation !== loadGeneration) {
692
+ onSuperseded();
693
+ return;
694
+ }
695
+ settled = true;
696
+ cleanup();
697
+ resume(Effect.fail(new AudioPlaybackError({
698
+ code: "MEDIA_LOAD_ERROR",
699
+ message: "Media element emitted an error before becoming ready.",
700
+ recoverable: true
701
+ })));
702
+ };
703
+ cancelPendingReadyWait = onSuperseded;
704
+ element.addEventListener("loadedmetadata", onReady, { once: true });
705
+ element.addEventListener("canplay", onReady, { once: true });
706
+ element.addEventListener("error", onError, { once: true });
707
+ if (hls && manifestEvent) hls.on(manifestEvent, onReady);
708
+ return Effect.sync(() => {
709
+ settled = true;
710
+ cleanup();
711
+ });
712
+ }).pipe(Effect.timeoutOrElse({
713
+ duration: Duration.millis(Math.max(1, timeoutMs)),
714
+ orElse: () => Effect.fail(new AudioPlaybackError({
715
+ code: "MEDIA_READY_TIMEOUT",
716
+ message: `Media did not become ready within ${timeoutMs} ms.`,
717
+ recoverable: true
718
+ }))
719
+ }));
720
+ };
721
+ const triggerStallRecovery = (generation) => {
722
+ if (disposed || generation !== loadGeneration || stallRecoveryFiber !== void 0) return;
723
+ const effect = Effect.gen(function* () {
724
+ if (!stallRecoveryStep) stallRecoveryStep = yield* Schedule.toStepWithSleep(recoverySchedule);
725
+ const nextAttempt = yield* stallRecoveryStep(void 0).pipe(Effect.option);
726
+ if (disposed || generation !== loadGeneration) return;
727
+ if (Option.isNone(nextAttempt)) {
728
+ stallRecoveryStep = void 0;
729
+ options.onStreamError?.(element.currentTime, new AudioPlaybackError({
730
+ code: "STALL_TIMEOUT",
731
+ message: "Media playback stalled and recovery attempts were exhausted.",
732
+ recoverable: false
733
+ }));
734
+ return;
735
+ }
736
+ if (mode === "hls.js" && hlsInstance) {
737
+ hlsInstance.startLoad();
738
+ armStallWatchdog();
739
+ return;
740
+ }
741
+ if (currentUrl !== void 0) {
742
+ const resumeAt = element.currentTime;
743
+ const wasPlaying = !element.paused;
744
+ element.src = currentUrl;
745
+ element.defaultPlaybackRate = playbackRate;
746
+ element.playbackRate = playbackRate;
747
+ applyPreservesPitch(element, preservesPitch);
748
+ if (typeof element.load === "function") element.load();
749
+ scheduleInitialSeek(Number.isFinite(resumeAt) && resumeAt > 0 ? resumeAt : void 0);
750
+ if (wasPlaying && !disposed && generation === loadGeneration) {
751
+ yield* play().pipe(Effect.timeoutOption(Duration.millis(Math.max(1, stallWatchdogMs))), Effect.catch(() => Effect.void));
752
+ armStallWatchdog();
753
+ }
754
+ }
755
+ }).pipe(Effect.ensuring(Effect.sync(() => {
756
+ stallRecoveryFiber = void 0;
757
+ })));
758
+ stallRecoveryFiber = Fiber.runIn(scope)(Effect.runFork(effect));
759
+ };
760
+ const armStallWatchdog = () => {
761
+ if (disposed || stallWatchdogMs <= 0 || stallWatchdogTimer !== void 0 || element.paused || currentUrl === void 0) return;
762
+ const expectedGen = loadGeneration;
763
+ const stallTime = element.currentTime;
764
+ stallWatchdogTimer = setTimeout(() => {
765
+ stallWatchdogTimer = void 0;
766
+ if (disposed || expectedGen !== loadGeneration || element.paused || currentUrl === void 0) return;
767
+ if (element.currentTime !== stallTime) {
768
+ lastProgressTime = element.currentTime;
769
+ return;
770
+ }
771
+ options.onStall?.(element.currentTime);
772
+ triggerStallRecovery(expectedGen);
773
+ }, stallWatchdogMs);
774
+ };
775
+ const onElementStallEvent = () => {
776
+ armStallWatchdog();
777
+ };
778
+ const onElementProgressEvent = () => {
779
+ lastProgressTime = element.currentTime;
780
+ stopStallRecovery();
781
+ };
782
+ const onElementTimeUpdate = () => {
783
+ if (element.currentTime !== lastProgressTime) {
784
+ lastProgressTime = element.currentTime;
785
+ stopStallRecovery();
786
+ }
787
+ };
788
+ const onElementPauseOrEnd = () => {
789
+ clearStallWatchdog();
790
+ };
791
+ const elementListenersAttached = hasElementEventTarget(element);
792
+ if (elementListenersAttached) {
793
+ element.addEventListener("waiting", onElementStallEvent);
794
+ element.addEventListener("stalled", onElementStallEvent);
795
+ element.addEventListener("playing", onElementProgressEvent);
796
+ element.addEventListener("canplay", onElementProgressEvent);
797
+ element.addEventListener("timeupdate", onElementTimeUpdate);
798
+ element.addEventListener("pause", onElementPauseOrEnd);
799
+ element.addEventListener("ended", onElementPauseOrEnd);
800
+ element.addEventListener("emptied", onElementPauseOrEnd);
801
+ }
802
+ const detachElementListeners = () => {
803
+ if (!elementListenersAttached) return;
804
+ element.removeEventListener("waiting", onElementStallEvent);
805
+ element.removeEventListener("stalled", onElementStallEvent);
806
+ element.removeEventListener("playing", onElementProgressEvent);
807
+ element.removeEventListener("canplay", onElementProgressEvent);
808
+ element.removeEventListener("timeupdate", onElementTimeUpdate);
809
+ element.removeEventListener("pause", onElementPauseOrEnd);
810
+ element.removeEventListener("ended", onElementPauseOrEnd);
811
+ element.removeEventListener("emptied", onElementPauseOrEnd);
812
+ };
813
+ const dispose = () => Effect.sync(() => {
814
+ if (disposed) return;
815
+ disposed = true;
816
+ loadGeneration += 1;
817
+ clearPendingReadyWait();
818
+ clearPendingSeek();
819
+ clearReadyWatchdog();
820
+ stopStallRecovery();
821
+ detachElementListeners();
822
+ destroyHls();
823
+ element.pause();
824
+ element.removeAttribute("src");
825
+ if (typeof element.load === "function") element.load();
826
+ mode = "idle";
827
+ currentUrl = void 0;
828
+ });
829
+ yield* Scope.addFinalizer(scope, dispose());
830
+ const load = (url, loadOptions = {}) => Effect.gen(function* () {
831
+ loadGeneration += 1;
832
+ const generation = loadGeneration;
833
+ clearPendingReadyWait();
834
+ clearPendingSeek();
835
+ clearReadyWatchdog();
836
+ stopStallRecovery();
837
+ destroyHls();
838
+ mediaRecoveryAttempted = false;
839
+ currentUrl = url;
840
+ lastProgressTime = element.currentTime;
841
+ const effectiveReadyTimeoutMs = loadOptions.readyTimeoutMs ?? mediaReadyTimeoutMs;
842
+ if (loadOptions.crossOrigin !== void 0) element.crossOrigin = loadOptions.crossOrigin;
843
+ const allowNative = loadOptions.allowNativeHls ?? options.allowNativeHls ?? true;
844
+ const hlsStream = isHlsUrl(url);
845
+ if (hlsStream && !shouldUseNativeHls(element, allowNative, options.userAgent)) {
846
+ const HlsCtor = (yield* Effect.tryPromise({
847
+ catch: (error) => new AudioPlaybackError({
848
+ cause: String(error),
849
+ code: "HLS_IMPORT_FAILED",
850
+ message: `Failed to lazy-load hls.js: ${String(error)}`,
851
+ recoverable: false
852
+ }),
853
+ try: () => loadHlsModule()
854
+ })).default;
855
+ if (typeof HlsCtor?.isSupported === "function" && HlsCtor.isSupported()) {
856
+ const hls = new HlsCtor({
857
+ capLevelOnFPSDrop: true,
858
+ liveDurationInfinity: true,
859
+ liveMaxLatencyDurationCount: 10,
860
+ liveSyncDurationCount: 4,
861
+ lowLatencyMode: false,
862
+ maxBufferLength: 60,
863
+ maxMaxBufferLength: 120,
864
+ startPosition: loadOptions.startPositionSeconds ?? -1,
865
+ ...options.hlsConfig,
866
+ ...loadOptions.hlsConfig
867
+ });
868
+ hlsInstance = hls;
869
+ mode = "hls.js";
870
+ hls.on(HlsCtor.Events.MANIFEST_PARSED, () => {
871
+ clearReadyWatchdog();
872
+ });
873
+ hls.on(HlsCtor.Events.FRAG_LOADED, () => {
874
+ clearReadyWatchdog();
875
+ stopHlsRecovery();
876
+ });
877
+ hls.on(HlsCtor.Events.ERROR, (_event, data) => {
878
+ if (!data.fatal || disposed || hlsInstance !== hls) return;
879
+ if (data.type === HlsCtor.ErrorTypes.NETWORK_ERROR) {
880
+ if (hlsRecoveryFiber !== void 0) return;
881
+ const errorDetails = String(data.details);
882
+ const retryEffect = Effect.gen(function* () {
883
+ if (!hlsRecoveryStep) hlsRecoveryStep = yield* Schedule.toStepWithSleep(recoverySchedule);
884
+ const attempt = yield* hlsRecoveryStep(void 0).pipe(Effect.option);
885
+ if (disposed || hlsInstance !== hls) return;
886
+ if (Option.isSome(attempt)) hls.startLoad();
887
+ else {
888
+ hlsRecoveryStep = void 0;
889
+ options.onStreamError?.(element.currentTime, new AudioPlaybackError({
890
+ code: `HLS_${errorDetails}`,
891
+ message: `Fatal HLS error: ${errorDetails}`,
892
+ recoverable: false
893
+ }));
894
+ }
895
+ }).pipe(Effect.ensuring(Effect.sync(() => {
896
+ hlsRecoveryFiber = void 0;
897
+ })));
898
+ hlsRecoveryFiber = Fiber.runIn(scope)(Effect.runFork(retryEffect));
899
+ return;
900
+ }
901
+ if (data.type === HlsCtor.ErrorTypes.MEDIA_ERROR && !mediaRecoveryAttempted) {
902
+ mediaRecoveryAttempted = true;
903
+ hls.recoverMediaError();
904
+ return;
905
+ }
906
+ options.onStreamError?.(element.currentTime, new AudioPlaybackError({
907
+ code: `HLS_${String(data.details)}`,
908
+ message: `Fatal HLS error: ${String(data.details)}`,
909
+ recoverable: false
910
+ }));
911
+ });
912
+ hls.attachMedia(element);
913
+ hls.loadSource(url);
914
+ element.defaultPlaybackRate = playbackRate;
915
+ element.playbackRate = playbackRate;
916
+ applyPreservesPitch(element, preservesPitch);
917
+ if (loadOptions.waitForReady) yield* waitForReadyEffect(effectiveReadyTimeoutMs, generation, hls, HlsCtor.Events.MANIFEST_PARSED);
918
+ else armReadyWatchdog(effectiveReadyTimeoutMs, generation);
919
+ return;
920
+ }
921
+ }
922
+ mode = hlsStream ? "native-hls" : "native";
923
+ element.src = url;
924
+ element.defaultPlaybackRate = playbackRate;
925
+ element.playbackRate = playbackRate;
926
+ applyPreservesPitch(element, preservesPitch);
927
+ if (typeof element.load === "function") element.load();
928
+ scheduleInitialSeek(loadOptions.startPositionSeconds);
929
+ if (loadOptions.waitForReady) yield* waitForReadyEffect(effectiveReadyTimeoutMs, generation);
930
+ else armReadyWatchdog(effectiveReadyTimeoutMs, generation);
931
+ });
932
+ const play = () => Effect.tryPromise({
933
+ catch: (error) => {
934
+ const errName = error instanceof Error ? error.name : "";
935
+ const recoverable = errName === "AbortError" || errName === "NotAllowedError";
936
+ return new AudioPlaybackError({
937
+ cause: String(error),
938
+ code: errName || "PLAY_FAILED",
939
+ message: `Media play() failed: ${String(error)}`,
940
+ recoverable
941
+ });
942
+ },
943
+ try: async () => {
944
+ element.defaultPlaybackRate = playbackRate;
945
+ element.playbackRate = playbackRate;
946
+ await element.play();
947
+ }
948
+ });
949
+ const pause = () => Effect.sync(() => {
950
+ clearStallWatchdog();
951
+ element.pause();
952
+ });
953
+ const seek = (seconds) => Effect.sync(() => {
954
+ clearPendingSeek();
955
+ if (Number.isFinite(seconds) && seconds >= 0) element.currentTime = seconds;
956
+ });
957
+ const setPlaybackRate = (rate) => Effect.sync(() => {
958
+ playbackRate = clampPlaybackRate(rate);
959
+ element.defaultPlaybackRate = playbackRate;
960
+ element.playbackRate = playbackRate;
961
+ return playbackRate;
962
+ });
963
+ const setPreservesPitch = (preserve) => Effect.sync(() => {
964
+ preservesPitch = applyPreservesPitch(element, preserve);
965
+ return preservesPitch;
966
+ });
967
+ const setVolume = (volume) => Effect.sync(() => {
968
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(volume) ? volume : 1));
969
+ element.volume = clamped;
970
+ return clamped;
971
+ });
972
+ const setMuted = (muted) => Effect.sync(() => {
973
+ element.muted = muted;
974
+ return muted;
975
+ });
976
+ const refreshUrl = (url, seekPositionSeconds) => Effect.gen(function* () {
977
+ const wasPlaying = !element.paused;
978
+ const resumeAt = seekPositionSeconds ?? element.currentTime;
979
+ yield* load(url, { startPositionSeconds: Number.isFinite(resumeAt) && resumeAt > 0 ? resumeAt : void 0 });
980
+ if (wasPlaying) yield* play();
981
+ });
982
+ const runWithStallRecovery = (effect) => effect.pipe(Effect.retry({
983
+ schedule: recoverySchedule,
984
+ while: (err) => err.recoverable !== false
985
+ }));
986
+ const getSnapshot = () => ({
987
+ currentTime: element.currentTime,
988
+ duration: Number.isFinite(element.duration) ? element.duration : void 0,
989
+ mode,
990
+ muted: element.muted,
991
+ paused: element.paused,
992
+ playbackRate,
993
+ preservesPitch,
994
+ src: currentUrl,
995
+ volume: element.volume
996
+ });
997
+ return {
998
+ dispose,
999
+ element,
1000
+ getSnapshot,
1001
+ load,
1002
+ pause,
1003
+ play,
1004
+ refreshUrl,
1005
+ runWithStallRecovery,
1006
+ seek,
1007
+ setMuted,
1008
+ setPlaybackRate,
1009
+ setPreservesPitch,
1010
+ setVolume
1011
+ };
1012
+ });
1013
+ }
1014
+ // src/playback/media-session.ts
1015
+ const SILENT_WAV_SAMPLE_RATE = 8e3;
1016
+ const SILENT_WAV_DURATION_SECONDS = 10;
1017
+ const SILENT_WAV_HEADER_BYTES = 44;
1018
+ const DIACRITICS_REGEX = /\p{M}/gu;
1019
+ const DASH_REGEX = /[\u2010-\u2015\u2212]/gu;
1020
+ const SINGLE_QUOTE_REGEX = /[\u2018\u2019\u201A\u2032]/gu;
1021
+ const DOUBLE_QUOTE_REGEX = /[\u201C\u201D\u201E\u00AB\u00BB\u2033]/gu;
1022
+ const ELLIPSIS_REGEX = /\u2026/gu;
1023
+ const BULLET_REGEX = /[\u00B7\u2022]/gu;
1024
+ const NON_PRINTABLE_ASCII_REGEX = /[^\u0020-\u007E]/gu;
1025
+ const MULTI_SPACE_REGEX = /\s+/gu;
1026
+ /**
1027
+ * Sanitizes metadata strings for Bluetooth AVRCP car/headphone displays:
1028
+ * strips diacritics via NFKD, maps typographic punctuation to plain ASCII,
1029
+ * removes non-printable/non-ASCII chars, collapses whitespace, and falls back
1030
+ * to `fallback` (default `"Radio"`).
1031
+ */
1032
+ function sanitizeForBluetooth(input, fallback = "Radio") {
1033
+ if (!input || input.trim().length === 0) return fallback;
1034
+ const ascii = input.normalize("NFKD").replaceAll(DIACRITICS_REGEX, "").replaceAll(DASH_REGEX, "-").replaceAll(SINGLE_QUOTE_REGEX, "'").replaceAll(DOUBLE_QUOTE_REGEX, "\"").replaceAll(ELLIPSIS_REGEX, "...").replaceAll(BULLET_REGEX, "-").replaceAll(NON_PRINTABLE_ASCII_REGEX, "").replaceAll(MULTI_SPACE_REGEX, " ").trim();
1035
+ return ascii.length > 0 ? ascii : fallback;
1036
+ }
1037
+ function writeAscii(view, offset, text) {
1038
+ for (let i = 0; i < text.length; i += 1) view.setUint8(offset + i, text.codePointAt(i) ?? 0);
1039
+ }
1040
+ /**
1041
+ * Generates an all-zero mono 16-bit PCM RIFF/WAVE binary buffer.
1042
+ * Defaults to Couch's exact 10 s @ 8 kHz keep-alive WAV (160,044 bytes total),
1043
+ * ensuring Chromium treats the element as real media (> 5 s) for OS Now Playing / MPRIS.
1044
+ */
1045
+ function createSilentWavBytes(durationSeconds = 10, sampleRate = SILENT_WAV_SAMPLE_RATE) {
1046
+ const safeDuration = Math.max(1, Math.round(durationSeconds));
1047
+ const safeRate = Math.max(8e3, Math.round(sampleRate));
1048
+ const channels = 1;
1049
+ const bitsPerSample = 16;
1050
+ const bytesPerSample = bitsPerSample / 8;
1051
+ const dataBytes = safeRate * channels * bytesPerSample * safeDuration;
1052
+ const totalBytes = 44 + dataBytes;
1053
+ const buffer = new Uint8Array(totalBytes);
1054
+ const view = new DataView(buffer.buffer);
1055
+ writeAscii(view, 0, "RIFF");
1056
+ view.setUint32(4, 36 + dataBytes, true);
1057
+ writeAscii(view, 8, "WAVEfmt ");
1058
+ view.setUint32(16, 16, true);
1059
+ view.setUint16(20, 1, true);
1060
+ view.setUint16(22, channels, true);
1061
+ view.setUint32(24, safeRate, true);
1062
+ view.setUint32(28, safeRate * channels * bytesPerSample, true);
1063
+ view.setUint16(32, 2, true);
1064
+ view.setUint16(34, bitsPerSample, true);
1065
+ writeAscii(view, 36, "data");
1066
+ view.setUint32(40, dataBytes, true);
1067
+ return buffer;
1068
+ }
1069
+ function createSilentWavBlob(durationSeconds = 10, sampleRate = SILENT_WAV_SAMPLE_RATE) {
1070
+ const bytes = createSilentWavBytes(durationSeconds, sampleRate);
1071
+ return new Blob([bytes.buffer], { type: "audio/wav" });
1072
+ }
1073
+ const INERT_HANDLER = () => {};
1074
+ const CORE_TRANSPORT_ACTIONS = [
1075
+ "play",
1076
+ "pause",
1077
+ "stop"
1078
+ ];
1079
+ const OPTIONAL_ACTIONS = [
1080
+ "previoustrack",
1081
+ "nexttrack",
1082
+ "seekbackward",
1083
+ "seekforward",
1084
+ "seekto"
1085
+ ];
1086
+ /**
1087
+ * Merged MediaSession controller combining Radio's Bluetooth AVRCP sanitizer
1088
+ * and Couch's 10 s silent WAV keep-alive element (`loop: true, volume: 0`, unmuted)
1089
+ * with inert transport guards for live streams.
1090
+ */
1091
+ function createMediaSessionController(options = {}) {
1092
+ return Effect.gen(function* () {
1093
+ const sanitize = options.sanitizeAvrcp ?? true;
1094
+ const fallback = options.avrcpFallback ?? "Radio";
1095
+ const defaultSession = globalThis.navigator === void 0 ? void 0 : globalThis.navigator.mediaSession;
1096
+ const session = options.mediaSession ?? defaultSession;
1097
+ let keepAliveAudio;
1098
+ let keepAliveUrl;
1099
+ const clean = (value, defaultVal) => sanitize ? sanitizeForBluetooth(value, defaultVal) : value ?? defaultVal;
1100
+ const setMetadata = (metadata) => {
1101
+ if (!session) return;
1102
+ const payload = {
1103
+ album: metadata.album ? clean(metadata.album, "") : "",
1104
+ artist: metadata.artist ? clean(metadata.artist, "") : "",
1105
+ artwork: metadata.artwork ? [...metadata.artwork] : [],
1106
+ title: clean(metadata.title, fallback)
1107
+ };
1108
+ session.metadata = typeof globalThis.MediaMetadata === "function" ? new globalThis.MediaMetadata(payload) : payload;
1109
+ };
1110
+ const setPlaybackState = (state) => {
1111
+ if (!session) return;
1112
+ session.playbackState = state;
1113
+ };
1114
+ const setPositionState = (state) => {
1115
+ if (!session || typeof session.setPositionState !== "function") return;
1116
+ try {
1117
+ if (state.isLive) {
1118
+ session.setPositionState({
1119
+ duration: 0,
1120
+ position: 0
1121
+ });
1122
+ return;
1123
+ }
1124
+ const duration = state.duration !== void 0 && Number.isFinite(state.duration) && state.duration >= 0 ? state.duration : 0;
1125
+ const position = state.position !== void 0 && Number.isFinite(state.position) ? Math.max(0, Math.min(duration, state.position)) : 0;
1126
+ session.setPositionState({
1127
+ duration,
1128
+ playbackRate: state.playbackRate ?? 1,
1129
+ position
1130
+ });
1131
+ } catch {}
1132
+ };
1133
+ const setHandlers = (handlers) => {
1134
+ if (!session || typeof session.setActionHandler !== "function") return;
1135
+ for (const action of CORE_TRANSPORT_ACTIONS) {
1136
+ const handler = handlers[action] ?? INERT_HANDLER;
1137
+ try {
1138
+ session.setActionHandler(action, handler);
1139
+ } catch {}
1140
+ }
1141
+ for (const action of OPTIONAL_ACTIONS) {
1142
+ const handler = handlers[action] ?? null;
1143
+ try {
1144
+ session.setActionHandler(action, handler);
1145
+ } catch {}
1146
+ }
1147
+ };
1148
+ const stopKeepAlive = () => {
1149
+ if (keepAliveAudio) {
1150
+ keepAliveAudio.pause();
1151
+ keepAliveAudio.removeAttribute("src");
1152
+ if (typeof keepAliveAudio.load === "function") keepAliveAudio.load();
1153
+ keepAliveAudio = void 0;
1154
+ }
1155
+ if (keepAliveUrl) {
1156
+ URL.revokeObjectURL(keepAliveUrl);
1157
+ keepAliveUrl = void 0;
1158
+ }
1159
+ };
1160
+ const startKeepAlive = () => Effect.sync(() => {
1161
+ if (options.enableKeepAlive === false) return;
1162
+ if (keepAliveAudio) {
1163
+ keepAliveAudio.play().catch(() => {});
1164
+ return;
1165
+ }
1166
+ if (!options.createKeepAliveElement && typeof globalThis.Audio !== "function") return;
1167
+ const blob = createSilentWavBlob();
1168
+ keepAliveUrl = URL.createObjectURL(blob);
1169
+ const audio = options.createKeepAliveElement ? options.createKeepAliveElement() : new globalThis.Audio();
1170
+ audio.loop = true;
1171
+ audio.volume = 0;
1172
+ audio.muted = false;
1173
+ audio.src = keepAliveUrl;
1174
+ keepAliveAudio = audio;
1175
+ audio.play().catch(() => {});
1176
+ });
1177
+ const dispose = () => {
1178
+ stopKeepAlive();
1179
+ if (session && typeof session.setActionHandler === "function") for (const action of [...CORE_TRANSPORT_ACTIONS, ...OPTIONAL_ACTIONS]) try {
1180
+ session.setActionHandler(action, null);
1181
+ } catch {}
1182
+ };
1183
+ yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(() => {
1184
+ dispose();
1185
+ }));
1186
+ return {
1187
+ dispose,
1188
+ setHandlers,
1189
+ setMetadata,
1190
+ setPlaybackState,
1191
+ setPositionState,
1192
+ startKeepAlive,
1193
+ stopKeepAlive
1194
+ };
1195
+ });
1196
+ }
1197
+ // src/playback/sampler.ts
1198
+ const SAMPLE_MIME_TYPES = {
1199
+ mp3: "audio/mpeg",
1200
+ ogg: "audio/ogg",
1201
+ wav: "audio/wav"
1202
+ };
1203
+ const SAMPLE_KEY_PATTERN = /^[\w\-./]+\.(?<ext>mp3|wav|ogg)$/u;
1204
+ const SAMPLER_MIN_SLICE_DURATION = .1;
1205
+ const SAMPLER_MAX_SLICE_DURATION = 2;
1206
+ const SAMPLER_RELEASE_SECONDS = 1;
1207
+ const SAMPLER_VOLUME_RAMP_SECONDS = .05;
1208
+ const SAMPLER_DEFAULT_BATCH_SIZE = 4;
1209
+ /**
1210
+ * Creates a Web Audio buffer/slice `Sampler` (`AudioBufferSourceNode -> voiceGain -> masterGain -> destination`).
1211
+ * Supports Cwavasape random-slice playback, one-shot envelope triggering, and batched loading.
1212
+ */
1213
+ function createSampler(context, options = {}) {
1214
+ const buffers = /* @__PURE__ */ new Map();
1215
+ const activeSources = /* @__PURE__ */ new Set();
1216
+ const masterGain = context.createGain();
1217
+ masterGain.gain.value = Math.max(0, Math.min(1, options.initialVolume ?? 1));
1218
+ const destination = options.destination ?? context.destination;
1219
+ masterGain.connect(destination);
1220
+ const random = options.random ?? (() => Math.random());
1221
+ const registerBuffer = (key, buffer) => {
1222
+ buffers.set(key, buffer);
1223
+ };
1224
+ const getBuffer = (key) => buffers.get(key);
1225
+ const keys = () => [...buffers.keys()];
1226
+ const loadBuffer = (key, url) => Effect.tryPromise({
1227
+ catch: (error) => new AudioDecodeError({
1228
+ message: `Failed to load sample "${key}": ${String(error)}`,
1229
+ source: url
1230
+ }),
1231
+ try: async () => {
1232
+ const cached = buffers.get(key);
1233
+ if (cached) return cached;
1234
+ const response = await (options.fetchImpl ?? globalThis.fetch)(url);
1235
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1236
+ const arrayBuffer = await response.arrayBuffer();
1237
+ const decoded = await context.decodeAudioData(arrayBuffer);
1238
+ buffers.set(key, decoded);
1239
+ return decoded;
1240
+ }
1241
+ });
1242
+ const loadBatch = (entries, batchSize = 4) => Effect.gen(function* () {
1243
+ const size = Math.max(1, Math.floor(batchSize));
1244
+ const loaded = [];
1245
+ const failed = [];
1246
+ for (let i = 0; i < entries.length; i += size) {
1247
+ const chunk = entries.slice(i, i + size);
1248
+ const results = yield* Effect.forEach(chunk, (entry) => loadBuffer(entry.key, entry.url).pipe(Effect.map(() => ({
1249
+ key: entry.key,
1250
+ ok: true
1251
+ })), Effect.catch((error) => Effect.succeed({
1252
+ error: error.message,
1253
+ key: entry.key,
1254
+ ok: false
1255
+ }))), { concurrency: "unbounded" });
1256
+ for (const item of results) if (item.ok) loaded.push(item.key);
1257
+ else failed.push({
1258
+ error: item.error,
1259
+ key: item.key
1260
+ });
1261
+ }
1262
+ return {
1263
+ failed,
1264
+ loaded
1265
+ };
1266
+ });
1267
+ const playSlice = (key, sliceOptions = {}) => {
1268
+ const buffer = buffers.get(key);
1269
+ if (!buffer) return;
1270
+ const now = context.currentTime;
1271
+ const attack = Math.max(0, sliceOptions.attackSeconds ?? 0);
1272
+ const release = Math.max(0, sliceOptions.releaseSeconds ?? 1);
1273
+ const gainLevel = Math.max(0, sliceOptions.gain ?? 1);
1274
+ const offset = Math.max(0, Math.min(buffer.duration, sliceOptions.offsetSeconds ?? 0));
1275
+ const available = Math.max(0, buffer.duration - offset);
1276
+ const duration = sliceOptions.durationSeconds === void 0 ? Math.max(0, available - release) : Math.max(0, Math.min(available, sliceOptions.durationSeconds));
1277
+ const source = context.createBufferSource();
1278
+ source.buffer = buffer;
1279
+ if (sliceOptions.playbackRate !== void 0 && Number.isFinite(sliceOptions.playbackRate) && sliceOptions.playbackRate > 0) source.playbackRate.value = sliceOptions.playbackRate;
1280
+ const voiceGain = context.createGain();
1281
+ if (attack > 0) {
1282
+ voiceGain.gain.setValueAtTime(0, now);
1283
+ voiceGain.gain.linearRampToValueAtTime(gainLevel, now + attack);
1284
+ } else voiceGain.gain.setValueAtTime(gainLevel, now);
1285
+ voiceGain.gain.setValueAtTime(gainLevel, now + duration);
1286
+ if (release > 0) voiceGain.gain.linearRampToValueAtTime(0, now + duration + release);
1287
+ source.connect(voiceGain);
1288
+ voiceGain.connect(masterGain);
1289
+ activeSources.add(source);
1290
+ let stopped = false;
1291
+ const cleanup = () => {
1292
+ if (stopped) return;
1293
+ stopped = true;
1294
+ activeSources.delete(source);
1295
+ source.disconnect();
1296
+ voiceGain.disconnect();
1297
+ };
1298
+ source.onended = cleanup;
1299
+ source.start(now, offset, duration + release);
1300
+ return {
1301
+ durationSeconds: duration,
1302
+ key,
1303
+ offsetSeconds: offset,
1304
+ stop: () => {
1305
+ if (stopped) return;
1306
+ try {
1307
+ source.stop();
1308
+ } catch {}
1309
+ cleanup();
1310
+ }
1311
+ };
1312
+ };
1313
+ const playRandom = (randomOptions = {}) => {
1314
+ const allKeys = [...buffers.keys()];
1315
+ if (allKeys.length === 0) return;
1316
+ const chosenKey = allKeys[Math.floor(random() * allKeys.length)];
1317
+ if (!chosenKey) return;
1318
+ const buffer = buffers.get(chosenKey);
1319
+ if (!buffer) return;
1320
+ const minDur = randomOptions.minDurationSeconds ?? .1;
1321
+ const maxDur = randomOptions.maxDurationSeconds ?? 2;
1322
+ const release = randomOptions.releaseSeconds ?? 1;
1323
+ const duration = minDur + random() * Math.max(0, maxDur - minDur);
1324
+ const maxOffset = Math.max(0, buffer.duration - duration - release);
1325
+ const offset = random() * maxOffset;
1326
+ return playSlice(chosenKey, {
1327
+ durationSeconds: duration,
1328
+ gain: randomOptions.gain,
1329
+ offsetSeconds: offset,
1330
+ releaseSeconds: release
1331
+ });
1332
+ };
1333
+ const setVolume = (value) => {
1334
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(value) ? value : 1));
1335
+ const now = context.currentTime;
1336
+ masterGain.gain.cancelScheduledValues(now);
1337
+ masterGain.gain.setValueAtTime(masterGain.gain.value, now);
1338
+ masterGain.gain.linearRampToValueAtTime(clamped, now + SAMPLER_VOLUME_RAMP_SECONDS);
1339
+ return clamped;
1340
+ };
1341
+ const stopAll = () => {
1342
+ for (const source of activeSources) {
1343
+ try {
1344
+ source.stop();
1345
+ } catch {}
1346
+ source.disconnect();
1347
+ }
1348
+ activeSources.clear();
1349
+ };
1350
+ const dispose = () => {
1351
+ stopAll();
1352
+ masterGain.disconnect();
1353
+ buffers.clear();
1354
+ };
1355
+ return {
1356
+ activeVoiceCount: () => activeSources.size,
1357
+ dispose,
1358
+ getBuffer,
1359
+ keys,
1360
+ loadBatch,
1361
+ loadBuffer,
1362
+ masterGain,
1363
+ playRandom,
1364
+ playSlice,
1365
+ registerBuffer,
1366
+ setVolume,
1367
+ stopAll
1368
+ };
1369
+ }
1370
+ export { AudioContextService, DEFAULT_MAX_RECOVERY_DELAY_MS, DEFAULT_MEDIA_READY_TIMEOUT_MS, DEFAULT_STALL_WATCHDOG_MS, MAX_PLAYBACK_RATE, MIN_PLAYBACK_RATE, SAMPLER_DEFAULT_BATCH_SIZE, SAMPLER_MAX_SLICE_DURATION, SAMPLER_MIN_SLICE_DURATION, SAMPLER_RELEASE_SECONDS, SAMPLER_VOLUME_RAMP_SECONDS, SAMPLE_KEY_PATTERN, SAMPLE_MIME_TYPES, SILENT_WAV_DURATION_SECONDS, SILENT_WAV_HEADER_BYTES, SILENT_WAV_SAMPLE_RATE, acquireAudioContext, acquireInputCapture, applyPreservesPitch, attachGestureUnlock, clampPlaybackRate, computeStallBackoffMs, createAudioContextOptions, createMediaEngine, createMediaSessionController, createSampler, createSilentWavBlob, createSilentWavBytes, createStallRecoverySchedule, ensureAudioContextRunning, isHlsUrl, isWebKitBrowser, makeAudioContextLayer, normalizeAudioContextState, requestDisplayAudio, sanitizeForBluetooth, shouldUseNativeHls, snapshotAudioContext };
1371
+
1372
+ //# sourceMappingURL=index.js.map