spessasynth_core 4.4.13 → 4.4.14

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.d.ts CHANGED
@@ -107,6 +107,15 @@ export declare class IndexedByteArray extends Uint8Array {
107
107
  * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
108
108
  */
109
109
  slice(start?: number, end?: number): IndexedByteArray;
110
+ /**
111
+ * Gets a new IndexedByteArray view of the ArrayBuffer store for this array, referencing the elements
112
+ * at begin, inclusive, up to end, exclusive.
113
+ * @param begin The index of the beginning of the array.
114
+ * @param end The index of the end of the array.
115
+ * @privateRemarks
116
+ * JSDoc copied from es5 type declarations
117
+ */
118
+ subarray(begin?: number, end?: number): IndexedByteArray;
110
119
  }
111
120
  /**
112
121
  * Reads number as Big endian.
@@ -1537,15 +1546,10 @@ export declare class CustomCurve extends ModulatorCurve {
1537
1546
  * > Duplicate entries are allowed since one element can use the same curve multiple times.
1538
1547
  */
1539
1548
  readonly linkedTo: CustomCurveUser[];
1540
- private storedPoints;
1541
- private px;
1542
- private py;
1543
- private readonly start;
1544
- private readonly gridUnipolar;
1545
- private readonly gridBipolar;
1549
+ private data;
1546
1550
  /**
1547
1551
  * Creates a new custom curve.
1548
- * @param points The points, ordered by `x`. At least two are needed.
1552
+ * @param points The points, ordered by `x`. At least two and at most 65,535 are needed.
1549
1553
  * @param name The name of the curve.
1550
1554
  */
1551
1555
  constructor(points: readonly CustomCurvePoint[], name?: string);
@@ -1557,10 +1561,18 @@ export declare class CustomCurve extends ModulatorCurve {
1557
1561
  * The curve points, ordered by `x`. They are frozen, use {@link setPoints} to change them.
1558
1562
  */
1559
1563
  get points(): readonly Readonly<CustomCurvePoint>[];
1560
- private static checkPoints;
1564
+ /**
1565
+ * The number of points in the curve.
1566
+ * @privateRemarks
1567
+ * Unlike `points.length`, it does not build the points list.
1568
+ */
1569
+ get pointCount(): number;
1570
+ private static fromPacked;
1571
+ private static pack;
1572
+ private static finishPacked;
1561
1573
  /**
1562
1574
  * Replaces the points of the curve. Every modulator using this curve follows the change.
1563
- * @param points The new points, ordered by `x`. At least two are needed.
1575
+ * @param points The new points, ordered by `x`. At least two and at most 65,535 are needed.
1564
1576
  * @throws Error if the points are invalid. The curve is left unchanged then.
1565
1577
  */
1566
1578
  setPoints(points: readonly CustomCurvePoint[]): void;
@@ -1571,7 +1583,6 @@ export declare class CustomCurve extends ModulatorCurve {
1571
1583
  isIdentical(other: ModulatorCurve): boolean;
1572
1584
  toString(): string;
1573
1585
  protected evaluate(value: number, isBipolar: boolean): number;
1574
- private precompute;
1575
1586
  }
1576
1587
  /**
1577
1588
  * This module represents a single sound bank as a [SpessaSynth SFe](../../../docs/extra/sfe-format.md) bank.
@@ -9036,6 +9047,12 @@ export declare class SoundBankCloner {
9036
9047
  private readonly sampleClones;
9037
9048
  private readonly curveClones;
9038
9049
  private readonly instrumentClones;
9050
+ /**
9051
+ * The names in the bank and the ones this session gave out, by element kind, built on first use.
9052
+ * A name changed or added in the bank from outside between two clone calls of one session is not seen,
9053
+ * The worst case is a repeated name, which banks allow
9054
+ */
9055
+ private readonly takenNames;
9039
9056
  /**
9040
9057
  * Creates a new clone session.
9041
9058
  * @param bank The bank to clone elements into.
@@ -9091,6 +9108,7 @@ export declare class SoundBankCloner {
9091
9108
  private copyCurve;
9092
9109
  /**
9093
9110
  * Finds the element to use instead of a copy, if the options allow one.
9111
+ * The lists are searched in order, without joining them, as this runs for every cloned element.
9094
9112
  */
9095
9113
  private findReused;
9096
9114
  private getFreeName;
package/dist/index.js CHANGED
@@ -157,6 +157,17 @@ var IndexedByteArray = class extends Uint8Array {
157
157
  a.currentIndex = 0;
158
158
  return a;
159
159
  }
160
+ /**
161
+ * Gets a new IndexedByteArray view of the ArrayBuffer store for this array, referencing the elements
162
+ * at begin, inclusive, up to end, exclusive.
163
+ * @param begin The index of the beginning of the array.
164
+ * @param end The index of the end of the array.
165
+ * @privateRemarks
166
+ * JSDoc copied from es5 type declarations
167
+ */
168
+ subarray(begin, end) {
169
+ return super.subarray(begin, end);
170
+ }
160
171
  };
161
172
  // src/utils/byte_functions/string.ts
162
173
  /**
@@ -321,6 +332,7 @@ var RIFFChunk = class RIFFChunk {
321
332
  size;
322
333
  /**
323
334
  * Chunk's binary data. Note that this will have a length of 0 if "readData" was set to false.
335
+ * When read from a file, it is a view into the file's buffer.
324
336
  */
325
337
  data;
326
338
  /**
@@ -347,7 +359,7 @@ var RIFFChunk = class RIFFChunk {
347
359
  const header = readBinaryStringIndexed(dataArray, 4);
348
360
  let size = rf64 ? readLE64Indexed(dataArray, 8) : readLittleEndianIndexed(dataArray, 4);
349
361
  if (header === "") size = 0;
350
- const chunkData = readData ? dataArray.slice(dataArray.currentIndex, dataArray.currentIndex + size) : new IndexedByteArray(0);
362
+ const chunkData = readData ? dataArray.subarray(dataArray.currentIndex, dataArray.currentIndex + size) : new IndexedByteArray(0);
351
363
  if (readData) {
352
364
  dataArray.currentIndex += size;
353
365
  if (size % 2 !== 0) dataArray.currentIndex++;
@@ -2861,7 +2873,13 @@ var MIDIPatchTools = class MIDIPatchTools {
2861
2873
  returnReplacement(patches[0]);
2862
2874
  return patches[0];
2863
2875
  }
2864
- if (!isXG) {
2876
+ if (isXG) {
2877
+ p = (bankMSB === 0 && bankLSB !== 48 && bankLSB !== 64 && bankLSB !== 126 && !matchingPrograms.some((p) => p.bankMSB === 0 && p.bankLSB !== 0) ? matchingPrograms.find((p) => p.bankMSB === bankLSB && p.bankLSB === 0) : void 0) ?? (bankMSB === 64 || bankMSB === 126 ? matchingPrograms.find((p) => p.bankMSB === bankMSB && p.bankLSB === 0) : void 0) ?? matchingPrograms.find((p) => p.bankMSB === BankSelectHacks.getDefaultBank(system) && p.bankLSB === 0) ?? matchingPrograms.find((p) => p.bankMSB === 0 && p.bankLSB === 0);
2878
+ if (p) {
2879
+ returnReplacement(p);
2880
+ return p;
2881
+ }
2882
+ } else {
2865
2883
  p = matchingPrograms.find((p) => p.bankMSB === 0 && p.bankLSB === bankLSB);
2866
2884
  if (p) {
2867
2885
  returnReplacement(p);
@@ -6469,7 +6487,7 @@ function parseRMIDIInternal(outputMIDI, binaryData, fileName) {
6469
6487
  while (currentChunk.data.currentIndex < currentChunk.size) {
6470
6488
  const infoChunk = RIFFChunk.read(currentChunk.data);
6471
6489
  const headerTyped = infoChunk.header;
6472
- const infoData = infoChunk.data;
6490
+ const infoData = infoChunk.data.slice();
6473
6491
  if (infoChunk.size === 0) {
6474
6492
  SpessaLog.warn(`Discarding empty RMIDI Info: ${headerTyped}`);
6475
6493
  continue;
@@ -8302,9 +8320,9 @@ const BUILT_IN_CURVES = [
8302
8320
  ];
8303
8321
  const UNRESOLVED_CURVES = /* @__PURE__ */ new Map();
8304
8322
  // src/soundbank/basic_soundbank/custom_curve.ts
8305
- const GRID_POSITIONS = [.../* @__PURE__ */ new Set([...SOURCE_VALUE_7_BIT, ...Array.from(SOURCE_VALUE_7_BIT, (x) => 16384 - x)])];
8306
- const GRID_SLOT = (/* @__PURE__ */ new Int16Array(16385)).fill(-1);
8307
- for (const [slot, x] of GRID_POSITIONS.entries()) GRID_SLOT[x] = slot;
8323
+ const START_SIZE = 33;
8324
+ let packedForConstructor;
8325
+ const POINTS_CACHE = /* @__PURE__ */ new WeakMap();
8308
8326
  /**
8309
8327
  * A modulator source curve stored in an SFe bank (curve type 4).
8310
8328
  * The value between two points is linearly interpolated.
@@ -8332,22 +8350,19 @@ var CustomCurve = class CustomCurve extends ModulatorCurve {
8332
8350
  * > Duplicate entries are allowed since one element can use the same curve multiple times.
8333
8351
  */
8334
8352
  linkedTo = new Array();
8335
- storedPoints;
8336
- px = /* @__PURE__ */ new Int32Array(0);
8337
- py = /* @__PURE__ */ new Float64Array(0);
8338
- start = /* @__PURE__ */ new Int32Array(129);
8339
- gridUnipolar = new Float32Array(GRID_POSITIONS.length);
8340
- gridBipolar = new Float32Array(GRID_POSITIONS.length);
8353
+ data;
8341
8354
  /**
8342
8355
  * Creates a new custom curve.
8343
- * @param points The points, ordered by `x`. At least two are needed.
8356
+ * @param points The points, ordered by `x`. At least two and at most 65,535 are needed.
8344
8357
  * @param name The name of the curve.
8345
8358
  */
8346
8359
  constructor(points, name = "") {
8347
8360
  super(ModulatorCurveTypes.custom);
8348
8361
  this.name = name;
8349
- this.storedPoints = CustomCurve.checkPoints(points);
8350
- this.precompute();
8362
+ if (packedForConstructor) {
8363
+ this.data = packedForConstructor;
8364
+ packedForConstructor = void 0;
8365
+ } else this.data = CustomCurve.pack(points);
8351
8366
  }
8352
8367
  /**
8353
8368
  * The number of modulator sources using this curve.
@@ -8359,18 +8374,87 @@ var CustomCurve = class CustomCurve extends ModulatorCurve {
8359
8374
  * The curve points, ordered by `x`. They are frozen, use {@link setPoints} to change them.
8360
8375
  */
8361
8376
  get points() {
8362
- return this.storedPoints;
8377
+ let points = POINTS_CACHE.get(this);
8378
+ if (!points) {
8379
+ const count = this.pointCount;
8380
+ const list = new Array(count);
8381
+ for (let i = 0; i < count; i++) list[i] = Object.freeze({
8382
+ x: this.data[START_SIZE + i],
8383
+ y: this.data[START_SIZE + count + i]
8384
+ });
8385
+ points = Object.freeze(list);
8386
+ POINTS_CACHE.set(this, points);
8387
+ }
8388
+ return points;
8389
+ }
8390
+ /**
8391
+ * The number of points in the curve.
8392
+ * @privateRemarks
8393
+ * Unlike `points.length`, it does not build the points list.
8394
+ */
8395
+ get pointCount() {
8396
+ return this.data.length - START_SIZE >> 1;
8363
8397
  }
8364
- static checkPoints(points) {
8365
- if (points.length < 2) throw new Error(`A custom curve needs at least 2 points, got ${points.length}.`);
8366
- for (const [i, { x, y }] of points.entries()) {
8398
+ /**
8399
+ * Reads a curve's points from its record in the CURV chunk, without making point objects.
8400
+ * @param data The chunk data, at the first point.
8401
+ * @param pointCount The number of points in the record.
8402
+ * @param name The name of the curve.
8403
+ * @returns The curve.
8404
+ * @throws Error if the points are invalid. The data's index is then left inside the record.
8405
+ * @internal
8406
+ */
8407
+ static read(data, pointCount, name) {
8408
+ const packed = new Uint16Array(START_SIZE + 2 * pointCount);
8409
+ for (let i = 0; i < pointCount; i++) {
8410
+ const x = readLittleEndianIndexed(data, 2);
8411
+ const y = readLittleEndianIndexed(data, 2);
8412
+ if (x > 16384 || y > 16384) throw new Error(`Custom curve point ${i} (${x}, ${y}) is out of range!`);
8413
+ packed[START_SIZE + i] = x;
8414
+ packed[START_SIZE + pointCount + i] = y;
8415
+ }
8416
+ CustomCurve.finishPacked(packed);
8417
+ return CustomCurve.fromPacked(packed, name);
8418
+ }
8419
+ /**
8420
+ * Copies a curve. The copy shares the packed points, since they are never changed in place.
8421
+ * @param curve The curve to copy.
8422
+ * @returns The copy, with the same name and points and no users.
8423
+ * @internal
8424
+ */
8425
+ static copyFrom(curve) {
8426
+ return CustomCurve.fromPacked(curve.data, curve.name);
8427
+ }
8428
+ static fromPacked(data, name) {
8429
+ packedForConstructor = data;
8430
+ return new CustomCurve([], name);
8431
+ }
8432
+ static pack(points) {
8433
+ if (points.length > 65535) throw new Error(`A custom curve can have at most 65535 points, got ${points.length}.`);
8434
+ const count = points.length;
8435
+ const data = new Uint16Array(START_SIZE + 2 * count);
8436
+ for (let i = 0; i < count; i++) {
8437
+ const { x, y } = points[i];
8367
8438
  if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || x > 16384 || y < 0 || y > 16384) throw new Error(`Custom curve point ${i} (${x}, ${y}) is out of range.`);
8368
- if (i > 0 && x < points[i - 1].x) throw new Error(`Custom curve point ${i} goes back in x (${points[i - 1].x} to ${x}).`);
8439
+ data[START_SIZE + i] = x;
8440
+ data[START_SIZE + count + i] = y;
8441
+ }
8442
+ CustomCurve.finishPacked(data);
8443
+ return data;
8444
+ }
8445
+ static finishPacked(data) {
8446
+ const count = data.length - START_SIZE >> 1;
8447
+ if (count < 2) throw new Error(`A custom curve needs at least 2 points, got ${count}.`);
8448
+ for (let i = 1; i < count; i++) {
8449
+ const x = data[START_SIZE + i];
8450
+ if (x < data[START_SIZE + i - 1]) throw new Error(`Custom curve point ${i} goes back in x (${data[START_SIZE + i - 1]} to ${x}).`);
8451
+ }
8452
+ let i = -1;
8453
+ for (let c = 0; c < START_SIZE; c++) {
8454
+ const x = c * 512;
8455
+ while (i < count - 1 && data[START_SIZE + i + 1] <= x) i++;
8456
+ data[c] = i + 1;
8369
8457
  }
8370
- return Object.freeze(points.map((p) => Object.freeze({
8371
- x: p.x,
8372
- y: p.y
8373
- })));
8374
8458
  }
8375
8459
  /**
8376
8460
  * Links the curve to an element that uses it.
@@ -8395,12 +8479,12 @@ var CustomCurve = class CustomCurve extends ModulatorCurve {
8395
8479
  }
8396
8480
  /**
8397
8481
  * Replaces the points of the curve. Every modulator using this curve follows the change.
8398
- * @param points The new points, ordered by `x`. At least two are needed.
8482
+ * @param points The new points, ordered by `x`. At least two and at most 65,535 are needed.
8399
8483
  * @throws Error if the points are invalid. The curve is left unchanged then.
8400
8484
  */
8401
8485
  setPoints(points) {
8402
- this.storedPoints = CustomCurve.checkPoints(points);
8403
- this.precompute();
8486
+ this.data = CustomCurve.pack(points);
8487
+ POINTS_CACHE.delete(this);
8404
8488
  }
8405
8489
  /**
8406
8490
  * Checks if two curves have the same points.
@@ -8409,8 +8493,12 @@ var CustomCurve = class CustomCurve extends ModulatorCurve {
8409
8493
  isIdentical(other) {
8410
8494
  if (other === this) return true;
8411
8495
  if (!(other instanceof CustomCurve)) return false;
8412
- if (other.points.length !== this.points.length) return false;
8413
- return this.points.every((p, i) => p.x === other.points[i].x && p.y === other.points[i].y);
8496
+ const a = this.data;
8497
+ const b = other.data;
8498
+ if (a === b) return true;
8499
+ if (a.length !== b.length) return false;
8500
+ for (let i = START_SIZE; i < a.length; i++) if (a[i] !== b[i]) return false;
8501
+ return true;
8414
8502
  }
8415
8503
  /**
8416
8504
  * Gets the curve's `y` for a source value.
@@ -8420,14 +8508,23 @@ var CustomCurve = class CustomCurve extends ModulatorCurve {
8420
8508
  * @internal
8421
8509
  */
8422
8510
  getY(x) {
8423
- const px = this.px;
8424
- const last = px.length - 1;
8425
- let i = this.start[x >> 7];
8426
- while (i < last && px[i + 1] <= x) i++;
8427
- if (i < 0) return this.py[0];
8428
- if (i === last) return this.py[last];
8429
- const ay = this.py[i];
8430
- return ay + (this.py[i + 1] - ay) * (x - px[i]) / (px[i + 1] - px[i]);
8511
+ const data = this.data;
8512
+ const count = data.length - START_SIZE >> 1;
8513
+ const last = count - 1;
8514
+ const ys = START_SIZE + count;
8515
+ const bucket = x >> 9;
8516
+ let i = data[bucket] - 1;
8517
+ let high = bucket < 32 ? data[bucket + 1] - 1 : last;
8518
+ while (i < high) {
8519
+ const middle = i + high + 1 >> 1;
8520
+ if (data[START_SIZE + middle] <= x) i = middle;
8521
+ else high = middle - 1;
8522
+ }
8523
+ if (i < 0) return data[ys];
8524
+ if (i === last) return data[ys + last];
8525
+ const ax = data[START_SIZE + i];
8526
+ const ay = data[ys + i];
8527
+ return ay + (data[ys + i + 1] - ay) * (x - ax) / (data[START_SIZE + i + 1] - ax);
8431
8528
  }
8432
8529
  /**
8433
8530
  * Gets the output of a source using this curve.
@@ -8439,33 +8536,29 @@ var CustomCurve = class CustomCurve extends ModulatorCurve {
8439
8536
  */
8440
8537
  getValue(raw, isBipolar, isNegative) {
8441
8538
  const x = isNegative ? 16384 - raw : raw;
8442
- const slot = GRID_SLOT[x];
8443
- if (slot >= 0) return isBipolar ? this.gridBipolar[slot] : this.gridUnipolar[slot];
8444
8539
  const y = this.getY(x);
8445
8540
  return Math.fround(isBipolar ? (y - 8192) / 8192 : y / 16384);
8446
8541
  }
8447
8542
  toString() {
8448
- return this.name || `Custom curve (${this.points.length} points)`;
8543
+ return this.name || `Custom curve (${this.pointCount} points)`;
8544
+ }
8545
+ /**
8546
+ * Writes the curve's record of the CURV chunk: the name, the point count and the points.
8547
+ * @param data The array to write to.
8548
+ * @internal
8549
+ */
8550
+ write(data) {
8551
+ const count = this.pointCount;
8552
+ writeBinaryStringIndexed(data, this.name, 40);
8553
+ writeWord(data, count);
8554
+ for (let i = 0; i < count; i++) {
8555
+ writeWord(data, this.data[START_SIZE + i]);
8556
+ writeWord(data, this.data[START_SIZE + count + i]);
8557
+ }
8449
8558
  }
8450
8559
  evaluate(value, isBipolar) {
8451
8560
  return this.getValue(Math.round(value * 16384), isBipolar, false);
8452
8561
  }
8453
- precompute() {
8454
- const points = this.storedPoints;
8455
- this.px = Int32Array.from(points, (p) => p.x);
8456
- this.py = Float64Array.from(points, (p) => p.y);
8457
- let i = -1;
8458
- for (let c = 0; c <= 128; c++) {
8459
- const x = c * 128;
8460
- while (i < points.length - 1 && points[i + 1].x <= x) i++;
8461
- this.start[c] = i;
8462
- }
8463
- for (const [slot, x] of GRID_POSITIONS.entries()) {
8464
- const y = this.getY(x);
8465
- this.gridUnipolar[slot] = y / 16384;
8466
- this.gridBipolar[slot] = (y - 8192) / 8192;
8467
- }
8468
- }
8469
8562
  };
8470
8563
  // src/soundbank/basic_soundbank/modulator_source.ts
8471
8564
  /**
@@ -8581,7 +8674,7 @@ var ModulatorSource = class ModulatorSource {
8581
8674
  */
8582
8675
  static copyFrom(source) {
8583
8676
  const curve = source.curve;
8584
- return new ModulatorSource(source.index, curve instanceof CustomCurve && Object.isFrozen(curve) ? new CustomCurve(curve.points, curve.name) : curve, source.isCC, source.isBipolar, source.isNegative);
8677
+ return new ModulatorSource(source.index, curve instanceof CustomCurve && Object.isFrozen(curve) ? CustomCurve.copyFrom(curve) : curve, source.isCC, source.isBipolar, source.isNegative);
8585
8678
  }
8586
8679
  toString() {
8587
8680
  return `${this.sourceName} ${this.curve.toString()} ${this.isBipolar ? "bipolar" : "unipolar"} ${this.isNegative ? "negative" : "positive"}`;
@@ -8966,7 +9059,7 @@ function copyWithOwnCurves(modulators) {
8966
9059
  if (!(curve instanceof CustomCurve)) return ModulatorSource.copyFrom(source);
8967
9060
  let own = curves.get(curve);
8968
9061
  if (!own) {
8969
- own = new CustomCurve(curve.points, curve.name);
9062
+ own = CustomCurve.copyFrom(curve);
8970
9063
  curves.set(curve, own);
8971
9064
  }
8972
9065
  return new ModulatorSource(source.index, own, source.isCC, source.isBipolar, source.isNegative);
@@ -10458,10 +10551,7 @@ function writeSF(bank, format, software, writeDefaultModulators, writeExtendedLi
10458
10551
  let curveIndex;
10459
10552
  if (isSFe) {
10460
10553
  const indexes = /* @__PURE__ */ new Map();
10461
- for (const [i, curve] of curves.entries()) {
10462
- if (curve.points.length > 65535) throw new Error(`The custom curve "${curve.toString()}" has too many points: ${curve.points.length}, the maximum is 65535.`);
10463
- indexes.set(curve, i);
10464
- }
10554
+ for (const [i, curve] of curves.entries()) indexes.set(curve, i);
10465
10555
  curveIndex = (curve) => {
10466
10556
  const index = indexes.get(curve);
10467
10557
  if (index === void 0) throw new Error(`The custom curve "${curve.toString()}" is used by a modulator but is not in the bank's customCurves.`);
@@ -10484,16 +10574,9 @@ function writeSF(bank, format, software, writeDefaultModulators, writeExtendedLi
10484
10574
  }
10485
10575
  if (curves.length > 0) {
10486
10576
  SpessaLog.info(`%cWriting %c${curves.length}%c custom curves...`, ConsoleColors.info, ConsoleColors.recognized, ConsoleColors.info);
10487
- const curvData = new IndexedByteArray(4 + curves.reduce((sum, c) => sum + 42 + c.points.length * 4, 0));
10577
+ const curvData = new IndexedByteArray(4 + curves.reduce((sum, c) => sum + 42 + c.pointCount * 4, 0));
10488
10578
  writeDword(curvData, curves.length);
10489
- for (const c of curves) {
10490
- writeBinaryStringIndexed(curvData, c.name, 40);
10491
- writeWord(curvData, c.points.length);
10492
- for (const p of c.points) {
10493
- writeWord(curvData, p.x);
10494
- writeWord(curvData, p.y);
10495
- }
10496
- }
10579
+ for (const c of curves) c.write(curvData);
10497
10580
  infoArrays.push(...RIFFChunk.getParts("CURV", [curvData], rf64));
10498
10581
  }
10499
10582
  SpessaLog.groupEnd();
@@ -10938,7 +11021,7 @@ var DownloadableSoundsSample = class DownloadableSoundsSample extends DLSVerifie
10938
11021
  const bytesPerSample = readLittleEndianIndexed(fmtChunk.data, 2) / 8;
10939
11022
  const dataChunk = chunks.find((c) => c.header === "data");
10940
11023
  if (!dataChunk) throw new Error("No data chunk in the WAVE chunk!");
10941
- const sample = new DownloadableSoundsSample(wFormatTag, bytesPerSample, sampleRate, dataChunk);
11024
+ const sample = new DownloadableSoundsSample(wFormatTag, bytesPerSample, sampleRate, new RIFFChunk("data", dataChunk.size, dataChunk.data.slice()));
10942
11025
  const waveInfo = RIFFChunk.findListType(chunks, "INFO");
10943
11026
  if (waveInfo) {
10944
11027
  let infoChunk = RIFFChunk.read(waveInfo.data);
@@ -12373,6 +12456,12 @@ var SoundBankCloner = class {
12373
12456
  curveClones = /* @__PURE__ */ new Map();
12374
12457
  instrumentClones = /* @__PURE__ */ new Map();
12375
12458
  /**
12459
+ * The names in the bank and the ones this session gave out, by element kind, built on first use.
12460
+ * A name changed or added in the bank from outside between two clone calls of one session is not seen,
12461
+ * The worst case is a repeated name, which banks allow
12462
+ */
12463
+ takenNames = /* @__PURE__ */ new Map();
12464
+ /**
12376
12465
  * Creates a new clone session.
12377
12466
  * @param bank The bank to clone elements into.
12378
12467
  * @param options The options for this session.
@@ -12433,11 +12522,11 @@ var SoundBankCloner = class {
12433
12522
  * @returns The clone, or the existing preset with the same name if it is reused.
12434
12523
  */
12435
12524
  clonePreset(preset) {
12436
- const all = [...this.bank.presets, ...this.created.presets];
12437
- const existing = this.findReused(preset, all, this.ownReuse);
12525
+ const lists = [this.bank.presets, this.created.presets];
12526
+ const existing = this.findReused(preset, lists, this.ownReuse);
12438
12527
  if (existing) return existing;
12439
12528
  const newPreset = new BasicPreset(this.bank);
12440
- newPreset.name = this.getFreeName(preset.name, all);
12529
+ newPreset.name = this.getFreeName(preset.name, "presets", lists);
12441
12530
  newPreset.bankMSB = preset.bankMSB;
12442
12531
  newPreset.bankLSB = preset.bankLSB;
12443
12532
  newPreset.isGMGSDrum = preset.isGMGSDrum;
@@ -12459,11 +12548,11 @@ var SoundBankCloner = class {
12459
12548
  copyInstrument(instrument, reuse) {
12460
12549
  const cloned = this.instrumentClones.get(instrument);
12461
12550
  if (cloned) return cloned;
12462
- const all = [...this.bank.instruments, ...this.created.instruments];
12463
- const existing = this.findReused(instrument, all, reuse);
12551
+ const lists = [this.bank.instruments, this.created.instruments];
12552
+ const existing = this.findReused(instrument, lists, reuse);
12464
12553
  if (existing) return existing;
12465
12554
  const newInstrument = new BasicInstrument();
12466
- newInstrument.name = this.getFreeName(instrument.name, all);
12555
+ newInstrument.name = this.getFreeName(instrument.name, "instruments", lists);
12467
12556
  newInstrument.globalZone.copyFrom(instrument.globalZone);
12468
12557
  this.cloneCurvesOf(newInstrument.globalZone.modulators);
12469
12558
  for (const zone of instrument.zones) {
@@ -12479,10 +12568,10 @@ var SoundBankCloner = class {
12479
12568
  copySample(sample, reuse) {
12480
12569
  const cloned = this.sampleClones.get(sample);
12481
12570
  if (cloned) return cloned;
12482
- const all = [...this.bank.samples, ...this.created.samples];
12483
- const existing = this.findReused(sample, all, reuse);
12571
+ const lists = [this.bank.samples, this.created.samples];
12572
+ const existing = this.findReused(sample, lists, reuse);
12484
12573
  if (existing) return existing;
12485
- const newSample = new BasicSample(this.getFreeName(sample.name, all), sample.sampleRate, sample.originalKey, sample.pitchCorrection, sample.sampleType, sample.loopStart, sample.loopEnd);
12574
+ const newSample = new BasicSample(this.getFreeName(sample.name, "samples", lists), sample.sampleRate, sample.originalKey, sample.pitchCorrection, sample.sampleType, sample.loopStart, sample.loopEnd);
12486
12575
  if (sample.hasData) newSample.setStoredData(sample.getStoredData());
12487
12576
  else {
12488
12577
  const form = sample.storedForm;
@@ -12502,32 +12591,52 @@ var SoundBankCloner = class {
12502
12591
  copyCurve(curve, reuse) {
12503
12592
  const cloned = this.curveClones.get(curve);
12504
12593
  if (cloned) return cloned;
12505
- const all = [...this.bank.customCurves, ...this.created.customCurves];
12506
- const existing = reuse === "name" ? all.find((c) => c.name === curve.name && c.isIdentical(curve)) : this.findReused(curve, all, reuse);
12594
+ const lists = [this.bank.customCurves, this.created.customCurves];
12595
+ let existing;
12596
+ if (reuse === "name") for (const list of lists) {
12597
+ existing = list.find((c) => c.name === curve.name && c.isIdentical(curve));
12598
+ if (existing) break;
12599
+ }
12600
+ else existing = this.findReused(curve, lists, reuse);
12507
12601
  if (existing) return existing;
12508
- const newCurve = new CustomCurve(curve.points, curve.name);
12602
+ const newCurve = CustomCurve.copyFrom(curve);
12509
12603
  this.curveClones.set(curve, newCurve);
12510
12604
  this.created.customCurves.push(newCurve);
12511
- if (this.options.addToBank) this.bank.addCustomCurves(newCurve);
12605
+ if (this.options.addToBank) this.bank.customCurves.push(newCurve);
12512
12606
  return newCurve;
12513
12607
  }
12514
12608
  /**
12515
12609
  * Finds the element to use instead of a copy, if the options allow one.
12610
+ * The lists are searched in order, without joining them, as this runs for every cloned element.
12516
12611
  */
12517
- findReused(element, elements, reuse) {
12612
+ findReused(element, lists, reuse) {
12518
12613
  switch (reuse) {
12519
12614
  case "none": return;
12520
- case "identity": return elements.includes(element) ? element : void 0;
12521
- case "name": return elements.find((e) => e.name === element.name);
12615
+ case "identity": return lists.some((list) => list.includes(element)) ? element : void 0;
12616
+ case "name":
12617
+ for (const list of lists) {
12618
+ const found = list.find((e) => e.name === element.name);
12619
+ if (found) return found;
12620
+ }
12621
+ return;
12522
12622
  }
12523
12623
  }
12524
- getFreeName(name, elements) {
12525
- const taken = new Set(elements.map((e) => e.name));
12526
- if (!taken.has(name)) return name;
12527
- const base = name.slice(0, MAX_BASE_NAME_LENGTH);
12528
- let count = 1;
12529
- while (taken.has(`${base}-${count}`)) count++;
12530
- return `${base}-${count}`;
12624
+ getFreeName(name, kind, lists) {
12625
+ let taken = this.takenNames.get(kind);
12626
+ if (!taken) {
12627
+ taken = /* @__PURE__ */ new Set();
12628
+ for (const list of lists) for (const e of list) taken.add(e.name);
12629
+ this.takenNames.set(kind, taken);
12630
+ }
12631
+ let free = name;
12632
+ if (taken.has(name)) {
12633
+ const base = name.slice(0, MAX_BASE_NAME_LENGTH);
12634
+ let count = 1;
12635
+ while (taken.has(`${base}-${count}`)) count++;
12636
+ free = `${base}-${count}`;
12637
+ }
12638
+ taken.add(free);
12639
+ return free;
12531
12640
  }
12532
12641
  };
12533
12642
  // src/soundbank/basic_soundbank/basic_soundbank.ts
@@ -12761,10 +12870,10 @@ var BasicSoundBank = class BasicSoundBank {
12761
12870
  * and adds the custom curves they use. The curves that only the old list used are removed.
12762
12871
  */
12763
12872
  resetDefaultModulators() {
12764
- const oldCurves = new Array();
12873
+ const oldCurves = /* @__PURE__ */ new Set();
12765
12874
  collectCurves(this.defaultModulators, oldCurves);
12766
12875
  this.defaultModulators = [];
12767
- this.customCurves = this.customCurves.filter((c) => !oldCurves.includes(c) || c.useCount > 0);
12876
+ this.customCurves = this.customCurves.filter((c) => !oldCurves.has(c) || c.useCount > 0);
12768
12877
  const defaults = copyDefaultModulators();
12769
12878
  this.addCustomCurves(...defaults.curves);
12770
12879
  this.defaultModulators = defaults.modulators;
@@ -12781,7 +12890,7 @@ var BasicSoundBank = class BasicSoundBank {
12781
12890
  const sampleList = [];
12782
12891
  for (const instrument of instrumentList) for (const zone of instrument.zones) if (zone.sample && !sampleList.includes(zone.sample)) sampleList.push(zone.sample);
12783
12892
  this.addElements(this.samples, sampleList);
12784
- const curveList = new Array();
12893
+ const curveList = /* @__PURE__ */ new Set();
12785
12894
  for (const element of [...presets, ...instrumentList]) {
12786
12895
  collectCurves(element.globalZone.modulators, curveList);
12787
12896
  for (const zone of element.zones) collectCurves(zone.modulators, curveList);
@@ -12793,7 +12902,11 @@ var BasicSoundBank = class BasicSoundBank {
12793
12902
  * @param curves The curves to add.
12794
12903
  */
12795
12904
  addCustomCurves(...curves) {
12796
- for (const curve of curves) if (!this.customCurves.includes(curve)) this.customCurves.push(curve);
12905
+ const present = new Set(this.customCurves);
12906
+ for (const curve of curves) if (!present.has(curve)) {
12907
+ present.add(curve);
12908
+ this.customCurves.push(curve);
12909
+ }
12797
12910
  }
12798
12911
  /**
12799
12912
  * Deletes a given custom curve from the sound bank.
@@ -13079,11 +13192,10 @@ var BasicSoundBank = class BasicSoundBank {
13079
13192
  if (deletable) s.unlinkSample();
13080
13193
  return !deletable;
13081
13194
  });
13082
- const used = new Array();
13195
+ const used = /* @__PURE__ */ new Set();
13083
13196
  collectCurves(this.defaultModulators, used);
13084
13197
  for (const element of [...this.presets, ...this.instruments]) for (const zone of [element.globalZone, ...element.zones]) collectCurves(zone.modulators, used);
13085
- const usedSet = new Set(used);
13086
- this.customCurves = this.customCurves.filter((c) => usedSet.has(c));
13198
+ this.customCurves = this.customCurves.filter((c) => used.has(c));
13087
13199
  }
13088
13200
  /**
13089
13201
  * Deletes a given instrument from the sound bank.
@@ -13198,8 +13310,8 @@ var BasicSoundBank = class BasicSoundBank {
13198
13310
  } else SpessaLog.info(`%c${info}: %c${value.toLocaleString()}`, ConsoleColors.info, ConsoleColors.recognized);
13199
13311
  }
13200
13312
  };
13201
- function collectCurves(modulators, list) {
13202
- for (const m of modulators) for (const curve of [m.primarySource.curve, m.secondarySource.curve]) if (curve instanceof CustomCurve && !list.includes(curve)) list.push(curve);
13313
+ function collectCurves(modulators, set) {
13314
+ for (const m of modulators) for (const curve of [m.primarySource.curve, m.secondarySource.curve]) if (curve instanceof CustomCurve) set.add(curve);
13203
13315
  }
13204
13316
  // src/midi/read/tracker/types.ts
13205
13317
  /**
@@ -64288,14 +64400,16 @@ function readModulators(modulatorChunk, allowSFe, curves = [], extendedChunk) {
64288
64400
  }
64289
64401
  mods.pop();
64290
64402
  flags.pop();
64291
- const flaggedCount = flags.filter(Boolean).length;
64403
+ let flaggedCount = 0;
64404
+ for (const flag of flags) if (flag) flaggedCount++;
64292
64405
  const ext = allowSFe && extendedChunk && extendedChunk.data.length % 16 === 0 && extendedChunk.data.length / 16 - 1 === flaggedCount ? extendedChunk.data : void 0;
64293
64406
  let record = 0;
64294
64407
  const resolveCurve = (source, index) => {
64295
64408
  if (source.curveType === ModulatorCurveTypes.custom && allowSFe) return curves[index];
64296
64409
  return source.curveType <= ModulatorCurveTypes.switch ? source.curve : void 0;
64297
64410
  };
64298
- for (const [m, mod] of mods.entries()) {
64411
+ for (let m = 0; m < mods.length; m++) {
64412
+ const mod = mods[m];
64299
64413
  let sourceCurve = 0;
64300
64414
  let amountCurve = 0;
64301
64415
  let understood = true;
@@ -64335,21 +64449,14 @@ function readCurves(curveChunk) {
64335
64449
  const name = readBinaryStringIndexed(data, 40);
64336
64450
  const pointCount = readLittleEndianIndexed(data, 2);
64337
64451
  if (data.currentIndex + pointCount * 4 > data.length) throw new Error(`The CURV chunk is truncated at curve ${c}.`);
64338
- const points = new Array(pointCount);
64339
- for (let i = 0; i < pointCount; i++) {
64340
- const x = readLittleEndianIndexed(data, 2);
64341
- const y = readLittleEndianIndexed(data, 2);
64342
- points[i] = {
64343
- x,
64344
- y
64345
- };
64346
- }
64452
+ const recordEnd = data.currentIndex + pointCount * 4;
64347
64453
  try {
64348
- curves.push(new CustomCurve(points, name));
64454
+ curves.push(CustomCurve.read(data, pointCount, name));
64349
64455
  } catch (error) {
64350
64456
  SpessaLog.warn(`Custom curve ${c} "${name}" is invalid, ignoring: ${error.message}`);
64351
64457
  curves.push(void 0);
64352
64458
  }
64459
+ data.currentIndex = recordEnd;
64353
64460
  }
64354
64461
  if (data.currentIndex !== data.length) throw new Error(`The CURV chunk has ${data.length - data.currentIndex} bytes after its last curve.`);
64355
64462
  return curves;