spessasynth_lib 3.26.6 → 3.26.8

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 +4 -2
  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 +4 -4
  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,12 +1,14 @@
1
1
  {
2
2
  "name": "spessasynth_lib",
3
- "version": "3.26.6",
3
+ "version": "3.26.8",
4
4
  "description": "MIDI and SoundFont2/DLS library for the browsers with no compromises",
5
5
  "browser": "index.js",
6
6
  "type": "module",
7
7
  "scripts": {
8
8
  "test": "echo \"Error: no test specified\" && exit 1",
9
- "build": "./build.sh"
9
+ "build": "build_scripts/build.sh",
10
+ "debug": "build_scripts/debug_enable.sh",
11
+ "release": "build_scripts/debug_disable.sh"
10
12
  },
11
13
  "repository": {
12
14
  "type": "git",
@@ -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
@@ -8,15 +8,15 @@ var bs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(
8
8
 
9
9
 
10
10
  `}sumTransform(A){return new e(this.sourceEnum,this.secondarySourceEnum,this.modulatorDestination,this.transformAmount+A.transformAmount,this.transformType)}},jn=960,$n=GA.concave;function Ie(e,A,t,n,s){return e<<10|A<<9|t<<8|n<<7|s}var ci=[new z(Ie($n,0,1,0,j.noteOnVelocity),0,a.initialAttenuation,jn,0),new z(129,0,a.vibLfoToPitch,50,0),new z(Ie($n,0,1,1,S.mainVolume),0,a.initialAttenuation,jn,0),new z(13,0,a.vibLfoToPitch,50,0),new z(526,16,a.fineTune,12700,0),new z(650,0,a.pan,500,0),new z(Ie($n,0,1,1,S.expressionController),0,a.initialAttenuation,jn,0),new z(219,0,a.reverbEffectsSend,200,0),new z(221,0,a.chorusEffectsSend,200,0)],li=[new z(Ie(GA.linear,0,0,0,j.polyPressure),0,a.vibLfoToPitch,50,0),new z(Ie(GA.linear,0,0,1,S.tremoloDepth),0,a.modLfoToVolume,24,0),new z(Ie(GA.convex,1,0,1,S.attackTime),0,a.attackVolEnv,6e3,0),new z(Ie(GA.linear,1,0,1,S.releaseTime),0,a.releaseVolEnv,3600,0),new z(Ie(GA.linear,1,0,1,S.brightness),0,a.initialFilterFc,6e3,0),new z(Ie(GA.linear,1,0,1,S.filterResonance),0,a.initialFilterQ,250,0)],js=ci.concat(li);var RA=128,sn=147,He=new Int16Array(sn).fill(0),MA=(e,A)=>He[e]=A<<7;MA(S.mainVolume,100);MA(S.balance,64);MA(S.expressionController,127);MA(S.pan,64);MA(S.portamentoOnOff,127);MA(S.filterResonance,64);MA(S.releaseTime,64);MA(S.attackTime,64);MA(S.brightness,64);MA(S.decayTime,64);MA(S.vibratoRate,64);MA(S.vibratoDepth,64);MA(S.vibratoDelay,64);MA(S.generalPurposeController6,64);MA(S.generalPurposeController8,64);MA(S.RPNLsb,127);MA(S.RPNMsb,127);MA(S.NRPNLsb,127);MA(S.NRPNMsb,127);var on=1;He[S.portamentoControl]=on;MA(RA+j.pitchWheel,64);MA(RA+j.pitchWheelRange,2);var cA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},As=Object.keys(cA).length,es=new Float32Array(As);es[cA.modulationMultiplier]=1;var HA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},ts={velocityOverride:128};function $s(e=!0){e&&y("%cResetting all controllers!",I.info),this.callEvent("allcontrollerreset",void 0),this.setSystem(Nt);for(let A=0;A<this.midiAudioChannels.length;A++){this.midiAudioChannels[A].resetControllers();let t=this.midiAudioChannels[A];t.lockPreset?this.callEvent("drumchange",{channel:A,isDrumChannel:t.drumChannel}):(t.setBankSelect(Xs(this.system)),A%16===9?(t.setPreset(this.drumPreset),t.presetUsesOverride=this.defaultDrumsUsesOverride,t.drumChannel=!0,this.callEvent("drumchange",{channel:A,isDrumChannel:!0})):(t.drumChannel=!1,t.presetUsesOverride=this.defaultDrumsUsesOverride,t.setPreset(this.defaultPreset),this.callEvent("drumchange",{channel:A,isDrumChannel:!1})));let n=t.preset.bank,s=n===128?128:t.presetUsesOverride?n+this.soundfontBankOffset:n;this.callEvent("programchange",{channel:A,program:t.preset.program,bank:s});for(let o=0;o<128;o++)this.midiAudioChannels[A].lockedControllers[o]&&this.callEvent("controllerchange",{channel:A,controllerNumber:o,controllerValue:this.midiAudioChannels[A].midiControllers[o]>>7});if(this.midiAudioChannels[A].lockedControllers[RA+j.pitchWheel]===!1){let o=this.midiAudioChannels[A].midiControllers[RA+j.pitchWheel],r=o>>7,g=o&127;this.callEvent("pitchwheel",{channel:A,MSB:r,LSB:g})}}this.tunings=[],this.tunings=[];for(let A=0;A<128;A++)this.tunings.push([]);this.setMIDIVolume(1)}function Ao(){this.channelOctaveTuning.fill(0);for(let A=0;A<He.length;A++){if(this.lockedControllers[A])continue;let t=He[A];this.midiControllers[A]!==t&&A<127?A===S.portamentoControl?this.midiControllers[A]=on:this.controllerChange(A,t>>7):this.midiControllers[A]=t}this.channelVibrato={rate:0,depth:0,delay:0},this.holdPedal=!1,this.randomPan=!1;let e=this.customControllers[cA.channelTransposeFine];this.customControllers.set(es),this.setCustomController(cA.channelTransposeFine,e),this.resetParameters()}var ns=new Set([S.bankSelect,S.lsbForControl0BankSelect,S.mainVolume,S.lsbForControl7MainVolume,S.pan,S.lsbForControl10Pan,S.reverbDepth,S.tremoloDepth,S.chorusDepth,S.detuneDepth,S.phaserDepth,S.soundVariation,S.filterResonance,S.releaseTime,S.attackTime,S.brightness,S.decayTime,S.vibratoRate,S.vibratoDepth,S.vibratoDelay,S.soundController10]);function eo(){this.channelOctaveTuning.fill(0),this.pitchWheel(64,0),this.channelVibrato={rate:0,depth:0,delay:0};for(let e=0;e<128;e++){let A=He[e];!ns.has(e)&&A!==this.midiControllers[e]&&(e===S.portamentoControl?this.midiControllers[e]=on:this.controllerChange(e,A>>7))}}function to(){this.dataEntryState=HA.Idle,y("%cResetting Registered and Non-Registered Parameters!",I.info)}var rn=class{soundfontList=[];presetList=[];constructor(A){this.presetListChangeCallback=A}generatePresetList(){let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let n=this.soundfontList[t],s=new Set;for(let o of n.soundfont.presets){let r=`${o.bank+n.bankOffset}-${o.program}`;s.has(r)||(s.add(r),A[r]=o.presetName)}}this.presetList=[];for(let[t,n]of Object.entries(A)){let s=t.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}this.presetListChangeCallback()}getPresetList(){return this.presetList.slice()}reloadManager(A){this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:A}),this.generatePresetList()}deleteSoundFont(A){if(this.soundfontList.length===0){H("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(n=>n.id===A);if(t===-1){H(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,n){if(this.soundfontList.find(s=>s.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:A,bankOffset:n}),this.generatePresetList()}rearrangeSoundFonts(A){this.soundfontList.sort((t,n)=>A.indexOf(t.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,t,n=!1){if(this.soundfontList.length<1)throw new Error("No soundfonts! Did you forget to add one?");for(let o of this.soundfontList){let r=o.soundfont.getPresetNoFallback(A-o.bankOffset,t,n);if(r!==void 0)return r}if(A===128||n&&$A(A)){for(let o of this.soundfontList){let r=o.soundfont.presets.find(i=>i.isDrumPreset(n)&&i.program===t);if(r)return r;let g=o.soundfont.presets.find(i=>i.isDrumPreset(n));if(g)return g}return this.soundfontList[0].soundfont.presets[0]}else{for(let o of this.soundfontList){let r=o.soundfont.presets.find(g=>g.program===t&&!g.isDrumPreset(n));if(r)return r}return this.soundfontList[0].soundfont.presets[0]}}destroyManager(){this.soundfontList.forEach(A=>{A.soundfont.destroySoundBank()}),delete this.soundfontList}};var an=class{_keyMappings=[];addMapping(A,t,n){this._keyMappings[A]===void 0&&(this._keyMappings[A]=[]),this._keyMappings[A][t]=n}deleteMapping(A,t){this._keyMappings[A]?.[t]!==void 0&&(this._keyMappings[A][t]=void 0)}clearMappings(){this._keyMappings=[]}setMappings(A){this._keyMappings=A}getMappings(){return this._keyMappings}getVelocity(A,t){return this._keyMappings[A]?.[t]?.velocity??-1}getGain(A,t){return this._keyMappings[A]?.[t]?.gain??1}hasOverridePatch(A,t){let n=this._keyMappings[A]?.[t]?.patch?.bank;return n!==void 0&&n>=0}getPatch(A,t){let n=this._keyMappings[A]?.[t];if(n)return n.patch;throw new Error("No modifier.")}};var no=.1,Ye=class e{static cachedCoefficients=[];a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;resonanceCb=0;currentInitialFc=13500;lastTargetCutoff=1/0;initialized=!1;sampleRate;constructor(A){this.sampleRate=A,this.maxCutoff=A*.45}static apply(A,t,n,s){let o=A.modulatedGenerators[a.initialFilterFc],r=A.filter;r.initialized?r.currentInitialFc+=(o-r.currentInitialFc)*s:(r.initialized=!0,r.currentInitialFc=o);let g=r.currentInitialFc+n,i=A.modulatedGenerators[a.initialFilterQ];if(r.currentInitialFc>13499&&g>13499&&i===0){r.currentInitialFc=13500;return}(Math.abs(r.lastTargetCutoff-g)>1||r.resonanceCb!==i)&&(r.lastTargetCutoff=g,r.resonanceCb=i,e.calculateCoefficients(r,g));for(let E=0;E<t.length;E++){let c=t[E],h=r.a0*c+r.a1*r.x1+r.a2*r.x2-r.a3*r.y1-r.a4*r.y2;r.x2=r.x1,r.x1=c,r.y2=r.y1,r.y1=h,t[E]=h}}static calculateCoefficients(A,t){t=~~t;let n=A.resonanceCb,s=e.cachedCoefficients?.[n]?.[t];if(s!==void 0){A.a0=s.a0,A.a1=s.a1,A.a2=s.a2,A.a3=s.a3,A.a4=s.a4;return}let o=bt(t);o=Math.min(o,A.maxCutoff);let r=n/10,g=ae(-(r-3.01)),i=1/Math.sqrt(ae(-r)),E=2*Math.PI*o/A.sampleRate,c=Math.cos(E),h=Math.sin(E)/(2*g),Q=(1-c)*i,B=Q/2,m=B,u=1+h,p=-2*c,R=1-h,D={};D.a0=B/u,D.a1=Q/u,D.a2=m/u,D.a3=p/u,D.a4=R/u,A.a0=D.a0,A.a1=D.a1,A.a2=D.a2,A.a3=D.a3,A.a4=D.a4,e.cachedCoefficients[n]===void 0&&(e.cachedCoefficients[n]=[]),e.cachedCoefficients[n][t]=D}},ss=new Ye(44100);ss.resonanceCb=0;for(let e=1500;e<13500;e++)ss.currentInitialFc=e,Ye.calculateCoefficients(ss,e);var bA=16384,Fe=new Float32Array(bA+1),_e=new Float32Array(bA+1);Fe[0]=0;Fe[Fe.length-1]=1;_e[0]=0;_e[_e.length-1]=1;for(let e=1;e<bA-1;e++){let A=-.4166666666666667*Math.log(e/(Fe.length-1))/Math.LN10;_e[e]=1-A,Fe[Fe.length-1-e]=A}function je(e,A,t,n){switch(e&&(t=1-t),A){case GA.linear:return n?t*2-1:t;case GA.switch:return t=t>.5?1:0,n?t*2-1:t;case GA.concave:return n?(t=t*2-1,t<0?-Fe[~~(t*-bA)]:Fe[~~(t*bA)]):Fe[~~(t*bA)];case GA.convex:return n?(t=t*2-1,t<0?-_e[~~(t*-bA)]:_e[~~(t*bA)]):_e[~~(t*bA)]}}var os=1,rs=new Float32Array(1e3);for(let e=0;e<rs.length;e++)rs[e]=je(0,GA.convex,e/1e3,0);var he=class e{attackDuration=0;decayDuration=0;holdDuration=0;releaseDuration=0;sustainLevel=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;releaseStartLevel=0;currentValue=0;static startRelease(A){e.recalculate(A)}static recalculate(A){let t=A.modulationEnvelope;A.isInRelease&&(t.releaseStartLevel=e.getValue(A,A.releaseStartTime,!0)),t.sustainLevel=1-A.modulatedGenerators[a.sustainModEnv]/1e3,t.attackDuration=Ce(A.modulatedGenerators[a.attackModEnv]);let n=(60-A.midiNote)*A.modulatedGenerators[a.keyNumToModEnvDecay],s=Ce(A.modulatedGenerators[a.decayModEnv]+n);t.decayDuration=s*(1-t.sustainLevel);let o=(60-A.midiNote)*A.modulatedGenerators[a.keyNumToModEnvHold];t.holdDuration=Ce(o+A.modulatedGenerators[a.holdModEnv]);let r=Ce(A.modulatedGenerators[a.releaseModEnv]);t.releaseDuration=r*t.releaseStartLevel,t.delayEnd=A.startTime+Ce(A.modulatedGenerators[a.delayModEnv]),t.attackEnd=t.delayEnd+t.attackDuration,t.holdEnd=t.attackEnd+t.holdDuration,t.decayEnd=t.holdEnd+t.decayDuration}static getValue(A,t,n=!1){let s=A.modulationEnvelope;return A.isInRelease&&!n?s.releaseStartLevel===0?0:Math.max(0,(1-(t-A.releaseStartTime)/s.releaseDuration)*s.releaseStartLevel):(t<s.delayEnd?s.currentValue=0:t<s.attackEnd?s.currentValue=rs[~~((1-(s.attackEnd-t)/s.attackDuration)*1e3)]:t<s.holdEnd?s.currentValue=os:t<s.decayEnd?s.currentValue=(1-(s.decayEnd-t)/s.decayDuration)*(s.sustainLevel-os)+os:s.currentValue=s.sustainLevel,s.currentValue)}};var Qi=-2320,di=-1130,In=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,t,n,s,o,r,g,i){this.sampleData=A,this.playbackStep=t,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=r,this.end=g,this.loopingMode=i,this.isLooping=this.loopingMode===1||this.loopingMode===3}},Ut=class e{sample;filter;gain=1;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new he;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=0;realKey;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;exclusiveClass=0;constructor(A,t,n,s,o,r,g,i,E,c){this.sample=t,this.generators=E,this.exclusiveClass=this.generators[a.exclusiveClass],this.modulatedGenerators=new Int16Array(E),this.modulators=c,this.filter=new Ye(A),this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=r,this.targetKey=g,this.realKey=i,this.volumeEnvelope=new Ee(A,E[a.sustainVolEnv])}static copy(A,t,n){let s=A.sample,o=new In(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new e(A.volumeEnvelope.sampleRate,o,A.midiNote,A.velocity,A.channelNumber,t,A.targetKey,n,A.generators,A.modulators.map(r=>z.copy(r)))}exclusiveRelease(A){this.release(A,ro),this.modulatedGenerators[a.releaseVolEnv]=Qi,this.modulatedGenerators[a.releaseModEnv]=di,Ee.recalculate(this),he.recalculate(this)}release(A,t=oo){this.releaseStartTime=A,this.releaseStartTime-this.startTime<t&&(this.releaseStartTime=this.startTime+t)}};function so(e,A,t,n){let s,o=this.midiAudioChannels[e],r=this.keyModifierManager.hasOverridePatch(e,A),g=o.getBankSelect(),i=o.preset.program;if(r){let h=this.keyModifierManager.getPatch(e,A);g=h.bank,i=h.program}let E=this.getCachedVoice(g,i,A,t);if(E!==void 0)return E.map(h=>Ut.copy(h,this.currentSynthTime,n));let c=o.preset;return r&&(c=this.soundfontManager.getPreset(g,i,kA(this.system))),s=c.getSamplesAndGenerators(A,t).reduce((h,Q)=>{if(Q.sample.getAudioData()===void 0)return H(`Discarding invalid sample: ${Q.sample.sampleName}`),h;let B=new Int16Array(60);for(let b=0;b<60;b++)B[b]=Os(b,Q.presetGenerators,Q.instrumentGenerators);B[a.initialAttenuation]=Math.floor(B[a.initialAttenuation]*.4);let m=Q.sample.samplePitch;B[a.overridingRootKey]>-1&&(m=B[a.overridingRootKey]);let u=A;B[a.keyNum]>-1&&(u=B[a.keyNum]);let p=Q.sample.sampleLoopStartIndex,R=Q.sample.sampleLoopEndIndex,D=B[a.sampleModes],M=new In(Q.sample.sampleData,Q.sample.sampleRate/this.sampleRate*Math.pow(2,Q.sample.samplePitchCorrection/1200),0,m,p,R,Math.floor(Q.sample.sampleData.length)-1,D);return B[a.velocity]>-1&&(t=B[a.velocity]),h.push(new Ut(this.sampleRate,M,A,t,e,this.currentSynthTime,u,n,B,Q.modulators.map(b=>z.copy(b)))),h},[]),this.setCachedVoice(g,i,A,t,s.map(h=>Ut.copy(h,this.currentSynthTime,n))),s}var ao=.05,fi=4600,ui=2e3,io=Math.PI/2,gn=-500,Io=500,is=Io-gn,go=new Float32Array(is+1),Co=new Float32Array(is+1);for(let e=gn;e<=Io;e++){let A=(e-gn)/is,t=e-gn;go[t]=Math.cos(io*A),Co[t]=Math.sin(io*A)}function Eo(e,A,t,n,s,o,r,g){if(isNaN(A[0]))return;let i;e.overridePan?i=e.overridePan:(e.currentPan+=(e.modulatedGenerators[a.pan]-e.currentPan)*this.synth.panSmoothingFactor,i=e.currentPan);let E=this.synth.currentGain*e.gain,c=~~(i+500),h=go[c]*E*this.synth.panLeft,Q=Co[c]*E*this.synth.panRight;if(this.synth.effectsEnabled){let B=e.modulatedGenerators[a.reverbEffectsSend];if(B>0){let u=this.synth.reverbGain*E*(B/fi);for(let p=0;p<A.length;p++)s[p]+=u*A[p];o.set(s)}let m=e.modulatedGenerators[a.chorusEffectsSend];if(m>0){let u=this.synth.chorusGain*m/ui,p=h*u,R=Q*u;for(let D=0;D<A.length;D++)r[D]+=p*A[D],g[D]+=R*A[D]}}if(h>0)for(let B=0;B<A.length;B++)t[B]+=h*A[B];if(Q>0)for(let B=0;B<A.length;B++)n[B]+=Q*A[B]}function ho(e=!1){y("%cStop all received!",I.info);for(let A=0;A<this.midiAudioChannels.length;A++)this.midiAudioChannels[A].stopAllNotes(e);this.callEvent("stopall",void 0)}function N(e,A){let t=0;for(let n=0;n<A;n++)t|=e[e.currentIndex++]<<n*8;return t>>>0}function Je(e,A,t){for(let n=0;n<t;n++)e[e.currentIndex++]=A>>n*8&255}function Y(e,A){e[e.currentIndex++]=A&255,e[e.currentIndex++]=A>>8}function eA(e,A){Je(e,A,4)}function Ke(e,A){let t=A<<8|e;return t>32767?t-65536:t}function Bo(e){return e>127?e-256:e}var BA=class{constructor(A,t,n){this.header=A,this.size=t,this.chunkData=n}};function IA(e,A=!0,t=!1){let n=$(e,4),s=N(e,4),o;return A&&(o=new x(e.buffer.slice(e.currentIndex,e.currentIndex+s))),(A||t)&&(e.currentIndex+=s),s%2!==0&&e[e.currentIndex]===0&&e.currentIndex++,new BA(n,s,o)}function dA(e,A=void 0){let t=8+e.size;e.size%2!==0&&t++,A&&(t+=A.length);let n=new x(t);return A&&(n.set(A,n.currentIndex),n.currentIndex+=A.length),NA(n,e.header),eA(n,t-8-(A?.length||0)),n.set(e.chunkData,n.currentIndex),n}function _(e,A,t=!1,n=!1){if(t){let E=new Uint8Array(A.length+1);E.set(A),A=E}let s=8,o=s+A.length,r=A.length;o%2!==0&&o++;let g=e;n&&(o+=4,r+=4,s+=4,g="LIST");let i=new x(o);return NA(i,g),eA(i,r),n&&NA(i,e),i.set(A,s),i}function ZA(e,A){return e.find(t=>t.header!=="LIST"?!1:(t.chunkData.currentIndex=0,$(t.chunkData,4)===A))}function co(){let e=4;for(let n of this.instruments)e+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(r=>r.generatorType!==a.sampleID&&r.generatorType!==a.keyRange&&r.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift(new U(a.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift(new U(a.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.isGlobal||o.generators.push(new U(a.sampleID,this.samples.indexOf(o.sample),!1)),o.generators.length*4+s),0);let A=new x(e),t=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=t;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue),t++}return eA(A,0),dA(new BA("igen",A.length,A))}function lo(e,A,t,n,s){let o=this.samples.map((E,c)=>{t&&E.compressSample(n,s);let h=E.getRawData();return y(`%cEncoded sample %c${c}. ${E.sampleName}%c of %c${this.samples.length}%c. Compressed: %c${E.isCompressed}%c.`,I.info,I.recognized,I.info,I.recognized,I.info,E.isCompressed?I.recognized:I.unrecognized,I.info),h}),r=this.samples.reduce((E,c,h)=>E+o[h].length+46,0),g=new x(r);this.samples.forEach((E,c)=>{let h=o[c],Q,B,m=h.length;E.isCompressed?(Q=g.currentIndex,B=Q+h.length):(Q=g.currentIndex/2,B=Q+h.length/2,m+=46),e.push(Q),g.set(h,g.currentIndex),g.currentIndex+=m,A.push(B)});let i=dA(new BA("smpl",g.length,g),new x([115,100,116,97]));return dA(new BA("LIST",i.length,i))}function Qo(e,A){let n=new x(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{NA(n,s.sampleName,20);let r=e[o];eA(n,r);let g=A[o];eA(n,g);let i=s.sampleLoopStartIndex+r,E=s.sampleLoopEndIndex+r;s.isCompressed&&(i-=r,E-=r),eA(n,i),eA(n,E),eA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,Y(n,s.sampleLink),Y(n,s.sampleType)}),NA(n,"EOS",46),dA(new BA("shdr",n.length,n))}function fo(){let e=10;for(let n of this.instruments)e+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new x(e),t=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=t;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),t++}return Je(A,0,10),dA(new BA("imod",A.length,A))}function uo(){let e=this.instruments.reduce((o,r)=>r.instrumentZones.length*4+o,4),A=new x(e),t=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=t;for(let r of o.instrumentZones)r.zoneID=t,Y(A,n),Y(A,s),n+=r.generators.length,s+=r.modulators.length,t++}return Y(A,n),Y(A,s),dA(new BA("ibag",A.length,A))}function mo(){let e=this.instruments.length*22+22,A=new x(e),t=0,n=0;for(let s of this.instruments)NA(A,s.instrumentName,20),Y(A,t),t+=s.instrumentZones.length,s.instrumentID=n,n++;return NA(A,"EOI",20),Y(A,t),dA(new BA("inst",A.length,A))}function po(){let e=4;for(let n of this.presets)e+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(r=>r.generatorType!==a.instrument&&r.generatorType!==a.keyRange&&r.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift(new U(a.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift(new U(a.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.isGlobal||o.generators.push(new U(a.instrument,this.instruments.indexOf(o.instrument),!1)),o.generators.length*4+s),0);let A=new x(e),t=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=t;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue);t+=s.generators.length}return Y(A,0),Y(A,0),dA(new BA("pgen",A.length,A))}function yo(){let e=10;for(let n of this.presets)e+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new x(e),t=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=t;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),t++}return Je(A,0,10),dA(new BA("pmod",A.length,A))}function So(){let e=this.presets.reduce((o,r)=>r.presetZones.length*4+o,4),A=new x(e),t=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=t;for(let r of o.presetZones)r.zoneID=t,Y(A,n),Y(A,s),n+=r.generators.length,s+=r.modulators.length,t++}return Y(A,n),Y(A,s),dA(new BA("pbag",A.length,A))}function Do(){let e=this.presets.length*38+38,A=new x(e),t=0;for(let n of this.presets)NA(A,n.presetName,20),Y(A,n.program),Y(A,n.bank),Y(A,t),eA(A,n.library),eA(A,n.genre),eA(A,n.morphology),t+=n.presetZones.length;return NA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,t),eA(A,0),eA(A,0),eA(A,0),dA(new BA("phdr",A.length,A))}var mi={compress:!1,compressionQuality:.5,compressionFunction:void 0};function ko(e=mi){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");fA("%cSaving soundfont...",I.info),y(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,I.info,I.recognized,I.info,I.recognized),y("%cWriting INFO...",I.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[b,G]of Object.entries(this.soundFontInfo))if(b==="ifil"||b==="iver"){let C=parseInt(G.split(".")[0]),L=parseInt(G.split(".")[1]),J=new x(4);Y(J,C),Y(J,L),A.push(dA(new BA(b,4,J)))}else if(b==="DMOD")A.push(dA(new BA(b,G.length,G)));else{let C=new x(G.length);NA(C,G),A.push(dA(new BA(b,G.length,C)))}let t=DA([new x([73,78,70,79]),...A]),n=dA(new BA("LIST",t.length,t));y("%cWriting SDTA...",I.info);let s=[],o=[],r=lo.call(this,s,o,e?.compress,e?.compressionQuality??.5,e.compressionFunction);y("%cWriting PDTA...",I.info),y("%cWriting SHDR...",I.info);let g=Qo.call(this,s,o);y("%cWriting IGEN...",I.info);let i=co.call(this);y("%cWriting IMOD...",I.info);let E=fo.call(this);y("%cWriting IBAG...",I.info);let c=uo.call(this);y("%cWriting INST...",I.info);let h=mo.call(this),Q=po.call(this);y("%cWriting PMOD...",I.info);let B=yo.call(this);y("%cWriting PBAG...",I.info);let m=So.call(this);y("%cWriting PHDR...",I.info);let u=Do.call(this),p=DA([new x([112,100,116,97]),u,m,B,Q,h,c,E,i,g]),R=dA(new BA("LIST",p.length,p));y("%cWriting the output file...",I.info);let D=DA([new x([115,102,98,107]),n,r,R]),M=dA(new BA("RIFF",D.length,D));return y(`%cSaved succesfully! Final file size: %c${M.length}`,I.info,I.recognized),q(),M}var Tt=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};isGlobal=!1;generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}getGeneratorValue(A,t){return this.generators.find(n=>n.generatorType===A)?.generatorValue??t}};var KA=class extends Tt{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},Re=class extends Tt{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var pi=new Set([a.velRange,a.keyRange,a.instrument,a.exclusiveClass,a.endOper,a.sampleModes,a.startloopAddrsOffset,a.startloopAddrsCoarseOffset,a.endloopAddrsOffset,a.endloopAddrsCoarseOffset,a.startAddrsOffset,a.startAddrsCoarseOffset,a.endAddrOffset,a.endAddrsCoarseOffset,a.initialAttenuation,a.fineTune,a.coarseTune,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay,a.keyNumToModEnvHold,a.keyNumToModEnvDecay]);function wo(e,A=!0){function t(h,Q){h.push(...Q.filter(B=>!h.find(m=>m.generatorType===B.generatorType)))}function n(h,Q){return{min:Math.max(h.min,Q.min),max:Math.min(h.max,Q.max)}}function s(h,Q){h.push(...Q.filter(B=>!h.find(m=>z.isIdentical(B,m))))}let o=[],r=[],g=[],i={min:0,max:127},E={min:0,max:127},c=e.presetZones.find(h=>h.isGlobal);c&&(r.push(...c.generators),g.push(...c.modulators),i=c.keyRange,E=c.velRange);for(let h of e.presetZones){if(h.isGlobal)continue;let Q=h.keyRange;h.hasKeyRange||(Q=i);let B=h.velRange;h.hasVelRange||(B=E);let m=h.generators.map(C=>new U(C.generatorType,C.generatorValue));t(m,r);let u=[...h.modulators];s(u,g);let p=h.instrument.instrumentZones,R=[],D=[],M={min:0,max:127},b={min:0,max:127},G=p.find(C=>C.isGlobal);G&&(R.push(...G.generators),D.push(...G.modulators),M=G.keyRange,b=G.velRange);for(let C of p){if(C.isGlobal)continue;let L=C.keyRange;C.hasKeyRange||(L=M);let J=C.velRange;if(C.hasVelRange||(J=b),L=n(L,Q),J=n(J,B),L.max<L.min||J.max<J.min)continue;let EA=C.generators.map(sA=>new U(sA.generatorType,sA.generatorValue));t(EA,R);let tA=[...C.modulators];s(tA,D);let T=[...tA];for(let sA of u){let oA=T.findIndex(CA=>z.isIdentical(sA,CA));oA!==-1?T[oA]=T[oA].sumTransform(sA):T.push(sA)}let AA=EA.map(sA=>new U(sA.generatorType,sA.generatorValue));for(let sA of m){if(sA.generatorType===a.velRange||sA.generatorType===a.keyRange||sA.generatorType===a.instrument||sA.generatorType===a.endOper||sA.generatorType===a.sampleModes)continue;let oA=EA.findIndex(CA=>CA.generatorType===sA.generatorType);if(oA!==-1){let CA=AA[oA].generatorValue+sA.generatorValue;AA[oA]=new U(sA.generatorType,CA)}else{let CA=X[sA.generatorType].def+sA.generatorValue;AA.push(new U(sA.generatorType,CA))}}AA=AA.filter(sA=>sA.generatorType!==a.sampleID&&sA.generatorType!==a.keyRange&&sA.generatorType!==a.velRange&&sA.generatorType!==a.endOper&&sA.generatorType!==a.instrument&&sA.generatorValue!==X[sA.generatorType].def);let hA=new KA;hA.keyRange=L,hA.velRange=J,hA.keyRange.min===0&&hA.keyRange.max===127&&(hA.keyRange.min=-1),hA.velRange.min===0&&hA.velRange.max===127&&(hA.velRange.min=-1),hA.isGlobal=!1,hA.sample=C.sample,hA.generators=AA,hA.modulators=T,o.push(hA)}}if(A){let h=new KA;h.isGlobal=!0;for(let m=0;m<58;m++){if(pi.has(m))continue;let u={},p=X[m]?.def||0;u[p]=0;for(let R of o){let D=R.generators.find(G=>G.generatorType===m);if(D){let G=D.generatorValue;u[G]===void 0?u[G]=1:u[G]++}else u[p]++;let M;switch(m){default:continue;case a.decayVolEnv:M=a.keyNumToVolEnvDecay;break;case a.holdVolEnv:M=a.keyNumToVolEnvHold;break;case a.decayModEnv:M=a.keyNumToModEnvDecay;break;case a.holdModEnv:M=a.keyNumToModEnvHold}if(R.generators.find(G=>G.generatorType===M)!==void 0){u={};break}}if(Object.keys(u).length>0){let R=Object.entries(u).reduce((M,b)=>M[1]<b[1]?b:M,[0,0]),D=parseInt(R[0]);D!==p&&h.generators.push(new U(m,D)),o.forEach(M=>{let b=M.generators.findIndex(G=>G.generatorType===m);b!==-1?M.generators[b].generatorValue===D&&M.generators.splice(b,1):D!==p&&M.generators.push(new U(m,p))})}}let B=o.find(m=>!m.isGlobal).modulators.map(m=>z.copy(m));for(let m of B){let u=!0;for(let p of o){if(p.isGlobal||!u)continue;p.modulators.find(D=>z.isIdentical(D,m))||(u=!1)}if(u===!0){h.modulators.push(z.copy(m));for(let p of o){let R=p.modulators.find(D=>z.isIdentical(D,m));R.transformAmount===m.transformAmount&&p.modulators.splice(p.modulators.indexOf(R),1)}}}o.splice(0,0,h)}return o}var Fo=20;function Cn(e,A,t,n,s,o,r){let g=r===0?0:1,i=new x(Fo+g*16);eA(i,Fo),Y(i,A),Y(i,t);let E=n*.4,c=Math.floor(E*-65536);eA(i,c),eA(i,2);let h=o-s,Q=0;switch(r){default:case 0:g=0;break;case 1:Q=0,g=1;break;case 3:Q=1,g=1}return eA(i,g),g===1&&(eA(i,16),eA(i,Q),eA(i,s),eA(i,h)),_("wsmp",i)}var V={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},En=new z(219,0,a.reverbEffectsSend,1e3,0),hn=new z(221,0,a.chorusEffectsSend,1e3,0),Bn=new z(129,0,a.vibLfoToPitch,0,0),cn=new z(13,0,a.vibLfoToPitch,0,0);var F={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281};var vt=class{source;control;destination;scale;transform;constructor(A,t,n,s,o){this.source=A,this.control=t,this.destination=n,this.scale=s,this.transform=o}writeArticulator(){let A=new x(12);return Y(A,this.source),Y(A,this.control),Y(A,this.destination),Y(A,this.transform),eA(A,this.scale<<16),A}};function Ro(e,A){if(e)switch(A){default:return;case S.modulationWheel:return V.modulationWheel;case S.mainVolume:return V.volume;case S.pan:return V.pan;case S.expressionController:return V.expression;case S.chorusDepth:return V.chorus;case S.reverbDepth:return V.reverb}else switch(A){default:return;case j.noteOnKeyNum:return V.keyNum;case j.noteOnVelocity:return V.velocity;case j.noController:return V.none;case j.polyPressure:return V.polyPressure;case j.channelPressure:return V.channelPressure;case j.pitchWheel:return V.pitchWheel;case j.pitchWheelRange:return V.pitchWheelRange}}function Go(e,A){switch(e){default:return;case a.initialAttenuation:return{dest:F.gain,amount:-A};case a.fineTune:return F.pitch;case a.pan:return F.pan;case a.keyNum:return F.keyNum;case a.reverbEffectsSend:return F.reverbSend;case a.chorusEffectsSend:return F.chorusSend;case a.freqModLFO:return F.modLfoFreq;case a.delayModLFO:return F.modLfoDelay;case a.delayVibLFO:return F.vibLfoDelay;case a.freqVibLFO:return F.vibLfoFreq;case a.delayVolEnv:return F.volEnvDelay;case a.attackVolEnv:return F.volEnvAttack;case a.holdVolEnv:return F.volEnvHold;case a.decayVolEnv:return F.volEnvDecay;case a.sustainVolEnv:return{dest:F.volEnvSustain,amount:1e3-A};case a.releaseVolEnv:return F.volEnvRelease;case a.delayModEnv:return F.modEnvDelay;case a.attackModEnv:return F.modEnvAttack;case a.holdModEnv:return F.modEnvHold;case a.decayModEnv:return F.modEnvDecay;case a.sustainModEnv:return{dest:F.modEnvSustain,amount:1e3-A};case a.releaseModEnv:return F.modEnvRelease;case a.initialFilterFc:return F.filterCutoff;case a.initialFilterQ:return F.filterQ}}function Mo(e,A){switch(e){default:return;case a.modEnvToFilterFc:return{source:V.modEnv,dest:F.filterCutoff,amt:A,isBipolar:!1};case a.modEnvToPitch:return{source:V.modEnv,dest:F.pitch,amt:A,isBipolar:!1};case a.modLfoToFilterFc:return{source:V.modLfo,dest:F.filterCutoff,amt:A,isBipolar:!0};case a.modLfoToVolume:return{source:V.modLfo,dest:F.gain,amt:A,isBipolar:!0};case a.modLfoToPitch:return{source:V.modLfo,dest:F.pitch,amt:A,isBipolar:!0};case a.vibLfoToPitch:return{source:V.vibratoLfo,dest:F.pitch,amt:A,isBipolar:!0};case a.keyNumToVolEnvHold:return{source:V.keyNum,dest:F.volEnvHold,amt:A,isBipolar:!0};case a.keyNumToVolEnvDecay:return{source:V.keyNum,dest:F.volEnvDecay,amt:A,isBipolar:!0};case a.keyNumToModEnvHold:return{source:V.keyNum,dest:F.modEnvHold,amt:A,isBipolar:!0};case a.keyNumToModEnvDecay:return{source:V.keyNum,dest:F.modEnvDecay,amt:A,isBipolar:!0};case a.scaleTuning:return{source:V.keyNum,dest:F.pitch,amt:A*128,isBipolar:!1}}}function xo(e){let A=Go(e.generatorType,e.generatorValue),t=A,n=0,s=e.generatorValue;A?.amount!==void 0&&(s=A.amount,t=A.dest);let o=Mo(e.generatorType,e.generatorValue);if(o!==void 0)s=o.amt,t=o.dest,n=o.source;else if(t===void 0){H(`Invalid generator type: ${e.generatorType}`);return}return new vt(n,0,t,s,0)}function No(e){if(e.transformType!==0){H("Other transform types are not supported.");return}let A=Ro(e.sourceUsesCC,e.sourceIndex),t=e.sourceCurveType,n=e.sourcePolarity,s=e.sourceDirection;if(A===void 0){H(`Invalid source: ${e.sourceIndex}, CC: ${e.sourceUsesCC}`);return}e.modulatorDestination===a.initialAttenuation&&(s=s===1?0:1);let o=Ro(e.secSrcUsesCC,e.secSrcIndex),r=e.secSrcCurveType,g=e.secSrcPolarity,i=e.secSrcDirection;if(o===void 0){H(`Invalid secondary source: ${e.secSrcIndex}, CC: ${e.secSrcUsesCC}`);return}let E=Go(e.modulatorDestination,e.transformAmount),c=E,h=e.transformAmount;E?.dest!==void 0&&(c=E.dest,h=E.amount);let Q=Mo(e.modulatorDestination,e.transformAmount);if(Q!==void 0)h=Q.amt,o=A,r=t,g=n,i=s,t=GA.linear,n=Q.isBipolar?1:0,s=0,A=Q.source,c=Q.dest;else if(c===void 0){H(`Invalid destination: ${e.modulatorDestination}`);return}let B=0;return B|=r<<4,B|=g<<8,B|=i<<9,B|=t,B|=n<<14,B|=s<<15,new vt(A,o,c,h,B)}var yi=new Set([a.sampleModes,a.initialAttenuation,a.keyRange,a.velRange,a.sampleID,a.fineTune,a.coarseTune,a.startAddrsOffset,a.startAddrsCoarseOffset,a.endAddrOffset,a.endAddrsCoarseOffset,a.startloopAddrsOffset,a.startloopAddrsCoarseOffset,a.endloopAddrsOffset,a.endloopAddrsCoarseOffset,a.overridingRootKey,a.exclusiveClass]);function ln(e){for(let o=0;o<e.generators.length;o++){let r=e.generators[o];(r.generatorType===a.delayVolEnv||r.generatorType===a.attackVolEnv||r.generatorType===a.holdVolEnv||r.generatorType===a.decayVolEnv||r.generatorType===a.releaseVolEnv||r.generatorType===a.delayModEnv||r.generatorType===a.attackModEnv||r.generatorType===a.holdModEnv||r.generatorType===a.decayModEnv)&&(e.generators[o]=new U(r.generatorType,Math.min(r.generatorValue,6386),!1))}for(let o=0;o<e.generators.length;o++){let r=e.generators[o],g;switch(r.generatorType){default:continue;case a.keyNumToVolEnvDecay:g=a.decayVolEnv;break;case a.keyNumToVolEnvHold:g=a.holdVolEnv;break;case a.keyNumToModEnvDecay:g=a.decayModEnv;break;case a.keyNumToModEnvHold:g=a.holdModEnv}let i=e.generators.find(m=>m.generatorType===g);if(i===void 0)continue;let E=r.generatorValue*-128,c=60/128*E,h=i.generatorValue-c,Q=e.generators.indexOf(r),B=e.generators.indexOf(i);e.generators[B]=new U(g,h,!1),e.generators[Q]=new U(r.generatorType,E,!1)}let A=e.generators.reduce((o,r)=>{if(yi.has(r.generatorType))return o;let g=xo(r);return g!==void 0?(o.push(g),y("%cSucceeded converting to DLS Articulator!",I.recognized)):H("Failed converting to DLS Articulator!"),o},[]),t=e.modulators.reduce((o,r)=>{if(z.isIdentical(r,hn,!0)||z.isIdentical(r,En,!0)||z.isIdentical(r,Bn,!0)||z.isIdentical(r,cn,!0))return o;let g=No(r);return g!==void 0?(o.push(g),y("%cSucceeded converting to DLS Articulator!",I.recognized)):H("Failed converting to DLS Articulator!"),o},[]);A.push(...t);let n=new x(8);eA(n,8),eA(n,A.length);let s=A.map(o=>o.writeArticulator());return _("art2",DA([n,...s]))}function bo(e,A){let t=new x(12);Y(t,Math.max(e.keyRange.min,0)),Y(t,e.keyRange.max),Y(t,Math.max(e.velRange.min,0)),Y(t,e.velRange.max),Y(t,0);let n=e.getGeneratorValue(a.exclusiveClass,0);Y(t,n),Y(t,0);let s=_("rgnh",t),o=e.getGeneratorValue(a.overridingRootKey,e.sample.samplePitch);e.getGeneratorValue(a.scaleTuning,A.getGeneratorValue(a.scaleTuning,100))===0&&e.keyRange.max-e.keyRange.min===0&&(o=e.keyRange.min);let g=Cn(e.sample,o,e.getGeneratorValue(a.fineTune,0)+e.getGeneratorValue(a.coarseTune,0)*100+e.sample.samplePitchCorrection,e.getGeneratorValue(a.initialAttenuation,0),e.sample.sampleLoopStartIndex+e.getGeneratorValue(a.startloopAddrsOffset,0)+e.getGeneratorValue(a.startloopAddrsCoarseOffset,0)*32768,e.sample.sampleLoopEndIndex+e.getGeneratorValue(a.endloopAddrsOffset,0)+e.getGeneratorValue(a.endloopAddrsCoarseOffset,0)*32768,e.getGeneratorValue(a.sampleModes,0)),i=new x(12);Y(i,0),Y(i,0),eA(i,1),eA(i,this.samples.indexOf(e.sample));let E=_("wlnk",i),c=new x(0);if(e.modulators.length+e.generators.length>0){let h=ln(e);c=_("lar2",h,!1,!0)}return _("rgn2",DA([s,g,E,c]),!1,!0)}function Lo(e){fA(`%cWriting %c${e.presetName}%c...`,I.info,I.recognized,I.info);let A=wo(e),t=A.reduce((Q,B)=>B.isGlobal?Q:Q+1,0),n=new x(12);eA(n,t);let s=(e.bank&127)<<8;e.bank===128&&(s|=1<<31),eA(n,s),eA(n,e.program&127);let o=_("insh",n),r=new x(0),g=A.find(Q=>Q.isGlobal===!0);if(g){let Q=ln(g);r=_("lar2",Q,!1,!0)}let i=DA(A.reduce((Q,B)=>(B.isGlobal||Q.push(bo.apply(this,[B,g])),Q),[])),E=_("lrgn",i,!1,!0),c=_("INAM",pe(e.presetName)),h=_("INFO",c,!1,!0);return q(),_("ins ",DA([o,E,r,h]),!1,!0)}function Uo(){let e=DA(this.presets.map(A=>Lo.apply(this,[A])));return _("lins",e,!1,!0)}function To(e){let A=new x(18);Y(A,1),Y(A,1),eA(A,e.sampleRate),eA(A,e.sampleRate*2),Y(A,2),Y(A,16);let t=_("fmt ",A),n=1;e.sampleLoopStartIndex+Math.abs(e.getAudioData().length-e.sampleLoopEndIndex)<2&&(n=0);let s=Cn(e,e.samplePitch,e.samplePitchCorrection,0,e.sampleLoopStartIndex,e.sampleLoopEndIndex,n),o=e.getAudioData(),r;if(e.isCompressed){let E=new Int16Array(o.length);for(let c=0;c<o.length;c++)E[c]=o[c]*32767;r=_("data",new x(E.buffer))}else r=_("data",e.getRawData());let g=_("INAM",pe(e.sampleName)),i=_("INFO",g,!1,!0);return y(`%cSaved %c${e.sampleName}%c succesfully!`,I.recognized,I.value,I.recognized),_("wave",DA([t,s,r,i]),!1,!0)}function vo(){let e=0,A=[],t=this.samples.map(n=>{let s=To(n);return A.push(e),e+=s.length,s});return{data:_("wvpl",DA(t),!1,!0),indexes:A}}function Ho(){fA("%cSaving DLS...",I.info);let e=new x(4);eA(e,this.presets.length);let A=_("colh",e);fA("%cWriting instruments...",I.info);let t=Uo.apply(this);y("%cSuccess!",I.recognized),q(),fA("%cWriting WAVE samples...",I.info);let n=vo.apply(this),s=n.data,o=n.indexes;y("%cSucceeded!",I.recognized),q();let r=new x(8+4*o.length);eA(r,8),eA(r,o.length);for(let h of o)eA(r,h);let g=_("ptbl",r);this.soundFontInfo.ICMT=(this.soundFontInfo.ICMT||"Soundfont")+`
11
- Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynth";let i=[];for(let[h,Q]of Object.entries(this.soundFontInfo))h!=="ICMT"&&h!=="INAM"&&h!=="ICRD"&&h!=="IENG"&&h!=="ICOP"&&h!=="ISFT"&&h!=="ISBJ"||i.push(_(h,pe(Q),!0));let E=_("INFO",DA(i),!1,!0),c=new x(A.length+t.length+g.length+s.length+E.length+4);return NA(c,"DLS "),c.set(DA([A,t,g,s,E]),4),y("%cSaved succesfully!",I.recognized),q(),_("RIFF",c)}var Si=48e3,Ge=class{sampleName;sampleRate;samplePitch;samplePitchCorrection;sampleLink;sampleType;sampleLoopStartIndex;sampleLoopEndIndex;isCompressed;compressedData=void 0;useCount=0;sampleData=void 0;constructor(A,t,n,s,o,r,g,i){this.sampleName=A,this.sampleRate=t,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=r,this.sampleLoopStartIndex=g,this.sampleLoopEndIndex=i,this.isCompressed=(r&16)>0}getRawData(){let A=new Uint8Array(this.sampleData.length*2);for(let t=0;t<this.sampleData.length;t++){let n=Math.floor(this.sampleData[t]*32768);A[t*2]=n&255,A[t*2+1]=n>>8&255}return A}resampleData(A){let t=this.getAudioData(),n=A/this.sampleRate,s=new Float32Array(Math.floor(t.length*n));for(let o=0;o<s.length;o++)s[o]=t[Math.floor(o*(1/n))];t=s,this.sampleRate=A,this.sampleLoopStartIndex=Math.floor(this.sampleLoopStartIndex*n),this.sampleLoopEndIndex=Math.floor(this.sampleLoopEndIndex*n),this.sampleData=t}compressSample(A,t){if(!this.isCompressed)try{let n=this.getAudioData();(this.sampleRate<8e3||this.sampleRate>96e3)&&(this.resampleData(Si),n=this.getAudioData()),this.compressedData=t([n],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{H(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=239}}getAudioData(){return this.sampleData}};var Me=class{instrumentName="";instrumentZones=[];_useCount=0;get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;A<this.instrumentZones.length;A++)this.safeDeleteZone(A)&&A--}deleteInstrument(){this.instrumentZones.forEach(A=>A.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var xe=class{parentSoundBank;presetName="";program=0;bank=0;presetZones=[];foundSamplesAndGenerators=[];library=0;genre=0;morphology=0;constructor(A){this.parentSoundBank=A;for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[]}isDrumPreset(A,t=!1){let n=A&&this.parentSoundBank.isXGBank;return this.bank===128||n&&$A(this.bank)&&(this.bank!==126||t)}deletePreset(){this.presetZones.forEach(A=>A.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,t){for(let n=A;n<t+1;n++)for(let s=0;s<128;s++)this.getSamplesAndGenerators(n,s).forEach(o=>{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,t){let n=this.foundSamplesAndGenerators[A][t];if(n)return n;if(this.presetZones.length<1)return[];function s(B,m){return m>=B.min&&m<=B.max}function o(B,m){B.push(...m.filter(u=>!B.find(p=>p.generatorType===u.generatorType)))}function r(B,m){B.push(...m.filter(u=>!B.find(p=>z.isIdentical(u,p))))}let g=[],i=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],E=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[],c=this.presetZones[0].isGlobal?this.presetZones[0].keyRange:{min:0,max:127},h=this.presetZones[0].isGlobal?this.presetZones[0].velRange:{min:0,max:127};return this.presetZones.filter(B=>s(B.hasKeyRange?B.keyRange:c,A)&&s(B.hasVelRange?B.velRange:h,t)&&!B.isGlobal).forEach(B=>{if(B.instrument.instrumentZones.length<1)return;let m=B.generators,u=B.modulators,p=B.instrument.instrumentZones[0],R=p.isGlobal?[...p.generators]:[],D=p.isGlobal?[...p.modulators]:[],M=p.isGlobal?p.keyRange:{min:0,max:127},b=p.isGlobal?p.velRange:{min:0,max:127};B.instrument.instrumentZones.filter(C=>s(C.hasKeyRange?C.keyRange:M,A)&&s(C.hasVelRange?C.velRange:b,t)&&!C.isGlobal).forEach(C=>{let L=[...C.generators],J=[...C.modulators];o(m,i),o(L,R),r(u,E),r(J,D),r(J,this.parentSoundBank.defaultModulators);let EA=[...J];for(let tA=0;tA<u.length;tA++){let T=u[tA],AA=EA.findIndex(hA=>z.isIdentical(T,hA));AA!==-1?EA[AA]=EA[AA].sumTransform(T):EA.push(T)}g.push({instrumentGenerators:L,presetGenerators:m,modulators:EA,sample:C.sample,sampleID:C.generators.find(tA=>tA.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=g,g}};var Ne=class e{soundFontInfo={};presets=[];samples=[];instruments=[];defaultModulators=js.map(A=>z.copy(A));isXGBank=!1;constructor(A=void 0){A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundBanks(...A){let t=A.shift(),n=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(r=>r.bank===o.bank&&r.program===o.program)===void 0&&n.push(o)});return new e({presets:n,info:t.soundFontInfo})}static getDummySoundfontFile(){let A=new e,t=new Ge("Saw",44100,65,20,0,0,0,127);t.sampleData=new Float32Array(128);for(let E=0;E<128;E++)t.sampleData[E]=E/128*2-1;A.samples.push(t);let n=new KA;n.isGlobal=!0,n.generators.push(new U(a.initialAttenuation,375)),n.generators.push(new U(a.releaseVolEnv,-1e3)),n.generators.push(new U(a.sampleModes,1));let s=new KA;s.sample=t;let o=new KA;o.sample=t,o.generators.push(new U(a.fineTune,-9));let r=new Me;r.instrumentName="Saw Wave",r.instrumentZones.push(n),r.instrumentZones.push(s),r.instrumentZones.push(o),A.instruments.push(r);let g=new Re;g.instrument=r;let i=new xe(A);return i.presetName="Saw Wave",i.presetZones.push(g),A.presets.push(i),A.soundFontInfo.ifil="2.1",A.soundFontInfo.isng="EMU8000",A.soundFontInfo.INAM="Dummy",A._parseInternal(),A.write().buffer}_parseInternal(){this.isXGBank=!1;let A=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let t of this.presets)if($A(t.bank)&&(this.isXGBank=!0,!A.has(t.program))){this.isXGBank=!1,y(`%cThis bank is not valid XG. Preset %c${t.bank}:${t.program}%c is not a valid XG drum. XG mode will use presets on bank 128.`,I.info,I.value,I.info);break}}trimSoundBank(A){let t=this;function n(o,r){let g=0;for(let i=0;i<o.instrumentZones.length;i++){let E=o.instrumentZones[i];if(E.isGlobal)continue;let c=E.keyRange,h=E.velRange,Q=!1;for(let B of r)if(B.key>=c.min&&B.key<=c.max&&B.velocity>=h.min&&B.velocity<=h.max){Q=!0;break}Q||(y(`%c${E.sample.sampleName} %cremoved from %c${o.instrumentName}%c. Use count: %c${E.useCount-1}`,I.recognized,I.info,I.recognized,I.info,I.recognized),o.safeDeleteZone(i)&&(g++,i--,y(`%c${E.sample.sampleName} %cdeleted`,I.recognized,I.info)),E.sample.useCount<1&&t.deleteSample(E.sample))}return g}ie("%cTrimming soundfont...",I.info);let s=A.getUsedProgramsAndKeys(t);fA("%cModifying soundfont...",I.info),y("Detected keys for midi:",s);for(let o=0;o<t.presets.length;o++){let r=t.presets[o],g=r.bank+":"+r.program,i=s[g];if(i===void 0)y(`%cDeleting preset %c${r.presetName}%c and its zones`,I.info,I.recognized,I.info),t.deletePreset(r),o--;else{let E=[...i].map(h=>{let Q=h.split("-");return{key:parseInt(Q[0]),velocity:parseInt(Q[1])}});fA(`%cTrimming %c${r.presetName}`,I.info,I.recognized),y(`Keys for ${r.presetName}:`,E);let c=0;for(let h=0;h<r.presetZones.length;h++){let Q=r.presetZones[h];if(Q.isGlobal)continue;let B=Q.keyRange,m=Q.velRange,u=!1;for(let p of E)if(p.key>=B.min&&p.key<=B.max&&p.velocity>=m.min&&p.velocity<=m.max){u=!0;let R=n(Q.instrument,E);y(`%cTrimmed off %c${R}%c zones from %c${Q.instrument.instrumentName}`,I.info,I.recognized,I.info,I.recognized);break}u||(c++,r.deleteZone(h),Q.instrument.useCount<1&&t.deleteInstrument(Q.instrument),h--)}y(`%cTrimmed off %c${c}%c zones from %c${r.presetName}`,I.info,I.recognized,I.info,I.recognized),q()}}t.removeUnusedElements(),t.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${A.midiName}"
11
+ Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynth";let i=[];for(let[h,Q]of Object.entries(this.soundFontInfo))h!=="ICMT"&&h!=="INAM"&&h!=="ICRD"&&h!=="IENG"&&h!=="ICOP"&&h!=="ISFT"&&h!=="ISBJ"||i.push(_(h,pe(Q),!0));let E=_("INFO",DA(i),!1,!0),c=new x(A.length+t.length+g.length+s.length+E.length+4);return NA(c,"DLS "),c.set(DA([A,t,g,s,E]),4),y("%cSaved succesfully!",I.recognized),q(),_("RIFF",c)}var Si=48e3,Ge=class{sampleName;sampleRate;samplePitch;samplePitchCorrection;sampleLink;sampleType;sampleLoopStartIndex;sampleLoopEndIndex;isCompressed;compressedData=void 0;useCount=0;sampleData=void 0;constructor(A,t,n,s,o,r,g,i){this.sampleName=A,this.sampleRate=t,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=r,this.sampleLoopStartIndex=g,this.sampleLoopEndIndex=i,this.isCompressed=(r&16)>0}getRawData(){let A=new Uint8Array(this.sampleData.length*2);for(let t=0;t<this.sampleData.length;t++){let n=Math.floor(this.sampleData[t]*32768);A[t*2]=n&255,A[t*2+1]=n>>8&255}return A}resampleData(A){let t=this.getAudioData(),n=A/this.sampleRate,s=new Float32Array(Math.floor(t.length*n));for(let o=0;o<s.length;o++)s[o]=t[Math.floor(o*(1/n))];t=s,this.sampleRate=A,this.sampleLoopStartIndex=Math.floor(this.sampleLoopStartIndex*n),this.sampleLoopEndIndex=Math.floor(this.sampleLoopEndIndex*n),this.sampleData=t}compressSample(A,t){if(!this.isCompressed)try{let n=this.getAudioData();(this.sampleRate<8e3||this.sampleRate>96e3)&&(this.resampleData(Si),n=this.getAudioData()),this.compressedData=t([n],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{H(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=239}}getAudioData(){return this.sampleData}};var Me=class{instrumentName="";instrumentZones=[];_useCount=0;get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;A<this.instrumentZones.length;A++)this.safeDeleteZone(A)&&A--}deleteInstrument(){this.instrumentZones.forEach(A=>A.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var xe=class{parentSoundBank;presetName="";program=0;bank=0;presetZones=[];foundSamplesAndGenerators=[];library=0;genre=0;morphology=0;constructor(A){this.parentSoundBank=A;for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[]}clearCache(){this.foundSamplesAndGenerators=[]}isDrumPreset(A,t=!1){let n=A&&this.parentSoundBank.isXGBank;return this.bank===128||n&&$A(this.bank)&&(this.bank!==126||t)}deletePreset(){this.presetZones.forEach(A=>A.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,t){for(let n=A;n<t+1;n++)for(let s=0;s<128;s++)this.getSamplesAndGenerators(n,s).forEach(o=>{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,t){let n=this.foundSamplesAndGenerators[A][t];if(n)return n;if(this.presetZones.length<1)return[];function s(B,m){return m>=B.min&&m<=B.max}function o(B,m){B.push(...m.filter(u=>!B.find(p=>p.generatorType===u.generatorType)))}function r(B,m){B.push(...m.filter(u=>!B.find(p=>z.isIdentical(u,p))))}let g=[],i=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],E=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[],c=this.presetZones[0].isGlobal?this.presetZones[0].keyRange:{min:0,max:127},h=this.presetZones[0].isGlobal?this.presetZones[0].velRange:{min:0,max:127};return this.presetZones.filter(B=>s(B.hasKeyRange?B.keyRange:c,A)&&s(B.hasVelRange?B.velRange:h,t)&&!B.isGlobal).forEach(B=>{if(B.instrument.instrumentZones.length<1)return;let m=B.generators,u=B.modulators,p=B.instrument.instrumentZones[0],R=p.isGlobal?[...p.generators]:[],D=p.isGlobal?[...p.modulators]:[],M=p.isGlobal?p.keyRange:{min:0,max:127},b=p.isGlobal?p.velRange:{min:0,max:127};B.instrument.instrumentZones.filter(C=>s(C.hasKeyRange?C.keyRange:M,A)&&s(C.hasVelRange?C.velRange:b,t)&&!C.isGlobal).forEach(C=>{let L=[...C.generators],J=[...C.modulators];o(m,i),o(L,R),r(u,E),r(J,D),r(J,this.parentSoundBank.defaultModulators);let EA=[...J];for(let tA=0;tA<u.length;tA++){let T=u[tA],AA=EA.findIndex(hA=>z.isIdentical(T,hA));AA!==-1?EA[AA]=EA[AA].sumTransform(T):EA.push(T)}g.push({instrumentGenerators:L,presetGenerators:m,modulators:EA,sample:C.sample,sampleID:C.generators.find(tA=>tA.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=g,g}};var Ne=class e{soundFontInfo={};presets=[];samples=[];instruments=[];defaultModulators=js.map(A=>z.copy(A));isXGBank=!1;constructor(A=void 0){A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundBanks(...A){let t=A.shift(),n=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(r=>r.bank===o.bank&&r.program===o.program)===void 0&&n.push(o)});return new e({presets:n,info:t.soundFontInfo})}static getDummySoundfontFile(){let A=new e,t=new Ge("Saw",44100,65,20,0,0,0,127);t.sampleData=new Float32Array(128);for(let E=0;E<128;E++)t.sampleData[E]=E/128*2-1;A.samples.push(t);let n=new KA;n.isGlobal=!0,n.generators.push(new U(a.initialAttenuation,375)),n.generators.push(new U(a.releaseVolEnv,-1e3)),n.generators.push(new U(a.sampleModes,1));let s=new KA;s.sample=t;let o=new KA;o.sample=t,o.generators.push(new U(a.fineTune,-9));let r=new Me;r.instrumentName="Saw Wave",r.instrumentZones.push(n),r.instrumentZones.push(s),r.instrumentZones.push(o),A.instruments.push(r);let g=new Re;g.instrument=r;let i=new xe(A);return i.presetName="Saw Wave",i.presetZones.push(g),A.presets.push(i),A.soundFontInfo.ifil="2.1",A.soundFontInfo.isng="EMU8000",A.soundFontInfo.INAM="Dummy",A._parseInternal(),A.write().buffer}_parseInternal(){this.isXGBank=!1;let A=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let t of this.presets)if($A(t.bank)&&(this.isXGBank=!0,!A.has(t.program))){this.isXGBank=!1,y(`%cThis bank is not valid XG. Preset %c${t.bank}:${t.program}%c is not a valid XG drum. XG mode will use presets on bank 128.`,I.info,I.value,I.info);break}}trimSoundBank(A){let t=this;function n(o,r){let g=0;for(let i=0;i<o.instrumentZones.length;i++){let E=o.instrumentZones[i];if(E.isGlobal)continue;let c=E.keyRange,h=E.velRange,Q=!1;for(let B of r)if(B.key>=c.min&&B.key<=c.max&&B.velocity>=h.min&&B.velocity<=h.max){Q=!0;break}Q||(y(`%c${E.sample.sampleName} %cremoved from %c${o.instrumentName}%c. Use count: %c${E.useCount-1}`,I.recognized,I.info,I.recognized,I.info,I.recognized),o.safeDeleteZone(i)&&(g++,i--,y(`%c${E.sample.sampleName} %cdeleted`,I.recognized,I.info)),E.sample.useCount<1&&t.deleteSample(E.sample))}return g}ie("%cTrimming soundfont...",I.info);let s=A.getUsedProgramsAndKeys(t);fA("%cModifying soundfont...",I.info),y("Detected keys for midi:",s);for(let o=0;o<t.presets.length;o++){let r=t.presets[o],g=r.bank+":"+r.program,i=s[g];if(i===void 0)y(`%cDeleting preset %c${r.presetName}%c and its zones`,I.info,I.recognized,I.info),t.deletePreset(r),o--;else{let E=[...i].map(h=>{let Q=h.split("-");return{key:parseInt(Q[0]),velocity:parseInt(Q[1])}});fA(`%cTrimming %c${r.presetName}`,I.info,I.recognized),y(`Keys for ${r.presetName}:`,E);let c=0;for(let h=0;h<r.presetZones.length;h++){let Q=r.presetZones[h];if(Q.isGlobal)continue;let B=Q.keyRange,m=Q.velRange,u=!1;for(let p of E)if(p.key>=B.min&&p.key<=B.max&&p.velocity>=m.min&&p.velocity<=m.max){u=!0;let R=n(Q.instrument,E);y(`%cTrimmed off %c${R}%c zones from %c${Q.instrument.instrumentName}`,I.info,I.recognized,I.info,I.recognized);break}u||(c++,r.deleteZone(h),Q.instrument.useCount<1&&t.deleteInstrument(Q.instrument),h--)}y(`%cTrimmed off %c${c}%c zones from %c${r.presetName}`,I.info,I.recognized,I.info,I.recognized),q()}}t.removeUnusedElements(),t.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${A.midiName}"
12
12
 
13
- `+t.soundFontInfo.ICMT,y("%cSoundfont modified!",I.recognized),q(),q()}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(t=>{t.isGlobal||t.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,t,n=!1){let s=A===128||n&&$A(A),o;if(s?o=this.presets.find(r=>r.bank===A&&r.isDrumPreset(n)&&r.program===t):o=this.presets.find(r=>r.bank===A&&r.program===t),o)return o;if(s&&n){let r=this.presets.find(g=>g.isDrumPreset(n)&&g.program===t);if(r)return r}}getPreset(A,t,n=!1){let s=A===128||n&&$A(A),o;return s?o=this.presets.find(r=>r.bank===A&&r.isDrumPreset(n)&&r.program===t):o=this.presets.find(r=>r.bank===A&&r.program===t),o||(s?(o=this.presets.find(r=>r.isDrumPreset(n)&&r.program===t),o||(o=this.presets.find(r=>r.isDrumPreset(n)))):o=this.presets.find(r=>r.program===t&&!r.isDrumPreset(n)),o&&H(`%cPreset ${A}.${t} not found. Replaced with %c${o.presetName} (${o.bank}.${o.program})`,I.warn,I.recognized),o||(H(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),o=this.presets[0]),o)}getPresetByName(A){let t=this.presets.find(n=>n.presetName===A);return t||(H("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}destroySoundBank(){delete this.presets,delete this.instruments,delete this.samples}};Ne.prototype.write=ko;Ne.prototype.writeDLS=Ho;function Yo(e){fA("%cLoading instruments...",I.info);for(let A=0;A<this.instrumentAmount;A++)this.readDLSInstrument(IA(e.chunkData));q()}var Qn=class extends xe{constructor(A,t,n){super(A),this.program=n&127;let s=t>>8&127,o=t&127;s>0?this.bank=s:this.bank=o,t>>31&&(this.bank=128),this.DLSInstrument=new Me,this.DLSInstrument.addUseCount();let g=new Re;g.instrument=this.DLSInstrument,this.presetZones=[g]}};function Jo(e){this.verifyHeader(e,"LIST"),this.verifyText($(e.chunkData,4),"ins ");let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(IA(e.chunkData));let t=A.find(B=>B.header==="insh");if(!t)throw q(),new Error("No instrument header!");let n=N(t.chunkData,4),s=N(t.chunkData,4),o=N(t.chunkData,4),r=new Qn(this,s,o),g="unnamedPreset",i=ZA(A,"INFO");if(i){let B=IA(i.chunkData);for(;B.header!=="INAM";)B=IA(i.chunkData);g=$(B.chunkData,B.chunkData.length).trim()}r.presetName=g,r.DLSInstrument.instrumentName=g,fA(`%cParsing %c"${g}"%c...`,I.info,I.recognized,I.info);let E=ZA(A,"lrgn");if(!E)throw q(),new Error("No region list!");let c=new KA;c.isGlobal=!0;let h=ZA(A,"lart"),Q=ZA(A,"lar2");(Q!==void 0||h!==void 0)&&this.readLart(h,Q,c),c.generators=c.generators.filter(B=>B.generatorValue!==X[B.generatorType].def),c.modulators.find(B=>B.modulatorDestination===a.reverbEffectsSend)===void 0&&c.modulators.push(z.copy(En)),c.modulators.find(B=>B.modulatorDestination===a.chorusEffectsSend)===void 0&&c.modulators.push(z.copy(hn)),r.DLSInstrument.instrumentZones.push(c);for(let B=0;B<n;B++){let m=IA(E.chunkData);this.verifyHeader(m,"LIST");let u=$(m.chunkData,4);u!=="rgn "&&u!=="rgn2"&&(q(),this.parsingError(`Invalid DLS region! Expected "rgn " or "rgn2" got "${u}"`));let p=this.readRegion(m);p&&r.DLSInstrument.instrumentZones.push(p)}this.presets.push(r),this.instruments.push(r.DLSInstrument),q()}function Ko(e){let A,t=!1;switch(e){default:case V.modLfo:case V.vibratoLfo:case V.coarseTune:case V.fineTune:case V.modEnv:return;case V.keyNum:A=j.noteOnKeyNum;break;case V.none:A=j.noController;break;case V.modulationWheel:A=S.modulationWheel,t=!0;break;case V.pan:A=S.pan,t=!0;break;case V.reverb:A=S.reverbDepth,t=!0;break;case V.chorus:A=S.chorusDepth,t=!0;break;case V.expression:A=S.expressionController,t=!0;break;case V.volume:A=S.mainVolume,t=!0;break;case V.velocity:A=j.noteOnVelocity;break;case V.polyPressure:A=j.polyPressure;break;case V.channelPressure:A=j.channelPressure;break;case V.pitchWheel:A=j.pitchWheel;break;case V.pitchWheelRange:A=j.pitchWheelRange;break}if(A===void 0)throw new Error(`Unknown DLS Source: ${e}`);return{enum:A,isCC:t}}function Di(e,A){switch(e){default:case F.none:return;case F.pan:return a.pan;case F.gain:return{gen:a.initialAttenuation,newAmount:A*-1};case F.pitch:return a.fineTune;case F.keyNum:return a.overridingRootKey;case F.volEnvDelay:return a.delayVolEnv;case F.volEnvAttack:return a.attackVolEnv;case F.volEnvHold:return a.holdVolEnv;case F.volEnvDecay:return a.decayVolEnv;case F.volEnvSustain:return{gen:a.sustainVolEnv,newAmount:1e3-A};case F.volEnvRelease:return a.releaseVolEnv;case F.modEnvDelay:return a.delayModEnv;case F.modEnvAttack:return a.attackModEnv;case F.modEnvHold:return a.holdModEnv;case F.modEnvDecay:return a.decayModEnv;case F.modEnvSustain:return{gen:a.sustainModEnv,newAmount:(1e3-A)/10};case F.modEnvRelease:return a.releaseModEnv;case F.filterCutoff:return a.initialFilterFc;case F.filterQ:return a.initialFilterQ;case F.chorusSend:return a.chorusEffectsSend;case F.reverbSend:return a.reverbEffectsSend;case F.modLfoFreq:return a.freqModLFO;case F.modLfoDelay:return a.delayModLFO;case F.vibLfoFreq:return a.freqVibLFO;case F.vibLfoDelay:return a.delayVibLFO}}function ki(e,A){return e===V.vibratoLfo&&A===F.pitch?a.vibLfoToPitch:e===V.modLfo&&A===F.pitch?a.modLfoToPitch:e===V.modLfo&&A===F.filterCutoff?a.modLfoToFilterFc:e===V.modLfo&&A===F.gain?a.modLfoToVolume:e===V.modEnv&&A===F.filterCutoff?a.modEnvToFilterFc:e===V.modEnv&&A===F.pitch?a.modEnvToPitch:void 0}function Oo(e,A,t,n,s){let o=ki(e,t),r,g,i=!1,E=!1,c=s;if(o===void 0){let R=Di(t,s);if(R===void 0){H(`Invalid destination: ${t}`);return}if(r=R,R.newAmount!==void 0&&(c=R.newAmount,r=R.gen),g=Ko(e),g===void 0){H(`Invalid source: ${e}`);return}}else r=o,i=!0,g={enum:j.noController,isCC:!1},E=!0;let h=Ko(A);if(h===void 0){H(`Invalid control: ${A}`);return}let Q;if(E)Q=0;else{let R=n&15,D=n>>10&15;D===GA.linear&&R!==GA.linear&&(D=R);let M=n>>14&1,b=n>>15&1;r===a.initialAttenuation&&s<0&&(b=1),Q=Ie(D,M,b,g.isCC,g.enum)}r===a.initialAttenuation&&(c=Math.max(960,Math.min(0,c)));let B=n>>4&15,m=n>>8&1,u=n>>9&1,p=Ie(B,m,u,h.isCC,h.enum);if(i){let R=p;p=Q,Q=R}return new z(Q,p,r,c,0)}function as(e,A){let t=e.chunkData,n=[],s=[];N(t,4);let o=N(t,4);for(let r=0;r<o;r++){let g=N(t,2),i=N(t,2),E=N(t,2),c=N(t,2),Q=(N(t,4)|0)>>16;if(g===0&&i===0&&c===0){let B;switch(E){case F.pan:B=new U(a.pan,Q);break;case F.gain:B=new U(a.initialAttenuation,-Q*10/.4);break;case F.filterCutoff:B=new U(a.initialFilterFc,Q);break;case F.filterQ:B=new U(a.initialFilterQ,Q);break;case F.modLfoFreq:B=new U(a.freqModLFO,Q);break;case F.modLfoDelay:B=new U(a.delayModLFO,Q);break;case F.vibLfoFreq:B=new U(a.freqVibLFO,Q);break;case F.vibLfoDelay:B=new U(a.delayVibLFO,Q);break;case F.volEnvDelay:B=new U(a.delayVolEnv,Q);break;case F.volEnvAttack:B=new U(a.attackVolEnv,Q);break;case F.volEnvHold:B=new U(a.holdVolEnv,Q,!1);break;case F.volEnvDecay:B=new U(a.decayVolEnv,Q,!1);break;case F.volEnvRelease:B=new U(a.releaseVolEnv,Q);break;case F.volEnvSustain:let m=1e3-Q;B=new U(a.sustainVolEnv,m);break;case F.modEnvDelay:B=new U(a.delayModEnv,Q);break;case F.modEnvAttack:B=new U(a.attackModEnv,Q);break;case F.modEnvHold:B=new U(a.holdModEnv,Q,!1);break;case F.modEnvDecay:B=new U(a.decayModEnv,Q,!1);break;case F.modEnvRelease:B=new U(a.releaseModEnv,Q);break;case F.modEnvSustain:let u=1e3-Q;B=new U(a.sustainModEnv,u);break;case F.reverbSend:B=new U(a.reverbEffectsSend,Q);break;case F.chorusSend:B=new U(a.chorusEffectsSend,Q);break;case F.pitch:let p=Math.floor(Q/100),R=Math.floor(Q-p*100);B=new U(a.fineTune,R),n.push(new U(a.coarseTune,p));break}B&&n.push(B)}else{let B=!0,m=(u,p,R)=>{let D=u/-128;if(n.push(new U(p,D)),D<=120){let M=Math.round(.46875*u);n.forEach(b=>{b.generatorType===R&&(b.generatorValue+=M)})}};if(i===V.none?g===V.modLfo&&E===F.pitch?n.push(new U(a.modLfoToPitch,Q)):g===V.modLfo&&E===F.gain?n.push(new U(a.modLfoToVolume,Q)):g===V.modLfo&&E===F.filterCutoff?n.push(new U(a.modLfoToFilterFc,Q)):g===V.vibratoLfo&&E===F.pitch?n.push(new U(a.vibLfoToPitch,Q)):g===V.modEnv&&E===F.pitch?n.push(new U(a.modEnvToPitch,Q)):g===V.modEnv&&E===F.filterCutoff?n.push(new U(a.modEnvToFilterFc,Q)):g===V.keyNum&&E===F.pitch?n.push(new U(a.scaleTuning,Q/128)):g===V.keyNum&&E===F.volEnvHold?m(Q,a.keyNumToVolEnvHold,a.holdVolEnv):g===V.keyNum&&E===F.volEnvDecay?m(Q,a.keyNumToVolEnvDecay,a.decayVolEnv):g===V.keyNum&&E===F.modEnvHold?m(Q,a.keyNumToModEnvHold,a.holdModEnv):g===V.keyNum&&E===F.modEnvDecay?m(Q,a.keyNumToModEnvDecay,a.decayModEnv):B=!1:B=!1,B===!1){let u=Oo(g,i,E,c,Q);u?(s.push(u),y("%cSucceeded converting to SF2 Modulator!",I.recognized)):H("Failed converting to SF2 Modulator!")}}}return A&&s.push(z.copy(Bn),z.copy(cn)),{modulators:s,generators:n}}function qo(e,A,t){if(e)for(;e.chunkData.currentIndex<e.chunkData.length;){let n=IA(e.chunkData);this.verifyHeader(n,"art1","art2");let s=as(n,!0);t.generators.push(...s.generators),t.modulators.push(...s.modulators)}if(A)for(;A.chunkData.currentIndex<A.chunkData.length;){let n=IA(A.chunkData);this.verifyHeader(n,"art2","art1");let s=as(n,!1);t.generators.push(...s.generators),t.modulators.push(...s.modulators)}}var dn=class extends KA{constructor(A,t){super(),this.keyRange=A,this.velRange=t,this.isGlobal=!0}setWavesample(A,t,n,s,o,r,g){t!==0&&this.generators.push(new U(a.sampleModes,t)),this.generators.push(new U(a.initialAttenuation,A)),this.isGlobal=!1,g-=o.samplePitchCorrection;let i=Math.trunc(g/100);i!==0&&this.generators.push(new U(a.coarseTune,i));let E=g-i*100;if(E!==0&&this.generators.push(new U(a.fineTune,E)),t!==0){let c=n.start-o.sampleLoopStartIndex,h=n.end-o.sampleLoopEndIndex;if(c!==0){let Q=c%32768;this.generators.push(new U(a.startloopAddrsOffset,Q));let B=Math.trunc(c/32768);B!==0&&this.generators.push(new U(a.startloopAddrsCoarseOffset,B))}if(h!==0){let Q=h%32768;this.generators.push(new U(a.endloopAddrsOffset,Q));let B=Math.trunc(h/32768);B!==0&&this.generators.push(new U(a.endloopAddrsCoarseOffset,B))}}s!==o.samplePitch&&this.generators.push(new U(a.overridingRootKey,s)),this.generators.push(new U(a.sampleID,r)),this.sample=o,o.useCount++}};function Po(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(IA(e.chunkData));let t=A.find(J=>J.header==="rgnh"),n=N(t.chunkData,2),s=N(t.chunkData,2),o=N(t.chunkData,2),r=N(t.chunkData,2);o===0&&r===0&&(r=127,o=0);let g=new dn({min:n,max:s},{min:o,max:r});N(t.chunkData,2);let i=N(t.chunkData,2);i!==0&&g.generators.push(new U(a.exclusiveClass,i));let E=ZA(A,"lart"),c=ZA(A,"lar2");this.readLart(E,c,g),g.isGlobal=!1;let h=A.find(J=>J.header==="wsmp");N(h.chunkData,4);let Q=N(h.chunkData,2),B=Ke(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),u=(N(h.chunkData,4)|0)/-655360;N(h.chunkData,4);let p=N(h.chunkData,4),R,D={start:0,end:0};if(p===0)R=0;else{N(h.chunkData,4),N(h.chunkData,4)===0?R=1:R=3,D.start=N(h.chunkData,4);let EA=N(h.chunkData,4);D.end=D.start+EA}let M=A.find(J=>J.header==="wlnk");if(M===void 0)return;N(M.chunkData,2),N(M.chunkData,2),N(M.chunkData,4);let b=N(M.chunkData,4),G=this.samples[b];if(G===void 0)throw new Error("Invalid sample ID!");let L=(u||G.sampleDbAttenuation)*10/.4;return g.setWavesample(L,R,D,Q,G,b,B),g}var fn=class extends Ge{sampleDbAttenuation;sampleData;constructor(A,t,n,s,o,r,g,i){super(A,t,n,s,0,1,o,r),this.sampleData=g,this.sampleDbAttenuation=i}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data?? This shouldn't happen!!");return this.compressedData}return super.getRawData()}};var Vo={PCM:1,ALAW:6};function wi(e,A){let t=Math.pow(2,A*8-1),n=Math.pow(2,A*8),s,o=!1;A===1?(s=255,o=!0):s=t;let r=e.size/A,g=new Float32Array(r);for(let i=0;i<g.length;i++){let E=N(e.chunkData,A);o?g[i]=E/s-.5:(E>=t&&(E-=n),g[i]=E/s)}return g}function Fi(e,A){let t=e.size/A,n=new Float32Array(t);for(let s=0;s<n.length;s++){let o=N(e.chunkData,A),r=o^85;r&=127;let g=r>>4,i=r&15;g>0&&(i+=16),i=(i<<4)+8,g>1&&(i=i<<g-1);let E=o>127?i:-i;n[s]=E/32678}return n}function Zo(e){fA("%cLoading Wave samples...",I.recognized);let A=0;for(;e.chunkData.currentIndex<e.chunkData.length;){let t=IA(e.chunkData);this.verifyHeader(t,"LIST"),this.verifyText($(t.chunkData,4),"wave");let n=[];for(;t.chunkData.currentIndex<t.chunkData.length;)n.push(IA(t.chunkData));let s=n.find(G=>G.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let o=N(s.chunkData,2),r=N(s.chunkData,2);if(r!==1)throw new Error(`Only mono samples are supported. Fmt reports ${r} channels`);let g=N(s.chunkData,4);N(s.chunkData,4),N(s.chunkData,2);let E=N(s.chunkData,2)/8,c=!1,h=n.find(G=>G.header==="data");h||this.parsingError("No data chunk in the WAVE chunk!");let Q;switch(o){default:c=!0,Q=new Float32Array(h.size/E);break;case Vo.PCM:Q=wi(h,E);break;case Vo.ALAW:Q=Fi(h,E);break}let B=ZA(n,"INFO"),m=`Unnamed ${A}`;if(B){let G=IA(B.chunkData);for(;G.header!=="INAM"&&B.chunkData.currentIndex<B.chunkData.length;)G=IA(B.chunkData);G.header==="INAM"&&(m=$(G.chunkData,G.size).trim())}let u=60,p=0,R=0,D=Q.length-1,M=0,b=n.find(G=>G.header==="wsmp");if(b){N(b.chunkData,4),u=N(b.chunkData,2),p=Ke(b.chunkData[b.chunkData.currentIndex++],b.chunkData[b.chunkData.currentIndex++]);let G=Math.trunc(p/100);if(u+=G,p-=G*100,M=(N(b.chunkData,4)|0)/-655360,N(b.chunkData,4),N(b.chunkData,4)===1){N(b.chunkData,8),R=N(b.chunkData,4);let J=N(b.chunkData,4);D=R+J}}else H("No wsmp chunk in wave... using sane defaults.");c&&console.error(`Failed to load '${m}': Unsupported format: (${o})`),this.samples.push(new fn(m,g,u,p,R,D,Q,M)),A++,y(`%cLoaded sample %c${m}`,I.info,I.recognized)}q()}var be=class extends Ne{constructor(A){super(),this.dataArray=new x(A),ie("%cParsing DLS...",I.info),this.dataArray||(q(),this.parsingError("No data provided!"));let t=IA(this.dataArray,!1);this.verifyHeader(t,"riff"),this.verifyText($(this.dataArray,4).toLowerCase(),"dls ");let n=[];for(;this.dataArray.currentIndex<this.dataArray.length;)n.push(IA(this.dataArray));this.soundFontInfo.ifil="2.1",this.soundFontInfo.isng="EMU8000",this.soundFontInfo.INAM="Unnamed DLS",this.soundFontInfo.IENG="Unknown",this.soundFontInfo.IPRD="SpessaSynth DLS",this.soundFontInfo.ICRD=new Date().toDateString();let s=ZA(n,"INFO");if(s)for(;s.chunkData.currentIndex<s.chunkData.length;){let i=IA(s.chunkData);this.soundFontInfo[i.header]=$(i.chunkData,i.size)}this.soundFontInfo.ICMT=this.soundFontInfo.ICMT||"(No description)",this.soundFontInfo.ISBJ&&(this.soundFontInfo.ICMT+=`
13
+ `+t.soundFontInfo.ICMT,y("%cSoundfont modified!",I.recognized),q(),q()}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(t=>{t.isGlobal||t.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,t,n=!1){let s=A===128||n&&$A(A),o;if(s?o=this.presets.find(r=>r.bank===A&&r.isDrumPreset(n)&&r.program===t):o=this.presets.find(r=>r.bank===A&&r.program===t),o)return o;if(s&&n){let r=this.presets.find(g=>g.isDrumPreset(n)&&g.program===t);if(r)return r}}getPreset(A,t,n=!1){let s=A===128||n&&$A(A),o;return s?o=this.presets.find(r=>r.bank===A&&r.isDrumPreset(n)&&r.program===t):o=this.presets.find(r=>r.bank===A&&r.program===t),o||(s?(o=this.presets.find(r=>r.isDrumPreset(n)&&r.program===t),o||(o=this.presets.find(r=>r.isDrumPreset(n)))):o=this.presets.find(r=>r.program===t&&!r.isDrumPreset(n)),o&&H(`%cPreset ${A}.${t} not found. Replaced with %c${o.presetName} (${o.bank}.${o.program})`,I.warn,I.recognized),o||(H(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),o=this.presets[0]),o)}getPresetByName(A){let t=this.presets.find(n=>n.presetName===A);return t||(H("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}destroySoundBank(){delete this.presets,delete this.instruments,delete this.samples}clearCache(){this.presets.forEach(A=>A.clearCache())}};Ne.prototype.write=ko;Ne.prototype.writeDLS=Ho;function Yo(e){fA("%cLoading instruments...",I.info);for(let A=0;A<this.instrumentAmount;A++)this.readDLSInstrument(IA(e.chunkData));q()}var Qn=class extends xe{constructor(A,t,n){super(A),this.program=n&127;let s=t>>8&127,o=t&127;s>0?this.bank=s:this.bank=o,t>>31&&(this.bank=128),this.DLSInstrument=new Me,this.DLSInstrument.addUseCount();let g=new Re;g.instrument=this.DLSInstrument,this.presetZones=[g]}};function Jo(e){this.verifyHeader(e,"LIST"),this.verifyText($(e.chunkData,4),"ins ");let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(IA(e.chunkData));let t=A.find(B=>B.header==="insh");if(!t)throw q(),new Error("No instrument header!");let n=N(t.chunkData,4),s=N(t.chunkData,4),o=N(t.chunkData,4),r=new Qn(this,s,o),g="unnamedPreset",i=ZA(A,"INFO");if(i){let B=IA(i.chunkData);for(;B.header!=="INAM";)B=IA(i.chunkData);g=$(B.chunkData,B.chunkData.length).trim()}r.presetName=g,r.DLSInstrument.instrumentName=g,fA(`%cParsing %c"${g}"%c...`,I.info,I.recognized,I.info);let E=ZA(A,"lrgn");if(!E)throw q(),new Error("No region list!");let c=new KA;c.isGlobal=!0;let h=ZA(A,"lart"),Q=ZA(A,"lar2");(Q!==void 0||h!==void 0)&&this.readLart(h,Q,c),c.generators=c.generators.filter(B=>B.generatorValue!==X[B.generatorType].def),c.modulators.find(B=>B.modulatorDestination===a.reverbEffectsSend)===void 0&&c.modulators.push(z.copy(En)),c.modulators.find(B=>B.modulatorDestination===a.chorusEffectsSend)===void 0&&c.modulators.push(z.copy(hn)),r.DLSInstrument.instrumentZones.push(c);for(let B=0;B<n;B++){let m=IA(E.chunkData);this.verifyHeader(m,"LIST");let u=$(m.chunkData,4);u!=="rgn "&&u!=="rgn2"&&(q(),this.parsingError(`Invalid DLS region! Expected "rgn " or "rgn2" got "${u}"`));let p=this.readRegion(m);p&&r.DLSInstrument.instrumentZones.push(p)}this.presets.push(r),this.instruments.push(r.DLSInstrument),q()}function Ko(e){let A,t=!1;switch(e){default:case V.modLfo:case V.vibratoLfo:case V.coarseTune:case V.fineTune:case V.modEnv:return;case V.keyNum:A=j.noteOnKeyNum;break;case V.none:A=j.noController;break;case V.modulationWheel:A=S.modulationWheel,t=!0;break;case V.pan:A=S.pan,t=!0;break;case V.reverb:A=S.reverbDepth,t=!0;break;case V.chorus:A=S.chorusDepth,t=!0;break;case V.expression:A=S.expressionController,t=!0;break;case V.volume:A=S.mainVolume,t=!0;break;case V.velocity:A=j.noteOnVelocity;break;case V.polyPressure:A=j.polyPressure;break;case V.channelPressure:A=j.channelPressure;break;case V.pitchWheel:A=j.pitchWheel;break;case V.pitchWheelRange:A=j.pitchWheelRange;break}if(A===void 0)throw new Error(`Unknown DLS Source: ${e}`);return{enum:A,isCC:t}}function Di(e,A){switch(e){default:case F.none:return;case F.pan:return a.pan;case F.gain:return{gen:a.initialAttenuation,newAmount:A*-1};case F.pitch:return a.fineTune;case F.keyNum:return a.overridingRootKey;case F.volEnvDelay:return a.delayVolEnv;case F.volEnvAttack:return a.attackVolEnv;case F.volEnvHold:return a.holdVolEnv;case F.volEnvDecay:return a.decayVolEnv;case F.volEnvSustain:return{gen:a.sustainVolEnv,newAmount:1e3-A};case F.volEnvRelease:return a.releaseVolEnv;case F.modEnvDelay:return a.delayModEnv;case F.modEnvAttack:return a.attackModEnv;case F.modEnvHold:return a.holdModEnv;case F.modEnvDecay:return a.decayModEnv;case F.modEnvSustain:return{gen:a.sustainModEnv,newAmount:(1e3-A)/10};case F.modEnvRelease:return a.releaseModEnv;case F.filterCutoff:return a.initialFilterFc;case F.filterQ:return a.initialFilterQ;case F.chorusSend:return a.chorusEffectsSend;case F.reverbSend:return a.reverbEffectsSend;case F.modLfoFreq:return a.freqModLFO;case F.modLfoDelay:return a.delayModLFO;case F.vibLfoFreq:return a.freqVibLFO;case F.vibLfoDelay:return a.delayVibLFO}}function ki(e,A){return e===V.vibratoLfo&&A===F.pitch?a.vibLfoToPitch:e===V.modLfo&&A===F.pitch?a.modLfoToPitch:e===V.modLfo&&A===F.filterCutoff?a.modLfoToFilterFc:e===V.modLfo&&A===F.gain?a.modLfoToVolume:e===V.modEnv&&A===F.filterCutoff?a.modEnvToFilterFc:e===V.modEnv&&A===F.pitch?a.modEnvToPitch:void 0}function Oo(e,A,t,n,s){let o=ki(e,t),r,g,i=!1,E=!1,c=s;if(o===void 0){let R=Di(t,s);if(R===void 0){H(`Invalid destination: ${t}`);return}if(r=R,R.newAmount!==void 0&&(c=R.newAmount,r=R.gen),g=Ko(e),g===void 0){H(`Invalid source: ${e}`);return}}else r=o,i=!0,g={enum:j.noController,isCC:!1},E=!0;let h=Ko(A);if(h===void 0){H(`Invalid control: ${A}`);return}let Q;if(E)Q=0;else{let R=n&15,D=n>>10&15;D===GA.linear&&R!==GA.linear&&(D=R);let M=n>>14&1,b=n>>15&1;r===a.initialAttenuation&&s<0&&(b=1),Q=Ie(D,M,b,g.isCC,g.enum)}r===a.initialAttenuation&&(c=Math.max(960,Math.min(0,c)));let B=n>>4&15,m=n>>8&1,u=n>>9&1,p=Ie(B,m,u,h.isCC,h.enum);if(i){let R=p;p=Q,Q=R}return new z(Q,p,r,c,0)}function as(e,A){let t=e.chunkData,n=[],s=[];N(t,4);let o=N(t,4);for(let r=0;r<o;r++){let g=N(t,2),i=N(t,2),E=N(t,2),c=N(t,2),Q=(N(t,4)|0)>>16;if(g===0&&i===0&&c===0){let B;switch(E){case F.pan:B=new U(a.pan,Q);break;case F.gain:B=new U(a.initialAttenuation,-Q*10/.4);break;case F.filterCutoff:B=new U(a.initialFilterFc,Q);break;case F.filterQ:B=new U(a.initialFilterQ,Q);break;case F.modLfoFreq:B=new U(a.freqModLFO,Q);break;case F.modLfoDelay:B=new U(a.delayModLFO,Q);break;case F.vibLfoFreq:B=new U(a.freqVibLFO,Q);break;case F.vibLfoDelay:B=new U(a.delayVibLFO,Q);break;case F.volEnvDelay:B=new U(a.delayVolEnv,Q);break;case F.volEnvAttack:B=new U(a.attackVolEnv,Q);break;case F.volEnvHold:B=new U(a.holdVolEnv,Q,!1);break;case F.volEnvDecay:B=new U(a.decayVolEnv,Q,!1);break;case F.volEnvRelease:B=new U(a.releaseVolEnv,Q);break;case F.volEnvSustain:let m=1e3-Q;B=new U(a.sustainVolEnv,m);break;case F.modEnvDelay:B=new U(a.delayModEnv,Q);break;case F.modEnvAttack:B=new U(a.attackModEnv,Q);break;case F.modEnvHold:B=new U(a.holdModEnv,Q,!1);break;case F.modEnvDecay:B=new U(a.decayModEnv,Q,!1);break;case F.modEnvRelease:B=new U(a.releaseModEnv,Q);break;case F.modEnvSustain:let u=1e3-Q;B=new U(a.sustainModEnv,u);break;case F.reverbSend:B=new U(a.reverbEffectsSend,Q);break;case F.chorusSend:B=new U(a.chorusEffectsSend,Q);break;case F.pitch:let p=Math.floor(Q/100),R=Math.floor(Q-p*100);B=new U(a.fineTune,R),n.push(new U(a.coarseTune,p));break}B&&n.push(B)}else{let B=!0,m=(u,p,R)=>{let D=u/-128;if(n.push(new U(p,D)),D<=120){let M=Math.round(.46875*u);n.forEach(b=>{b.generatorType===R&&(b.generatorValue+=M)})}};if(i===V.none?g===V.modLfo&&E===F.pitch?n.push(new U(a.modLfoToPitch,Q)):g===V.modLfo&&E===F.gain?n.push(new U(a.modLfoToVolume,Q)):g===V.modLfo&&E===F.filterCutoff?n.push(new U(a.modLfoToFilterFc,Q)):g===V.vibratoLfo&&E===F.pitch?n.push(new U(a.vibLfoToPitch,Q)):g===V.modEnv&&E===F.pitch?n.push(new U(a.modEnvToPitch,Q)):g===V.modEnv&&E===F.filterCutoff?n.push(new U(a.modEnvToFilterFc,Q)):g===V.keyNum&&E===F.pitch?n.push(new U(a.scaleTuning,Q/128)):g===V.keyNum&&E===F.volEnvHold?m(Q,a.keyNumToVolEnvHold,a.holdVolEnv):g===V.keyNum&&E===F.volEnvDecay?m(Q,a.keyNumToVolEnvDecay,a.decayVolEnv):g===V.keyNum&&E===F.modEnvHold?m(Q,a.keyNumToModEnvHold,a.holdModEnv):g===V.keyNum&&E===F.modEnvDecay?m(Q,a.keyNumToModEnvDecay,a.decayModEnv):B=!1:B=!1,B===!1){let u=Oo(g,i,E,c,Q);u?(s.push(u),y("%cSucceeded converting to SF2 Modulator!",I.recognized)):H("Failed converting to SF2 Modulator!")}}}return A&&s.push(z.copy(Bn),z.copy(cn)),{modulators:s,generators:n}}function qo(e,A,t){if(e)for(;e.chunkData.currentIndex<e.chunkData.length;){let n=IA(e.chunkData);this.verifyHeader(n,"art1","art2");let s=as(n,!0);t.generators.push(...s.generators),t.modulators.push(...s.modulators)}if(A)for(;A.chunkData.currentIndex<A.chunkData.length;){let n=IA(A.chunkData);this.verifyHeader(n,"art2","art1");let s=as(n,!1);t.generators.push(...s.generators),t.modulators.push(...s.modulators)}}var dn=class extends KA{constructor(A,t){super(),this.keyRange=A,this.velRange=t,this.isGlobal=!0}setWavesample(A,t,n,s,o,r,g){t!==0&&this.generators.push(new U(a.sampleModes,t)),this.generators.push(new U(a.initialAttenuation,A)),this.isGlobal=!1,g-=o.samplePitchCorrection;let i=Math.trunc(g/100);i!==0&&this.generators.push(new U(a.coarseTune,i));let E=g-i*100;if(E!==0&&this.generators.push(new U(a.fineTune,E)),t!==0){let c=n.start-o.sampleLoopStartIndex,h=n.end-o.sampleLoopEndIndex;if(c!==0){let Q=c%32768;this.generators.push(new U(a.startloopAddrsOffset,Q));let B=Math.trunc(c/32768);B!==0&&this.generators.push(new U(a.startloopAddrsCoarseOffset,B))}if(h!==0){let Q=h%32768;this.generators.push(new U(a.endloopAddrsOffset,Q));let B=Math.trunc(h/32768);B!==0&&this.generators.push(new U(a.endloopAddrsCoarseOffset,B))}}s!==o.samplePitch&&this.generators.push(new U(a.overridingRootKey,s)),this.generators.push(new U(a.sampleID,r)),this.sample=o,o.useCount++}};function Po(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(IA(e.chunkData));let t=A.find(J=>J.header==="rgnh"),n=N(t.chunkData,2),s=N(t.chunkData,2),o=N(t.chunkData,2),r=N(t.chunkData,2);o===0&&r===0&&(r=127,o=0);let g=new dn({min:n,max:s},{min:o,max:r});N(t.chunkData,2);let i=N(t.chunkData,2);i!==0&&g.generators.push(new U(a.exclusiveClass,i));let E=ZA(A,"lart"),c=ZA(A,"lar2");this.readLart(E,c,g),g.isGlobal=!1;let h=A.find(J=>J.header==="wsmp");N(h.chunkData,4);let Q=N(h.chunkData,2),B=Ke(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),u=(N(h.chunkData,4)|0)/-655360;N(h.chunkData,4);let p=N(h.chunkData,4),R,D={start:0,end:0};if(p===0)R=0;else{N(h.chunkData,4),N(h.chunkData,4)===0?R=1:R=3,D.start=N(h.chunkData,4);let EA=N(h.chunkData,4);D.end=D.start+EA}let M=A.find(J=>J.header==="wlnk");if(M===void 0)return;N(M.chunkData,2),N(M.chunkData,2),N(M.chunkData,4);let b=N(M.chunkData,4),G=this.samples[b];if(G===void 0)throw new Error("Invalid sample ID!");let L=(u||G.sampleDbAttenuation)*10/.4;return g.setWavesample(L,R,D,Q,G,b,B),g}var fn=class extends Ge{sampleDbAttenuation;sampleData;constructor(A,t,n,s,o,r,g,i){super(A,t,n,s,0,1,o,r),this.sampleData=g,this.sampleDbAttenuation=i}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data?? This shouldn't happen!!");return this.compressedData}return super.getRawData()}};var Vo={PCM:1,ALAW:6};function wi(e,A){let t=Math.pow(2,A*8-1),n=Math.pow(2,A*8),s,o=!1;A===1?(s=255,o=!0):s=t;let r=e.size/A,g=new Float32Array(r);for(let i=0;i<g.length;i++){let E=N(e.chunkData,A);o?g[i]=E/s-.5:(E>=t&&(E-=n),g[i]=E/s)}return g}function Fi(e,A){let t=e.size/A,n=new Float32Array(t);for(let s=0;s<n.length;s++){let o=N(e.chunkData,A),r=o^85;r&=127;let g=r>>4,i=r&15;g>0&&(i+=16),i=(i<<4)+8,g>1&&(i=i<<g-1);let E=o>127?i:-i;n[s]=E/32678}return n}function Zo(e){fA("%cLoading Wave samples...",I.recognized);let A=0;for(;e.chunkData.currentIndex<e.chunkData.length;){let t=IA(e.chunkData);this.verifyHeader(t,"LIST"),this.verifyText($(t.chunkData,4),"wave");let n=[];for(;t.chunkData.currentIndex<t.chunkData.length;)n.push(IA(t.chunkData));let s=n.find(G=>G.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let o=N(s.chunkData,2),r=N(s.chunkData,2);if(r!==1)throw new Error(`Only mono samples are supported. Fmt reports ${r} channels`);let g=N(s.chunkData,4);N(s.chunkData,4),N(s.chunkData,2);let E=N(s.chunkData,2)/8,c=!1,h=n.find(G=>G.header==="data");h||this.parsingError("No data chunk in the WAVE chunk!");let Q;switch(o){default:c=!0,Q=new Float32Array(h.size/E);break;case Vo.PCM:Q=wi(h,E);break;case Vo.ALAW:Q=Fi(h,E);break}let B=ZA(n,"INFO"),m=`Unnamed ${A}`;if(B){let G=IA(B.chunkData);for(;G.header!=="INAM"&&B.chunkData.currentIndex<B.chunkData.length;)G=IA(B.chunkData);G.header==="INAM"&&(m=$(G.chunkData,G.size).trim())}let u=60,p=0,R=0,D=Q.length-1,M=0,b=n.find(G=>G.header==="wsmp");if(b){N(b.chunkData,4),u=N(b.chunkData,2),p=Ke(b.chunkData[b.chunkData.currentIndex++],b.chunkData[b.chunkData.currentIndex++]);let G=Math.trunc(p/100);if(u+=G,p-=G*100,M=(N(b.chunkData,4)|0)/-655360,N(b.chunkData,4),N(b.chunkData,4)===1){N(b.chunkData,8),R=N(b.chunkData,4);let J=N(b.chunkData,4);D=R+J}}else H("No wsmp chunk in wave... using sane defaults.");c&&console.error(`Failed to load '${m}': Unsupported format: (${o})`),this.samples.push(new fn(m,g,u,p,R,D,Q,M)),A++,y(`%cLoaded sample %c${m}`,I.info,I.recognized)}q()}var be=class extends Ne{constructor(A){super(),this.dataArray=new x(A),ie("%cParsing DLS...",I.info),this.dataArray||(q(),this.parsingError("No data provided!"));let t=IA(this.dataArray,!1);this.verifyHeader(t,"riff"),this.verifyText($(this.dataArray,4).toLowerCase(),"dls ");let n=[];for(;this.dataArray.currentIndex<this.dataArray.length;)n.push(IA(this.dataArray));this.soundFontInfo.ifil="2.1",this.soundFontInfo.isng="EMU8000",this.soundFontInfo.INAM="Unnamed DLS",this.soundFontInfo.IENG="Unknown",this.soundFontInfo.IPRD="SpessaSynth DLS",this.soundFontInfo.ICRD=new Date().toDateString();let s=ZA(n,"INFO");if(s)for(;s.chunkData.currentIndex<s.chunkData.length;){let i=IA(s.chunkData);this.soundFontInfo[i.header]=$(i.chunkData,i.size)}this.soundFontInfo.ICMT=this.soundFontInfo.ICMT||"(No description)",this.soundFontInfo.ISBJ&&(this.soundFontInfo.ICMT+=`
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
- `)||""),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(`
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].actualBank>=0){let E=s[i];E.program!==-1?(this.synth.controllerChange(i,S.bankSelect,E.actualBank),this.synth.programChange(i,E.program)):this.synth.controllerChange(i,S.bankSelect,E.bank)}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(`
21
21
  `," ")),this.RMIDInfo.IALB&&!this.RMIDInfo.IPRD&&(this.RMIDInfo.IPRD=this.RMIDInfo.IALB),this.RMIDInfo.IPRD&&!this.RMIDInfo.IALB&&(this.RMIDInfo.IALB=this.RMIDInfo.IPRD),this.bankOffset=1,this.RMIDInfo[mA.bankOffset]&&(this.bankOffset=N(this.RMIDInfo[mA.bankOffset],2))}}this.isDLSRMIDI&&(this.bankOffset=0),this.embeddedSoundFont===void 0&&(this.bankOffset=0)}else o==="XMF_"?s=jr(this,n):s=n;let r=this._readMIDIChunk(s);if(r.type!=="MThd")throw q(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${r.type}"`);if(r.size!==6)throw q(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${r.size}`);this.format=OA(r.data,2),this.tracksAmount=OA(r.data,2),this.timeDivision=OA(r.data,2);for(let g=0;g<this.tracksAmount;g++){let i=[],E=this._readMIDIChunk(s);if(E.type!=="MTrk")throw q(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${E.type}"`);let c,h=0;for(this.format===2&&g>0&&(h+=this.tracks[g-1][this.tracks[g-1].length-1].ticks);E.data.currentIndex<E.size;){h+=uA(E.data);let Q=E.data[E.data.currentIndex],B;if(c!==void 0&&Q<128)B=c;else{if(c===void 0&&Q<128)throw q(),new SyntaxError(`Unexpected byte with no running byte. (${Q})`);B=E.data[E.data.currentIndex++]}let m=Ps(B),u;switch(m){case-1:u=0;break;case-2:B=E.data[E.data.currentIndex++],u=uA(E.data);break;case-3:u=uA(E.data);break;default:u=Vs[B>>4],c=B;break}let p=new x(u);p.set(E.data.slice(E.data.currentIndex,E.data.currentIndex+u),0);let R=new YA(h,B,p);i.push(R),E.data.currentIndex+=u}this.tracks.push(i),y(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,I.info,I.value,I.info,I.value)}y("%cAll tracks parsed correctly!",I.recognized),this._parseInternal(),q(),y(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}%c, total seconds time: %c${this.duration}`,I.info,I.recognized,I.info,I.recognized)}_readMIDIChunk(A){let t={};t.type=$(A,4),t.size=OA(A,4),t.data=new x(t.size);let n=A.slice(A.currentIndex,A.currentIndex+t.size);return t.data.set(n,0),A.currentIndex+=t.size,t}};var st={consoleColors:I,SpessaSynthInfo:y,SpessaSynthWarn:H,SpessaSynthGroupCollapsed:fA,SpessaSynthGroupEnd:q,readBytesAsUintBigEndian:OA,readLittleEndian:N,readBytesAsString:$,readVariableLengthQuantity:uA,inflateSync:Kt};var ps=st.consoleColors;var FA={midiMessage:0,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customCcChange:14,debugMessage:15,setMasterParameter:17,setDrums:18,transpose:19,highPerformanceMode:20,lockController:21,sequencerSpecific:22,requestSynthesizerSnapshot:23,setLogLevel:24,keyModifierManager:25,setEffectsGain:26,destroyWorklet:27},ee={channelPropertyChange:0,eventCall:1,masterParameterChange:2,sequencerSpecific:3,synthesizerSnapshot:4,isFullyInitialized:5,soundfontError:6};var $r="spessasynth-worklet-processor";var Rn={addMapping:0,deleteMapping:1,clearMappings:2};var qt={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var pt={backwards:0,forwards:1,shuffleOn:2,shuffleOff:3,index:4},te={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10,setPreservePlaybackState:11},ce={midiEvent:0,songChange:1,timeChange:2,pause:3,getMIDI:4,midiError:5,metaEvent:6,loopCountChange:7,songListChange:8};function Ai(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var ei={skipToFirstNoteOn:!0,autoPlay:!0,preservePlaybackState:!1};var Gn=class extends tt{isEmbedded=!1;constructor(A){super(),this._copyFromSequence(A),this.isEmbedded=A.embeddedSoundFont!==void 0}},Xu={duration:99999,firstNoteOn:0,loop:{start:0,end:123456},lastVoiceEventTick:123456,lyrics:[],copyright:"",midiPorts:[],midiPortChannelOffsets:[],tracksAmount:0,tempoChanges:[{ticks:0,tempo:120}],fileName:"NOT_LOADED.mid",midiName:"Loading...",rawMidiName:new Uint8Array([76,111,97,100,105,110,103,46,46,46]),usedChannelsOnTrack:[],timeDivision:0,keyRange:{min:0,max:127},isEmbedded:!1,RMIDInfo:{},bankOffset:0,midiNameUsesFileName:!1,format:0};var ys=class extends AudioWorkletProcessor{alive=!0;oneOutputMode=!1;constructor(A){super();let t=A.processorOptions;this.oneOutputMode=t.midiChannels===1;let n=(g,i)=>{this.postMessageToMainThread({messageType:g,messageData:i})},s=t?.startRenderingData,o=s?.snapshot;this.synthesizer=new LA(sampleRate,{effectsEnabled:!this.oneOutputMode,enableEventSystem:t?.enableEventSystem,midiChannels:16,initialTime:currentTime}),this.synthesizer.onEventCall=(g,i)=>{n(ee.eventCall,{eventName:g,eventData:i})},this.synthesizer.onChannelPropertyChange=(g,i)=>n(ee.channelPropertyChange,[i,g]),this.synthesizer.onMasterParameterChange=(g,i)=>n(ee.masterParameterChange,[g,i]);let r=$e(t.soundfont);this.synthesizer.soundfontManager.reloadManager(r),this.synthesizer.processorInitialized.then(()=>{this.sequencer=new wA(this.synthesizer);let g=(i,E)=>{this.postMessageToMainThread({messageType:ee.sequencerSpecific,messageData:{messageType:i,messageData:E}})};if(this.port.onmessage=i=>this.handleMessage(i.data),this.sequencer.onMIDIMessage=i=>{g(ce.midiEvent,i)},this.sequencer.onTimeChange=i=>{g(ce.timeChange,i)},this.sequencer.onPlaybackStop=i=>{g(ce.pause,i)},this.sequencer.onSongChange=(i,E)=>{g(ce.songChange,[i,E])},this.sequencer.onMetaEvent=(i,E)=>{g(ce.metaEvent,[i,E])},this.sequencer.onLoopCountChange=i=>{g(ce.loopCountChange,i)},this.sequencer.onSongListChange=i=>{let E=i.map(c=>new Gn(c));this.postMessageToMainThread({messageType:ee.sequencerSpecific,messageData:{messageType:ce.songListChange,messageData:E}})},o!==void 0&&this.synthesizer.applySynthesizerSnapshot(o),s&&(st.SpessaSynthInfo("%cRendering enabled! Starting render.",ps.info),s.parsedMIDI)){s?.loopCount!==void 0?(this.sequencer.loopCount=s?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.synthesizer.voiceCap=1/0;let i=Ai(s.sequencerOptions,ei);this.sequencer.skipToFirstNoteOn=i.skipToFirstNoteOn,this.sequencer.preservePlaybackState=i.preservePlaybackState;try{this.sequencer.loadNewSongList([s.parsedMIDI])}catch(E){console.error(E),g(ce.midiError,E)}}this.postReady()})}postReady(){this.postMessageToMainThread({messageType:ee.isFullyInitialized,messageData:void 0})}postMessageToMainThread(A){this.port.postMessage(A)}handleMessage(A){let t=A.messageData,n=A.channelNumber,s;if(n>=0&&(s=this.synthesizer.midiAudioChannels[n],s===void 0)){st.SpessaSynthWarn(`Trying to access channel ${n} which does not exist... ignoring!`);return}switch(A.messageType){case FA.midiMessage:this.synthesizer.processMessage(...t);break;case FA.customCcChange:s.setCustomController(t[0],t[1]),s.updateChannelTuning();break;case FA.ccReset:n===-1?this.synthesizer.resetAllControllers():s.resetControllers();break;case FA.setChannelVibrato:if(n===-1)for(let m=0;m<this.synthesizer.midiAudioChannels.length;m++){let u=this.synthesizer.midiAudioChannels[m];t.rate===-1?u.disableAndLockGSNRPN():u.setVibrato(t.depth,t.rate,t.delay)}else t.rate===-1?s.disableAndLockGSNRPN():s.setVibrato(t.depth,t.rate,t.delay);break;case FA.stopAll:n===-1?this.synthesizer.stopAllChannels(t===1):s.stopAllNotes(t===1);break;case FA.killNotes:this.synthesizer.voiceKilling(t);break;case FA.muteChannel:s.muteChannel(t);break;case FA.addNewChannel:this.synthesizer.createMidiChannel(!0);break;case FA.debugMessage:console.debug(this.synthesizer);break;case FA.setMasterParameter:let o=t[0],r=t[1];this.synthesizer.setMasterParameter(o,r);break;case FA.setDrums:s.setDrums(t);break;case FA.transpose:n===-1?this.synthesizer.transposeAllChannels(t[0],t[1]):s.transposeChannel(t[0],t[1]);break;case FA.highPerformanceMode:this.synthesizer.highPerformanceMode=t;break;case FA.lockController:t[0]===-1?s.setPresetLock(t[1]):s.lockedControllers[t[0]]=t[1];break;case FA.sequencerSpecific:let g=this.sequencer,i=t.messageData;switch(t.messageType){default:break;case te.loadNewSongList:try{let R=i[0].map(D=>D.duration?D:new Ot(D.binary,D.altName));g.loadNewSongList(R,i[1])}catch(p){console.error(p),this.postMessageToMainThread({messageType:ee.sequencerSpecific,messageData:{messageType:ce.midiError,messageData:p}})}break;case te.pause:g.pause();break;case te.play:g.play(i);break;case te.stop:g.stop();break;case te.setTime:g.currentTime=i;break;case te.changeMIDIMessageSending:g.sendMIDIMessages=i;break;case te.setPlaybackRate:g.playbackRate=i;break;case te.setLoop:let[m,u]=i;g.loop=m,u===-1?g.loopCount=1/0:g.loopCount=u;break;case te.changeSong:switch(i[0]){case pt.forwards:g.nextSong();break;case pt.backwards:g.previousSong();break;case pt.shuffleOff:g.shuffleMode=!1,g.songIndex=g.shuffledSongIndexes[g.songIndex];break;case pt.shuffleOn:g.shuffleMode=!0,g.shuffleSongIndexes(),g.songIndex=0,g.loadCurrentSong();break;case pt.index:g.songIndex=i[1],g.loadCurrentSong();break}break;case te.getMIDI:this.postMessageToMainThread({messageType:ee.sequencerSpecific,messageData:{messageType:ce.getMIDI,messageData:g.midiData}});break;case te.setSkipToFirstNote:g.skipToFirstNoteOn=i;break;case te.setPreservePlaybackState:g.preservePlaybackState=i}break;case FA.soundFontManager:try{let m=this.synthesizer.soundfontManager,u=t[0],p=t[1],R;switch(u){case qt.addNewSoundFont:R=$e(p[0]),m.addNewSoundFont(R,p[1],p[2]),this.postMessageToMainThread({messageType:ee.isFullyInitialized,messageData:void 0});break;case qt.reloadSoundFont:R=$e(p),m.reloadManager(R),this.postMessageToMainThread({messageType:ee.isFullyInitialized,messageData:void 0});break;case qt.deleteSoundFont:m.deleteSoundFont(p);break;case qt.rearrangeSoundFonts:m.rearrangeSoundFonts(p)}}catch(m){this.postMessageToMainThread({messageType:ee.soundfontError,messageData:m})}break;case FA.keyModifierManager:let c=t[0],h=this.synthesizer.keyModifierManager,Q=t[1];switch(c){default:return;case Rn.addMapping:h.addMapping(...Q);break;case Rn.clearMappings:h.clearMappings();break;case Rn.deleteMapping:h.deleteMapping(...Q)}break;case FA.requestSynthesizerSnapshot:let B=At.createSynthesizerSnapshot(this.synthesizer);this.postMessageToMainThread({messageType:ee.synthesizerSnapshot,messageData:B});break;case FA.setLogLevel:qn(t[0],t[1],t[2],t[3]);break;case FA.setEffectsGain:this.synthesizer.reverbGain=t[0],this.synthesizer.chorusGain=t[1];break;case FA.destroyWorklet:this.alive=!1,this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencer.midiData,delete this.sequencer;break;default:st.SpessaSynthWarn("Unrecognized event:",t);break}}process(A,t){if(!this.alive)return!1;if(this.sequencer.processTick(),this.oneOutputMode){let n=t[0],s=[];for(let o=0;o<32;o+=2)s.push([n[o],n[o+1]]);this.synthesizer.renderAudioSplit([],[],s)}else this.synthesizer.renderAudioSplit(t[0],t[1],t.slice(2));return!0}};registerProcessor($r,ys);st.SpessaSynthInfo("%cProcessor successfully registered!",ps.recognized);
22
22
  //# sourceMappingURL=worklet_processor.min.js.map
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