@schmooky/zvuk 1.11.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -126,6 +126,8 @@ var Ducker = class {
126
126
  analyser;
127
127
  buf;
128
128
  rafId = null;
129
+ /** Timestamp of the previous tick (ms), for measuring the real frame delta. */
130
+ lastTickMs = 0;
129
131
  envelope = 0;
130
132
  targetGain = 1;
131
133
  ctx;
@@ -179,7 +181,12 @@ var Ducker = class {
179
181
  } catch {
180
182
  }
181
183
  }
182
- tick = () => {
184
+ tick = (timeMs) => {
185
+ let dtSec = 1 / 60;
186
+ if (timeMs != null && this.lastTickMs > 0) {
187
+ dtSec = Math.min(0.1, Math.max(1e-3, (timeMs - this.lastTickMs) / 1e3));
188
+ }
189
+ if (timeMs != null) this.lastTickMs = timeMs;
183
190
  if (this._bypassed) {
184
191
  this.rafId = requestAnimationFrame(this.tick);
185
192
  return;
@@ -195,7 +202,7 @@ var Ducker = class {
195
202
  const target = exceeded > 0 ? 1 - this.cfg.amount : 1;
196
203
  const useAttack = target < this.envelope;
197
204
  const tau = (useAttack ? this.cfg.attack : this.cfg.release) || 1e-3;
198
- const alpha = 1 - Math.exp(-0.016666666666666666 / tau);
205
+ const alpha = 1 - Math.exp(-dtSec / tau);
199
206
  this.envelope = this.envelope + alpha * (target - this.envelope);
200
207
  if (Math.abs(this.envelope - this.targetGain) > 1e-3) {
201
208
  this.targetGain = this.envelope;
@@ -232,6 +239,10 @@ var Filter = class {
232
239
  setType(t) {
233
240
  this.filter.type = t;
234
241
  }
242
+ /** Set the filter gain in dB. Only affects `peaking` (the one shelf-like mode exposed). */
243
+ setGain(db) {
244
+ this.filter.gain.setValueAtTime(db, this.ctx.currentTime);
245
+ }
235
246
  get bypassed() {
236
247
  return this._bypassed;
237
248
  }
@@ -273,6 +284,8 @@ var Reverb = class {
273
284
  preDelay;
274
285
  ctx;
275
286
  _bypassed = false;
287
+ /** Active wet mix (0..1), so bypass can restore it instead of guessing. */
288
+ _wet;
276
289
  constructor(ctx, config = {}) {
277
290
  this.ctx = ctx;
278
291
  this.input = ctx.createGain();
@@ -282,6 +295,7 @@ var Reverb = class {
282
295
  this.preDelay = ctx.createDelay(1);
283
296
  this.convolver = ctx.createConvolver();
284
297
  const wetMix = config.wet ?? 0.3;
298
+ this._wet = wetMix;
285
299
  this.dry.gain.value = 1 - wetMix;
286
300
  this.wet.gain.value = wetMix;
287
301
  if (config.impulse) {
@@ -295,6 +309,8 @@ var Reverb = class {
295
309
  }
296
310
  setWet(mix) {
297
311
  const m = Math.max(0, Math.min(1, mix));
312
+ this._wet = m;
313
+ if (this._bypassed) return;
298
314
  const t = this.ctx.currentTime;
299
315
  this.dry.gain.setValueAtTime(1 - m, t);
300
316
  this.wet.gain.setValueAtTime(m, t);
@@ -308,7 +324,14 @@ var Reverb = class {
308
324
  set bypassed(v) {
309
325
  if (this._bypassed === v) return;
310
326
  this._bypassed = v;
311
- this.wet.gain.value = v ? 0 : 0.3;
327
+ const t = this.ctx.currentTime;
328
+ if (v) {
329
+ this.dry.gain.setValueAtTime(1, t);
330
+ this.wet.gain.setValueAtTime(0, t);
331
+ } else {
332
+ this.dry.gain.setValueAtTime(1 - this._wet, t);
333
+ this.wet.gain.setValueAtTime(this._wet, t);
334
+ }
312
335
  }
313
336
  dispose() {
314
337
  try {
@@ -466,18 +489,11 @@ class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
466
489
  constructor(options) {
467
490
  super();
468
491
  const grain = (options && options.processorOptions && options.processorOptions.grainSize) || 1024;
469
- this.grainSize = grain;
470
492
  this.ringSize = grain * 8;
471
493
  this.ringL = new Float32Array(this.ringSize);
472
494
  this.ringR = new Float32Array(this.ringSize);
473
495
  this.writePos = 0;
474
496
  this.readPos = 0;
475
- this.window = new Float32Array(grain);
476
- for (let i = 0; i < grain; i++) {
477
- const t = i / (grain - 1);
478
- // Hann window for OLA crossfade.
479
- this.window[i] = 0.5 * (1 - Math.cos(2 * Math.PI * t));
480
- }
481
497
  }
482
498
 
483
499
  process(inputs, outputs, params) {
@@ -583,16 +599,20 @@ function applyRamp(param, now, to, duration, curve) {
583
599
  const samples = sampleCurve(from, to, curve, 64);
584
600
  param.setValueCurveAtTime(samples, now, seconds);
585
601
  }
602
+ function equalPowerCurve(from, to, n = 33) {
603
+ return sampleCurve(from, to, "equal-power", n);
604
+ }
586
605
  function sampleCurve(from, to, curve, n) {
587
606
  const out = new Float32Array(n);
607
+ const rising = to >= from;
588
608
  for (let i = 0; i < n; i++) {
589
609
  const t = i / (n - 1);
590
- const eased = ease(t, curve);
610
+ const eased = ease(t, curve, rising);
591
611
  out[i] = from + (to - from) * eased;
592
612
  }
593
613
  return out;
594
614
  }
595
- function ease(t, curve) {
615
+ function ease(t, curve, rising = true) {
596
616
  switch (curve) {
597
617
  case "easeIn":
598
618
  return t * t;
@@ -600,8 +620,9 @@ function ease(t, curve) {
600
620
  return 1 - (1 - t) * (1 - t);
601
621
  case "easeInOut":
602
622
  return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
603
- case "equal-power":
604
- return Math.sin(t * Math.PI / 2) ** 2;
623
+ case "equal-power": {
624
+ return rising ? Math.sin(t * Math.PI / 2) : 1 - Math.cos(t * Math.PI / 2);
625
+ }
605
626
  default:
606
627
  return t;
607
628
  }
@@ -653,13 +674,15 @@ var Send = class {
653
674
  var Bus = class {
654
675
  name;
655
676
  input;
656
- /** Sub-bus where FX inserts go. Currently == input; reserved for FX chain. */
677
+ /** Sub-bus the FX chain splices into: input → fxInput → (fx…) → output. */
657
678
  fxInput;
658
679
  /** Output node — connect to master.input or another bus.input for sends. */
659
680
  output;
660
681
  _level;
661
682
  _muted;
662
683
  _soloed = false;
684
+ /** True while the engine's solo rule is silencing this (non-soloed) bus. */
685
+ _soloVeiled = false;
663
686
  ctx;
664
687
  _concurrency;
665
688
  _voices = /* @__PURE__ */ new Set();
@@ -694,19 +717,20 @@ var Bus = class {
694
717
  }
695
718
  set level(v) {
696
719
  this._level = clamp01(v);
697
- if (!this._muted) this.rampOutput(this._level, 0.01);
720
+ if (!this._muted && !this._soloVeiled) this.rampOutput(this._level, 0.01);
698
721
  }
699
722
  get muted() {
700
723
  return this._muted;
701
724
  }
702
725
  set muted(v) {
703
726
  this._muted = v;
704
- this.rampOutput(v ? 0 : this._level, 0.01);
727
+ this.rampOutput(v || this._soloVeiled ? 0 : this._level, 0.01);
705
728
  }
706
729
  /** Fade the bus output to `target` over `duration` seconds. */
707
730
  fadeTo(target, duration, curve = "linear") {
708
731
  const to = clamp01(target);
709
732
  this._level = to;
733
+ if (this._muted || this._soloVeiled) return wait(duration);
710
734
  return this.ramp(to, duration, curve);
711
735
  }
712
736
  /** Active voice count on this bus. */
@@ -767,7 +791,7 @@ var Bus = class {
767
791
  this.rewireFxChain();
768
792
  }
769
793
  fx() {
770
- return this._fxChain;
794
+ return [...this._fxChain];
771
795
  }
772
796
  /**
773
797
  * Live amplitude readout on the bus output. Returns `{ rms, peak }` as
@@ -827,7 +851,7 @@ var Bus = class {
827
851
  }
828
852
  /** Read-only snapshot of every active send originating on this bus. */
829
853
  sends() {
830
- return this._sends;
854
+ return [...this._sends];
831
855
  }
832
856
  /**
833
857
  * Solo this bus. The engine coordinates the global rule: while any bus
@@ -858,6 +882,7 @@ var Bus = class {
858
882
  * user-visible mute state without re-rendering.
859
883
  */
860
884
  applySoloVeil(soloMute) {
885
+ this._soloVeiled = soloMute;
861
886
  const target = this._muted ? 0 : soloMute ? 0 : this._level;
862
887
  this.rampOutput(target, 0.01);
863
888
  }
@@ -884,6 +909,10 @@ var Bus = class {
884
909
  return wait(duration);
885
910
  }
886
911
  dispose() {
912
+ for (const send of this._sends) send.dispose();
913
+ this._sends = [];
914
+ for (const fx of this._fxChain) fx.dispose();
915
+ this._fxChain = [];
887
916
  try {
888
917
  this.input.disconnect();
889
918
  this.fxInput.disconnect();
@@ -1013,14 +1042,15 @@ var Parameter = class {
1013
1042
  const from = opts.from ?? 0;
1014
1043
  const to = opts.to ?? 1;
1015
1044
  const curve = opts.curve ?? "linear";
1045
+ const rising = to >= from;
1016
1046
  return this.subscribe((v) => {
1017
1047
  const t = Math.max(0, Math.min(1, v));
1018
- const eased = ease2(t, curve);
1048
+ const eased = ease2(t, curve, rising);
1019
1049
  setter(from + (to - from) * eased);
1020
1050
  });
1021
1051
  }
1022
1052
  };
1023
- function ease2(t, curve) {
1053
+ function ease2(t, curve, rising = true) {
1024
1054
  switch (curve) {
1025
1055
  case "easeIn":
1026
1056
  return t * t;
@@ -1029,7 +1059,7 @@ function ease2(t, curve) {
1029
1059
  case "easeInOut":
1030
1060
  return t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);
1031
1061
  case "equal-power":
1032
- return Math.sin(t * Math.PI / 2) ** 2;
1062
+ return rising ? Math.sin(t * Math.PI / 2) : 1 - Math.cos(t * Math.PI / 2);
1033
1063
  default:
1034
1064
  return t;
1035
1065
  }
@@ -1313,12 +1343,12 @@ var DEFAULTS = {
1313
1343
  targetRms: 0.1,
1314
1344
  peakCeiling: 0.99
1315
1345
  };
1316
- function applyLoudnessNormalization(buffer, flag) {
1346
+ function applyLoudnessNormalization(buffer, flag, ctx) {
1317
1347
  if (!flag) return buffer;
1318
1348
  const opts = { ...DEFAULTS, ...typeof flag === "object" ? flag : {} };
1319
1349
  const gain = computeNormalizationGain(buffer, opts);
1320
1350
  if (Math.abs(gain - 1) < 1e-3) return buffer;
1321
- return scaleBuffer(buffer, gain);
1351
+ return scaleBuffer(buffer, gain, ctx);
1322
1352
  }
1323
1353
  function computeNormalizationGain(buffer, opts) {
1324
1354
  const rms = measureRms(buffer);
@@ -1350,7 +1380,16 @@ function measurePeak(buffer) {
1350
1380
  }
1351
1381
  return peak;
1352
1382
  }
1353
- function scaleBuffer(src, gain) {
1383
+ function scaleBuffer(src, gain, ctx) {
1384
+ if (ctx) {
1385
+ const out = ctx.createBuffer(src.numberOfChannels, src.length, src.sampleRate);
1386
+ for (let c = 0; c < src.numberOfChannels; c++) {
1387
+ const from = src.getChannelData(c);
1388
+ const to = out.getChannelData(c);
1389
+ for (let i = 0; i < from.length; i++) to[i] = from[i] * gain;
1390
+ }
1391
+ return out;
1392
+ }
1354
1393
  for (let c = 0; c < src.numberOfChannels; c++) {
1355
1394
  const data = src.getChannelData(c);
1356
1395
  for (let i = 0; i < data.length; i++) data[i] = data[i] * gain;
@@ -1624,14 +1663,14 @@ var MusicVoice = class {
1624
1663
  const segGain = this.ctx.createGain();
1625
1664
  if (fadeIn) {
1626
1665
  segGain.gain.setValueAtTime(0, when);
1627
- segGain.gain.linearRampToValueAtTime(1, when + this.loopCrossfadeSec);
1666
+ segGain.gain.setValueCurveAtTime(equalPowerCurve(0, 1), when, this.loopCrossfadeSec);
1628
1667
  } else {
1629
1668
  segGain.gain.setValueAtTime(1, when);
1630
1669
  }
1631
1670
  if (this.crossfadeViable()) {
1632
1671
  const fadeOutAt = when + this.buffers.loop.duration - this.loopCrossfadeSec;
1633
1672
  segGain.gain.setValueAtTime(1, fadeOutAt);
1634
- segGain.gain.linearRampToValueAtTime(0, when + this.buffers.loop.duration);
1673
+ segGain.gain.setValueCurveAtTime(equalPowerCurve(1, 0), fadeOutAt, this.loopCrossfadeSec);
1635
1674
  }
1636
1675
  src.connect(segGain).connect(this.gain);
1637
1676
  try {
@@ -2104,6 +2143,10 @@ var Voice = class _Voice {
2104
2143
  }
2105
2144
  /** Async iterator of lifecycle cues — yields started, optional paused, ended. */
2106
2145
  async *cues() {
2146
+ if (this.done) {
2147
+ yield "ended";
2148
+ return;
2149
+ }
2107
2150
  const queue = [];
2108
2151
  let waiter = null;
2109
2152
  const push = (c) => {
@@ -2125,7 +2168,10 @@ var Voice = class _Voice {
2125
2168
  if (next2 === "ended") return;
2126
2169
  continue;
2127
2170
  }
2128
- if (this.done) return;
2171
+ if (this.done) {
2172
+ yield "ended";
2173
+ return;
2174
+ }
2129
2175
  const next = await new Promise((res) => {
2130
2176
  waiter = res;
2131
2177
  });
@@ -2220,13 +2266,13 @@ var Voice = class _Voice {
2220
2266
  const segGain = this.ctx.createGain();
2221
2267
  if (fadeIn) {
2222
2268
  segGain.gain.setValueAtTime(0, when);
2223
- segGain.gain.linearRampToValueAtTime(1, when + this.crossfadeSec);
2269
+ segGain.gain.setValueCurveAtTime(equalPowerCurve(0, 1), when, this.crossfadeSec);
2224
2270
  } else {
2225
2271
  segGain.gain.setValueAtTime(1, when);
2226
2272
  }
2227
2273
  const fadeOutAt = when + this.crossfadeRegionLen - this.crossfadeSec;
2228
2274
  segGain.gain.setValueAtTime(1, fadeOutAt);
2229
- segGain.gain.linearRampToValueAtTime(0, when + this.crossfadeRegionLen);
2275
+ segGain.gain.setValueCurveAtTime(equalPowerCurve(1, 0), fadeOutAt, this.crossfadeSec);
2230
2276
  src.connect(segGain).connect(this.gain);
2231
2277
  try {
2232
2278
  src.start(when, this.crossfadeRegionStart, this.crossfadeRegionLen);
@@ -2280,11 +2326,12 @@ var Voice = class _Voice {
2280
2326
  return offset;
2281
2327
  }
2282
2328
  };
2283
- function resolveJittered(v, base = 1) {
2329
+ function resolveJittered(v, fallbackBase = 1) {
2284
2330
  if (typeof v === "number") return v;
2285
- if (!v || v.jitter == null) return base;
2286
- const j = v.jitter;
2287
- return base + (Math.random() * 2 - 1) * j;
2331
+ if (!v) return fallbackBase;
2332
+ const center = v.base ?? fallbackBase;
2333
+ if (v.jitter == null) return center;
2334
+ return center + (Math.random() * 2 - 1) * v.jitter;
2288
2335
  }
2289
2336
  function clamp013(v) {
2290
2337
  if (Number.isNaN(v)) return 0;
@@ -2567,7 +2614,7 @@ var Spatializer = class {
2567
2614
  const filter = ctx.createBiquadFilter();
2568
2615
  filter.type = "lowpass";
2569
2616
  filter.frequency.value = OCCLUSION_OPEN_HZ;
2570
- filter.Q.value = 0.707;
2617
+ filter.Q.value = Math.SQRT1_2;
2571
2618
  const gain = ctx.createGain();
2572
2619
  gain.gain.value = 1;
2573
2620
  panner.connect(filter).connect(gain);
@@ -2788,6 +2835,39 @@ var Snapshot = class {
2788
2835
  }
2789
2836
  return Promise.all(tasks).then(() => void 0);
2790
2837
  }
2838
+ /**
2839
+ * Snap the live mix to a linear interpolation between this snapshot and
2840
+ * `other`. `t` is clamped to [0, 1]: `t = 0` matches this snapshot,
2841
+ * `t = 1` matches `other`, and intermediate values lerp every shared
2842
+ * bus level and parameter.
2843
+ *
2844
+ * Designed to be called continuously (e.g. from a `Parameter` subscriber)
2845
+ * — each call snaps instantly. For a one-shot crossfade with a fade
2846
+ * duration, use `apply({ fade })` instead.
2847
+ *
2848
+ * Buses or parameters present in only one of the two snapshots are
2849
+ * skipped. Mute flags are not interpolated: `t < 0.5` uses this
2850
+ * snapshot's mute, `t >= 0.5` uses `other`'s.
2851
+ */
2852
+ blendWith(other, t) {
2853
+ const u = t < 0 ? 0 : t > 1 ? 1 : t;
2854
+ const v = 1 - u;
2855
+ for (const [name, busA] of Object.entries(this.state.buses)) {
2856
+ const busB = other.state.buses[name];
2857
+ if (!busB) continue;
2858
+ const bus = this.getBus(name);
2859
+ if (!bus) continue;
2860
+ bus.muted = u < 0.5 ? busA.muted : busB.muted;
2861
+ bus.level = busA.level * v + busB.level * u;
2862
+ }
2863
+ for (const [name, valA] of Object.entries(this.state.parameters)) {
2864
+ const valB = other.state.parameters[name];
2865
+ if (valB === void 0) continue;
2866
+ const param = this.getParam(name);
2867
+ if (!param) continue;
2868
+ param.set(valA * v + valB * u);
2869
+ }
2870
+ }
2791
2871
  };
2792
2872
 
2793
2873
  // src/mixer/engine.ts
@@ -2874,7 +2954,7 @@ var EngineImpl = class {
2874
2954
  const decodeOpts = { signal: options.signal };
2875
2955
  let buffer = await this.resolveBuffer(name, url, decodeOpts);
2876
2956
  if (options.normalize) {
2877
- buffer = applyLoudnessNormalization(buffer, options.normalize);
2957
+ buffer = applyLoudnessNormalization(buffer, options.normalize, this.host.touch());
2878
2958
  }
2879
2959
  this.soundUrls.set(name, typeof url === "string" ? [url] : [...url]);
2880
2960
  return this.createSound(name, buffer, { bus: options.bus });
@@ -2980,10 +3060,11 @@ var EngineImpl = class {
2980
3060
  const loopBuf = await this.resolveBuffer(`__music:${name}:loop`, parts.loop, decodeOpts);
2981
3061
  const introBuf = parts.intro ? await this.resolveBuffer(`__music:${name}:intro`, parts.intro, decodeOpts) : void 0;
2982
3062
  const outroBuf = parts.outro ? await this.resolveBuffer(`__music:${name}:outro`, parts.outro, decodeOpts) : void 0;
3063
+ const ctx = this.host.touch();
2983
3064
  const buffers = {
2984
- intro: introBuf ? options.normalize ? applyLoudnessNormalization(introBuf, options.normalize) : introBuf : void 0,
2985
- loop: options.normalize ? applyLoudnessNormalization(loopBuf, options.normalize) : loopBuf,
2986
- outro: outroBuf ? options.normalize ? applyLoudnessNormalization(outroBuf, options.normalize) : outroBuf : void 0
3065
+ intro: introBuf ? options.normalize ? applyLoudnessNormalization(introBuf, options.normalize, ctx) : introBuf : void 0,
3066
+ loop: options.normalize ? applyLoudnessNormalization(loopBuf, options.normalize, ctx) : loopBuf,
3067
+ outro: outroBuf ? options.normalize ? applyLoudnessNormalization(outroBuf, options.normalize, ctx) : outroBuf : void 0
2987
3068
  };
2988
3069
  const busName = options.bus ?? this.busOrder[0];
2989
3070
  const bus = this.buses.get(busName);
@@ -3037,7 +3118,9 @@ var EngineImpl = class {
3037
3118
  volume: 0
3038
3119
  });
3039
3120
  void newVoice.fade({ to: toVolume, duration, curve });
3040
- const outgoing = this.activeVoices().filter((v) => v !== newVoice && v.sourceName === from);
3121
+ const outgoing = this.activeVoices().filter(
3122
+ (v) => v !== newVoice && v.sourceName === from && v.bus === newVoice.bus
3123
+ );
3041
3124
  for (const v of outgoing) {
3042
3125
  void v.fade({ to: 0, duration, curve }).then(() => v.stop());
3043
3126
  }
@@ -3171,6 +3254,9 @@ var EngineImpl = class {
3171
3254
  (paramName) => this.parameters.get(paramName)
3172
3255
  );
3173
3256
  }
3257
+ blendSnapshots(a, b, t) {
3258
+ a.blendWith(b, t);
3259
+ }
3174
3260
  /**
3175
3261
  * Lazily instantiate the bus graph against the live AudioContext. Called
3176
3262
  * from any path that touches the context (unlock, loadSound, bus, ...).
@@ -3232,10 +3318,20 @@ function combineSignals(a, b) {
3232
3318
  if (a.aborted) return a;
3233
3319
  if (b.aborted) return b;
3234
3320
  const ac = new AbortController();
3235
- const onAbortA = () => ac.abort(a.reason);
3236
- const onAbortB = () => ac.abort(b.reason);
3237
- a.addEventListener("abort", onAbortA, { once: true });
3238
- b.addEventListener("abort", onAbortB, { once: true });
3321
+ const cleanup = () => {
3322
+ a.removeEventListener("abort", onAbortA);
3323
+ b.removeEventListener("abort", onAbortB);
3324
+ };
3325
+ const onAbortA = () => {
3326
+ cleanup();
3327
+ ac.abort(a.reason);
3328
+ };
3329
+ const onAbortB = () => {
3330
+ cleanup();
3331
+ ac.abort(b.reason);
3332
+ };
3333
+ a.addEventListener("abort", onAbortA);
3334
+ b.addEventListener("abort", onAbortB);
3239
3335
  return ac.signal;
3240
3336
  }
3241
3337
  function levenshtein(a, b) {