spessasynth_lib 3.26.6 → 3.26.7

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.
Files changed (31) hide show
  1. package/index.js +7 -7
  2. package/package.json +1 -1
  3. package/{sequencer → src/sequencer}/README.md +2 -4
  4. package/{synthetizer → src/synthetizer}/README.md +2 -10
  5. package/synthetizer/worklet_processor.min.js +1 -1
  6. package/build.sh +0 -8
  7. package/debug_disable.sh +0 -5
  8. package/debug_enable.sh +0 -3
  9. /package/{external_midi → src/external_midi}/README.md +0 -0
  10. /package/{external_midi → src/external_midi}/midi_handler.js +0 -0
  11. /package/{external_midi → src/external_midi}/web_midi_link.js +0 -0
  12. /package/{sequencer → src/sequencer}/default_sequencer_options.js +0 -0
  13. /package/{sequencer → src/sequencer}/midi_data.js +0 -0
  14. /package/{sequencer → src/sequencer}/sequencer.js +0 -0
  15. /package/{sequencer → src/sequencer}/sequencer_message.js +0 -0
  16. /package/{synthetizer → src/synthetizer}/audio_effects/effects_config.js +0 -0
  17. /package/{synthetizer → src/synthetizer}/audio_effects/fancy_chorus.js +0 -0
  18. /package/{synthetizer → src/synthetizer}/audio_effects/rb_compressed.min.js +0 -0
  19. /package/{synthetizer → src/synthetizer}/audio_effects/reverb.js +0 -0
  20. /package/{synthetizer → src/synthetizer}/audio_effects/reverb_as_binary.js +0 -0
  21. /package/{synthetizer → src/synthetizer}/key_modifier_manager.js +0 -0
  22. /package/{synthetizer → src/synthetizer}/sfman_message.js +0 -0
  23. /package/{synthetizer → src/synthetizer}/synth_event_handler.js +0 -0
  24. /package/{synthetizer → src/synthetizer}/synth_soundfont_manager.js +0 -0
  25. /package/{synthetizer → src/synthetizer}/synthetizer.js +0 -0
  26. /package/{synthetizer → src/synthetizer}/worklet_message.js +0 -0
  27. /package/{synthetizer → src/synthetizer}/worklet_processor.js +0 -0
  28. /package/{synthetizer → src/synthetizer}/worklet_url.js +0 -0
  29. /package/{utils → src/utils}/buffer_to_wav.js +0 -0
  30. /package/{utils → src/utils}/fill_with_defaults.js +0 -0
  31. /package/{utils → src/utils}/other.js +0 -0
package/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  // Import modules
2
2
 
3
- import { Synthetizer } from "./synthetizer/synthetizer.js";
4
- import { Sequencer } from "./sequencer/sequencer.js";
5
- import { audioBufferToWav } from "./utils/buffer_to_wav.js";
6
- import { MIDIDeviceHandler } from "./external_midi/midi_handler.js";
7
- import { WebMIDILinkHandler } from "./external_midi/web_midi_link.js";
8
- import { DEFAULT_SYNTH_CONFIG } from "./synthetizer/audio_effects/effects_config.js";
9
- import { WORKLET_URL_ABSOLUTE } from "./synthetizer/worklet_url.js";
3
+ import { Synthetizer } from "./src/synthetizer/synthetizer.js";
4
+ import { Sequencer } from "./src/sequencer/sequencer.js";
5
+ import { audioBufferToWav } from "./src/utils/buffer_to_wav.js";
6
+ import { MIDIDeviceHandler } from "./src/external_midi/midi_handler.js";
7
+ import { WebMIDILinkHandler } from "./src/external_midi/web_midi_link.js";
8
+ import { DEFAULT_SYNTH_CONFIG } from "./src/synthetizer/audio_effects/effects_config.js";
9
+ import { WORKLET_URL_ABSOLUTE } from "./src/synthetizer/worklet_url.js";
10
10
 
11
11
  // Export modules
12
12
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spessasynth_lib",
3
- "version": "3.26.6",
3
+ "version": "3.26.7",
4
4
  "description": "MIDI and SoundFont2/DLS library for the browsers with no compromises",
5
5
  "browser": "index.js",
6
6
  "type": "module",
@@ -1,8 +1,6 @@
1
1
  ## This is the sequencer's folder.
2
2
 
3
- The code here is responsible for playing back the parsed MIDI sequence with the synthesizer.
4
-
5
- - `sequencer_engine` - the core sequencer engine, currently runs in audio worklet
3
+ The code here is responsible for wrapping the `SpessaSynthSequencer` from `spessasynth_core`.
6
4
 
7
5
  ### Message protocol:
8
6
 
@@ -29,4 +27,4 @@ The `messageData` is set to the sequencer's return message.
29
27
 
30
28
  ### Process tick
31
29
 
32
- `processTick` is called every time the `process` method is called via `SpessaSynthProcessor.processTickCallback`.
30
+ `processTick` is called every time the `process` method is called via `sequencer.processTick()` every rendering quantum.
@@ -1,19 +1,11 @@
1
1
  ## This is the main synthesizer folder.
2
2
 
3
- The code here is responsible for making the actual sound.
4
- This is the heart of the SpessaSynth library.
5
-
6
- - `audio_engine` - the core synthesis engine, it theoretically can run on non-browser environments.
7
- - `audio_effects` - the WebAudioAPI audio effects.
8
- - `worklet_wrapper` - the wrapper for the core synthesis engine using audio worklets.
9
-
10
- `worklet_processor.min.js` - the minified worklet processor code to import.
11
-
3
+ The code here is responsible for wrapping `SpessaSynthProcessor` from `spessasynth_core`.
12
4
  # About the message protocol
13
5
  Since spessasynth_lib runs in the audioWorklet thread, here is an explanation of how it works:
14
6
 
15
7
  There's one processor per synthesizer, with a `MessagePort` for communication.
16
- Each processor has a single `SpessaSynthequencer` instance that is idle by default.
8
+ Each processor has a single `SpessaSynthSequencer` instance that is idle by default.
17
9
 
18
10
  The `Synthetizer`,
19
11
  `Sequencer` and `SoundFontManager` classes are all interfaces
@@ -14,7 +14,7 @@ Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynt
14
14
  `+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ),this.soundFontInfo.ICMT+=`
15
15
  Converted from DLS to SF2 with SpessaSynth`;for(let[i,E]of Object.entries(this.soundFontInfo))y(`%c"${i}": %c"${E}"`,I.info,I.recognized);let o=n.find(i=>i.header==="colh");o||(q(),this.parsingError("No colh chunk!")),this.instrumentAmount=N(o.chunkData,4),y(`%cInstruments amount: %c${this.instrumentAmount}`,I.info,I.recognized);let r=ZA(n,"wvpl");r||(q(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(r);let g=ZA(n,"lins");g||(q(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(g),this.presets.sort((i,E)=>i.program-E.program+(i.bank-E.bank)),this._parseInternal(),y(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets,
16
16
  %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),q()}verifyHeader(A,...t){for(let n of t)if(A.header.toLowerCase()===n.toLowerCase())return;q(),this.parsingError(`Invalid DLS chunk header! Expected "${t.toString()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`FourCC error: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`))}parsingError(A){throw new Error(`DLS parse error: ${A} The file may be corrupted.`)}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};be.prototype.readDLSInstrumentList=Yo;be.prototype.readDLSInstrument=Jo;be.prototype.readRegion=Po;be.prototype.readLart=qo;be.prototype.readDLSSamples=Zo;var Is=class extends Ge{constructor(A,t,n,s,o,r,g,i,E,c,h,Q,B){super(A,r,g,i,E,c,s-t/2,o-t/2),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=Q,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=B}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let t=A.currentIndex;return A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t)}else{this.isDataRaw||super.getRawData();let t=A.currentIndex;return A.slice(t+this.sampleStartIndex,t+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,t=A.currentIndex,n=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);try{let s=me.decode(n.buffer);this.sampleData=s.data[0],this.sampleData===void 0&&H(`Error decoding sample ${this.sampleName}: Vorbis decode returned undefined.`)}catch(s){H(`Error decoding sample ${this.sampleName}: ${s}`),this.sampleData=new Float32Array(this.sampleLoopEndIndex+1)}}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?(H(`Invalid sample ${this.sampleName}! Invalid length: ${this.sampleLength}`),new Float32Array(1)):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return H("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let s=0;s<n.length;s++)A[s]=n[s]/32768;return this.sampleData=A,this.isSampleLoaded=!0,A}getUncompressedReadyData(){let A=this.sampleDataArray.slice(this.sampleStartIndex/2,this.sampleEndIndex/2);return this.sampleData=A,this.isSampleLoaded=!0,A}};function Xo(e,A,t=!0){let n=[],s=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let o=Ri(s,e.chunkData,A,t);n.push(o),s++}return n.length>1&&n.pop(),n}function Ri(e,A,t,n){let s=$(A,20),o=N(A,4)*2,r=N(A,4)*2,g=N(A,4),i=N(A,4),E=N(A,4),c=A[A.currentIndex++];c===255&&(c=60);let h=Bo(A[A.currentIndex++]),Q=N(A,2),B=N(A,2);return new Is(s,o,r,g,i,E,c,h,Q,B,t,e,n)}var gs=class extends U{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=Ke(A[t+2],A[t+3]),A.currentIndex+=4}};function Cs(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new gs(e.chunkData));return A.length>1&&A.pop(),A}var Es=class extends KA{constructor(A){super(),this.generatorZoneStartIndex=N(A,2),this.modulatorZoneStartIndex=N(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getSample(A){let t=this.generators.find(n=>n.generatorType===a.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Wo(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Es(e.chunkData);if(s.length>0){let r=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,g),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var hs=class extends Re{constructor(A){super(),this.generatorZoneStartIndex=N(A,2),this.modulatorZoneStartIndex=N(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getInstrument(A){let t=this.generators.find(n=>n.generatorType===a.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function zo(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new hs(e.chunkData);if(s.length>0){let r=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,g),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Bs=class extends xe{constructor(A,t){super(t),this.presetName=$(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=N(A.chunkData,2),this.bank=N(A.chunkData,2),this.presetZoneStartIndex=N(A.chunkData,2),this.library=N(A.chunkData,4),this.genre=N(A.chunkData,4),this.morphology=N(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;n<this.presetZonesAmount+this.presetZoneStartIndex;n++)this.presetZones.push(t[n])}};function _o(e,A,t){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let s=new Bs(e,t);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var cs=class extends Me{constructor(A){super(),this.instrumentName=$(A.chunkData,20).trim(),this.instrumentZoneIndex=N(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;n<this.instrumentZonesAmount+this.instrumentZoneIndex;n++)this.instrumentZones.push(t[n])}};function jo(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let n=new cs(e);if(t.length>0){let s=n.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(s,A)}t.push(n)}return t.length>1&&t.pop(),t}var ls=class extends z{constructor(A){let t=N(A,2),n=N(A,2),s=Ke(A[A.currentIndex++],A[A.currentIndex++]),o=N(A,2),r=N(A,2);super(t,o,n,s,r)}};function un(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new ls(e.chunkData));return A}var mn=class extends Ne{constructor(A,t=!0){super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new x(A),ie("%cParsing SoundFont...",I.info),this.dataArray||(q(),this.parsingError("No data provided!"));let n=IA(this.dataArray,!1);this.verifyHeader(n,"riff");let s=$(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw q(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",r=IA(this.dataArray);for(this.verifyHeader(r,"list"),$(r.chunkData,4);r.chunkData.length>r.chunkData.currentIndex;){let tA=IA(r.chunkData),T;switch(tA.header.toLowerCase()){case"ifil":case"iver":T=`${N(tA.chunkData,2)}.${N(tA.chunkData,2)}`,this.soundFontInfo[tA.header]=T;break;case"icmt":T=$(tA.chunkData,tA.chunkData.length,void 0,!1),this.soundFontInfo[tA.header]=T;break;case"dmod":let AA=un(tA);AA.pop(),T=`Modulators: ${AA.length}`;let hA=this.defaultModulators;this.defaultModulators=AA,this.defaultModulators.push(...hA.filter(sA=>!this.defaultModulators.find(oA=>z.isIdentical(sA,oA)))),this.soundFontInfo[tA.header]=tA.chunkData;break;default:T=$(tA.chunkData,tA.chunkData.length),this.soundFontInfo[tA.header]=T}y(`%c"${tA.header}": %c"${T}"`,I.info,I.recognized)}let g=IA(this.dataArray,!1);this.verifyHeader(g,"list"),this.verifyText($(this.dataArray,4),"sdta"),y("%cVerifying smpl chunk...",I.warn);let i=IA(this.dataArray,!1);this.verifyHeader(i,"smpl");let E;if(o){y("%cSF2Pack detected, attempting to decode the smpl chunk...",I.info);try{E=me.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+g.size-12)).data[0]}catch(tA){throw q(),new Error(`SF2Pack Ogg Vorbis decode error: ${tA}`)}y(`%cDecoded the smpl chunk! Length: %c${E.length}`,I.info,I.value)}else E=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;y(`%cSkipping sample chunk, length: %c${g.size-12}`,I.info,I.value),this.dataArray.currentIndex+=g.size-12,y("%cLoading preset data chunk...",I.warn);let c=IA(this.dataArray);this.verifyHeader(c,"list"),$(c.chunkData,4);let h=IA(c.chunkData);this.verifyHeader(h,"phdr");let Q=IA(c.chunkData);this.verifyHeader(Q,"pbag");let B=IA(c.chunkData);this.verifyHeader(B,"pmod");let m=IA(c.chunkData);this.verifyHeader(m,"pgen");let u=IA(c.chunkData);this.verifyHeader(u,"inst");let p=IA(c.chunkData);this.verifyHeader(p,"ibag");let R=IA(c.chunkData);this.verifyHeader(R,"imod");let D=IA(c.chunkData);this.verifyHeader(D,"igen");let M=IA(c.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Xo(M,E,!o));let b=Cs(D),G=un(R),C=Wo(p,b,G,this.samples);this.instruments=jo(u,C);let L=Cs(m),J=un(B),EA=zo(Q,L,J,this.instruments);this.presets.push(..._o(h,EA,this)),this.presets.sort((tA,T)=>tA.program-T.program+(tA.bank-T.bank)),this._parseInternal(),y(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
17
- %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),q(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};function $e(e){let A=e.slice(8,12),t=new x(A);return $(t,4,void 0,!1).toLowerCase()==="dls "?new be(e):new mn(e,!1)}function $o(e,A){this.soundfontBankOffset=A,this.clearSoundFont(!1,!0),this.overrideSoundfont=$e(e),this.updatePresetList(),this.getDefaultPresets(),this.midiAudioChannels.forEach(t=>t.programChange(t.preset.program)),this.overrideSoundfont.samples.forEach(t=>t.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),y("%cSpessaSynth is ready!",I.recognized)}function Ar(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.getDefaultPresets(),this.cachedVoices=[],e&&this.updatePresetList();for(let t=0;t<this.midiAudioChannels.length;t++){let n=this.midiAudioChannels[t];(!A||A&&n.presetUsesOverride)&&n.setPresetLock(!1),n.programChange(n.preset.program)}}function er(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,n=e.find(s=>s.bank===t&&s.program===A.program);n!==void 0?n.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e),this.getDefaultPresets(),this.resetAllControllers(!1)}function tr(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(t,A,kA(this.system));if(n)return n}return this.soundfontManager.getPreset(e,A,kA(this.system))}function nr(e,A=!1){this.transposition=0;for(let t=0;t<this.midiAudioChannels.length;t++)this.midiAudioChannels[t].transposeChannel(e,A);this.transposition=e}function sr(e){e=Math.round(e);for(let A=0;A<this.midiAudioChannels.length;A++)this.midiAudioChannels[A].setCustomController(cA.masterTuning,e)}var lt=class e{program;bank;isBankLSB;patchName;lockPreset;lockedSystem;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;isMuted;velocityOverride;drumChannel;static getChannelSnapshot(A,t){let n=A.midiAudioChannels[t],s=new e;return s.program=n.preset.program,s.bank=n.getBankSelect(),s.isBankLSB=s.bank!==n.bank,s.lockPreset=n.lockPreset,s.lockedSystem=n.lockedSystem,s.patchName=n.preset.presetName,s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockVibrato=n.lockGSNRPNParams,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.isMuted=n.isMuted,s.velocityOverride=n.velocityOverride,s.drumChannel=n.drumChannel,s}static applyChannelSnapshot(A,t,n){let s=A.midiAudioChannels[t];s.muteChannel(n.isMuted),s.setDrums(n.drumChannel),s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.updateChannelTuning(),s.channelVibrato=n.channelVibrato,s.lockGSNRPNParams=n.lockVibrato,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.velocityOverride=n.velocityOverride,s.setPresetLock(!1),s.setBankSelect(n.bank,n.isBankLSB),s.programChange(n.program),s.setPresetLock(n.lockPreset),s.lockedSystem=n.lockedSystem}};var At=class e{channelSnapshots;keyMappings;mainVolume;pan;interpolation;system;transposition;static createSynthesizerSnapshot(A){let t=new e;return t.channelSnapshots=A.midiAudioChannels.map((n,s)=>lt.getChannelSnapshot(A,s)),t.keyMappings=A.keyModifierManager.getMappings(),t.mainVolume=A.midiVolume,t.pan=A.pan,t.system=A.system,t.interpolation=A.interpolationType,t.transposition=A.transposition,t.effectsConfig={},t}static applySnapshot(A,t){for(A.setSystem(t.system),A.setMasterParameter(JA.mainVolume,t.mainVolume),A.setMasterParameter(JA.masterPan,t.pan),A.transposeAllChannels(t.transposition),A.interpolationType=t.interpolation,A.keyModifierManager.setMappings(t.keyMappings);A.midiAudioChannels.length<t.channelSnapshots.length;)A.createMidiChannel();t.channelSnapshots.forEach((n,s)=>{lt.applyChannelSnapshot(A,s,n)}),y("%cFinished restoring controllers!",I.info)}};function or(e){this._snapshot=e,At.applySnapshot(this,e),y("%cFinished applying snapshot!",I.info),this.resetAllControllers()}function pn(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}var Qt=class{static getSampleLinear(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1;for(;E>=n.loopEnd;)E-=r;let c=s-i,h=o[E],Q=o[i];t[g]=Q+(h-Q)*c,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1;if(i>=n.end){A.finished=!0;return}let E=s-g,c=o[i],h=o[g];t[r]=h+(c-h)*E,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}static getSampleNearest(A,t){let n=A.sample,s=n.cursor,o=n.loopEnd-n.loopStart,r=n.sampleData;if(A.sample.isLooping)for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=o;let i=~~s+1;for(;i>=n.loopEnd;)i-=o;t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let g=0;g<t.length;g++){let i=~~s+1;if(i>=n.end){A.finished=!0;return}t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1,c=E+1,h=c+1,Q=s-i;E>=n.loopEnd&&(E-=r),c>=n.loopEnd&&(c-=r),h>=n.loopEnd&&(h-=r);let B=o[i],m=o[E],u=o[c],p=o[h],R=.5*(u-B),D=B-2.5*m+2*u-.5*p,M=.5*(p-B)+1.5*(m-u);t[g]=((M*Q+D)*Q+R)*Q+m,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1,E=i+1,c=E+1,h=s-g;if(i>=n.end||E>=n.end||c>=n.end){A.finished=!0;return}let Q=o[g],B=o[i],m=o[E],u=o[c],p=.5*(m-Q),R=Q-2.5*B+2*m-.5*u,D=.5*(u-Q)+1.5*(B-m);t[r]=((D*h+R)*h+p)*h+B,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};function rr(e,A,t,n,s,o,r,g){if(e.isInRelease||A>=e.releaseStartTime&&(e.isInRelease=!0,Ee.startRelease(e),he.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[a.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let i=e.targetKey,E=e.modulatedGenerators[a.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,c=e.modulatedGenerators[a.coarseTune],h=this.synth.tunings[this.preset.program]?.[e.realKey];if(h!==void 0&&h?.midiNote>=0&&(i=h.midiNote,E+=h.centTuning),e.portamentoFromKey>-1){let C=Math.min((A-e.startTime)/e.portamentoDuration,1),L=i-e.portamentoFromKey;c-=L*(1-C)}E+=(i-e.sample.rootKey)*e.modulatedGenerators[a.scaleTuning];let Q=e.modulatedGenerators[a.vibLfoToPitch];if(Q!==0){let C=e.startTime+Ce(e.modulatedGenerators[a.delayVibLFO]),L=bt(e.modulatedGenerators[a.freqVibLFO]),J=pn(C,L,A);E+=J*(Q*this.customControllers[cA.modulationMultiplier])}let B=0,m=e.modulatedGenerators[a.modLfoToPitch],u=e.modulatedGenerators[a.modLfoToVolume],p=e.modulatedGenerators[a.modLfoToFilterFc],R=0;if(m!==0||p!==0||u!==0){let C=e.startTime+Ce(e.modulatedGenerators[a.delayModLFO]),L=bt(e.modulatedGenerators[a.freqModLFO]),J=pn(C,L,A);E+=J*(m*this.customControllers[cA.modulationMultiplier]),R=-J*u,B+=J*p}if(this.channelVibrato.depth>0){let C=pn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,A);C&&(E+=C*this.channelVibrato.depth)}let D=e.modulatedGenerators[a.modEnvToPitch],M=e.modulatedGenerators[a.modEnvToFilterFc];if(M!==0||D!==0){let C=he.getValue(e,A);B+=C*M,E+=C*D}let b=~~(E+c*100);b!==e.currentTuningCents&&(e.currentTuningCents=b,e.currentTuningCalculated=Math.pow(2,b/1200));let G=new Float32Array(t.length);switch(this.synth.interpolationType){case ze.fourthOrder:Qt.getSampleCubic(e,G);break;case ze.linear:default:Qt.getSampleLinear(e,G);break;case ze.nearestNeighbor:Qt.getSampleNearest(e,G);break}return Ye.apply(e,G,B,this.synth.filterSmoothingFactor),Ee.apply(e,G,R,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,G,t,n,s,o,r,g),e.finished}function ir(e,A=-12e3){this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[a.releaseVolEnv]=A,t.release(this.synth.currentSynthTime))})}function ar(e,A=!0){e=Math.round(e),this.setCustomController(cA.channelTuning,e),A&&y(`%cFine tuning for %c${this.channelNumber}%c is now set to %c${e}%c cents.`,I.info,I.recognized,I.info,I.value,I.info)}function Ir(e){e=Math.round(e),y(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,I.info,I.value),this.setCustomController(cA.modulationMultiplier,e/50)}function gr(e){switch(this.dataEntryState){default:break;case HA.RPCoarse:case HA.RPFine:switch(this.midiControllers[S.RPNMsb]|this.midiControllers[S.RPNLsb]>>7){default:break;case 0:if(e===0)break;this.midiControllers[RA+j.pitchWheelRange]|=e;let t=(this.midiControllers[RA+j.pitchWheelRange]>>7)+e/128;y(`%cChannel ${this.channelNumber} bend range. Semitones: %c${t}`,I.info,I.value);break;case 1:let s=this.customControllers[cA.channelTuning]<<7|e;this.setTuning(s*.01220703125);break;case 5:let r=this.customControllers[cA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(r);break;case 16383:this.resetParameters();break}}}var Gi=1e3/200;function Cr(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let E=A.sourceIndex+RA;switch(A.sourceIndex){case j.noController:n=16383;break;case j.noteOnKeyNum:n=t.midiNote<<7;break;case j.noteOnVelocity:n=t.velocity<<7;break;case j.polyPressure:n=t.pressure<<7;break;default:n=e[E];break}}let s=et[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let E=A.secSrcIndex+RA;switch(A.secSrcIndex){case j.noController:o=16383;break;case j.noteOnKeyNum:o=t.midiNote<<7;break;case j.noteOnVelocity:o=t.velocity<<7;break;case j.polyPressure:o=t.pressure<<7;break;default:o=e[E]}}let r=et[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Gi,g=Math.min(g,1e3));let i=s*r*g;return A.transformType===2&&(i=Math.abs(i)),A.currentValue=i,i}function Be(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,r=e.modulatedGenerators;if(t===-1){r.set(o),s.forEach(E=>{let c=X[E.modulatorDestination],h=r[E.modulatorDestination]+Cr(A,E,e);r[E.modulatorDestination]=Math.max(c.min,Math.min(h,c.max))}),Ee.recalculate(e),he.recalculate(e);return}let g=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),i=new Set;s.forEach(E=>{if(E.sourceUsesCC===t&&E.sourceIndex===n||E.secSrcUsesCC===t&&E.secSrcIndex===n){let c=E.modulatorDestination;i.has(c)||(r[c]=o[c],Cr(A,E,e),s.forEach(h=>{if(h.modulatorDestination===c){let Q=X[E.modulatorDestination],B=r[E.modulatorDestination]+h.currentValue;r[E.modulatorDestination]=Math.max(Q.min,Math.min(B,Q.max))}}),i.add(c))}}),[...i].some(E=>g.has(E))&&Ee.recalculate(e),he.recalculate(e)}var et=[];for(let e=0;e<4;e++){et[e]=[[new Float32Array(bA),new Float32Array(bA)],[new Float32Array(bA),new Float32Array(bA)]];for(let A=0;A<bA;A++)et[e][0][0][A]=je(0,e,A/bA,0),et[e][1][0][A]=je(0,e,A/bA,1),et[e][0][1][A]=je(1,e,A/bA,0),et[e][1][1][A]=je(1,e,A/bA,1)}function Er(e,A,t=!1){if(e>127){if(!t)return;switch(e){default:return;case ts.velocityOverride:this.velocityOverride=A}}if(e>=S.lsbForControl1ModulationWheel&&e<=S.lsbForControl13EffectControl2&&e!==S.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>Be(s,this.midiControllers,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case S.allNotesOff:this.stopAllNotes();break;case S.allSoundOff:this.stopAllNotes(!0);break;case S.bankSelect:this.setBankSelect(A);break;case S.lsbForControl0BankSelect:this.setBankSelect(A,!0);break;case S.RPNLsb:this.dataEntryState=HA.RPFine;break;case S.RPNMsb:this.dataEntryState=HA.RPCoarse;break;case S.NRPNMsb:this.dataEntryState=HA.NRPCoarse;break;case S.NRPNLsb:this.dataEntryState=HA.NRPFine;break;case S.dataEntryMsb:this.dataEntryCoarse(A);break;case S.lsbForControl6DataEntry:this.dataEntryFine(A);break;case S.resetAllControllers:this.resetControllersRP15Compliant();break;case S.sustainPedal:A>=64?this.holdPedal=!0:(this.holdPedal=!1,this.sustainedVoices.forEach(n=>{n.release(this.synth.currentSynthTime)}),this.sustainedVoices=[]);break;default:this.voices.forEach(n=>Be(n,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}function hr(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.sendChannelProperty()):(this.voices.forEach(A=>{A.isInRelease||A.release(this.synth.currentSynthTime)}),this.sustainedVoices.forEach(A=>{A.release(this.synth.currentSynthTime)}))}function Br(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.sendChannelProperty(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function cr(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[cA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.controllerChange(S.allNotesOff,127),this.channelTransposeKeyShift=t,this.setCustomController(cA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}var Ht={pitchBendRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},Oe={partParameter:1,vibratoRate:8,vibratoDepth:9,vibratoDelay:10,EGAttackTime:100,EGReleaseTime:102,TVFFilterCutoff:32,drumReverb:29};function lr(e){let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)},t=(n,s,o)=>{o.length>0&&(o=" "+o),y(`%c${n} for %c${this.channelNumber}%c is now set to %c${s}%c${o}.`,I.info,I.recognized,I.info,I.value,I.info)};switch(this.dataEntryState){default:case HA.Idle:break;case HA.NRPFine:if(this.lockGSNRPNParams)return;let n=this.midiControllers[S.NRPNMsb]>>7,s=this.midiControllers[S.NRPNLsb]>>7;switch(n){default:if(e===64)return;H(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${s.toString(16).toUpperCase()} 0x${s.toString(16).toUpperCase()})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Oe.partParameter:switch(s){default:if(e===64)return;H(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)} 0x${s.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Oe.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case Oe.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case Oe.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case Oe.TVFFilterCutoff:this.controllerChange(S.brightness,e),t("Filter cutoff",e.toString(),"");break;case Oe.EGAttackTime:this.controllerChange(S.attackTime,e),t("EG attack time",e.toString(),"");break;case Oe.EGReleaseTime:this.controllerChange(S.releaseTime,e),t("EG release time",e.toString(),"");break}break;case Oe.drumReverb:let r=e;this.controllerChange(S.reverbDepth,r),t("GS Drum reverb",r.toString(),"percent");break}break;case HA.RPCoarse:case HA.RPFine:let o=this.midiControllers[S.RPNMsb]|this.midiControllers[S.RPNLsb]>>7;switch(o){default:H(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${o.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Ht.pitchBendRange:this.midiControllers[RA+j.pitchWheelRange]=e<<7,t("Pitch bend range",e.toString(),"semitones");break;case Ht.coarseTuning:let r=e-64;this.setCustomController(cA.channelTuningSemitones,r),t("Coarse tuning",r.toString(),"semitones");break;case Ht.fineTuning:this.setTuning(e-64,!1);break;case Ht.modulationDepth:this.setModulationDepth(e*100);break;case Ht.resetParameters:this.resetParameters();break}}}var Yt={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function Mi(e){if(Yt[e]!==void 0)return Yt[e];let A=null,t=null;for(let n of Object.keys(Yt))n=parseInt(n),n<e&&(A===null||n>A)&&(A=n),n>e&&(t===null||n<t)&&(t=n);if(A!==null&&t!==null){let n=Yt[A],s=Yt[t];return n+(e-A)*(s-n)/(t-A)}return 0}function Qr(e,A){return Mi(e)*(A/30)}function dr(e,A){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synth.highPerformanceMode&&this.synth.totalVoicesAmount>200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let t=e+this.channelTransposeKeyShift,n=t;if(t>127||t<0)return;let s=this.preset.program,o=this.synth.tunings[s]?.[t]?.midiNote;o>=0&&(n=o),this.velocityOverride>0&&(A=this.velocityOverride);let r=this.synth.keyModifierManager.getVelocity(this.channelNumber,t);r>-1&&(A=r);let g=this.synth.keyModifierManager.getGain(this.channelNumber,t),i=-1,E=0,c=this.midiControllers[S.portamentoTime]>>7,h=this.midiControllers[S.portamentoControl],Q=h>>7;if(!this.drumChannel&&Q!==n&&this.midiControllers[S.portamentoOnOff]>=8192&&c>0){if(h!==1){let p=Math.abs(n-Q);E=Qr(c,p),i=Q}this.controllerChange(S.portamentoControl,n)}let B=this.synth.getVoices(this.channelNumber,n,A,t),m=0;this.randomPan&&(m=Math.round(Math.random()*1e3-500));let u=this.voices;B.forEach(p=>{p.portamentoFromKey=i,p.portamentoDuration=E,p.overridePan=m,p.gain=g;let R=p.exclusiveClass;R!==0&&u.forEach(J=>{J.exclusiveClass===R&&J.exclusiveRelease(this.synth.currentSynthTime)}),Be(p,this.midiControllers);let D=p.modulatedGenerators[a.startAddrsOffset]+p.modulatedGenerators[a.startAddrsCoarseOffset]*32768,M=p.modulatedGenerators[a.endAddrOffset]+p.modulatedGenerators[a.endAddrsCoarseOffset]*32768,b=p.modulatedGenerators[a.startloopAddrsOffset]+p.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,G=p.modulatedGenerators[a.endloopAddrsOffset]+p.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,C=p.sample,L=J=>Math.max(0,Math.min(C.sampleData.length-1,J));if(C.cursor=L(C.cursor+D),C.end=L(C.end+M),C.loopStart=L(C.loopStart+b),C.loopEnd=L(C.loopEnd+G),C.loopEnd<C.loopStart){let J=C.loopStart;C.loopStart=C.loopEnd,C.loopEnd=J}C.loopEnd-C.loopStart<1&&(C.loopingMode=0,C.isLooping=!1),p.volumeEnvelope.attenuation=p.volumeEnvelope.attenuationTargetGain,p.currentPan=Math.max(-500,Math.min(500,p.modulatedGenerators[a.pan]))}),this.synth.totalVoicesAmount+=B.length,this.synth.totalVoicesAmount>this.synth.voiceCap&&this.synth.voiceKilling(B.length),u.push(...B),this.sendChannelProperty(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A})}function fr(e){if(e>127||e<0){H("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift;if(this.synth.highPerformanceMode&&!this.drumChannel){this.killNote(A,-6950),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease===!0||(this.holdPedal?this.sustainedVoices.push(n):n.release(this.synth.currentSynthTime))}),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber})}function ur(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,Be(t,this.midiControllers,0,j.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function mr(e){this.midiControllers[RA+j.channelPressure]=e<<7,this.voices.forEach(A=>Be(A,this.midiControllers,0,j.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function pr(e,A){if(this.lockedControllers[RA+j.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[RA+j.pitchWheel]=t,this.voices.forEach(n=>Be(n,this.midiControllers,0,j.pitchWheel)),this.sendChannelProperty()}function yr(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=new Int8Array(128);for(let A=0;A<128;A++)this.channelOctaveTuning[A]=e[A%12]}function Sr(e){if(this.lockPreset)return;let A=this.getBankSelect(),t,n,s=this.isXGChannel;if(this.synth.overrideSoundfont){let o=A===128?128:A-this.synth.soundfontBankOffset,r=this.synth.overrideSoundfont.getPresetNoFallback(o,e,s);if(r)t=r.bank===128?128:r.bank+this.synth.soundfontBankOffset,n=r,this.presetUsesOverride=!0;else{n=this.synth.soundfontManager.getPreset(A,e,s);let g=this.synth.soundfontManager.soundfontList.find(i=>i.soundfont===n.parentSoundBank).bankOffset;t=n.bank-g,this.presetUsesOverride=!1}}else{n=this.synth.soundfontManager.getPreset(A,e,s);let o=this.synth.soundfontManager.soundfontList.find(r=>r.soundfont===n.parentSoundBank).bankOffset;t=n.bank-o,this.presetUsesOverride=!1}this.setPreset(n),this.sentBank=t,this.synth.callEvent("programchange",{channel:this.channelNumber,program:n.program,bank:t}),this.sendChannelProperty()}var SA=class{midiControllers=new Int16Array(sn);lockedControllers=Array(sn).fill(!1);customControllers=new Float32Array(As);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);channelTuningCents=0;holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=HA.Idle;bank=0;sentBank=0;bankLSB=0;preset=void 0;lockPreset=!1;lockedSystem="gs";presetUsesOverride=!1;lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};isMuted=!1;voices=[];sustainedVoices=[];channelNumber;synth;constructor(A,t,n){this.synth=A,this.preset=t,this.channelNumber=n}get isXGChannel(){return kA(this.synth.system)||this.lockPreset&&kA(this.lockedSystem)}setCustomController(A,t){this.customControllers[A]=t,this.updateChannelTuning()}updateChannelTuning(){this.channelTuningCents=this.customControllers[cA.channelTuning]+this.customControllers[cA.channelTransposeFine]+this.customControllers[cA.masterTuning]+this.customControllers[cA.channelTuningSemitones]*100}renderAudio(A,t,n,s,o,r){this.voices=this.voices.filter(g=>!this.renderVoice(g,this.synth.currentSynthTime,A,t,n,s,o,r))}setPresetLock(A){this.lockPreset=A,A&&(this.lockedSystem=this.synth.system)}setBankSelect(A,t=!1){if(!this.lockPreset)if(t)this.bankLSB=A;else switch(this.bank=A,Bt(this.getBankSelect(),A,this.synth.system,!1,this.drumChannel,this.channelNumber).drumsStatus){default:case 0:break;case 1:this.channelNumber%16===9&&(this.bank=127);break;case 2:this.setDrums(!0);break}}getBankSelect(){return ct(this.bank,this.bankLSB,this.drumChannel,this.isXGChannel)}setPreset(A){this.lockPreset||(delete this.preset,this.preset=A)}setDrums(A){this.lockPreset||this.drumChannel!==A&&(A?(this.channelTransposeKeyShift=0,this.drumChannel=!0):this.drumChannel=!1,this.presetUsesOverride=!1,this.synth.callEvent("drumchange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}),this.programChange(this.preset.program),this.sendChannelProperty())}setVibrato(A,t,n){this.lockGSNRPNParams||(this.channelVibrato.rate=t,this.channelVibrato.delay=n,this.channelVibrato.depth=A)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}sendChannelProperty(){if(!this.synth.enableEventSystem)return;let A={voicesAmount:this.voices.length,pitchBend:this.midiControllers[RA+j.pitchWheel],pitchBendRangeSemitones:this.midiControllers[RA+j.pitchWheelRange]/128,isMuted:this.isMuted,isDrum:this.drumChannel,transposition:this.channelTransposeKeyShift+this.customControllers[cA.channelTransposeFine]/100,bank:this.sentBank,program:this.preset.program};this.synth?.onChannelPropertyChange?.(A,this.channelNumber)}};SA.prototype.renderVoice=rr;SA.prototype.panVoice=Eo;SA.prototype.killNote=ir;SA.prototype.stopAllNotes=hr;SA.prototype.muteChannel=Br;SA.prototype.noteOn=dr;SA.prototype.noteOff=fr;SA.prototype.polyPressure=ur;SA.prototype.channelPressure=mr;SA.prototype.pitchWheel=pr;SA.prototype.programChange=Sr;SA.prototype.setTuning=ar;SA.prototype.setOctaveTuning=yr;SA.prototype.setModulationDepth=Ir;SA.prototype.transposeChannel=cr;SA.prototype.controllerChange=Er;SA.prototype.resetControllers=Ao;SA.prototype.resetControllersRP15Compliant=eo;SA.prototype.resetParameters=to;SA.prototype.dataEntryFine=gr;SA.prototype.dataEntryCoarse=lr;function Dr(e=!1){let A=new SA(this,this.defaultPreset,this.midiAudioChannels.length);this.midiAudioChannels.push(A),e&&(this.callEvent("newchannel",void 0),A.sendChannelProperty(),this.midiAudioChannels[this.midiAudioChannels.length-1].setDrums(!0))}var Qs={enableEventSystem:!0,initialTime:0,effectsEnabled:!0,midiChannels:16};function kr(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var oo=.03,ro=.07,_n=1,LA=class{cachedVoices=[];deviceID=-1;eventQueue=[];interpolationType=ze.fourthOrder;transposition=0;tunings=[];soundfontBankOffset=0;masterGain=_n;midiVolume=1;reverbGain=1;chorusGain=1;voiceCap=350;pan=0;panLeft=.5;panRight=.5;highPerformanceMode=!1;keyModifierManager=new an;overrideSoundfont=void 0;midiAudioChannels=[];system=Nt;totalVoicesAmount=0;defaultPreset;defaultPresetUsesOverride=!1;drumPreset;defaultDrumsUsesOverride=!1;processorInitialized=me.isInitialized;currentSynthTime=0;sampleRate;sampleTime;effectsEnabled;_snapshot;onEventCall;onChannelPropertyChange;onMasterParameterChange;constructor(A,t=Qs){t=kr(t,Qs),this.midiOutputsCount=t.midiChannels,this.effectsEnabled=t.effectsEnabled,this.enableEventSystem=t.enableEventSystem,this.currentSynthTime=t.midiChannels,this.sampleTime=1/A,this.sampleRate=A,this.volumeEnvelopeSmoothingFactor=qs*(44100/A),this.panSmoothingFactor=ao*(44100/A),this.filterSmoothingFactor=no*(44100/A);for(let n=0;n<128;n++)this.tunings.push([]);this.soundfontManager=new rn(this.updatePresetList.bind(this));for(let n=0;n<this.midiOutputsCount;n++)this.createMidiChannel(!1);this.processorInitialized.then(()=>{y("%cSpessaSynth is ready!",I.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}getDefaultPresets(){let A=this.system;this.system="xg",this.defaultPreset=this.getPreset(0,0),this.defaultPresetUsesOverride=this.overrideSoundfont?.presets?.indexOf(this.defaultPreset)>=0,this.system=A,this.drumPreset=this.getPreset(128,0),this.defaultDrumsUsesOverride=this.overrideSoundfont?.presets?.indexOf(this.drumPreset)>=0}setSystem(A){this.system=A,this?.onMasterParameterChange?.(JA.midiSystem,this.system)}getCachedVoice(A,t,n,s){return this.cachedVoices?.[A]?.[t]?.[n]?.[s]}setCachedVoice(A,t,n,s,o){this.cachedVoices||(this.cachedVoices=[]),this.cachedVoices[A]||(this.cachedVoices[A]=[]),this.cachedVoices[A][t]||(this.cachedVoices[A][t]=[]),this.cachedVoices[A][t][n]||(this.cachedVoices[A][t][n]=[]),this.cachedVoices[A][t][n][s]=o}renderAudio(A,t,n){this.renderAudioSplit(t,n,Array(16).fill(A))}renderAudioSplit(A,t,n){let s=this.currentSynthTime;for(;this.eventQueue[0]?.time<=s;)this.eventQueue.shift().callback();let o=A[0],r=A[1],g=t[0],i=t[1];this.totalVoicesAmount=0,this.midiAudioChannels.forEach((E,c)=>{if(E.voices.length<1||E.isMuted)return;let h=E.voices.length,Q=c%16;E.renderAudio(n[Q][0],n[Q][1],o,r,g,i),this.totalVoicesAmount+=E.voices.length,E.voices.length!==h&&E.sendChannelProperty()}),this.currentSynthTime+=n[0][0].length*this.sampleTime}destroySynthProcessor(){this.midiAudioChannels.forEach(A=>{delete A.midiControllers,delete A.voices,delete A.sustainedVoices,delete A.lockedControllers,delete A.preset,delete A.customControllers}),delete this.cachedVoices,delete this.midiAudioChannels,this.soundfontManager.destroyManager(),delete this.soundfontManager}controllerChange(A,t,n,s=!1){this.midiAudioChannels[A].controllerChange(t,n,s)}noteOn(A,t,n){this.midiAudioChannels[A].noteOn(t,n)}noteOff(A,t){this.midiAudioChannels[A].noteOff(t)}polyPressure(A,t,n){this.midiAudioChannels[A].polyPressure(t,n)}channelPressure(A,t){this.midiAudioChannels[A].channelPressure(t)}pitchWheel(A,t,n){this.midiAudioChannels[A].pitchWheel(t,n)}programChange(A,t){this.midiAudioChannels[A].programChange(t)}processMessage(A,t,n,s){let o=()=>{let g=ht(A[0]),i=g.channel+t;switch(g.status){case w.noteOn:let E=A[2];E>0?this.noteOn(i,A[1],E):this.noteOff(i,A[1]);break;case w.noteOff:n?this.midiAudioChannels[i].killNote(A[1]):this.noteOff(i,A[1]);break;case w.pitchBend:this.pitchWheel(i,A[2],A[1]);break;case w.controllerChange:this.controllerChange(i,A[1],A[2],n);break;case w.programChange:this.programChange(i,A[1]);break;case w.polyPressure:this.polyPressure(i,A[0],A[1]);break;case w.channelPressure:this.channelPressure(i,A[1]);break;case w.systemExclusive:this.systemExclusive(new x(A.slice(1)),t);break;case w.reset:this.stopAllChannels(!0),this.resetAllControllers();break;default:break}},r=s.time;r>this.currentSynthTime?(this.eventQueue.push({callback:o.bind(this),time:r}),this.eventQueue.sort((g,i)=>g.time-i.time)):o()}setMIDIVolume(A){this.midiVolume=Math.pow(A,Math.E),this.setMasterParameter(JA.masterPan,this.pan)}callEvent(A,t){this?.onEventCall?.(A,t)}};LA.prototype.voiceKilling=Hs;LA.prototype.getVoices=so;LA.prototype.systemExclusive=_s;LA.prototype.stopAllChannels=ho;LA.prototype.createMidiChannel=Dr;LA.prototype.resetAllControllers=$s;LA.prototype.setMasterParameter=Ws;LA.prototype.transposeAllChannels=nr;LA.prototype.setMasterTuning=sr;LA.prototype.getPreset=tr;LA.prototype.clearSoundFont=Ar;LA.prototype.setEmbeddedSoundFont=$o;LA.prototype.updatePresetList=er;LA.prototype.applySynthesizerSnapshot=or;function OA(e,A){let t=0;for(let n=8*(A-1);n>=0;n-=8)t|=e[e.currentIndex++]<<n;return t>>>0}function Jt(e,A){let t=new Array(A).fill(0);for(let n=A-1;n>=0;n--)t[n]=e&255,e>>=8;return t}function Fr(e,A){if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=ht(e.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=n,t.status){case w.noteOn:let s=e.messageData[1];if(s>0)this.synth.noteOn(t.channel,e.messageData[0],s),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:s});else{this.synth.noteOff(t.channel,e.messageData[0]);let g=this.playingNotes.findIndex(i=>i.midiNote===e.messageData[0]&&i.channel===t.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case w.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===e.messageData[0]&&g.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case w.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.programChange(t.channel,e.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(e.messageData,n);break;case w.setTempo:e.messageData.currentIndex=0;let r=6e7/OA(e.messageData,3);this.oneTickToSeconds=60/(r*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),H("invalid tempo! falling back to 120 BPM"),r=120);break;case w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:case w.sequenceNumber:case w.sequenceSpecific:case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:case w.programName:break;case w.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:H(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(w).find(g=>w[g]===t.status)}`,I.warn,I.unrecognized,I.warn,I.value);break}t.status>=0&&t.status<128&&this?.onMetaEvent?.(e,A)}function Rr(){for(let e=0;e<16;e++)this.synth.createMidiChannel(!0)}function Gr(){if(!this.isActive)return;let e=this.currentTime;for(;this.playedTime<e;){let A=this._findFirstEventIndex(),t=this.tracks[A][this.eventIndex[A]];if(this._processEvent(t,A),this.eventIndex[A]++,A=this._findFirstEventIndex(),this.tracks[A].length<=this.eventIndex[A]){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];this.playedTime+=this.oneTickToSeconds*(n.ticks-t.ticks);let s=this.loop&&(this.loopCount>0||this.loopCount===-1);if(this.midiData.loop.end<=t.ticks&&s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Mr(){let e=0,A=1/0;return this.tracks.forEach((t,n)=>{this.eventIndex[n]>=t.length||t[this.eventIndex[n]].ticks<A&&(e=n,A=t[this.eventIndex[n]].ticks)}),e}var tt=class{timeDivision=0;duration=0;tempoChanges=[{ticks:0,tempo:120}];copyright="";tracksAmount=0;trackNames=[];lyrics=[];lyricsTicks=[];firstNoteOn=0;keyRange={min:0,max:127};lastVoiceEventTick=0;midiPorts=[0];midiPortChannelOffsets=[0];usedChannelsOnTrack=[];loop={start:0,end:0};midiName="";midiNameUsesFileName=!1;fileName="";rawMidiName;format=0;RMIDInfo={};bankOffset=0;isKaraokeFile=!1;isMultiPort=!1;MIDIticksToSeconds(A){let t=0;for(;A>0;){let n=this.tempoChanges.find(o=>o.ticks<A),s=A-n.ticks;t+=s*60/(n.tempo*this.timeDivision),A-=s}return t}_copyFromSequence(A){this.midiName=A.midiName,this.midiNameUsesFileName=A.midiNameUsesFileName,this.fileName=A.fileName,this.timeDivision=A.timeDivision,this.duration=A.duration,this.copyright=A.copyright,this.tracksAmount=A.tracksAmount,this.firstNoteOn=A.firstNoteOn,this.lastVoiceEventTick=A.lastVoiceEventTick,this.format=A.format,this.bankOffset=A.bankOffset,this.isKaraokeFile=A.isKaraokeFile,this.isMultiPort=A.isMultiPort,this.tempoChanges=[...A.tempoChanges],this.lyrics=A.lyrics.map(t=>new Uint8Array(t)),this.lyricsTicks=[...A.lyricsTicks],this.midiPorts=[...A.midiPorts],this.trackNames=[...A.trackNames],this.midiPortChannelOffsets=[...A.midiPortChannelOffsets],this.usedChannelsOnTrack=A.usedChannelsOnTrack.map(t=>new Set(t)),this.rawMidiName=A.rawMidiName?new Uint8Array(A.rawMidiName):void 0,this.loop={...A.loop},this.keyRange={...A.keyRange},this.RMIDInfo={...A.RMIDInfo}}};function uA(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}function yn(e){let A=[e&127];for(e>>=7;e>0;)A.unshift(e&127|128),e>>=7;return A}function xr(){let e=this;if(!e.tracks)throw new Error("MIDI has no tracks!");let A=[];for(let s of e.tracks){let o=[],r=0,g;for(let i of s){let E=i.ticks-r,c;i.messageStatusByte<=w.sequenceSpecific?c=[255,i.messageStatusByte,...yn(i.messageData.length),...i.messageData]:i.messageStatusByte===w.systemExclusive?c=[240,...yn(i.messageData.length),...i.messageData]:(c=[],g!==i.messageStatusByte&&(g=i.messageStatusByte,c.push(i.messageStatusByte)),c.push(...i.messageData)),o.push(...yn(E)),o.push(...c),r+=E}A.push(new Uint8Array(o))}function t(s,o){for(let r=0;r<s.length;r++)o.push(s.charCodeAt(r))}let n=[];t("MThd",n),n.push(...Jt(6,4)),n.push(0,e.format),n.push(...Jt(e.tracksAmount,2)),n.push(...Jt(e.timeDivision,2));for(let s of A)t("MTrk",n),n.push(...Jt(s.length,4)),n.push(...s);return new Uint8Array(n)}function dt(e){return e.messageData[0]===67&&e.messageData[2]===76&&e.messageData[5]===126&&e.messageData[6]===0}function Sn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[3]===18&&e.messageData[4]===64&&(e.messageData[5]&16)!==0&&e.messageData[6]===21}function Dn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[6]===127}function kn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===1}function wn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===3}function ds(e){return new YA(e,w.systemExclusive,new x([65,16,66,18,64,0,127,0,65,247]))}function ft(e,A,t,n){return new YA(n,w.controllerChange|e%16,new x([A,t]))}function xi(e,A){let t=16|[1,2,3,4,5,6,7,8,0,9,10,11,12,13,14,15][e%16],n=[65,16,66,18,64,t,21,1],o=128-(64+t+21+1)%128;return new YA(A,w.systemExclusive,new x([...n,o,247]))}function Nr(e=[],A=[],t=[],n=[]){let s=this;fA("%cApplying changes to the MIDI file...",I.info),y("Desired program changes:",e),y("Desired CC changes:",A),y("Desired channels to clear:",t),y("Desired channels to transpose:",n);let o=new Set;e.forEach(M=>{o.add(M.channel)});let r="gs",g=!1,i=Array(s.tracks.length).fill(0),E=s.tracks.length;function c(){let M=0,b=1/0;return s.tracks.forEach((G,C)=>{i[C]>=G.length||G[i[C]].ticks<b&&(M=C,b=G[i[C]].ticks)}),M}let h=s.midiPorts.slice(),Q={},B=0;function m(M,b){s.usedChannelsOnTrack[M].size!==0&&(B===0&&(B+=16,Q[b]=0),Q[b]===void 0&&(Q[b]=B,B+=16),h[M]=b)}s.midiPorts.forEach((M,b)=>{m(b,M)});let u=B,p=Array(u).fill(!0),R=Array(u).fill(0),D=Array(u).fill(0);for(n.forEach(M=>{let b=Math.trunc(M.keyShift),G=M.keyShift-b;R[M.channel]=b,D[M.channel]=G});E>0;){let M=c(),b=s.tracks[M];if(i[M]>=b.length){E--;continue}let G=i[M]++,C=b[G],L=()=>{b.splice(G,1),i[M]--},J=(hA,sA=0)=>{b.splice(G+sA,0,hA),i[M]++},EA=Q[h[M]]||0;if(C.messageStatusByte===w.midiPort){m(M,C.messageData[0]);continue}if(C.messageStatusByte<=w.sequenceSpecific&&C.messageStatusByte>=w.sequenceNumber)continue;let tA=C.messageStatusByte&240,T=C.messageStatusByte&15,AA=T+EA;if(t.indexOf(AA)!==-1){L();continue}switch(tA){case w.noteOn:if(p[AA]){p[AA]=!1,A.filter(CA=>CA.channel===AA).forEach(CA=>{let v=ft(T,CA.controllerNumber,CA.controllerValue,C.ticks);J(v)});let oA=D[AA];if(oA!==0){let CA=oA*64+64,v=ft(T,S.RPNMsb,0,C.ticks),K=ft(T,S.RPNLsb,1,C.ticks),W=ft(AA,S.dataEntryMsb,CA,C.ticks),P=ft(T,S.lsbForControl6DataEntry,0,C.ticks);J(P),J(W),J(K),J(v)}if(o.has(AA)){let CA=e.find(rA=>rA.channel===AA),v=Math.max(0,Math.min(CA.bank,127)),K=CA.program;y(`%cSetting %c${CA.channel}%c to %c${v}:${K}%c. Track num: %c${M}`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized);let W=new YA(C.ticks,w.programChange|T,new x([K]));J(W);let P=(rA,qA)=>{let ge=ft(T,rA?S.lsbForControl0BankSelect:S.bankSelect,qA,C.ticks);J(ge)};kA(r)?CA.isDrum?(y(`%cAdding XG Drum change on track %c${M}`,I.recognized,I.value),P(!1,$A(v)?v:127),P(!0,0)):v===nn?(P(!1,nn),P(!0,0)):(P(!1,0),P(!0,v)):(P(!1,v),CA.isDrum&&T!==9&&(y(`%cAdding GS Drum change on track %c${M}`,I.recognized,I.value),J(xi(T,C.ticks))))}}C.messageData[0]+=R[AA];break;case w.noteOff:C.messageData[0]+=R[AA];break;case w.programChange:if(o.has(AA)){L();continue}break;case w.controllerChange:let hA=C.messageData[0];if(A.find(oA=>oA.channel===AA&&hA===oA.controllerNumber)!==void 0){L();continue}if((hA===S.bankSelect||hA===S.lsbForControl0BankSelect)&&o.has(AA)){L();continue}break;case w.systemExclusive:if(dt(C))y("%cXG system on detected",I.info),r="xg",g=!0;else if(C.messageData[0]===67&&C.messageData[2]===76&&C.messageData[3]===8&&C.messageData[5]===3)o.has(C.messageData[4]+EA)&&L();else if(Dn(C)){g=!0,y("%cGS on detected!",I.recognized);break}else(kn(C)||wn(C))&&(y("%cGM/2 on detected, removing!",I.info),L(),g=!1)}}if(!g&&e.length>0){let M=0;s.tracks[0][0].messageStatusByte===w.trackName&&M++,s.tracks[0].splice(M,0,ds(0)),y("%cGS on not detected. Adding it.",I.info)}this.flush(),q()}function br(e){let A=[],t=[],n=[],s=[];e.channelSnapshots.forEach((o,r)=>{if(o.isMuted){t.push(r);return}let g=o.channelTransposeKeyShift+o.customControllers[cA.channelTransposeFine]/100;g!==0&&A.push({channel:r,keyShift:g}),o.lockPreset&&n.push({channel:r,program:o.program,bank:o.bank,isDrum:o.drumChannel}),o.lockedControllers.forEach((i,E)=>{if(!i||E>127||E===S.bankSelect)return;let c=o.midiControllers[E]>>7;s.push({channel:r,controllerNumber:E,controllerValue:c})})}),this.modifyMIDI(n,s,t,A)}var mA={name:"INAM",album:"IPRD",album2:"IALB",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"},qe="utf-8",Ni="Created using SpessaSynth";function Lr(e,A,t=0,n="Shift_JIS",s={},o=!0){let r=this;if(ie("%cWriting the RMIDI File...",I.info),y(`%cConfiguration: Bank offset: %c${t}%c, encoding: %c${n}`,I.info,I.value,I.info,I.value),y("metadata",s),y("Initial bank offset",r.bankOffset),o){let R=function(){let G=0,C=1/0;return r.tracks.forEach((L,J)=>{u[J]>=L.length||L[u[J]].ticks<C&&(G=J,C=L[u[J]].ticks)}),G},B="gm",m=[],u=Array(r.tracks.length).fill(0),p=r.tracks.length,D=Array(r.tracks.length).fill(0),M=16+r.midiPortChannelOffsets.reduce((G,C)=>C>G?C:G),b=[];for(let G=0;G<M;G++)b.push({program:0,drums:G%16===9,lastBank:void 0,lastBankLSB:void 0,hasBankSelect:!1});for(;p>0;){let G=R(),C=r.tracks[G];if(u[G]>=C.length){p--;continue}let L=C[u[G]];u[G]++;let J=r.midiPortChannelOffsets[D[G]];if(L.messageStatusByte===w.midiPort){D[G]=L.messageData[0];continue}let EA=L.messageStatusByte&240;if(EA!==w.controllerChange&&EA!==w.programChange&&EA!==w.systemExclusive)continue;if(EA===w.systemExclusive){if(!Sn(L)){dt(L)?B="xg":Dn(L)?B="gs":kn(L)?(B="gm",m.push({tNum:G,e:L})):wn(L)&&(B="gm2");continue}let oA=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][L.messageData[5]&15]+J;b[oA].drums=!!(L.messageData[7]>0&&L.messageData[5]>>4);continue}let tA=(L.messageStatusByte&15)+J,T=b[tA];if(EA===w.programChange){let oA=kA(B),CA=L.messageData[0];T.drums?A.presets.findIndex(P=>P.program===CA&&P.isDrumPreset(oA,!0))===-1&&(L.messageData[0]=A.presets.find(P=>P.isDrumPreset(oA))?.program||0,y(`%cNo drum preset %c${CA}%c. Channel %c${tA}%c. Changing program to ${L.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)):A.presets.findIndex(P=>P.program===CA&&!P.isDrumPreset(oA))===-1&&(L.messageData[0]=A.presets.find(P=>!P.isDrumPreset(oA))?.program||0,y(`%cNo preset %c${CA}%c. Channel %c${tA}%c. Changing program to ${L.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)),T.program=L.messageData[0];let v=Math.max(0,T.lastBank?.messageData[1]-r.bankOffset),K=T?.lastBankLSB?.messageData[1]-r.bankOffset||0;if(T.lastBank===void 0)continue;let W=ct(v,K,T.drums,oA);if(A.presets.findIndex(P=>P.bank===W&&P.program===L.messageData[0])===-1){let P=A.presets.find(rA=>rA.program===L.messageData[0])?.bank+t||t;T.lastBank.messageData[1]=P,T?.lastBankLSB?.messageData&&(T.lastBankLSB.messageData[1]=P),y(`%cNo preset %c${W}:${L.messageData[0]}%c. Channel %c${tA}%c. Changing bank to ${P}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)}else{let P=W;kA(B)&&W===128&&(W=127);let rA=(W===128?128:P)+t;T.lastBank.messageData[1]=rA,T?.lastBankLSB?.messageData&&!T.drums&&(T.lastBankLSB.messageData[1]=T.lastBankLSB.messageData[1]-r.bankOffset+t),y(`%cPreset %c${W}:${L.messageData[0]}%c exists. Channel %c${tA}%c. Changing bank to ${rA}.`,I.info,I.recognized,I.info,I.recognized,I.info)}continue}let AA=L.messageData[0]===S.lsbForControl0BankSelect;if(L.messageData[0]!==S.bankSelect&&!AA)continue;T.hasBankSelect=!0;let hA=L.messageData[1],sA=Bt(T?.lastBank?.messageData[1]||0,hA,B,AA,T.drums,tA);sA.drumsStatus===2?T.drums=!0:sA.drumsStatus===1&&(T.drums=!1),AA?T.lastBankLSB=L:T.lastBank=L}if(b.forEach((G,C)=>{if(G.hasBankSelect===!0)return;let L=C%16,J=w.programChange|L,EA=Math.floor(C/16)*16,tA=r.midiPortChannelOffsets.indexOf(EA),T=r.tracks.find((oA,CA)=>r.midiPorts[CA]===tA&&r.usedChannelsOnTrack[CA].has(L));if(T===void 0)return;let AA=T.findIndex(oA=>oA.messageStatusByte===J);if(AA===-1){let oA=T.findIndex(K=>K.messageStatusByte>128&&K.messageStatusByte<240&&(K.messageStatusByte&15)===L);if(oA===-1)return;let CA=T[oA].ticks,v=A.getPreset(0,0).program;T.splice(oA,0,new YA(CA,w.programChange|L,new x([v]))),AA=oA}y(`%cAdding bank select for %c${C}`,I.info,I.recognized);let hA=T[AA].ticks,sA=A.getPreset(0,G.program,kA(B))?.bank+t||t;T.splice(AA,0,new YA(hA,w.controllerChange|L,new x([S.bankSelect,sA])))}),B!=="gs"&&!kA(B)){for(let C of m)r.tracks[C.tNum].splice(r.tracks[C.tNum].indexOf(C.e),1);let G=0;r.tracks[0][0].messageStatusByte===w.trackName&&G++,r.tracks[0].splice(G,0,ds(0))}}let g=new x(r.writeMIDI().buffer),i=[We("INFO")],E=new TextEncoder;if(i.push(_(mA.software,E.encode("SpessaSynth"),!0)),s.name!==void 0?(i.push(_(mA.name,E.encode(s.name),!0)),n=qe):i.push(_(mA.name,r.rawMidiName,!0)),s.creationDate!==void 0)n=qe,i.push(_(mA.creationDate,E.encode(s.creationDate),!0));else{let B=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});i.push(_(mA.creationDate,pe(B),!0))}if(s.comment!==void 0&&(n=qe,i.push(_(mA.comment,E.encode(s.comment)))),s.engineer!==void 0&&i.push(_(mA.engineer,E.encode(s.engineer),!0)),s.album!==void 0&&(n=qe,i.push(_(mA.album,E.encode(s.album),!0)),i.push(_(mA.album2,E.encode(s.album),!0))),s.artist!==void 0&&(n=qe,i.push(_(mA.artist,E.encode(s.artist),!0))),s.genre!==void 0&&(n=qe,i.push(_(mA.genre,E.encode(s.genre),!0))),s.picture!==void 0&&i.push(_(mA.picture,new Uint8Array(s.picture))),s.copyright!==void 0)n=qe,i.push(_(mA.copyright,E.encode(s.copyright),!0));else{let B=r.copyright.length>0?r.copyright:Ni;i.push(_(mA.copyright,pe(B)))}let c=new x(2);Je(c,t,2),i.push(_(mA.bankOffset,c)),s.midiEncoding!==void 0&&(i.push(_(mA.midiEncoding,E.encode(s.midiEncoding))),n=qe),i.push(_(mA.encoding,pe(n)));let h=DA(i),Q=DA([We("RMID"),_("data",g),_("LIST",h),e]);return y("%cFinished!",I.info),q(),_("RIFF",Q)}function Ur(e){let A=this;fA("%cSearching for all used programs and keys...",I.info);let t=16+A.midiPortChannelOffsets.reduce((h,Q)=>Q>h?Q:h),n=[];for(let h=0;h<t;h++){let Q=h%16===9?128:0;n.push({program:0,bank:Q,bankLSB:0,actualBank:Q,drums:h%16===9,string:`${Q}:0`})}let s="gs";function o(h){let Q=ct(h.bank,h.bankLSB,h.drums,kA(s)),B=e.getPreset(Q,h.program,kA(s));h.actualBank=B.bank,h.program=B.program,h.string=h.actualBank+":"+h.program,r[h.string]||(y(`%cDetected a new preset: %c${h.string}`,I.info,I.recognized),r[h.string]=new Set)}let r={},g=Array(A.tracks.length).fill(0),i=A.tracks.length;function E(){let h=0,Q=1/0;return A.tracks.forEach((B,m)=>{g[m]>=B.length||B[g[m]].ticks<Q&&(h=m,Q=B[g[m]].ticks)}),h}let c=A.midiPorts.slice();for(n.forEach(h=>{o(h)});i>0;){let h=E(),Q=A.tracks[h];if(g[h]>=Q.length){i--;continue}let B=Q[g[h]];if(g[h]++,B.messageStatusByte===w.midiPort){c[h]=B.messageData[0];continue}let m=B.messageStatusByte&240;if(m!==w.noteOn&&m!==w.controllerChange&&m!==w.programChange&&m!==w.systemExclusive)continue;let u=(B.messageStatusByte&15)+A.midiPortChannelOffsets[c[h]]||0,p=n[u];switch(m){case w.programChange:p.program=B.messageData[0],o(p);break;case w.controllerChange:let R=B.messageData[0]===S.lsbForControl0BankSelect;if(B.messageData[0]!==S.bankSelect&&!R||s==="gs"&&p.drums)continue;let D=B.messageData[1],M=Math.max(0,D-A.bankOffset);switch(R?p.bankLSB=M:p.bank=M,Bt(p.bank,M,s,R,p.drums,u).drumsStatus){case 0:break;case 1:p.drums=!1,o(p);break;case 2:p.drums=!0,o(p);break}break;case w.noteOn:if(B.messageData[1]===0)continue;r[p.string].add(`${B.messageData[0]}-${B.messageData[1]}`);break;case w.systemExclusive:if(!Sn(B)){dt(B)&&(s="xg",y("%cXG on detected!",I.recognized));continue}let G=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][B.messageData[5]&15]+A.midiPortChannelOffsets[c[h]],C=!!(B.messageData[7]>0&&B.messageData[5]>>4);p=n[G],p.drums=C,o(p);break}}for(let h of Object.keys(r))r[h].size===0&&(y(`%cDetected change but no keys for %c${h}`,I.info,I.value),delete r[h]);return q(),r}function Tr(e=0){function A(h){return h.messageData=new x(h.messageData.buffer),h.messageData.currentIndex=0,6e7/OA(h.messageData,3)}let t=[],s=this.tracks.flat();s.sort((h,Q)=>h.ticks-Q.ticks);for(let h=0;h<16;h++)t.push([]);let o=0,r=60/(120*this.timeDivision),g=0,i=0,E=[];for(let h=0;h<16;h++)E.push([]);let c=(h,Q)=>{let B=E[Q].findIndex(u=>u.midiNote===h),m=E[Q][B];if(m){let u=o-m.start;m.length=u,Q===9&&(m.length=u<e?e:u),E[Q].splice(B,1)}i--};for(;g<s.length;){let h=s[g],Q=h.messageStatusByte>>4,B=h.messageStatusByte&15;if(Q===8)c(h.messageData[0],B);else if(Q===9)if(h.messageData[1]===0)c(h.messageData[0],B);else{c(h.messageData[0],B);let m={midiNote:h.messageData[0],start:o,length:-1,velocity:h.messageData[1]/127};t[B].push(m),E[B].push(m),i++}else h.messageStatusByte===81&&(r=60/(A(h)*this.timeDivision));if(++g>=s.length)break;o+=r*(s[g].ticks-h.ticks)}return i>0&&E.forEach((h,Q)=>{h.forEach(B=>{let m=o-B.start;B.length=m,Q===9&&(B.length=m<e?e:m)})}),t}var XA=class e extends tt{embeddedSoundFont=void 0;tracks=[];isDLSRMIDI=!1;static copyFrom(A){let t=new e;return t._copyFromSequence(A),t.isDLSRMIDI=A.isDLSRMIDI,t.embeddedSoundFont=A.embeddedSoundFont?A.embeddedSoundFont.slice(0):void 0,t.tracks=A.tracks.map(n=>[...n]),t}_parseInternal(){ie("%cInterpreting MIDI events...",I.info);let A=!1;this.keyRange={max:0,min:127};let t=[],n=!1;typeof this.RMIDInfo.ICOP<"u"&&(n=!0);let s=!1;typeof this.RMIDInfo.INAM<"u"&&(s=!0);let o=null,r=null;for(let c=0;c<this.tracks.length;c++){let h=this.tracks[c],Q=new Set,B=!1;for(let u of h){if(u.messageStatusByte>=128&&u.messageStatusByte<240){B=!0;for(let R=0;R<u.messageData.length;R++)u.messageData[R]=Math.min(127,u.messageData[R]);switch(u.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=u.ticks),u.messageStatusByte&240){case w.controllerChange:switch(u.messageData[0]){case 2:case 116:o=u.ticks;break;case 4:case 117:r===null?r=u.ticks:r=0;break;case 0:this.isDLSRMIDI&&u.messageData[1]!==0&&u.messageData[1]!==127&&(y("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}break;case w.noteOn:Q.add(u.messageStatusByte&15);let R=u.messageData[0];this.keyRange.min=Math.min(this.keyRange.min,R),this.keyRange.max=Math.max(this.keyRange.max,R);break}}u.messageData.currentIndex=0;let p=$(u.messageData,u.messageData.length);switch(u.messageData.currentIndex=0,u.messageStatusByte){case w.setTempo:u.messageData.currentIndex=0,this.tempoChanges.push({ticks:u.ticks,tempo:6e7/OA(u.messageData,3)}),u.messageData.currentIndex=0;break;case w.marker:switch(p.trim().toLowerCase()){default:break;case"start":case"loopstart":o=u.ticks;break;case"loopend":r=u.ticks}u.messageData.currentIndex=0;break;case w.copyright:n||(u.messageData.currentIndex=0,t.push($(u.messageData,u.messageData.length,void 0,!1)),u.messageData.currentIndex=0);break;case w.lyric:if(p.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)),this.isKaraokeFile)u.messageStatusByte=w.text;else{this.lyrics.push(u.messageData),this.lyricsTicks.push(u.ticks);break}case w.text:let D=p.trim();D.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)):this.isKaraokeFile&&(D.startsWith("@T")||D.startsWith("@A")?A?t.push(D.substring(2).trim()):(this.midiName=D.substring(2).trim(),A=!0,s=!0,this.rawMidiName=We(this.midiName)):D[0]!=="@"&&(this.lyrics.push(vs(u.messageData)),this.lyricsTicks.push(u.ticks)));break;case w.trackName:break}}this.usedChannelsOnTrack.push(Q),this.trackNames[c]="";let m=h.find(u=>u.messageStatusByte===w.trackName);if(m){m.messageData.currentIndex=0;let u=$(m.messageData,m.messageData.length);this.trackNames[c]=u,B||t.push(u)}}this.tempoChanges.reverse(),y("%cCorrecting loops, ports and detecting notes...",I.info);let g=[];for(let c of this.tracks){let h=c.find(Q=>(Q.messageStatusByte&240)===w.noteOn);h&&g.push(h.ticks)}this.firstNoteOn=Math.min(...g),y(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,I.info,I.recognized,I.info),o!==null&&r===null?(o=this.firstNoteOn,r=this.lastVoiceEventTick):(o===null&&(o=this.firstNoteOn),(r===null||r===0)&&(r=this.lastVoiceEventTick)),this.loop={start:o,end:r},y(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,I.info,I.recognized,I.info,I.recognized);let i=0;this.midiPorts=[],this.midiPortChannelOffsets=[];for(let c=0;c<this.tracks.length;c++)if(this.midiPorts.push(-1),this.usedChannelsOnTrack[c].size!==0)for(let h of this.tracks[c]){if(h.messageStatusByte!==w.midiPort)continue;let Q=h.messageData[0];this.midiPorts[c]=Q,this.midiPortChannelOffsets[Q]===void 0&&(this.midiPortChannelOffsets[Q]=i,i+=16)}let E=1/0;for(let c of this.midiPorts)c!==-1&&E>c&&(E=c);if(E===1/0&&(E=0),this.midiPorts=this.midiPorts.map(c=>c===-1?E:c),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?y("%cNo additional MIDI Ports detected.",I.info):(this.isMultiPort=!0,y("%cMIDI Ports detected!",I.recognized)),!s)if(this.tracks.length>1){if(this.tracks[0].find(c=>c.messageStatusByte>=w.noteOn&&c.messageStatusByte<w.polyPressure)===void 0){let c=this.tracks[0].find(h=>h.messageStatusByte===w.trackName);c&&(this.rawMidiName=c.messageData,c.messageData.currentIndex=0,this.midiName=$(c.messageData,c.messageData.length,void 0,!1))}}else{let c=this.tracks[0].find(h=>h.messageStatusByte===w.trackName);c&&(this.rawMidiName=c.messageData,c.messageData.currentIndex=0,this.midiName=$(c.messageData,c.messageData.length,void 0,!1))}if(n||(this.copyright=t.map(c=>c.trim().replace(/(\r?\n)+/g,`
17
+ %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),q(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};function $e(e){let A=e.slice(8,12),t=new x(A);return $(t,4,void 0,!1).toLowerCase()==="dls "?new be(e):new mn(e,!1)}function $o(e,A){this.soundfontBankOffset=A,this.clearSoundFont(!1,!0),this.overrideSoundfont=$e(e),this.updatePresetList(),this.getDefaultPresets(),this.midiAudioChannels.forEach(t=>t.programChange(t.preset.program)),this.overrideSoundfont.samples.forEach(t=>t.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),y("%cSpessaSynth is ready!",I.recognized)}function Ar(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.getDefaultPresets(),this.clearCache(),e&&this.updatePresetList();for(let t=0;t<this.midiAudioChannels.length;t++){let n=this.midiAudioChannels[t];(!A||A&&n.presetUsesOverride)&&n.setPresetLock(!1),n.programChange(n.preset.program)}}function er(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,n=e.find(s=>s.bank===t&&s.program===A.program);n!==void 0?n.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.clearCache(),this.callEvent("presetlistchange",e),this.getDefaultPresets(),this.resetAllControllers(!1)}function tr(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(t,A,kA(this.system));if(n)return n}return this.soundfontManager.getPreset(e,A,kA(this.system))}function nr(e,A=!1){this.transposition=0;for(let t=0;t<this.midiAudioChannels.length;t++)this.midiAudioChannels[t].transposeChannel(e,A);this.transposition=e}function sr(e){e=Math.round(e);for(let A=0;A<this.midiAudioChannels.length;A++)this.midiAudioChannels[A].setCustomController(cA.masterTuning,e)}var lt=class e{program;bank;isBankLSB;patchName;lockPreset;lockedSystem;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;isMuted;velocityOverride;drumChannel;static getChannelSnapshot(A,t){let n=A.midiAudioChannels[t],s=new e;return s.program=n.preset.program,s.bank=n.getBankSelect(),s.isBankLSB=s.bank!==n.bank,s.lockPreset=n.lockPreset,s.lockedSystem=n.lockedSystem,s.patchName=n.preset.presetName,s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockVibrato=n.lockGSNRPNParams,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.isMuted=n.isMuted,s.velocityOverride=n.velocityOverride,s.drumChannel=n.drumChannel,s}static applyChannelSnapshot(A,t,n){let s=A.midiAudioChannels[t];s.muteChannel(n.isMuted),s.setDrums(n.drumChannel),s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.updateChannelTuning(),s.channelVibrato=n.channelVibrato,s.lockGSNRPNParams=n.lockVibrato,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.velocityOverride=n.velocityOverride,s.setPresetLock(!1),s.setBankSelect(n.bank,n.isBankLSB),s.programChange(n.program),s.setPresetLock(n.lockPreset),s.lockedSystem=n.lockedSystem}};var At=class e{channelSnapshots;keyMappings;mainVolume;pan;interpolation;system;transposition;static createSynthesizerSnapshot(A){let t=new e;return t.channelSnapshots=A.midiAudioChannels.map((n,s)=>lt.getChannelSnapshot(A,s)),t.keyMappings=A.keyModifierManager.getMappings(),t.mainVolume=A.midiVolume,t.pan=A.pan,t.system=A.system,t.interpolation=A.interpolationType,t.transposition=A.transposition,t.effectsConfig={},t}static applySnapshot(A,t){for(A.setSystem(t.system),A.setMasterParameter(JA.mainVolume,t.mainVolume),A.setMasterParameter(JA.masterPan,t.pan),A.transposeAllChannels(t.transposition),A.interpolationType=t.interpolation,A.keyModifierManager.setMappings(t.keyMappings);A.midiAudioChannels.length<t.channelSnapshots.length;)A.createMidiChannel();t.channelSnapshots.forEach((n,s)=>{lt.applyChannelSnapshot(A,s,n)}),y("%cFinished restoring controllers!",I.info)}};function or(e){this._snapshot=e,At.applySnapshot(this,e),y("%cFinished applying snapshot!",I.info),this.resetAllControllers()}function pn(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}var Qt=class{static getSampleLinear(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1;for(;E>=n.loopEnd;)E-=r;let c=s-i,h=o[E],Q=o[i];t[g]=Q+(h-Q)*c,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1;if(i>=n.end){A.finished=!0;return}let E=s-g,c=o[i],h=o[g];t[r]=h+(c-h)*E,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}static getSampleNearest(A,t){let n=A.sample,s=n.cursor,o=n.loopEnd-n.loopStart,r=n.sampleData;if(A.sample.isLooping)for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=o;let i=~~s+1;for(;i>=n.loopEnd;)i-=o;t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let g=0;g<t.length;g++){let i=~~s+1;if(i>=n.end){A.finished=!0;return}t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1,c=E+1,h=c+1,Q=s-i;E>=n.loopEnd&&(E-=r),c>=n.loopEnd&&(c-=r),h>=n.loopEnd&&(h-=r);let B=o[i],m=o[E],u=o[c],p=o[h],R=.5*(u-B),D=B-2.5*m+2*u-.5*p,M=.5*(p-B)+1.5*(m-u);t[g]=((M*Q+D)*Q+R)*Q+m,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1,E=i+1,c=E+1,h=s-g;if(i>=n.end||E>=n.end||c>=n.end){A.finished=!0;return}let Q=o[g],B=o[i],m=o[E],u=o[c],p=.5*(m-Q),R=Q-2.5*B+2*m-.5*u,D=.5*(u-Q)+1.5*(B-m);t[r]=((D*h+R)*h+p)*h+B,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};function rr(e,A,t,n,s,o,r,g){if(e.isInRelease||A>=e.releaseStartTime&&(e.isInRelease=!0,Ee.startRelease(e),he.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[a.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let i=e.targetKey,E=e.modulatedGenerators[a.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,c=e.modulatedGenerators[a.coarseTune],h=this.synth.tunings[this.preset.program]?.[e.realKey];if(h!==void 0&&h?.midiNote>=0&&(i=h.midiNote,E+=h.centTuning),e.portamentoFromKey>-1){let C=Math.min((A-e.startTime)/e.portamentoDuration,1),L=i-e.portamentoFromKey;c-=L*(1-C)}E+=(i-e.sample.rootKey)*e.modulatedGenerators[a.scaleTuning];let Q=e.modulatedGenerators[a.vibLfoToPitch];if(Q!==0){let C=e.startTime+Ce(e.modulatedGenerators[a.delayVibLFO]),L=bt(e.modulatedGenerators[a.freqVibLFO]),J=pn(C,L,A);E+=J*(Q*this.customControllers[cA.modulationMultiplier])}let B=0,m=e.modulatedGenerators[a.modLfoToPitch],u=e.modulatedGenerators[a.modLfoToVolume],p=e.modulatedGenerators[a.modLfoToFilterFc],R=0;if(m!==0||p!==0||u!==0){let C=e.startTime+Ce(e.modulatedGenerators[a.delayModLFO]),L=bt(e.modulatedGenerators[a.freqModLFO]),J=pn(C,L,A);E+=J*(m*this.customControllers[cA.modulationMultiplier]),R=-J*u,B+=J*p}if(this.channelVibrato.depth>0){let C=pn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,A);C&&(E+=C*this.channelVibrato.depth)}let D=e.modulatedGenerators[a.modEnvToPitch],M=e.modulatedGenerators[a.modEnvToFilterFc];if(M!==0||D!==0){let C=he.getValue(e,A);B+=C*M,E+=C*D}let b=~~(E+c*100);b!==e.currentTuningCents&&(e.currentTuningCents=b,e.currentTuningCalculated=Math.pow(2,b/1200));let G=new Float32Array(t.length);switch(this.synth.interpolationType){case ze.fourthOrder:Qt.getSampleCubic(e,G);break;case ze.linear:default:Qt.getSampleLinear(e,G);break;case ze.nearestNeighbor:Qt.getSampleNearest(e,G);break}return Ye.apply(e,G,B,this.synth.filterSmoothingFactor),Ee.apply(e,G,R,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,G,t,n,s,o,r,g),e.finished}function ir(e,A=-12e3){this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[a.releaseVolEnv]=A,t.release(this.synth.currentSynthTime))})}function ar(e,A=!0){e=Math.round(e),this.setCustomController(cA.channelTuning,e),A&&y(`%cFine tuning for %c${this.channelNumber}%c is now set to %c${e}%c cents.`,I.info,I.recognized,I.info,I.value,I.info)}function Ir(e){e=Math.round(e),y(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,I.info,I.value),this.setCustomController(cA.modulationMultiplier,e/50)}function gr(e){switch(this.dataEntryState){default:break;case HA.RPCoarse:case HA.RPFine:switch(this.midiControllers[S.RPNMsb]|this.midiControllers[S.RPNLsb]>>7){default:break;case 0:if(e===0)break;this.midiControllers[RA+j.pitchWheelRange]|=e;let t=(this.midiControllers[RA+j.pitchWheelRange]>>7)+e/128;y(`%cChannel ${this.channelNumber} bend range. Semitones: %c${t}`,I.info,I.value);break;case 1:let s=this.customControllers[cA.channelTuning]<<7|e;this.setTuning(s*.01220703125);break;case 5:let r=this.customControllers[cA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(r);break;case 16383:this.resetParameters();break}}}var Gi=1e3/200;function Cr(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let E=A.sourceIndex+RA;switch(A.sourceIndex){case j.noController:n=16383;break;case j.noteOnKeyNum:n=t.midiNote<<7;break;case j.noteOnVelocity:n=t.velocity<<7;break;case j.polyPressure:n=t.pressure<<7;break;default:n=e[E];break}}let s=et[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let E=A.secSrcIndex+RA;switch(A.secSrcIndex){case j.noController:o=16383;break;case j.noteOnKeyNum:o=t.midiNote<<7;break;case j.noteOnVelocity:o=t.velocity<<7;break;case j.polyPressure:o=t.pressure<<7;break;default:o=e[E]}}let r=et[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Gi,g=Math.min(g,1e3));let i=s*r*g;return A.transformType===2&&(i=Math.abs(i)),A.currentValue=i,i}function Be(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,r=e.modulatedGenerators;if(t===-1){r.set(o),s.forEach(E=>{let c=X[E.modulatorDestination],h=r[E.modulatorDestination]+Cr(A,E,e);r[E.modulatorDestination]=Math.max(c.min,Math.min(h,c.max))}),Ee.recalculate(e),he.recalculate(e);return}let g=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),i=new Set;s.forEach(E=>{if(E.sourceUsesCC===t&&E.sourceIndex===n||E.secSrcUsesCC===t&&E.secSrcIndex===n){let c=E.modulatorDestination;i.has(c)||(r[c]=o[c],Cr(A,E,e),s.forEach(h=>{if(h.modulatorDestination===c){let Q=X[E.modulatorDestination],B=r[E.modulatorDestination]+h.currentValue;r[E.modulatorDestination]=Math.max(Q.min,Math.min(B,Q.max))}}),i.add(c))}}),[...i].some(E=>g.has(E))&&Ee.recalculate(e),he.recalculate(e)}var et=[];for(let e=0;e<4;e++){et[e]=[[new Float32Array(bA),new Float32Array(bA)],[new Float32Array(bA),new Float32Array(bA)]];for(let A=0;A<bA;A++)et[e][0][0][A]=je(0,e,A/bA,0),et[e][1][0][A]=je(0,e,A/bA,1),et[e][0][1][A]=je(1,e,A/bA,0),et[e][1][1][A]=je(1,e,A/bA,1)}function Er(e,A,t=!1){if(e>127){if(!t)return;switch(e){default:return;case ts.velocityOverride:this.velocityOverride=A}}if(e>=S.lsbForControl1ModulationWheel&&e<=S.lsbForControl13EffectControl2&&e!==S.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>Be(s,this.midiControllers,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case S.allNotesOff:this.stopAllNotes();break;case S.allSoundOff:this.stopAllNotes(!0);break;case S.bankSelect:this.setBankSelect(A);break;case S.lsbForControl0BankSelect:this.setBankSelect(A,!0);break;case S.RPNLsb:this.dataEntryState=HA.RPFine;break;case S.RPNMsb:this.dataEntryState=HA.RPCoarse;break;case S.NRPNMsb:this.dataEntryState=HA.NRPCoarse;break;case S.NRPNLsb:this.dataEntryState=HA.NRPFine;break;case S.dataEntryMsb:this.dataEntryCoarse(A);break;case S.lsbForControl6DataEntry:this.dataEntryFine(A);break;case S.resetAllControllers:this.resetControllersRP15Compliant();break;case S.sustainPedal:A>=64?this.holdPedal=!0:(this.holdPedal=!1,this.sustainedVoices.forEach(n=>{n.release(this.synth.currentSynthTime)}),this.sustainedVoices=[]);break;default:this.voices.forEach(n=>Be(n,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}function hr(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.sendChannelProperty()):(this.voices.forEach(A=>{A.isInRelease||A.release(this.synth.currentSynthTime)}),this.sustainedVoices.forEach(A=>{A.release(this.synth.currentSynthTime)}))}function Br(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.sendChannelProperty(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function cr(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[cA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.controllerChange(S.allNotesOff,127),this.channelTransposeKeyShift=t,this.setCustomController(cA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}var Ht={pitchBendRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},Oe={partParameter:1,vibratoRate:8,vibratoDepth:9,vibratoDelay:10,EGAttackTime:100,EGReleaseTime:102,TVFFilterCutoff:32,drumReverb:29};function lr(e){let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)},t=(n,s,o)=>{o.length>0&&(o=" "+o),y(`%c${n} for %c${this.channelNumber}%c is now set to %c${s}%c${o}.`,I.info,I.recognized,I.info,I.value,I.info)};switch(this.dataEntryState){default:case HA.Idle:break;case HA.NRPFine:if(this.lockGSNRPNParams)return;let n=this.midiControllers[S.NRPNMsb]>>7,s=this.midiControllers[S.NRPNLsb]>>7;switch(n){default:if(e===64)return;H(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${s.toString(16).toUpperCase()} 0x${s.toString(16).toUpperCase()})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Oe.partParameter:switch(s){default:if(e===64)return;H(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)} 0x${s.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Oe.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case Oe.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case Oe.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case Oe.TVFFilterCutoff:this.controllerChange(S.brightness,e),t("Filter cutoff",e.toString(),"");break;case Oe.EGAttackTime:this.controllerChange(S.attackTime,e),t("EG attack time",e.toString(),"");break;case Oe.EGReleaseTime:this.controllerChange(S.releaseTime,e),t("EG release time",e.toString(),"");break}break;case Oe.drumReverb:let r=e;this.controllerChange(S.reverbDepth,r),t("GS Drum reverb",r.toString(),"percent");break}break;case HA.RPCoarse:case HA.RPFine:let o=this.midiControllers[S.RPNMsb]|this.midiControllers[S.RPNLsb]>>7;switch(o){default:H(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${o.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Ht.pitchBendRange:this.midiControllers[RA+j.pitchWheelRange]=e<<7,t("Pitch bend range",e.toString(),"semitones");break;case Ht.coarseTuning:let r=e-64;this.setCustomController(cA.channelTuningSemitones,r),t("Coarse tuning",r.toString(),"semitones");break;case Ht.fineTuning:this.setTuning(e-64,!1);break;case Ht.modulationDepth:this.setModulationDepth(e*100);break;case Ht.resetParameters:this.resetParameters();break}}}var Yt={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function Mi(e){if(Yt[e]!==void 0)return Yt[e];let A=null,t=null;for(let n of Object.keys(Yt))n=parseInt(n),n<e&&(A===null||n>A)&&(A=n),n>e&&(t===null||n<t)&&(t=n);if(A!==null&&t!==null){let n=Yt[A],s=Yt[t];return n+(e-A)*(s-n)/(t-A)}return 0}function Qr(e,A){return Mi(e)*(A/30)}function dr(e,A){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synth.highPerformanceMode&&this.synth.totalVoicesAmount>200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let t=e+this.channelTransposeKeyShift,n=t;if(t>127||t<0)return;let s=this.preset.program,o=this.synth.tunings[s]?.[t]?.midiNote;o>=0&&(n=o),this.velocityOverride>0&&(A=this.velocityOverride);let r=this.synth.keyModifierManager.getVelocity(this.channelNumber,t);r>-1&&(A=r);let g=this.synth.keyModifierManager.getGain(this.channelNumber,t),i=-1,E=0,c=this.midiControllers[S.portamentoTime]>>7,h=this.midiControllers[S.portamentoControl],Q=h>>7;if(!this.drumChannel&&Q!==n&&this.midiControllers[S.portamentoOnOff]>=8192&&c>0){if(h!==1){let p=Math.abs(n-Q);E=Qr(c,p),i=Q}this.controllerChange(S.portamentoControl,n)}let B=this.synth.getVoices(this.channelNumber,n,A,t),m=0;this.randomPan&&(m=Math.round(Math.random()*1e3-500));let u=this.voices;B.forEach(p=>{p.portamentoFromKey=i,p.portamentoDuration=E,p.overridePan=m,p.gain=g;let R=p.exclusiveClass;R!==0&&u.forEach(J=>{J.exclusiveClass===R&&J.exclusiveRelease(this.synth.currentSynthTime)}),Be(p,this.midiControllers);let D=p.modulatedGenerators[a.startAddrsOffset]+p.modulatedGenerators[a.startAddrsCoarseOffset]*32768,M=p.modulatedGenerators[a.endAddrOffset]+p.modulatedGenerators[a.endAddrsCoarseOffset]*32768,b=p.modulatedGenerators[a.startloopAddrsOffset]+p.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,G=p.modulatedGenerators[a.endloopAddrsOffset]+p.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,C=p.sample,L=J=>Math.max(0,Math.min(C.sampleData.length-1,J));if(C.cursor=L(C.cursor+D),C.end=L(C.end+M),C.loopStart=L(C.loopStart+b),C.loopEnd=L(C.loopEnd+G),C.loopEnd<C.loopStart){let J=C.loopStart;C.loopStart=C.loopEnd,C.loopEnd=J}C.loopEnd-C.loopStart<1&&(C.loopingMode=0,C.isLooping=!1),p.volumeEnvelope.attenuation=p.volumeEnvelope.attenuationTargetGain,p.currentPan=Math.max(-500,Math.min(500,p.modulatedGenerators[a.pan]))}),this.synth.totalVoicesAmount+=B.length,this.synth.totalVoicesAmount>this.synth.voiceCap&&this.synth.voiceKilling(B.length),u.push(...B),this.sendChannelProperty(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A})}function fr(e){if(e>127||e<0){H("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift;if(this.synth.highPerformanceMode&&!this.drumChannel){this.killNote(A,-6950),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease===!0||(this.holdPedal?this.sustainedVoices.push(n):n.release(this.synth.currentSynthTime))}),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber})}function ur(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,Be(t,this.midiControllers,0,j.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function mr(e){this.midiControllers[RA+j.channelPressure]=e<<7,this.voices.forEach(A=>Be(A,this.midiControllers,0,j.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function pr(e,A){if(this.lockedControllers[RA+j.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[RA+j.pitchWheel]=t,this.voices.forEach(n=>Be(n,this.midiControllers,0,j.pitchWheel)),this.sendChannelProperty()}function yr(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=new Int8Array(128);for(let A=0;A<128;A++)this.channelOctaveTuning[A]=e[A%12]}function Sr(e){if(this.lockPreset)return;let A=this.getBankSelect(),t,n,s=this.isXGChannel;if(this.synth.overrideSoundfont){let o=A===128?128:A-this.synth.soundfontBankOffset,r=this.synth.overrideSoundfont.getPresetNoFallback(o,e,s);if(r)t=r.bank===128?128:r.bank+this.synth.soundfontBankOffset,n=r,this.presetUsesOverride=!0;else{n=this.synth.soundfontManager.getPreset(A,e,s);let g=this.synth.soundfontManager.soundfontList.find(i=>i.soundfont===n.parentSoundBank).bankOffset;t=n.bank-g,this.presetUsesOverride=!1}}else{n=this.synth.soundfontManager.getPreset(A,e,s);let o=this.synth.soundfontManager.soundfontList.find(r=>r.soundfont===n.parentSoundBank).bankOffset;t=n.bank-o,this.presetUsesOverride=!1}this.setPreset(n),this.sentBank=t,this.synth.callEvent("programchange",{channel:this.channelNumber,program:n.program,bank:t}),this.sendChannelProperty()}var SA=class{midiControllers=new Int16Array(sn);lockedControllers=Array(sn).fill(!1);customControllers=new Float32Array(As);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);channelTuningCents=0;holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=HA.Idle;bank=0;sentBank=0;bankLSB=0;preset=void 0;lockPreset=!1;lockedSystem="gs";presetUsesOverride=!1;lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};isMuted=!1;voices=[];sustainedVoices=[];channelNumber;synth;constructor(A,t,n){this.synth=A,this.preset=t,this.channelNumber=n}get isXGChannel(){return kA(this.synth.system)||this.lockPreset&&kA(this.lockedSystem)}setCustomController(A,t){this.customControllers[A]=t,this.updateChannelTuning()}updateChannelTuning(){this.channelTuningCents=this.customControllers[cA.channelTuning]+this.customControllers[cA.channelTransposeFine]+this.customControllers[cA.masterTuning]+this.customControllers[cA.channelTuningSemitones]*100}renderAudio(A,t,n,s,o,r){this.voices=this.voices.filter(g=>!this.renderVoice(g,this.synth.currentSynthTime,A,t,n,s,o,r))}setPresetLock(A){this.lockPreset=A,A&&(this.lockedSystem=this.synth.system)}setBankSelect(A,t=!1){if(!this.lockPreset)if(t)this.bankLSB=A;else switch(this.bank=A,Bt(this.getBankSelect(),A,this.synth.system,!1,this.drumChannel,this.channelNumber).drumsStatus){default:case 0:break;case 1:this.channelNumber%16===9&&(this.bank=127);break;case 2:this.setDrums(!0);break}}getBankSelect(){return ct(this.bank,this.bankLSB,this.drumChannel,this.isXGChannel)}setPreset(A){this.lockPreset||(delete this.preset,this.preset=A)}setDrums(A){this.lockPreset||this.drumChannel!==A&&(A?(this.channelTransposeKeyShift=0,this.drumChannel=!0):this.drumChannel=!1,this.presetUsesOverride=!1,this.synth.callEvent("drumchange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}),this.programChange(this.preset.program),this.sendChannelProperty())}setVibrato(A,t,n){this.lockGSNRPNParams||(this.channelVibrato.rate=t,this.channelVibrato.delay=n,this.channelVibrato.depth=A)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}sendChannelProperty(){if(!this.synth.enableEventSystem)return;let A={voicesAmount:this.voices.length,pitchBend:this.midiControllers[RA+j.pitchWheel],pitchBendRangeSemitones:this.midiControllers[RA+j.pitchWheelRange]/128,isMuted:this.isMuted,isDrum:this.drumChannel,transposition:this.channelTransposeKeyShift+this.customControllers[cA.channelTransposeFine]/100,bank:this.sentBank,program:this.preset.program};this.synth?.onChannelPropertyChange?.(A,this.channelNumber)}};SA.prototype.renderVoice=rr;SA.prototype.panVoice=Eo;SA.prototype.killNote=ir;SA.prototype.stopAllNotes=hr;SA.prototype.muteChannel=Br;SA.prototype.noteOn=dr;SA.prototype.noteOff=fr;SA.prototype.polyPressure=ur;SA.prototype.channelPressure=mr;SA.prototype.pitchWheel=pr;SA.prototype.programChange=Sr;SA.prototype.setTuning=ar;SA.prototype.setOctaveTuning=yr;SA.prototype.setModulationDepth=Ir;SA.prototype.transposeChannel=cr;SA.prototype.controllerChange=Er;SA.prototype.resetControllers=Ao;SA.prototype.resetControllersRP15Compliant=eo;SA.prototype.resetParameters=to;SA.prototype.dataEntryFine=gr;SA.prototype.dataEntryCoarse=lr;function Dr(e=!1){let A=new SA(this,this.defaultPreset,this.midiAudioChannels.length);this.midiAudioChannels.push(A),e&&(this.callEvent("newchannel",void 0),A.sendChannelProperty(),this.midiAudioChannels[this.midiAudioChannels.length-1].setDrums(!0))}var Qs={enableEventSystem:!0,initialTime:0,effectsEnabled:!0,midiChannels:16};function kr(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var oo=.03,ro=.07,_n=1,LA=class{cachedVoices=[];deviceID=-1;eventQueue=[];interpolationType=ze.fourthOrder;transposition=0;tunings=[];soundfontBankOffset=0;masterGain=_n;midiVolume=1;reverbGain=1;chorusGain=1;voiceCap=350;pan=0;panLeft=.5;panRight=.5;highPerformanceMode=!1;keyModifierManager=new an;overrideSoundfont=void 0;midiAudioChannels=[];system=Nt;totalVoicesAmount=0;defaultPreset;defaultPresetUsesOverride=!1;drumPreset;defaultDrumsUsesOverride=!1;processorInitialized=me.isInitialized;currentSynthTime=0;sampleRate;sampleTime;effectsEnabled;_snapshot;onEventCall;onChannelPropertyChange;onMasterParameterChange;constructor(A,t=Qs){t=kr(t,Qs),this.midiOutputsCount=t.midiChannels,this.effectsEnabled=t.effectsEnabled,this.enableEventSystem=t.enableEventSystem,this.currentSynthTime=t.midiChannels,this.sampleTime=1/A,this.sampleRate=A,this.volumeEnvelopeSmoothingFactor=qs*(44100/A),this.panSmoothingFactor=ao*(44100/A),this.filterSmoothingFactor=no*(44100/A);for(let n=0;n<128;n++)this.tunings.push([]);this.soundfontManager=new rn(this.updatePresetList.bind(this));for(let n=0;n<this.midiOutputsCount;n++)this.createMidiChannel(!1);this.processorInitialized.then(()=>{y("%cSpessaSynth is ready!",I.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}getDefaultPresets(){let A=this.system;this.system="xg",this.defaultPreset=this.getPreset(0,0),this.defaultPresetUsesOverride=this.overrideSoundfont?.presets?.indexOf(this.defaultPreset)>=0,this.system=A,this.drumPreset=this.getPreset(128,0),this.defaultDrumsUsesOverride=this.overrideSoundfont?.presets?.indexOf(this.drumPreset)>=0}setSystem(A){this.system=A,this?.onMasterParameterChange?.(JA.midiSystem,this.system)}getCachedVoice(A,t,n,s){return this.cachedVoices?.[A]?.[t]?.[n]?.[s]}setCachedVoice(A,t,n,s,o){this.cachedVoices[A]||(this.cachedVoices[A]=[]),this.cachedVoices[A][t]||(this.cachedVoices[A][t]=[]),this.cachedVoices[A][t][n]||(this.cachedVoices[A][t][n]=[]),this.cachedVoices[A][t][n][s]=o}renderAudio(A,t,n){this.renderAudioSplit(t,n,Array(16).fill(A))}renderAudioSplit(A,t,n){let s=this.currentSynthTime;for(;this.eventQueue[0]?.time<=s;)this.eventQueue.shift().callback();let o=A[0],r=A[1],g=t[0],i=t[1];this.totalVoicesAmount=0,this.midiAudioChannels.forEach((E,c)=>{if(E.voices.length<1||E.isMuted)return;let h=E.voices.length,Q=c%16;E.renderAudio(n[Q][0],n[Q][1],o,r,g,i),this.totalVoicesAmount+=E.voices.length,E.voices.length!==h&&E.sendChannelProperty()}),this.currentSynthTime+=n[0][0].length*this.sampleTime}destroySynthProcessor(){this.midiAudioChannels.forEach(A=>{delete A.midiControllers,delete A.voices,delete A.sustainedVoices,delete A.lockedControllers,delete A.preset,delete A.customControllers}),delete this.cachedVoices,delete this.midiAudioChannels,this.soundfontManager.destroyManager(),delete this.soundfontManager}controllerChange(A,t,n,s=!1){this.midiAudioChannels[A].controllerChange(t,n,s)}noteOn(A,t,n){this.midiAudioChannels[A].noteOn(t,n)}noteOff(A,t){this.midiAudioChannels[A].noteOff(t)}polyPressure(A,t,n){this.midiAudioChannels[A].polyPressure(t,n)}channelPressure(A,t){this.midiAudioChannels[A].channelPressure(t)}pitchWheel(A,t,n){this.midiAudioChannels[A].pitchWheel(t,n)}programChange(A,t){this.midiAudioChannels[A].programChange(t)}processMessage(A,t,n,s){let o=()=>{let g=ht(A[0]),i=g.channel+t;switch(g.status){case w.noteOn:let E=A[2];E>0?this.noteOn(i,A[1],E):this.noteOff(i,A[1]);break;case w.noteOff:n?this.midiAudioChannels[i].killNote(A[1]):this.noteOff(i,A[1]);break;case w.pitchBend:this.pitchWheel(i,A[2],A[1]);break;case w.controllerChange:this.controllerChange(i,A[1],A[2],n);break;case w.programChange:this.programChange(i,A[1]);break;case w.polyPressure:this.polyPressure(i,A[0],A[1]);break;case w.channelPressure:this.channelPressure(i,A[1]);break;case w.systemExclusive:this.systemExclusive(new x(A.slice(1)),t);break;case w.reset:this.stopAllChannels(!0),this.resetAllControllers();break;default:break}},r=s.time;r>this.currentSynthTime?(this.eventQueue.push({callback:o.bind(this),time:r}),this.eventQueue.sort((g,i)=>g.time-i.time)):o()}setMIDIVolume(A){this.midiVolume=Math.pow(A,Math.E),this.setMasterParameter(JA.masterPan,this.pan)}callEvent(A,t){this?.onEventCall?.(A,t)}clearCache(){this.cachedVoices=[]}};LA.prototype.voiceKilling=Hs;LA.prototype.getVoices=so;LA.prototype.systemExclusive=_s;LA.prototype.stopAllChannels=ho;LA.prototype.createMidiChannel=Dr;LA.prototype.resetAllControllers=$s;LA.prototype.setMasterParameter=Ws;LA.prototype.transposeAllChannels=nr;LA.prototype.setMasterTuning=sr;LA.prototype.getPreset=tr;LA.prototype.clearSoundFont=Ar;LA.prototype.setEmbeddedSoundFont=$o;LA.prototype.updatePresetList=er;LA.prototype.applySynthesizerSnapshot=or;function OA(e,A){let t=0;for(let n=8*(A-1);n>=0;n-=8)t|=e[e.currentIndex++]<<n;return t>>>0}function Jt(e,A){let t=new Array(A).fill(0);for(let n=A-1;n>=0;n--)t[n]=e&255,e>>=8;return t}function Fr(e,A){if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=ht(e.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=n,t.status){case w.noteOn:let s=e.messageData[1];if(s>0)this.synth.noteOn(t.channel,e.messageData[0],s),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:s});else{this.synth.noteOff(t.channel,e.messageData[0]);let g=this.playingNotes.findIndex(i=>i.midiNote===e.messageData[0]&&i.channel===t.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case w.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===e.messageData[0]&&g.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case w.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.programChange(t.channel,e.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(e.messageData,n);break;case w.setTempo:e.messageData.currentIndex=0;let r=6e7/OA(e.messageData,3);this.oneTickToSeconds=60/(r*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),H("invalid tempo! falling back to 120 BPM"),r=120);break;case w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:case w.sequenceNumber:case w.sequenceSpecific:case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:case w.programName:break;case w.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:H(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(w).find(g=>w[g]===t.status)}`,I.warn,I.unrecognized,I.warn,I.value);break}t.status>=0&&t.status<128&&this?.onMetaEvent?.(e,A)}function Rr(){for(let e=0;e<16;e++)this.synth.createMidiChannel(!0)}function Gr(){if(!this.isActive)return;let e=this.currentTime;for(;this.playedTime<e;){let A=this._findFirstEventIndex(),t=this.tracks[A][this.eventIndex[A]];if(this._processEvent(t,A),this.eventIndex[A]++,A=this._findFirstEventIndex(),this.tracks[A].length<=this.eventIndex[A]){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];this.playedTime+=this.oneTickToSeconds*(n.ticks-t.ticks);let s=this.loop&&(this.loopCount>0||this.loopCount===-1);if(this.midiData.loop.end<=t.ticks&&s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Mr(){let e=0,A=1/0;return this.tracks.forEach((t,n)=>{this.eventIndex[n]>=t.length||t[this.eventIndex[n]].ticks<A&&(e=n,A=t[this.eventIndex[n]].ticks)}),e}var tt=class{timeDivision=0;duration=0;tempoChanges=[{ticks:0,tempo:120}];copyright="";tracksAmount=0;trackNames=[];lyrics=[];lyricsTicks=[];firstNoteOn=0;keyRange={min:0,max:127};lastVoiceEventTick=0;midiPorts=[0];midiPortChannelOffsets=[0];usedChannelsOnTrack=[];loop={start:0,end:0};midiName="";midiNameUsesFileName=!1;fileName="";rawMidiName;format=0;RMIDInfo={};bankOffset=0;isKaraokeFile=!1;isMultiPort=!1;MIDIticksToSeconds(A){let t=0;for(;A>0;){let n=this.tempoChanges.find(o=>o.ticks<A),s=A-n.ticks;t+=s*60/(n.tempo*this.timeDivision),A-=s}return t}_copyFromSequence(A){this.midiName=A.midiName,this.midiNameUsesFileName=A.midiNameUsesFileName,this.fileName=A.fileName,this.timeDivision=A.timeDivision,this.duration=A.duration,this.copyright=A.copyright,this.tracksAmount=A.tracksAmount,this.firstNoteOn=A.firstNoteOn,this.lastVoiceEventTick=A.lastVoiceEventTick,this.format=A.format,this.bankOffset=A.bankOffset,this.isKaraokeFile=A.isKaraokeFile,this.isMultiPort=A.isMultiPort,this.tempoChanges=[...A.tempoChanges],this.lyrics=A.lyrics.map(t=>new Uint8Array(t)),this.lyricsTicks=[...A.lyricsTicks],this.midiPorts=[...A.midiPorts],this.trackNames=[...A.trackNames],this.midiPortChannelOffsets=[...A.midiPortChannelOffsets],this.usedChannelsOnTrack=A.usedChannelsOnTrack.map(t=>new Set(t)),this.rawMidiName=A.rawMidiName?new Uint8Array(A.rawMidiName):void 0,this.loop={...A.loop},this.keyRange={...A.keyRange},this.RMIDInfo={...A.RMIDInfo}}};function uA(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}function yn(e){let A=[e&127];for(e>>=7;e>0;)A.unshift(e&127|128),e>>=7;return A}function xr(){let e=this;if(!e.tracks)throw new Error("MIDI has no tracks!");let A=[];for(let s of e.tracks){let o=[],r=0,g;for(let i of s){let E=i.ticks-r,c;i.messageStatusByte<=w.sequenceSpecific?c=[255,i.messageStatusByte,...yn(i.messageData.length),...i.messageData]:i.messageStatusByte===w.systemExclusive?c=[240,...yn(i.messageData.length),...i.messageData]:(c=[],g!==i.messageStatusByte&&(g=i.messageStatusByte,c.push(i.messageStatusByte)),c.push(...i.messageData)),o.push(...yn(E)),o.push(...c),r+=E}A.push(new Uint8Array(o))}function t(s,o){for(let r=0;r<s.length;r++)o.push(s.charCodeAt(r))}let n=[];t("MThd",n),n.push(...Jt(6,4)),n.push(0,e.format),n.push(...Jt(e.tracksAmount,2)),n.push(...Jt(e.timeDivision,2));for(let s of A)t("MTrk",n),n.push(...Jt(s.length,4)),n.push(...s);return new Uint8Array(n)}function dt(e){return e.messageData[0]===67&&e.messageData[2]===76&&e.messageData[5]===126&&e.messageData[6]===0}function Sn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[3]===18&&e.messageData[4]===64&&(e.messageData[5]&16)!==0&&e.messageData[6]===21}function Dn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[6]===127}function kn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===1}function wn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===3}function ds(e){return new YA(e,w.systemExclusive,new x([65,16,66,18,64,0,127,0,65,247]))}function ft(e,A,t,n){return new YA(n,w.controllerChange|e%16,new x([A,t]))}function xi(e,A){let t=16|[1,2,3,4,5,6,7,8,0,9,10,11,12,13,14,15][e%16],n=[65,16,66,18,64,t,21,1],o=128-(64+t+21+1)%128;return new YA(A,w.systemExclusive,new x([...n,o,247]))}function Nr(e=[],A=[],t=[],n=[]){let s=this;fA("%cApplying changes to the MIDI file...",I.info),y("Desired program changes:",e),y("Desired CC changes:",A),y("Desired channels to clear:",t),y("Desired channels to transpose:",n);let o=new Set;e.forEach(M=>{o.add(M.channel)});let r="gs",g=!1,i=Array(s.tracks.length).fill(0),E=s.tracks.length;function c(){let M=0,b=1/0;return s.tracks.forEach((G,C)=>{i[C]>=G.length||G[i[C]].ticks<b&&(M=C,b=G[i[C]].ticks)}),M}let h=s.midiPorts.slice(),Q={},B=0;function m(M,b){s.usedChannelsOnTrack[M].size!==0&&(B===0&&(B+=16,Q[b]=0),Q[b]===void 0&&(Q[b]=B,B+=16),h[M]=b)}s.midiPorts.forEach((M,b)=>{m(b,M)});let u=B,p=Array(u).fill(!0),R=Array(u).fill(0),D=Array(u).fill(0);for(n.forEach(M=>{let b=Math.trunc(M.keyShift),G=M.keyShift-b;R[M.channel]=b,D[M.channel]=G});E>0;){let M=c(),b=s.tracks[M];if(i[M]>=b.length){E--;continue}let G=i[M]++,C=b[G],L=()=>{b.splice(G,1),i[M]--},J=(hA,sA=0)=>{b.splice(G+sA,0,hA),i[M]++},EA=Q[h[M]]||0;if(C.messageStatusByte===w.midiPort){m(M,C.messageData[0]);continue}if(C.messageStatusByte<=w.sequenceSpecific&&C.messageStatusByte>=w.sequenceNumber)continue;let tA=C.messageStatusByte&240,T=C.messageStatusByte&15,AA=T+EA;if(t.indexOf(AA)!==-1){L();continue}switch(tA){case w.noteOn:if(p[AA]){p[AA]=!1,A.filter(CA=>CA.channel===AA).forEach(CA=>{let v=ft(T,CA.controllerNumber,CA.controllerValue,C.ticks);J(v)});let oA=D[AA];if(oA!==0){let CA=oA*64+64,v=ft(T,S.RPNMsb,0,C.ticks),K=ft(T,S.RPNLsb,1,C.ticks),W=ft(AA,S.dataEntryMsb,CA,C.ticks),P=ft(T,S.lsbForControl6DataEntry,0,C.ticks);J(P),J(W),J(K),J(v)}if(o.has(AA)){let CA=e.find(rA=>rA.channel===AA),v=Math.max(0,Math.min(CA.bank,127)),K=CA.program;y(`%cSetting %c${CA.channel}%c to %c${v}:${K}%c. Track num: %c${M}`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized);let W=new YA(C.ticks,w.programChange|T,new x([K]));J(W);let P=(rA,qA)=>{let ge=ft(T,rA?S.lsbForControl0BankSelect:S.bankSelect,qA,C.ticks);J(ge)};kA(r)?CA.isDrum?(y(`%cAdding XG Drum change on track %c${M}`,I.recognized,I.value),P(!1,$A(v)?v:127),P(!0,0)):v===nn?(P(!1,nn),P(!0,0)):(P(!1,0),P(!0,v)):(P(!1,v),CA.isDrum&&T!==9&&(y(`%cAdding GS Drum change on track %c${M}`,I.recognized,I.value),J(xi(T,C.ticks))))}}C.messageData[0]+=R[AA];break;case w.noteOff:C.messageData[0]+=R[AA];break;case w.programChange:if(o.has(AA)){L();continue}break;case w.controllerChange:let hA=C.messageData[0];if(A.find(oA=>oA.channel===AA&&hA===oA.controllerNumber)!==void 0){L();continue}if((hA===S.bankSelect||hA===S.lsbForControl0BankSelect)&&o.has(AA)){L();continue}break;case w.systemExclusive:if(dt(C))y("%cXG system on detected",I.info),r="xg",g=!0;else if(C.messageData[0]===67&&C.messageData[2]===76&&C.messageData[3]===8&&C.messageData[5]===3)o.has(C.messageData[4]+EA)&&L();else if(Dn(C)){g=!0,y("%cGS on detected!",I.recognized);break}else(kn(C)||wn(C))&&(y("%cGM/2 on detected, removing!",I.info),L(),g=!1)}}if(!g&&e.length>0){let M=0;s.tracks[0][0].messageStatusByte===w.trackName&&M++,s.tracks[0].splice(M,0,ds(0)),y("%cGS on not detected. Adding it.",I.info)}this.flush(),q()}function br(e){let A=[],t=[],n=[],s=[];e.channelSnapshots.forEach((o,r)=>{if(o.isMuted){t.push(r);return}let g=o.channelTransposeKeyShift+o.customControllers[cA.channelTransposeFine]/100;g!==0&&A.push({channel:r,keyShift:g}),o.lockPreset&&n.push({channel:r,program:o.program,bank:o.bank,isDrum:o.drumChannel}),o.lockedControllers.forEach((i,E)=>{if(!i||E>127||E===S.bankSelect)return;let c=o.midiControllers[E]>>7;s.push({channel:r,controllerNumber:E,controllerValue:c})})}),this.modifyMIDI(n,s,t,A)}var mA={name:"INAM",album:"IPRD",album2:"IALB",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"},qe="utf-8",Ni="Created using SpessaSynth";function Lr(e,A,t=0,n="Shift_JIS",s={},o=!0){let r=this;if(ie("%cWriting the RMIDI File...",I.info),y(`%cConfiguration: Bank offset: %c${t}%c, encoding: %c${n}`,I.info,I.value,I.info,I.value),y("metadata",s),y("Initial bank offset",r.bankOffset),o){let R=function(){let G=0,C=1/0;return r.tracks.forEach((L,J)=>{u[J]>=L.length||L[u[J]].ticks<C&&(G=J,C=L[u[J]].ticks)}),G},B="gm",m=[],u=Array(r.tracks.length).fill(0),p=r.tracks.length,D=Array(r.tracks.length).fill(0),M=16+r.midiPortChannelOffsets.reduce((G,C)=>C>G?C:G),b=[];for(let G=0;G<M;G++)b.push({program:0,drums:G%16===9,lastBank:void 0,lastBankLSB:void 0,hasBankSelect:!1});for(;p>0;){let G=R(),C=r.tracks[G];if(u[G]>=C.length){p--;continue}let L=C[u[G]];u[G]++;let J=r.midiPortChannelOffsets[D[G]];if(L.messageStatusByte===w.midiPort){D[G]=L.messageData[0];continue}let EA=L.messageStatusByte&240;if(EA!==w.controllerChange&&EA!==w.programChange&&EA!==w.systemExclusive)continue;if(EA===w.systemExclusive){if(!Sn(L)){dt(L)?B="xg":Dn(L)?B="gs":kn(L)?(B="gm",m.push({tNum:G,e:L})):wn(L)&&(B="gm2");continue}let oA=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][L.messageData[5]&15]+J;b[oA].drums=!!(L.messageData[7]>0&&L.messageData[5]>>4);continue}let tA=(L.messageStatusByte&15)+J,T=b[tA];if(EA===w.programChange){let oA=kA(B),CA=L.messageData[0];T.drums?A.presets.findIndex(P=>P.program===CA&&P.isDrumPreset(oA,!0))===-1&&(L.messageData[0]=A.presets.find(P=>P.isDrumPreset(oA))?.program||0,y(`%cNo drum preset %c${CA}%c. Channel %c${tA}%c. Changing program to ${L.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)):A.presets.findIndex(P=>P.program===CA&&!P.isDrumPreset(oA))===-1&&(L.messageData[0]=A.presets.find(P=>!P.isDrumPreset(oA))?.program||0,y(`%cNo preset %c${CA}%c. Channel %c${tA}%c. Changing program to ${L.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)),T.program=L.messageData[0];let v=Math.max(0,T.lastBank?.messageData[1]-r.bankOffset),K=T?.lastBankLSB?.messageData[1]-r.bankOffset||0;if(T.lastBank===void 0)continue;let W=ct(v,K,T.drums,oA);if(A.presets.findIndex(P=>P.bank===W&&P.program===L.messageData[0])===-1){let P=A.presets.find(rA=>rA.program===L.messageData[0])?.bank+t||t;T.lastBank.messageData[1]=P,T?.lastBankLSB?.messageData&&(T.lastBankLSB.messageData[1]=P),y(`%cNo preset %c${W}:${L.messageData[0]}%c. Channel %c${tA}%c. Changing bank to ${P}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)}else{let P=W;kA(B)&&W===128&&(W=127);let rA=(W===128?128:P)+t;T.lastBank.messageData[1]=rA,T?.lastBankLSB?.messageData&&!T.drums&&(T.lastBankLSB.messageData[1]=T.lastBankLSB.messageData[1]-r.bankOffset+t),y(`%cPreset %c${W}:${L.messageData[0]}%c exists. Channel %c${tA}%c. Changing bank to ${rA}.`,I.info,I.recognized,I.info,I.recognized,I.info)}continue}let AA=L.messageData[0]===S.lsbForControl0BankSelect;if(L.messageData[0]!==S.bankSelect&&!AA)continue;T.hasBankSelect=!0;let hA=L.messageData[1],sA=Bt(T?.lastBank?.messageData[1]||0,hA,B,AA,T.drums,tA);sA.drumsStatus===2?T.drums=!0:sA.drumsStatus===1&&(T.drums=!1),AA?T.lastBankLSB=L:T.lastBank=L}if(b.forEach((G,C)=>{if(G.hasBankSelect===!0)return;let L=C%16,J=w.programChange|L,EA=Math.floor(C/16)*16,tA=r.midiPortChannelOffsets.indexOf(EA),T=r.tracks.find((oA,CA)=>r.midiPorts[CA]===tA&&r.usedChannelsOnTrack[CA].has(L));if(T===void 0)return;let AA=T.findIndex(oA=>oA.messageStatusByte===J);if(AA===-1){let oA=T.findIndex(K=>K.messageStatusByte>128&&K.messageStatusByte<240&&(K.messageStatusByte&15)===L);if(oA===-1)return;let CA=T[oA].ticks,v=A.getPreset(0,0).program;T.splice(oA,0,new YA(CA,w.programChange|L,new x([v]))),AA=oA}y(`%cAdding bank select for %c${C}`,I.info,I.recognized);let hA=T[AA].ticks,sA=A.getPreset(0,G.program,kA(B))?.bank+t||t;T.splice(AA,0,new YA(hA,w.controllerChange|L,new x([S.bankSelect,sA])))}),B!=="gs"&&!kA(B)){for(let C of m)r.tracks[C.tNum].splice(r.tracks[C.tNum].indexOf(C.e),1);let G=0;r.tracks[0][0].messageStatusByte===w.trackName&&G++,r.tracks[0].splice(G,0,ds(0))}}let g=new x(r.writeMIDI().buffer),i=[We("INFO")],E=new TextEncoder;if(i.push(_(mA.software,E.encode("SpessaSynth"),!0)),s.name!==void 0?(i.push(_(mA.name,E.encode(s.name),!0)),n=qe):i.push(_(mA.name,r.rawMidiName,!0)),s.creationDate!==void 0)n=qe,i.push(_(mA.creationDate,E.encode(s.creationDate),!0));else{let B=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});i.push(_(mA.creationDate,pe(B),!0))}if(s.comment!==void 0&&(n=qe,i.push(_(mA.comment,E.encode(s.comment)))),s.engineer!==void 0&&i.push(_(mA.engineer,E.encode(s.engineer),!0)),s.album!==void 0&&(n=qe,i.push(_(mA.album,E.encode(s.album),!0)),i.push(_(mA.album2,E.encode(s.album),!0))),s.artist!==void 0&&(n=qe,i.push(_(mA.artist,E.encode(s.artist),!0))),s.genre!==void 0&&(n=qe,i.push(_(mA.genre,E.encode(s.genre),!0))),s.picture!==void 0&&i.push(_(mA.picture,new Uint8Array(s.picture))),s.copyright!==void 0)n=qe,i.push(_(mA.copyright,E.encode(s.copyright),!0));else{let B=r.copyright.length>0?r.copyright:Ni;i.push(_(mA.copyright,pe(B)))}let c=new x(2);Je(c,t,2),i.push(_(mA.bankOffset,c)),s.midiEncoding!==void 0&&(i.push(_(mA.midiEncoding,E.encode(s.midiEncoding))),n=qe),i.push(_(mA.encoding,pe(n)));let h=DA(i),Q=DA([We("RMID"),_("data",g),_("LIST",h),e]);return y("%cFinished!",I.info),q(),_("RIFF",Q)}function Ur(e){let A=this;fA("%cSearching for all used programs and keys...",I.info);let t=16+A.midiPortChannelOffsets.reduce((h,Q)=>Q>h?Q:h),n=[];for(let h=0;h<t;h++){let Q=h%16===9?128:0;n.push({program:0,bank:Q,bankLSB:0,actualBank:Q,drums:h%16===9,string:`${Q}:0`})}let s="gs";function o(h){let Q=ct(h.bank,h.bankLSB,h.drums,kA(s)),B=e.getPreset(Q,h.program,kA(s));h.actualBank=B.bank,h.program=B.program,h.string=h.actualBank+":"+h.program,r[h.string]||(y(`%cDetected a new preset: %c${h.string}`,I.info,I.recognized),r[h.string]=new Set)}let r={},g=Array(A.tracks.length).fill(0),i=A.tracks.length;function E(){let h=0,Q=1/0;return A.tracks.forEach((B,m)=>{g[m]>=B.length||B[g[m]].ticks<Q&&(h=m,Q=B[g[m]].ticks)}),h}let c=A.midiPorts.slice();for(n.forEach(h=>{o(h)});i>0;){let h=E(),Q=A.tracks[h];if(g[h]>=Q.length){i--;continue}let B=Q[g[h]];if(g[h]++,B.messageStatusByte===w.midiPort){c[h]=B.messageData[0];continue}let m=B.messageStatusByte&240;if(m!==w.noteOn&&m!==w.controllerChange&&m!==w.programChange&&m!==w.systemExclusive)continue;let u=(B.messageStatusByte&15)+A.midiPortChannelOffsets[c[h]]||0,p=n[u];switch(m){case w.programChange:p.program=B.messageData[0],o(p);break;case w.controllerChange:let R=B.messageData[0]===S.lsbForControl0BankSelect;if(B.messageData[0]!==S.bankSelect&&!R||s==="gs"&&p.drums)continue;let D=B.messageData[1],M=Math.max(0,D-A.bankOffset);switch(R?p.bankLSB=M:p.bank=M,Bt(p.bank,M,s,R,p.drums,u).drumsStatus){case 0:break;case 1:p.drums=!1,o(p);break;case 2:p.drums=!0,o(p);break}break;case w.noteOn:if(B.messageData[1]===0)continue;r[p.string].add(`${B.messageData[0]}-${B.messageData[1]}`);break;case w.systemExclusive:if(!Sn(B)){dt(B)&&(s="xg",y("%cXG on detected!",I.recognized));continue}let G=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][B.messageData[5]&15]+A.midiPortChannelOffsets[c[h]],C=!!(B.messageData[7]>0&&B.messageData[5]>>4);p=n[G],p.drums=C,o(p);break}}for(let h of Object.keys(r))r[h].size===0&&(y(`%cDetected change but no keys for %c${h}`,I.info,I.value),delete r[h]);return q(),r}function Tr(e=0){function A(h){return h.messageData=new x(h.messageData.buffer),h.messageData.currentIndex=0,6e7/OA(h.messageData,3)}let t=[],s=this.tracks.flat();s.sort((h,Q)=>h.ticks-Q.ticks);for(let h=0;h<16;h++)t.push([]);let o=0,r=60/(120*this.timeDivision),g=0,i=0,E=[];for(let h=0;h<16;h++)E.push([]);let c=(h,Q)=>{let B=E[Q].findIndex(u=>u.midiNote===h),m=E[Q][B];if(m){let u=o-m.start;m.length=u,Q===9&&(m.length=u<e?e:u),E[Q].splice(B,1)}i--};for(;g<s.length;){let h=s[g],Q=h.messageStatusByte>>4,B=h.messageStatusByte&15;if(Q===8)c(h.messageData[0],B);else if(Q===9)if(h.messageData[1]===0)c(h.messageData[0],B);else{c(h.messageData[0],B);let m={midiNote:h.messageData[0],start:o,length:-1,velocity:h.messageData[1]/127};t[B].push(m),E[B].push(m),i++}else h.messageStatusByte===81&&(r=60/(A(h)*this.timeDivision));if(++g>=s.length)break;o+=r*(s[g].ticks-h.ticks)}return i>0&&E.forEach((h,Q)=>{h.forEach(B=>{let m=o-B.start;B.length=m,Q===9&&(B.length=m<e?e:m)})}),t}var XA=class e extends tt{embeddedSoundFont=void 0;tracks=[];isDLSRMIDI=!1;static copyFrom(A){let t=new e;return t._copyFromSequence(A),t.isDLSRMIDI=A.isDLSRMIDI,t.embeddedSoundFont=A.embeddedSoundFont?A.embeddedSoundFont.slice(0):void 0,t.tracks=A.tracks.map(n=>[...n]),t}_parseInternal(){ie("%cInterpreting MIDI events...",I.info);let A=!1;this.keyRange={max:0,min:127};let t=[],n=!1;typeof this.RMIDInfo.ICOP<"u"&&(n=!0);let s=!1;typeof this.RMIDInfo.INAM<"u"&&(s=!0);let o=null,r=null;for(let c=0;c<this.tracks.length;c++){let h=this.tracks[c],Q=new Set,B=!1;for(let u of h){if(u.messageStatusByte>=128&&u.messageStatusByte<240){B=!0;for(let R=0;R<u.messageData.length;R++)u.messageData[R]=Math.min(127,u.messageData[R]);switch(u.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=u.ticks),u.messageStatusByte&240){case w.controllerChange:switch(u.messageData[0]){case 2:case 116:o=u.ticks;break;case 4:case 117:r===null?r=u.ticks:r=0;break;case 0:this.isDLSRMIDI&&u.messageData[1]!==0&&u.messageData[1]!==127&&(y("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}break;case w.noteOn:Q.add(u.messageStatusByte&15);let R=u.messageData[0];this.keyRange.min=Math.min(this.keyRange.min,R),this.keyRange.max=Math.max(this.keyRange.max,R);break}}u.messageData.currentIndex=0;let p=$(u.messageData,u.messageData.length);switch(u.messageData.currentIndex=0,u.messageStatusByte){case w.setTempo:u.messageData.currentIndex=0,this.tempoChanges.push({ticks:u.ticks,tempo:6e7/OA(u.messageData,3)}),u.messageData.currentIndex=0;break;case w.marker:switch(p.trim().toLowerCase()){default:break;case"start":case"loopstart":o=u.ticks;break;case"loopend":r=u.ticks}u.messageData.currentIndex=0;break;case w.copyright:n||(u.messageData.currentIndex=0,t.push($(u.messageData,u.messageData.length,void 0,!1)),u.messageData.currentIndex=0);break;case w.lyric:if(p.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)),this.isKaraokeFile)u.messageStatusByte=w.text;else{this.lyrics.push(u.messageData),this.lyricsTicks.push(u.ticks);break}case w.text:let D=p.trim();D.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)):this.isKaraokeFile&&(D.startsWith("@T")||D.startsWith("@A")?A?t.push(D.substring(2).trim()):(this.midiName=D.substring(2).trim(),A=!0,s=!0,this.rawMidiName=We(this.midiName)):D[0]!=="@"&&(this.lyrics.push(vs(u.messageData)),this.lyricsTicks.push(u.ticks)));break;case w.trackName:break}}this.usedChannelsOnTrack.push(Q),this.trackNames[c]="";let m=h.find(u=>u.messageStatusByte===w.trackName);if(m){m.messageData.currentIndex=0;let u=$(m.messageData,m.messageData.length);this.trackNames[c]=u,B||t.push(u)}}this.tempoChanges.reverse(),y("%cCorrecting loops, ports and detecting notes...",I.info);let g=[];for(let c of this.tracks){let h=c.find(Q=>(Q.messageStatusByte&240)===w.noteOn);h&&g.push(h.ticks)}this.firstNoteOn=Math.min(...g),y(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,I.info,I.recognized,I.info),o!==null&&r===null?(o=this.firstNoteOn,r=this.lastVoiceEventTick):(o===null&&(o=this.firstNoteOn),(r===null||r===0)&&(r=this.lastVoiceEventTick)),this.loop={start:o,end:r},y(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,I.info,I.recognized,I.info,I.recognized);let i=0;this.midiPorts=[],this.midiPortChannelOffsets=[];for(let c=0;c<this.tracks.length;c++)if(this.midiPorts.push(-1),this.usedChannelsOnTrack[c].size!==0)for(let h of this.tracks[c]){if(h.messageStatusByte!==w.midiPort)continue;let Q=h.messageData[0];this.midiPorts[c]=Q,this.midiPortChannelOffsets[Q]===void 0&&(this.midiPortChannelOffsets[Q]=i,i+=16)}let E=1/0;for(let c of this.midiPorts)c!==-1&&E>c&&(E=c);if(E===1/0&&(E=0),this.midiPorts=this.midiPorts.map(c=>c===-1?E:c),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?y("%cNo additional MIDI Ports detected.",I.info):(this.isMultiPort=!0,y("%cMIDI Ports detected!",I.recognized)),!s)if(this.tracks.length>1){if(this.tracks[0].find(c=>c.messageStatusByte>=w.noteOn&&c.messageStatusByte<w.polyPressure)===void 0){let c=this.tracks[0].find(h=>h.messageStatusByte===w.trackName);c&&(this.rawMidiName=c.messageData,c.messageData.currentIndex=0,this.midiName=$(c.messageData,c.messageData.length,void 0,!1))}}else{let c=this.tracks[0].find(h=>h.messageStatusByte===w.trackName);c&&(this.rawMidiName=c.messageData,c.messageData.currentIndex=0,this.midiName=$(c.messageData,c.messageData.length,void 0,!1))}if(n||(this.copyright=t.map(c=>c.trim().replace(/(\r?\n)+/g,`
18
18
  `)).filter(c=>c.length>0).join(`
19
19
  `)||""),this.midiName=this.midiName.trim(),this.midiNameUsesFileName=!1,this.midiName.length===0){y("%cNo name detected. Using the alt name!",I.info),this.midiName=Ts(this.fileName),this.midiNameUsesFileName=!0,this.rawMidiName=new Uint8Array(this.midiName.length);for(let c=0;c<this.midiName.length;c++)this.rawMidiName[c]=this.midiName.charCodeAt(c)}else y(`%cMIDI Name detected! %c"${this.midiName}"`,I.info,I.recognized);this.tracks.some(c=>c[0].ticks===0)||this.tracks[0].unshift(new YA(0,w.trackName,new x(this.rawMidiName.buffer))),this.duration=this.MIDIticksToSeconds(this.lastVoiceEventTick),y("%cSuccess!",I.recognized),q()}flush(){for(let A of this.tracks)A.sort((t,n)=>t.ticks-n.ticks);this._parseInternal()}};XA.prototype.writeMIDI=xr;XA.prototype.modifyMIDI=Nr;XA.prototype.applySnapshotToMIDI=br;XA.prototype.writeRMIDI=Lr;XA.prototype.getUsedProgramsAndKeys=Ur;XA.prototype.getNoteTimes=Tr;function vr(e,A){this.midiData.usedChannelsOnTrack[e].size!==0&&(this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.midiAudioChannels.length<this.midiPortChannelOffset+15&&this._addNewMidiPort(),this.midiPortChannelOffsets[A]=this.midiPortChannelOffset,this.midiPortChannelOffset+=16),this.midiPorts[e]=A)}function Hr(e,A=!0){if(this.stop(),!e.tracks)throw new Error("This MIDI has no tracks!");if(this.oneTickToSeconds=60/(120*e.timeDivision),this.midiData=e,this.midiData.embeddedSoundFont!==void 0)y("%cEmbedded soundfont detected! Using it.",I.recognized),this.synth.setEmbeddedSoundFont(this.midiData.embeddedSoundFont,this.midiData.bankOffset);else{this.synth.overrideSoundfont&&this.synth.clearSoundFont(!0,!0),fA("%cPreloading samples...",I.info);let t=this.midiData.getUsedProgramsAndKeys(this.synth.soundfontManager);for(let[n,s]of Object.entries(t)){let o=parseInt(n.split(":")[0]),r=parseInt(n.split(":")[1]),g=this.synth.getPreset(o,r);y(`%cPreloading used samples on %c${g.presetName}%c...`,I.info,I.recognized,I.info);for(let i of s){let E=i.split("-");g.preloadSpecific(parseInt(E[0]),parseInt(E[1]))}}q()}if(this.tracks=this.midiData.tracks,this.midiPorts=this.midiData.midiPorts.slice(),this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this.midiData.midiPorts.forEach((t,n)=>{this.assignMIDIPort(n,t)}),this.duration=this.midiData.duration,this.firstNoteTime=this.midiData.MIDIticksToSeconds(this.midiData.firstNoteOn),y(`%cTotal song time: ${Pn(Math.ceil(this.duration)).time}`,I.recognized),this?.onSongChange?.(this.songIndex,A),this.duration<=1&&(H(`%cVery short song: (${Pn(Math.round(this.duration)).time}). Disabling loop!`,I.warn),this.loop=!1),A)this.play(!0);else{let t=this.skipToFirstNoteOn?this.midiData.firstNoteOn-1:0;this.setTimeTicks(t),this.pause()}}function Yr(e,A=!0){this.songs=e.map(t=>XA.copyFrom(t)),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.shuffleSongIndexes(),this?.onSongListChange?.(this.songs),this.loadCurrentSong(A))}function Jr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadCurrentSong()}function Kr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadCurrentSong()}var nt=He.slice(0,128);function Or(e,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let t=this.synth.midiAudioChannels.length,n=Array(t).fill(8192),s=[];for(let i=0;i<t;i++)s.push({program:-1,bank:0,actualBank:0});let o=i=>i===S.dataDecrement||i===S.dataIncrement||i===S.dataEntryMsb||i===S.dataDecrement||i===S.lsbForControl6DataEntry||i===S.RPNLsb||i===S.RPNMsb||i===S.NRPNLsb||i===S.NRPNMsb||i===S.bankSelect||i===S.lsbForControl0BankSelect||i===S.resetAllControllers,r=[];for(let i=0;i<t;i++)r.push(Array.from(nt));function g(i){if(n[i]=8192,r?.[i]!==void 0)for(let E=0;E<nt.length;E++)ns.has(E)||(r[i][E]=nt[E])}for(;;){let i=this._findFirstEventIndex(),E=this.tracks[i][this.eventIndex[i]];if(A!==void 0){if(E.ticks>=A)break}else if(this.playedTime>=e)break;let c=ht(E.messageStatusByte),h=c.channel+(this.midiPortChannelOffsets[this.midiPorts[i]]||0);switch(c.status){case w.noteOn:r[h]===void 0&&(r[h]=Array.from(nt)),r[h][S.portamentoControl]=E.messageData[0];break;case w.noteOff:break;case w.pitchBend:n[h]=E.messageData[1]<<7|E.messageData[0];break;case w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let B=s[h];B.program=E.messageData[0],B.actualBank=B.bank;break;case w.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let m=E.messageData[0];if(o(m)){let u=E.messageData[1];if(m===S.bankSelect){s[h].bank=u;break}else m===S.resetAllControllers&&g(h);this.sendMIDIMessages?this.sendMIDICC(h,m,u):this.synth.controllerChange(h,m,u)}else r[h]===void 0&&(r[h]=Array.from(nt)),r[h][m]=E.messageData[1];break;default:this._processEvent(E,i);break}this.eventIndex[i]++,i=this._findFirstEventIndex();let Q=this.tracks[i][this.eventIndex[i]];if(Q===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(Q.ticks-E.ticks)}if(this.sendMIDIMessages){for(let i=0;i<t;i++)if(n[i]!==void 0&&this.sendMIDIPitchWheel(i,n[i]>>7,n[i]&127),r[i]!==void 0&&r[i].forEach((E,c)=>{E!==nt[c]&&!o(c)&&this.sendMIDICC(i,c,E)}),s[i].program>=0&&s[i].actualBank>=0){let E=s[i].actualBank;this.sendMIDICC(i,S.bankSelect,E),this.sendMIDIProgramChange(i,s[i].program)}}else for(let i=0;i<t;i++)if(n[i]!==void 0&&this.synth.pitchWheel(i,n[i]>>7,n[i]&127),r[i]!==void 0&&r[i].forEach((E,c)=>{E!==nt[c]&&!o(c)&&this.synth.controllerChange(i,c,E)}),s[i].program>=0&&s[i].actualBank>=0){let E=s[i].actualBank;this.synth.controllerChange(i,S.bankSelect,E),this.synth.programChange(i,s[i].program)}return!0}function qr(e=!1){if(this.midiData!==void 0){if(e){this.pausedTime=void 0,this.currentTime=0;return}if(this.currentTime>=this.duration){this.pausedTime=void 0,this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity)}),this.setProcessHandler()}}function Pr(e){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this?.onTimeChange?.(this.midiData.MIDIticksToSeconds(e));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function Vr(e){this.absoluteStartTime=this.synth.currentSynthTime-e/this._playbackRate}function Zr(e){this.sendMIDIMessages&&this?.onMIDIMessage?.(e)}function Xr(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.controllerChange|e,A,t])}function Wr(e,A){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.programChange|e,A])}function zr(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.pitchBend|e,t,A])}function _r(){if(this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let e=0;e<16;e++)this.sendMIDIMessage([w.controllerChange|e,S.allSoundOff,0]),this.sendMIDIMessage([w.controllerChange|e,S.resetAllControllers,0])}}var wA=class{songs=[];songIndex=0;shuffledSongIndexes=[];synth;isActive=!1;sendMIDIMessages=!1;loopCount=1/0;eventIndex=[];playedTime=0;pausedTime=void 0;absoluteStartTime=0;playingNotes=[];loop=!0;shuffleMode=!1;midiData=void 0;midiPorts=[];midiPortChannelOffset=0;midiPortChannelOffsets={};skipToFirstNoteOn=!0;preservePlaybackState=!1;onMIDIMessage;onTimeChange;onPlaybackStop;onSongListChange;onSongChange;onMetaEvent;onLoopCountChange;constructor(A){this.synth=A,this.absoluteStartTime=this.synth.currentSynthTime}_playbackRate=1;set playbackRate(A){let t=this.currentTime;this._playbackRate=A,this.currentTime=t}get currentTime(){return this.pausedTime!==void 0?this.pausedTime:(this.synth.currentSynthTime-this.absoluteStartTime)*this._playbackRate}set currentTime(A){if(A>this.duration||A<0){this.skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this.skipToFirstNoteOn&&A<this.firstNoteTime){this.setTimeTicks(this.midiData.firstNoteOn-1);return}this.stop(),this.playingNotes=[];let t=this.paused&&this.preservePlaybackState;if(this.pausedTime=void 0,this?.onTimeChange?.(A),this.midiData.duration===0){H("No duration!"),this?.onPlaybackStop?.(!0);return}this._playTo(A),this._recalculateStartTime(A),t?this.pause():this.play()}get paused(){return this.pausedTime!==void 0}pause(A=!1){if(this.paused){H("Already paused");return}this.pausedTime=this.currentTime,this.stop(),this?.onPlaybackStop?.(A)}stop(){this.clearProcessHandler();for(let A=0;A<16;A++)this.synth.controllerChange(A,S.sustainPedal,0);if(this.synth.stopAllChannels(),this.sendMIDIMessages){for(let A of this.playingNotes)this.sendMIDIMessage([w.noteOff|A.channel%16,A.midiNote]);for(let A=0;A<16;A++)this.sendMIDICC(A,S.allNotesOff,0)}}loadCurrentSong(A=!0){let t=this.songIndex;this.shuffleMode&&(t=this.shuffledSongIndexes[this.songIndex]),this.loadNewSequence(this.songs[t],A)}_resetTimers(){this.playedTime=0,this.eventIndex=Array(this.tracks.length).fill(0)}setProcessHandler(){this.isActive=!0}clearProcessHandler(){this.isActive=!1}shuffleSongIndexes(){let A=this.songs.map((t,n)=>n);for(this.shuffledSongIndexes=[];A.length>0;){let t=A[Math.floor(Math.random()*A.length)];this.shuffledSongIndexes.push(t),A.splice(A.indexOf(t),1)}}};wA.prototype.sendMIDIMessage=Zr;wA.prototype.sendMIDIReset=_r;wA.prototype.sendMIDICC=Xr;wA.prototype.sendMIDIProgramChange=Wr;wA.prototype.sendMIDIPitchWheel=zr;wA.prototype.assignMIDIPort=vr;wA.prototype._processEvent=Fr;wA.prototype._addNewMidiPort=Rr;wA.prototype.processTick=Gr;wA.prototype._findFirstEventIndex=Mr;wA.prototype.loadNewSequence=Hr;wA.prototype.loadNewSongList=Yr;wA.prototype.nextSong=Jr;wA.prototype.previousSong=Kr;wA.prototype.play=qr;wA.prototype._playTo=Or;wA.prototype.setTimeTicks=Pr;wA.prototype._recalculateStartTime=Vr;var Kt;(()=>{var e=Uint8Array,A=Uint16Array,t=Int32Array,n=new e([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),s=new e([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(v,K){for(var W=new A(31),P=0;P<31;++P)W[P]=K+=1<<v[P-1];for(var rA=new t(W[30]),P=1;P<30;++P)for(var qA=W[P];qA<W[P+1];++qA)rA[qA]=qA-W[P]<<5|P;return{b:W,r:rA}},g=r(n,2),i=g.b,E=g.r;i[28]=258,E[258]=28;var c=r(s,0),h=c.b,Q=c.r,B=new A(32768);for(D=0;D<32768;++D)m=(D&43690)>>1|(D&21845)<<1,m=(m&52428)>>2|(m&13107)<<2,m=(m&61680)>>4|(m&3855)<<4,B[D]=((m&65280)>>8|(m&255)<<8)>>1;var m,D,u=function(v,K,W){for(var P=v.length,rA=0,qA=new A(K);rA<P;++rA)v[rA]&&++qA[v[rA]-1];var ge=new A(K);for(rA=1;rA<K;++rA)ge[rA]=ge[rA-1]+qA[rA-1]<<1;var le;if(W){le=new A(1<<K);var Qe=15-K;for(rA=0;rA<P;++rA)if(v[rA])for(var ot=rA<<4|v[rA],ye=K-v[rA],aA=ge[v[rA]-1]++<<ye,lA=aA|(1<<ye)-1;aA<=lA;++aA)le[B[aA]>>Qe]=ot}else for(le=new A(P),rA=0;rA<P;++rA)v[rA]&&(le[rA]=B[ge[v[rA]-1]++]>>15-v[rA]);return le},p=new e(288);for(D=0;D<144;++D)p[D]=8;var D;for(D=144;D<256;++D)p[D]=9;var D;for(D=256;D<280;++D)p[D]=7;var D;for(D=280;D<288;++D)p[D]=8;var D,R=new e(32);for(D=0;D<32;++D)R[D]=5;var D,M=u(p,9,1),b=u(R,5,1),G=function(v){for(var K=v[0],W=1;W<v.length;++W)v[W]>K&&(K=v[W]);return K},C=function(v,K,W){var P=K/8|0;return(v[P]|v[P+1]<<8)>>(K&7)&W},L=function(v,K){var W=K/8|0;return(v[W]|v[W+1]<<8|v[W+2]<<16)>>(K&7)},J=function(v){return(v+7)/8|0},EA=function(v,K,W){return(K==null||K<0)&&(K=0),(W==null||W>v.length)&&(W=v.length),new e(v.subarray(K,W))},tA=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],T=function(v,K,W){var P=new Error(K||tA[v]);if(P.code=v,Error.captureStackTrace&&Error.captureStackTrace(P,T),!W)throw P;return P},AA=function(v,K,W,P){var rA=v.length,qA=P?P.length:0;if(!rA||K.f&&!K.l)return W||new e(0);var ge=!W,le=ge||K.i!=2,Qe=K.i;ge&&(W=new e(rA*3));var ot=function(Wt){var ve=W.length;if(Wt>ve){var Ft=new e(Math.max(ve*2,Wt));Ft.set(W),W=Ft}},ye=K.f||0,aA=K.p||0,lA=K.b||0,de=K.l,WA=K.d,Le=K.m,Ue=K.n,yt=rA*8;do{if(!de){ye=C(v,aA,1);var rt=C(v,aA+1,3);if(aA+=3,rt)if(rt==1)de=M,WA=b,Le=9,Ue=5;else if(rt==2){var St=C(v,aA,31)+257,Mn=C(v,aA+10,15)+4,xn=St+C(v,aA+5,31)+1;aA+=14;for(var it=new e(xn),Te=new e(19),zA=0;zA<Mn;++zA)Te[o[zA]]=C(v,aA+zA*3,7);aA+=Mn*3;for(var Nn=G(Te),Pt=(1<<Nn)-1,at=u(Te,Nn,1),zA=0;zA<xn;){var Dt=at[C(v,aA,Pt)];aA+=Dt&15;var PA=Dt>>4;if(PA<16)it[zA++]=PA;else{var Se=0,kt=0;for(PA==16?(kt=3+C(v,aA,3),aA+=2,Se=it[zA-1]):PA==17?(kt=3+C(v,aA,7),aA+=3):PA==18&&(kt=11+C(v,aA,127),aA+=7);kt--;)it[zA++]=Se}}var bn=it.subarray(0,St),De=it.subarray(St);Le=G(bn),Ue=G(De),de=u(bn,Le,1),WA=u(De,Ue,1)}else T(1);else{var PA=J(aA)+4,Vt=v[PA-4]|v[PA-3]<<8,Zt=PA+Vt;if(Zt>rA){Qe&&T(0);break}le&&ot(lA+Vt),W.set(v.subarray(PA,Zt),lA),K.b=lA+=Vt,K.p=aA=Zt*8,K.f=ye;continue}if(aA>yt){Qe&&T(0);break}}le&&ot(lA+131072);for(var Ss=(1<<Le)-1,Ds=(1<<Ue)-1,Xt=aA;;Xt=aA){var Se=de[L(v,aA)&Ss],Pe=Se>>4;if(aA+=Se&15,aA>yt){Qe&&T(0);break}if(Se||T(2),Pe<256)W[lA++]=Pe;else if(Pe==256){Xt=aA,de=null;break}else{var Ln=Pe-254;if(Pe>264){var zA=Pe-257,ke=n[zA];Ln=C(v,aA,(1<<ke)-1)+i[zA],aA+=ke}var It=WA[L(v,aA)&Ds],Ve=It>>4;It||T(3),aA+=It&15;var De=h[Ve];if(Ve>3){var ke=s[Ve];De+=L(v,aA)&(1<<ke)-1,aA+=ke}if(aA>yt){Qe&&T(0);break}le&&ot(lA+131072);var wt=lA+Ln;if(lA<De){var gt=qA-De,xA=Math.min(De,wt);for(gt+lA<0&&T(3);lA<xA;++lA)W[lA]=P[gt+lA]}for(;lA<wt;++lA)W[lA]=W[lA-De]}}K.l=de,K.p=Xt,K.b=lA,K.f=ye,de&&(ye=1,K.m=Le,K.d=WA,K.n=Ue)}while(!ye);return lA!=W.length&&ge?EA(W,0,lA):W.subarray(0,lA)},hA=new e(0);function sA(v,K){return AA(v,{i:2},K&&K.out,K&&K.dictionary)}var oA=typeof TextDecoder<"u"&&new TextDecoder,CA=0;try{oA.decode(hA,{stream:!0}),CA=1}catch{}Kt=sA})();var fs={XMFFileType:0,nodeName:1,nodeIDNumber:2,resourceFormat:3,filenameOnDisk:4,filenameExtensionOnDisk:5,macOSFileTypeAndCreator:6,mimeType:7,title:8,copyrightNotice:9,comment:10,autoStart:11,preload:12,contentDescription:13,ID3Metadata:14},mt={inLineResource:1,inFileResource:2,inFileNode:3,externalFile:4,externalXMF:5,XMFFileURIandNodeID:6},us={StandardMIDIFile:0,StandardMIDIFileType1:1,DLS1:2,DLS2:3,DLS22:4,mobileDLS:5},bi={standard:0,MMA:1,registered:2,nonRegistered:3},Fn={none:0,MMAUnpacker:1,registered:2,nonRegistered:3},ms=class e{length;itemCount;metadataLength;metadata={};nodeData;innerNodes=[];packedContent=!1;nodeUnpackers=[];resourceFormat="unknown";constructor(A){let t=A.currentIndex;this.length=uA(A),this.itemCount=uA(A);let n=uA(A),s=A.currentIndex-t,o=n-s,r=A.slice(A.currentIndex,A.currentIndex+o);A.currentIndex+=o,this.metadataLength=uA(r);let g=r.slice(r.currentIndex,r.currentIndex+this.metadataLength);r.currentIndex+=this.metadataLength;let i,E;for(;g.currentIndex<g.length;){if(g[g.currentIndex]===0)g.currentIndex++,i=uA(g),Object.values(fs).indexOf(i)===-1?(H(`Unknown field specifier: ${i}`),E=`unknown_${i}`):E=Object.keys(fs).find(u=>fs[u]===i);else{let u=uA(g);i=$(g,u),E=i}let m=uA(g);if(m===0){let u=uA(g),p=g.slice(g.currentIndex,g.currentIndex+u);g.currentIndex+=u,uA(p)<4?this.metadata[E]=$(p,u-1):this.metadata[E]=p.slice(p.currentIndex)}else H(`International content: ${m}`),g.currentIndex+=uA(g)}let c=r.currentIndex,h=uA(r),Q=r.slice(r.currentIndex,c+h);if(r.currentIndex=c+h,h>0)for(this.packedContent=!0;Q.currentIndex<h;){let B={};switch(B.id=uA(Q),B.id){case Fn.nonRegistered:case Fn.registered:throw q(),new Error(`Unsupported unpacker ID: ${B.id}`);default:throw q(),new Error(`Unknown unpacker ID: ${B.id}`);case Fn.none:B.standardID=uA(Q);break;case Fn.MMAUnpacker:let m=Q[Q.currentIndex++];m===0&&(m<<=8,m|=Q[Q.currentIndex++],m<<=8,m|=Q[Q.currentIndex++]);let u=uA(Q);B.manufacturerID=m,B.manufacturerInternalID=u;break}B.decodedSize=uA(Q),this.nodeUnpackers.push(B)}switch(A.currentIndex=t+n,this.referenceTypeID=uA(A),this.nodeData=A.slice(A.currentIndex,t+this.length),A.currentIndex=t+this.length,this.referenceTypeID){case mt.inLineResource:break;case mt.externalXMF:case mt.inFileNode:case mt.XMFFileURIandNodeID:case mt.externalFile:case mt.inFileResource:throw q(),new Error(`Unsupported reference type: ${this.referenceTypeID}`);default:throw q(),new Error(`Unknown reference type: ${this.referenceTypeID}`)}if(this.isFile){if(this.packedContent){let m=this.nodeData.slice(2,this.nodeData.length);y(`%cPacked content. Attemting to deflate. Target size: %c${this.nodeUnpackers[0].decodedSize}`,I.warn,I.value);try{this.nodeData=new x(Kt(m).buffer)}catch(u){throw q(),new Error(`Error unpacking XMF file contents: ${u.message}.`)}}let B=this.metadata.resourceFormat;if(B===void 0)H("No resource format for this file node!");else{B[0]!==bi.standard&&(H(`Non-standard formatTypeID: ${B}`),this.resourceFormat=B.toString());let u=B[1];Object.values(us).indexOf(u)===-1?H(`Unrecognized resource format: ${u}`):this.resourceFormat=Object.keys(us).find(p=>us[p]===u)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex<this.nodeData.length;){let B=this.nodeData.currentIndex,m=uA(this.nodeData),u=this.nodeData.slice(B,B+m);this.nodeData.currentIndex=B+m,this.innerNodes.push(new e(u))}}get isFile(){return this.itemCount===0}};function jr(e,A){e.bankOffset=0;let t=$(A,4);if(t!=="XMF_")throw q(),new SyntaxError(`Invalid XMF Header! Expected "_XMF", got "${t}"`);ie("%cParsing XMF file...",I.info);let n=$(A,4);if(y(`%cXMF version: %c${n}`,I.info,I.recognized),n==="2.00"){let i=OA(A,4),E=OA(A,4);y(`%cFile Type ID: %c${i}%c, File Type Revision ID: %c${E}`,I.info,I.recognized,I.info,I.recognized)}uA(A);let s=uA(A);A.currentIndex+=s,A.currentIndex=uA(A);let o=new ms(A),r,g=i=>{let E=(c,h)=>{i.metadata[c]!==void 0&&typeof i.metadata[c]=="string"&&(e.RMIDInfo[h]=i.metadata[c])};if(E("nodeName",mA.name),E("title",mA.name),E("copyrightNotice",mA.copyright),E("comment",mA.comment),i.isFile)switch(i.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":y("%cFound embedded DLS!",I.recognized),e.embeddedSoundFont=i.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":y("%cFound embedded MIDI!",I.recognized),r=i.nodeData;break}else for(let c of i.innerNodes)g(c)};return g(o),q(),r}var Ot=class extends XA{constructor(A,t=""){super(),fA("%cParsing MIDI File...",I.info),this.fileName=t;let n=new x(A),s,o=$(n,4);if(n.currentIndex-=4,o==="RIFF"){n.currentIndex+=8;let g=$(n,4,void 0,!1);if(g!=="RMID")throw q(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${g}"`);let i=IA(n);if(i.header!=="data")throw q(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${g}"`);for(s=i.chunkData;n.currentIndex<=n.length;){let E=n.currentIndex,c=IA(n,!0);if(c.header==="RIFF"){let h=$(c.chunkData,4).toLowerCase();h==="sfbk"||h==="sfpk"||h==="dls "?(y("%cFound embedded soundfont!",I.recognized),this.embeddedSoundFont=n.slice(E,E+c.size).buffer):H(`Unknown RIFF chunk: "${h}"`),h==="dls "&&(this.isDLSRMIDI=!0)}else if(c.header==="LIST"&&$(c.chunkData,4)==="INFO"){for(y("%cFound RMIDI INFO chunk!",I.recognized),this.RMIDInfo={};c.chunkData.currentIndex<=c.size;){let Q=IA(c.chunkData,!0);this.RMIDInfo[Q.header]=Q.chunkData}this.RMIDInfo.ICOP&&(this.copyright=$(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length,void 0,!1).replaceAll(`
20
20
  `," ")),this.RMIDInfo.INAM&&(this.rawMidiName=this.RMIDInfo[mA.name],this.midiName=$(this.rawMidiName,this.rawMidiName.length,void 0,!1).replaceAll(`
package/build.sh DELETED
@@ -1,8 +0,0 @@
1
- #!/bin/bash
2
- cd "$(dirname "$0")" || exit
3
-
4
- chmod +x examples/build_examples.sh
5
- ./examples/build_examples.sh
6
-
7
- esbuild synthetizer/worklet_processor.js --bundle --tree-shaking=true --minify --sourcemap=linked --format=esm --outfile=synthetizer/worklet_processor.min.js --platform=browser
8
- echo "Processor minified successfully"
package/debug_disable.sh DELETED
@@ -1,5 +0,0 @@
1
- npm uninstall spessasynth_core
2
- npm install spessasynth_core
3
- npm pkg set dependencies.spessasynth_core=latest
4
- npm update
5
- npm run build
package/debug_enable.sh DELETED
@@ -1,3 +0,0 @@
1
- npm uninstall spessasynth_core
2
- npm install ../spessasynth_core
3
- npm run build
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes