@avoid.quest/audio 0.0.0-stage → 0.1.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.
Files changed (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +70 -2
  3. package/dist/effects/index.d.ts +266 -0
  4. package/dist/effects/index.js +744 -0
  5. package/dist/effects/index.js.map +1 -0
  6. package/dist/errors-BT9HxDLn.js +74 -0
  7. package/dist/errors-BT9HxDLn.js.map +1 -0
  8. package/dist/errors-ChTQFwuZ.d.ts +53 -0
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.js +3 -0
  11. package/dist/midi/index.d.ts +162 -0
  12. package/dist/midi/index.js +338 -0
  13. package/dist/midi/index.js.map +1 -0
  14. package/dist/playback/index.d.ts +349 -0
  15. package/dist/playback/index.js +1372 -0
  16. package/dist/playback/index.js.map +1 -0
  17. package/dist/queue/index.d.ts +144 -0
  18. package/dist/queue/index.js +1062 -0
  19. package/dist/queue/index.js.map +1 -0
  20. package/dist/recognize/index.d.ts +161 -0
  21. package/dist/recognize/index.js +2816 -0
  22. package/dist/recognize/index.js.map +1 -0
  23. package/dist/routing/index.d.ts +140 -0
  24. package/dist/routing/index.js +678 -0
  25. package/dist/routing/index.js.map +1 -0
  26. package/dist/sync/index.d.ts +282 -0
  27. package/dist/sync/index.js +1103 -0
  28. package/dist/sync/index.js.map +1 -0
  29. package/dist/worklet-loader-BvEW0oVO.d.ts +44 -0
  30. package/dist/worklet-loader-S7R8ZAmP.js +175 -0
  31. package/dist/worklet-loader-S7R8ZAmP.js.map +1 -0
  32. package/dist/worklets/couch-live.d.ts +1 -0
  33. package/dist/worklets/couch-live.js +365 -0
  34. package/dist/worklets/couch-live.js.map +1 -0
  35. package/dist/worklets/meter.d.ts +7 -0
  36. package/dist/worklets/meter.js +80 -0
  37. package/dist/worklets/meter.js.map +1 -0
  38. package/package.json +109 -4
@@ -0,0 +1,744 @@
1
+ import { Duration, Effect, Schema, Semaphore } from "effect";
2
+ import { l as AudioUnsupportedError } from "../errors-BT9HxDLn.js";
3
+ // src/effects/native.ts
4
+ const DEFAULT_CROSSFADE_STEPS = 48;
5
+ const DEFAULT_PARAM_TIME_CONSTANT_S = .01;
6
+ const MIN_EXPONENTIAL_GAIN = 1e-4;
7
+ function cancelAndHoldParam(param, time) {
8
+ if (typeof param.cancelAndHoldAtTime === "function") try {
9
+ param.cancelAndHoldAtTime(time);
10
+ return;
11
+ } catch {}
12
+ const held = param.value;
13
+ if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(time);
14
+ if (typeof param.setValueAtTime === "function") param.setValueAtTime(held, time);
15
+ }
16
+ function scheduleParam(param, context, value, rampSeconds = 0) {
17
+ const now = context.currentTime;
18
+ if (rampSeconds <= 0) {
19
+ if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(now);
20
+ param.value = value;
21
+ return;
22
+ }
23
+ if (typeof param.linearRampToValueAtTime === "function") {
24
+ cancelAndHoldParam(param, now);
25
+ param.linearRampToValueAtTime(value, now + rampSeconds);
26
+ return;
27
+ }
28
+ if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(now);
29
+ param.value = value;
30
+ }
31
+ function applyCrossfadeCurve(param, curve, now, durationSeconds, targetValue) {
32
+ cancelAndHoldParam(param, now);
33
+ try {
34
+ param.setValueCurveAtTime(curve, now, durationSeconds);
35
+ } catch {
36
+ try {
37
+ param.setValueCurveAtTime(curve, now + 1e-4, durationSeconds);
38
+ } catch {
39
+ if (typeof param.linearRampToValueAtTime === "function") param.linearRampToValueAtTime(targetValue, now + durationSeconds);
40
+ else param.value = targetValue;
41
+ }
42
+ }
43
+ }
44
+ /**
45
+ * Generates a 48-step (`Float32Array(steps + 1)`) fade-in and fade-out gain curve pair
46
+ * for `AudioParam.setValueCurveAtTime`.
47
+ */
48
+ function createCrossfadeCurves(steps = 48, curve = "equalPower") {
49
+ const count = Math.max(2, Math.floor(steps));
50
+ const fadeIn = new Float32Array(count + 1);
51
+ const fadeOut = new Float32Array(count + 1);
52
+ for (let i = 0; i <= count; i += 1) {
53
+ const p = i / count;
54
+ if (curve === "linear") {
55
+ fadeIn[i] = p;
56
+ fadeOut[i] = 1 - p;
57
+ } else if (curve === "exponential") {
58
+ fadeIn[i] = p * p;
59
+ fadeOut[i] = (1 - p) * (1 - p);
60
+ } else {
61
+ fadeIn[i] = Math.sin(p * (Math.PI / 2));
62
+ fadeOut[i] = Math.cos(p * (Math.PI / 2));
63
+ }
64
+ }
65
+ return {
66
+ fadeIn,
67
+ fadeOut
68
+ };
69
+ }
70
+ /**
71
+ * Evaluates equal-power, linear, or exponential gains for a mix value in `[0, 1]`
72
+ * (`0` = 100% A, `1` = 100% B).
73
+ */
74
+ function computeCrossfadeGains(mix, curve = "equalPower") {
75
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(mix) ? mix : .5));
76
+ if (curve === "linear") return {
77
+ gainA: 1 - clamped,
78
+ gainB: clamped
79
+ };
80
+ if (curve === "exponential") return {
81
+ gainA: (1 - clamped) * (1 - clamped),
82
+ gainB: clamped * clamped
83
+ };
84
+ return {
85
+ gainA: Math.cos(clamped * (Math.PI / 2)),
86
+ gainB: Math.sin(clamped * (Math.PI / 2))
87
+ };
88
+ }
89
+ function createGain(context, initialGain = 1) {
90
+ const node = context.createGain();
91
+ const safeInitial = Number.isFinite(initialGain) ? Math.max(0, initialGain) : 1;
92
+ node.gain.value = safeInitial;
93
+ return {
94
+ dispose: () => {
95
+ node.disconnect();
96
+ },
97
+ getGain: () => node.gain.value,
98
+ input: node,
99
+ node,
100
+ output: node,
101
+ setGain: (value, rampSeconds = 0) => {
102
+ const clamped = Number.isFinite(value) ? Math.max(0, value) : 0;
103
+ scheduleParam(node.gain, context, clamped, rampSeconds);
104
+ return clamped;
105
+ }
106
+ };
107
+ }
108
+ function createPan(context, initialPan = 0) {
109
+ const node = context.createStereoPanner();
110
+ const safeInitial = Number.isFinite(initialPan) ? Math.max(-1, Math.min(1, initialPan)) : 0;
111
+ node.pan.value = safeInitial;
112
+ return {
113
+ dispose: () => {
114
+ node.disconnect();
115
+ },
116
+ getPan: () => node.pan.value,
117
+ input: node,
118
+ node,
119
+ output: node,
120
+ setPan: (value, rampSeconds = 0) => {
121
+ const clamped = Number.isFinite(value) ? Math.max(-1, Math.min(1, value)) : 0;
122
+ scheduleParam(node.pan, context, clamped, rampSeconds);
123
+ return clamped;
124
+ }
125
+ };
126
+ }
127
+ function createBiquadFilter(context, options = {}) {
128
+ const node = context.createBiquadFilter();
129
+ if (options.type !== void 0) node.type = options.type;
130
+ if (options.frequency !== void 0 && Number.isFinite(options.frequency)) node.frequency.value = Math.max(10, Math.min(24e3, options.frequency));
131
+ if (options.q !== void 0 && Number.isFinite(options.q)) node.Q.value = Math.max(1e-4, Math.min(1e3, options.q));
132
+ if (options.gain !== void 0 && Number.isFinite(options.gain)) node.gain.value = Math.max(-40, Math.min(40, options.gain));
133
+ if (options.detune !== void 0 && Number.isFinite(options.detune)) node.detune.value = options.detune;
134
+ return {
135
+ dispose: () => {
136
+ node.disconnect();
137
+ },
138
+ input: node,
139
+ node,
140
+ output: node,
141
+ setDetune: (cents, rampSeconds = 0) => {
142
+ const safe = Number.isFinite(cents) ? cents : 0;
143
+ scheduleParam(node.detune, context, safe, rampSeconds);
144
+ return safe;
145
+ },
146
+ setFrequency: (hz, rampSeconds = 0) => {
147
+ const nyquist = context.sampleRate / 2;
148
+ const clamped = Number.isFinite(hz) ? Math.max(10, Math.min(nyquist, hz)) : 1e3;
149
+ scheduleParam(node.frequency, context, clamped, rampSeconds);
150
+ return clamped;
151
+ },
152
+ setGain: (db, rampSeconds = 0) => {
153
+ const clamped = Number.isFinite(db) ? Math.max(-40, Math.min(40, db)) : 0;
154
+ scheduleParam(node.gain, context, clamped, rampSeconds);
155
+ return clamped;
156
+ },
157
+ setQ: (q, rampSeconds = 0) => {
158
+ const clamped = Number.isFinite(q) ? Math.max(1e-4, Math.min(1e3, q)) : 1;
159
+ scheduleParam(node.Q, context, clamped, rampSeconds);
160
+ return clamped;
161
+ },
162
+ setType: (type) => {
163
+ node.type = type;
164
+ }
165
+ };
166
+ }
167
+ /**
168
+ * Equal-power (or linear/exponential) two-input crossfader (`inputA` + `inputB` -> `output`).
169
+ */
170
+ function createCrossfade(context, initialMix = 0, defaultCurve = "equalPower") {
171
+ const inputA = context.createGain();
172
+ const inputB = context.createGain();
173
+ const output = context.createGain();
174
+ inputA.connect(output);
175
+ inputB.connect(output);
176
+ let currentMix = Math.max(0, Math.min(1, Number.isFinite(initialMix) ? initialMix : 0));
177
+ const initialGains = computeCrossfadeGains(currentMix, defaultCurve);
178
+ inputA.gain.value = initialGains.gainA;
179
+ inputB.gain.value = initialGains.gainB;
180
+ return {
181
+ dispose: () => {
182
+ inputA.disconnect();
183
+ inputB.disconnect();
184
+ output.disconnect();
185
+ },
186
+ getMix: () => currentMix,
187
+ inputA,
188
+ inputB,
189
+ output,
190
+ setMix: (mix, durationSeconds = 0, curve = defaultCurve) => {
191
+ const targetMix = Math.max(0, Math.min(1, Number.isFinite(mix) ? mix : 0));
192
+ const gains = computeCrossfadeGains(targetMix, curve);
193
+ const now = context.currentTime;
194
+ if (durationSeconds > 0 && typeof inputA.gain.setValueCurveAtTime === "function" && typeof inputB.gain.setValueCurveAtTime === "function") {
195
+ const steps = 48;
196
+ const curveA = /* @__PURE__ */ new Float32Array(49);
197
+ const curveB = /* @__PURE__ */ new Float32Array(49);
198
+ for (let i = 0; i <= steps; i += 1) {
199
+ const p = i / steps;
200
+ const stepGains = computeCrossfadeGains(currentMix + (targetMix - currentMix) * p, curve);
201
+ curveA[i] = stepGains.gainA;
202
+ curveB[i] = stepGains.gainB;
203
+ }
204
+ applyCrossfadeCurve(inputA.gain, curveA, now, durationSeconds, gains.gainA);
205
+ applyCrossfadeCurve(inputB.gain, curveB, now, durationSeconds, gains.gainB);
206
+ } else {
207
+ scheduleParam(inputA.gain, context, gains.gainA, durationSeconds);
208
+ scheduleParam(inputB.gain, context, gains.gainB, durationSeconds);
209
+ }
210
+ currentMix = targetMix;
211
+ return currentMix;
212
+ }
213
+ };
214
+ }
215
+ // src/effects/compressor.ts
216
+ const COMPRESSOR_LOOKAHEAD_SECONDS = .006;
217
+ const COMPRESSOR_PARAMETERS = {
218
+ attack: {
219
+ label: "Attack",
220
+ max: 1e3,
221
+ min: .1,
222
+ step: .1,
223
+ unit: "ms"
224
+ },
225
+ gain: {
226
+ label: "Output gain",
227
+ max: 12,
228
+ min: -12,
229
+ step: .5,
230
+ unit: "dB"
231
+ },
232
+ knee: {
233
+ label: "Knee",
234
+ max: 18,
235
+ min: 0,
236
+ step: 1,
237
+ unit: "dB"
238
+ },
239
+ ratio: {
240
+ label: "Ratio",
241
+ max: 20,
242
+ min: 1,
243
+ step: .1,
244
+ unit: ":1"
245
+ },
246
+ release: {
247
+ label: "Release",
248
+ max: 1e3,
249
+ min: 1,
250
+ step: 1,
251
+ unit: "ms"
252
+ },
253
+ threshold: {
254
+ label: "Threshold",
255
+ max: 0,
256
+ min: -60,
257
+ step: 1,
258
+ unit: "dB"
259
+ }
260
+ };
261
+ const CompressorSettingsSchema = Schema.Struct({
262
+ attack: Schema.Number,
263
+ enabled: Schema.Boolean,
264
+ gain: Schema.Number,
265
+ knee: Schema.Number,
266
+ ratio: Schema.Number,
267
+ release: Schema.Number,
268
+ threshold: Schema.Number
269
+ });
270
+ const DEFAULT_COMPRESSOR_SETTINGS = Object.freeze({
271
+ attack: 10,
272
+ enabled: false,
273
+ gain: 0,
274
+ knee: 9,
275
+ ratio: 3,
276
+ release: 250,
277
+ threshold: -18
278
+ });
279
+ /**
280
+ * Runtime type guard validating a partial compressor settings patch against
281
+ * the defined parameter ranges.
282
+ */
283
+ function isCompressorPatch(value) {
284
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
285
+ const entries = Object.entries(value);
286
+ return entries.length > 0 && entries.every(([key, val]) => {
287
+ if (key === "enabled") return typeof val === "boolean";
288
+ if (!Object.hasOwn(COMPRESSOR_PARAMETERS, key)) return false;
289
+ const spec = COMPRESSOR_PARAMETERS[key];
290
+ return typeof val === "number" && Number.isFinite(val) && val >= spec.min && val <= spec.max;
291
+ });
292
+ }
293
+ /**
294
+ * Converts `CompressorSettings` to Couch's exact FFmpeg / mpv `libavfilter` string.
295
+ */
296
+ function compressorToFfmpegFilter(settings) {
297
+ const thresholdLinear = 10 ** (settings.threshold / 20);
298
+ const kneeLinear = 10 ** (settings.knee / 20);
299
+ return `acompressor=threshold=${thresholdLinear}:ratio=${settings.ratio}:attack=${settings.attack}:release=${settings.release}:knee=${kneeLinear}:link=maximum:makeup=1,volume=${settings.gain}dB`;
300
+ }
301
+ /**
302
+ * Creates a delay-aligned Web Audio `DynamicsCompressorNode` graph:
303
+ * - Wet branch: `input -> DynamicsCompressorNode -> makeup (GainNode) -> wet (GainNode) -> output (GainNode)`
304
+ * - Dry branch: `input -> delay (6 ms matching Web Audio lookahead) -> dry (GainNode) -> output`
305
+ * - Clickless bypass crossfade (10 ms prime + 40 ms linear ramp + unused branch disconnect).
306
+ */
307
+ function createCompressor(context, initialSettings = DEFAULT_COMPRESSOR_SETTINGS) {
308
+ const input = context.createGain();
309
+ const compressorNode = context.createDynamicsCompressor();
310
+ const makeup = context.createGain();
311
+ const wet = context.createGain();
312
+ const dry = context.createGain();
313
+ const delayNode = context.createDelay(.1);
314
+ const output = context.createGain();
315
+ delayNode.delayTime.value = COMPRESSOR_LOOKAHEAD_SECONDS;
316
+ let wetConnected = false;
317
+ let dryConnected = false;
318
+ let disposed = false;
319
+ let currentSettings = { ...initialSettings };
320
+ let settledTimer;
321
+ const cancelPendingBypass = () => {
322
+ if (settledTimer !== void 0) {
323
+ clearTimeout(settledTimer);
324
+ settledTimer = void 0;
325
+ }
326
+ const now = context.currentTime;
327
+ for (const param of [wet.gain, dry.gain]) if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(now);
328
+ };
329
+ const connectBranch = (compressed) => {
330
+ if (compressed && !wetConnected) {
331
+ input.connect(compressorNode);
332
+ compressorNode.connect(makeup);
333
+ makeup.connect(wet);
334
+ wet.connect(output);
335
+ wetConnected = true;
336
+ }
337
+ if (!compressed && !dryConnected) {
338
+ input.connect(delayNode);
339
+ delayNode.connect(dry);
340
+ dry.connect(output);
341
+ dryConnected = true;
342
+ }
343
+ };
344
+ const disconnectBranch = (compressed) => {
345
+ if (compressed && wetConnected) {
346
+ try {
347
+ input.disconnect(compressorNode);
348
+ } catch {}
349
+ compressorNode.disconnect();
350
+ makeup.disconnect();
351
+ wet.disconnect();
352
+ wetConnected = false;
353
+ }
354
+ if (!compressed && dryConnected) {
355
+ try {
356
+ input.disconnect(delayNode);
357
+ } catch {}
358
+ delayNode.disconnect();
359
+ dry.disconnect();
360
+ dryConnected = false;
361
+ }
362
+ };
363
+ const updateParam = (parameter, value, immediate) => {
364
+ const now = context.currentTime;
365
+ if (immediate || typeof parameter.setTargetAtTime !== "function") {
366
+ if (typeof parameter.cancelScheduledValues === "function") parameter.cancelScheduledValues(now);
367
+ parameter.value = value;
368
+ } else {
369
+ cancelAndHoldParam(parameter, now);
370
+ parameter.setTargetAtTime(value, now, .01);
371
+ }
372
+ };
373
+ const set = (next, immediate = false) => {
374
+ if (disposed) return;
375
+ const prevEnabled = currentSettings.enabled;
376
+ updateParam(compressorNode.threshold, next.threshold, immediate);
377
+ updateParam(compressorNode.ratio, next.ratio, immediate);
378
+ updateParam(compressorNode.knee, next.knee, immediate);
379
+ updateParam(compressorNode.attack, next.attack / 1e3, immediate);
380
+ updateParam(compressorNode.release, next.release / 1e3, immediate);
381
+ updateParam(makeup.gain, 10 ** (next.gain / 20), immediate);
382
+ connectBranch(next.enabled);
383
+ if (immediate) {
384
+ cancelPendingBypass();
385
+ wet.gain.value = next.enabled ? 1 : 0;
386
+ dry.gain.value = next.enabled ? 0 : 1;
387
+ disconnectBranch(!next.enabled);
388
+ } else if (next.enabled !== prevEnabled) {
389
+ if (settledTimer !== void 0) {
390
+ clearTimeout(settledTimer);
391
+ settledTimer = void 0;
392
+ }
393
+ const at = context.currentTime;
394
+ const begin = at + .01;
395
+ const end = begin + .04;
396
+ const targets = [[wet.gain, next.enabled ? 1 : 0], [dry.gain, next.enabled ? 0 : 1]];
397
+ for (const [param, targetVal] of targets) {
398
+ cancelAndHoldParam(param, at);
399
+ if (typeof param.setValueAtTime === "function" && typeof param.linearRampToValueAtTime === "function") {
400
+ param.setValueAtTime(param.value, begin);
401
+ param.linearRampToValueAtTime(targetVal, end);
402
+ } else param.value = targetVal;
403
+ }
404
+ const finish = () => {
405
+ settledTimer = void 0;
406
+ if (disposed) return;
407
+ if (context.state === "running" && context.currentTime < end) {
408
+ settledTimer = setTimeout(finish, 20);
409
+ return;
410
+ }
411
+ for (const [param, targetVal] of [[wet.gain, currentSettings.enabled ? 1 : 0], [dry.gain, currentSettings.enabled ? 0 : 1]]) {
412
+ if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(context.currentTime);
413
+ param.value = targetVal;
414
+ }
415
+ disconnectBranch(!currentSettings.enabled);
416
+ };
417
+ settledTimer = setTimeout(finish, 70);
418
+ }
419
+ currentSettings = { ...next };
420
+ };
421
+ set(initialSettings, true);
422
+ return {
423
+ compressorNode,
424
+ delayNode,
425
+ dispose: () => {
426
+ disposed = true;
427
+ cancelPendingBypass();
428
+ for (const node of [
429
+ input,
430
+ compressorNode,
431
+ makeup,
432
+ wet,
433
+ dry,
434
+ delayNode,
435
+ output
436
+ ]) node.disconnect();
437
+ },
438
+ getSettings: () => ({ ...currentSettings }),
439
+ input,
440
+ output,
441
+ set,
442
+ setVolume: (value) => {
443
+ const clamped = Math.max(0, Number.isFinite(value) ? value : 1);
444
+ updateParam(output.gain, clamped, false);
445
+ }
446
+ };
447
+ }
448
+ // src/effects/dsp-seam.ts
449
+ /**
450
+ * Upstream `@opendaw/studio-core` `EngineWorklet` monitoring cap:
451
+ * 8 monitoring channels = 4 stereo sources (or 8 mono sources).
452
+ */
453
+ const DEFAULT_MAX_MONITORING_CHANNELS = 8;
454
+ const DEFAULT_MAX_STEREO_SOURCES = 4;
455
+ const DSP_SWITCH_SECONDS = .03;
456
+ /**
457
+ * Inspects COOP/COEP (`crossOriginIsolated`), `SharedArrayBuffer`, and `AudioWorkletNode`
458
+ * support plus the upstream 4-stereo-source (8-channel) monitoring budget.
459
+ */
460
+ function detectExternalDspCapabilities(overrides = {}) {
461
+ const crossOriginIsolated = overrides.crossOriginIsolated ?? (typeof globalThis.crossOriginIsolated === "boolean" ? globalThis.crossOriginIsolated : false);
462
+ const sharedArrayBuffer = overrides.sharedArrayBuffer ?? globalThis.SharedArrayBuffer !== void 0;
463
+ const audioWorklet = overrides.audioWorklet ?? globalThis.AudioWorkletNode !== void 0;
464
+ const maxMonitoringChannels = Math.max(1, overrides.maxMonitoringChannels ?? 8);
465
+ return {
466
+ audioWorklet,
467
+ canRunWasmDsp: crossOriginIsolated && sharedArrayBuffer && audioWorklet,
468
+ crossOriginIsolated,
469
+ maxMonitoringChannels,
470
+ maxStereoSources: Math.floor(maxMonitoringChannels / 2),
471
+ sharedArrayBuffer
472
+ };
473
+ }
474
+ function toVoidEffect(result) {
475
+ if (result === void 0) return Effect.void;
476
+ return result;
477
+ }
478
+ function sanitizeLatencySeconds(value) {
479
+ if (value === void 0 || !Number.isFinite(value) || value < 0) return 0;
480
+ return value;
481
+ }
482
+ /**
483
+ * Creates a clickless `DspPluginHost` managing:
484
+ * - A shared stereo-master insert shell (`masterInput -> masterBypassGain || masterPluginInput -> [DspPlugin] -> masterPluginOutput -> masterPluginGain -> masterOutput`)
485
+ * - Optional per-source routing slots bounded by the 4-stereo-source (8-channel) monitoring cap
486
+ * - 30 ms clickless crossfades (waiting for fade-out before disconnecting on detach)
487
+ * - COOP/COEP `SharedArrayBuffer` capability gating and latency compensation reporting.
488
+ */
489
+ function createDspPluginHost(context, options = {}) {
490
+ const capabilities = detectExternalDspCapabilities(options.capabilities);
491
+ const switchSeconds = Math.max(0, options.switchSeconds ?? .03);
492
+ const masterInput = context.createGain();
493
+ const masterBypassGain = context.createGain();
494
+ const masterPluginInput = context.createGain();
495
+ const masterPluginOutput = context.createGain();
496
+ const masterPluginGain = context.createGain();
497
+ const masterOutput = context.createGain();
498
+ masterBypassGain.gain.value = 1;
499
+ masterPluginGain.gain.value = 0;
500
+ masterInput.connect(masterBypassGain);
501
+ masterBypassGain.connect(masterOutput);
502
+ masterInput.connect(masterPluginInput);
503
+ masterPluginOutput.connect(masterPluginGain);
504
+ masterPluginGain.connect(masterOutput);
505
+ if (options.masterDestination) masterOutput.connect(options.masterDestination);
506
+ const slots = /* @__PURE__ */ new Map();
507
+ const lifecycleSemaphore = Semaphore.makeUnsafe(1);
508
+ let activePlugin;
509
+ let masterBusConnected = false;
510
+ let detaching = false;
511
+ let bypassed = false;
512
+ let reservedChannels = 0;
513
+ const getAllocatedChannels = () => {
514
+ let total = reservedChannels;
515
+ for (const slot of slots.values()) if (slot.connectedToPlugin) total += slot.channels;
516
+ return total;
517
+ };
518
+ const rampPair = (bypassGain, pluginGain, usePlugin) => {
519
+ const now = context.currentTime;
520
+ const targetBypass = usePlugin ? 0 : 1;
521
+ const targetPlugin = usePlugin ? 1 : 0;
522
+ for (const [param, target] of [[bypassGain.gain, targetBypass], [pluginGain.gain, targetPlugin]]) if (switchSeconds > 0 && typeof param.linearRampToValueAtTime === "function") {
523
+ cancelAndHoldParam(param, now);
524
+ param.linearRampToValueAtTime(target, now + switchSeconds);
525
+ } else {
526
+ if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(now);
527
+ param.value = target;
528
+ }
529
+ };
530
+ const rampSlot = (slot, usePlugin) => {
531
+ rampPair(slot.bypassGain, slot.pluginGain, usePlugin);
532
+ };
533
+ const rampMasterBus = (usePlugin) => {
534
+ rampPair(masterBypassGain, masterPluginGain, usePlugin);
535
+ };
536
+ const checkPluginRequirements = (plugin) => {
537
+ const req = plugin.requirements;
538
+ if (req?.sharedArrayBuffer && !capabilities.canRunWasmDsp) return Effect.fail(new AudioUnsupportedError({
539
+ feature: "SharedArrayBuffer/COOP-COEP",
540
+ message: `DSP plugin "${plugin.name}" requires crossOriginIsolated + SharedArrayBuffer + AudioWorklet.`
541
+ }));
542
+ if (req?.audioWorklet && !capabilities.audioWorklet) return Effect.fail(new AudioUnsupportedError({
543
+ feature: "AudioWorklet",
544
+ message: `DSP plugin "${plugin.name}" requires AudioWorklet support.`
545
+ }));
546
+ return Effect.void;
547
+ };
548
+ const maxChannelsFor = (plugin) => Math.min(capabilities.maxMonitoringChannels, plugin?.requirements?.maxMonitoringChannels ?? capabilities.maxMonitoringChannels);
549
+ const connectSlotToPlugin = (slot, plugin) => Effect.gen(function* () {
550
+ if (!plugin.connectSource) return false;
551
+ const cap = maxChannelsFor(plugin);
552
+ if (getAllocatedChannels() + slot.channels > cap) return false;
553
+ reservedChannels += slot.channels;
554
+ let released = false;
555
+ const releaseReservation = () => {
556
+ if (!released) {
557
+ released = true;
558
+ reservedChannels = Math.max(0, reservedChannels - slot.channels);
559
+ }
560
+ };
561
+ yield* toVoidEffect(plugin.connectSource(slot.sourceId, slot.pluginInput, slot.pluginOutput, slot.channels)).pipe(Effect.onExit(() => {
562
+ releaseReservation();
563
+ return Effect.void;
564
+ }));
565
+ slot.connectedToPlugin = true;
566
+ rampSlot(slot, !bypassed);
567
+ return true;
568
+ });
569
+ const unregisterSourceUnlocked = (sourceId) => Effect.gen(function* () {
570
+ const slot = slots.get(sourceId);
571
+ if (!slot) return;
572
+ slots.delete(sourceId);
573
+ if (slot.connectedToPlugin) {
574
+ slot.connectedToPlugin = false;
575
+ if (activePlugin?.disconnectSource) yield* toVoidEffect(activePlugin.disconnectSource(sourceId));
576
+ }
577
+ try {
578
+ slot.source.disconnect(slot.bypassGain);
579
+ } catch {}
580
+ try {
581
+ slot.source.disconnect(slot.pluginInput);
582
+ } catch {}
583
+ for (const node of [
584
+ slot.bypassGain,
585
+ slot.pluginInput,
586
+ slot.pluginOutput,
587
+ slot.pluginGain
588
+ ]) node.disconnect();
589
+ });
590
+ const registerSource = (sourceId, source, destination, channels = 2) => lifecycleSemaphore.withPermits(1)(Effect.gen(function* () {
591
+ if (slots.has(sourceId)) yield* unregisterSourceUnlocked(sourceId);
592
+ const bypassGain = context.createGain();
593
+ const pluginInput = context.createGain();
594
+ const pluginOutput = context.createGain();
595
+ const pluginGain = context.createGain();
596
+ bypassGain.gain.value = 1;
597
+ pluginGain.gain.value = 0;
598
+ source.connect(bypassGain);
599
+ bypassGain.connect(destination);
600
+ source.connect(pluginInput);
601
+ pluginOutput.connect(pluginGain);
602
+ pluginGain.connect(destination);
603
+ const slot = {
604
+ bypassGain,
605
+ channels,
606
+ connectedToPlugin: false,
607
+ destination,
608
+ pluginGain,
609
+ pluginInput,
610
+ pluginOutput,
611
+ source,
612
+ sourceId
613
+ };
614
+ slots.set(sourceId, slot);
615
+ if (activePlugin) yield* connectSlotToPlugin(slot, activePlugin);
616
+ return {
617
+ activeMode: slot.connectedToPlugin && !bypassed ? "plugin" : "bypass",
618
+ channels,
619
+ sourceId
620
+ };
621
+ }));
622
+ const unregisterSource = (sourceId) => lifecycleSemaphore.withPermits(1)(unregisterSourceUnlocked(sourceId));
623
+ const disconnectPluginPaths = (plugin, connectedSlots, hadMasterBus) => Effect.gen(function* () {
624
+ for (const slot of connectedSlots) if (slot.connectedToPlugin) {
625
+ slot.connectedToPlugin = false;
626
+ if (plugin.disconnectSource) yield* toVoidEffect(plugin.disconnectSource(slot.sourceId));
627
+ else slot.pluginInput.disconnect();
628
+ rampSlot(slot, false);
629
+ }
630
+ if (hadMasterBus) {
631
+ masterBusConnected = false;
632
+ if (plugin.disconnectMasterBus) yield* toVoidEffect(plugin.disconnectMasterBus());
633
+ else masterPluginInput.disconnect();
634
+ rampMasterBus(false);
635
+ }
636
+ if (plugin.dispose) yield* toVoidEffect(plugin.dispose());
637
+ });
638
+ const detachPluginUnlocked = () => Effect.gen(function* () {
639
+ const previous = activePlugin;
640
+ if (!previous) return;
641
+ activePlugin = void 0;
642
+ detaching = true;
643
+ const connectedSlots = [];
644
+ for (const slot of slots.values()) if (slot.connectedToPlugin) {
645
+ connectedSlots.push(slot);
646
+ rampSlot(slot, false);
647
+ }
648
+ const hadMasterBus = masterBusConnected;
649
+ if (hadMasterBus) rampMasterBus(false);
650
+ let disconnected = false;
651
+ const finalizeDisconnect = () => Effect.gen(function* () {
652
+ if (disconnected) return;
653
+ disconnected = true;
654
+ try {
655
+ yield* disconnectPluginPaths(previous, connectedSlots, hadMasterBus);
656
+ } finally {
657
+ detaching = false;
658
+ }
659
+ });
660
+ yield* switchSeconds > 0 && !bypassed && (hadMasterBus || connectedSlots.length > 0) ? Effect.sleep(Duration.millis(Math.ceil(switchSeconds * 1e3))).pipe(Effect.ensuring(finalizeDisconnect())) : finalizeDisconnect();
661
+ });
662
+ const detachPlugin = () => lifecycleSemaphore.withPermits(1)(detachPluginUnlocked());
663
+ const attachPlugin = (plugin) => lifecycleSemaphore.withPermits(1)(Effect.gen(function* () {
664
+ yield* checkPluginRequirements(plugin);
665
+ if (activePlugin) yield* detachPluginUnlocked();
666
+ activePlugin = plugin;
667
+ const connectedDuringAttach = [];
668
+ let attachedMasterBus = false;
669
+ const rollbackAttach = () => Effect.gen(function* () {
670
+ if (activePlugin === plugin) activePlugin = void 0;
671
+ yield* disconnectPluginPaths(plugin, connectedDuringAttach, attachedMasterBus);
672
+ });
673
+ if (plugin.connectMasterBus) {
674
+ yield* toVoidEffect(plugin.connectMasterBus(masterPluginInput, masterPluginOutput)).pipe(Effect.onError(() => {
675
+ if (activePlugin === plugin) activePlugin = void 0;
676
+ return Effect.void;
677
+ }));
678
+ masterBusConnected = true;
679
+ attachedMasterBus = true;
680
+ rampMasterBus(!bypassed);
681
+ }
682
+ if (plugin.connectSource) {
683
+ for (const slot of slots.values()) if (yield* connectSlotToPlugin(slot, plugin).pipe(Effect.onError(() => rollbackAttach()))) connectedDuringAttach.push(slot);
684
+ }
685
+ }));
686
+ const setBypass = (nextBypass) => {
687
+ bypassed = nextBypass;
688
+ if (detaching || !activePlugin) return;
689
+ if (masterBusConnected) rampMasterBus(!bypassed);
690
+ for (const slot of slots.values()) rampSlot(slot, !bypassed && slot.connectedToPlugin);
691
+ };
692
+ const updateParameter = (sourceId, effectId, parameter, value) => {
693
+ if (!activePlugin?.updateParameter) return "unavailable";
694
+ const slot = slots.get(sourceId);
695
+ if (slot) {
696
+ if (!slot.connectedToPlugin) return "unavailable";
697
+ return activePlugin.updateParameter(sourceId, effectId, parameter, value);
698
+ }
699
+ if (masterBusConnected) return activePlugin.updateParameter(sourceId, effectId, parameter, value);
700
+ return "unavailable";
701
+ };
702
+ const getLatencySeconds = () => {
703
+ if (!activePlugin || bypassed) return 0;
704
+ if (!(masterBusConnected || [...slots.values()].some((slot) => slot.connectedToPlugin))) return 0;
705
+ return sanitizeLatencySeconds(typeof activePlugin.getLatencySeconds === "function" ? activePlugin.getLatencySeconds() : activePlugin.latencySeconds);
706
+ };
707
+ const dispose = () => lifecycleSemaphore.withPermits(1)(Effect.gen(function* () {
708
+ yield* detachPluginUnlocked();
709
+ for (const sourceId of slots.keys()) yield* unregisterSourceUnlocked(sourceId);
710
+ for (const node of [
711
+ masterInput,
712
+ masterBypassGain,
713
+ masterPluginInput,
714
+ masterPluginOutput,
715
+ masterPluginGain,
716
+ masterOutput
717
+ ]) node.disconnect();
718
+ }));
719
+ return {
720
+ attachPlugin,
721
+ detachPlugin,
722
+ dispose,
723
+ getActivePlugin: () => activePlugin,
724
+ getAllocatedChannels,
725
+ getCapabilities: () => capabilities,
726
+ getLatencySeconds,
727
+ getSources: () => [...slots.values()].map((slot) => ({
728
+ activeMode: slot.connectedToPlugin && !bypassed ? "plugin" : "bypass",
729
+ channels: slot.channels,
730
+ sourceId: slot.sourceId
731
+ })),
732
+ isBypassed: () => bypassed,
733
+ isMasterBusActive: () => masterBusConnected && !bypassed,
734
+ masterInput,
735
+ masterOutput,
736
+ registerSource,
737
+ setBypass,
738
+ unregisterSource,
739
+ updateParameter
740
+ };
741
+ }
742
+ export { COMPRESSOR_LOOKAHEAD_SECONDS, COMPRESSOR_PARAMETERS, CompressorSettingsSchema, DEFAULT_COMPRESSOR_SETTINGS, DEFAULT_CROSSFADE_STEPS, DEFAULT_MAX_MONITORING_CHANNELS, DEFAULT_MAX_STEREO_SOURCES, DEFAULT_PARAM_TIME_CONSTANT_S, DSP_SWITCH_SECONDS, MIN_EXPONENTIAL_GAIN, compressorToFfmpegFilter, computeCrossfadeGains, createBiquadFilter, createCompressor, createCrossfade, createCrossfadeCurves, createDspPluginHost, createGain, createPan, detectExternalDspCapabilities, isCompressorPatch };
743
+
744
+ //# sourceMappingURL=index.js.map