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