spessasynth_core 4.4.7 → 4.4.9

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
@@ -411,7 +411,7 @@ var RIFFChunk = class RIFFChunk {
411
411
  }
412
412
  const parts = [getStringBytes(headerWritten), sizeBytes];
413
413
  if (isList) parts.push(getStringBytes(header));
414
- parts.push(...chunks);
414
+ for (const chunk of chunks) parts.push(chunk);
415
415
  if (totalSize % 2 !== 0) parts.push(/* @__PURE__ */ new Uint8Array(1));
416
416
  return parts;
417
417
  }
@@ -511,8 +511,8 @@ function audioToWav(audioData, sampleRate, options = DEFAULT_WAV_WRITE_OPTIONS)
511
511
  let cueChunk = new IndexedByteArray(0);
512
512
  const cueOn = loop?.end !== void 0 && loop?.start !== void 0;
513
513
  if (cueOn) {
514
- const loopStartSamples = Math.floor(loop.start * sampleRate);
515
- const loopEndSamples = Math.floor(loop.end * sampleRate);
514
+ const loopStartSamples = Math.round(loop.start * sampleRate);
515
+ const loopEndSamples = Math.round(loop.end * sampleRate);
516
516
  const cueStart = new IndexedByteArray(24);
517
517
  writeLittleEndianIndexed(cueStart, 0, 4);
518
518
  writeLittleEndianIndexed(cueStart, 0, 4);
@@ -629,6 +629,146 @@ function audioToWav(audioData, sampleRate, options = DEFAULT_WAV_WRITE_OPTIONS)
629
629
  if (cueOn) wavData.set(cueChunk, offset);
630
630
  return wavData.buffer;
631
631
  }
632
+ // src/utils/read_wav.ts
633
+ /**
634
+ * Reads a WAVE file into PCM audio data, the counterpart of {@link audioToWav}.
635
+ *
636
+ * It reads 8, 16, 24 and 32-bit integer PCM and 32 and 64-bit float files (including `WAVE_FORMAT_EXTENSIBLE`).
637
+ * The loop is read from the first loop of the `smpl` chunk. Without one, a `cue ` chunk with exactly two points
638
+ * is taken as the loop start and end, which is how {@link audioToWav} writes it.
639
+ *
640
+ * > **Note**
641
+ * >
642
+ * > The returned loop end is exclusive, like the SoundFont loop end.
643
+ *
644
+ * @param buffer The binary WAVE file.
645
+ * @returns The audio data (one array per channel), the sample rate and the loop, if the file has one.
646
+ * @throws Error if the file is not a valid or supported WAVE file.
647
+ *
648
+ * @group Utilities
649
+ */
650
+ function wavToAudio(buffer) {
651
+ const bytes = new Uint8Array(buffer);
652
+ const fourCC = (at) => String.fromCodePoint(bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]);
653
+ const isFourCC = (at) => at + 4 <= bytes.length && /^[\dA-Za-z]+ *$/.test(fourCC(at));
654
+ const nextChunk = (body, size) => {
655
+ const end = body + size;
656
+ return size % 2 === 1 && !(isFourCC(end) && !isFourCC(end + 1)) ? end + 1 : end;
657
+ };
658
+ if (buffer.byteLength < 12 || fourCC(0) !== "RIFF" || fourCC(8) !== "WAVE") throw new Error("Not a WAVE file.");
659
+ let format = 0;
660
+ let channels = 0;
661
+ let sampleRate = 0;
662
+ let bitsPerSample = 0;
663
+ let dataStart = -1;
664
+ let dataSize = 0;
665
+ let smplLoop;
666
+ const cuePoints = new Array();
667
+ const namedCues = /* @__PURE__ */ new Set();
668
+ let pos = 12;
669
+ while (pos + 8 <= buffer.byteLength) {
670
+ const id = fourCC(pos);
671
+ const size = readLittleEndian(bytes, 4, pos + 4);
672
+ const body = pos + 8;
673
+ const available = Math.min(size, buffer.byteLength - body);
674
+ switch (id) {
675
+ case "fmt ":
676
+ if (available < 16) throw new Error("The WAVE file's fmt chunk is too short.");
677
+ format = readLittleEndian(bytes, 2, body);
678
+ channels = readLittleEndian(bytes, 2, body + 2);
679
+ sampleRate = readLittleEndian(bytes, 4, body + 4);
680
+ bitsPerSample = readLittleEndian(bytes, 2, body + 14);
681
+ if (format === 65534 && available >= 26) format = readLittleEndian(bytes, 2, body + 24);
682
+ break;
683
+ case "data":
684
+ dataStart = body;
685
+ dataSize = available;
686
+ break;
687
+ case "smpl":
688
+ if ((available >= 36 ? readLittleEndian(bytes, 4, body + 28) : 0) > 0 && available >= 60) smplLoop = {
689
+ start: readLittleEndian(bytes, 4, body + 36 + 8),
690
+ end: readLittleEndian(bytes, 4, body + 36 + 12) + 1
691
+ };
692
+ break;
693
+ case "cue ": {
694
+ const count = available >= 4 ? readLittleEndian(bytes, 4, body) : 0;
695
+ for (let i = 0; i < count && 4 + (i + 1) * 24 <= available; i++) {
696
+ const point = body + 4 + i * 24;
697
+ cuePoints.push({
698
+ id: readLittleEndian(bytes, 4, point),
699
+ offset: readLittleEndian(bytes, 4, point + 20)
700
+ });
701
+ }
702
+ break;
703
+ }
704
+ case "LIST": {
705
+ if (available < 4 || fourCC(body) !== "adtl") break;
706
+ const end = body + available;
707
+ let at = body + 4;
708
+ while (at + 12 <= end) {
709
+ const subId = fourCC(at);
710
+ const subSize = readLittleEndian(bytes, 4, at + 4);
711
+ if (subSize >= 4 && (subId === "labl" || subId === "note" || subId === "ltxt")) namedCues.add(readLittleEndian(bytes, 4, at + 8));
712
+ at = nextChunk(at + 8, subSize);
713
+ }
714
+ break;
715
+ }
716
+ }
717
+ pos = nextChunk(body, size);
718
+ }
719
+ if (channels === 0 || dataStart === -1) throw new Error("The WAVE file has no fmt or data chunk!");
720
+ const bytesPerSample = bitsPerSample >> 3;
721
+ const isFloat = format === 3;
722
+ if (format !== 1 && format !== 3 || (isFloat ? ![4, 8].includes(bytesPerSample) : bytesPerSample < 1 || bytesPerSample > 4)) throw new Error(`Unsupported WAVE format ${format} with ${bitsPerSample} bits per sample.`);
723
+ const frames = Math.floor(dataSize / (bytesPerSample * channels));
724
+ const count = frames * channels;
725
+ const pcm = bytes.slice(dataStart, dataStart + count * bytesPerSample);
726
+ let samples;
727
+ let offset = 0;
728
+ let scale = 1;
729
+ if (isFloat) samples = bytesPerSample === 4 ? new Float32Array(pcm.buffer) : new Float64Array(pcm.buffer);
730
+ else switch (bytesPerSample) {
731
+ case 1:
732
+ samples = pcm;
733
+ offset = 128;
734
+ scale = 128;
735
+ break;
736
+ case 2:
737
+ samples = new Int16Array(pcm.buffer);
738
+ scale = 32768;
739
+ break;
740
+ case 3: {
741
+ const s24 = new Int32Array(count);
742
+ for (let i = 0; i < count; i++) {
743
+ const at = i * 3;
744
+ s24[i] = (pcm[at + 2] << 24 | pcm[at + 1] << 16 | pcm[at] << 8) >> 8;
745
+ }
746
+ samples = s24;
747
+ scale = 8388608;
748
+ break;
749
+ }
750
+ default:
751
+ samples = new Int32Array(pcm.buffer);
752
+ scale = 2147483648;
753
+ }
754
+ const audioData = Array.from({ length: channels }, () => new Float32Array(frames));
755
+ for (let i = 0; i < frames; i++) for (let c = 0; c < channels; c++) audioData[c][i] = (samples[i * channels + c] - offset) / scale;
756
+ let loop = smplLoop;
757
+ const [cueStart, cueEnd] = cuePoints;
758
+ if (!loop && cuePoints.length === 2 && !namedCues.has(cueStart.id) && !namedCues.has(cueEnd.id)) loop = {
759
+ start: cueStart.offset,
760
+ end: cueEnd.offset
761
+ };
762
+ if (loop) loop = loop.end <= loop.start || loop.start >= frames ? void 0 : {
763
+ start: loop.start,
764
+ end: Math.min(loop.end, frames)
765
+ };
766
+ return {
767
+ audioData,
768
+ sampleRate,
769
+ loop
770
+ };
771
+ }
632
772
  // src/utils/loggin.ts
633
773
  /**
634
774
  * SpessaSynth can print out additional info to the console or print nothing at all.
@@ -1603,56 +1743,43 @@ const GeneratorLimits = Object.freeze({
1603
1743
  min: -12e3,
1604
1744
  max: 12e3,
1605
1745
  def: 0,
1606
- nrpn: 2,
1607
- presetMin: -24e3,
1608
- presetMax: 24e3
1746
+ nrpn: 2
1609
1747
  },
1610
1748
  [GeneratorTypes.vibLfoToPitch]: {
1611
1749
  min: -12e3,
1612
1750
  max: 12e3,
1613
1751
  def: 0,
1614
- nrpn: 2,
1615
- presetMin: -24e3,
1616
- presetMax: 24e3
1752
+ nrpn: 2
1617
1753
  },
1618
1754
  [GeneratorTypes.modEnvToPitch]: {
1619
1755
  min: -12e3,
1620
1756
  max: 12e3,
1621
1757
  def: 0,
1622
- nrpn: 2,
1623
- presetMin: -24e3,
1624
- presetMax: 24e3
1758
+ nrpn: 2
1625
1759
  },
1626
1760
  [GeneratorTypes.initialFilterFc]: {
1627
1761
  min: 1500,
1628
1762
  max: 13500,
1629
1763
  def: 13500,
1630
- nrpn: 2,
1631
- presetMin: -21e3,
1632
- presetMax: 21e3
1764
+ nrpn: 2
1633
1765
  },
1634
1766
  [GeneratorTypes.initialFilterQ]: {
1635
1767
  min: 0,
1636
1768
  max: 960,
1637
1769
  def: 0,
1638
- nrpn: 1,
1639
- presetMin: -960
1770
+ nrpn: 1
1640
1771
  },
1641
1772
  [GeneratorTypes.modLfoToFilterFc]: {
1642
1773
  min: -12e3,
1643
1774
  max: 12e3,
1644
1775
  def: 0,
1645
- nrpn: 2,
1646
- presetMin: -24e3,
1647
- presetMax: 24e3
1776
+ nrpn: 2
1648
1777
  },
1649
1778
  [GeneratorTypes.modEnvToFilterFc]: {
1650
1779
  min: -12e3,
1651
1780
  max: 12e3,
1652
1781
  def: 0,
1653
- nrpn: 2,
1654
- presetMin: -24e3,
1655
- presetMax: 24e3
1782
+ nrpn: 2
1656
1783
  },
1657
1784
  [GeneratorTypes.endAddrsCoarseOffset]: {
1658
1785
  min: -32768,
@@ -1664,189 +1791,145 @@ const GeneratorLimits = Object.freeze({
1664
1791
  min: -960,
1665
1792
  max: 960,
1666
1793
  def: 0,
1667
- nrpn: 1,
1668
- presetMin: -1920,
1669
- presetMax: 1920
1794
+ nrpn: 1
1670
1795
  },
1671
1796
  [GeneratorTypes.chorusEffectsSend]: {
1672
1797
  min: 0,
1673
1798
  max: 1e3,
1674
1799
  def: 0,
1675
- nrpn: 1,
1676
- presetMin: -1e3
1800
+ nrpn: 1
1677
1801
  },
1678
1802
  [GeneratorTypes.reverbEffectsSend]: {
1679
1803
  min: 0,
1680
1804
  max: 1e3,
1681
1805
  def: 0,
1682
- nrpn: 1,
1683
- presetMin: -1e3
1806
+ nrpn: 1
1684
1807
  },
1685
1808
  [GeneratorTypes.pan]: {
1686
1809
  min: -500,
1687
1810
  max: 500,
1688
1811
  def: 0,
1689
- nrpn: 1,
1690
- presetMin: -1e3,
1691
- presetMax: 1e3
1812
+ nrpn: 1
1692
1813
  },
1693
1814
  [GeneratorTypes.delayModLFO]: {
1694
1815
  min: -12e3,
1695
1816
  max: 5e3,
1696
1817
  def: -12e3,
1697
- nrpn: 2,
1698
- presetMin: -21e3,
1699
- presetMax: 21e3
1818
+ nrpn: 2
1700
1819
  },
1701
1820
  [GeneratorTypes.freqModLFO]: {
1702
1821
  min: -16e3,
1703
1822
  max: 4500,
1704
1823
  def: 0,
1705
- nrpn: 4,
1706
- presetMin: -21e3,
1707
- presetMax: 21e3
1824
+ nrpn: 4
1708
1825
  },
1709
1826
  [GeneratorTypes.delayVibLFO]: {
1710
1827
  min: -12e3,
1711
1828
  max: 5e3,
1712
1829
  def: -12e3,
1713
- nrpn: 2,
1714
- presetMin: -21e3,
1715
- presetMax: 21e3
1830
+ nrpn: 2
1716
1831
  },
1717
1832
  [GeneratorTypes.freqVibLFO]: {
1718
1833
  min: -16e3,
1719
1834
  max: 4500,
1720
1835
  def: 0,
1721
- nrpn: 4,
1722
- presetMin: -21e3,
1723
- presetMax: 21e3
1836
+ nrpn: 4
1724
1837
  },
1725
1838
  [GeneratorTypes.delayModEnv]: {
1726
1839
  min: -32768,
1727
1840
  max: 5e3,
1728
1841
  def: -32768,
1729
- nrpn: 2,
1730
- presetMin: -21e3,
1731
- presetMax: 21e3
1842
+ nrpn: 2
1732
1843
  },
1733
1844
  [GeneratorTypes.attackModEnv]: {
1734
1845
  min: -32768,
1735
1846
  max: 8e3,
1736
1847
  def: -32768,
1737
- nrpn: 2,
1738
- presetMin: -21e3,
1739
- presetMax: 21e3
1848
+ nrpn: 2
1740
1849
  },
1741
1850
  [GeneratorTypes.holdModEnv]: {
1742
1851
  min: -12e3,
1743
1852
  max: 5e3,
1744
1853
  def: -12e3,
1745
- nrpn: 2,
1746
- presetMin: -21e3,
1747
- presetMax: 21e3
1854
+ nrpn: 2
1748
1855
  },
1749
1856
  [GeneratorTypes.decayModEnv]: {
1750
1857
  min: -12e3,
1751
1858
  max: 8e3,
1752
1859
  def: -12e3,
1753
- nrpn: 2,
1754
- presetMin: -21e3,
1755
- presetMax: 21e3
1860
+ nrpn: 2
1756
1861
  },
1757
1862
  [GeneratorTypes.sustainModEnv]: {
1758
1863
  min: 0,
1759
1864
  max: 1e3,
1760
1865
  def: 0,
1761
- nrpn: 1,
1762
- presetMin: -1e3
1866
+ nrpn: 1
1763
1867
  },
1764
1868
  [GeneratorTypes.releaseModEnv]: {
1765
1869
  min: -12e3,
1766
1870
  max: 8e3,
1767
1871
  def: -12e3,
1768
- nrpn: 2,
1769
- presetMin: -21e3,
1770
- presetMax: 21e3
1872
+ nrpn: 2
1771
1873
  },
1772
1874
  [GeneratorTypes.keyNumToModEnvHold]: {
1773
1875
  min: -1200,
1774
1876
  max: 1200,
1775
1877
  def: 0,
1776
- nrpn: 1,
1777
- presetMin: -2400,
1778
- presetMax: 2400
1878
+ nrpn: 1
1779
1879
  },
1780
1880
  [GeneratorTypes.keyNumToModEnvDecay]: {
1781
1881
  min: -1200,
1782
1882
  max: 1200,
1783
1883
  def: 0,
1784
- nrpn: 1,
1785
- presetMin: -2400,
1786
- presetMax: 2400
1884
+ nrpn: 1
1787
1885
  },
1788
1886
  [GeneratorTypes.delayVolEnv]: {
1789
1887
  min: -12e3,
1790
1888
  max: 5e3,
1791
1889
  def: -12e3,
1792
- nrpn: 2,
1793
- presetMin: -21e3,
1794
- presetMax: 21e3
1890
+ nrpn: 2
1795
1891
  },
1796
1892
  [GeneratorTypes.attackVolEnv]: {
1797
1893
  min: -12e3,
1798
1894
  max: 8e3,
1799
1895
  def: -12e3,
1800
- nrpn: 2,
1801
- presetMin: -21e3,
1802
- presetMax: 21e3
1896
+ nrpn: 2
1803
1897
  },
1804
1898
  [GeneratorTypes.holdVolEnv]: {
1805
1899
  min: -12e3,
1806
1900
  max: 5e3,
1807
1901
  def: -12e3,
1808
- nrpn: 2,
1809
- presetMin: -21e3,
1810
- presetMax: 21e3
1902
+ nrpn: 2
1811
1903
  },
1812
1904
  [GeneratorTypes.decayVolEnv]: {
1813
1905
  min: -12e3,
1814
1906
  max: 8e3,
1815
1907
  def: -12e3,
1816
- nrpn: 2,
1817
- presetMin: -21e3,
1818
- presetMax: 21e3
1908
+ nrpn: 2
1819
1909
  },
1820
1910
  [GeneratorTypes.sustainVolEnv]: {
1821
1911
  min: 0,
1822
1912
  max: 1440,
1823
1913
  def: 0,
1824
- nrpn: 1,
1825
- presetMin: -1440
1914
+ nrpn: 1
1826
1915
  },
1827
1916
  [GeneratorTypes.releaseVolEnv]: {
1828
1917
  min: -12e3,
1829
1918
  max: 8e3,
1830
1919
  def: -12e3,
1831
- nrpn: 2,
1832
- presetMin: -21e3,
1833
- presetMax: 21e3
1920
+ nrpn: 2
1834
1921
  },
1835
1922
  [GeneratorTypes.keyNumToVolEnvHold]: {
1836
1923
  min: -1200,
1837
1924
  max: 1200,
1838
1925
  def: 0,
1839
- nrpn: 1,
1840
- presetMin: -2400,
1841
- presetMax: 2400
1926
+ nrpn: 1
1842
1927
  },
1843
1928
  [GeneratorTypes.keyNumToVolEnvDecay]: {
1844
1929
  min: -1200,
1845
1930
  max: 1200,
1846
1931
  def: 0,
1847
- nrpn: 1,
1848
- presetMin: -2400,
1849
- presetMax: 2400
1932
+ nrpn: 1
1850
1933
  },
1851
1934
  [GeneratorTypes.startloopAddrsCoarseOffset]: {
1852
1935
  min: -32768,
@@ -1870,8 +1953,7 @@ const GeneratorLimits = Object.freeze({
1870
1953
  min: 0,
1871
1954
  max: 1440,
1872
1955
  def: 0,
1873
- nrpn: 1,
1874
- presetMin: -1440
1956
+ nrpn: 1
1875
1957
  },
1876
1958
  [GeneratorTypes.endloopAddrsCoarseOffset]: {
1877
1959
  min: -32768,
@@ -1883,28 +1965,23 @@ const GeneratorLimits = Object.freeze({
1883
1965
  min: -120,
1884
1966
  max: 120,
1885
1967
  def: 0,
1886
- nrpn: 1,
1887
- presetMin: -240,
1888
- presetMax: 240
1968
+ nrpn: 1
1889
1969
  },
1890
1970
  [GeneratorTypes.fineTune]: {
1891
1971
  min: -12700,
1892
1972
  max: 12700,
1893
1973
  def: 0,
1894
- nrpn: 1,
1895
- presetMin: -198,
1896
- presetMax: 198
1974
+ nrpn: 1
1897
1975
  },
1898
1976
  [GeneratorTypes.scaleTuning]: {
1899
1977
  min: 0,
1900
1978
  max: 1200,
1901
1979
  def: 100,
1902
- nrpn: 1,
1903
- presetMin: -1200
1980
+ nrpn: 1
1904
1981
  },
1905
1982
  [GeneratorTypes.exclusiveClass]: {
1906
1983
  min: 0,
1907
- max: 99999,
1984
+ max: 32767,
1908
1985
  def: 0,
1909
1986
  nrpn: 0
1910
1987
  },
@@ -2703,6 +2780,13 @@ var MIDIPatchTools = class MIDIPatchTools {
2703
2780
  returnReplacement(patches[0]);
2704
2781
  return patches[0];
2705
2782
  }
2783
+ if (system === "gs") {
2784
+ p = matchingPrograms.find((p) => p.bankMSB === 0 && p.bankLSB === bankLSB);
2785
+ if (p) {
2786
+ returnReplacement(p);
2787
+ return p;
2788
+ }
2789
+ }
2706
2790
  p = isXG ? matchingPrograms.find((p) => p.bankLSB === bankLSB) : matchingPrograms.find((p) => p.bankMSB === bankMSB);
2707
2791
  if (p) {
2708
2792
  returnReplacement(p);
@@ -3997,6 +4081,12 @@ var MIDIUtils = class MIDIUtils {
3997
4081
  controller: MIDIControllers.reverbDepth,
3998
4082
  value
3999
4083
  }];
4084
+ case 20: return [{
4085
+ type: "Controller Change",
4086
+ channel,
4087
+ controller: MIDIControllers.variationDepth,
4088
+ value
4089
+ }];
4000
4090
  case 21: return [{
4001
4091
  type: "Controller Change",
4002
4092
  channel,
@@ -7337,6 +7427,22 @@ var BasicSample = class {
7337
7427
  return this.linkedTo.length;
7338
7428
  }
7339
7429
  /**
7430
+ * If the decoded float data is currently held in memory.
7431
+ * Check it before {@link getAudioData} to know if the call has to decode,
7432
+ * then use {@link releaseDecoded} to drop the copy again.
7433
+ */
7434
+ get isDecoded() {
7435
+ return this.audioData !== void 0;
7436
+ }
7437
+ /**
7438
+ * If the decoded float data can be made again from the stored data.
7439
+ * False for replaced data (set with {@link BasicSample.setAudioData}), which has nothing to decode from.
7440
+ * @internal
7441
+ */
7442
+ get canRedecode() {
7443
+ return !this.dataOverridden && (this.compressedData !== void 0 || this.s16leData !== void 0);
7444
+ }
7445
+ /**
7340
7446
  * Get raw data for writing the file, either a compressed bit stream or signed 16-bit little endian PCM data.
7341
7447
  * @param allowVorbis if vorbis file data is allowed.
7342
7448
  * @return either s16le or vorbis data.
@@ -7412,7 +7518,7 @@ var BasicSample = class {
7412
7518
  * @returns True if the decoded data was dropped.
7413
7519
  */
7414
7520
  releaseDecoded() {
7415
- if (this.audioData && !this.dataOverridden && (this.compressedData || this.s16leData)) {
7521
+ if (this.audioData && this.canRedecode) {
7416
7522
  this.audioData = void 0;
7417
7523
  return true;
7418
7524
  }
@@ -7444,12 +7550,13 @@ var BasicSample = class {
7444
7550
  this.setAudioData(resampled, newSampleRate);
7445
7551
  }
7446
7552
  /**
7447
- * Compresses the audio data
7553
+ * Compresses the audio data.
7448
7554
  * @param encodeVorbis the compression function to use when compressing.
7555
+ * @returns True if the sample is compressed afterward, false if the encoder failed and it stays uncompressed.
7449
7556
  * @internal
7450
7557
  */
7451
7558
  async compressSample(encodeVorbis) {
7452
- if (this.isCompressed) return;
7559
+ if (this.isCompressed) return true;
7453
7560
  try {
7454
7561
  let audioData = this.getAudioData();
7455
7562
  if (this.sampleRate < 8e3 || this.sampleRate > 96e3) {
@@ -7458,9 +7565,11 @@ var BasicSample = class {
7458
7565
  }
7459
7566
  const compressed = await encodeVorbis(audioData, this.sampleRate);
7460
7567
  this.setCompressedData(compressed);
7568
+ return true;
7461
7569
  } catch (error) {
7462
7570
  SpessaLog.warn(`Failed to compress ${this.name}. Leaving as uncompressed!`, error);
7463
7571
  this.compressedData = void 0;
7572
+ return false;
7464
7573
  }
7465
7574
  }
7466
7575
  /**
@@ -7510,16 +7619,17 @@ var BasicSample = class {
7510
7619
  }
7511
7620
  }
7512
7621
  /**
7513
- * Links the sample to a given instrument
7514
- * @param instrument the instrument to link to
7622
+ * Links the sample to a given instrument.
7623
+ * @param instrument the instrument to link to.
7515
7624
  * @internal
7516
7625
  */
7517
7626
  linkTo(instrument) {
7518
7627
  this.linkedTo.push(instrument);
7519
7628
  }
7520
7629
  /**
7521
- * Unlinks the sample from a given instrument
7522
- * @param instrument the instrument to unlink from
7630
+ * Unlinks the sample from a given instrument.
7631
+ * @param instrument the instrument to unlink from.
7632
+ * @internal
7523
7633
  */
7524
7634
  unlinkFrom(instrument) {
7525
7635
  const index = this.linkedTo.indexOf(instrument);
@@ -7587,13 +7697,9 @@ var BasicSample = class {
7587
7697
  return /* @__PURE__ */ new Float32Array(1);
7588
7698
  }
7589
7699
  const audioData = new Float32Array(length);
7590
- if (data.byteOffset % 2 === 0) {
7591
- const s16 = new Int16Array(data.buffer, data.byteOffset, length);
7592
- for (let i = 0; i < length; i++) audioData[i] = s16[i] / 32768;
7593
- } else {
7594
- const view = new DataView(data.buffer, data.byteOffset, length * 2);
7595
- for (let i = 0; i < length; i++) audioData[i] = view.getInt16(i * 2, true) / 32768;
7596
- }
7700
+ const aligned = data.byteOffset % 2 === 0 ? data : data.slice(0, length * 2);
7701
+ const s16 = new Int16Array(aligned.buffer, aligned.byteOffset, length);
7702
+ for (let i = 0; i < length; i++) audioData[i] = s16[i] / 32768;
7597
7703
  return audioData;
7598
7704
  }
7599
7705
  /**
@@ -7886,12 +7992,12 @@ var ModulatorSource = class ModulatorSource {
7886
7992
  */
7887
7993
  curveType;
7888
7994
  /**
7889
- * @internal
7890
- * @param index
7891
- * @param curveType
7892
- * @param isCC
7893
- * @param isBipolar
7894
- * @param isNegative
7995
+ * Creates a new modulator source.
7996
+ * @param index The controller or MIDI CC number, see `isCC`.
7997
+ * @param curveType How the minimum value approaches the maximum value.
7998
+ * @param isCC If the index is a MIDI CC instead of a general controller.
7999
+ * @param isBipolar If the source is bipolar (-1 to 1) instead of unipolar (0 to 1).
8000
+ * @param isNegative If the direction of the source is flipped.
7895
8001
  */
7896
8002
  constructor(index = ModulatorControllerSources.noController, curveType = ModulatorCurveTypes.linear, isCC = false, isBipolar = false, isNegative = false) {
7897
8003
  this.isBipolar = isBipolar;
@@ -8359,14 +8465,13 @@ var BasicLinkedZone = class extends BasicZone {
8359
8465
  }
8360
8466
  /**
8361
8467
  * Links the child to the parent, unless this zone was created without linking.
8362
- * @internal
8468
+ * Use it to put a zone back after {@link unlinkChild}, for example when undoing a zone deletion.
8363
8469
  */
8364
8470
  linkChild() {
8365
8471
  if (this.linked) this.child.linkTo(this.parent);
8366
8472
  }
8367
8473
  /**
8368
8474
  * Unlinks the child from the parent, unless this zone was created without linking.
8369
- * @internal
8370
8475
  */
8371
8476
  unlinkChild() {
8372
8477
  if (this.linked) this.child.unlinkFrom(this.parent);
@@ -8754,7 +8859,7 @@ var BasicPreset = class BasicPreset {
8754
8859
  }
8755
8860
  }
8756
8861
  finalGenList = finalGenList.filter((g) => g.type !== GeneratorTypes.sampleID && g.type !== GeneratorTypes.keyRange && g.type !== GeneratorTypes.velRange && g.type !== GeneratorTypes.endOper && g.type !== GeneratorTypes.instrument && (!(g.type in GeneratorLimits) || g.value !== GeneratorLimits[g.type].def));
8757
- const zone = outputInstrument.createZone(instZone.sample);
8862
+ const zone = outputInstrument.createZone(instZone.sample, false);
8758
8863
  zone.keyRange = instZoneKeyRange;
8759
8864
  zone.velRange = instZoneVelRange;
8760
8865
  if (zone.keyRange.min === 0 && zone.keyRange.max === 127) zone.keyRange.min = -1;
@@ -8884,6 +8989,7 @@ var BasicInstrument = class {
8884
8989
  /**
8885
8990
  * Unlinks the instrument from a given preset.
8886
8991
  * @param preset The preset to unlink from.
8992
+ * @internal
8887
8993
  */
8888
8994
  unlinkFrom(preset) {
8889
8995
  const index = this.linkedTo.indexOf(preset);
@@ -9168,7 +9274,7 @@ function writeSF(bank, software, writeDefaultModulators, writeExtendedLimits, wr
9168
9274
  */
9169
9275
  const infoArrays = [];
9170
9276
  const writeSF2Info = (type, data) => {
9171
- if (!data) return;
9277
+ if (data === void 0) return;
9172
9278
  infoArrays.push(...RIFFChunk.getParts(type, [getStringBytes(data, true, true)], rf64));
9173
9279
  };
9174
9280
  const info = bank.soundBankInfo;
@@ -9179,7 +9285,7 @@ function writeSF(bank, software, writeDefaultModulators, writeExtendedLimits, wr
9179
9285
  infoArrays.push(RIFFChunk.write("ifil", ifilData, rf64));
9180
9286
  }
9181
9287
  writeSF2Info("isng", info.soundEngine);
9182
- writeSF2Info("INAM", info.name);
9288
+ writeSF2Info("INAM", info.name ?? "");
9183
9289
  writeSF2Info("irom", info.romInfo);
9184
9290
  if (info.romVersion) {
9185
9291
  const ifilData = new IndexedByteArray(4);
@@ -9566,6 +9672,9 @@ var DLSSample = class extends BasicSample {
9566
9672
  if (this.rawData && !this.audioData) return "float32";
9567
9673
  return super.storedForm;
9568
9674
  }
9675
+ get canRedecode() {
9676
+ return this.rawData !== void 0 && !this.dataOverridden || super.canRedecode;
9677
+ }
9569
9678
  getStoredData() {
9570
9679
  if (this.rawData && !this.audioData) this.getAudioData();
9571
9680
  return super.getStoredData();
@@ -9574,13 +9683,6 @@ var DLSSample = class extends BasicSample {
9574
9683
  this.rawData = void 0;
9575
9684
  super.setStoredData(stored);
9576
9685
  }
9577
- releaseDecoded() {
9578
- if (this.rawData && this.audioData && !this.dataOverridden) {
9579
- this.audioData = void 0;
9580
- return true;
9581
- }
9582
- return super.releaseDecoded();
9583
- }
9584
9686
  releaseData() {
9585
9687
  if (this.hasData) this.releasedForm = this.storedForm;
9586
9688
  this.cachedLength = this.sampleLength;
@@ -9658,7 +9760,7 @@ var DownloadableSoundsSample = class DownloadableSoundsSample extends DLSVerifie
9658
9760
  }
9659
9761
  static fromSFSample(sample) {
9660
9762
  const raw = sample.getRawData(false);
9661
- const dlsSample = new DownloadableSoundsSample(1, 2, sample.sampleRate, new RIFFChunk("data", raw.length, new IndexedByteArray(raw.buffer)));
9763
+ const dlsSample = new DownloadableSoundsSample(1, 2, sample.sampleRate, new RIFFChunk("data", raw.length, new IndexedByteArray(raw.buffer, raw.byteOffset, raw.byteLength)));
9662
9764
  dlsSample.name = sample.name;
9663
9765
  dlsSample.waveSample = WaveSample.fromSFSample(sample);
9664
9766
  return dlsSample;
@@ -10746,8 +10848,8 @@ var DownloadableSoundsInstrument = class DownloadableSoundsInstrument extends DL
10746
10848
  SpessaLog.groupCollapsed(`%cWriting %c${this.name}%c...`, ConsoleColors.info, ConsoleColors.recognized, ConsoleColors.info);
10747
10849
  const chunks = [this.writeHeader()];
10748
10850
  const regionChunks = this.regions.flatMap((r) => r.write());
10749
- chunks.push(...RIFFChunk.getParts("lrgn", regionChunks, false, true));
10750
- if (this.articulation.length > 0) chunks.push(...this.articulation.write());
10851
+ for (const part of RIFFChunk.getParts("lrgn", regionChunks, false, true)) chunks.push(part);
10852
+ if (this.articulation.length > 0) for (const part of this.articulation.write()) chunks.push(part);
10751
10853
  const inam = RIFFChunk.write("INAM", getStringBytes(this.name, true));
10752
10854
  chunks.push(RIFFChunk.write("INFO", inam, false, true));
10753
10855
  SpessaLog.groupEnd();
@@ -11032,7 +11134,7 @@ var DownloadableSounds = class DownloadableSounds extends DLSVerifier {
11032
11134
  */
11033
11135
  const DEFAULT_SOUND_BANK_CLONE_OPTIONS = {
11034
11136
  reuseByName: true,
11035
- reuseChildrenByName: true,
11137
+ reuseChildren: "name",
11036
11138
  addToBank: true
11037
11139
  };
11038
11140
  const MAX_BASE_NAME_LENGTH = 37;
@@ -11079,6 +11181,17 @@ var SoundBankCloner = class {
11079
11181
  this.bank = bank;
11080
11182
  this.options = fillWithDefaults(options, DEFAULT_SOUND_BANK_CLONE_OPTIONS);
11081
11183
  }
11184
+ get ownReuse() {
11185
+ return this.options.reuseByName ? "name" : "none";
11186
+ }
11187
+ /**
11188
+ * Gets the clone this session made of an element.
11189
+ * @param source The sample or instrument that was cloned.
11190
+ * @returns The clone, or undefined if the session has not cloned the element.
11191
+ */
11192
+ getClone(source) {
11193
+ return source instanceof BasicSample ? this.sampleClones.get(source) : this.instrumentClones.get(source);
11194
+ }
11082
11195
  /**
11083
11196
  * Clones a sample and its stereo partner.
11084
11197
  * The data is shared with the original, not copied.
@@ -11086,7 +11199,7 @@ var SoundBankCloner = class {
11086
11199
  * @returns The clone, or the existing sample with the same name if it is reused.
11087
11200
  */
11088
11201
  cloneSample(sample) {
11089
- return this.copySample(sample, this.options.reuseByName);
11202
+ return this.copySample(sample, this.ownReuse);
11090
11203
  }
11091
11204
  /**
11092
11205
  * Clones an instrument and the samples it uses.
@@ -11094,7 +11207,7 @@ var SoundBankCloner = class {
11094
11207
  * @returns The clone, or the existing instrument with the same name if it is reused.
11095
11208
  */
11096
11209
  cloneInstrument(instrument) {
11097
- return this.copyInstrument(instrument, this.options.reuseByName);
11210
+ return this.copyInstrument(instrument, this.ownReuse);
11098
11211
  }
11099
11212
  /**
11100
11213
  * Clones a preset and the instruments and samples it uses.
@@ -11103,10 +11216,8 @@ var SoundBankCloner = class {
11103
11216
  */
11104
11217
  clonePreset(preset) {
11105
11218
  const all = [...this.bank.presets, ...this.created.presets];
11106
- if (this.options.reuseByName) {
11107
- const existing = all.find((p) => p.name === preset.name);
11108
- if (existing) return existing;
11109
- }
11219
+ const existing = this.findReused(preset, all, this.ownReuse);
11220
+ if (existing) return existing;
11110
11221
  const newPreset = new BasicPreset(this.bank);
11111
11222
  newPreset.name = this.getFreeName(preset.name, all);
11112
11223
  newPreset.bankMSB = preset.bankMSB;
@@ -11117,7 +11228,7 @@ var SoundBankCloner = class {
11117
11228
  newPreset.genre = preset.genre;
11118
11229
  newPreset.morphology = preset.morphology;
11119
11230
  newPreset.globalZone.copyFrom(preset.globalZone);
11120
- for (const zone of preset.zones) newPreset.createZone(this.copyInstrument(zone.instrument, this.options.reuseChildrenByName)).copyFrom(zone);
11231
+ for (const zone of preset.zones) newPreset.createZone(this.copyInstrument(zone.instrument, this.options.reuseChildren)).copyFrom(zone);
11121
11232
  this.created.presets.push(newPreset);
11122
11233
  if (this.options.addToBank) this.bank.addPresets(newPreset);
11123
11234
  return newPreset;
@@ -11126,14 +11237,12 @@ var SoundBankCloner = class {
11126
11237
  const cloned = this.instrumentClones.get(instrument);
11127
11238
  if (cloned) return cloned;
11128
11239
  const all = [...this.bank.instruments, ...this.created.instruments];
11129
- if (reuse) {
11130
- const existing = all.find((i) => i.name === instrument.name);
11131
- if (existing) return existing;
11132
- }
11240
+ const existing = this.findReused(instrument, all, reuse);
11241
+ if (existing) return existing;
11133
11242
  const newInstrument = new BasicInstrument();
11134
11243
  newInstrument.name = this.getFreeName(instrument.name, all);
11135
11244
  newInstrument.globalZone.copyFrom(instrument.globalZone);
11136
- for (const zone of instrument.zones) newInstrument.createZone(this.copySample(zone.sample, this.options.reuseChildrenByName)).copyFrom(zone);
11245
+ for (const zone of instrument.zones) newInstrument.createZone(this.copySample(zone.sample, this.options.reuseChildren)).copyFrom(zone);
11137
11246
  this.instrumentClones.set(instrument, newInstrument);
11138
11247
  this.created.instruments.push(newInstrument);
11139
11248
  if (this.options.addToBank) this.bank.addInstruments(newInstrument);
@@ -11143,10 +11252,8 @@ var SoundBankCloner = class {
11143
11252
  const cloned = this.sampleClones.get(sample);
11144
11253
  if (cloned) return cloned;
11145
11254
  const all = [...this.bank.samples, ...this.created.samples];
11146
- if (reuse) {
11147
- const existing = all.find((s) => s.name === sample.name);
11148
- if (existing) return existing;
11149
- }
11255
+ const existing = this.findReused(sample, all, reuse);
11256
+ if (existing) return existing;
11150
11257
  const newSample = new BasicSample(this.getFreeName(sample.name, all), sample.sampleRate, sample.originalKey, sample.pitchCorrection, sample.sampleType, sample.loopStart, sample.loopEnd);
11151
11258
  if (sample.hasData) newSample.setStoredData(sample.getStoredData());
11152
11259
  else {
@@ -11160,10 +11267,20 @@ var SoundBankCloner = class {
11160
11267
  if (linked) {
11161
11268
  const newLinked = this.sampleClones.get(linked);
11162
11269
  if (newLinked) newSample.setLinkedSample(newLinked, sample.sampleType);
11163
- else this.copySample(linked, false);
11270
+ else this.copySample(linked, "none");
11164
11271
  }
11165
11272
  return newSample;
11166
11273
  }
11274
+ /**
11275
+ * Finds the element to use instead of a copy, if the options allow one.
11276
+ */
11277
+ findReused(element, elements, reuse) {
11278
+ switch (reuse) {
11279
+ case "none": return;
11280
+ case "identity": return elements.includes(element) ? element : void 0;
11281
+ case "name": return elements.find((e) => e.name === element.name);
11282
+ }
11283
+ }
11167
11284
  getFreeName(name, elements) {
11168
11285
  const taken = new Set(elements.map((e) => e.name));
11169
11286
  if (!taken.has(name)) return name;
@@ -11329,7 +11446,7 @@ var BasicSoundBank = class BasicSoundBank {
11329
11446
  const copied = new BasicSoundBank(bank.type);
11330
11447
  const cloner = new SoundBankCloner(copied, {
11331
11448
  reuseByName: false,
11332
- reuseChildrenByName: false
11449
+ reuseChildren: "none"
11333
11450
  });
11334
11451
  for (const p of bank.presets) cloner.clonePreset(p);
11335
11452
  copied.soundBankInfo = { ...bank.soundBankInfo };
@@ -11343,13 +11460,13 @@ var BasicSoundBank = class BasicSoundBank {
11343
11460
  * @param presets The presets to add.
11344
11461
  */
11345
11462
  addCompletePresets(presets) {
11346
- this.addPresets(...presets);
11463
+ this.addElements(this.presets, presets);
11347
11464
  const instrumentList = [];
11348
11465
  for (const preset of presets) for (const zone of preset.zones) if (zone.instrument && !instrumentList.includes(zone.instrument)) instrumentList.push(zone.instrument);
11349
- this.addInstruments(...instrumentList);
11466
+ this.addElements(this.instruments, instrumentList);
11350
11467
  const sampleList = [];
11351
11468
  for (const instrument of instrumentList) for (const zone of instrument.zones) if (zone.sample && !sampleList.includes(zone.sample)) sampleList.push(zone.sample);
11352
- this.addSamples(...sampleList);
11469
+ this.addElements(this.samples, sampleList);
11353
11470
  }
11354
11471
  /**
11355
11472
  * Sets the sound bank's sample format _in place_.
@@ -11363,9 +11480,11 @@ var BasicSoundBank = class BasicSoundBank {
11363
11480
  * @param options Options associated with setting the sample format.
11364
11481
  * @returns The samples whose sample rate or loop points changed.
11365
11482
  * Compressing resamples samples outside 8000 to 96000 Hz.
11483
+ * @throws Error if `rejectOnFailure` is set and one of the samples has failed to compress.
11366
11484
  */
11367
11485
  async setSampleFormat(options) {
11368
11486
  const changed = new Array();
11487
+ const failed = new Array();
11369
11488
  let writtenCount = 0;
11370
11489
  const format = options.format;
11371
11490
  const progressFunc = options.progressFunction;
@@ -11379,7 +11498,7 @@ var BasicSoundBank = class BasicSoundBank {
11379
11498
  const f = options.compressionFunction;
11380
11499
  if (!f) throw new Error(`No compression function supplied but '${format}' was requested.`);
11381
11500
  const { sampleRate, loopStart, loopEnd } = s;
11382
- await s.compressSample(f);
11501
+ if (!await s.compressSample(f)) failed.push(s);
11383
11502
  if (s.sampleRate !== sampleRate || s.loopStart !== loopStart || s.loopEnd !== loopEnd) changed.push(s);
11384
11503
  }
11385
11504
  }
@@ -11387,6 +11506,7 @@ var BasicSoundBank = class BasicSoundBank {
11387
11506
  progressFunc?.(writtenCount / this.samples.length);
11388
11507
  SpessaLog.info(`%cEncoded sample %c${writtenCount}. ${s.name}%c of %c${this.samples.length}%c. Compressed: %c${s.isCompressed}%c.`, ConsoleColors.info, ConsoleColors.recognized, ConsoleColors.info, ConsoleColors.recognized, ConsoleColors.info, s.isCompressed ? ConsoleColors.recognized : ConsoleColors.unrecognized, ConsoleColors.info);
11389
11508
  }
11509
+ if (failed.length > 0 && options.format === "compressed" && options.rejectOnFailure) throw new Error(`Failed to compress ${failed.length} samples: ${failed.map((s) => s.name).join(", ")}`);
11390
11510
  switch (format) {
11391
11511
  default:
11392
11512
  case "pcm":
@@ -11450,21 +11570,21 @@ var BasicSoundBank = class BasicSoundBank {
11450
11570
  * @param presets The presets to add.
11451
11571
  */
11452
11572
  addPresets(...presets) {
11453
- this.presets.push(...presets);
11573
+ this.addElements(this.presets, presets);
11454
11574
  }
11455
11575
  /**
11456
11576
  * Adds {@link BasicInstrument}s to this sound bank.
11457
11577
  * @param instruments The instruments to add.
11458
11578
  */
11459
11579
  addInstruments(...instruments) {
11460
- this.instruments.push(...instruments);
11580
+ this.addElements(this.instruments, instruments);
11461
11581
  }
11462
11582
  /**
11463
11583
  * Adds {@link BasicSample}s to this sound bank.
11464
11584
  * @param samples The samples to add.
11465
11585
  */
11466
11586
  addSamples(...samples) {
11467
- this.samples.push(...samples);
11587
+ this.addElements(this.samples, samples);
11468
11588
  }
11469
11589
  /**
11470
11590
  * Clones a sample into this bank, together with its stereo partner.
@@ -11516,9 +11636,11 @@ var BasicSoundBank = class BasicSoundBank {
11516
11636
  }
11517
11637
  /**
11518
11638
  * Updates internal values. Call after updating the preset list.
11639
+ * @param sort If the presets should be sorted. Set it to `false` to keep a custom order,
11640
+ * only the internal values (like {@link isXGBank}) are then recomputed.
11519
11641
  */
11520
- flush() {
11521
- this.presets.sort(MIDIPatchTools.compare.bind(MIDIPatchTools));
11642
+ flush(sort = true) {
11643
+ if (sort) this.presets.sort(MIDIPatchTools.compare.bind(MIDIPatchTools));
11522
11644
  this.parseInternal();
11523
11645
  }
11524
11646
  /**
@@ -11663,6 +11785,9 @@ var BasicSoundBank = class BasicSoundBank {
11663
11785
  this.instruments.length = 0;
11664
11786
  this.samples.length = 0;
11665
11787
  }
11788
+ addElements(list, elements) {
11789
+ for (const element of elements) list.push(element);
11790
+ }
11666
11791
  parsingError(error) {
11667
11792
  throw new Error(`SF parsing error: ${error} The file may be corrupted.`);
11668
11793
  }
@@ -15464,7 +15589,6 @@ function setTimeToInternal(time, ticks = void 0) {
15464
15589
  const channel = analyzed.channel + portOffset;
15465
15590
  if (channel >= this.synth.midiChannels.length) break;
15466
15591
  channels[channel] ??= createChannelStatus(channel);
15467
- if (this._midiData.isMultiPort && track.channels.size === 0) break;
15468
15592
  if (controller === MIDIControllers.resetAllControllers) {
15469
15593
  resetAllControllers(channel);
15470
15594
  break;
@@ -52867,15 +52991,19 @@ var SoundBankManager = class {
52867
52991
  */
52868
52992
  userDrumSets;
52869
52993
  presetListChangeCallback;
52994
+ bankRemovedCallback;
52870
52995
  selectablePresetList = [];
52871
52996
  /**
52872
52997
  * @internal
52873
52998
  * @param presetListChangeCallback Supplied by the parent synthesizer class,
52874
52999
  * this is called whenever the preset list changes.
52875
53000
  * The argument tells if the synthesizer should reset after updating its channels.
53001
+ * @param bankRemovedCallback Called when a sound bank leaves the manager (deleted, replaced or destroyed),
53002
+ * so the synthesizer can drop what it holds of it.
52876
53003
  */
52877
- constructor(presetListChangeCallback) {
53004
+ constructor(presetListChangeCallback, bankRemovedCallback) {
52878
53005
  this.presetListChangeCallback = presetListChangeCallback;
53006
+ this.bankRemovedCallback = bankRemovedCallback;
52879
53007
  const resolvePatch = (patch) => this.getPreset(patch, this.systemGetter());
52880
53008
  this.userDrumSets = [new UserDrumSet(64, "User Drum Set 1", resolvePatch), new UserDrumSet(65, "User Drum Set 2", resolvePatch)];
52881
53009
  }
@@ -52924,13 +53052,16 @@ var SoundBankManager = class {
52924
53052
  /**
52925
53053
  * This method removes a sound bank with a given ID from the sound bank list.
52926
53054
  * @param id The ID of the sound bank to delete.
53055
+ * @param reset If the synthesizer should reset (put every channel's controllers back to defaults) after the change.
53056
+ * Set it to `false` to keep a song playing, the channels then only update to the new presets.
52927
53057
  * @throws Error An error if there's no sound bank with the given ID.
52928
53058
  */
52929
- deleteSoundBank(id) {
53059
+ deleteSoundBank(id, reset = true) {
52930
53060
  const index = this.soundBankList.findIndex((s) => s.id === id);
52931
53061
  if (index === -1) throw new Error(`No sound bank with id "${id}"`);
52932
- this.soundBankList.splice(index, 1);
52933
- this.generatePresetList();
53062
+ const [removed] = this.soundBankList.splice(index, 1);
53063
+ this.bankRemoved(removed.soundBank);
53064
+ this.generatePresetList(reset);
52934
53065
  }
52935
53066
  /**
52936
53067
  * Adds a new sound bank with a given ID, or replaces an existing one.
@@ -52938,8 +53069,10 @@ var SoundBankManager = class {
52938
53069
  * @param id The unique ID to assign to the sound bank.
52939
53070
  * If a sound bank with this ID already exists, it will be replaced.
52940
53071
  * @param bankOffset The bank offset of the sound bank. Offsets the bank MSB value of all presets in this sound bank.
53072
+ * @param reset If the synthesizer should reset (put every channel's controllers back to defaults) after the change.
53073
+ * Set it to `false` to keep a song playing, the channels then only update to the new presets.
52941
53074
  */
52942
- addSoundBank(bank, id, bankOffset = 0) {
53075
+ addSoundBank(bank, id, bankOffset = 0, reset = true) {
52943
53076
  const foundBank = this.soundBankList.find((s) => s.id === id);
52944
53077
  if (foundBank === void 0) this.soundBankList.push({
52945
53078
  id,
@@ -52947,10 +53080,12 @@ var SoundBankManager = class {
52947
53080
  bankOffset
52948
53081
  });
52949
53082
  else {
53083
+ const old = foundBank.soundBank;
52950
53084
  foundBank.soundBank = bank;
52951
53085
  foundBank.bankOffset = bankOffset;
53086
+ this.bankRemoved(old);
52952
53087
  }
52953
- this.generatePresetList();
53088
+ this.generatePresetList(reset);
52954
53089
  }
52955
53090
  /**
52956
53091
  * Rebuilds the preset list from the current sound banks.
@@ -52980,11 +53115,17 @@ var SoundBankManager = class {
52980
53115
  * @internal
52981
53116
  */
52982
53117
  destroy() {
52983
- for (const s of this.soundBankList) s.soundBank.destroySoundBank();
53118
+ for (const s of this.soundBankList) {
53119
+ this.bankRemovedCallback?.(s.soundBank);
53120
+ s.soundBank.destroySoundBank();
53121
+ }
52984
53122
  this.soundBankList = [];
52985
53123
  this.selectablePresetList = [];
52986
53124
  this._presetList = [];
52987
53125
  }
53126
+ bankRemoved(bank) {
53127
+ if (!this.soundBankList.some((s) => s.soundBank === bank)) this.bankRemovedCallback?.(bank);
53128
+ }
52988
53129
  generatePresetList(resetSynth = true) {
52989
53130
  const presetList = new Array();
52990
53131
  const addedPresets = /* @__PURE__ */ new Set();
@@ -53133,7 +53274,7 @@ function renderVoice(voice, timeNow, sampleCount) {
53133
53274
  let targetKey = voice.targetKey;
53134
53275
  let cents = voice.pitchOffset + modulated[GeneratorTypes.fineTune] + this.octaveTuning[targetKey] + this.currentTuning;
53135
53276
  let semitones = modulated[GeneratorTypes.coarseTune];
53136
- const tuning = core.tunings[this.preset.program * 128 + voice.midiNote];
53277
+ const tuning = core.tunings[(this.preset?.program ?? this.patch.program) * 128 + voice.midiNote];
53137
53278
  if (tuning !== -1) {
53138
53279
  targetKey = Math.trunc(tuning);
53139
53280
  semitones += tuning - targetKey;
@@ -58986,7 +59127,7 @@ var SoundFont2 = class extends BasicSoundBank {
58986
59127
  }
58987
59128
  }
58988
59129
  for (const s of samples) s.name = s.name.trim();
58989
- this.samples.push(...samples);
59130
+ this.addElements(this.samples, samples);
58990
59131
  const instrumentGenerators = readGenerators(igenChunk, isSFE);
58991
59132
  const instrumentModulators = readModulators(imodChunk, isSFE);
58992
59133
  const extendInstruments = xdtaChunk !== void 0 && !!xChunks.inst;
@@ -59003,7 +59144,7 @@ var SoundFont2 = class extends BasicSoundBank {
59003
59144
  instruments.pop();
59004
59145
  }
59005
59146
  for (const i of instruments) i.name = i.name.trim();
59006
- this.instruments.push(...instruments);
59147
+ this.addElements(this.instruments, instruments);
59007
59148
  const ibagIndexes = readZoneIndexes(ibagChunk);
59008
59149
  if (xdtaChunk && xChunks.ibag) {
59009
59150
  const extraIndexes = readZoneIndexes(xChunks.ibag);
@@ -59030,7 +59171,7 @@ var SoundFont2 = class extends BasicSoundBank {
59030
59171
  presets.pop();
59031
59172
  }
59032
59173
  for (const p of presets) p.name = p.name.trim();
59033
- this.addPresets(...presets);
59174
+ this.addElements(this.presets, presets);
59034
59175
  const pbagIndexes = readZoneIndexes(pbagChunk);
59035
59176
  if (xdtaChunk && xChunks.pbag) {
59036
59177
  const extraIndexes = readZoneIndexes(xChunks.pbag);
@@ -59161,7 +59302,6 @@ var DecodedSampleCache = class {
59161
59302
  */
59162
59303
  totalBytes = 0;
59163
59304
  entries = /* @__PURE__ */ new Map();
59164
- unreleasable = /* @__PURE__ */ new WeakSet();
59165
59305
  voiceCache;
59166
59306
  /**
59167
59307
  * @param budget The budget in bytes.
@@ -59182,7 +59322,7 @@ var DecodedSampleCache = class {
59182
59322
  touch(sample, cacheKey) {
59183
59323
  let entry = this.entries.get(sample);
59184
59324
  if (entry) this.entries.delete(sample);
59185
- if (this.unreleasable.has(sample) || sample.storedForm === "float32" && !(sample instanceof DLSSample)) {
59325
+ if (!sample.canRedecode) {
59186
59326
  if (entry) this.totalBytes -= entry.bytes;
59187
59327
  return;
59188
59328
  }
@@ -59197,16 +59337,29 @@ var DecodedSampleCache = class {
59197
59337
  this.entries.set(sample, entry);
59198
59338
  if (this.totalBytes > this.budget) this.evict(sample);
59199
59339
  }
59340
+ /**
59341
+ * Stops tracking samples, for example when their sound bank is removed.
59342
+ * The samples are not released, the cache just stops holding them.
59343
+ * Voices cached from them are dropped too.
59344
+ * @param samples The samples to forget.
59345
+ */
59346
+ forget(samples) {
59347
+ for (const sample of samples) {
59348
+ const entry = this.entries.get(sample);
59349
+ if (!entry) continue;
59350
+ this.entries.delete(sample);
59351
+ this.totalBytes -= entry.bytes;
59352
+ for (const key of entry.cacheKeys) this.voiceCache.delete(key);
59353
+ }
59354
+ }
59200
59355
  evict(keep) {
59201
59356
  for (const [sample, entry] of this.entries) {
59202
59357
  if (this.totalBytes <= this.budget) return;
59203
59358
  if (sample === keep) continue;
59204
59359
  this.entries.delete(sample);
59205
59360
  this.totalBytes -= entry.bytes;
59206
- if (!sample.releaseDecoded()) {
59207
- this.unreleasable.add(sample);
59208
- continue;
59209
- }
59361
+ if (!sample.canRedecode) continue;
59362
+ sample.releaseDecoded();
59210
59363
  for (const key of entry.cacheKeys) this.voiceCache.delete(key);
59211
59364
  }
59212
59365
  }
@@ -59494,10 +59647,6 @@ var SpessaSynthProcessor = class {
59494
59647
  */
59495
59648
  gsDelayActive = false;
59496
59649
  /**
59497
- * The sound bank manager, which manages all sound banks and presets.
59498
- */
59499
- soundBankManager = new SoundBankManager(this.updatePresetList.bind(this));
59500
- /**
59501
59650
  * The sample rate, in Hertz.
59502
59651
  */
59503
59652
  sampleRate;
@@ -59593,6 +59742,12 @@ var SpessaSynthProcessor = class {
59593
59742
  */
59594
59743
  decodedSamples;
59595
59744
  /**
59745
+ * The sound bank manager, which manages all sound banks and presets.
59746
+ */
59747
+ soundBankManager = new SoundBankManager(this.updatePresetList.bind(this), (bank) => {
59748
+ this.decodedSamples.forget(bank.samples);
59749
+ });
59750
+ /**
59596
59751
  * The synthesizer's GS reverb processor.
59597
59752
  *
59598
59753
  * Used when {@link GlobalMIDIParameter.system} is `gm` `gm2` or `gs`.
@@ -60918,8 +61073,8 @@ var SpessaSynthProcessor = class {
60918
61073
  createMIDIChannelInternal(sendEvent) {
60919
61074
  const channel = new MIDIChannel(this, this.defaultPreset, this.drumPreset, this.midiChannels.length);
60920
61075
  this.midiChannels.push(channel);
60921
- channel.reset(false);
60922
61076
  if (sendEvent) this.callEvent("channelAdded", void 0);
61077
+ channel.reset(false);
60923
61078
  }
60924
61079
  processMessageInternal(message, channelOffset) {
60925
61080
  const byte = message[0];
@@ -61023,6 +61178,6 @@ var SpessaSynthProcessor = class {
61023
61178
  return (isGMGSDrum ? 128 + patch.bankMSB : patch.bankMSB) + bankLSB * 256 + program * 32768 + 4194304 * midiNote + 536870912 * velocity;
61024
61179
  }
61025
61180
  };
61026
- export { BasicInstrument, BasicInstrumentZone, BasicLinkedZone, BasicMIDI, BasicPreset, BasicPresetZone, BasicSample, BasicSoundBank, BasicZone, DEFAULT_CHANNEL_MIDI_PARAMETERS, DEFAULT_CHANNEL_SYSTEM_PARAMETERS, DEFAULT_DRUM_REVERB, DEFAULT_GLOBAL_MIDI_PARAMETERS, DEFAULT_GLOBAL_SYSTEM_PARAMETERS, DEFAULT_MIDI_CONTROLLERS, DEFAULT_SOUND_BANK_CLONE_OPTIONS, DEFAULT_SOUND_BANK_LOAD_OPTIONS, DEFAULT_SYNTH_MODE, DefaultGSChorus, DefaultGSDelay, DefaultGSEqualizer, DefaultGSInsertion, DefaultGSReverb, DefaultXGChorus, DefaultXGEffect, DefaultXGInsertion, DefaultXGReverb, DefaultXGSystemEffect, DefaultXGVariation, DrumParameterUtils, EmptySample, GENERATORS_AMOUNT, GSInsertionControlSources, Generator, GeneratorLimits, GeneratorTypes, INSTRUMENT_ONLY_GENERATORS, IndexedByteArray, InterpolationTypes, MAX_GENERATOR, MIDIBuilder, MIDIChannel, MIDIControllers, MIDIMessage, MIDIMessageTypes, MIDIPatchTools, MIDITrack, MIDIUtils, MIDI_DRUM_CHANNEL, Modulator, ModulatorControllerSources, ModulatorCurveTypes, ModulatorSource, ModulatorTransformTypes, NonRegisteredParameterTypesLSB, NonRegisteredParameterTypesMSB, RegisteredParameterTypes, SPESSASYNTH_GAIN_FACTOR, SPESSA_BUFSIZE, SampleTypes, SoundBankCloner, SoundBankLoader, SoundBankManager, SpessaLog, SpessaSynthCoreUtils, SpessaSynthProcessor, SpessaSynthSequencer, VOICE_CAP, audioToWav };
61181
+ export { BasicInstrument, BasicInstrumentZone, BasicLinkedZone, BasicMIDI, BasicPreset, BasicPresetZone, BasicSample, BasicSoundBank, BasicZone, DEFAULT_CHANNEL_MIDI_PARAMETERS, DEFAULT_CHANNEL_SYSTEM_PARAMETERS, DEFAULT_DRUM_REVERB, DEFAULT_GLOBAL_MIDI_PARAMETERS, DEFAULT_GLOBAL_SYSTEM_PARAMETERS, DEFAULT_MIDI_CONTROLLERS, DEFAULT_SOUND_BANK_CLONE_OPTIONS, DEFAULT_SOUND_BANK_LOAD_OPTIONS, DEFAULT_SYNTH_MODE, DefaultGSChorus, DefaultGSDelay, DefaultGSEqualizer, DefaultGSInsertion, DefaultGSReverb, DefaultXGChorus, DefaultXGEffect, DefaultXGInsertion, DefaultXGReverb, DefaultXGSystemEffect, DefaultXGVariation, DrumParameterUtils, EmptySample, GENERATORS_AMOUNT, GSInsertionControlSources, Generator, GeneratorLimits, GeneratorTypes, INSTRUMENT_ONLY_GENERATORS, IndexedByteArray, InterpolationTypes, MAX_GENERATOR, MIDIBuilder, MIDIChannel, MIDIControllers, MIDIMessage, MIDIMessageTypes, MIDIPatchTools, MIDITrack, MIDIUtils, MIDI_DRUM_CHANNEL, Modulator, ModulatorControllerSources, ModulatorCurveTypes, ModulatorSource, ModulatorTransformTypes, NonRegisteredParameterTypesLSB, NonRegisteredParameterTypesMSB, RegisteredParameterTypes, SPESSASYNTH_GAIN_FACTOR, SPESSA_BUFSIZE, SampleTypes, SoundBankCloner, SoundBankLoader, SoundBankManager, SpessaLog, SpessaSynthCoreUtils, SpessaSynthProcessor, SpessaSynthSequencer, VOICE_CAP, audioToWav, wavToAudio };
61027
61182
 
61028
61183
  //# sourceMappingURL=index.js.map