@schmooky/zvuk 1.7.3 → 1.9.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,21 +659,28 @@ var Bus = class {
617
659
  output;
618
660
  _level;
619
661
  _muted;
620
- _baseLevel;
662
+ _soloed = false;
621
663
  ctx;
622
664
  _concurrency;
623
665
  _voices = /* @__PURE__ */ new Set();
624
666
  _fxChain = [];
667
+ _sends = [];
625
668
  // Lazy meter tap. Connected as a passive sibling of bus.output → master.input
626
669
  // so the audio path is unchanged.
627
670
  _meterAnalyser = null;
628
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;
629
679
  constructor(ctx, name, config = {}) {
630
680
  this.ctx = ctx;
631
681
  this.name = name;
632
682
  this._level = config.level ?? 1;
633
683
  this._muted = config.mute ?? false;
634
- this._baseLevel = this._level;
635
684
  this._concurrency = config.concurrency ?? null;
636
685
  this.input = ctx.createGain();
637
686
  this.fxInput = ctx.createGain();
@@ -645,7 +694,6 @@ var Bus = class {
645
694
  }
646
695
  set level(v) {
647
696
  this._level = clamp01(v);
648
- this._baseLevel = this._level;
649
697
  if (!this._muted) this.rampOutput(this._level, 0.01);
650
698
  }
651
699
  get muted() {
@@ -659,7 +707,6 @@ var Bus = class {
659
707
  fadeTo(target, duration, curve = "linear") {
660
708
  const to = clamp01(target);
661
709
  this._level = to;
662
- this._baseLevel = to;
663
710
  return this.ramp(to, duration, curve);
664
711
  }
665
712
  /** Active voice count on this bus. */
@@ -751,6 +798,69 @@ var Bus = class {
751
798
  }
752
799
  return { rms: Math.sqrt(sumSq / buf.length), peak };
753
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
+ }
754
864
  rewireFxChain() {
755
865
  try {
756
866
  this.fxInput.disconnect();
@@ -823,6 +933,55 @@ function pickVictim(voices, strategy, newVoice) {
823
933
  return victim;
824
934
  }
825
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
+
826
985
  // src/params/parameter.ts
827
986
  var Parameter = class {
828
987
  name;
@@ -903,7 +1062,7 @@ function canPlay(mime) {
903
1062
  }
904
1063
  function mimeForUrl(url) {
905
1064
  const m = /\.([a-z0-9]+)(?:[?#]|$)/i.exec(url);
906
- if (!m || !m[1]) return null;
1065
+ if (!m?.[1]) return null;
907
1066
  return EXT_TO_MIME[m[1].toLowerCase()] ?? null;
908
1067
  }
909
1068
  function pickSource(urls) {
@@ -1277,8 +1436,379 @@ var Scheduler = class {
1277
1436
  }
1278
1437
  };
1279
1438
 
1280
- // src/sources/voice.ts
1439
+ // src/sources/music.ts
1281
1440
  var DEFAULT_STOP_FADE_SEC = 8e-3;
1441
+ var SKIP_NOW_FADE_SEC = 0.05;
1442
+ var Music = class {
1443
+ name;
1444
+ deps;
1445
+ constructor(name, deps) {
1446
+ this.name = name;
1447
+ this.deps = deps;
1448
+ }
1449
+ get loopDuration() {
1450
+ return this.deps.buffers.loop.duration;
1451
+ }
1452
+ get hasIntro() {
1453
+ return this.deps.buffers.intro != null;
1454
+ }
1455
+ get hasOutro() {
1456
+ return this.deps.buffers.outro != null;
1457
+ }
1458
+ play(options = {}) {
1459
+ return new MusicVoice({
1460
+ ctx: this.deps.ctx,
1461
+ buffers: this.deps.buffers,
1462
+ destination: this.deps.destination,
1463
+ loopCrossfade: this.deps.loopCrossfade,
1464
+ defaultStopFade: this.deps.defaultStopFade,
1465
+ options
1466
+ });
1467
+ }
1468
+ };
1469
+ var MusicVoice = class {
1470
+ ended;
1471
+ ctx;
1472
+ buffers;
1473
+ destination;
1474
+ gain;
1475
+ state = "intro";
1476
+ done = false;
1477
+ resolveEnded;
1478
+ stopFade;
1479
+ loopCrossfadeSec;
1480
+ // Live audio sources + their per-segment gain nodes. The chain is the
1481
+ // (1+) loop iterations under crossfade-mode; when crossfade is off this
1482
+ // is at most one live loop source.
1483
+ introSource = null;
1484
+ outroSource = null;
1485
+ loopChain = [];
1486
+ loopArmTimer = null;
1487
+ outroTimer = null;
1488
+ // Wall-clock anchor for the loop chain — when the next iteration is due
1489
+ // to start in audioContext time. Used by skipToOutro({ at: 'loop-end' }).
1490
+ nextLoopBoundaryAt = Number.POSITIVE_INFINITY;
1491
+ constructor(deps) {
1492
+ this.ctx = deps.ctx;
1493
+ this.buffers = deps.buffers;
1494
+ this.destination = deps.destination;
1495
+ this.loopCrossfadeSec = Math.max(0, deps.loopCrossfade);
1496
+ this.stopFade = Math.max(0, deps.defaultStopFade ?? DEFAULT_STOP_FADE_SEC);
1497
+ this.gain = this.ctx.createGain();
1498
+ const initialVolume = clamp012(deps.options.volume ?? 1);
1499
+ const fadeIn = Math.max(0, deps.options.fadeIn ?? 0);
1500
+ if (fadeIn > 0) {
1501
+ this.gain.gain.setValueAtTime(0, this.ctx.currentTime);
1502
+ this.gain.gain.linearRampToValueAtTime(initialVolume, this.ctx.currentTime + fadeIn);
1503
+ } else {
1504
+ this.gain.gain.value = initialVolume;
1505
+ }
1506
+ this.gain.connect(this.destination);
1507
+ this.ended = new Promise((resolve) => {
1508
+ this.resolveEnded = resolve;
1509
+ });
1510
+ this.start(this.ctx.currentTime);
1511
+ }
1512
+ /** Currently-sounding part. Transitions automatically as parts hand off. */
1513
+ get currentPart() {
1514
+ return this.state;
1515
+ }
1516
+ fade(opts) {
1517
+ const param = this.gain.gain;
1518
+ const now = this.ctx.currentTime;
1519
+ applyRamp(param, now, clamp012(opts.to), opts.duration, opts.curve ?? "linear");
1520
+ return new Promise((res) => setTimeout(res, Math.max(0, opts.duration) * 1e3));
1521
+ }
1522
+ /**
1523
+ * Stop the music with the same click-free fade-out semantics as
1524
+ * `voice.stop()`. Skips the outro — call `skipToOutro` first if you
1525
+ * want the music to end musically.
1526
+ */
1527
+ stop(opts = {}) {
1528
+ if (this.done) return;
1529
+ const fade = Math.max(0, opts.fade ?? this.stopFade);
1530
+ this.cancelTimers();
1531
+ if (fade === 0) {
1532
+ this.stopAllSources(0);
1533
+ this.finish();
1534
+ return;
1535
+ }
1536
+ const now = this.ctx.currentTime;
1537
+ const stopAt = now + fade;
1538
+ try {
1539
+ const param = this.gain.gain;
1540
+ param.cancelScheduledValues(now);
1541
+ param.setValueAtTime(param.value, now);
1542
+ param.linearRampToValueAtTime(0, stopAt);
1543
+ this.stopAllSources(stopAt);
1544
+ } catch {
1545
+ this.finish();
1546
+ return;
1547
+ }
1548
+ setTimeout(() => this.finish(), fade * 1e3);
1549
+ }
1550
+ /**
1551
+ * Schedule the outro. With `at: 'loop-end'` (default) the outro starts
1552
+ * at the next natural loop boundary so the music ends musically. With
1553
+ * `at: 'now'` the loop fades out (~50 ms) and the outro starts
1554
+ * immediately — useful when responsiveness matters more than musicality
1555
+ * (e.g. user pressed Stop).
1556
+ *
1557
+ * No-op if there is no outro buffer, or if the music is already past
1558
+ * the loop part. Calling `skipToOutro` more than once is a no-op too —
1559
+ * the first call wins.
1560
+ */
1561
+ skipToOutro(opts = {}) {
1562
+ if (this.done) return;
1563
+ if (this.state === "outro" || this.state === "ended") return;
1564
+ if (!this.buffers.outro) {
1565
+ this.stop();
1566
+ return;
1567
+ }
1568
+ const at = opts.at ?? "loop-end";
1569
+ if (at === "now") {
1570
+ this.skipToOutroNow();
1571
+ } else {
1572
+ this.skipToOutroAtLoopEnd();
1573
+ }
1574
+ }
1575
+ start(when) {
1576
+ if (this.buffers.intro) {
1577
+ this.scheduleIntro(when);
1578
+ this.scheduleLoopStart(when + this.buffers.intro.duration);
1579
+ } else {
1580
+ this.state = "loop";
1581
+ this.scheduleLoopStart(when);
1582
+ }
1583
+ }
1584
+ scheduleIntro(when) {
1585
+ const src = this.ctx.createBufferSource();
1586
+ src.buffer = this.buffers.intro;
1587
+ src.connect(this.gain);
1588
+ src.start(when);
1589
+ src.onended = () => {
1590
+ if (this.introSource === src) this.introSource = null;
1591
+ };
1592
+ this.introSource = src;
1593
+ }
1594
+ scheduleLoopStart(when) {
1595
+ if (this.done) return;
1596
+ const segment = this.spawnLoopSegment(
1597
+ when,
1598
+ /* fadeIn */
1599
+ false
1600
+ );
1601
+ this.nextLoopBoundaryAt = when + this.buffers.loop.duration;
1602
+ if (this.loopCrossfadeSec > 0 && this.crossfadeViable()) {
1603
+ this.armNextLoopSegment(when);
1604
+ } else {
1605
+ segment.source.loop = true;
1606
+ const lr = this.buffers.loop;
1607
+ segment.source.loopStart = 0;
1608
+ segment.source.loopEnd = lr.duration;
1609
+ if (!this.buffers.intro) this.state = "loop";
1610
+ else {
1611
+ const ms = Math.max(0, (when - this.ctx.currentTime) * 1e3);
1612
+ setTimeout(() => {
1613
+ if (!this.done && this.state === "intro") this.state = "loop";
1614
+ }, ms);
1615
+ }
1616
+ }
1617
+ }
1618
+ spawnLoopSegment(when, fadeIn) {
1619
+ const src = this.ctx.createBufferSource();
1620
+ src.buffer = this.buffers.loop;
1621
+ src.loop = false;
1622
+ const segGain = this.ctx.createGain();
1623
+ if (fadeIn) {
1624
+ segGain.gain.setValueAtTime(0, when);
1625
+ segGain.gain.linearRampToValueAtTime(1, when + this.loopCrossfadeSec);
1626
+ } else {
1627
+ segGain.gain.setValueAtTime(1, when);
1628
+ }
1629
+ if (this.crossfadeViable()) {
1630
+ const fadeOutAt = when + this.buffers.loop.duration - this.loopCrossfadeSec;
1631
+ segGain.gain.setValueAtTime(1, fadeOutAt);
1632
+ segGain.gain.linearRampToValueAtTime(0, when + this.buffers.loop.duration);
1633
+ }
1634
+ src.connect(segGain).connect(this.gain);
1635
+ try {
1636
+ if (this.crossfadeViable()) {
1637
+ src.start(when, 0, this.buffers.loop.duration);
1638
+ } else {
1639
+ src.start(when);
1640
+ }
1641
+ } catch {
1642
+ }
1643
+ src.onended = () => this.releaseLoopSegment(src, segGain);
1644
+ const entry = { source: src, gain: segGain, startTime: when };
1645
+ this.loopChain.push(entry);
1646
+ return entry;
1647
+ }
1648
+ armNextLoopSegment(currentSegmentStart) {
1649
+ if (this.loopArmTimer != null) {
1650
+ clearTimeout(this.loopArmTimer);
1651
+ this.loopArmTimer = null;
1652
+ }
1653
+ const nextStart = currentSegmentStart + this.buffers.loop.duration - this.loopCrossfadeSec;
1654
+ const SAFETY_LEAD_MS = 50;
1655
+ const delayMs = Math.max(0, (nextStart - this.ctx.currentTime) * 1e3 - SAFETY_LEAD_MS);
1656
+ this.loopArmTimer = setTimeout(() => {
1657
+ this.loopArmTimer = null;
1658
+ if (this.done || this.state !== "loop" && this.state !== "intro") return;
1659
+ this.state = "loop";
1660
+ this.spawnLoopSegment(
1661
+ nextStart,
1662
+ /* fadeIn */
1663
+ true
1664
+ );
1665
+ this.nextLoopBoundaryAt = nextStart + this.buffers.loop.duration;
1666
+ this.armNextLoopSegment(nextStart);
1667
+ }, delayMs);
1668
+ }
1669
+ crossfadeViable() {
1670
+ return this.loopCrossfadeSec > 0 && this.buffers.loop.duration > this.loopCrossfadeSec * 2;
1671
+ }
1672
+ releaseLoopSegment(src, gain) {
1673
+ const idx = this.loopChain.findIndex((e) => e.source === src);
1674
+ if (idx >= 0) this.loopChain.splice(idx, 1);
1675
+ try {
1676
+ src.disconnect();
1677
+ gain.disconnect();
1678
+ } catch {
1679
+ }
1680
+ }
1681
+ skipToOutroAtLoopEnd() {
1682
+ if (this.loopArmTimer != null) {
1683
+ clearTimeout(this.loopArmTimer);
1684
+ this.loopArmTimer = null;
1685
+ }
1686
+ let outroAt;
1687
+ if (this.state === "intro") {
1688
+ outroAt = this.ctx.currentTime + (this.buffers.intro?.duration ?? 0);
1689
+ this.cancelLoopArm();
1690
+ } else {
1691
+ outroAt = this.nextLoopBoundaryAt;
1692
+ }
1693
+ this.stopLoopSourcesAt(outroAt);
1694
+ this.scheduleOutro(outroAt);
1695
+ }
1696
+ skipToOutroNow() {
1697
+ this.cancelLoopArm();
1698
+ const now = this.ctx.currentTime;
1699
+ const fadeEnd = now + SKIP_NOW_FADE_SEC;
1700
+ for (const entry of this.loopChain) {
1701
+ try {
1702
+ const param = entry.gain.gain;
1703
+ param.cancelScheduledValues(now);
1704
+ param.setValueAtTime(param.value, now);
1705
+ param.linearRampToValueAtTime(0, fadeEnd);
1706
+ } catch {
1707
+ }
1708
+ try {
1709
+ entry.source.stop(fadeEnd);
1710
+ } catch {
1711
+ }
1712
+ }
1713
+ if (this.introSource) {
1714
+ try {
1715
+ this.introSource.stop(fadeEnd);
1716
+ } catch {
1717
+ }
1718
+ }
1719
+ this.scheduleOutro(fadeEnd);
1720
+ }
1721
+ cancelLoopArm() {
1722
+ if (this.loopArmTimer != null) {
1723
+ clearTimeout(this.loopArmTimer);
1724
+ this.loopArmTimer = null;
1725
+ }
1726
+ }
1727
+ stopLoopSourcesAt(when) {
1728
+ for (const entry of this.loopChain) {
1729
+ try {
1730
+ entry.source.stop(when);
1731
+ } catch {
1732
+ }
1733
+ }
1734
+ }
1735
+ scheduleOutro(when) {
1736
+ const buf = this.buffers.outro;
1737
+ if (!buf) {
1738
+ const ms2 = Math.max(0, (when - this.ctx.currentTime) * 1e3);
1739
+ this.outroTimer = setTimeout(() => this.finish(), ms2);
1740
+ return;
1741
+ }
1742
+ const src = this.ctx.createBufferSource();
1743
+ src.buffer = buf;
1744
+ src.connect(this.gain);
1745
+ try {
1746
+ src.start(when);
1747
+ } catch {
1748
+ }
1749
+ src.onended = () => {
1750
+ if (this.outroSource === src) this.outroSource = null;
1751
+ this.finish();
1752
+ };
1753
+ this.outroSource = src;
1754
+ const ms = Math.max(0, (when - this.ctx.currentTime) * 1e3);
1755
+ this.outroTimer = setTimeout(() => {
1756
+ this.outroTimer = null;
1757
+ if (!this.done) this.state = "outro";
1758
+ }, ms);
1759
+ }
1760
+ cancelTimers() {
1761
+ if (this.loopArmTimer != null) {
1762
+ clearTimeout(this.loopArmTimer);
1763
+ this.loopArmTimer = null;
1764
+ }
1765
+ if (this.outroTimer != null) {
1766
+ clearTimeout(this.outroTimer);
1767
+ this.outroTimer = null;
1768
+ }
1769
+ }
1770
+ stopAllSources(when) {
1771
+ const sources = [];
1772
+ if (this.introSource) sources.push(this.introSource);
1773
+ for (const e of this.loopChain) sources.push(e.source);
1774
+ if (this.outroSource) sources.push(this.outroSource);
1775
+ for (const src of sources) {
1776
+ try {
1777
+ src.onended = null;
1778
+ if (when === 0) src.stop();
1779
+ else src.stop(when);
1780
+ } catch {
1781
+ }
1782
+ }
1783
+ }
1784
+ finish() {
1785
+ if (this.done) return;
1786
+ this.done = true;
1787
+ this.state = "ended";
1788
+ this.cancelTimers();
1789
+ try {
1790
+ if (this.introSource) this.introSource.disconnect();
1791
+ for (const e of this.loopChain) {
1792
+ e.source.disconnect();
1793
+ e.gain.disconnect();
1794
+ }
1795
+ if (this.outroSource) this.outroSource.disconnect();
1796
+ this.gain.disconnect();
1797
+ } catch {
1798
+ }
1799
+ this.introSource = null;
1800
+ this.outroSource = null;
1801
+ this.loopChain = [];
1802
+ this.resolveEnded();
1803
+ }
1804
+ };
1805
+ function clamp012(v) {
1806
+ if (Number.isNaN(v)) return 0;
1807
+ return Math.min(1, Math.max(0, v));
1808
+ }
1809
+
1810
+ // src/sources/voice.ts
1811
+ var DEFAULT_STOP_FADE_SEC2 = 8e-3;
1282
1812
  var Voice = class _Voice {
1283
1813
  id;
1284
1814
  priority;
@@ -1342,10 +1872,10 @@ var Voice = class _Voice {
1342
1872
  this.regionDuration = options.duration;
1343
1873
  this.loopStart = options.loopStart;
1344
1874
  this.loopEnd = options.loopEnd;
1345
- this.stopFade = Math.max(0, deps.defaultStopFade ?? DEFAULT_STOP_FADE_SEC);
1875
+ this.stopFade = Math.max(0, deps.defaultStopFade ?? DEFAULT_STOP_FADE_SEC2);
1346
1876
  this.gain = ctx.createGain();
1347
1877
  const initialVolume = resolveJittered(options.volume ?? 1);
1348
- this.gain.gain.value = clamp012(initialVolume);
1878
+ this.gain.gain.value = clamp013(initialVolume);
1349
1879
  this.gain.connect(destination);
1350
1880
  this.startCtxTime = ctx.currentTime;
1351
1881
  this.ended = new Promise((resolve) => {
@@ -1389,7 +1919,7 @@ var Voice = class _Voice {
1389
1919
  fade(opts) {
1390
1920
  const param = this.gain.gain;
1391
1921
  const now = this.ctx.currentTime;
1392
- applyRamp(param, now, clamp012(opts.to), opts.duration, opts.curve ?? "linear");
1922
+ applyRamp(param, now, clamp013(opts.to), opts.duration, opts.curve ?? "linear");
1393
1923
  return new Promise((res) => setTimeout(res, Math.max(0, opts.duration) * 1e3));
1394
1924
  }
1395
1925
  /**
@@ -1748,7 +2278,7 @@ function resolveJittered(v, base = 1) {
1748
2278
  const j = v.jitter;
1749
2279
  return base + (Math.random() * 2 - 1) * j;
1750
2280
  }
1751
- function clamp012(v) {
2281
+ function clamp013(v) {
1752
2282
  if (Number.isNaN(v)) return 0;
1753
2283
  return Math.min(1, Math.max(0, v));
1754
2284
  }
@@ -1877,7 +2407,7 @@ var StreamSound = class {
1877
2407
  async play(options = {}) {
1878
2408
  this.ensure();
1879
2409
  if (!this.el) return;
1880
- if (this.gain) this.gain.gain.value = clamp013(options.volume ?? 1);
2410
+ if (this.gain) this.gain.gain.value = clamp014(options.volume ?? 1);
1881
2411
  this.el.loop = options.loop ?? false;
1882
2412
  try {
1883
2413
  await this.el.play();
@@ -1912,11 +2442,11 @@ var StreamSound = class {
1912
2442
  return this.el?.paused ?? true;
1913
2443
  }
1914
2444
  setVolume(v) {
1915
- if (this.gain) this.gain.gain.value = clamp013(v);
2445
+ if (this.gain) this.gain.gain.value = clamp014(v);
1916
2446
  }
1917
2447
  fade(opts) {
1918
2448
  if (!this.gain) return Promise.resolve();
1919
- applyRamp(this.gain.gain, this.ctx.currentTime, clamp013(opts.to), opts.duration, opts.curve ?? "linear");
2449
+ applyRamp(this.gain.gain, this.ctx.currentTime, clamp014(opts.to), opts.duration, opts.curve ?? "linear");
1920
2450
  return new Promise((res) => setTimeout(res, Math.max(0, opts.duration) * 1e3));
1921
2451
  }
1922
2452
  dispose() {
@@ -1935,7 +2465,7 @@ var StreamSound = class {
1935
2465
  this.gain = null;
1936
2466
  }
1937
2467
  };
1938
- function clamp013(v) {
2468
+ function clamp014(v) {
1939
2469
  if (Number.isNaN(v)) return 0;
1940
2470
  return Math.min(1, Math.max(0, v));
1941
2471
  }
@@ -2006,6 +2536,8 @@ var Master = class {
2006
2536
  limiterNode = null;
2007
2537
  limiterCfg;
2008
2538
  destination;
2539
+ _meterAnalyser = null;
2540
+ _meterBuf = null;
2009
2541
  constructor(ctx, config = {}) {
2010
2542
  this.ctx = ctx;
2011
2543
  this.input = ctx.createGain();
@@ -2034,13 +2566,42 @@ var Master = class {
2034
2566
  get reduction() {
2035
2567
  return this.limiterNode?.reduction ?? 0;
2036
2568
  }
2569
+ /**
2570
+ * Live amplitude readout on the master input. Returns `{ rms, peak }`
2571
+ * as linear values in [0..1]. The first call lazily attaches an
2572
+ * AnalyserNode as a passive sibling of the master gain — no audio-path
2573
+ * change. Same shape as `bus.meter()` and `voice.level()`.
2574
+ */
2575
+ meter() {
2576
+ if (!this._meterAnalyser) {
2577
+ const a = this.ctx.createAnalyser();
2578
+ a.fftSize = 1024;
2579
+ this.input.connect(a);
2580
+ this._meterAnalyser = a;
2581
+ this._meterBuf = new Float32Array(a.fftSize);
2582
+ }
2583
+ const buf = this._meterBuf;
2584
+ this._meterAnalyser.getFloatTimeDomainData(buf);
2585
+ let sumSq = 0;
2586
+ let peak = 0;
2587
+ for (let i = 0; i < buf.length; i++) {
2588
+ const s = buf[i] ?? 0;
2589
+ sumSq += s * s;
2590
+ const a = Math.abs(s);
2591
+ if (a > peak) peak = a;
2592
+ }
2593
+ return { rms: Math.sqrt(sumSq / buf.length), peak };
2594
+ }
2037
2595
  dispose() {
2038
2596
  try {
2039
2597
  this.input.disconnect();
2040
2598
  this.limiterNode?.disconnect();
2599
+ this._meterAnalyser?.disconnect();
2041
2600
  } catch {
2042
2601
  }
2043
2602
  this.limiterNode = null;
2603
+ this._meterAnalyser = null;
2604
+ this._meterBuf = null;
2044
2605
  }
2045
2606
  rewire() {
2046
2607
  try {
@@ -2113,6 +2674,9 @@ var EngineImpl = class {
2113
2674
  sounds = /* @__PURE__ */ new Map();
2114
2675
  sprites = /* @__PURE__ */ new Map();
2115
2676
  streams = /* @__PURE__ */ new Map();
2677
+ musics = /* @__PURE__ */ new Map();
2678
+ busGroups = /* @__PURE__ */ new Map();
2679
+ soloedBuses = /* @__PURE__ */ new Set();
2116
2680
  voices = /* @__PURE__ */ new Map();
2117
2681
  parameters = /* @__PURE__ */ new Map();
2118
2682
  config;
@@ -2154,6 +2718,7 @@ var EngineImpl = class {
2154
2718
  this.master = null;
2155
2719
  this.sounds.clear();
2156
2720
  this.sprites.clear();
2721
+ this.musics.clear();
2157
2722
  for (const s of this.streams.values()) s.dispose();
2158
2723
  this.streams.clear();
2159
2724
  this.parameters.clear();
@@ -2243,6 +2808,40 @@ var EngineImpl = class {
2243
2808
  hasSprite(name) {
2244
2809
  return this.sprites.has(name);
2245
2810
  }
2811
+ async loadMusic(name, parts, options = {}) {
2812
+ if (this.host.state === "closed") throw new EngineClosedError();
2813
+ this.host.touch();
2814
+ this.ensureGraph();
2815
+ const decodeOpts = { signal: options.signal };
2816
+ const loopBuf = await this.resolveBuffer(`__music:${name}:loop`, parts.loop, decodeOpts);
2817
+ const introBuf = parts.intro ? await this.resolveBuffer(`__music:${name}:intro`, parts.intro, decodeOpts) : void 0;
2818
+ const outroBuf = parts.outro ? await this.resolveBuffer(`__music:${name}:outro`, parts.outro, decodeOpts) : void 0;
2819
+ const buffers = {
2820
+ intro: introBuf ? options.normalize ? applyLoudnessNormalization(introBuf, options.normalize) : introBuf : void 0,
2821
+ loop: options.normalize ? applyLoudnessNormalization(loopBuf, options.normalize) : loopBuf,
2822
+ outro: outroBuf ? options.normalize ? applyLoudnessNormalization(outroBuf, options.normalize) : outroBuf : void 0
2823
+ };
2824
+ const busName = options.bus ?? this.busOrder[0];
2825
+ const bus = this.buses.get(busName);
2826
+ if (!bus) throw new BusNotFoundError(suggest(busName, [...this.buses.keys()]));
2827
+ const music = new Music(name, {
2828
+ ctx: this.host.touch(),
2829
+ buffers,
2830
+ destination: bus.input,
2831
+ loopCrossfade: options.loopCrossfade ?? 0,
2832
+ defaultStopFade: this.config.voice?.stopFade
2833
+ });
2834
+ this.musics.set(name, music);
2835
+ return music;
2836
+ }
2837
+ music(name) {
2838
+ const m = this.musics.get(name);
2839
+ if (!m) throw new SoundNotFoundError(suggest(name, [...this.musics.keys()]));
2840
+ return m;
2841
+ }
2842
+ hasMusic(name) {
2843
+ return this.musics.has(name);
2844
+ }
2246
2845
  loadStream(name, url, options = {}) {
2247
2846
  if (this.host.state === "closed") throw new EngineClosedError();
2248
2847
  this.host.touch();
@@ -2346,6 +2945,22 @@ var EngineImpl = class {
2346
2945
  if (!b) throw new BusNotFoundError(suggest(name, [...this.buses.keys()]));
2347
2946
  return b;
2348
2947
  }
2948
+ busGroup(name, members) {
2949
+ if (members != null) {
2950
+ const group = new BusGroup(name, members);
2951
+ this.busGroups.set(name, group);
2952
+ return group;
2953
+ }
2954
+ const existing = this.busGroups.get(name);
2955
+ if (!existing) {
2956
+ throw new BusNotFoundError(suggest(name, [...this.busGroups.keys()]));
2957
+ }
2958
+ return existing;
2959
+ }
2960
+ masterMeter() {
2961
+ this.ensureGraph();
2962
+ return this.master.meter();
2963
+ }
2349
2964
  scheduleAt(audioTime, fn) {
2350
2965
  this.host.touch();
2351
2966
  this.ensureGraph();
@@ -2395,10 +3010,29 @@ var EngineImpl = class {
2395
3010
  const cfg = this.config.buses?.[name] ?? {};
2396
3011
  const bus = new Bus(ctx, name, cfg);
2397
3012
  bus.output.connect(this.master.input);
3013
+ bus.notifySoloChange = (b, soloed) => this.handleSoloChange(b, soloed);
2398
3014
  this.buses.set(name, bus);
2399
3015
  if (!this.voices.has(name)) this.voices.set(name, /* @__PURE__ */ new Set());
2400
3016
  }
2401
3017
  }
3018
+ /**
3019
+ * Coordinate the global solo rule. When any bus is in the solo set,
3020
+ * every non-soloed bus is muted via `applySoloVeil(true)`. When the
3021
+ * solo set drains, every bus is restored via `applySoloVeil(false)` —
3022
+ * which honours the bus's own `muted` setting independently.
3023
+ */
3024
+ handleSoloChange(bus, soloed) {
3025
+ if (soloed) this.soloedBuses.add(bus);
3026
+ else this.soloedBuses.delete(bus);
3027
+ const anySoloed = this.soloedBuses.size > 0;
3028
+ for (const b of this.buses.values()) {
3029
+ if (!anySoloed) {
3030
+ b.applySoloVeil(false);
3031
+ } else {
3032
+ b.applySoloVeil(!this.soloedBuses.has(b));
3033
+ }
3034
+ }
3035
+ }
2402
3036
  };
2403
3037
  function suggest(missing, candidates) {
2404
3038
  if (candidates.length === 0) return missing;
@@ -2448,6 +3082,6 @@ function levenshtein(a, b) {
2448
3082
  return prev[b.length];
2449
3083
  }
2450
3084
 
2451
- export { AggregateDecodeError, Bus, BusNotFoundError, Compressor, DecodeError, Ducker, EngineClosedError, Filter, Master, Parameter, PreloadError, Reverb, Snapshot, Sound, SoundNotFoundError, Spatializer, Sprite, StreamSound, StretchProcessor, Voice, ZvukError, applyLoudnessNormalization, canPlay, computeNormalizationGain, createEngine, createStretchWorkletNode, ensureStretchWorklet, mimeForUrl, pickSource, pickSourceOrder };
3085
+ 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 };
2452
3086
  //# sourceMappingURL=index.js.map
2453
3087
  //# sourceMappingURL=index.js.map