@schmooky/zvuk 1.8.0 → 1.10.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
@@ -608,6 +608,48 @@ function ease(t, curve) {
608
608
  }
609
609
 
610
610
  // src/mixer/bus.ts
611
+ var Send = class {
612
+ source;
613
+ target;
614
+ post;
615
+ gainNode;
616
+ ctx;
617
+ disposed = false;
618
+ constructor(source, target, options, ctx) {
619
+ this.source = source;
620
+ this.target = target;
621
+ this.post = options.post ?? true;
622
+ this.ctx = ctx;
623
+ this.gainNode = ctx.createGain();
624
+ this.gainNode.gain.value = clamp01(options.amount ?? 1);
625
+ const tap = this.post ? source.output : source.input;
626
+ tap.connect(this.gainNode);
627
+ this.gainNode.connect(target.input);
628
+ }
629
+ /** Live send level (0..1). Setter ramps over 10 ms to avoid clicks. */
630
+ get amount() {
631
+ return this.gainNode.gain.value;
632
+ }
633
+ set amount(v) {
634
+ if (this.disposed) return;
635
+ applyRamp(this.gainNode.gain, this.ctx.currentTime, clamp01(v), 0.01, "linear");
636
+ }
637
+ /** Fade the send to `target` over `duration` seconds. */
638
+ fadeTo(target, duration, curve = "linear") {
639
+ if (this.disposed) return Promise.resolve();
640
+ applyRamp(this.gainNode.gain, this.ctx.currentTime, clamp01(target), duration, curve);
641
+ if (duration <= 0) return Promise.resolve();
642
+ return new Promise((res) => setTimeout(res, duration * 1e3));
643
+ }
644
+ dispose() {
645
+ if (this.disposed) return;
646
+ this.disposed = true;
647
+ try {
648
+ this.gainNode.disconnect();
649
+ } catch {
650
+ }
651
+ }
652
+ };
611
653
  var Bus = class {
612
654
  name;
613
655
  input;
@@ -617,14 +659,23 @@ var Bus = class {
617
659
  output;
618
660
  _level;
619
661
  _muted;
662
+ _soloed = false;
620
663
  ctx;
621
664
  _concurrency;
622
665
  _voices = /* @__PURE__ */ new Set();
623
666
  _fxChain = [];
667
+ _sends = [];
624
668
  // Lazy meter tap. Connected as a passive sibling of bus.output → master.input
625
669
  // so the audio path is unchanged.
626
670
  _meterAnalyser = null;
627
671
  _meterBuf = null;
672
+ /**
673
+ * Engine-injected callback fired when this bus's solo state changes.
674
+ * The Engine uses it to coordinate the global "any soloed → mute the
675
+ * rest" rule across every bus in the graph. Bus does not depend on
676
+ * Engine; the callback is the only escape hatch.
677
+ */
678
+ notifySoloChange;
628
679
  constructor(ctx, name, config = {}) {
629
680
  this.ctx = ctx;
630
681
  this.name = name;
@@ -747,6 +798,69 @@ var Bus = class {
747
798
  }
748
799
  return { rms: Math.sqrt(sumSq / buf.length), peak };
749
800
  }
801
+ /**
802
+ * Route a copy of this bus's signal into another bus at the configured
803
+ * level. `target.input` mixes the send naturally with whatever else is
804
+ * already feeding it, so the typical pattern — "send 30 % of music to a
805
+ * dedicated reverb bus" — is just two lines:
806
+ *
807
+ * ```ts
808
+ * const verbSend = engine.bus('music').send(engine.bus('reverb'), { amount: 0.3 });
809
+ * verbSend.amount = 0.5; // turn it up live
810
+ * verbSend.dispose(); // remove the send entirely
811
+ * ```
812
+ *
813
+ * Default tap is post-fader / post-FX (`post: true`); set `post: false`
814
+ * if you want a monitor send that hears the dry pre-fader signal.
815
+ */
816
+ send(target, options = {}) {
817
+ const send = new Send(this, target, options, this.ctx);
818
+ this._sends.push(send);
819
+ return send;
820
+ }
821
+ /** Remove a previously-created send. Idempotent. */
822
+ removeSend(send) {
823
+ const idx = this._sends.indexOf(send);
824
+ if (idx === -1) return;
825
+ this._sends.splice(idx, 1);
826
+ send.dispose();
827
+ }
828
+ /** Read-only snapshot of every active send originating on this bus. */
829
+ sends() {
830
+ return this._sends;
831
+ }
832
+ /**
833
+ * Solo this bus. The engine coordinates the global rule: while any bus
834
+ * is soloed, every non-soloed bus is muted. Soloing multiple buses is
835
+ * additive — they all stay audible. Calling `unsolo()` (or `solo(false)`)
836
+ * removes this bus from the soloed set.
837
+ *
838
+ * Solo state is independent of `muted`; un-soloing returns the bus to
839
+ * whatever its `muted` setting was. Useful in mixer UIs where the user
840
+ * wants to A/B a single channel without disturbing the rest of the mix.
841
+ */
842
+ solo(on = true) {
843
+ if (this._soloed === on) return;
844
+ this._soloed = on;
845
+ this.notifySoloChange?.(this, on);
846
+ }
847
+ /** Turn solo off on this bus. Equivalent to `solo(false)`. */
848
+ unsolo() {
849
+ this.solo(false);
850
+ }
851
+ /** True when this bus is in the engine's solo set. */
852
+ get soloed() {
853
+ return this._soloed;
854
+ }
855
+ /**
856
+ * Engine-only. Apply a transient mute (or restore) driven by the global
857
+ * solo state. Distinct from `muted` so un-soloing returns the bus to its
858
+ * user-visible mute state without re-rendering.
859
+ */
860
+ applySoloVeil(soloMute) {
861
+ const target = this._muted ? 0 : soloMute ? 0 : this._level;
862
+ this.rampOutput(target, 0.01);
863
+ }
750
864
  rewireFxChain() {
751
865
  try {
752
866
  this.fxInput.disconnect();
@@ -819,6 +933,55 @@ function pickVictim(voices, strategy, newVoice) {
819
933
  return victim;
820
934
  }
821
935
 
936
+ // src/mixer/bus-group.ts
937
+ var BusGroup = class {
938
+ name;
939
+ members;
940
+ constructor(name, members) {
941
+ this.name = name;
942
+ this.members = members;
943
+ }
944
+ /** Set the level on every member. Same 10 ms ramp as direct `bus.level =`. */
945
+ set level(v) {
946
+ for (const b of this.members) b.level = v;
947
+ }
948
+ /**
949
+ * Read the current level. Returns the average across members — useful
950
+ * when every member shares a level (the common case) and informational
951
+ * otherwise.
952
+ */
953
+ get level() {
954
+ if (this.members.length === 0) return 0;
955
+ let sum = 0;
956
+ for (const b of this.members) sum += b.level;
957
+ return sum / this.members.length;
958
+ }
959
+ set muted(v) {
960
+ for (const b of this.members) b.muted = v;
961
+ }
962
+ /** True if every member is currently muted. */
963
+ get muted() {
964
+ if (this.members.length === 0) return false;
965
+ return this.members.every((b) => b.muted);
966
+ }
967
+ /**
968
+ * Fade every member to `target` over `duration` seconds. Returns when
969
+ * the slowest leg completes — in practice they're all equal because
970
+ * each member uses the same duration.
971
+ */
972
+ fadeTo(target, duration, curve = "linear") {
973
+ return Promise.all(this.members.map((b) => b.fadeTo(target, duration, curve))).then(() => void 0);
974
+ }
975
+ /** Solo every member of the group. Engine handles the global mute-the-rest rule. */
976
+ solo(on = true) {
977
+ for (const b of this.members) b.solo(on);
978
+ }
979
+ /** Un-solo every member. */
980
+ unsolo() {
981
+ this.solo(false);
982
+ }
983
+ };
984
+
822
985
  // src/params/parameter.ts
823
986
  var Parameter = class {
824
987
  name;
@@ -2308,50 +2471,113 @@ function clamp014(v) {
2308
2471
  }
2309
2472
 
2310
2473
  // src/spatial/spatializer.ts
2474
+ var DEFAULT_REF_DISTANCE = 1;
2475
+ var DEFAULT_MAX_DISTANCE = 1e4;
2476
+ var DEFAULT_ROLLOFF = 1;
2477
+ var DEFAULT_DISTANCE_MODEL = "inverse";
2478
+ var OCCLUSION_OPEN_HZ = 22050;
2479
+ var OCCLUSION_MUFFLED_HZ = 500;
2311
2480
  var Spatializer = class {
2312
- node;
2481
+ ctx;
2313
2482
  kind;
2483
+ input;
2484
+ // what the Voice connects into
2485
+ output;
2486
+ // what we connect to the Bus
2487
+ // 2D-only.
2488
+ stereoPan = null;
2489
+ // 3D-only.
2490
+ panner = null;
2491
+ occlusionFilter = null;
2492
+ occlusionGain = null;
2314
2493
  constructor(ctx, opts) {
2494
+ this.ctx = ctx;
2315
2495
  if (opts.position) {
2316
2496
  const panner = ctx.createPanner();
2317
2497
  panner.panningModel = "HRTF";
2318
- panner.distanceModel = "inverse";
2319
- panner.refDistance = 1;
2320
- panner.maxDistance = 1e3;
2321
- panner.rolloffFactor = 1;
2498
+ panner.distanceModel = opts.distanceModel ?? DEFAULT_DISTANCE_MODEL;
2499
+ panner.refDistance = opts.refDistance ?? DEFAULT_REF_DISTANCE;
2500
+ panner.maxDistance = opts.maxDistance ?? DEFAULT_MAX_DISTANCE;
2501
+ panner.rolloffFactor = opts.rolloffFactor ?? DEFAULT_ROLLOFF;
2322
2502
  const [x, y, z] = opts.position;
2323
2503
  this.setPanner3D(panner, x, y, z);
2324
- this.node = panner;
2504
+ const filter = ctx.createBiquadFilter();
2505
+ filter.type = "lowpass";
2506
+ filter.frequency.value = OCCLUSION_OPEN_HZ;
2507
+ filter.Q.value = 0.707;
2508
+ const gain = ctx.createGain();
2509
+ gain.gain.value = 1;
2510
+ panner.connect(filter).connect(gain);
2511
+ this.panner = panner;
2512
+ this.occlusionFilter = filter;
2513
+ this.occlusionGain = gain;
2514
+ this.input = panner;
2515
+ this.output = gain;
2325
2516
  this.kind = "3d";
2517
+ if (opts.occlusion != null) this.setOcclusion(opts.occlusion);
2326
2518
  } else {
2327
2519
  const sp = ctx.createStereoPanner();
2328
2520
  sp.pan.value = clampPan(opts.pan ?? 0);
2329
- this.node = sp;
2521
+ this.stereoPan = sp;
2522
+ this.input = sp;
2523
+ this.output = sp;
2330
2524
  this.kind = "2d";
2331
2525
  }
2332
2526
  }
2333
2527
  setPan(pan) {
2334
- if (this.kind !== "2d") return;
2335
- this.node.pan.value = clampPan(pan);
2528
+ if (this.kind !== "2d" || !this.stereoPan) return;
2529
+ this.stereoPan.pan.value = clampPan(pan);
2336
2530
  }
2337
2531
  setPosition(x, y, z) {
2338
- if (this.kind !== "3d") return;
2339
- this.setPanner3D(this.node, x, y, z);
2532
+ if (this.kind !== "3d" || !this.panner) return;
2533
+ this.setPanner3D(this.panner, x, y, z);
2534
+ }
2535
+ setRefDistance(d) {
2536
+ if (!this.panner) return;
2537
+ this.panner.refDistance = Math.max(0, d);
2538
+ }
2539
+ setMaxDistance(d) {
2540
+ if (!this.panner) return;
2541
+ this.panner.maxDistance = Math.max(0, d);
2542
+ }
2543
+ setRolloffFactor(f) {
2544
+ if (!this.panner) return;
2545
+ this.panner.rolloffFactor = Math.max(0, f);
2546
+ }
2547
+ setDistanceModel(m) {
2548
+ if (!this.panner) return;
2549
+ this.panner.distanceModel = m;
2550
+ }
2551
+ /**
2552
+ * Set occlusion amount (0..1). Drives the internal lowpass cutoff
2553
+ * and a small gain dip — independent of distance attenuation.
2554
+ * No-op on 2D spatializers.
2555
+ */
2556
+ setOcclusion(amount) {
2557
+ if (!this.occlusionFilter || !this.occlusionGain) return;
2558
+ const a = clamp015(amount);
2559
+ const cutoff = OCCLUSION_OPEN_HZ * (OCCLUSION_MUFFLED_HZ / OCCLUSION_OPEN_HZ) ** a;
2560
+ const now = this.ctx.currentTime;
2561
+ this.occlusionFilter.frequency.setValueAtTime(cutoff, now);
2562
+ const gainLin = 10 ** (-6 * a / 20);
2563
+ this.occlusionGain.gain.setValueAtTime(gainLin, now);
2340
2564
  }
2341
- /** Connects internal node into `dest` and returns the input the Voice should use. */
2565
+ /** Connects the spatializer's output into `dest` and returns the input the Voice should use. */
2342
2566
  connectInto(dest) {
2343
- this.node.connect(dest);
2344
- return this.node;
2567
+ this.output.connect(dest);
2568
+ return this.input;
2345
2569
  }
2346
2570
  dispose() {
2347
2571
  try {
2348
- this.node.disconnect();
2572
+ this.input.disconnect();
2573
+ this.occlusionFilter?.disconnect();
2574
+ this.occlusionGain?.disconnect();
2349
2575
  } catch {
2350
2576
  }
2351
2577
  }
2352
2578
  setPanner3D(p, x, y, z) {
2353
2579
  if (typeof p.positionX?.setValueAtTime === "function") {
2354
- const now = p.context.currentTime;
2580
+ const now = this.ctx.currentTime;
2355
2581
  p.positionX.setValueAtTime(x, now);
2356
2582
  p.positionY.setValueAtTime(y, now);
2357
2583
  p.positionZ.setValueAtTime(z, now);
@@ -2364,6 +2590,10 @@ var Spatializer = class {
2364
2590
  function clampPan(v) {
2365
2591
  return Math.max(-1, Math.min(1, v));
2366
2592
  }
2593
+ function clamp015(v) {
2594
+ if (Number.isNaN(v)) return 0;
2595
+ return Math.max(0, Math.min(1, v));
2596
+ }
2367
2597
 
2368
2598
  // src/mixer/master.ts
2369
2599
  var Master = class {
@@ -2373,6 +2603,8 @@ var Master = class {
2373
2603
  limiterNode = null;
2374
2604
  limiterCfg;
2375
2605
  destination;
2606
+ _meterAnalyser = null;
2607
+ _meterBuf = null;
2376
2608
  constructor(ctx, config = {}) {
2377
2609
  this.ctx = ctx;
2378
2610
  this.input = ctx.createGain();
@@ -2401,13 +2633,42 @@ var Master = class {
2401
2633
  get reduction() {
2402
2634
  return this.limiterNode?.reduction ?? 0;
2403
2635
  }
2636
+ /**
2637
+ * Live amplitude readout on the master input. Returns `{ rms, peak }`
2638
+ * as linear values in [0..1]. The first call lazily attaches an
2639
+ * AnalyserNode as a passive sibling of the master gain — no audio-path
2640
+ * change. Same shape as `bus.meter()` and `voice.level()`.
2641
+ */
2642
+ meter() {
2643
+ if (!this._meterAnalyser) {
2644
+ const a = this.ctx.createAnalyser();
2645
+ a.fftSize = 1024;
2646
+ this.input.connect(a);
2647
+ this._meterAnalyser = a;
2648
+ this._meterBuf = new Float32Array(a.fftSize);
2649
+ }
2650
+ const buf = this._meterBuf;
2651
+ this._meterAnalyser.getFloatTimeDomainData(buf);
2652
+ let sumSq = 0;
2653
+ let peak = 0;
2654
+ for (let i = 0; i < buf.length; i++) {
2655
+ const s = buf[i] ?? 0;
2656
+ sumSq += s * s;
2657
+ const a = Math.abs(s);
2658
+ if (a > peak) peak = a;
2659
+ }
2660
+ return { rms: Math.sqrt(sumSq / buf.length), peak };
2661
+ }
2404
2662
  dispose() {
2405
2663
  try {
2406
2664
  this.input.disconnect();
2407
2665
  this.limiterNode?.disconnect();
2666
+ this._meterAnalyser?.disconnect();
2408
2667
  } catch {
2409
2668
  }
2410
2669
  this.limiterNode = null;
2670
+ this._meterAnalyser = null;
2671
+ this._meterBuf = null;
2411
2672
  }
2412
2673
  rewire() {
2413
2674
  try {
@@ -2481,6 +2742,8 @@ var EngineImpl = class {
2481
2742
  sprites = /* @__PURE__ */ new Map();
2482
2743
  streams = /* @__PURE__ */ new Map();
2483
2744
  musics = /* @__PURE__ */ new Map();
2745
+ busGroups = /* @__PURE__ */ new Map();
2746
+ soloedBuses = /* @__PURE__ */ new Set();
2484
2747
  voices = /* @__PURE__ */ new Map();
2485
2748
  parameters = /* @__PURE__ */ new Map();
2486
2749
  config;
@@ -2749,6 +3012,22 @@ var EngineImpl = class {
2749
3012
  if (!b) throw new BusNotFoundError(suggest(name, [...this.buses.keys()]));
2750
3013
  return b;
2751
3014
  }
3015
+ busGroup(name, members) {
3016
+ if (members != null) {
3017
+ const group = new BusGroup(name, members);
3018
+ this.busGroups.set(name, group);
3019
+ return group;
3020
+ }
3021
+ const existing = this.busGroups.get(name);
3022
+ if (!existing) {
3023
+ throw new BusNotFoundError(suggest(name, [...this.busGroups.keys()]));
3024
+ }
3025
+ return existing;
3026
+ }
3027
+ masterMeter() {
3028
+ this.ensureGraph();
3029
+ return this.master.meter();
3030
+ }
2752
3031
  scheduleAt(audioTime, fn) {
2753
3032
  this.host.touch();
2754
3033
  this.ensureGraph();
@@ -2798,10 +3077,29 @@ var EngineImpl = class {
2798
3077
  const cfg = this.config.buses?.[name] ?? {};
2799
3078
  const bus = new Bus(ctx, name, cfg);
2800
3079
  bus.output.connect(this.master.input);
3080
+ bus.notifySoloChange = (b, soloed) => this.handleSoloChange(b, soloed);
2801
3081
  this.buses.set(name, bus);
2802
3082
  if (!this.voices.has(name)) this.voices.set(name, /* @__PURE__ */ new Set());
2803
3083
  }
2804
3084
  }
3085
+ /**
3086
+ * Coordinate the global solo rule. When any bus is in the solo set,
3087
+ * every non-soloed bus is muted via `applySoloVeil(true)`. When the
3088
+ * solo set drains, every bus is restored via `applySoloVeil(false)` —
3089
+ * which honours the bus's own `muted` setting independently.
3090
+ */
3091
+ handleSoloChange(bus, soloed) {
3092
+ if (soloed) this.soloedBuses.add(bus);
3093
+ else this.soloedBuses.delete(bus);
3094
+ const anySoloed = this.soloedBuses.size > 0;
3095
+ for (const b of this.buses.values()) {
3096
+ if (!anySoloed) {
3097
+ b.applySoloVeil(false);
3098
+ } else {
3099
+ b.applySoloVeil(!this.soloedBuses.has(b));
3100
+ }
3101
+ }
3102
+ }
2805
3103
  };
2806
3104
  function suggest(missing, candidates) {
2807
3105
  if (candidates.length === 0) return missing;
@@ -2851,6 +3149,6 @@ function levenshtein(a, b) {
2851
3149
  return prev[b.length];
2852
3150
  }
2853
3151
 
2854
- export { AggregateDecodeError, Bus, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Music, MusicVoice, Parameter, PreloadError, Reverb, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
3152
+ export { AggregateDecodeError, Bus, BusGroup, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Music, MusicVoice, Parameter, PreloadError, Reverb, Send, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
2855
3153
  //# sourceMappingURL=index.js.map
2856
3154
  //# sourceMappingURL=index.js.map