@avoid.quest/audio 0.1.1-beta.1 → 0.1.1-beta.3

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 (46) hide show
  1. package/README.md +6 -6
  2. package/dist/effects/index.d.ts +3 -23
  3. package/dist/effects/index.js +11 -34
  4. package/dist/effects/index.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/midi/index.d.ts +1 -1
  8. package/dist/midi/index.js +5 -7
  9. package/dist/midi/index.js.map +1 -1
  10. package/dist/native-Bern4_PB.js.map +1 -1
  11. package/dist/{pcm-buffer-DSzGHbon.js → pcm-buffer-CYMaauzk.js} +33 -37
  12. package/dist/pcm-buffer-CYMaauzk.js.map +1 -0
  13. package/dist/playback/index.d.ts +118 -47
  14. package/dist/playback/index.js +232 -138
  15. package/dist/playback/index.js.map +1 -1
  16. package/dist/queue/index.d.ts +0 -7
  17. package/dist/queue/index.js +6 -32
  18. package/dist/queue/index.js.map +1 -1
  19. package/dist/recognize/index.d.ts +8 -98
  20. package/dist/recognize/index.js +1 -273
  21. package/dist/routing/index.d.ts +5 -4
  22. package/dist/routing/index.js +56 -58
  23. package/dist/routing/index.js.map +1 -1
  24. package/dist/{shazam-gBrX1NEY.d.ts → shazam-D9clxt6q.d.ts} +3 -3
  25. package/dist/sync/index.d.ts +23 -178
  26. package/dist/sync/index.js +167 -732
  27. package/dist/sync/index.js.map +1 -1
  28. package/dist/{worklet-loader-f741D1tk.js → worklet-loader-BJy5r9pD.js} +53 -63
  29. package/dist/worklet-loader-BJy5r9pD.js.map +1 -0
  30. package/dist/worklet-loader-DEEeZBiD.d.ts +27 -0
  31. package/dist/worklets/live-pcm.d.ts +1 -0
  32. package/dist/worklets/live-pcm.js +285 -0
  33. package/dist/worklets/live-pcm.js.map +1 -0
  34. package/dist/worklets/meter.js.map +1 -1
  35. package/dist/worklets/pcm-capture.d.ts +0 -2
  36. package/dist/worklets/pcm-capture.js +0 -2
  37. package/dist/worklets/pcm-capture.js.map +1 -1
  38. package/package.json +12 -13
  39. package/types/hls-unavailable.d.ts +10 -0
  40. package/dist/pcm-buffer-DSzGHbon.js.map +0 -1
  41. package/dist/recognize/index.js.map +0 -1
  42. package/dist/worklet-loader-BabwPALw.d.ts +0 -41
  43. package/dist/worklet-loader-f741D1tk.js.map +0 -1
  44. package/dist/worklets/couch-live.d.ts +0 -1
  45. package/dist/worklets/couch-live.js +0 -283
  46. package/dist/worklets/couch-live.js.map +0 -1
@@ -1,8 +1,9 @@
1
- import { Context, Duration, Effect, Fiber, Layer, Option, Result, Schedule, Scope } from "effect";
1
+ import { Context, Duration, Effect, FiberSet, Layer, Option, Result, Schedule, Scope } from "effect";
2
2
  import { a as AudioPlaybackError, l as AudioUnsupportedError, n as AudioDecodeError, t as AudioCaptureError } from "../errors-BT9HxDLn.js";
3
3
  import { a as clampFinite, p as scheduleParam } from "../native-Bern4_PB.js";
4
- import { i as prepareShazamPcm, n as createPcmRingBuffer, r as generateShazamSignatureFromFloat32 } from "../pcm-buffer-DSzGHbon.js";
5
- import { i as loadAudioWorklet, r as createWorkletModuleUrl } from "../worklet-loader-f741D1tk.js";
4
+ import { constVoid } from "effect/Function";
5
+ import { a as prepareShazamPcm, i as generateShazamSignatureFromFloat32, r as createPcmRingBuffer } from "../pcm-buffer-CYMaauzk.js";
6
+ import { i as loadAudioWorklet, r as createWorkletModuleUrl } from "../worklet-loader-BJy5r9pD.js";
6
7
  // src/playback/audio-context.ts
7
8
  var AudioContextService = class extends Context.Service()("@avoid.quest/audio/AudioContextService") {};
8
9
  function createAudioContextOptions(options = {}) {
@@ -18,11 +19,10 @@ function normalizeAudioContextState(state) {
18
19
  }
19
20
  const normalizedState = (ctx) => normalizeAudioContextState(ctx.state);
20
21
  function snapshotAudioContext(context) {
21
- const ext = context;
22
22
  return {
23
23
  baseLatency: typeof context.baseLatency === "number" ? context.baseLatency : void 0,
24
24
  currentTime: context.currentTime,
25
- outputLatency: typeof ext.outputLatency === "number" ? ext.outputLatency : void 0,
25
+ outputLatency: typeof context.outputLatency === "number" ? context.outputLatency : void 0,
26
26
  sampleRate: context.sampleRate,
27
27
  state: normalizedState(context)
28
28
  };
@@ -63,7 +63,7 @@ const GESTURE_EVENTS = [
63
63
  "click",
64
64
  "keydown"
65
65
  ];
66
- const noop = () => {};
66
+ const noop = () => void 0;
67
67
  function attachGestureUnlock(context, target = globalThis.window) {
68
68
  const isTerminal = () => normalizedState(context) !== "suspended";
69
69
  if (!target || isTerminal()) return noop;
@@ -102,13 +102,18 @@ function closeContextSafely(context) {
102
102
  }
103
103
  }).pipe(Effect.catch(() => Effect.void));
104
104
  }
105
+ const isAudioContextConstructor = (value) => typeof value === "function";
106
+ const legacyAudioContext = () => {
107
+ const scope = globalThis;
108
+ const legacy = "webkitAudioContext" in scope ? scope.webkitAudioContext : void 0;
109
+ return isAudioContextConstructor(legacy) ? legacy : void 0;
110
+ };
105
111
  function resolveContext(options) {
106
112
  if (options.context) return Effect.succeed(options.context);
107
113
  const ctxOpts = createAudioContextOptions(options);
108
114
  const { createContext } = options;
109
115
  if (createContext) return Effect.sync(() => createContext(ctxOpts));
110
- const g = globalThis;
111
- const Ctor = g.AudioContext ?? g.webkitAudioContext;
116
+ const Ctor = globalThis.AudioContext ?? legacyAudioContext();
112
117
  return typeof Ctor === "function" ? Effect.sync(() => new Ctor(ctxOpts)) : Effect.fail(new AudioUnsupportedError({
113
118
  feature: "AudioContext",
114
119
  message: "AudioContext is not supported in this environment."
@@ -209,25 +214,23 @@ const DISPLAY_CONSTRAINTS = {
209
214
  },
210
215
  windowAudio: "exclude"
211
216
  };
212
- function requestDisplayAudio(options = {}) {
213
- return Effect.gen(function* () {
214
- const devices = options.mediaDevices ?? globalThis.navigator?.mediaDevices;
215
- if (typeof devices?.getDisplayMedia !== "function") return yield* Effect.fail(capErr("UNSUPPORTED", "getDisplayMedia unavailable."));
216
- const stream = yield* acquireStreamWithAbort(() => devices.getDisplayMedia(DISPLAY_CONSTRAINTS), options.signal, "Display audio capture cancelled.", "DISPLAY_AUDIO_FAILED", "Display audio capture failed");
217
- if (!stream.getAudioTracks().some((t) => t.readyState === "live")) {
217
+ const requestDisplayAudio = Effect.fn("InputCapture.requestDisplayAudio")(function* (options = {}) {
218
+ const devices = options.mediaDevices ?? globalThis.navigator?.mediaDevices;
219
+ if (typeof devices?.getDisplayMedia !== "function") return yield* Effect.fail(capErr("UNSUPPORTED", "getDisplayMedia unavailable."));
220
+ const stream = yield* acquireStreamWithAbort(() => devices.getDisplayMedia(DISPLAY_CONSTRAINTS), options.signal, "Display audio capture cancelled.", "DISPLAY_AUDIO_FAILED", "Display audio capture failed");
221
+ if (!stream.getAudioTracks().some((t) => t.readyState === "live")) {
222
+ stopTracks(stream);
223
+ return yield* Effect.fail(capErr("NO_AUDIO_TRACK", "No live audio track."));
224
+ }
225
+ if (options.requireBrowserTab ?? true) {
226
+ const surface = stream.getVideoTracks()[0]?.getSettings().displaySurface;
227
+ if (surface !== void 0 && surface !== "browser") {
218
228
  stopTracks(stream);
219
- return yield* Effect.fail(capErr("NO_AUDIO_TRACK", "No live audio track."));
229
+ return yield* Effect.fail(capErr("INVALID_SURFACE", `Expected browser tab, got "${surface}".`));
220
230
  }
221
- if (options.requireBrowserTab ?? true) {
222
- const surface = (stream.getVideoTracks()[0]?.getSettings())?.displaySurface;
223
- if (surface !== void 0 && surface !== "browser") {
224
- stopTracks(stream);
225
- return yield* Effect.fail(capErr("INVALID_SURFACE", `Expected browser tab, got "${surface}".`));
226
- }
227
- }
228
- return stream;
229
- });
230
- }
231
+ }
232
+ return stream;
233
+ });
231
234
  function resolveInputStream(options) {
232
235
  if (options.signal?.aborted) return Effect.fail(capErr("ABORTED", "Input capture cancelled.", true));
233
236
  if (options.stream) return Effect.succeed(options.stream);
@@ -313,24 +316,34 @@ const MAX_PLAYBACK_RATE = 2;
313
316
  const DEFAULT_MEDIA_READY_TIMEOUT_MS = 2e4;
314
317
  const DEFAULT_STALL_WATCHDOG_MS = 6e3;
315
318
  const DEFAULT_MAX_RECOVERY_DELAY_MS = 3e4;
316
- const clampPlaybackRate = (rate) => clampFinite(rate, MIN_PLAYBACK_RATE, 2, 1);
319
+ const clampPlaybackRate = (rate, min = MIN_PLAYBACK_RATE, max = 2) => {
320
+ const lower = Number.isFinite(min) && min > 0 ? min : MIN_PLAYBACK_RATE;
321
+ const upper = Number.isFinite(max) && max >= lower ? max : Math.max(lower, 2);
322
+ return clampFinite(rate, lower, upper, Math.min(upper, Math.max(lower, 1)));
323
+ };
317
324
  function applyPreservesPitch(element, preserve) {
318
- const ext = element;
319
- if ("preservesPitch" in ext) ext.preservesPitch = preserve;
320
- if ("webkitPreservesPitch" in ext) ext.webkitPreservesPitch = preserve;
325
+ if ("preservesPitch" in element) element.preservesPitch = preserve;
326
+ if ("webkitPreservesPitch" in element) element.webkitPreservesPitch = preserve;
321
327
  return preserve;
322
328
  }
323
- function isHlsUrl(url, depth = 0) {
329
+ function isHlsUrl(url) {
324
330
  try {
325
- const parsed = new URL(url, "https://placeholder.invalid");
326
- if (parsed.pathname.toLowerCase().endsWith(".m3u8")) return true;
327
- const nested = depth < 1 ? parsed.searchParams.get("url") : null;
328
- return nested !== null && isHlsUrl(nested, depth + 1);
331
+ return new URL(url, "https://placeholder.invalid").pathname.toLowerCase().endsWith(".m3u8");
329
332
  } catch {
330
333
  return url.toLowerCase().includes(".m3u8");
331
334
  }
332
335
  }
333
- const isWebKitBrowser = (ua = globalThis.navigator?.userAgent) => Boolean(ua && /safari/iu.test(ua) && !/chrome|chromium|crios|fxios|edg|opr/iu.test(ua));
336
+ const IOS_DEVICE_PATTERN = /\b(?:iPhone|iPad|iPod)\b/iu;
337
+ const isWebKitBrowser = (ua = globalThis.navigator?.userAgent) => {
338
+ if (!ua) return false;
339
+ if (IOS_DEVICE_PATTERN.test(ua) && /AppleWebKit/iu.test(ua)) return true;
340
+ return /safari/iu.test(ua) && !/chrome|chromium|crios|fxios|edg|opr/iu.test(ua);
341
+ };
342
+ function canRouteThroughWebAudio(input = {}) {
343
+ if (input.browser?.webAudio === "no") return false;
344
+ if (isWebKitBrowser(input.userAgent) && (input.live === true || input.protocol === "hls")) return false;
345
+ return true;
346
+ }
334
347
  function shouldUseNativeHls(element, allowNativeHls = true, userAgent) {
335
348
  if (!allowNativeHls || !isWebKitBrowser(userAgent)) return false;
336
349
  const s = element.canPlayType("application/vnd.apple.mpegurl");
@@ -349,6 +362,8 @@ const pbErr = (code, message, recoverable, cause) => new AudioPlaybackError({
349
362
  recoverable
350
363
  });
351
364
  const failSuperseded = () => Effect.fail(pbErr("MEDIA_LOAD_SUPERSEDED", "Media load superseded.", true));
365
+ const HTML_MEDIA_ELEMENT_TAGS = /* @__PURE__ */ new Set(["[object HTMLAudioElement]", "[object HTMLVideoElement]"]);
366
+ const isHtmlMediaElement = (element) => HTML_MEDIA_ELEMENT_TAGS.has(Object.prototype.toString.call(element));
352
367
  const hasEventTarget = (el) => typeof el.addEventListener === "function" && typeof el.removeEventListener === "function";
353
368
  function bindEvents(target, entries, opts) {
354
369
  for (const [type, fn] of entries) target.addEventListener(type, fn, opts);
@@ -356,7 +371,7 @@ function bindEvents(target, entries, opts) {
356
371
  for (const [type, fn] of entries) target.removeEventListener(type, fn);
357
372
  };
358
373
  }
359
- function createRecoveryRunner(scope, schedule) {
374
+ function createRecoveryRunner(fork, schedule) {
360
375
  let step;
361
376
  let fiber;
362
377
  return {
@@ -367,7 +382,7 @@ function createRecoveryRunner(scope, schedule) {
367
382
  },
368
383
  trigger: (isStale, onRetry, onExhausted) => {
369
384
  if (isStale() || fiber !== void 0) return;
370
- fiber = Fiber.runIn(scope)(Effect.runFork(Effect.gen(function* () {
385
+ fiber = fork(Effect.gen(function* () {
371
386
  step ??= yield* Schedule.toStepWithSleep(schedule);
372
387
  const attempt = yield* step(void 0).pipe(Effect.option);
373
388
  if (isStale()) return;
@@ -377,7 +392,7 @@ function createRecoveryRunner(scope, schedule) {
377
392
  } else yield* onRetry();
378
393
  }).pipe(Effect.ensuring(Effect.sync(() => {
379
394
  fiber = void 0;
380
- })))));
395
+ }))));
381
396
  }
382
397
  };
383
398
  }
@@ -394,8 +409,8 @@ const DEFAULT_HLS_CONFIG = {
394
409
  function attachHlsInstance(HlsCtor, element, url, baseConfig, loadOptions, hlsRecovery, isActive, onReady, onStreamError) {
395
410
  const hls = new HlsCtor({
396
411
  ...DEFAULT_HLS_CONFIG,
397
- startPosition: loadOptions.startPositionSeconds ?? -1,
398
412
  ...baseConfig,
413
+ startPosition: loadOptions.startPositionSeconds ?? baseConfig?.startPosition ?? -1,
399
414
  ...loadOptions.hlsConfig
400
415
  });
401
416
  let mediaRecoveryAttempted = false;
@@ -418,14 +433,43 @@ function attachHlsInstance(HlsCtor, element, url, baseConfig, loadOptions, hlsRe
418
433
  hls.loadSource(url);
419
434
  return hls;
420
435
  }
421
- function waitForMediaReady(element, timeoutMs, isStale, hasMetadata, registerCancel, hls, manifestEvent) {
436
+ function attachMpegtsInstance(mod, element, url, baseConfig, loadOptions, isActive, onStreamError) {
437
+ const config = {
438
+ ...baseConfig,
439
+ ...loadOptions.mpegtsConfig
440
+ };
441
+ const player = mod.createPlayer({
442
+ type: "mpegts",
443
+ url
444
+ }, config);
445
+ const errorEvent = mod.Events?.ERROR ?? "error";
446
+ const onError = (...args) => {
447
+ if (!isActive(player)) return;
448
+ const codeSuffix = args[0] === void 0 ? "ERROR" : String(args[0]);
449
+ const details = args.map(String).join(": ") || "unknown";
450
+ onStreamError?.(element.currentTime, pbErr(`MPEGTS_${codeSuffix}`, `MPEG-TS error: ${details}`, false));
451
+ };
452
+ player.on?.(errorEvent, onError);
453
+ player.attachMediaElement(element);
454
+ player.load();
455
+ return {
456
+ cleanup: () => {
457
+ player.off?.(errorEvent, onError);
458
+ player.unload?.();
459
+ player.detachMediaElement?.();
460
+ player.destroy();
461
+ },
462
+ player
463
+ };
464
+ }
465
+ function waitForMediaReady(element, timeoutMs, isStale, hasMetadata, registerCancel, onManifestParsed) {
422
466
  if (isStale()) return failSuperseded();
423
467
  if (hasMetadata() || !hasEventTarget(element)) return Effect.void;
424
468
  return Effect.callback((resume) => {
425
469
  let settled = false;
426
470
  const cleanup = () => {
427
471
  unbind();
428
- if (hls && manifestEvent) hls.off(manifestEvent, onReady);
472
+ offManifestParsed?.();
429
473
  unregisterCancel();
430
474
  };
431
475
  const settle = (e) => {
@@ -443,7 +487,7 @@ function waitForMediaReady(element, timeoutMs, isStale, hasMetadata, registerCan
443
487
  ["playing", onReady],
444
488
  ["error", onError]
445
489
  ], { once: true });
446
- if (hls && manifestEvent) hls.on(manifestEvent, onReady);
490
+ const offManifestParsed = onManifestParsed?.(onReady);
447
491
  return Effect.sync(() => {
448
492
  settled = true;
449
493
  cleanup();
@@ -453,11 +497,11 @@ function waitForMediaReady(element, timeoutMs, isStale, hasMetadata, registerCan
453
497
  orElse: () => Effect.fail(pbErr("MEDIA_READY_TIMEOUT", `Media not ready within ${timeoutMs} ms.`, true))
454
498
  }));
455
499
  }
456
- function forkReadyWatchdog(scope, ready, onFailure) {
457
- return Fiber.runIn(scope)(Effect.runFork(ready.pipe(Effect.match({
500
+ function forkReadyWatchdog(fork, ready, onFailure) {
501
+ return fork(ready.pipe(Effect.match({
458
502
  onFailure,
459
- onSuccess: () => {}
460
- }))));
503
+ onSuccess: constVoid
504
+ })));
461
505
  }
462
506
  const applySeekSafe = (element, sec) => {
463
507
  if (!Number.isFinite(sec) || sec < 0) return;
@@ -537,25 +581,36 @@ function createStallWatchdog(element, stallWatchdogMs, stallRecovery, getState,
537
581
  };
538
582
  }
539
583
  // src/playback/media-engine.ts
540
- function buildMediaEngine(scope, options) {
584
+ const loadBundledHls = () => import("hls.js");
585
+ function unwrapMpegtsModule(loaded) {
586
+ return "default" in loaded ? loaded.default : loaded;
587
+ }
588
+ function buildMediaEngine(fork, options) {
541
589
  const { element } = options;
542
590
  const readyTimeoutDefault = options.mediaReadyTimeoutMs ?? 2e4;
543
591
  const stallWatchdogMs = options.stallWatchdogMs ?? 6e3;
592
+ const minPlaybackRate = options.minPlaybackRate ?? .5;
593
+ const maxPlaybackRate = options.maxPlaybackRate ?? 2;
594
+ const clampRate = (rate) => clampPlaybackRate(rate, minPlaybackRate, maxPlaybackRate);
544
595
  const recoverySchedule = createStallRecoverySchedule(options.stallRecovery);
545
- const loadHlsModule = options.loadHls ?? (() => import("hls.js"));
546
596
  let hlsInstance;
597
+ let mpegtsInstance;
598
+ let mpegtsCleanup;
547
599
  let currentProtocol;
600
+ let currentHlsConfig;
601
+ let currentMpegtsConfig;
602
+ let currentAllowNativeHls;
548
603
  let currentUrl;
549
604
  let mode = "idle";
550
- let playbackRate = clampPlaybackRate(element.playbackRate || 1);
605
+ let playbackRate = clampRate(element.playbackRate || 1);
551
606
  let preservesPitch = true;
552
607
  let disposed = false;
553
608
  let loadGeneration = 0;
554
609
  let pendingSeekCleanup;
555
610
  let readyWatchdogFiber;
556
611
  let cancelPendingReadyWait;
557
- const hlsRecovery = createRecoveryRunner(scope, recoverySchedule);
558
- const stallRecovery = createRecoveryRunner(scope, recoverySchedule);
612
+ const hlsRecovery = createRecoveryRunner(fork, recoverySchedule);
613
+ const stallRecovery = createRecoveryRunner(fork, recoverySchedule);
559
614
  const hasMetadata = () => typeof element.readyState === "number" && element.readyState >= 1;
560
615
  const applyRate = () => {
561
616
  element.defaultPlaybackRate = playbackRate;
@@ -590,12 +645,22 @@ function buildMediaEngine(scope, options) {
590
645
  await element.play();
591
646
  }
592
647
  });
593
- const recoverStall = (gen) => Effect.gen(function* () {
648
+ const stallWatchdog = createStallWatchdog(element, stallWatchdogMs, stallRecovery, () => ({
649
+ disposed,
650
+ gen: loadGeneration,
651
+ hasUrl: currentUrl !== void 0
652
+ }), Effect.fn("MediaEngine.recoverStall")(function* (gen) {
594
653
  if (mode === "hls.js" && hlsInstance) {
595
654
  hlsInstance.startLoad();
596
655
  stallWatchdog.arm();
597
656
  return;
598
657
  }
658
+ if (mode === "mpegts" && mpegtsInstance) {
659
+ mpegtsInstance.unload?.();
660
+ mpegtsInstance.load();
661
+ stallWatchdog.arm();
662
+ return;
663
+ }
599
664
  if (currentUrl === void 0) return;
600
665
  const at = element.currentTime;
601
666
  const wasPlaying = !element.paused;
@@ -604,12 +669,7 @@ function buildMediaEngine(scope, options) {
604
669
  yield* play().pipe(Effect.timeoutOption(Duration.millis(Math.max(1, stallWatchdogMs))), Effect.catch(() => Effect.void));
605
670
  stallWatchdog.arm();
606
671
  }
607
- });
608
- const stallWatchdog = createStallWatchdog(element, stallWatchdogMs, stallRecovery, () => ({
609
- disposed,
610
- gen: loadGeneration,
611
- hasUrl: currentUrl !== void 0
612
- }), recoverStall, options.onStall, options.onStreamError);
672
+ }), options.onStall, options.onStreamError);
613
673
  const resetPlayback = () => {
614
674
  cancelPendingReadyWait?.();
615
675
  cancelPendingReadyWait = void 0;
@@ -620,46 +680,85 @@ function buildMediaEngine(scope, options) {
620
680
  hlsRecovery.stop();
621
681
  hlsInstance?.destroy();
622
682
  hlsInstance = void 0;
683
+ mpegtsCleanup?.();
684
+ mpegtsCleanup = void 0;
685
+ mpegtsInstance = void 0;
623
686
  };
624
- const load = (url, loadOptions = {}) => Effect.gen(function* () {
687
+ const startHls = Effect.fn("MediaEngine.startHls")(function* (loadModule, media, url, loadOptions, gen) {
688
+ const { default: HlsCtor } = yield* Effect.tryPromise({
689
+ catch: (e) => pbErr("HLS_IMPORT_FAILED", `Load hls.js: ${String(e)}`, false, `${e}`),
690
+ try: () => loadModule()
691
+ });
692
+ if (disposed || gen !== loadGeneration) return yield* failSuperseded();
693
+ if (typeof HlsCtor?.isSupported !== "function" || !HlsCtor.isSupported()) return;
694
+ const player = attachHlsInstance(HlsCtor, media, url, options.hlsConfig, loadOptions, hlsRecovery, (hls) => !disposed && hlsInstance === hls, clearReady, options.onStreamError);
695
+ const parsed = HlsCtor.Events.MANIFEST_PARSED;
696
+ return {
697
+ onManifestParsed: (listener) => {
698
+ player.on(parsed, listener);
699
+ return () => player.off(parsed, listener);
700
+ },
701
+ player
702
+ };
703
+ });
704
+ const startMpegts = Effect.fn("MediaEngine.startMpegts")(function* (url, loadOptions, gen) {
705
+ if (!options.loadMpegts) return yield* pbErr("MPEGTS_UNSUPPORTED", "MPEG-TS playback requires a loadMpegts loader.", false);
706
+ const loadModule = options.loadMpegts;
707
+ const loaded = yield* Effect.tryPromise({
708
+ catch: (e) => pbErr("MPEGTS_IMPORT_FAILED", `Load mpegts.js: ${String(e)}`, false, `${e}`),
709
+ try: () => loadModule()
710
+ });
711
+ if (disposed || gen !== loadGeneration) return yield* failSuperseded();
712
+ const mod = unwrapMpegtsModule(loaded);
713
+ if (typeof mod.isSupported !== "function" || !mod.isSupported()) return yield* pbErr("MPEGTS_UNSUPPORTED", "mpegts.js is not supported in this environment.", false);
714
+ return attachMpegtsInstance(mod, element, url, options.mpegtsConfig, loadOptions, (player) => !disposed && mpegtsInstance === player, options.onStreamError);
715
+ });
716
+ const load = Effect.fn("MediaEngine.load")(function* (url, loadOptions = {}) {
717
+ if (disposed) return yield* pbErr("MEDIA_ENGINE_DISPOSED", "Media engine has been disposed.", false);
625
718
  loadGeneration += 1;
626
719
  const gen = loadGeneration;
627
720
  resetPlayback();
628
721
  currentUrl = url;
629
722
  currentProtocol = loadOptions.protocol;
723
+ currentHlsConfig = loadOptions.hlsConfig;
724
+ currentMpegtsConfig = loadOptions.mpegtsConfig;
725
+ currentAllowNativeHls = loadOptions.allowNativeHls;
630
726
  stallWatchdog.resetProgress();
631
727
  const readyMs = loadOptions.readyTimeoutMs ?? readyTimeoutDefault;
632
728
  if (loadOptions.crossOrigin !== void 0) element.crossOrigin = loadOptions.crossOrigin;
633
- const allowNative = loadOptions.allowNativeHls ?? options.allowNativeHls ?? true;
634
- const hlsStream = loadOptions.protocol === void 0 ? isHlsUrl(url) : loadOptions.protocol === "hls";
635
- let activeHls;
636
- let manifestEvent;
637
- if (hlsStream && !shouldUseNativeHls(element, allowNative, options.userAgent)) {
638
- const { default: HlsCtor } = yield* Effect.tryPromise({
639
- catch: (e) => pbErr("HLS_IMPORT_FAILED", `Load hls.js: ${String(e)}`, false, `${e}`),
640
- try: () => loadHlsModule()
641
- });
642
- if (disposed || gen !== loadGeneration) return yield* failSuperseded();
643
- if (typeof HlsCtor?.isSupported === "function" && HlsCtor.isSupported()) {
644
- activeHls = attachHlsInstance(HlsCtor, element, url, options.hlsConfig, loadOptions, hlsRecovery, (hls) => !disposed && hlsInstance === hls, clearReady, options.onStreamError);
645
- hlsInstance = activeHls;
729
+ let started;
730
+ if (loadOptions.protocol === "mpegts") {
731
+ const attached = yield* startMpegts(url, loadOptions, gen);
732
+ mpegtsInstance = attached.player;
733
+ mpegtsCleanup = attached.cleanup;
734
+ mode = "mpegts";
735
+ syncRateAndPitch();
736
+ clearSeek();
737
+ pendingSeekCleanup = scheduleElementSeek(element, loadOptions.startPositionSeconds, hasMetadata, () => disposed);
738
+ } else {
739
+ const allowNative = loadOptions.allowNativeHls ?? options.allowNativeHls ?? true;
740
+ const hlsStream = loadOptions.protocol === void 0 ? isHlsUrl(url) : loadOptions.protocol === "hls";
741
+ if (hlsStream && !shouldUseNativeHls(element, allowNative, options.userAgent)) {
742
+ if (options.loadHls) started = yield* startHls(options.loadHls, element, url, loadOptions, gen);
743
+ else if (isHtmlMediaElement(element)) started = yield* startHls(loadBundledHls, element, url, loadOptions, gen);
744
+ }
745
+ if (started) {
746
+ hlsInstance = started.player;
646
747
  mode = "hls.js";
647
748
  syncRateAndPitch();
648
- manifestEvent = HlsCtor.Events.MANIFEST_PARSED;
749
+ } else {
750
+ mode = hlsStream ? "native-hls" : "native";
751
+ loadNative(url, loadOptions.startPositionSeconds);
649
752
  }
650
753
  }
651
- if (!activeHls) {
652
- mode = hlsStream ? "native-hls" : "native";
653
- loadNative(url, loadOptions.startPositionSeconds);
654
- }
655
754
  const ready = waitForMediaReady(element, readyMs, () => disposed || gen !== loadGeneration, hasMetadata, (cancel) => {
656
755
  cancelPendingReadyWait = cancel;
657
756
  return () => {
658
757
  if (cancelPendingReadyWait === cancel) cancelPendingReadyWait = void 0;
659
758
  };
660
- }, activeHls, manifestEvent);
759
+ }, started?.onManifestParsed);
661
760
  if (loadOptions.waitForReady) yield* ready;
662
- else if (readyMs > 0 && !disposed) readyWatchdogFiber = forkReadyWatchdog(scope, ready, (failure) => {
761
+ else if (readyMs > 0 && !disposed) readyWatchdogFiber = forkReadyWatchdog(fork, ready, (failure) => {
663
762
  if (!disposed && gen === loadGeneration && failure.code !== "MEDIA_LOAD_SUPERSEDED" && !hasMetadata()) options.onStreamError?.(element.currentTime, failure);
664
763
  });
665
764
  });
@@ -674,6 +773,9 @@ function buildMediaEngine(scope, options) {
674
773
  element.load?.();
675
774
  mode = "idle";
676
775
  currentProtocol = void 0;
776
+ currentHlsConfig = void 0;
777
+ currentMpegtsConfig = void 0;
778
+ currentAllowNativeHls = void 0;
677
779
  currentUrl = void 0;
678
780
  });
679
781
  return {
@@ -696,10 +798,13 @@ function buildMediaEngine(scope, options) {
696
798
  element.pause();
697
799
  }),
698
800
  play,
699
- refreshUrl: (url, seekPos) => Effect.gen(function* () {
801
+ refreshUrl: Effect.fn("MediaEngine.refreshUrl")(function* (url, seekPos) {
700
802
  const wasPlaying = !element.paused;
701
803
  const at = seekPos ?? element.currentTime;
702
804
  yield* load(url, {
805
+ allowNativeHls: currentAllowNativeHls,
806
+ hlsConfig: currentHlsConfig,
807
+ mpegtsConfig: currentMpegtsConfig,
703
808
  protocol: currentProtocol,
704
809
  startPositionSeconds: Number.isFinite(at) && at > 0 ? at : void 0
705
810
  });
@@ -715,7 +820,7 @@ function buildMediaEngine(scope, options) {
715
820
  }),
716
821
  setMuted: (m) => Effect.sync(() => element.muted = m),
717
822
  setPlaybackRate: (rate) => Effect.sync(() => {
718
- playbackRate = clampPlaybackRate(rate);
823
+ playbackRate = clampRate(rate);
719
824
  applyRate();
720
825
  return playbackRate;
721
826
  }),
@@ -723,17 +828,15 @@ function buildMediaEngine(scope, options) {
723
828
  setVolume: (vol) => Effect.sync(() => element.volume = clampFinite(vol, 0, 1, 1))
724
829
  };
725
830
  }
726
- function createMediaEngine(options) {
727
- return Effect.gen(function* () {
728
- const scope = yield* Scope.Scope;
729
- const engine = buildMediaEngine(scope, options);
730
- yield* Scope.addFinalizer(scope, engine.dispose());
731
- return engine;
732
- });
733
- }
831
+ const createMediaEngine = Effect.fn("MediaEngine.create")(function* (options) {
832
+ const engine = buildMediaEngine(yield* FiberSet.makeRuntime(), options);
833
+ yield* Effect.addFinalizer(() => engine.dispose());
834
+ return engine;
835
+ });
734
836
  // src/playback/media-source.ts
735
837
  const elementSources = /* @__PURE__ */ new WeakMap();
736
838
  const destinationRouted = /* @__PURE__ */ new WeakSet();
839
+ const isElementHolder = (target) => "element" in target;
737
840
  function sourceError(code, message, cause) {
738
841
  return new AudioPlaybackError({
739
842
  ...cause === void 0 ? {} : { cause: String(cause) },
@@ -743,15 +846,14 @@ function sourceError(code, message, cause) {
743
846
  });
744
847
  }
745
848
  /**
746
- * Returns the memoized `MediaElementAudioSourceNode` for a `MediaEngine` or
747
- * media element (browsers allow only one per element), so live playback can
748
- * feed `acquirePcmCapture`, meters, or effects. Requesting it for another
749
- * `AudioContext` fails with `MEDIA_SOURCE_CONTEXT_MISMATCH`. Cross-origin
750
- * media needs CORS + `crossOrigin: "anonymous"`, otherwise the graph is silent.
849
+ * Memoized because browsers allow one source node per element, so a second
850
+ * `AudioContext` fails with `MEDIA_SOURCE_CONTEXT_MISMATCH`. Cross-origin media
851
+ * needs CORS and `crossOrigin: "anonymous"`, otherwise the graph is silent.
751
852
  */
752
853
  function getMediaElementSourceNode(context, target, options = {}) {
753
854
  return Effect.suspend(() => {
754
- const element = "element" in target ? target.element : target;
855
+ if (options.guard !== void 0 && !canRouteThroughWebAudio(options.guard)) return Effect.fail(sourceError("WEBKIT_LIVE_GRAPH_UNSUPPORTED", "Cannot route this stream through MediaElementAudioSourceNode without silent output."));
856
+ const element = isElementHolder(target) ? target.element : target;
755
857
  let node = elementSources.get(element);
756
858
  if (node && node.context !== context) return Effect.fail(sourceError("MEDIA_SOURCE_CONTEXT_MISMATCH", "This media element is already bound to a different AudioContext."));
757
859
  if (!node) {
@@ -778,11 +880,9 @@ function getMediaElementSourceNode(context, target, options = {}) {
778
880
  // src/worklets/pcm-capture.ts
779
881
  const PCM_CAPTURE_PROCESSOR_NAME = "avoid-pcm-capture";
780
882
  const PCM_CAPTURE_DEFAULT_CHUNK_FRAMES = 2048;
781
- /** Main-thread → processor message that ends the processor's lifetime. */
782
883
  const PCM_CAPTURE_STOP_MESSAGE = "stop";
783
884
  const PCM_CAPTURE_MIN_CHUNK_FRAMES = 128;
784
885
  const PCM_CAPTURE_MAX_CHUNK_FRAMES = 16384;
785
- /** Clamps a requested chunk size to whole frames within `[128, 16384]`. */
786
886
  function clampPcmChunkFrames(chunkFrames) {
787
887
  if (chunkFrames === void 0 || !Number.isFinite(chunkFrames)) return PCM_CAPTURE_DEFAULT_CHUNK_FRAMES;
788
888
  return Math.max(PCM_CAPTURE_MIN_CHUNK_FRAMES, Math.min(PCM_CAPTURE_MAX_CHUNK_FRAMES, Math.round(chunkFrames)));
@@ -825,7 +925,6 @@ if (typeof registerProcessor === "function") registerProcessor(PCM_CAPTURE_PROCE
825
925
  }
826
926
  });
827
927
  // src/playback/pcm-capture.ts
828
- /** Loads the standalone `@avoid.quest/audio/worklets/pcm-capture` module. */
829
928
  function loadPcmCaptureWorklet(context, options = {}) {
830
929
  return loadAudioWorklet(context, {
831
930
  ...options,
@@ -838,12 +937,8 @@ function bestEffort(run) {
838
937
  run();
839
938
  } catch {}
840
939
  }
841
- function buildPcmCapture(context, source, options) {
940
+ function buildPcmCapture(context, source, ring, options) {
842
941
  const { sampleRate } = context;
843
- const ring = createPcmRingBuffer({
844
- maxSeconds: options.maxSeconds,
845
- sampleRate
846
- });
847
942
  let active = true;
848
943
  const node = new globalThis.AudioWorkletNode(context, PCM_CAPTURE_PROCESSOR_NAME, {
849
944
  numberOfInputs: 1,
@@ -895,29 +990,30 @@ function buildPcmCapture(context, source, options) {
895
990
  toShazamPcm: (seconds) => prepareShazamPcm(snapshot(seconds), sampleRate)
896
991
  }, teardown];
897
992
  }
898
- /**
899
- * Passively taps any `AudioNode` (e.g. from `getMediaElementSourceNode` or
900
- * `acquireInputCapture`) into a rolling mono PCM window via the allocation-free
901
- * `pcm-capture` AudioWorklet, so live audio can be fingerprinted with
902
- * `capture.fingerprint()`. Fully torn down when the owning `Scope` closes.
903
- */
904
- function acquirePcmCapture(context, source, options = {}) {
905
- return Effect.gen(function* () {
906
- if (typeof globalThis.AudioWorkletNode !== "function") return yield* Effect.fail(new AudioUnsupportedError({
907
- feature: "AudioWorkletNode",
908
- message: "PCM capture requires AudioWorkletNode support."
909
- }));
910
- yield* loadPcmCaptureWorklet(context, options.workletOptions);
911
- const [capture] = yield* Effect.acquireRelease(Effect.try({
912
- catch: (error) => new AudioCaptureError({
913
- code: "PCM_CAPTURE_FAILED",
914
- message: `PCM capture setup failed: ${String(error)}`
915
- }),
916
- try: () => buildPcmCapture(context, source, options)
917
- }), ([, teardown]) => Effect.sync(teardown));
918
- return capture;
993
+ const acquirePcmCapture = Effect.fn("PcmCapture.acquire")(function* (context, source, options = {}) {
994
+ if (typeof globalThis.AudioWorkletNode !== "function") return yield* Effect.fail(new AudioUnsupportedError({
995
+ feature: "AudioWorkletNode",
996
+ message: "PCM capture requires AudioWorkletNode support."
997
+ }));
998
+ const ringResult = createPcmRingBuffer({
999
+ maxLimitSeconds: options.maxLimitSeconds,
1000
+ maxSeconds: options.maxSeconds,
1001
+ sampleRate: context.sampleRate
919
1002
  });
920
- }
1003
+ if (Result.isFailure(ringResult)) return yield* Effect.fail(new AudioCaptureError({
1004
+ code: "PCM_CAPTURE_FAILED",
1005
+ message: ringResult.failure.message
1006
+ }));
1007
+ yield* loadPcmCaptureWorklet(context, options.workletOptions);
1008
+ const [capture] = yield* Effect.acquireRelease(Effect.try({
1009
+ catch: (error) => new AudioCaptureError({
1010
+ code: "PCM_CAPTURE_FAILED",
1011
+ message: `PCM capture setup failed: ${String(error)}`
1012
+ }),
1013
+ try: () => buildPcmCapture(context, source, ringResult.success, options)
1014
+ }), ([, teardown]) => Effect.sync(teardown));
1015
+ return capture;
1016
+ });
921
1017
  // src/playback/media-session.ts
922
1018
  const SILENT_WAV_SAMPLE_RATE = 8e3;
923
1019
  const SILENT_WAV_DURATION_SECONDS = 10;
@@ -931,7 +1027,7 @@ const BLUETOOTH_REPLACEMENTS = [
931
1027
  [/[^\u0020-\u007E]/gu, ""],
932
1028
  [/\s+/gu, " "]
933
1029
  ];
934
- function sanitizeForBluetooth(input, fallback = "Radio") {
1030
+ function sanitizeForBluetooth(input, fallback = "") {
935
1031
  if (!input?.trim()) return fallback;
936
1032
  let out = input.normalize("NFKD");
937
1033
  for (const [pattern, replacement] of BLUETOOTH_REPLACEMENTS) out = out.replaceAll(pattern, replacement);
@@ -962,7 +1058,7 @@ function createSilentWavBytes(durationSeconds = 10, sampleRate = SILENT_WAV_SAMP
962
1058
  }
963
1059
  function createSilentWavBlob(durationSeconds = 10, sampleRate = SILENT_WAV_SAMPLE_RATE) {
964
1060
  const bytes = createSilentWavBytes(durationSeconds, sampleRate);
965
- return new Blob([bytes.buffer], { type: "audio/wav" });
1061
+ return new Blob([bytes], { type: "audio/wav" });
966
1062
  }
967
1063
  const INERT_HANDLER = () => {};
968
1064
  const CORE_ACTIONS = [
@@ -984,7 +1080,7 @@ const setActionSafe = (session, action, handler) => {
984
1080
  };
985
1081
  function buildMediaSessionController(options) {
986
1082
  const sanitize = options.sanitizeAvrcp ?? true;
987
- const fallback = options.avrcpFallback ?? "Radio";
1083
+ const fallback = options.avrcpFallback ?? "";
988
1084
  const session = options.mediaSession ?? globalThis.navigator?.mediaSession;
989
1085
  let keepAliveAudio;
990
1086
  let keepAliveUrl;
@@ -1061,13 +1157,11 @@ function buildMediaSessionController(options) {
1061
1157
  stopKeepAlive
1062
1158
  };
1063
1159
  }
1064
- function createMediaSessionController(options = {}) {
1065
- return Effect.gen(function* () {
1066
- const controller = buildMediaSessionController(options);
1067
- yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(controller.dispose));
1068
- return controller;
1069
- });
1070
- }
1160
+ const createMediaSessionController = Effect.fn("MediaSession.createController")(function* (options = {}) {
1161
+ const controller = buildMediaSessionController(options);
1162
+ yield* Effect.addFinalizer(() => Effect.sync(controller.dispose));
1163
+ return controller;
1164
+ });
1071
1165
  // src/playback/sampler.ts
1072
1166
  const SAMPLE_MIME_TYPES = {
1073
1167
  mp3: "audio/mpeg",
@@ -1100,7 +1194,7 @@ function createSampler(context, options = {}) {
1100
1194
  try: async () => {
1101
1195
  const cached = buffers.get(key);
1102
1196
  if (cached) return cached;
1103
- const res = await (options.fetchImpl ?? globalThis.fetch)(url);
1197
+ const res = options.fetchImpl === void 0 || options.fetchImpl === globalThis.fetch ? await globalThis.fetch(url) : await options.fetchImpl(url);
1104
1198
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
1105
1199
  const decoded = await context.decodeAudioData(await res.arrayBuffer());
1106
1200
  buffers.set(key, decoded);
@@ -1136,7 +1230,7 @@ function createSampler(context, options = {}) {
1136
1230
  source.disconnect();
1137
1231
  voice.disconnect();
1138
1232
  };
1139
- source.onended = cleanup;
1233
+ source.addEventListener("ended", cleanup, { once: true });
1140
1234
  source.start(now, offset, duration + release);
1141
1235
  return {
1142
1236
  durationSeconds: duration,
@@ -1211,6 +1305,6 @@ function createSampler(context, options = {}) {
1211
1305
  stopAll
1212
1306
  };
1213
1307
  }
1214
- export { AudioContextService, DEFAULT_MAX_RECOVERY_DELAY_MS, DEFAULT_MEDIA_READY_TIMEOUT_MS, DEFAULT_STALL_WATCHDOG_MS, MAX_PLAYBACK_RATE, MIN_PLAYBACK_RATE, PCM_CAPTURE_DEFAULT_CHUNK_FRAMES, PCM_CAPTURE_PROCESSOR_NAME, 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, acquirePcmCapture, applyPreservesPitch, attachGestureUnlock, clampPlaybackRate, computeStallBackoffMs, createAudioContextOptions, createMediaEngine, createMediaSessionController, createSampler, createSilentWavBlob, createSilentWavBytes, createStallRecoverySchedule, ensureAudioContextRunning, getMediaElementSourceNode, isHlsUrl, isWebKitBrowser, loadPcmCaptureWorklet, makeAudioContextLayer, normalizeAudioContextState, requestDisplayAudio, sanitizeForBluetooth, shouldUseNativeHls, snapshotAudioContext };
1308
+ export { AudioContextService, DEFAULT_MAX_RECOVERY_DELAY_MS, DEFAULT_MEDIA_READY_TIMEOUT_MS, DEFAULT_STALL_WATCHDOG_MS, MAX_PLAYBACK_RATE, MIN_PLAYBACK_RATE, PCM_CAPTURE_DEFAULT_CHUNK_FRAMES, PCM_CAPTURE_PROCESSOR_NAME, 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, acquirePcmCapture, applyPreservesPitch, attachGestureUnlock, canRouteThroughWebAudio, clampPlaybackRate, computeStallBackoffMs, createAudioContextOptions, createMediaEngine, createMediaSessionController, createSampler, createSilentWavBlob, createSilentWavBytes, createStallRecoverySchedule, ensureAudioContextRunning, getMediaElementSourceNode, isHlsUrl, isWebKitBrowser, loadPcmCaptureWorklet, makeAudioContextLayer, normalizeAudioContextState, requestDisplayAudio, sanitizeForBluetooth, shouldUseNativeHls, snapshotAudioContext };
1215
1309
 
1216
1310
  //# sourceMappingURL=index.js.map