@schmooky/zvuk 1.13.0 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -74
- package/dist/cli.js +9 -189
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +109 -27
- package/dist/index.js +7 -3293
- package/dist/index.js.map +1 -1
- package/package.json +12 -4
package/dist/index.js
CHANGED
|
@@ -1,484 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
7
|
-
};
|
|
8
|
-
var EngineClosedError = class extends ZvukError {
|
|
9
|
-
constructor() {
|
|
10
|
-
super("Engine is closed. Create a new engine with createEngine().");
|
|
11
|
-
this.name = "EngineClosedError";
|
|
12
|
-
}
|
|
13
|
-
};
|
|
14
|
-
var BusNotFoundError = class extends ZvukError {
|
|
15
|
-
constructor(name) {
|
|
16
|
-
super(`Bus "${name}" is not configured. Declare it in createEngine({ buses: { ... } }).`);
|
|
17
|
-
this.name = "BusNotFoundError";
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
var SoundNotFoundError = class extends ZvukError {
|
|
21
|
-
constructor(name) {
|
|
22
|
-
super(`Sound "${name}" is not loaded. Call engine.loadSound() or load a bank that contains it.`);
|
|
23
|
-
this.name = "SoundNotFoundError";
|
|
24
|
-
}
|
|
25
|
-
};
|
|
26
|
-
var DecodeError = class extends ZvukError {
|
|
27
|
-
constructor(url, cause) {
|
|
28
|
-
super(`Failed to decode audio at "${url}": ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
29
|
-
this.name = "DecodeError";
|
|
30
|
-
}
|
|
31
|
-
};
|
|
32
|
-
var PreloadError = class extends ZvukError {
|
|
33
|
-
failures;
|
|
34
|
-
constructor(failures) {
|
|
35
|
-
const summary = failures.map((f) => ` - ${f.name}: ${f.cause instanceof Error ? f.cause.message : String(f.cause)}`).join("\n");
|
|
36
|
-
super(`Failed to preload ${failures.length} item(s):
|
|
37
|
-
${summary}`);
|
|
38
|
-
this.name = "PreloadError";
|
|
39
|
-
this.failures = failures;
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
var AggregateDecodeError = class extends DecodeError {
|
|
43
|
-
attempts;
|
|
44
|
-
constructor(urls, attempts) {
|
|
45
|
-
const last = attempts[attempts.length - 1];
|
|
46
|
-
super(urls[urls.length - 1] ?? "<empty>", last?.cause);
|
|
47
|
-
this.name = "AggregateDecodeError";
|
|
48
|
-
this.attempts = attempts;
|
|
49
|
-
const summary = attempts.map((a) => ` - ${a.url}: ${a.cause instanceof Error ? a.cause.message : String(a.cause)}`).join("\n");
|
|
50
|
-
this.message = `Failed to load any of ${urls.length} fallback URLs:
|
|
51
|
-
${summary}`;
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
|
|
55
|
-
// src/fx/compressor.ts
|
|
56
|
-
var Compressor = class {
|
|
57
|
-
input;
|
|
58
|
-
output;
|
|
59
|
-
compressor;
|
|
60
|
-
makeup;
|
|
61
|
-
ctx;
|
|
62
|
-
_bypassed = false;
|
|
63
|
-
constructor(ctx, config = {}) {
|
|
64
|
-
this.ctx = ctx;
|
|
65
|
-
this.input = ctx.createGain();
|
|
66
|
-
this.output = ctx.createGain();
|
|
67
|
-
this.compressor = ctx.createDynamicsCompressor();
|
|
68
|
-
this.makeup = ctx.createGain();
|
|
69
|
-
this.applyConfig(config);
|
|
70
|
-
this.wire();
|
|
71
|
-
}
|
|
72
|
-
applyConfig(c) {
|
|
73
|
-
const t = this.ctx.currentTime;
|
|
74
|
-
if (c.threshold != null) this.compressor.threshold.setValueAtTime(c.threshold, t);
|
|
75
|
-
if (c.knee != null) this.compressor.knee.setValueAtTime(c.knee, t);
|
|
76
|
-
if (c.ratio != null) this.compressor.ratio.setValueAtTime(c.ratio, t);
|
|
77
|
-
if (c.attack != null) this.compressor.attack.setValueAtTime(c.attack, t);
|
|
78
|
-
if (c.release != null) this.compressor.release.setValueAtTime(c.release, t);
|
|
79
|
-
if (c.makeupGain != null) {
|
|
80
|
-
this.makeup.gain.setValueAtTime(10 ** (c.makeupGain / 20), t);
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
/** Live gain reduction in dB (read-only, negative when compressing). */
|
|
84
|
-
get reduction() {
|
|
85
|
-
return this.compressor.reduction;
|
|
86
|
-
}
|
|
87
|
-
get bypassed() {
|
|
88
|
-
return this._bypassed;
|
|
89
|
-
}
|
|
90
|
-
set bypassed(v) {
|
|
91
|
-
if (this._bypassed === v) return;
|
|
92
|
-
this._bypassed = v;
|
|
93
|
-
this.wire();
|
|
94
|
-
}
|
|
95
|
-
dispose() {
|
|
96
|
-
try {
|
|
97
|
-
this.input.disconnect();
|
|
98
|
-
this.compressor.disconnect();
|
|
99
|
-
this.makeup.disconnect();
|
|
100
|
-
this.output.disconnect();
|
|
101
|
-
} catch {
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
wire() {
|
|
105
|
-
try {
|
|
106
|
-
this.input.disconnect();
|
|
107
|
-
this.compressor.disconnect();
|
|
108
|
-
this.makeup.disconnect();
|
|
109
|
-
} catch {
|
|
110
|
-
}
|
|
111
|
-
if (this._bypassed) {
|
|
112
|
-
this.input.connect(this.output);
|
|
113
|
-
} else {
|
|
114
|
-
this.input.connect(this.compressor);
|
|
115
|
-
this.compressor.connect(this.makeup);
|
|
116
|
-
this.makeup.connect(this.output);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
|
-
|
|
121
|
-
// src/fx/ducker.ts
|
|
122
|
-
var Ducker = class {
|
|
123
|
-
input;
|
|
124
|
-
output;
|
|
125
|
-
gain;
|
|
126
|
-
analyser;
|
|
127
|
-
buf;
|
|
128
|
-
rafId = null;
|
|
129
|
-
/** Timestamp of the previous tick (ms), for measuring the real frame delta. */
|
|
130
|
-
lastTickMs = 0;
|
|
131
|
-
envelope = 0;
|
|
132
|
-
targetGain = 1;
|
|
133
|
-
ctx;
|
|
134
|
-
cfg;
|
|
135
|
-
_bypassed = false;
|
|
136
|
-
sourceBus;
|
|
137
|
-
constructor(ctx, sourceBus, config = {}) {
|
|
138
|
-
this.ctx = ctx;
|
|
139
|
-
this.sourceBus = sourceBus;
|
|
140
|
-
this.cfg = {
|
|
141
|
-
amount: config.amount ?? 0.5,
|
|
142
|
-
attack: config.attack ?? 0.08,
|
|
143
|
-
release: config.release ?? 0.4,
|
|
144
|
-
threshold: config.threshold ?? 0.05
|
|
145
|
-
};
|
|
146
|
-
this.input = ctx.createGain();
|
|
147
|
-
this.output = ctx.createGain();
|
|
148
|
-
this.gain = ctx.createGain();
|
|
149
|
-
this.input.connect(this.gain).connect(this.output);
|
|
150
|
-
this.analyser = ctx.createAnalyser();
|
|
151
|
-
this.analyser.fftSize = 1024;
|
|
152
|
-
this.buf = new Float32Array(this.analyser.fftSize);
|
|
153
|
-
sourceBus.output.connect(this.analyser);
|
|
154
|
-
this.tick();
|
|
155
|
-
}
|
|
156
|
-
setAmount(a) {
|
|
157
|
-
this.cfg.amount = Math.max(0, Math.min(1, a));
|
|
158
|
-
}
|
|
159
|
-
setThreshold(t) {
|
|
160
|
-
this.cfg.threshold = Math.max(0, t);
|
|
161
|
-
}
|
|
162
|
-
get bypassed() {
|
|
163
|
-
return this._bypassed;
|
|
164
|
-
}
|
|
165
|
-
set bypassed(v) {
|
|
166
|
-
if (this._bypassed === v) return;
|
|
167
|
-
this._bypassed = v;
|
|
168
|
-
if (v) this.gain.gain.value = 1;
|
|
169
|
-
}
|
|
170
|
-
dispose() {
|
|
171
|
-
if (this.rafId != null) cancelAnimationFrame(this.rafId);
|
|
172
|
-
try {
|
|
173
|
-
this.sourceBus.output.disconnect(this.analyser);
|
|
174
|
-
} catch {
|
|
175
|
-
}
|
|
176
|
-
try {
|
|
177
|
-
this.input.disconnect();
|
|
178
|
-
this.gain.disconnect();
|
|
179
|
-
this.analyser.disconnect();
|
|
180
|
-
this.output.disconnect();
|
|
181
|
-
} catch {
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
tick = (timeMs) => {
|
|
185
|
-
let dtSec = 1 / 60;
|
|
186
|
-
if (timeMs != null && this.lastTickMs > 0) {
|
|
187
|
-
dtSec = Math.min(0.1, Math.max(1e-3, (timeMs - this.lastTickMs) / 1e3));
|
|
188
|
-
}
|
|
189
|
-
if (timeMs != null) this.lastTickMs = timeMs;
|
|
190
|
-
if (this._bypassed) {
|
|
191
|
-
this.rafId = requestAnimationFrame(this.tick);
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
this.analyser.getFloatTimeDomainData(this.buf);
|
|
195
|
-
let sum = 0;
|
|
196
|
-
for (let i = 0; i < this.buf.length; i++) {
|
|
197
|
-
const s = this.buf[i] ?? 0;
|
|
198
|
-
sum += s * s;
|
|
199
|
-
}
|
|
200
|
-
const rms = Math.sqrt(sum / this.buf.length);
|
|
201
|
-
const exceeded = Math.max(0, rms - this.cfg.threshold);
|
|
202
|
-
const target = exceeded > 0 ? 1 - this.cfg.amount : 1;
|
|
203
|
-
const useAttack = target < this.envelope;
|
|
204
|
-
const tau = (useAttack ? this.cfg.attack : this.cfg.release) || 1e-3;
|
|
205
|
-
const alpha = 1 - Math.exp(-dtSec / tau);
|
|
206
|
-
this.envelope = this.envelope + alpha * (target - this.envelope);
|
|
207
|
-
if (Math.abs(this.envelope - this.targetGain) > 1e-3) {
|
|
208
|
-
this.targetGain = this.envelope;
|
|
209
|
-
this.gain.gain.setTargetAtTime(this.envelope, this.ctx.currentTime, 5e-3);
|
|
210
|
-
}
|
|
211
|
-
this.rafId = requestAnimationFrame(this.tick);
|
|
212
|
-
};
|
|
213
|
-
};
|
|
214
|
-
|
|
215
|
-
// src/fx/filter.ts
|
|
216
|
-
var Filter = class {
|
|
217
|
-
input;
|
|
218
|
-
output;
|
|
219
|
-
filter;
|
|
220
|
-
ctx;
|
|
221
|
-
_bypassed = false;
|
|
222
|
-
constructor(ctx, config = {}) {
|
|
223
|
-
this.ctx = ctx;
|
|
224
|
-
this.input = ctx.createGain();
|
|
225
|
-
this.output = ctx.createGain();
|
|
226
|
-
this.filter = ctx.createBiquadFilter();
|
|
227
|
-
this.filter.type = config.type ?? "lowpass";
|
|
228
|
-
this.filter.frequency.value = config.frequency ?? 1e3;
|
|
229
|
-
this.filter.Q.value = config.q ?? 1;
|
|
230
|
-
this.filter.gain.value = config.gain ?? 0;
|
|
231
|
-
this.wire();
|
|
232
|
-
}
|
|
233
|
-
setFrequency(hz) {
|
|
234
|
-
this.filter.frequency.setValueAtTime(hz, this.ctx.currentTime);
|
|
235
|
-
}
|
|
236
|
-
setQ(q) {
|
|
237
|
-
this.filter.Q.setValueAtTime(q, this.ctx.currentTime);
|
|
238
|
-
}
|
|
239
|
-
setType(t) {
|
|
240
|
-
this.filter.type = t;
|
|
241
|
-
}
|
|
242
|
-
/** Set the filter gain in dB. Only affects `peaking` (the one shelf-like mode exposed). */
|
|
243
|
-
setGain(db) {
|
|
244
|
-
this.filter.gain.setValueAtTime(db, this.ctx.currentTime);
|
|
245
|
-
}
|
|
246
|
-
get bypassed() {
|
|
247
|
-
return this._bypassed;
|
|
248
|
-
}
|
|
249
|
-
set bypassed(v) {
|
|
250
|
-
if (this._bypassed === v) return;
|
|
251
|
-
this._bypassed = v;
|
|
252
|
-
this.wire();
|
|
253
|
-
}
|
|
254
|
-
dispose() {
|
|
255
|
-
try {
|
|
256
|
-
this.input.disconnect();
|
|
257
|
-
this.filter.disconnect();
|
|
258
|
-
this.output.disconnect();
|
|
259
|
-
} catch {
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
wire() {
|
|
263
|
-
try {
|
|
264
|
-
this.input.disconnect();
|
|
265
|
-
this.filter.disconnect();
|
|
266
|
-
} catch {
|
|
267
|
-
}
|
|
268
|
-
if (this._bypassed) {
|
|
269
|
-
this.input.connect(this.output);
|
|
270
|
-
} else {
|
|
271
|
-
this.input.connect(this.filter);
|
|
272
|
-
this.filter.connect(this.output);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
};
|
|
276
|
-
|
|
277
|
-
// src/fx/reverb.ts
|
|
278
|
-
var Reverb = class {
|
|
279
|
-
input;
|
|
280
|
-
output;
|
|
281
|
-
dry;
|
|
282
|
-
wet;
|
|
283
|
-
convolver;
|
|
284
|
-
preDelay;
|
|
285
|
-
ctx;
|
|
286
|
-
_bypassed = false;
|
|
287
|
-
/** Active wet mix (0..1), so bypass can restore it instead of guessing. */
|
|
288
|
-
_wet;
|
|
289
|
-
constructor(ctx, config = {}) {
|
|
290
|
-
this.ctx = ctx;
|
|
291
|
-
this.input = ctx.createGain();
|
|
292
|
-
this.output = ctx.createGain();
|
|
293
|
-
this.dry = ctx.createGain();
|
|
294
|
-
this.wet = ctx.createGain();
|
|
295
|
-
this.preDelay = ctx.createDelay(1);
|
|
296
|
-
this.convolver = ctx.createConvolver();
|
|
297
|
-
const wetMix = config.wet ?? 0.3;
|
|
298
|
-
this._wet = wetMix;
|
|
299
|
-
this.dry.gain.value = 1 - wetMix;
|
|
300
|
-
this.wet.gain.value = wetMix;
|
|
301
|
-
if (config.impulse) {
|
|
302
|
-
this.convolver.buffer = config.impulse;
|
|
303
|
-
} else {
|
|
304
|
-
this.convolver.buffer = this.synthIR(config.decay?.seconds ?? 1.5);
|
|
305
|
-
}
|
|
306
|
-
this.preDelay.delayTime.value = config.decay?.preDelay ?? 0;
|
|
307
|
-
this.input.connect(this.dry).connect(this.output);
|
|
308
|
-
this.input.connect(this.preDelay).connect(this.convolver).connect(this.wet).connect(this.output);
|
|
309
|
-
}
|
|
310
|
-
setWet(mix) {
|
|
311
|
-
const m = Math.max(0, Math.min(1, mix));
|
|
312
|
-
this._wet = m;
|
|
313
|
-
if (this._bypassed) return;
|
|
314
|
-
const t = this.ctx.currentTime;
|
|
315
|
-
this.dry.gain.setValueAtTime(1 - m, t);
|
|
316
|
-
this.wet.gain.setValueAtTime(m, t);
|
|
317
|
-
}
|
|
318
|
-
setImpulse(buffer) {
|
|
319
|
-
this.convolver.buffer = buffer;
|
|
320
|
-
}
|
|
321
|
-
get bypassed() {
|
|
322
|
-
return this._bypassed;
|
|
323
|
-
}
|
|
324
|
-
set bypassed(v) {
|
|
325
|
-
if (this._bypassed === v) return;
|
|
326
|
-
this._bypassed = v;
|
|
327
|
-
const t = this.ctx.currentTime;
|
|
328
|
-
if (v) {
|
|
329
|
-
this.dry.gain.setValueAtTime(1, t);
|
|
330
|
-
this.wet.gain.setValueAtTime(0, t);
|
|
331
|
-
} else {
|
|
332
|
-
this.dry.gain.setValueAtTime(1 - this._wet, t);
|
|
333
|
-
this.wet.gain.setValueAtTime(this._wet, t);
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
dispose() {
|
|
337
|
-
try {
|
|
338
|
-
this.input.disconnect();
|
|
339
|
-
this.dry.disconnect();
|
|
340
|
-
this.wet.disconnect();
|
|
341
|
-
this.preDelay.disconnect();
|
|
342
|
-
this.convolver.disconnect();
|
|
343
|
-
this.output.disconnect();
|
|
344
|
-
} catch {
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
/** Generate a synthetic exponential-decay impulse response. */
|
|
348
|
-
synthIR(seconds) {
|
|
349
|
-
const rate = this.ctx.sampleRate;
|
|
350
|
-
const length = Math.floor(rate * seconds);
|
|
351
|
-
const ir = this.ctx.createBuffer(2, length, rate);
|
|
352
|
-
for (let ch = 0; ch < 2; ch++) {
|
|
353
|
-
const data = ir.getChannelData(ch);
|
|
354
|
-
for (let i = 0; i < length; i++) {
|
|
355
|
-
const t = i / length;
|
|
356
|
-
data[i] = (Math.random() * 2 - 1) * (1 - t) ** 3;
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
return ir;
|
|
360
|
-
}
|
|
361
|
-
};
|
|
362
|
-
|
|
363
|
-
// src/fx/stretch.ts
|
|
364
|
-
var StretchProcessor = class _StretchProcessor {
|
|
365
|
-
factor;
|
|
366
|
-
constructor(stretchFactor = 1) {
|
|
367
|
-
this.factor = stretchFactor;
|
|
368
|
-
}
|
|
369
|
-
process(input) {
|
|
370
|
-
if (this.factor === 1) return new Float32Array(input);
|
|
371
|
-
const outLen = Math.floor(input.length / this.factor);
|
|
372
|
-
const out = new Float32Array(outLen);
|
|
373
|
-
const baseGrain = 4096;
|
|
374
|
-
const grain = Math.max(160, Math.floor(baseGrain / Math.sqrt(this.factor)));
|
|
375
|
-
const overlap = Math.max(48, Math.floor(grain / 4));
|
|
376
|
-
const inHop = Math.max(1, grain - overlap);
|
|
377
|
-
const outHop = Math.max(1, Math.floor(inHop / this.factor));
|
|
378
|
-
const fadeIn = new Float32Array(overlap);
|
|
379
|
-
const fadeOut = new Float32Array(overlap);
|
|
380
|
-
for (let i = 0; i < overlap; i++) {
|
|
381
|
-
const t = i / (overlap - 1);
|
|
382
|
-
const a = Math.sin(Math.PI * t / 2);
|
|
383
|
-
const b = Math.cos(Math.PI * t / 2);
|
|
384
|
-
fadeIn[i] = a * a;
|
|
385
|
-
fadeOut[i] = b * b;
|
|
386
|
-
}
|
|
387
|
-
const jitter = Math.max(0, Math.floor(inHop * 0.03));
|
|
388
|
-
let inPos = 0;
|
|
389
|
-
let outPos = 0;
|
|
390
|
-
while (inPos + grain < input.length && outPos + grain < outLen) {
|
|
391
|
-
let bestPos = inPos;
|
|
392
|
-
if (this.factor < 2.5 && outPos >= overlap) {
|
|
393
|
-
let bestCorr = -Infinity;
|
|
394
|
-
const search = Math.min(64, inHop);
|
|
395
|
-
for (let off = -search; off <= search; off += 4) {
|
|
396
|
-
const test = inPos + off;
|
|
397
|
-
if (test >= 0 && test + overlap < input.length) {
|
|
398
|
-
let corr = 0;
|
|
399
|
-
for (let i = 0; i < overlap; i++) {
|
|
400
|
-
corr += (out[outPos - overlap + i] ?? 0) * (input[test + i] ?? 0);
|
|
401
|
-
}
|
|
402
|
-
if (corr > bestCorr) {
|
|
403
|
-
bestCorr = corr;
|
|
404
|
-
bestPos = test;
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
if (jitter > 0) {
|
|
410
|
-
bestPos = Math.max(
|
|
411
|
-
0,
|
|
412
|
-
Math.min(input.length - grain, bestPos + (Math.random() * 2 - 1) * jitter | 0)
|
|
413
|
-
);
|
|
414
|
-
}
|
|
415
|
-
let eOut = 0;
|
|
416
|
-
let eIn = 0;
|
|
417
|
-
if (outPos > 0) {
|
|
418
|
-
for (let i = 0; i < overlap; i++) {
|
|
419
|
-
const a = out[outPos - overlap + i] ?? 0;
|
|
420
|
-
const b = input[bestPos + i] ?? 0;
|
|
421
|
-
eOut += a * a;
|
|
422
|
-
eIn += b * b;
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
let scale = 1;
|
|
426
|
-
if (eIn > 1e-8 && eOut > 0) scale = Math.sqrt(eOut / eIn);
|
|
427
|
-
scale = Math.min(1.1, Math.max(0.9, scale));
|
|
428
|
-
for (let i = 0; i < grain && outPos + i < outLen; i++) {
|
|
429
|
-
const src = input[bestPos + i] ?? 0;
|
|
430
|
-
if (i < overlap && outPos > 0) {
|
|
431
|
-
const existing = out[outPos + i] ?? 0;
|
|
432
|
-
out[outPos + i] = existing * (fadeOut[i] ?? 0) + src * scale * (fadeIn[i] ?? 0);
|
|
433
|
-
} else {
|
|
434
|
-
out[outPos + i] = src;
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
inPos += inHop;
|
|
438
|
-
outPos += outHop;
|
|
439
|
-
}
|
|
440
|
-
for (let i = outPos; i < outLen; i++) {
|
|
441
|
-
const idxF = i * this.factor;
|
|
442
|
-
const idx = Math.floor(idxF);
|
|
443
|
-
const frac = idxF - idx;
|
|
444
|
-
if (idx >= 0 && idx + 1 < input.length) {
|
|
445
|
-
out[i] = (input[idx] ?? 0) * (1 - frac) + (input[idx + 1] ?? 0) * frac;
|
|
446
|
-
} else {
|
|
447
|
-
out[i] = input[Math.min(input.length - 1, Math.max(0, idx))] ?? 0;
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
if (this.factor > 1) {
|
|
451
|
-
const k = Math.min(0.12, Math.max(0.05, 0.18 / this.factor));
|
|
452
|
-
let prev = 0;
|
|
453
|
-
for (let i = 0; i < out.length; i++) {
|
|
454
|
-
const x = out[i] ?? 0;
|
|
455
|
-
out[i] = x + k * (x - prev);
|
|
456
|
-
prev = x;
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
return out;
|
|
460
|
-
}
|
|
461
|
-
/** Convenience: process an AudioBuffer in place to a new buffer. */
|
|
462
|
-
static stretchBuffer(ctx, src, factor) {
|
|
463
|
-
if (factor === 1) return src;
|
|
464
|
-
const proc = new _StretchProcessor(factor);
|
|
465
|
-
const channels = [];
|
|
466
|
-
for (let c = 0; c < src.numberOfChannels; c++) {
|
|
467
|
-
channels.push(proc.process(src.getChannelData(c)));
|
|
468
|
-
}
|
|
469
|
-
const length = Math.max(...channels.map((ch) => ch.length));
|
|
470
|
-
const out = ctx.createBuffer(src.numberOfChannels, length, src.sampleRate);
|
|
471
|
-
for (let c = 0; c < src.numberOfChannels; c++) {
|
|
472
|
-
out.copyToChannel(channels[c], c);
|
|
473
|
-
}
|
|
474
|
-
return out;
|
|
475
|
-
}
|
|
476
|
-
};
|
|
477
|
-
|
|
478
|
-
// src/fx/stretch-worklet.ts
|
|
479
|
-
var PROCESSOR_NAME = "zvuk-realtime-stretch";
|
|
480
|
-
var loaded = /* @__PURE__ */ new WeakSet();
|
|
481
|
-
var PROCESSOR_SOURCE = `
|
|
1
|
+
var _=class extends Error{constructor(t,e){super(t,e),this.name="ZvukError";}},x=class extends _{constructor(){super("Engine is closed. Create a new engine with createEngine()."),this.name="EngineClosedError";}};function ft(o){return o?` Did you mean "${o}"?`:""}var T=class extends _{constructor(t,e){super(`Bus "${t}" is not configured. Declare it in createEngine({ buses: { ... } }).${ft(e)}`),this.name="BusNotFoundError";}},A=class extends _{constructor(t,e){super(`Sound "${t}" is not loaded. Call engine.loadSound() or load a bank that contains it.${ft(e)}`),this.name="SoundNotFoundError";}};function tt(o){return o instanceof Error?o.message:String(o)}var M=class extends _{constructor(t,e,i){super(i??`Failed to decode audio at "${t}": ${tt(e)}`,{cause:e}),this.name="DecodeError";}},N=class extends _{failures;constructor(t){let e=t.map(i=>` - ${i.name}: ${tt(i.cause)}`).join(`
|
|
2
|
+
`);super(`Failed to preload ${t.length} item(s):
|
|
3
|
+
${e}`,{cause:t[0]?.cause}),this.name="PreloadError",this.failures=t;}},B=class extends M{attempts;constructor(t,e){let i=e[e.length-1],s=e.map(r=>` - ${r.url}: ${tt(r.cause)}`).join(`
|
|
4
|
+
`);super(t[t.length-1]??"<empty>",i?.cause,`Failed to load any of ${t.length} fallback URLs:
|
|
5
|
+
${s}`),this.name="AggregateDecodeError",this.attempts=e;}};var et=class{input;output;compressor;makeup;ctx;_bypassed=false;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.compressor=t.createDynamicsCompressor(),this.makeup=t.createGain(),this.applyConfig(e),this.wire();}applyConfig(t){let e=this.ctx.currentTime;t.threshold!=null&&this.compressor.threshold.setValueAtTime(t.threshold,e),t.knee!=null&&this.compressor.knee.setValueAtTime(t.knee,e),t.ratio!=null&&this.compressor.ratio.setValueAtTime(t.ratio,e),t.attack!=null&&this.compressor.attack.setValueAtTime(t.attack,e),t.release!=null&&this.compressor.release.setValueAtTime(t.release,e),t.makeupGain!=null&&this.makeup.gain.setValueAtTime(10**(t.makeupGain/20),e);}get reduction(){return this.compressor.reduction}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,this.wire());}dispose(){try{this.input.disconnect(),this.compressor.disconnect(),this.makeup.disconnect(),this.output.disconnect();}catch{}}wire(){try{this.input.disconnect(),this.compressor.disconnect(),this.makeup.disconnect();}catch{}this._bypassed?this.input.connect(this.output):(this.input.connect(this.compressor),this.compressor.connect(this.makeup),this.makeup.connect(this.output));}};var it=class{input;output;gain;analyser;buf;rafId=null;lastTickMs=0;envelope=1;targetGain=1;ctx;cfg;_bypassed=false;sourceBus;constructor(t,e,i={}){this.ctx=t,this.sourceBus=e,this.cfg={amount:i.amount??.5,attack:i.attack??.08,release:i.release??.4,threshold:i.threshold??.05},this.input=t.createGain(),this.output=t.createGain(),this.gain=t.createGain(),this.input.connect(this.gain).connect(this.output),this.analyser=t.createAnalyser(),this.analyser.fftSize=1024,this.buf=new Float32Array(this.analyser.fftSize),e.output.connect(this.analyser),typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibility),this.startLoop();}setAmount(t){this.cfg.amount=Math.max(0,Math.min(1,t));}setThreshold(t){this.cfg.threshold=Math.max(0,t);}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,t?(this.releaseToUnity(),this.stopLoop()):(this.resetEnvelope(),this.startLoop()));}dispose(){this.stopLoop(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility);try{this.sourceBus.output.disconnect(this.analyser);}catch{}try{this.input.disconnect(),this.gain.disconnect(),this.analyser.disconnect(),this.output.disconnect();}catch{}}tick=t=>{let e=.016666666666666666;if(t!=null&&this.lastTickMs>0&&(e=Math.min(.1,Math.max(.001,(t-this.lastTickMs)/1e3))),t!=null&&(this.lastTickMs=t),this._bypassed){this.rafId=null;return}this.analyser.getFloatTimeDomainData(this.buf);let i=0;for(let l=0;l<this.buf.length;l++){let d=this.buf[l]??0;i+=d*d;}let s=Math.sqrt(i/this.buf.length),n=Math.max(0,s-this.cfg.threshold)>0?1-this.cfg.amount:1,u=(n<this.envelope?this.cfg.attack:this.cfg.release)||.001,c=1-Math.exp(-e/u);this.envelope=this.envelope+c*(n-this.envelope),Math.abs(this.envelope-this.targetGain)>.001&&(this.targetGain=this.envelope,this.gain.gain.setTargetAtTime(this.envelope,this.ctx.currentTime,.005)),this.rafId=requestAnimationFrame(this.tick);};handleVisibility=()=>{document.visibilityState==="visible"&&(this.resetEnvelope(),this._bypassed||this.startLoop());};resetEnvelope(){this.envelope=1,this.targetGain=1,this.lastTickMs=0,this.releaseToUnity();}releaseToUnity(){this.gain.gain.setTargetAtTime(1,this.ctx.currentTime,.005);}startLoop(){typeof requestAnimationFrame>"u"||this.rafId==null&&this.tick();}stopLoop(){this.rafId!=null&&cancelAnimationFrame(this.rafId),this.rafId=null;}};var st=class{input;output;filter;ctx;_bypassed=false;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.filter=t.createBiquadFilter(),this.filter.type=e.type??"lowpass",this.filter.frequency.value=e.frequency??1e3,this.filter.Q.value=e.q??1,this.filter.gain.value=e.gain??0,this.wire();}setFrequency(t){this.filter.frequency.setValueAtTime(t,this.ctx.currentTime);}setQ(t){this.filter.Q.setValueAtTime(t,this.ctx.currentTime);}setType(t){this.filter.type=t;}setGain(t){this.filter.gain.setValueAtTime(t,this.ctx.currentTime);}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,this.wire());}dispose(){try{this.input.disconnect(),this.filter.disconnect(),this.output.disconnect();}catch{}}wire(){try{this.input.disconnect(),this.filter.disconnect();}catch{}this._bypassed?this.input.connect(this.output):(this.input.connect(this.filter),this.filter.connect(this.output));}};var rt=class{input;output;dry;wet;convolver;preDelay;ctx;_bypassed=false;_wet;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.dry=t.createGain(),this.wet=t.createGain(),this.preDelay=t.createDelay(1),this.convolver=t.createConvolver();let i=e.wet??.3;this._wet=i,this.dry.gain.value=1-i,this.wet.gain.value=i,e.impulse?this.convolver.buffer=e.impulse:this.convolver.buffer=this.synthIR(e.decay?.seconds??1.5),this.preDelay.delayTime.value=e.decay?.preDelay??0,this.input.connect(this.dry).connect(this.output),this.input.connect(this.preDelay).connect(this.convolver).connect(this.wet).connect(this.output);}setWet(t){let e=Math.max(0,Math.min(1,t));if(this._wet=e,this._bypassed)return;let i=this.ctx.currentTime;this.dry.gain.setValueAtTime(1-e,i),this.wet.gain.setValueAtTime(e,i);}setImpulse(t){this.convolver.buffer=t;}get bypassed(){return this._bypassed}set bypassed(t){if(this._bypassed===t)return;this._bypassed=t;let e=this.ctx.currentTime;t?(this.dry.gain.setValueAtTime(1,e),this.wet.gain.setValueAtTime(0,e)):(this.dry.gain.setValueAtTime(1-this._wet,e),this.wet.gain.setValueAtTime(this._wet,e));}dispose(){try{this.input.disconnect(),this.dry.disconnect(),this.wet.disconnect(),this.preDelay.disconnect(),this.convolver.disconnect(),this.output.disconnect();}catch{}}synthIR(t){let e=this.ctx.sampleRate,i=Math.floor(e*t),s=this.ctx.createBuffer(2,i,e);for(let r=0;r<2;r++){let n=s.getChannelData(r);for(let a=0;a<i;a++){let u=a/i;n[a]=(Math.random()*2-1)*(1-u)**3;}}return s}};var ot=class o{factor;constructor(t=1){this.factor=t;}process(t){if(this.factor===1)return new Float32Array(t);let e=Math.floor(t.length/this.factor),i=new Float32Array(e),r=Math.max(160,Math.floor(4096/Math.sqrt(this.factor))),n=Math.max(48,Math.floor(r/4)),a=Math.max(1,r-n),u=Math.max(1,Math.floor(a/this.factor)),c=new Float32Array(n),l=new Float32Array(n);for(let p=0;p<n;p++){let b=p/(n-1),h=Math.sin(Math.PI*b/2),v=Math.cos(Math.PI*b/2);c[p]=h*h,l[p]=v*v;}let d=Math.max(0,Math.floor(a*.03)),m=0,g=0;for(;m+r<t.length&&g+r<e;){let p=m;if(this.factor<2.5&&g>=n){let f=-1/0,y=Math.min(64,a);for(let O=-y;O<=y;O+=4){let W=m+O;if(W>=0&&W+n<t.length){let J=0;for(let j=0;j<n;j++)J+=(i[g-n+j]??0)*(t[W+j]??0);J>f&&(f=J,p=W);}}}d>0&&(p=Math.max(0,Math.min(t.length-r,p+(Math.random()*2-1)*d|0)));let b=0,h=0;if(g>0)for(let f=0;f<n;f++){let y=i[g-n+f]??0,O=t[p+f]??0;b+=y*y,h+=O*O;}let v=1;h>1e-8&&b>0&&(v=Math.sqrt(b/h)),v=Math.min(1.1,Math.max(.9,v));for(let f=0;f<r&&g+f<e;f++){let y=t[p+f]??0;if(f<n&&g>0){let O=i[g+f]??0;i[g+f]=O*(l[f]??0)+y*v*(c[f]??0);}else i[g+f]=y;}m+=a,g+=u;}for(let p=g;p<e;p++){let b=p*this.factor,h=Math.floor(b),v=b-h;h>=0&&h+1<t.length?i[p]=(t[h]??0)*(1-v)+(t[h+1]??0)*v:i[p]=t[Math.min(t.length-1,Math.max(0,h))]??0;}if(this.factor>1){let p=Math.min(.12,Math.max(.05,.18/this.factor)),b=0;for(let h=0;h<i.length;h++){let v=i[h]??0;i[h]=v+p*(v-b),b=v;}}return i}static stretchBuffer(t,e,i){if(i===1)return e;let s=new o(i),r=[];for(let u=0;u<e.numberOfChannels;u++)r.push(s.process(e.getChannelData(u)));let n=Math.max(...r.map(u=>u.length)),a=t.createBuffer(e.numberOfChannels,n,e.sampleRate);for(let u=0;u<e.numberOfChannels;u++)a.copyToChannel(r[u],u);return a}};var gt="zvuk-realtime-stretch",mt=new WeakSet,Mt=`
|
|
482
6
|
class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
|
|
483
7
|
static get parameterDescriptors() {
|
|
484
8
|
return [
|
|
@@ -542,2816 +66,6 @@ class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
|
|
|
542
66
|
}
|
|
543
67
|
}
|
|
544
68
|
|
|
545
|
-
registerProcessor('${
|
|
546
|
-
`;
|
|
547
|
-
async function ensureStretchWorklet(ctx) {
|
|
548
|
-
if (loaded.has(ctx)) return;
|
|
549
|
-
const w = ctx.audioWorklet;
|
|
550
|
-
if (!w) throw new Error("AudioWorklet not supported in this context");
|
|
551
|
-
const blob = new Blob([PROCESSOR_SOURCE], { type: "application/javascript" });
|
|
552
|
-
const url = URL.createObjectURL(blob);
|
|
553
|
-
try {
|
|
554
|
-
await w.addModule(url);
|
|
555
|
-
} finally {
|
|
556
|
-
URL.revokeObjectURL(url);
|
|
557
|
-
}
|
|
558
|
-
loaded.add(ctx);
|
|
559
|
-
}
|
|
560
|
-
function createStretchWorkletNode(ctx, options = {}) {
|
|
561
|
-
const Ctor = globalThis.AudioWorkletNode;
|
|
562
|
-
if (!Ctor) throw new Error("AudioWorkletNode not available");
|
|
563
|
-
const node = new Ctor(ctx, PROCESSOR_NAME, {
|
|
564
|
-
numberOfInputs: 1,
|
|
565
|
-
numberOfOutputs: 1,
|
|
566
|
-
outputChannelCount: [2],
|
|
567
|
-
processorOptions: { grainSize: options.grainSize ?? 1024 }
|
|
568
|
-
});
|
|
569
|
-
const stretch = node.parameters.get("stretch");
|
|
570
|
-
if (stretch && options.stretchFactor != null) stretch.value = options.stretchFactor;
|
|
571
|
-
const disposable = node;
|
|
572
|
-
Object.defineProperty(disposable, "stretch", {
|
|
573
|
-
value: stretch,
|
|
574
|
-
enumerable: true
|
|
575
|
-
});
|
|
576
|
-
disposable.dispose = () => {
|
|
577
|
-
try {
|
|
578
|
-
node.disconnect();
|
|
579
|
-
} catch {
|
|
580
|
-
}
|
|
581
|
-
};
|
|
582
|
-
return disposable;
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
// src/mixer/curve.ts
|
|
586
|
-
function applyRamp(param, now, to, duration, curve) {
|
|
587
|
-
const seconds = Math.max(0, duration);
|
|
588
|
-
const from = param.value;
|
|
589
|
-
param.cancelScheduledValues(now);
|
|
590
|
-
param.setValueAtTime(from, now);
|
|
591
|
-
if (seconds === 0) {
|
|
592
|
-
param.setValueAtTime(to, now);
|
|
593
|
-
return;
|
|
594
|
-
}
|
|
595
|
-
if (curve === "linear") {
|
|
596
|
-
param.linearRampToValueAtTime(to, now + seconds);
|
|
597
|
-
return;
|
|
598
|
-
}
|
|
599
|
-
const samples = sampleCurve(from, to, curve, 64);
|
|
600
|
-
param.setValueCurveAtTime(samples, now, seconds);
|
|
601
|
-
}
|
|
602
|
-
function equalPowerCurve(from, to, n = 33) {
|
|
603
|
-
return sampleCurve(from, to, "equal-power", n);
|
|
604
|
-
}
|
|
605
|
-
function sampleCurve(from, to, curve, n) {
|
|
606
|
-
const out = new Float32Array(n);
|
|
607
|
-
const rising = to >= from;
|
|
608
|
-
for (let i = 0; i < n; i++) {
|
|
609
|
-
const t = i / (n - 1);
|
|
610
|
-
const eased = ease(t, curve, rising);
|
|
611
|
-
out[i] = from + (to - from) * eased;
|
|
612
|
-
}
|
|
613
|
-
return out;
|
|
614
|
-
}
|
|
615
|
-
function ease(t, curve, rising = true) {
|
|
616
|
-
switch (curve) {
|
|
617
|
-
case "easeIn":
|
|
618
|
-
return t * t;
|
|
619
|
-
case "easeOut":
|
|
620
|
-
return 1 - (1 - t) * (1 - t);
|
|
621
|
-
case "easeInOut":
|
|
622
|
-
return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
|
|
623
|
-
case "equal-power": {
|
|
624
|
-
return rising ? Math.sin(t * Math.PI / 2) : 1 - Math.cos(t * Math.PI / 2);
|
|
625
|
-
}
|
|
626
|
-
default:
|
|
627
|
-
return t;
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
// src/mixer/bus.ts
|
|
632
|
-
var Send = class {
|
|
633
|
-
source;
|
|
634
|
-
target;
|
|
635
|
-
post;
|
|
636
|
-
gainNode;
|
|
637
|
-
ctx;
|
|
638
|
-
disposed = false;
|
|
639
|
-
constructor(source, target, options, ctx) {
|
|
640
|
-
this.source = source;
|
|
641
|
-
this.target = target;
|
|
642
|
-
this.post = options.post ?? true;
|
|
643
|
-
this.ctx = ctx;
|
|
644
|
-
this.gainNode = ctx.createGain();
|
|
645
|
-
this.gainNode.gain.value = clamp01(options.amount ?? 1);
|
|
646
|
-
const tap = this.post ? source.output : source.input;
|
|
647
|
-
tap.connect(this.gainNode);
|
|
648
|
-
this.gainNode.connect(target.input);
|
|
649
|
-
}
|
|
650
|
-
/** Live send level (0..1). Setter ramps over 10 ms to avoid clicks. */
|
|
651
|
-
get amount() {
|
|
652
|
-
return this.gainNode.gain.value;
|
|
653
|
-
}
|
|
654
|
-
set amount(v) {
|
|
655
|
-
if (this.disposed) return;
|
|
656
|
-
applyRamp(this.gainNode.gain, this.ctx.currentTime, clamp01(v), 0.01, "linear");
|
|
657
|
-
}
|
|
658
|
-
/** Fade the send to `target` over `duration` seconds. */
|
|
659
|
-
fadeTo(target, duration, curve = "linear") {
|
|
660
|
-
if (this.disposed) return Promise.resolve();
|
|
661
|
-
applyRamp(this.gainNode.gain, this.ctx.currentTime, clamp01(target), duration, curve);
|
|
662
|
-
if (duration <= 0) return Promise.resolve();
|
|
663
|
-
return new Promise((res) => setTimeout(res, duration * 1e3));
|
|
664
|
-
}
|
|
665
|
-
dispose() {
|
|
666
|
-
if (this.disposed) return;
|
|
667
|
-
this.disposed = true;
|
|
668
|
-
try {
|
|
669
|
-
this.gainNode.disconnect();
|
|
670
|
-
} catch {
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
};
|
|
674
|
-
var Bus = class {
|
|
675
|
-
name;
|
|
676
|
-
input;
|
|
677
|
-
/** Sub-bus the FX chain splices into: input → fxInput → (fx…) → output. */
|
|
678
|
-
fxInput;
|
|
679
|
-
/** Output node — connect to master.input or another bus.input for sends. */
|
|
680
|
-
output;
|
|
681
|
-
_level;
|
|
682
|
-
_muted;
|
|
683
|
-
_soloed = false;
|
|
684
|
-
/** True while the engine's solo rule is silencing this (non-soloed) bus. */
|
|
685
|
-
_soloVeiled = false;
|
|
686
|
-
ctx;
|
|
687
|
-
_concurrency;
|
|
688
|
-
_voices = /* @__PURE__ */ new Set();
|
|
689
|
-
_fxChain = [];
|
|
690
|
-
_sends = [];
|
|
691
|
-
// Lazy meter tap. Connected as a passive sibling of bus.output → master.input
|
|
692
|
-
// so the audio path is unchanged.
|
|
693
|
-
_meterAnalyser = null;
|
|
694
|
-
_meterBuf = null;
|
|
695
|
-
/**
|
|
696
|
-
* Engine-injected callback fired when this bus's solo state changes.
|
|
697
|
-
* The Engine uses it to coordinate the global "any soloed → mute the
|
|
698
|
-
* rest" rule across every bus in the graph. Bus does not depend on
|
|
699
|
-
* Engine; the callback is the only escape hatch.
|
|
700
|
-
*/
|
|
701
|
-
notifySoloChange;
|
|
702
|
-
constructor(ctx, name, config = {}) {
|
|
703
|
-
this.ctx = ctx;
|
|
704
|
-
this.name = name;
|
|
705
|
-
this._level = config.level ?? 1;
|
|
706
|
-
this._muted = config.mute ?? false;
|
|
707
|
-
this._concurrency = config.concurrency ?? null;
|
|
708
|
-
this.input = ctx.createGain();
|
|
709
|
-
this.fxInput = ctx.createGain();
|
|
710
|
-
this.output = ctx.createGain();
|
|
711
|
-
this.input.connect(this.fxInput);
|
|
712
|
-
this.fxInput.connect(this.output);
|
|
713
|
-
this.output.gain.value = this._muted ? 0 : this._level;
|
|
714
|
-
}
|
|
715
|
-
get level() {
|
|
716
|
-
return this._level;
|
|
717
|
-
}
|
|
718
|
-
set level(v) {
|
|
719
|
-
this._level = clamp01(v);
|
|
720
|
-
if (!this._muted && !this._soloVeiled) this.rampOutput(this._level, 0.01);
|
|
721
|
-
}
|
|
722
|
-
get muted() {
|
|
723
|
-
return this._muted;
|
|
724
|
-
}
|
|
725
|
-
set muted(v) {
|
|
726
|
-
this._muted = v;
|
|
727
|
-
this.rampOutput(v || this._soloVeiled ? 0 : this._level, 0.01);
|
|
728
|
-
}
|
|
729
|
-
/** Fade the bus output to `target` over `duration` seconds. */
|
|
730
|
-
fadeTo(target, duration, curve = "linear") {
|
|
731
|
-
const to = clamp01(target);
|
|
732
|
-
this._level = to;
|
|
733
|
-
if (this._muted || this._soloVeiled) return wait(duration);
|
|
734
|
-
return this.ramp(to, duration, curve);
|
|
735
|
-
}
|
|
736
|
-
/** Active voice count on this bus. */
|
|
737
|
-
get voiceCount() {
|
|
738
|
-
return this._voices.size;
|
|
739
|
-
}
|
|
740
|
-
/** Read-only iterator over active voices. */
|
|
741
|
-
voices() {
|
|
742
|
-
return Array.from(this._voices);
|
|
743
|
-
}
|
|
744
|
-
/** Concurrency config — read it for UI, mutate via setConcurrency. */
|
|
745
|
-
get concurrency() {
|
|
746
|
-
return this._concurrency;
|
|
747
|
-
}
|
|
748
|
-
setConcurrency(c) {
|
|
749
|
-
this._concurrency = c;
|
|
750
|
-
}
|
|
751
|
-
/**
|
|
752
|
-
* Called by Engine right before adding a new Voice. Returns a Voice that
|
|
753
|
-
* was stolen to make room (so the engine can release it from its tracking),
|
|
754
|
-
* or null if no steal was needed (or the new voice itself was rejected,
|
|
755
|
-
* in which case onReject is invoked instead).
|
|
756
|
-
*/
|
|
757
|
-
applyConcurrencyOnSpawn(newVoice, onReject) {
|
|
758
|
-
const c = this._concurrency;
|
|
759
|
-
if (!c) return null;
|
|
760
|
-
if (this._voices.size <= c.max) return null;
|
|
761
|
-
const strategy = c.steal ?? "oldest";
|
|
762
|
-
if (strategy === "none") {
|
|
763
|
-
onReject();
|
|
764
|
-
return null;
|
|
765
|
-
}
|
|
766
|
-
const victim = pickVictim(this._voices, strategy, newVoice);
|
|
767
|
-
if (!victim) {
|
|
768
|
-
onReject();
|
|
769
|
-
return null;
|
|
770
|
-
}
|
|
771
|
-
victim.stop();
|
|
772
|
-
return victim;
|
|
773
|
-
}
|
|
774
|
-
/** Engine-only: register an active voice. */
|
|
775
|
-
trackVoice(v) {
|
|
776
|
-
this._voices.add(v);
|
|
777
|
-
}
|
|
778
|
-
/** Engine-only: deregister a finished voice. */
|
|
779
|
-
releaseVoice(v) {
|
|
780
|
-
this._voices.delete(v);
|
|
781
|
-
}
|
|
782
|
-
/** Add an FX insert to the bus's FX chain (post-input, pre-output). */
|
|
783
|
-
addFx(fx) {
|
|
784
|
-
this._fxChain.push(fx);
|
|
785
|
-
this.rewireFxChain();
|
|
786
|
-
}
|
|
787
|
-
removeFx(fx) {
|
|
788
|
-
const idx = this._fxChain.indexOf(fx);
|
|
789
|
-
if (idx === -1) return;
|
|
790
|
-
this._fxChain.splice(idx, 1);
|
|
791
|
-
this.rewireFxChain();
|
|
792
|
-
}
|
|
793
|
-
fx() {
|
|
794
|
-
return [...this._fxChain];
|
|
795
|
-
}
|
|
796
|
-
/**
|
|
797
|
-
* Live amplitude readout on the bus output. Returns `{ rms, peak }` as
|
|
798
|
-
* linear values in [0..1]. The first call lazily attaches an AnalyserNode
|
|
799
|
-
* as a passive sibling of `bus.output → master.input`; subsequent calls
|
|
800
|
-
* reuse it.
|
|
801
|
-
*
|
|
802
|
-
* Use this to drive a mixer-dashboard VU meter, drive automation that
|
|
803
|
-
* reacts to overall bus level, or implement custom voice-stealing rules.
|
|
804
|
-
*/
|
|
805
|
-
meter() {
|
|
806
|
-
if (!this._meterAnalyser) {
|
|
807
|
-
const a = this.ctx.createAnalyser();
|
|
808
|
-
a.fftSize = 1024;
|
|
809
|
-
this.output.connect(a);
|
|
810
|
-
this._meterAnalyser = a;
|
|
811
|
-
this._meterBuf = new Float32Array(a.fftSize);
|
|
812
|
-
}
|
|
813
|
-
const buf = this._meterBuf;
|
|
814
|
-
this._meterAnalyser.getFloatTimeDomainData(buf);
|
|
815
|
-
let sumSq = 0;
|
|
816
|
-
let peak = 0;
|
|
817
|
-
for (let i = 0; i < buf.length; i++) {
|
|
818
|
-
const s = buf[i] ?? 0;
|
|
819
|
-
sumSq += s * s;
|
|
820
|
-
const a = Math.abs(s);
|
|
821
|
-
if (a > peak) peak = a;
|
|
822
|
-
}
|
|
823
|
-
return { rms: Math.sqrt(sumSq / buf.length), peak };
|
|
824
|
-
}
|
|
825
|
-
/**
|
|
826
|
-
* Route a copy of this bus's signal into another bus at the configured
|
|
827
|
-
* level. `target.input` mixes the send naturally with whatever else is
|
|
828
|
-
* already feeding it, so the typical pattern — "send 30 % of music to a
|
|
829
|
-
* dedicated reverb bus" — is just two lines:
|
|
830
|
-
*
|
|
831
|
-
* ```ts
|
|
832
|
-
* const verbSend = engine.bus('music').send(engine.bus('reverb'), { amount: 0.3 });
|
|
833
|
-
* verbSend.amount = 0.5; // turn it up live
|
|
834
|
-
* verbSend.dispose(); // remove the send entirely
|
|
835
|
-
* ```
|
|
836
|
-
*
|
|
837
|
-
* Default tap is post-fader / post-FX (`post: true`); set `post: false`
|
|
838
|
-
* if you want a monitor send that hears the dry pre-fader signal.
|
|
839
|
-
*/
|
|
840
|
-
send(target, options = {}) {
|
|
841
|
-
const send = new Send(this, target, options, this.ctx);
|
|
842
|
-
this._sends.push(send);
|
|
843
|
-
return send;
|
|
844
|
-
}
|
|
845
|
-
/** Remove a previously-created send. Idempotent. */
|
|
846
|
-
removeSend(send) {
|
|
847
|
-
const idx = this._sends.indexOf(send);
|
|
848
|
-
if (idx === -1) return;
|
|
849
|
-
this._sends.splice(idx, 1);
|
|
850
|
-
send.dispose();
|
|
851
|
-
}
|
|
852
|
-
/** Read-only snapshot of every active send originating on this bus. */
|
|
853
|
-
sends() {
|
|
854
|
-
return [...this._sends];
|
|
855
|
-
}
|
|
856
|
-
/**
|
|
857
|
-
* Solo this bus. The engine coordinates the global rule: while any bus
|
|
858
|
-
* is soloed, every non-soloed bus is muted. Soloing multiple buses is
|
|
859
|
-
* additive — they all stay audible. Calling `unsolo()` (or `solo(false)`)
|
|
860
|
-
* removes this bus from the soloed set.
|
|
861
|
-
*
|
|
862
|
-
* Solo state is independent of `muted`; un-soloing returns the bus to
|
|
863
|
-
* whatever its `muted` setting was. Useful in mixer UIs where the user
|
|
864
|
-
* wants to A/B a single channel without disturbing the rest of the mix.
|
|
865
|
-
*/
|
|
866
|
-
solo(on = true) {
|
|
867
|
-
if (this._soloed === on) return;
|
|
868
|
-
this._soloed = on;
|
|
869
|
-
this.notifySoloChange?.(this, on);
|
|
870
|
-
}
|
|
871
|
-
/** Turn solo off on this bus. Equivalent to `solo(false)`. */
|
|
872
|
-
unsolo() {
|
|
873
|
-
this.solo(false);
|
|
874
|
-
}
|
|
875
|
-
/** True when this bus is in the engine's solo set. */
|
|
876
|
-
get soloed() {
|
|
877
|
-
return this._soloed;
|
|
878
|
-
}
|
|
879
|
-
/**
|
|
880
|
-
* Engine-only. Apply a transient mute (or restore) driven by the global
|
|
881
|
-
* solo state. Distinct from `muted` so un-soloing returns the bus to its
|
|
882
|
-
* user-visible mute state without re-rendering.
|
|
883
|
-
*/
|
|
884
|
-
applySoloVeil(soloMute) {
|
|
885
|
-
this._soloVeiled = soloMute;
|
|
886
|
-
const target = this._muted ? 0 : soloMute ? 0 : this._level;
|
|
887
|
-
this.rampOutput(target, 0.01);
|
|
888
|
-
}
|
|
889
|
-
rewireFxChain() {
|
|
890
|
-
try {
|
|
891
|
-
this.fxInput.disconnect();
|
|
892
|
-
for (const fx of this._fxChain) fx.output.disconnect();
|
|
893
|
-
} catch {
|
|
894
|
-
}
|
|
895
|
-
let head = this.fxInput;
|
|
896
|
-
for (const fx of this._fxChain) {
|
|
897
|
-
head.connect(fx.input);
|
|
898
|
-
head = fx.output;
|
|
899
|
-
}
|
|
900
|
-
head.connect(this.output);
|
|
901
|
-
}
|
|
902
|
-
rampOutput(to, duration) {
|
|
903
|
-
void this.ramp(to, duration, "linear");
|
|
904
|
-
}
|
|
905
|
-
ramp(to, duration, curve) {
|
|
906
|
-
const param = this.output.gain;
|
|
907
|
-
const now = this.ctx.currentTime;
|
|
908
|
-
applyRamp(param, now, to, duration, curve);
|
|
909
|
-
return wait(duration);
|
|
910
|
-
}
|
|
911
|
-
dispose() {
|
|
912
|
-
for (const send of this._sends) send.dispose();
|
|
913
|
-
this._sends = [];
|
|
914
|
-
for (const fx of this._fxChain) fx.dispose();
|
|
915
|
-
this._fxChain = [];
|
|
916
|
-
try {
|
|
917
|
-
this.input.disconnect();
|
|
918
|
-
this.fxInput.disconnect();
|
|
919
|
-
this.output.disconnect();
|
|
920
|
-
this._meterAnalyser?.disconnect();
|
|
921
|
-
} catch {
|
|
922
|
-
}
|
|
923
|
-
this._meterAnalyser = null;
|
|
924
|
-
this._meterBuf = null;
|
|
925
|
-
}
|
|
926
|
-
};
|
|
927
|
-
function clamp01(v) {
|
|
928
|
-
if (Number.isNaN(v)) return 0;
|
|
929
|
-
return Math.min(1, Math.max(0, v));
|
|
930
|
-
}
|
|
931
|
-
function wait(seconds) {
|
|
932
|
-
if (seconds <= 0) return Promise.resolve();
|
|
933
|
-
return new Promise((res) => setTimeout(res, seconds * 1e3));
|
|
934
|
-
}
|
|
935
|
-
function pickVictim(voices, strategy, newVoice) {
|
|
936
|
-
const rmsCache = strategy === "quietest" ? /* @__PURE__ */ new Map() : null;
|
|
937
|
-
if (rmsCache) {
|
|
938
|
-
for (const v of voices) if (v !== newVoice) rmsCache.set(v, v.level().rms);
|
|
939
|
-
}
|
|
940
|
-
let victim = null;
|
|
941
|
-
for (const v of voices) {
|
|
942
|
-
if (v === newVoice) continue;
|
|
943
|
-
if (!victim) {
|
|
944
|
-
victim = v;
|
|
945
|
-
continue;
|
|
946
|
-
}
|
|
947
|
-
switch (strategy) {
|
|
948
|
-
case "oldest":
|
|
949
|
-
if (v.startedAt < victim.startedAt) victim = v;
|
|
950
|
-
break;
|
|
951
|
-
case "lowest-priority":
|
|
952
|
-
if (v.priority < victim.priority) victim = v;
|
|
953
|
-
break;
|
|
954
|
-
case "quietest": {
|
|
955
|
-
const a = rmsCache?.get(v) ?? 0;
|
|
956
|
-
const b = rmsCache?.get(victim) ?? 0;
|
|
957
|
-
if (a < b) victim = v;
|
|
958
|
-
break;
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
}
|
|
962
|
-
return victim;
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
// src/mixer/bus-group.ts
|
|
966
|
-
var BusGroup = class {
|
|
967
|
-
name;
|
|
968
|
-
members;
|
|
969
|
-
constructor(name, members) {
|
|
970
|
-
this.name = name;
|
|
971
|
-
this.members = members;
|
|
972
|
-
}
|
|
973
|
-
/** Set the level on every member. Same 10 ms ramp as direct `bus.level =`. */
|
|
974
|
-
set level(v) {
|
|
975
|
-
for (const b of this.members) b.level = v;
|
|
976
|
-
}
|
|
977
|
-
/**
|
|
978
|
-
* Read the current level. Returns the average across members — useful
|
|
979
|
-
* when every member shares a level (the common case) and informational
|
|
980
|
-
* otherwise.
|
|
981
|
-
*/
|
|
982
|
-
get level() {
|
|
983
|
-
if (this.members.length === 0) return 0;
|
|
984
|
-
let sum = 0;
|
|
985
|
-
for (const b of this.members) sum += b.level;
|
|
986
|
-
return sum / this.members.length;
|
|
987
|
-
}
|
|
988
|
-
set muted(v) {
|
|
989
|
-
for (const b of this.members) b.muted = v;
|
|
990
|
-
}
|
|
991
|
-
/** True if every member is currently muted. */
|
|
992
|
-
get muted() {
|
|
993
|
-
if (this.members.length === 0) return false;
|
|
994
|
-
return this.members.every((b) => b.muted);
|
|
995
|
-
}
|
|
996
|
-
/**
|
|
997
|
-
* Fade every member to `target` over `duration` seconds. Returns when
|
|
998
|
-
* the slowest leg completes — in practice they're all equal because
|
|
999
|
-
* each member uses the same duration.
|
|
1000
|
-
*/
|
|
1001
|
-
fadeTo(target, duration, curve = "linear") {
|
|
1002
|
-
return Promise.all(this.members.map((b) => b.fadeTo(target, duration, curve))).then(() => void 0);
|
|
1003
|
-
}
|
|
1004
|
-
/** Solo every member of the group. Engine handles the global mute-the-rest rule. */
|
|
1005
|
-
solo(on = true) {
|
|
1006
|
-
for (const b of this.members) b.solo(on);
|
|
1007
|
-
}
|
|
1008
|
-
/** Un-solo every member. */
|
|
1009
|
-
unsolo() {
|
|
1010
|
-
this.solo(false);
|
|
1011
|
-
}
|
|
1012
|
-
};
|
|
1013
|
-
|
|
1014
|
-
// src/params/parameter.ts
|
|
1015
|
-
var Parameter = class {
|
|
1016
|
-
name;
|
|
1017
|
-
_value;
|
|
1018
|
-
subs = /* @__PURE__ */ new Set();
|
|
1019
|
-
constructor(name, initial) {
|
|
1020
|
-
this.name = name;
|
|
1021
|
-
this._value = initial;
|
|
1022
|
-
}
|
|
1023
|
-
get value() {
|
|
1024
|
-
return this._value;
|
|
1025
|
-
}
|
|
1026
|
-
set(v) {
|
|
1027
|
-
if (v === this._value) return;
|
|
1028
|
-
this._value = v;
|
|
1029
|
-
for (const s of this.subs) s(v);
|
|
1030
|
-
}
|
|
1031
|
-
subscribe(fn) {
|
|
1032
|
-
this.subs.add(fn);
|
|
1033
|
-
fn(this._value);
|
|
1034
|
-
return () => this.subs.delete(fn);
|
|
1035
|
-
}
|
|
1036
|
-
/**
|
|
1037
|
-
* Bind a setter to this parameter. The parameter's [0..1] value (clamped)
|
|
1038
|
-
* is mapped to [from..to] via `curve`, then the setter is called with the
|
|
1039
|
-
* mapped value. Returns an unbind function.
|
|
1040
|
-
*/
|
|
1041
|
-
bindTo(setter, opts = {}) {
|
|
1042
|
-
const from = opts.from ?? 0;
|
|
1043
|
-
const to = opts.to ?? 1;
|
|
1044
|
-
const curve = opts.curve ?? "linear";
|
|
1045
|
-
const rising = to >= from;
|
|
1046
|
-
return this.subscribe((v) => {
|
|
1047
|
-
const t = Math.max(0, Math.min(1, v));
|
|
1048
|
-
const eased = ease2(t, curve, rising);
|
|
1049
|
-
setter(from + (to - from) * eased);
|
|
1050
|
-
});
|
|
1051
|
-
}
|
|
1052
|
-
};
|
|
1053
|
-
function ease2(t, curve, rising = true) {
|
|
1054
|
-
switch (curve) {
|
|
1055
|
-
case "easeIn":
|
|
1056
|
-
return t * t;
|
|
1057
|
-
case "easeOut":
|
|
1058
|
-
return 1 - (1 - t) * (1 - t);
|
|
1059
|
-
case "easeInOut":
|
|
1060
|
-
return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
|
|
1061
|
-
case "equal-power":
|
|
1062
|
-
return rising ? Math.sin(t * Math.PI / 2) : 1 - Math.cos(t * Math.PI / 2);
|
|
1063
|
-
default:
|
|
1064
|
-
return t;
|
|
1065
|
-
}
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
// src/runtime/codecs.ts
|
|
1069
|
-
var EXT_TO_MIME = {
|
|
1070
|
-
webm: 'audio/webm; codecs="opus"',
|
|
1071
|
-
opus: 'audio/ogg; codecs="opus"',
|
|
1072
|
-
ogg: 'audio/ogg; codecs="vorbis"',
|
|
1073
|
-
m4a: 'audio/mp4; codecs="mp4a.40.2"',
|
|
1074
|
-
mp4: 'audio/mp4; codecs="mp4a.40.2"',
|
|
1075
|
-
aac: 'audio/mp4; codecs="mp4a.40.2"',
|
|
1076
|
-
mp3: "audio/mpeg",
|
|
1077
|
-
wav: "audio/wav",
|
|
1078
|
-
flac: "audio/flac"
|
|
1079
|
-
};
|
|
1080
|
-
var probe = null;
|
|
1081
|
-
function canPlay(mime) {
|
|
1082
|
-
if (typeof document === "undefined") return true;
|
|
1083
|
-
if (!probe) {
|
|
1084
|
-
try {
|
|
1085
|
-
probe = document.createElement("audio");
|
|
1086
|
-
} catch {
|
|
1087
|
-
return true;
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
const result = probe.canPlayType(mime);
|
|
1091
|
-
return result === "probably" || result === "maybe";
|
|
1092
|
-
}
|
|
1093
|
-
function mimeForUrl(url) {
|
|
1094
|
-
const m = /\.([a-z0-9]+)(?:[?#]|$)/i.exec(url);
|
|
1095
|
-
if (!m?.[1]) return null;
|
|
1096
|
-
return EXT_TO_MIME[m[1].toLowerCase()] ?? null;
|
|
1097
|
-
}
|
|
1098
|
-
function pickSource(urls) {
|
|
1099
|
-
if (urls.length === 0) throw new Error("pickSource requires at least one URL");
|
|
1100
|
-
for (const url of urls) {
|
|
1101
|
-
const mime = mimeForUrl(url);
|
|
1102
|
-
if (!mime) continue;
|
|
1103
|
-
if (canPlay(mime)) return url;
|
|
1104
|
-
}
|
|
1105
|
-
return urls[0];
|
|
1106
|
-
}
|
|
1107
|
-
function pickSourceOrder(urls) {
|
|
1108
|
-
if (urls.length === 0) return urls;
|
|
1109
|
-
const playable = [];
|
|
1110
|
-
const unknown = [];
|
|
1111
|
-
for (const url of urls) {
|
|
1112
|
-
const mime = mimeForUrl(url);
|
|
1113
|
-
if (mime && canPlay(mime)) playable.push(url);
|
|
1114
|
-
else unknown.push(url);
|
|
1115
|
-
}
|
|
1116
|
-
return [...playable, ...unknown];
|
|
1117
|
-
}
|
|
1118
|
-
|
|
1119
|
-
// src/runtime/context.ts
|
|
1120
|
-
var AudioContextHost = class {
|
|
1121
|
-
_ctx = null;
|
|
1122
|
-
_state = "cold";
|
|
1123
|
-
_unlocking = null;
|
|
1124
|
-
_listeners = /* @__PURE__ */ new Set();
|
|
1125
|
-
opts;
|
|
1126
|
-
constructor(opts = {}) {
|
|
1127
|
-
this.opts = opts;
|
|
1128
|
-
}
|
|
1129
|
-
get state() {
|
|
1130
|
-
return this._state;
|
|
1131
|
-
}
|
|
1132
|
-
/** Returns the live AudioContext, constructing it if necessary. */
|
|
1133
|
-
touch() {
|
|
1134
|
-
if (this._state === "closed") throw new EngineClosedError();
|
|
1135
|
-
if (!this._ctx) {
|
|
1136
|
-
const opts = {};
|
|
1137
|
-
if (this.opts.latencyHint != null) opts.latencyHint = this.opts.latencyHint;
|
|
1138
|
-
this._ctx = new AudioContext(opts);
|
|
1139
|
-
this.attachVisibilityHandler();
|
|
1140
|
-
this.attachStateChangeHandler(this._ctx);
|
|
1141
|
-
}
|
|
1142
|
-
return this._ctx;
|
|
1143
|
-
}
|
|
1144
|
-
/** Returns null instead of constructing — use when you need to peek. */
|
|
1145
|
-
peek() {
|
|
1146
|
-
return this._ctx;
|
|
1147
|
-
}
|
|
1148
|
-
/** Resume the context. Safe to call from any handler; promise resolves to live state. */
|
|
1149
|
-
async unlock() {
|
|
1150
|
-
if (this._state === "closed") throw new EngineClosedError();
|
|
1151
|
-
if (this._state === "live") return;
|
|
1152
|
-
if (this._unlocking) return this._unlocking;
|
|
1153
|
-
this.setState("unlocking");
|
|
1154
|
-
const ctx = this.touch();
|
|
1155
|
-
this._unlocking = (async () => {
|
|
1156
|
-
try {
|
|
1157
|
-
if (ctx.state === "suspended") await ctx.resume();
|
|
1158
|
-
this.setState("live");
|
|
1159
|
-
} catch (e) {
|
|
1160
|
-
this.setState("cold");
|
|
1161
|
-
throw e;
|
|
1162
|
-
} finally {
|
|
1163
|
-
this._unlocking = null;
|
|
1164
|
-
}
|
|
1165
|
-
})();
|
|
1166
|
-
return this._unlocking;
|
|
1167
|
-
}
|
|
1168
|
-
/** Sample-accurate "now" in seconds. */
|
|
1169
|
-
get now() {
|
|
1170
|
-
return this._ctx?.currentTime ?? 0;
|
|
1171
|
-
}
|
|
1172
|
-
onStateChange(fn) {
|
|
1173
|
-
this._listeners.add(fn);
|
|
1174
|
-
return () => this._listeners.delete(fn);
|
|
1175
|
-
}
|
|
1176
|
-
async close() {
|
|
1177
|
-
if (this._state === "closed") return;
|
|
1178
|
-
if (typeof document !== "undefined") {
|
|
1179
|
-
document.removeEventListener("visibilitychange", this.handleVisibility);
|
|
1180
|
-
}
|
|
1181
|
-
if (this._ctx) {
|
|
1182
|
-
this._ctx.removeEventListener("statechange", this.handleCtxStateChange);
|
|
1183
|
-
if (this._ctx.state !== "closed") {
|
|
1184
|
-
await this._ctx.close().catch(() => void 0);
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
this._ctx = null;
|
|
1188
|
-
this.setState("closed");
|
|
1189
|
-
this._listeners.clear();
|
|
1190
|
-
}
|
|
1191
|
-
setState(s) {
|
|
1192
|
-
if (this._state === s) return;
|
|
1193
|
-
this._state = s;
|
|
1194
|
-
for (const fn of this._listeners) fn(s);
|
|
1195
|
-
}
|
|
1196
|
-
attachVisibilityHandler() {
|
|
1197
|
-
if (this.opts.autoPauseOnHidden === false) return;
|
|
1198
|
-
if (typeof document === "undefined") return;
|
|
1199
|
-
document.addEventListener("visibilitychange", this.handleVisibility);
|
|
1200
|
-
}
|
|
1201
|
-
handleVisibility = () => {
|
|
1202
|
-
if (!this._ctx || this._state === "closed") return;
|
|
1203
|
-
const visible = document.visibilityState === "visible";
|
|
1204
|
-
if (visible) {
|
|
1205
|
-
setTimeout(() => {
|
|
1206
|
-
if (document.visibilityState === "visible" && this._ctx?.state === "suspended") {
|
|
1207
|
-
void this._ctx.resume().catch(() => void 0);
|
|
1208
|
-
}
|
|
1209
|
-
}, 200);
|
|
1210
|
-
} else {
|
|
1211
|
-
void this._ctx.suspend().catch(() => void 0);
|
|
1212
|
-
}
|
|
1213
|
-
};
|
|
1214
|
-
attachStateChangeHandler(ctx) {
|
|
1215
|
-
ctx.addEventListener("statechange", this.handleCtxStateChange);
|
|
1216
|
-
}
|
|
1217
|
-
// iOS Safari moves the AudioContext into 'interrupted' on phone calls, Siri,
|
|
1218
|
-
// and other system audio takeovers. resume() does not recover from
|
|
1219
|
-
// 'interrupted' — we have to wait for the OS to flip it back to 'suspended'
|
|
1220
|
-
// and resume from there.
|
|
1221
|
-
handleCtxStateChange = () => {
|
|
1222
|
-
const ctx = this._ctx;
|
|
1223
|
-
if (!ctx || this._state === "closed") return;
|
|
1224
|
-
const state = ctx.state;
|
|
1225
|
-
if (state === "interrupted") {
|
|
1226
|
-
this.setState("interrupted");
|
|
1227
|
-
return;
|
|
1228
|
-
}
|
|
1229
|
-
if (state === "suspended" && this._state === "interrupted") {
|
|
1230
|
-
setTimeout(() => {
|
|
1231
|
-
if (this._ctx === ctx && ctx.state === "suspended") {
|
|
1232
|
-
void ctx.resume().catch(() => void 0);
|
|
1233
|
-
}
|
|
1234
|
-
}, 200);
|
|
1235
|
-
return;
|
|
1236
|
-
}
|
|
1237
|
-
if (state === "running" && this._state === "interrupted") {
|
|
1238
|
-
this.setState("live");
|
|
1239
|
-
}
|
|
1240
|
-
};
|
|
1241
|
-
};
|
|
1242
|
-
|
|
1243
|
-
// src/runtime/decode.ts
|
|
1244
|
-
var Decoder = class {
|
|
1245
|
-
constructor(getCtx, maxEntries = 128) {
|
|
1246
|
-
this.getCtx = getCtx;
|
|
1247
|
-
this.maxEntries = maxEntries;
|
|
1248
|
-
}
|
|
1249
|
-
getCtx;
|
|
1250
|
-
maxEntries;
|
|
1251
|
-
cache = /* @__PURE__ */ new Map();
|
|
1252
|
-
has(url) {
|
|
1253
|
-
return this.cache.has(url);
|
|
1254
|
-
}
|
|
1255
|
-
async load(url, opts = {}) {
|
|
1256
|
-
const cached = this.cache.get(url);
|
|
1257
|
-
if (cached) {
|
|
1258
|
-
this.touch(url, cached);
|
|
1259
|
-
return cached;
|
|
1260
|
-
}
|
|
1261
|
-
let response;
|
|
1262
|
-
try {
|
|
1263
|
-
response = await fetch(url, { signal: opts.signal });
|
|
1264
|
-
} catch (e) {
|
|
1265
|
-
if (e.name === "AbortError") throw e;
|
|
1266
|
-
throw new DecodeError(url, e);
|
|
1267
|
-
}
|
|
1268
|
-
if (!response.ok) {
|
|
1269
|
-
throw new DecodeError(url, new Error(`${response.status} ${response.statusText}`));
|
|
1270
|
-
}
|
|
1271
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
1272
|
-
const ctx = this.getCtx();
|
|
1273
|
-
let buffer;
|
|
1274
|
-
try {
|
|
1275
|
-
buffer = await ctx.decodeAudioData(arrayBuffer);
|
|
1276
|
-
} catch (e) {
|
|
1277
|
-
throw new DecodeError(url, e);
|
|
1278
|
-
}
|
|
1279
|
-
this.touch(url, buffer);
|
|
1280
|
-
return buffer;
|
|
1281
|
-
}
|
|
1282
|
-
/**
|
|
1283
|
-
* Walk a list of URLs, returning the first successful load. Falls through
|
|
1284
|
-
* on per-URL fetch failures (404, 5xx, network) AND decode failures
|
|
1285
|
-
* (decodeAudioData rejections), so a single broken codec or stale CDN
|
|
1286
|
-
* entry doesn't bring the whole sound down.
|
|
1287
|
-
*
|
|
1288
|
-
* Cache fast-path: if any URL in the list is already cached, that buffer
|
|
1289
|
-
* is returned immediately without any fetch — useful when a previous load
|
|
1290
|
-
* already resolved a fallback for the same asset.
|
|
1291
|
-
*
|
|
1292
|
-
* AbortError (from opts.signal) is fatal and propagates verbatim — once
|
|
1293
|
-
* the caller pulled the plug, we don't keep trying.
|
|
1294
|
-
*
|
|
1295
|
-
* On total failure: if a single URL was given, the underlying DecodeError
|
|
1296
|
-
* is rethrown verbatim. If multiple URLs were given, an
|
|
1297
|
-
* AggregateDecodeError is thrown with per-URL causes attached.
|
|
1298
|
-
*/
|
|
1299
|
-
async loadFirst(urls, opts = {}) {
|
|
1300
|
-
if (urls.length === 0) throw new Error("loadFirst requires at least one URL");
|
|
1301
|
-
for (const url of urls) {
|
|
1302
|
-
const cached = this.cache.get(url);
|
|
1303
|
-
if (cached) {
|
|
1304
|
-
this.touch(url, cached);
|
|
1305
|
-
return cached;
|
|
1306
|
-
}
|
|
1307
|
-
}
|
|
1308
|
-
const attempts = [];
|
|
1309
|
-
for (const url of urls) {
|
|
1310
|
-
try {
|
|
1311
|
-
return await this.load(url, opts);
|
|
1312
|
-
} catch (e) {
|
|
1313
|
-
if (e.name === "AbortError") throw e;
|
|
1314
|
-
attempts.push({ url, cause: e });
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
if (urls.length === 1) {
|
|
1318
|
-
const cause = attempts[0]?.cause;
|
|
1319
|
-
if (cause instanceof Error) throw cause;
|
|
1320
|
-
throw new DecodeError(urls[0], cause);
|
|
1321
|
-
}
|
|
1322
|
-
throw new AggregateDecodeError(urls, attempts);
|
|
1323
|
-
}
|
|
1324
|
-
evict(url) {
|
|
1325
|
-
this.cache.delete(url);
|
|
1326
|
-
}
|
|
1327
|
-
clear() {
|
|
1328
|
-
this.cache.clear();
|
|
1329
|
-
}
|
|
1330
|
-
touch(url, buffer) {
|
|
1331
|
-
if (this.cache.has(url)) this.cache.delete(url);
|
|
1332
|
-
this.cache.set(url, buffer);
|
|
1333
|
-
while (this.cache.size > this.maxEntries) {
|
|
1334
|
-
const oldest = this.cache.keys().next().value;
|
|
1335
|
-
if (oldest === void 0) break;
|
|
1336
|
-
this.cache.delete(oldest);
|
|
1337
|
-
}
|
|
1338
|
-
}
|
|
1339
|
-
};
|
|
1340
|
-
|
|
1341
|
-
// src/runtime/loudness.ts
|
|
1342
|
-
var DEFAULTS = {
|
|
1343
|
-
targetRms: 0.1,
|
|
1344
|
-
peakCeiling: 0.99
|
|
1345
|
-
};
|
|
1346
|
-
function applyLoudnessNormalization(buffer, flag, ctx) {
|
|
1347
|
-
if (!flag) return buffer;
|
|
1348
|
-
const opts = { ...DEFAULTS, ...typeof flag === "object" ? flag : {} };
|
|
1349
|
-
const gain = computeNormalizationGain(buffer, opts);
|
|
1350
|
-
if (Math.abs(gain - 1) < 1e-3) return buffer;
|
|
1351
|
-
return scaleBuffer(buffer, gain, ctx);
|
|
1352
|
-
}
|
|
1353
|
-
function computeNormalizationGain(buffer, opts) {
|
|
1354
|
-
const rms = measureRms(buffer);
|
|
1355
|
-
if (rms <= 1e-6) return 1;
|
|
1356
|
-
let gain = opts.targetRms / rms;
|
|
1357
|
-
const peak = measurePeak(buffer) * gain;
|
|
1358
|
-
if (peak > opts.peakCeiling) gain *= opts.peakCeiling / peak;
|
|
1359
|
-
return gain;
|
|
1360
|
-
}
|
|
1361
|
-
function measureRms(buffer) {
|
|
1362
|
-
let sumSq = 0;
|
|
1363
|
-
let count = 0;
|
|
1364
|
-
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
|
1365
|
-
const data = buffer.getChannelData(c);
|
|
1366
|
-
for (let i = 0; i < data.length; i++) sumSq += data[i] * data[i];
|
|
1367
|
-
count += data.length;
|
|
1368
|
-
}
|
|
1369
|
-
if (count === 0) return 0;
|
|
1370
|
-
return Math.sqrt(sumSq / count);
|
|
1371
|
-
}
|
|
1372
|
-
function measurePeak(buffer) {
|
|
1373
|
-
let peak = 0;
|
|
1374
|
-
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
|
1375
|
-
const data = buffer.getChannelData(c);
|
|
1376
|
-
for (let i = 0; i < data.length; i++) {
|
|
1377
|
-
const a = Math.abs(data[i]);
|
|
1378
|
-
if (a > peak) peak = a;
|
|
1379
|
-
}
|
|
1380
|
-
}
|
|
1381
|
-
return peak;
|
|
1382
|
-
}
|
|
1383
|
-
function scaleBuffer(src, gain, ctx) {
|
|
1384
|
-
if (ctx) {
|
|
1385
|
-
const out = ctx.createBuffer(src.numberOfChannels, src.length, src.sampleRate);
|
|
1386
|
-
for (let c = 0; c < src.numberOfChannels; c++) {
|
|
1387
|
-
const from = src.getChannelData(c);
|
|
1388
|
-
const to = out.getChannelData(c);
|
|
1389
|
-
for (let i = 0; i < from.length; i++) to[i] = from[i] * gain;
|
|
1390
|
-
}
|
|
1391
|
-
return out;
|
|
1392
|
-
}
|
|
1393
|
-
for (let c = 0; c < src.numberOfChannels; c++) {
|
|
1394
|
-
const data = src.getChannelData(c);
|
|
1395
|
-
for (let i = 0; i < data.length; i++) data[i] = data[i] * gain;
|
|
1396
|
-
}
|
|
1397
|
-
return src;
|
|
1398
|
-
}
|
|
1399
|
-
|
|
1400
|
-
// src/runtime/scheduler.ts
|
|
1401
|
-
var Scheduler = class {
|
|
1402
|
-
constructor(host, tickSource) {
|
|
1403
|
-
this.host = host;
|
|
1404
|
-
this.tickSource = tickSource;
|
|
1405
|
-
}
|
|
1406
|
-
host;
|
|
1407
|
-
tickSource;
|
|
1408
|
-
tasks = [];
|
|
1409
|
-
timer = null;
|
|
1410
|
-
unsubscribe = null;
|
|
1411
|
-
scheduleAt(audioTime, fn) {
|
|
1412
|
-
const task = { audioTime, fn, cancelled: false };
|
|
1413
|
-
this.tasks.push(task);
|
|
1414
|
-
this.tasks.sort((a, b) => a.audioTime - b.audioTime);
|
|
1415
|
-
this.arm();
|
|
1416
|
-
return () => {
|
|
1417
|
-
task.cancelled = true;
|
|
1418
|
-
};
|
|
1419
|
-
}
|
|
1420
|
-
arm() {
|
|
1421
|
-
if (this.tickSource) {
|
|
1422
|
-
if (!this.unsubscribe) {
|
|
1423
|
-
this.unsubscribe = this.tickSource.subscribe(() => this.tick());
|
|
1424
|
-
}
|
|
1425
|
-
return;
|
|
1426
|
-
}
|
|
1427
|
-
this.rearmTimer();
|
|
1428
|
-
}
|
|
1429
|
-
rearmTimer() {
|
|
1430
|
-
if (this.timer != null) {
|
|
1431
|
-
clearTimeout(this.timer);
|
|
1432
|
-
this.timer = null;
|
|
1433
|
-
}
|
|
1434
|
-
const next = this.tasks.find((t) => !t.cancelled);
|
|
1435
|
-
if (!next) return;
|
|
1436
|
-
const now = this.host.now;
|
|
1437
|
-
const delayMs = Math.max(0, (next.audioTime - now) * 1e3);
|
|
1438
|
-
this.timer = setTimeout(() => this.tick(), delayMs);
|
|
1439
|
-
}
|
|
1440
|
-
tick() {
|
|
1441
|
-
if (this.timer != null) {
|
|
1442
|
-
this.timer = null;
|
|
1443
|
-
}
|
|
1444
|
-
const now = this.host.now;
|
|
1445
|
-
const due = [];
|
|
1446
|
-
const remaining = [];
|
|
1447
|
-
for (const t of this.tasks) {
|
|
1448
|
-
if (t.cancelled) continue;
|
|
1449
|
-
if (t.audioTime <= now) due.push(t);
|
|
1450
|
-
else remaining.push(t);
|
|
1451
|
-
}
|
|
1452
|
-
this.tasks = remaining;
|
|
1453
|
-
for (const t of due) {
|
|
1454
|
-
try {
|
|
1455
|
-
t.fn();
|
|
1456
|
-
} catch (e) {
|
|
1457
|
-
console.error("[zvuk] scheduled task threw", e);
|
|
1458
|
-
}
|
|
1459
|
-
}
|
|
1460
|
-
if (this.tasks.length === 0) {
|
|
1461
|
-
if (this.unsubscribe) {
|
|
1462
|
-
this.unsubscribe();
|
|
1463
|
-
this.unsubscribe = null;
|
|
1464
|
-
}
|
|
1465
|
-
return;
|
|
1466
|
-
}
|
|
1467
|
-
if (!this.tickSource) this.rearmTimer();
|
|
1468
|
-
}
|
|
1469
|
-
dispose() {
|
|
1470
|
-
if (this.timer != null) clearTimeout(this.timer);
|
|
1471
|
-
this.timer = null;
|
|
1472
|
-
if (this.unsubscribe) {
|
|
1473
|
-
this.unsubscribe();
|
|
1474
|
-
this.unsubscribe = null;
|
|
1475
|
-
}
|
|
1476
|
-
this.tasks = [];
|
|
1477
|
-
}
|
|
1478
|
-
};
|
|
1479
|
-
|
|
1480
|
-
// src/sources/music.ts
|
|
1481
|
-
var DEFAULT_STOP_FADE_SEC = 8e-3;
|
|
1482
|
-
var SKIP_NOW_FADE_SEC = 0.05;
|
|
1483
|
-
var Music = class {
|
|
1484
|
-
name;
|
|
1485
|
-
deps;
|
|
1486
|
-
constructor(name, deps) {
|
|
1487
|
-
this.name = name;
|
|
1488
|
-
this.deps = deps;
|
|
1489
|
-
}
|
|
1490
|
-
get loopDuration() {
|
|
1491
|
-
return this.deps.buffers.loop.duration;
|
|
1492
|
-
}
|
|
1493
|
-
get hasIntro() {
|
|
1494
|
-
return this.deps.buffers.intro != null;
|
|
1495
|
-
}
|
|
1496
|
-
get hasOutro() {
|
|
1497
|
-
return this.deps.buffers.outro != null;
|
|
1498
|
-
}
|
|
1499
|
-
play(options = {}) {
|
|
1500
|
-
return new MusicVoice({
|
|
1501
|
-
ctx: this.deps.ctx,
|
|
1502
|
-
buffers: this.deps.buffers,
|
|
1503
|
-
destination: this.deps.destination,
|
|
1504
|
-
loopCrossfade: this.deps.loopCrossfade,
|
|
1505
|
-
defaultStopFade: this.deps.defaultStopFade,
|
|
1506
|
-
options
|
|
1507
|
-
});
|
|
1508
|
-
}
|
|
1509
|
-
};
|
|
1510
|
-
var MusicVoice = class {
|
|
1511
|
-
ended;
|
|
1512
|
-
ctx;
|
|
1513
|
-
buffers;
|
|
1514
|
-
destination;
|
|
1515
|
-
gain;
|
|
1516
|
-
state = "intro";
|
|
1517
|
-
done = false;
|
|
1518
|
-
resolveEnded;
|
|
1519
|
-
stopFade;
|
|
1520
|
-
loopCrossfadeSec;
|
|
1521
|
-
// Live audio sources + their per-segment gain nodes. The chain is the
|
|
1522
|
-
// (1+) loop iterations under crossfade-mode; when crossfade is off this
|
|
1523
|
-
// is at most one live loop source.
|
|
1524
|
-
introSource = null;
|
|
1525
|
-
outroSource = null;
|
|
1526
|
-
loopChain = [];
|
|
1527
|
-
loopArmTimer = null;
|
|
1528
|
-
outroTimer = null;
|
|
1529
|
-
// Wall-clock anchor for the loop chain — when the next iteration is due
|
|
1530
|
-
// to start in audioContext time. Used by skipToOutro({ at: 'loop-end' }).
|
|
1531
|
-
nextLoopBoundaryAt = Number.POSITIVE_INFINITY;
|
|
1532
|
-
constructor(deps) {
|
|
1533
|
-
this.ctx = deps.ctx;
|
|
1534
|
-
this.buffers = deps.buffers;
|
|
1535
|
-
this.destination = deps.destination;
|
|
1536
|
-
this.loopCrossfadeSec = Math.max(0, deps.loopCrossfade);
|
|
1537
|
-
this.stopFade = Math.max(0, deps.defaultStopFade ?? DEFAULT_STOP_FADE_SEC);
|
|
1538
|
-
this.gain = this.ctx.createGain();
|
|
1539
|
-
const initialVolume = clamp012(deps.options.volume ?? 1);
|
|
1540
|
-
const fadeIn = Math.max(0, deps.options.fadeIn ?? 0);
|
|
1541
|
-
if (fadeIn > 0) {
|
|
1542
|
-
this.gain.gain.setValueAtTime(0, this.ctx.currentTime);
|
|
1543
|
-
this.gain.gain.linearRampToValueAtTime(initialVolume, this.ctx.currentTime + fadeIn);
|
|
1544
|
-
} else {
|
|
1545
|
-
this.gain.gain.value = initialVolume;
|
|
1546
|
-
}
|
|
1547
|
-
this.gain.connect(this.destination);
|
|
1548
|
-
this.ended = new Promise((resolve) => {
|
|
1549
|
-
this.resolveEnded = resolve;
|
|
1550
|
-
});
|
|
1551
|
-
this.start(this.ctx.currentTime);
|
|
1552
|
-
}
|
|
1553
|
-
/** Currently-sounding part. Transitions automatically as parts hand off. */
|
|
1554
|
-
get currentPart() {
|
|
1555
|
-
return this.state;
|
|
1556
|
-
}
|
|
1557
|
-
fade(opts) {
|
|
1558
|
-
const param = this.gain.gain;
|
|
1559
|
-
const now = this.ctx.currentTime;
|
|
1560
|
-
applyRamp(param, now, clamp012(opts.to), opts.duration, opts.curve ?? "linear");
|
|
1561
|
-
return new Promise((res) => setTimeout(res, Math.max(0, opts.duration) * 1e3));
|
|
1562
|
-
}
|
|
1563
|
-
/**
|
|
1564
|
-
* Stop the music with the same click-free fade-out semantics as
|
|
1565
|
-
* `voice.stop()`. Skips the outro — call `skipToOutro` first if you
|
|
1566
|
-
* want the music to end musically.
|
|
1567
|
-
*/
|
|
1568
|
-
stop(opts = {}) {
|
|
1569
|
-
if (this.done) return;
|
|
1570
|
-
const fade = Math.max(0, opts.fade ?? this.stopFade);
|
|
1571
|
-
this.cancelTimers();
|
|
1572
|
-
if (fade === 0) {
|
|
1573
|
-
this.stopAllSources(0);
|
|
1574
|
-
this.finish();
|
|
1575
|
-
return;
|
|
1576
|
-
}
|
|
1577
|
-
const now = this.ctx.currentTime;
|
|
1578
|
-
const stopAt = now + fade;
|
|
1579
|
-
try {
|
|
1580
|
-
const param = this.gain.gain;
|
|
1581
|
-
param.cancelScheduledValues(now);
|
|
1582
|
-
param.setValueAtTime(param.value, now);
|
|
1583
|
-
param.linearRampToValueAtTime(0, stopAt);
|
|
1584
|
-
this.stopAllSources(stopAt);
|
|
1585
|
-
} catch {
|
|
1586
|
-
this.finish();
|
|
1587
|
-
return;
|
|
1588
|
-
}
|
|
1589
|
-
setTimeout(() => this.finish(), fade * 1e3);
|
|
1590
|
-
}
|
|
1591
|
-
/**
|
|
1592
|
-
* Schedule the outro. With `at: 'loop-end'` (default) the outro starts
|
|
1593
|
-
* at the next natural loop boundary so the music ends musically. With
|
|
1594
|
-
* `at: 'now'` the loop fades out (~50 ms) and the outro starts
|
|
1595
|
-
* immediately — useful when responsiveness matters more than musicality
|
|
1596
|
-
* (e.g. user pressed Stop).
|
|
1597
|
-
*
|
|
1598
|
-
* No-op if there is no outro buffer, or if the music is already past
|
|
1599
|
-
* the loop part. Calling `skipToOutro` more than once is a no-op too —
|
|
1600
|
-
* the first call wins.
|
|
1601
|
-
*/
|
|
1602
|
-
skipToOutro(opts = {}) {
|
|
1603
|
-
if (this.done) return;
|
|
1604
|
-
if (this.state === "outro" || this.state === "ended") return;
|
|
1605
|
-
if (!this.buffers.outro) {
|
|
1606
|
-
this.stop();
|
|
1607
|
-
return;
|
|
1608
|
-
}
|
|
1609
|
-
const at = opts.at ?? "loop-end";
|
|
1610
|
-
if (at === "now") {
|
|
1611
|
-
this.skipToOutroNow();
|
|
1612
|
-
} else {
|
|
1613
|
-
this.skipToOutroAtLoopEnd();
|
|
1614
|
-
}
|
|
1615
|
-
}
|
|
1616
|
-
start(when) {
|
|
1617
|
-
if (this.buffers.intro) {
|
|
1618
|
-
this.scheduleIntro(when);
|
|
1619
|
-
this.scheduleLoopStart(when + this.buffers.intro.duration);
|
|
1620
|
-
} else {
|
|
1621
|
-
this.state = "loop";
|
|
1622
|
-
this.scheduleLoopStart(when);
|
|
1623
|
-
}
|
|
1624
|
-
}
|
|
1625
|
-
scheduleIntro(when) {
|
|
1626
|
-
const src = this.ctx.createBufferSource();
|
|
1627
|
-
src.buffer = this.buffers.intro;
|
|
1628
|
-
src.connect(this.gain);
|
|
1629
|
-
src.start(when);
|
|
1630
|
-
src.onended = () => {
|
|
1631
|
-
if (this.introSource === src) this.introSource = null;
|
|
1632
|
-
};
|
|
1633
|
-
this.introSource = src;
|
|
1634
|
-
}
|
|
1635
|
-
scheduleLoopStart(when) {
|
|
1636
|
-
if (this.done) return;
|
|
1637
|
-
const segment = this.spawnLoopSegment(
|
|
1638
|
-
when,
|
|
1639
|
-
/* fadeIn */
|
|
1640
|
-
false
|
|
1641
|
-
);
|
|
1642
|
-
this.nextLoopBoundaryAt = when + this.buffers.loop.duration;
|
|
1643
|
-
if (this.loopCrossfadeSec > 0 && this.crossfadeViable()) {
|
|
1644
|
-
this.armNextLoopSegment(when);
|
|
1645
|
-
} else {
|
|
1646
|
-
segment.source.loop = true;
|
|
1647
|
-
const lr = this.buffers.loop;
|
|
1648
|
-
segment.source.loopStart = 0;
|
|
1649
|
-
segment.source.loopEnd = lr.duration;
|
|
1650
|
-
if (!this.buffers.intro) this.state = "loop";
|
|
1651
|
-
else {
|
|
1652
|
-
const ms = Math.max(0, (when - this.ctx.currentTime) * 1e3);
|
|
1653
|
-
setTimeout(() => {
|
|
1654
|
-
if (!this.done && this.state === "intro") this.state = "loop";
|
|
1655
|
-
}, ms);
|
|
1656
|
-
}
|
|
1657
|
-
}
|
|
1658
|
-
}
|
|
1659
|
-
spawnLoopSegment(when, fadeIn) {
|
|
1660
|
-
const src = this.ctx.createBufferSource();
|
|
1661
|
-
src.buffer = this.buffers.loop;
|
|
1662
|
-
src.loop = false;
|
|
1663
|
-
const segGain = this.ctx.createGain();
|
|
1664
|
-
if (fadeIn) {
|
|
1665
|
-
segGain.gain.setValueAtTime(0, when);
|
|
1666
|
-
segGain.gain.setValueCurveAtTime(equalPowerCurve(0, 1), when, this.loopCrossfadeSec);
|
|
1667
|
-
} else {
|
|
1668
|
-
segGain.gain.setValueAtTime(1, when);
|
|
1669
|
-
}
|
|
1670
|
-
if (this.crossfadeViable()) {
|
|
1671
|
-
const fadeOutAt = when + this.buffers.loop.duration - this.loopCrossfadeSec;
|
|
1672
|
-
segGain.gain.setValueAtTime(1, fadeOutAt);
|
|
1673
|
-
segGain.gain.setValueCurveAtTime(equalPowerCurve(1, 0), fadeOutAt, this.loopCrossfadeSec);
|
|
1674
|
-
}
|
|
1675
|
-
src.connect(segGain).connect(this.gain);
|
|
1676
|
-
try {
|
|
1677
|
-
if (this.crossfadeViable()) {
|
|
1678
|
-
src.start(when, 0, this.buffers.loop.duration);
|
|
1679
|
-
} else {
|
|
1680
|
-
src.start(when);
|
|
1681
|
-
}
|
|
1682
|
-
} catch {
|
|
1683
|
-
}
|
|
1684
|
-
src.onended = () => this.releaseLoopSegment(src, segGain);
|
|
1685
|
-
const entry = { source: src, gain: segGain, startTime: when };
|
|
1686
|
-
this.loopChain.push(entry);
|
|
1687
|
-
return entry;
|
|
1688
|
-
}
|
|
1689
|
-
armNextLoopSegment(currentSegmentStart) {
|
|
1690
|
-
if (this.loopArmTimer != null) {
|
|
1691
|
-
clearTimeout(this.loopArmTimer);
|
|
1692
|
-
this.loopArmTimer = null;
|
|
1693
|
-
}
|
|
1694
|
-
const nextStart = currentSegmentStart + this.buffers.loop.duration - this.loopCrossfadeSec;
|
|
1695
|
-
const SAFETY_LEAD_MS = 50;
|
|
1696
|
-
const delayMs = Math.max(0, (nextStart - this.ctx.currentTime) * 1e3 - SAFETY_LEAD_MS);
|
|
1697
|
-
this.loopArmTimer = setTimeout(() => {
|
|
1698
|
-
this.loopArmTimer = null;
|
|
1699
|
-
if (this.done || this.state !== "loop" && this.state !== "intro") return;
|
|
1700
|
-
this.state = "loop";
|
|
1701
|
-
this.spawnLoopSegment(
|
|
1702
|
-
nextStart,
|
|
1703
|
-
/* fadeIn */
|
|
1704
|
-
true
|
|
1705
|
-
);
|
|
1706
|
-
this.nextLoopBoundaryAt = nextStart + this.buffers.loop.duration;
|
|
1707
|
-
this.armNextLoopSegment(nextStart);
|
|
1708
|
-
}, delayMs);
|
|
1709
|
-
}
|
|
1710
|
-
crossfadeViable() {
|
|
1711
|
-
return this.loopCrossfadeSec > 0 && this.buffers.loop.duration > this.loopCrossfadeSec * 2;
|
|
1712
|
-
}
|
|
1713
|
-
releaseLoopSegment(src, gain) {
|
|
1714
|
-
const idx = this.loopChain.findIndex((e) => e.source === src);
|
|
1715
|
-
if (idx >= 0) this.loopChain.splice(idx, 1);
|
|
1716
|
-
try {
|
|
1717
|
-
src.disconnect();
|
|
1718
|
-
gain.disconnect();
|
|
1719
|
-
} catch {
|
|
1720
|
-
}
|
|
1721
|
-
}
|
|
1722
|
-
skipToOutroAtLoopEnd() {
|
|
1723
|
-
if (this.loopArmTimer != null) {
|
|
1724
|
-
clearTimeout(this.loopArmTimer);
|
|
1725
|
-
this.loopArmTimer = null;
|
|
1726
|
-
}
|
|
1727
|
-
let outroAt;
|
|
1728
|
-
if (this.state === "intro") {
|
|
1729
|
-
outroAt = this.ctx.currentTime + (this.buffers.intro?.duration ?? 0);
|
|
1730
|
-
this.cancelLoopArm();
|
|
1731
|
-
} else {
|
|
1732
|
-
outroAt = this.nextLoopBoundaryAt;
|
|
1733
|
-
}
|
|
1734
|
-
this.stopLoopSourcesAt(outroAt);
|
|
1735
|
-
this.scheduleOutro(outroAt);
|
|
1736
|
-
}
|
|
1737
|
-
skipToOutroNow() {
|
|
1738
|
-
this.cancelLoopArm();
|
|
1739
|
-
const now = this.ctx.currentTime;
|
|
1740
|
-
const fadeEnd = now + SKIP_NOW_FADE_SEC;
|
|
1741
|
-
for (const entry of this.loopChain) {
|
|
1742
|
-
try {
|
|
1743
|
-
const param = entry.gain.gain;
|
|
1744
|
-
param.cancelScheduledValues(now);
|
|
1745
|
-
param.setValueAtTime(param.value, now);
|
|
1746
|
-
param.linearRampToValueAtTime(0, fadeEnd);
|
|
1747
|
-
} catch {
|
|
1748
|
-
}
|
|
1749
|
-
try {
|
|
1750
|
-
entry.source.stop(fadeEnd);
|
|
1751
|
-
} catch {
|
|
1752
|
-
}
|
|
1753
|
-
}
|
|
1754
|
-
if (this.introSource) {
|
|
1755
|
-
try {
|
|
1756
|
-
this.introSource.stop(fadeEnd);
|
|
1757
|
-
} catch {
|
|
1758
|
-
}
|
|
1759
|
-
}
|
|
1760
|
-
this.scheduleOutro(fadeEnd);
|
|
1761
|
-
}
|
|
1762
|
-
cancelLoopArm() {
|
|
1763
|
-
if (this.loopArmTimer != null) {
|
|
1764
|
-
clearTimeout(this.loopArmTimer);
|
|
1765
|
-
this.loopArmTimer = null;
|
|
1766
|
-
}
|
|
1767
|
-
}
|
|
1768
|
-
stopLoopSourcesAt(when) {
|
|
1769
|
-
for (const entry of this.loopChain) {
|
|
1770
|
-
try {
|
|
1771
|
-
entry.source.stop(when);
|
|
1772
|
-
} catch {
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
}
|
|
1776
|
-
scheduleOutro(when) {
|
|
1777
|
-
const buf = this.buffers.outro;
|
|
1778
|
-
if (!buf) {
|
|
1779
|
-
const ms2 = Math.max(0, (when - this.ctx.currentTime) * 1e3);
|
|
1780
|
-
this.outroTimer = setTimeout(() => this.finish(), ms2);
|
|
1781
|
-
return;
|
|
1782
|
-
}
|
|
1783
|
-
const src = this.ctx.createBufferSource();
|
|
1784
|
-
src.buffer = buf;
|
|
1785
|
-
src.connect(this.gain);
|
|
1786
|
-
try {
|
|
1787
|
-
src.start(when);
|
|
1788
|
-
} catch {
|
|
1789
|
-
}
|
|
1790
|
-
src.onended = () => {
|
|
1791
|
-
if (this.outroSource === src) this.outroSource = null;
|
|
1792
|
-
this.finish();
|
|
1793
|
-
};
|
|
1794
|
-
this.outroSource = src;
|
|
1795
|
-
const ms = Math.max(0, (when - this.ctx.currentTime) * 1e3);
|
|
1796
|
-
this.outroTimer = setTimeout(() => {
|
|
1797
|
-
this.outroTimer = null;
|
|
1798
|
-
if (!this.done) this.state = "outro";
|
|
1799
|
-
}, ms);
|
|
1800
|
-
}
|
|
1801
|
-
cancelTimers() {
|
|
1802
|
-
if (this.loopArmTimer != null) {
|
|
1803
|
-
clearTimeout(this.loopArmTimer);
|
|
1804
|
-
this.loopArmTimer = null;
|
|
1805
|
-
}
|
|
1806
|
-
if (this.outroTimer != null) {
|
|
1807
|
-
clearTimeout(this.outroTimer);
|
|
1808
|
-
this.outroTimer = null;
|
|
1809
|
-
}
|
|
1810
|
-
}
|
|
1811
|
-
stopAllSources(when) {
|
|
1812
|
-
const sources = [];
|
|
1813
|
-
if (this.introSource) sources.push(this.introSource);
|
|
1814
|
-
for (const e of this.loopChain) sources.push(e.source);
|
|
1815
|
-
if (this.outroSource) sources.push(this.outroSource);
|
|
1816
|
-
for (const src of sources) {
|
|
1817
|
-
try {
|
|
1818
|
-
src.onended = null;
|
|
1819
|
-
if (when === 0) src.stop();
|
|
1820
|
-
else src.stop(when);
|
|
1821
|
-
} catch {
|
|
1822
|
-
}
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
finish() {
|
|
1826
|
-
if (this.done) return;
|
|
1827
|
-
this.done = true;
|
|
1828
|
-
this.state = "ended";
|
|
1829
|
-
this.cancelTimers();
|
|
1830
|
-
try {
|
|
1831
|
-
if (this.introSource) this.introSource.disconnect();
|
|
1832
|
-
for (const e of this.loopChain) {
|
|
1833
|
-
e.source.disconnect();
|
|
1834
|
-
e.gain.disconnect();
|
|
1835
|
-
}
|
|
1836
|
-
if (this.outroSource) this.outroSource.disconnect();
|
|
1837
|
-
this.gain.disconnect();
|
|
1838
|
-
} catch {
|
|
1839
|
-
}
|
|
1840
|
-
this.introSource = null;
|
|
1841
|
-
this.outroSource = null;
|
|
1842
|
-
this.loopChain = [];
|
|
1843
|
-
this.resolveEnded();
|
|
1844
|
-
}
|
|
1845
|
-
};
|
|
1846
|
-
function clamp012(v) {
|
|
1847
|
-
if (Number.isNaN(v)) return 0;
|
|
1848
|
-
return Math.min(1, Math.max(0, v));
|
|
1849
|
-
}
|
|
1850
|
-
|
|
1851
|
-
// src/sources/voice.ts
|
|
1852
|
-
var DEFAULT_STOP_FADE_SEC2 = 8e-3;
|
|
1853
|
-
var Voice = class _Voice {
|
|
1854
|
-
id;
|
|
1855
|
-
priority;
|
|
1856
|
-
bus;
|
|
1857
|
-
startedAt;
|
|
1858
|
-
/** Name of the Sound that spawned this voice (if any). Used for crossfade. */
|
|
1859
|
-
sourceName;
|
|
1860
|
-
/** Resolves when playback finishes (natural end, stop(), or abort). */
|
|
1861
|
-
ended;
|
|
1862
|
-
ctx;
|
|
1863
|
-
gain;
|
|
1864
|
-
source;
|
|
1865
|
-
buffer;
|
|
1866
|
-
loop;
|
|
1867
|
-
basePitch;
|
|
1868
|
-
done = false;
|
|
1869
|
-
stopping = false;
|
|
1870
|
-
paused = false;
|
|
1871
|
-
resolveEnded;
|
|
1872
|
-
cueListeners = /* @__PURE__ */ new Set();
|
|
1873
|
-
startCtxTime;
|
|
1874
|
-
pausedOffset = 0;
|
|
1875
|
-
currentOffset = 0;
|
|
1876
|
-
_spatializer;
|
|
1877
|
-
startOffset;
|
|
1878
|
-
regionDuration;
|
|
1879
|
-
loopStart;
|
|
1880
|
-
loopEnd;
|
|
1881
|
-
regionTimer = null;
|
|
1882
|
-
stopFade;
|
|
1883
|
-
// Loop-crossfade state. Inactive when crossfadeSec === 0.
|
|
1884
|
-
// In crossfade mode, `source` is the most-recently-armed segment and the
|
|
1885
|
-
// `crossfadeChain` carries every segment currently scheduled or live so
|
|
1886
|
-
// that stop/pause/setPlaybackRate can fan out across them.
|
|
1887
|
-
crossfadeSec = 0;
|
|
1888
|
-
crossfadeRegionStart = 0;
|
|
1889
|
-
crossfadeRegionLen = 0;
|
|
1890
|
-
crossfadeChain = [];
|
|
1891
|
-
crossfadeArmTimer = null;
|
|
1892
|
-
// Lazily-allocated meter tap. Created on first level() read; kept alive
|
|
1893
|
-
// until finish(). The tap connects voice gain → analyser as a sibling of
|
|
1894
|
-
// gain → destination, so the audio path is unchanged and the analyser is
|
|
1895
|
-
// a passive read-only observer.
|
|
1896
|
-
levelAnalyser = null;
|
|
1897
|
-
levelBuf = null;
|
|
1898
|
-
static nextId = 1;
|
|
1899
|
-
constructor(deps) {
|
|
1900
|
-
const { ctx, buffer, destination, options } = deps;
|
|
1901
|
-
this.id = _Voice.nextId++;
|
|
1902
|
-
this.ctx = ctx;
|
|
1903
|
-
this.priority = options.priority ?? 0;
|
|
1904
|
-
this.bus = options.bus;
|
|
1905
|
-
this.sourceName = deps.sourceName;
|
|
1906
|
-
this.startedAt = ctx.currentTime;
|
|
1907
|
-
this.buffer = buffer;
|
|
1908
|
-
this.loop = options.loop ?? false;
|
|
1909
|
-
this.basePitch = resolveJittered(options.pitch ?? 1, 1);
|
|
1910
|
-
this._spatializer = deps.spatializer;
|
|
1911
|
-
this.startOffset = options.offset ?? 0;
|
|
1912
|
-
this.currentOffset = this.startOffset;
|
|
1913
|
-
this.regionDuration = options.duration;
|
|
1914
|
-
this.loopStart = options.loopStart;
|
|
1915
|
-
this.loopEnd = options.loopEnd;
|
|
1916
|
-
this.stopFade = Math.max(0, deps.defaultStopFade ?? DEFAULT_STOP_FADE_SEC2);
|
|
1917
|
-
this.gain = ctx.createGain();
|
|
1918
|
-
const initialVolume = clamp013(resolveJittered(options.volume ?? 1));
|
|
1919
|
-
const fadeIn = Math.max(0, options.fadeIn ?? 0);
|
|
1920
|
-
if (fadeIn > 0) {
|
|
1921
|
-
this.gain.gain.setValueAtTime(0, ctx.currentTime);
|
|
1922
|
-
this.gain.gain.linearRampToValueAtTime(initialVolume, ctx.currentTime + fadeIn);
|
|
1923
|
-
} else {
|
|
1924
|
-
this.gain.gain.value = initialVolume;
|
|
1925
|
-
}
|
|
1926
|
-
this.gain.connect(destination);
|
|
1927
|
-
this.startCtxTime = ctx.currentTime;
|
|
1928
|
-
this.ended = new Promise((resolve) => {
|
|
1929
|
-
this.resolveEnded = resolve;
|
|
1930
|
-
});
|
|
1931
|
-
if (options.signal) {
|
|
1932
|
-
if (options.signal.aborted) {
|
|
1933
|
-
queueMicrotask(() => this.stop());
|
|
1934
|
-
} else {
|
|
1935
|
-
options.signal.addEventListener("abort", () => this.stop(), { once: true });
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
if (this.shouldUseLoopCrossfade(options)) {
|
|
1939
|
-
this.crossfadeSec = options.loopCrossfade;
|
|
1940
|
-
this.crossfadeRegionStart = options.loopStart ?? this.startOffset;
|
|
1941
|
-
const regionEnd = options.loopEnd ?? buffer.duration;
|
|
1942
|
-
this.crossfadeRegionLen = Math.max(0, regionEnd - this.crossfadeRegionStart);
|
|
1943
|
-
this.source = this.startCrossfadeChain(ctx.currentTime);
|
|
1944
|
-
} else {
|
|
1945
|
-
this.source = this.createSourceNode(this.basePitch);
|
|
1946
|
-
this.bindSourceLifecycle(this.source, () => {
|
|
1947
|
-
});
|
|
1948
|
-
try {
|
|
1949
|
-
this.source.start(0, this.startOffset);
|
|
1950
|
-
} catch {
|
|
1951
|
-
}
|
|
1952
|
-
this.armRegionTimer(this.regionDuration);
|
|
1953
|
-
}
|
|
1954
|
-
queueMicrotask(() => this.emit("started"));
|
|
1955
|
-
void this.ended.then(() => deps.onEnded(this));
|
|
1956
|
-
}
|
|
1957
|
-
shouldUseLoopCrossfade(options) {
|
|
1958
|
-
if (!this.loop) return false;
|
|
1959
|
-
const cf = options.loopCrossfade;
|
|
1960
|
-
if (cf == null || cf <= 0) return false;
|
|
1961
|
-
const start = options.loopStart ?? this.startOffset;
|
|
1962
|
-
const end = options.loopEnd ?? this.buffer.duration;
|
|
1963
|
-
const len = end - start;
|
|
1964
|
-
return len > cf * 2;
|
|
1965
|
-
}
|
|
1966
|
-
fade(opts) {
|
|
1967
|
-
const param = this.gain.gain;
|
|
1968
|
-
const now = this.ctx.currentTime;
|
|
1969
|
-
applyRamp(param, now, clamp013(opts.to), opts.duration, opts.curve ?? "linear");
|
|
1970
|
-
return new Promise((res) => setTimeout(res, Math.max(0, opts.duration) * 1e3));
|
|
1971
|
-
}
|
|
1972
|
-
/**
|
|
1973
|
-
* Stop the voice. Applies a short linear gain ramp (default ~8 ms) before
|
|
1974
|
-
* the source node actually stops, to suppress the digital click that
|
|
1975
|
-
* would otherwise fire if the source is cut mid-waveform on a non-zero
|
|
1976
|
-
* crossing. Pass `{ fade: 0 }` for an instant hard cut, or a longer
|
|
1977
|
-
* duration for an explicit tail.
|
|
1978
|
-
*
|
|
1979
|
-
* Re-entrant calls during an in-progress stop are no-ops — the first
|
|
1980
|
-
* stop wins. The voice's `.ended` promise resolves when the audio
|
|
1981
|
-
* actually stops (i.e. after the ramp completes).
|
|
1982
|
-
*/
|
|
1983
|
-
stop(opts = {}) {
|
|
1984
|
-
if (this.done || this.stopping) return;
|
|
1985
|
-
const fade = Math.max(0, opts.fade ?? this.stopFade);
|
|
1986
|
-
if (this.crossfadeArmTimer != null) {
|
|
1987
|
-
clearTimeout(this.crossfadeArmTimer);
|
|
1988
|
-
this.crossfadeArmTimer = null;
|
|
1989
|
-
}
|
|
1990
|
-
if (fade === 0) {
|
|
1991
|
-
this.stopAllSources(0);
|
|
1992
|
-
this.finish("ended");
|
|
1993
|
-
return;
|
|
1994
|
-
}
|
|
1995
|
-
this.stopping = true;
|
|
1996
|
-
const now = this.ctx.currentTime;
|
|
1997
|
-
const stopAt = now + fade;
|
|
1998
|
-
for (const src of this.activeSources()) src.onended = null;
|
|
1999
|
-
if (this.regionTimer != null) {
|
|
2000
|
-
clearTimeout(this.regionTimer);
|
|
2001
|
-
this.regionTimer = null;
|
|
2002
|
-
}
|
|
2003
|
-
try {
|
|
2004
|
-
const param = this.gain.gain;
|
|
2005
|
-
param.cancelScheduledValues(now);
|
|
2006
|
-
param.setValueAtTime(param.value, now);
|
|
2007
|
-
param.linearRampToValueAtTime(0, stopAt);
|
|
2008
|
-
this.stopAllSources(stopAt);
|
|
2009
|
-
} catch {
|
|
2010
|
-
this.finish("ended");
|
|
2011
|
-
return;
|
|
2012
|
-
}
|
|
2013
|
-
setTimeout(() => this.finish("ended"), fade * 1e3);
|
|
2014
|
-
}
|
|
2015
|
-
activeSources() {
|
|
2016
|
-
if (this.inCrossfadeMode) return this.crossfadeChain.map((e) => e.source);
|
|
2017
|
-
return [this.source];
|
|
2018
|
-
}
|
|
2019
|
-
stopAllSources(when) {
|
|
2020
|
-
for (const src of this.activeSources()) {
|
|
2021
|
-
try {
|
|
2022
|
-
if (when === 0) src.stop();
|
|
2023
|
-
else src.stop(when);
|
|
2024
|
-
} catch {
|
|
2025
|
-
}
|
|
2026
|
-
}
|
|
2027
|
-
}
|
|
2028
|
-
/**
|
|
2029
|
-
* Pause this voice. Tracks the playback offset so resume() picks up
|
|
2030
|
-
* where it left off. No-op on a finished voice.
|
|
2031
|
-
*/
|
|
2032
|
-
pause() {
|
|
2033
|
-
if (this.done || this.paused) return;
|
|
2034
|
-
const offset = this.computeOffset();
|
|
2035
|
-
this.pausedOffset = offset;
|
|
2036
|
-
this.currentOffset = offset;
|
|
2037
|
-
this.paused = true;
|
|
2038
|
-
if (this.regionTimer != null) {
|
|
2039
|
-
clearTimeout(this.regionTimer);
|
|
2040
|
-
this.regionTimer = null;
|
|
2041
|
-
}
|
|
2042
|
-
if (this.crossfadeArmTimer != null) {
|
|
2043
|
-
clearTimeout(this.crossfadeArmTimer);
|
|
2044
|
-
this.crossfadeArmTimer = null;
|
|
2045
|
-
}
|
|
2046
|
-
for (const src of this.activeSources()) {
|
|
2047
|
-
try {
|
|
2048
|
-
src.onended = null;
|
|
2049
|
-
src.stop();
|
|
2050
|
-
} catch {
|
|
2051
|
-
}
|
|
2052
|
-
try {
|
|
2053
|
-
src.disconnect();
|
|
2054
|
-
} catch {
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
if (this.inCrossfadeMode) this.crossfadeChain = [];
|
|
2058
|
-
this.emit("paused");
|
|
2059
|
-
}
|
|
2060
|
-
/** Resume from the offset captured on pause(). No-op when not paused. */
|
|
2061
|
-
resume() {
|
|
2062
|
-
if (this.done || !this.paused) return;
|
|
2063
|
-
this.paused = false;
|
|
2064
|
-
this.startCtxTime = this.ctx.currentTime;
|
|
2065
|
-
if (this.inCrossfadeMode) {
|
|
2066
|
-
this.source = this.startCrossfadeChain(this.startCtxTime);
|
|
2067
|
-
} else {
|
|
2068
|
-
this.source = this.createSourceNode(this.basePitch);
|
|
2069
|
-
this.bindSourceLifecycle(this.source, () => {
|
|
2070
|
-
});
|
|
2071
|
-
try {
|
|
2072
|
-
this.source.start(0, this.pausedOffset);
|
|
2073
|
-
} catch {
|
|
2074
|
-
}
|
|
2075
|
-
if (this.regionDuration != null) {
|
|
2076
|
-
const consumed = Math.max(0, this.pausedOffset - this.startOffset);
|
|
2077
|
-
const remaining = Math.max(0, this.regionDuration - consumed);
|
|
2078
|
-
this.armRegionTimer(remaining);
|
|
2079
|
-
}
|
|
2080
|
-
}
|
|
2081
|
-
this.emit("resumed");
|
|
2082
|
-
}
|
|
2083
|
-
/** Whether the voice is currently paused (and thus retaining its offset). */
|
|
2084
|
-
get isPaused() {
|
|
2085
|
-
return this.paused;
|
|
2086
|
-
}
|
|
2087
|
-
/**
|
|
2088
|
-
* Live playback-rate setter. Optional ramp via curve.
|
|
2089
|
-
* Setting while paused only updates the value used on the next start.
|
|
2090
|
-
*/
|
|
2091
|
-
setPlaybackRate(rate, opts = {}) {
|
|
2092
|
-
if (this.done) return;
|
|
2093
|
-
const r = Math.max(0, rate);
|
|
2094
|
-
const duration = Math.max(0, opts.duration ?? 0);
|
|
2095
|
-
if (!this.paused) {
|
|
2096
|
-
this.currentOffset = this.computeOffset();
|
|
2097
|
-
this.startCtxTime = this.ctx.currentTime;
|
|
2098
|
-
}
|
|
2099
|
-
this.basePitch = r;
|
|
2100
|
-
if (this.paused) return;
|
|
2101
|
-
for (const src of this.activeSources()) {
|
|
2102
|
-
const param = src.playbackRate;
|
|
2103
|
-
if (duration === 0) {
|
|
2104
|
-
param.value = r;
|
|
2105
|
-
} else {
|
|
2106
|
-
applyRamp(param, this.ctx.currentTime, r, duration, opts.curve ?? "linear");
|
|
2107
|
-
}
|
|
2108
|
-
}
|
|
2109
|
-
}
|
|
2110
|
-
get playbackRate() {
|
|
2111
|
-
return this.basePitch;
|
|
2112
|
-
}
|
|
2113
|
-
/** The Spatializer attached to this voice (if any). Use for live setPan/setPosition. */
|
|
2114
|
-
get spatializer() {
|
|
2115
|
-
return this._spatializer;
|
|
2116
|
-
}
|
|
2117
|
-
/**
|
|
2118
|
-
* Live amplitude readout. Returns `{ rms, peak }` as linear values in
|
|
2119
|
-
* [0..1]. The first call lazily attaches an AnalyserNode to the voice's
|
|
2120
|
-
* gain stage; subsequent calls reuse it. Returns zeros once the voice has
|
|
2121
|
-
* finished.
|
|
2122
|
-
*/
|
|
2123
|
-
level() {
|
|
2124
|
-
if (this.done) return { rms: 0, peak: 0 };
|
|
2125
|
-
if (!this.levelAnalyser) {
|
|
2126
|
-
const a = this.ctx.createAnalyser();
|
|
2127
|
-
a.fftSize = 512;
|
|
2128
|
-
this.gain.connect(a);
|
|
2129
|
-
this.levelAnalyser = a;
|
|
2130
|
-
this.levelBuf = new Float32Array(a.fftSize);
|
|
2131
|
-
}
|
|
2132
|
-
const buf = this.levelBuf;
|
|
2133
|
-
this.levelAnalyser.getFloatTimeDomainData(buf);
|
|
2134
|
-
let sumSq = 0;
|
|
2135
|
-
let peak = 0;
|
|
2136
|
-
for (let i = 0; i < buf.length; i++) {
|
|
2137
|
-
const s = buf[i] ?? 0;
|
|
2138
|
-
sumSq += s * s;
|
|
2139
|
-
const a = Math.abs(s);
|
|
2140
|
-
if (a > peak) peak = a;
|
|
2141
|
-
}
|
|
2142
|
-
return { rms: Math.sqrt(sumSq / buf.length), peak };
|
|
2143
|
-
}
|
|
2144
|
-
/** Async iterator of lifecycle cues — yields started, optional paused, ended. */
|
|
2145
|
-
async *cues() {
|
|
2146
|
-
if (this.done) {
|
|
2147
|
-
yield "ended";
|
|
2148
|
-
return;
|
|
2149
|
-
}
|
|
2150
|
-
const queue = [];
|
|
2151
|
-
let waiter = null;
|
|
2152
|
-
const push = (c) => {
|
|
2153
|
-
if (waiter) {
|
|
2154
|
-
const w = waiter;
|
|
2155
|
-
waiter = null;
|
|
2156
|
-
w({ value: c, done: false });
|
|
2157
|
-
} else {
|
|
2158
|
-
queue.push(c);
|
|
2159
|
-
}
|
|
2160
|
-
};
|
|
2161
|
-
const sub = (c) => push(c);
|
|
2162
|
-
this.cueListeners.add(sub);
|
|
2163
|
-
try {
|
|
2164
|
-
while (true) {
|
|
2165
|
-
if (queue.length > 0) {
|
|
2166
|
-
const next2 = queue.shift();
|
|
2167
|
-
yield next2;
|
|
2168
|
-
if (next2 === "ended") return;
|
|
2169
|
-
continue;
|
|
2170
|
-
}
|
|
2171
|
-
if (this.done) {
|
|
2172
|
-
yield "ended";
|
|
2173
|
-
return;
|
|
2174
|
-
}
|
|
2175
|
-
const next = await new Promise((res) => {
|
|
2176
|
-
waiter = res;
|
|
2177
|
-
});
|
|
2178
|
-
if (next.done) return;
|
|
2179
|
-
yield next.value;
|
|
2180
|
-
if (next.value === "ended") return;
|
|
2181
|
-
}
|
|
2182
|
-
} finally {
|
|
2183
|
-
this.cueListeners.delete(sub);
|
|
2184
|
-
}
|
|
2185
|
-
}
|
|
2186
|
-
finish(reason, hook) {
|
|
2187
|
-
if (this.done) return;
|
|
2188
|
-
this.done = true;
|
|
2189
|
-
if (this.regionTimer != null) {
|
|
2190
|
-
clearTimeout(this.regionTimer);
|
|
2191
|
-
this.regionTimer = null;
|
|
2192
|
-
}
|
|
2193
|
-
if (this.crossfadeArmTimer != null) {
|
|
2194
|
-
clearTimeout(this.crossfadeArmTimer);
|
|
2195
|
-
this.crossfadeArmTimer = null;
|
|
2196
|
-
}
|
|
2197
|
-
try {
|
|
2198
|
-
for (const src of this.activeSources()) src.disconnect();
|
|
2199
|
-
for (const e of this.crossfadeChain) e.gain.disconnect();
|
|
2200
|
-
this.levelAnalyser?.disconnect();
|
|
2201
|
-
this.gain.disconnect();
|
|
2202
|
-
} catch {
|
|
2203
|
-
}
|
|
2204
|
-
this.levelAnalyser = null;
|
|
2205
|
-
this.levelBuf = null;
|
|
2206
|
-
this.crossfadeChain = [];
|
|
2207
|
-
this.emit(reason);
|
|
2208
|
-
this.resolveEnded();
|
|
2209
|
-
hook?.(this);
|
|
2210
|
-
}
|
|
2211
|
-
emit(c) {
|
|
2212
|
-
for (const fn of this.cueListeners) fn(c);
|
|
2213
|
-
}
|
|
2214
|
-
createSourceNode(rate) {
|
|
2215
|
-
const src = this.ctx.createBufferSource();
|
|
2216
|
-
src.buffer = this.buffer;
|
|
2217
|
-
src.loop = this.loop;
|
|
2218
|
-
if (this.loop && this.loopStart != null) src.loopStart = this.loopStart;
|
|
2219
|
-
if (this.loop && this.loopEnd != null) src.loopEnd = this.loopEnd;
|
|
2220
|
-
src.playbackRate.value = rate;
|
|
2221
|
-
src.connect(this.gain);
|
|
2222
|
-
return src;
|
|
2223
|
-
}
|
|
2224
|
-
armRegionTimer(remainingSec) {
|
|
2225
|
-
if (this.regionTimer != null) {
|
|
2226
|
-
clearTimeout(this.regionTimer);
|
|
2227
|
-
this.regionTimer = null;
|
|
2228
|
-
}
|
|
2229
|
-
if (remainingSec == null) return;
|
|
2230
|
-
const ms = Math.max(0, remainingSec * 1e3) / Math.max(1e-4, this.basePitch);
|
|
2231
|
-
this.regionTimer = setTimeout(() => {
|
|
2232
|
-
this.regionTimer = null;
|
|
2233
|
-
if (!this.done) this.stop();
|
|
2234
|
-
}, ms);
|
|
2235
|
-
}
|
|
2236
|
-
bindSourceLifecycle(src, hook) {
|
|
2237
|
-
src.onended = () => {
|
|
2238
|
-
if (this.paused) return;
|
|
2239
|
-
if (!src.loop) this.finish("ended", hook);
|
|
2240
|
-
};
|
|
2241
|
-
}
|
|
2242
|
-
/**
|
|
2243
|
-
* Begin the loop-crossfade chain. Spawns the first segment immediately at
|
|
2244
|
-
* full level, then arms a setTimeout to spawn the next one shortly before
|
|
2245
|
-
* the boundary. Each subsequent spawn re-arms its own follow-up.
|
|
2246
|
-
*
|
|
2247
|
-
* Audio scheduling uses absolute `ctx.currentTime` values so drift between
|
|
2248
|
-
* setTimeout (wall clock) and the audio thread doesn't cause click-y
|
|
2249
|
-
* misalignment — setTimeout only needs to wake us in time to call
|
|
2250
|
-
* `source.start(when, ...)` before `when`.
|
|
2251
|
-
*/
|
|
2252
|
-
startCrossfadeChain(when) {
|
|
2253
|
-
const first = this.spawnCrossfadeSegment(
|
|
2254
|
-
when,
|
|
2255
|
-
/* fadeIn */
|
|
2256
|
-
false
|
|
2257
|
-
);
|
|
2258
|
-
this.armNextCrossfadeSegment(when);
|
|
2259
|
-
return first.source;
|
|
2260
|
-
}
|
|
2261
|
-
spawnCrossfadeSegment(when, fadeIn) {
|
|
2262
|
-
const src = this.ctx.createBufferSource();
|
|
2263
|
-
src.buffer = this.buffer;
|
|
2264
|
-
src.loop = false;
|
|
2265
|
-
src.playbackRate.value = this.basePitch;
|
|
2266
|
-
const segGain = this.ctx.createGain();
|
|
2267
|
-
if (fadeIn) {
|
|
2268
|
-
segGain.gain.setValueAtTime(0, when);
|
|
2269
|
-
segGain.gain.setValueCurveAtTime(equalPowerCurve(0, 1), when, this.crossfadeSec);
|
|
2270
|
-
} else {
|
|
2271
|
-
segGain.gain.setValueAtTime(1, when);
|
|
2272
|
-
}
|
|
2273
|
-
const fadeOutAt = when + this.crossfadeRegionLen - this.crossfadeSec;
|
|
2274
|
-
segGain.gain.setValueAtTime(1, fadeOutAt);
|
|
2275
|
-
segGain.gain.setValueCurveAtTime(equalPowerCurve(1, 0), fadeOutAt, this.crossfadeSec);
|
|
2276
|
-
src.connect(segGain).connect(this.gain);
|
|
2277
|
-
try {
|
|
2278
|
-
src.start(when, this.crossfadeRegionStart, this.crossfadeRegionLen);
|
|
2279
|
-
} catch {
|
|
2280
|
-
}
|
|
2281
|
-
src.onended = () => this.releaseCrossfadeSegment(src, segGain);
|
|
2282
|
-
const entry = { source: src, gain: segGain, startTime: when };
|
|
2283
|
-
this.crossfadeChain.push(entry);
|
|
2284
|
-
return entry;
|
|
2285
|
-
}
|
|
2286
|
-
armNextCrossfadeSegment(currentSegmentStart) {
|
|
2287
|
-
if (this.crossfadeArmTimer != null) {
|
|
2288
|
-
clearTimeout(this.crossfadeArmTimer);
|
|
2289
|
-
this.crossfadeArmTimer = null;
|
|
2290
|
-
}
|
|
2291
|
-
const nextStart = currentSegmentStart + this.crossfadeRegionLen - this.crossfadeSec;
|
|
2292
|
-
const SAFETY_LEAD_MS = 50;
|
|
2293
|
-
const delayMs = Math.max(0, (nextStart - this.ctx.currentTime) * 1e3 - SAFETY_LEAD_MS);
|
|
2294
|
-
this.crossfadeArmTimer = setTimeout(() => {
|
|
2295
|
-
this.crossfadeArmTimer = null;
|
|
2296
|
-
if (this.done || this.stopping || this.paused) return;
|
|
2297
|
-
this.spawnCrossfadeSegment(
|
|
2298
|
-
nextStart,
|
|
2299
|
-
/* fadeIn */
|
|
2300
|
-
true
|
|
2301
|
-
);
|
|
2302
|
-
this.armNextCrossfadeSegment(nextStart);
|
|
2303
|
-
}, delayMs);
|
|
2304
|
-
}
|
|
2305
|
-
releaseCrossfadeSegment(src, gain) {
|
|
2306
|
-
const idx = this.crossfadeChain.findIndex((e) => e.source === src);
|
|
2307
|
-
if (idx >= 0) this.crossfadeChain.splice(idx, 1);
|
|
2308
|
-
try {
|
|
2309
|
-
src.disconnect();
|
|
2310
|
-
gain.disconnect();
|
|
2311
|
-
} catch {
|
|
2312
|
-
}
|
|
2313
|
-
}
|
|
2314
|
-
get inCrossfadeMode() {
|
|
2315
|
-
return this.crossfadeSec > 0;
|
|
2316
|
-
}
|
|
2317
|
-
computeOffset() {
|
|
2318
|
-
if (this.paused) return this.pausedOffset;
|
|
2319
|
-
const elapsed = (this.ctx.currentTime - this.startCtxTime) * this.basePitch;
|
|
2320
|
-
let offset = this.currentOffset + elapsed;
|
|
2321
|
-
if (this.loop) {
|
|
2322
|
-
offset = (offset % this.buffer.duration + this.buffer.duration) % this.buffer.duration;
|
|
2323
|
-
} else {
|
|
2324
|
-
offset = Math.min(offset, this.buffer.duration);
|
|
2325
|
-
}
|
|
2326
|
-
return offset;
|
|
2327
|
-
}
|
|
2328
|
-
};
|
|
2329
|
-
function resolveJittered(v, fallbackBase = 1) {
|
|
2330
|
-
if (typeof v === "number") return v;
|
|
2331
|
-
if (!v) return fallbackBase;
|
|
2332
|
-
const center = v.base ?? fallbackBase;
|
|
2333
|
-
if (v.jitter == null) return center;
|
|
2334
|
-
return center + (Math.random() * 2 - 1) * v.jitter;
|
|
2335
|
-
}
|
|
2336
|
-
function clamp013(v) {
|
|
2337
|
-
if (Number.isNaN(v)) return 0;
|
|
2338
|
-
return Math.min(1, Math.max(0, v));
|
|
2339
|
-
}
|
|
2340
|
-
|
|
2341
|
-
// src/sources/sound.ts
|
|
2342
|
-
var Sound = class {
|
|
2343
|
-
name;
|
|
2344
|
-
deps;
|
|
2345
|
-
constructor(name, deps) {
|
|
2346
|
-
this.name = name;
|
|
2347
|
-
this.deps = deps;
|
|
2348
|
-
}
|
|
2349
|
-
get duration() {
|
|
2350
|
-
return this.deps.buffer.duration;
|
|
2351
|
-
}
|
|
2352
|
-
play(options = {}) {
|
|
2353
|
-
const bus = options.bus ?? this.deps.defaultBus;
|
|
2354
|
-
const busInput = this.deps.resolveBusInput(bus);
|
|
2355
|
-
const spatializer = this.deps.resolveSpatializer?.(bus, options.spatializer);
|
|
2356
|
-
const destination = spatializer ? spatializer.connectInto(busInput) : busInput;
|
|
2357
|
-
const voice = new Voice({
|
|
2358
|
-
ctx: this.deps.ctx,
|
|
2359
|
-
buffer: this.deps.buffer,
|
|
2360
|
-
destination,
|
|
2361
|
-
options: { ...options, bus },
|
|
2362
|
-
spatializer,
|
|
2363
|
-
sourceName: this.name,
|
|
2364
|
-
defaultStopFade: this.deps.defaultStopFade,
|
|
2365
|
-
onEnded: (v) => {
|
|
2366
|
-
this.deps.releaseVoice(v, bus);
|
|
2367
|
-
spatializer?.dispose();
|
|
2368
|
-
}
|
|
2369
|
-
});
|
|
2370
|
-
this.deps.trackVoice(voice, bus);
|
|
2371
|
-
const accepted = this.deps.applyConcurrency?.(voice, bus) ?? true;
|
|
2372
|
-
if (!accepted) {
|
|
2373
|
-
voice.stop();
|
|
2374
|
-
}
|
|
2375
|
-
return voice;
|
|
2376
|
-
}
|
|
2377
|
-
};
|
|
2378
|
-
|
|
2379
|
-
// src/sources/sprite.ts
|
|
2380
|
-
var Sprite = class {
|
|
2381
|
-
name;
|
|
2382
|
-
regions;
|
|
2383
|
-
sound;
|
|
2384
|
-
constructor(name, sound, regions) {
|
|
2385
|
-
this.name = name;
|
|
2386
|
-
this.sound = sound;
|
|
2387
|
-
this.regions = { ...regions };
|
|
2388
|
-
}
|
|
2389
|
-
/** Region names defined on this sprite. */
|
|
2390
|
-
list() {
|
|
2391
|
-
return Object.keys(this.regions);
|
|
2392
|
-
}
|
|
2393
|
-
has(region) {
|
|
2394
|
-
return region in this.regions;
|
|
2395
|
-
}
|
|
2396
|
-
region(name) {
|
|
2397
|
-
const r = this.regions[name];
|
|
2398
|
-
if (!r) throw new SoundNotFoundError(`${this.name}#${name}`);
|
|
2399
|
-
return r;
|
|
2400
|
-
}
|
|
2401
|
-
/**
|
|
2402
|
-
* Spawn a Voice playing the named region. The voice stops itself after
|
|
2403
|
-
* `region.duration` seconds via an internal scheduleAt — the underlying
|
|
2404
|
-
* AudioBufferSourceNode is one big buffer, so we can't rely on its
|
|
2405
|
-
* natural-end event for region timing.
|
|
2406
|
-
*/
|
|
2407
|
-
play(region, options = {}) {
|
|
2408
|
-
const r = this.region(region);
|
|
2409
|
-
const loop = options.loop ?? r.loop ?? false;
|
|
2410
|
-
const voice = this.sound.play({
|
|
2411
|
-
...options,
|
|
2412
|
-
loop,
|
|
2413
|
-
offset: r.start,
|
|
2414
|
-
duration: r.duration,
|
|
2415
|
-
loopStart: r.start,
|
|
2416
|
-
loopEnd: r.start + r.duration
|
|
2417
|
-
});
|
|
2418
|
-
return voice;
|
|
2419
|
-
}
|
|
2420
|
-
};
|
|
2421
|
-
|
|
2422
|
-
// src/sources/stream.ts
|
|
2423
|
-
var StreamSound = class {
|
|
2424
|
-
name;
|
|
2425
|
-
ctx;
|
|
2426
|
-
url;
|
|
2427
|
-
destination;
|
|
2428
|
-
el = null;
|
|
2429
|
-
node = null;
|
|
2430
|
-
gain = null;
|
|
2431
|
-
disposed = false;
|
|
2432
|
-
constructor(name, ctx, url, destination) {
|
|
2433
|
-
this.name = name;
|
|
2434
|
-
this.ctx = ctx;
|
|
2435
|
-
this.url = url;
|
|
2436
|
-
this.destination = destination;
|
|
2437
|
-
}
|
|
2438
|
-
/** Lazily construct the <audio> element + media-element source on first use. */
|
|
2439
|
-
ensure() {
|
|
2440
|
-
if (this.el) return;
|
|
2441
|
-
if (this.disposed) return;
|
|
2442
|
-
if (typeof document === "undefined" || typeof Audio === "undefined") {
|
|
2443
|
-
return;
|
|
2444
|
-
}
|
|
2445
|
-
const el = new Audio();
|
|
2446
|
-
el.src = this.url;
|
|
2447
|
-
el.crossOrigin = "anonymous";
|
|
2448
|
-
el.preload = "auto";
|
|
2449
|
-
const create = this.ctx.createMediaElementSource;
|
|
2450
|
-
if (typeof create !== "function") {
|
|
2451
|
-
this.el = el;
|
|
2452
|
-
return;
|
|
2453
|
-
}
|
|
2454
|
-
const node = create.call(this.ctx, el);
|
|
2455
|
-
const gain = this.ctx.createGain();
|
|
2456
|
-
node.connect(gain);
|
|
2457
|
-
gain.connect(this.destination);
|
|
2458
|
-
this.el = el;
|
|
2459
|
-
this.node = node;
|
|
2460
|
-
this.gain = gain;
|
|
2461
|
-
}
|
|
2462
|
-
async play(options = {}) {
|
|
2463
|
-
this.ensure();
|
|
2464
|
-
if (!this.el) return;
|
|
2465
|
-
if (this.gain) this.gain.gain.value = clamp014(options.volume ?? 1);
|
|
2466
|
-
this.el.loop = options.loop ?? false;
|
|
2467
|
-
try {
|
|
2468
|
-
await this.el.play();
|
|
2469
|
-
} catch {
|
|
2470
|
-
}
|
|
2471
|
-
}
|
|
2472
|
-
pause() {
|
|
2473
|
-
this.el?.pause();
|
|
2474
|
-
}
|
|
2475
|
-
stop() {
|
|
2476
|
-
if (!this.el) return;
|
|
2477
|
-
this.el.pause();
|
|
2478
|
-
try {
|
|
2479
|
-
this.el.currentTime = 0;
|
|
2480
|
-
} catch {
|
|
2481
|
-
}
|
|
2482
|
-
}
|
|
2483
|
-
seek(seconds) {
|
|
2484
|
-
if (!this.el) return;
|
|
2485
|
-
try {
|
|
2486
|
-
this.el.currentTime = Math.max(0, seconds);
|
|
2487
|
-
} catch {
|
|
2488
|
-
}
|
|
2489
|
-
}
|
|
2490
|
-
get currentTime() {
|
|
2491
|
-
return this.el?.currentTime ?? 0;
|
|
2492
|
-
}
|
|
2493
|
-
get duration() {
|
|
2494
|
-
return this.el?.duration ?? 0;
|
|
2495
|
-
}
|
|
2496
|
-
get paused() {
|
|
2497
|
-
return this.el?.paused ?? true;
|
|
2498
|
-
}
|
|
2499
|
-
setVolume(v) {
|
|
2500
|
-
if (this.gain) this.gain.gain.value = clamp014(v);
|
|
2501
|
-
}
|
|
2502
|
-
fade(opts) {
|
|
2503
|
-
if (!this.gain) return Promise.resolve();
|
|
2504
|
-
applyRamp(this.gain.gain, this.ctx.currentTime, clamp014(opts.to), opts.duration, opts.curve ?? "linear");
|
|
2505
|
-
return new Promise((res) => setTimeout(res, Math.max(0, opts.duration) * 1e3));
|
|
2506
|
-
}
|
|
2507
|
-
dispose() {
|
|
2508
|
-
this.disposed = true;
|
|
2509
|
-
try {
|
|
2510
|
-
this.node?.disconnect();
|
|
2511
|
-
this.gain?.disconnect();
|
|
2512
|
-
} catch {
|
|
2513
|
-
}
|
|
2514
|
-
if (this.el) {
|
|
2515
|
-
this.el.pause();
|
|
2516
|
-
this.el.src = "";
|
|
2517
|
-
}
|
|
2518
|
-
this.el = null;
|
|
2519
|
-
this.node = null;
|
|
2520
|
-
this.gain = null;
|
|
2521
|
-
}
|
|
2522
|
-
};
|
|
2523
|
-
function clamp014(v) {
|
|
2524
|
-
if (Number.isNaN(v)) return 0;
|
|
2525
|
-
return Math.min(1, Math.max(0, v));
|
|
2526
|
-
}
|
|
2527
|
-
|
|
2528
|
-
// src/sources/variants.ts
|
|
2529
|
-
var Variants = class {
|
|
2530
|
-
name;
|
|
2531
|
-
count;
|
|
2532
|
-
sounds;
|
|
2533
|
-
strategy;
|
|
2534
|
-
lastIndex = -1;
|
|
2535
|
-
bag = [];
|
|
2536
|
-
constructor(name, sounds, options = {}) {
|
|
2537
|
-
if (sounds.length === 0) throw new Error(`Variants "${name}" requires at least one sound`);
|
|
2538
|
-
this.name = name;
|
|
2539
|
-
this.sounds = sounds;
|
|
2540
|
-
this.count = sounds.length;
|
|
2541
|
-
this.strategy = options.strategy ?? "no-repeat";
|
|
2542
|
-
}
|
|
2543
|
-
/** Spawn a Voice on a randomly-picked variant. */
|
|
2544
|
-
play(options = {}) {
|
|
2545
|
-
return this.sounds[this.pick()].play(options);
|
|
2546
|
-
}
|
|
2547
|
-
/** Force the next pick to use a specific variant index. Useful for tests. */
|
|
2548
|
-
playIndex(index, options = {}) {
|
|
2549
|
-
const i = (index % this.count + this.count) % this.count;
|
|
2550
|
-
this.lastIndex = i;
|
|
2551
|
-
return this.sounds[i].play(options);
|
|
2552
|
-
}
|
|
2553
|
-
pick() {
|
|
2554
|
-
const n = this.count;
|
|
2555
|
-
if (n === 1) return 0;
|
|
2556
|
-
if (this.strategy === "random") {
|
|
2557
|
-
const i2 = Math.floor(Math.random() * n);
|
|
2558
|
-
this.lastIndex = i2;
|
|
2559
|
-
return i2;
|
|
2560
|
-
}
|
|
2561
|
-
if (this.strategy === "shuffle-bag") {
|
|
2562
|
-
if (this.bag.length === 0) {
|
|
2563
|
-
this.bag = Array.from({ length: n }, (_, i3) => i3);
|
|
2564
|
-
for (let i3 = n - 1; i3 > 0; i3--) {
|
|
2565
|
-
const j = Math.floor(Math.random() * (i3 + 1));
|
|
2566
|
-
[this.bag[i3], this.bag[j]] = [this.bag[j], this.bag[i3]];
|
|
2567
|
-
}
|
|
2568
|
-
if (n > 1 && this.bag[0] === this.lastIndex) {
|
|
2569
|
-
[this.bag[0], this.bag[1]] = [this.bag[1], this.bag[0]];
|
|
2570
|
-
}
|
|
2571
|
-
}
|
|
2572
|
-
const i2 = this.bag.shift();
|
|
2573
|
-
this.lastIndex = i2;
|
|
2574
|
-
return i2;
|
|
2575
|
-
}
|
|
2576
|
-
let i = Math.floor(Math.random() * (n - 1));
|
|
2577
|
-
if (i >= this.lastIndex) i++;
|
|
2578
|
-
this.lastIndex = i;
|
|
2579
|
-
return i;
|
|
2580
|
-
}
|
|
2581
|
-
};
|
|
2582
|
-
|
|
2583
|
-
// src/spatial/spatializer.ts
|
|
2584
|
-
var DEFAULT_REF_DISTANCE = 1;
|
|
2585
|
-
var DEFAULT_MAX_DISTANCE = 1e4;
|
|
2586
|
-
var DEFAULT_ROLLOFF = 1;
|
|
2587
|
-
var DEFAULT_DISTANCE_MODEL = "inverse";
|
|
2588
|
-
var OCCLUSION_OPEN_HZ = 22050;
|
|
2589
|
-
var OCCLUSION_MUFFLED_HZ = 500;
|
|
2590
|
-
var Spatializer = class {
|
|
2591
|
-
ctx;
|
|
2592
|
-
kind;
|
|
2593
|
-
input;
|
|
2594
|
-
// what the Voice connects into
|
|
2595
|
-
output;
|
|
2596
|
-
// what we connect to the Bus
|
|
2597
|
-
// 2D-only.
|
|
2598
|
-
stereoPan = null;
|
|
2599
|
-
// 3D-only.
|
|
2600
|
-
panner = null;
|
|
2601
|
-
occlusionFilter = null;
|
|
2602
|
-
occlusionGain = null;
|
|
2603
|
-
constructor(ctx, opts) {
|
|
2604
|
-
this.ctx = ctx;
|
|
2605
|
-
if (opts.position) {
|
|
2606
|
-
const panner = ctx.createPanner();
|
|
2607
|
-
panner.panningModel = "HRTF";
|
|
2608
|
-
panner.distanceModel = opts.distanceModel ?? DEFAULT_DISTANCE_MODEL;
|
|
2609
|
-
panner.refDistance = opts.refDistance ?? DEFAULT_REF_DISTANCE;
|
|
2610
|
-
panner.maxDistance = opts.maxDistance ?? DEFAULT_MAX_DISTANCE;
|
|
2611
|
-
panner.rolloffFactor = opts.rolloffFactor ?? DEFAULT_ROLLOFF;
|
|
2612
|
-
const [x, y, z] = opts.position;
|
|
2613
|
-
this.setPanner3D(panner, x, y, z);
|
|
2614
|
-
const filter = ctx.createBiquadFilter();
|
|
2615
|
-
filter.type = "lowpass";
|
|
2616
|
-
filter.frequency.value = OCCLUSION_OPEN_HZ;
|
|
2617
|
-
filter.Q.value = Math.SQRT1_2;
|
|
2618
|
-
const gain = ctx.createGain();
|
|
2619
|
-
gain.gain.value = 1;
|
|
2620
|
-
panner.connect(filter).connect(gain);
|
|
2621
|
-
this.panner = panner;
|
|
2622
|
-
this.occlusionFilter = filter;
|
|
2623
|
-
this.occlusionGain = gain;
|
|
2624
|
-
this.input = panner;
|
|
2625
|
-
this.output = gain;
|
|
2626
|
-
this.kind = "3d";
|
|
2627
|
-
if (opts.occlusion != null) this.setOcclusion(opts.occlusion);
|
|
2628
|
-
} else {
|
|
2629
|
-
const sp = ctx.createStereoPanner();
|
|
2630
|
-
sp.pan.value = clampPan(opts.pan ?? 0);
|
|
2631
|
-
this.stereoPan = sp;
|
|
2632
|
-
this.input = sp;
|
|
2633
|
-
this.output = sp;
|
|
2634
|
-
this.kind = "2d";
|
|
2635
|
-
}
|
|
2636
|
-
}
|
|
2637
|
-
setPan(pan) {
|
|
2638
|
-
if (this.kind !== "2d" || !this.stereoPan) return;
|
|
2639
|
-
this.stereoPan.pan.value = clampPan(pan);
|
|
2640
|
-
}
|
|
2641
|
-
setPosition(x, y, z) {
|
|
2642
|
-
if (this.kind !== "3d" || !this.panner) return;
|
|
2643
|
-
this.setPanner3D(this.panner, x, y, z);
|
|
2644
|
-
}
|
|
2645
|
-
setRefDistance(d) {
|
|
2646
|
-
if (!this.panner) return;
|
|
2647
|
-
this.panner.refDistance = Math.max(0, d);
|
|
2648
|
-
}
|
|
2649
|
-
setMaxDistance(d) {
|
|
2650
|
-
if (!this.panner) return;
|
|
2651
|
-
this.panner.maxDistance = Math.max(0, d);
|
|
2652
|
-
}
|
|
2653
|
-
setRolloffFactor(f) {
|
|
2654
|
-
if (!this.panner) return;
|
|
2655
|
-
this.panner.rolloffFactor = Math.max(0, f);
|
|
2656
|
-
}
|
|
2657
|
-
setDistanceModel(m) {
|
|
2658
|
-
if (!this.panner) return;
|
|
2659
|
-
this.panner.distanceModel = m;
|
|
2660
|
-
}
|
|
2661
|
-
/**
|
|
2662
|
-
* Set occlusion amount (0..1). Drives the internal lowpass cutoff
|
|
2663
|
-
* and a small gain dip — independent of distance attenuation.
|
|
2664
|
-
* No-op on 2D spatializers.
|
|
2665
|
-
*/
|
|
2666
|
-
setOcclusion(amount) {
|
|
2667
|
-
if (!this.occlusionFilter || !this.occlusionGain) return;
|
|
2668
|
-
const a = clamp015(amount);
|
|
2669
|
-
const cutoff = OCCLUSION_OPEN_HZ * (OCCLUSION_MUFFLED_HZ / OCCLUSION_OPEN_HZ) ** a;
|
|
2670
|
-
const now = this.ctx.currentTime;
|
|
2671
|
-
this.occlusionFilter.frequency.setValueAtTime(cutoff, now);
|
|
2672
|
-
const gainLin = 10 ** (-6 * a / 20);
|
|
2673
|
-
this.occlusionGain.gain.setValueAtTime(gainLin, now);
|
|
2674
|
-
}
|
|
2675
|
-
/** Connects the spatializer's output into `dest` and returns the input the Voice should use. */
|
|
2676
|
-
connectInto(dest) {
|
|
2677
|
-
this.output.connect(dest);
|
|
2678
|
-
return this.input;
|
|
2679
|
-
}
|
|
2680
|
-
dispose() {
|
|
2681
|
-
try {
|
|
2682
|
-
this.input.disconnect();
|
|
2683
|
-
this.occlusionFilter?.disconnect();
|
|
2684
|
-
this.occlusionGain?.disconnect();
|
|
2685
|
-
} catch {
|
|
2686
|
-
}
|
|
2687
|
-
}
|
|
2688
|
-
setPanner3D(p, x, y, z) {
|
|
2689
|
-
if (typeof p.positionX?.setValueAtTime === "function") {
|
|
2690
|
-
const now = this.ctx.currentTime;
|
|
2691
|
-
p.positionX.setValueAtTime(x, now);
|
|
2692
|
-
p.positionY.setValueAtTime(y, now);
|
|
2693
|
-
p.positionZ.setValueAtTime(z, now);
|
|
2694
|
-
} else {
|
|
2695
|
-
const legacy = p;
|
|
2696
|
-
legacy.setPosition?.(x, y, z);
|
|
2697
|
-
}
|
|
2698
|
-
}
|
|
2699
|
-
};
|
|
2700
|
-
function clampPan(v) {
|
|
2701
|
-
return Math.max(-1, Math.min(1, v));
|
|
2702
|
-
}
|
|
2703
|
-
function clamp015(v) {
|
|
2704
|
-
if (Number.isNaN(v)) return 0;
|
|
2705
|
-
return Math.max(0, Math.min(1, v));
|
|
2706
|
-
}
|
|
2707
|
-
|
|
2708
|
-
// src/mixer/master.ts
|
|
2709
|
-
var Master = class {
|
|
2710
|
-
input;
|
|
2711
|
-
headroomDb;
|
|
2712
|
-
ctx;
|
|
2713
|
-
limiterNode = null;
|
|
2714
|
-
limiterCfg;
|
|
2715
|
-
destination;
|
|
2716
|
-
_meterAnalyser = null;
|
|
2717
|
-
_meterBuf = null;
|
|
2718
|
-
constructor(ctx, config = {}) {
|
|
2719
|
-
this.ctx = ctx;
|
|
2720
|
-
this.input = ctx.createGain();
|
|
2721
|
-
this.headroomDb = config.headroom ?? 0;
|
|
2722
|
-
this.input.gain.value = dbToLinear(this.headroomDb);
|
|
2723
|
-
this.destination = ctx.destination;
|
|
2724
|
-
this.limiterCfg = config.limiter ?? null;
|
|
2725
|
-
this.rewire();
|
|
2726
|
-
}
|
|
2727
|
-
setHeadroom(db) {
|
|
2728
|
-
this.headroomDb = db;
|
|
2729
|
-
this.input.gain.value = dbToLinear(db);
|
|
2730
|
-
}
|
|
2731
|
-
get headroom() {
|
|
2732
|
-
return this.headroomDb;
|
|
2733
|
-
}
|
|
2734
|
-
/**
|
|
2735
|
-
* Enable or update the master limiter. Pass `null` to disable.
|
|
2736
|
-
* The limiter sits between master gain and destination.
|
|
2737
|
-
*/
|
|
2738
|
-
setLimiter(cfg) {
|
|
2739
|
-
this.limiterCfg = cfg;
|
|
2740
|
-
this.rewire();
|
|
2741
|
-
}
|
|
2742
|
-
/** Live gain reduction in dB. 0 if no limiter is engaged. */
|
|
2743
|
-
get reduction() {
|
|
2744
|
-
return this.limiterNode?.reduction ?? 0;
|
|
2745
|
-
}
|
|
2746
|
-
/**
|
|
2747
|
-
* Live amplitude readout on the master input. Returns `{ rms, peak }`
|
|
2748
|
-
* as linear values in [0..1]. The first call lazily attaches an
|
|
2749
|
-
* AnalyserNode as a passive sibling of the master gain — no audio-path
|
|
2750
|
-
* change. Same shape as `bus.meter()` and `voice.level()`.
|
|
2751
|
-
*/
|
|
2752
|
-
meter() {
|
|
2753
|
-
if (!this._meterAnalyser) {
|
|
2754
|
-
const a = this.ctx.createAnalyser();
|
|
2755
|
-
a.fftSize = 1024;
|
|
2756
|
-
this.input.connect(a);
|
|
2757
|
-
this._meterAnalyser = a;
|
|
2758
|
-
this._meterBuf = new Float32Array(a.fftSize);
|
|
2759
|
-
}
|
|
2760
|
-
const buf = this._meterBuf;
|
|
2761
|
-
this._meterAnalyser.getFloatTimeDomainData(buf);
|
|
2762
|
-
let sumSq = 0;
|
|
2763
|
-
let peak = 0;
|
|
2764
|
-
for (let i = 0; i < buf.length; i++) {
|
|
2765
|
-
const s = buf[i] ?? 0;
|
|
2766
|
-
sumSq += s * s;
|
|
2767
|
-
const a = Math.abs(s);
|
|
2768
|
-
if (a > peak) peak = a;
|
|
2769
|
-
}
|
|
2770
|
-
return { rms: Math.sqrt(sumSq / buf.length), peak };
|
|
2771
|
-
}
|
|
2772
|
-
dispose() {
|
|
2773
|
-
try {
|
|
2774
|
-
this.input.disconnect();
|
|
2775
|
-
this.limiterNode?.disconnect();
|
|
2776
|
-
this._meterAnalyser?.disconnect();
|
|
2777
|
-
} catch {
|
|
2778
|
-
}
|
|
2779
|
-
this.limiterNode = null;
|
|
2780
|
-
this._meterAnalyser = null;
|
|
2781
|
-
this._meterBuf = null;
|
|
2782
|
-
}
|
|
2783
|
-
rewire() {
|
|
2784
|
-
try {
|
|
2785
|
-
this.input.disconnect();
|
|
2786
|
-
this.limiterNode?.disconnect();
|
|
2787
|
-
} catch {
|
|
2788
|
-
}
|
|
2789
|
-
this.limiterNode = null;
|
|
2790
|
-
if (!this.limiterCfg) {
|
|
2791
|
-
this.input.connect(this.destination);
|
|
2792
|
-
return;
|
|
2793
|
-
}
|
|
2794
|
-
const cfg = this.limiterCfg;
|
|
2795
|
-
const limiter = this.ctx.createDynamicsCompressor();
|
|
2796
|
-
limiter.threshold.value = cfg.threshold ?? -1;
|
|
2797
|
-
limiter.knee.value = 0;
|
|
2798
|
-
limiter.ratio.value = Math.max(20, cfg.ratio ?? 20);
|
|
2799
|
-
limiter.attack.value = cfg.attack ?? 1e-3;
|
|
2800
|
-
limiter.release.value = cfg.release ?? 0.05;
|
|
2801
|
-
this.input.connect(limiter);
|
|
2802
|
-
limiter.connect(this.destination);
|
|
2803
|
-
this.limiterNode = limiter;
|
|
2804
|
-
}
|
|
2805
|
-
};
|
|
2806
|
-
function dbToLinear(db) {
|
|
2807
|
-
return 10 ** (db / 20);
|
|
2808
|
-
}
|
|
2809
|
-
|
|
2810
|
-
// src/mixer/snapshot.ts
|
|
2811
|
-
var Snapshot = class {
|
|
2812
|
-
name;
|
|
2813
|
-
state;
|
|
2814
|
-
getBus;
|
|
2815
|
-
getParam;
|
|
2816
|
-
constructor(name, state, getBus, getParam) {
|
|
2817
|
-
this.name = name;
|
|
2818
|
-
this.state = state;
|
|
2819
|
-
this.getBus = getBus;
|
|
2820
|
-
this.getParam = getParam;
|
|
2821
|
-
}
|
|
2822
|
-
apply(opts = {}) {
|
|
2823
|
-
const fade = opts.fade ?? 0;
|
|
2824
|
-
const tasks = [];
|
|
2825
|
-
for (const [name, bs] of Object.entries(this.state.buses)) {
|
|
2826
|
-
const bus = this.getBus(name);
|
|
2827
|
-
if (!bus) continue;
|
|
2828
|
-
bus.muted = bs.muted;
|
|
2829
|
-
tasks.push(bus.fadeTo(bs.level, fade));
|
|
2830
|
-
}
|
|
2831
|
-
for (const [name, value] of Object.entries(this.state.parameters)) {
|
|
2832
|
-
const param = this.getParam(name);
|
|
2833
|
-
if (!param) continue;
|
|
2834
|
-
param.set(value);
|
|
2835
|
-
}
|
|
2836
|
-
return Promise.all(tasks).then(() => void 0);
|
|
2837
|
-
}
|
|
2838
|
-
/**
|
|
2839
|
-
* Snap the live mix to a linear interpolation between this snapshot and
|
|
2840
|
-
* `other`. `t` is clamped to [0, 1]: `t = 0` matches this snapshot,
|
|
2841
|
-
* `t = 1` matches `other`, and intermediate values lerp every shared
|
|
2842
|
-
* bus level and parameter.
|
|
2843
|
-
*
|
|
2844
|
-
* Designed to be called continuously (e.g. from a `Parameter` subscriber)
|
|
2845
|
-
* — each call snaps instantly. For a one-shot crossfade with a fade
|
|
2846
|
-
* duration, use `apply({ fade })` instead.
|
|
2847
|
-
*
|
|
2848
|
-
* Buses or parameters present in only one of the two snapshots are
|
|
2849
|
-
* skipped. Mute flags are not interpolated: `t < 0.5` uses this
|
|
2850
|
-
* snapshot's mute, `t >= 0.5` uses `other`'s.
|
|
2851
|
-
*/
|
|
2852
|
-
blendWith(other, t) {
|
|
2853
|
-
const u = t < 0 ? 0 : t > 1 ? 1 : t;
|
|
2854
|
-
const v = 1 - u;
|
|
2855
|
-
for (const [name, busA] of Object.entries(this.state.buses)) {
|
|
2856
|
-
const busB = other.state.buses[name];
|
|
2857
|
-
if (!busB) continue;
|
|
2858
|
-
const bus = this.getBus(name);
|
|
2859
|
-
if (!bus) continue;
|
|
2860
|
-
bus.muted = u < 0.5 ? busA.muted : busB.muted;
|
|
2861
|
-
bus.level = busA.level * v + busB.level * u;
|
|
2862
|
-
}
|
|
2863
|
-
for (const [name, valA] of Object.entries(this.state.parameters)) {
|
|
2864
|
-
const valB = other.state.parameters[name];
|
|
2865
|
-
if (valB === void 0) continue;
|
|
2866
|
-
const param = this.getParam(name);
|
|
2867
|
-
if (!param) continue;
|
|
2868
|
-
param.set(valA * v + valB * u);
|
|
2869
|
-
}
|
|
2870
|
-
}
|
|
2871
|
-
};
|
|
2872
|
-
|
|
2873
|
-
// src/mixer/engine.ts
|
|
2874
|
-
function createEngine(config = {}) {
|
|
2875
|
-
return new EngineImpl(config);
|
|
2876
|
-
}
|
|
2877
|
-
var EngineImpl = class {
|
|
2878
|
-
host;
|
|
2879
|
-
decoder;
|
|
2880
|
-
scheduler = null;
|
|
2881
|
-
master = null;
|
|
2882
|
-
buses = /* @__PURE__ */ new Map();
|
|
2883
|
-
busOrder = [];
|
|
2884
|
-
sounds = /* @__PURE__ */ new Map();
|
|
2885
|
-
sprites = /* @__PURE__ */ new Map();
|
|
2886
|
-
streams = /* @__PURE__ */ new Map();
|
|
2887
|
-
musics = /* @__PURE__ */ new Map();
|
|
2888
|
-
variantsByName = /* @__PURE__ */ new Map();
|
|
2889
|
-
busGroups = /* @__PURE__ */ new Map();
|
|
2890
|
-
soloedBuses = /* @__PURE__ */ new Set();
|
|
2891
|
-
/**
|
|
2892
|
-
* URL fingerprint per loadSound call so `unloadSound` can evict the
|
|
2893
|
-
* matching entries from the Decoder LRU. Sounds registered via
|
|
2894
|
-
* `createSound` (procedural buffers) leave no fingerprint here.
|
|
2895
|
-
*/
|
|
2896
|
-
soundUrls = /* @__PURE__ */ new Map();
|
|
2897
|
-
voices = /* @__PURE__ */ new Map();
|
|
2898
|
-
parameters = /* @__PURE__ */ new Map();
|
|
2899
|
-
config;
|
|
2900
|
-
constructor(config) {
|
|
2901
|
-
this.config = config;
|
|
2902
|
-
this.host = new AudioContextHost({
|
|
2903
|
-
autoPauseOnHidden: config.autoPauseOnHidden,
|
|
2904
|
-
latencyHint: config.latencyHint
|
|
2905
|
-
});
|
|
2906
|
-
this.decoder = new Decoder(() => this.host.touch());
|
|
2907
|
-
const declared = Object.keys(config.buses ?? {});
|
|
2908
|
-
this.busOrder = declared.length > 0 ? declared : ["default"];
|
|
2909
|
-
for (const name of this.busOrder) this.voices.set(name, /* @__PURE__ */ new Set());
|
|
2910
|
-
}
|
|
2911
|
-
get state() {
|
|
2912
|
-
return this.host.state;
|
|
2913
|
-
}
|
|
2914
|
-
get now() {
|
|
2915
|
-
return this.host.now;
|
|
2916
|
-
}
|
|
2917
|
-
get context() {
|
|
2918
|
-
return this.host.touch();
|
|
2919
|
-
}
|
|
2920
|
-
async unlock() {
|
|
2921
|
-
await this.host.unlock();
|
|
2922
|
-
this.ensureGraph();
|
|
2923
|
-
}
|
|
2924
|
-
async close() {
|
|
2925
|
-
if (this.host.state === "closed") return;
|
|
2926
|
-
for (const set of this.voices.values()) {
|
|
2927
|
-
for (const v of set) v.stop();
|
|
2928
|
-
set.clear();
|
|
2929
|
-
}
|
|
2930
|
-
this.scheduler?.dispose();
|
|
2931
|
-
this.scheduler = null;
|
|
2932
|
-
for (const bus of this.buses.values()) {
|
|
2933
|
-
for (const fx of bus.fx()) fx.dispose();
|
|
2934
|
-
bus.dispose();
|
|
2935
|
-
}
|
|
2936
|
-
this.buses.clear();
|
|
2937
|
-
this.master?.dispose();
|
|
2938
|
-
this.master = null;
|
|
2939
|
-
this.sounds.clear();
|
|
2940
|
-
this.sprites.clear();
|
|
2941
|
-
this.musics.clear();
|
|
2942
|
-
this.variantsByName.clear();
|
|
2943
|
-
this.soundUrls.clear();
|
|
2944
|
-
for (const s of this.streams.values()) s.dispose();
|
|
2945
|
-
this.streams.clear();
|
|
2946
|
-
this.parameters.clear();
|
|
2947
|
-
this.decoder.clear();
|
|
2948
|
-
await this.host.close();
|
|
2949
|
-
}
|
|
2950
|
-
async loadSound(name, url, options = {}) {
|
|
2951
|
-
if (this.host.state === "closed") throw new EngineClosedError();
|
|
2952
|
-
this.host.touch();
|
|
2953
|
-
this.ensureGraph();
|
|
2954
|
-
const decodeOpts = { signal: options.signal };
|
|
2955
|
-
let buffer = await this.resolveBuffer(name, url, decodeOpts);
|
|
2956
|
-
if (options.normalize) {
|
|
2957
|
-
buffer = applyLoudnessNormalization(buffer, options.normalize, this.host.touch());
|
|
2958
|
-
}
|
|
2959
|
-
this.soundUrls.set(name, typeof url === "string" ? [url] : [...url]);
|
|
2960
|
-
return this.createSound(name, buffer, { bus: options.bus });
|
|
2961
|
-
}
|
|
2962
|
-
async resolveBuffer(name, url, decodeOpts) {
|
|
2963
|
-
const resolver = this.config.resolveAsset;
|
|
2964
|
-
if (resolver) {
|
|
2965
|
-
const resolved = await resolver({ name, url, signal: decodeOpts.signal });
|
|
2966
|
-
if (resolved != null) {
|
|
2967
|
-
if (resolved instanceof AudioBuffer) return resolved;
|
|
2968
|
-
if (resolved instanceof ArrayBuffer) {
|
|
2969
|
-
return await this.host.touch().decodeAudioData(resolved);
|
|
2970
|
-
}
|
|
2971
|
-
if (typeof resolved === "string") {
|
|
2972
|
-
return await this.decoder.load(resolved, decodeOpts);
|
|
2973
|
-
}
|
|
2974
|
-
}
|
|
2975
|
-
}
|
|
2976
|
-
const urls = typeof url === "string" ? [url] : pickSourceOrder(url);
|
|
2977
|
-
return await this.decoder.loadFirst(urls, decodeOpts);
|
|
2978
|
-
}
|
|
2979
|
-
async preload(items, options = {}) {
|
|
2980
|
-
if (this.host.state === "closed") throw new EngineClosedError();
|
|
2981
|
-
if (items.length === 0) return;
|
|
2982
|
-
const concurrency = Math.max(1, options.concurrency ?? 4);
|
|
2983
|
-
const onProgress = options.onProgress;
|
|
2984
|
-
const batchSignal = options.signal;
|
|
2985
|
-
const total = items.length;
|
|
2986
|
-
let completed = 0;
|
|
2987
|
-
const failures = [];
|
|
2988
|
-
let nextIdx = 0;
|
|
2989
|
-
const workerCount = Math.min(concurrency, total);
|
|
2990
|
-
const workers = [];
|
|
2991
|
-
for (let w = 0; w < workerCount; w++) {
|
|
2992
|
-
workers.push(
|
|
2993
|
-
(async () => {
|
|
2994
|
-
while (true) {
|
|
2995
|
-
const idx = nextIdx++;
|
|
2996
|
-
if (idx >= total) return;
|
|
2997
|
-
if (batchSignal?.aborted) {
|
|
2998
|
-
throw batchSignal.reason ?? new DOMException("preload aborted", "AbortError");
|
|
2999
|
-
}
|
|
3000
|
-
const item = items[idx];
|
|
3001
|
-
const itemSignal = combineSignals(batchSignal, item.options?.signal);
|
|
3002
|
-
const opts = { ...item.options ?? {}, signal: itemSignal };
|
|
3003
|
-
try {
|
|
3004
|
-
await this.loadSound(item.name, item.url, opts);
|
|
3005
|
-
completed++;
|
|
3006
|
-
onProgress?.({ name: item.name, status: "loaded", completed, total });
|
|
3007
|
-
} catch (e) {
|
|
3008
|
-
if (e.name === "AbortError") throw e;
|
|
3009
|
-
completed++;
|
|
3010
|
-
failures.push({ name: item.name, cause: e });
|
|
3011
|
-
onProgress?.({ name: item.name, status: "failed", error: e, completed, total });
|
|
3012
|
-
}
|
|
3013
|
-
}
|
|
3014
|
-
})()
|
|
3015
|
-
);
|
|
3016
|
-
}
|
|
3017
|
-
await Promise.all(workers);
|
|
3018
|
-
if (failures.length > 0) throw new PreloadError(failures);
|
|
3019
|
-
}
|
|
3020
|
-
async loadSprite(name, url, regions, options = {}) {
|
|
3021
|
-
const sound = await this.loadSound(`__sprite:${name}`, url, options);
|
|
3022
|
-
const sprite = new Sprite(name, sound, regions);
|
|
3023
|
-
this.sprites.set(name, sprite);
|
|
3024
|
-
return sprite;
|
|
3025
|
-
}
|
|
3026
|
-
sprite(name) {
|
|
3027
|
-
const s = this.sprites.get(name);
|
|
3028
|
-
if (!s) throw new SoundNotFoundError(suggest(name, [...this.sprites.keys()]));
|
|
3029
|
-
return s;
|
|
3030
|
-
}
|
|
3031
|
-
hasSprite(name) {
|
|
3032
|
-
return this.sprites.has(name);
|
|
3033
|
-
}
|
|
3034
|
-
async loadVariants(name, urls, options = {}) {
|
|
3035
|
-
if (urls.length === 0) {
|
|
3036
|
-
throw new Error(`engine.loadVariants("${name}") requires at least one URL set`);
|
|
3037
|
-
}
|
|
3038
|
-
const { strategy, ...loadOpts } = options;
|
|
3039
|
-
const sounds = [];
|
|
3040
|
-
for (let i = 0; i < urls.length; i++) {
|
|
3041
|
-
sounds.push(await this.loadSound(`__variant:${name}:${i}`, urls[i], loadOpts));
|
|
3042
|
-
}
|
|
3043
|
-
const v = new Variants(name, sounds, { strategy });
|
|
3044
|
-
this.variantsByName.set(name, v);
|
|
3045
|
-
return v;
|
|
3046
|
-
}
|
|
3047
|
-
variants(name) {
|
|
3048
|
-
const v = this.variantsByName.get(name);
|
|
3049
|
-
if (!v) throw new SoundNotFoundError(suggest(name, [...this.variantsByName.keys()]));
|
|
3050
|
-
return v;
|
|
3051
|
-
}
|
|
3052
|
-
hasVariants(name) {
|
|
3053
|
-
return this.variantsByName.has(name);
|
|
3054
|
-
}
|
|
3055
|
-
async loadMusic(name, parts, options = {}) {
|
|
3056
|
-
if (this.host.state === "closed") throw new EngineClosedError();
|
|
3057
|
-
this.host.touch();
|
|
3058
|
-
this.ensureGraph();
|
|
3059
|
-
const decodeOpts = { signal: options.signal };
|
|
3060
|
-
const loopBuf = await this.resolveBuffer(`__music:${name}:loop`, parts.loop, decodeOpts);
|
|
3061
|
-
const introBuf = parts.intro ? await this.resolveBuffer(`__music:${name}:intro`, parts.intro, decodeOpts) : void 0;
|
|
3062
|
-
const outroBuf = parts.outro ? await this.resolveBuffer(`__music:${name}:outro`, parts.outro, decodeOpts) : void 0;
|
|
3063
|
-
const ctx = this.host.touch();
|
|
3064
|
-
const buffers = {
|
|
3065
|
-
intro: introBuf ? options.normalize ? applyLoudnessNormalization(introBuf, options.normalize, ctx) : introBuf : void 0,
|
|
3066
|
-
loop: options.normalize ? applyLoudnessNormalization(loopBuf, options.normalize, ctx) : loopBuf,
|
|
3067
|
-
outro: outroBuf ? options.normalize ? applyLoudnessNormalization(outroBuf, options.normalize, ctx) : outroBuf : void 0
|
|
3068
|
-
};
|
|
3069
|
-
const busName = options.bus ?? this.busOrder[0];
|
|
3070
|
-
const bus = this.buses.get(busName);
|
|
3071
|
-
if (!bus) throw new BusNotFoundError(suggest(busName, [...this.buses.keys()]));
|
|
3072
|
-
const music = new Music(name, {
|
|
3073
|
-
ctx: this.host.touch(),
|
|
3074
|
-
buffers,
|
|
3075
|
-
destination: bus.input,
|
|
3076
|
-
loopCrossfade: options.loopCrossfade ?? 0,
|
|
3077
|
-
defaultStopFade: this.config.voice?.stopFade
|
|
3078
|
-
});
|
|
3079
|
-
this.musics.set(name, music);
|
|
3080
|
-
return music;
|
|
3081
|
-
}
|
|
3082
|
-
music(name) {
|
|
3083
|
-
const m = this.musics.get(name);
|
|
3084
|
-
if (!m) throw new SoundNotFoundError(suggest(name, [...this.musics.keys()]));
|
|
3085
|
-
return m;
|
|
3086
|
-
}
|
|
3087
|
-
hasMusic(name) {
|
|
3088
|
-
return this.musics.has(name);
|
|
3089
|
-
}
|
|
3090
|
-
loadStream(name, url, options = {}) {
|
|
3091
|
-
if (this.host.state === "closed") throw new EngineClosedError();
|
|
3092
|
-
this.host.touch();
|
|
3093
|
-
this.ensureGraph();
|
|
3094
|
-
const resolvedUrl = typeof url === "string" ? url : pickSource(url);
|
|
3095
|
-
const bus = options.bus ?? this.busOrder[0];
|
|
3096
|
-
const busObj = this.buses.get(bus);
|
|
3097
|
-
if (!busObj) throw new BusNotFoundError(suggest(bus, [...this.buses.keys()]));
|
|
3098
|
-
const stream = new StreamSound(name, this.host.touch(), resolvedUrl, busObj.input);
|
|
3099
|
-
this.streams.set(name, stream);
|
|
3100
|
-
return stream;
|
|
3101
|
-
}
|
|
3102
|
-
stream(name) {
|
|
3103
|
-
const s = this.streams.get(name);
|
|
3104
|
-
if (!s) throw new SoundNotFoundError(suggest(name, [...this.streams.keys()]));
|
|
3105
|
-
return s;
|
|
3106
|
-
}
|
|
3107
|
-
hasStream(name) {
|
|
3108
|
-
return this.streams.has(name);
|
|
3109
|
-
}
|
|
3110
|
-
crossfade(from, to, options = {}) {
|
|
3111
|
-
const duration = options.duration ?? 1.5;
|
|
3112
|
-
const curve = options.curve ?? "equal-power";
|
|
3113
|
-
const toVolume = options.toVolume ?? 1;
|
|
3114
|
-
const target = this.sound(to);
|
|
3115
|
-
const newVoice = target.play({
|
|
3116
|
-
bus: options.bus,
|
|
3117
|
-
loop: options.loop ?? true,
|
|
3118
|
-
volume: 0
|
|
3119
|
-
});
|
|
3120
|
-
void newVoice.fade({ to: toVolume, duration, curve });
|
|
3121
|
-
const outgoing = this.activeVoices().filter(
|
|
3122
|
-
(v) => v !== newVoice && v.sourceName === from && v.bus === newVoice.bus
|
|
3123
|
-
);
|
|
3124
|
-
for (const v of outgoing) {
|
|
3125
|
-
void v.fade({ to: 0, duration, curve }).then(() => v.stop());
|
|
3126
|
-
}
|
|
3127
|
-
return newVoice;
|
|
3128
|
-
}
|
|
3129
|
-
createSound(name, buffer, options = {}) {
|
|
3130
|
-
if (this.host.state === "closed") throw new EngineClosedError();
|
|
3131
|
-
this.host.touch();
|
|
3132
|
-
this.ensureGraph();
|
|
3133
|
-
const defaultBus = options.bus ?? this.busOrder[0];
|
|
3134
|
-
if (!this.buses.has(defaultBus)) throw new BusNotFoundError(suggest(defaultBus, [...this.buses.keys()]));
|
|
3135
|
-
const sound = new Sound(name, {
|
|
3136
|
-
ctx: this.host.touch(),
|
|
3137
|
-
buffer,
|
|
3138
|
-
defaultBus,
|
|
3139
|
-
defaultStopFade: this.config.voice?.stopFade,
|
|
3140
|
-
resolveBusInput: (busName) => {
|
|
3141
|
-
const bus = this.buses.get(busName);
|
|
3142
|
-
if (!bus) throw new BusNotFoundError(suggest(busName, [...this.buses.keys()]));
|
|
3143
|
-
return bus.input;
|
|
3144
|
-
},
|
|
3145
|
-
resolveSpatializer: (_busName, opts) => {
|
|
3146
|
-
if (!opts) return void 0;
|
|
3147
|
-
return new Spatializer(this.host.touch(), opts);
|
|
3148
|
-
},
|
|
3149
|
-
trackVoice: (v, busName) => {
|
|
3150
|
-
this.voices.get(busName)?.add(v);
|
|
3151
|
-
this.buses.get(busName)?.trackVoice(v);
|
|
3152
|
-
},
|
|
3153
|
-
releaseVoice: (v, busName) => {
|
|
3154
|
-
this.voices.get(busName)?.delete(v);
|
|
3155
|
-
this.buses.get(busName)?.releaseVoice(v);
|
|
3156
|
-
},
|
|
3157
|
-
applyConcurrency: (v, busName) => {
|
|
3158
|
-
const bus = this.buses.get(busName);
|
|
3159
|
-
if (!bus) return true;
|
|
3160
|
-
let rejected = false;
|
|
3161
|
-
const stolen = bus.applyConcurrencyOnSpawn(v, () => {
|
|
3162
|
-
rejected = true;
|
|
3163
|
-
});
|
|
3164
|
-
if (stolen) {
|
|
3165
|
-
this.voices.get(busName)?.delete(stolen);
|
|
3166
|
-
bus.releaseVoice(stolen);
|
|
3167
|
-
}
|
|
3168
|
-
if (rejected) {
|
|
3169
|
-
this.voices.get(busName)?.delete(v);
|
|
3170
|
-
bus.releaseVoice(v);
|
|
3171
|
-
}
|
|
3172
|
-
return !rejected;
|
|
3173
|
-
}
|
|
3174
|
-
});
|
|
3175
|
-
this.sounds.set(name, sound);
|
|
3176
|
-
return sound;
|
|
3177
|
-
}
|
|
3178
|
-
removeSound(name) {
|
|
3179
|
-
this.sounds.delete(name);
|
|
3180
|
-
}
|
|
3181
|
-
unloadSound(name, options = {}) {
|
|
3182
|
-
this.sounds.delete(name);
|
|
3183
|
-
if (options.evictBuffer ?? true) {
|
|
3184
|
-
const urls = this.soundUrls.get(name);
|
|
3185
|
-
if (urls) {
|
|
3186
|
-
for (const u of urls) this.decoder.evict(u);
|
|
3187
|
-
}
|
|
3188
|
-
}
|
|
3189
|
-
this.soundUrls.delete(name);
|
|
3190
|
-
}
|
|
3191
|
-
hasSound(name) {
|
|
3192
|
-
return this.sounds.has(name);
|
|
3193
|
-
}
|
|
3194
|
-
sound(name) {
|
|
3195
|
-
const s = this.sounds.get(name);
|
|
3196
|
-
if (!s) throw new SoundNotFoundError(suggest(name, [...this.sounds.keys()]));
|
|
3197
|
-
return s;
|
|
3198
|
-
}
|
|
3199
|
-
bus(name) {
|
|
3200
|
-
this.ensureGraph();
|
|
3201
|
-
const b = this.buses.get(name);
|
|
3202
|
-
if (!b) throw new BusNotFoundError(suggest(name, [...this.buses.keys()]));
|
|
3203
|
-
return b;
|
|
3204
|
-
}
|
|
3205
|
-
busGroup(name, members) {
|
|
3206
|
-
if (members != null) {
|
|
3207
|
-
const group = new BusGroup(name, members);
|
|
3208
|
-
this.busGroups.set(name, group);
|
|
3209
|
-
return group;
|
|
3210
|
-
}
|
|
3211
|
-
const existing = this.busGroups.get(name);
|
|
3212
|
-
if (!existing) {
|
|
3213
|
-
throw new BusNotFoundError(suggest(name, [...this.busGroups.keys()]));
|
|
3214
|
-
}
|
|
3215
|
-
return existing;
|
|
3216
|
-
}
|
|
3217
|
-
masterMeter() {
|
|
3218
|
-
this.ensureGraph();
|
|
3219
|
-
return this.master.meter();
|
|
3220
|
-
}
|
|
3221
|
-
scheduleAt(audioTime, fn) {
|
|
3222
|
-
this.host.touch();
|
|
3223
|
-
this.ensureGraph();
|
|
3224
|
-
return this.scheduler.scheduleAt(audioTime, fn);
|
|
3225
|
-
}
|
|
3226
|
-
activeVoices() {
|
|
3227
|
-
const all = [];
|
|
3228
|
-
for (const set of this.voices.values()) for (const v of set) all.push(v);
|
|
3229
|
-
return all;
|
|
3230
|
-
}
|
|
3231
|
-
onStateChange(fn) {
|
|
3232
|
-
return this.host.onStateChange(fn);
|
|
3233
|
-
}
|
|
3234
|
-
parameter(name, initial = 0) {
|
|
3235
|
-
let p = this.parameters.get(name);
|
|
3236
|
-
if (!p) {
|
|
3237
|
-
p = new Parameter(name, initial);
|
|
3238
|
-
this.parameters.set(name, p);
|
|
3239
|
-
}
|
|
3240
|
-
return p;
|
|
3241
|
-
}
|
|
3242
|
-
captureSnapshot(name) {
|
|
3243
|
-
const buses = {};
|
|
3244
|
-
for (const [n, b] of this.buses) buses[n] = { level: b.level, muted: b.muted };
|
|
3245
|
-
const parameters = {};
|
|
3246
|
-
for (const [n, p] of this.parameters) parameters[n] = p.value;
|
|
3247
|
-
return this.snapshot(name, { buses, parameters });
|
|
3248
|
-
}
|
|
3249
|
-
snapshot(name, state) {
|
|
3250
|
-
return new Snapshot(
|
|
3251
|
-
name,
|
|
3252
|
-
state,
|
|
3253
|
-
(busName) => this.buses.get(busName),
|
|
3254
|
-
(paramName) => this.parameters.get(paramName)
|
|
3255
|
-
);
|
|
3256
|
-
}
|
|
3257
|
-
blendSnapshots(a, b, t) {
|
|
3258
|
-
a.blendWith(b, t);
|
|
3259
|
-
}
|
|
3260
|
-
/**
|
|
3261
|
-
* Lazily instantiate the bus graph against the live AudioContext. Called
|
|
3262
|
-
* from any path that touches the context (unlock, loadSound, bus, ...).
|
|
3263
|
-
*/
|
|
3264
|
-
ensureGraph() {
|
|
3265
|
-
if (this.master) return;
|
|
3266
|
-
const ctx = this.host.touch();
|
|
3267
|
-
this.master = new Master(ctx, this.config.master);
|
|
3268
|
-
this.scheduler = new Scheduler(this.host, this.config.tickSource);
|
|
3269
|
-
for (const name of this.busOrder) {
|
|
3270
|
-
const cfg = this.config.buses?.[name] ?? {};
|
|
3271
|
-
const bus = new Bus(ctx, name, cfg);
|
|
3272
|
-
bus.output.connect(this.master.input);
|
|
3273
|
-
bus.notifySoloChange = (b, soloed) => this.handleSoloChange(b, soloed);
|
|
3274
|
-
this.buses.set(name, bus);
|
|
3275
|
-
if (!this.voices.has(name)) this.voices.set(name, /* @__PURE__ */ new Set());
|
|
3276
|
-
}
|
|
3277
|
-
}
|
|
3278
|
-
/**
|
|
3279
|
-
* Coordinate the global solo rule. When any bus is in the solo set,
|
|
3280
|
-
* every non-soloed bus is muted via `applySoloVeil(true)`. When the
|
|
3281
|
-
* solo set drains, every bus is restored via `applySoloVeil(false)` —
|
|
3282
|
-
* which honours the bus's own `muted` setting independently.
|
|
3283
|
-
*/
|
|
3284
|
-
handleSoloChange(bus, soloed) {
|
|
3285
|
-
if (soloed) this.soloedBuses.add(bus);
|
|
3286
|
-
else this.soloedBuses.delete(bus);
|
|
3287
|
-
const anySoloed = this.soloedBuses.size > 0;
|
|
3288
|
-
for (const b of this.buses.values()) {
|
|
3289
|
-
if (!anySoloed) {
|
|
3290
|
-
b.applySoloVeil(false);
|
|
3291
|
-
} else {
|
|
3292
|
-
b.applySoloVeil(!this.soloedBuses.has(b));
|
|
3293
|
-
}
|
|
3294
|
-
}
|
|
3295
|
-
}
|
|
3296
|
-
};
|
|
3297
|
-
function suggest(missing, candidates) {
|
|
3298
|
-
if (candidates.length === 0) return missing;
|
|
3299
|
-
let best = null;
|
|
3300
|
-
let bestDist = Infinity;
|
|
3301
|
-
for (const c of candidates) {
|
|
3302
|
-
const d = levenshtein(missing, c);
|
|
3303
|
-
if (d < bestDist) {
|
|
3304
|
-
bestDist = d;
|
|
3305
|
-
best = c;
|
|
3306
|
-
}
|
|
3307
|
-
}
|
|
3308
|
-
const longest = Math.max(missing.length, best?.length ?? 0);
|
|
3309
|
-
const threshold = Math.max(1, Math.ceil(longest / 2));
|
|
3310
|
-
if (best && bestDist <= threshold) {
|
|
3311
|
-
return `${missing}"; did you mean "${best}`;
|
|
3312
|
-
}
|
|
3313
|
-
return missing;
|
|
3314
|
-
}
|
|
3315
|
-
function combineSignals(a, b) {
|
|
3316
|
-
if (!a) return b;
|
|
3317
|
-
if (!b) return a;
|
|
3318
|
-
if (a.aborted) return a;
|
|
3319
|
-
if (b.aborted) return b;
|
|
3320
|
-
const ac = new AbortController();
|
|
3321
|
-
const cleanup = () => {
|
|
3322
|
-
a.removeEventListener("abort", onAbortA);
|
|
3323
|
-
b.removeEventListener("abort", onAbortB);
|
|
3324
|
-
};
|
|
3325
|
-
const onAbortA = () => {
|
|
3326
|
-
cleanup();
|
|
3327
|
-
ac.abort(a.reason);
|
|
3328
|
-
};
|
|
3329
|
-
const onAbortB = () => {
|
|
3330
|
-
cleanup();
|
|
3331
|
-
ac.abort(b.reason);
|
|
3332
|
-
};
|
|
3333
|
-
a.addEventListener("abort", onAbortA);
|
|
3334
|
-
b.addEventListener("abort", onAbortB);
|
|
3335
|
-
return ac.signal;
|
|
3336
|
-
}
|
|
3337
|
-
function levenshtein(a, b) {
|
|
3338
|
-
if (a === b) return 0;
|
|
3339
|
-
if (a.length === 0) return b.length;
|
|
3340
|
-
if (b.length === 0) return a.length;
|
|
3341
|
-
const prev = new Array(b.length + 1);
|
|
3342
|
-
const curr = new Array(b.length + 1);
|
|
3343
|
-
for (let j = 0; j <= b.length; j++) prev[j] = j;
|
|
3344
|
-
for (let i = 1; i <= a.length; i++) {
|
|
3345
|
-
curr[0] = i;
|
|
3346
|
-
for (let j = 1; j <= b.length; j++) {
|
|
3347
|
-
const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
|
|
3348
|
-
curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
|
|
3349
|
-
}
|
|
3350
|
-
for (let j = 0; j <= b.length; j++) prev[j] = curr[j];
|
|
3351
|
-
}
|
|
3352
|
-
return prev[b.length];
|
|
3353
|
-
}
|
|
3354
|
-
|
|
3355
|
-
export { AggregateDecodeError, Bus, BusGroup, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Music, MusicVoice, Parameter, PreloadError, Reverb, Send, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Variants, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
|
|
3356
|
-
//# sourceMappingURL=index.js.map
|
|
69
|
+
registerProcessor('${gt}', ZvukRealtimeStretchProcessor);
|
|
70
|
+
`;async function Ot(o){if(mt.has(o))return;let t=o.audioWorklet;if(!t)throw new Error("AudioWorklet not supported in this context");let e=new Blob([Mt],{type:"application/javascript"}),i=URL.createObjectURL(e);try{await t.addModule(i);}finally{URL.revokeObjectURL(i);}mt.add(o);}function _t(o,t={}){let e=globalThis.AudioWorkletNode;if(!e)throw new Error("AudioWorkletNode not available");let i=new e(o,gt,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],processorOptions:{grainSize:t.grainSize??1024}}),s=i.parameters.get("stretch");s&&t.stretchFactor!=null&&(s.value=t.stretchFactor);let r=i;return Object.defineProperty(r,"stretch",{value:s,enumerable:true}),r.dispose=()=>{try{i.disconnect();}catch{}},r}function w(o,t,e){let i=Math.max(0,t);if(i===0)return Promise.resolve();if(o.state!=="running")return Pt(i,e);let s=o.currentTime+i;return new Promise(r=>{let n=null,a=false,u=()=>{a||(a=true,n!=null&&clearTimeout(n),n=null,r());},c=()=>{if(n=null,a)return;let l=s-o.currentTime;if(l<=0){u();return}n=setTimeout(c,Math.min(l*1e3,250));};e&&e.then(u,u),n=setTimeout(c,i*1e3);})}function Pt(o,t){return new Promise(e=>{let i=setTimeout(e,o*1e3);t&&t.then(()=>{clearTimeout(i),e();},()=>{clearTimeout(i),e();});})}function S(o,t,e,i,s){let r=Math.max(0,i),n=o.value;if(kt(o,t,n),r===0){nt(o,e,()=>o.setValueAtTime(e,t));return}if(s==="linear"){nt(o,e,()=>o.linearRampToValueAtTime(e,t+r));return}let a=vt(n,e,s,64);nt(o,e,()=>o.setValueCurveAtTime(a,t,r));}function kt(o,t,e){let i=o;if(typeof i.cancelAndHoldAtTime=="function")try{i.cancelAndHoldAtTime(t);}catch{o.cancelScheduledValues(t);}else o.cancelScheduledValues(t);try{o.setValueAtTime(e,t);}catch{}}function nt(o,t,e){try{e();}catch{o.value=t;}}function P(o,t,e=33){return vt(o,t,"equal-power",e)}function vt(o,t,e,i){let s=new Float32Array(i),r=t>=o;for(let n=0;n<i;n++){let a=n/(i-1),u=Nt(a,e,r);s[n]=o+(t-o)*u;}return s}function Nt(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Z=class{source;target;post;gainNode;ctx;disposed=false;constructor(t,e,i,s){this.source=t,this.target=e,this.post=i.post??true,this.ctx=s,this.gainNode=s.createGain(),this.gainNode.gain.value=E(i.amount??1),(this.post?t.output:t.input).connect(this.gainNode),this.gainNode.connect(e.input);}get amount(){return this.gainNode.gain.value}set amount(t){this.disposed||S(this.gainNode.gain,this.ctx.currentTime,E(t),.01,"linear");}fadeTo(t,e,i="linear"){return this.disposed?Promise.resolve():(S(this.gainNode.gain,this.ctx.currentTime,E(t),e,i),w(this.ctx,e))}dispose(){if(!this.disposed){this.disposed=true;try{this.gainNode.disconnect();}catch{}}}},F=class{name;input;fxInput;output;_level;_muted;_soloed=false;_soloVeiled=false;ctx;_concurrency;_voices=new Set;_fxChain=[];_sends=[];_meterAnalyser=null;_meterBuf=null;notifySoloChange;constructor(t,e,i={}){this.ctx=t,this.name=e,this._level=i.level??1,this._muted=i.mute??false,this._concurrency=i.concurrency??null,this.input=t.createGain(),this.fxInput=t.createGain(),this.output=t.createGain(),this.input.connect(this.fxInput),this.fxInput.connect(this.output),this.output.gain.value=this._muted?0:this._level;}get level(){return this._level}set level(t){this._level=E(t),!this._muted&&!this._soloVeiled&&this.rampOutput(this._level,.01);}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this.rampOutput(t||this._soloVeiled?0:this._level,.01));}fadeTo(t,e,i="linear"){let s=E(t);return this._level=s,this._muted||this._soloVeiled?w(this.ctx,e):this.ramp(s,e,i)}get voiceCount(){return this._voices.size}voices(){return Array.from(this._voices)}get concurrency(){return this._concurrency}setConcurrency(t){this._concurrency=t;}applyConcurrencyOnSpawn(t,e){let i=this._concurrency;if(!i||this._voices.size<=i.max)return null;let s=i.steal??"oldest";if(s==="none")return e(),null;let r=Bt(this._voices,s,t);return r?(r.stop(),r):(e(),null)}trackVoice(t){this._voices.add(t);}releaseVoice(t){this._voices.delete(t);}addFx(t){this._fxChain.push(t),this.rewireFxChain();}removeFx(t){let e=this._fxChain.indexOf(t);e!==-1&&(this._fxChain.splice(e,1),this.rewireFxChain());}fx(){return [...this._fxChain]}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.output.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}send(t,e={}){let i=new Z(this,t,e,this.ctx);return this._sends.push(i),i}removeSend(t){let e=this._sends.indexOf(t);e!==-1&&(this._sends.splice(e,1),t.dispose());}sends(){return [...this._sends]}solo(t=true){this._soloed!==t&&(this._soloed=t,this.notifySoloChange?.(this,t));}unsolo(){this.solo(false);}get soloed(){return this._soloed}applySoloVeil(t){this._soloVeiled=t;let e=this._muted||t?0:this._level;this.rampOutput(e,.01);}rewireFxChain(){try{this.fxInput.disconnect();for(let e of this._fxChain)e.output.disconnect();}catch{}let t=this.fxInput;for(let e of this._fxChain)t.connect(e.input),t=e.output;t.connect(this.output);}rampOutput(t,e){this.ramp(t,e,"linear");}ramp(t,e,i){let s=this.output.gain,r=this.ctx.currentTime;return S(s,r,t,e,i),w(this.ctx,e)}dispose(){for(let t of this._sends)t.dispose();this._sends=[];for(let t of this._fxChain)t.dispose();this._fxChain=[];try{this.input.disconnect(),this.fxInput.disconnect(),this.output.disconnect(),this._meterAnalyser?.disconnect();}catch{}this._meterAnalyser=null,this._meterBuf=null;}};function E(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}function Bt(o,t,e){let i=t==="quietest"?new Map:null;if(i)for(let r of o)r!==e&&i.set(r,r.levelHint());let s=null;for(let r of o)if(r!==e){if(!s){s=r;continue}switch(t){case "oldest":r.startedAt<s.startedAt&&(s=r);break;case "lowest-priority":r.priority<s.priority&&(s=r);break;case "quietest":{let n=i?.get(r)??0,a=i?.get(s)??0;n<a&&(s=r);break}}}return s}var L=class{name;members;constructor(t,e){this.name=t,this.members=e;}set level(t){for(let e of this.members)e.level=t;}get level(){if(this.members.length===0)return 0;let t=0;for(let e of this.members)t+=e.level;return t/this.members.length}set muted(t){for(let e of this.members)e.muted=t;}get muted(){return this.members.length===0?false:this.members.every(t=>t.muted)}fadeTo(t,e,i="linear"){return Promise.all(this.members.map(s=>s.fadeTo(t,e,i))).then(()=>{})}solo(t=true){for(let e of this.members)e.solo(t);}unsolo(){this.solo(false);}};var V=class{name;_value;subs=new Set;constructor(t,e){this.name=t,this._value=e;}get value(){return this._value}set(t){if(t!==this._value){this._value=t;for(let e of this.subs)e(t);}}subscribe(t){return this.subs.add(t),t(this._value),()=>this.subs.delete(t)}bindTo(t,e={}){let i=e.from??0,s=e.to??1,r=e.curve??"linear",n=s>=i;return this.subscribe(a=>{let u=Math.max(0,Math.min(1,a)),c=Et(u,r,n);t(i+(s-i)*c);})}};function Et(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Ft={webm:'audio/webm; codecs="opus"',opus:'audio/ogg; codecs="opus"',ogg:'audio/ogg; codecs="vorbis"',m4a:'audio/mp4; codecs="mp4a.40.2"',mp4:'audio/mp4; codecs="mp4a.40.2"',aac:'audio/mp4; codecs="mp4a.40.2"',mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac"},at=null;function ut(o){if(typeof document>"u")return true;if(!at)try{at=document.createElement("audio");}catch{return true}let t=at.canPlayType(o);return t==="probably"||t==="maybe"}function ct(o){let t=/\.([a-z0-9]+)(?:[?#]|$)/i.exec(o);return t?.[1]?Ft[t[1].toLowerCase()]??null:null}function lt(o){if(o.length===0)throw new Error("pickSource requires at least one URL");for(let t of o){let e=ct(t);if(e&&ut(e))return t}return o[0]}function ht(o){if(o.length===0)return o;let t=[],e=[];for(let i of o){let s=ct(i);s&&ut(s)?t.push(i):e.push(i);}return [...t,...e]}var X=class{_ctx=null;_state="cold";_unlocking=null;_listeners=new Set;opts;constructor(t={}){this.opts=t;}get state(){return this._state}touch(){if(this._state==="closed")throw new x;if(!this._ctx){let t={};this.opts.latencyHint!=null&&(t.latencyHint=this.opts.latencyHint);let e=Lt();this._ctx=new e(t),this.attachVisibilityHandler(),this.attachStateChangeHandler(this._ctx);}return this._ctx}peek(){return this._ctx}async unlock(){if(this._state==="closed")throw new x;if(this._unlocking)return this._unlocking;if(this._state==="live"&&this._ctx?.state==="running")return;this.setState("unlocking");let t=this.touch();return this._unlocking=(async()=>{try{t.state==="suspended"&&await t.resume(),this.setState("live");}catch(e){throw this.setState("cold"),e}finally{this._unlocking=null;}})(),this._unlocking}get now(){return this._ctx?.currentTime??0}onStateChange(t){return this._listeners.add(t),()=>this._listeners.delete(t)}async close(){this._state!=="closed"&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility),this._ctx&&(this._ctx.removeEventListener("statechange",this.handleCtxStateChange),this._ctx.state!=="closed"&&await this._ctx.close().catch(()=>{})),this._ctx=null,this.setState("closed"),this._listeners.clear());}setState(t){if(this._state!==t){this._state=t;for(let e of this._listeners)e(t);}}attachVisibilityHandler(){this.opts.autoPauseOnHidden!==false&&(typeof document>"u"||document.addEventListener("visibilitychange",this.handleVisibility));}handleVisibility=()=>{if(!this._ctx||this._state==="closed")return;document.visibilityState==="visible"?setTimeout(()=>{document.visibilityState==="visible"&&this._ctx?.state==="suspended"&&this._ctx.resume().catch(()=>{});},200):this._ctx.suspend().catch(()=>{});};attachStateChangeHandler(t){t.addEventListener("statechange",this.handleCtxStateChange);}handleCtxStateChange=()=>{let t=this._ctx;if(!t||this._state==="closed")return;let e=t.state;if(e==="interrupted"){this.setState("interrupted");return}if(e==="suspended"){if(this._state==="interrupted"){setTimeout(()=>{this._ctx===t&&t.state==="suspended"&&t.resume().catch(()=>{});},200);return}(this._state==="live"||this._state==="unlocking")&&this.setState("suspended");return}e==="running"&&this._state!=="live"&&this.setState("live");}};function Lt(){let o=globalThis,t=o.AudioContext??o.webkitAudioContext;if(!t)throw new Error("No AudioContext constructor available in this environment.");return t}var Vt=64*1024*1024,Dt=128;function It(o){return o.length*o.numberOfChannels*4}var Y=class{constructor(t,e={}){this.getCtx=t;let i=typeof e=="number"?{maxEntries:e}:e;this.maxBytes=Math.max(1,i.maxBytes??Vt),this.maxEntries=Math.max(1,i.maxEntries??Dt);}getCtx;cache=new Map;bytes=0;inflight=new Map;maxBytes;maxEntries;has(t){return this.cache.has(t)}get cachedBytes(){return this.bytes}async load(t,e={}){let i=this.cache.get(t);if(i)return this.touch(t,i.buffer),i.buffer;let s=this.inflight.get(t);if(s)return this.join(s,e.signal);let r=new AbortController,n;return n={promise:this.fetchAndDecode(t,r.signal,e.onProgress).finally(()=>{this.inflight.get(t)===n&&this.inflight.delete(t);}),controller:r,waiters:0},this.inflight.set(t,n),this.join(n,e.signal)}join(t,e){t.waiters++;let i=()=>{t.waiters--,t.waiters<=0&&t.controller.abort();};return e?e.aborted?(i(),Promise.reject(bt(e))):new Promise((s,r)=>{let n=false,a=()=>{n||(n=true,i(),r(bt(e)));};e.addEventListener("abort",a,{once:true}),t.promise.then(u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),s(u));},u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),r(u));});}):t.promise.finally(()=>t.waiters--)}async fetchAndDecode(t,e,i){let s;try{s=await fetch(t,{signal:e});}catch(u){throw u.name==="AbortError"?u:new M(t,u)}if(!s.ok)throw new M(t,new Error(`${s.status} ${s.statusText}`));let r=i?await Rt(s,i):await s.arrayBuffer(),n=this.getCtx(),a;try{a=await n.decodeAudioData(r);}catch(u){throw new M(t,u)}return this.touch(t,a),a}async loadFirst(t,e={}){if(t.length===0)throw new Error("loadFirst requires at least one URL");for(let s of t){let r=this.cache.get(s);if(r)return this.touch(s,r.buffer),r.buffer}let i=[];for(let s of t)try{return await this.load(s,e)}catch(r){if(r.name==="AbortError")throw r;i.push({url:s,cause:r});}if(t.length===1){let s=i[0]?.cause;throw s instanceof Error?s:new M(t[0],s)}throw new B(t,i)}evict(t){let e=this.cache.get(t);e&&(this.bytes-=e.bytes,this.cache.delete(t));}clear(){this.cache.clear(),this.bytes=0;}touch(t,e){this.evict(t);let i=It(e);for(this.cache.set(t,{buffer:e,bytes:i}),this.bytes+=i;this.cache.size>this.maxEntries||this.bytes>this.maxBytes&&this.cache.size>1;){let s=this.cache.keys().next().value;if(s===void 0)break;this.evict(s);}}};function bt(o){return o.reason??new DOMException("load aborted","AbortError")}async function Rt(o,t){let e=o.body;if(!e||typeof e.getReader!="function"){let d=await o.arrayBuffer();return t(d.byteLength,d.byteLength),d}let i=o.headers.get("content-length"),s=i?Number.parseInt(i,10):Number.NaN,r=Number.isFinite(s)?s:null,n=e.getReader(),a=[],u=0;for(;;){let{done:d,value:m}=await n.read();if(d)break;m&&(a.push(m),u+=m.byteLength,t(u,r));}let c=new Uint8Array(u),l=0;for(let d of a)c.set(d,l),l+=d.byteLength;return c.buffer}var Gt={targetRms:.1,peakCeiling:.99};function k(o,t,e){if(!t)return o;let i={...Gt,...typeof t=="object"?t:{}},s=yt(o,i);return Math.abs(s-1)<.001?o:qt(o,s,e)}function yt(o,t){let e=zt(o);if(e<=1e-6)return 1;let i=t.targetRms/e,s=Ut(o)*i;return s>t.peakCeiling&&(i*=t.peakCeiling/s),i}function zt(o){let t=0,e=0;for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)t+=s[r]*s[r];e+=s.length;}return e===0?0:Math.sqrt(t/e)}function Ut(o){let t=0;for(let e=0;e<o.numberOfChannels;e++){let i=o.getChannelData(e);for(let s=0;s<i.length;s++){let r=Math.abs(i[s]);r>t&&(t=r);}}return t}function qt(o,t,e){if(e){let i=e.createBuffer(o.numberOfChannels,o.length,o.sampleRate);for(let s=0;s<o.numberOfChannels;s++){let r=o.getChannelData(s),n=i.getChannelData(s);for(let a=0;a<r.length;a++)n[a]=r[a]*t;}return i}for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)s[r]=s[r]*t;}return o}var K=class{constructor(t,e){this.host=t;this.tickSource=e;}host;tickSource;tasks=[];cancelled=0;timer=null;unsubscribe=null;scheduleAt(t,e){let i={audioTime:t,fn:e,cancelled:false};return this.tasks.splice(this.insertionIndex(t),0,i),this.arm(),()=>{i.cancelled||(i.cancelled=true,this.cancelled++,this.cancelled>32&&this.cancelled*2>this.tasks.length&&this.compact());}}insertionIndex(t){let e=0,i=this.tasks.length;for(;e<i;){let s=e+i>>>1;this.tasks[s].audioTime<=t?e=s+1:i=s;}return e}compact(){this.tasks=this.tasks.filter(t=>!t.cancelled),this.cancelled=0;}arm(){if(this.tickSource){this.unsubscribe||(this.unsubscribe=this.tickSource.subscribe(()=>this.tick()));return}this.rearmTimer();}rearmTimer(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null);let t=this.tasks.find(s=>!s.cancelled);if(!t)return;let e=this.host.now,i=Math.max(0,(t.audioTime-e)*1e3);this.timer=setTimeout(()=>this.tick(),i);}tick(){this.timer!=null&&(this.timer=null);let t=this.host.now,e=[],i=[];for(let s of this.tasks)s.cancelled||(s.audioTime<=t?e.push(s):i.push(s));this.tasks=i,this.cancelled=0;for(let s of e)try{s.fn();}catch(r){console.error("[zvuk] scheduled task threw",r);}if(this.tasks.length===0){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);return}this.tickSource||this.rearmTimer();}dispose(){this.timer!=null&&clearTimeout(this.timer),this.timer=null,this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.tasks=[],this.cancelled=0;}};var Ht=.008,$t=.05,D=class{name;deps;live=new Set;constructor(t,e){this.name=t,this.deps=e;}get loopDuration(){return this.deps.buffers.loop.duration}get hasIntro(){return this.deps.buffers.intro!=null}get hasOutro(){return this.deps.buffers.outro!=null}play(t={}){let e=new Q({ctx:this.deps.ctx,buffers:this.deps.buffers,destination:this.deps.destination,loopCrossfade:this.deps.loopCrossfade,defaultStopFade:this.deps.defaultStopFade,options:t});return this.live.add(e),e.ended.then(()=>this.live.delete(e)),e}voices(){return Array.from(this.live)}stopAll(t={}){for(let e of Array.from(this.live))e.stop(t);this.live.clear();}},Q=class{ended;ctx;buffers;destination;gain;state="intro";done=false;resolveEnded;stopFade;loopCrossfadeSec;introSource=null;outroSource=null;loopChain=[];loopArmTimer=null;outroTimer=null;nextLoopBoundaryAt=Number.POSITIVE_INFINITY;constructor(t){this.ctx=t.ctx,this.buffers=t.buffers,this.destination=t.destination,this.loopCrossfadeSec=Math.max(0,t.loopCrossfade),this.stopFade=Math.max(0,t.defaultStopFade??Ht),this.gain=this.ctx.createGain();let e=St(t.options.volume??1),i=Math.max(0,t.options.fadeIn??0);i>0?(this.gain.gain.setValueAtTime(0,this.ctx.currentTime),this.gain.gain.linearRampToValueAtTime(e,this.ctx.currentTime+i)):this.gain.gain.value=e,this.gain.connect(this.destination),this.ended=new Promise(s=>{this.resolveEnded=s;}),this.start(this.ctx.currentTime);}get currentPart(){return this.state}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,St(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done)return;let e=Math.max(0,t.fade??this.stopFade);if(this.cancelTimers(),e===0){this.stopAllSources(0),this.finish();return}let i=this.ctx.currentTime,s=i+e;try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish();return}setTimeout(()=>this.finish(),e*1e3);}skipToOutro(t={}){if(this.done||this.state==="outro"||this.state==="ended")return;if(!this.buffers.outro){this.stop();return}(t.at??"loop-end")==="now"?this.skipToOutroNow():this.skipToOutroAtLoopEnd();}start(t){this.buffers.intro?(this.scheduleIntro(t),this.scheduleLoopStart(t+this.buffers.intro.duration)):(this.state="loop",this.scheduleLoopStart(t));}scheduleIntro(t){let e=this.ctx.createBufferSource();e.buffer=this.buffers.intro,e.connect(this.gain),e.start(t),e.onended=()=>{this.introSource===e&&(this.introSource=null);},this.introSource=e;}scheduleLoopStart(t){if(this.done)return;let e=this.spawnLoopSegment(t,false);if(this.nextLoopBoundaryAt=t+this.buffers.loop.duration,this.loopCrossfadeSec>0&&this.crossfadeViable())this.armNextLoopSegment(t);else {e.source.loop=true;let i=this.buffers.loop;if(e.source.loopStart=0,e.source.loopEnd=i.duration,!this.buffers.intro)this.state="loop";else {let s=Math.max(0,(t-this.ctx.currentTime)*1e3);setTimeout(()=>{!this.done&&this.state==="intro"&&(this.state="loop");},s);}}}spawnLoopSegment(t,e){let i=this.ctx.createBufferSource();i.buffer=this.buffers.loop,i.loop=false;let s=this.ctx.createGain();if(e?(s.gain.setValueAtTime(0,t),s.gain.setValueCurveAtTime(P(0,1),t,this.loopCrossfadeSec)):s.gain.setValueAtTime(1,t),this.crossfadeViable()){let n=t+this.buffers.loop.duration-this.loopCrossfadeSec;s.gain.setValueAtTime(1,n),s.gain.setValueCurveAtTime(P(1,0),n,this.loopCrossfadeSec);}i.connect(s).connect(this.gain);try{this.crossfadeViable()?i.start(t,0,this.buffers.loop.duration):i.start(t);}catch{}i.onended=()=>this.releaseLoopSegment(i,s);let r={source:i,gain:s,startTime:t};return this.loopChain.push(r),r}armNextLoopSegment(t){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let e=t+this.buffers.loop.duration-this.loopCrossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.loopArmTimer=setTimeout(()=>{this.loopArmTimer=null,!(this.done||this.state!=="loop"&&this.state!=="intro")&&(this.state="loop",this.spawnLoopSegment(e,true),this.nextLoopBoundaryAt=e+this.buffers.loop.duration,this.armNextLoopSegment(e));},s);}crossfadeViable(){return this.loopCrossfadeSec>0&&this.buffers.loop.duration>this.loopCrossfadeSec*2}releaseLoopSegment(t,e){let i=this.loopChain.findIndex(s=>s.source===t);i>=0&&this.loopChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}skipToOutroAtLoopEnd(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let t;this.state==="intro"?(t=this.ctx.currentTime+(this.buffers.intro?.duration??0),this.cancelLoopArm()):t=this.nextLoopBoundaryAt,this.stopLoopSourcesAt(t),this.scheduleOutro(t);}skipToOutroNow(){this.cancelLoopArm();let t=this.ctx.currentTime,e=t+$t;for(let i of this.loopChain){try{let s=i.gain.gain;s.cancelScheduledValues(t),s.setValueAtTime(s.value,t),s.linearRampToValueAtTime(0,e);}catch{}try{i.source.stop(e);}catch{}}if(this.introSource)try{this.introSource.stop(e);}catch{}this.scheduleOutro(e);}cancelLoopArm(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);}stopLoopSourcesAt(t){for(let e of this.loopChain)try{e.source.stop(t);}catch{}}scheduleOutro(t){let e=this.buffers.outro;if(!e){let r=Math.max(0,(t-this.ctx.currentTime)*1e3);this.outroTimer=setTimeout(()=>this.finish(),r);return}let i=this.ctx.createBufferSource();i.buffer=e,i.connect(this.gain);try{i.start(t);}catch{}i.onended=()=>{this.outroSource===i&&(this.outroSource=null),this.finish();},this.outroSource=i;let s=Math.max(0,(t-this.ctx.currentTime)*1e3);this.outroTimer=setTimeout(()=>{this.outroTimer=null,this.done||(this.state="outro");},s);}cancelTimers(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null),this.outroTimer!=null&&(clearTimeout(this.outroTimer),this.outroTimer=null);}stopAllSources(t){let e=[];this.introSource&&e.push(this.introSource);for(let i of this.loopChain)e.push(i.source);this.outroSource&&e.push(this.outroSource);for(let i of e)try{i.onended=null,t===0?i.stop():i.stop(t);}catch{}}finish(){if(!this.done){this.done=true,this.state="ended",this.cancelTimers();try{this.introSource&&this.introSource.disconnect();for(let t of this.loopChain)t.source.disconnect(),t.gain.disconnect();this.outroSource&&this.outroSource.disconnect(),this.gain.disconnect();}catch{}this.introSource=null,this.outroSource=null,this.loopChain=[],this.resolveEnded();}}};function St(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var Wt=.008,I=class o{id;priority;bus;startedAt;sourceName;ended;ctx;gain;source;buffer;loop;basePitch;done=false;stopping=false;paused=false;resolveEnded;cueListeners=new Set;startCtxTime;pausedOffset=0;currentOffset=0;_spatializer;startOffset;regionDuration;loopStart;loopEnd;regionTimer=null;stopFade;crossfadeSec=0;crossfadeRegionStart=0;crossfadeRegionLen=0;crossfadeChain=[];crossfadeArmTimer=null;levelAnalyser=null;levelBuf=null;static nextId=1;constructor(t){let{ctx:e,buffer:i,destination:s,options:r}=t;this.id=o.nextId++,this.ctx=e,this.priority=r.priority??0,this.bus=r.bus,this.sourceName=t.sourceName,this.startedAt=e.currentTime,this.buffer=i,this.loop=r.loop??false,this.basePitch=xt(r.pitch??1,1),this._spatializer=t.spatializer,this.startOffset=r.offset??0,this.currentOffset=this.startOffset,this.regionDuration=r.duration,this.loopStart=r.loopStart,this.loopEnd=r.loopEnd,this.stopFade=Math.max(0,t.defaultStopFade??Wt),this.gain=e.createGain();let n=At(xt(r.volume??1)),a=Math.max(0,r.fadeIn??0);if(a>0?(this.gain.gain.setValueAtTime(0,e.currentTime),this.gain.gain.linearRampToValueAtTime(n,e.currentTime+a)):this.gain.gain.value=n,this.gain.connect(s),this.startCtxTime=e.currentTime,this.ended=new Promise(u=>{this.resolveEnded=u;}),r.signal&&(r.signal.aborted?queueMicrotask(()=>this.stop()):r.signal.addEventListener("abort",()=>this.stop(),{once:true})),this.shouldUseLoopCrossfade(r)){this.crossfadeSec=r.loopCrossfade,this.crossfadeRegionStart=r.loopStart??this.startOffset;let u=r.loopEnd??i.duration;this.crossfadeRegionLen=Math.max(0,u-this.crossfadeRegionStart),this.source=this.startCrossfadeChain(e.currentTime);}else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.startOffset);}catch{}this.armRegionTimer(this.regionDuration);}queueMicrotask(()=>this.emit("started")),this.ended.then(()=>t.onEnded(this));}shouldUseLoopCrossfade(t){if(!this.loop)return false;let e=t.loopCrossfade;if(e==null||e<=0)return false;let i=t.loopStart??this.startOffset;return (t.loopEnd??this.buffer.duration)-i>e*2}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,At(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done||this.stopping)return;let e=Math.max(0,t.fade??this.stopFade);if(this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null),e===0){this.stopAllSources(0),this.finish("ended");return}this.stopping=true;let i=this.ctx.currentTime,s=i+e;for(let r of this.activeSources())r.onended=null;this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null);try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish("ended");return}setTimeout(()=>this.finish("ended"),e*1e3);}activeSources(){return this.inCrossfadeMode?this.crossfadeChain.map(t=>t.source):[this.source]}stopAllSources(t){for(let e of this.activeSources())try{t===0?e.stop():e.stop(t);}catch{}}pause(){if(this.done||this.paused)return;let t=this.computeOffset();this.pausedOffset=t,this.currentOffset=t,this.paused=true,this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);for(let e of this.activeSources()){try{e.onended=null,e.stop();}catch{}try{e.disconnect();}catch{}}this.inCrossfadeMode&&(this.crossfadeChain=[]),this.emit("paused");}resume(){if(!(this.done||!this.paused)){if(this.paused=false,this.startCtxTime=this.ctx.currentTime,this.inCrossfadeMode)this.source=this.startCrossfadeChain(this.startCtxTime);else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.pausedOffset);}catch{}if(this.regionDuration!=null){let t=Math.max(0,this.pausedOffset-this.startOffset),e=Math.max(0,this.regionDuration-t);this.armRegionTimer(e);}}this.emit("resumed");}}get isPaused(){return this.paused}setPlaybackRate(t,e={}){if(this.done)return;let i=Math.max(0,t),s=Math.max(0,e.duration??0);if(this.paused||(this.currentOffset=this.computeOffset(),this.startCtxTime=this.ctx.currentTime),this.basePitch=i,!this.paused){if(this.regionTimer!=null&&this.regionDuration!=null){let r=Math.max(0,this.currentOffset-this.startOffset);this.armRegionTimer(Math.max(0,this.regionDuration-r));}for(let r of this.activeSources()){let n=r.playbackRate;s===0?n.value=i:S(n,this.ctx.currentTime,i,s,e.curve??"linear");}}}get playbackRate(){return this.basePitch}get spatializer(){return this._spatializer}level(){if(this.done)return {rms:0,peak:0};if(!this.levelAnalyser){let s=this.ctx.createAnalyser();s.fftSize=512,this.gain.connect(s),this.levelAnalyser=s,this.levelBuf=new Float32Array(s.fftSize);}let t=this.levelBuf;this.levelAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}levelHint(){return this.done?0:this.levelAnalyser?this.level().rms:this.gain.gain.value}async*cues(){if(this.done){yield "ended";return}let t=[],e=null,i=r=>{if(e){let n=e;e=null,n({value:r,done:false});}else t.push(r);},s=r=>i(r);this.cueListeners.add(s);try{for(;;){if(t.length>0){let n=t.shift();if(yield n,n==="ended")return;continue}if(this.done){yield "ended";return}let r=await new Promise(n=>{e=n;});if(r.done||(yield r.value,r.value==="ended"))return}}finally{this.cueListeners.delete(s);}}finish(t,e){if(!this.done){this.done=true,this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);try{for(let i of this.activeSources())i.disconnect();for(let i of this.crossfadeChain)i.gain.disconnect();this.levelAnalyser?.disconnect(),this.gain.disconnect();}catch{}this.levelAnalyser=null,this.levelBuf=null,this.crossfadeChain=[],this.emit(t),this.resolveEnded(),e?.(this);}}emit(t){for(let e of this.cueListeners)e(t);}createSourceNode(t){let e=this.ctx.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,this.loop&&this.loopStart!=null&&(e.loopStart=this.loopStart),this.loop&&this.loopEnd!=null&&(e.loopEnd=this.loopEnd),e.playbackRate.value=t,e.connect(this.gain),e}armRegionTimer(t){if(this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),t==null||this.loop)return;let e=Math.max(0,t*1e3)/Math.max(1e-4,this.basePitch);this.regionTimer=setTimeout(()=>{this.regionTimer=null,this.done||this.stop();},e);}bindSourceLifecycle(t,e){t.onended=()=>{this.paused||t.loop||this.finish("ended",e);};}startCrossfadeChain(t){let e=this.spawnCrossfadeSegment(t,false);return this.armNextCrossfadeSegment(t),e.source}spawnCrossfadeSegment(t,e){let i=this.ctx.createBufferSource();i.buffer=this.buffer,i.loop=false,i.playbackRate.value=this.basePitch;let s=this.ctx.createGain();e?(s.gain.setValueAtTime(0,t),s.gain.setValueCurveAtTime(P(0,1),t,this.crossfadeSec)):s.gain.setValueAtTime(1,t);let r=t+this.crossfadeRegionLen-this.crossfadeSec;s.gain.setValueAtTime(1,r),s.gain.setValueCurveAtTime(P(1,0),r,this.crossfadeSec),i.connect(s).connect(this.gain);try{i.start(t,this.crossfadeRegionStart,this.crossfadeRegionLen);}catch{}i.onended=()=>this.releaseCrossfadeSegment(i,s);let n={source:i,gain:s,startTime:t};return this.crossfadeChain.push(n),n}armNextCrossfadeSegment(t){this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);let e=t+this.crossfadeRegionLen-this.crossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.crossfadeArmTimer=setTimeout(()=>{this.crossfadeArmTimer=null,!(this.done||this.stopping||this.paused)&&(this.spawnCrossfadeSegment(e,true),this.armNextCrossfadeSegment(e));},s);}releaseCrossfadeSegment(t,e){let i=this.crossfadeChain.findIndex(s=>s.source===t);i>=0&&this.crossfadeChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}get inCrossfadeMode(){return this.crossfadeSec>0}computeOffset(){if(this.paused)return this.pausedOffset;let t=(this.ctx.currentTime-this.startCtxTime)*this.basePitch,e=this.currentOffset+t;return this.loop?e=(e%this.buffer.duration+this.buffer.duration)%this.buffer.duration:e=Math.min(e,this.buffer.duration),e}};function xt(o,t=1){if(typeof o=="number")return o;if(!o)return t;let e=o.base??t;return o.jitter==null?e:e+(Math.random()*2-1)*o.jitter}function At(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var R=class{name;deps;constructor(t,e){this.name=t,this.deps=e;}get duration(){return this.deps.buffer.duration}play(t={}){let e=t.bus??this.deps.defaultBus,i=this.deps.resolveBusInput(e),s=this.deps.resolveSpatializer?.(e,t.spatializer),r=s?s.connectInto(i):i,n=new I({ctx:this.deps.ctx,buffer:this.deps.buffer,destination:r,options:{...t,bus:e},spatializer:s,sourceName:this.deps.sourceName??this.name,defaultStopFade:this.deps.defaultStopFade,onEnded:u=>{this.deps.releaseVoice(u,e),s?.dispose();}});return this.deps.trackVoice(n,e),(this.deps.applyConcurrency?.(n,e)??true)||n.stop(),n}};var G=class{name;regions;sound;constructor(t,e,i){this.name=t,this.sound=e,this.regions={...i};}list(){return Object.keys(this.regions)}has(t){return t in this.regions}region(t){let e=this.regions[t];if(!e)throw new A(`${this.name}#${t}`);return e}play(t,e={}){let i=this.region(t),s=e.loop??i.loop??false;return this.sound.play({...e,loop:s,offset:i.start,duration:i.duration,loopStart:i.start,loopEnd:i.start+i.duration})}};var z=class{name;ctx;url;destination;el=null;node=null;gain=null;disposed=false;constructor(t,e,i,s){this.name=t,this.ctx=e,this.url=i,this.destination=s;}ensure(){if(this.el||this.disposed||typeof document>"u"||typeof Audio>"u")return;let t=new Audio;t.src=this.url,t.crossOrigin="anonymous",t.preload="auto";let e=this.ctx.createMediaElementSource;if(typeof e!="function"){this.el=t;return}let i=e.call(this.ctx,t),s=this.ctx.createGain();i.connect(s),s.connect(this.destination),this.el=t,this.node=i,this.gain=s;}async play(t={}){if(this.ensure(),!!this.el){this.gain&&(this.gain.gain.value=dt(t.volume??1)),this.el.loop=t.loop??false;try{await this.el.play();}catch{}}}pause(){this.el?.pause();}stop(){if(this.el){this.el.pause();try{this.el.currentTime=0;}catch{}}}seek(t){if(this.el)try{this.el.currentTime=Math.max(0,t);}catch{}}get currentTime(){return this.el?.currentTime??0}get duration(){return this.el?.duration??0}get paused(){return this.el?.paused??true}setVolume(t){this.gain&&(this.gain.gain.value=dt(t));}fade(t){return this.gain?(S(this.gain.gain,this.ctx.currentTime,dt(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration)):Promise.resolve()}dispose(){this.disposed=true;try{this.node?.disconnect(),this.gain?.disconnect();}catch{}this.el&&(this.el.pause(),this.el.src=""),this.el=null,this.node=null,this.gain=null;}};function dt(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var U=class{name;count;sounds;strategy;lastIndex=-1;bag=[];constructor(t,e,i={}){if(e.length===0)throw new Error(`Variants "${t}" requires at least one sound`);this.name=t,this.sounds=e,this.count=e.length,this.strategy=i.strategy??"no-repeat";}get lastPick(){return this.lastIndex}play(t={}){return this.sounds[this.pick()].play(t)}playIndex(t,e={}){let i=(t%this.count+this.count)%this.count;return this.lastIndex=i,this.sounds[i].play(e)}pick(){let t=this.count;if(t===1)return 0;if(this.strategy==="random"){let i=Math.floor(Math.random()*t);return this.lastIndex=i,i}if(this.strategy==="shuffle-bag"){if(this.bag.length===0){this.bag=Array.from({length:t},(s,r)=>r);for(let s=t-1;s>0;s--){let r=Math.floor(Math.random()*(s+1));[this.bag[s],this.bag[r]]=[this.bag[r],this.bag[s]];}t>1&&this.bag[0]===this.lastIndex&&([this.bag[0],this.bag[1]]=[this.bag[1],this.bag[0]]);}let i=this.bag.shift();return this.lastIndex=i,i}let e=Math.floor(Math.random()*(t-1));return e>=this.lastIndex&&e++,this.lastIndex=e,e}};var jt="inverse";var q=class{ctx;kind;input;output;stereoPan=null;panner=null;occlusionFilter=null;occlusionGain=null;constructor(t,e){if(this.ctx=t,e.position){let i=t.createPanner();i.panningModel="HRTF",i.distanceModel=e.distanceModel??jt,i.refDistance=e.refDistance??1,i.maxDistance=e.maxDistance??1e4,i.rolloffFactor=e.rolloffFactor??1;let[s,r,n]=e.position;this.setPanner3D(i,s,r,n);let a=t.createBiquadFilter();a.type="lowpass",a.frequency.value=22050,a.Q.value=Math.SQRT1_2;let u=t.createGain();u.gain.value=1,i.connect(a).connect(u),this.panner=i,this.occlusionFilter=a,this.occlusionGain=u,this.input=i,this.output=u,this.kind="3d",e.occlusion!=null&&this.setOcclusion(e.occlusion);}else {let i=t.createStereoPanner();i.pan.value=Ct(e.pan??0),this.stereoPan=i,this.input=i,this.output=i,this.kind="2d";}}setPan(t){this.kind!=="2d"||!this.stereoPan||(this.stereoPan.pan.value=Ct(t));}setPosition(t,e,i){this.kind!=="3d"||!this.panner||this.setPanner3D(this.panner,t,e,i);}setRefDistance(t){this.panner&&(this.panner.refDistance=Math.max(0,t));}setMaxDistance(t){this.panner&&(this.panner.maxDistance=Math.max(0,t));}setRolloffFactor(t){this.panner&&(this.panner.rolloffFactor=Math.max(0,t));}setDistanceModel(t){this.panner&&(this.panner.distanceModel=t);}setOcclusion(t){if(!this.occlusionFilter||!this.occlusionGain)return;let e=Zt(t),i=22050*(500/22050)**e,s=this.ctx.currentTime;this.occlusionFilter.frequency.setValueAtTime(i,s);let r=10**(-6*e/20);this.occlusionGain.gain.setValueAtTime(r,s);}connectInto(t){return this.output.connect(t),this.input}dispose(){try{this.input.disconnect(),this.occlusionFilter?.disconnect(),this.occlusionGain?.disconnect();}catch{}}setPanner3D(t,e,i,s){if(typeof t.positionX?.setValueAtTime=="function"){let r=this.ctx.currentTime;t.positionX.setValueAtTime(e,r),t.positionY.setValueAtTime(i,r),t.positionZ.setValueAtTime(s,r);}else t.setPosition?.(e,i,s);}};function Ct(o){return Math.max(-1,Math.min(1,o))}function Zt(o){return Number.isNaN(o)?0:Math.max(0,Math.min(1,o))}var H=class{input;headroomDb;ctx;limiterNode=null;limiterCfg;destination;_meterAnalyser=null;_meterBuf=null;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.headroomDb=e.headroom??0,this.input.gain.value=Tt(this.headroomDb),this.destination=t.destination,this.limiterCfg=e.limiter??null,this.rewire();}setHeadroom(t){this.headroomDb=t,S(this.input.gain,this.ctx.currentTime,Tt(t),.01,"linear");}get headroom(){return this.headroomDb}setLimiter(t){this.limiterCfg=t,this.rewire();}get reduction(){return this.limiterNode?.reduction??0}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.input.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}dispose(){try{this.input.disconnect(),this.limiterNode?.disconnect(),this._meterAnalyser?.disconnect();}catch{}this.limiterNode=null,this._meterAnalyser=null,this._meterBuf=null;}rewire(){try{this.input.disconnect(),this.limiterNode?.disconnect();}catch{}if(this.limiterNode=null,this.limiterCfg){let t=this.limiterCfg,e=this.ctx.createDynamicsCompressor();e.threshold.value=t.threshold??-1,e.knee.value=0,e.ratio.value=Math.max(20,t.ratio??20),e.attack.value=t.attack??.001,e.release.value=t.release??.05,this.input.connect(e),e.connect(this.destination),this.limiterNode=e;}else this.input.connect(this.destination);this._meterAnalyser&&this.input.connect(this._meterAnalyser);}};function Tt(o){return 10**(o/20)}var $=class{name;state;getBus;getParam;constructor(t,e,i,s){this.name=t,this.state=e,this.getBus=i,this.getParam=s;}apply(t={}){let e=t.fade??0,i=[];for(let[s,r]of Object.entries(this.state.buses)){let n=this.getBus(s);n&&(n.muted=r.muted,i.push(n.fadeTo(r.level,e)));}for(let[s,r]of Object.entries(this.state.parameters)){let n=this.getParam(s);n&&n.set(r);}return Promise.all(i).then(()=>{})}blendWith(t,e){let i=e<0?0:e>1?1:e,s=1-i;for(let[r,n]of Object.entries(this.state.buses)){let a=t.state.buses[r];if(!a)continue;let u=this.getBus(r);u&&(u.muted=i<.5?n.muted:a.muted,u.level=n.level*s+a.level*i);}for(let[r,n]of Object.entries(this.state.parameters)){let a=t.state.parameters[r];if(a===void 0)continue;let u=this.getParam(r);u&&u.set(n*s+a*i);}}};function Xt(o={}){return new pt(o)}var pt=class{host;decoder;scheduler=null;master=null;buses=new Map;busOrder=[];sounds=new Map;internalSounds=new Map;sprites=new Map;streams=new Map;musics=new Map;variantsByName=new Map;busGroups=new Map;soloedBuses=new Set;soundUrls=new Map;voices=new Map;parameters=new Map;config;constructor(t){this.config=t,this.host=new X({autoPauseOnHidden:t.autoPauseOnHidden,latencyHint:t.latencyHint}),this.decoder=new Y(()=>this.host.touch(),t.cache??{});let e=Object.keys(t.buses??{});this.busOrder=e.length>0?e:["default"];for(let i of this.busOrder)this.voices.set(i,new Set);}get state(){return this.host.state}get now(){return this.host.now}get context(){return this.host.touch()}async unlock(){await this.host.unlock(),this.ensureGraph();}async close(){if(this.host.state!=="closed"){for(let t of this.voices.values()){for(let e of t)e.stop();t.clear();}this.scheduler?.dispose(),this.scheduler=null;for(let t of this.buses.values()){for(let e of t.fx())e.dispose();t.dispose();}this.buses.clear(),this.master?.dispose(),this.master=null,this.sounds.clear(),this.internalSounds.clear(),this.sprites.clear();for(let t of this.musics.values())t.stopAll({fade:0});this.musics.clear(),this.variantsByName.clear(),this.busGroups.clear(),this.soloedBuses.clear(),this.soundUrls.clear();for(let t of this.streams.values())t.dispose();this.streams.clear(),this.parameters.clear(),this.decoder.clear(),await this.host.close();}}async loadSound(t,e,i={}){return this.loadSoundAs(t,t,e,i,false)}async loadSoundAs(t,e,i,s,r){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let n={signal:s.signal},a=await this.resolveBuffer(t,i,n);return s.normalize&&(a=k(a,s.normalize,this.host.touch())),this.soundUrls.set(t,typeof i=="string"?[i]:[...i]),this.registerSound(t,e,a,{bus:s.bus},r)}async resolveBuffer(t,e,i){let s=this.config.resolveAsset;if(s){let n=await s({name:t,url:e,signal:i.signal});if(n!=null){if(n instanceof AudioBuffer)return n;if(n instanceof ArrayBuffer)return await this.host.touch().decodeAudioData(n.slice(0));if(typeof n=="string")return await this.decoder.load(n,i)}}let r=typeof e=="string"?[e]:ht(e);return await this.decoder.loadFirst(r,i)}async preload(t,e={}){if(this.host.state==="closed")throw new x;if(t.length===0)return;let i=Math.max(1,e.concurrency??wt),s=e.onProgress,r=e.signal,n=t.length,a=0,u=[],c=0,l=Math.min(i,n),d=[];for(let p=0;p<l;p++)d.push((async()=>{for(;;){let b=c++;if(b>=n)return;if(r?.aborted)throw r.reason??new DOMException("preload aborted","AbortError");let h=t[b],v=Kt(r,h.options?.signal),f={...h.options??{},signal:v};try{await this.loadSound(h.name,h.url,f),a++,s?.({name:h.name,status:"loaded",completed:a,total:n});}catch(y){if(y.name==="AbortError")throw y;a++,u.push({name:h.name,cause:y}),s?.({name:h.name,status:"failed",error:y,completed:a,total:n});}}})());let g=(await Promise.allSettled(d)).find(p=>p.status==="rejected");if(g&&g.status==="rejected")throw g.reason;if(u.length>0)throw new N(u)}async loadSprite(t,e,i,s={}){let r=await this.loadSoundAs(`__sprite:${t}`,t,e,s,true),n=new G(t,r,i);return this.sprites.set(t,n),n}sprite(t){let e=this.sprites.get(t);if(!e)throw new A(t,C(t,[...this.sprites.keys()]));return e}hasSprite(t){return this.sprites.has(t)}async loadVariants(t,e,i={}){if(e.length===0)throw new Error(`engine.loadVariants("${t}") requires at least one URL set`);let{strategy:s,...r}=i,n=await Yt(e,wt,(u,c)=>this.loadSoundAs(`__variant:${t}:${c}`,t,u,r,true)),a=new U(t,n,{strategy:s});return this.variantsByName.set(t,a),a}variants(t){let e=this.variantsByName.get(t);if(!e)throw new A(t,C(t,[...this.variantsByName.keys()]));return e}hasVariants(t){return this.variantsByName.has(t)}async loadMusic(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s={signal:i.signal},[r,n,a]=await Promise.all([this.resolveBuffer(`__music:${t}:loop`,e.loop,s),e.intro?this.resolveBuffer(`__music:${t}:intro`,e.intro,s):Promise.resolve(void 0),e.outro?this.resolveBuffer(`__music:${t}:outro`,e.outro,s):Promise.resolve(void 0)]),u=this.host.touch(),c={intro:n?i.normalize?k(n,i.normalize,u):n:void 0,loop:i.normalize?k(r,i.normalize,u):r,outro:a?i.normalize?k(a,i.normalize,u):a:void 0},l=i.bus??this.busOrder[0],d=this.buses.get(l);if(!d)throw new T(l,C(l,[...this.buses.keys()]));let m=new D(t,{ctx:this.host.touch(),buffers:c,destination:d.input,loopCrossfade:i.loopCrossfade??0,defaultStopFade:this.config.voice?.stopFade});return this.musics.set(t,m),m}music(t){let e=this.musics.get(t);if(!e)throw new A(t,C(t,[...this.musics.keys()]));return e}hasMusic(t){return this.musics.has(t)}loadStream(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s=typeof e=="string"?e:lt(e),r=i.bus??this.busOrder[0],n=this.buses.get(r);if(!n)throw new T(r,C(r,[...this.buses.keys()]));let a=new z(t,this.host.touch(),s,n.input);return this.streams.set(t,a),a}stream(t){let e=this.streams.get(t);if(!e)throw new A(t,C(t,[...this.streams.keys()]));return e}hasStream(t){return this.streams.has(t)}crossfade(t,e,i={}){let s=i.duration??1.5,r=i.curve??"equal-power",n=i.toVolume??1,u=this.sound(e).play({bus:i.bus,loop:i.loop??true,volume:0});u.fade({to:n,duration:s,curve:r}).catch(()=>{});let c=this.activeVoices().filter(l=>l!==u&&l.sourceName===t&&l.bus===u.bus);for(let l of c)l.fade({to:0,duration:s,curve:r}).then(()=>l.stop()).catch(()=>{});return u}createSound(t,e,i={}){return this.registerSound(t,t,e,i,false)}registerSound(t,e,i,s,r){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let n=s.bus??this.busOrder[0];if(!this.buses.has(n))throw new T(n,C(n,[...this.buses.keys()]));let a=new R(t,{ctx:this.host.touch(),buffer:i,defaultBus:n,sourceName:e,defaultStopFade:this.config.voice?.stopFade,resolveBusInput:u=>{let c=this.buses.get(u);if(!c)throw new T(u,C(u,[...this.buses.keys()]));return c.input},resolveSpatializer:(u,c)=>{if(c)return new q(this.host.touch(),c)},trackVoice:(u,c)=>{this.voices.get(c)?.add(u),this.buses.get(c)?.trackVoice(u);},releaseVoice:(u,c)=>{this.voices.get(c)?.delete(u),this.buses.get(c)?.releaseVoice(u);},applyConcurrency:(u,c)=>{let l=this.buses.get(c);if(!l)return true;let d=false,m=l.applyConcurrencyOnSpawn(u,()=>{d=true;});return m&&(this.voices.get(c)?.delete(m),l.releaseVoice(m)),d&&(this.voices.get(c)?.delete(u),l.releaseVoice(u)),!d}});return (r?this.internalSounds:this.sounds).set(t,a),a}removeSound(t){this.sounds.delete(t);}unloadSound(t,e={}){if(this.sounds.delete(t),e.evictBuffer??true){let i=this.soundUrls.get(t);if(i)for(let s of i)this.decoder.evict(s);}this.soundUrls.delete(t);}hasSound(t){return this.sounds.has(t)}sound(t){let e=this.sounds.get(t);if(!e)throw new A(t,C(t,[...this.sounds.keys()]));return e}bus(t){this.ensureGraph();let e=this.buses.get(t);if(!e)throw new T(t,C(t,[...this.buses.keys()]));return e}busGroup(t,e){if(e!=null){let s=new L(t,e);return this.busGroups.set(t,s),s}let i=this.busGroups.get(t);if(!i)throw new T(t,C(t,[...this.busGroups.keys()]));return i}masterMeter(){return this.ensureGraph(),this.master.meter()}scheduleAt(t,e){return this.host.touch(),this.ensureGraph(),this.scheduler.scheduleAt(t,e)}activeVoices(){let t=[];for(let e of this.voices.values())for(let i of e)t.push(i);return t}onStateChange(t){return this.host.onStateChange(t)}parameter(t,e=0){let i=this.parameters.get(t);return i||(i=new V(t,e),this.parameters.set(t,i)),i}captureSnapshot(t){let e={};for(let[s,r]of this.buses)e[s]={level:r.level,muted:r.muted};let i={};for(let[s,r]of this.parameters)i[s]=r.value;return this.snapshot(t,{buses:e,parameters:i})}snapshot(t,e){return new $(t,e,i=>this.buses.get(i),i=>this.parameters.get(i))}blendSnapshots(t,e,i){t.blendWith(e,i);}ensureGraph(){if(this.master)return;let t=this.host.touch();this.master=new H(t,this.config.master),this.scheduler=new K(this.host,this.config.tickSource);for(let e of this.busOrder){let i=this.config.buses?.[e]??{},s=new F(t,e,i);s.output.connect(this.master.input),s.notifySoloChange=(r,n)=>this.handleSoloChange(r,n),this.buses.set(e,s),this.voices.has(e)||this.voices.set(e,new Set);}}handleSoloChange(t,e){e?this.soloedBuses.add(t):this.soloedBuses.delete(t);let i=this.soloedBuses.size>0;for(let s of this.buses.values())i?s.applySoloVeil(!this.soloedBuses.has(s)):s.applySoloVeil(false);}},wt=4;async function Yt(o,t,e){let i=new Array(o.length),s=0,r=async()=>{for(;;){let a=s++;if(a>=o.length)return;i[a]=await e(o[a],a);}},n=Array.from({length:Math.min(t,o.length)},r);return await Promise.all(n),i}function C(o,t){if(t.length===0)return null;let e=null,i=1/0;for(let n of t){let a=Qt(o,n);a<i&&(i=a,e=n);}let s=Math.max(o.length,e?.length??0),r=Math.max(1,Math.ceil(s/2));return e&&i<=r?e:null}function Kt(o,t){if(!o)return t;if(!t||o.aborted)return o;if(t.aborted)return t;let e=new AbortController,i=()=>{o.removeEventListener("abort",s),t.removeEventListener("abort",r);},s=()=>{i(),e.abort(o.reason);},r=()=>{i(),e.abort(t.reason);};return o.addEventListener("abort",s),t.addEventListener("abort",r),e.signal}function Qt(o,t){if(o===t)return 0;if(o.length===0)return t.length;if(t.length===0)return o.length;let e=new Array(t.length+1),i=new Array(t.length+1);for(let s=0;s<=t.length;s++)e[s]=s;for(let s=1;s<=o.length;s++){i[0]=s;for(let r=1;r<=t.length;r++){let n=o.charCodeAt(s-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(i[r-1]+1,e[r]+1,e[r-1]+n);}for(let r=0;r<=t.length;r++)e[r]=i[r];}return e[t.length]}export{B as AggregateDecodeError,F as Bus,L as BusGroup,T as BusNotFoundError,et as Compressor,M as DecodeError,it as Ducker,x as EngineClosedError,st as Filter,H as Master,D as Music,Q as MusicVoice,V as Parameter,N as PreloadError,rt as Reverb,Z as Send,$ as Snapshot,R as Sound,A as SoundNotFoundError,q as Spatializer,G as Sprite,z as StreamSound,ot as StretchProcessor,U as Variants,I as Voice,_ as ZvukError,k as applyLoudnessNormalization,ut as canPlay,yt as computeNormalizationGain,Xt as createEngine,_t as createStretchWorkletNode,Ot as ensureStretchWorklet,ct as mimeForUrl,lt as pickSource,ht as pickSourceOrder};//# sourceMappingURL=index.js.map
|
|
3357
71
|
//# sourceMappingURL=index.js.map
|