@schmooky/zvuk 0.0.0-develop-20260503095453
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +85 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +204 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +798 -0
- package/dist/index.js +1979 -0
- package/dist/index.js.map +1 -0
- package/package.json +86 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1979 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var ZvukError = class extends Error {
|
|
3
|
+
constructor(message) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "ZvukError";
|
|
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 BankNotLoadedError = class extends ZvukError {
|
|
27
|
+
constructor(id) {
|
|
28
|
+
super(`Bank "${id}" is not loaded. Call engine.loadBank() before requesting its sounds.`);
|
|
29
|
+
this.name = "BankNotLoadedError";
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var DecodeError = class extends ZvukError {
|
|
33
|
+
constructor(url, cause) {
|
|
34
|
+
super(`Failed to decode audio at "${url}": ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
35
|
+
this.name = "DecodeError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// src/fx/compressor.ts
|
|
40
|
+
var Compressor = class {
|
|
41
|
+
input;
|
|
42
|
+
output;
|
|
43
|
+
compressor;
|
|
44
|
+
makeup;
|
|
45
|
+
ctx;
|
|
46
|
+
_bypassed = false;
|
|
47
|
+
constructor(ctx, config = {}) {
|
|
48
|
+
this.ctx = ctx;
|
|
49
|
+
this.input = ctx.createGain();
|
|
50
|
+
this.output = ctx.createGain();
|
|
51
|
+
this.compressor = ctx.createDynamicsCompressor();
|
|
52
|
+
this.makeup = ctx.createGain();
|
|
53
|
+
this.applyConfig(config);
|
|
54
|
+
this.wire();
|
|
55
|
+
}
|
|
56
|
+
applyConfig(c) {
|
|
57
|
+
const t = this.ctx.currentTime;
|
|
58
|
+
if (c.threshold != null) this.compressor.threshold.setValueAtTime(c.threshold, t);
|
|
59
|
+
if (c.knee != null) this.compressor.knee.setValueAtTime(c.knee, t);
|
|
60
|
+
if (c.ratio != null) this.compressor.ratio.setValueAtTime(c.ratio, t);
|
|
61
|
+
if (c.attack != null) this.compressor.attack.setValueAtTime(c.attack, t);
|
|
62
|
+
if (c.release != null) this.compressor.release.setValueAtTime(c.release, t);
|
|
63
|
+
if (c.makeupGain != null) {
|
|
64
|
+
this.makeup.gain.setValueAtTime(10 ** (c.makeupGain / 20), t);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** Live gain reduction in dB (read-only, negative when compressing). */
|
|
68
|
+
get reduction() {
|
|
69
|
+
return this.compressor.reduction;
|
|
70
|
+
}
|
|
71
|
+
get bypassed() {
|
|
72
|
+
return this._bypassed;
|
|
73
|
+
}
|
|
74
|
+
set bypassed(v) {
|
|
75
|
+
if (this._bypassed === v) return;
|
|
76
|
+
this._bypassed = v;
|
|
77
|
+
this.wire();
|
|
78
|
+
}
|
|
79
|
+
dispose() {
|
|
80
|
+
try {
|
|
81
|
+
this.input.disconnect();
|
|
82
|
+
this.compressor.disconnect();
|
|
83
|
+
this.makeup.disconnect();
|
|
84
|
+
this.output.disconnect();
|
|
85
|
+
} catch {
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
wire() {
|
|
89
|
+
try {
|
|
90
|
+
this.input.disconnect();
|
|
91
|
+
this.compressor.disconnect();
|
|
92
|
+
this.makeup.disconnect();
|
|
93
|
+
} catch {
|
|
94
|
+
}
|
|
95
|
+
if (this._bypassed) {
|
|
96
|
+
this.input.connect(this.output);
|
|
97
|
+
} else {
|
|
98
|
+
this.input.connect(this.compressor);
|
|
99
|
+
this.compressor.connect(this.makeup);
|
|
100
|
+
this.makeup.connect(this.output);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// src/fx/ducker.ts
|
|
106
|
+
var Ducker = class {
|
|
107
|
+
input;
|
|
108
|
+
output;
|
|
109
|
+
gain;
|
|
110
|
+
analyser;
|
|
111
|
+
buf;
|
|
112
|
+
rafId = null;
|
|
113
|
+
envelope = 0;
|
|
114
|
+
targetGain = 1;
|
|
115
|
+
ctx;
|
|
116
|
+
cfg;
|
|
117
|
+
_bypassed = false;
|
|
118
|
+
constructor(ctx, sourceBus, config = {}) {
|
|
119
|
+
this.ctx = ctx;
|
|
120
|
+
this.cfg = {
|
|
121
|
+
amount: config.amount ?? 0.5,
|
|
122
|
+
attack: config.attack ?? 80,
|
|
123
|
+
release: config.release ?? 400,
|
|
124
|
+
threshold: config.threshold ?? 0.05
|
|
125
|
+
};
|
|
126
|
+
this.input = ctx.createGain();
|
|
127
|
+
this.output = ctx.createGain();
|
|
128
|
+
this.gain = ctx.createGain();
|
|
129
|
+
this.input.connect(this.gain).connect(this.output);
|
|
130
|
+
this.analyser = ctx.createAnalyser();
|
|
131
|
+
this.analyser.fftSize = 1024;
|
|
132
|
+
this.buf = new Float32Array(this.analyser.fftSize);
|
|
133
|
+
sourceBus.output.connect(this.analyser);
|
|
134
|
+
this.tick();
|
|
135
|
+
}
|
|
136
|
+
setAmount(a) {
|
|
137
|
+
this.cfg.amount = Math.max(0, Math.min(1, a));
|
|
138
|
+
}
|
|
139
|
+
setThreshold(t) {
|
|
140
|
+
this.cfg.threshold = Math.max(0, t);
|
|
141
|
+
}
|
|
142
|
+
get bypassed() {
|
|
143
|
+
return this._bypassed;
|
|
144
|
+
}
|
|
145
|
+
set bypassed(v) {
|
|
146
|
+
if (this._bypassed === v) return;
|
|
147
|
+
this._bypassed = v;
|
|
148
|
+
if (v) this.gain.gain.value = 1;
|
|
149
|
+
}
|
|
150
|
+
dispose() {
|
|
151
|
+
if (this.rafId != null) cancelAnimationFrame(this.rafId);
|
|
152
|
+
try {
|
|
153
|
+
this.input.disconnect();
|
|
154
|
+
this.gain.disconnect();
|
|
155
|
+
this.analyser.disconnect();
|
|
156
|
+
this.output.disconnect();
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
tick = () => {
|
|
161
|
+
if (this._bypassed) {
|
|
162
|
+
this.rafId = requestAnimationFrame(this.tick);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
this.analyser.getFloatTimeDomainData(this.buf);
|
|
166
|
+
let sum = 0;
|
|
167
|
+
for (let i = 0; i < this.buf.length; i++) {
|
|
168
|
+
const s = this.buf[i] ?? 0;
|
|
169
|
+
sum += s * s;
|
|
170
|
+
}
|
|
171
|
+
const rms = Math.sqrt(sum / this.buf.length);
|
|
172
|
+
const exceeded = Math.max(0, rms - this.cfg.threshold);
|
|
173
|
+
const target = exceeded > 0 ? 1 - this.cfg.amount : 1;
|
|
174
|
+
const useAttack = target < this.envelope;
|
|
175
|
+
const tau = (useAttack ? this.cfg.attack : this.cfg.release) || 1;
|
|
176
|
+
const alpha = 1 - Math.exp(-16.666666666666668 / tau);
|
|
177
|
+
this.envelope = this.envelope + alpha * (target - this.envelope);
|
|
178
|
+
if (Math.abs(this.envelope - this.targetGain) > 1e-3) {
|
|
179
|
+
this.targetGain = this.envelope;
|
|
180
|
+
this.gain.gain.setTargetAtTime(this.envelope, this.ctx.currentTime, 5e-3);
|
|
181
|
+
}
|
|
182
|
+
this.rafId = requestAnimationFrame(this.tick);
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
// src/fx/filter.ts
|
|
187
|
+
var Filter = class {
|
|
188
|
+
input;
|
|
189
|
+
output;
|
|
190
|
+
bypassPath;
|
|
191
|
+
direct;
|
|
192
|
+
ctx;
|
|
193
|
+
_bypassed = false;
|
|
194
|
+
constructor(ctx, config = {}) {
|
|
195
|
+
this.ctx = ctx;
|
|
196
|
+
const node = ctx.createBiquadFilter();
|
|
197
|
+
node.type = config.type ?? "lowpass";
|
|
198
|
+
node.frequency.value = config.frequency ?? 1e3;
|
|
199
|
+
node.Q.value = config.q ?? 1;
|
|
200
|
+
node.gain.value = config.gain ?? 0;
|
|
201
|
+
this.input = node;
|
|
202
|
+
this.output = node;
|
|
203
|
+
this.bypassPath = ctx.createGain();
|
|
204
|
+
this.direct = ctx.createGain();
|
|
205
|
+
this.direct.connect(node);
|
|
206
|
+
}
|
|
207
|
+
setFrequency(hz) {
|
|
208
|
+
this.input.frequency.setValueAtTime(hz, this.ctx.currentTime);
|
|
209
|
+
}
|
|
210
|
+
setQ(q) {
|
|
211
|
+
this.input.Q.setValueAtTime(q, this.ctx.currentTime);
|
|
212
|
+
}
|
|
213
|
+
setType(t) {
|
|
214
|
+
this.input.type = t;
|
|
215
|
+
}
|
|
216
|
+
get bypassed() {
|
|
217
|
+
return this._bypassed;
|
|
218
|
+
}
|
|
219
|
+
set bypassed(v) {
|
|
220
|
+
if (this._bypassed === v) return;
|
|
221
|
+
this._bypassed = v;
|
|
222
|
+
this.input.frequency.value = v ? 22050 : this.input.frequency.value || 1e3;
|
|
223
|
+
}
|
|
224
|
+
dispose() {
|
|
225
|
+
try {
|
|
226
|
+
this.input.disconnect();
|
|
227
|
+
this.bypassPath.disconnect();
|
|
228
|
+
this.direct.disconnect();
|
|
229
|
+
} catch {
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
// src/fx/reverb.ts
|
|
235
|
+
var Reverb = class {
|
|
236
|
+
input;
|
|
237
|
+
output;
|
|
238
|
+
dry;
|
|
239
|
+
wet;
|
|
240
|
+
convolver;
|
|
241
|
+
preDelay;
|
|
242
|
+
ctx;
|
|
243
|
+
_bypassed = false;
|
|
244
|
+
constructor(ctx, config = {}) {
|
|
245
|
+
this.ctx = ctx;
|
|
246
|
+
this.input = ctx.createGain();
|
|
247
|
+
this.output = ctx.createGain();
|
|
248
|
+
this.dry = ctx.createGain();
|
|
249
|
+
this.wet = ctx.createGain();
|
|
250
|
+
this.preDelay = ctx.createDelay(1);
|
|
251
|
+
this.convolver = ctx.createConvolver();
|
|
252
|
+
const wetMix = config.wet ?? 0.3;
|
|
253
|
+
this.dry.gain.value = 1 - wetMix;
|
|
254
|
+
this.wet.gain.value = wetMix;
|
|
255
|
+
if (config.impulse) {
|
|
256
|
+
this.convolver.buffer = config.impulse;
|
|
257
|
+
} else {
|
|
258
|
+
this.convolver.buffer = this.synthIR(config.decay?.seconds ?? 1.5);
|
|
259
|
+
}
|
|
260
|
+
this.preDelay.delayTime.value = config.decay?.preDelay ?? 0;
|
|
261
|
+
this.input.connect(this.dry).connect(this.output);
|
|
262
|
+
this.input.connect(this.preDelay).connect(this.convolver).connect(this.wet).connect(this.output);
|
|
263
|
+
}
|
|
264
|
+
setWet(mix) {
|
|
265
|
+
const m = Math.max(0, Math.min(1, mix));
|
|
266
|
+
const t = this.ctx.currentTime;
|
|
267
|
+
this.dry.gain.setValueAtTime(1 - m, t);
|
|
268
|
+
this.wet.gain.setValueAtTime(m, t);
|
|
269
|
+
}
|
|
270
|
+
setImpulse(buffer) {
|
|
271
|
+
this.convolver.buffer = buffer;
|
|
272
|
+
}
|
|
273
|
+
get bypassed() {
|
|
274
|
+
return this._bypassed;
|
|
275
|
+
}
|
|
276
|
+
set bypassed(v) {
|
|
277
|
+
if (this._bypassed === v) return;
|
|
278
|
+
this._bypassed = v;
|
|
279
|
+
this.wet.gain.value = v ? 0 : 0.3;
|
|
280
|
+
}
|
|
281
|
+
dispose() {
|
|
282
|
+
try {
|
|
283
|
+
this.input.disconnect();
|
|
284
|
+
this.dry.disconnect();
|
|
285
|
+
this.wet.disconnect();
|
|
286
|
+
this.preDelay.disconnect();
|
|
287
|
+
this.convolver.disconnect();
|
|
288
|
+
this.output.disconnect();
|
|
289
|
+
} catch {
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/** Generate a synthetic exponential-decay impulse response. */
|
|
293
|
+
synthIR(seconds) {
|
|
294
|
+
const rate = this.ctx.sampleRate;
|
|
295
|
+
const length = Math.floor(rate * seconds);
|
|
296
|
+
const ir = this.ctx.createBuffer(2, length, rate);
|
|
297
|
+
for (let ch = 0; ch < 2; ch++) {
|
|
298
|
+
const data = ir.getChannelData(ch);
|
|
299
|
+
for (let i = 0; i < length; i++) {
|
|
300
|
+
const t = i / length;
|
|
301
|
+
data[i] = (Math.random() * 2 - 1) * (1 - t) ** 3;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return ir;
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
// src/fx/stretch.ts
|
|
309
|
+
var StretchProcessor = class _StretchProcessor {
|
|
310
|
+
factor;
|
|
311
|
+
constructor(stretchFactor = 1) {
|
|
312
|
+
this.factor = stretchFactor;
|
|
313
|
+
}
|
|
314
|
+
process(input) {
|
|
315
|
+
if (this.factor === 1) return new Float32Array(input);
|
|
316
|
+
const outLen = Math.floor(input.length / this.factor);
|
|
317
|
+
const out = new Float32Array(outLen);
|
|
318
|
+
const baseGrain = 4096;
|
|
319
|
+
const grain = Math.max(160, Math.floor(baseGrain / Math.sqrt(this.factor)));
|
|
320
|
+
const overlap = Math.max(48, Math.floor(grain / 4));
|
|
321
|
+
const inHop = Math.max(1, grain - overlap);
|
|
322
|
+
const outHop = Math.max(1, Math.floor(inHop / this.factor));
|
|
323
|
+
const fadeIn = new Float32Array(overlap);
|
|
324
|
+
const fadeOut = new Float32Array(overlap);
|
|
325
|
+
for (let i = 0; i < overlap; i++) {
|
|
326
|
+
const t = i / (overlap - 1);
|
|
327
|
+
const a = Math.sin(Math.PI * t / 2);
|
|
328
|
+
const b = Math.cos(Math.PI * t / 2);
|
|
329
|
+
fadeIn[i] = a * a;
|
|
330
|
+
fadeOut[i] = b * b;
|
|
331
|
+
}
|
|
332
|
+
const jitter = Math.max(0, Math.floor(inHop * 0.03));
|
|
333
|
+
let inPos = 0;
|
|
334
|
+
let outPos = 0;
|
|
335
|
+
while (inPos + grain < input.length && outPos + grain < outLen) {
|
|
336
|
+
let bestPos = inPos;
|
|
337
|
+
if (this.factor < 2.5 && outPos >= overlap) {
|
|
338
|
+
let bestCorr = -Infinity;
|
|
339
|
+
const search = Math.min(64, inHop);
|
|
340
|
+
for (let off = -search; off <= search; off += 4) {
|
|
341
|
+
const test = inPos + off;
|
|
342
|
+
if (test >= 0 && test + overlap < input.length) {
|
|
343
|
+
let corr = 0;
|
|
344
|
+
for (let i = 0; i < overlap; i++) {
|
|
345
|
+
corr += (out[outPos - overlap + i] ?? 0) * (input[test + i] ?? 0);
|
|
346
|
+
}
|
|
347
|
+
if (corr > bestCorr) {
|
|
348
|
+
bestCorr = corr;
|
|
349
|
+
bestPos = test;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (jitter > 0) {
|
|
355
|
+
bestPos = Math.max(
|
|
356
|
+
0,
|
|
357
|
+
Math.min(input.length - grain, bestPos + (Math.random() * 2 - 1) * jitter | 0)
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
let eOut = 0;
|
|
361
|
+
let eIn = 0;
|
|
362
|
+
if (outPos > 0) {
|
|
363
|
+
for (let i = 0; i < overlap; i++) {
|
|
364
|
+
const a = out[outPos - overlap + i] ?? 0;
|
|
365
|
+
const b = input[bestPos + i] ?? 0;
|
|
366
|
+
eOut += a * a;
|
|
367
|
+
eIn += b * b;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
let scale = 1;
|
|
371
|
+
if (eIn > 1e-8 && eOut > 0) scale = Math.sqrt(eOut / eIn);
|
|
372
|
+
scale = Math.min(1.1, Math.max(0.9, scale));
|
|
373
|
+
for (let i = 0; i < grain && outPos + i < outLen; i++) {
|
|
374
|
+
const src = input[bestPos + i] ?? 0;
|
|
375
|
+
if (i < overlap && outPos > 0) {
|
|
376
|
+
const existing = out[outPos + i] ?? 0;
|
|
377
|
+
out[outPos + i] = existing * (fadeOut[i] ?? 0) + src * scale * (fadeIn[i] ?? 0);
|
|
378
|
+
} else {
|
|
379
|
+
out[outPos + i] = src;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
inPos += inHop;
|
|
383
|
+
outPos += outHop;
|
|
384
|
+
}
|
|
385
|
+
for (let i = outPos; i < outLen; i++) {
|
|
386
|
+
const idxF = i * this.factor;
|
|
387
|
+
const idx = Math.floor(idxF);
|
|
388
|
+
const frac = idxF - idx;
|
|
389
|
+
if (idx >= 0 && idx + 1 < input.length) {
|
|
390
|
+
out[i] = (input[idx] ?? 0) * (1 - frac) + (input[idx + 1] ?? 0) * frac;
|
|
391
|
+
} else {
|
|
392
|
+
out[i] = input[Math.min(input.length - 1, Math.max(0, idx))] ?? 0;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
if (this.factor > 1) {
|
|
396
|
+
const k = Math.min(0.12, Math.max(0.05, 0.18 / this.factor));
|
|
397
|
+
let prev = 0;
|
|
398
|
+
for (let i = 0; i < out.length; i++) {
|
|
399
|
+
const x = out[i] ?? 0;
|
|
400
|
+
out[i] = x + k * (x - prev);
|
|
401
|
+
prev = x;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return out;
|
|
405
|
+
}
|
|
406
|
+
/** Convenience: process an AudioBuffer in place to a new buffer. */
|
|
407
|
+
static stretchBuffer(ctx, src, factor) {
|
|
408
|
+
if (factor === 1) return src;
|
|
409
|
+
const proc = new _StretchProcessor(factor);
|
|
410
|
+
const channels = [];
|
|
411
|
+
for (let c = 0; c < src.numberOfChannels; c++) {
|
|
412
|
+
channels.push(proc.process(src.getChannelData(c)));
|
|
413
|
+
}
|
|
414
|
+
const length = Math.max(...channels.map((ch) => ch.length));
|
|
415
|
+
const out = ctx.createBuffer(src.numberOfChannels, length, src.sampleRate);
|
|
416
|
+
for (let c = 0; c < src.numberOfChannels; c++) {
|
|
417
|
+
out.copyToChannel(channels[c], c);
|
|
418
|
+
}
|
|
419
|
+
return out;
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
// src/fx/stretch-worklet.ts
|
|
424
|
+
var PROCESSOR_NAME = "zvuk-realtime-stretch";
|
|
425
|
+
var loaded = /* @__PURE__ */ new WeakSet();
|
|
426
|
+
var PROCESSOR_SOURCE = `
|
|
427
|
+
class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
|
|
428
|
+
static get parameterDescriptors() {
|
|
429
|
+
return [
|
|
430
|
+
{ name: 'stretch', defaultValue: 1, minValue: 0.25, maxValue: 4, automationRate: 'k-rate' },
|
|
431
|
+
];
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
constructor(options) {
|
|
435
|
+
super();
|
|
436
|
+
const grain = (options && options.processorOptions && options.processorOptions.grainSize) || 1024;
|
|
437
|
+
this.grainSize = grain;
|
|
438
|
+
this.ringSize = grain * 8;
|
|
439
|
+
this.ringL = new Float32Array(this.ringSize);
|
|
440
|
+
this.ringR = new Float32Array(this.ringSize);
|
|
441
|
+
this.writePos = 0;
|
|
442
|
+
this.readPos = 0;
|
|
443
|
+
this.window = new Float32Array(grain);
|
|
444
|
+
for (let i = 0; i < grain; i++) {
|
|
445
|
+
const t = i / (grain - 1);
|
|
446
|
+
// Hann window for OLA crossfade.
|
|
447
|
+
this.window[i] = 0.5 * (1 - Math.cos(2 * Math.PI * t));
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
process(inputs, outputs, params) {
|
|
452
|
+
const input = inputs[0];
|
|
453
|
+
const output = outputs[0];
|
|
454
|
+
if (!input || !output || input.length === 0) return true;
|
|
455
|
+
|
|
456
|
+
const inL = input[0];
|
|
457
|
+
const inR = input[1] || inL;
|
|
458
|
+
const outL = output[0];
|
|
459
|
+
const outR = output[1] || outL;
|
|
460
|
+
const stretch = params.stretch[0] || 1;
|
|
461
|
+
|
|
462
|
+
const blockLen = inL.length;
|
|
463
|
+
for (let i = 0; i < blockLen; i++) {
|
|
464
|
+
this.ringL[this.writePos] = inL[i] || 0;
|
|
465
|
+
this.ringR[this.writePos] = inR[i] || 0;
|
|
466
|
+
this.writePos = (this.writePos + 1) % this.ringSize;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
const step = 1 / Math.max(0.0001, stretch);
|
|
470
|
+
for (let i = 0; i < outL.length; i++) {
|
|
471
|
+
const idx = this.readPos;
|
|
472
|
+
const i0 = Math.floor(idx);
|
|
473
|
+
const frac = idx - i0;
|
|
474
|
+
const a = i0 % this.ringSize;
|
|
475
|
+
const b = (i0 + 1) % this.ringSize;
|
|
476
|
+
outL[i] = this.ringL[a] * (1 - frac) + this.ringL[b] * frac;
|
|
477
|
+
outR[i] = this.ringR[a] * (1 - frac) + this.ringR[b] * frac;
|
|
478
|
+
this.readPos += step;
|
|
479
|
+
if (this.readPos >= this.ringSize) this.readPos -= this.ringSize;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// Drift correction \u2014 keep the read head behind the write head by ~ringSize/2.
|
|
483
|
+
const writeF = this.writePos;
|
|
484
|
+
const target = writeF - this.ringSize / 2;
|
|
485
|
+
let lag = this.readPos - target;
|
|
486
|
+
if (lag > this.ringSize / 2) lag -= this.ringSize;
|
|
487
|
+
if (lag < -this.ringSize / 2) lag += this.ringSize;
|
|
488
|
+
if (Math.abs(lag) > this.ringSize / 4) {
|
|
489
|
+
this.readPos = target;
|
|
490
|
+
if (this.readPos < 0) this.readPos += this.ringSize;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return true;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
registerProcessor('${PROCESSOR_NAME}', ZvukRealtimeStretchProcessor);
|
|
498
|
+
`;
|
|
499
|
+
async function ensureStretchWorklet(ctx) {
|
|
500
|
+
if (loaded.has(ctx)) return;
|
|
501
|
+
const w = ctx.audioWorklet;
|
|
502
|
+
if (!w) throw new Error("AudioWorklet not supported in this context");
|
|
503
|
+
const blob = new Blob([PROCESSOR_SOURCE], { type: "application/javascript" });
|
|
504
|
+
const url = URL.createObjectURL(blob);
|
|
505
|
+
try {
|
|
506
|
+
await w.addModule(url);
|
|
507
|
+
} finally {
|
|
508
|
+
URL.revokeObjectURL(url);
|
|
509
|
+
}
|
|
510
|
+
loaded.add(ctx);
|
|
511
|
+
}
|
|
512
|
+
function createStretchWorkletNode(ctx, options = {}) {
|
|
513
|
+
const Ctor = globalThis.AudioWorkletNode;
|
|
514
|
+
if (!Ctor) throw new Error("AudioWorkletNode not available");
|
|
515
|
+
const node = new Ctor(ctx, PROCESSOR_NAME, {
|
|
516
|
+
numberOfInputs: 1,
|
|
517
|
+
numberOfOutputs: 1,
|
|
518
|
+
outputChannelCount: [2],
|
|
519
|
+
processorOptions: { grainSize: options.grainSize ?? 1024 }
|
|
520
|
+
});
|
|
521
|
+
const stretch = node.parameters.get("stretch");
|
|
522
|
+
if (stretch && options.stretchFactor != null) stretch.value = options.stretchFactor;
|
|
523
|
+
const disposable = node;
|
|
524
|
+
Object.defineProperty(disposable, "stretch", {
|
|
525
|
+
value: stretch,
|
|
526
|
+
enumerable: true
|
|
527
|
+
});
|
|
528
|
+
disposable.dispose = () => {
|
|
529
|
+
try {
|
|
530
|
+
node.disconnect();
|
|
531
|
+
} catch {
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
return disposable;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/mixer/curve.ts
|
|
538
|
+
function applyRamp(param, now, to, durationMs, curve) {
|
|
539
|
+
const durationSec = Math.max(0, durationMs / 1e3);
|
|
540
|
+
const from = param.value;
|
|
541
|
+
param.cancelScheduledValues(now);
|
|
542
|
+
param.setValueAtTime(from, now);
|
|
543
|
+
if (durationSec === 0) {
|
|
544
|
+
param.setValueAtTime(to, now);
|
|
545
|
+
return;
|
|
546
|
+
}
|
|
547
|
+
if (curve === "linear") {
|
|
548
|
+
param.linearRampToValueAtTime(to, now + durationSec);
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
const samples = sampleCurve(from, to, curve, 64);
|
|
552
|
+
param.setValueCurveAtTime(samples, now, durationSec);
|
|
553
|
+
}
|
|
554
|
+
function sampleCurve(from, to, curve, n) {
|
|
555
|
+
const out = new Float32Array(n);
|
|
556
|
+
for (let i = 0; i < n; i++) {
|
|
557
|
+
const t = i / (n - 1);
|
|
558
|
+
const eased = ease(t, curve);
|
|
559
|
+
out[i] = from + (to - from) * eased;
|
|
560
|
+
}
|
|
561
|
+
return out;
|
|
562
|
+
}
|
|
563
|
+
function ease(t, curve) {
|
|
564
|
+
switch (curve) {
|
|
565
|
+
case "easeIn":
|
|
566
|
+
return t * t;
|
|
567
|
+
case "easeOut":
|
|
568
|
+
return 1 - (1 - t) * (1 - t);
|
|
569
|
+
case "easeInOut":
|
|
570
|
+
return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
|
|
571
|
+
case "equal-power":
|
|
572
|
+
return Math.sin(t * Math.PI / 2) ** 2;
|
|
573
|
+
default:
|
|
574
|
+
return t;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/mixer/bus.ts
|
|
579
|
+
var Bus = class {
|
|
580
|
+
name;
|
|
581
|
+
input;
|
|
582
|
+
/** Sub-bus where FX inserts go. Currently == input; reserved for FX chain. */
|
|
583
|
+
fxInput;
|
|
584
|
+
/** Output node — connect to master.input or another bus.input for sends. */
|
|
585
|
+
output;
|
|
586
|
+
_level;
|
|
587
|
+
_muted;
|
|
588
|
+
_baseLevel;
|
|
589
|
+
ctx;
|
|
590
|
+
_concurrency;
|
|
591
|
+
_voices = /* @__PURE__ */ new Set();
|
|
592
|
+
_fxChain = [];
|
|
593
|
+
constructor(ctx, name, config = {}) {
|
|
594
|
+
this.ctx = ctx;
|
|
595
|
+
this.name = name;
|
|
596
|
+
this._level = config.level ?? 1;
|
|
597
|
+
this._muted = config.mute ?? false;
|
|
598
|
+
this._baseLevel = this._level;
|
|
599
|
+
this._concurrency = config.concurrency ?? null;
|
|
600
|
+
this.input = ctx.createGain();
|
|
601
|
+
this.fxInput = ctx.createGain();
|
|
602
|
+
this.output = ctx.createGain();
|
|
603
|
+
this.input.connect(this.fxInput);
|
|
604
|
+
this.fxInput.connect(this.output);
|
|
605
|
+
this.output.gain.value = this._muted ? 0 : this._level;
|
|
606
|
+
}
|
|
607
|
+
get level() {
|
|
608
|
+
return this._level;
|
|
609
|
+
}
|
|
610
|
+
set level(v) {
|
|
611
|
+
this._level = clamp01(v);
|
|
612
|
+
this._baseLevel = this._level;
|
|
613
|
+
if (!this._muted) this.rampOutput(this._level, 10);
|
|
614
|
+
}
|
|
615
|
+
get muted() {
|
|
616
|
+
return this._muted;
|
|
617
|
+
}
|
|
618
|
+
set muted(v) {
|
|
619
|
+
this._muted = v;
|
|
620
|
+
this.rampOutput(v ? 0 : this._level, 10);
|
|
621
|
+
}
|
|
622
|
+
fadeTo(target, durationMs, curve = "linear") {
|
|
623
|
+
const to = clamp01(target);
|
|
624
|
+
this._level = to;
|
|
625
|
+
this._baseLevel = to;
|
|
626
|
+
return this.ramp(to, durationMs, curve);
|
|
627
|
+
}
|
|
628
|
+
/** Active voice count on this bus. */
|
|
629
|
+
get voiceCount() {
|
|
630
|
+
return this._voices.size;
|
|
631
|
+
}
|
|
632
|
+
/** Read-only iterator over active voices. */
|
|
633
|
+
voices() {
|
|
634
|
+
return Array.from(this._voices);
|
|
635
|
+
}
|
|
636
|
+
/** Concurrency config — read it for UI, mutate via setConcurrency. */
|
|
637
|
+
get concurrency() {
|
|
638
|
+
return this._concurrency;
|
|
639
|
+
}
|
|
640
|
+
setConcurrency(c) {
|
|
641
|
+
this._concurrency = c;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Called by Engine right before adding a new Voice. Returns a Voice that
|
|
645
|
+
* was stolen to make room (so the engine can release it from its tracking),
|
|
646
|
+
* or null if no steal was needed (or the new voice itself was rejected,
|
|
647
|
+
* in which case onReject is invoked instead).
|
|
648
|
+
*/
|
|
649
|
+
applyConcurrencyOnSpawn(newVoice, onReject) {
|
|
650
|
+
const c = this._concurrency;
|
|
651
|
+
if (!c) return null;
|
|
652
|
+
if (this._voices.size <= c.max) return null;
|
|
653
|
+
const strategy = c.steal ?? "oldest";
|
|
654
|
+
if (strategy === "none") {
|
|
655
|
+
onReject();
|
|
656
|
+
return null;
|
|
657
|
+
}
|
|
658
|
+
const victim = pickVictim(this._voices, strategy, newVoice);
|
|
659
|
+
if (!victim) {
|
|
660
|
+
onReject();
|
|
661
|
+
return null;
|
|
662
|
+
}
|
|
663
|
+
victim.stop();
|
|
664
|
+
return victim;
|
|
665
|
+
}
|
|
666
|
+
/** Engine-only: register an active voice. */
|
|
667
|
+
trackVoice(v) {
|
|
668
|
+
this._voices.add(v);
|
|
669
|
+
}
|
|
670
|
+
/** Engine-only: deregister a finished voice. */
|
|
671
|
+
releaseVoice(v) {
|
|
672
|
+
this._voices.delete(v);
|
|
673
|
+
}
|
|
674
|
+
/** Add an FX insert to the bus's FX chain (post-input, pre-output). */
|
|
675
|
+
addFx(fx) {
|
|
676
|
+
this._fxChain.push(fx);
|
|
677
|
+
this.rewireFxChain();
|
|
678
|
+
}
|
|
679
|
+
removeFx(fx) {
|
|
680
|
+
const idx = this._fxChain.indexOf(fx);
|
|
681
|
+
if (idx === -1) return;
|
|
682
|
+
this._fxChain.splice(idx, 1);
|
|
683
|
+
this.rewireFxChain();
|
|
684
|
+
}
|
|
685
|
+
fx() {
|
|
686
|
+
return this._fxChain;
|
|
687
|
+
}
|
|
688
|
+
rewireFxChain() {
|
|
689
|
+
try {
|
|
690
|
+
this.fxInput.disconnect();
|
|
691
|
+
for (const fx of this._fxChain) fx.output.disconnect();
|
|
692
|
+
} catch {
|
|
693
|
+
}
|
|
694
|
+
let head = this.fxInput;
|
|
695
|
+
for (const fx of this._fxChain) {
|
|
696
|
+
head.connect(fx.input);
|
|
697
|
+
head = fx.output;
|
|
698
|
+
}
|
|
699
|
+
head.connect(this.output);
|
|
700
|
+
}
|
|
701
|
+
rampOutput(to, durationMs) {
|
|
702
|
+
void this.ramp(to, durationMs, "linear");
|
|
703
|
+
}
|
|
704
|
+
ramp(to, durationMs, curve) {
|
|
705
|
+
const param = this.output.gain;
|
|
706
|
+
const now = this.ctx.currentTime;
|
|
707
|
+
applyRamp(param, now, to, durationMs, curve);
|
|
708
|
+
return wait(durationMs);
|
|
709
|
+
}
|
|
710
|
+
dispose() {
|
|
711
|
+
try {
|
|
712
|
+
this.input.disconnect();
|
|
713
|
+
this.fxInput.disconnect();
|
|
714
|
+
this.output.disconnect();
|
|
715
|
+
} catch {
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
function clamp01(v) {
|
|
720
|
+
if (Number.isNaN(v)) return 0;
|
|
721
|
+
return Math.min(1, Math.max(0, v));
|
|
722
|
+
}
|
|
723
|
+
function wait(ms) {
|
|
724
|
+
if (ms <= 0) return Promise.resolve();
|
|
725
|
+
return new Promise((res) => setTimeout(res, ms));
|
|
726
|
+
}
|
|
727
|
+
function pickVictim(voices, strategy, newVoice) {
|
|
728
|
+
let victim = null;
|
|
729
|
+
for (const v of voices) {
|
|
730
|
+
if (v === newVoice) continue;
|
|
731
|
+
if (!victim) {
|
|
732
|
+
victim = v;
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
switch (strategy) {
|
|
736
|
+
case "oldest":
|
|
737
|
+
if (v.startedAt < victim.startedAt) victim = v;
|
|
738
|
+
break;
|
|
739
|
+
case "lowest-priority":
|
|
740
|
+
if (v.priority < victim.priority) victim = v;
|
|
741
|
+
break;
|
|
742
|
+
case "quietest":
|
|
743
|
+
if (v.startedAt < victim.startedAt) victim = v;
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
return victim;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// src/params/parameter.ts
|
|
751
|
+
var Parameter = class {
|
|
752
|
+
name;
|
|
753
|
+
_value;
|
|
754
|
+
subs = /* @__PURE__ */ new Set();
|
|
755
|
+
constructor(name, initial) {
|
|
756
|
+
this.name = name;
|
|
757
|
+
this._value = initial;
|
|
758
|
+
}
|
|
759
|
+
get value() {
|
|
760
|
+
return this._value;
|
|
761
|
+
}
|
|
762
|
+
set(v) {
|
|
763
|
+
if (v === this._value) return;
|
|
764
|
+
this._value = v;
|
|
765
|
+
for (const s of this.subs) s(v);
|
|
766
|
+
}
|
|
767
|
+
subscribe(fn) {
|
|
768
|
+
this.subs.add(fn);
|
|
769
|
+
fn(this._value);
|
|
770
|
+
return () => this.subs.delete(fn);
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* Bind a setter to this parameter. The parameter's [0..1] value (clamped)
|
|
774
|
+
* is mapped to [from..to] via `curve`, then the setter is called with the
|
|
775
|
+
* mapped value. Returns an unbind function.
|
|
776
|
+
*/
|
|
777
|
+
bindTo(setter, opts = {}) {
|
|
778
|
+
const from = opts.from ?? 0;
|
|
779
|
+
const to = opts.to ?? 1;
|
|
780
|
+
const curve = opts.curve ?? "linear";
|
|
781
|
+
return this.subscribe((v) => {
|
|
782
|
+
const t = Math.max(0, Math.min(1, v));
|
|
783
|
+
const eased = ease2(t, curve);
|
|
784
|
+
setter(from + (to - from) * eased);
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
};
|
|
788
|
+
function ease2(t, curve) {
|
|
789
|
+
switch (curve) {
|
|
790
|
+
case "easeIn":
|
|
791
|
+
return t * t;
|
|
792
|
+
case "easeOut":
|
|
793
|
+
return 1 - (1 - t) * (1 - t);
|
|
794
|
+
case "easeInOut":
|
|
795
|
+
return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
|
|
796
|
+
case "equal-power":
|
|
797
|
+
return Math.sin(t * Math.PI / 2) ** 2;
|
|
798
|
+
default:
|
|
799
|
+
return t;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// src/runtime/codecs.ts
|
|
804
|
+
var EXT_TO_MIME = {
|
|
805
|
+
webm: 'audio/webm; codecs="opus"',
|
|
806
|
+
opus: 'audio/ogg; codecs="opus"',
|
|
807
|
+
ogg: 'audio/ogg; codecs="vorbis"',
|
|
808
|
+
m4a: 'audio/mp4; codecs="mp4a.40.2"',
|
|
809
|
+
mp4: 'audio/mp4; codecs="mp4a.40.2"',
|
|
810
|
+
aac: 'audio/mp4; codecs="mp4a.40.2"',
|
|
811
|
+
mp3: "audio/mpeg",
|
|
812
|
+
wav: "audio/wav",
|
|
813
|
+
flac: "audio/flac"
|
|
814
|
+
};
|
|
815
|
+
var probe = null;
|
|
816
|
+
function canPlay(mime) {
|
|
817
|
+
if (typeof document === "undefined") return true;
|
|
818
|
+
if (!probe) {
|
|
819
|
+
try {
|
|
820
|
+
probe = document.createElement("audio");
|
|
821
|
+
} catch {
|
|
822
|
+
return true;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
const result = probe.canPlayType(mime);
|
|
826
|
+
return result === "probably" || result === "maybe";
|
|
827
|
+
}
|
|
828
|
+
function mimeForUrl(url) {
|
|
829
|
+
const m = /\.([a-z0-9]+)(?:[?#]|$)/i.exec(url);
|
|
830
|
+
if (!m || !m[1]) return null;
|
|
831
|
+
return EXT_TO_MIME[m[1].toLowerCase()] ?? null;
|
|
832
|
+
}
|
|
833
|
+
function pickSource(urls) {
|
|
834
|
+
if (urls.length === 0) throw new Error("pickSource requires at least one URL");
|
|
835
|
+
for (const url of urls) {
|
|
836
|
+
const mime = mimeForUrl(url);
|
|
837
|
+
if (!mime) continue;
|
|
838
|
+
if (canPlay(mime)) return url;
|
|
839
|
+
}
|
|
840
|
+
return urls[0];
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// src/runtime/context.ts
|
|
844
|
+
var AudioContextHost = class {
|
|
845
|
+
_ctx = null;
|
|
846
|
+
_state = "cold";
|
|
847
|
+
_unlocking = null;
|
|
848
|
+
_listeners = /* @__PURE__ */ new Set();
|
|
849
|
+
get state() {
|
|
850
|
+
return this._state;
|
|
851
|
+
}
|
|
852
|
+
/** Returns the live AudioContext, constructing it if necessary. */
|
|
853
|
+
touch() {
|
|
854
|
+
if (this._state === "closed") throw new EngineClosedError();
|
|
855
|
+
if (!this._ctx) {
|
|
856
|
+
this._ctx = new AudioContext();
|
|
857
|
+
this.attachVisibilityHandler();
|
|
858
|
+
}
|
|
859
|
+
return this._ctx;
|
|
860
|
+
}
|
|
861
|
+
/** Returns null instead of constructing — use when you need to peek. */
|
|
862
|
+
peek() {
|
|
863
|
+
return this._ctx;
|
|
864
|
+
}
|
|
865
|
+
/** Resume the context. Safe to call from any handler; promise resolves to live state. */
|
|
866
|
+
async unlock() {
|
|
867
|
+
if (this._state === "closed") throw new EngineClosedError();
|
|
868
|
+
if (this._state === "live") return;
|
|
869
|
+
if (this._unlocking) return this._unlocking;
|
|
870
|
+
this.setState("unlocking");
|
|
871
|
+
const ctx = this.touch();
|
|
872
|
+
this._unlocking = (async () => {
|
|
873
|
+
try {
|
|
874
|
+
if (ctx.state === "suspended") await ctx.resume();
|
|
875
|
+
this.setState("live");
|
|
876
|
+
} catch (e) {
|
|
877
|
+
this.setState("cold");
|
|
878
|
+
throw e;
|
|
879
|
+
} finally {
|
|
880
|
+
this._unlocking = null;
|
|
881
|
+
}
|
|
882
|
+
})();
|
|
883
|
+
return this._unlocking;
|
|
884
|
+
}
|
|
885
|
+
/** Sample-accurate "now" in seconds. */
|
|
886
|
+
get now() {
|
|
887
|
+
return this._ctx?.currentTime ?? 0;
|
|
888
|
+
}
|
|
889
|
+
onStateChange(fn) {
|
|
890
|
+
this._listeners.add(fn);
|
|
891
|
+
return () => this._listeners.delete(fn);
|
|
892
|
+
}
|
|
893
|
+
async close() {
|
|
894
|
+
if (this._state === "closed") return;
|
|
895
|
+
document.removeEventListener("visibilitychange", this.handleVisibility);
|
|
896
|
+
if (this._ctx && this._ctx.state !== "closed") {
|
|
897
|
+
await this._ctx.close().catch(() => void 0);
|
|
898
|
+
}
|
|
899
|
+
this._ctx = null;
|
|
900
|
+
this.setState("closed");
|
|
901
|
+
this._listeners.clear();
|
|
902
|
+
}
|
|
903
|
+
setState(s) {
|
|
904
|
+
if (this._state === s) return;
|
|
905
|
+
this._state = s;
|
|
906
|
+
for (const fn of this._listeners) fn(s);
|
|
907
|
+
}
|
|
908
|
+
attachVisibilityHandler() {
|
|
909
|
+
if (typeof document === "undefined") return;
|
|
910
|
+
document.addEventListener("visibilitychange", this.handleVisibility);
|
|
911
|
+
}
|
|
912
|
+
handleVisibility = () => {
|
|
913
|
+
if (!this._ctx || this._state === "closed") return;
|
|
914
|
+
const visible = document.visibilityState === "visible";
|
|
915
|
+
if (visible) {
|
|
916
|
+
setTimeout(() => {
|
|
917
|
+
if (document.visibilityState === "visible" && this._ctx?.state === "suspended") {
|
|
918
|
+
void this._ctx.resume().catch(() => void 0);
|
|
919
|
+
}
|
|
920
|
+
}, 200);
|
|
921
|
+
} else {
|
|
922
|
+
void this._ctx.suspend().catch(() => void 0);
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
};
|
|
926
|
+
|
|
927
|
+
// src/runtime/decode.ts
|
|
928
|
+
var Decoder = class {
|
|
929
|
+
constructor(getCtx, maxEntries = 128) {
|
|
930
|
+
this.getCtx = getCtx;
|
|
931
|
+
this.maxEntries = maxEntries;
|
|
932
|
+
}
|
|
933
|
+
getCtx;
|
|
934
|
+
maxEntries;
|
|
935
|
+
cache = /* @__PURE__ */ new Map();
|
|
936
|
+
has(url) {
|
|
937
|
+
return this.cache.has(url);
|
|
938
|
+
}
|
|
939
|
+
async load(url, opts = {}) {
|
|
940
|
+
const cached = this.cache.get(url);
|
|
941
|
+
if (cached) {
|
|
942
|
+
this.touch(url, cached);
|
|
943
|
+
return cached;
|
|
944
|
+
}
|
|
945
|
+
let response;
|
|
946
|
+
try {
|
|
947
|
+
response = await fetch(url, { signal: opts.signal });
|
|
948
|
+
} catch (e) {
|
|
949
|
+
if (e.name === "AbortError") throw e;
|
|
950
|
+
throw new DecodeError(url, e);
|
|
951
|
+
}
|
|
952
|
+
if (!response.ok) {
|
|
953
|
+
throw new DecodeError(url, new Error(`${response.status} ${response.statusText}`));
|
|
954
|
+
}
|
|
955
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
956
|
+
const ctx = this.getCtx();
|
|
957
|
+
let buffer;
|
|
958
|
+
try {
|
|
959
|
+
buffer = await ctx.decodeAudioData(arrayBuffer);
|
|
960
|
+
} catch (e) {
|
|
961
|
+
throw new DecodeError(url, e);
|
|
962
|
+
}
|
|
963
|
+
this.touch(url, buffer);
|
|
964
|
+
return buffer;
|
|
965
|
+
}
|
|
966
|
+
evict(url) {
|
|
967
|
+
this.cache.delete(url);
|
|
968
|
+
}
|
|
969
|
+
clear() {
|
|
970
|
+
this.cache.clear();
|
|
971
|
+
}
|
|
972
|
+
touch(url, buffer) {
|
|
973
|
+
if (this.cache.has(url)) this.cache.delete(url);
|
|
974
|
+
this.cache.set(url, buffer);
|
|
975
|
+
while (this.cache.size > this.maxEntries) {
|
|
976
|
+
const oldest = this.cache.keys().next().value;
|
|
977
|
+
if (oldest === void 0) break;
|
|
978
|
+
this.cache.delete(oldest);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
// src/runtime/loudness.ts
|
|
984
|
+
var DEFAULTS = {
|
|
985
|
+
targetRms: 0.1,
|
|
986
|
+
peakCeiling: 0.99
|
|
987
|
+
};
|
|
988
|
+
function applyLoudnessNormalization(buffer, flag) {
|
|
989
|
+
if (!flag) return buffer;
|
|
990
|
+
const opts = { ...DEFAULTS, ...typeof flag === "object" ? flag : {} };
|
|
991
|
+
const gain = computeNormalizationGain(buffer, opts);
|
|
992
|
+
if (Math.abs(gain - 1) < 1e-3) return buffer;
|
|
993
|
+
return scaleBuffer(buffer, gain);
|
|
994
|
+
}
|
|
995
|
+
function computeNormalizationGain(buffer, opts) {
|
|
996
|
+
const rms = measureRms(buffer);
|
|
997
|
+
if (rms <= 1e-6) return 1;
|
|
998
|
+
let gain = opts.targetRms / rms;
|
|
999
|
+
const peak = measurePeak(buffer) * gain;
|
|
1000
|
+
if (peak > opts.peakCeiling) gain *= opts.peakCeiling / peak;
|
|
1001
|
+
return gain;
|
|
1002
|
+
}
|
|
1003
|
+
function measureRms(buffer) {
|
|
1004
|
+
let sumSq = 0;
|
|
1005
|
+
let count = 0;
|
|
1006
|
+
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
|
1007
|
+
const data = buffer.getChannelData(c);
|
|
1008
|
+
for (let i = 0; i < data.length; i++) sumSq += data[i] * data[i];
|
|
1009
|
+
count += data.length;
|
|
1010
|
+
}
|
|
1011
|
+
if (count === 0) return 0;
|
|
1012
|
+
return Math.sqrt(sumSq / count);
|
|
1013
|
+
}
|
|
1014
|
+
function measurePeak(buffer) {
|
|
1015
|
+
let peak = 0;
|
|
1016
|
+
for (let c = 0; c < buffer.numberOfChannels; c++) {
|
|
1017
|
+
const data = buffer.getChannelData(c);
|
|
1018
|
+
for (let i = 0; i < data.length; i++) {
|
|
1019
|
+
const a = Math.abs(data[i]);
|
|
1020
|
+
if (a > peak) peak = a;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
return peak;
|
|
1024
|
+
}
|
|
1025
|
+
function scaleBuffer(src, gain) {
|
|
1026
|
+
for (let c = 0; c < src.numberOfChannels; c++) {
|
|
1027
|
+
const data = src.getChannelData(c);
|
|
1028
|
+
for (let i = 0; i < data.length; i++) data[i] = data[i] * gain;
|
|
1029
|
+
}
|
|
1030
|
+
return src;
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
// src/runtime/scheduler.ts
|
|
1034
|
+
var Scheduler = class {
|
|
1035
|
+
constructor(host) {
|
|
1036
|
+
this.host = host;
|
|
1037
|
+
}
|
|
1038
|
+
host;
|
|
1039
|
+
tasks = [];
|
|
1040
|
+
timer = null;
|
|
1041
|
+
scheduleAt(audioTime, fn) {
|
|
1042
|
+
const task = { audioTime, fn, cancelled: false };
|
|
1043
|
+
this.tasks.push(task);
|
|
1044
|
+
this.tasks.sort((a, b) => a.audioTime - b.audioTime);
|
|
1045
|
+
this.reschedule();
|
|
1046
|
+
return () => {
|
|
1047
|
+
task.cancelled = true;
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
reschedule() {
|
|
1051
|
+
if (this.timer != null) {
|
|
1052
|
+
clearTimeout(this.timer);
|
|
1053
|
+
this.timer = null;
|
|
1054
|
+
}
|
|
1055
|
+
const next = this.tasks.find((t) => !t.cancelled);
|
|
1056
|
+
if (!next) return;
|
|
1057
|
+
const now = this.host.now;
|
|
1058
|
+
const delayMs = Math.max(0, (next.audioTime - now) * 1e3);
|
|
1059
|
+
this.timer = setTimeout(() => this.tick(), delayMs);
|
|
1060
|
+
}
|
|
1061
|
+
tick() {
|
|
1062
|
+
this.timer = null;
|
|
1063
|
+
const now = this.host.now;
|
|
1064
|
+
const due = [];
|
|
1065
|
+
const remaining = [];
|
|
1066
|
+
for (const t of this.tasks) {
|
|
1067
|
+
if (t.cancelled) continue;
|
|
1068
|
+
if (t.audioTime <= now) due.push(t);
|
|
1069
|
+
else remaining.push(t);
|
|
1070
|
+
}
|
|
1071
|
+
this.tasks = remaining;
|
|
1072
|
+
for (const t of due) {
|
|
1073
|
+
try {
|
|
1074
|
+
t.fn();
|
|
1075
|
+
} catch (e) {
|
|
1076
|
+
console.error("[zvuk] scheduled task threw", e);
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
this.reschedule();
|
|
1080
|
+
}
|
|
1081
|
+
dispose() {
|
|
1082
|
+
if (this.timer != null) clearTimeout(this.timer);
|
|
1083
|
+
this.timer = null;
|
|
1084
|
+
this.tasks = [];
|
|
1085
|
+
}
|
|
1086
|
+
};
|
|
1087
|
+
|
|
1088
|
+
// src/sources/voice.ts
|
|
1089
|
+
var Voice = class _Voice {
|
|
1090
|
+
id;
|
|
1091
|
+
priority;
|
|
1092
|
+
bus;
|
|
1093
|
+
startedAt;
|
|
1094
|
+
/** Name of the Sound that spawned this voice (if any). Used for crossfade. */
|
|
1095
|
+
sourceName;
|
|
1096
|
+
/** Resolves when playback finishes (natural end, stop(), or abort). */
|
|
1097
|
+
ended;
|
|
1098
|
+
ctx;
|
|
1099
|
+
gain;
|
|
1100
|
+
source;
|
|
1101
|
+
buffer;
|
|
1102
|
+
loop;
|
|
1103
|
+
basePitch;
|
|
1104
|
+
done = false;
|
|
1105
|
+
paused = false;
|
|
1106
|
+
resolveEnded;
|
|
1107
|
+
cueListeners = /* @__PURE__ */ new Set();
|
|
1108
|
+
startCtxTime;
|
|
1109
|
+
pausedOffset = 0;
|
|
1110
|
+
currentOffset = 0;
|
|
1111
|
+
_spatializer;
|
|
1112
|
+
startOffset;
|
|
1113
|
+
regionDuration;
|
|
1114
|
+
loopStart;
|
|
1115
|
+
loopEnd;
|
|
1116
|
+
regionTimer = null;
|
|
1117
|
+
static nextId = 1;
|
|
1118
|
+
constructor(deps) {
|
|
1119
|
+
const { ctx, buffer, destination, options } = deps;
|
|
1120
|
+
this.id = _Voice.nextId++;
|
|
1121
|
+
this.ctx = ctx;
|
|
1122
|
+
this.priority = options.priority ?? 0;
|
|
1123
|
+
this.bus = options.bus;
|
|
1124
|
+
this.sourceName = deps.sourceName;
|
|
1125
|
+
this.startedAt = ctx.currentTime;
|
|
1126
|
+
this.buffer = buffer;
|
|
1127
|
+
this.loop = options.loop ?? false;
|
|
1128
|
+
this.basePitch = resolveJittered(options.pitch ?? 1, 1);
|
|
1129
|
+
this._spatializer = deps.spatializer;
|
|
1130
|
+
this.startOffset = options.offset ?? 0;
|
|
1131
|
+
this.currentOffset = this.startOffset;
|
|
1132
|
+
this.regionDuration = options.duration;
|
|
1133
|
+
this.loopStart = options.loopStart;
|
|
1134
|
+
this.loopEnd = options.loopEnd;
|
|
1135
|
+
this.gain = ctx.createGain();
|
|
1136
|
+
const initialVolume = resolveJittered(options.volume ?? 1);
|
|
1137
|
+
this.gain.gain.value = clamp012(initialVolume);
|
|
1138
|
+
this.gain.connect(destination);
|
|
1139
|
+
this.source = this.createSourceNode(this.basePitch);
|
|
1140
|
+
this.startCtxTime = ctx.currentTime;
|
|
1141
|
+
this.ended = new Promise((resolve) => {
|
|
1142
|
+
this.resolveEnded = resolve;
|
|
1143
|
+
});
|
|
1144
|
+
this.bindSourceLifecycle(this.source, deps.onEnded);
|
|
1145
|
+
if (options.signal) {
|
|
1146
|
+
if (options.signal.aborted) {
|
|
1147
|
+
queueMicrotask(() => this.stop());
|
|
1148
|
+
} else {
|
|
1149
|
+
options.signal.addEventListener("abort", () => this.stop(), { once: true });
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
try {
|
|
1153
|
+
this.source.start(0, this.startOffset);
|
|
1154
|
+
} catch {
|
|
1155
|
+
}
|
|
1156
|
+
this.armRegionTimer(this.regionDuration);
|
|
1157
|
+
queueMicrotask(() => this.emit("started"));
|
|
1158
|
+
void this.ended.then(() => deps.onEnded(this));
|
|
1159
|
+
}
|
|
1160
|
+
fade(opts) {
|
|
1161
|
+
const param = this.gain.gain;
|
|
1162
|
+
const now = this.ctx.currentTime;
|
|
1163
|
+
applyRamp(param, now, clamp012(opts.to), opts.ms, opts.curve ?? "linear");
|
|
1164
|
+
return new Promise((res) => setTimeout(res, Math.max(0, opts.ms)));
|
|
1165
|
+
}
|
|
1166
|
+
stop() {
|
|
1167
|
+
if (this.done) return;
|
|
1168
|
+
try {
|
|
1169
|
+
this.source.stop();
|
|
1170
|
+
} catch {
|
|
1171
|
+
}
|
|
1172
|
+
this.finish("ended");
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Pause this voice. Tracks the playback offset so resume() picks up
|
|
1176
|
+
* where it left off. No-op on a finished voice.
|
|
1177
|
+
*/
|
|
1178
|
+
pause() {
|
|
1179
|
+
if (this.done || this.paused) return;
|
|
1180
|
+
const offset = this.computeOffset();
|
|
1181
|
+
this.pausedOffset = offset;
|
|
1182
|
+
this.currentOffset = offset;
|
|
1183
|
+
this.paused = true;
|
|
1184
|
+
if (this.regionTimer != null) {
|
|
1185
|
+
clearTimeout(this.regionTimer);
|
|
1186
|
+
this.regionTimer = null;
|
|
1187
|
+
}
|
|
1188
|
+
try {
|
|
1189
|
+
this.source.onended = null;
|
|
1190
|
+
this.source.stop();
|
|
1191
|
+
} catch {
|
|
1192
|
+
}
|
|
1193
|
+
try {
|
|
1194
|
+
this.source.disconnect();
|
|
1195
|
+
} catch {
|
|
1196
|
+
}
|
|
1197
|
+
this.emit("paused");
|
|
1198
|
+
}
|
|
1199
|
+
/** Resume from the offset captured on pause(). No-op when not paused. */
|
|
1200
|
+
resume() {
|
|
1201
|
+
if (this.done || !this.paused) return;
|
|
1202
|
+
this.paused = false;
|
|
1203
|
+
this.source = this.createSourceNode(this.basePitch);
|
|
1204
|
+
this.bindSourceLifecycle(this.source, () => {
|
|
1205
|
+
});
|
|
1206
|
+
this.startCtxTime = this.ctx.currentTime;
|
|
1207
|
+
try {
|
|
1208
|
+
this.source.start(0, this.pausedOffset);
|
|
1209
|
+
} catch {
|
|
1210
|
+
}
|
|
1211
|
+
if (this.regionDuration != null) {
|
|
1212
|
+
const consumed = Math.max(0, this.pausedOffset - this.startOffset);
|
|
1213
|
+
const remaining = Math.max(0, this.regionDuration - consumed);
|
|
1214
|
+
this.armRegionTimer(remaining);
|
|
1215
|
+
}
|
|
1216
|
+
this.emit("resumed");
|
|
1217
|
+
}
|
|
1218
|
+
/** Whether the voice is currently paused (and thus retaining its offset). */
|
|
1219
|
+
get isPaused() {
|
|
1220
|
+
return this.paused;
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Live playback-rate setter. Optional ramp via curve.
|
|
1224
|
+
* Setting while paused only updates the value used on the next start.
|
|
1225
|
+
*/
|
|
1226
|
+
setPlaybackRate(rate, opts = {}) {
|
|
1227
|
+
if (this.done) return;
|
|
1228
|
+
const r = Math.max(0, rate);
|
|
1229
|
+
const ms = Math.max(0, opts.ms ?? 0);
|
|
1230
|
+
if (!this.paused) {
|
|
1231
|
+
this.currentOffset = this.computeOffset();
|
|
1232
|
+
this.startCtxTime = this.ctx.currentTime;
|
|
1233
|
+
}
|
|
1234
|
+
this.basePitch = r;
|
|
1235
|
+
if (this.paused) return;
|
|
1236
|
+
const param = this.source.playbackRate;
|
|
1237
|
+
if (ms === 0) {
|
|
1238
|
+
param.value = r;
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
applyRamp(param, this.ctx.currentTime, r, ms, opts.curve ?? "linear");
|
|
1242
|
+
}
|
|
1243
|
+
get playbackRate() {
|
|
1244
|
+
return this.basePitch;
|
|
1245
|
+
}
|
|
1246
|
+
/** The Spatializer attached to this voice (if any). Use for live setPan/setPosition. */
|
|
1247
|
+
get spatializer() {
|
|
1248
|
+
return this._spatializer;
|
|
1249
|
+
}
|
|
1250
|
+
/** Async iterator of lifecycle cues — yields started, optional paused, ended. */
|
|
1251
|
+
async *cues() {
|
|
1252
|
+
const queue = [];
|
|
1253
|
+
let waiter = null;
|
|
1254
|
+
const push = (c) => {
|
|
1255
|
+
if (waiter) {
|
|
1256
|
+
const w = waiter;
|
|
1257
|
+
waiter = null;
|
|
1258
|
+
w({ value: c, done: false });
|
|
1259
|
+
} else {
|
|
1260
|
+
queue.push(c);
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1263
|
+
const sub = (c) => push(c);
|
|
1264
|
+
this.cueListeners.add(sub);
|
|
1265
|
+
try {
|
|
1266
|
+
while (true) {
|
|
1267
|
+
if (queue.length > 0) {
|
|
1268
|
+
const next2 = queue.shift();
|
|
1269
|
+
yield next2;
|
|
1270
|
+
if (next2 === "ended") return;
|
|
1271
|
+
continue;
|
|
1272
|
+
}
|
|
1273
|
+
if (this.done) return;
|
|
1274
|
+
const next = await new Promise((res) => {
|
|
1275
|
+
waiter = res;
|
|
1276
|
+
});
|
|
1277
|
+
if (next.done) return;
|
|
1278
|
+
yield next.value;
|
|
1279
|
+
if (next.value === "ended") return;
|
|
1280
|
+
}
|
|
1281
|
+
} finally {
|
|
1282
|
+
this.cueListeners.delete(sub);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
finish(reason, hook) {
|
|
1286
|
+
if (this.done) return;
|
|
1287
|
+
this.done = true;
|
|
1288
|
+
if (this.regionTimer != null) {
|
|
1289
|
+
clearTimeout(this.regionTimer);
|
|
1290
|
+
this.regionTimer = null;
|
|
1291
|
+
}
|
|
1292
|
+
try {
|
|
1293
|
+
this.source.disconnect();
|
|
1294
|
+
this.gain.disconnect();
|
|
1295
|
+
} catch {
|
|
1296
|
+
}
|
|
1297
|
+
this.emit(reason);
|
|
1298
|
+
this.resolveEnded();
|
|
1299
|
+
hook?.(this);
|
|
1300
|
+
}
|
|
1301
|
+
emit(c) {
|
|
1302
|
+
for (const fn of this.cueListeners) fn(c);
|
|
1303
|
+
}
|
|
1304
|
+
createSourceNode(rate) {
|
|
1305
|
+
const src = this.ctx.createBufferSource();
|
|
1306
|
+
src.buffer = this.buffer;
|
|
1307
|
+
src.loop = this.loop;
|
|
1308
|
+
if (this.loop && this.loopStart != null) src.loopStart = this.loopStart;
|
|
1309
|
+
if (this.loop && this.loopEnd != null) src.loopEnd = this.loopEnd;
|
|
1310
|
+
src.playbackRate.value = rate;
|
|
1311
|
+
src.connect(this.gain);
|
|
1312
|
+
return src;
|
|
1313
|
+
}
|
|
1314
|
+
armRegionTimer(remainingSec) {
|
|
1315
|
+
if (this.regionTimer != null) {
|
|
1316
|
+
clearTimeout(this.regionTimer);
|
|
1317
|
+
this.regionTimer = null;
|
|
1318
|
+
}
|
|
1319
|
+
if (remainingSec == null) return;
|
|
1320
|
+
const ms = Math.max(0, remainingSec * 1e3) / Math.max(1e-4, this.basePitch);
|
|
1321
|
+
this.regionTimer = setTimeout(() => {
|
|
1322
|
+
this.regionTimer = null;
|
|
1323
|
+
if (!this.done) this.stop();
|
|
1324
|
+
}, ms);
|
|
1325
|
+
}
|
|
1326
|
+
bindSourceLifecycle(src, hook) {
|
|
1327
|
+
src.onended = () => {
|
|
1328
|
+
if (this.paused) return;
|
|
1329
|
+
if (!src.loop) this.finish("ended", hook);
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
computeOffset() {
|
|
1333
|
+
if (this.paused) return this.pausedOffset;
|
|
1334
|
+
const elapsed = (this.ctx.currentTime - this.startCtxTime) * this.basePitch;
|
|
1335
|
+
let offset = this.currentOffset + elapsed;
|
|
1336
|
+
if (this.loop) {
|
|
1337
|
+
offset = (offset % this.buffer.duration + this.buffer.duration) % this.buffer.duration;
|
|
1338
|
+
} else {
|
|
1339
|
+
offset = Math.min(offset, this.buffer.duration);
|
|
1340
|
+
}
|
|
1341
|
+
return offset;
|
|
1342
|
+
}
|
|
1343
|
+
};
|
|
1344
|
+
function resolveJittered(v, base = 1) {
|
|
1345
|
+
if (typeof v === "number") return v;
|
|
1346
|
+
if (!v || v.jitter == null) return base;
|
|
1347
|
+
const j = v.jitter;
|
|
1348
|
+
return base + (Math.random() * 2 - 1) * j;
|
|
1349
|
+
}
|
|
1350
|
+
function clamp012(v) {
|
|
1351
|
+
if (Number.isNaN(v)) return 0;
|
|
1352
|
+
return Math.min(1, Math.max(0, v));
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
// src/sources/sound.ts
|
|
1356
|
+
var Sound = class {
|
|
1357
|
+
name;
|
|
1358
|
+
deps;
|
|
1359
|
+
constructor(name, deps) {
|
|
1360
|
+
this.name = name;
|
|
1361
|
+
this.deps = deps;
|
|
1362
|
+
}
|
|
1363
|
+
get duration() {
|
|
1364
|
+
return this.deps.buffer.duration;
|
|
1365
|
+
}
|
|
1366
|
+
play(options = {}) {
|
|
1367
|
+
const bus = options.bus ?? this.deps.defaultBus;
|
|
1368
|
+
const busInput = this.deps.resolveBusInput(bus);
|
|
1369
|
+
const spatializer = this.deps.resolveSpatializer?.(bus, options.spatializer);
|
|
1370
|
+
const destination = spatializer ? spatializer.connectInto(busInput) : busInput;
|
|
1371
|
+
const voice = new Voice({
|
|
1372
|
+
ctx: this.deps.ctx,
|
|
1373
|
+
buffer: this.deps.buffer,
|
|
1374
|
+
destination,
|
|
1375
|
+
options: { ...options, bus },
|
|
1376
|
+
spatializer,
|
|
1377
|
+
sourceName: this.name,
|
|
1378
|
+
onEnded: (v) => {
|
|
1379
|
+
this.deps.releaseVoice(v, bus);
|
|
1380
|
+
spatializer?.dispose();
|
|
1381
|
+
}
|
|
1382
|
+
});
|
|
1383
|
+
this.deps.trackVoice(voice, bus);
|
|
1384
|
+
const accepted = this.deps.applyConcurrency?.(voice, bus) ?? true;
|
|
1385
|
+
if (!accepted) {
|
|
1386
|
+
voice.stop();
|
|
1387
|
+
}
|
|
1388
|
+
return voice;
|
|
1389
|
+
}
|
|
1390
|
+
};
|
|
1391
|
+
|
|
1392
|
+
// src/sources/sprite.ts
|
|
1393
|
+
var Sprite = class {
|
|
1394
|
+
name;
|
|
1395
|
+
regions;
|
|
1396
|
+
sound;
|
|
1397
|
+
constructor(name, sound, regions) {
|
|
1398
|
+
this.name = name;
|
|
1399
|
+
this.sound = sound;
|
|
1400
|
+
this.regions = { ...regions };
|
|
1401
|
+
}
|
|
1402
|
+
/** Region names defined on this sprite. */
|
|
1403
|
+
list() {
|
|
1404
|
+
return Object.keys(this.regions);
|
|
1405
|
+
}
|
|
1406
|
+
has(region) {
|
|
1407
|
+
return region in this.regions;
|
|
1408
|
+
}
|
|
1409
|
+
region(name) {
|
|
1410
|
+
const r = this.regions[name];
|
|
1411
|
+
if (!r) throw new SoundNotFoundError(`${this.name}#${name}`);
|
|
1412
|
+
return r;
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* Spawn a Voice playing the named region. The voice stops itself after
|
|
1416
|
+
* `region.duration` seconds via an internal scheduleAt — the underlying
|
|
1417
|
+
* AudioBufferSourceNode is one big buffer, so we can't rely on its
|
|
1418
|
+
* natural-end event for region timing.
|
|
1419
|
+
*/
|
|
1420
|
+
play(region, options = {}) {
|
|
1421
|
+
const r = this.region(region);
|
|
1422
|
+
const loop = options.loop ?? r.loop ?? false;
|
|
1423
|
+
const voice = this.sound.play({
|
|
1424
|
+
...options,
|
|
1425
|
+
loop,
|
|
1426
|
+
offset: r.start,
|
|
1427
|
+
duration: r.duration,
|
|
1428
|
+
loopStart: r.start,
|
|
1429
|
+
loopEnd: r.start + r.duration
|
|
1430
|
+
});
|
|
1431
|
+
return voice;
|
|
1432
|
+
}
|
|
1433
|
+
};
|
|
1434
|
+
|
|
1435
|
+
// src/sources/stream.ts
|
|
1436
|
+
var StreamSound = class {
|
|
1437
|
+
name;
|
|
1438
|
+
ctx;
|
|
1439
|
+
url;
|
|
1440
|
+
destination;
|
|
1441
|
+
el = null;
|
|
1442
|
+
node = null;
|
|
1443
|
+
gain = null;
|
|
1444
|
+
disposed = false;
|
|
1445
|
+
constructor(name, ctx, url, destination) {
|
|
1446
|
+
this.name = name;
|
|
1447
|
+
this.ctx = ctx;
|
|
1448
|
+
this.url = url;
|
|
1449
|
+
this.destination = destination;
|
|
1450
|
+
}
|
|
1451
|
+
/** Lazily construct the <audio> element + media-element source on first use. */
|
|
1452
|
+
ensure() {
|
|
1453
|
+
if (this.el) return;
|
|
1454
|
+
if (this.disposed) return;
|
|
1455
|
+
if (typeof document === "undefined" || typeof Audio === "undefined") {
|
|
1456
|
+
return;
|
|
1457
|
+
}
|
|
1458
|
+
const el = new Audio();
|
|
1459
|
+
el.src = this.url;
|
|
1460
|
+
el.crossOrigin = "anonymous";
|
|
1461
|
+
el.preload = "auto";
|
|
1462
|
+
const create = this.ctx.createMediaElementSource;
|
|
1463
|
+
if (typeof create !== "function") {
|
|
1464
|
+
this.el = el;
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const node = create.call(this.ctx, el);
|
|
1468
|
+
const gain = this.ctx.createGain();
|
|
1469
|
+
node.connect(gain);
|
|
1470
|
+
gain.connect(this.destination);
|
|
1471
|
+
this.el = el;
|
|
1472
|
+
this.node = node;
|
|
1473
|
+
this.gain = gain;
|
|
1474
|
+
}
|
|
1475
|
+
async play(options = {}) {
|
|
1476
|
+
this.ensure();
|
|
1477
|
+
if (!this.el) return;
|
|
1478
|
+
if (this.gain) this.gain.gain.value = clamp013(options.volume ?? 1);
|
|
1479
|
+
this.el.loop = options.loop ?? false;
|
|
1480
|
+
try {
|
|
1481
|
+
await this.el.play();
|
|
1482
|
+
} catch {
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
pause() {
|
|
1486
|
+
this.el?.pause();
|
|
1487
|
+
}
|
|
1488
|
+
stop() {
|
|
1489
|
+
if (!this.el) return;
|
|
1490
|
+
this.el.pause();
|
|
1491
|
+
try {
|
|
1492
|
+
this.el.currentTime = 0;
|
|
1493
|
+
} catch {
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
seek(seconds) {
|
|
1497
|
+
if (!this.el) return;
|
|
1498
|
+
try {
|
|
1499
|
+
this.el.currentTime = Math.max(0, seconds);
|
|
1500
|
+
} catch {
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
get currentTime() {
|
|
1504
|
+
return this.el?.currentTime ?? 0;
|
|
1505
|
+
}
|
|
1506
|
+
get duration() {
|
|
1507
|
+
return this.el?.duration ?? 0;
|
|
1508
|
+
}
|
|
1509
|
+
get paused() {
|
|
1510
|
+
return this.el?.paused ?? true;
|
|
1511
|
+
}
|
|
1512
|
+
setVolume(v) {
|
|
1513
|
+
if (this.gain) this.gain.gain.value = clamp013(v);
|
|
1514
|
+
}
|
|
1515
|
+
fade(opts) {
|
|
1516
|
+
if (!this.gain) return Promise.resolve();
|
|
1517
|
+
applyRamp(this.gain.gain, this.ctx.currentTime, clamp013(opts.to), opts.ms, opts.curve ?? "linear");
|
|
1518
|
+
return new Promise((res) => setTimeout(res, Math.max(0, opts.ms)));
|
|
1519
|
+
}
|
|
1520
|
+
dispose() {
|
|
1521
|
+
this.disposed = true;
|
|
1522
|
+
try {
|
|
1523
|
+
this.node?.disconnect();
|
|
1524
|
+
this.gain?.disconnect();
|
|
1525
|
+
} catch {
|
|
1526
|
+
}
|
|
1527
|
+
if (this.el) {
|
|
1528
|
+
this.el.pause();
|
|
1529
|
+
this.el.src = "";
|
|
1530
|
+
}
|
|
1531
|
+
this.el = null;
|
|
1532
|
+
this.node = null;
|
|
1533
|
+
this.gain = null;
|
|
1534
|
+
}
|
|
1535
|
+
};
|
|
1536
|
+
function clamp013(v) {
|
|
1537
|
+
if (Number.isNaN(v)) return 0;
|
|
1538
|
+
return Math.min(1, Math.max(0, v));
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
// src/spatial/spatializer.ts
|
|
1542
|
+
var Spatializer = class {
|
|
1543
|
+
node;
|
|
1544
|
+
kind;
|
|
1545
|
+
constructor(ctx, opts) {
|
|
1546
|
+
if (opts.position) {
|
|
1547
|
+
const panner = ctx.createPanner();
|
|
1548
|
+
panner.panningModel = "HRTF";
|
|
1549
|
+
panner.distanceModel = "inverse";
|
|
1550
|
+
panner.refDistance = 1;
|
|
1551
|
+
panner.maxDistance = 1e3;
|
|
1552
|
+
panner.rolloffFactor = 1;
|
|
1553
|
+
const [x, y, z] = opts.position;
|
|
1554
|
+
this.setPanner3D(panner, x, y, z);
|
|
1555
|
+
this.node = panner;
|
|
1556
|
+
this.kind = "3d";
|
|
1557
|
+
} else {
|
|
1558
|
+
const sp = ctx.createStereoPanner();
|
|
1559
|
+
sp.pan.value = clampPan(opts.pan ?? 0);
|
|
1560
|
+
this.node = sp;
|
|
1561
|
+
this.kind = "2d";
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
setPan(pan) {
|
|
1565
|
+
if (this.kind !== "2d") return;
|
|
1566
|
+
this.node.pan.value = clampPan(pan);
|
|
1567
|
+
}
|
|
1568
|
+
setPosition(x, y, z) {
|
|
1569
|
+
if (this.kind !== "3d") return;
|
|
1570
|
+
this.setPanner3D(this.node, x, y, z);
|
|
1571
|
+
}
|
|
1572
|
+
/** Connects internal node into `dest` and returns the input the Voice should use. */
|
|
1573
|
+
connectInto(dest) {
|
|
1574
|
+
this.node.connect(dest);
|
|
1575
|
+
return this.node;
|
|
1576
|
+
}
|
|
1577
|
+
dispose() {
|
|
1578
|
+
try {
|
|
1579
|
+
this.node.disconnect();
|
|
1580
|
+
} catch {
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
setPanner3D(p, x, y, z) {
|
|
1584
|
+
if (typeof p.positionX?.setValueAtTime === "function") {
|
|
1585
|
+
const now = p.context.currentTime;
|
|
1586
|
+
p.positionX.setValueAtTime(x, now);
|
|
1587
|
+
p.positionY.setValueAtTime(y, now);
|
|
1588
|
+
p.positionZ.setValueAtTime(z, now);
|
|
1589
|
+
} else {
|
|
1590
|
+
const legacy = p;
|
|
1591
|
+
legacy.setPosition?.(x, y, z);
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
};
|
|
1595
|
+
function clampPan(v) {
|
|
1596
|
+
return Math.max(-1, Math.min(1, v));
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
// src/mixer/master.ts
|
|
1600
|
+
var Master = class {
|
|
1601
|
+
input;
|
|
1602
|
+
headroomDb;
|
|
1603
|
+
ctx;
|
|
1604
|
+
limiterNode = null;
|
|
1605
|
+
limiterCfg;
|
|
1606
|
+
destination;
|
|
1607
|
+
constructor(ctx, config = {}) {
|
|
1608
|
+
this.ctx = ctx;
|
|
1609
|
+
this.input = ctx.createGain();
|
|
1610
|
+
this.headroomDb = config.headroom ?? 0;
|
|
1611
|
+
this.input.gain.value = dbToLinear(this.headroomDb);
|
|
1612
|
+
this.destination = ctx.destination;
|
|
1613
|
+
this.limiterCfg = config.limiter ?? null;
|
|
1614
|
+
this.rewire();
|
|
1615
|
+
}
|
|
1616
|
+
setHeadroom(db) {
|
|
1617
|
+
this.headroomDb = db;
|
|
1618
|
+
this.input.gain.value = dbToLinear(db);
|
|
1619
|
+
}
|
|
1620
|
+
get headroom() {
|
|
1621
|
+
return this.headroomDb;
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Enable or update the master limiter. Pass `null` to disable.
|
|
1625
|
+
* The limiter sits between master gain and destination.
|
|
1626
|
+
*/
|
|
1627
|
+
setLimiter(cfg) {
|
|
1628
|
+
this.limiterCfg = cfg;
|
|
1629
|
+
this.rewire();
|
|
1630
|
+
}
|
|
1631
|
+
/** Live gain reduction in dB. 0 if no limiter is engaged. */
|
|
1632
|
+
get reduction() {
|
|
1633
|
+
return this.limiterNode?.reduction ?? 0;
|
|
1634
|
+
}
|
|
1635
|
+
dispose() {
|
|
1636
|
+
try {
|
|
1637
|
+
this.input.disconnect();
|
|
1638
|
+
this.limiterNode?.disconnect();
|
|
1639
|
+
} catch {
|
|
1640
|
+
}
|
|
1641
|
+
this.limiterNode = null;
|
|
1642
|
+
}
|
|
1643
|
+
rewire() {
|
|
1644
|
+
try {
|
|
1645
|
+
this.input.disconnect();
|
|
1646
|
+
this.limiterNode?.disconnect();
|
|
1647
|
+
} catch {
|
|
1648
|
+
}
|
|
1649
|
+
this.limiterNode = null;
|
|
1650
|
+
if (!this.limiterCfg) {
|
|
1651
|
+
this.input.connect(this.destination);
|
|
1652
|
+
return;
|
|
1653
|
+
}
|
|
1654
|
+
const cfg = this.limiterCfg;
|
|
1655
|
+
const limiter = this.ctx.createDynamicsCompressor();
|
|
1656
|
+
limiter.threshold.value = cfg.threshold ?? -1;
|
|
1657
|
+
limiter.knee.value = 0;
|
|
1658
|
+
limiter.ratio.value = Math.max(20, cfg.ratio ?? 20);
|
|
1659
|
+
limiter.attack.value = cfg.attack ?? 1e-3;
|
|
1660
|
+
limiter.release.value = cfg.release ?? 0.05;
|
|
1661
|
+
this.input.connect(limiter);
|
|
1662
|
+
limiter.connect(this.destination);
|
|
1663
|
+
this.limiterNode = limiter;
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
1666
|
+
function dbToLinear(db) {
|
|
1667
|
+
return 10 ** (db / 20);
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
// src/mixer/snapshot.ts
|
|
1671
|
+
var Snapshot = class {
|
|
1672
|
+
name;
|
|
1673
|
+
state;
|
|
1674
|
+
getBus;
|
|
1675
|
+
getParam;
|
|
1676
|
+
constructor(name, state, getBus, getParam) {
|
|
1677
|
+
this.name = name;
|
|
1678
|
+
this.state = state;
|
|
1679
|
+
this.getBus = getBus;
|
|
1680
|
+
this.getParam = getParam;
|
|
1681
|
+
}
|
|
1682
|
+
apply(opts = {}) {
|
|
1683
|
+
const fadeMs = opts.fadeMs ?? 0;
|
|
1684
|
+
const tasks = [];
|
|
1685
|
+
for (const [name, bs] of Object.entries(this.state.buses)) {
|
|
1686
|
+
const bus = this.getBus(name);
|
|
1687
|
+
if (!bus) continue;
|
|
1688
|
+
bus.muted = bs.muted;
|
|
1689
|
+
tasks.push(bus.fadeTo(bs.level, fadeMs));
|
|
1690
|
+
}
|
|
1691
|
+
for (const [name, value] of Object.entries(this.state.parameters)) {
|
|
1692
|
+
const param = this.getParam(name);
|
|
1693
|
+
if (!param) continue;
|
|
1694
|
+
param.set(value);
|
|
1695
|
+
}
|
|
1696
|
+
return Promise.all(tasks).then(() => void 0);
|
|
1697
|
+
}
|
|
1698
|
+
};
|
|
1699
|
+
|
|
1700
|
+
// src/mixer/engine.ts
|
|
1701
|
+
function createEngine(config = {}) {
|
|
1702
|
+
return new EngineImpl(config);
|
|
1703
|
+
}
|
|
1704
|
+
var EngineImpl = class {
|
|
1705
|
+
host = new AudioContextHost();
|
|
1706
|
+
decoder = new Decoder(() => this.host.touch());
|
|
1707
|
+
scheduler = null;
|
|
1708
|
+
master = null;
|
|
1709
|
+
buses = /* @__PURE__ */ new Map();
|
|
1710
|
+
busOrder = [];
|
|
1711
|
+
sounds = /* @__PURE__ */ new Map();
|
|
1712
|
+
sprites = /* @__PURE__ */ new Map();
|
|
1713
|
+
streams = /* @__PURE__ */ new Map();
|
|
1714
|
+
voices = /* @__PURE__ */ new Map();
|
|
1715
|
+
parameters = /* @__PURE__ */ new Map();
|
|
1716
|
+
config;
|
|
1717
|
+
constructor(config) {
|
|
1718
|
+
this.config = config;
|
|
1719
|
+
const declared = Object.keys(config.buses ?? {});
|
|
1720
|
+
this.busOrder = declared.length > 0 ? declared : ["default"];
|
|
1721
|
+
for (const name of this.busOrder) this.voices.set(name, /* @__PURE__ */ new Set());
|
|
1722
|
+
}
|
|
1723
|
+
get state() {
|
|
1724
|
+
return this.host.state;
|
|
1725
|
+
}
|
|
1726
|
+
get now() {
|
|
1727
|
+
return this.host.now;
|
|
1728
|
+
}
|
|
1729
|
+
get context() {
|
|
1730
|
+
return this.host.touch();
|
|
1731
|
+
}
|
|
1732
|
+
async unlock() {
|
|
1733
|
+
await this.host.unlock();
|
|
1734
|
+
this.ensureGraph();
|
|
1735
|
+
}
|
|
1736
|
+
async close() {
|
|
1737
|
+
if (this.host.state === "closed") return;
|
|
1738
|
+
for (const set of this.voices.values()) {
|
|
1739
|
+
for (const v of set) v.stop();
|
|
1740
|
+
set.clear();
|
|
1741
|
+
}
|
|
1742
|
+
this.scheduler?.dispose();
|
|
1743
|
+
this.scheduler = null;
|
|
1744
|
+
for (const bus of this.buses.values()) {
|
|
1745
|
+
for (const fx of bus.fx()) fx.dispose();
|
|
1746
|
+
bus.dispose();
|
|
1747
|
+
}
|
|
1748
|
+
this.buses.clear();
|
|
1749
|
+
this.master?.dispose();
|
|
1750
|
+
this.master = null;
|
|
1751
|
+
this.sounds.clear();
|
|
1752
|
+
this.sprites.clear();
|
|
1753
|
+
for (const s of this.streams.values()) s.dispose();
|
|
1754
|
+
this.streams.clear();
|
|
1755
|
+
this.parameters.clear();
|
|
1756
|
+
this.decoder.clear();
|
|
1757
|
+
await this.host.close();
|
|
1758
|
+
}
|
|
1759
|
+
async loadSound(name, url, options = {}) {
|
|
1760
|
+
if (this.host.state === "closed") throw new EngineClosedError();
|
|
1761
|
+
this.host.touch();
|
|
1762
|
+
this.ensureGraph();
|
|
1763
|
+
const resolvedUrl = typeof url === "string" ? url : pickSource(url);
|
|
1764
|
+
const decodeOpts = { signal: options.signal };
|
|
1765
|
+
let buffer = await this.decoder.load(resolvedUrl, decodeOpts);
|
|
1766
|
+
if (options.normalize) {
|
|
1767
|
+
buffer = applyLoudnessNormalization(buffer, options.normalize);
|
|
1768
|
+
}
|
|
1769
|
+
return this.createSound(name, buffer, { bus: options.bus });
|
|
1770
|
+
}
|
|
1771
|
+
async loadSprite(name, url, regions, options = {}) {
|
|
1772
|
+
const sound = await this.loadSound(`__sprite:${name}`, url, options);
|
|
1773
|
+
const sprite = new Sprite(name, sound, regions);
|
|
1774
|
+
this.sprites.set(name, sprite);
|
|
1775
|
+
return sprite;
|
|
1776
|
+
}
|
|
1777
|
+
sprite(name) {
|
|
1778
|
+
const s = this.sprites.get(name);
|
|
1779
|
+
if (!s) throw new SoundNotFoundError(suggest(name, [...this.sprites.keys()]));
|
|
1780
|
+
return s;
|
|
1781
|
+
}
|
|
1782
|
+
hasSprite(name) {
|
|
1783
|
+
return this.sprites.has(name);
|
|
1784
|
+
}
|
|
1785
|
+
loadStream(name, url, options = {}) {
|
|
1786
|
+
if (this.host.state === "closed") throw new EngineClosedError();
|
|
1787
|
+
this.host.touch();
|
|
1788
|
+
this.ensureGraph();
|
|
1789
|
+
const resolvedUrl = typeof url === "string" ? url : pickSource(url);
|
|
1790
|
+
const bus = options.bus ?? this.busOrder[0];
|
|
1791
|
+
const busObj = this.buses.get(bus);
|
|
1792
|
+
if (!busObj) throw new BusNotFoundError(suggest(bus, [...this.buses.keys()]));
|
|
1793
|
+
const stream = new StreamSound(name, this.host.touch(), resolvedUrl, busObj.input);
|
|
1794
|
+
this.streams.set(name, stream);
|
|
1795
|
+
return stream;
|
|
1796
|
+
}
|
|
1797
|
+
stream(name) {
|
|
1798
|
+
const s = this.streams.get(name);
|
|
1799
|
+
if (!s) throw new SoundNotFoundError(suggest(name, [...this.streams.keys()]));
|
|
1800
|
+
return s;
|
|
1801
|
+
}
|
|
1802
|
+
hasStream(name) {
|
|
1803
|
+
return this.streams.has(name);
|
|
1804
|
+
}
|
|
1805
|
+
crossfade(from, to, options = {}) {
|
|
1806
|
+
const ms = options.ms ?? 1500;
|
|
1807
|
+
const curve = options.curve ?? "equal-power";
|
|
1808
|
+
const toVolume = options.toVolume ?? 1;
|
|
1809
|
+
const target = this.sound(to);
|
|
1810
|
+
const newVoice = target.play({
|
|
1811
|
+
bus: options.bus,
|
|
1812
|
+
loop: options.loop ?? true,
|
|
1813
|
+
volume: 0
|
|
1814
|
+
});
|
|
1815
|
+
void newVoice.fade({ to: toVolume, ms, curve });
|
|
1816
|
+
const outgoing = this.activeVoices().filter((v) => v !== newVoice && v.sourceName === from);
|
|
1817
|
+
for (const v of outgoing) {
|
|
1818
|
+
void v.fade({ to: 0, ms, curve }).then(() => v.stop());
|
|
1819
|
+
}
|
|
1820
|
+
return newVoice;
|
|
1821
|
+
}
|
|
1822
|
+
createSound(name, buffer, options = {}) {
|
|
1823
|
+
if (this.host.state === "closed") throw new EngineClosedError();
|
|
1824
|
+
this.host.touch();
|
|
1825
|
+
this.ensureGraph();
|
|
1826
|
+
const defaultBus = options.bus ?? this.busOrder[0];
|
|
1827
|
+
if (!this.buses.has(defaultBus)) throw new BusNotFoundError(suggest(defaultBus, [...this.buses.keys()]));
|
|
1828
|
+
const sound = new Sound(name, {
|
|
1829
|
+
ctx: this.host.touch(),
|
|
1830
|
+
buffer,
|
|
1831
|
+
defaultBus,
|
|
1832
|
+
resolveBusInput: (busName) => {
|
|
1833
|
+
const bus = this.buses.get(busName);
|
|
1834
|
+
if (!bus) throw new BusNotFoundError(suggest(busName, [...this.buses.keys()]));
|
|
1835
|
+
return bus.input;
|
|
1836
|
+
},
|
|
1837
|
+
resolveSpatializer: (_busName, opts) => {
|
|
1838
|
+
if (!opts) return void 0;
|
|
1839
|
+
return new Spatializer(this.host.touch(), opts);
|
|
1840
|
+
},
|
|
1841
|
+
trackVoice: (v, busName) => {
|
|
1842
|
+
this.voices.get(busName)?.add(v);
|
|
1843
|
+
this.buses.get(busName)?.trackVoice(v);
|
|
1844
|
+
},
|
|
1845
|
+
releaseVoice: (v, busName) => {
|
|
1846
|
+
this.voices.get(busName)?.delete(v);
|
|
1847
|
+
this.buses.get(busName)?.releaseVoice(v);
|
|
1848
|
+
},
|
|
1849
|
+
applyConcurrency: (v, busName) => {
|
|
1850
|
+
const bus = this.buses.get(busName);
|
|
1851
|
+
if (!bus) return true;
|
|
1852
|
+
let rejected = false;
|
|
1853
|
+
const stolen = bus.applyConcurrencyOnSpawn(v, () => {
|
|
1854
|
+
rejected = true;
|
|
1855
|
+
});
|
|
1856
|
+
if (stolen) {
|
|
1857
|
+
this.voices.get(busName)?.delete(stolen);
|
|
1858
|
+
bus.releaseVoice(stolen);
|
|
1859
|
+
}
|
|
1860
|
+
if (rejected) {
|
|
1861
|
+
this.voices.get(busName)?.delete(v);
|
|
1862
|
+
bus.releaseVoice(v);
|
|
1863
|
+
}
|
|
1864
|
+
return !rejected;
|
|
1865
|
+
}
|
|
1866
|
+
});
|
|
1867
|
+
this.sounds.set(name, sound);
|
|
1868
|
+
return sound;
|
|
1869
|
+
}
|
|
1870
|
+
removeSound(name) {
|
|
1871
|
+
this.sounds.delete(name);
|
|
1872
|
+
}
|
|
1873
|
+
hasSound(name) {
|
|
1874
|
+
return this.sounds.has(name);
|
|
1875
|
+
}
|
|
1876
|
+
sound(name) {
|
|
1877
|
+
const s = this.sounds.get(name);
|
|
1878
|
+
if (!s) throw new SoundNotFoundError(suggest(name, [...this.sounds.keys()]));
|
|
1879
|
+
return s;
|
|
1880
|
+
}
|
|
1881
|
+
bus(name) {
|
|
1882
|
+
this.ensureGraph();
|
|
1883
|
+
const b = this.buses.get(name);
|
|
1884
|
+
if (!b) throw new BusNotFoundError(suggest(name, [...this.buses.keys()]));
|
|
1885
|
+
return b;
|
|
1886
|
+
}
|
|
1887
|
+
scheduleAt(audioTime, fn) {
|
|
1888
|
+
this.host.touch();
|
|
1889
|
+
this.ensureGraph();
|
|
1890
|
+
return this.scheduler.scheduleAt(audioTime, fn);
|
|
1891
|
+
}
|
|
1892
|
+
activeVoices() {
|
|
1893
|
+
const all = [];
|
|
1894
|
+
for (const set of this.voices.values()) for (const v of set) all.push(v);
|
|
1895
|
+
return all;
|
|
1896
|
+
}
|
|
1897
|
+
onStateChange(fn) {
|
|
1898
|
+
return this.host.onStateChange(fn);
|
|
1899
|
+
}
|
|
1900
|
+
parameter(name, initial = 0) {
|
|
1901
|
+
let p = this.parameters.get(name);
|
|
1902
|
+
if (!p) {
|
|
1903
|
+
p = new Parameter(name, initial);
|
|
1904
|
+
this.parameters.set(name, p);
|
|
1905
|
+
}
|
|
1906
|
+
return p;
|
|
1907
|
+
}
|
|
1908
|
+
captureSnapshot(name) {
|
|
1909
|
+
const buses = {};
|
|
1910
|
+
for (const [n, b] of this.buses) buses[n] = { level: b.level, muted: b.muted };
|
|
1911
|
+
const parameters = {};
|
|
1912
|
+
for (const [n, p] of this.parameters) parameters[n] = p.value;
|
|
1913
|
+
return this.snapshot(name, { buses, parameters });
|
|
1914
|
+
}
|
|
1915
|
+
snapshot(name, state) {
|
|
1916
|
+
return new Snapshot(
|
|
1917
|
+
name,
|
|
1918
|
+
state,
|
|
1919
|
+
(busName) => this.buses.get(busName),
|
|
1920
|
+
(paramName) => this.parameters.get(paramName)
|
|
1921
|
+
);
|
|
1922
|
+
}
|
|
1923
|
+
/**
|
|
1924
|
+
* Lazily instantiate the bus graph against the live AudioContext. Called
|
|
1925
|
+
* from any path that touches the context (unlock, loadSound, bus, ...).
|
|
1926
|
+
*/
|
|
1927
|
+
ensureGraph() {
|
|
1928
|
+
if (this.master) return;
|
|
1929
|
+
const ctx = this.host.touch();
|
|
1930
|
+
this.master = new Master(ctx, this.config.master);
|
|
1931
|
+
this.scheduler = new Scheduler(this.host);
|
|
1932
|
+
for (const name of this.busOrder) {
|
|
1933
|
+
const cfg = this.config.buses?.[name] ?? {};
|
|
1934
|
+
const bus = new Bus(ctx, name, cfg);
|
|
1935
|
+
bus.output.connect(this.master.input);
|
|
1936
|
+
this.buses.set(name, bus);
|
|
1937
|
+
if (!this.voices.has(name)) this.voices.set(name, /* @__PURE__ */ new Set());
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
};
|
|
1941
|
+
function suggest(missing, candidates) {
|
|
1942
|
+
if (candidates.length === 0) return missing;
|
|
1943
|
+
let best = null;
|
|
1944
|
+
let bestDist = Infinity;
|
|
1945
|
+
for (const c of candidates) {
|
|
1946
|
+
const d = levenshtein(missing, c);
|
|
1947
|
+
if (d < bestDist) {
|
|
1948
|
+
bestDist = d;
|
|
1949
|
+
best = c;
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
const longest = Math.max(missing.length, best?.length ?? 0);
|
|
1953
|
+
const threshold = Math.max(1, Math.ceil(longest / 2));
|
|
1954
|
+
if (best && bestDist <= threshold) {
|
|
1955
|
+
return `${missing}"; did you mean "${best}`;
|
|
1956
|
+
}
|
|
1957
|
+
return missing;
|
|
1958
|
+
}
|
|
1959
|
+
function levenshtein(a, b) {
|
|
1960
|
+
if (a === b) return 0;
|
|
1961
|
+
if (a.length === 0) return b.length;
|
|
1962
|
+
if (b.length === 0) return a.length;
|
|
1963
|
+
const prev = new Array(b.length + 1);
|
|
1964
|
+
const curr = new Array(b.length + 1);
|
|
1965
|
+
for (let j = 0; j <= b.length; j++) prev[j] = j;
|
|
1966
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1967
|
+
curr[0] = i;
|
|
1968
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1969
|
+
const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
|
|
1970
|
+
curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
|
|
1971
|
+
}
|
|
1972
|
+
for (let j = 0; j <= b.length; j++) prev[j] = curr[j];
|
|
1973
|
+
}
|
|
1974
|
+
return prev[b.length];
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
export { BankNotLoadedError, Bus, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Parameter, Reverb, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource };
|
|
1978
|
+
//# sourceMappingURL=index.js.map
|
|
1979
|
+
//# sourceMappingURL=index.js.map
|