@avoid.quest/audio 0.1.0 → 0.1.1-beta.1
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 +32 -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 +63 -115
- package/dist/playback/index.js +906 -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 +18 -4
- package/types/hls-unavailable.d.ts +4 -0
- 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,397 @@ 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
|
-
|
|
913
|
-
|
|
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 currentProtocol;
|
|
548
|
+
let currentUrl;
|
|
549
|
+
let mode = "idle";
|
|
550
|
+
let playbackRate = clampPlaybackRate(element.playbackRate || 1);
|
|
551
|
+
let preservesPitch = true;
|
|
552
|
+
let disposed = false;
|
|
553
|
+
let loadGeneration = 0;
|
|
554
|
+
let pendingSeekCleanup;
|
|
555
|
+
let readyWatchdogFiber;
|
|
556
|
+
let cancelPendingReadyWait;
|
|
557
|
+
const hlsRecovery = createRecoveryRunner(scope, recoverySchedule);
|
|
558
|
+
const stallRecovery = createRecoveryRunner(scope, recoverySchedule);
|
|
559
|
+
const hasMetadata = () => typeof element.readyState === "number" && element.readyState >= 1;
|
|
560
|
+
const applyRate = () => {
|
|
561
|
+
element.defaultPlaybackRate = playbackRate;
|
|
562
|
+
element.playbackRate = playbackRate;
|
|
563
|
+
};
|
|
564
|
+
const syncRateAndPitch = () => {
|
|
565
|
+
applyRate();
|
|
566
|
+
applyPreservesPitch(element, preservesPitch);
|
|
567
|
+
};
|
|
568
|
+
const clearSeek = () => {
|
|
569
|
+
pendingSeekCleanup?.();
|
|
570
|
+
pendingSeekCleanup = void 0;
|
|
571
|
+
};
|
|
572
|
+
const clearReady = () => {
|
|
573
|
+
readyWatchdogFiber?.interruptUnsafe();
|
|
574
|
+
readyWatchdogFiber = void 0;
|
|
575
|
+
};
|
|
576
|
+
const loadNative = (url, startSec) => {
|
|
577
|
+
element.src = url;
|
|
578
|
+
syncRateAndPitch();
|
|
579
|
+
element.load?.();
|
|
580
|
+
clearSeek();
|
|
581
|
+
pendingSeekCleanup = scheduleElementSeek(element, startSec, hasMetadata, () => disposed);
|
|
582
|
+
};
|
|
583
|
+
const play = () => Effect.tryPromise({
|
|
584
|
+
catch: (error) => {
|
|
585
|
+
const name = error instanceof Error ? error.name : "";
|
|
586
|
+
return pbErr(name || "PLAY_FAILED", `Media play() failed: ${String(error)}`, name === "AbortError" || name === "NotAllowedError", String(error));
|
|
587
|
+
},
|
|
588
|
+
try: async () => {
|
|
589
|
+
applyRate();
|
|
590
|
+
await element.play();
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
const recoverStall = (gen) => Effect.gen(function* () {
|
|
594
|
+
if (mode === "hls.js" && hlsInstance) {
|
|
595
|
+
hlsInstance.startLoad();
|
|
596
|
+
stallWatchdog.arm();
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
if (currentUrl === void 0) return;
|
|
600
|
+
const at = element.currentTime;
|
|
601
|
+
const wasPlaying = !element.paused;
|
|
602
|
+
loadNative(currentUrl, Number.isFinite(at) && at > 0 ? at : void 0);
|
|
603
|
+
if (wasPlaying && !disposed && gen === loadGeneration) {
|
|
604
|
+
yield* play().pipe(Effect.timeoutOption(Duration.millis(Math.max(1, stallWatchdogMs))), Effect.catch(() => Effect.void));
|
|
605
|
+
stallWatchdog.arm();
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
const stallWatchdog = createStallWatchdog(element, stallWatchdogMs, stallRecovery, () => ({
|
|
609
|
+
disposed,
|
|
610
|
+
gen: loadGeneration,
|
|
611
|
+
hasUrl: currentUrl !== void 0
|
|
612
|
+
}), recoverStall, options.onStall, options.onStreamError);
|
|
613
|
+
const resetPlayback = () => {
|
|
614
|
+
cancelPendingReadyWait?.();
|
|
615
|
+
cancelPendingReadyWait = void 0;
|
|
616
|
+
clearSeek();
|
|
617
|
+
clearReady();
|
|
618
|
+
stallWatchdog.clear();
|
|
619
|
+
stallRecovery.stop();
|
|
620
|
+
hlsRecovery.stop();
|
|
621
|
+
hlsInstance?.destroy();
|
|
622
|
+
hlsInstance = void 0;
|
|
623
|
+
};
|
|
624
|
+
const load = (url, loadOptions = {}) => Effect.gen(function* () {
|
|
625
|
+
loadGeneration += 1;
|
|
626
|
+
const gen = loadGeneration;
|
|
627
|
+
resetPlayback();
|
|
628
|
+
currentUrl = url;
|
|
629
|
+
currentProtocol = loadOptions.protocol;
|
|
630
|
+
stallWatchdog.resetProgress();
|
|
631
|
+
const readyMs = loadOptions.readyTimeoutMs ?? readyTimeoutDefault;
|
|
632
|
+
if (loadOptions.crossOrigin !== void 0) element.crossOrigin = loadOptions.crossOrigin;
|
|
633
|
+
const allowNative = loadOptions.allowNativeHls ?? options.allowNativeHls ?? true;
|
|
634
|
+
const hlsStream = loadOptions.protocol === void 0 ? isHlsUrl(url) : loadOptions.protocol === "hls";
|
|
635
|
+
let activeHls;
|
|
636
|
+
let manifestEvent;
|
|
637
|
+
if (hlsStream && !shouldUseNativeHls(element, allowNative, options.userAgent)) {
|
|
638
|
+
const { default: HlsCtor } = yield* Effect.tryPromise({
|
|
639
|
+
catch: (e) => pbErr("HLS_IMPORT_FAILED", `Load hls.js: ${String(e)}`, false, `${e}`),
|
|
640
|
+
try: () => loadHlsModule()
|
|
641
|
+
});
|
|
642
|
+
if (disposed || gen !== loadGeneration) return yield* failSuperseded();
|
|
643
|
+
if (typeof HlsCtor?.isSupported === "function" && HlsCtor.isSupported()) {
|
|
644
|
+
activeHls = attachHlsInstance(HlsCtor, element, url, options.hlsConfig, loadOptions, hlsRecovery, (hls) => !disposed && hlsInstance === hls, clearReady, options.onStreamError);
|
|
645
|
+
hlsInstance = activeHls;
|
|
646
|
+
mode = "hls.js";
|
|
647
|
+
syncRateAndPitch();
|
|
648
|
+
manifestEvent = HlsCtor.Events.MANIFEST_PARSED;
|
|
921
649
|
}
|
|
650
|
+
}
|
|
651
|
+
if (!activeHls) {
|
|
922
652
|
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();
|
|
653
|
+
loadNative(url, loadOptions.startPositionSeconds);
|
|
654
|
+
}
|
|
655
|
+
const ready = waitForMediaReady(element, readyMs, () => disposed || gen !== loadGeneration, hasMetadata, (cancel) => {
|
|
656
|
+
cancelPendingReadyWait = cancel;
|
|
657
|
+
return () => {
|
|
658
|
+
if (cancelPendingReadyWait === cancel) cancelPendingReadyWait = void 0;
|
|
659
|
+
};
|
|
660
|
+
}, activeHls, manifestEvent);
|
|
661
|
+
if (loadOptions.waitForReady) yield* ready;
|
|
662
|
+
else if (readyMs > 0 && !disposed) readyWatchdogFiber = forkReadyWatchdog(scope, ready, (failure) => {
|
|
663
|
+
if (!disposed && gen === loadGeneration && failure.code !== "MEDIA_LOAD_SUPERSEDED" && !hasMetadata()) options.onStreamError?.(element.currentTime, failure);
|
|
981
664
|
});
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
665
|
+
});
|
|
666
|
+
const dispose = () => Effect.sync(() => {
|
|
667
|
+
if (disposed) return;
|
|
668
|
+
disposed = true;
|
|
669
|
+
loadGeneration += 1;
|
|
670
|
+
resetPlayback();
|
|
671
|
+
stallWatchdog.detach();
|
|
672
|
+
element.pause();
|
|
673
|
+
element.removeAttribute("src");
|
|
674
|
+
element.load?.();
|
|
675
|
+
mode = "idle";
|
|
676
|
+
currentProtocol = void 0;
|
|
677
|
+
currentUrl = void 0;
|
|
678
|
+
});
|
|
679
|
+
return {
|
|
680
|
+
dispose,
|
|
681
|
+
element,
|
|
682
|
+
getSnapshot: () => ({
|
|
987
683
|
currentTime: element.currentTime,
|
|
988
684
|
duration: Number.isFinite(element.duration) ? element.duration : void 0,
|
|
989
685
|
mode,
|
|
@@ -993,75 +689,273 @@ function createMediaEngine(options) {
|
|
|
993
689
|
preservesPitch,
|
|
994
690
|
src: currentUrl,
|
|
995
691
|
volume: element.volume
|
|
692
|
+
}),
|
|
693
|
+
load,
|
|
694
|
+
pause: () => Effect.sync(() => {
|
|
695
|
+
stallWatchdog.clear();
|
|
696
|
+
element.pause();
|
|
697
|
+
}),
|
|
698
|
+
play,
|
|
699
|
+
refreshUrl: (url, seekPos) => Effect.gen(function* () {
|
|
700
|
+
const wasPlaying = !element.paused;
|
|
701
|
+
const at = seekPos ?? element.currentTime;
|
|
702
|
+
yield* load(url, {
|
|
703
|
+
protocol: currentProtocol,
|
|
704
|
+
startPositionSeconds: Number.isFinite(at) && at > 0 ? at : void 0
|
|
705
|
+
});
|
|
706
|
+
if (wasPlaying) yield* play();
|
|
707
|
+
}),
|
|
708
|
+
runWithStallRecovery: (effect) => effect.pipe(Effect.retry({
|
|
709
|
+
schedule: recoverySchedule,
|
|
710
|
+
while: (err) => err.recoverable !== false
|
|
711
|
+
})),
|
|
712
|
+
seek: (sec) => Effect.sync(() => {
|
|
713
|
+
clearSeek();
|
|
714
|
+
if (Number.isFinite(sec) && sec >= 0) element.currentTime = sec;
|
|
715
|
+
}),
|
|
716
|
+
setMuted: (m) => Effect.sync(() => element.muted = m),
|
|
717
|
+
setPlaybackRate: (rate) => Effect.sync(() => {
|
|
718
|
+
playbackRate = clampPlaybackRate(rate);
|
|
719
|
+
applyRate();
|
|
720
|
+
return playbackRate;
|
|
721
|
+
}),
|
|
722
|
+
setPreservesPitch: (p) => Effect.sync(() => preservesPitch = applyPreservesPitch(element, p)),
|
|
723
|
+
setVolume: (vol) => Effect.sync(() => element.volume = clampFinite(vol, 0, 1, 1))
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
function createMediaEngine(options) {
|
|
727
|
+
return Effect.gen(function* () {
|
|
728
|
+
const scope = yield* Scope.Scope;
|
|
729
|
+
const engine = buildMediaEngine(scope, options);
|
|
730
|
+
yield* Scope.addFinalizer(scope, engine.dispose());
|
|
731
|
+
return engine;
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
// src/playback/media-source.ts
|
|
735
|
+
const elementSources = /* @__PURE__ */ new WeakMap();
|
|
736
|
+
const destinationRouted = /* @__PURE__ */ new WeakSet();
|
|
737
|
+
function sourceError(code, message, cause) {
|
|
738
|
+
return new AudioPlaybackError({
|
|
739
|
+
...cause === void 0 ? {} : { cause: String(cause) },
|
|
740
|
+
code,
|
|
741
|
+
message,
|
|
742
|
+
recoverable: false
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
/**
|
|
746
|
+
* Returns the memoized `MediaElementAudioSourceNode` for a `MediaEngine` or
|
|
747
|
+
* media element (browsers allow only one per element), so live playback can
|
|
748
|
+
* feed `acquirePcmCapture`, meters, or effects. Requesting it for another
|
|
749
|
+
* `AudioContext` fails with `MEDIA_SOURCE_CONTEXT_MISMATCH`. Cross-origin
|
|
750
|
+
* media needs CORS + `crossOrigin: "anonymous"`, otherwise the graph is silent.
|
|
751
|
+
*/
|
|
752
|
+
function getMediaElementSourceNode(context, target, options = {}) {
|
|
753
|
+
return Effect.suspend(() => {
|
|
754
|
+
const element = "element" in target ? target.element : target;
|
|
755
|
+
let node = elementSources.get(element);
|
|
756
|
+
if (node && node.context !== context) return Effect.fail(sourceError("MEDIA_SOURCE_CONTEXT_MISMATCH", "This media element is already bound to a different AudioContext."));
|
|
757
|
+
if (!node) {
|
|
758
|
+
try {
|
|
759
|
+
node = context.createMediaElementSource(element);
|
|
760
|
+
} catch (error) {
|
|
761
|
+
return Effect.fail(sourceError("MEDIA_SOURCE_FAILED", "Failed to create a MediaElementAudioSourceNode.", error));
|
|
762
|
+
}
|
|
763
|
+
elementSources.set(element, node);
|
|
764
|
+
}
|
|
765
|
+
const connect = options.connectToDestination ?? true;
|
|
766
|
+
if (connect !== destinationRouted.has(node)) {
|
|
767
|
+
if (connect) {
|
|
768
|
+
node.connect(context.destination);
|
|
769
|
+
destinationRouted.add(node);
|
|
770
|
+
} else {
|
|
771
|
+
node.disconnect(context.destination);
|
|
772
|
+
destinationRouted.delete(node);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return Effect.succeed(node);
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
// src/worklets/pcm-capture.ts
|
|
779
|
+
const PCM_CAPTURE_PROCESSOR_NAME = "avoid-pcm-capture";
|
|
780
|
+
const PCM_CAPTURE_DEFAULT_CHUNK_FRAMES = 2048;
|
|
781
|
+
/** Main-thread → processor message that ends the processor's lifetime. */
|
|
782
|
+
const PCM_CAPTURE_STOP_MESSAGE = "stop";
|
|
783
|
+
const PCM_CAPTURE_MIN_CHUNK_FRAMES = 128;
|
|
784
|
+
const PCM_CAPTURE_MAX_CHUNK_FRAMES = 16384;
|
|
785
|
+
/** Clamps a requested chunk size to whole frames within `[128, 16384]`. */
|
|
786
|
+
function clampPcmChunkFrames(chunkFrames) {
|
|
787
|
+
if (chunkFrames === void 0 || !Number.isFinite(chunkFrames)) return PCM_CAPTURE_DEFAULT_CHUNK_FRAMES;
|
|
788
|
+
return Math.max(PCM_CAPTURE_MIN_CHUNK_FRAMES, Math.min(PCM_CAPTURE_MAX_CHUNK_FRAMES, Math.round(chunkFrames)));
|
|
789
|
+
}
|
|
790
|
+
if (typeof registerProcessor === "function") registerProcessor(PCM_CAPTURE_PROCESSOR_NAME, class AvoidPcmCaptureProcessor extends AudioWorkletProcessor {
|
|
791
|
+
chunk;
|
|
792
|
+
writeIndex = 0;
|
|
793
|
+
stopped = false;
|
|
794
|
+
constructor(options) {
|
|
795
|
+
super(options);
|
|
796
|
+
this.chunk = new Float32Array(clampPcmChunkFrames(options?.processorOptions?.chunkFrames));
|
|
797
|
+
this.port.addEventListener("message", (event) => {
|
|
798
|
+
if (event.data === "stop") this.stopped = true;
|
|
996
799
|
});
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
800
|
+
if (typeof this.port.start === "function") this.port.start();
|
|
801
|
+
}
|
|
802
|
+
process(inputs) {
|
|
803
|
+
if (this.stopped) return false;
|
|
804
|
+
const [input] = inputs;
|
|
805
|
+
const first = input?.[0];
|
|
806
|
+
if (!input || !first || first.length === 0) return true;
|
|
807
|
+
const frames = first.length;
|
|
808
|
+
const channelCount = input.length;
|
|
809
|
+
const scale = 1 / channelCount;
|
|
810
|
+
const { chunk } = this;
|
|
811
|
+
const capacity = chunk.length;
|
|
812
|
+
let { writeIndex } = this;
|
|
813
|
+
for (let i = 0; i < frames; i += 1) {
|
|
814
|
+
let sum = 0;
|
|
815
|
+
for (let channel = 0; channel < channelCount; channel += 1) sum += input[channel]?.[i] ?? 0;
|
|
816
|
+
chunk[writeIndex] = sum * scale;
|
|
817
|
+
writeIndex += 1;
|
|
818
|
+
if (writeIndex === capacity) {
|
|
819
|
+
this.port.postMessage(chunk);
|
|
820
|
+
writeIndex = 0;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
this.writeIndex = writeIndex;
|
|
824
|
+
return true;
|
|
825
|
+
}
|
|
826
|
+
});
|
|
827
|
+
// src/playback/pcm-capture.ts
|
|
828
|
+
/** Loads the standalone `@avoid.quest/audio/worklets/pcm-capture` module. */
|
|
829
|
+
function loadPcmCaptureWorklet(context, options = {}) {
|
|
830
|
+
return loadAudioWorklet(context, {
|
|
831
|
+
...options,
|
|
832
|
+
moduleUrl: options.moduleUrl ?? createWorkletModuleUrl("pcm-capture"),
|
|
833
|
+
processorName: PCM_CAPTURE_PROCESSOR_NAME
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
function bestEffort(run) {
|
|
837
|
+
try {
|
|
838
|
+
run();
|
|
839
|
+
} catch {}
|
|
840
|
+
}
|
|
841
|
+
function buildPcmCapture(context, source, options) {
|
|
842
|
+
const { sampleRate } = context;
|
|
843
|
+
const ring = createPcmRingBuffer({
|
|
844
|
+
maxSeconds: options.maxSeconds,
|
|
845
|
+
sampleRate
|
|
846
|
+
});
|
|
847
|
+
let active = true;
|
|
848
|
+
const node = new globalThis.AudioWorkletNode(context, PCM_CAPTURE_PROCESSOR_NAME, {
|
|
849
|
+
numberOfInputs: 1,
|
|
850
|
+
numberOfOutputs: 1,
|
|
851
|
+
outputChannelCount: [1],
|
|
852
|
+
processorOptions: { chunkFrames: clampPcmChunkFrames(options.chunkFrames) }
|
|
853
|
+
});
|
|
854
|
+
const silentSink = context.createGain();
|
|
855
|
+
silentSink.gain.value = 0;
|
|
856
|
+
const onMessage = (event) => {
|
|
857
|
+
if (active && event.data instanceof Float32Array) {
|
|
858
|
+
ring.push(event.data);
|
|
859
|
+
options.onChunk?.(event.data);
|
|
860
|
+
}
|
|
861
|
+
};
|
|
862
|
+
const teardown = () => {
|
|
863
|
+
if (!active) return;
|
|
864
|
+
active = false;
|
|
865
|
+
node.port.removeEventListener("message", onMessage);
|
|
866
|
+
bestEffort(() => node.port.postMessage(PCM_CAPTURE_STOP_MESSAGE));
|
|
867
|
+
bestEffort(() => source.disconnect(node));
|
|
868
|
+
node.port.close?.();
|
|
869
|
+
node.disconnect();
|
|
870
|
+
silentSink.disconnect();
|
|
871
|
+
ring.clear();
|
|
872
|
+
};
|
|
873
|
+
try {
|
|
874
|
+
node.port.addEventListener("message", onMessage);
|
|
875
|
+
node.port.start?.();
|
|
876
|
+
source.connect(node);
|
|
877
|
+
node.connect(silentSink);
|
|
878
|
+
silentSink.connect(context.destination);
|
|
879
|
+
} catch (error) {
|
|
880
|
+
teardown();
|
|
881
|
+
throw error;
|
|
882
|
+
}
|
|
883
|
+
const snapshot = (seconds) => ring.snapshot(seconds);
|
|
884
|
+
return [{
|
|
885
|
+
bufferedSeconds: () => ring.bufferedSeconds(),
|
|
886
|
+
capacitySeconds: ring.capacityFrames / sampleRate,
|
|
887
|
+
clear: () => {
|
|
888
|
+
ring.clear();
|
|
889
|
+
},
|
|
890
|
+
fingerprint: (seconds) => Effect.suspend(() => generateShazamSignatureFromFloat32(snapshot(seconds), sampleRate)),
|
|
891
|
+
isActive: () => active,
|
|
892
|
+
node,
|
|
893
|
+
sampleRate,
|
|
894
|
+
snapshot,
|
|
895
|
+
toShazamPcm: (seconds) => prepareShazamPcm(snapshot(seconds), sampleRate)
|
|
896
|
+
}, teardown];
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Passively taps any `AudioNode` (e.g. from `getMediaElementSourceNode` or
|
|
900
|
+
* `acquireInputCapture`) into a rolling mono PCM window via the allocation-free
|
|
901
|
+
* `pcm-capture` AudioWorklet, so live audio can be fingerprinted with
|
|
902
|
+
* `capture.fingerprint()`. Fully torn down when the owning `Scope` closes.
|
|
903
|
+
*/
|
|
904
|
+
function acquirePcmCapture(context, source, options = {}) {
|
|
905
|
+
return Effect.gen(function* () {
|
|
906
|
+
if (typeof globalThis.AudioWorkletNode !== "function") return yield* Effect.fail(new AudioUnsupportedError({
|
|
907
|
+
feature: "AudioWorkletNode",
|
|
908
|
+
message: "PCM capture requires AudioWorkletNode support."
|
|
909
|
+
}));
|
|
910
|
+
yield* loadPcmCaptureWorklet(context, options.workletOptions);
|
|
911
|
+
const [capture] = yield* Effect.acquireRelease(Effect.try({
|
|
912
|
+
catch: (error) => new AudioCaptureError({
|
|
913
|
+
code: "PCM_CAPTURE_FAILED",
|
|
914
|
+
message: `PCM capture setup failed: ${String(error)}`
|
|
915
|
+
}),
|
|
916
|
+
try: () => buildPcmCapture(context, source, options)
|
|
917
|
+
}), ([, teardown]) => Effect.sync(teardown));
|
|
918
|
+
return capture;
|
|
1012
919
|
});
|
|
1013
920
|
}
|
|
1014
921
|
// src/playback/media-session.ts
|
|
1015
922
|
const SILENT_WAV_SAMPLE_RATE = 8e3;
|
|
1016
923
|
const SILENT_WAV_DURATION_SECONDS = 10;
|
|
1017
924
|
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
|
-
*/
|
|
925
|
+
const BLUETOOTH_REPLACEMENTS = [
|
|
926
|
+
[/\p{M}/gu, ""],
|
|
927
|
+
[/[\u2010-\u2015\u2212\u00B7\u2022]/gu, "-"],
|
|
928
|
+
[/[\u2018\u2019\u201A\u2032]/gu, "'"],
|
|
929
|
+
[/[\u201C\u201D\u201E\u00AB\u00BB\u2033]/gu, "\""],
|
|
930
|
+
[/\u2026/gu, "..."],
|
|
931
|
+
[/[^\u0020-\u007E]/gu, ""],
|
|
932
|
+
[/\s+/gu, " "]
|
|
933
|
+
];
|
|
1032
934
|
function sanitizeForBluetooth(input, fallback = "Radio") {
|
|
1033
|
-
if (!input
|
|
1034
|
-
|
|
1035
|
-
|
|
935
|
+
if (!input?.trim()) return fallback;
|
|
936
|
+
let out = input.normalize("NFKD");
|
|
937
|
+
for (const [pattern, replacement] of BLUETOOTH_REPLACEMENTS) out = out.replaceAll(pattern, replacement);
|
|
938
|
+
return out.trim() || fallback;
|
|
1036
939
|
}
|
|
1037
|
-
|
|
940
|
+
const writeAscii = (view, offset, text) => {
|
|
1038
941
|
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
|
-
*/
|
|
942
|
+
};
|
|
1045
943
|
function createSilentWavBytes(durationSeconds = 10, sampleRate = SILENT_WAV_SAMPLE_RATE) {
|
|
1046
944
|
const safeDuration = Math.max(1, Math.round(durationSeconds));
|
|
1047
945
|
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);
|
|
946
|
+
const dataBytes = safeRate * 2 * safeDuration;
|
|
947
|
+
const buffer = new Uint8Array(44 + dataBytes);
|
|
1054
948
|
const view = new DataView(buffer.buffer);
|
|
1055
949
|
writeAscii(view, 0, "RIFF");
|
|
1056
950
|
view.setUint32(4, 36 + dataBytes, true);
|
|
1057
951
|
writeAscii(view, 8, "WAVEfmt ");
|
|
1058
952
|
view.setUint32(16, 16, true);
|
|
1059
953
|
view.setUint16(20, 1, true);
|
|
1060
|
-
view.setUint16(22,
|
|
954
|
+
view.setUint16(22, 1, true);
|
|
1061
955
|
view.setUint32(24, safeRate, true);
|
|
1062
|
-
view.setUint32(28, safeRate *
|
|
956
|
+
view.setUint32(28, safeRate * 2, true);
|
|
1063
957
|
view.setUint16(32, 2, true);
|
|
1064
|
-
view.setUint16(34,
|
|
958
|
+
view.setUint16(34, 16, true);
|
|
1065
959
|
writeAscii(view, 36, "data");
|
|
1066
960
|
view.setUint32(40, dataBytes, true);
|
|
1067
961
|
return buffer;
|
|
@@ -1071,7 +965,7 @@ function createSilentWavBlob(durationSeconds = 10, sampleRate = SILENT_WAV_SAMPL
|
|
|
1071
965
|
return new Blob([bytes.buffer], { type: "audio/wav" });
|
|
1072
966
|
}
|
|
1073
967
|
const INERT_HANDLER = () => {};
|
|
1074
|
-
const
|
|
968
|
+
const CORE_ACTIONS = [
|
|
1075
969
|
"play",
|
|
1076
970
|
"pause",
|
|
1077
971
|
"stop"
|
|
@@ -1083,21 +977,42 @@ const OPTIONAL_ACTIONS = [
|
|
|
1083
977
|
"seekforward",
|
|
1084
978
|
"seekto"
|
|
1085
979
|
];
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
function
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
980
|
+
const setActionSafe = (session, action, handler) => {
|
|
981
|
+
try {
|
|
982
|
+
session.setActionHandler(action, handler);
|
|
983
|
+
} catch {}
|
|
984
|
+
};
|
|
985
|
+
function buildMediaSessionController(options) {
|
|
986
|
+
const sanitize = options.sanitizeAvrcp ?? true;
|
|
987
|
+
const fallback = options.avrcpFallback ?? "Radio";
|
|
988
|
+
const session = options.mediaSession ?? globalThis.navigator?.mediaSession;
|
|
989
|
+
let keepAliveAudio;
|
|
990
|
+
let keepAliveUrl;
|
|
991
|
+
const clean = (value, def) => sanitize ? sanitizeForBluetooth(value, def) : value ?? def;
|
|
992
|
+
const stopKeepAlive = () => {
|
|
993
|
+
if (keepAliveAudio) {
|
|
994
|
+
keepAliveAudio.pause();
|
|
995
|
+
keepAliveAudio.removeAttribute("src");
|
|
996
|
+
keepAliveAudio.load?.();
|
|
997
|
+
keepAliveAudio = void 0;
|
|
998
|
+
}
|
|
999
|
+
if (keepAliveUrl) {
|
|
1000
|
+
URL.revokeObjectURL(keepAliveUrl);
|
|
1001
|
+
keepAliveUrl = void 0;
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
const dispose = () => {
|
|
1005
|
+
stopKeepAlive();
|
|
1006
|
+
if (typeof session?.setActionHandler === "function") for (const action of [...CORE_ACTIONS, ...OPTIONAL_ACTIONS]) setActionSafe(session, action, null);
|
|
1007
|
+
};
|
|
1008
|
+
return {
|
|
1009
|
+
dispose,
|
|
1010
|
+
setHandlers: (handlers) => {
|
|
1011
|
+
if (typeof session?.setActionHandler !== "function") return;
|
|
1012
|
+
for (const action of CORE_ACTIONS) setActionSafe(session, action, handlers[action] ?? INERT_HANDLER);
|
|
1013
|
+
for (const action of OPTIONAL_ACTIONS) setActionSafe(session, action, handlers[action] ?? null);
|
|
1014
|
+
},
|
|
1015
|
+
setMetadata: (metadata) => {
|
|
1101
1016
|
if (!session) return;
|
|
1102
1017
|
const payload = {
|
|
1103
1018
|
album: metadata.album ? clean(metadata.album, "") : "",
|
|
@@ -1106,13 +1021,12 @@ function createMediaSessionController(options = {}) {
|
|
|
1106
1021
|
title: clean(metadata.title, fallback)
|
|
1107
1022
|
};
|
|
1108
1023
|
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;
|
|
1024
|
+
},
|
|
1025
|
+
setPlaybackState: (state) => {
|
|
1026
|
+
if (session) session.playbackState = state;
|
|
1027
|
+
},
|
|
1028
|
+
setPositionState: (state) => {
|
|
1029
|
+
if (typeof session?.setPositionState !== "function") return;
|
|
1116
1030
|
try {
|
|
1117
1031
|
if (state.isLive) {
|
|
1118
1032
|
session.setPositionState({
|
|
@@ -1121,77 +1035,37 @@ function createMediaSessionController(options = {}) {
|
|
|
1121
1035
|
});
|
|
1122
1036
|
return;
|
|
1123
1037
|
}
|
|
1124
|
-
const duration = state.duration
|
|
1125
|
-
const position = state.position
|
|
1038
|
+
const duration = clampFinite(state.duration ?? 0, 0, Number.POSITIVE_INFINITY, 0);
|
|
1039
|
+
const position = clampFinite(state.position ?? 0, 0, duration, 0);
|
|
1126
1040
|
session.setPositionState({
|
|
1127
1041
|
duration,
|
|
1128
1042
|
playbackRate: state.playbackRate ?? 1,
|
|
1129
1043
|
position
|
|
1130
1044
|
});
|
|
1131
1045
|
} 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(() => {
|
|
1046
|
+
},
|
|
1047
|
+
startKeepAlive: () => Effect.sync(() => {
|
|
1161
1048
|
if (options.enableKeepAlive === false) return;
|
|
1162
|
-
if (keepAliveAudio) {
|
|
1163
|
-
|
|
1164
|
-
|
|
1049
|
+
if (!keepAliveAudio) {
|
|
1050
|
+
if (!options.createKeepAliveElement && typeof globalThis.Audio !== "function") return;
|
|
1051
|
+
keepAliveUrl = URL.createObjectURL(createSilentWavBlob());
|
|
1052
|
+
const audio = options.createKeepAliveElement ? options.createKeepAliveElement() : new globalThis.Audio();
|
|
1053
|
+
audio.loop = true;
|
|
1054
|
+
audio.volume = 0;
|
|
1055
|
+
audio.muted = false;
|
|
1056
|
+
audio.src = keepAliveUrl;
|
|
1057
|
+
keepAliveAudio = audio;
|
|
1165
1058
|
}
|
|
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
|
-
};
|
|
1059
|
+
keepAliveAudio.play().catch(() => {});
|
|
1060
|
+
}),
|
|
1061
|
+
stopKeepAlive
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
function createMediaSessionController(options = {}) {
|
|
1065
|
+
return Effect.gen(function* () {
|
|
1066
|
+
const controller = buildMediaSessionController(options);
|
|
1067
|
+
yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(controller.dispose));
|
|
1068
|
+
return controller;
|
|
1195
1069
|
});
|
|
1196
1070
|
}
|
|
1197
1071
|
// src/playback/sampler.ts
|
|
@@ -1206,94 +1080,61 @@ const SAMPLER_MAX_SLICE_DURATION = 2;
|
|
|
1206
1080
|
const SAMPLER_RELEASE_SECONDS = 1;
|
|
1207
1081
|
const SAMPLER_VOLUME_RAMP_SECONDS = .05;
|
|
1208
1082
|
const SAMPLER_DEFAULT_BATCH_SIZE = 4;
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1083
|
+
const stopSourceSafe = (source) => {
|
|
1084
|
+
try {
|
|
1085
|
+
source.stop();
|
|
1086
|
+
} catch {}
|
|
1087
|
+
};
|
|
1213
1088
|
function createSampler(context, options = {}) {
|
|
1214
1089
|
const buffers = /* @__PURE__ */ new Map();
|
|
1215
|
-
const
|
|
1090
|
+
const active = /* @__PURE__ */ new Set();
|
|
1216
1091
|
const masterGain = context.createGain();
|
|
1217
1092
|
masterGain.gain.value = Math.max(0, Math.min(1, options.initialVolume ?? 1));
|
|
1218
|
-
|
|
1219
|
-
masterGain.connect(destination);
|
|
1093
|
+
masterGain.connect(options.destination ?? context.destination);
|
|
1220
1094
|
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
1095
|
const loadBuffer = (key, url) => Effect.tryPromise({
|
|
1227
|
-
catch: (
|
|
1228
|
-
message: `Failed to load sample "${key}": ${String(
|
|
1096
|
+
catch: (err) => new AudioDecodeError({
|
|
1097
|
+
message: `Failed to load sample "${key}": ${String(err)}`,
|
|
1229
1098
|
source: url
|
|
1230
1099
|
}),
|
|
1231
1100
|
try: async () => {
|
|
1232
1101
|
const cached = buffers.get(key);
|
|
1233
1102
|
if (cached) return cached;
|
|
1234
|
-
const
|
|
1235
|
-
if (!
|
|
1236
|
-
const
|
|
1237
|
-
const decoded = await context.decodeAudioData(arrayBuffer);
|
|
1103
|
+
const res = await (options.fetchImpl ?? globalThis.fetch)(url);
|
|
1104
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
1105
|
+
const decoded = await context.decodeAudioData(await res.arrayBuffer());
|
|
1238
1106
|
buffers.set(key, decoded);
|
|
1239
1107
|
return decoded;
|
|
1240
1108
|
}
|
|
1241
1109
|
});
|
|
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 = {}) => {
|
|
1110
|
+
const playSlice = (key, opts = {}) => {
|
|
1268
1111
|
const buffer = buffers.get(key);
|
|
1269
1112
|
if (!buffer) return;
|
|
1270
1113
|
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 =
|
|
1114
|
+
const attack = Math.max(0, opts.attackSeconds ?? 0);
|
|
1115
|
+
const release = Math.max(0, opts.releaseSeconds ?? 1);
|
|
1116
|
+
const level = Math.max(0, opts.gain ?? 1);
|
|
1117
|
+
const offset = Math.max(0, Math.min(buffer.duration, opts.offsetSeconds ?? 0));
|
|
1118
|
+
const avail = Math.max(0, buffer.duration - offset);
|
|
1119
|
+
const duration = opts.durationSeconds === void 0 ? Math.max(0, avail - release) : Math.max(0, Math.min(avail, opts.durationSeconds));
|
|
1277
1120
|
const source = context.createBufferSource();
|
|
1278
1121
|
source.buffer = buffer;
|
|
1279
|
-
if (
|
|
1280
|
-
const
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
voiceGain.connect(masterGain);
|
|
1289
|
-
activeSources.add(source);
|
|
1122
|
+
if (opts.playbackRate !== void 0 && Number.isFinite(opts.playbackRate) && opts.playbackRate > 0) source.playbackRate.value = opts.playbackRate;
|
|
1123
|
+
const voice = context.createGain();
|
|
1124
|
+
voice.gain.setValueAtTime(attack > 0 ? 0 : level, now);
|
|
1125
|
+
if (attack > 0) voice.gain.linearRampToValueAtTime(level, now + attack);
|
|
1126
|
+
voice.gain.setValueAtTime(level, now + duration);
|
|
1127
|
+
if (release > 0) voice.gain.linearRampToValueAtTime(0, now + duration + release);
|
|
1128
|
+
source.connect(voice);
|
|
1129
|
+
voice.connect(masterGain);
|
|
1130
|
+
active.add(source);
|
|
1290
1131
|
let stopped = false;
|
|
1291
1132
|
const cleanup = () => {
|
|
1292
1133
|
if (stopped) return;
|
|
1293
1134
|
stopped = true;
|
|
1294
|
-
|
|
1135
|
+
active.delete(source);
|
|
1295
1136
|
source.disconnect();
|
|
1296
|
-
|
|
1137
|
+
voice.disconnect();
|
|
1297
1138
|
};
|
|
1298
1139
|
source.onended = cleanup;
|
|
1299
1140
|
source.start(now, offset, duration + release);
|
|
@@ -1303,70 +1144,73 @@ function createSampler(context, options = {}) {
|
|
|
1303
1144
|
offsetSeconds: offset,
|
|
1304
1145
|
stop: () => {
|
|
1305
1146
|
if (stopped) return;
|
|
1306
|
-
|
|
1307
|
-
source.stop();
|
|
1308
|
-
} catch {}
|
|
1147
|
+
stopSourceSafe(source);
|
|
1309
1148
|
cleanup();
|
|
1310
1149
|
}
|
|
1311
1150
|
};
|
|
1312
1151
|
};
|
|
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
1152
|
const stopAll = () => {
|
|
1342
|
-
for (const
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
} catch {}
|
|
1346
|
-
source.disconnect();
|
|
1153
|
+
for (const s of active) {
|
|
1154
|
+
stopSourceSafe(s);
|
|
1155
|
+
s.disconnect();
|
|
1347
1156
|
}
|
|
1348
|
-
|
|
1349
|
-
};
|
|
1350
|
-
const dispose = () => {
|
|
1351
|
-
stopAll();
|
|
1352
|
-
masterGain.disconnect();
|
|
1353
|
-
buffers.clear();
|
|
1157
|
+
active.clear();
|
|
1354
1158
|
};
|
|
1355
1159
|
return {
|
|
1356
|
-
activeVoiceCount: () =>
|
|
1357
|
-
dispose
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1160
|
+
activeVoiceCount: () => active.size,
|
|
1161
|
+
dispose: () => {
|
|
1162
|
+
stopAll();
|
|
1163
|
+
masterGain.disconnect();
|
|
1164
|
+
buffers.clear();
|
|
1165
|
+
},
|
|
1166
|
+
getBuffer: (key) => buffers.get(key),
|
|
1167
|
+
keys: () => [...buffers.keys()],
|
|
1168
|
+
loadBatch: (entries, batchSize = 4) => Effect.forEach(entries, (entry) => loadBuffer(entry.key, entry.url).pipe(Effect.result, Effect.map((res) => ({
|
|
1169
|
+
key: entry.key,
|
|
1170
|
+
res
|
|
1171
|
+
}))), { concurrency: Math.max(1, Math.floor(batchSize)) }).pipe(Effect.map((results) => {
|
|
1172
|
+
const loaded = [];
|
|
1173
|
+
const failed = [];
|
|
1174
|
+
for (const { key, res } of results) if (Result.isSuccess(res)) loaded.push(key);
|
|
1175
|
+
else failed.push({
|
|
1176
|
+
error: res.failure.message,
|
|
1177
|
+
key
|
|
1178
|
+
});
|
|
1179
|
+
return {
|
|
1180
|
+
failed,
|
|
1181
|
+
loaded
|
|
1182
|
+
};
|
|
1183
|
+
})),
|
|
1361
1184
|
loadBuffer,
|
|
1362
1185
|
masterGain,
|
|
1363
|
-
playRandom
|
|
1186
|
+
playRandom: (opts = {}) => {
|
|
1187
|
+
const allKeys = [...buffers.keys()];
|
|
1188
|
+
const key = allKeys[Math.floor(random() * allKeys.length)];
|
|
1189
|
+
const buf = key ? buffers.get(key) : void 0;
|
|
1190
|
+
if (!key || !buf) return;
|
|
1191
|
+
const minD = opts.minDurationSeconds ?? .1;
|
|
1192
|
+
const maxD = opts.maxDurationSeconds ?? 2;
|
|
1193
|
+
const release = opts.releaseSeconds ?? 1;
|
|
1194
|
+
const duration = minD + random() * Math.max(0, maxD - minD);
|
|
1195
|
+
return playSlice(key, {
|
|
1196
|
+
durationSeconds: duration,
|
|
1197
|
+
gain: opts.gain,
|
|
1198
|
+
offsetSeconds: random() * Math.max(0, buf.duration - duration - release),
|
|
1199
|
+
releaseSeconds: release
|
|
1200
|
+
});
|
|
1201
|
+
},
|
|
1364
1202
|
playSlice,
|
|
1365
|
-
registerBuffer,
|
|
1366
|
-
|
|
1203
|
+
registerBuffer: (key, buffer) => {
|
|
1204
|
+
buffers.set(key, buffer);
|
|
1205
|
+
},
|
|
1206
|
+
setVolume: (value) => {
|
|
1207
|
+
const clamped = clampFinite(value, 0, 1, 1);
|
|
1208
|
+
scheduleParam(masterGain.gain, context, clamped, SAMPLER_VOLUME_RAMP_SECONDS);
|
|
1209
|
+
return clamped;
|
|
1210
|
+
},
|
|
1367
1211
|
stopAll
|
|
1368
1212
|
};
|
|
1369
1213
|
}
|
|
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 };
|
|
1214
|
+
export { AudioContextService, DEFAULT_MAX_RECOVERY_DELAY_MS, DEFAULT_MEDIA_READY_TIMEOUT_MS, DEFAULT_STALL_WATCHDOG_MS, MAX_PLAYBACK_RATE, MIN_PLAYBACK_RATE, PCM_CAPTURE_DEFAULT_CHUNK_FRAMES, PCM_CAPTURE_PROCESSOR_NAME, SAMPLER_DEFAULT_BATCH_SIZE, SAMPLER_MAX_SLICE_DURATION, SAMPLER_MIN_SLICE_DURATION, SAMPLER_RELEASE_SECONDS, SAMPLER_VOLUME_RAMP_SECONDS, SAMPLE_KEY_PATTERN, SAMPLE_MIME_TYPES, SILENT_WAV_DURATION_SECONDS, SILENT_WAV_HEADER_BYTES, SILENT_WAV_SAMPLE_RATE, acquireAudioContext, acquireInputCapture, acquirePcmCapture, applyPreservesPitch, attachGestureUnlock, clampPlaybackRate, computeStallBackoffMs, createAudioContextOptions, createMediaEngine, createMediaSessionController, createSampler, createSilentWavBlob, createSilentWavBytes, createStallRecoverySchedule, ensureAudioContextRunning, getMediaElementSourceNode, isHlsUrl, isWebKitBrowser, loadPcmCaptureWorklet, makeAudioContextLayer, normalizeAudioContextState, requestDisplayAudio, sanitizeForBluetooth, shouldUseNativeHls, snapshotAudioContext };
|
|
1371
1215
|
|
|
1372
1216
|
//# sourceMappingURL=index.js.map
|