spessasynth_core 4.4.9 → 4.4.10

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
@@ -1434,7 +1434,7 @@ function tryYear(dateString) {
1434
1434
  }
1435
1435
  function parseDateString(dateString) {
1436
1436
  dateString = dateString.trim();
1437
- if (dateString.length === 0) return /* @__PURE__ */ new Date();
1437
+ if (dateString.length === 0) return;
1438
1438
  const filtered = dateString.replaceAll(/\b(\d+)(st|nd|rd|th)\b/g, "$1").replace(/\s+at\s+/i, " ");
1439
1439
  const date = new Date(filtered);
1440
1440
  if (Number.isNaN(date.getTime())) {
@@ -1446,8 +1446,8 @@ function parseDateString(dateString) {
1446
1446
  if (awe) return awe;
1447
1447
  const year = tryYear(dateString);
1448
1448
  if (year) return year;
1449
- SpessaLog.warn(`Invalid date: "${dateString}". Replacing with the current date!`);
1450
- return /* @__PURE__ */ new Date();
1449
+ SpessaLog.warn(`Invalid date: "${dateString}".`);
1450
+ return;
1451
1451
  }
1452
1452
  return date;
1453
1453
  }
@@ -6373,9 +6373,12 @@ function parseRMIDIInternal(outputMIDI, binaryData, fileName) {
6373
6373
  if (type === "sfbk" || type === "sfpk" || type === "dls ") {
6374
6374
  SpessaLog.info("%cFound embedded soundbank!", ConsoleColors.recognized);
6375
6375
  outputMIDI.embeddedSoundBank = binaryData.slice(startIndex, startIndex + currentChunk.headerSize + currentChunk.size).buffer;
6376
- } else SpessaLog.warn(`Unknown RIFF chunk: "${type}"`);
6377
- if (type === "dls ") outputMIDI.isDLSRMIDI = true;
6378
- else isSF2RMIDI = true;
6376
+ if (type === "dls ") outputMIDI.isDLSRMIDI = true;
6377
+ else isSF2RMIDI = true;
6378
+ } else {
6379
+ SpessaLog.warn(`Unknown RIFF chunk: "${type}"`);
6380
+ outputMIDI.rmidiExtraChunks.file.push(RIFFChunk.write(currentChunk.header, currentChunk.data));
6381
+ }
6379
6382
  } else if (currentChunk.header === "LIST") {
6380
6383
  if (readBinaryStringIndexed(currentChunk.data, 4) === "INFO") {
6381
6384
  SpessaLog.info("%cFound RMIDI INFO chunk!", ConsoleColors.recognized);
@@ -6383,17 +6386,24 @@ function parseRMIDIInternal(outputMIDI, binaryData, fileName) {
6383
6386
  const infoChunk = RIFFChunk.read(currentChunk.data);
6384
6387
  const headerTyped = infoChunk.header;
6385
6388
  const infoData = infoChunk.data;
6389
+ if (infoChunk.size === 0) {
6390
+ SpessaLog.warn(`Discarding empty RMIDI Info: ${headerTyped}`);
6391
+ continue;
6392
+ }
6386
6393
  switch (headerTyped) {
6387
6394
  default:
6388
6395
  SpessaLog.warn(`Unknown RMIDI Info: ${headerTyped}`);
6396
+ outputMIDI.rmidiExtraChunks.info.push(RIFFChunk.write(infoChunk.header, infoData));
6389
6397
  break;
6390
6398
  case "INAM":
6391
6399
  outputMIDI.rmidiInfo.name = infoData;
6392
6400
  break;
6393
6401
  case "IALB":
6394
- case "IPRD":
6395
6402
  outputMIDI.rmidiInfo.album = infoData;
6396
6403
  break;
6404
+ case "IPRD":
6405
+ outputMIDI.rmidiInfo.album ??= infoData;
6406
+ break;
6397
6407
  case "ICRT":
6398
6408
  case "ICRD":
6399
6409
  outputMIDI.rmidiInfo.creationDate = infoData;
@@ -6428,11 +6438,19 @@ function parseRMIDIInternal(outputMIDI, binaryData, fileName) {
6428
6438
  case "MENC":
6429
6439
  outputMIDI.rmidiInfo.midiEncoding = infoData;
6430
6440
  break;
6431
- case "DBNK": dbnk = readLittleEndian(infoData, 2);
6441
+ case "DBNK": {
6442
+ const offset = infoData.length === 2 ? readLittleEndian(infoData, 2) : void 0;
6443
+ if (offset === void 0 || offset > 127) {
6444
+ SpessaLog.warn(`Invalid DBNK chunk (${offset ?? `${infoData.length} bytes`}), ignoring it.`);
6445
+ break;
6446
+ }
6447
+ dbnk = offset;
6448
+ break;
6449
+ }
6432
6450
  }
6433
6451
  }
6434
- }
6435
- }
6452
+ } else outputMIDI.rmidiExtraChunks.file.push(RIFFChunk.write(currentChunk.header, currentChunk.data));
6453
+ } else outputMIDI.rmidiExtraChunks.file.push(RIFFChunk.write(currentChunk.header, currentChunk.data));
6436
6454
  }
6437
6455
  if (outputMIDI.embeddedSoundBank === void 0) outputMIDI.bankOffset = 0;
6438
6456
  else if (dbnk !== void 0) outputMIDI.bankOffset = dbnk;
@@ -6692,12 +6710,44 @@ function loadXMF(midi, binaryData, fileName) {
6692
6710
  }
6693
6711
  // src/midi/read/tracker/tracker_channel.ts
6694
6712
  /**
6713
+ * @license
6714
+ * The random waveform table in this file is taken from the sound library of OpenMPT (https://openmpt.org/).
6715
+ * OpenMPT is distributed under the BSD license below.
6716
+ *
6717
+ * Copyright (c) 2004-2026, OpenMPT Project Developers and Contributors
6718
+ * Copyright (c) 1997-2003, Olivier Lapicque
6719
+ * All rights reserved.
6720
+ *
6721
+ * Redistribution and use in source and binary forms, with or without
6722
+ * modification, are permitted provided that the following conditions are met:
6723
+ * * Redistributions of source code must retain the above copyright
6724
+ * notice, this list of conditions and the following disclaimer.
6725
+ * * Redistributions in binary form must reproduce the above copyright
6726
+ * notice, this list of conditions and the following disclaimer in the
6727
+ * documentation and/or other materials provided with the distribution.
6728
+ * * Neither the name of the OpenMPT project nor the
6729
+ * names of its contributors may be used to endorse or promote products
6730
+ * derived from this software without specific prior written permission.
6731
+ *
6732
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
6733
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
6734
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
6735
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
6736
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
6737
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
6738
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
6739
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
6740
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6741
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6742
+ */
6743
+ /**
6695
6744
  * The 64-step sine table shared by the vibrato and tremolo effects.
6696
6745
  */
6697
- const SINE_TABLE = /* @__PURE__ */ new Int8Array(64);
6746
+ const SINE_TABLE$1 = /* @__PURE__ */ new Int8Array(64);
6698
6747
  /**
6699
6748
  * The random waveform table,
6700
6749
  * Fixed so conversions are deterministic, and we can test them.
6750
+ * This is the random table of OpenMPT (ModRandomTable).
6701
6751
  */
6702
6752
  const RANDOM_TABLE = new Int8Array([
6703
6753
  98,
@@ -6765,7 +6815,7 @@ const RANDOM_TABLE = new Int8Array([
6765
6815
  -54,
6766
6816
  -95
6767
6817
  ]);
6768
- for (let i = 0; i < 64; i++) SINE_TABLE[i] = Math.round(127 * Math.sin(i * Math.PI / 32));
6818
+ for (let i = 0; i < 64; i++) SINE_TABLE$1[i] = Math.round(127 * Math.sin(i * Math.PI / 32));
6769
6819
  /**
6770
6820
  * The playback state of a single tracker channel.
6771
6821
  * Contains the effect primitives that are shared between the module formats.
@@ -6787,6 +6837,15 @@ var TrackerChannel = class TrackerChannel {
6787
6837
  */
6788
6838
  sampleIndex = -1;
6789
6839
  /**
6840
+ * The sound bank preset that plays the sample, usually the sample index.
6841
+ * Other values select a variant of the sample, see {@link TrackerSampleBank}.
6842
+ */
6843
+ preset = -1;
6844
+ /**
6845
+ * The playback position in the preset's sample, Infinity once a sample without a loop has ended.
6846
+ */
6847
+ samplePosition = 0;
6848
+ /**
6790
6849
  * The fine-tuning used for the next notes, initialized from the sample.
6791
6850
  * Its unit is specific to the module format, see {@link TrackerSample.finetune}.
6792
6851
  */
@@ -6818,6 +6877,11 @@ var TrackerChannel = class TrackerChannel {
6818
6877
  */
6819
6878
  volumeDelta = 0;
6820
6879
  /**
6880
+ * An additional volume multiplier (0-1) for the format-specific volumes,
6881
+ * such as the channel, sample and instrument global volumes.
6882
+ */
6883
+ volumeScale = 1;
6884
+ /**
6821
6885
  * Set to true while tremor silences the channel.
6822
6886
  */
6823
6887
  tremorMuted = false;
@@ -6826,6 +6890,18 @@ var TrackerChannel = class TrackerChannel {
6826
6890
  * The channel panning (0-255).
6827
6891
  */
6828
6892
  panning = 128;
6893
+ /**
6894
+ * The final panning (0-256) computed by the format, -1 to compute it from the panning and its envelope.
6895
+ */
6896
+ outputPanning = -1;
6897
+ /**
6898
+ * The resonant filter cutoff in absolute cents, 13,500 or above leaves the filter open.
6899
+ */
6900
+ filterCutoff = 13500;
6901
+ /**
6902
+ * The resonant filter resonance in centibels.
6903
+ */
6904
+ filterResonance = 0;
6829
6905
  keyOn = false;
6830
6906
  volumeEnvelopeTick = 0;
6831
6907
  panningEnvelopeTick = 0;
@@ -6888,6 +6964,18 @@ var TrackerChannel = class TrackerChannel {
6888
6964
  noteCutTick = -1;
6889
6965
  patternLoopRow = 0;
6890
6966
  patternLoopCount = 0;
6967
+ /**
6968
+ * The MIDI track (one MIDI channel) this channel writes to.
6969
+ */
6970
+ output;
6971
+ /**
6972
+ * True for the background voices that keep playing after a new note (Impulse Tracker new note actions).
6973
+ */
6974
+ background = false;
6975
+ /**
6976
+ * The volume of the last written tick (0-1), used to pick the voice to stop when there are too many.
6977
+ */
6978
+ outputLevel = 0;
6891
6979
  constructor(index, panning) {
6892
6980
  this.index = index;
6893
6981
  this.panning = panning;
@@ -6901,13 +6989,19 @@ var TrackerChannel = class TrackerChannel {
6901
6989
  static getWaveform(waveform, position) {
6902
6990
  position &= 63;
6903
6991
  switch (waveform & 3) {
6904
- default: return SINE_TABLE[position];
6992
+ default: return SINE_TABLE$1[position];
6905
6993
  case 1: return (position < 32 ? 0 : 255) - position * 4;
6906
6994
  case 2: return position < 32 ? 127 : -127;
6907
6995
  case 3: return RANDOM_TABLE[position];
6908
6996
  }
6909
6997
  }
6910
6998
  /**
6999
+ * Creates a copy of this channel, keeping its class.
7000
+ */
7001
+ clone() {
7002
+ return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
7003
+ }
7004
+ /**
6911
7005
  * Slides the channel volume, clamping it to 0-64.
6912
7006
  * @param amount The amount to add.
6913
7007
  */
@@ -7046,6 +7140,22 @@ const OFFSET_FINE_CC = MIDIControllers.undefinedCC21;
7046
7140
  */
7047
7141
  const OFFSET_COARSE_CC = MIDIControllers.undefinedCC20;
7048
7142
  /**
7143
+ * The LSB of {@link OFFSET_FINE_CC}, sets the sample offset in units of 2 sample points.
7144
+ */
7145
+ const OFFSET_FINEST_CC = MIDIControllers.undefinedCC21LSB;
7146
+ /**
7147
+ * The 14-bit controller (with its LSB) that lowers the filter cutoff from fully open, see {@link FILTER_CUTOFF_RANGE}.
7148
+ */
7149
+ const FILTER_CUTOFF_CC = MIDIControllers.undefinedCC22;
7150
+ /**
7151
+ * The 14-bit controller (with its LSB) that sets the filter resonance, see {@link FILTER_RESONANCE_RANGE}.
7152
+ */
7153
+ const FILTER_RESONANCE_CC = MIDIControllers.undefinedCC23;
7154
+ /**
7155
+ * The full scale of {@link FILTER_CUTOFF_CC} in cents, from 13,500 (open) down to 4,500.
7156
+ */
7157
+ const FILTER_CUTOFF_RANGE = 9e3;
7158
+ /**
7049
7159
  * Pitch changes smaller than this (in semitones) are floating point noise and are not written.
7050
7160
  */
7051
7161
  const PITCH_EPSILON = 1e-9;
@@ -7113,13 +7223,25 @@ var TrackerMIDITrack = class {
7113
7223
  * @param ticks The MIDI tick time.
7114
7224
  * @param controller The controller number.
7115
7225
  * @param value The new value (0-127).
7226
+ * @param skipDefault If a zero value is not written while the controller is still at its reset value.
7116
7227
  */
7117
- controllerChange(ticks, controller, value) {
7118
- if (this.controllers[controller] === value) return;
7228
+ controllerChange(ticks, controller, value, skipDefault = false) {
7229
+ if (this.controllers[controller] === value || skipDefault && value === 0 && this.controllers[controller] === -1) return;
7119
7230
  this.controllers[controller] = value;
7120
7231
  this.addEvent(ticks, MIDIMessageTypes.controllerChange, controller, value);
7121
7232
  }
7122
7233
  /**
7234
+ * Changes a 14-bit controller (0-31) and its LSB if the value differs from the last one.
7235
+ * @param ticks The MIDI tick time.
7236
+ * @param controller The controller number.
7237
+ * @param value The new value (0-16,383).
7238
+ * @param skipDefault If a zero value is not written while the controller is still at its reset value.
7239
+ */
7240
+ controllerChange14(ticks, controller, value, skipDefault = false) {
7241
+ this.controllerChange(ticks, controller, value >> 7, skipDefault);
7242
+ this.controllerChange(ticks, controller + 32, value & 127, skipDefault);
7243
+ }
7244
+ /**
7123
7245
  * Sets the pitch offset from the playing key.
7124
7246
  * @param ticks The MIDI tick time.
7125
7247
  * @param semitones The offset in semitones.
@@ -7167,7 +7289,7 @@ var TrackerMIDITrack = class {
7167
7289
  this.createEvent(cc, MIDIControllers.registeredParameterLSB, 127)
7168
7290
  ];
7169
7291
  if (this.channel === 9) setup.push(...MIDIUtils.setChannelMIDIParameter(0, this.channel, "gs", "drumMap", 0));
7170
- track.pushEvents(...setup, ...this.events);
7292
+ track.events = setup.concat(this.events);
7171
7293
  track.channels.add(this.channel);
7172
7294
  return track;
7173
7295
  }
@@ -8222,10 +8344,29 @@ const defaultSoundFont2Modulators = [
8222
8344
  new DecodedModulator(219, 0, GeneratorTypes.reverbEffectsSend, 200, 0),
8223
8345
  new DecodedModulator(221, 0, GeneratorTypes.chorusEffectsSend, 200, 0)
8224
8346
  ];
8347
+ /**
8348
+ * One term of an envelope time response: a bipolar CC source gated to one half of the CC.
8349
+ * @param cc the controller
8350
+ * @param curve the curve of the bipolar source
8351
+ * @param destination the envelope generator
8352
+ * @param amount the amount in timecents
8353
+ * @param below true for the half under 64, false for the half over it
8354
+ */
8355
+ function envelopeCC(cc, curve, destination, amount, below) {
8356
+ return new DecodedModulator(getModSourceEnum(curve, true, false, true, cc), getModSourceEnum(ModulatorCurveTypes.switch, false, below, true, cc), destination, amount, 0);
8357
+ }
8225
8358
  const defaultSpessaSynthModulators = [
8226
- new DecodedModulator(getModSourceEnum(ModulatorCurveTypes.convex, true, false, true, MIDIControllers.attackTime), 0, GeneratorTypes.attackVolEnv, 6e3, 0),
8227
- new DecodedModulator(getModSourceEnum(ModulatorCurveTypes.linear, true, false, true, MIDIControllers.releaseTime), 0, GeneratorTypes.releaseVolEnv, 3600, 0),
8228
- new DecodedModulator(getModSourceEnum(ModulatorCurveTypes.linear, true, false, true, MIDIControllers.decayTime), 0, GeneratorTypes.decayVolEnv, 3600, 0),
8359
+ envelopeCC(MIDIControllers.attackTime, ModulatorCurveTypes.linear, GeneratorTypes.attackVolEnv, 9600, true),
8360
+ envelopeCC(MIDIControllers.attackTime, ModulatorCurveTypes.linear, GeneratorTypes.attackVolEnv, 9657, false),
8361
+ envelopeCC(MIDIControllers.attackTime, ModulatorCurveTypes.convex, GeneratorTypes.attackVolEnv, -1445, false),
8362
+ envelopeCC(MIDIControllers.decayTime, ModulatorCurveTypes.linear, GeneratorTypes.decayVolEnv, 9779, true),
8363
+ envelopeCC(MIDIControllers.decayTime, ModulatorCurveTypes.linear, GeneratorTypes.decayVolEnv, -2997, false),
8364
+ envelopeCC(MIDIControllers.decayTime, ModulatorCurveTypes.concave, GeneratorTypes.releaseVolEnv, 8035, false),
8365
+ envelopeCC(MIDIControllers.decayTime, ModulatorCurveTypes.convex, GeneratorTypes.decayVolEnv, 435, false),
8366
+ envelopeCC(MIDIControllers.releaseTime, ModulatorCurveTypes.linear, GeneratorTypes.releaseVolEnv, 9779, true),
8367
+ envelopeCC(MIDIControllers.releaseTime, ModulatorCurveTypes.linear, GeneratorTypes.releaseVolEnv, -2997, false),
8368
+ envelopeCC(MIDIControllers.releaseTime, ModulatorCurveTypes.concave, GeneratorTypes.releaseVolEnv, 8035, false),
8369
+ envelopeCC(MIDIControllers.releaseTime, ModulatorCurveTypes.convex, GeneratorTypes.releaseVolEnv, 435, false),
8229
8370
  new DecodedModulator(getModSourceEnum(ModulatorCurveTypes.linear, true, false, true, MIDIControllers.brightness), 0, GeneratorTypes.initialFilterFc, 9600, 0),
8230
8371
  new DecodedModulator(DEFAULT_RESONANT_MOD_SOURCE, 0, GeneratorTypes.initialFilterQ, 250, 0),
8231
8372
  new DecodedModulator(getModSourceEnum(ModulatorCurveTypes.switch, false, false, true, MIDIControllers.softPedal), 0, GeneratorTypes.initialFilterFc, -1200, 0)
@@ -9596,7 +9737,7 @@ const W_FORMAT_TAG = {
9596
9737
  PCM: 1,
9597
9738
  ALAW: 6
9598
9739
  };
9599
- function readPCM(data, bytesPerSample) {
9740
+ function readPCM$1(data, bytesPerSample) {
9600
9741
  const maxSampleValue = Math.pow(2, bytesPerSample * 8 - 1);
9601
9742
  const maxUnsigned = Math.pow(2, bytesPerSample * 8);
9602
9743
  let normalizationFactor;
@@ -9699,7 +9840,7 @@ var DLSSample = class extends BasicSample {
9699
9840
  sampleData = new Float32Array(this.rawData.length / this.bytesPerSample);
9700
9841
  break;
9701
9842
  case W_FORMAT_TAG.PCM:
9702
- sampleData = readPCM(this.rawData, this.bytesPerSample);
9843
+ sampleData = readPCM$1(this.rawData, this.bytesPerSample);
9703
9844
  break;
9704
9845
  case W_FORMAT_TAG.ALAW: sampleData = readALAW(this.rawData, this.bytesPerSample);
9705
9846
  }
@@ -10925,7 +11066,7 @@ var DownloadableSounds = class DownloadableSounds extends DLSVerifier {
10925
11066
  dls.soundBankInfo.name = text;
10926
11067
  break;
10927
11068
  case "ICRD":
10928
- dls.soundBankInfo.creationDate = parseDateString(text);
11069
+ dls.soundBankInfo.creationDate = parseDateString(text) ?? /* @__PURE__ */ new Date();
10929
11070
  break;
10930
11071
  case "ICMT":
10931
11072
  dls.soundBankInfo.comment = text;
@@ -11857,6 +11998,23 @@ const TrackerLoopTypes = {
11857
11998
  forward: 1,
11858
11999
  pingPong: 2
11859
12000
  };
12001
+ /**
12002
+ * The ways a sample can be played, each one is a separate preset in the sound bank.
12003
+ */
12004
+ const TrackerSampleVariants = {
12005
+ /**
12006
+ * Uses the sustain loop if the sample has one, otherwise the regular loop.
12007
+ */
12008
+ normal: 0,
12009
+ /**
12010
+ * The sample after its sustain loop has been released, with the regular loop.
12011
+ */
12012
+ release: 1,
12013
+ /**
12014
+ * Reversed playback.
12015
+ */
12016
+ reverse: 2
12017
+ };
11860
12018
  // src/midi/read/tracker/tracker_sound_bank.ts
11861
12019
  /**
11862
12020
  * The volume envelope release (in timecents) of the sound bank instruments.
@@ -11864,62 +12022,242 @@ const TrackerLoopTypes = {
11864
12022
  */
11865
12023
  const RELEASE_TIMECENTS = -9e3;
11866
12024
  /**
11867
- * Creates the sound bank of a tracker module with one preset per sample.
11868
- * The preset of a sample is selected with its index (program, and bank MSB above 127).
11869
- * @param samples The module samples.
11870
- * @param title The module title.
11871
- * @param formatName The module format name.
11872
- * @param rootKey The MIDI key at which the samples play at their middle C rate.
11873
- * @param attenuation The attenuation of every sample in centibels.
11874
- * @returns The SF2 binary.
11875
- */
11876
- function createTrackerSoundBank(samples, title, formatName, rootKey, attenuation) {
11877
- const bank = new BasicSoundBank();
11878
- bank.soundBankInfo.name = title || "Tracker module";
11879
- bank.soundBankInfo.software = "SpessaSynth";
11880
- bank.soundBankInfo.comment = `Converted from ${formatName}`;
11881
- const offsetModulators = [new Modulator(new ModulatorSource(OFFSET_FINE_CC, ModulatorCurveTypes.linear, true), new ModulatorSource(), GeneratorTypes.startAddrsOffset, 32767, 0), new Modulator(new ModulatorSource(OFFSET_COARSE_CC, ModulatorCurveTypes.linear, true), new ModulatorSource(), GeneratorTypes.startAddrsCoarseOffset, 129, 0)];
11882
- for (const [index, trackerSample] of samples.entries()) {
11883
- if (trackerSample.data.length === 0) continue;
11884
- const name = trackerSample.name.trim() || `Sample ${index + 1}`;
11885
- let data = trackerSample.data;
11886
- let loopStart = trackerSample.loopStart;
11887
- let loopEnd = trackerSample.loopEnd;
11888
- if (trackerSample.loopType === TrackerLoopTypes.pingPong) {
11889
- const forward = data.subarray(0, loopEnd);
11890
- const backward = data.slice(loopStart + 1, loopEnd - 1);
11891
- backward.reverse();
11892
- data = new Float32Array(forward.length + backward.length);
11893
- data.set(forward);
11894
- data.set(backward, forward.length);
11895
- loopEnd = data.length;
11896
- } else if (trackerSample.loopType === TrackerLoopTypes.none) {
12025
+ * Unrolls or trims the data of a sample for a forward-looping synthesizer.
12026
+ * @param data The source data (already reversed for reversed playback).
12027
+ * @param loopType The loop type.
12028
+ * @param loopStart The loop start.
12029
+ * @param loopEnd The loop end.
12030
+ * @param pingPongTail How far before the loop end the backward part starts, see {@link TrackerSampleBank}.
12031
+ */
12032
+ function layoutData(data, loopType, loopStart, loopEnd, pingPongTail) {
12033
+ if (loopType !== TrackerLoopTypes.pingPong) return data;
12034
+ const forward = data.subarray(0, loopEnd);
12035
+ const backward = data.slice(loopStart + 1, loopEnd + 1 - pingPongTail);
12036
+ backward.reverse();
12037
+ const out = new Float32Array(forward.length + backward.length);
12038
+ out.set(forward);
12039
+ out.set(backward, forward.length);
12040
+ return out;
12041
+ }
12042
+ /**
12043
+ * Creates the sound bank of a tracker module.
12044
+ * Every sample is one preset, selected with its index (program, and bank MSB above 127).
12045
+ * Extra variants of a sample (the sample after the sustain loop is released, reversed playback)
12046
+ * get their own presets after the samples, created when the playback first needs them.
12047
+ */
12048
+ var TrackerSampleBank = class {
12049
+ samples;
12050
+ layouts = new Array();
12051
+ variantPresets = /* @__PURE__ */ new Map();
12052
+ /**
12053
+ * The backward part of an unrolled ping-pong loop starts this many points before the loop end.
12054
+ * 2 plays every point once per direction, 1 repeats the last point (Impulse Tracker).
12055
+ */
12056
+ pingPongTail;
12057
+ /**
12058
+ * Creates the sound bank of the samples.
12059
+ * @param samples The module samples.
12060
+ * @param repeatPingPongEnd If ping-pong loops play their last point twice, like Impulse Tracker.
12061
+ */
12062
+ constructor(samples, repeatPingPongEnd = false) {
12063
+ this.samples = samples;
12064
+ this.pingPongTail = repeatPingPongEnd ? 1 : 2;
12065
+ for (const [index, sample] of samples.entries()) this.layouts.push(sample.data.length > 0 ? this.createLayout(index, TrackerSampleVariants.normal) : void 0);
12066
+ }
12067
+ /**
12068
+ * Gets the preset of a sample variant, creating it if needed.
12069
+ * @param sampleIndex The index of the sample in the module.
12070
+ * @param variant The variant.
12071
+ * @returns The preset index.
12072
+ */
12073
+ getPreset(sampleIndex, variant) {
12074
+ if (variant === TrackerSampleVariants.normal) return sampleIndex;
12075
+ const key = sampleIndex * 4 + variant;
12076
+ let preset = this.variantPresets.get(key);
12077
+ if (preset === void 0) {
12078
+ preset = this.layouts.length;
12079
+ this.layouts.push(this.createLayout(sampleIndex, variant));
12080
+ this.variantPresets.set(key, preset);
12081
+ }
12082
+ return preset;
12083
+ }
12084
+ /**
12085
+ * Gets the length of a preset's sample.
12086
+ * @param preset The preset index.
12087
+ */
12088
+ getLength(preset) {
12089
+ return this.layouts[preset]?.length ?? 0;
12090
+ }
12091
+ /**
12092
+ * Gets the loop start of a preset's sample.
12093
+ * @param preset The preset index.
12094
+ */
12095
+ getLoopStart(preset) {
12096
+ return this.layouts[preset]?.playLoopStart ?? 0;
12097
+ }
12098
+ /**
12099
+ * Checks if a preset's sample loops.
12100
+ * @param preset The preset index.
12101
+ */
12102
+ isLooped(preset) {
12103
+ const layout = this.layouts[preset];
12104
+ return !!layout && layout.playLoopEnd > layout.playLoopStart;
12105
+ }
12106
+ /**
12107
+ * Advances a playback position, wrapping it in the loop.
12108
+ * @param preset The preset index.
12109
+ * @param position The position in the preset's sample.
12110
+ * @param frames The amount of sample points to advance.
12111
+ * @returns The new position, Infinity if the sample has ended.
12112
+ */
12113
+ advance(preset, position, frames) {
12114
+ const layout = this.layouts[preset];
12115
+ if (!layout) return Infinity;
12116
+ position += frames;
12117
+ if (layout.playLoopEnd > layout.playLoopStart) {
12118
+ if (position >= layout.playLoopEnd) {
12119
+ const length = layout.playLoopEnd - layout.playLoopStart;
12120
+ position = layout.playLoopStart + (position - layout.playLoopStart) % length;
12121
+ }
12122
+ return position;
12123
+ }
12124
+ return position >= layout.length ? Infinity : position;
12125
+ }
12126
+ /**
12127
+ * Converts a position in a preset's sample to the position in the source sample.
12128
+ * @param preset The preset index.
12129
+ * @param position The position in the preset's sample.
12130
+ * @returns The source position and if it is played backwards.
12131
+ */
12132
+ toSource(preset, position) {
12133
+ const layout = this.layouts[preset];
12134
+ if (!layout) return {
12135
+ position: 0,
12136
+ backwards: false
12137
+ };
12138
+ let backwards = false;
12139
+ if (layout.loopType === TrackerLoopTypes.pingPong && position >= layout.loopEnd) {
12140
+ backwards = true;
12141
+ position = layout.loopEnd - this.pingPongTail - (position - layout.loopEnd);
12142
+ }
12143
+ if (layout.variant === TrackerSampleVariants.reverse) {
12144
+ position = layout.sourceLength - 1 - position;
12145
+ backwards = !backwards;
12146
+ }
12147
+ return {
12148
+ position: Math.max(0, position),
12149
+ backwards
12150
+ };
12151
+ }
12152
+ /**
12153
+ * Converts a position in the source sample to the position in a preset's sample.
12154
+ * @param preset The preset index.
12155
+ * @param position The position in the source sample.
12156
+ * @param backwards If the source sample is played backwards.
12157
+ * @returns The position in the preset's sample.
12158
+ */
12159
+ fromSource(preset, position, backwards) {
12160
+ const layout = this.layouts[preset];
12161
+ if (!layout) return 0;
12162
+ if (layout.variant === TrackerSampleVariants.reverse) {
12163
+ position = layout.sourceLength - 1 - position;
12164
+ backwards = !backwards;
12165
+ }
12166
+ if (backwards && layout.loopType === TrackerLoopTypes.pingPong && position > layout.loopStart && position <= layout.loopEnd - this.pingPongTail) position = layout.loopEnd + (layout.loopEnd - this.pingPongTail - position);
12167
+ return this.advance(preset, Math.max(0, position), 0);
12168
+ }
12169
+ /**
12170
+ * Writes the sound bank.
12171
+ * @param title The module title.
12172
+ * @param formatName The module format name.
12173
+ * @param rootKey The MIDI key at which the samples play at their middle C rate.
12174
+ * @param attenuation The attenuation of every sample in centibels.
12175
+ * @returns The SF2 binary.
12176
+ */
12177
+ write(title, formatName, rootKey, attenuation) {
12178
+ const bank = new BasicSoundBank();
12179
+ bank.soundBankInfo.name = title || "Tracker module";
12180
+ bank.soundBankInfo.software = "SpessaSynth";
12181
+ bank.soundBankInfo.comment = `Converted from ${formatName}`;
12182
+ const ccSource = (cc) => new ModulatorSource(cc, ModulatorCurveTypes.linear, true);
12183
+ const modulators = [
12184
+ new Modulator(ccSource(OFFSET_FINE_CC), new ModulatorSource(), GeneratorTypes.startAddrsOffset, 32767, 0),
12185
+ new Modulator(ccSource(OFFSET_COARSE_CC), new ModulatorSource(), GeneratorTypes.startAddrsCoarseOffset, 129, 0),
12186
+ new Modulator(ccSource(FILTER_CUTOFF_CC), new ModulatorSource(), GeneratorTypes.initialFilterFc, -9e3, 0),
12187
+ new Modulator(ccSource(FILTER_RESONANCE_CC), new ModulatorSource(), GeneratorTypes.initialFilterQ, 320, 0),
12188
+ new Modulator(ccSource(FILTER_RESONANCE_CC), new ModulatorSource(), GeneratorTypes.initialAttenuation, -160, 0)
12189
+ ];
12190
+ for (const [preset, layout] of this.layouts.entries()) {
12191
+ if (!layout) continue;
12192
+ const trackerSample = this.samples[layout.sampleIndex];
12193
+ const baseName = trackerSample.name.trim() || `Sample ${layout.sampleIndex + 1}`;
12194
+ const name = layout.variant === TrackerSampleVariants.release ? `${baseName} (release)` : layout.variant === TrackerSampleVariants.reverse ? `${baseName} (reverse)` : baseName;
12195
+ const channels = trackerSample.rightData ? [trackerSample.data, trackerSample.rightData] : [trackerSample.data];
12196
+ const instrument = new BasicInstrument();
12197
+ instrument.name = name;
12198
+ instrument.globalZone.addGenerators(new Generator(GeneratorTypes.releaseVolEnv, RELEASE_TIMECENTS), new Generator(GeneratorTypes.initialAttenuation, attenuation), new Generator(GeneratorTypes.sampleModes, layout.playLoopEnd > layout.playLoopStart ? 1 : 0));
12199
+ instrument.globalZone.addModulators(...modulators.map((m) => Modulator.copyFrom(m)));
12200
+ for (const [c, source] of channels.entries()) {
12201
+ let data = source;
12202
+ if (layout.variant === TrackerSampleVariants.reverse) {
12203
+ data = source.slice();
12204
+ data.reverse();
12205
+ }
12206
+ const sample = new EmptySample();
12207
+ sample.name = channels.length > 1 ? `${name} ${c ? "R" : "L"}` : name;
12208
+ sample.originalKey = rootKey;
12209
+ sample.setAudioData(layoutData(data, layout.loopType, layout.loopStart, layout.loopEnd, this.pingPongTail), Math.round(trackerSample.middleCRate));
12210
+ sample.loopStart = layout.playLoopStart;
12211
+ sample.loopEnd = layout.playLoopEnd;
12212
+ bank.addSamples(sample);
12213
+ const zone = instrument.createZone(sample);
12214
+ if (channels.length > 1) zone.addGenerators(new Generator(GeneratorTypes.pan, c ? 500 : -500), new Generator(GeneratorTypes.initialAttenuation, attenuation + 75));
12215
+ }
12216
+ bank.addInstruments(instrument);
12217
+ const bankPreset = new BasicPreset(bank);
12218
+ bankPreset.name = name;
12219
+ bankPreset.program = preset & 127;
12220
+ bankPreset.bankMSB = preset >> 7;
12221
+ bankPreset.createZone(instrument);
12222
+ bank.addPresets(bankPreset);
12223
+ }
12224
+ bank.flush();
12225
+ return bank.writeSF2();
12226
+ }
12227
+ createLayout(sampleIndex, variant) {
12228
+ const sample = this.samples[sampleIndex];
12229
+ const length = sample.data.length;
12230
+ const sustain = variant !== TrackerSampleVariants.release && (sample.sustainLoopType ?? TrackerLoopTypes.none) !== TrackerLoopTypes.none;
12231
+ let loopType = sustain ? sample.sustainLoopType ?? TrackerLoopTypes.none : sample.loopType;
12232
+ let loopStart = sustain ? sample.sustainLoopStart ?? 0 : sample.loopStart;
12233
+ let loopEnd = sustain ? sample.sustainLoopEnd ?? 0 : sample.loopEnd;
12234
+ loopEnd = Math.min(loopEnd, length);
12235
+ if (loopStart >= loopEnd) loopType = TrackerLoopTypes.none;
12236
+ if (variant === TrackerSampleVariants.reverse) [loopStart, loopEnd] = [length - loopEnd, length - loopStart];
12237
+ if (loopType === TrackerLoopTypes.none) {
11897
12238
  loopStart = 0;
11898
12239
  loopEnd = 0;
11899
12240
  }
11900
- const sample = new EmptySample();
11901
- sample.name = name;
11902
- sample.originalKey = rootKey;
11903
- sample.setAudioData(data, Math.round(trackerSample.middleCRate));
11904
- sample.loopStart = loopStart;
11905
- sample.loopEnd = loopEnd;
11906
- bank.addSamples(sample);
11907
- const instrument = new BasicInstrument();
11908
- instrument.name = name;
11909
- instrument.globalZone.addGenerators(new Generator(GeneratorTypes.releaseVolEnv, RELEASE_TIMECENTS), new Generator(GeneratorTypes.initialAttenuation, attenuation), new Generator(GeneratorTypes.sampleModes, trackerSample.loopType === TrackerLoopTypes.none ? 0 : 1));
11910
- instrument.globalZone.addModulators(...offsetModulators.map((m) => Modulator.copyFrom(m)));
11911
- instrument.createZone(sample);
11912
- bank.addInstruments(instrument);
11913
- const preset = new BasicPreset(bank);
11914
- preset.name = name;
11915
- preset.program = index & 127;
11916
- preset.bankMSB = index >> 7;
11917
- preset.createZone(instrument);
11918
- bank.addPresets(preset);
12241
+ let playLength = length;
12242
+ const playLoopStart = loopStart;
12243
+ let playLoopEnd = loopEnd;
12244
+ if (loopType === TrackerLoopTypes.pingPong) {
12245
+ playLength = loopEnd + Math.max(0, loopEnd - loopStart - this.pingPongTail);
12246
+ playLoopEnd = playLength;
12247
+ }
12248
+ return {
12249
+ sampleIndex,
12250
+ variant,
12251
+ loopType,
12252
+ loopStart,
12253
+ loopEnd,
12254
+ sourceLength: length,
12255
+ length: playLength,
12256
+ playLoopStart,
12257
+ playLoopEnd
12258
+ };
11919
12259
  }
11920
- bank.flush();
11921
- return bank.writeSF2();
11922
- }
12260
+ };
11923
12261
  // src/midi/read/tracker/tracker_pattern.ts
11924
12262
  /**
11925
12263
  * The number of bytes each pattern cell takes up.
@@ -12006,6 +12344,14 @@ const MAX_ROWS = 1e5;
12006
12344
  */
12007
12345
  const CHANNELS_PER_PORT = 16;
12008
12346
  /**
12347
+ * The maximum number of voices (pattern channels and background voices), like Impulse Tracker.
12348
+ */
12349
+ const MAX_VOICES = 256;
12350
+ /**
12351
+ * The cutoff (in absolute cents) at which the synthesizer's filter is fully open.
12352
+ */
12353
+ const FILTER_OPEN_CENTS = 13500;
12354
+ /**
12009
12355
  * Creates a disabled envelope.
12010
12356
  */
12011
12357
  function emptyEnvelope() {
@@ -12013,11 +12359,30 @@ function emptyEnvelope() {
12013
12359
  enabled: false,
12014
12360
  points: [],
12015
12361
  sustainPoint: -1,
12362
+ sustainStart: -1,
12016
12363
  loopStart: -1,
12017
12364
  loopEnd: -1
12018
12365
  };
12019
12366
  }
12020
12367
  /**
12368
+ * Gets the value of an envelope at a position, interpolating linearly between the points.
12369
+ * @param envelope The envelope.
12370
+ * @param tick The position.
12371
+ * @returns The value (0-64).
12372
+ */
12373
+ function getEnvelopeValue(envelope, tick) {
12374
+ const points = envelope.points;
12375
+ for (let i = 0; i < points.length - 1; i++) {
12376
+ const a = points[i];
12377
+ const b = points[i + 1];
12378
+ if (tick < b.tick) {
12379
+ if (tick <= a.tick || b.tick === a.tick) return a.value;
12380
+ return a.value + (b.value - a.value) * (tick - a.tick) / (b.tick - a.tick);
12381
+ }
12382
+ }
12383
+ return points[points.length - 1]?.value ?? 64;
12384
+ }
12385
+ /**
12021
12386
  * Creates an instrument that maps every note to a single sample.
12022
12387
  * Used for the formats without instruments.
12023
12388
  * @param name The instrument name.
@@ -12039,10 +12404,11 @@ function singleSampleInstrument(name, sampleIndex) {
12039
12404
  * and implement the format-specific effects using the primitives of {@link TrackerChannel}.
12040
12405
  * This class plays the module tick by tick and converts it to MIDI events with an embedded sound bank:
12041
12406
  * - Each tracker channel becomes one MIDI channel on its own track.
12407
+ * Background voices (Impulse Tracker new note actions) get extra MIDI channels from a shared pool.
12042
12408
  * - Each sample becomes one preset. Notes select the preset with program changes (and bank select above 127).
12043
12409
  * - Pitch is the closest key plus the pitch wheel. The pitch wheel range is set per channel to fit the highest offset.
12044
12410
  * - Volume and envelopes are sent as main volume and expression, panning as the pan controller.
12045
- * - Sample offsets are sent as two controllers that modulate the sample start in the sound bank.
12411
+ * - Sample offsets and the resonant filter are sent as controllers that drive modulators in the sound bank.
12046
12412
  */
12047
12413
  var TrackerModule = class {
12048
12414
  title = "";
@@ -12098,26 +12464,85 @@ var TrackerModule = class {
12098
12464
  * If a pattern break to a row above 63 is ignored instead of breaking to the first row.
12099
12465
  */
12100
12466
  ignoreInvalidBreaks = false;
12467
+ /**
12468
+ * If {@link processTick} is also called for the first ticks of the rows repeated by a pattern delay.
12469
+ */
12470
+ processRepeatedFirstTicks = false;
12471
+ /**
12472
+ * If ping-pong loops play their last point twice (Impulse Tracker).
12473
+ */
12474
+ repeatPingPongEnd = false;
12475
+ /**
12476
+ * If the level of a channel follows the linear pan law of the tracker (quieter in the center),
12477
+ * instead of the constant power of the synthesizer.
12478
+ */
12479
+ linearPanLevel = false;
12101
12480
  speed = 6;
12102
12481
  globalVolume = 64;
12103
12482
  /**
12104
- * The tick of the current row.
12483
+ * The tick of the current row, counted from zero again for each row repeated by a pattern delay.
12105
12484
  */
12106
12485
  tick = 0;
12107
12486
  /**
12108
- * The attenuation of every sample in centibels, set with {@link setPreAmp}.
12487
+ * The tick of the current row, including the rows repeated by a pattern delay.
12109
12488
  */
12110
- attenuation = 0;
12489
+ rowTick = 0;
12490
+ /**
12491
+ * Extra ticks added to every repetition of the current row (fine pattern delay).
12492
+ */
12493
+ frameDelay = 0;
12111
12494
  tempo = 125;
12495
+ /**
12496
+ * The pattern being played.
12497
+ */
12498
+ currentPattern = new TrackerPattern(64, 0);
12499
+ /**
12500
+ * The row being played.
12501
+ */
12502
+ currentRow = 0;
12503
+ /**
12504
+ * If a position jump wins over a pattern loop on the same row (Impulse Tracker), instead of the loop winning.
12505
+ */
12506
+ jumpOverridesLoop = false;
12507
+ /**
12508
+ * The sample variants used by the playback, they become the presets of the sound bank.
12509
+ */
12510
+ sampleBank = new TrackerSampleBank([]);
12511
+ /**
12512
+ * The pattern channels.
12513
+ */
12112
12514
  channels = new Array();
12515
+ /**
12516
+ * The voices that keep playing in the background after a new note.
12517
+ */
12518
+ backgroundVoices = new Array();
12519
+ /**
12520
+ * The attenuation of every sample in centibels, set with {@link setPreAmp}.
12521
+ */
12522
+ attenuation = 0;
12523
+ outputs = new Array();
12524
+ /**
12525
+ * The voice that writes to each output, undefined if the output is free.
12526
+ */
12527
+ outputOwners = new Array();
12113
12528
  positionJump = -1;
12114
12529
  breakRow = -1;
12115
12530
  patternLoopRow = -1;
12116
12531
  patternDelay = 0;
12532
+ rowDelaySet = false;
12117
12533
  songEnded = false;
12118
- currentRow = 0;
12534
+ /**
12535
+ * The MIDI tick of the tick being processed.
12536
+ */
12537
+ currentTicks = 0;
12119
12538
  lastNoteOnTick = -1;
12120
12539
  /**
12540
+ * The number of ticks in the current row, including pattern delays.
12541
+ */
12542
+ get rowTicks() {
12543
+ return (this.speed + this.frameDelay) * (this.patternDelay + 1);
12544
+ }
12545
+ /**
12121
12546
  * Converts the module into the given MIDI.
12122
12547
  * @param outputMIDI The MIDI to populate.
12123
12548
  * @param fileName The file name.
@@ -12127,11 +12552,17 @@ var TrackerModule = class {
12127
12552
  this.speed = this.initialSpeed;
12128
12553
  this.tempo = this.initialTempo;
12129
12554
  this.globalVolume = this.initialGlobalVolume;
12555
+ this.sampleBank = new TrackerSampleBank(this.samples, this.repeatPingPongEnd);
12130
12556
  this.channels = [];
12131
- const outputs = new Array();
12557
+ this.backgroundVoices = [];
12558
+ this.outputs = [];
12559
+ this.outputOwners = [];
12132
12560
  for (let i = 0; i < this.channelCount; i++) {
12133
- this.channels.push(new TrackerChannel(i, this.channelPanning[i] ?? 128));
12134
- outputs.push(new TrackerMIDITrack(i % CHANNELS_PER_PORT, Math.floor(i / CHANNELS_PER_PORT)));
12561
+ const channel = this.createChannel(i, this.channelPanning[i] ?? 128);
12562
+ this.channels.push(channel);
12563
+ this.createOutput();
12564
+ channel.output = this.outputs[i];
12565
+ this.outputOwners[i] = channel;
12135
12566
  }
12136
12567
  const conductor = new MIDITrack();
12137
12568
  conductor.name = this.title;
@@ -12139,7 +12570,7 @@ var TrackerModule = class {
12139
12570
  conductorEvent(0, MIDIMessageTypes.trackName, getStringBytes(this.title));
12140
12571
  conductor.pushEvents(MIDIUtils.reset(0, "gs"));
12141
12572
  const writeTempo = (ticks) => {
12142
- const microseconds = Math.round(6e7 / this.tempo);
12573
+ const microseconds = Math.round(this.getTickDuration() * TRACKER_TIME_DIVISION * 1e6);
12143
12574
  conductorEvent(ticks, MIDIMessageTypes.setTempo, [
12144
12575
  microseconds >> 16 & 255,
12145
12576
  microseconds >> 8 & 255,
@@ -12147,34 +12578,45 @@ var TrackerModule = class {
12147
12578
  ]);
12148
12579
  };
12149
12580
  writeTempo(0);
12581
+ let writtenTempo = this.getTickDuration();
12150
12582
  const emptyPattern = new TrackerPattern(64, this.channelCount);
12151
12583
  const visitedRows = /* @__PURE__ */ new Map();
12584
+ const getRowKey = (order, row) => {
12585
+ let key = `${order}:${row}`;
12586
+ for (const channel of this.channels) if (channel.patternLoopCount) key += `:${channel.index},${channel.patternLoopCount}`;
12587
+ return key;
12588
+ };
12152
12589
  let absoluteTick = 0;
12153
12590
  let order = 0;
12154
12591
  let row = 0;
12155
12592
  let lastOrder = -1;
12156
12593
  let loopStart = -1;
12594
+ let jumped = false;
12157
12595
  for (let rowCount = 0; rowCount < MAX_ROWS; rowCount++) {
12158
12596
  if (this.songEnded) break;
12159
12597
  if (order >= this.orders.length) {
12160
12598
  if (this.restartPosition < 0 || this.restartPosition >= this.orders.length) break;
12161
12599
  order = this.restartPosition;
12162
- row = 0;
12600
+ if (!jumped) row = 0;
12163
12601
  continue;
12164
12602
  }
12165
12603
  const patternIndex = this.orders[order];
12166
12604
  if (patternIndex < 0) {
12167
12605
  order++;
12168
- row = 0;
12606
+ if (!jumped) row = 0;
12169
12607
  continue;
12170
12608
  }
12171
12609
  const pattern = this.patterns[patternIndex] ?? emptyPattern;
12172
12610
  if (row >= pattern.rows) {
12173
- order++;
12174
- row = 0;
12175
- continue;
12611
+ if (jumped) row = 0;
12612
+ else {
12613
+ order++;
12614
+ row = 0;
12615
+ continue;
12616
+ }
12176
12617
  }
12177
- const rowKey = order * 1024 + row;
12618
+ jumped = false;
12619
+ const rowKey = getRowKey(order, row);
12178
12620
  const visitedTick = visitedRows.get(rowKey);
12179
12621
  if (visitedTick !== void 0) {
12180
12622
  loopStart = visitedTick;
@@ -12189,9 +12631,13 @@ var TrackerModule = class {
12189
12631
  this.breakRow = -1;
12190
12632
  this.patternLoopRow = -1;
12191
12633
  this.patternDelay = 0;
12634
+ this.rowDelaySet = false;
12635
+ this.frameDelay = 0;
12192
12636
  this.currentRow = row;
12637
+ this.currentPattern = pattern;
12193
12638
  this.tick = 0;
12194
- const tempo = this.tempo;
12639
+ this.rowTick = 0;
12640
+ this.currentTicks = absoluteTick;
12195
12641
  for (const channel of this.channels) {
12196
12642
  const offset = pattern.getCellOffset(row, channel.index);
12197
12643
  channel.rowNote = pattern.getNote(offset);
@@ -12205,25 +12651,39 @@ var TrackerModule = class {
12205
12651
  channel.volumeDelta = 0;
12206
12652
  this.processRow(channel);
12207
12653
  }
12208
- if (this.tempo !== tempo) writeTempo(absoluteTick);
12209
12654
  if (this.songEnded) break;
12210
- const rowTicks = this.speed * (this.patternDelay + 1);
12655
+ const rowTicks = this.rowTicks;
12211
12656
  for (let t = 0; t < rowTicks; t++) {
12212
- this.tick = t % this.speed;
12657
+ this.rowTick = t;
12658
+ this.tick = t % (this.speed + this.frameDelay);
12659
+ this.currentTicks = absoluteTick;
12660
+ if (t > 0) {
12661
+ if (this.tick === 0 && this.processRepeatedFirstTicks) {
12662
+ this.positionJump = -1;
12663
+ this.breakRow = -1;
12664
+ this.patternLoopRow = -1;
12665
+ }
12666
+ for (const channel of this.channels) if (this.tick > 0 || this.processRepeatedFirstTicks) this.processTick(channel);
12667
+ }
12213
12668
  for (const channel of this.channels) {
12214
- if (this.tick > 0) this.processTick(channel);
12215
12669
  if (this.tick === channel.noteCutTick) channel.volume = 0;
12216
12670
  this.updateChannel(channel);
12217
- this.writeChannel(channel, outputs[channel.index], absoluteTick);
12671
+ this.writeChannel(channel, absoluteTick);
12672
+ }
12673
+ this.processBackgroundVoices(absoluteTick);
12674
+ const tickDuration = this.getTickDuration();
12675
+ if (tickDuration !== writtenTempo) {
12676
+ writtenTempo = tickDuration;
12677
+ writeTempo(absoluteTick);
12218
12678
  }
12219
12679
  absoluteTick++;
12220
12680
  }
12221
- if (this.patternLoopRow >= 0) {
12222
- for (let r = this.patternLoopRow; r <= row; r++) visitedRows.delete(order * 1024 + r);
12223
- row = this.patternLoopRow;
12224
- } else if (this.positionJump >= 0 || this.breakRow >= 0) {
12681
+ const doJump = this.positionJump >= 0 || this.breakRow >= 0;
12682
+ if (this.patternLoopRow >= 0 && !(doJump && this.jumpOverridesLoop && this.positionJump >= 0)) row = this.patternLoopRow;
12683
+ else if (doJump) {
12225
12684
  order = this.positionJump >= 0 ? this.positionJump : order + 1;
12226
12685
  row = Math.max(0, this.breakRow);
12686
+ jumped = true;
12227
12687
  } else row++;
12228
12688
  }
12229
12689
  if (loopStart >= 0 && this.lastNoteOnTick >= loopStart) {
@@ -12233,8 +12693,8 @@ var TrackerModule = class {
12233
12693
  outputMIDI.fileName = fileName;
12234
12694
  outputMIDI.format = 1;
12235
12695
  outputMIDI.timeDivision = TRACKER_TIME_DIVISION;
12236
- outputMIDI.tracks = [conductor, ...outputs.map((o, i) => o.finish(`Channel ${i + 1}`, absoluteTick))];
12237
- outputMIDI.embeddedSoundBank = createTrackerSoundBank(this.samples, this.title, this.formatName, this.rootKey, this.attenuation);
12696
+ outputMIDI.tracks = [conductor, ...this.outputs.map((o, i) => o.finish(i < this.channelCount ? `Channel ${i + 1}` : `Voice ${i - this.channelCount + 1}`, absoluteTick))];
12697
+ outputMIDI.embeddedSoundBank = this.sampleBank.write(this.title, this.formatName, this.rootKey, this.attenuation);
12238
12698
  outputMIDI.bankOffset = 0;
12239
12699
  const info = (key, text) => {
12240
12700
  outputMIDI.rmidiInfo[key] = getStringBytes(text, true);
@@ -12249,11 +12709,84 @@ var TrackerModule = class {
12249
12709
  SpessaLog.groupEnd();
12250
12710
  }
12251
12711
  /**
12712
+ * Gets the duration of a tick in seconds. A tick lasts 2.5 / tempo seconds by default.
12713
+ */
12714
+ getTickDuration() {
12715
+ return 2.5 / this.tempo;
12716
+ }
12717
+ /**
12718
+ * Creates a pattern channel. Formats with their own channel state override this.
12719
+ * @param index The channel index.
12720
+ * @param panning The initial panning (0-255).
12721
+ */
12722
+ createChannel(index, panning) {
12723
+ return new TrackerChannel(index, panning);
12724
+ }
12725
+ /**
12252
12726
  * Updates the channel after the effects of every tick (envelopes, automatic vibrato). Does nothing by default.
12727
+ * Also called for the background voices.
12253
12728
  * @param channel The channel to update.
12254
12729
  */
12255
12730
  updateChannel(channel) {}
12256
12731
  /**
12732
+ * Checks if a background voice has become silent for good and can be stopped.
12733
+ * @param voice The background voice.
12734
+ */
12735
+ isVoiceFinished(voice) {
12736
+ return voice.output?.activeKey === -1 || voice.samplePosition === Infinity;
12737
+ }
12738
+ /**
12739
+ * Moves the note playing on a pattern channel into a background voice, so it keeps playing
12740
+ * while the channel starts a new note on another MIDI channel.
12741
+ * @param channel The pattern channel.
12742
+ * @returns The background voice, undefined if no note was playing.
12743
+ */
12744
+ moveToBackground(channel) {
12745
+ const output = channel.output;
12746
+ if (!output || output.activeKey === -1) return;
12747
+ if (this.backgroundVoices.length >= MAX_VOICES - this.channelCount) {
12748
+ let quietest = this.backgroundVoices[0];
12749
+ for (const voice of this.backgroundVoices) if (voice.outputLevel < quietest.outputLevel) quietest = voice;
12750
+ this.stopVoice(quietest);
12751
+ }
12752
+ const voice = channel.clone();
12753
+ voice.background = true;
12754
+ voice.rowEffect = 0;
12755
+ voice.rowParam = 0;
12756
+ voice.rowVolume = 0;
12757
+ voice.trigger = false;
12758
+ voice.stop = false;
12759
+ voice.arpeggio = 0;
12760
+ voice.vibratoDelta = 0;
12761
+ voice.volumeDelta = 0;
12762
+ voice.tremorMuted = false;
12763
+ this.backgroundVoices.push(voice);
12764
+ this.outputOwners[this.outputs.indexOf(output)] = voice;
12765
+ let index = this.outputOwners[channel.index] === void 0 ? channel.index : -1;
12766
+ if (index === -1) index = this.outputOwners.indexOf(void 0, this.channelCount);
12767
+ if (index === -1) {
12768
+ index = this.outputs.length;
12769
+ this.createOutput();
12770
+ }
12771
+ channel.output = this.outputs[index];
12772
+ this.outputOwners[index] = channel;
12773
+ return voice;
12774
+ }
12775
+ /**
12776
+ * Stops a background voice and frees its MIDI channel.
12777
+ * @param voice The background voice.
12778
+ */
12779
+ stopVoice(voice) {
12780
+ const index = this.backgroundVoices.indexOf(voice);
12781
+ if (index === -1) return;
12782
+ this.backgroundVoices.splice(index, 1);
12783
+ if (voice.output) {
12784
+ voice.output.noteOff(this.currentTicks);
12785
+ const outputIndex = this.outputs.indexOf(voice.output);
12786
+ if (this.outputOwners[outputIndex] === voice) this.outputOwners[outputIndex] = void 0;
12787
+ }
12788
+ }
12789
+ /**
12257
12790
  * Selects the sample for a note from the channel's instrument.
12258
12791
  * @param channel The channel.
12259
12792
  * @param note The one-based note.
@@ -12269,6 +12802,7 @@ var TrackerModule = class {
12269
12802
  }
12270
12803
  channel.sample = sample;
12271
12804
  channel.sampleIndex = index;
12805
+ channel.preset = index;
12272
12806
  return sample;
12273
12807
  }
12274
12808
  /**
@@ -12318,8 +12852,13 @@ var TrackerModule = class {
12318
12852
  /**
12319
12853
  * Breaks to a row of the next order.
12320
12854
  * @param param The effect parameter, the row as a binary-coded decimal.
12855
+ * @param binaryCodedDecimal False if the parameter is the row number itself (Impulse Tracker).
12321
12856
  */
12322
- patternBreak(param) {
12857
+ patternBreak(param, binaryCodedDecimal = true) {
12858
+ if (!binaryCodedDecimal) {
12859
+ this.breakRow = param;
12860
+ return;
12861
+ }
12323
12862
  const row = (param >> 4) * 10 + (param & 15);
12324
12863
  if (row < 64) this.breakRow = row;
12325
12864
  else if (!this.ignoreInvalidBreaks) this.breakRow = 0;
@@ -12328,6 +12867,38 @@ var TrackerModule = class {
12328
12867
  if (this.patternDelay === 0) this.patternDelay = rows;
12329
12868
  }
12330
12869
  /**
12870
+ * Sets the pattern delay if no other channel has set it on this row, even to zero rows.
12871
+ * @param rows The number of extra repetitions of the row.
12872
+ */
12873
+ setRowDelay(rows) {
12874
+ if (!this.rowDelaySet) {
12875
+ this.rowDelaySet = true;
12876
+ this.patternDelay = rows;
12877
+ }
12878
+ }
12879
+ /**
12880
+ * Jumps back to a row of the current pattern after this row.
12881
+ * @param row The row to jump to.
12882
+ */
12883
+ setPatternLoopTarget(row) {
12884
+ this.patternLoopRow = row;
12885
+ }
12886
+ /**
12887
+ * Cancels a position jump set earlier on this row.
12888
+ */
12889
+ clearPositionJump() {
12890
+ this.positionJump = -1;
12891
+ }
12892
+ /**
12893
+ * Computes the playback rate of a channel's sample in Hertz, including all pitch effects.
12894
+ * @param channel The channel.
12895
+ * @returns The rate, zero or below if the channel has no pitch.
12896
+ */
12897
+ getFrequency(channel) {
12898
+ const period = channel.period + channel.vibratoDelta + channel.autoVibratoDelta;
12899
+ return period > 0 ? this.periodToFrequency(period) : 0;
12900
+ }
12901
+ /**
12331
12902
  * Processes a pattern loop effect.
12332
12903
  * @param channel The channel.
12333
12904
  * @param count Zero sets the loop start, other values loop that many times.
@@ -12342,12 +12913,34 @@ var TrackerModule = class {
12342
12913
  this.patternLoopRow = channel.patternLoopRow;
12343
12914
  }
12344
12915
  /**
12916
+ * Updates, writes and stops the background voices for the current tick.
12917
+ * @param ticks The current MIDI tick.
12918
+ */
12919
+ processBackgroundVoices(ticks) {
12920
+ for (let i = 0; i < this.backgroundVoices.length; i++) {
12921
+ const voice = this.backgroundVoices[i];
12922
+ if (this.isVoiceFinished(voice)) {
12923
+ this.stopVoice(voice);
12924
+ i--;
12925
+ continue;
12926
+ }
12927
+ this.updateChannel(voice);
12928
+ this.writeChannel(voice, ticks);
12929
+ }
12930
+ }
12931
+ createOutput() {
12932
+ const index = this.outputs.length;
12933
+ this.outputs.push(new TrackerMIDITrack(index % CHANNELS_PER_PORT, Math.floor(index / CHANNELS_PER_PORT)));
12934
+ this.outputOwners.push(void 0);
12935
+ }
12936
+ /**
12345
12937
  * Writes the MIDI events of a channel for the current tick.
12346
12938
  * @param channel The channel.
12347
- * @param output The MIDI track of the channel.
12348
12939
  * @param ticks The current MIDI tick.
12349
12940
  */
12350
- writeChannel(channel, output, ticks) {
12941
+ writeChannel(channel, ticks) {
12942
+ const output = channel.output;
12943
+ if (!output) return;
12351
12944
  if (channel.stop) {
12352
12945
  channel.stop = false;
12353
12946
  output.noteOff(ticks);
@@ -12356,16 +12949,19 @@ var TrackerModule = class {
12356
12949
  if (channel.trigger) {
12357
12950
  channel.trigger = false;
12358
12951
  output.noteOff(ticks);
12952
+ channel.samplePosition = Infinity;
12359
12953
  if (!sample) return;
12954
+ const preset = channel.preset;
12360
12955
  let offset = channel.sampleOffset;
12361
- if (offset >= sample.data.length) {
12362
- if (sample.loopType === TrackerLoopTypes.none) return;
12363
- offset = sample.loopStart;
12956
+ if (offset >= this.sampleBank.getLength(preset)) {
12957
+ if (!this.sampleBank.isLooped(preset)) return;
12958
+ offset = this.sampleBank.getLoopStart(preset);
12364
12959
  }
12365
- output.selectPreset(ticks, channel.sampleIndex);
12960
+ output.selectPreset(ticks, preset);
12366
12961
  const units = Math.floor(offset / 256);
12367
12962
  output.controllerChange(ticks, OFFSET_FINE_CC, units & 127);
12368
12963
  output.controllerChange(ticks, OFFSET_COARSE_CC, units >> 7);
12964
+ output.controllerChange(ticks, OFFSET_FINEST_CC, Math.floor((offset & 255) / 2), true);
12369
12965
  const semitones = this.getSemitones(channel, sample);
12370
12966
  if (semitones === void 0) return;
12371
12967
  const key = Math.min(127, Math.max(0, Math.round(semitones)));
@@ -12373,36 +12969,59 @@ var TrackerModule = class {
12373
12969
  output.setPitch(ticks, semitones - key);
12374
12970
  output.noteOn(ticks, key);
12375
12971
  this.lastNoteOnTick = ticks;
12972
+ channel.samplePosition = offset;
12973
+ this.advancePosition(channel, sample, semitones);
12376
12974
  return;
12377
12975
  }
12378
12976
  if (output.activeKey === -1 || !sample) return;
12379
12977
  const semitones = this.getSemitones(channel, sample);
12380
- if (semitones !== void 0) output.setPitch(ticks, semitones - output.activeKey);
12978
+ if (semitones !== void 0) {
12979
+ output.setPitch(ticks, semitones - output.activeKey);
12980
+ this.advancePosition(channel, sample, semitones);
12981
+ }
12381
12982
  this.writeControllers(channel, output, ticks);
12382
12983
  }
12383
12984
  /**
12985
+ * Advances the sample position of a channel by one tick.
12986
+ * @param channel The channel.
12987
+ * @param sample The playing sample.
12988
+ * @param semitones The current pitch, see {@link getSemitones}.
12989
+ */
12990
+ advancePosition(channel, sample, semitones) {
12991
+ if (channel.samplePosition === Infinity) return;
12992
+ const rate = Math.round(sample.middleCRate) * Math.pow(2, (semitones - this.rootKey) / 12);
12993
+ channel.samplePosition = this.sampleBank.advance(channel.preset, channel.samplePosition, rate * this.getTickDuration());
12994
+ }
12995
+ /**
12384
12996
  * Computes the MIDI pitch of the channel relative to the sound bank sample.
12385
12997
  * @param channel The channel.
12386
12998
  * @param sample The playing sample.
12387
12999
  * @returns The pitch in semitones, undefined if the channel has no pitch.
12388
13000
  */
12389
13001
  getSemitones(channel, sample) {
12390
- const period = channel.period + channel.vibratoDelta + channel.autoVibratoDelta;
12391
- if (period <= 0) return;
12392
- const frequency = this.periodToFrequency(period);
13002
+ const frequency = this.getFrequency(channel);
12393
13003
  if (frequency <= 0) return;
12394
13004
  return this.rootKey + 12 * Math.log2(frequency / Math.round(sample.middleCRate)) + channel.arpeggio;
12395
13005
  }
12396
13006
  writeControllers(channel, output, ticks) {
12397
13007
  const volume = channel.tremorMuted ? 0 : Math.min(64, Math.max(0, channel.volume + channel.volumeDelta)) / 64;
12398
- const expression = this.globalVolume / 64 * channel.envelopeVolume * channel.fadeoutVolume;
13008
+ let expression = this.globalVolume / 64 * channel.volumeScale * channel.envelopeVolume * channel.fadeoutVolume;
13009
+ let panning = channel.outputPanning;
13010
+ if (panning < 0) {
13011
+ panning = channel.panning;
13012
+ if (channel.envelopePanning !== 32) panning += (channel.envelopePanning - 32) * (128 - Math.abs(panning - 128)) / 32;
13013
+ }
13014
+ const clamped = Math.min(256, Math.max(0, panning));
13015
+ if (this.linearPanLevel) expression *= Math.hypot(256 - clamped, clamped) / 256;
13016
+ channel.outputLevel = volume * expression;
12399
13017
  output.controllerChange(ticks, MIDIControllers.mainVolume, Math.min(127, Math.round(128 * Math.sqrt(volume))));
12400
13018
  output.controllerChange(ticks, MIDIControllers.expression, Math.min(127, Math.round(128 * Math.sqrt(expression))));
12401
- let panning = channel.panning;
12402
- if (channel.envelopePanning !== 32) panning += (channel.envelopePanning - 32) * (128 - Math.abs(panning - 128)) / 32;
12403
- const clamped = Math.min(256, Math.max(0, panning));
12404
13019
  const angle = (this.squareRootPanning ? Math.atan2(Math.sqrt(clamped), Math.sqrt(256 - clamped)) : Math.atan2(clamped, 256 - clamped)) / (Math.PI / 2);
12405
13020
  output.controllerChange(ticks, MIDIControllers.pan, Math.min(127, Math.max(0, Math.round(64 + (angle - .5) * 128))));
13021
+ const cutoff = channel.filterCutoff >= FILTER_OPEN_CENTS ? 0 : Math.min(16383, Math.max(1, Math.round((FILTER_OPEN_CENTS - channel.filterCutoff) / FILTER_CUTOFF_RANGE * 16384)));
13022
+ const resonance = Math.min(16383, Math.max(0, Math.round(channel.filterResonance / 320 * 16384)));
13023
+ output.controllerChange14(ticks, FILTER_CUTOFF_CC, cutoff, true);
13024
+ output.controllerChange14(ticks, FILTER_RESONANCE_CC, resonance, true);
12406
13025
  }
12407
13026
  };
12408
13027
  // src/midi/read/tracker/protracker.ts
@@ -12836,24 +13455,6 @@ const VolumeColumnCommands = {
12836
13455
  const AUTO_VIBRATO_SINE = /* @__PURE__ */ new Int8Array(256);
12837
13456
  for (let i = 0; i < 256; i++) AUTO_VIBRATO_SINE[i] = Math.round(64 * Math.sin(i * Math.PI / 128));
12838
13457
  /**
12839
- * Gets the value of an envelope at a position.
12840
- * @param envelope The envelope.
12841
- * @param tick The position.
12842
- * @returns The value (0-64).
12843
- */
12844
- function getEnvelopeValue(envelope, tick) {
12845
- const points = envelope.points;
12846
- for (let i = 0; i < points.length - 1; i++) {
12847
- const a = points[i];
12848
- const b = points[i + 1];
12849
- if (tick < b.tick) {
12850
- if (tick <= a.tick || b.tick === a.tick) return a.value;
12851
- return a.value + (b.value - a.value) * (tick - a.tick) / (b.tick - a.tick);
12852
- }
12853
- }
12854
- return points[points.length - 1]?.value ?? 64;
12855
- }
12856
- /**
12857
13458
  * Advances the envelope position by one tick.
12858
13459
  * @param envelope The envelope.
12859
13460
  * @param tick The current position.
@@ -12916,7 +13517,7 @@ function decodeADPCM(binary, offset, length) {
12916
13517
  * @param panning True for the panning envelope, false for the volume envelope.
12917
13518
  * @returns The envelope.
12918
13519
  */
12919
- function readEnvelope(binary, offset, panning) {
13520
+ function readEnvelope$1(binary, offset, panning) {
12920
13521
  const pointsOffset = offset + (panning ? 177 : 129);
12921
13522
  const count = Math.min(12, binary[offset + (panning ? 226 : 225)]);
12922
13523
  const settings = offset + (panning ? 230 : 227);
@@ -12930,10 +13531,12 @@ function readEnvelope(binary, offset, panning) {
12930
13531
  value: readLittleEndian(binary, 2, pointsOffset + p * 4 + 2)
12931
13532
  });
12932
13533
  const hasLoop = (type & 4) !== 0 && loopEnd < count && loopStart <= loopEnd;
13534
+ const sustainPoint = (type & 2) !== 0 && sustain < count ? sustain : -1;
12933
13535
  return {
12934
13536
  enabled: (type & 1) !== 0 && count > 0,
12935
13537
  points,
12936
- sustainPoint: (type & 2) !== 0 && sustain < count ? sustain : -1,
13538
+ sustainPoint,
13539
+ sustainStart: sustainPoint,
12937
13540
  loopStart: hasLoop ? loopStart : -1,
12938
13541
  loopEnd: hasLoop ? loopEnd : -1
12939
13542
  };
@@ -13034,8 +13637,8 @@ var FastTrackerModule = class extends ProTrackerModule {
13034
13637
  const sample = binary[offset + 33 + n];
13035
13638
  if (sample < sampleCount) instrument.sampleMap[n] = firstSample + sample;
13036
13639
  }
13037
- instrument.volumeEnvelope = readEnvelope(binary, offset, false);
13038
- instrument.panningEnvelope = readEnvelope(binary, offset, true);
13640
+ instrument.volumeEnvelope = readEnvelope$1(binary, offset, false);
13641
+ instrument.panningEnvelope = readEnvelope$1(binary, offset, true);
13039
13642
  const vibratoType = binary[offset + 235];
13040
13643
  const vibratoSweep = binary[offset + 236];
13041
13644
  const vibratoDepth = binary[offset + 237];
@@ -13423,7 +14026,7 @@ const SHARED_MEMORY_EFFECTS = /* @__PURE__ */ new Set([
13423
14026
  /**
13424
14027
  * The middle C rates set by the fine-tuning (S2x) effect.
13425
14028
  */
13426
- const FINETUNE_RATES = [
14029
+ const FINETUNE_RATES$1 = [
13427
14030
  7895,
13428
14031
  7941,
13429
14032
  7985,
@@ -13733,7 +14336,7 @@ var ScreamTrackerModule = class extends TrackerModule {
13733
14336
  }
13734
14337
  }
13735
14338
  const param = channel.rowParam;
13736
- if (channel.rowEffect === ScreamTrackerEffects.extended && param >> 4 === ScreamTrackerExtendedEffects.finetune) channel.finetune = FINETUNE_RATES[param & 15];
14339
+ if (channel.rowEffect === ScreamTrackerEffects.extended && param >> 4 === ScreamTrackerExtendedEffects.finetune) channel.finetune = FINETUNE_RATES$1[param & 15];
13737
14340
  const note = channel.rowNote;
13738
14341
  if (note === 253) channel.stop = true;
13739
14342
  else if (note !== 0) {
@@ -13799,6 +14402,2915 @@ var ScreamTrackerModule = class extends TrackerModule {
13799
14402
  } else if (!firstTick || this.fastVolumeSlides) channel.slideVolume(down ? -down : up);
13800
14403
  }
13801
14404
  };
14405
+ // src/midi/read/tracker/impulse_tracker_channel.ts
14406
+ /**
14407
+ * @license
14408
+ * Parts of this file are ported from the sound library of OpenMPT (https://openmpt.org/).
14409
+ * OpenMPT is distributed under the BSD license below.
14410
+ *
14411
+ * Copyright (c) 2004-2026, OpenMPT Project Developers and Contributors
14412
+ * Copyright (c) 1997-2003, Olivier Lapicque
14413
+ * All rights reserved.
14414
+ *
14415
+ * Redistribution and use in source and binary forms, with or without
14416
+ * modification, are permitted provided that the following conditions are met:
14417
+ * * Redistributions of source code must retain the above copyright
14418
+ * notice, this list of conditions and the following disclaimer.
14419
+ * * Redistributions in binary form must reproduce the above copyright
14420
+ * notice, this list of conditions and the following disclaimer in the
14421
+ * documentation and/or other materials provided with the distribution.
14422
+ * * Neither the name of the OpenMPT project nor the
14423
+ * names of its contributors may be used to endorse or promote products
14424
+ * derived from this software without specific prior written permission.
14425
+ *
14426
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
14427
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14428
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
14429
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
14430
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14431
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
14432
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
14433
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
14434
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14435
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14436
+ */
14437
+ /**
14438
+ * The playback state of an Impulse Tracker channel or background voice.
14439
+ * Follows the channel model of OpenMPT, with volumes scaled to 0-64.
14440
+ */
14441
+ var ImpulseTrackerChannel = class extends TrackerChannel {
14442
+ /**
14443
+ * The channel volume (0-64), set with Mxx.
14444
+ */
14445
+ channelVolume;
14446
+ /**
14447
+ * The sample global volume multiplied by the instrument global volume (0-64).
14448
+ */
14449
+ instrumentVolume = 64;
14450
+ volumeSwing = 0;
14451
+ panningSwing = 0;
14452
+ cutoffSwing = 0;
14453
+ resonanceSwing = 0;
14454
+ /**
14455
+ * The fadeout volume (0-65,536).
14456
+ */
14457
+ fadeout = 0;
14458
+ /**
14459
+ * The pattern note used for pitch-pan separation and duplicate checks, 0 if none.
14460
+ * Starts at C-0, so a lone instrument number at the start plays that note.
14461
+ */
14462
+ note = 1;
14463
+ /**
14464
+ * The last note of the pattern, used by note-less instrument numbers.
14465
+ */
14466
+ newNote = 1;
14467
+ lastNote = 0;
14468
+ /**
14469
+ * The one-based instrument to change to on the next note, 0 if none.
14470
+ */
14471
+ newInstrument = 0;
14472
+ /**
14473
+ * The last instrument number of the pattern.
14474
+ */
14475
+ oldInstrument = 0;
14476
+ keyOff = true;
14477
+ noteFade = true;
14478
+ /**
14479
+ * If the sample's sustain loop is active.
14480
+ */
14481
+ sustainLoop = false;
14482
+ /**
14483
+ * If the sample plays backwards (S9F).
14484
+ */
14485
+ reverse = false;
14486
+ surround = false;
14487
+ /**
14488
+ * If the sample was playing on the previous tick (OpenMPT's IsSamplePlaying).
14489
+ * Unlike {@link playing}, a stopped sample counts as playing until the next tick, except after a note cut.
14490
+ */
14491
+ active = false;
14492
+ /**
14493
+ * Set when a note starts on this tick (OpenMPT's triggerNote).
14494
+ */
14495
+ triggered = false;
14496
+ /**
14497
+ * If this tick is the first one of the row's effects, which moves with a note delay.
14498
+ */
14499
+ isFirstTick = false;
14500
+ newNoteAction = 0;
14501
+ volumeEnvelopeState = {
14502
+ position: 0,
14503
+ enabled: false
14504
+ };
14505
+ panningEnvelopeState = {
14506
+ position: 0,
14507
+ enabled: false
14508
+ };
14509
+ pitchEnvelopeState = {
14510
+ position: 0,
14511
+ enabled: false
14512
+ };
14513
+ /**
14514
+ * The key off flag of the previous tick, used by the envelope sustain loops.
14515
+ */
14516
+ previousKeyOff = false;
14517
+ /**
14518
+ * The panning to restore on the next note after pitch-pan separation, plus one (0 if none).
14519
+ */
14520
+ restorePanning = 0;
14521
+ restoreCutoff = 0;
14522
+ restoreResonance = 0;
14523
+ /**
14524
+ * The tone portamento target frequency, 0 if none.
14525
+ */
14526
+ portamentoTarget = 0;
14527
+ /**
14528
+ * The tone portamento speed.
14529
+ */
14530
+ portamentoSlide = 0;
14531
+ portamentoActive = false;
14532
+ glissando = false;
14533
+ autoVibratoDepth = 0;
14534
+ autoVibratoPos = 0;
14535
+ /**
14536
+ * The final playback rate in Hertz, with every pitch effect applied.
14537
+ */
14538
+ outputFrequency = 0;
14539
+ vibratoActive = false;
14540
+ tremoloActive = false;
14541
+ vibratoType = 0;
14542
+ vibratoPos = 0;
14543
+ tremoloType = 0;
14544
+ tremoloPos = 0;
14545
+ panbrelloType = 0;
14546
+ panbrelloPos = 0;
14547
+ panbrelloSpeed = 0;
14548
+ panbrelloDepth = 0;
14549
+ /**
14550
+ * The panbrello offset that stays until the next note or panning command.
14551
+ */
14552
+ panbrelloOffset = 0;
14553
+ panbrelloRandom = 0;
14554
+ arpeggioParam = 0;
14555
+ /**
14556
+ * The effect active on this row (arpeggio and tremor are only processed while set).
14557
+ */
14558
+ command = 0;
14559
+ tremorParam = 0;
14560
+ tremorCount = 0;
14561
+ retriggerParam = 1;
14562
+ retriggerCount = 0;
14563
+ cutoff = 127;
14564
+ resonance = 0;
14565
+ filterEnabled = false;
14566
+ /**
14567
+ * The cutoff with the filter envelope applied (0-127), used while the filter is enabled.
14568
+ */
14569
+ filterCutoffValue = 127;
14570
+ activeMacro = 0;
14571
+ oldVolumeSlide = 0;
14572
+ oldFineVolume = 0;
14573
+ oldPortamento = 0;
14574
+ oldVolumeColumn = 0;
14575
+ oldChannelVolumeSlide = 0;
14576
+ oldPanningSlide = 0;
14577
+ oldGlobalVolumeSlide = 0;
14578
+ oldOffset = 0;
14579
+ oldHighOffset = 0;
14580
+ oldTempo = 0;
14581
+ oldExtended = 0;
14582
+ /**
14583
+ * The index of the playing instrument, -1 if none.
14584
+ */
14585
+ instrumentIndex = -1;
14586
+ constructor(index, panning, channelVolume) {
14587
+ super(index, panning);
14588
+ this.channelVolume = channelVolume;
14589
+ this.volume = 0;
14590
+ }
14591
+ /**
14592
+ * If a sample is assigned and has not stopped (OpenMPT's nonzero sample length).
14593
+ * Impulse Tracker stops channels when a sample without a loop ends, after note cuts,
14594
+ * new note actions and when the fadeout has reached zero.
14595
+ */
14596
+ get playing() {
14597
+ return this.sample !== void 0 && this.samplePosition !== Infinity;
14598
+ }
14599
+ /**
14600
+ * Resets the envelope positions.
14601
+ */
14602
+ resetEnvelopes() {
14603
+ this.volumeEnvelopeState.position = 0;
14604
+ this.panningEnvelopeState.position = 0;
14605
+ this.pitchEnvelopeState.position = 0;
14606
+ }
14607
+ /**
14608
+ * Creates a copy of this channel with its own envelope states.
14609
+ */
14610
+ clone() {
14611
+ const copy = super.clone();
14612
+ copy.volumeEnvelopeState = { ...this.volumeEnvelopeState };
14613
+ copy.panningEnvelopeState = { ...this.panningEnvelopeState };
14614
+ copy.pitchEnvelopeState = { ...this.pitchEnvelopeState };
14615
+ return copy;
14616
+ }
14617
+ };
14618
+ // src/midi/read/tracker/impulse_tracker_samples.ts
14619
+ /**
14620
+ * @license
14621
+ * Parts of this file are ported from the sound library of OpenMPT (https://openmpt.org/).
14622
+ * OpenMPT is distributed under the BSD license below.
14623
+ *
14624
+ * Copyright (c) 2004-2026, OpenMPT Project Developers and Contributors
14625
+ * Copyright (c) 1997-2003, Olivier Lapicque
14626
+ * All rights reserved.
14627
+ *
14628
+ * Redistribution and use in source and binary forms, with or without
14629
+ * modification, are permitted provided that the following conditions are met:
14630
+ * * Redistributions of source code must retain the above copyright
14631
+ * notice, this list of conditions and the following disclaimer.
14632
+ * * Redistributions in binary form must reproduce the above copyright
14633
+ * notice, this list of conditions and the following disclaimer in the
14634
+ * documentation and/or other materials provided with the distribution.
14635
+ * * Neither the name of the OpenMPT project nor the
14636
+ * names of its contributors may be used to endorse or promote products
14637
+ * derived from this software without specific prior written permission.
14638
+ *
14639
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
14640
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14641
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
14642
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
14643
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14644
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
14645
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
14646
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
14647
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14648
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14649
+ */
14650
+ /**
14651
+ * The block size of compressed samples, in sample points.
14652
+ */
14653
+ const COMPRESSED_BLOCK_8_BIT = 32768;
14654
+ const COMPRESSED_BLOCK_16_BIT = 16384;
14655
+ /**
14656
+ * The conversion value of ModPlug ADPCM compressed samples.
14657
+ */
14658
+ const CONVERSION_ADPCM = 255;
14659
+ /**
14660
+ * Decodes one channel of an IT2.14 or IT2.15 compressed sample.
14661
+ * The data is split into blocks, each starting with its compressed size and resetting the decoder.
14662
+ * Every block is a little-endian bit stream of variable width values, with special values changing the width.
14663
+ * @param binary The file data.
14664
+ * @param offset The offset of the first block.
14665
+ * @param length The number of sample points.
14666
+ * @param is16Bit If the sample is 16-bit.
14667
+ * @param doubleDelta If the sample uses IT2.15 compression (the values are integrated twice).
14668
+ * @returns The decoded data and the offset after the last block.
14669
+ */
14670
+ function decompressSample(binary, offset, length, is16Bit, doubleDelta) {
14671
+ const data = new Float32Array(length);
14672
+ const sampleBits = is16Bit ? 16 : 8;
14673
+ const baseWidth = sampleBits + 1;
14674
+ const blockSize = is16Bit ? COMPRESSED_BLOCK_16_BIT : COMPRESSED_BLOCK_8_BIT;
14675
+ const signShift = 32 - sampleBits;
14676
+ const scale = 1 / (1 << sampleBits - 1);
14677
+ let position = offset;
14678
+ let written = 0;
14679
+ while (written < length && position + 2 <= binary.length) {
14680
+ const blockEnd = Math.min(binary.length, position + 2 + readLittleEndian(binary, 2, position));
14681
+ let bitPosition = (position + 2) * 8;
14682
+ const bitEnd = blockEnd * 8;
14683
+ const blockLength = Math.min(blockSize, length - written);
14684
+ let width = baseWidth;
14685
+ let delta = 0;
14686
+ let doubleDeltaValue = 0;
14687
+ let decoded = 0;
14688
+ while (decoded < blockLength) {
14689
+ if (bitPosition + width > bitEnd) break;
14690
+ let value = 0;
14691
+ for (let bit = 0; bit < width; bit++) {
14692
+ value |= (binary[bitPosition >> 3] >> (bitPosition & 7) & 1) << bit;
14693
+ bitPosition++;
14694
+ }
14695
+ if (width < 7) {
14696
+ if (value === 1 << width - 1) {
14697
+ const widthBits = is16Bit ? 4 : 3;
14698
+ let newWidth = 1;
14699
+ for (let bit = 0; bit < widthBits; bit++) {
14700
+ newWidth += (binary[bitPosition >> 3] >> (bitPosition & 7) & 1) << bit;
14701
+ bitPosition++;
14702
+ }
14703
+ width = newWidth < width ? newWidth : newWidth + 1;
14704
+ continue;
14705
+ }
14706
+ } else if (width < baseWidth) {
14707
+ const border = ((is16Bit ? 65535 : 255) >> baseWidth - width) - (is16Bit ? 8 : 4);
14708
+ if (value > border && value <= border + (is16Bit ? 16 : 8)) {
14709
+ const newWidth = value - border;
14710
+ width = newWidth < width ? newWidth : newWidth + 1;
14711
+ continue;
14712
+ }
14713
+ } else if (width === baseWidth) {
14714
+ if (value & 1 << sampleBits) {
14715
+ width = value + 1 & 255;
14716
+ continue;
14717
+ }
14718
+ } else break;
14719
+ if (width === 0) break;
14720
+ const bits = Math.min(width, sampleBits);
14721
+ value = value << 32 - bits >> 32 - bits;
14722
+ delta = delta + value << signShift >> signShift;
14723
+ doubleDeltaValue = doubleDeltaValue + delta << signShift >> signShift;
14724
+ data[written++] = (doubleDelta ? doubleDeltaValue : delta) * scale;
14725
+ decoded++;
14726
+ }
14727
+ position = blockEnd;
14728
+ }
14729
+ return {
14730
+ data,
14731
+ end: position
14732
+ };
14733
+ }
14734
+ /**
14735
+ * Reads one channel of uncompressed PCM sample data.
14736
+ * @param binary The file data.
14737
+ * @param offset The offset of the data.
14738
+ * @param length The number of sample points.
14739
+ * @param is16Bit If the sample is 16-bit.
14740
+ * @param signed If the data is signed.
14741
+ * @param bigEndian If 16-bit data is big-endian.
14742
+ * @param delta If the data is delta-encoded.
14743
+ */
14744
+ function readPCM(binary, offset, length, is16Bit, signed, bigEndian, delta) {
14745
+ const bytes = is16Bit ? 2 : 1;
14746
+ const available = Math.max(0, Math.min(length, Math.floor((binary.length - offset) / bytes)));
14747
+ const data = new Float32Array(length);
14748
+ const bits = is16Bit ? 16 : 8;
14749
+ const shift = 32 - bits;
14750
+ let last = 0;
14751
+ for (let s = 0; s < available; s++) {
14752
+ let value;
14753
+ if (is16Bit) {
14754
+ const p = offset + s * 2;
14755
+ value = bigEndian ? binary[p] << 8 | binary[p + 1] : binary[p] | binary[p + 1] << 8;
14756
+ } else value = binary[offset + s];
14757
+ if (!signed) value ^= 1 << bits - 1;
14758
+ value = value << shift >> shift;
14759
+ if (delta) {
14760
+ value = last + value << shift >> shift;
14761
+ last = value;
14762
+ }
14763
+ data[s] = value / (1 << bits - 1);
14764
+ }
14765
+ return data;
14766
+ }
14767
+ /**
14768
+ * Reads a loop from a sample header, validating it against the sample length.
14769
+ * @param binary The file data.
14770
+ * @param offset The offset of the loop start (the end follows it).
14771
+ * @param enabled If the loop flag is set.
14772
+ * @param pingPong If the ping-pong flag is set.
14773
+ * @param length The sample length.
14774
+ */
14775
+ function readLoop(binary, offset, enabled, pingPong, length) {
14776
+ const start = readLittleEndian(binary, 4, offset);
14777
+ const end = Math.min(length, readLittleEndian(binary, 4, offset + 4));
14778
+ const type = !enabled || start >= end ? TrackerLoopTypes.none : pingPong ? TrackerLoopTypes.pingPong : TrackerLoopTypes.forward;
14779
+ return type === TrackerLoopTypes.none ? {
14780
+ type,
14781
+ start: 0,
14782
+ end: 0
14783
+ } : {
14784
+ type,
14785
+ start,
14786
+ end
14787
+ };
14788
+ }
14789
+ /**
14790
+ * Reads an Impulse Tracker sample header and its data.
14791
+ * Supports 8 and 16-bit, signed and unsigned, big-endian, delta, IT2.14/IT2.15 compressed
14792
+ * and ModPlug ADPCM data, and stereo samples.
14793
+ * @param binary The file data.
14794
+ * @param offset The sample header offset.
14795
+ * @param trackerVersion The Cwt/v field of the module header.
14796
+ * @param muteMissingData If samples without the "sample data present" flag are empty.
14797
+ * Impulse Tracker sometimes keeps the length of deleted samples, but other trackers forget to set the flag.
14798
+ * @returns The sample and the offset after its data (or its header).
14799
+ */
14800
+ function readImpulseTrackerSample(binary, offset, trackerVersion, muteMissingData) {
14801
+ const name = readBinaryString(binary, 26, offset + 20);
14802
+ let c5Speed = readLittleEndian(binary, 4, offset + 60) || 8363;
14803
+ c5Speed = Math.max(256, c5Speed);
14804
+ const defaultPanning = binary[offset + 47];
14805
+ const sample = {
14806
+ name,
14807
+ data: /* @__PURE__ */ new Float32Array(0),
14808
+ loopType: TrackerLoopTypes.none,
14809
+ loopStart: 0,
14810
+ loopEnd: 0,
14811
+ volume: Math.min(64, binary[offset + 19]),
14812
+ globalVolume: Math.min(64, binary[offset + 17]),
14813
+ panning: defaultPanning & 128 ? Math.min(256, (defaultPanning & 127) * 4) : -1,
14814
+ finetune: c5Speed,
14815
+ relativeNote: 0,
14816
+ middleCRate: c5Speed,
14817
+ vibratoType: binary[offset + 79] & 7,
14818
+ vibratoSweep: binary[offset + 78],
14819
+ vibratoDepth: binary[offset + 77] & 127,
14820
+ vibratoRate: binary[offset + 76]
14821
+ };
14822
+ const flags = binary[offset + 18];
14823
+ const headerEnd = offset + 80;
14824
+ if (headerEnd > binary.length) return {
14825
+ sample,
14826
+ end: headerEnd
14827
+ };
14828
+ if (muteMissingData && (flags & 1) === 0) return {
14829
+ sample,
14830
+ end: headerEnd
14831
+ };
14832
+ const conversion = binary[offset + 46];
14833
+ const is16Bit = (flags & 2) !== 0;
14834
+ const isStereo = (flags & 4) !== 0 && trackerVersion >= 532;
14835
+ const isCompressed = (flags & 8) !== 0;
14836
+ const length = readLittleEndian(binary, 4, offset + 48);
14837
+ const dataOffset = readLittleEndian(binary, 4, offset + 72);
14838
+ if (length === 0 || dataOffset >= binary.length) return {
14839
+ sample,
14840
+ end: headerEnd
14841
+ };
14842
+ const channels = new Array();
14843
+ let end;
14844
+ if (isCompressed) {
14845
+ const doubleDelta = (conversion & 4) !== 0;
14846
+ let position = dataOffset;
14847
+ for (let c = 0; c < (isStereo ? 2 : 1); c++) {
14848
+ const decoded = decompressSample(binary, position, Math.min(length, (binary.length - position) * 8), is16Bit, doubleDelta);
14849
+ channels.push(decoded.data);
14850
+ position = decoded.end;
14851
+ }
14852
+ end = position;
14853
+ } else if (!is16Bit && conversion === CONVERSION_ADPCM) {
14854
+ channels.push(decodeADPCM(binary, dataOffset, Math.max(0, Math.min(length, (binary.length - dataOffset - 16) * 2))));
14855
+ end = dataOffset + 16 + Math.ceil(length / 2);
14856
+ } else {
14857
+ const bytes = (is16Bit ? 2 : 1) * length;
14858
+ const readLength = Math.min(length, Math.floor((binary.length - dataOffset) / (is16Bit ? 2 : 1)));
14859
+ for (let c = 0; c < (isStereo ? 2 : 1); c++) channels.push(readPCM(binary, dataOffset + c * bytes, readLength, is16Bit, (conversion & 1) !== 0, (conversion & 2) !== 0, (conversion & 4) !== 0));
14860
+ end = dataOffset + bytes * channels.length;
14861
+ }
14862
+ sample.data = channels[0];
14863
+ if (channels.length > 1) sample.rightData = channels[1];
14864
+ const sampleLength = sample.data.length;
14865
+ const loop = readLoop(binary, offset + 52, (flags & 16) !== 0, (flags & 64) !== 0, sampleLength);
14866
+ sample.loopType = loop.type;
14867
+ sample.loopStart = loop.start;
14868
+ sample.loopEnd = loop.end;
14869
+ const sustain = readLoop(binary, offset + 64, (flags & 32) !== 0, (flags & 128) !== 0, sampleLength);
14870
+ if (sustain.type !== TrackerLoopTypes.none) {
14871
+ sample.sustainLoopType = sustain.type;
14872
+ sample.sustainLoopStart = sustain.start;
14873
+ sample.sustainLoopEnd = sustain.end;
14874
+ }
14875
+ return {
14876
+ sample,
14877
+ end: Math.max(headerEnd, end)
14878
+ };
14879
+ }
14880
+ // src/midi/read/tracker/impulsetracker.ts
14881
+ /**
14882
+ * @license
14883
+ * Parts of this file are ported from the sound library of OpenMPT (https://openmpt.org/).
14884
+ * OpenMPT is distributed under the BSD license below.
14885
+ *
14886
+ * Copyright (c) 2004-2026, OpenMPT Project Developers and Contributors
14887
+ * Copyright (c) 1997-2003, Olivier Lapicque
14888
+ * All rights reserved.
14889
+ *
14890
+ * Redistribution and use in source and binary forms, with or without
14891
+ * modification, are permitted provided that the following conditions are met:
14892
+ * * Redistributions of source code must retain the above copyright
14893
+ * notice, this list of conditions and the following disclaimer.
14894
+ * * Redistributions in binary form must reproduce the above copyright
14895
+ * notice, this list of conditions and the following disclaimer in the
14896
+ * documentation and/or other materials provided with the distribution.
14897
+ * * Neither the name of the OpenMPT project nor the
14898
+ * names of its contributors may be used to endorse or promote products
14899
+ * derived from this software without specific prior written permission.
14900
+ *
14901
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
14902
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
14903
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
14904
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
14905
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
14906
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
14907
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
14908
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
14909
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14910
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14911
+ */
14912
+ /**
14913
+ * The Impulse Tracker effects (letters converted to numbers, A = 1).
14914
+ */
14915
+ const ImpulseTrackerEffects = {
14916
+ speed: 1,
14917
+ positionJump: 2,
14918
+ patternBreak: 3,
14919
+ volumeSlide: 4,
14920
+ portamentoDown: 5,
14921
+ portamentoUp: 6,
14922
+ tonePortamento: 7,
14923
+ vibrato: 8,
14924
+ tremor: 9,
14925
+ arpeggio: 10,
14926
+ vibratoVolumeSlide: 11,
14927
+ tonePortamentoVolumeSlide: 12,
14928
+ channelVolume: 13,
14929
+ channelVolumeSlide: 14,
14930
+ sampleOffset: 15,
14931
+ panningSlide: 16,
14932
+ retrigger: 17,
14933
+ tremolo: 18,
14934
+ extended: 19,
14935
+ tempo: 20,
14936
+ fineVibrato: 21,
14937
+ globalVolume: 22,
14938
+ globalVolumeSlide: 23,
14939
+ panning: 24,
14940
+ panbrello: 25,
14941
+ midiMacro: 26,
14942
+ extendedParameter: 27,
14943
+ smoothMidiMacro: 28,
14944
+ delayCut: 29
14945
+ };
14946
+ /**
14947
+ * The Impulse Tracker extended (Sxy) effects.
14948
+ */
14949
+ const ImpulseTrackerExtendedEffects = {
14950
+ glissando: 1,
14951
+ finetune: 2,
14952
+ vibratoWaveform: 3,
14953
+ tremoloWaveform: 4,
14954
+ panbrelloWaveform: 5,
14955
+ fineRowDelay: 6,
14956
+ instrumentControl: 7,
14957
+ panning: 8,
14958
+ soundControl: 9,
14959
+ highOffset: 10,
14960
+ patternLoop: 11,
14961
+ noteCut: 12,
14962
+ noteDelay: 13,
14963
+ rowDelay: 14,
14964
+ activeMacro: 15
14965
+ };
14966
+ /**
14967
+ * The volume column commands, decoded from the volume byte.
14968
+ */
14969
+ const VolumeCommands = {
14970
+ none: 0,
14971
+ volume: 1,
14972
+ panning: 2,
14973
+ fineVolumeUp: 3,
14974
+ fineVolumeDown: 4,
14975
+ volumeSlideUp: 5,
14976
+ volumeSlideDown: 6,
14977
+ portamentoDown: 7,
14978
+ portamentoUp: 8,
14979
+ tonePortamento: 9,
14980
+ vibratoDepth: 10
14981
+ };
14982
+ /**
14983
+ * The new note actions and the duplicate check actions.
14984
+ */
14985
+ const NoteActions = {
14986
+ cut: 0,
14987
+ continue: 1,
14988
+ noteOff: 2,
14989
+ noteFade: 3
14990
+ };
14991
+ /**
14992
+ * The maximum number of channels in an Impulse Tracker module.
14993
+ */
14994
+ const MAX_CHANNELS = 64;
14995
+ /**
14996
+ * The maximum number of envelope points.
14997
+ */
14998
+ const MAX_ENVELOPE_POINTS = 25;
14999
+ /**
15000
+ * Note fade (~~~ in Impulse Tracker), starts the instrument fadeout.
15001
+ */
15002
+ const NOTE_FADE = 252;
15003
+ /**
15004
+ * The one-based C-5 note, which plays the samples at their middle C rate.
15005
+ */
15006
+ const MIDDLE_C_NOTE = 61;
15007
+ /**
15008
+ * The tone portamento speeds of the volume column (gx).
15009
+ */
15010
+ const VOLUME_COLUMN_PORTAMENTO = [
15011
+ 0,
15012
+ 1,
15013
+ 4,
15014
+ 8,
15015
+ 16,
15016
+ 32,
15017
+ 64,
15018
+ 96,
15019
+ 128,
15020
+ 255,
15021
+ 255,
15022
+ 255,
15023
+ 255,
15024
+ 255,
15025
+ 255,
15026
+ 255
15027
+ ];
15028
+ /**
15029
+ * The middle C rates of the S2x finetune values.
15030
+ */
15031
+ const FINETUNE_RATES = [
15032
+ 7895,
15033
+ 7941,
15034
+ 7985,
15035
+ 8046,
15036
+ 8107,
15037
+ 8169,
15038
+ 8232,
15039
+ 8280,
15040
+ 8363,
15041
+ 8413,
15042
+ 8463,
15043
+ 8529,
15044
+ 8581,
15045
+ 8651,
15046
+ 8723,
15047
+ 8757
15048
+ ];
15049
+ /**
15050
+ * The volume multipliers (in 1/16) and offsets of the retrigger effect.
15051
+ */
15052
+ const RETRIGGER_MULTIPLIERS = [
15053
+ 0,
15054
+ 0,
15055
+ 0,
15056
+ 0,
15057
+ 0,
15058
+ 0,
15059
+ 10,
15060
+ 8,
15061
+ 0,
15062
+ 0,
15063
+ 0,
15064
+ 0,
15065
+ 0,
15066
+ 0,
15067
+ 24,
15068
+ 32
15069
+ ];
15070
+ const RETRIGGER_OFFSETS = [
15071
+ 0,
15072
+ -1,
15073
+ -2,
15074
+ -4,
15075
+ -8,
15076
+ -16,
15077
+ 0,
15078
+ 0,
15079
+ 0,
15080
+ 1,
15081
+ 2,
15082
+ 4,
15083
+ 8,
15084
+ 16,
15085
+ 0,
15086
+ 0
15087
+ ];
15088
+ /**
15089
+ * The Amiga period of a 8363 Hz middle C, used by the Amiga frequency slides.
15090
+ */
15091
+ const AMIGA_CONSTANT = 14317456;
15092
+ /**
15093
+ * The OpenMPT mixing levels.
15094
+ */
15095
+ const MixLevels = {
15096
+ original: 0,
15097
+ v117RC1: 1,
15098
+ v117RC2: 2,
15099
+ v117RC3: 3,
15100
+ compatible: 4
15101
+ };
15102
+ /**
15103
+ * The channel count dependent attenuation of the old OpenMPT mixing levels, for every two channels.
15104
+ */
15105
+ const PRE_AMP_TABLE = [
15106
+ 96,
15107
+ 96,
15108
+ 96,
15109
+ 112,
15110
+ 128,
15111
+ 136,
15112
+ 144,
15113
+ 152,
15114
+ 160,
15115
+ 164,
15116
+ 168,
15117
+ 172,
15118
+ 176,
15119
+ 180,
15120
+ 184,
15121
+ 188
15122
+ ];
15123
+ /**
15124
+ * The size of one MIDI macro string.
15125
+ */
15126
+ const MACRO_LENGTH = 32;
15127
+ /**
15128
+ * The Impulse Tracker sine table (256 steps, -64 to 64).
15129
+ */
15130
+ const SINE_TABLE = /* @__PURE__ */ new Int8Array(256);
15131
+ for (let i = 0; i < 256; i++) SINE_TABLE[i] = Math.round(64 * Math.sin(i * Math.PI / 128));
15132
+ /**
15133
+ * The sample of an empty instrument keyboard slot that points to a sample that does not exist.
15134
+ */
15135
+ const EMPTY_SAMPLE = {
15136
+ name: "",
15137
+ data: /* @__PURE__ */ new Float32Array(0),
15138
+ loopType: TrackerLoopTypes.none,
15139
+ loopStart: 0,
15140
+ loopEnd: 0,
15141
+ volume: 0,
15142
+ globalVolume: 0,
15143
+ panning: -1,
15144
+ finetune: 8363,
15145
+ relativeNote: 0,
15146
+ middleCRate: 8363,
15147
+ vibratoType: 0,
15148
+ vibratoSweep: 0,
15149
+ vibratoDepth: 0,
15150
+ vibratoRate: 0
15151
+ };
15152
+ /**
15153
+ * Background voices below this level (-60 dB) are stopped once they can only get quieter.
15154
+ */
15155
+ const INAUDIBLE_LEVEL = .001;
15156
+ /**
15157
+ * The sample rate the resonant filter is matched at. The OpenMPT reference renders use it.
15158
+ */
15159
+ const FILTER_SAMPLE_RATE = 44100;
15160
+ const isNote = (note) => note > 0 && note <= 120;
15161
+ /**
15162
+ * Decodes the volume column byte.
15163
+ * @param value The stored value, zero if the column is empty and the byte plus one otherwise.
15164
+ */
15165
+ function decodeVolume(value) {
15166
+ const v = value - 1;
15167
+ if (v < 0) return [VolumeCommands.none, 0];
15168
+ if (v <= 64) return [VolumeCommands.volume, v];
15169
+ if (v <= 74) return [VolumeCommands.fineVolumeUp, v - 65];
15170
+ if (v <= 84) return [VolumeCommands.fineVolumeDown, v - 75];
15171
+ if (v <= 94) return [VolumeCommands.volumeSlideUp, v - 85];
15172
+ if (v <= 104) return [VolumeCommands.volumeSlideDown, v - 95];
15173
+ if (v <= 114) return [VolumeCommands.portamentoDown, v - 105];
15174
+ if (v <= 124) return [VolumeCommands.portamentoUp, v - 115];
15175
+ if (v >= 128 && v <= 192) return [VolumeCommands.panning, v - 128];
15176
+ if (v >= 193 && v <= 202) return [VolumeCommands.tonePortamento, v - 193];
15177
+ if (v >= 203 && v <= 212) return [VolumeCommands.vibratoDepth, v - 203];
15178
+ return [VolumeCommands.none, 0];
15179
+ }
15180
+ /**
15181
+ * Creates an envelope, clamping the loop points to the existing points.
15182
+ * @param points The envelope points.
15183
+ * @param flags The flags (bit 0 enabled, bit 1 loop, bit 2 sustain loop, bit 3 carry).
15184
+ * @param loopStart The loop start point.
15185
+ * @param loopEnd The loop end point.
15186
+ * @param sustainStart The sustain loop start point.
15187
+ * @param sustainEnd The sustain loop end point.
15188
+ */
15189
+ function createEnvelope(points, flags, loopStart, loopEnd, sustainStart, sustainEnd) {
15190
+ const last = points.length - 1;
15191
+ const hasLoop = (flags & 2) !== 0 && last >= 0;
15192
+ const hasSustain = (flags & 4) !== 0 && last >= 0;
15193
+ loopStart = Math.min(loopStart, last);
15194
+ sustainStart = Math.min(sustainStart, last);
15195
+ return {
15196
+ enabled: (flags & 1) !== 0 && last >= 0,
15197
+ points,
15198
+ sustainPoint: hasSustain ? Math.min(last, Math.max(sustainEnd, sustainStart)) : -1,
15199
+ sustainStart: hasSustain ? sustainStart : -1,
15200
+ loopStart: hasLoop ? loopStart : -1,
15201
+ loopEnd: hasLoop ? Math.min(last, Math.max(loopEnd, loopStart)) : -1,
15202
+ carry: (flags & 8) !== 0
15203
+ };
15204
+ }
15205
+ /**
15206
+ * Reads an envelope of a new format (Impulse Tracker 2.00 and above) instrument.
15207
+ * @param binary The file data.
15208
+ * @param offset The envelope offset.
15209
+ * @param signed True for the panning and pitch envelopes (stored from -32 to 32).
15210
+ */
15211
+ function readEnvelope(binary, offset, signed) {
15212
+ const flags = binary[offset];
15213
+ const count = Math.min(MAX_ENVELOPE_POINTS, binary[offset + 1]);
15214
+ const points = new Array();
15215
+ for (let p = 0; p < count; p++) {
15216
+ const value = binary[offset + 6 + p * 3];
15217
+ let tick = readLittleEndian(binary, 2, offset + 7 + p * 3);
15218
+ const previous = points[p - 1];
15219
+ if (previous && tick < previous.tick && !(tick & 65280)) {
15220
+ tick |= previous.tick & 65280;
15221
+ if (tick < previous.tick) tick += 256;
15222
+ }
15223
+ points.push({
15224
+ value: Math.min(64, Math.max(0, signed ? (value << 24 >> 24) + 32 : value)),
15225
+ tick
15226
+ });
15227
+ }
15228
+ return createEnvelope(points, flags, binary[offset + 2], binary[offset + 3], binary[offset + 4], binary[offset + 5]);
15229
+ }
15230
+ /**
15231
+ * Matches the Impulse Tracker resonant filter to the synthesizer's filter.
15232
+ * Both are two-pole filters, so the synthesizer's cutoff and resonance are chosen to give the same poles.
15233
+ * @param cutoff The cutoff (0-127), already scaled by the filter envelope.
15234
+ * @param resonance The resonance (0-127).
15235
+ * @param extendedRange If the OpenMPT extended filter range is used.
15236
+ * @returns The cutoff in absolute cents and the resonance in centibels.
15237
+ */
15238
+ function matchFilter(cutoff, resonance, extendedRange) {
15239
+ const fs = FILTER_SAMPLE_RATE;
15240
+ const frequency = Math.min(fs / 2, Math.max(120, Math.min(2e4, 110 * Math.pow(2, .25 + cutoff / (extendedRange ? 20 : 24)))));
15241
+ const damping = Math.pow(10, -resonance * (24 / 128) / 20);
15242
+ let d;
15243
+ let e;
15244
+ if (extendedRange) {
15245
+ const r = 2 * Math.PI * frequency / fs;
15246
+ d = Math.min(2, (1 - 2 * damping) * r);
15247
+ d = (2 * damping - d) / r;
15248
+ e = 1 / (r * r);
15249
+ } else {
15250
+ const r = fs / (2 * Math.PI * frequency);
15251
+ d = damping * r + damping - 1;
15252
+ e = r * r;
15253
+ }
15254
+ const a1 = -(d + 2 * e) / (1 + d + e);
15255
+ const a2 = e / (1 + d + e);
15256
+ const alpha = (1 - a2) / (1 + a2);
15257
+ const w = Math.acos(Math.min(1, Math.max(-1, -a1 * (1 + alpha) / 2)));
15258
+ const q = Math.sin(w) / (2 * alpha);
15259
+ const hz = w * fs / (2 * Math.PI);
15260
+ return {
15261
+ cents: 1200 * Math.log2(Math.max(1, hz) / 8.176),
15262
+ centibels: Math.max(0, 30.1 + 200 * Math.log10(q))
15263
+ };
15264
+ }
15265
+ /**
15266
+ * Impulse Tracker module (IT) loader and player.
15267
+ *
15268
+ * The playback follows the Impulse Tracker compatible behavior of OpenMPT:
15269
+ * - Instrument and sample modes, new note actions (background voices on their own MIDI channels)
15270
+ * and duplicate checks, the volume, panning and pitch/filter envelopes with loops, sustain loops and carry,
15271
+ * fadeout, random volume and panning variation and pitch-pan separation.
15272
+ * - The resonant filter (instrument cutoff and resonance, filter envelope, Zxx and \xx MIDI macros).
15273
+ * - Sample sustain loops (switching to the regular loop on key off), stereo samples
15274
+ * and reversed playback (S9F), all through extra presets in the sound bank.
15275
+ * - Every effect, including the OpenMPT extensions to the IT format that change the playback.
15276
+ */
15277
+ var ImpulseTrackerModule = class extends TrackerModule {
15278
+ formatName = "Impulse Tracker IT";
15279
+ processRepeatedFirstTicks = true;
15280
+ jumpOverridesLoop = true;
15281
+ repeatPingPongEnd = true;
15282
+ linearPanLevel = true;
15283
+ linearSlides = false;
15284
+ oldEffects = false;
15285
+ /**
15286
+ * If Gxx does not share the memory of Exx and Fxx ("Compatible Gxx").
15287
+ */
15288
+ compatibleGxx = false;
15289
+ instrumentMode = false;
15290
+ stereo = true;
15291
+ extendedFilterRange = false;
15292
+ /**
15293
+ * If the retrigger effect also restarts samples that have stopped (ChibiTracker).
15294
+ */
15295
+ retriggerStoppedSamples = false;
15296
+ /**
15297
+ * The OpenMPT tempo mode (0 classic, 1 alternative, 2 modern).
15298
+ */
15299
+ tempoMode = 0;
15300
+ /**
15301
+ * The rows per beat, used by the modern tempo mode.
15302
+ */
15303
+ rowsPerBeat = 4;
15304
+ /**
15305
+ * Set with S9D, the filter is only used when an instrument enables it.
15306
+ */
15307
+ openMPTFilterMode = false;
15308
+ itInstruments = new Array();
15309
+ itSamples = new Array();
15310
+ /**
15311
+ * The initial channel volume of each channel (0-64).
15312
+ */
15313
+ channelVolumes = new Array();
15314
+ /**
15315
+ * The channels with surround panning at the start.
15316
+ */
15317
+ channelSurround = new Array();
15318
+ /**
15319
+ * The parametered (SFx) MIDI macros.
15320
+ */
15321
+ parameteredMacros = new Array(16).fill("");
15322
+ /**
15323
+ * The fixed (Z80-ZFF) MIDI macros.
15324
+ */
15325
+ fixedMacros = new Array(128).fill("");
15326
+ /**
15327
+ * The state of the random number generator, fixed so conversions are deterministic.
15328
+ */
15329
+ randomState = 305419896;
15330
+ /**
15331
+ * The background voice that was created last, used by the envelope carry with Compatible Gxx.
15332
+ */
15333
+ lastMovedVoice;
15334
+ /**
15335
+ * Checks if the file is an IT module.
15336
+ * @param binary The file data.
15337
+ */
15338
+ static isIT(binary) {
15339
+ return binary.length > 192 && readBinaryString(binary, 4, 0) === "IMPM";
15340
+ }
15341
+ /**
15342
+ * Parses an IT file.
15343
+ * @param binary The file data.
15344
+ */
15345
+ parse(binary) {
15346
+ this.title = readBinaryString(binary, 26, 4).trim();
15347
+ this.restartPosition = 0;
15348
+ const orderCount = readLittleEndian(binary, 2, 32);
15349
+ const instrumentCount = readLittleEndian(binary, 2, 34);
15350
+ const sampleCount = readLittleEndian(binary, 2, 36);
15351
+ const patternCount = readLittleEndian(binary, 2, 38);
15352
+ const trackerVersion = readLittleEndian(binary, 2, 40);
15353
+ const compatibleVersion = readLittleEndian(binary, 2, 42);
15354
+ const flags = readLittleEndian(binary, 2, 44);
15355
+ const special = readLittleEndian(binary, 2, 46);
15356
+ const reserved = readLittleEndian(binary, 4, 60);
15357
+ this.stereo = (flags & 1) !== 0;
15358
+ this.instrumentMode = (flags & 4) !== 0;
15359
+ this.linearSlides = (flags & 8) !== 0;
15360
+ this.oldEffects = (flags & 16) !== 0;
15361
+ this.compatibleGxx = (flags & 32) !== 0;
15362
+ this.extendedFilterRange = (flags & 4096) !== 0;
15363
+ this.initialGlobalVolume = Math.min(128, binary[48]) / 2;
15364
+ const mixVolume = Math.min(128, binary[49]);
15365
+ this.initialSpeed = binary[50] || 6;
15366
+ this.initialTempo = binary[51] >= 32 ? binary[51] : 125;
15367
+ this.madeWith = this.detectTracker(binary, trackerVersion, compatibleVersion, reserved);
15368
+ const muteMissingData = !(trackerVersion === 535 && compatibleVersion === 512 && reserved === 0) && trackerVersion >= 256 && trackerVersion <= 535 && (trackerVersion < 519 || reserved !== 0);
15369
+ for (let i = 0; i < orderCount; i++) {
15370
+ const order = binary[192 + i];
15371
+ if (order === 255) break;
15372
+ this.orders.push(order === 254 || order >= patternCount ? -1 : order);
15373
+ }
15374
+ const instrumentOffsets = 192 + orderCount;
15375
+ const sampleOffsets = instrumentOffsets + instrumentCount * 4;
15376
+ const patternOffsets = sampleOffsets + sampleCount * 4;
15377
+ this.readMacros(binary, patternOffsets + patternCount * 4, flags, special);
15378
+ const sampleNames = new Array();
15379
+ let extensionsOffset = 0;
15380
+ for (let i = 0; i < sampleCount; i++) {
15381
+ const offset = readLittleEndian(binary, 4, sampleOffsets + i * 4);
15382
+ let sample = {
15383
+ ...EMPTY_SAMPLE,
15384
+ data: /* @__PURE__ */ new Float32Array(0)
15385
+ };
15386
+ if (offset > 0 && offset < binary.length) {
15387
+ const read = readImpulseTrackerSample(binary, offset, trackerVersion, muteMissingData);
15388
+ sample = read.sample;
15389
+ extensionsOffset = Math.max(extensionsOffset, read.end);
15390
+ }
15391
+ this.itSamples.push(sample);
15392
+ this.samples.push(sample);
15393
+ sampleNames.push(sample.name);
15394
+ }
15395
+ const instrumentNames = new Array();
15396
+ if (this.instrumentMode) for (let i = 0; i < instrumentCount; i++) {
15397
+ const offset = readLittleEndian(binary, 4, instrumentOffsets + i * 4);
15398
+ const instrument = offset > 0 && offset + 560 <= binary.length ? this.readInstrument(binary, offset, compatibleVersion) : void 0;
15399
+ this.itInstruments.push(instrument);
15400
+ instrumentNames.push(instrument?.name ?? "");
15401
+ }
15402
+ const fullPatterns = new Array();
15403
+ const usedChannels = new Array(MAX_CHANNELS).fill(false);
15404
+ for (let p = 0; p < patternCount; p++) {
15405
+ const offset = readLittleEndian(binary, 4, patternOffsets + p * 4);
15406
+ const rows = offset > 0 && offset + 8 <= binary.length ? readLittleEndian(binary, 2, offset + 2) : 0;
15407
+ if (rows < 1 || rows > 1024) {
15408
+ fullPatterns.push(new TrackerPattern(64, MAX_CHANNELS));
15409
+ continue;
15410
+ }
15411
+ const pattern = new TrackerPattern(rows, MAX_CHANNELS);
15412
+ fullPatterns.push(pattern);
15413
+ extensionsOffset = Math.max(extensionsOffset, offset + 8 + readLittleEndian(binary, 2, offset));
15414
+ this.readPattern(binary, offset, pattern, usedChannels, trackerVersion);
15415
+ }
15416
+ const channelMap = new Array();
15417
+ const mutedChannels = new Array();
15418
+ for (let c = 0; c < MAX_CHANNELS; c++) {
15419
+ if (!usedChannels[c]) continue;
15420
+ const panning = binary[64 + c];
15421
+ channelMap.push(c);
15422
+ mutedChannels.push(panning >= 128);
15423
+ const surround = (panning & 127) === 100;
15424
+ this.channelSurround.push(surround);
15425
+ this.channelPanning.push(surround ? 128 : Math.min(256, (panning & 127) * 4));
15426
+ this.channelVolumes.push(Math.min(64, binary[128 + c]));
15427
+ }
15428
+ this.channelCount = channelMap.length;
15429
+ for (const full of fullPatterns) {
15430
+ const pattern = new TrackerPattern(full.rows, this.channelCount);
15431
+ for (let row = 0; row < full.rows; row++) for (const [c, source] of channelMap.entries()) {
15432
+ const offset = full.getCellOffset(row, source);
15433
+ const muted = mutedChannels[c];
15434
+ pattern.setCell(row, c, muted ? 0 : full.getNote(offset), muted ? 0 : full.getInstrument(offset), muted ? 0 : full.getVolume(offset), full.getEffect(offset), full.getParam(offset));
15435
+ }
15436
+ this.patterns.push(pattern);
15437
+ }
15438
+ let modPlugMade = (trackerVersion & 61440) === 20480 && readBinaryString(binary, 4, 60) === "OMPT" || compatibleVersion === 2184 || trackerVersion === 2184 || trackerVersion === 532 && compatibleVersion === 514 && reserved === 0 || trackerVersion === 535 && compatibleVersion === 512 && reserved === 0;
15439
+ let highestChannel = usedChannels.lastIndexOf(true) + 1;
15440
+ const extensions = this.readExtensions(binary, extensionsOffset, this.instrumentMode ? instrumentCount : 0);
15441
+ let mixLevels = -1;
15442
+ const chibiTracker = readBinaryString(binary, 4, 60) === "CHBI";
15443
+ let samplePreAmp = chibiTracker ? mixVolume / 2 : mixVolume;
15444
+ this.retriggerStoppedSamples = chibiTracker;
15445
+ if (extensions) {
15446
+ modPlugMade = true;
15447
+ mixLevels = extensions.mixLevels;
15448
+ if (extensions.samplePreAmp >= 0) samplePreAmp = Math.min(2e3, extensions.samplePreAmp);
15449
+ highestChannel = Math.max(highestChannel, extensions.channels);
15450
+ }
15451
+ if (mixLevels < 0) mixLevels = modPlugMade ? MixLevels.original : MixLevels.compatible;
15452
+ const preAmpTable = PRE_AMP_TABLE[Math.min(31, Math.max(1, highestChannel)) >> 1];
15453
+ let gain = 1;
15454
+ switch (mixLevels) {
15455
+ default: break;
15456
+ case MixLevels.original:
15457
+ gain = 64 / preAmpTable;
15458
+ break;
15459
+ case MixLevels.v117RC1:
15460
+ gain = 8 / preAmpTable;
15461
+ break;
15462
+ case MixLevels.v117RC2:
15463
+ gain = 128 / preAmpTable;
15464
+ break;
15465
+ case MixLevels.v117RC3: gain = 2;
15466
+ }
15467
+ this.setPreAmp(Math.max(1, samplePreAmp * gain * Math.SQRT2 * .89));
15468
+ let message = "";
15469
+ if (special & 1) message = readBinaryString(binary, readLittleEndian(binary, 2, 54), readLittleEndian(binary, 4, 56)).replaceAll("\r\n", "\n").replaceAll("\r", "\n").trim();
15470
+ const names = (this.instrumentMode ? instrumentNames : sampleNames).join("\n").trim();
15471
+ this.comment = [message, names].filter(Boolean).join("\n\n");
15472
+ }
15473
+ createChannel(index, panning) {
15474
+ const channel = new ImpulseTrackerChannel(index, panning, this.channelVolumes[index] ?? 64);
15475
+ channel.surround = this.channelSurround[index] ?? false;
15476
+ return channel;
15477
+ }
15478
+ noteToPeriod(note, channel) {
15479
+ return channel.finetune * Math.pow(2, (note - MIDDLE_C_NOTE) / 12);
15480
+ }
15481
+ periodToFrequency(period) {
15482
+ return period;
15483
+ }
15484
+ getFrequency(channel) {
15485
+ return channel.outputFrequency;
15486
+ }
15487
+ processRow(channel) {
15488
+ this.processEffects(channel);
15489
+ }
15490
+ processTick(channel) {
15491
+ this.processEffects(channel);
15492
+ }
15493
+ isVoiceFinished(voice) {
15494
+ const v = voice;
15495
+ if (super.isVoiceFinished(voice) || !v.playing || v.noteFade && v.fadeout <= 0 || !v.volume || !v.channelVolume || !v.instrumentVolume) return true;
15496
+ if (!v.noteFade || v.outputLevel >= INAUDIBLE_LEVEL) return false;
15497
+ const envelope = v.instrument?.volumeEnvelope;
15498
+ const points = envelope?.points ?? [];
15499
+ return !envelope?.enabled || points.length === 0 || envelope.loopEnd < 0 && v.volumeEnvelopeState.position - 1 >= points[points.length - 1].tick;
15500
+ }
15501
+ /**
15502
+ * Processes the volumes, envelopes, panning, filter and pitch of a channel or background voice for the current tick.
15503
+ * Follows the mixer setup of OpenMPT.
15504
+ * @param channel The channel.
15505
+ */
15506
+ updateChannel(channel) {
15507
+ const ch = channel;
15508
+ const firstTick = this.tick === 0;
15509
+ const instrument = ch.instrument;
15510
+ const samplePlaying = ch.playing && ch.period > 0;
15511
+ let volume = ch.volume * 4;
15512
+ let instrumentVolume = ch.instrumentVolume;
15513
+ let panning = ch.panning;
15514
+ let envelopeVolume = 1;
15515
+ let fadeoutVolume = 1;
15516
+ let frequency = ch.period;
15517
+ ch.tremorMuted = false;
15518
+ if (samplePlaying) {
15519
+ instrumentVolume = Math.min(64, Math.max(0, instrumentVolume + ch.volumeSwing));
15520
+ panning = Math.min(256, Math.max(0, panning + ch.panningSwing));
15521
+ if (ch.tremoloActive) {
15522
+ const delta = this.getWaveform(ch.tremoloType, ch.tremoloPos);
15523
+ volume += Math.trunc(delta * ch.tremoloDepth / 32);
15524
+ if (!firstTick || !this.oldEffects) ch.tremoloPos = ch.tremoloPos + 4 * ch.tremoloSpeed & 255;
15525
+ }
15526
+ if (ch.command === ImpulseTrackerEffects.tremor) {
15527
+ if (ch.tremorCount & 128) {
15528
+ if (ch.tremorCount === 128) ch.tremorCount = ch.tremorParam >> 4 | 192;
15529
+ else if (ch.tremorCount === 192) ch.tremorCount = ch.tremorParam & 15 | 128;
15530
+ else ch.tremorCount--;
15531
+ }
15532
+ if ((ch.tremorCount & 192) === 128) volume = 0;
15533
+ }
15534
+ volume = Math.min(256, Math.max(0, volume));
15535
+ if (instrument) {
15536
+ this.incrementEnvelope(ch, ch.volumeEnvelopeState, instrument.volumeEnvelope, true);
15537
+ this.incrementEnvelope(ch, ch.panningEnvelopeState, instrument.panningEnvelope, false);
15538
+ this.incrementEnvelope(ch, ch.pitchEnvelopeState, instrument.pitchEnvelope, false);
15539
+ const volumeState = ch.volumeEnvelopeState;
15540
+ if ((volumeState.enabled || instrument.volumeEnvelope.enabled) && volumeState.position > 0) envelopeVolume = getEnvelopeValue(instrument.volumeEnvelope, volumeState.position - 1) / 64;
15541
+ if (ch.noteFade) {
15542
+ if (instrument.fadeout) {
15543
+ ch.fadeout = Math.max(0, ch.fadeout - instrument.fadeout * 2);
15544
+ fadeoutVolume = ch.fadeout / 65536;
15545
+ } else if (!ch.fadeout) fadeoutVolume = 0;
15546
+ }
15547
+ const panningState = ch.panningEnvelopeState;
15548
+ if ((panningState.enabled || instrument.panningEnvelope.enabled) && panningState.position > 0) {
15549
+ const value = getEnvelopeValue(instrument.panningEnvelope, panningState.position - 1) - 32;
15550
+ panning += value * (panning >= 128 ? 256 - panning : panning) / 32;
15551
+ panning = Math.min(256, Math.max(0, panning));
15552
+ }
15553
+ } else if (ch.noteFade) {
15554
+ ch.fadeout = 0;
15555
+ volume = 0;
15556
+ }
15557
+ if (ch.glissando && ch.portamentoActive && frequency > 0) {
15558
+ const note = Math.min(120, Math.max(1, Math.ceil(MIDDLE_C_NOTE + 12 * Math.log2(frequency / ch.finetune) - 1e-6)));
15559
+ frequency = this.noteToPeriod(note, ch);
15560
+ }
15561
+ if (ch.command === ImpulseTrackerEffects.arpeggio && ch.arpeggioParam) {
15562
+ const step = this.rowTick % (this.speed + this.frameDelay) % 3;
15563
+ const semitones = step === 1 ? ch.arpeggioParam >> 4 : step === 2 ? ch.arpeggioParam & 15 : 0;
15564
+ frequency *= Math.pow(2, semitones / 12);
15565
+ }
15566
+ let delta = ch.panbrelloOffset;
15567
+ if (ch.rowEffect === ImpulseTrackerEffects.panbrello) {
15568
+ delta = this.getWaveform(ch.panbrelloType, ch.panbrelloPos);
15569
+ if (ch.panbrelloType === 3) {
15570
+ if (ch.panbrelloPos === 0 || ch.panbrelloPos >= ch.panbrelloSpeed) {
15571
+ ch.panbrelloPos = 0;
15572
+ ch.panbrelloRandom = delta;
15573
+ }
15574
+ ch.panbrelloPos = ch.panbrelloPos + 1 & 255;
15575
+ delta = ch.panbrelloRandom;
15576
+ } else ch.panbrelloPos = ch.panbrelloPos + ch.panbrelloSpeed & 255;
15577
+ ch.panbrelloOffset = delta;
15578
+ }
15579
+ if (delta) panning = Math.min(256, Math.max(0, panning + Math.trunc((delta * ch.panbrelloDepth + 2) / 8)));
15580
+ }
15581
+ if (ch.surround || !this.stereo) panning = 128;
15582
+ if (ch.triggered) {
15583
+ let useFilter = !this.openMPTFilterMode;
15584
+ if (instrument) {
15585
+ if (instrument.resonance >= 0) {
15586
+ ch.resonance = instrument.resonance;
15587
+ useFilter = true;
15588
+ }
15589
+ if (instrument.cutoff >= 0) {
15590
+ ch.cutoff = instrument.cutoff;
15591
+ useFilter = true;
15592
+ }
15593
+ } else {
15594
+ ch.volumeSwing = 0;
15595
+ ch.panningSwing = 0;
15596
+ ch.cutoffSwing = 0;
15597
+ ch.resonanceSwing = 0;
15598
+ }
15599
+ if (useFilter) this.setupFilter(ch, 256);
15600
+ }
15601
+ if (!ch.background) this.processMacro(ch);
15602
+ if (samplePlaying && instrument) {
15603
+ const state = ch.pitchEnvelopeState;
15604
+ if ((state.enabled || instrument.pitchEnvelope.enabled) && instrument.pitchEnvelope.points.length > 0) {
15605
+ if (state.position === 0) {
15606
+ if (instrument.filterEnvelope) this.setupFilter(ch, 0);
15607
+ } else {
15608
+ const value = (getEnvelopeValue(instrument.pitchEnvelope, state.position - 1) - 32) * 8;
15609
+ if (instrument.filterEnvelope) this.setupFilter(ch, value);
15610
+ else frequency *= Math.pow(2, Math.min(255, Math.max(-255, value)) / 192);
15611
+ }
15612
+ }
15613
+ }
15614
+ const [volumeCommand, volumeParam] = decodeVolume(ch.rowVolume);
15615
+ if (volumeCommand === VolumeCommands.vibratoDepth && (ch.rowEffect === ImpulseTrackerEffects.vibrato || ch.rowEffect === ImpulseTrackerEffects.vibratoVolumeSlide || ch.rowEffect === ImpulseTrackerEffects.fineVibrato)) {
15616
+ this.setVibrato(ch, volumeParam, 4);
15617
+ frequency = this.applyVibrato(ch, frequency, firstTick);
15618
+ }
15619
+ frequency = this.applyVibrato(ch, frequency, firstTick);
15620
+ const sample = ch.sample;
15621
+ if (samplePlaying && sample?.vibratoDepth && sample.vibratoRate) {
15622
+ const position = ch.autoVibratoPos & 255;
15623
+ ch.autoVibratoDepth = Math.min(sample.vibratoDepth * 256, ch.autoVibratoDepth + sample.vibratoSweep);
15624
+ const depth = Math.trunc(ch.autoVibratoDepth / 256);
15625
+ ch.autoVibratoPos = ch.autoVibratoPos + sample.vibratoRate & 255;
15626
+ let delta;
15627
+ switch (sample.vibratoType) {
15628
+ default:
15629
+ delta = SINE_TABLE[position];
15630
+ break;
15631
+ case 1:
15632
+ delta = 64 - Math.trunc((position + 1) / 2);
15633
+ break;
15634
+ case 2:
15635
+ delta = position < 128 ? 64 : 0;
15636
+ break;
15637
+ case 3:
15638
+ delta = this.random7() - 64;
15639
+ break;
15640
+ case 4: delta = Math.trunc((position + 1) / 2) - 64;
15641
+ }
15642
+ delta = Math.trunc(delta * depth / 64);
15643
+ frequency *= Math.pow(2, delta / 768);
15644
+ }
15645
+ ch.active = samplePlaying;
15646
+ if (ch.noteFade && ch.fadeout <= 0 && !ch.trigger) ch.samplePosition = Infinity;
15647
+ if (!samplePlaying && !ch.trigger) {
15648
+ fadeoutVolume = 0;
15649
+ if (ch.output && ch.output.activeKey !== -1) ch.stop = true;
15650
+ }
15651
+ ch.outputFrequency = samplePlaying ? frequency : 0;
15652
+ ch.volumeDelta = volume / 4 - ch.volume;
15653
+ ch.envelopeVolume = envelopeVolume;
15654
+ ch.fadeoutVolume = fadeoutVolume;
15655
+ ch.volumeScale = ch.channelVolume / 64 * (instrumentVolume / 64);
15656
+ ch.outputPanning = panning;
15657
+ if (ch.filterEnabled) {
15658
+ const filter = matchFilter(ch.filterCutoffValue, ch.resonance, this.extendedFilterRange);
15659
+ ch.filterCutoff = filter.cents;
15660
+ ch.filterResonance = filter.centibels;
15661
+ } else {
15662
+ ch.filterCutoff = 13500;
15663
+ ch.filterResonance = 0;
15664
+ }
15665
+ ch.previousKeyOff = ch.keyOff;
15666
+ }
15667
+ getTickDuration() {
15668
+ switch (this.tempoMode) {
15669
+ default: return 2.5 / this.tempo;
15670
+ case 1: return 1 / this.tempo;
15671
+ case 2: return 60 / (this.tempo * this.speed * this.rowsPerBeat);
15672
+ }
15673
+ }
15674
+ /**
15675
+ * Reads the OpenMPT instrument (XTPM) and song (STPM) extensions.
15676
+ * @param binary The file data.
15677
+ * @param offset The offset after the last sample and pattern.
15678
+ * @param instrumentCount The number of instruments in the file.
15679
+ * @returns The song properties that need the rest of the file, undefined if there are no song extensions.
15680
+ */
15681
+ readExtensions(binary, offset, instrumentCount) {
15682
+ const readCode = (position) => {
15683
+ const code = readBinaryString(binary, 4, position);
15684
+ return code[3] + code[2] + code[1] + code[0];
15685
+ };
15686
+ const isText = (position) => {
15687
+ let anyLetter = false;
15688
+ for (let i = 0; i < 4; i++) {
15689
+ const byte = binary[position + i];
15690
+ if (byte >= 128) return false;
15691
+ anyLetter ||= (byte & 96) !== 0;
15692
+ }
15693
+ return anyLetter;
15694
+ };
15695
+ const readValue = (position, size) => size > 0 ? readLittleEndian(binary, Math.min(4, size), position) : 0;
15696
+ if (readBinaryString(binary, 4, offset) === "XTPM") {
15697
+ offset += 4;
15698
+ while (offset + 6 <= binary.length) {
15699
+ const code = readCode(offset);
15700
+ if (code === "MPTS" || !isText(offset)) break;
15701
+ const size = readLittleEndian(binary, 2, offset + 4);
15702
+ offset += 6;
15703
+ for (let i = 0; i < instrumentCount; i++) {
15704
+ const instrument = this.itInstruments[i];
15705
+ if (instrument && offset + size <= binary.length) this.readInstrumentExtension(instrument, code, readValue(offset, size));
15706
+ offset += size;
15707
+ }
15708
+ }
15709
+ }
15710
+ if (readBinaryString(binary, 4, offset) !== "STPM") return;
15711
+ offset += 4;
15712
+ const properties = {
15713
+ mixLevels: -1,
15714
+ samplePreAmp: -1,
15715
+ channels: 0
15716
+ };
15717
+ let tempo = this.initialTempo;
15718
+ let tempoFraction = 0;
15719
+ while (offset + 7 <= binary.length && isText(offset)) {
15720
+ const code = readCode(offset);
15721
+ const size = readLittleEndian(binary, 2, offset + 4);
15722
+ offset += 6;
15723
+ if (offset + size > binary.length) break;
15724
+ const value = readValue(offset, size);
15725
+ switch (code) {
15726
+ default: break;
15727
+ case "DT..":
15728
+ tempo = value;
15729
+ break;
15730
+ case "DTFR":
15731
+ tempoFraction = value;
15732
+ break;
15733
+ case "RPB.":
15734
+ this.rowsPerBeat = value || 4;
15735
+ break;
15736
+ case "TM..":
15737
+ this.tempoMode = value < 3 ? value : 0;
15738
+ break;
15739
+ case "PMM.":
15740
+ properties.mixLevels = value < 6 ? value : 0;
15741
+ break;
15742
+ case "SPA.":
15743
+ properties.samplePreAmp = value;
15744
+ break;
15745
+ case "DGV.":
15746
+ this.initialGlobalVolume = Math.min(256, value) / 4;
15747
+ break;
15748
+ case "RP..":
15749
+ this.restartPosition = value;
15750
+ break;
15751
+ case "C...":
15752
+ properties.channels = value;
15753
+ break;
15754
+ case "AUTH": this.artist = readBinaryString(binary, size, offset).trim();
15755
+ }
15756
+ offset += size;
15757
+ }
15758
+ this.initialTempo = Math.min(this.tempoMode === 2 ? 1e3 : 255, Math.max(32, tempo + tempoFraction / 1e4));
15759
+ return properties;
15760
+ }
15761
+ /**
15762
+ * Applies one OpenMPT instrument extension field.
15763
+ * @param instrument The instrument.
15764
+ * @param code The field code.
15765
+ * @param value The field value.
15766
+ */
15767
+ readInstrumentExtension(instrument, code, value) {
15768
+ switch (code) {
15769
+ default: break;
15770
+ case "FO..":
15771
+ instrument.fadeout = value;
15772
+ break;
15773
+ case "GV..":
15774
+ instrument.globalVolume = Math.min(64, value);
15775
+ break;
15776
+ case "P...":
15777
+ instrument.panning = Math.min(256, value);
15778
+ break;
15779
+ case "VS..":
15780
+ instrument.volumeSwing = Math.min(100, value);
15781
+ break;
15782
+ case "PS..":
15783
+ instrument.panningSwing = Math.min(64, value);
15784
+ break;
15785
+ case "CS..":
15786
+ instrument.cutoffSwing = Math.min(64, value);
15787
+ break;
15788
+ case "RS..":
15789
+ instrument.resonanceSwing = Math.min(64, value);
15790
+ break;
15791
+ case "NNA.":
15792
+ instrument.newNoteAction = value & 3;
15793
+ break;
15794
+ case "DCT.":
15795
+ instrument.duplicateCheckType = value & 3;
15796
+ break;
15797
+ case "DNA.":
15798
+ instrument.duplicateCheckAction = value % 3;
15799
+ break;
15800
+ case "PPS.":
15801
+ instrument.pitchPanSeparation = value << 24 >> 24;
15802
+ break;
15803
+ case "PPC.":
15804
+ instrument.pitchPanCenter = Math.min(119, value);
15805
+ break;
15806
+ case "IFC.":
15807
+ instrument.cutoff = value & 128 ? value & 127 : -1;
15808
+ break;
15809
+ case "IFR.": instrument.resonance = value & 128 ? value & 127 : -1;
15810
+ }
15811
+ }
15812
+ /**
15813
+ * Detects the tracker that saved the module.
15814
+ * @param binary The file data.
15815
+ * @param trackerVersion The Cwt/v field.
15816
+ * @param compatibleVersion The Cmwt field.
15817
+ * @param reserved The reserved field.
15818
+ */
15819
+ detectTracker(binary, trackerVersion, compatibleVersion, reserved) {
15820
+ if (readBinaryString(binary, 4, 60) === "CHBI") return "ChibiTracker";
15821
+ switch (trackerVersion >> 12) {
15822
+ default: return "";
15823
+ case 0:
15824
+ if (trackerVersion === 535 && compatibleVersion === 512 && reserved === 0) return "ModPlug Tracker";
15825
+ if (trackerVersion === 532 && compatibleVersion === 514) return "ModPlug Tracker";
15826
+ if (compatibleVersion > 532) return "Impulse Tracker 2.15";
15827
+ if (trackerVersion >= 533 && trackerVersion <= 535) return `Impulse Tracker 2.14p${[
15828
+ "1-2",
15829
+ "3",
15830
+ "4-5"
15831
+ ][trackerVersion - 533]}`;
15832
+ return `Impulse Tracker ${trackerVersion >> 8 & 15}.${(trackerVersion & 255).toString(16).padStart(2, "0")}`;
15833
+ case 1: return "Schism Tracker";
15834
+ case 4: return "pyIT";
15835
+ case 5: return "OpenMPT";
15836
+ case 6: return "BeRoTracker";
15837
+ case 7: return "ITMCK";
15838
+ case 8: return "Tralala";
15839
+ case 12: return "ChickDune ChipTune Tracker";
15840
+ case 13: return "Dushin";
15841
+ }
15842
+ }
15843
+ /**
15844
+ * Reads the MIDI macros, embedded in the file or the defaults.
15845
+ * @param binary The file data.
15846
+ * @param offset The offset after the parapointers.
15847
+ * @param flags The header flags.
15848
+ * @param special The header special flags.
15849
+ */
15850
+ readMacros(binary, offset, flags, special) {
15851
+ this.parameteredMacros[0] = "F0F000z";
15852
+ for (let i = 0; i < 16; i++) this.fixedMacros[i] = `F0F001${(i * 8).toString(16).padStart(2, "0").toUpperCase()}`;
15853
+ if ((flags & 128) === 0 && (special & 8) === 0) return;
15854
+ if (special & 2) offset += 2 + readLittleEndian(binary, 2, offset) * 8;
15855
+ offset += 288;
15856
+ if (offset + 4608 > binary.length) return;
15857
+ for (let i = 0; i < 16; i++) this.parameteredMacros[i] = readBinaryString(binary, MACRO_LENGTH, offset + i * MACRO_LENGTH);
15858
+ offset += 512;
15859
+ for (let i = 0; i < 128; i++) this.fixedMacros[i] = readBinaryString(binary, MACRO_LENGTH, offset + i * MACRO_LENGTH);
15860
+ }
15861
+ /**
15862
+ * Reads the packed data of a pattern.
15863
+ * @param binary The file data.
15864
+ * @param offset The pattern header offset.
15865
+ * @param pattern The pattern to fill (64 channels).
15866
+ * @param usedChannels Set to true for the channels with data.
15867
+ * @param trackerVersion The Cwt/v field of the module header.
15868
+ */
15869
+ readPattern(binary, offset, pattern, usedChannels, trackerVersion) {
15870
+ const end = Math.min(binary.length, offset + 8 + readLittleEndian(binary, 2, offset));
15871
+ const masks = new Uint8Array(MAX_CHANNELS);
15872
+ const lastNote = new Uint8Array(MAX_CHANNELS);
15873
+ const lastInstrument = new Uint8Array(MAX_CHANNELS);
15874
+ const lastVolume = new Uint8Array(MAX_CHANNELS);
15875
+ const lastEffect = new Uint8Array(MAX_CHANNELS);
15876
+ const lastParam = new Uint8Array(MAX_CHANNELS);
15877
+ let position = offset + 8;
15878
+ for (let row = 0; row < pattern.rows && position < end;) {
15879
+ const channelVariable = binary[position++];
15880
+ if (channelVariable === 0) {
15881
+ row++;
15882
+ continue;
15883
+ }
15884
+ const channel = channelVariable - 1 & 63;
15885
+ if (channelVariable & 128) masks[channel] = binary[position++];
15886
+ const mask = masks[channel];
15887
+ let note = 0;
15888
+ let instrument = 0;
15889
+ let volume = 0;
15890
+ let effect = 0;
15891
+ let param = 0;
15892
+ if (mask & 1) lastNote[channel] = binary[position++];
15893
+ if (mask & 2) lastInstrument[channel] = binary[position++];
15894
+ if (mask & 4) lastVolume[channel] = binary[position++];
15895
+ if (mask & 8) {
15896
+ lastEffect[channel] = binary[position++];
15897
+ lastParam[channel] = binary[position++];
15898
+ }
15899
+ if (mask & 17) {
15900
+ const value = lastNote[channel];
15901
+ if (value < 120) note = value + 1;
15902
+ else if (value === 255) note = 254;
15903
+ else if (value === 254) note = 253;
15904
+ else note = NOTE_FADE;
15905
+ }
15906
+ if (mask & 34) instrument = lastInstrument[channel];
15907
+ if (mask & 68) volume = lastVolume[channel] + 1;
15908
+ if (mask & 136) {
15909
+ effect = lastEffect[channel];
15910
+ param = lastParam[channel];
15911
+ if (effect === ImpulseTrackerEffects.extended && param >> 4 === ImpulseTrackerExtendedEffects.highOffset && trackerVersion < 512) effect = 0;
15912
+ else if (effect === ImpulseTrackerEffects.globalVolume && param > 128 && trackerVersion >= 4096 && trackerVersion <= 4176) param = 128;
15913
+ }
15914
+ usedChannels[channel] = true;
15915
+ pattern.setCell(row, channel, note, instrument, volume, effect, param);
15916
+ }
15917
+ }
15918
+ /**
15919
+ * Reads an instrument.
15920
+ * @param binary The file data.
15921
+ * @param offset The instrument header offset.
15922
+ * @param compatibleVersion The compatible tracker version of the module.
15923
+ */
15924
+ readInstrument(binary, offset, compatibleVersion) {
15925
+ const instrument = {
15926
+ name: readBinaryString(binary, 26, offset + 32),
15927
+ sampleMap: (/* @__PURE__ */ new Int16Array(120)).fill(-1),
15928
+ noteMap: /* @__PURE__ */ new Uint8Array(120),
15929
+ volumeEnvelope: emptyEnvelope(),
15930
+ panningEnvelope: emptyEnvelope(),
15931
+ pitchEnvelope: emptyEnvelope(),
15932
+ filterEnvelope: false,
15933
+ fadeout: 0,
15934
+ newNoteAction: NoteActions.cut,
15935
+ duplicateCheckType: 0,
15936
+ duplicateCheckAction: NoteActions.cut,
15937
+ globalVolume: 64,
15938
+ panning: -1,
15939
+ volumeSwing: 0,
15940
+ panningSwing: 0,
15941
+ cutoffSwing: 0,
15942
+ resonanceSwing: 0,
15943
+ pitchPanSeparation: 0,
15944
+ pitchPanCenter: 60,
15945
+ cutoff: -1,
15946
+ resonance: -1
15947
+ };
15948
+ for (let n = 0; n < 120; n++) {
15949
+ const note = binary[offset + 64 + n * 2];
15950
+ const sample = binary[offset + 65 + n * 2];
15951
+ instrument.noteMap[n] = note < 120 ? note : n;
15952
+ instrument.sampleMap[n] = sample > 0 ? sample - 1 : -1;
15953
+ }
15954
+ if (readBinaryString(binary, 4, offset) !== "IMPI") return instrument;
15955
+ if (compatibleVersion >= 512) {
15956
+ instrument.newNoteAction = binary[offset + 17] & 3;
15957
+ instrument.duplicateCheckType = binary[offset + 18] & 3;
15958
+ instrument.duplicateCheckAction = binary[offset + 19] % 3;
15959
+ instrument.fadeout = readLittleEndian(binary, 2, offset + 20) << 5;
15960
+ instrument.pitchPanSeparation = binary[offset + 22] << 24 >> 24;
15961
+ instrument.pitchPanCenter = Math.min(119, binary[offset + 23]);
15962
+ instrument.globalVolume = Math.min(64, binary[offset + 24] >> 1);
15963
+ const panning = binary[offset + 25];
15964
+ if ((panning & 128) === 0) {
15965
+ instrument.panning = panning * 4;
15966
+ if (instrument.panning > 256) instrument.panning = 128;
15967
+ }
15968
+ instrument.volumeSwing = Math.min(100, binary[offset + 26]);
15969
+ instrument.panningSwing = Math.min(64, binary[offset + 27]);
15970
+ const cutoff = binary[offset + 58];
15971
+ const resonance = binary[offset + 59];
15972
+ if (cutoff & 128) instrument.cutoff = cutoff & 127;
15973
+ if (resonance & 128) instrument.resonance = resonance & 127;
15974
+ instrument.volumeEnvelope = readEnvelope(binary, offset + 304, false);
15975
+ instrument.panningEnvelope = readEnvelope(binary, offset + 386, true);
15976
+ instrument.pitchEnvelope = readEnvelope(binary, offset + 468, true);
15977
+ instrument.filterEnvelope = (binary[offset + 468] & 128) !== 0;
15978
+ return instrument;
15979
+ }
15980
+ instrument.fadeout = readLittleEndian(binary, 2, offset + 24) << 6;
15981
+ instrument.newNoteAction = binary[offset + 26] & 3;
15982
+ instrument.duplicateCheckType = binary[offset + 27] ? 1 : 0;
15983
+ const points = new Array();
15984
+ for (let p = 0; p < MAX_ENVELOPE_POINTS; p++) {
15985
+ const tick = binary[offset + 504 + p * 2];
15986
+ if (tick === 255) break;
15987
+ points.push({
15988
+ tick,
15989
+ value: Math.min(64, binary[offset + 505 + p * 2])
15990
+ });
15991
+ }
15992
+ const flags = binary[offset + 17];
15993
+ const loop = [binary[offset + 18], binary[offset + 19]];
15994
+ const sustain = [binary[offset + 20], binary[offset + 21]];
15995
+ instrument.volumeEnvelope = createEnvelope(points, flags & 1 | (Math.max(loop[0], loop[1]) < points.length ? flags & 2 : 0) | (Math.max(sustain[0], sustain[1]) < points.length ? flags & 4 : 0), loop[0], loop[1], sustain[0], sustain[1]);
15996
+ return instrument;
15997
+ }
15998
+ /**
15999
+ * A 7-bit random number, deterministic.
16000
+ */
16001
+ random7() {
16002
+ return this.randomByte() & 127;
16003
+ }
16004
+ /**
16005
+ * A signed 8-bit random number, deterministic.
16006
+ */
16007
+ randomInt8() {
16008
+ return this.randomByte() << 24 >> 24;
16009
+ }
16010
+ randomByte() {
16011
+ let x = this.randomState;
16012
+ x ^= x << 13;
16013
+ x ^= x >>> 17;
16014
+ x ^= x << 5;
16015
+ this.randomState = x >>> 0;
16016
+ return this.randomState >>> 8 & 255;
16017
+ }
16018
+ /**
16019
+ * Gets the value of a vibrato, tremolo or panbrello waveform.
16020
+ * @param waveform The waveform (0 sine, 1 ramp down, 2 square, 3 random).
16021
+ * @param position The position (0-255).
16022
+ * @returns The value (-64 to 64).
16023
+ */
16024
+ getWaveform(waveform, position) {
16025
+ position &= 255;
16026
+ switch (waveform & 3) {
16027
+ default: return SINE_TABLE[position];
16028
+ case 1: return 64 - Math.trunc((position + 1) / 2);
16029
+ case 2: return position < 128 ? 64 : 0;
16030
+ case 3: return this.random7() - 64;
16031
+ }
16032
+ }
16033
+ /**
16034
+ * Gets the sample index of a note of an instrument (or of a sample number in sample mode).
16035
+ * @param note The one-based note.
16036
+ * @param instrument The one-based instrument number.
16037
+ * @returns The sample index, -1 if none.
16038
+ */
16039
+ getSampleIndex(note, instrument) {
16040
+ if (!this.instrumentMode) return instrument - 1;
16041
+ if (!isNote(note)) return -1;
16042
+ return this.itInstruments[instrument - 1]?.sampleMap[note - 1] ?? -1;
16043
+ }
16044
+ /**
16045
+ * Gets a sample by its index, the empty sample for an index that does not exist.
16046
+ * @param index The sample index.
16047
+ */
16048
+ getSample(index) {
16049
+ return this.itSamples[index] ?? EMPTY_SAMPLE;
16050
+ }
16051
+ /**
16052
+ * Combines an effect parameter with the extended parameters (#xx) on the following rows.
16053
+ * @param channel The channel.
16054
+ * @param param The effect parameter.
16055
+ * @param rows The maximum number of extended parameter rows.
16056
+ * @returns The combined value and the number of extended parameter rows.
16057
+ */
16058
+ getExtendedParameter(channel, param, rows) {
16059
+ const pattern = this.currentPattern;
16060
+ let value = param;
16061
+ let count = 0;
16062
+ for (let row = this.currentRow + 1; row < pattern.rows && count < rows; row++) {
16063
+ const offset = pattern.getCellOffset(row, channel.index);
16064
+ if (pattern.getEffect(offset) !== ImpulseTrackerEffects.extendedParameter) break;
16065
+ value = value * 256 + pattern.getParam(offset);
16066
+ count++;
16067
+ }
16068
+ return {
16069
+ value,
16070
+ count
16071
+ };
16072
+ }
16073
+ /**
16074
+ * Processes the row data and the effects of a channel for the current tick.
16075
+ * Follows the effect processing of OpenMPT in its Impulse Tracker compatible mode.
16076
+ * @param ch The channel.
16077
+ */
16078
+ processEffects(ch) {
16079
+ const rowTick = this.rowTick;
16080
+ const firstTick = this.tick === 0;
16081
+ const rowLength = this.speed + this.frameDelay;
16082
+ const tickCount = rowTick % rowLength;
16083
+ if (rowTick === 0) {
16084
+ ch.vibratoActive = false;
16085
+ ch.tremoloActive = false;
16086
+ ch.command = 0;
16087
+ }
16088
+ let instrumentNumber = ch.rowInstrument;
16089
+ let note = ch.rowNote;
16090
+ const [volumeCommand, volumeColumn] = decodeVolume(ch.rowVolume);
16091
+ let volumeParam = volumeColumn;
16092
+ const effect = ch.rowEffect;
16093
+ let param = ch.rowParam;
16094
+ const porta = effect === ImpulseTrackerEffects.tonePortamento || effect === ImpulseTrackerEffects.tonePortamentoVolumeSlide || volumeCommand === VolumeCommands.tonePortamento;
16095
+ let startTick = 0;
16096
+ ch.isFirstTick = firstTick;
16097
+ if (this.instrumentMode && instrumentNumber > 0) {
16098
+ const instrument = this.itInstruments[instrumentNumber - 1];
16099
+ const mapNote = note === 0 ? ch.newNote : note;
16100
+ if (instrument && isNote(mapNote) && instrument.sampleMap[mapNote - 1] < 0) {
16101
+ ch.newNote = mapNote;
16102
+ ch.lastNote = mapNote;
16103
+ ch.newInstrument = instrumentNumber;
16104
+ ch.rowNote = 0;
16105
+ ch.rowInstrument = 0;
16106
+ ch.rowVolume = 0;
16107
+ ch.rowEffect = 0;
16108
+ ch.rowParam = 0;
16109
+ return;
16110
+ }
16111
+ }
16112
+ if (effect === ImpulseTrackerEffects.delayCut) {
16113
+ startTick = param >> 4;
16114
+ this.noteCut(ch, startTick + (param & 15));
16115
+ } else if (effect === ImpulseTrackerEffects.extended) {
16116
+ if (param) ch.oldExtended = param;
16117
+ else param = ch.oldExtended;
16118
+ if (param >> 4 === ImpulseTrackerExtendedEffects.noteDelay) {
16119
+ startTick = param & 15 || 1;
16120
+ if (startTick >= rowLength) {
16121
+ if (instrumentNumber) ch.newInstrument = instrumentNumber;
16122
+ return;
16123
+ }
16124
+ } else if (firstTick && param >> 4 === ImpulseTrackerExtendedEffects.rowDelay) this.setRowDelay(param & 15);
16125
+ }
16126
+ let triggerNote = rowTick === startTick;
16127
+ if (startTick > 0 && tickCount === startTick) triggerNote = true;
16128
+ ch.isFirstTick = tickCount === startTick;
16129
+ ch.triggered = false;
16130
+ if (triggerNote) {
16131
+ if (instrumentNumber) ch.newInstrument = instrumentNumber;
16132
+ if (this.instrumentMode && (note === 0 || isNote(note))) {
16133
+ const check = instrumentNumber || ch.oldInstrument;
16134
+ if (check && !this.itInstruments[check - 1]) {
16135
+ note = 0;
16136
+ instrumentNumber = 0;
16137
+ }
16138
+ }
16139
+ const retriggerEnvelopes = note === 0 && instrumentNumber !== 0;
16140
+ if (this.instrumentMode && instrumentNumber && !isNote(note) && (porta && this.compatibleGxx || !porta && this.oldEffects)) {
16141
+ ch.resetEnvelopes();
16142
+ ch.fadeout = 65536;
16143
+ }
16144
+ if (retriggerEnvelopes) {
16145
+ const ended = !ch.active;
16146
+ if (this.instrumentMode) {
16147
+ if (ch.instrument !== this.itInstruments[instrumentNumber - 1] || ended) note = ch.note;
16148
+ } else if (ch.sample !== this.getSample(instrumentNumber - 1) || ended) note = ch.note;
16149
+ }
16150
+ if (note >= NOTE_FADE) {
16151
+ if (instrumentNumber) {
16152
+ const sample = this.getSampleIndex(ch.lastNote, instrumentNumber);
16153
+ if (sample >= 0) ch.volume = this.getSample(sample).volume;
16154
+ }
16155
+ if (!this.oldEffects) instrumentNumber = 0;
16156
+ }
16157
+ const previousNewNote = ch.newNote;
16158
+ if (isNote(note)) {
16159
+ ch.newNote = note;
16160
+ ch.lastNote = note;
16161
+ if (!porta) this.checkNNA(ch, instrumentNumber, note, false);
16162
+ this.restorePanningAndFilter(ch);
16163
+ }
16164
+ if (instrumentNumber) {
16165
+ const oldSample = ch.sample;
16166
+ this.instrumentChange(ch, instrumentNumber, porta, true, true);
16167
+ if (isNote(note)) {
16168
+ ch.newInstrument = 0;
16169
+ if (oldSample !== ch.sample && porta && ch.playing) this.retrigger(ch, 0);
16170
+ }
16171
+ }
16172
+ if (note !== 0) {
16173
+ if (!instrumentNumber && ch.newInstrument && isNote(note)) {
16174
+ if (isNote(previousNewNote)) ch.newNote = previousNewNote;
16175
+ this.instrumentChange(ch, ch.newInstrument, porta, !ch.sample && !ch.instrument, true);
16176
+ ch.newNote = note;
16177
+ ch.newInstrument = 0;
16178
+ }
16179
+ this.noteChange(ch, note, porta, true);
16180
+ }
16181
+ if (volumeCommand === VolumeCommands.volume) ch.volume = Math.min(64, volumeParam);
16182
+ else if (volumeCommand === VolumeCommands.panning) this.setPanning(ch, Math.min(64, volumeParam) * 4);
16183
+ }
16184
+ if (ch.isFirstTick) {
16185
+ const effectTonePorta = effect === ImpulseTrackerEffects.tonePortamento || effect === ImpulseTrackerEffects.tonePortamentoVolumeSlide;
16186
+ if (effectTonePorta) this.initTonePortamento(ch, effect === ImpulseTrackerEffects.tonePortamentoVolumeSlide ? 0 : param);
16187
+ if (volumeCommand === VolumeCommands.tonePortamento) this.initTonePortamento(ch, VOLUME_COLUMN_PORTAMENTO[volumeParam & 15]);
16188
+ if (volumeParam && (volumeCommand === VolumeCommands.portamentoUp || volumeCommand === VolumeCommands.portamentoDown)) {
16189
+ ch.oldPortamento = volumeParam << 2;
16190
+ if (!effectTonePorta && !this.compatibleGxx) ch.portamentoSlide = volumeParam << 2;
16191
+ }
16192
+ if (param && (effect === ImpulseTrackerEffects.portamentoUp || effect === ImpulseTrackerEffects.portamentoDown)) {
16193
+ ch.oldPortamento = param;
16194
+ if (!this.compatibleGxx) ch.portamentoSlide = param;
16195
+ }
16196
+ }
16197
+ if (volumeCommand > VolumeCommands.panning && rowTick >= startTick) switch (volumeCommand) {
16198
+ default: break;
16199
+ case VolumeCommands.tonePortamento:
16200
+ this.tonePortamento(ch, VOLUME_COLUMN_PORTAMENTO[volumeParam & 15]);
16201
+ break;
16202
+ case VolumeCommands.volumeSlideUp:
16203
+ case VolumeCommands.volumeSlideDown:
16204
+ if (volumeParam === 0) {
16205
+ volumeParam = ch.oldVolumeColumn;
16206
+ if (volumeParam === 0) break;
16207
+ } else ch.oldVolumeColumn = volumeParam;
16208
+ this.volumeSlide(ch, volumeCommand === VolumeCommands.volumeSlideUp ? volumeParam << 4 : volumeParam, true);
16209
+ break;
16210
+ case VolumeCommands.fineVolumeUp:
16211
+ if (rowTick === startTick) this.fineVolume(ch, volumeParam, 1, true);
16212
+ break;
16213
+ case VolumeCommands.fineVolumeDown:
16214
+ if (rowTick === startTick) this.fineVolume(ch, volumeParam, -1, true);
16215
+ break;
16216
+ case VolumeCommands.vibratoDepth:
16217
+ this.setVibrato(ch, volumeParam, 4);
16218
+ break;
16219
+ case VolumeCommands.portamentoUp:
16220
+ this.portamento(ch, volumeParam << 2, 1, true);
16221
+ break;
16222
+ case VolumeCommands.portamentoDown: this.portamento(ch, volumeParam << 2, -1, true);
16223
+ }
16224
+ switch (effect) {
16225
+ default: break;
16226
+ case ImpulseTrackerEffects.speed:
16227
+ if (firstTick) this.setSpeed(param);
16228
+ break;
16229
+ case ImpulseTrackerEffects.positionJump:
16230
+ if (firstTick) this.setPositionJump(this.getExtendedParameter(ch, param, 1).value);
16231
+ break;
16232
+ case ImpulseTrackerEffects.patternBreak:
16233
+ if (firstTick) this.patternBreak(this.getExtendedParameter(ch, param, 1).value, false);
16234
+ break;
16235
+ case ImpulseTrackerEffects.volumeSlide:
16236
+ this.volumeSlide(ch, param, false);
16237
+ break;
16238
+ case ImpulseTrackerEffects.portamentoDown:
16239
+ this.portamento(ch, param, -1, false);
16240
+ break;
16241
+ case ImpulseTrackerEffects.portamentoUp:
16242
+ this.portamento(ch, param, 1, false);
16243
+ break;
16244
+ case ImpulseTrackerEffects.tonePortamento:
16245
+ this.tonePortamento(ch, param);
16246
+ break;
16247
+ case ImpulseTrackerEffects.tonePortamentoVolumeSlide:
16248
+ this.volumeSlide(ch, param, false);
16249
+ this.tonePortamento(ch, 0);
16250
+ break;
16251
+ case ImpulseTrackerEffects.vibrato:
16252
+ this.setVibrato(ch, param, 4);
16253
+ break;
16254
+ case ImpulseTrackerEffects.vibratoVolumeSlide:
16255
+ this.volumeSlide(ch, param, false);
16256
+ this.setVibrato(ch, 0, 4);
16257
+ break;
16258
+ case ImpulseTrackerEffects.fineVibrato:
16259
+ this.setVibrato(ch, param, 1);
16260
+ break;
16261
+ case ImpulseTrackerEffects.tremor:
16262
+ if (!firstTick) break;
16263
+ if (param && !this.oldEffects) {
16264
+ if (param & 240) param -= 16;
16265
+ if (param & 15) param -= 1;
16266
+ }
16267
+ ch.tremorCount |= 128;
16268
+ ch.command = ImpulseTrackerEffects.tremor;
16269
+ if (param) ch.tremorParam = param;
16270
+ break;
16271
+ case ImpulseTrackerEffects.arpeggio:
16272
+ if (rowTick) break;
16273
+ ch.command = ImpulseTrackerEffects.arpeggio;
16274
+ if (param) ch.arpeggioParam = param;
16275
+ break;
16276
+ case ImpulseTrackerEffects.channelVolume:
16277
+ if (firstTick && param <= 64) ch.channelVolume = param;
16278
+ break;
16279
+ case ImpulseTrackerEffects.channelVolumeSlide:
16280
+ if (param) ch.oldChannelVolumeSlide = param;
16281
+ ch.channelVolume = Math.min(64, Math.max(0, ch.channelVolume + this.getSlideAmount(ch.oldChannelVolumeSlide, firstTick)));
16282
+ break;
16283
+ case ImpulseTrackerEffects.sampleOffset:
16284
+ if (triggerNote) this.sampleOffset(ch, param);
16285
+ break;
16286
+ case ImpulseTrackerEffects.panningSlide: {
16287
+ if (param) ch.oldPanningSlide = param;
16288
+ const slide = -this.getSlideAmount(ch.oldPanningSlide, firstTick);
16289
+ if (slide) {
16290
+ ch.panning = Math.min(256, Math.max(0, ch.panning + slide * 4));
16291
+ ch.restorePanning = 0;
16292
+ }
16293
+ break;
16294
+ }
16295
+ case ImpulseTrackerEffects.retrigger:
16296
+ if (param) ch.retriggerParam = param;
16297
+ this.retriggerNote(ch, ch.retriggerParam);
16298
+ break;
16299
+ case ImpulseTrackerEffects.tremolo:
16300
+ if (param & 15) ch.tremoloDepth = (param & 15) << 2;
16301
+ if (param & 240) ch.tremoloSpeed = param >> 4;
16302
+ ch.tremoloActive = true;
16303
+ break;
16304
+ case ImpulseTrackerEffects.extended:
16305
+ this.extendedEffect(ch, param);
16306
+ break;
16307
+ case ImpulseTrackerEffects.tempo:
16308
+ param = this.getExtendedParameter(ch, param, 1).value;
16309
+ if (param) ch.oldTempo = param;
16310
+ else param = ch.oldTempo;
16311
+ if (param >= 32) {
16312
+ if (firstTick) this.tempo = Math.min(255, param);
16313
+ } else if (!firstTick) {
16314
+ const change = param & 15;
16315
+ this.tempo = Math.min(255, Math.max(32, this.tempo + ((param & 240) === 16 ? change : -change)));
16316
+ }
16317
+ break;
16318
+ case ImpulseTrackerEffects.globalVolume:
16319
+ if (firstTick && param <= 128) this.globalVolume = param / 2;
16320
+ break;
16321
+ case ImpulseTrackerEffects.globalVolumeSlide:
16322
+ if (param) ch.oldGlobalVolumeSlide = param;
16323
+ this.globalVolume = Math.min(64, Math.max(0, this.globalVolume + this.getSlideAmount(ch.oldGlobalVolumeSlide, firstTick) / 2));
16324
+ break;
16325
+ case ImpulseTrackerEffects.panning:
16326
+ if (firstTick) this.setPanning(ch, param);
16327
+ break;
16328
+ case ImpulseTrackerEffects.panbrello:
16329
+ if (param & 15) ch.panbrelloDepth = param & 15;
16330
+ if (param & 240) ch.panbrelloSpeed = param >> 4;
16331
+ }
16332
+ if (ch.rowInstrument) ch.oldInstrument = ch.rowInstrument;
16333
+ }
16334
+ /**
16335
+ * Gets the amount of a Dxy style slide (volume, channel volume, panning and global volume slides).
16336
+ * @param param The effect parameter. The high nibble slides up, the low nibble slides down.
16337
+ * F in the other nibble is a fine slide, which only applies on the first tick.
16338
+ * @param firstTick If this is the first tick of the row.
16339
+ * @returns The amount to add on this tick.
16340
+ */
16341
+ getSlideAmount(param, firstTick) {
16342
+ const up = param >> 4;
16343
+ const down = param & 15;
16344
+ if (down === 15 && up) return firstTick ? up : 0;
16345
+ if (up === 15 && down) return firstTick ? -down : 0;
16346
+ if (firstTick) return 0;
16347
+ if (up === 0) return -down;
16348
+ return down === 0 ? up : 0;
16349
+ }
16350
+ /**
16351
+ * Processes a volume slide (Dxy and the volume column slides).
16352
+ * @param ch The channel.
16353
+ * @param param The parameter, zero uses the memory (for the effect column).
16354
+ * @param volumeColumn If the slide comes from the volume column, which has its own memory.
16355
+ */
16356
+ volumeSlide(ch, param, volumeColumn) {
16357
+ if (!volumeColumn) {
16358
+ if (param) ch.oldVolumeSlide = param;
16359
+ else param = ch.oldVolumeSlide;
16360
+ }
16361
+ let volume = ch.volume;
16362
+ if ((param & 15) === 15) {
16363
+ if (param & 240) {
16364
+ this.fineVolume(ch, param >> 4, 1, false);
16365
+ return;
16366
+ } else if (ch.isFirstTick) volume -= 15;
16367
+ } else if ((param & 240) === 240) {
16368
+ if (param & 15) {
16369
+ this.fineVolume(ch, param & 15, -1, false);
16370
+ return;
16371
+ } else if (ch.isFirstTick) volume += 15;
16372
+ }
16373
+ if (!ch.isFirstTick) {
16374
+ if (param & 15) {
16375
+ if ((param & 240) === 0) volume -= param & 15;
16376
+ } else volume += param >> 4;
16377
+ }
16378
+ ch.volume = Math.min(64, Math.max(0, volume));
16379
+ }
16380
+ /**
16381
+ * Processes a fine volume slide, only on the first tick.
16382
+ * @param ch The channel.
16383
+ * @param param The amount, zero uses the memory.
16384
+ * @param direction 1 for up, -1 for down.
16385
+ * @param volumeColumn If the slide comes from the volume column, which has its own memory.
16386
+ */
16387
+ fineVolume(ch, param, direction, volumeColumn) {
16388
+ if (volumeColumn) {
16389
+ if (param) ch.oldVolumeColumn = param;
16390
+ else param = ch.oldVolumeColumn;
16391
+ } else if (param) ch.oldFineVolume = param;
16392
+ else param = ch.oldFineVolume;
16393
+ if (ch.isFirstTick) ch.volume = Math.min(64, Math.max(0, ch.volume + direction * param));
16394
+ }
16395
+ /**
16396
+ * Sets the panning, cancelling surround, panning variation and panbrello.
16397
+ * @param ch The channel.
16398
+ * @param panning The panning (0-256).
16399
+ */
16400
+ setPanning(ch, panning) {
16401
+ ch.surround = false;
16402
+ ch.panning = panning;
16403
+ ch.restorePanning = 0;
16404
+ ch.panningSwing = 0;
16405
+ ch.panbrelloOffset = 0;
16406
+ }
16407
+ /**
16408
+ * Sets the vibrato speed and depth, keeping the previous values for zero nibbles.
16409
+ * @param ch The channel.
16410
+ * @param param The speed (high nibble) and the depth (low nibble).
16411
+ * @param depthScale The multiplier of the depth (4 for regular, 1 for fine vibrato).
16412
+ */
16413
+ setVibrato(ch, param, depthScale) {
16414
+ if (param & 15) ch.vibratoDepth = (param & 15) * depthScale;
16415
+ if (param & 240) ch.vibratoSpeed = param >> 4;
16416
+ ch.vibratoActive = true;
16417
+ }
16418
+ /**
16419
+ * Applies the vibrato to a frequency.
16420
+ * @param ch The channel.
16421
+ * @param frequency The frequency.
16422
+ * @param firstTick If this is the first tick of the row.
16423
+ * @returns The frequency with the vibrato.
16424
+ */
16425
+ applyVibrato(ch, frequency, firstTick) {
16426
+ if (!ch.vibratoActive) return frequency;
16427
+ if (!firstTick || !this.oldEffects) ch.vibratoPos = ch.vibratoPos + 4 * ch.vibratoSpeed & 255;
16428
+ let delta = this.getWaveform(ch.vibratoType, ch.vibratoPos);
16429
+ let shift = 5;
16430
+ if (!this.oldEffects) {
16431
+ shift = 6;
16432
+ delta = -delta;
16433
+ }
16434
+ delta = Math.trunc(-delta * ch.vibratoDepth / (1 << shift));
16435
+ return this.slideFrequency(ch, frequency, delta);
16436
+ }
16437
+ /**
16438
+ * Slides a frequency in Impulse Tracker units (1/64 semitone for linear slides).
16439
+ * @param ch The channel.
16440
+ * @param frequency The frequency.
16441
+ * @param amount The slide amount, positive slides up.
16442
+ * @param tonePortamento If the slide is a tone portamento.
16443
+ * @returns The new frequency.
16444
+ */
16445
+ slideFrequency(ch, frequency, amount, tonePortamento = false) {
16446
+ if (!frequency || !amount) return frequency;
16447
+ if (this.linearSlides) {
16448
+ let absolute = Math.abs(amount);
16449
+ if (absolute >= 16) absolute = Math.trunc(absolute / 4) * 4;
16450
+ frequency *= Math.pow(2, Math.sign(amount) * absolute / 768);
16451
+ } else if (amount < 0) frequency = AMIGA_CONSTANT * frequency / (frequency * -amount + AMIGA_CONSTANT);
16452
+ else {
16453
+ const divisor = AMIGA_CONSTANT - frequency * amount;
16454
+ if (divisor <= 0) {
16455
+ if (tonePortamento) return 2147483647;
16456
+ ch.fadeout = 0;
16457
+ ch.noteFade = true;
16458
+ return 0;
16459
+ }
16460
+ frequency = AMIGA_CONSTANT * frequency / divisor;
16461
+ }
16462
+ return Math.max(1, frequency);
16463
+ }
16464
+ /**
16465
+ * Processes the portamento up and down, including the fine (xFx) and extra fine (xEx) variants.
16466
+ * @param ch The channel.
16467
+ * @param param The effect parameter, the memory is used instead.
16468
+ * @param direction 1 for up, -1 for down.
16469
+ * @param regularOnly True for the volume column, which has no fine slides.
16470
+ */
16471
+ portamento(ch, param, direction, regularOnly) {
16472
+ param = ch.oldPortamento;
16473
+ if (!regularOnly && param >= 224) {
16474
+ if (param & 15 && ch.isFirstTick && ch.period) {
16475
+ const fine = param & 15;
16476
+ ch.period = this.slideFrequency(ch, ch.period, direction * ((param & 240) === 240 ? fine * 4 : fine));
16477
+ }
16478
+ return;
16479
+ }
16480
+ if (!ch.isFirstTick) ch.period = this.slideFrequency(ch, ch.period, direction * param * 4);
16481
+ }
16482
+ /**
16483
+ * Initializes the tone portamento memory.
16484
+ * @param ch The channel.
16485
+ * @param param The speed, zero uses the memory.
16486
+ */
16487
+ initTonePortamento(ch, param) {
16488
+ if (!this.compatibleGxx) {
16489
+ if (param === 0) param = ch.oldPortamento;
16490
+ ch.oldPortamento = param;
16491
+ }
16492
+ if (param) ch.portamentoSlide = param;
16493
+ }
16494
+ /**
16495
+ * Processes the tone portamento.
16496
+ * @param ch The channel.
16497
+ * @param param The parameter, the memory was initialized with it already.
16498
+ */
16499
+ tonePortamento(ch, param) {
16500
+ ch.portamentoActive = true;
16501
+ const delta = ch.portamentoSlide * 4;
16502
+ if (ch.period && ch.portamentoTarget && !ch.isFirstTick) {
16503
+ if (!delta && ch.rowEffect === ImpulseTrackerEffects.tonePortamentoVolumeSlide) {
16504
+ if (ch.period > 1 && this.linearSlides) ch.period--;
16505
+ if (ch.period < ch.portamentoTarget) ch.period = ch.portamentoTarget;
16506
+ } else if (ch.period < ch.portamentoTarget) ch.period = Math.min(ch.portamentoTarget, this.slideFrequency(ch, ch.period, delta, true));
16507
+ else if (ch.period > ch.portamentoTarget) ch.period = Math.max(ch.portamentoTarget, this.slideFrequency(ch, ch.period, -delta, true));
16508
+ }
16509
+ if (ch.period === ch.portamentoTarget) ch.portamentoTarget = 0;
16510
+ }
16511
+ /**
16512
+ * Processes a sample offset (Oxx, with SAx and extended parameters).
16513
+ * @param ch The channel.
16514
+ * @param param The effect parameter.
16515
+ */
16516
+ sampleOffset(ch, param) {
16517
+ const extended = this.getExtendedParameter(ch, param, 2);
16518
+ let offset;
16519
+ if (extended.count) offset = extended.value;
16520
+ else {
16521
+ offset = param << 8;
16522
+ if (offset) ch.oldOffset = offset;
16523
+ else offset = ch.oldOffset;
16524
+ offset += ch.oldHighOffset * 65536;
16525
+ }
16526
+ const note = ch.rowInstrument ? ch.newNote : ch.rowNote;
16527
+ if (!isNote(note) || !ch.sample) return;
16528
+ if (ch.instrument && ch.instrument.sampleMap[note - 1] < 0) return;
16529
+ const sample = ch.sample;
16530
+ const loopEnd = ch.sustainLoop ? sample.sustainLoopEnd ?? 0 : sample.loopEnd;
16531
+ const looped = (ch.sustainLoop ? sample.sustainLoopType : sample.loopType) !== TrackerLoopTypes.none;
16532
+ if (offset >= sample.data.length || looped && offset >= loopEnd) offset = this.oldEffects ? sample.data.length : 0;
16533
+ this.setSamplePosition(ch, offset);
16534
+ }
16535
+ /**
16536
+ * Sets the playback position of the channel's sample and restarts it there.
16537
+ * @param ch The channel.
16538
+ * @param position The position in the sample.
16539
+ */
16540
+ setSamplePosition(ch, position) {
16541
+ if (!ch.sample) return;
16542
+ const offset = position >= ch.sample.data.length ? Infinity : this.sampleBank.fromSource(ch.preset, position, ch.reverse);
16543
+ ch.sampleOffset = offset;
16544
+ if (!ch.trigger && ch.playing) ch.trigger = true;
16545
+ if (ch.trigger) ch.samplePosition = offset === Infinity ? 0 : offset;
16546
+ }
16547
+ /**
16548
+ * Restarts the playing sample from a position, keeping the pitch and the volume.
16549
+ * @param ch The channel.
16550
+ * @param position The position in the sample.
16551
+ */
16552
+ retrigger(ch, position) {
16553
+ ch.trigger = true;
16554
+ ch.samplePosition = 0;
16555
+ this.setSamplePosition(ch, position);
16556
+ }
16557
+ /**
16558
+ * Gets the sound bank variant a channel's sample should play with.
16559
+ * @param ch The channel.
16560
+ */
16561
+ getVariant(ch) {
16562
+ if (ch.reverse) return TrackerSampleVariants.reverse;
16563
+ const sample = ch.sample;
16564
+ if (sample?.sustainLoopType !== void 0 && sample.sustainLoopType !== TrackerLoopTypes.none && !ch.sustainLoop) return TrackerSampleVariants.release;
16565
+ return TrackerSampleVariants.normal;
16566
+ }
16567
+ /**
16568
+ * Switches the playing sample to the variant the channel's state needs, continuing from the same position.
16569
+ * @param ch The channel.
16570
+ */
16571
+ updateVariant(ch) {
16572
+ if (ch.sampleIndex < 0 || !ch.sample || ch.sample === EMPTY_SAMPLE) return;
16573
+ const preset = this.sampleBank.getPreset(ch.sampleIndex, this.getVariant(ch));
16574
+ if (preset === ch.preset) return;
16575
+ if (!ch.playing || ch.trigger) {
16576
+ ch.preset = preset;
16577
+ return;
16578
+ }
16579
+ const source = this.sampleBank.toSource(ch.preset, ch.samplePosition);
16580
+ ch.preset = preset;
16581
+ ch.sampleOffset = this.sampleBank.fromSource(preset, source.position, ch.reverse);
16582
+ ch.samplePosition = ch.sampleOffset;
16583
+ ch.trigger = true;
16584
+ }
16585
+ /**
16586
+ * Releases the key of a channel (note off).
16587
+ * @param ch The channel.
16588
+ */
16589
+ keyOff(ch) {
16590
+ const keyWasOn = !ch.keyOff;
16591
+ ch.keyOff = true;
16592
+ if (ch.instrument && !ch.volumeEnvelopeState.enabled) ch.noteFade = true;
16593
+ if (!ch.playing) return;
16594
+ if (ch.sustainLoop && ch.sample && keyWasOn) {
16595
+ ch.sustainLoop = false;
16596
+ if (ch.sample.loopType !== TrackerLoopTypes.pingPong) ch.reverse = false;
16597
+ this.updateVariant(ch);
16598
+ }
16599
+ const instrument = ch.instrument;
16600
+ if (instrument && instrument.volumeEnvelope.loopEnd >= 0 && instrument.fadeout) ch.noteFade = true;
16601
+ }
16602
+ /**
16603
+ * Cuts the note on a tick (SCx).
16604
+ * @param ch The channel.
16605
+ * @param tick The tick to cut the note on.
16606
+ */
16607
+ noteCut(ch, tick) {
16608
+ let tickCount = this.rowTick;
16609
+ if (isNote(ch.rowNote) && this.isTonePortamento(ch)) {
16610
+ const rowLength = this.speed + this.frameDelay;
16611
+ if (tickCount < rowLength) return;
16612
+ tickCount %= rowLength;
16613
+ }
16614
+ if (tickCount === tick) {
16615
+ this.stopSample(ch);
16616
+ ch.active = false;
16617
+ ch.period = 0;
16618
+ ch.fadeout = 0;
16619
+ ch.noteFade = true;
16620
+ }
16621
+ }
16622
+ /**
16623
+ * Checks if the row of a channel has a tone portamento.
16624
+ * @param ch The channel.
16625
+ */
16626
+ isTonePortamento(ch) {
16627
+ return ch.rowEffect === ImpulseTrackerEffects.tonePortamento || ch.rowEffect === ImpulseTrackerEffects.tonePortamentoVolumeSlide || decodeVolume(ch.rowVolume)[0] === VolumeCommands.tonePortamento;
16628
+ }
16629
+ /**
16630
+ * Stops the sample of a channel.
16631
+ * @param ch The channel.
16632
+ */
16633
+ stopSample(ch) {
16634
+ if (ch.playing || ch.trigger) ch.stop = true;
16635
+ ch.trigger = false;
16636
+ ch.samplePosition = Infinity;
16637
+ }
16638
+ /**
16639
+ * Restores the panning and filter changed by the previous note (instrument panning, random variation).
16640
+ * @param ch The channel.
16641
+ */
16642
+ restorePanningAndFilter(ch) {
16643
+ if (ch.restorePanning > 0) {
16644
+ ch.panning = (ch.restorePanning & 32767) - 1;
16645
+ if (ch.restorePanning & 32768) ch.surround = true;
16646
+ ch.restorePanning = 0;
16647
+ }
16648
+ if (ch.restoreResonance > 0) {
16649
+ ch.resonance = ch.restoreResonance - 1;
16650
+ ch.restoreResonance = 0;
16651
+ }
16652
+ if (ch.restoreCutoff > 0) {
16653
+ ch.cutoff = ch.restoreCutoff - 1;
16654
+ ch.restoreCutoff = 0;
16655
+ }
16656
+ }
16657
+ /**
16658
+ * Applies the default panning of the instrument and the sample, for this note only.
16659
+ * @param ch The channel.
16660
+ * @param instrument The instrument.
16661
+ * @param sample The sample.
16662
+ */
16663
+ applyInstrumentPanning(ch, instrument, sample) {
16664
+ let panning = instrument?.panning ?? -1;
16665
+ if (sample && sample.panning >= 0) panning = sample.panning;
16666
+ if (panning < 0) return;
16667
+ ch.restorePanning = ch.panning + 1 | (ch.surround ? 32768 : 0);
16668
+ ch.panning = panning;
16669
+ ch.surround = false;
16670
+ }
16671
+ /**
16672
+ * Changes the instrument of a channel. A port of OpenMPT's InstrumentChange for Impulse Tracker.
16673
+ * @param ch The channel.
16674
+ * @param instrumentNumber The one-based instrument (or sample) number.
16675
+ * @param porta If there is a tone portamento.
16676
+ * @param updateVolume If the volume is reset to the sample's default.
16677
+ * @param resetEnvelopes If the envelopes may be reset.
16678
+ */
16679
+ instrumentChange(ch, instrumentNumber, porta, updateVolume, resetEnvelopes) {
16680
+ const instrument = this.instrumentMode ? this.itInstruments[instrumentNumber - 1] : void 0;
16681
+ let sampleIndex = this.instrumentMode ? -1 : instrumentNumber - 1;
16682
+ let sample = this.instrumentMode ? void 0 : this.getSample(sampleIndex);
16683
+ const oldInstrumentVolume = ch.instrumentVolume;
16684
+ const note = ch.newNote;
16685
+ if (note === 0) return;
16686
+ if (instrument && isNote(note)) {
16687
+ if (instrument.sampleMap[note - 1] < 0) {
16688
+ ch.instrument = instrument;
16689
+ ch.instrumentIndex = instrumentNumber - 1;
16690
+ return;
16691
+ }
16692
+ sampleIndex = instrument.sampleMap[note - 1];
16693
+ sample = this.getSample(sampleIndex);
16694
+ } else if (this.instrumentMode) {
16695
+ if (note >= NOTE_FADE) return;
16696
+ ch.instrument = void 0;
16697
+ ch.instrumentIndex = -1;
16698
+ ch.newInstrument = 0;
16699
+ return;
16700
+ }
16701
+ let instrumentChanged = instrument !== ch.instrument;
16702
+ const sampleChanged = ch.sample !== void 0 && sample !== ch.sample;
16703
+ let returnAfterVolume = false;
16704
+ if (sampleChanged && porta) {
16705
+ if (this.compatibleGxx && ch.active) {
16706
+ sample = ch.sample;
16707
+ sampleIndex = ch.sampleIndex;
16708
+ }
16709
+ if (!this.instrumentMode) ch.triggered = true;
16710
+ }
16711
+ if (this.instrumentMode && !instrumentChanged && sampleChanged && ch.sample && !isNote(ch.rowNote)) returnAfterVolume = true;
16712
+ if (!ch.active) instrumentChanged = true;
16713
+ ch.instrument = instrument;
16714
+ ch.instrumentIndex = instrument ? instrumentNumber - 1 : -1;
16715
+ if (updateVolume) ch.volume = sample ? sample.volume : 0;
16716
+ if (returnAfterVolume) return;
16717
+ ch.newInstrument = 0;
16718
+ if (instrument && instrumentChanged) ch.newNoteAction = instrument.newNoteAction;
16719
+ ch.instrumentVolume = Math.trunc((sample ? sample.globalVolume : 64) * (instrument?.globalVolume ?? 64) / 64);
16720
+ if (resetEnvelopes) {
16721
+ const hasNumber = instrumentNumber !== 0;
16722
+ const reset = !ch.playing || hasNumber && porta && this.compatibleGxx || hasNumber && !porta && (ch.noteFade || ch.keyOff) && this.oldEffects;
16723
+ const resetAlways = !ch.fadeout || instrumentChanged || !isNote(ch.rowNote);
16724
+ if (reset) {
16725
+ if (instrument) {
16726
+ if (resetAlways) ch.resetEnvelopes();
16727
+ else {
16728
+ const carryReset = porta && this.compatibleGxx;
16729
+ const last = this.lastMovedVoice;
16730
+ const resetEnvelope = (envelope, state, lastState) => {
16731
+ if (!envelope.carry) state.position = 0;
16732
+ else if (carryReset) state.position = lastState?.position ?? 0;
16733
+ };
16734
+ resetEnvelope(instrument.volumeEnvelope, ch.volumeEnvelopeState, last?.volumeEnvelopeState);
16735
+ resetEnvelope(instrument.panningEnvelope, ch.panningEnvelopeState, last?.panningEnvelopeState);
16736
+ resetEnvelope(instrument.pitchEnvelope, ch.pitchEnvelopeState, last?.pitchEnvelopeState);
16737
+ }
16738
+ }
16739
+ } else if (instrument && !instrument.volumeEnvelope.enabled) ch.volumeEnvelopeState.position = 0;
16740
+ }
16741
+ if (!sample) {
16742
+ ch.sample = void 0;
16743
+ ch.sampleIndex = -1;
16744
+ ch.instrumentVolume = 0;
16745
+ return;
16746
+ }
16747
+ const wasKeyOff = ch.keyOff;
16748
+ if (porta && sample === ch.sample) {
16749
+ if (instrumentChanged && instrument) {
16750
+ ch.keyOff = false;
16751
+ ch.noteFade = false;
16752
+ }
16753
+ if (ch.playing) return;
16754
+ ch.keyOff = false;
16755
+ ch.noteFade = false;
16756
+ } else {
16757
+ ch.keyOff = false;
16758
+ ch.noteFade = false;
16759
+ if (sample !== ch.sample || instrumentChanged) ch.reverse = false;
16760
+ if (instrument) {
16761
+ ch.volumeEnvelopeState.enabled = instrument.volumeEnvelope.enabled;
16762
+ ch.panningEnvelopeState.enabled = instrument.panningEnvelope.enabled;
16763
+ ch.pitchEnvelopeState.enabled = instrument.pitchEnvelope.enabled;
16764
+ if (instrument.cutoff >= 0) ch.cutoff = instrument.cutoff;
16765
+ if (instrument.resonance >= 0) ch.resonance = instrument.resonance;
16766
+ }
16767
+ }
16768
+ if (ch.rowNote === 254 && this.oldEffects && sampleChanged) {
16769
+ ch.instrumentVolume = oldInstrumentVolume;
16770
+ ch.volume = sample.volume;
16771
+ if (sample.panning >= 0) {
16772
+ ch.restorePanning = ch.panning + 1;
16773
+ ch.panning = sample.panning;
16774
+ }
16775
+ return;
16776
+ }
16777
+ const changed = sample !== ch.sample;
16778
+ ch.sample = sample;
16779
+ ch.sampleIndex = sample === EMPTY_SAMPLE ? -1 : sampleIndex;
16780
+ ch.sustainLoop = sample.sustainLoopType !== void 0 && sample.sustainLoopType !== TrackerLoopTypes.none && (!porta || instrument !== void 0 && !wasKeyOff);
16781
+ ch.autoVibratoDepth = 0;
16782
+ ch.autoVibratoPos = 0;
16783
+ ch.finetune = sample.middleCRate;
16784
+ ch.portamentoTarget = 0;
16785
+ if (changed && ch.playing && !ch.trigger) {
16786
+ ch.preset = this.sampleBank.getPreset(ch.sampleIndex, this.getVariant(ch));
16787
+ this.retrigger(ch, this.sampleBank.toSource(ch.preset, ch.samplePosition).position);
16788
+ } else this.updateVariant(ch);
16789
+ }
16790
+ /**
16791
+ * Starts a note (or changes the portamento target). A port of OpenMPT's NoteChange for Impulse Tracker.
16792
+ * @param ch The channel.
16793
+ * @param note The one-based note or a special note.
16794
+ * @param porta If there is a tone portamento.
16795
+ * @param resetEnvelopes If the envelopes and the random variations are reset.
16796
+ */
16797
+ noteChange(ch, note, porta, resetEnvelopes) {
16798
+ if (note === 0) return;
16799
+ const patternNote = note;
16800
+ let sample = ch.sample;
16801
+ let sampleIndex = ch.sampleIndex;
16802
+ const instrument = ch.instrument;
16803
+ if (instrument && isNote(note)) {
16804
+ const mapped = instrument.sampleMap[note - 1];
16805
+ if (mapped < 0) return;
16806
+ sampleIndex = mapped;
16807
+ sample = this.getSample(mapped);
16808
+ note = instrument.noteMap[note - 1] + 1;
16809
+ }
16810
+ if (!isNote(note)) {
16811
+ if (note === 254) {
16812
+ this.keyOff(ch);
16813
+ if (!porta && this.oldEffects && ch.rowInstrument) {
16814
+ ch.noteFade = false;
16815
+ ch.keyOff = false;
16816
+ }
16817
+ } else if (this.instrumentMode) ch.noteFade = true;
16818
+ if (note === 253) {
16819
+ ch.noteFade = true;
16820
+ ch.fadeout = 0;
16821
+ this.stopSample(ch);
16822
+ ch.active = false;
16823
+ }
16824
+ ch.note = 0;
16825
+ ch.newNote = 0;
16826
+ return;
16827
+ }
16828
+ if (!porta && sample) ch.finetune = sample.middleCRate;
16829
+ if (porta && !ch.active) porta = false;
16830
+ ch.note = patternNote;
16831
+ ch.newInstrument = 0;
16832
+ const frequency = this.noteToPeriod(note, ch);
16833
+ ch.panbrelloOffset = 0;
16834
+ this.applyInstrumentPanning(ch, instrument, sample);
16835
+ if (instrument?.pitchPanSeparation) {
16836
+ if (!ch.restorePanning) ch.restorePanning = ch.panning + 1;
16837
+ ch.panning = Math.min(256, Math.max(0, ch.panning + Math.trunc((patternNote - 1 - instrument.pitchPanCenter) * instrument.pitchPanSeparation / 2)));
16838
+ }
16839
+ if (resetEnvelopes && !porta) {
16840
+ ch.volumeSwing = 0;
16841
+ ch.panningSwing = 0;
16842
+ ch.cutoffSwing = 0;
16843
+ ch.resonanceSwing = 0;
16844
+ if (instrument) {
16845
+ ch.newNoteAction = instrument.newNoteAction;
16846
+ if (!instrument.volumeEnvelope.carry) ch.volumeEnvelopeState.position = 0;
16847
+ if (!instrument.panningEnvelope.carry) ch.panningEnvelopeState.position = 0;
16848
+ if (!instrument.pitchEnvelope.carry) ch.pitchEnvelopeState.position = 0;
16849
+ if (instrument.volumeSwing) ch.volumeSwing = Math.trunc((Math.trunc(this.randomInt8() * instrument.volumeSwing / 64) + 1) * ch.instrumentVolume / 199);
16850
+ if (instrument.panningSwing) ch.panningSwing = Math.trunc(this.randomInt8() * instrument.panningSwing * 4 / 128);
16851
+ if (instrument.cutoffSwing) {
16852
+ const d = Math.trunc(instrument.cutoffSwing * (this.randomInt8() + 1) / 128);
16853
+ ch.cutoffSwing = Math.trunc((d * ch.cutoff + 1) / 128);
16854
+ ch.restoreCutoff = ch.cutoff + 1;
16855
+ }
16856
+ if (instrument.resonanceSwing) {
16857
+ const d = Math.trunc(instrument.resonanceSwing * (this.randomInt8() + 1) / 128);
16858
+ ch.resonanceSwing = Math.trunc((d * ch.resonance + 1) / 128);
16859
+ ch.restoreResonance = ch.resonance + 1;
16860
+ }
16861
+ }
16862
+ }
16863
+ if (!sample) return;
16864
+ if (!porta || !ch.period) ch.period = frequency;
16865
+ ch.portamentoTarget = porta ? frequency : 0;
16866
+ if (!porta || !ch.playing) {
16867
+ ch.sample = sample;
16868
+ ch.sampleIndex = sample === EMPTY_SAMPLE ? -1 : sampleIndex;
16869
+ ch.sustainLoop = sample.sustainLoopType !== void 0 && sample.sustainLoopType !== TrackerLoopTypes.none;
16870
+ ch.portamentoActive = false;
16871
+ if (ch.vibratoType < 4) ch.vibratoPos = 0;
16872
+ ch.preset = ch.sampleIndex < 0 ? -1 : this.sampleBank.getPreset(ch.sampleIndex, this.getVariant(ch));
16873
+ ch.trigger = true;
16874
+ ch.stop = false;
16875
+ ch.samplePosition = 0;
16876
+ this.setSamplePosition(ch, ch.reverse ? Math.max(0, sample.data.length - 1) : 0);
16877
+ }
16878
+ if (!porta || ch.noteFade && !ch.fadeout || this.compatibleGxx && ch.rowInstrument) {
16879
+ if (ch.noteFade && !ch.fadeout) {
16880
+ ch.resetEnvelopes();
16881
+ ch.noteFade = false;
16882
+ ch.fadeout = 65536;
16883
+ }
16884
+ if (!porta || !this.compatibleGxx || ch.rowInstrument) {
16885
+ ch.noteFade = false;
16886
+ ch.fadeout = 65536;
16887
+ }
16888
+ }
16889
+ if (!porta || this.compatibleGxx && ch.rowInstrument) ch.keyOff = false;
16890
+ if (!porta) {
16891
+ ch.triggered = true;
16892
+ ch.filterEnabled = false;
16893
+ if (resetEnvelopes) {
16894
+ ch.autoVibratoDepth = 0;
16895
+ ch.autoVibratoPos = 0;
16896
+ }
16897
+ }
16898
+ }
16899
+ /**
16900
+ * Applies the duplicate checks and the new note action before a new note.
16901
+ * A port of OpenMPT's CheckNNA for Impulse Tracker.
16902
+ * @param ch The channel.
16903
+ * @param instrumentNumber The one-based instrument number of the new note, 0 if none.
16904
+ * @param note The one-based note.
16905
+ * @param forceCut If the previous note is always cut (retrigger).
16906
+ */
16907
+ checkNNA(ch, instrumentNumber, note, forceCut) {
16908
+ if (!isNote(note)) return;
16909
+ if (!this.instrumentMode || forceCut) {
16910
+ if (ch.playing) this.stopSample(ch);
16911
+ return;
16912
+ }
16913
+ let instrument = ch.instrument;
16914
+ if (instrumentNumber > 0) instrument = this.itInstruments[instrumentNumber - 1];
16915
+ let sample = ch.sample;
16916
+ if (instrument) {
16917
+ const mapped = instrument.sampleMap[note - 1];
16918
+ if (mapped < 0) return;
16919
+ sample = this.getSample(mapped);
16920
+ }
16921
+ const voices = [ch, ...this.backgroundVoices.filter((v) => v.index === ch.index)];
16922
+ for (const voice of voices) {
16923
+ const voiceInstrument = voice.instrument;
16924
+ if (!voiceInstrument) continue;
16925
+ let duplicate = false;
16926
+ switch (voiceInstrument.duplicateCheckType) {
16927
+ default: break;
16928
+ case 1:
16929
+ duplicate = voice.note === note && instrument === voiceInstrument;
16930
+ break;
16931
+ case 2:
16932
+ duplicate = sample !== void 0 && sample === voice.sample && instrument === voiceInstrument;
16933
+ break;
16934
+ case 3: duplicate = instrument === voiceInstrument;
16935
+ }
16936
+ if (!duplicate) continue;
16937
+ switch (voiceInstrument.duplicateCheckAction) {
16938
+ default:
16939
+ this.keyOff(voice);
16940
+ voice.volume = 0;
16941
+ break;
16942
+ case 1:
16943
+ this.keyOff(voice);
16944
+ break;
16945
+ case 2: voice.noteFade = true;
16946
+ }
16947
+ if (!voice.volume) {
16948
+ voice.fadeout = 0;
16949
+ voice.noteFade = true;
16950
+ }
16951
+ }
16952
+ if (!ch.active) return;
16953
+ if (ch.newNoteAction === NoteActions.cut) {
16954
+ this.stopSample(ch);
16955
+ return;
16956
+ }
16957
+ const voice = this.moveToBackground(ch);
16958
+ ch.samplePosition = Infinity;
16959
+ if (!voice) return;
16960
+ voice.vibratoActive = false;
16961
+ voice.tremoloActive = false;
16962
+ voice.portamentoActive = false;
16963
+ voice.panbrelloOffset = 0;
16964
+ voice.command = 0;
16965
+ voice.triggered = false;
16966
+ if (ch.instrument === instrument) this.lastMovedVoice = voice;
16967
+ switch (ch.newNoteAction) {
16968
+ default: break;
16969
+ case NoteActions.noteOff:
16970
+ this.keyOff(voice);
16971
+ break;
16972
+ case NoteActions.noteFade: voice.noteFade = true;
16973
+ }
16974
+ if (!voice.volume) {
16975
+ voice.fadeout = 0;
16976
+ voice.noteFade = true;
16977
+ }
16978
+ }
16979
+ /**
16980
+ * Processes the retrigger effect (Qxy).
16981
+ * @param ch The channel.
16982
+ * @param param The parameter (volume change in the high nibble, interval in the low nibble).
16983
+ */
16984
+ retriggerNote(ch, param) {
16985
+ let doRetrigger = false;
16986
+ if (this.rowTick === 0 && ch.rowNote) ch.retriggerCount = param & 15;
16987
+ else if (!ch.retriggerCount || !--ch.retriggerCount) {
16988
+ ch.retriggerCount = param & 15;
16989
+ doRetrigger = true;
16990
+ }
16991
+ if (!ch.playing && !this.retriggerStoppedSamples || !doRetrigger) return;
16992
+ const change = param >> 4;
16993
+ let volume = ch.volume * 4;
16994
+ if (change) {
16995
+ volume = RETRIGGER_MULTIPLIERS[change] ? Math.trunc(volume * RETRIGGER_MULTIPLIERS[change] / 16) : volume + RETRIGGER_OFFSETS[change] * 4;
16996
+ volume = Math.min(256, Math.max(0, volume));
16997
+ }
16998
+ const note = ch.newNote;
16999
+ const oldPeriod = ch.period;
17000
+ if (isNote(note)) this.checkNNA(ch, 0, note, true);
17001
+ this.noteChange(ch, note, true, false);
17002
+ ch.volume = volume / 4;
17003
+ if (this.instrumentMode) ch.rowNote = note;
17004
+ else if (ch.rowNote === 0 && oldPeriod) ch.period = oldPeriod;
17005
+ this.retrigger(ch, 0);
17006
+ }
17007
+ /**
17008
+ * Processes an extended effect (Sxy).
17009
+ * @param ch The channel.
17010
+ * @param param The effect parameter, with the memory applied.
17011
+ */
17012
+ extendedEffect(ch, param) {
17013
+ const value = param & 15;
17014
+ const firstTick = this.tick === 0;
17015
+ switch (param >> 4) {
17016
+ default: break;
17017
+ case ImpulseTrackerExtendedEffects.glissando:
17018
+ ch.glissando = value !== 0;
17019
+ break;
17020
+ case ImpulseTrackerExtendedEffects.finetune:
17021
+ if (firstTick) {
17022
+ ch.finetune = FINETUNE_RATES[value];
17023
+ if (ch.period && isNote(ch.note)) {
17024
+ const mapped = ch.instrument ? ch.instrument.noteMap[ch.note - 1] + 1 : ch.note;
17025
+ ch.period = this.noteToPeriod(mapped, ch);
17026
+ }
17027
+ }
17028
+ break;
17029
+ case ImpulseTrackerExtendedEffects.vibratoWaveform:
17030
+ ch.vibratoType = value < 4 ? value : 0;
17031
+ break;
17032
+ case ImpulseTrackerExtendedEffects.tremoloWaveform:
17033
+ ch.tremoloType = value < 4 ? value : 0;
17034
+ break;
17035
+ case ImpulseTrackerExtendedEffects.panbrelloWaveform:
17036
+ ch.panbrelloType = value < 4 ? value : 0;
17037
+ ch.panbrelloPos = 0;
17038
+ break;
17039
+ case ImpulseTrackerExtendedEffects.fineRowDelay:
17040
+ if (firstTick && this.rowTick === 0) this.frameDelay += value;
17041
+ break;
17042
+ case ImpulseTrackerExtendedEffects.instrumentControl:
17043
+ if (firstTick) this.instrumentControl(ch, value);
17044
+ break;
17045
+ case ImpulseTrackerExtendedEffects.panning:
17046
+ if (firstTick) this.setPanning(ch, Math.trunc((value * 256 + 8) / 15));
17047
+ break;
17048
+ case ImpulseTrackerExtendedEffects.soundControl:
17049
+ if (firstTick) this.soundControl(ch, value);
17050
+ break;
17051
+ case ImpulseTrackerExtendedEffects.highOffset:
17052
+ if (firstTick) ch.oldHighOffset = value;
17053
+ break;
17054
+ case ImpulseTrackerExtendedEffects.patternLoop:
17055
+ if (firstTick) this.patternLoopIT(ch, value);
17056
+ break;
17057
+ case ImpulseTrackerExtendedEffects.noteCut:
17058
+ this.noteCut(ch, value || 1);
17059
+ break;
17060
+ case ImpulseTrackerExtendedEffects.activeMacro: ch.activeMacro = value;
17061
+ }
17062
+ }
17063
+ /**
17064
+ * Processes a pattern loop (SBx), following Impulse Tracker.
17065
+ * @param ch The channel.
17066
+ * @param count Zero sets the loop start, other values loop that many times.
17067
+ */
17068
+ patternLoopIT(ch, count) {
17069
+ if (count === 0) {
17070
+ ch.patternLoopRow = this.currentRow;
17071
+ return;
17072
+ }
17073
+ if (ch.patternLoopCount) {
17074
+ if (--ch.patternLoopCount === 0) {
17075
+ ch.patternLoopRow = this.currentRow + 1;
17076
+ return;
17077
+ }
17078
+ } else ch.patternLoopCount = count;
17079
+ this.setPatternLoopTarget(ch.patternLoopRow);
17080
+ this.clearPositionJump();
17081
+ }
17082
+ /**
17083
+ * Processes the past note actions, new note action overrides and envelope toggles (S7x).
17084
+ * @param ch The channel.
17085
+ * @param value The effect value.
17086
+ */
17087
+ instrumentControl(ch, value) {
17088
+ switch (value) {
17089
+ case 0:
17090
+ case 1:
17091
+ case 2:
17092
+ for (const voice of this.backgroundVoices) {
17093
+ if (voice.index !== ch.index) continue;
17094
+ if (value === 1) this.keyOff(voice);
17095
+ else {
17096
+ voice.noteFade = true;
17097
+ if (value === 0) voice.fadeout = 0;
17098
+ }
17099
+ }
17100
+ break;
17101
+ case 3:
17102
+ ch.newNoteAction = NoteActions.cut;
17103
+ break;
17104
+ case 4:
17105
+ ch.newNoteAction = NoteActions.continue;
17106
+ break;
17107
+ case 5:
17108
+ ch.newNoteAction = NoteActions.noteOff;
17109
+ break;
17110
+ case 6:
17111
+ ch.newNoteAction = NoteActions.noteFade;
17112
+ break;
17113
+ case 7:
17114
+ ch.volumeEnvelopeState.enabled = false;
17115
+ break;
17116
+ case 8:
17117
+ ch.volumeEnvelopeState.enabled = true;
17118
+ break;
17119
+ case 9:
17120
+ ch.panningEnvelopeState.enabled = false;
17121
+ break;
17122
+ case 10:
17123
+ ch.panningEnvelopeState.enabled = true;
17124
+ break;
17125
+ case 11:
17126
+ ch.pitchEnvelopeState.enabled = false;
17127
+ break;
17128
+ case 12: ch.pitchEnvelopeState.enabled = true;
17129
+ }
17130
+ }
17131
+ /**
17132
+ * Processes the sound control effects (S9x).
17133
+ * @param ch The channel.
17134
+ * @param value The effect value.
17135
+ */
17136
+ soundControl(ch, value) {
17137
+ switch (value) {
17138
+ case 0:
17139
+ ch.surround = false;
17140
+ break;
17141
+ case 1:
17142
+ ch.surround = true;
17143
+ ch.panning = 128;
17144
+ break;
17145
+ case 12:
17146
+ this.openMPTFilterMode = false;
17147
+ break;
17148
+ case 13:
17149
+ this.openMPTFilterMode = true;
17150
+ break;
17151
+ case 14:
17152
+ if (ch.reverse) {
17153
+ ch.reverse = false;
17154
+ this.updateVariant(ch);
17155
+ }
17156
+ break;
17157
+ case 15: {
17158
+ if (ch.reverse || !ch.sample) break;
17159
+ const sample = ch.sample;
17160
+ const looped = (ch.sustainLoop ? sample.sustainLoopType : sample.loopType) !== TrackerLoopTypes.none;
17161
+ const atStart = ch.trigger ? ch.sampleOffset === 0 : ch.samplePosition === 0;
17162
+ ch.reverse = true;
17163
+ if (atStart && (isNote(ch.rowNote) || !looped)) {
17164
+ ch.preset = this.sampleBank.getPreset(ch.sampleIndex, TrackerSampleVariants.reverse);
17165
+ this.retrigger(ch, Math.max(0, sample.data.length - 1));
17166
+ } else this.updateVariant(ch);
17167
+ break;
17168
+ }
17169
+ }
17170
+ }
17171
+ /**
17172
+ * Advances the position of an envelope by one tick, following the Impulse Tracker loop rules.
17173
+ * @param ch The channel.
17174
+ * @param state The envelope state.
17175
+ * @param envelope The instrument envelope.
17176
+ * @param isVolume If this is the volume envelope, which starts the fadeout at its end.
17177
+ */
17178
+ incrementEnvelope(ch, state, envelope, isVolume) {
17179
+ const points = envelope.points;
17180
+ if (!state.enabled || points.length === 0) return;
17181
+ let position = state.position;
17182
+ let start;
17183
+ let end;
17184
+ let endReached = false;
17185
+ if (envelope.sustainPoint >= 0 && !ch.previousKeyOff) {
17186
+ start = points[envelope.sustainStart].tick;
17187
+ end = points[envelope.sustainPoint].tick + 1;
17188
+ } else if (envelope.loopEnd >= 0) {
17189
+ start = points[envelope.loopStart].tick;
17190
+ end = points[envelope.loopEnd].tick + 1;
17191
+ } else {
17192
+ start = end = points[points.length - 1].tick;
17193
+ if (position > end) endReached = true;
17194
+ }
17195
+ if (position >= end) position = start;
17196
+ if (isVolume && endReached) {
17197
+ ch.noteFade = true;
17198
+ if (points[points.length - 1].value === 0) ch.fadeout = 0;
17199
+ }
17200
+ state.position = position + 1;
17201
+ }
17202
+ /**
17203
+ * Sets up the resonant filter of a channel. A port of OpenMPT's SetupChannelFilter.
17204
+ * @param ch The channel.
17205
+ * @param envelopeModifier The filter envelope value (-256 to 256), 256 without the envelope.
17206
+ */
17207
+ setupFilter(ch, envelopeModifier) {
17208
+ const cutoff = Math.min(127, Math.max(0, ch.cutoff + ch.cutoffSwing));
17209
+ const resonance = Math.min(127, Math.max(0, ch.resonance + ch.resonanceSwing));
17210
+ ch.cutoff = cutoff;
17211
+ ch.resonance = resonance;
17212
+ ch.cutoffSwing = 0;
17213
+ ch.resonanceSwing = 0;
17214
+ const computed = Math.trunc(cutoff * (envelopeModifier + 256) / 256);
17215
+ if (resonance === 0 && computed >= 254) {
17216
+ if (ch.triggered) ch.filterEnabled = false;
17217
+ return;
17218
+ }
17219
+ ch.filterEnabled = true;
17220
+ ch.filterCutoffValue = cutoff * (envelopeModifier + 256) / 512;
17221
+ }
17222
+ /**
17223
+ * Gets the value of a MIDI macro variable.
17224
+ * @param ch The channel.
17225
+ * @param variable The variable letter.
17226
+ * @param param The Zxx parameter.
17227
+ */
17228
+ getMacroVariable(ch, variable, param) {
17229
+ const volumes = this.globalVolume * 4 * ch.channelVolume * ch.instrumentVolume;
17230
+ switch (variable) {
17231
+ default: return 0;
17232
+ case "z": return param;
17233
+ case "n": return isNote(ch.lastNote) ? ch.lastNote - 1 : 0;
17234
+ case "v": {
17235
+ const volume = (ch.volume * 4 + ch.volumeSwing) * volumes / (1 << 20);
17236
+ return Math.min(127, Math.max(1, Math.trunc(volume / 2)));
17237
+ }
17238
+ case "u": {
17239
+ const volume = (ch.volume + ch.volumeDelta) * 4 * ch.envelopeVolume * ch.fadeoutVolume * volumes / (1 << 20);
17240
+ return Math.min(127, Math.max(1, Math.trunc(volume / 2)));
17241
+ }
17242
+ case "x": return Math.min(127, Math.trunc(ch.panning / 2));
17243
+ case "y": {
17244
+ const panning = ch.outputPanning >= 0 ? ch.outputPanning : ch.panning;
17245
+ return Math.min(127, Math.trunc(panning / 2));
17246
+ }
17247
+ case "o": return ch.oldOffset >> 8 & 255;
17248
+ case "h": return ch.index & 127;
17249
+ case "m": return ch.reverse ? 1 : 0;
17250
+ }
17251
+ }
17252
+ /**
17253
+ * Processes the Zxx and \xx MIDI macros of a channel. Only the internal filter macros have an effect.
17254
+ * @param ch The channel.
17255
+ */
17256
+ processMacro(ch) {
17257
+ const effect = ch.rowEffect;
17258
+ const smooth = effect === ImpulseTrackerEffects.smoothMidiMacro;
17259
+ if (!(effect === ImpulseTrackerEffects.midiMacro && this.tick === 0 || smooth)) return;
17260
+ const param = ch.rowParam;
17261
+ const macro = param < 128 ? this.parameteredMacros[ch.activeMacro] : this.fixedMacros[param & 127];
17262
+ const bytes = new Array();
17263
+ let firstNibble = true;
17264
+ for (const char of macro) {
17265
+ let data;
17266
+ let isNibble = true;
17267
+ if (char >= "0" && char <= "9") data = char.charCodeAt(0) - 48;
17268
+ else if (char >= "A" && char <= "F") data = char.charCodeAt(0) - 55;
17269
+ else if (char === "c") data = 0;
17270
+ else if ("znvuxyohmabp".includes(char)) {
17271
+ data = this.getMacroVariable(ch, char, param);
17272
+ isNibble = false;
17273
+ } else continue;
17274
+ if (isNibble) {
17275
+ if (firstNibble) bytes.push(data);
17276
+ else bytes[bytes.length - 1] = bytes[bytes.length - 1] << 4 | data;
17277
+ firstNibble = !firstNibble;
17278
+ } else {
17279
+ bytes.push(data);
17280
+ firstNibble = true;
17281
+ }
17282
+ }
17283
+ for (let i = 0; i < bytes.length; i++) {
17284
+ const byte = bytes[i];
17285
+ if (byte === 250 || byte === 252 || byte === 255) {
17286
+ for (const channel of this.channels) {
17287
+ channel.cutoff = 127;
17288
+ channel.resonance = 0;
17289
+ }
17290
+ continue;
17291
+ }
17292
+ if (byte !== 240 || bytes[i + 1] !== 240 || i + 3 >= bytes.length) continue;
17293
+ const code = bytes[i + 2];
17294
+ const value = bytes[i + 3];
17295
+ i += 3;
17296
+ if (value >= 128 || code > 1) continue;
17297
+ const current = code === 0 ? ch.cutoff : ch.resonance;
17298
+ let target = value;
17299
+ if (smooth) {
17300
+ const ticksLeft = this.rowTicks - this.rowTick;
17301
+ if (ticksLeft > 1) target = Math.round(current + (value - current) / ticksLeft);
17302
+ }
17303
+ if (code === 0) {
17304
+ ch.cutoff = target;
17305
+ ch.restoreCutoff = 0;
17306
+ } else {
17307
+ ch.resonance = target;
17308
+ ch.restoreResonance = 0;
17309
+ }
17310
+ this.setupFilter(ch, 256);
17311
+ }
17312
+ }
17313
+ };
13802
17314
  // src/midi/read/tracker/load_tracker_module.ts
13803
17315
  /**
13804
17316
  * Detects a tracker module and converts it into the given MIDI.
@@ -13810,6 +17322,7 @@ var ScreamTrackerModule = class extends TrackerModule {
13810
17322
  function loadTrackerModule(outputMIDI, binary, fileName) {
13811
17323
  let module;
13812
17324
  if (FastTrackerModule.isXM(binary)) module = new FastTrackerModule();
17325
+ else if (ImpulseTrackerModule.isIT(binary)) module = new ImpulseTrackerModule();
13813
17326
  else if (ScreamTrackerModule.isS3M(binary)) module = new ScreamTrackerModule();
13814
17327
  else if (ProTrackerModule.getChannelCount(binary) > 0) module = new ProTrackerModule();
13815
17328
  else return false;
@@ -14056,6 +17569,8 @@ const DEFAULT_RMIDI_WRITE_OPTIONS = {
14056
17569
  * @returns the binary data
14057
17570
  */
14058
17571
  function writeRMIDIInternal(mid, soundBankBinary, options) {
17572
+ const offset = options.bankOffset;
17573
+ if (!Number.isInteger(offset) || offset < 0 || offset > 127) throw new Error(`Invalid bank offset: ${offset}. It must be an integer between 0 and 127.`);
14059
17574
  const metadata = { ...options.metadata };
14060
17575
  SpessaLog.group("%cWriting the RMIDI File...", ConsoleColors.info);
14061
17576
  SpessaLog.info("metadata", metadata);
@@ -14077,6 +17592,7 @@ function writeRMIDIInternal(mid, soundBankBinary, options) {
14077
17592
  for (const v of Object.entries(mid.rmidiInfo)) {
14078
17593
  const type = v[0];
14079
17594
  const data = v[1];
17595
+ if (data.length === 0) continue;
14080
17596
  switch (type) {
14081
17597
  case "album":
14082
17598
  writeInfo("IALB", data);
@@ -14119,15 +17635,16 @@ function writeRMIDIInternal(mid, soundBankBinary, options) {
14119
17635
  }
14120
17636
  }
14121
17637
  const DBNK = new IndexedByteArray(2);
14122
- writeLittleEndianIndexed(DBNK, options.bankOffset, 2);
14123
- infoContent.push(RIFFChunk.write("DBNK", DBNK));
17638
+ writeLittleEndianIndexed(DBNK, offset, 2);
17639
+ infoContent.push(RIFFChunk.write("DBNK", DBNK), ...mid.rmidiExtraChunks.info);
14124
17640
  SpessaLog.info("%cFinished!", ConsoleColors.info);
14125
17641
  SpessaLog.groupEnd();
14126
17642
  return RIFFChunk.writeParts("RIFF", [
14127
17643
  getStringBytes("RMID"),
14128
17644
  RIFFChunk.write("data", newMid),
14129
17645
  RIFFChunk.writeParts("INFO", infoContent, false, true),
14130
- new IndexedByteArray(soundBankBinary)
17646
+ new IndexedByteArray(soundBankBinary),
17647
+ ...mid.rmidiExtraChunks.file
14131
17648
  ]).buffer;
14132
17649
  }
14133
17650
  // src/midi/basic_midi.ts
@@ -14285,6 +17802,21 @@ var BasicMIDI = class BasicMIDI {
14285
17802
  */
14286
17803
  rmidiInfo = {};
14287
17804
  /**
17805
+ * RMIDI chunks that SpessaSynth does not recognize, kept so {@link BasicMIDI.writeRMIDI} can write them back.
17806
+ * Each entry is a complete RIFF chunk (FourCC, size, data and the pad byte).
17807
+ *
17808
+ * - `info` holds unknown chunks from the `INFO` list.
17809
+ * - `file` holds unknown chunks from the main `RIFF` chunk. They get written after the sound bank.
17810
+ *
17811
+ * > **Tip**
17812
+ * >
17813
+ * > See [SF2 RMIDI Extension Specification](https://github.com/spessasus/sf2-rmidi-specification#handling-differences) for more info.
17814
+ */
17815
+ rmidiExtraChunks = {
17816
+ info: new Array(),
17817
+ file: new Array()
17818
+ };
17819
+ /**
14288
17820
  * The bank offset used for RMID files.
14289
17821
  * Only applies to RMID, for normal MIDIs it's set to 0.
14290
17822
  */
@@ -14334,7 +17866,7 @@ var BasicMIDI = class BasicMIDI {
14334
17866
  return readBinaryString(encodingInfo, lengthToRead);
14335
17867
  }
14336
17868
  /**
14337
- * Loads a MIDI file (SMF, RMIDI, XMF, MOD, XM, S3M) from a given ArrayBuffer.
17869
+ * Loads a MIDI file (SMF, RMIDI, XMF, Tracker Modules) from a given ArrayBuffer.
14338
17870
  * @param arrayBuffer The ArrayBuffer containing the binary file data.
14339
17871
  * @param fileName The _optional_ name of the file, will be used if the MIDI file does not have a name.
14340
17872
  *
@@ -14343,8 +17875,7 @@ var BasicMIDI = class BasicMIDI {
14343
17875
  * and populates the BasicMIDI instance with the parsed data.
14344
17876
  * It supports Standard MIDI Files (SMF), RIFF MIDI (RMIDI), and Extensible Music Format (XMF).
14345
17877
  * It also handles embedded soundbanks in RMIDI and XMF files.
14346
- * Tracker modules (ProTracker MOD, Fast Tracker 2 XM, Scream Tracker 3 S3M) are converted
14347
- * into MIDI with an embedded sound bank.
17878
+ * Tracker modules are converted into MIDI with an embedded sound bank.
14348
17879
  */
14349
17880
  static fromArrayBuffer(arrayBuffer, fileName = "") {
14350
17881
  const mid = new BasicMIDI();
@@ -14364,7 +17895,7 @@ var BasicMIDI = class BasicMIDI {
14364
17895
  return mid;
14365
17896
  }
14366
17897
  /**
14367
- * Loads a MIDI file (SMF, RMIDI, XMF, MOD, XM, S3M) from a given file.
17898
+ * Loads a MIDI file (SMF, RMIDI, XMF, Tracker Modules) from a given file.
14368
17899
  * @param file The file to load.
14369
17900
  */
14370
17901
  static async fromFile(file) {
@@ -14764,7 +18295,7 @@ var BasicMIDI = class BasicMIDI {
14764
18295
  * > Do not call in audioWorkletGlobalScope as it uses TextDecoder.
14765
18296
  *
14766
18297
  * @param infoType The metadata type.
14767
- * @returns `string`, `Date`, `ArrayBuffer` or undefined if the info is not set.
18298
+ * @returns `string`, `Date`, `ArrayBuffer` or undefined if the info is not set (or the creation date cannot be parsed).
14768
18299
  */
14769
18300
  getRMIDInfo(infoType) {
14770
18301
  if (!this.rmidiInfo[infoType]) return;
@@ -14848,6 +18379,10 @@ var BasicMIDI = class BasicMIDI {
14848
18379
  const value = v[1];
14849
18380
  this.rmidiInfo[key] = new Uint8Array(value);
14850
18381
  }
18382
+ this.rmidiExtraChunks = {
18383
+ info: mid.rmidiExtraChunks.info.map((c) => c.slice()),
18384
+ file: mid.rmidiExtraChunks.file.map((c) => c.slice())
18385
+ };
14851
18386
  }
14852
18387
  /**
14853
18388
  * Parses internal MIDI values
@@ -31642,7 +35177,7 @@ const GSInsertionControlSources = {
31642
35177
  */
31643
35178
  pitchBend: 113
31644
35179
  };
31645
- // src/synthesizer/audio_engine/effects/implementation/dattorro.ts
35180
+ // src/synthesizer/audio_engine/effects/gs/implementation/dsp/dattorro.ts
31646
35181
  /**
31647
35182
  * Dattorro Reverb Node
31648
35183
  * by khoin on GitHub, public domain.
@@ -31908,7 +35443,7 @@ var DattorroReverb = class {
31908
35443
  this.delayMask[index] = nextPow2 - 1;
31909
35444
  }
31910
35445
  };
31911
- // src/synthesizer/audio_engine/effects/implementation/delay_line.ts
35446
+ // src/synthesizer/audio_engine/effects/gs/implementation/dsp/delay_line.ts
31912
35447
  var DelayLine$1 = class {
31913
35448
  feedback = 0;
31914
35449
  gain = 1;
@@ -53069,6 +56604,7 @@ var SoundBankManager = class {
53069
56604
  * @param id The unique ID to assign to the sound bank.
53070
56605
  * If a sound bank with this ID already exists, it will be replaced.
53071
56606
  * @param bankOffset The bank offset of the sound bank. Offsets the bank MSB value of all presets in this sound bank.
56607
+ * Presets that would end up above bank 127 are left out.
53072
56608
  * @param reset If the synthesizer should reset (put every channel's controllers back to defaults) after the change.
53073
56609
  * Set it to `false` to keep a song playing, the channels then only update to the new presets.
53074
56610
  */
@@ -53140,6 +56676,7 @@ var SoundBankManager = class {
53140
56676
  const bank = s.soundBank;
53141
56677
  const bankOffset = s.bankOffset;
53142
56678
  for (const p of bank.presets) {
56679
+ if (p.bankMSB + bankOffset > 127 && !BankSelectHacks.isXGDrum(p.bankMSB)) continue;
53143
56680
  const selectablePreset = new SoundBankManagerPreset(p, bankOffset);
53144
56681
  const key = selectablePreset.toMIDIString();
53145
56682
  if (!addedPresets.has(key)) {
@@ -53424,8 +56961,10 @@ function renderVoice(voice, timeNow, sampleCount) {
53424
56961
  {
53425
56962
  const f = voice.filter;
53426
56963
  const initialFc = modulated[GeneratorTypes.initialFilterFc];
53427
- if (f.initialized) f.currentInitialFc += (initialFc - f.currentInitialFc) * f.smoothingConstant;
53428
- else {
56964
+ if (f.initialized) {
56965
+ const step = f.smoothingStep;
56966
+ f.currentInitialFc += Math.max(-step, Math.min(step, initialFc - f.currentInitialFc));
56967
+ } else {
53429
56968
  f.initialized = true;
53430
56969
  f.currentInitialFc = initialFc;
53431
56970
  }
@@ -55386,9 +58925,10 @@ var MIDIChannel = class {
55386
58925
  const channelMIDI = this._midiParameters;
55387
58926
  const midiKeyShift = globalMIDI.keyShift + channelMIDI.keyShift;
55388
58927
  const pitchBased = globalSystem.pitchBasedKeyShift;
58928
+ const drumFineTune = this._drumChannel && this.channelSystem === "xg" ? channelMIDI.keyShift * 100 : 0;
55389
58929
  const currentKeyShift = this._drumChannel ? channelSystem.keyShift : globalSystem.keyShift + (pitchBased ? 0 : midiKeyShift) + channelSystem.keyShift;
55390
58930
  this.currentKeyShift = Math.trunc(currentKeyShift);
55391
- this.currentTuning = this._drumChannel ? channelSystem.fineTune : globalSystem.fineTune + globalMIDI.fineTune + channelSystem.fineTune + channelMIDI.fineTune + (pitchBased ? midiKeyShift * 100 : 0);
58931
+ this.currentTuning = this._drumChannel ? channelSystem.fineTune + drumFineTune : globalSystem.fineTune + globalMIDI.fineTune + channelSystem.fineTune + channelMIDI.fineTune + (pitchBased ? midiKeyShift * 100 : 0);
55392
58932
  const currentPanNormalized = globalSystem.pan + globalMIDI.pan + channelSystem.pan;
55393
58933
  this.currentPan = currentPanNormalized * 500;
55394
58934
  this.currentGain = SPESSASYNTH_GAIN_FACTOR * globalSystem.gain * Math.pow(globalMIDI.volume, 2) * channelSystem.gain;
@@ -55633,16 +59173,6 @@ function setSystemParameterInternal(parameter, value) {
55633
59173
  case "pitchBasedKeyShift": this.stopAll(true);
55634
59174
  }
55635
59175
  }
55636
- // src/synthesizer/audio_engine/voice/lowpass_filter.ts
55637
- /**
55638
- * Applies a lowpass filter to a voice.
55639
- * A lot of the tricks here come from FluidSynth.
55640
- * They are the real smart guys.
55641
- * Shoutout to them!
55642
- * Give their repo a star over at:
55643
- * https://github.com/FluidSynth/fluidsynth
55644
- */
55645
- const FILTER_SMOOTHING_FACTOR = .03;
55646
59176
  const CHUNK_BITS = 7;
55647
59177
  const CHUNK_MASK = 127;
55648
59178
  const CACHE_MAX_CENTS = 16384;
@@ -55653,10 +59183,10 @@ var LowpassFilter = class LowpassFilter {
55653
59183
  */
55654
59184
  static caches = /* @__PURE__ */ new Map();
55655
59185
  /**
55656
- * For smoothing the filter cutoff frequency.
59186
+ * The largest change of the cutoff frequency (in cents) per rendering quantum.
55657
59187
  * This is per filter, as it depends on the sample rate.
55658
59188
  */
55659
- smoothingConstant;
59189
+ smoothingStep;
55660
59190
  /**
55661
59191
  * Resonance in centibels.
55662
59192
  */
@@ -55738,7 +59268,7 @@ var LowpassFilter = class LowpassFilter {
55738
59268
  constructor(sampleRate) {
55739
59269
  this.sampleRate = sampleRate;
55740
59270
  this.maxCutoff = sampleRate * .45;
55741
- this.smoothingConstant = FILTER_SMOOTHING_FACTOR * (44100 / sampleRate);
59271
+ this.smoothingStep = 300 * (44100 / sampleRate);
55742
59272
  this.coefficientCache = LowpassFilter.initCache(sampleRate);
55743
59273
  }
55744
59274
  /**
@@ -59020,7 +62550,7 @@ var SoundFont2 = class extends BasicSoundBank {
59020
62550
  }
59021
62551
  break;
59022
62552
  case "ICRD":
59023
- this.soundBankInfo.creationDate = parseDateString(readBinaryStringIndexed(chunk.data, chunk.data.length));
62553
+ this.soundBankInfo.creationDate = parseDateString(readBinaryStringIndexed(chunk.data, chunk.data.length)) ?? /* @__PURE__ */ new Date();
59024
62554
  break;
59025
62555
  case "ISFT":
59026
62556
  this.soundBankInfo.software = text;