@avoid.quest/audio 0.1.0 → 0.1.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +32 -2
  2. package/dist/effects/index.d.ts +21 -72
  3. package/dist/effects/index.js +212 -505
  4. package/dist/effects/index.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/midi/index.d.ts +0 -24
  8. package/dist/midi/index.js +222 -258
  9. package/dist/midi/index.js.map +1 -1
  10. package/dist/native-Bern4_PB.js +172 -0
  11. package/dist/native-Bern4_PB.js.map +1 -0
  12. package/dist/pcm-buffer-DSzGHbon.js +436 -0
  13. package/dist/pcm-buffer-DSzGHbon.js.map +1 -0
  14. package/dist/playback/index.d.ts +63 -115
  15. package/dist/playback/index.js +906 -1062
  16. package/dist/playback/index.js.map +1 -1
  17. package/dist/queue/index.d.ts +8 -19
  18. package/dist/queue/index.js +461 -960
  19. package/dist/queue/index.js.map +1 -1
  20. package/dist/recognize/index.d.ts +37 -74
  21. package/dist/recognize/index.js +172 -2715
  22. package/dist/recognize/index.js.map +1 -1
  23. package/dist/routing/index.d.ts +3 -34
  24. package/dist/routing/index.js +413 -536
  25. package/dist/routing/index.js.map +1 -1
  26. package/dist/shazam-gBrX1NEY.d.ts +27 -0
  27. package/dist/sync/index.d.ts +9 -77
  28. package/dist/sync/index.js +320 -542
  29. package/dist/sync/index.js.map +1 -1
  30. package/dist/{worklet-loader-BvEW0oVO.d.ts → worklet-loader-BabwPALw.d.ts} +4 -7
  31. package/dist/{worklet-loader-S7R8ZAmP.js → worklet-loader-f741D1tk.js} +37 -52
  32. package/dist/worklet-loader-f741D1tk.js.map +1 -0
  33. package/dist/worklets/couch-live.js +110 -192
  34. package/dist/worklets/couch-live.js.map +1 -1
  35. package/dist/worklets/meter.js +14 -20
  36. package/dist/worklets/meter.js.map +1 -1
  37. package/dist/worklets/pcm-capture.d.ts +6 -0
  38. package/dist/worklets/pcm-capture.js +52 -0
  39. package/dist/worklets/pcm-capture.js.map +1 -0
  40. package/package.json +18 -4
  41. package/types/hls-unavailable.d.ts +4 -0
  42. package/dist/worklet-loader-S7R8ZAmP.js.map +0 -1
@@ -1,217 +1,6 @@
1
1
  import { Duration, Effect, Schema, Semaphore } from "effect";
2
+ import { c as createCrossfade, d as createPan, f as disconnectEdge, i as cancelAndHoldParam, l as createCrossfadeCurves, n as DEFAULT_PARAM_TIME_CONSTANT_S, o as computeCrossfadeGains, p as scheduleParam, r as MIN_EXPONENTIAL_GAIN, s as createBiquadFilter, t as DEFAULT_CROSSFADE_STEPS, u as createGain } from "../native-Bern4_PB.js";
2
3
  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
4
  // src/effects/compressor.ts
216
5
  const COMPRESSOR_LOOKAHEAD_SECONDS = .006;
217
6
  const COMPRESSOR_PARAMETERS = {
@@ -258,14 +47,29 @@ const COMPRESSOR_PARAMETERS = {
258
47
  unit: "dB"
259
48
  }
260
49
  };
50
+ function boundedParameter(parameter) {
51
+ const { max, min } = COMPRESSOR_PARAMETERS[parameter];
52
+ return Schema.Finite.check(Schema.isBetween({
53
+ maximum: max,
54
+ minimum: min
55
+ }));
56
+ }
57
+ /**
58
+ * Finite, range-checked compressor settings. Bounds mirror
59
+ * `COMPRESSOR_PARAMETERS` (the `@avoid.quest/ui` `CompressorControls` ranges),
60
+ * which sit inside the native `DynamicsCompressorNode` ranges
61
+ * (threshold `[-100, 0]` dB, knee `[0, 40]` dB, ratio `[1, 20]`,
62
+ * attack/release `[0, 1]` s) so decoded settings never get silently clamped
63
+ * by Web Audio. `NaN` / `±Infinity` are rejected.
64
+ */
261
65
  const CompressorSettingsSchema = Schema.Struct({
262
- attack: Schema.Number,
66
+ attack: boundedParameter("attack"),
263
67
  enabled: Schema.Boolean,
264
- gain: Schema.Number,
265
- knee: Schema.Number,
266
- ratio: Schema.Number,
267
- release: Schema.Number,
268
- threshold: Schema.Number
68
+ gain: boundedParameter("gain"),
69
+ knee: boundedParameter("knee"),
70
+ ratio: boundedParameter("ratio"),
71
+ release: boundedParameter("release"),
72
+ threshold: boundedParameter("threshold")
269
73
  });
270
74
  const DEFAULT_COMPRESSOR_SETTINGS = Object.freeze({
271
75
  attack: 10,
@@ -276,19 +80,12 @@ const DEFAULT_COMPRESSOR_SETTINGS = Object.freeze({
276
80
  release: 250,
277
81
  threshold: -18
278
82
  });
279
- /**
280
- * Runtime type guard validating a partial compressor settings patch against
281
- * the defined parameter ranges.
282
- */
83
+ /** Type guard for a non-empty partial settings patch within `CompressorSettingsSchema`. */
283
84
  function isCompressorPatch(value) {
284
85
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
86
+ const { fields } = CompressorSettingsSchema;
285
87
  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
- });
88
+ return entries.length > 0 && entries.every(([key, val]) => Object.hasOwn(fields, key) && Schema.is(fields[key])(val));
292
89
  }
293
90
  /**
294
91
  * Converts `CompressorSettings` to Couch's exact FFmpeg / mpv `libavfilter` string.
@@ -298,10 +95,13 @@ function compressorToFfmpegFilter(settings) {
298
95
  const kneeLinear = 10 ** (settings.knee / 20);
299
96
  return `acompressor=threshold=${thresholdLinear}:ratio=${settings.ratio}:attack=${settings.attack}:release=${settings.release}:knee=${kneeLinear}:link=maximum:makeup=1,volume=${settings.gain}dB`;
300
97
  }
98
+ function cancelScheduled(param, at) {
99
+ if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(at);
100
+ }
301
101
  /**
302
102
  * 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`
103
+ * - Wet branch: `input -> DynamicsCompressorNode -> makeup -> wet -> output`
104
+ * - Dry branch: `input -> delay (6 ms Web Audio lookahead) -> dry -> output`
305
105
  * - Clickless bypass crossfade (10 ms prime + 40 ms linear ramp + unused branch disconnect).
306
106
  */
307
107
  function createCompressor(context, initialSettings = DEFAULT_COMPRESSOR_SETTINGS) {
@@ -313,57 +113,54 @@ function createCompressor(context, initialSettings = DEFAULT_COMPRESSOR_SETTINGS
313
113
  const delayNode = context.createDelay(.1);
314
114
  const output = context.createGain();
315
115
  delayNode.delayTime.value = COMPRESSOR_LOOKAHEAD_SECONDS;
316
- let wetConnected = false;
317
- let dryConnected = false;
116
+ const wetBranch = {
117
+ chain: [
118
+ compressorNode,
119
+ makeup,
120
+ wet
121
+ ],
122
+ connected: false
123
+ };
124
+ const dryBranch = {
125
+ chain: [delayNode, dry],
126
+ connected: false
127
+ };
318
128
  let disposed = false;
319
129
  let currentSettings = { ...initialSettings };
320
130
  let settledTimer;
321
- const cancelPendingBypass = () => {
131
+ const mixTargets = (enabled) => [[wet.gain, enabled ? 1 : 0], [dry.gain, enabled ? 0 : 1]];
132
+ const clearSettledTimer = () => {
322
133
  if (settledTimer !== void 0) {
323
134
  clearTimeout(settledTimer);
324
135
  settledTimer = void 0;
325
136
  }
326
- const now = context.currentTime;
327
- for (const param of [wet.gain, dry.gain]) if (typeof param.cancelScheduledValues === "function") param.cancelScheduledValues(now);
328
137
  };
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
- }
138
+ const cancelPendingBypass = () => {
139
+ clearSettledTimer();
140
+ cancelScheduled(wet.gain, context.currentTime);
141
+ cancelScheduled(dry.gain, context.currentTime);
343
142
  };
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) {
143
+ const setBranch = (branch, connect) => {
144
+ if (branch.connected === connect) return;
145
+ if (connect) {
146
+ let previous = input;
147
+ for (const node of branch.chain) {
148
+ previous.connect(node);
149
+ previous = node;
150
+ }
151
+ previous.connect(output);
152
+ } else {
355
153
  try {
356
- input.disconnect(delayNode);
154
+ input.disconnect(branch.chain[0]);
357
155
  } catch {}
358
- delayNode.disconnect();
359
- dry.disconnect();
360
- dryConnected = false;
156
+ for (const node of branch.chain) node.disconnect();
361
157
  }
158
+ branch.connected = connect;
362
159
  };
363
160
  const updateParam = (parameter, value, immediate) => {
364
161
  const now = context.currentTime;
365
162
  if (immediate || typeof parameter.setTargetAtTime !== "function") {
366
- if (typeof parameter.cancelScheduledValues === "function") parameter.cancelScheduledValues(now);
163
+ cancelScheduled(parameter, now);
367
164
  parameter.value = value;
368
165
  } else {
369
166
  cancelAndHoldParam(parameter, now);
@@ -379,27 +176,22 @@ function createCompressor(context, initialSettings = DEFAULT_COMPRESSOR_SETTINGS
379
176
  updateParam(compressorNode.attack, next.attack / 1e3, immediate);
380
177
  updateParam(compressorNode.release, next.release / 1e3, immediate);
381
178
  updateParam(makeup.gain, 10 ** (next.gain / 20), immediate);
382
- connectBranch(next.enabled);
179
+ setBranch(next.enabled ? wetBranch : dryBranch, true);
383
180
  if (immediate) {
384
181
  cancelPendingBypass();
385
- wet.gain.value = next.enabled ? 1 : 0;
386
- dry.gain.value = next.enabled ? 0 : 1;
387
- disconnectBranch(!next.enabled);
182
+ for (const [param, target] of mixTargets(next.enabled)) param.value = target;
183
+ setBranch(next.enabled ? dryBranch : wetBranch, false);
388
184
  } else if (next.enabled !== prevEnabled) {
389
- if (settledTimer !== void 0) {
390
- clearTimeout(settledTimer);
391
- settledTimer = void 0;
392
- }
185
+ clearSettledTimer();
393
186
  const at = context.currentTime;
394
187
  const begin = at + .01;
395
188
  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) {
189
+ for (const [param, target] of mixTargets(next.enabled)) {
398
190
  cancelAndHoldParam(param, at);
399
191
  if (typeof param.setValueAtTime === "function" && typeof param.linearRampToValueAtTime === "function") {
400
192
  param.setValueAtTime(param.value, begin);
401
- param.linearRampToValueAtTime(targetVal, end);
402
- } else param.value = targetVal;
193
+ param.linearRampToValueAtTime(target, end);
194
+ } else param.value = target;
403
195
  }
404
196
  const finish = () => {
405
197
  settledTimer = void 0;
@@ -408,11 +200,12 @@ function createCompressor(context, initialSettings = DEFAULT_COMPRESSOR_SETTINGS
408
200
  settledTimer = setTimeout(finish, 20);
409
201
  return;
410
202
  }
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;
203
+ const { enabled } = currentSettings;
204
+ for (const [param, target] of mixTargets(enabled)) {
205
+ cancelScheduled(param, context.currentTime);
206
+ param.value = target;
414
207
  }
415
- disconnectBranch(!currentSettings.enabled);
208
+ setBranch(enabled ? dryBranch : wetBranch, false);
416
209
  };
417
210
  settledTimer = setTimeout(finish, 70);
418
211
  }
@@ -427,13 +220,10 @@ function createCompressor(context, initialSettings = DEFAULT_COMPRESSOR_SETTINGS
427
220
  cancelPendingBypass();
428
221
  for (const node of [
429
222
  input,
430
- compressorNode,
431
- makeup,
432
- wet,
433
- dry,
434
- delayNode,
435
- output
223
+ ...wetBranch.chain,
224
+ ...dryBranch.chain
436
225
  ]) node.disconnect();
226
+ output.disconnect();
437
227
  },
438
228
  getSettings: () => ({ ...currentSettings }),
439
229
  input,
@@ -445,20 +235,12 @@ function createCompressor(context, initialSettings = DEFAULT_COMPRESSOR_SETTINGS
445
235
  }
446
236
  };
447
237
  }
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
- */
238
+ // src/effects/dsp-types.ts
453
239
  const DEFAULT_MAX_MONITORING_CHANNELS = 8;
454
240
  const DEFAULT_MAX_STEREO_SOURCES = 4;
455
241
  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
242
  function detectExternalDspCapabilities(overrides = {}) {
461
- const crossOriginIsolated = overrides.crossOriginIsolated ?? (typeof globalThis.crossOriginIsolated === "boolean" ? globalThis.crossOriginIsolated : false);
243
+ const crossOriginIsolated = overrides.crossOriginIsolated ?? globalThis.crossOriginIsolated === true;
462
244
  const sharedArrayBuffer = overrides.sharedArrayBuffer ?? globalThis.SharedArrayBuffer !== void 0;
463
245
  const audioWorklet = overrides.audioWorklet ?? globalThis.AudioWorkletNode !== void 0;
464
246
  const maxMonitoringChannels = Math.max(1, overrides.maxMonitoringChannels ?? 8);
@@ -471,272 +253,197 @@ function detectExternalDspCapabilities(overrides = {}) {
471
253
  sharedArrayBuffer
472
254
  };
473
255
  }
474
- function toVoidEffect(result) {
475
- if (result === void 0) return Effect.void;
476
- return result;
256
+ const runVoid = (r) => r ?? Effect.void;
257
+ function createInsertShell(context, input, output) {
258
+ const [bypassGain, pluginInput, pluginOutput, pluginGain] = [
259
+ context.createGain(),
260
+ context.createGain(),
261
+ context.createGain(),
262
+ context.createGain()
263
+ ];
264
+ bypassGain.gain.value = 1;
265
+ pluginGain.gain.value = 0;
266
+ input.connect(bypassGain);
267
+ bypassGain.connect(output);
268
+ input.connect(pluginInput);
269
+ pluginOutput.connect(pluginGain);
270
+ pluginGain.connect(output);
271
+ return {
272
+ bypassGain,
273
+ pluginGain,
274
+ pluginInput,
275
+ pluginOutput
276
+ };
477
277
  }
478
- function sanitizeLatencySeconds(value) {
479
- if (value === void 0 || !Number.isFinite(value) || value < 0) return 0;
480
- return value;
278
+ const disconnectShell = (s) => {
279
+ s.bypassGain.disconnect();
280
+ s.pluginInput.disconnect();
281
+ s.pluginOutput.disconnect();
282
+ s.pluginGain.disconnect();
283
+ };
284
+ function checkPluginRequirements(plugin, capabilities) {
285
+ const req = plugin.requirements;
286
+ if (req?.sharedArrayBuffer && !capabilities.canRunWasmDsp) return Effect.fail(new AudioUnsupportedError({
287
+ feature: "SharedArrayBuffer/COOP-COEP",
288
+ message: `DSP plugin "${plugin.name}" requires COOP/COEP + SharedArrayBuffer + AudioWorklet.`
289
+ }));
290
+ if (req?.audioWorklet && !capabilities.audioWorklet) return Effect.fail(new AudioUnsupportedError({
291
+ feature: "AudioWorklet",
292
+ message: `DSP plugin "${plugin.name}" requires AudioWorklet support.`
293
+ }));
294
+ return Effect.void;
481
295
  }
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
- */
296
+ // src/effects/dsp-seam.ts
489
297
  function createDspPluginHost(context, options = {}) {
490
298
  const capabilities = detectExternalDspCapabilities(options.capabilities);
491
- const switchSeconds = Math.max(0, options.switchSeconds ?? .03);
299
+ const switchSec = Math.max(0, options.switchSeconds ?? .03);
492
300
  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
301
  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);
302
+ const masterShell = createInsertShell(context, masterInput, masterOutput);
505
303
  if (options.masterDestination) masterOutput.connect(options.masterDestination);
506
304
  const slots = /* @__PURE__ */ new Map();
507
- const lifecycleSemaphore = Semaphore.makeUnsafe(1);
305
+ const withLock = Semaphore.makeUnsafe(1).withPermits(1);
508
306
  let activePlugin;
509
307
  let masterBusConnected = false;
510
308
  let detaching = false;
511
309
  let bypassed = false;
512
310
  let reservedChannels = 0;
311
+ const toRegistered = (s) => ({
312
+ activeMode: s.connectedToPlugin && !bypassed ? "plugin" : "bypass",
313
+ channels: s.channels,
314
+ sourceId: s.sourceId
315
+ });
513
316
  const getAllocatedChannels = () => {
514
317
  let total = reservedChannels;
515
- for (const slot of slots.values()) if (slot.connectedToPlugin) total += slot.channels;
318
+ for (const s of slots.values()) if (s.connectedToPlugin) total += s.channels;
516
319
  return total;
517
320
  };
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);
321
+ const rampShell = (shell, usePlugin) => {
322
+ scheduleParam(shell.bypassGain.gain, context, usePlugin ? 0 : 1, switchSec);
323
+ scheduleParam(shell.pluginGain.gain, context, usePlugin ? 1 : 0, switchSec);
532
324
  };
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;
325
+ const detachPath = (shell, hook) => (hook ? runVoid(hook()) : Effect.sync(() => shell.pluginInput.disconnect())).pipe(Effect.andThen(Effect.sync(() => rampShell(shell, false))));
326
+ const connectSlot = (slot, plugin) => Effect.gen(function* () {
327
+ const cap = Math.min(capabilities.maxMonitoringChannels, plugin.requirements?.maxMonitoringChannels ?? capabilities.maxMonitoringChannels);
328
+ if (!plugin.connectSource || getAllocatedChannels() + slot.channels > cap) return false;
553
329
  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
- }));
330
+ yield* runVoid(plugin.connectSource(slot.sourceId, slot.pluginInput, slot.pluginOutput, slot.channels)).pipe(Effect.ensuring(Effect.sync(() => {
331
+ reservedChannels = Math.max(0, reservedChannels - slot.channels);
332
+ })));
565
333
  slot.connectedToPlugin = true;
566
- rampSlot(slot, !bypassed);
334
+ rampShell(slot, !bypassed);
567
335
  return true;
568
336
  });
569
- const unregisterSourceUnlocked = (sourceId) => Effect.gen(function* () {
337
+ const unregisterUnlocked = (sourceId) => Effect.gen(function* () {
570
338
  const slot = slots.get(sourceId);
571
339
  if (!slot) return;
572
340
  slots.delete(sourceId);
573
341
  if (slot.connectedToPlugin) {
574
342
  slot.connectedToPlugin = false;
575
- if (activePlugin?.disconnectSource) yield* toVoidEffect(activePlugin.disconnectSource(sourceId));
343
+ yield* runVoid(activePlugin?.disconnectSource?.(sourceId));
576
344
  }
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();
345
+ disconnectEdge(slot.source, slot.bypassGain);
346
+ disconnectEdge(slot.source, slot.pluginInput);
347
+ disconnectShell(slot);
589
348
  });
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
349
  const disconnectPluginPaths = (plugin, connectedSlots, hadMasterBus) => Effect.gen(function* () {
624
- for (const slot of connectedSlots) if (slot.connectedToPlugin) {
350
+ for (const slot of connectedSlots) {
351
+ if (!slot.connectedToPlugin) continue;
625
352
  slot.connectedToPlugin = false;
626
- if (plugin.disconnectSource) yield* toVoidEffect(plugin.disconnectSource(slot.sourceId));
627
- else slot.pluginInput.disconnect();
628
- rampSlot(slot, false);
353
+ yield* detachPath(slot, plugin.disconnectSource ? () => plugin.disconnectSource?.(slot.sourceId) : void 0);
629
354
  }
630
355
  if (hadMasterBus) {
631
356
  masterBusConnected = false;
632
- if (plugin.disconnectMasterBus) yield* toVoidEffect(plugin.disconnectMasterBus());
633
- else masterPluginInput.disconnect();
634
- rampMasterBus(false);
357
+ yield* detachPath(masterShell, plugin.disconnectMasterBus ? () => plugin.disconnectMasterBus?.() : void 0);
635
358
  }
636
- if (plugin.dispose) yield* toVoidEffect(plugin.dispose());
359
+ yield* runVoid(plugin.dispose?.());
637
360
  });
638
- const detachPluginUnlocked = () => Effect.gen(function* () {
639
- const previous = activePlugin;
640
- if (!previous) return;
361
+ const detachUnlocked = () => Effect.gen(function* () {
362
+ const prev = activePlugin;
363
+ if (!prev) return;
641
364
  activePlugin = void 0;
642
365
  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();
366
+ const connectedSlots = [...slots.values()].filter((s) => s.connectedToPlugin);
367
+ for (const s of connectedSlots) rampShell(s, false);
368
+ const hadMaster = masterBusConnected;
369
+ if (hadMaster) rampShell(masterShell, false);
370
+ const cleanup = disconnectPluginPaths(prev, connectedSlots, hadMaster).pipe(Effect.ensuring(Effect.sync(() => {
371
+ detaching = false;
372
+ })));
373
+ yield* switchSec > 0 && !bypassed && (hadMaster || connectedSlots.length > 0) ? Effect.sleep(Duration.millis(Math.ceil(switchSec * 1e3))).pipe(Effect.ensuring(cleanup)) : cleanup;
661
374
  });
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();
375
+ const attachPlugin = (plugin) => withLock(Effect.gen(function* () {
376
+ yield* checkPluginRequirements(plugin, capabilities);
377
+ if (activePlugin) yield* detachUnlocked();
666
378
  activePlugin = plugin;
667
- const connectedDuringAttach = [];
668
- let attachedMasterBus = false;
669
- const rollbackAttach = () => Effect.gen(function* () {
379
+ const connected = [];
380
+ let attachedMaster = false;
381
+ const clearActive = () => {
670
382
  if (activePlugin === plugin) activePlugin = void 0;
671
- yield* disconnectPluginPaths(plugin, connectedDuringAttach, attachedMasterBus);
672
- });
383
+ };
384
+ const rollbackSources = () => {
385
+ clearActive();
386
+ return disconnectPluginPaths(plugin, connected, attachedMaster);
387
+ };
673
388
  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
- }));
389
+ yield* runVoid(plugin.connectMasterBus(masterShell.pluginInput, masterShell.pluginOutput)).pipe(Effect.onError(() => Effect.sync(clearActive)));
678
390
  masterBusConnected = true;
679
- attachedMasterBus = true;
680
- rampMasterBus(!bypassed);
391
+ attachedMaster = true;
392
+ rampShell(masterShell, !bypassed);
681
393
  }
682
394
  if (plugin.connectSource) {
683
- for (const slot of slots.values()) if (yield* connectSlotToPlugin(slot, plugin).pipe(Effect.onError(() => rollbackAttach()))) connectedDuringAttach.push(slot);
395
+ for (const slot of slots.values()) if (yield* connectSlot(slot, plugin).pipe(Effect.onError(rollbackSources))) connected.push(slot);
684
396
  }
685
397
  }));
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();
398
+ const registerSource = (sourceId, source, destination, channels = 2) => withLock(Effect.gen(function* () {
399
+ if (slots.has(sourceId)) yield* unregisterUnlocked(sourceId);
400
+ const slot = {
401
+ ...createInsertShell(context, source, destination),
402
+ channels,
403
+ connectedToPlugin: false,
404
+ source,
405
+ sourceId
406
+ };
407
+ slots.set(sourceId, slot);
408
+ if (activePlugin) yield* connectSlot(slot, activePlugin);
409
+ return toRegistered(slot);
718
410
  }));
719
411
  return {
720
412
  attachPlugin,
721
- detachPlugin,
722
- dispose,
413
+ detachPlugin: () => withLock(detachUnlocked()),
414
+ dispose: () => withLock(Effect.gen(function* () {
415
+ yield* detachUnlocked();
416
+ for (const id of slots.keys()) yield* unregisterUnlocked(id);
417
+ masterInput.disconnect();
418
+ disconnectShell(masterShell);
419
+ masterOutput.disconnect();
420
+ })),
723
421
  getActivePlugin: () => activePlugin,
724
422
  getAllocatedChannels,
725
423
  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
- })),
424
+ getLatencySeconds: () => {
425
+ if (!activePlugin || bypassed) return 0;
426
+ const raw = masterBusConnected || [...slots.values()].some((s) => s.connectedToPlugin) ? activePlugin.getLatencySeconds?.() ?? activePlugin.latencySeconds : void 0;
427
+ return raw !== void 0 && Number.isFinite(raw) && raw >= 0 ? raw : 0;
428
+ },
429
+ getSources: () => [...slots.values()].map(toRegistered),
732
430
  isBypassed: () => bypassed,
733
431
  isMasterBusActive: () => masterBusConnected && !bypassed,
734
432
  masterInput,
735
433
  masterOutput,
736
434
  registerSource,
737
- setBypass,
738
- unregisterSource,
739
- updateParameter
435
+ setBypass: (nextBypass) => {
436
+ bypassed = nextBypass;
437
+ if (detaching || !activePlugin) return;
438
+ if (masterBusConnected) rampShell(masterShell, !bypassed);
439
+ for (const s of slots.values()) rampShell(s, !bypassed && s.connectedToPlugin);
440
+ },
441
+ unregisterSource: (id) => withLock(unregisterUnlocked(id)),
442
+ updateParameter: (sourceId, effectId, parameter, value) => {
443
+ if (!activePlugin?.updateParameter) return "unavailable";
444
+ const slot = slots.get(sourceId);
445
+ return (slot ? slot.connectedToPlugin : masterBusConnected) ? activePlugin.updateParameter(sourceId, effectId, parameter, value) : "unavailable";
446
+ }
740
447
  };
741
448
  }
742
449
  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 };