@avoid.quest/audio 0.0.0-stage → 0.1.1-beta.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.
- package/LICENSE +21 -0
- package/README.md +98 -2
- package/dist/effects/index.d.ts +215 -0
- package/dist/effects/index.js +451 -0
- package/dist/effects/index.js.map +1 -0
- package/dist/errors-BT9HxDLn.js +74 -0
- package/dist/errors-BT9HxDLn.js.map +1 -0
- package/dist/errors-ChTQFwuZ.d.ts +53 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/midi/index.d.ts +138 -0
- package/dist/midi/index.js +302 -0
- package/dist/midi/index.js.map +1 -0
- package/dist/native-Bern4_PB.js +172 -0
- package/dist/native-Bern4_PB.js.map +1 -0
- package/dist/pcm-buffer-DSzGHbon.js +436 -0
- package/dist/pcm-buffer-DSzGHbon.js.map +1 -0
- package/dist/playback/index.d.ts +295 -0
- package/dist/playback/index.js +1209 -0
- package/dist/playback/index.js.map +1 -0
- package/dist/queue/index.d.ts +133 -0
- package/dist/queue/index.js +563 -0
- package/dist/queue/index.js.map +1 -0
- package/dist/recognize/index.d.ts +124 -0
- package/dist/recognize/index.js +273 -0
- package/dist/recognize/index.js.map +1 -0
- package/dist/routing/index.d.ts +109 -0
- package/dist/routing/index.js +555 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/shazam-gBrX1NEY.d.ts +27 -0
- package/dist/sync/index.d.ts +214 -0
- package/dist/sync/index.js +881 -0
- package/dist/sync/index.js.map +1 -0
- package/dist/worklet-loader-BabwPALw.d.ts +41 -0
- package/dist/worklet-loader-f741D1tk.js +160 -0
- package/dist/worklet-loader-f741D1tk.js.map +1 -0
- package/dist/worklets/couch-live.d.ts +1 -0
- package/dist/worklets/couch-live.js +283 -0
- package/dist/worklets/couch-live.js.map +1 -0
- package/dist/worklets/meter.d.ts +7 -0
- package/dist/worklets/meter.js +74 -0
- package/dist/worklets/meter.js.map +1 -0
- package/dist/worklets/pcm-capture.d.ts +6 -0
- package/dist/worklets/pcm-capture.js +52 -0
- package/dist/worklets/pcm-capture.js.map +1 -0
- package/package.json +114 -4
|
@@ -0,0 +1,1209 @@
|
|
|
1
|
+
import { Context, Duration, Effect, Fiber, Layer, Option, Result, Schedule, Scope } from "effect";
|
|
2
|
+
import { a as AudioPlaybackError, l as AudioUnsupportedError, n as AudioDecodeError, t as AudioCaptureError } from "../errors-BT9HxDLn.js";
|
|
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";
|
|
6
|
+
// src/playback/audio-context.ts
|
|
7
|
+
var AudioContextService = class extends Context.Service()("@avoid.quest/audio/AudioContextService") {};
|
|
8
|
+
function createAudioContextOptions(options = {}) {
|
|
9
|
+
const sampleRate = options.sampleRate ?? 48e3;
|
|
10
|
+
const latencyHint = options.isMobile ? 128 / sampleRate : 0;
|
|
11
|
+
return options.isFirefox ? { latencyHint } : {
|
|
12
|
+
latencyHint,
|
|
13
|
+
sampleRate
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
function normalizeAudioContextState(state) {
|
|
17
|
+
return state === "running" || state === "closed" ? state : "suspended";
|
|
18
|
+
}
|
|
19
|
+
const normalizedState = (ctx) => normalizeAudioContextState(ctx.state);
|
|
20
|
+
function snapshotAudioContext(context) {
|
|
21
|
+
const ext = context;
|
|
22
|
+
return {
|
|
23
|
+
baseLatency: typeof context.baseLatency === "number" ? context.baseLatency : void 0,
|
|
24
|
+
currentTime: context.currentTime,
|
|
25
|
+
outputLatency: typeof ext.outputLatency === "number" ? ext.outputLatency : void 0,
|
|
26
|
+
sampleRate: context.sampleRate,
|
|
27
|
+
state: normalizedState(context)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const pendingResumes = /* @__PURE__ */ new WeakMap();
|
|
31
|
+
function resumeDeduplicated(context) {
|
|
32
|
+
const existing = pendingResumes.get(context);
|
|
33
|
+
if (existing) return existing;
|
|
34
|
+
try {
|
|
35
|
+
const promise = Promise.resolve(context.resume()).finally(() => {
|
|
36
|
+
pendingResumes.delete(context);
|
|
37
|
+
});
|
|
38
|
+
pendingResumes.set(context, promise);
|
|
39
|
+
return promise;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
return Promise.reject(error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function ensureAudioContextRunning(context) {
|
|
45
|
+
return Effect.tryPromise({
|
|
46
|
+
catch: (error) => new AudioPlaybackError({
|
|
47
|
+
cause: String(error),
|
|
48
|
+
code: "CONTEXT_RESUME_FAILED",
|
|
49
|
+
message: `Failed to resume AudioContext: ${String(error)}`,
|
|
50
|
+
recoverable: true
|
|
51
|
+
}),
|
|
52
|
+
try: async () => {
|
|
53
|
+
const state = normalizedState(context);
|
|
54
|
+
if (state === "running") return;
|
|
55
|
+
if (state === "closed") throw new Error("AudioContext is closed.");
|
|
56
|
+
await resumeDeduplicated(context);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
const GESTURE_EVENTS = [
|
|
61
|
+
"touchstart",
|
|
62
|
+
"touchend",
|
|
63
|
+
"click",
|
|
64
|
+
"keydown"
|
|
65
|
+
];
|
|
66
|
+
const noop = () => {};
|
|
67
|
+
function attachGestureUnlock(context, target = globalThis.window) {
|
|
68
|
+
const isTerminal = () => normalizedState(context) !== "suspended";
|
|
69
|
+
if (!target || isTerminal()) return noop;
|
|
70
|
+
const hasStateChange = typeof context.addEventListener === "function" && typeof context.removeEventListener === "function";
|
|
71
|
+
let cleaned = false;
|
|
72
|
+
const cleanup = () => {
|
|
73
|
+
if (cleaned) return;
|
|
74
|
+
cleaned = true;
|
|
75
|
+
for (const ev of GESTURE_EVENTS) target.removeEventListener(ev, onGesture);
|
|
76
|
+
if (hasStateChange) context.removeEventListener("statechange", onStateChange);
|
|
77
|
+
};
|
|
78
|
+
const onStateChange = () => {
|
|
79
|
+
if (isTerminal()) cleanup();
|
|
80
|
+
};
|
|
81
|
+
const onGesture = () => {
|
|
82
|
+
if (cleaned || isTerminal()) {
|
|
83
|
+
cleanup();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
Promise.resolve(context.resume()).then(() => {
|
|
88
|
+
onStateChange();
|
|
89
|
+
return true;
|
|
90
|
+
}).catch(() => false);
|
|
91
|
+
} catch {}
|
|
92
|
+
};
|
|
93
|
+
for (const ev of GESTURE_EVENTS) target.addEventListener(ev, onGesture, { passive: true });
|
|
94
|
+
if (hasStateChange) context.addEventListener("statechange", onStateChange);
|
|
95
|
+
return cleanup;
|
|
96
|
+
}
|
|
97
|
+
function closeContextSafely(context) {
|
|
98
|
+
return Effect.tryPromise({
|
|
99
|
+
catch: () => "CLOSE_FAILED",
|
|
100
|
+
try: async () => {
|
|
101
|
+
if (normalizedState(context) !== "closed") await context.close?.();
|
|
102
|
+
}
|
|
103
|
+
}).pipe(Effect.catch(() => Effect.void));
|
|
104
|
+
}
|
|
105
|
+
function resolveContext(options) {
|
|
106
|
+
if (options.context) return Effect.succeed(options.context);
|
|
107
|
+
const ctxOpts = createAudioContextOptions(options);
|
|
108
|
+
const { createContext } = options;
|
|
109
|
+
if (createContext) return Effect.sync(() => createContext(ctxOpts));
|
|
110
|
+
const g = globalThis;
|
|
111
|
+
const Ctor = g.AudioContext ?? g.webkitAudioContext;
|
|
112
|
+
return typeof Ctor === "function" ? Effect.sync(() => new Ctor(ctxOpts)) : Effect.fail(new AudioUnsupportedError({
|
|
113
|
+
feature: "AudioContext",
|
|
114
|
+
message: "AudioContext is not supported in this environment."
|
|
115
|
+
}));
|
|
116
|
+
}
|
|
117
|
+
function acquireAudioContext(options = {}) {
|
|
118
|
+
const shouldClose = options.closeOnRelease ?? options.context === void 0;
|
|
119
|
+
return Effect.uninterruptible(Effect.gen(function* () {
|
|
120
|
+
const scope = yield* Scope.Scope;
|
|
121
|
+
const context = yield* resolveContext(options);
|
|
122
|
+
const detachUnlock = options.unlockOnGesture ?? true ? attachGestureUnlock(context, options.unlockTarget) : noop;
|
|
123
|
+
const close = () => Effect.sync(detachUnlock).pipe(Effect.andThen(closeContextSafely(context)));
|
|
124
|
+
yield* Scope.addFinalizer(scope, shouldClose ? close() : Effect.sync(detachUnlock));
|
|
125
|
+
return {
|
|
126
|
+
close,
|
|
127
|
+
context,
|
|
128
|
+
ensureRunning: () => ensureAudioContextRunning(context),
|
|
129
|
+
getSnapshot: () => snapshotAudioContext(context)
|
|
130
|
+
};
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
function makeAudioContextLayer(options = {}) {
|
|
134
|
+
return Layer.effect(AudioContextService, acquireAudioContext(options));
|
|
135
|
+
}
|
|
136
|
+
// src/playback/input-capture.ts
|
|
137
|
+
const stopTracks = (stream) => {
|
|
138
|
+
for (const track of stream.getTracks()) track.stop();
|
|
139
|
+
};
|
|
140
|
+
const capErr = (code, message, cancelled) => new AudioCaptureError({
|
|
141
|
+
cancelled,
|
|
142
|
+
code,
|
|
143
|
+
message
|
|
144
|
+
});
|
|
145
|
+
const mapCapErr = (error, fallbackCode, prefix) => {
|
|
146
|
+
if (error instanceof AudioCaptureError) return error;
|
|
147
|
+
const name = error instanceof Error ? error.name : "";
|
|
148
|
+
return capErr(name || fallbackCode, `${prefix}: ${String(error)}`, name === "NotAllowedError" || name === "AbortError");
|
|
149
|
+
};
|
|
150
|
+
function acquireStreamWithAbort(requestStream, userSignal, abortMessage, fallbackCode, prefix) {
|
|
151
|
+
const abortFail = () => Effect.fail(capErr("ABORTED", abortMessage, true));
|
|
152
|
+
return Effect.callback((resume, effectSignal) => {
|
|
153
|
+
const isAborted = () => effectSignal.aborted || userSignal?.aborted === true;
|
|
154
|
+
if (isAborted()) {
|
|
155
|
+
resume(abortFail());
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
let settled = false;
|
|
159
|
+
let pending;
|
|
160
|
+
try {
|
|
161
|
+
pending = requestStream();
|
|
162
|
+
} catch (error) {
|
|
163
|
+
resume(Effect.fail(mapCapErr(error, fallbackCode, prefix)));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const settle = (out) => {
|
|
167
|
+
if (settled) return;
|
|
168
|
+
settled = true;
|
|
169
|
+
effectSignal.removeEventListener("abort", onAbort);
|
|
170
|
+
userSignal?.removeEventListener("abort", onAbort);
|
|
171
|
+
resume(out);
|
|
172
|
+
};
|
|
173
|
+
const onAbort = () => {
|
|
174
|
+
settle(abortFail());
|
|
175
|
+
};
|
|
176
|
+
effectSignal.addEventListener("abort", onAbort, { once: true });
|
|
177
|
+
userSignal?.addEventListener("abort", onAbort, { once: true });
|
|
178
|
+
(async () => {
|
|
179
|
+
try {
|
|
180
|
+
const stream = await pending;
|
|
181
|
+
if (settled || isAborted()) {
|
|
182
|
+
stopTracks(stream);
|
|
183
|
+
settle(abortFail());
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
settle(Effect.succeed(stream));
|
|
187
|
+
} catch (error) {
|
|
188
|
+
settle(Effect.fail(mapCapErr(error, fallbackCode, prefix)));
|
|
189
|
+
}
|
|
190
|
+
})();
|
|
191
|
+
return Effect.sync(onAbort);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
const DISPLAY_CONSTRAINTS = {
|
|
195
|
+
audio: {
|
|
196
|
+
autoGainControl: false,
|
|
197
|
+
echoCancellation: false,
|
|
198
|
+
noiseSuppression: false,
|
|
199
|
+
restrictOwnAudio: true,
|
|
200
|
+
suppressLocalAudioPlayback: true
|
|
201
|
+
},
|
|
202
|
+
monitorTypeSurfaces: "exclude",
|
|
203
|
+
selfBrowserSurface: "exclude",
|
|
204
|
+
surfaceSwitching: "exclude",
|
|
205
|
+
systemAudio: "exclude",
|
|
206
|
+
video: {
|
|
207
|
+
displaySurface: "browser",
|
|
208
|
+
frameRate: 1
|
|
209
|
+
},
|
|
210
|
+
windowAudio: "exclude"
|
|
211
|
+
};
|
|
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")) {
|
|
218
|
+
stopTracks(stream);
|
|
219
|
+
return yield* Effect.fail(capErr("NO_AUDIO_TRACK", "No live audio track."));
|
|
220
|
+
}
|
|
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
|
+
function resolveInputStream(options) {
|
|
232
|
+
if (options.signal?.aborted) return Effect.fail(capErr("ABORTED", "Input capture cancelled.", true));
|
|
233
|
+
if (options.stream) return Effect.succeed(options.stream);
|
|
234
|
+
const devices = options.mediaDevices ?? globalThis.navigator?.mediaDevices;
|
|
235
|
+
if (typeof devices?.getUserMedia !== "function") return Effect.fail(capErr("UNSUPPORTED", "getUserMedia unavailable."));
|
|
236
|
+
return acquireStreamWithAbort(() => devices.getUserMedia({
|
|
237
|
+
audio: {
|
|
238
|
+
autoGainControl: false,
|
|
239
|
+
channelCount: { ideal: options.channelCount ?? 2 },
|
|
240
|
+
echoCancellation: false,
|
|
241
|
+
noiseSuppression: false,
|
|
242
|
+
...options.deviceId ? { deviceId: { exact: options.deviceId } } : {}
|
|
243
|
+
},
|
|
244
|
+
video: false
|
|
245
|
+
}), options.signal, "Input capture cancelled.", "INPUT_CAPTURE_FAILED", "Input capture failed");
|
|
246
|
+
}
|
|
247
|
+
function buildCaptureGraph(context, stream, options) {
|
|
248
|
+
const live = stream.getAudioTracks().filter((t) => t.readyState === "live");
|
|
249
|
+
if (live.length === 0) throw capErr("NO_AUDIO_TRACK", "Stream has no live audio track.");
|
|
250
|
+
const sourceNode = context.createMediaStreamSource(stream);
|
|
251
|
+
const outputNode = context.createGain();
|
|
252
|
+
const detected = live[0]?.getSettings().channelCount ?? options.channelCount ?? 2;
|
|
253
|
+
const sel = options.channelSelection;
|
|
254
|
+
const outputChannelCount = detected === 1 || sel !== void 0 && sel.left === sel.right ? 1 : 2;
|
|
255
|
+
outputNode.channelCount = outputChannelCount;
|
|
256
|
+
outputNode.channelCountMode = "explicit";
|
|
257
|
+
let splitter;
|
|
258
|
+
let merger;
|
|
259
|
+
if (sel === void 0 || detected <= 2 && sel.left === 0 && sel.right === 1) sourceNode.connect(outputNode);
|
|
260
|
+
else {
|
|
261
|
+
splitter = context.createChannelSplitter(Math.max(2, detected, sel.left + 1, sel.right + 1));
|
|
262
|
+
merger = context.createChannelMerger(outputChannelCount);
|
|
263
|
+
sourceNode.connect(splitter);
|
|
264
|
+
splitter.connect(merger, sel.left, 0);
|
|
265
|
+
if (outputChannelCount === 2) splitter.connect(merger, sel.right, 1);
|
|
266
|
+
merger.connect(outputNode);
|
|
267
|
+
}
|
|
268
|
+
let stopped = false;
|
|
269
|
+
const onEnded = () => {
|
|
270
|
+
stop();
|
|
271
|
+
options.onEnded?.();
|
|
272
|
+
};
|
|
273
|
+
const stop = () => {
|
|
274
|
+
if (stopped) return;
|
|
275
|
+
stopped = true;
|
|
276
|
+
for (const t of stream.getAudioTracks()) t.removeEventListener("ended", onEnded);
|
|
277
|
+
sourceNode.disconnect();
|
|
278
|
+
splitter?.disconnect();
|
|
279
|
+
merger?.disconnect();
|
|
280
|
+
outputNode.disconnect();
|
|
281
|
+
stopTracks(stream);
|
|
282
|
+
};
|
|
283
|
+
for (const t of stream.getAudioTracks()) t.addEventListener("ended", onEnded, { once: true });
|
|
284
|
+
return {
|
|
285
|
+
outputChannelCount,
|
|
286
|
+
outputNode,
|
|
287
|
+
sourceNode,
|
|
288
|
+
stop,
|
|
289
|
+
stream
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
function acquireInputCapture(context, options = {}) {
|
|
293
|
+
return Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
294
|
+
const scope = yield* Scope.Scope;
|
|
295
|
+
const stream = yield* restore(resolveInputStream(options));
|
|
296
|
+
const capture = yield* Effect.try({
|
|
297
|
+
catch: (err) => {
|
|
298
|
+
stopTracks(stream);
|
|
299
|
+
return mapCapErr(err, "INPUT_CAPTURE_FAILED", "Input capture failed");
|
|
300
|
+
},
|
|
301
|
+
try: () => {
|
|
302
|
+
if (options.signal?.aborted) throw capErr("ABORTED", "Input capture cancelled.", true);
|
|
303
|
+
return buildCaptureGraph(context, stream, options);
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
yield* Scope.addFinalizer(scope, Effect.sync(capture.stop));
|
|
307
|
+
return capture;
|
|
308
|
+
}));
|
|
309
|
+
}
|
|
310
|
+
// src/playback/media-engine-utils.ts
|
|
311
|
+
const MIN_PLAYBACK_RATE = .5;
|
|
312
|
+
const MAX_PLAYBACK_RATE = 2;
|
|
313
|
+
const DEFAULT_MEDIA_READY_TIMEOUT_MS = 2e4;
|
|
314
|
+
const DEFAULT_STALL_WATCHDOG_MS = 6e3;
|
|
315
|
+
const DEFAULT_MAX_RECOVERY_DELAY_MS = 3e4;
|
|
316
|
+
const clampPlaybackRate = (rate) => clampFinite(rate, MIN_PLAYBACK_RATE, 2, 1);
|
|
317
|
+
function applyPreservesPitch(element, preserve) {
|
|
318
|
+
const ext = element;
|
|
319
|
+
if ("preservesPitch" in ext) ext.preservesPitch = preserve;
|
|
320
|
+
if ("webkitPreservesPitch" in ext) ext.webkitPreservesPitch = preserve;
|
|
321
|
+
return preserve;
|
|
322
|
+
}
|
|
323
|
+
function isHlsUrl(url, depth = 0) {
|
|
324
|
+
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);
|
|
329
|
+
} catch {
|
|
330
|
+
return url.toLowerCase().includes(".m3u8");
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
const isWebKitBrowser = (ua = globalThis.navigator?.userAgent) => Boolean(ua && /safari/iu.test(ua) && !/chrome|chromium|crios|fxios|edg|opr/iu.test(ua));
|
|
334
|
+
function shouldUseNativeHls(element, allowNativeHls = true, userAgent) {
|
|
335
|
+
if (!allowNativeHls || !isWebKitBrowser(userAgent)) return false;
|
|
336
|
+
const s = element.canPlayType("application/vnd.apple.mpegurl");
|
|
337
|
+
return s === "probably" || s === "maybe";
|
|
338
|
+
}
|
|
339
|
+
const computeStallBackoffMs = (attempt, base = 1e3, max = DEFAULT_MAX_RECOVERY_DELAY_MS) => attempt <= 0 ? 0 : Math.min(base * 2 ** Math.min(attempt - 1, 10), max);
|
|
340
|
+
function createStallRecoverySchedule(config = {}) {
|
|
341
|
+
const base = config.baseDelayMs ?? 1e3;
|
|
342
|
+
const max = config.maxDelayMs ?? 3e4;
|
|
343
|
+
return Schedule.recurs(config.maxAttempts ?? 5).pipe(Schedule.modifyDelay(({ attempt }) => Effect.succeed(Duration.millis(computeStallBackoffMs(attempt, base, max)))));
|
|
344
|
+
}
|
|
345
|
+
const pbErr = (code, message, recoverable, cause) => new AudioPlaybackError({
|
|
346
|
+
cause,
|
|
347
|
+
code,
|
|
348
|
+
message,
|
|
349
|
+
recoverable
|
|
350
|
+
});
|
|
351
|
+
const failSuperseded = () => Effect.fail(pbErr("MEDIA_LOAD_SUPERSEDED", "Media load superseded.", true));
|
|
352
|
+
const hasEventTarget = (el) => typeof el.addEventListener === "function" && typeof el.removeEventListener === "function";
|
|
353
|
+
function bindEvents(target, entries, opts) {
|
|
354
|
+
for (const [type, fn] of entries) target.addEventListener(type, fn, opts);
|
|
355
|
+
return () => {
|
|
356
|
+
for (const [type, fn] of entries) target.removeEventListener(type, fn);
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
function createRecoveryRunner(scope, schedule) {
|
|
360
|
+
let step;
|
|
361
|
+
let fiber;
|
|
362
|
+
return {
|
|
363
|
+
stop: () => {
|
|
364
|
+
fiber?.interruptUnsafe();
|
|
365
|
+
fiber = void 0;
|
|
366
|
+
step = void 0;
|
|
367
|
+
},
|
|
368
|
+
trigger: (isStale, onRetry, onExhausted) => {
|
|
369
|
+
if (isStale() || fiber !== void 0) return;
|
|
370
|
+
fiber = Fiber.runIn(scope)(Effect.runFork(Effect.gen(function* () {
|
|
371
|
+
step ??= yield* Schedule.toStepWithSleep(schedule);
|
|
372
|
+
const attempt = yield* step(void 0).pipe(Effect.option);
|
|
373
|
+
if (isStale()) return;
|
|
374
|
+
if (Option.isNone(attempt)) {
|
|
375
|
+
step = void 0;
|
|
376
|
+
onExhausted();
|
|
377
|
+
} else yield* onRetry();
|
|
378
|
+
}).pipe(Effect.ensuring(Effect.sync(() => {
|
|
379
|
+
fiber = void 0;
|
|
380
|
+
})))));
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
// src/playback/media-engine-hls.ts
|
|
385
|
+
const DEFAULT_HLS_CONFIG = {
|
|
386
|
+
capLevelOnFPSDrop: true,
|
|
387
|
+
liveDurationInfinity: true,
|
|
388
|
+
liveMaxLatencyDurationCount: 10,
|
|
389
|
+
liveSyncDurationCount: 4,
|
|
390
|
+
lowLatencyMode: false,
|
|
391
|
+
maxBufferLength: 60,
|
|
392
|
+
maxMaxBufferLength: 120
|
|
393
|
+
};
|
|
394
|
+
function attachHlsInstance(HlsCtor, element, url, baseConfig, loadOptions, hlsRecovery, isActive, onReady, onStreamError) {
|
|
395
|
+
const hls = new HlsCtor({
|
|
396
|
+
...DEFAULT_HLS_CONFIG,
|
|
397
|
+
startPosition: loadOptions.startPositionSeconds ?? -1,
|
|
398
|
+
...baseConfig,
|
|
399
|
+
...loadOptions.hlsConfig
|
|
400
|
+
});
|
|
401
|
+
let mediaRecoveryAttempted = false;
|
|
402
|
+
hls.on(HlsCtor.Events.MANIFEST_PARSED, onReady);
|
|
403
|
+
hls.on(HlsCtor.Events.FRAG_LOADED, () => {
|
|
404
|
+
onReady();
|
|
405
|
+
hlsRecovery.stop();
|
|
406
|
+
});
|
|
407
|
+
hls.on(HlsCtor.Events.ERROR, (_event, data) => {
|
|
408
|
+
if (!data.fatal || !isActive(hls)) return;
|
|
409
|
+
const details = String(data.details);
|
|
410
|
+
const reportFatal = () => onStreamError?.(element.currentTime, pbErr(`HLS_${details}`, `Fatal HLS error: ${details}`, false));
|
|
411
|
+
if (data.type === HlsCtor.ErrorTypes.NETWORK_ERROR) hlsRecovery.trigger(() => !isActive(hls), () => Effect.sync(() => hls.startLoad()), reportFatal);
|
|
412
|
+
else if (data.type === HlsCtor.ErrorTypes.MEDIA_ERROR && !mediaRecoveryAttempted) {
|
|
413
|
+
mediaRecoveryAttempted = true;
|
|
414
|
+
hls.recoverMediaError();
|
|
415
|
+
} else reportFatal();
|
|
416
|
+
});
|
|
417
|
+
hls.attachMedia(element);
|
|
418
|
+
hls.loadSource(url);
|
|
419
|
+
return hls;
|
|
420
|
+
}
|
|
421
|
+
function waitForMediaReady(element, timeoutMs, isStale, hasMetadata, registerCancel, hls, manifestEvent) {
|
|
422
|
+
if (isStale()) return failSuperseded();
|
|
423
|
+
if (hasMetadata() || !hasEventTarget(element)) return Effect.void;
|
|
424
|
+
return Effect.callback((resume) => {
|
|
425
|
+
let settled = false;
|
|
426
|
+
const cleanup = () => {
|
|
427
|
+
unbind();
|
|
428
|
+
if (hls && manifestEvent) hls.off(manifestEvent, onReady);
|
|
429
|
+
unregisterCancel();
|
|
430
|
+
};
|
|
431
|
+
const settle = (e) => {
|
|
432
|
+
if (settled) return;
|
|
433
|
+
settled = true;
|
|
434
|
+
cleanup();
|
|
435
|
+
resume(e);
|
|
436
|
+
};
|
|
437
|
+
const onReady = () => settle(isStale() ? failSuperseded() : Effect.void);
|
|
438
|
+
const onError = () => settle(isStale() ? failSuperseded() : Effect.fail(pbErr("MEDIA_LOAD_ERROR", "Media load error.", true)));
|
|
439
|
+
const unregisterCancel = registerCancel(() => settle(failSuperseded()));
|
|
440
|
+
const unbind = bindEvents(element, [
|
|
441
|
+
["loadedmetadata", onReady],
|
|
442
|
+
["canplay", onReady],
|
|
443
|
+
["playing", onReady],
|
|
444
|
+
["error", onError]
|
|
445
|
+
], { once: true });
|
|
446
|
+
if (hls && manifestEvent) hls.on(manifestEvent, onReady);
|
|
447
|
+
return Effect.sync(() => {
|
|
448
|
+
settled = true;
|
|
449
|
+
cleanup();
|
|
450
|
+
});
|
|
451
|
+
}).pipe(Effect.timeoutOrElse({
|
|
452
|
+
duration: Duration.millis(Math.max(1, timeoutMs)),
|
|
453
|
+
orElse: () => Effect.fail(pbErr("MEDIA_READY_TIMEOUT", `Media not ready within ${timeoutMs} ms.`, true))
|
|
454
|
+
}));
|
|
455
|
+
}
|
|
456
|
+
function forkReadyWatchdog(scope, ready, onFailure) {
|
|
457
|
+
return Fiber.runIn(scope)(Effect.runFork(ready.pipe(Effect.match({
|
|
458
|
+
onFailure,
|
|
459
|
+
onSuccess: () => {}
|
|
460
|
+
}))));
|
|
461
|
+
}
|
|
462
|
+
const applySeekSafe = (element, sec) => {
|
|
463
|
+
if (!Number.isFinite(sec) || sec < 0) return;
|
|
464
|
+
try {
|
|
465
|
+
element.currentTime = sec;
|
|
466
|
+
} catch {}
|
|
467
|
+
};
|
|
468
|
+
function scheduleElementSeek(element, sec, hasMetadata, isDisposed) {
|
|
469
|
+
if (sec === void 0 || !Number.isFinite(sec) || sec <= 0) return;
|
|
470
|
+
if (hasMetadata() || !hasEventTarget(element)) {
|
|
471
|
+
applySeekSafe(element, sec);
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
const clear = () => unbind();
|
|
475
|
+
const unbind = bindEvents(element, [["loadedmetadata", () => {
|
|
476
|
+
unbind();
|
|
477
|
+
if (!isDisposed()) applySeekSafe(element, sec);
|
|
478
|
+
}], ["error", clear]], { once: true });
|
|
479
|
+
return unbind;
|
|
480
|
+
}
|
|
481
|
+
function createStallWatchdog(element, stallWatchdogMs, stallRecovery, getState, recoverStall, onStall, onStreamError) {
|
|
482
|
+
let timer;
|
|
483
|
+
let lastProgress = element.currentTime;
|
|
484
|
+
const clear = () => {
|
|
485
|
+
if (timer !== void 0) {
|
|
486
|
+
clearTimeout(timer);
|
|
487
|
+
timer = void 0;
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
const arm = () => {
|
|
491
|
+
const s = getState();
|
|
492
|
+
if (s.disposed || stallWatchdogMs <= 0 || timer !== void 0 || element.paused || !s.hasUrl) return;
|
|
493
|
+
const { gen } = s;
|
|
494
|
+
const stallTime = element.currentTime;
|
|
495
|
+
timer = setTimeout(() => {
|
|
496
|
+
timer = void 0;
|
|
497
|
+
const cur = getState();
|
|
498
|
+
if (cur.disposed || cur.gen !== gen || element.paused || !cur.hasUrl) return;
|
|
499
|
+
if (element.currentTime !== stallTime) {
|
|
500
|
+
lastProgress = element.currentTime;
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
onStall?.(element.currentTime);
|
|
504
|
+
stallRecovery.trigger(() => {
|
|
505
|
+
const st = getState();
|
|
506
|
+
return st.disposed || st.gen !== gen;
|
|
507
|
+
}, () => recoverStall(gen), () => onStreamError?.(element.currentTime, pbErr("STALL_TIMEOUT", "Stall recovery exhausted.", false)));
|
|
508
|
+
}, stallWatchdogMs);
|
|
509
|
+
};
|
|
510
|
+
const onProgress = () => {
|
|
511
|
+
lastProgress = element.currentTime;
|
|
512
|
+
clear();
|
|
513
|
+
stallRecovery.stop();
|
|
514
|
+
};
|
|
515
|
+
const unbind = hasEventTarget(element) ? bindEvents(element, [
|
|
516
|
+
["waiting", arm],
|
|
517
|
+
["stalled", arm],
|
|
518
|
+
["playing", onProgress],
|
|
519
|
+
["canplay", onProgress],
|
|
520
|
+
["timeupdate", () => {
|
|
521
|
+
if (element.currentTime !== lastProgress) onProgress();
|
|
522
|
+
}],
|
|
523
|
+
["pause", clear],
|
|
524
|
+
["ended", clear],
|
|
525
|
+
["emptied", clear]
|
|
526
|
+
]) : void 0;
|
|
527
|
+
return {
|
|
528
|
+
arm,
|
|
529
|
+
clear,
|
|
530
|
+
detach: () => {
|
|
531
|
+
clear();
|
|
532
|
+
unbind?.();
|
|
533
|
+
},
|
|
534
|
+
resetProgress: () => {
|
|
535
|
+
lastProgress = element.currentTime;
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
// src/playback/media-engine.ts
|
|
540
|
+
function buildMediaEngine(scope, options) {
|
|
541
|
+
const { element } = options;
|
|
542
|
+
const readyTimeoutDefault = options.mediaReadyTimeoutMs ?? 2e4;
|
|
543
|
+
const stallWatchdogMs = options.stallWatchdogMs ?? 6e3;
|
|
544
|
+
const recoverySchedule = createStallRecoverySchedule(options.stallRecovery);
|
|
545
|
+
const loadHlsModule = options.loadHls ?? (() => import("hls.js"));
|
|
546
|
+
let hlsInstance;
|
|
547
|
+
let currentUrl;
|
|
548
|
+
let mode = "idle";
|
|
549
|
+
let playbackRate = clampPlaybackRate(element.playbackRate || 1);
|
|
550
|
+
let preservesPitch = true;
|
|
551
|
+
let disposed = false;
|
|
552
|
+
let loadGeneration = 0;
|
|
553
|
+
let pendingSeekCleanup;
|
|
554
|
+
let readyWatchdogFiber;
|
|
555
|
+
let cancelPendingReadyWait;
|
|
556
|
+
const hlsRecovery = createRecoveryRunner(scope, recoverySchedule);
|
|
557
|
+
const stallRecovery = createRecoveryRunner(scope, recoverySchedule);
|
|
558
|
+
const hasMetadata = () => typeof element.readyState === "number" && element.readyState >= 1;
|
|
559
|
+
const applyRate = () => {
|
|
560
|
+
element.defaultPlaybackRate = playbackRate;
|
|
561
|
+
element.playbackRate = playbackRate;
|
|
562
|
+
};
|
|
563
|
+
const syncRateAndPitch = () => {
|
|
564
|
+
applyRate();
|
|
565
|
+
applyPreservesPitch(element, preservesPitch);
|
|
566
|
+
};
|
|
567
|
+
const clearSeek = () => {
|
|
568
|
+
pendingSeekCleanup?.();
|
|
569
|
+
pendingSeekCleanup = void 0;
|
|
570
|
+
};
|
|
571
|
+
const clearReady = () => {
|
|
572
|
+
readyWatchdogFiber?.interruptUnsafe();
|
|
573
|
+
readyWatchdogFiber = void 0;
|
|
574
|
+
};
|
|
575
|
+
const loadNative = (url, startSec) => {
|
|
576
|
+
element.src = url;
|
|
577
|
+
syncRateAndPitch();
|
|
578
|
+
element.load?.();
|
|
579
|
+
clearSeek();
|
|
580
|
+
pendingSeekCleanup = scheduleElementSeek(element, startSec, hasMetadata, () => disposed);
|
|
581
|
+
};
|
|
582
|
+
const play = () => Effect.tryPromise({
|
|
583
|
+
catch: (error) => {
|
|
584
|
+
const name = error instanceof Error ? error.name : "";
|
|
585
|
+
return pbErr(name || "PLAY_FAILED", `Media play() failed: ${String(error)}`, name === "AbortError" || name === "NotAllowedError", String(error));
|
|
586
|
+
},
|
|
587
|
+
try: async () => {
|
|
588
|
+
applyRate();
|
|
589
|
+
await element.play();
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
const recoverStall = (gen) => Effect.gen(function* () {
|
|
593
|
+
if (mode === "hls.js" && hlsInstance) {
|
|
594
|
+
hlsInstance.startLoad();
|
|
595
|
+
stallWatchdog.arm();
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
if (currentUrl === void 0) return;
|
|
599
|
+
const at = element.currentTime;
|
|
600
|
+
const wasPlaying = !element.paused;
|
|
601
|
+
loadNative(currentUrl, Number.isFinite(at) && at > 0 ? at : void 0);
|
|
602
|
+
if (wasPlaying && !disposed && gen === loadGeneration) {
|
|
603
|
+
yield* play().pipe(Effect.timeoutOption(Duration.millis(Math.max(1, stallWatchdogMs))), Effect.catch(() => Effect.void));
|
|
604
|
+
stallWatchdog.arm();
|
|
605
|
+
}
|
|
606
|
+
});
|
|
607
|
+
const stallWatchdog = createStallWatchdog(element, stallWatchdogMs, stallRecovery, () => ({
|
|
608
|
+
disposed,
|
|
609
|
+
gen: loadGeneration,
|
|
610
|
+
hasUrl: currentUrl !== void 0
|
|
611
|
+
}), recoverStall, options.onStall, options.onStreamError);
|
|
612
|
+
const resetPlayback = () => {
|
|
613
|
+
cancelPendingReadyWait?.();
|
|
614
|
+
cancelPendingReadyWait = void 0;
|
|
615
|
+
clearSeek();
|
|
616
|
+
clearReady();
|
|
617
|
+
stallWatchdog.clear();
|
|
618
|
+
stallRecovery.stop();
|
|
619
|
+
hlsRecovery.stop();
|
|
620
|
+
hlsInstance?.destroy();
|
|
621
|
+
hlsInstance = void 0;
|
|
622
|
+
};
|
|
623
|
+
const load = (url, loadOptions = {}) => Effect.gen(function* () {
|
|
624
|
+
loadGeneration += 1;
|
|
625
|
+
const gen = loadGeneration;
|
|
626
|
+
resetPlayback();
|
|
627
|
+
currentUrl = url;
|
|
628
|
+
stallWatchdog.resetProgress();
|
|
629
|
+
const readyMs = loadOptions.readyTimeoutMs ?? readyTimeoutDefault;
|
|
630
|
+
if (loadOptions.crossOrigin !== void 0) element.crossOrigin = loadOptions.crossOrigin;
|
|
631
|
+
const allowNative = loadOptions.allowNativeHls ?? options.allowNativeHls ?? true;
|
|
632
|
+
const hlsStream = isHlsUrl(url);
|
|
633
|
+
let activeHls;
|
|
634
|
+
let manifestEvent;
|
|
635
|
+
if (hlsStream && !shouldUseNativeHls(element, allowNative, options.userAgent)) {
|
|
636
|
+
const { default: HlsCtor } = yield* Effect.tryPromise({
|
|
637
|
+
catch: (e) => pbErr("HLS_IMPORT_FAILED", `Load hls.js: ${String(e)}`, false, `${e}`),
|
|
638
|
+
try: () => loadHlsModule()
|
|
639
|
+
});
|
|
640
|
+
if (typeof HlsCtor?.isSupported === "function" && HlsCtor.isSupported()) {
|
|
641
|
+
activeHls = attachHlsInstance(HlsCtor, element, url, options.hlsConfig, loadOptions, hlsRecovery, (hls) => !disposed && hlsInstance === hls, clearReady, options.onStreamError);
|
|
642
|
+
hlsInstance = activeHls;
|
|
643
|
+
mode = "hls.js";
|
|
644
|
+
syncRateAndPitch();
|
|
645
|
+
manifestEvent = HlsCtor.Events.MANIFEST_PARSED;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
if (!activeHls) {
|
|
649
|
+
mode = hlsStream ? "native-hls" : "native";
|
|
650
|
+
loadNative(url, loadOptions.startPositionSeconds);
|
|
651
|
+
}
|
|
652
|
+
const ready = waitForMediaReady(element, readyMs, () => disposed || gen !== loadGeneration, hasMetadata, (cancel) => {
|
|
653
|
+
cancelPendingReadyWait = cancel;
|
|
654
|
+
return () => {
|
|
655
|
+
if (cancelPendingReadyWait === cancel) cancelPendingReadyWait = void 0;
|
|
656
|
+
};
|
|
657
|
+
}, activeHls, manifestEvent);
|
|
658
|
+
if (loadOptions.waitForReady) yield* ready;
|
|
659
|
+
else if (readyMs > 0 && !disposed) readyWatchdogFiber = forkReadyWatchdog(scope, ready, (failure) => {
|
|
660
|
+
if (!disposed && gen === loadGeneration && failure.code !== "MEDIA_LOAD_SUPERSEDED" && !hasMetadata()) options.onStreamError?.(element.currentTime, failure);
|
|
661
|
+
});
|
|
662
|
+
});
|
|
663
|
+
const dispose = () => Effect.sync(() => {
|
|
664
|
+
if (disposed) return;
|
|
665
|
+
disposed = true;
|
|
666
|
+
loadGeneration += 1;
|
|
667
|
+
resetPlayback();
|
|
668
|
+
stallWatchdog.detach();
|
|
669
|
+
element.pause();
|
|
670
|
+
element.removeAttribute("src");
|
|
671
|
+
element.load?.();
|
|
672
|
+
mode = "idle";
|
|
673
|
+
currentUrl = void 0;
|
|
674
|
+
});
|
|
675
|
+
return {
|
|
676
|
+
dispose,
|
|
677
|
+
element,
|
|
678
|
+
getSnapshot: () => ({
|
|
679
|
+
currentTime: element.currentTime,
|
|
680
|
+
duration: Number.isFinite(element.duration) ? element.duration : void 0,
|
|
681
|
+
mode,
|
|
682
|
+
muted: element.muted,
|
|
683
|
+
paused: element.paused,
|
|
684
|
+
playbackRate,
|
|
685
|
+
preservesPitch,
|
|
686
|
+
src: currentUrl,
|
|
687
|
+
volume: element.volume
|
|
688
|
+
}),
|
|
689
|
+
load,
|
|
690
|
+
pause: () => Effect.sync(() => {
|
|
691
|
+
stallWatchdog.clear();
|
|
692
|
+
element.pause();
|
|
693
|
+
}),
|
|
694
|
+
play,
|
|
695
|
+
refreshUrl: (url, seekPos) => Effect.gen(function* () {
|
|
696
|
+
const wasPlaying = !element.paused;
|
|
697
|
+
const at = seekPos ?? element.currentTime;
|
|
698
|
+
yield* load(url, { startPositionSeconds: Number.isFinite(at) && at > 0 ? at : void 0 });
|
|
699
|
+
if (wasPlaying) yield* play();
|
|
700
|
+
}),
|
|
701
|
+
runWithStallRecovery: (effect) => effect.pipe(Effect.retry({
|
|
702
|
+
schedule: recoverySchedule,
|
|
703
|
+
while: (err) => err.recoverable !== false
|
|
704
|
+
})),
|
|
705
|
+
seek: (sec) => Effect.sync(() => {
|
|
706
|
+
clearSeek();
|
|
707
|
+
if (Number.isFinite(sec) && sec >= 0) element.currentTime = sec;
|
|
708
|
+
}),
|
|
709
|
+
setMuted: (m) => Effect.sync(() => element.muted = m),
|
|
710
|
+
setPlaybackRate: (rate) => Effect.sync(() => {
|
|
711
|
+
playbackRate = clampPlaybackRate(rate);
|
|
712
|
+
applyRate();
|
|
713
|
+
return playbackRate;
|
|
714
|
+
}),
|
|
715
|
+
setPreservesPitch: (p) => Effect.sync(() => preservesPitch = applyPreservesPitch(element, p)),
|
|
716
|
+
setVolume: (vol) => Effect.sync(() => element.volume = clampFinite(vol, 0, 1, 1))
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
function createMediaEngine(options) {
|
|
720
|
+
return Effect.gen(function* () {
|
|
721
|
+
const scope = yield* Scope.Scope;
|
|
722
|
+
const engine = buildMediaEngine(scope, options);
|
|
723
|
+
yield* Scope.addFinalizer(scope, engine.dispose());
|
|
724
|
+
return engine;
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
// src/playback/media-source.ts
|
|
728
|
+
const elementSources = /* @__PURE__ */ new WeakMap();
|
|
729
|
+
const destinationRouted = /* @__PURE__ */ new WeakSet();
|
|
730
|
+
function sourceError(code, message, cause) {
|
|
731
|
+
return new AudioPlaybackError({
|
|
732
|
+
...cause === void 0 ? {} : { cause: String(cause) },
|
|
733
|
+
code,
|
|
734
|
+
message,
|
|
735
|
+
recoverable: false
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Returns the memoized `MediaElementAudioSourceNode` for a `MediaEngine` or
|
|
740
|
+
* media element (browsers allow only one per element), so live playback can
|
|
741
|
+
* feed `acquirePcmCapture`, meters, or effects. Requesting it for another
|
|
742
|
+
* `AudioContext` fails with `MEDIA_SOURCE_CONTEXT_MISMATCH`. Cross-origin
|
|
743
|
+
* media needs CORS + `crossOrigin: "anonymous"`, otherwise the graph is silent.
|
|
744
|
+
*/
|
|
745
|
+
function getMediaElementSourceNode(context, target, options = {}) {
|
|
746
|
+
return Effect.suspend(() => {
|
|
747
|
+
const element = "element" in target ? target.element : target;
|
|
748
|
+
let node = elementSources.get(element);
|
|
749
|
+
if (node && node.context !== context) return Effect.fail(sourceError("MEDIA_SOURCE_CONTEXT_MISMATCH", "This media element is already bound to a different AudioContext."));
|
|
750
|
+
if (!node) {
|
|
751
|
+
try {
|
|
752
|
+
node = context.createMediaElementSource(element);
|
|
753
|
+
} catch (error) {
|
|
754
|
+
return Effect.fail(sourceError("MEDIA_SOURCE_FAILED", "Failed to create a MediaElementAudioSourceNode.", error));
|
|
755
|
+
}
|
|
756
|
+
elementSources.set(element, node);
|
|
757
|
+
}
|
|
758
|
+
const connect = options.connectToDestination ?? true;
|
|
759
|
+
if (connect !== destinationRouted.has(node)) {
|
|
760
|
+
if (connect) {
|
|
761
|
+
node.connect(context.destination);
|
|
762
|
+
destinationRouted.add(node);
|
|
763
|
+
} else {
|
|
764
|
+
node.disconnect(context.destination);
|
|
765
|
+
destinationRouted.delete(node);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return Effect.succeed(node);
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
// src/worklets/pcm-capture.ts
|
|
772
|
+
const PCM_CAPTURE_PROCESSOR_NAME = "avoid-pcm-capture";
|
|
773
|
+
const PCM_CAPTURE_DEFAULT_CHUNK_FRAMES = 2048;
|
|
774
|
+
/** Main-thread → processor message that ends the processor's lifetime. */
|
|
775
|
+
const PCM_CAPTURE_STOP_MESSAGE = "stop";
|
|
776
|
+
const PCM_CAPTURE_MIN_CHUNK_FRAMES = 128;
|
|
777
|
+
const PCM_CAPTURE_MAX_CHUNK_FRAMES = 16384;
|
|
778
|
+
/** Clamps a requested chunk size to whole frames within `[128, 16384]`. */
|
|
779
|
+
function clampPcmChunkFrames(chunkFrames) {
|
|
780
|
+
if (chunkFrames === void 0 || !Number.isFinite(chunkFrames)) return PCM_CAPTURE_DEFAULT_CHUNK_FRAMES;
|
|
781
|
+
return Math.max(PCM_CAPTURE_MIN_CHUNK_FRAMES, Math.min(PCM_CAPTURE_MAX_CHUNK_FRAMES, Math.round(chunkFrames)));
|
|
782
|
+
}
|
|
783
|
+
if (typeof registerProcessor === "function") registerProcessor(PCM_CAPTURE_PROCESSOR_NAME, class AvoidPcmCaptureProcessor extends AudioWorkletProcessor {
|
|
784
|
+
chunk;
|
|
785
|
+
writeIndex = 0;
|
|
786
|
+
stopped = false;
|
|
787
|
+
constructor(options) {
|
|
788
|
+
super(options);
|
|
789
|
+
this.chunk = new Float32Array(clampPcmChunkFrames(options?.processorOptions?.chunkFrames));
|
|
790
|
+
this.port.addEventListener("message", (event) => {
|
|
791
|
+
if (event.data === "stop") this.stopped = true;
|
|
792
|
+
});
|
|
793
|
+
if (typeof this.port.start === "function") this.port.start();
|
|
794
|
+
}
|
|
795
|
+
process(inputs) {
|
|
796
|
+
if (this.stopped) return false;
|
|
797
|
+
const [input] = inputs;
|
|
798
|
+
const first = input?.[0];
|
|
799
|
+
if (!input || !first || first.length === 0) return true;
|
|
800
|
+
const frames = first.length;
|
|
801
|
+
const channelCount = input.length;
|
|
802
|
+
const scale = 1 / channelCount;
|
|
803
|
+
const { chunk } = this;
|
|
804
|
+
const capacity = chunk.length;
|
|
805
|
+
let { writeIndex } = this;
|
|
806
|
+
for (let i = 0; i < frames; i += 1) {
|
|
807
|
+
let sum = 0;
|
|
808
|
+
for (let channel = 0; channel < channelCount; channel += 1) sum += input[channel]?.[i] ?? 0;
|
|
809
|
+
chunk[writeIndex] = sum * scale;
|
|
810
|
+
writeIndex += 1;
|
|
811
|
+
if (writeIndex === capacity) {
|
|
812
|
+
this.port.postMessage(chunk);
|
|
813
|
+
writeIndex = 0;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
this.writeIndex = writeIndex;
|
|
817
|
+
return true;
|
|
818
|
+
}
|
|
819
|
+
});
|
|
820
|
+
// src/playback/pcm-capture.ts
|
|
821
|
+
/** Loads the standalone `@avoid.quest/audio/worklets/pcm-capture` module. */
|
|
822
|
+
function loadPcmCaptureWorklet(context, options = {}) {
|
|
823
|
+
return loadAudioWorklet(context, {
|
|
824
|
+
...options,
|
|
825
|
+
moduleUrl: options.moduleUrl ?? createWorkletModuleUrl("pcm-capture"),
|
|
826
|
+
processorName: PCM_CAPTURE_PROCESSOR_NAME
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
function bestEffort(run) {
|
|
830
|
+
try {
|
|
831
|
+
run();
|
|
832
|
+
} catch {}
|
|
833
|
+
}
|
|
834
|
+
function buildPcmCapture(context, source, options) {
|
|
835
|
+
const { sampleRate } = context;
|
|
836
|
+
const ring = createPcmRingBuffer({
|
|
837
|
+
maxSeconds: options.maxSeconds,
|
|
838
|
+
sampleRate
|
|
839
|
+
});
|
|
840
|
+
let active = true;
|
|
841
|
+
const node = new globalThis.AudioWorkletNode(context, PCM_CAPTURE_PROCESSOR_NAME, {
|
|
842
|
+
numberOfInputs: 1,
|
|
843
|
+
numberOfOutputs: 1,
|
|
844
|
+
outputChannelCount: [1],
|
|
845
|
+
processorOptions: { chunkFrames: clampPcmChunkFrames(options.chunkFrames) }
|
|
846
|
+
});
|
|
847
|
+
const silentSink = context.createGain();
|
|
848
|
+
silentSink.gain.value = 0;
|
|
849
|
+
const onMessage = (event) => {
|
|
850
|
+
if (active && event.data instanceof Float32Array) {
|
|
851
|
+
ring.push(event.data);
|
|
852
|
+
options.onChunk?.(event.data);
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
const teardown = () => {
|
|
856
|
+
if (!active) return;
|
|
857
|
+
active = false;
|
|
858
|
+
node.port.removeEventListener("message", onMessage);
|
|
859
|
+
bestEffort(() => node.port.postMessage(PCM_CAPTURE_STOP_MESSAGE));
|
|
860
|
+
bestEffort(() => source.disconnect(node));
|
|
861
|
+
node.port.close?.();
|
|
862
|
+
node.disconnect();
|
|
863
|
+
silentSink.disconnect();
|
|
864
|
+
ring.clear();
|
|
865
|
+
};
|
|
866
|
+
try {
|
|
867
|
+
node.port.addEventListener("message", onMessage);
|
|
868
|
+
node.port.start?.();
|
|
869
|
+
source.connect(node);
|
|
870
|
+
node.connect(silentSink);
|
|
871
|
+
silentSink.connect(context.destination);
|
|
872
|
+
} catch (error) {
|
|
873
|
+
teardown();
|
|
874
|
+
throw error;
|
|
875
|
+
}
|
|
876
|
+
const snapshot = (seconds) => ring.snapshot(seconds);
|
|
877
|
+
return [{
|
|
878
|
+
bufferedSeconds: () => ring.bufferedSeconds(),
|
|
879
|
+
capacitySeconds: ring.capacityFrames / sampleRate,
|
|
880
|
+
clear: () => {
|
|
881
|
+
ring.clear();
|
|
882
|
+
},
|
|
883
|
+
fingerprint: (seconds) => Effect.suspend(() => generateShazamSignatureFromFloat32(snapshot(seconds), sampleRate)),
|
|
884
|
+
isActive: () => active,
|
|
885
|
+
node,
|
|
886
|
+
sampleRate,
|
|
887
|
+
snapshot,
|
|
888
|
+
toShazamPcm: (seconds) => prepareShazamPcm(snapshot(seconds), sampleRate)
|
|
889
|
+
}, teardown];
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* Passively taps any `AudioNode` (e.g. from `getMediaElementSourceNode` or
|
|
893
|
+
* `acquireInputCapture`) into a rolling mono PCM window via the allocation-free
|
|
894
|
+
* `pcm-capture` AudioWorklet, so live audio can be fingerprinted with
|
|
895
|
+
* `capture.fingerprint()`. Fully torn down when the owning `Scope` closes.
|
|
896
|
+
*/
|
|
897
|
+
function acquirePcmCapture(context, source, options = {}) {
|
|
898
|
+
return Effect.gen(function* () {
|
|
899
|
+
if (typeof globalThis.AudioWorkletNode !== "function") return yield* Effect.fail(new AudioUnsupportedError({
|
|
900
|
+
feature: "AudioWorkletNode",
|
|
901
|
+
message: "PCM capture requires AudioWorkletNode support."
|
|
902
|
+
}));
|
|
903
|
+
yield* loadPcmCaptureWorklet(context, options.workletOptions);
|
|
904
|
+
const [capture] = yield* Effect.acquireRelease(Effect.try({
|
|
905
|
+
catch: (error) => new AudioCaptureError({
|
|
906
|
+
code: "PCM_CAPTURE_FAILED",
|
|
907
|
+
message: `PCM capture setup failed: ${String(error)}`
|
|
908
|
+
}),
|
|
909
|
+
try: () => buildPcmCapture(context, source, options)
|
|
910
|
+
}), ([, teardown]) => Effect.sync(teardown));
|
|
911
|
+
return capture;
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
// src/playback/media-session.ts
|
|
915
|
+
const SILENT_WAV_SAMPLE_RATE = 8e3;
|
|
916
|
+
const SILENT_WAV_DURATION_SECONDS = 10;
|
|
917
|
+
const SILENT_WAV_HEADER_BYTES = 44;
|
|
918
|
+
const BLUETOOTH_REPLACEMENTS = [
|
|
919
|
+
[/\p{M}/gu, ""],
|
|
920
|
+
[/[\u2010-\u2015\u2212\u00B7\u2022]/gu, "-"],
|
|
921
|
+
[/[\u2018\u2019\u201A\u2032]/gu, "'"],
|
|
922
|
+
[/[\u201C\u201D\u201E\u00AB\u00BB\u2033]/gu, "\""],
|
|
923
|
+
[/\u2026/gu, "..."],
|
|
924
|
+
[/[^\u0020-\u007E]/gu, ""],
|
|
925
|
+
[/\s+/gu, " "]
|
|
926
|
+
];
|
|
927
|
+
function sanitizeForBluetooth(input, fallback = "Radio") {
|
|
928
|
+
if (!input?.trim()) return fallback;
|
|
929
|
+
let out = input.normalize("NFKD");
|
|
930
|
+
for (const [pattern, replacement] of BLUETOOTH_REPLACEMENTS) out = out.replaceAll(pattern, replacement);
|
|
931
|
+
return out.trim() || fallback;
|
|
932
|
+
}
|
|
933
|
+
const writeAscii = (view, offset, text) => {
|
|
934
|
+
for (let i = 0; i < text.length; i += 1) view.setUint8(offset + i, text.codePointAt(i) ?? 0);
|
|
935
|
+
};
|
|
936
|
+
function createSilentWavBytes(durationSeconds = 10, sampleRate = SILENT_WAV_SAMPLE_RATE) {
|
|
937
|
+
const safeDuration = Math.max(1, Math.round(durationSeconds));
|
|
938
|
+
const safeRate = Math.max(8e3, Math.round(sampleRate));
|
|
939
|
+
const dataBytes = safeRate * 2 * safeDuration;
|
|
940
|
+
const buffer = new Uint8Array(44 + dataBytes);
|
|
941
|
+
const view = new DataView(buffer.buffer);
|
|
942
|
+
writeAscii(view, 0, "RIFF");
|
|
943
|
+
view.setUint32(4, 36 + dataBytes, true);
|
|
944
|
+
writeAscii(view, 8, "WAVEfmt ");
|
|
945
|
+
view.setUint32(16, 16, true);
|
|
946
|
+
view.setUint16(20, 1, true);
|
|
947
|
+
view.setUint16(22, 1, true);
|
|
948
|
+
view.setUint32(24, safeRate, true);
|
|
949
|
+
view.setUint32(28, safeRate * 2, true);
|
|
950
|
+
view.setUint16(32, 2, true);
|
|
951
|
+
view.setUint16(34, 16, true);
|
|
952
|
+
writeAscii(view, 36, "data");
|
|
953
|
+
view.setUint32(40, dataBytes, true);
|
|
954
|
+
return buffer;
|
|
955
|
+
}
|
|
956
|
+
function createSilentWavBlob(durationSeconds = 10, sampleRate = SILENT_WAV_SAMPLE_RATE) {
|
|
957
|
+
const bytes = createSilentWavBytes(durationSeconds, sampleRate);
|
|
958
|
+
return new Blob([bytes.buffer], { type: "audio/wav" });
|
|
959
|
+
}
|
|
960
|
+
const INERT_HANDLER = () => {};
|
|
961
|
+
const CORE_ACTIONS = [
|
|
962
|
+
"play",
|
|
963
|
+
"pause",
|
|
964
|
+
"stop"
|
|
965
|
+
];
|
|
966
|
+
const OPTIONAL_ACTIONS = [
|
|
967
|
+
"previoustrack",
|
|
968
|
+
"nexttrack",
|
|
969
|
+
"seekbackward",
|
|
970
|
+
"seekforward",
|
|
971
|
+
"seekto"
|
|
972
|
+
];
|
|
973
|
+
const setActionSafe = (session, action, handler) => {
|
|
974
|
+
try {
|
|
975
|
+
session.setActionHandler(action, handler);
|
|
976
|
+
} catch {}
|
|
977
|
+
};
|
|
978
|
+
function buildMediaSessionController(options) {
|
|
979
|
+
const sanitize = options.sanitizeAvrcp ?? true;
|
|
980
|
+
const fallback = options.avrcpFallback ?? "Radio";
|
|
981
|
+
const session = options.mediaSession ?? globalThis.navigator?.mediaSession;
|
|
982
|
+
let keepAliveAudio;
|
|
983
|
+
let keepAliveUrl;
|
|
984
|
+
const clean = (value, def) => sanitize ? sanitizeForBluetooth(value, def) : value ?? def;
|
|
985
|
+
const stopKeepAlive = () => {
|
|
986
|
+
if (keepAliveAudio) {
|
|
987
|
+
keepAliveAudio.pause();
|
|
988
|
+
keepAliveAudio.removeAttribute("src");
|
|
989
|
+
keepAliveAudio.load?.();
|
|
990
|
+
keepAliveAudio = void 0;
|
|
991
|
+
}
|
|
992
|
+
if (keepAliveUrl) {
|
|
993
|
+
URL.revokeObjectURL(keepAliveUrl);
|
|
994
|
+
keepAliveUrl = void 0;
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
const dispose = () => {
|
|
998
|
+
stopKeepAlive();
|
|
999
|
+
if (typeof session?.setActionHandler === "function") for (const action of [...CORE_ACTIONS, ...OPTIONAL_ACTIONS]) setActionSafe(session, action, null);
|
|
1000
|
+
};
|
|
1001
|
+
return {
|
|
1002
|
+
dispose,
|
|
1003
|
+
setHandlers: (handlers) => {
|
|
1004
|
+
if (typeof session?.setActionHandler !== "function") return;
|
|
1005
|
+
for (const action of CORE_ACTIONS) setActionSafe(session, action, handlers[action] ?? INERT_HANDLER);
|
|
1006
|
+
for (const action of OPTIONAL_ACTIONS) setActionSafe(session, action, handlers[action] ?? null);
|
|
1007
|
+
},
|
|
1008
|
+
setMetadata: (metadata) => {
|
|
1009
|
+
if (!session) return;
|
|
1010
|
+
const payload = {
|
|
1011
|
+
album: metadata.album ? clean(metadata.album, "") : "",
|
|
1012
|
+
artist: metadata.artist ? clean(metadata.artist, "") : "",
|
|
1013
|
+
artwork: metadata.artwork ? [...metadata.artwork] : [],
|
|
1014
|
+
title: clean(metadata.title, fallback)
|
|
1015
|
+
};
|
|
1016
|
+
session.metadata = typeof globalThis.MediaMetadata === "function" ? new globalThis.MediaMetadata(payload) : payload;
|
|
1017
|
+
},
|
|
1018
|
+
setPlaybackState: (state) => {
|
|
1019
|
+
if (session) session.playbackState = state;
|
|
1020
|
+
},
|
|
1021
|
+
setPositionState: (state) => {
|
|
1022
|
+
if (typeof session?.setPositionState !== "function") return;
|
|
1023
|
+
try {
|
|
1024
|
+
if (state.isLive) {
|
|
1025
|
+
session.setPositionState({
|
|
1026
|
+
duration: 0,
|
|
1027
|
+
position: 0
|
|
1028
|
+
});
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
const duration = clampFinite(state.duration ?? 0, 0, Number.POSITIVE_INFINITY, 0);
|
|
1032
|
+
const position = clampFinite(state.position ?? 0, 0, duration, 0);
|
|
1033
|
+
session.setPositionState({
|
|
1034
|
+
duration,
|
|
1035
|
+
playbackRate: state.playbackRate ?? 1,
|
|
1036
|
+
position
|
|
1037
|
+
});
|
|
1038
|
+
} catch {}
|
|
1039
|
+
},
|
|
1040
|
+
startKeepAlive: () => Effect.sync(() => {
|
|
1041
|
+
if (options.enableKeepAlive === false) return;
|
|
1042
|
+
if (!keepAliveAudio) {
|
|
1043
|
+
if (!options.createKeepAliveElement && typeof globalThis.Audio !== "function") return;
|
|
1044
|
+
keepAliveUrl = URL.createObjectURL(createSilentWavBlob());
|
|
1045
|
+
const audio = options.createKeepAliveElement ? options.createKeepAliveElement() : new globalThis.Audio();
|
|
1046
|
+
audio.loop = true;
|
|
1047
|
+
audio.volume = 0;
|
|
1048
|
+
audio.muted = false;
|
|
1049
|
+
audio.src = keepAliveUrl;
|
|
1050
|
+
keepAliveAudio = audio;
|
|
1051
|
+
}
|
|
1052
|
+
keepAliveAudio.play().catch(() => {});
|
|
1053
|
+
}),
|
|
1054
|
+
stopKeepAlive
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
function createMediaSessionController(options = {}) {
|
|
1058
|
+
return Effect.gen(function* () {
|
|
1059
|
+
const controller = buildMediaSessionController(options);
|
|
1060
|
+
yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(controller.dispose));
|
|
1061
|
+
return controller;
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
// src/playback/sampler.ts
|
|
1065
|
+
const SAMPLE_MIME_TYPES = {
|
|
1066
|
+
mp3: "audio/mpeg",
|
|
1067
|
+
ogg: "audio/ogg",
|
|
1068
|
+
wav: "audio/wav"
|
|
1069
|
+
};
|
|
1070
|
+
const SAMPLE_KEY_PATTERN = /^[\w\-./]+\.(?<ext>mp3|wav|ogg)$/u;
|
|
1071
|
+
const SAMPLER_MIN_SLICE_DURATION = .1;
|
|
1072
|
+
const SAMPLER_MAX_SLICE_DURATION = 2;
|
|
1073
|
+
const SAMPLER_RELEASE_SECONDS = 1;
|
|
1074
|
+
const SAMPLER_VOLUME_RAMP_SECONDS = .05;
|
|
1075
|
+
const SAMPLER_DEFAULT_BATCH_SIZE = 4;
|
|
1076
|
+
const stopSourceSafe = (source) => {
|
|
1077
|
+
try {
|
|
1078
|
+
source.stop();
|
|
1079
|
+
} catch {}
|
|
1080
|
+
};
|
|
1081
|
+
function createSampler(context, options = {}) {
|
|
1082
|
+
const buffers = /* @__PURE__ */ new Map();
|
|
1083
|
+
const active = /* @__PURE__ */ new Set();
|
|
1084
|
+
const masterGain = context.createGain();
|
|
1085
|
+
masterGain.gain.value = Math.max(0, Math.min(1, options.initialVolume ?? 1));
|
|
1086
|
+
masterGain.connect(options.destination ?? context.destination);
|
|
1087
|
+
const random = options.random ?? (() => Math.random());
|
|
1088
|
+
const loadBuffer = (key, url) => Effect.tryPromise({
|
|
1089
|
+
catch: (err) => new AudioDecodeError({
|
|
1090
|
+
message: `Failed to load sample "${key}": ${String(err)}`,
|
|
1091
|
+
source: url
|
|
1092
|
+
}),
|
|
1093
|
+
try: async () => {
|
|
1094
|
+
const cached = buffers.get(key);
|
|
1095
|
+
if (cached) return cached;
|
|
1096
|
+
const res = await (options.fetchImpl ?? globalThis.fetch)(url);
|
|
1097
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
1098
|
+
const decoded = await context.decodeAudioData(await res.arrayBuffer());
|
|
1099
|
+
buffers.set(key, decoded);
|
|
1100
|
+
return decoded;
|
|
1101
|
+
}
|
|
1102
|
+
});
|
|
1103
|
+
const playSlice = (key, opts = {}) => {
|
|
1104
|
+
const buffer = buffers.get(key);
|
|
1105
|
+
if (!buffer) return;
|
|
1106
|
+
const now = context.currentTime;
|
|
1107
|
+
const attack = Math.max(0, opts.attackSeconds ?? 0);
|
|
1108
|
+
const release = Math.max(0, opts.releaseSeconds ?? 1);
|
|
1109
|
+
const level = Math.max(0, opts.gain ?? 1);
|
|
1110
|
+
const offset = Math.max(0, Math.min(buffer.duration, opts.offsetSeconds ?? 0));
|
|
1111
|
+
const avail = Math.max(0, buffer.duration - offset);
|
|
1112
|
+
const duration = opts.durationSeconds === void 0 ? Math.max(0, avail - release) : Math.max(0, Math.min(avail, opts.durationSeconds));
|
|
1113
|
+
const source = context.createBufferSource();
|
|
1114
|
+
source.buffer = buffer;
|
|
1115
|
+
if (opts.playbackRate !== void 0 && Number.isFinite(opts.playbackRate) && opts.playbackRate > 0) source.playbackRate.value = opts.playbackRate;
|
|
1116
|
+
const voice = context.createGain();
|
|
1117
|
+
voice.gain.setValueAtTime(attack > 0 ? 0 : level, now);
|
|
1118
|
+
if (attack > 0) voice.gain.linearRampToValueAtTime(level, now + attack);
|
|
1119
|
+
voice.gain.setValueAtTime(level, now + duration);
|
|
1120
|
+
if (release > 0) voice.gain.linearRampToValueAtTime(0, now + duration + release);
|
|
1121
|
+
source.connect(voice);
|
|
1122
|
+
voice.connect(masterGain);
|
|
1123
|
+
active.add(source);
|
|
1124
|
+
let stopped = false;
|
|
1125
|
+
const cleanup = () => {
|
|
1126
|
+
if (stopped) return;
|
|
1127
|
+
stopped = true;
|
|
1128
|
+
active.delete(source);
|
|
1129
|
+
source.disconnect();
|
|
1130
|
+
voice.disconnect();
|
|
1131
|
+
};
|
|
1132
|
+
source.onended = cleanup;
|
|
1133
|
+
source.start(now, offset, duration + release);
|
|
1134
|
+
return {
|
|
1135
|
+
durationSeconds: duration,
|
|
1136
|
+
key,
|
|
1137
|
+
offsetSeconds: offset,
|
|
1138
|
+
stop: () => {
|
|
1139
|
+
if (stopped) return;
|
|
1140
|
+
stopSourceSafe(source);
|
|
1141
|
+
cleanup();
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
};
|
|
1145
|
+
const stopAll = () => {
|
|
1146
|
+
for (const s of active) {
|
|
1147
|
+
stopSourceSafe(s);
|
|
1148
|
+
s.disconnect();
|
|
1149
|
+
}
|
|
1150
|
+
active.clear();
|
|
1151
|
+
};
|
|
1152
|
+
return {
|
|
1153
|
+
activeVoiceCount: () => active.size,
|
|
1154
|
+
dispose: () => {
|
|
1155
|
+
stopAll();
|
|
1156
|
+
masterGain.disconnect();
|
|
1157
|
+
buffers.clear();
|
|
1158
|
+
},
|
|
1159
|
+
getBuffer: (key) => buffers.get(key),
|
|
1160
|
+
keys: () => [...buffers.keys()],
|
|
1161
|
+
loadBatch: (entries, batchSize = 4) => Effect.forEach(entries, (entry) => loadBuffer(entry.key, entry.url).pipe(Effect.result, Effect.map((res) => ({
|
|
1162
|
+
key: entry.key,
|
|
1163
|
+
res
|
|
1164
|
+
}))), { concurrency: Math.max(1, Math.floor(batchSize)) }).pipe(Effect.map((results) => {
|
|
1165
|
+
const loaded = [];
|
|
1166
|
+
const failed = [];
|
|
1167
|
+
for (const { key, res } of results) if (Result.isSuccess(res)) loaded.push(key);
|
|
1168
|
+
else failed.push({
|
|
1169
|
+
error: res.failure.message,
|
|
1170
|
+
key
|
|
1171
|
+
});
|
|
1172
|
+
return {
|
|
1173
|
+
failed,
|
|
1174
|
+
loaded
|
|
1175
|
+
};
|
|
1176
|
+
})),
|
|
1177
|
+
loadBuffer,
|
|
1178
|
+
masterGain,
|
|
1179
|
+
playRandom: (opts = {}) => {
|
|
1180
|
+
const allKeys = [...buffers.keys()];
|
|
1181
|
+
const key = allKeys[Math.floor(random() * allKeys.length)];
|
|
1182
|
+
const buf = key ? buffers.get(key) : void 0;
|
|
1183
|
+
if (!key || !buf) return;
|
|
1184
|
+
const minD = opts.minDurationSeconds ?? .1;
|
|
1185
|
+
const maxD = opts.maxDurationSeconds ?? 2;
|
|
1186
|
+
const release = opts.releaseSeconds ?? 1;
|
|
1187
|
+
const duration = minD + random() * Math.max(0, maxD - minD);
|
|
1188
|
+
return playSlice(key, {
|
|
1189
|
+
durationSeconds: duration,
|
|
1190
|
+
gain: opts.gain,
|
|
1191
|
+
offsetSeconds: random() * Math.max(0, buf.duration - duration - release),
|
|
1192
|
+
releaseSeconds: release
|
|
1193
|
+
});
|
|
1194
|
+
},
|
|
1195
|
+
playSlice,
|
|
1196
|
+
registerBuffer: (key, buffer) => {
|
|
1197
|
+
buffers.set(key, buffer);
|
|
1198
|
+
},
|
|
1199
|
+
setVolume: (value) => {
|
|
1200
|
+
const clamped = clampFinite(value, 0, 1, 1);
|
|
1201
|
+
scheduleParam(masterGain.gain, context, clamped, SAMPLER_VOLUME_RAMP_SECONDS);
|
|
1202
|
+
return clamped;
|
|
1203
|
+
},
|
|
1204
|
+
stopAll
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
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 };
|
|
1208
|
+
|
|
1209
|
+
//# sourceMappingURL=index.js.map
|