From 132df04e34ff898b6bc94f21b28ab23d515fa197 Mon Sep 17 00:00:00 2001 From: spessasus Date: Wed, 25 Sep 2024 21:17:04 +0200 Subject: [PATCH] fix sustained voices not ending --- README.md | 17 +++++++++++------ package.json | 2 +- .../synthetizer/worklet_processor.min.js | 16 ++++++++-------- .../worklet_utilities/volume_envelope.js | 16 ++++++++++++++-- .../worklet_utilities/worklet_voice.js | 2 +- 5 files changed, 35 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index c2882401..65e3372e 100644 --- a/README.md +++ b/README.md @@ -2,16 +2,18 @@ SpessaSynth logo

-**SpessaSynth** is a SoundFont2-based real-time synthesizer and MIDI player written in vanilla JavaScript. -It’s a powerful and versatile library that allows you to read, write, or play MIDI files, -read DLS files and read/write SF2/SF3 files with ease. +**SpessaSynth** is a SoundFont2-based real-time synthesizer and MIDI library written in vanilla JavaScript. +It’s a powerful and versatile library that allows you to: +- Play MIDI files using SF2/SF3/DLS files +- Write MIDI files +- Write SF2/SF3 files +- Convert DLS to SF2 +- [and more!](#easy-integration) ```shell npm install --save spessasynth_lib ``` -### DLS Support now available! -

Live Demo (no download needed!)

YouTube Video

@@ -37,7 +39,7 @@ This repository contains both the library and a complete musical web application ### Powerful SoundFont Synthesizer - Suitable for both **real-time** and **offline** synthesis - **Excellent SoundFont support:** - - **Generator Support** + - **Full Generator Support** - **Modulator Support:** *First (to my knowledge) JavaScript SoundFont synth with that feature!* - **SoundFont3 Support:** Play compressed SoundFonts! - **Experimental SF2Pack Support:** Play soundfonts compressed with BASSMIDI! (*Note: only works with vorbis compression*) @@ -119,6 +121,9 @@ This repository contains both the library and a complete musical web application ## Limitations - Synth's performance may be suboptimal, especially on mobile devices. +- Audio may sometimes sound distored in Chrome, Edge, Brave, + etc. due to a **[Chromium Bug](https://issues.chromium.org/issues/367304685).** + I can't do anything about it, only hope that it gets fixed. ### Installation #### Npm package diff --git a/package.json b/package.json index d42f90fd..73fe633e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.27", + "version": "3.20.28", "type": "module", "scripts": { "start": "node src/website/server/server.js" diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index ca27bd05..c36e0f54 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,16 +1,16 @@ -var is=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(typeof require<"u"?require:A)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function De(e){let A=e.reduce((n,o)=>n+o.length,0),t=new H(A),s=0;for(let n of e)t.set(n,s),s+=n.length;return t}function ft(e){e=Math.floor(e);let A=Math.floor(e/60),t=Math.round(e-A*60);return{minutes:A,seconds:t,time:`${A.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}}function as(e){return e.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function QA(e){let A="";for(let t=0;t=128&&A<=224&&(s=t,n=A),{status:n,channel:s}}var p={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},gs={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var tA={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},ae={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},TA=-1,mA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var Cs=!0,Es=!0,qe=!0,Bs=!0;function hs(e,A,t,s){Cs=e,Es=A,qe=t,Bs=s}function m(...e){Cs&&console.info(...e)}function N(...e){Es&&console.warn(...e)}function Qs(...e){Bs&&console.table(...e)}function te(...e){qe&&console.group(...e)}function pA(...e){qe&&console.groupCollapsed(...e)}function X(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var cs="spessasynth-worklet-system",ls=450,SA=9,ve=16,Ke="gs";var UA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},wA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function zA(e,A){let t=0;for(let s=8*(A-1);s>=0;s-=8)t|=e[e.currentIndex++]<>>0}function us(e,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=ke(e.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=s,t.status){case w.noteOn:let n=e.messageData[1];if(n>0)this.synth.noteOn(t.channel,e.messageData[0],n),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:n});else{this.synth.noteOff(t.channel,e.messageData[0]);let g=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.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:this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case w.programChange: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,s);break;case w.setTempo:this.oneTickToSeconds=60/(Do(e)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),N("invalid tempo! falling back to 120 BPM"));break;case w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:break;case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:this.post(wA.textEvent,[e.messageData,t.status]);break;case w.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:N(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(w).find(g=>w[g]===t.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function ds(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0),e===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Do(e){return e.messageData.currentIndex=0,6e7/zA(e.messageData,3)}function fs(){let e=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-t.ticks),this.midiData.loop.end<=t.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ms(){let e=0,A=1/0;return this.tracks.forEach((t,s)=>{this.eventIndex[s]>=t.length||t[this.eventIndex[s]].ticks>>0}function ge(e,A,t){for(let s=0;s>s*8&255}function Y(e,A){e[e.currentIndex++]=A&255,e[e.currentIndex++]=A>>8}function cA(e,A){ge(e,A,4)}function jA(e,A){let t=A<<8|e;return t>32767?t-65536:t}function ps(e){return e>127?e-256:e}function O(e,A,t=void 0,s=!0){if(t){let n=e.slice(e.currentIndex,e.currentIndex+A);return e.currentIndex+=A,new TextDecoder(t.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let g=0;g127){if(s){n=!0;continue}else if(C===0){n=!0;continue}}o+=String.fromCharCode(C)}}return o}}function FA(e,A,t=0){t>0&&A.length>t&&(A=A.slice(0,t));for(let s=0;sA.length)for(let s=0;st.header!=="LIST"?!1:(t.chunkData.currentIndex=0,O(t.chunkData,4)===A))}function Ve(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}var a={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},U=[];U[a.startAddrsOffset]={min:0,max:32768,def:0};U[a.endAddrOffset]={min:-32768,max:32768,def:0};U[a.startloopAddrsOffset]={min:-32768,max:32768,def:0};U[a.endloopAddrsOffset]={min:-32768,max:32768,def:0};U[a.startAddrsCoarseOffset]={min:0,max:32768,def:0};U[a.modLfoToPitch]={min:-12e3,max:12e3,def:0};U[a.vibLfoToPitch]={min:-12e3,max:12e3,def:0};U[a.modEnvToPitch]={min:-12e3,max:12e3,def:0};U[a.initialFilterFc]={min:1500,max:13500,def:13500};U[a.initialFilterQ]={min:0,max:960,def:0};U[a.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};U[a.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};U[a.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.modLfoToVolume]={min:-960,max:960,def:0};U[a.chorusEffectsSend]={min:0,max:1e3,def:0};U[a.reverbEffectsSend]={min:0,max:1e3,def:0};U[a.pan]={min:-500,max:500,def:0};U[a.delayModLFO]={min:-12e3,max:5e3,def:-12e3};U[a.freqModLFO]={min:-16e3,max:4500,def:0};U[a.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};U[a.freqVibLFO]={min:-16e3,max:4500,def:0};U[a.delayModEnv]={min:-32768,max:5e3,def:-32768};U[a.attackModEnv]={min:-32768,max:8e3,def:-32768};U[a.holdModEnv]={min:-12e3,max:5e3,def:-12e3};U[a.decayModEnv]={min:-12e3,max:8e3,def:-12e3};U[a.sustainModEnv]={min:0,max:1e3,def:0};U[a.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};U[a.keyNumToModEnvHold]={min:-1200,max:1200,def:0};U[a.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};U[a.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};U[a.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};U[a.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};U[a.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};U[a.sustainVolEnv]={min:0,max:1440,def:0};U[a.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};U[a.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};U[a.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};U[a.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.keyNum]={min:-1,max:127,def:-1};U[a.velocity]={min:-1,max:127,def:-1};U[a.initialAttenuation]={min:-250,max:1440,def:0};U[a.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.coarseTune]={min:-120,max:120,def:0};U[a.fineTune]={min:-99,max:99,def:0};U[a.scaleTuning]={min:0,max:1200,def:100};U[a.exclusiveClass]={min:0,max:99999,def:0};U[a.overridingRootKey]={min:-1,max:127,def:-1};var b=class{constructor(A=a.INVALID,t=0){if(this.generatorType=A,t===void 0)throw new Error("No value provided.");let s=U[A];this.generatorValue=Math.round(t),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=a.INVALID;generatorValue=0};function Ss(e,A,t){let s=U[e]||{min:0,max:32768,def:0},n=A.find(h=>h.generatorType===e),o=0;n&&(o=n.generatorValue);let g=t.find(h=>h.generatorType===e),C=s.def;g&&(C=g.generatorValue);let c=C+o;return e===a.initialAttenuation?c:Math.max(s.min,Math.min(s.max,c))}var mt=class extends b{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=jA(A[t+2],A[t+3]),A.currentIndex+=4}};function pt(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new mt(e.chunkData));return A.length>1&&A.pop(),A}var V={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},lA={linear:0,concave:1,convex:2,switch:3},ko=[];for(let e=0;e<4;e++)ko.push([[],[]]);var eA=class e{constructor(A){A.srcEnum?(this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.sourceEnum=S(A,2),this.modulatorDestination=S(A,2),this.transformAmount=jA(A[A.currentIndex++],A[A.currentIndex++]),this.secondarySourceEnum=S(A,2),this.transformType=S(A,2)),this.modulatorDestination>58&&(this.modulatorDestination=a.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new e({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,t){return A.sourceEnum===t.sourceEnum&&A.modulatorDestination===t.modulatorDestination&&A.secondarySourceEnum===t.secondarySourceEnum&&A.transformType===t.transformType}sumTransform(A){return new e({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(n,o){return Object.keys(n).find(g=>n[g]===o)}let t=A(lA,this.sourceCurveType);t+=this.sourcePolarity===0?" unipolar ":" bipolar ",t+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?t+=A(p,this.sourceIndex):t+=A(V,this.sourceIndex);let s=A(lA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(p,this.secSrcIndex):s+=A(V,this.secSrcIndex),`Modulator: - Source: ${t} +var as=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function De(t){let A=t.reduce((n,o)=>n+o.length,0),e=new H(A),s=0;for(let n of t)e.set(n,s),s+=n.length;return e}function mt(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function Is(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function QA(t){let A="";for(let e=0;e=128&&A<=224&&(s=e,n=A),{status:n,channel:s}}var p={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},Cs={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var tA={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},ae={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},TA=-1,mA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var Es=!0,Bs=!0,qe=!0,hs=!0;function Qs(t,A,e,s){Es=t,Bs=A,qe=e,hs=s}function m(...t){Es&&console.info(...t)}function N(...t){Bs&&console.warn(...t)}function cs(...t){hs&&console.table(...t)}function te(...t){qe&&console.group(...t)}function pA(...t){qe&&console.groupCollapsed(...t)}function X(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var ls="spessasynth-worklet-system",us=450,SA=9,ve=16,Ke="gs";var UA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},wA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function zA(t,A){let e=0;for(let s=8*(A-1);s>=0;s-=8)e|=t[t.currentIndex++]<>>0}function ds(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=ke(t.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=s,e.status){case w.noteOn:let n=t.messageData[1];if(n>0)this.synth.noteOn(e.channel,t.messageData[0],n),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:n});else{this.synth.noteOff(e.channel,t.messageData[0]);let g=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case w.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===t.messageData[0]&&g.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case w.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case w.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(t.messageData,s);break;case w.setTempo:this.oneTickToSeconds=60/(Do(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),N("invalid tempo! falling back to 120 BPM"));break;case w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:break;case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:this.post(wA.textEvent,[t.messageData,e.status]);break;case w.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:N(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(w).find(g=>w[g]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function fs(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Do(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function ms(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ps(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticks>>0}function ge(t,A,e){for(let s=0;s>s*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function cA(t,A){ge(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Ss(t){return t>127?t-256:t}function O(t,A,e=void 0,s=!0){if(e){let n=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let g=0;g127){if(s){n=!0;continue}else if(C===0){n=!0;continue}}o+=String.fromCharCode(C)}}return o}}function FA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let s=0;sA.length)for(let s=0;se.header!=="LIST"?!1:(e.chunkData.currentIndex=0,O(e.chunkData,4)===A))}function Ve(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var a={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},U=[];U[a.startAddrsOffset]={min:0,max:32768,def:0};U[a.endAddrOffset]={min:-32768,max:32768,def:0};U[a.startloopAddrsOffset]={min:-32768,max:32768,def:0};U[a.endloopAddrsOffset]={min:-32768,max:32768,def:0};U[a.startAddrsCoarseOffset]={min:0,max:32768,def:0};U[a.modLfoToPitch]={min:-12e3,max:12e3,def:0};U[a.vibLfoToPitch]={min:-12e3,max:12e3,def:0};U[a.modEnvToPitch]={min:-12e3,max:12e3,def:0};U[a.initialFilterFc]={min:1500,max:13500,def:13500};U[a.initialFilterQ]={min:0,max:960,def:0};U[a.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};U[a.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};U[a.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.modLfoToVolume]={min:-960,max:960,def:0};U[a.chorusEffectsSend]={min:0,max:1e3,def:0};U[a.reverbEffectsSend]={min:0,max:1e3,def:0};U[a.pan]={min:-500,max:500,def:0};U[a.delayModLFO]={min:-12e3,max:5e3,def:-12e3};U[a.freqModLFO]={min:-16e3,max:4500,def:0};U[a.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};U[a.freqVibLFO]={min:-16e3,max:4500,def:0};U[a.delayModEnv]={min:-32768,max:5e3,def:-32768};U[a.attackModEnv]={min:-32768,max:8e3,def:-32768};U[a.holdModEnv]={min:-12e3,max:5e3,def:-12e3};U[a.decayModEnv]={min:-12e3,max:8e3,def:-12e3};U[a.sustainModEnv]={min:0,max:1e3,def:0};U[a.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};U[a.keyNumToModEnvHold]={min:-1200,max:1200,def:0};U[a.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};U[a.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};U[a.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};U[a.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};U[a.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};U[a.sustainVolEnv]={min:0,max:1440,def:0};U[a.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};U[a.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};U[a.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};U[a.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.keyNum]={min:-1,max:127,def:-1};U[a.velocity]={min:-1,max:127,def:-1};U[a.initialAttenuation]={min:-250,max:1440,def:0};U[a.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.coarseTune]={min:-120,max:120,def:0};U[a.fineTune]={min:-99,max:99,def:0};U[a.scaleTuning]={min:0,max:1200,def:100};U[a.exclusiveClass]={min:0,max:99999,def:0};U[a.overridingRootKey]={min:-1,max:127,def:-1};var b=class{constructor(A=a.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=U[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=a.INVALID;generatorValue=0};function ys(t,A,e){let s=U[t]||{min:0,max:32768,def:0},n=A.find(h=>h.generatorType===t),o=0;n&&(o=n.generatorValue);let g=e.find(h=>h.generatorType===t),C=s.def;g&&(C=g.generatorValue);let Q=C+o;return t===a.initialAttenuation?Q:Math.max(s.min,Math.min(s.max,Q))}var pt=class extends b{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=jA(A[e+2],A[e+3]),A.currentIndex+=4}};function St(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new pt(t.chunkData));return A.length>1&&A.pop(),A}var V={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},lA={linear:0,concave:1,convex:2,switch:3},ko=[];for(let t=0;t<4;t++)ko.push([[],[]]);var eA=class t{constructor(A){A.srcEnum?(this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.sourceEnum=S(A,2),this.modulatorDestination=S(A,2),this.transformAmount=jA(A[A.currentIndex++],A[A.currentIndex++]),this.secondarySourceEnum=S(A,2),this.transformType=S(A,2)),this.modulatorDestination>58&&(this.modulatorDestination=a.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(n,o){return Object.keys(n).find(g=>n[g]===o)}let e=A(lA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(p,this.sourceIndex):e+=A(V,this.sourceIndex);let s=A(lA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(p,this.secSrcIndex):s+=A(V,this.secSrcIndex),`Modulator: + Source: ${e} Secondary source: ${s} Destination: ${A(a,this.modulatorDestination)} Trasform amount: ${this.transformAmount} Transform type: ${this.transformType} -`}};function vA(e,A,t,s,n){return e<<10|A<<9|t<<8|s<<7|n}var St=960,yt=lA.concave,Oe=[new eA({srcEnum:vA(yt,0,1,0,V.noteOnVelocity),dest:a.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new eA({srcEnum:129,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(yt,0,1,1,p.mainVolume),dest:a.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new eA({srcEnum:13,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:526,dest:a.fineTune,amt:12700,secSrcEnum:16,transform:0}),new eA({srcEnum:650,dest:a.pan,amt:1e3,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(yt,0,1,1,p.expressionController),dest:a.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new eA({srcEnum:219,dest:a.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new eA({srcEnum:221,dest:a.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,0,0,0,V.polyPressure),dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,0,0,1,p.effects2Depth),dest:a.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,1,0,1,p.releaseTime),dest:a.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,1,0,1,p.brightness),dest:a.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function Ze(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new eA(e.chunkData));return A}function ys(e=!1){let A={midiControllers:new Int16Array(Dt),lockedControllers:Array(Dt).fill(!1),customControllers:new Float32Array(Ds),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let t=0;t<128;t++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),e&&this.callEvent("newchannel",void 0)}var CA=128,Dt=147,KA=new Int16Array(Dt).fill(0);KA[p.mainVolume]=12800;KA[p.expressionController]=16256;KA[p.pan]=8192;KA[p.releaseTime]=8192;KA[p.brightness]=8192;KA[p.effects1Depth]=5120;KA[CA+V.pitchWheel]=8192;KA[CA+V.pitchWheelRange]=256;var uA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},aA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Ds=Object.keys(aA).length,kt=new Float32Array(Ds);kt[aA.modulationMultiplier]=1;var Xe={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var We=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Ce(e,A){let t=0;for(;e>0;){let s=A.tempoChanges.find(o=>o.ticks0&&(v+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);F.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=v),K=gs[I>>4],(I&240)===w.noteOn){q.add(AA);let oA=F.data[F.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,oA),this.keyRange.max=Math.max(this.keyRange.max,oA)}M=I;break}let j=new H(K),z=F.data.slice(F.data.currentIndex,F.data.currentIndex+K);F.data.currentIndex+=K,j.set(z,0);let gA=new ie(v,I,j);switch(k.push(gA),AA){case-2:switch(I){case w.setTempo:this.tempoChanges.push({ticks:v,tempo:6e7/zA(z,3)});break;case w.marker:switch(O(j,j.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=v;break;case"loopend":Q=v}j.currentIndex=0;break;case w.midiPort:let GA=j[0];this.midiPorts[y]=GA,this.midiPortChannelOffsets[GA]===void 0&&(this.midiPortChannelOffsets[GA]=u,u+=16);break;case w.copyright:o||(this.copyright+=O(j,j.length,void 0,!1)+` +`}};function vA(t,A,e,s,n){return t<<10|A<<9|e<<8|s<<7|n}var yt=960,Dt=lA.concave,Oe=[new eA({srcEnum:vA(Dt,0,1,0,V.noteOnVelocity),dest:a.initialAttenuation,amt:yt,secSrcEnum:0,transform:0}),new eA({srcEnum:129,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(Dt,0,1,1,p.mainVolume),dest:a.initialAttenuation,amt:yt,secSrcEnum:0,transform:0}),new eA({srcEnum:13,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:526,dest:a.fineTune,amt:12700,secSrcEnum:16,transform:0}),new eA({srcEnum:650,dest:a.pan,amt:1e3,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(Dt,0,1,1,p.expressionController),dest:a.initialAttenuation,amt:yt,secSrcEnum:0,transform:0}),new eA({srcEnum:219,dest:a.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new eA({srcEnum:221,dest:a.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,0,0,0,V.polyPressure),dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,0,0,1,p.effects2Depth),dest:a.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,1,0,1,p.releaseTime),dest:a.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new eA({srcEnum:vA(lA.linear,1,0,1,p.brightness),dest:a.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function Ze(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new eA(t.chunkData));return A}function Ds(t=!1){let A={midiControllers:new Int16Array(kt),lockedControllers:Array(kt).fill(!1),customControllers:new Float32Array(ks),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}var CA=128,kt=147,KA=new Int16Array(kt).fill(0);KA[p.mainVolume]=12800;KA[p.expressionController]=16256;KA[p.pan]=8192;KA[p.releaseTime]=8192;KA[p.brightness]=8192;KA[p.effects1Depth]=5120;KA[CA+V.pitchWheel]=8192;KA[CA+V.pitchWheelRange]=256;var uA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},aA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},ks=Object.keys(aA).length,wt=new Float32Array(ks);wt[aA.modulationMultiplier]=1;var Xe={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var We=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Ce(t,A){let e=0;for(;t>0;){let s=A.tempoChanges.find(o=>o.ticks0&&(v+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);F.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=v),K=Cs[I>>4],(I&240)===w.noteOn){q.add(AA);let oA=F.data[F.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,oA),this.keyRange.max=Math.max(this.keyRange.max,oA)}M=I;break}let j=new H(K),z=F.data.slice(F.data.currentIndex,F.data.currentIndex+K);F.data.currentIndex+=K,j.set(z,0);let gA=new ie(v,I,j);switch(k.push(gA),AA){case-2:switch(I){case w.setTempo:this.tempoChanges.push({ticks:v,tempo:6e7/zA(z,3)});break;case w.marker:switch(O(j,j.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=v;break;case"loopend":c=v}j.currentIndex=0;break;case w.midiPort:let GA=j[0];this.midiPorts[y]=GA,this.midiPortChannelOffsets[GA]===void 0&&(this.midiPortChannelOffsets[GA]=u,u+=16);break;case w.copyright:o||(this.copyright+=O(j,j.length,void 0,!1)+` `);break;case w.lyric:this.lyrics.push(j)}break;case-3:if(QA(j.slice(0,7)).trim()==="41 10 45 12 10 00 00"){let oA=j.slice(7,z.length-3),GA=O(oA,oA.length)+` -`;this.copyright+=GA,m(`%cDecoded Roland SC message! %c${GA}`,r.recognized,r.value)}break;default:if((I&240)===w.controllerChange)switch(j[0]){case 2:case 116:d=v;break;case 4:case 117:Q===null?Q=v:Q=0;break;case 0:C&&j[1]!==0&&j[1]!==127&&(m("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(k),this.usedChannelsOnTrack.push(q),m(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}m("%cAll tracks parsed correctly!",r.recognized),pA("%cCorrecting loops, ports and detecting notes...",r.info);let l=[];for(let y of this.tracks){let k=y.find(F=>(F.messageStatusByte&240)===w.noteOn);k&&l.push(k.ticks)}this.firstNoteOn=Math.min(...l),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&Q===null?(d=this.firstNoteOn,Q=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(Q===null||Q===0)&&(Q=this.lastVoiceEventTick)),this.loop={start:d,end:Q},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let D=0;for(let y of this.midiPorts)if(y!==-1){D=y;break}if(this.midiPorts=this.midiPorts.map(y=>y===-1?D:y),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!g)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=w.noteOn&&y.messageStatusBytek.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=O(y.messageData,y.messageData.length,void 0,!1))}}else{let y=this.tracks[0].find(k=>k.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=O(y.messageData,y.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=as(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yu>Q?u:Q),s=[];for(let Q=0;Q{g[D]>=l.length||l[g[D]].ticks0;){let Q=c(),u=e.tracks[Q];if(g[Q]>=u.length){C--;continue}let l=u[g[Q]];if(g[Q]++,l.messageStatusByte===w.midiPort){h[Q]=l.messageData[0];continue}let D=l.messageStatusByte&240;if(D!==w.noteOn&&D!==w.controllerChange&&D!==w.programChange&&D!==w.systemExclusive)continue;let y=(l.messageStatusByte&15)+e.midiPortChannelOffsets[h[Q]]||0,k=s[y];switch(D){case w.programChange:k.program=l.messageData[0],n(k);break;case w.controllerChange:if(l.messageData[0]!==p.bankSelect||d==="gs"&&k.drums)continue;let F=l.messageData[1],q=Math.max(0,F-e.bankOffset);if(d==="xg"){let T=F===120||F===126||F===127;T!==k.drums?(k.drums=T,k.bank=k.drums?128:q,n(k)):k.bank=k.drums?128:q;continue}s[y].bank=q;break;case w.noteOn:if(l.messageData[1]===0)continue;n(k),o[k.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case w.systemExclusive:if(l.messageData[0]!==65||l.messageData[2]!==66||l.messageData[3]!==18||l.messageData[4]!==64||!(l.messageData[5]&16)||l.messageData[6]!==21){l.messageData[0]===67&&l.messageData[2]===76&&l.messageData[5]===126&&l.messageData[6]===0&&(d="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+e.midiPortChannelOffsets[h[Q]],v=!!(l.messageData[7]>0&&l.messageData[5]>>4);k=s[M],k.drums=v,k.bank=v?128:0,n(k);break}}for(let Q of Object.keys(o))o[Q].size===0&&(m(`%cDetected change but no keys for %c${Q}`,r.info,r.value),delete o[Q]);return X(),o}function ws(e,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(t,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${ft(Math.ceil(this.duration)).time}`,r.recognized),this.post(wA.songChange,[new Pe(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(N(`%cVery short song: (${ft(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function Rs(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new _e(t.binary,t.altName||""))}catch(s){return this.post(wA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function Gs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function xs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var PA=new Int16Array(127);PA[p.mainVolume]=100;PA[p.expressionController]=127;PA[p.pan]=64;PA[p.releaseTime]=64;PA[p.brightness]=64;PA[p.effects1Depth]=40;function Ms(e,A=void 0){if(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,g=[];for(let C=0;C=A)break}else if(this.playedTime>=e)break;let h=ke(c.messageStatusByte),d=h.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(h.status){case w.noteOn:case w.noteOff:case w.keySignature:break;case w.pitchBend:s[d]=c.messageData[1]<<7|c.messageData[0];break;case w.programChange:let u=n[d];u.program=c.messageData[0],u.actualBank=u.bank;break;case w.controllerChange:let l=c.messageData[0];if(o(l))if(this.sendMIDIMessages)this.sendMIDIMessage([w.controllerChange|d%16,l,c.messageData[1]]);else{let D=c.messageData[1];if(l===p.bankSelect){n[d].bank=D;break}this.synth.controllerChange(d,l,D)}else g[d]===void 0&&(g[d]=Array.from(PA)),g[d][l]=c.messageData[1];break;default:this._processEvent(c,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let Q=this.tracks[C][this.eventIndex[C]];if(Q===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(Q.ticks-c.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7]),g[C].forEach((c,h)=>{c!==PA[h]&&!o(h)&&this.sendMIDIMessage([w.controllerChange|C%16,h,c])}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.sendMIDIMessage([w.controllerChange|C%16,p.bankSelect,c]),this.sendMIDIMessage([w.programChange|C%16,n[C].program])}}else for(let C=0;C>7,s[C]&127),g[C]!==void 0&&g[C].forEach((c,h)=>{c!==PA[h]&&!o(h)&&this.synth.controllerChange(C,h,c)}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.synth.controllerChange(C,p.bankSelect,c),this.synth.programChange(C,n[C].program)}return!0}function Ns(e=!1){if(this.midiData!==void 0){if(e){this.currentTime=0;return}if(this.currentTime>=this.duration){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,!1,!0)}),this.setProcessHandler()}}function bs(e){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(wA.timeChange,currentTime-Ce(e,this.midiData));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function Ls(e){this.absoluteStartTime=currentTime-e/this._playbackRate}function Us(e,A){switch(e){default:break;case UA.loadNewSongList:this.loadNewSongList(A);break;case UA.pause:this.pause();break;case UA.play:this.play(A);break;case UA.stop:this.stop();break;case UA.setTime:this.currentTime=A;break;case UA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case UA.setPlaybackRate:this.playbackRate=A;break;case UA.setLoop:this.loop=A;break;case UA.changeSong:A?this.nextSong():this.previousSong();break;case UA.getMIDI:this.post(wA.getMIDI,this.midiData);break;case UA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ts(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function Hs(e){this.post(wA.midiEvent,e)}var EA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.loopCount=1/0,this.currentLoopCount=this.loopCount,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0}set playbackRate(A){let t=this.currentTime;this._playbackRate=A,this.currentTime=t}get currentTime(){return this.pausedTime?this.pausedTime:(currentTime-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&&AYs?440*Math.pow(2,(e-6900)/1200):Ft[~~e-ze]}var Gt=-1660,wo=1600,Rt=new Float32Array((wo-Gt)*100+1);for(let e=0;e.5?1:0,s?t*2-1:t;case lA.concave:return s?(t=t*2-1,t<0?1-Ee[~~(t*-IA)]-1:Ee[~~t*IA]):Ee[~~(t*IA)];case lA.convex:return s?(t=t*2-1,t<0?1-Be[~~(t*-IA)]-1:Be[~~(t*IA)]):Be[~~(t*IA)]}}var xt=1,Mt=new Float32Array(1e3);for(let e=0;e=e.sample.loopEnd;)t-=o;let C=~~t,c=C+1;for(;c>=e.sample.loopEnd;)c-=o;let h=t-C,d=n[c],Q=n[C];A[g]=Q+(d-Q)*h,t+=e.sample.playbackStep*e.currentTuningCalculated}}else{e.sample.end>=n.length&&(e.sample.end=n.length-1);for(let o=0;o=e.sample.end){e.finished=!0;return}let c=t-g,h=n[C],d=n[g];A[o]=d+(h-d)*c,t+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=t}function qs(e,A){let t=e.sample.cursor,s=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,n=e.sample.loopEnd-e.sample.loopStart,o=e.sample.sampleData;if(s)for(let g=0;g=e.sample.loopEnd;)t-=n;let C=~~t+1;for(;C>=e.sample.loopEnd;)C-=n;A[g]=o[C],t+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=o.length&&(e.sample.end=o.length-1);for(let g=0;g=e.sample.end){e.finished=!0;return}A[g]=o[C],t+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=t}function vs(e,A,t,s,n,o,g,C,c){if(!isNaN(t[0])){if(g>0){let h=o[0],d=o[1];g=Math.min(g,1e3);let Q=g/1300,u=e*Q,l=A*Q;for(let D=0;D0){let h=C[0],d=C[1];c=Math.min(c,1e3);let Q=c/1300,u=e*Q,l=A*Q;for(let D=0;D0)for(let h=0;h0)for(let h=0;h13499&&A.filter.reasonanceCb===0)return;let n=A.filter;(n.cutoffCents!==s||n.reasonanceCb!==A.modulatedGenerators[a.initialFilterQ])&&(n.cutoffCents=s,n.reasonanceCb=A.modulatedGenerators[a.initialFilterQ],e.calculateCoefficients(A));for(let o=0;o.45*sampleRate&&(t.cutoffHz=.45*sampleRate);let s=t.reasonanceCb/10-3.01;t.reasonanceGain=VA(-1*s);let n=1/Math.sqrt(t.reasonanceGain),o=2*Math.PI*t.cutoffHz/sampleRate,g=Math.cos(o),C=Math.sin(o)/(2*t.reasonanceGain),c=(1-g)*n,h=c/2,d=h,Q=1+C,u=-2*g,l=1-C;t.a0=h/Q,t.a1=c/Q,t.a2=d/Q,t.a3=u/Q,t.a4=l/Q}};var Ps=.001,DA=100,Ks=96,RA=class e{constructor(A){this.sampleRate=A}currentSampleTime=0;sampleRate;currentAttenuationDb=DA;state=0;releaseStartDb=DA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=VA(A.volumeEnvelope.currentAttenuationDb),e.recalculate(A)}static intialize(A){e.recalculate(A,!0),A.volumeEnvelope.attenuation=A.volumeEnvelope.attenuationTarget}static recalculate(A,t=!1){let s=A.volumeEnvelope,n=d=>Math.max(0,Math.floor(HA(d)*s.sampleRate));s.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[a.initialAttenuation],1440))/10,s.sustainDbRelative=Math.min(DA,A.modulatedGenerators[a.sustainVolEnv]/10),t&&(s.attenuation=s.attenuationTarget);let o=Math.min(DA,s.sustainDbRelative+s.attenuation);s.attackDuration=n(A.modulatedGenerators[a.attackVolEnv]);let g=A.modulatedGenerators[a.decayVolEnv],C=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],c=(o-s.attenuation)/DA;s.decayDuration=n(g+C)*c,s.releaseDuration=n(A.modulatedGenerators[a.releaseVolEnv]),s.delayEnd=n(A.modulatedGenerators[a.delayVolEnv]),s.attackEnd=s.attackDuration+s.delayEnd;let h=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(s.holdEnd=n(A.modulatedGenerators[a.holdVolEnv]+h)+s.attackEnd,s.decayEnd=s.decayDuration+s.holdEnd,s.state===0&&s.attackEnd===0&&(s.currentAttenuationDb=s.attenuationTarget,s.state=2),A.isInRelease){s.attenuation=Math.min(DA,s.attenuationTarget);let d=Math.max(0,Math.min(DA,s.sustainDbRelative+s.attenuation)),Q=(d-s.attenuation)/DA;switch(s.decayDuration=n(g+C)*Q,s.state){case 0:s.releaseStartDb=DA;break;case 1:let l=(1-(s.attackEnd-s.releaseStartTimeSamples)/s.attackDuration)*VA(s.attenuation);s.releaseStartDb=20*Math.log10(l)*-1;break;case 2:s.releaseStartDb=s.attenuation;break;case 3:s.releaseStartDb=(1-(s.decayEnd-s.releaseStartTimeSamples)/s.decayDuration)*(d-s.attenuation)+s.attenuation;break;case 4:s.releaseStartDb=d;break;default:s.releaseStartDb=s.currentAttenuationDb}s.releaseStartDb=Math.max(0,Math.min(s.releaseStartDb,DA)),s.releaseStartDb>=Ks&&(A.finished=!0)}}static apply(A,t,s,n){let o=A.volumeEnvelope,g=s/10,C=n;if(A.isInRelease){let h=n*10,d=o.currentSampleTime-o.releaseStartTimeSamples;if(d>=o.releaseDuration){for(let l=0;l=Ks&&(A.finished=!0);return}let c=0;switch(o.state){case 0:for(;o.currentSampleTime=t.length)return;o.state++;case 1:for(;o.currentSampleTime=t.length)return}o.state++;case 2:for(;o.currentSampleTime=t.length)return;o.state++;case 3:for(;o.currentSampleTime=t.length)return}o.state++;case 4:for(;;){o.attenuation+=(o.attenuationTarget-o.attenuation)*C;let h=Math.min(DA,o.sustainDbRelative+o.attenuation);if(t[c]*=VA(h+g),o.currentAttenuationDb=h,o.currentSampleTime++,++c>=t.length)return}}}};var Vs=Math.PI/2,Os=.01;function Zs(e,A,t,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,RA.startRelease(A),YA.startRelease(A)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let g=A.targetKey,C=A.modulatedGenerators[a.fineTune]+e.customControllers[aA.channelTuning]+e.customControllers[aA.channelTransposeFine]+e.customControllers[aA.masterTuning]+e.channelOctaveTuning[A.midiNote%12]+e.keyCentTuning[A.midiNote],c=A.modulatedGenerators[a.coarseTune]+e.customControllers[aA.channelTuningSemitones],h=this.tunings[e.preset.program]?.[g];h?.midiNote>=0&&(g=h.midiNote,C+=h.centTuning),C+=(g-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let d=A.modulatedGenerators[a.vibLfoToPitch];if(d!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayVibLFO]),gA=we(A.modulatedGenerators[a.freqVibLFO]),oA=je(z,gA,currentTime);C+=oA*(d*e.customControllers[aA.modulationMultiplier])}let Q=A.modulatedGenerators[a.initialFilterFc],u=A.modulatedGenerators[a.modLfoToPitch],l=A.modulatedGenerators[a.modLfoToVolume],D=A.modulatedGenerators[a.modLfoToFilterFc],y=0;if(u+D+l!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayModLFO]),gA=we(A.modulatedGenerators[a.freqModLFO]),oA=je(z,gA,currentTime);C+=oA*(u*e.customControllers[aA.modulationMultiplier]),y=-oA*l,Q+=oA*D}if(e.channelVibrato.depth>0){let z=je(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);z&&(C+=z*e.channelVibrato.depth)}let k=A.modulatedGenerators[a.modEnvToPitch],F=A.modulatedGenerators[a.modEnvToFilterFc],q=YA.getValue(A,currentTime);Q+=q*F,C+=q*k;let M=~~(C+c*100);M!==A.currentTuningCents&&(A.currentTuningCents=M,A.currentTuningCalculated=Math.pow(2,M/1200));let v=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,T=new Float32Array(t.length);this.interpolationType===$e.linear?Js(A,T):qs(A,T),he.apply(A,T,Q),RA.apply(A,T,y,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(v-A.currentPan)*this.panSmoothingFactor;let I=Math.cos(Vs*A.currentPan)*this.panLeft,AA=Math.sin(Vs*A.currentPan)*this.panRight,K=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],j=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];vs(I,AA,T,t,s,n,K,o,j)}function Fo(e,A){let t=0;return e.drumChannel&&(t+=5),A.isInRelease&&(t-=5),t+=A.velocity/25,t-=A.volumeEnvelope.state,A.isInRelease&&(t-=5),t-=A.volumeEnvelope.currentAttenuationDb/50,t}function Xs(e){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=Fo(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let t=A.slice(0,e);for(let{channel:s,voice:n}of t){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function Ws(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTimezs=e);var Ro=function(e){var A,t,s,n,o,g,C,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",d=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=c.indexOf(e.charAt(d++)),o=c.indexOf(e.charAt(d++)),g=c.indexOf(e.charAt(d++)),C=c.indexOf(e.charAt(d++)),A=n<<2|o>>4,t=(15&o)<<4|g>>2,s=(3&g)<<6|C,h+=String.fromCharCode(A),g!==64&&(h+=String.fromCharCode(t)),C!==64&&(h+=String.fromCharCode(s));while(d1&&(I.thisProgram=process.argv[1].replace(/\\/g,"/")),I.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof pe))throw i}),process.on("unhandledRejection",function(i,E){process.exit(1)}),I.quit=function(i){process.exit(i)},I.inspect=function(){return"[Emscripten Module object]"}):gA?(typeof read<"u"&&(I.read=function(E){return read(E)}),I.readBinary=function(E){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(B=read(E,"binary"))=="object"),B)},typeof scriptArgs<"u"?I.arguments=scriptArgs:typeof arguments<"u"&&(I.arguments=arguments),typeof quit=="function"&&(I.quit=function(i){quit(i)})):(K||j)&&(K?document.currentScript&&(oA=document.currentScript.src):oA=self.location.href,oA=oA.indexOf("blob:")!==0?oA.split("/").slice(0,-1).join("/")+"/":"",I.read=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.send(null),B.responseText},j&&(I.readBinary=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),I.readAsync=function(E,B,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){B(R.response);return}f()},R.onerror=f,R.send(null)},I.setWindowTitle=function(i){document.title=i});var xe=I.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),xA=I.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||xe);for(e in AA)AA.hasOwnProperty(e)&&(I[e]=AA[e]);function Me(i){var E=l;return l=l+i+15&-16,E}function qt(i){var E=c[M>>2],B=E+i+15&-16;return c[M>>2]=B,B>=BA&&!zt()?(c[M>>2]=E,0):E}function vt(i,E){return E||(E=16),i=Math.ceil(i/E)*E}function Co(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var E=parseInt(i.substr(1));return _A(E%8==0),E/8}}function de(i){de.shown||(de.shown={}),de.shown[i]||(de.shown[i]=1,xA(i))}AA=void 0;var Eo={"f64-rem":function(i,E){return i%E},debugger:function(){}},rt=[];function Lo(i,E){for(var B=0,f=B;f>>0)+4294967296*+(E>>>0):+(i>>>0)+4294967296*+(0|E)}function at(i,E,B){return B&&B.length?I["dynCall_"+i].apply(null,[E].concat(B)):I["dynCall_"+i].call(null,E)}var Ne=0,Kt=0;function _A(i,E){i||ZA("Assertion failed: "+E)}function Pt(i){var E=I["_"+i];return _A(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Vt={stackSave:function(){ct()},stackRestore:function(){Qt()},arrayToC:function(i){var E,B,f=Ye(i.length);return E=i,B=f,n.set(E,B),f},stringToC:function(i){var E=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;E=Ye(B),Xt(i,E,B)}return E}},Bo={string:Vt.stringToC,array:Vt.arrayToC};function Ot(i,E,B,f,R){var P=Pt(i),W=[],x=0;if(f)for(var hA=0;hA>0]=E;break;case"i16":g[i>>1]=E;break;case"i32":c[i>>2]=E;break;case"i64":tempI64=[E>>>0,+fo(tempDouble=E)>=1?tempDouble>0?(0|po(+ts(tempDouble/4294967296),4294967295))>>>0:~~+mo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],c[i>>2]=tempI64[0],c[i+4>>2]=tempI64[1];break;case"float":d[i>>2]=E;break;case"double":Q[i>>3]=E;break;default:ZA("invalid type for setValue: "+B)}}function Yo(i,E,B){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[i>>0];case"i16":return g[i>>1];case"i32":case"i64":return c[i>>2];case"float":return d[i>>2];case"double":return Q[i>>3];default:ZA("invalid type for getValue: "+E)}return null}function Jo(i,E,B,f){typeof i=="number"?(P=!0,W=i):(P=!1,W=i.length);var R=typeof E=="string"?E:null;if(x=B==4?f:[typeof He=="function"?He:Me,Ye,Me,qt][B===void 0?2:B](Math.max(W,R?1:E.length)),P){for(f=x,_A((3&x)==0),hA=x+(-4&W);f>2]=0;for(hA=x+W;f>0]=0;return x}if(R==="i8")return i.subarray||i.slice?o.set(i,x):o.set(new Uint8Array(i),x),x;for(var P,W,x,hA,rA,iA,sA,J=0;J>0],(f!=0||E)&&(W++,!E||W!=E););E||(E=W);var x="";if(P<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(E,1024))),x=x?x+R:R,i+=1024,E-=1024;return x}return B=i,function(rA,iA){for(var sA=iA;rA[sA];)++sA;if(sA-iA>16&&rA.subarray&&Zt)return Zt.decode(rA.subarray(iA,sA));for(var J,fA,MA,NA,bA,ee,LA="";;){if(!(J=rA[iA++]))return LA;if(!(128&J)){LA+=String.fromCharCode(J);continue}if(fA=63&rA[iA++],(224&J)==192){LA+=String.fromCharCode((31&J)<<6|fA);continue}if(MA=63&rA[iA++],(240&J)==224?J=(15&J)<<12|fA<<6|MA:(NA=63&rA[iA++],(248&J)==240?J=(7&J)<<18|fA<<12|MA<<6|NA:(bA=63&rA[iA++],J=(252&J)==248?(3&J)<<24|fA<<18|MA<<12|NA<<6|bA:(1&J)<<30|fA<<24|MA<<18|NA<<12|bA<<6|(ee=63&rA[iA++]))),J<65536)LA+=String.fromCharCode(J);else{var Se=J-65536;LA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,B)}function vo(i){for(var E="";;){var B=n[i++>>0];if(!B)return E;E+=String.fromCharCode(B)}}function Ko(i,E){return function(f,R,P){for(var W=0;W>0]=f.charCodeAt(W);P||(n[R>>0]=0)}(i,E,!1)}var Zt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Le(i,E,B,f){if(!(f>0))return 0;for(var R=B,P=B+f-1,W=0;W=55296&&x<=57343&&(x=65536+((1023&x)<<10)|1023&i.charCodeAt(++W)),x<=127){if(B>=P)break;E[B++]=x}else if(x<=2047){if(B+1>=P)break;E[B++]=192|x>>6,E[B++]=128|63&x}else if(x<=65535){if(B+2>=P)break;E[B++]=224|x>>12,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=2097151){if(B+3>=P)break;E[B++]=240|x>>18,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=67108863){if(B+4>=P)break;E[B++]=248|x>>24,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else{if(B+5>=P)break;E[B++]=252|x>>30,E[B++]=128|x>>24&63,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}}return E[B]=0,B-R}function Xt(i,E,B){return Le(i,o,E,B)}function Ue(i){for(var E=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var Wt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Po(i){for(var E=i,B=E>>1;g[B];)++B;if((E=B<<1)-i>32&&Wt)return Wt.decode(o.subarray(i,E));for(var f=0,R="";;){var P=g[i+2*f>>1];if(P==0)return R;++f,R+=String.fromCharCode(P)}}function Vo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=E,R=(B-=2)<2*i.length?B/2:i.length,P=0;P>1]=W,E+=2}return g[E>>1]=0,E-f}function Oo(i){return 2*i.length}function Zo(i){for(var E=0,B="";;){var f=c[i+4*E>>2];if(f==0)return B;if(++E,f>=65536){var R=f-65536;B+=String.fromCharCode(55296|R>>10,56320|1023&R)}else B+=String.fromCharCode(f)}}function Xo(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=E,R=f+B-4,P=0;P=55296&&W<=57343&&(W=65536+((1023&W)<<10)|1023&i.charCodeAt(++P)),c[E>>2]=W,(E+=4)+4>R)break}return c[E>>2]=0,E-f}function Wo(i){for(var E=0,B=0;B=55296&&f<=57343&&++B,E+=4}return E}function _o(i){var E=Ue(i)+1,B=He(E);return B&&Le(i,n,B,E),B}function zo(i){var E=Ue(i)+1,B=Ye(E);return Le(i,n,B,E),B}function jo(i){return i}function $o(){var i,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return I.extraStackTrace&&(E+=` -`+I.extraStackTrace()),(i=E).replace(/__Z[\w\d_]+/g,function(B){var f,R=f=B;return B===R?B:B+" ["+R+"]"})}function It(i,E){return i%E>0&&(i+=E-i%E),i}function _t(i){I.buffer=s=i}function gt(){I.HEAP8=n=new Int8Array(s),I.HEAP16=g=new Int16Array(s),I.HEAP32=c=new Int32Array(s),I.HEAPU8=o=new Uint8Array(s),I.HEAPU16=C=new Uint16Array(s),I.HEAPU32=h=new Uint32Array(s),I.HEAPF32=d=new Float32Array(s),I.HEAPF64=Q=new Float64Array(s)}function zt(){var i=I.usingWasm?65536:16777216,E=2147483648-i;if(c[M>>2]>E)return!1;var B=BA;for(BA=Math.max(BA,16777216);BA>2];)BA=BA<=536870912?It(2*BA,i):Math.min(It((3*BA+2147483648)/4,i),E);var f=I.reallocBuffer(BA);return f&&f.byteLength==BA?(_t(f),gt(),!0):(BA=B,!1)}u=l=y=k=F=q=M=0,D=!1,I.reallocBuffer||(I.reallocBuffer=function(i){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,i);else{var E,B=n;E=new ArrayBuffer(i),new Int8Array(E).set(B)}}catch{return!1}return!!So(E)&&E});try{(v=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{v=function(E){return E.byteLength}}var Ct=I.TOTAL_STACK||5242880,BA=I.TOTAL_MEMORY||16777216;function Qo(){return BA}function fe(i){for(;i.length>0;){var E=i.shift();if(typeof E=="function"){E();continue}var B=E.func;typeof B=="number"?E.arg===void 0?I.dynCall_v(B):I.dynCall_vi(B,E.arg):B(E.arg===void 0?null:E.arg)}}BA=0?i:E<=32?2*Math.abs(1<=f&&(E<=32||i>f)&&(i=-2*f+i),i}var fo=Math.abs,mo=Math.ceil,ts=Math.floor,po=Math.min,Ae=0,ht=null,me=null;function rr(i){return i}I.preloadedImages={},I.preloadedAudios={};var ss="data:application/octet-stream;base64,";function Te(i){return String.prototype.startsWith?i.startsWith(ss):i.indexOf(ss)===0}(function(){var E="main.wast",B="main.wasm",f="main.temp.asm.js";Te(E)||(E=GA(E)),Te(B)||(B=GA(B)),Te(f)||(f=GA(f));var R={global:null,env:null,asm2wasm:Eo,parent:I},P=null;function W(sA){return sA}function x(){try{if(I.wasmBinary)return new Uint8Array(I.wasmBinary);if(I.readBinary)return I.readBinary(B);throw"both async and sync fetching of the wasm failed"}catch(sA){ZA(sA)}}I.asmPreload=I.asm;var hA=I.reallocBuffer,rA=function(sA){sA=It(sA,I.usingWasm?65536:16777216);var J=I.buffer.byteLength;if(I.usingWasm)try{var fA=I.wasmMemory.grow((sA-J)/65536);return fA!==-1?I.buffer=I.wasmMemory.buffer:null}catch{return null}};I.reallocBuffer=function(sA){return iA==="asmjs"?hA(sA):rA(sA)};var iA="";I.asm=function(sA,J,fA){var MA;if(!(J=MA=J).table){var NA,bA=I.wasmTableSize;bA===void 0&&(bA=1024);var ee=I.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?J.table=new WebAssembly.Table({initial:bA,maximum:ee,element:"anyfunc"}):J.table=new WebAssembly.Table({initial:bA,element:"anyfunc"}):J.table=Array(bA),I.wasmTable=J.table}return J.memoryBase||(J.memoryBase=I.STATIC_BASE),J.tableBase||(J.tableBase=0),NA=function(Se,oe,ut){if(typeof WebAssembly!="object")return xA("no native wasm support detected"),!1;if(!(I.wasmMemory instanceof WebAssembly.Memory))return xA("no native wasm Memory in use"),!1;function Je(JA,qA){if((P=JA.exports).memory){var ye,dt,rs;ye=P.memory,dt=I.buffer,ye.byteLength0?B:Ue(i)+1,R=Array(f),P=Le(i,R,0,R.length);return E&&(R.length=P),R}function gr(i){for(var E=[],B=0;B255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}l+=16,M=Me(4),F=(y=k=vt(l))+Ct,q=vt(F),c[M>>2]=q,D=!0,I.wasmTableSize=4,I.wasmMaxTableSize=4,I.asmGlobalArg={},I.asmLibraryArg={abort:ZA,assert:_A,enlargeMemory:zt,getTotalMemory:Qo,abortOnCannotGrowMemory:function(){ZA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+BA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,B,f){var R=ct();try{return I.dynCall_iii(E,B,f)}catch(P){if(Qt(R),typeof P!="number"&&P!=="longjmp")throw P;I.setThrew(1,0)}},___assert_fail:function(E,B,f,R){ZA("Assertion failed: "+be(E)+", at: "+[B?be(B):"unknown filename",f,R?be(R):"unknown function"])},___setErrNo:function(E){return I.___errno_location&&(c[I.___errno_location()>>2]=E),E},_abort:function(){I.abort()},_emscripten_memcpy_big:function(E,B,f){return o.set(o.subarray(B,B+f),E),E},_llvm_floor_f64:ts,DYNAMICTOP_PTR:M,tempDoublePtr:kA,ABORT:Ne,STACKTOP:k,STACK_MAX:F};var ns=I.asm(I.asmGlobalArg,I.asmLibraryArg,s);I.asm=ns,I.___errno_location=function(){return I.asm.___errno_location.apply(null,arguments)};var So=I._emscripten_replace_memory=function(){return I.asm._emscripten_replace_memory.apply(null,arguments)};I._free=function(){return I.asm._free.apply(null,arguments)};var He=I._malloc=function(){return I.asm._malloc.apply(null,arguments)};I._memcpy=function(){return I.asm._memcpy.apply(null,arguments)},I._memset=function(){return I.asm._memset.apply(null,arguments)},I._sbrk=function(){return I.asm._sbrk.apply(null,arguments)},I._stb_vorbis_js_channels=function(){return I.asm._stb_vorbis_js_channels.apply(null,arguments)},I._stb_vorbis_js_close=function(){return I.asm._stb_vorbis_js_close.apply(null,arguments)},I._stb_vorbis_js_decode=function(){return I.asm._stb_vorbis_js_decode.apply(null,arguments)},I._stb_vorbis_js_open=function(){return I.asm._stb_vorbis_js_open.apply(null,arguments)},I._stb_vorbis_js_sample_rate=function(){return I.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},I.establishStackSpace=function(){return I.asm.establishStackSpace.apply(null,arguments)},I.getTempRet0=function(){return I.asm.getTempRet0.apply(null,arguments)},I.runPostSets=function(){return I.asm.runPostSets.apply(null,arguments)},I.setTempRet0=function(){return I.asm.setTempRet0.apply(null,arguments)},I.setThrew=function(){return I.asm.setThrew.apply(null,arguments)};var Ye=I.stackAlloc=function(){return I.asm.stackAlloc.apply(null,arguments)},Qt=I.stackRestore=function(){return I.asm.stackRestore.apply(null,arguments)},ct=I.stackSave=function(){return I.asm.stackSave.apply(null,arguments)};function pe(i){this.name="ExitStatus",this.message="Program terminated with exit("+i+")",this.status=i}function lt(i){i=i||I.arguments,!(Ae>0)&&(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)lo(I.preRun.shift());fe(jt)}(),!(Ae>0)&&(I.calledRun||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),E()},1)):E())));function E(){!I.calledRun&&(I.calledRun=!0,Ne||(Bt||(Bt=!0,fe(Et)),fe($t),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)uo(I.postRun.shift());fe(es)}()))}}function Cr(i,E){(!E||!I.noExitRuntime||i!==0)&&(I.noExitRuntime||(Ne=!0,Kt=i,k=T,fe(As),co=!0,I.onExit&&I.onExit(i)),I.quit(i,new pe(i)))}function ZA(i){throw I.onAbort&&I.onAbort(i),i!==void 0?(xe(i),xA(i),i=JSON.stringify(i)):i="",Ne=!0,Kt=1,"abort("+i+"). Build with -s ASSERTIONS=1 for more info."}if(I.dynCall_iii=function(){return I.asm.dynCall_iii.apply(null,arguments)},I.asm=ns,I.ccall=Ot,I.cwrap=function(E,B,f,R){var P=(f=f||[]).every(function(W){return W==="number"});return B!=="string"&&P&&!R?Pt(E):function(){return Ot(E,B,f,arguments,R)}},pe.prototype=Error(),pe.prototype.constructor=pe,me=function i(){I.calledRun||lt(),I.calledRun||(me=i)},I.run=lt,I.abort=ZA,I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();I.noExitRuntime=!0,lt(),I.onRuntimeInitialized=()=>{_s=!0,zs()},OA.decode=function(i){return function(B){if(!_s)throw Error("Not initialized");var f={};function R(oe){return new Int32Array(I.HEAPU8.buffer,oe,1)[0]}function P(oe,ut){var Je=new ArrayBuffer(ut*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(Je);return re.set(new Float32Array(I.HEAPU8.buffer,oe,ut)),re}f.open=I.cwrap("stb_vorbis_js_open","number",[]),f.close=I.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=I.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=I.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=I.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var W,x,hA,rA,iA=f.open(),sA=(W=B,x=B.byteLength,hA=I._malloc(x),(rA=new Uint8Array(I.HEAPU8.buffer,hA,x)).set(new Uint8Array(W,0,x)),rA),J=I._malloc(4),fA=I._malloc(4),MA=f.decode(iA,sA.byteOffset,sA.byteLength,J,fA);if(I._free(sA.byteOffset),MA<0)throw f.close(iA),I._free(J),Error("stbvorbis decode failed: "+MA);for(var NA=f.channels(iA),bA=Array(NA),ee=new Int32Array(I.HEAPU32.buffer,R(J),NA),LA=0;LA=0&&(s=this.workletProcessorChannels[t]),e.messageType){case tA.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case tA.noteOff:this.noteOff(t,A);break;case tA.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case tA.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case tA.customcCcChange:s.customControllers[A[0]]=A[1];break;case tA.killNote:this.killNote(t,A);break;case tA.programChange:this.programChange(t,A[0],A[1]);break;case tA.channelPressure:this.channelPressure(t,A);break;case tA.polyPressure:this.polyPressure(t,A[0],A[1]);break;case tA.ccReset:t===TA?this.resetAllControllers():this.resetControllers(t);break;case tA.systemExclusive:this.systemExclusive(A);break;case tA.setChannelVibrato:if(t===TA)for(let g=0;g{let t=(A.midiControllers[CA+V.pitchWheelRange]>>7)+(A.midiControllers[CA+V.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[CA+V.pitchWheel],pitchBendRangeSemitones:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:mA.channelProperties,messageData:e})}function Go(e,A,t){let s=e,n=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function en(e,A=0){let t=e[0];if(!(this.deviceID!==TA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:N(`%cUnrecognized SysEx: %c${QA(e)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(e[2]){case 4:let n;switch(e[3]){case 1:let o=e[5]<<7|e[4];this.setMIDIVolume(o/16384),m(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(C),m(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let c=(e[5]<<7|e[6])-8192;n=Math.floor(c/81.92),this.setMasterTuning(n),m(`%cMaster Fine Tuning. Cents: %c${n}`,r.info,r.value);break;case 4:n=(e[5]-64)*100,this.setMasterTuning(n),m(`%cMaster Coarse Tuning. Cents: %c${n}`,r.info,r.value);break;default:N(`%cUnrecognized MIDI Device Control Real-time message: %c${QA(e)}`,r.warn,r.unrecognized)}break;case 9:e[3]===1?(m("%cGM system on",r.info),this.system="gm"):e[3]===3?(m("%cGM2 system on",r.info),this.system="gm2"):(m("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(e[3]){case 2:case 7:let o=4;e[3]===7&&o++;let g=e[o++],C=e[o++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,c);for(let h=0;h<7;h++)(e[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,c);for(let h=0;h<7;h++)(e[6]>>h&1)===1&&this.setOctaveTuning(h+A,c);m(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${c.join(" ")}`,r.info,r.value);break;default:N(`%cUnrecognized MIDI Tuning standard message: %c${QA(e)}`,r.warn,r.unrecognized);break}break;default:N(`%cUnrecognized MIDI Realtime/non realtime message: %c${QA(e)}`,r.warn,r.unrecognized)}break;case 65:let s=function(){N(`%cUnrecognized Roland %cGS %cSysEx: %c${QA(e)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(e[2]===66&&e[3]===18){let n=e[7];if(e[6]===127){n===0?(m("%cGS system on",r.info),this.system="gs"):n===127&&(m("%cGS system off, switching to GM2",r.info),this.system="gm2");return}else if(e[4]===64){if((e[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A;switch(e[6]){default:s();break;case 21:let g=n>0&&e[5]>>4;this.setDrums(o,g),m(`%cChannel %c${o}%c ${g?"is now a drum channel":"now isn't a drum channel"}%c via: %c${QA(e)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=n-64;this.transposeChannel(o,C),m(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${QA(e)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let c=n-64;m(`%cChannel %c${o}%c scale tuning. Cents %c${c}%c, with %c${QA(e)}`,r.info,r.recognized,r.info,r.value,r.info,r.value),this.setChannelTuning(o,c);break}return}else if(e[5]===0&&e[6]===6){m(`%cRoland GS Master Pan set to: %c${n}%c with: %c${QA(e)}`,r.info,r.value,r.info,r.value),this.setMasterPan((n-64)/64);return}else if(e[5]===0&&e[6]===5){let o=n-64;m(`%cRoland GS Master Key-Shift set to: %c${o}%c with: %c${QA(e)}`,r.info,r.value,r.info,r.value),this.setMasterTuning(o*100);return}else if(e[5]===0&&e[6]===4){m(`%cRoland GS Master Volume set to: %c${n}%c with: %c${QA(e)}`,r.info,r.value,r.info,r.value),this.setMIDIVolume(n/127);return}}s();return}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),m(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${QA(e)}`,r.info,r.value,r.info,r.value);return}else{N(`%cUnrecognized Roland SysEx: %c${QA(e)}`,r.warn,r.unrecognized);return}case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:let n=e[6];this.setMIDIVolume(n/127),m(`%cXG master volume. Volume: %c${n}`,r.info,r.recognized);break;case 6:let o=e[6]-64;this.transposeAllChannels(o),m(`%cXG master transpose. Volume: %c${o}`,r.info,r.recognized);break;case 126:m("%cXG system on",r.info),this.system="xg";break}else if(e[3]===8){if(this.system!=="xg")return;let n=e[4]+A;if(n>=this.workletProcessorChannels.length)return;let o=e[6];switch(e[5]){case 1:this.controllerChange(n,p.bankSelect,o);break;case 2:this.controllerChange(n,p.lsbForControl0BankSelect,o);break;case 3:this.programChange(n,o);break;case 8:let g=this.workletProcessorChannels[n];if(g.drumChannel)return;let C=o-64;g.channelTransposeKeyShift=C;break;case 11:this.controllerChange(n,p.mainVolume,o);break;case 14:let c=o;c===0&&(c=Math.floor(Math.random()*127)),this.controllerChange(n,p.pan,c);break;case 19:this.controllerChange(n,p.effects1Depth,o);break;case 18:this.controllerChange(n,p.effects3Depth,o);break;default:N(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&N(`%cUnrecognized Yamaha XG SysEx: %c${QA(e)}`,r.warn,r.unrecognized);else this.system==="xg"&&N(`%cUnrecognized Yamaha SysEx: %c${QA(e)}`,r.warn,r.unrecognized);break}}function tn(e,A,t){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=e[A.sourceIndex];else{let c=A.sourceIndex+CA;switch(A.sourceIndex){case V.noController:s=16383;break;case V.noteOnKeyNum:s=t.midiNote<<7;break;case V.noteOnVelocity:s=t.velocity<<7;break;case V.polyPressure:s=t.pressure<<7;break;default:s=e[c];break}}let n=dA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let c=A.secSrcIndex+CA;switch(A.secSrcIndex){case V.noController:o=16383;break;case V.noteOnKeyNum:o=t.midiNote<<7;break;case V.noteOnVelocity:o=t.velocity<<7;break;case V.polyPressure:o=t.pressure<<7;break;default:o=e[c]}}let g=dA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=n*g*A.transformAmount;return A.transformType===2?Math.abs(C):C}function XA(e,A,t=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:g}=e;if(YA.recalculate(e),t===-1){g.set(o),n.forEach(h=>{g[h.modulatorDestination]+=tn(A,h,e)}),RA.recalculate(e);return}let C=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),c=new Set;n.forEach(h=>{if(h.sourceUsesCC===t&&h.sourceIndex===s||h.secSrcUsesCC===t&&h.secSrcIndex===s){let d=h.modulatorDestination;c.has(d)||(g[d]=o[d],n.forEach(Q=>{Q.modulatorDestination===d&&(g[d]+=tn(A,Q,e))}),c.add(d))}}),[...c].some(h=>C.has(h))&&RA.recalculate(e)}var dA=[];for(let e=0;e<4;e++){dA[e]=[[new Float32Array(IA),new Float32Array(IA)],[new Float32Array(IA),new Float32Array(IA)]];for(let A=0;A200&&t<40||this.highPerformanceMode&&t<10||g.isMuted)return;let C=A+g.channelTransposeKeyShift;if(A>127||A<0)return;let c=g.preset.program;this.tunings[c]?.[A]?.midiNote>=0&&(C=this.tunings[c]?.[A].midiNote);let h=this.getWorkletVoices(e,C,t,g,o,s),d=g.voices;h.forEach(Q=>{let u=Q.generators[a.exclusiveClass];u!==0&&d.forEach(l=>{l.generators[a.exclusiveClass]===u&&(this.releaseVoice(l),l.modulatedGenerators[a.releaseVolEnv]=-7e3,l.modulatedGenerators[a.releaseModEnv]=-7e3,RA.recalculate(l),YA.recalculate(l))}),XA(Q,g.midiControllers),RA.intialize(Q),Q.currentPan=(Math.max(-500,Math.min(500,Q.modulatedGenerators[a.pan]))+500)/1e3}),this.totalVoicesAmount+=h.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(h.length),d.push(...h),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:e,velocity:t}))}function nn(e,A){if(A>127||A<0){N("Received a noteOn for note",A,"Ignoring.");return}let t=A+this.workletProcessorChannels[e].channelTransposeKeyShift,s=this.workletProcessorChannels[e].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(t=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[e].drumChannel){this.killNote(e,t);return}this.workletProcessorChannels[e].voices.forEach(o=>{o.midiNote!==t||o.isInRelease===!0||(this.workletProcessorChannels[e].holdPedal?this.workletProcessorChannels[e].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:e})}function on(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function rn(e,A=!1){let t=this.workletProcessorChannels[e].voices;A?(t.length=0,this.workletProcessorChannels[e].sustainedVoices.length=0,this.sendChannelProperties()):(t.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[e].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function an(e=!1){m("%cStop all received!",r.info);for(let A=0;AXA(n,this.workletProcessorChannels[e].midiControllers,0,V.pitchWheel)),this.sendChannelProperties()}function cn(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[CA+V.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>XA(s,t.midiControllers,0,V.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function ln(e,A,t){this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote===A&&(s.pressure=t,XA(s,this.workletProcessorChannels[e].midiControllers,0,V.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function un(e,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[e].channelOctaveTuning=A}function dn(e,A,t,s=!1){let n=this.workletProcessorChannels[e];if(n===void 0){N(`Trying to access channel ${e} which does not exist... ignoring!`);return}if(A>=p.lsbForControl1ModulationWheel&&A<=p.lsbForControl13EffectControl2&&A!==p.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|t&127,n.voices.forEach(g=>XA(g,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(e);break;case p.allSoundOff:this.stopAll(e,!0);break;case p.bankSelect:let o=t;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(e,!0):e%16!==SA&&this.setDrums(e,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[p.bankSelect])}n.midiControllers[p.bankSelect]=o;break;case p.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||t!==127&&(n.midiControllers[p.bankSelect]=t):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=t);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|t,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=t,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=t,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=t,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(e,t);break;case p.lsbForControl6DataEntry:this.dataEntryFine(e,t);break;case p.resetAllControllers:this.resetControllers(e);break;case p.sustainPedal:t>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(g=>{this.releaseVoice(g)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=t<<7,n.voices.forEach(g=>XA(g,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function fn(e){this.midiVolume=e,this.setMasterPan(this.pan)}function mn(e){this.masterGain=e*bt,this.setMasterPan(this.pan)}function pn(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function Sn(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function yn(e){this.workletProcessorChannels[e].lockGSNRPNParams=!0,this.workletProcessorChannels[e].channelVibrato.rate=0,this.workletProcessorChannels[e].channelVibrato.delay=0,this.workletProcessorChannels[e].channelVibrato.depth=0}function Dn(e,A,t,s){this.workletProcessorChannels[e].lockGSNRPNParams||(this.workletProcessorChannels[e].channelVibrato.rate=t,this.workletProcessorChannels[e].channelVibrato.delay=s,this.workletProcessorChannels[e].channelVibrato.depth=A)}function kn(e,A){let t=this.workletProcessorChannels[e],s=()=>{t.channelVibrato.delay===0&&t.channelVibrato.rate===0&&t.channelVibrato.depth===0&&(t.channelVibrato.depth=50,t.channelVibrato.rate=8,t.channelVibrato.delay=.6)};switch(t.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs"||t.lockGSNRPNParams)return;switch(t.NRPCoarse){default:if(A===64)return;N(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 1:switch(t.NRPFine){default:if(A===64)return;N(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;s(),t.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${e}%c is now set to %c${A} = ${t.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;s(),t.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${e}%c is now set to %c${A} = ${t.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;s(),t.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${e}%c is now set to %c${A} = ${t.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let g=A;this.controllerChange(e,p.brightness,A),m(`%cFilter cutoff for %c${e}%c is now set to %c${g}`,r.info,r.recognized,r.info,r.value)}break;case 24:let n=A-64;t.keyCentTuning[t.NRPFine]=n*100,m(`%cGS drum key tuning. MIDI note: %c${t.NRPFine}%c semitones: %c${n}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(e,p.effects1Depth,o),m(`%cGS Drum reverb for %c${e}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:N(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:t.midiControllers[CA+V.pitchWheelRange]=A<<7,m(`%cChannel ${e} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(e,A-64);break;case 1:this.setChannelTuning(e,A-64,!1);break;case 5:this.setModulationDepth(e,A*100);break;case 16383:this.resetParameters(e);break}}}function wn(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[CA+V.pitchWheelRange]|=A;let s=(t.midiControllers[CA+V.pitchWheelRange]>>7)+A/127;m(`%cChannel ${e} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=t.customControllers[aA.channelTuning]<<7|A;this.setChannelTuning(e,o*.01220703125);break;case 5:let C=t.customControllers[aA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,C);break;case 16383:this.resetParameters(e);break}}}function Fn(){m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let e=0;e{this.workletProcessorChannels[e].lockedControllers[s]&&this.callEvent("controllerchange",{channel:e,controllerNumber:s,controllerValue:this.workletProcessorChannels[e].midiControllers[s]>>7})};if(t(p.mainVolume),t(p.pan),t(p.expressionController),t(p.modulationWheel),t(p.effects3Depth),t(p.effects1Depth),this.workletProcessorChannels[e].lockedControllers[CA+V.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[CA+V.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:e,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Ke}function Rn(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((o,g,C)=>(g&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(KA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[aA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[aA.channelTransposeFine]=n,this.resetParameters(e)}function Gn(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function xn(){let e=4;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==a.sampleID&&g.generatorType!==a.keyRange&&g.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new H(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=t;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),t++}return cA(A,0),nA(new $("igen",A.length,A))}function Mn(e,A,t,s,n){let o=this.samples.map((h,d)=>{t&&h.compressSample(s,n);let Q=h.getRawData();return m(`%cEncoded sample %c${d}. ${h.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),Q}),g=this.samples.reduce((h,d,Q)=>h+o[Q].length+46,0),C=new H(g);this.samples.forEach((h,d)=>{let Q=o[d],u,l,D=Q.length;h.isCompressed?(u=C.currentIndex,l=u+Q.length):(u=C.currentIndex/2,l=u+Q.length/2,D+=46),e.push(u),C.set(Q,C.currentIndex),C.currentIndex+=D,A.push(l)});let c=nA(new $("smpl",C.length,C),new H([115,100,116,97]));return nA(new $("LIST",c.length,c))}function Nn(e,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{FA(s,n.sampleName,20);let g=e[o];cA(s,g);let C=A[o];cA(s,C);let c=n.sampleLoopStartIndex/2+g,h=n.sampleLoopEndIndex/2+g;n.isCompressed&&(c-=g,h-=g),cA(s,c),cA(s,h),cA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,Y(s,n.sampleLink),Y(s,n.sampleType)}),FA(s,"EOS",46),nA(new $("shdr",s.length,s))}function bn(){let e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=t;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),t++}return ge(A,0,10),nA(new $("imod",A.length,A))}function Ln(){let e=this.instruments.reduce((o,g)=>g.instrumentZones.length*4+o,4),A=new H(e),t=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=t;for(let g of o.instrumentZones)g.zoneID=t,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,t++}return Y(A,s),Y(A,n),nA(new $("ibag",A.length,A))}function Un(){let e=this.instruments.length*22+22,A=new H(e),t=0,s=0;for(let n of this.instruments)FA(A,n.instrumentName,20),Y(A,t),t+=n.instrumentZones.length,n.instrumentID=s,s++;return FA(A,"EOI",20),Y(A,t),nA(new $("inst",A.length,A))}function Tn(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==a.instrument&&g.generatorType!==a.keyRange&&g.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+n),0);let A=new H(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=t;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue);t+=n.generators.length}return Y(A,0),Y(A,0),nA(new $("pgen",A.length,A))}function Hn(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=t;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),t++}return ge(A,0,10),nA(new $("pmod",A.length,A))}function Yn(){let e=this.presets.reduce((o,g)=>g.presetZones.length*4+o,4),A=new H(e),t=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=t;for(let g of o.presetZones)g.zoneID=t,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,t++}return Y(A,s),Y(A,n),nA(new $("pbag",A.length,A))}function Jn(){let e=this.presets.length*38+38,A=new H(e),t=0;for(let s of this.presets)FA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,t),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),t+=s.presetZones.length;return FA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,t),cA(A,0),cA(A,0),cA(A,0),nA(new $("phdr",A.length,A))}var xo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function qn(e=xo){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");pA("%cSaving soundfont...",r.info),m(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[v,T]of Object.entries(this.soundFontInfo))if(v==="ifil"||v==="iver"){let I=parseInt(T.split(".")[0]),AA=parseInt(T.split(".")[1]),K=new H(4);Y(K,I),Y(K,AA),A.push(nA(new $(v,4,K)))}else if(v==="DMOD")A.push(nA(new $(v,T.length,T)));else{let I=new H(T.length);FA(I,T),A.push(nA(new $(v,T.length,I)))}let t=De([new H([73,78,70,79]),...A]),s=nA(new $("LIST",t.length,t));m("%cWriting SDTA...",r.info);let n=[],o=[],g=Mn.call(this,n,o,e?.compress,e?.compressionQuality||.5,e.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=Nn.call(this,n,o);m("%cWriting IGEN...",r.info);let c=xn.call(this);m("%cWriting IMOD...",r.info);let h=bn.call(this);m("%cWriting IBAG...",r.info);let d=Ln.call(this);m("%cWriting INST...",r.info);let Q=Un.call(this),u=Tn.call(this);m("%cWriting PMOD...",r.info);let l=Hn.call(this);m("%cWriting PBAG...",r.info);let D=Yn.call(this);m("%cWriting PHDR...",r.info);let y=Jn.call(this),k=De([new H([112,100,116,97]),y,D,l,u,Q,d,h,c,C]),F=nA(new $("LIST",k.length,k));m("%cWriting the output file...",r.info);let q=De([new H([115,102,98,107]),s,g,F]),M=nA(new $("RIFF",q.length,q));return m(`%cSaved succesfully! Final file size: %c${M.length}`,r.info,r.recognized),X(),M}var ne=class e{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Oe.map(t=>eA.copy(t)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}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()}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()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,t,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===t);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===t)}setSampleIDOffset(A){this.presets.forEach(t=>t.sampleIDOffset=A)}getPreset(A,t){let s=this.presets.find(n=>n.bank===A&&n.program===t);return s||(A===128?(s=this.presets.find(n=>n.bank===128&&n.program===t),s||(s=this.presets.find(n=>n.bank===128))):s=this.presets.find(n=>n.program===t&&n.bank!==128),s&&N(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(N(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let t=this.presets.find(s=>s.presetName===A);return t||(N("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}static mergeSoundfonts(...A){let t=A.shift(),s=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(g=>g.bank===o.bank&&g.program===o.program)===void 0&&s.push(o)});return new e({presets:s,info:t.soundFontInfo})}};ne.prototype.write=qn;function vn(e){pA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,t){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,t){let s=this.foundSamplesAndGenerators[A][t];if(s)return s;if(this.presetZones.length<1)return[];function n(Q,u,l){return l>=Q&&l<=u}function o(Q,u){Q.push(...u.filter(l=>!Q.find(D=>D.generatorType===l.generatorType)))}function g(Q,u){Q.push(...u.filter(l=>!Q.find(D=>eA.isIdentical(l,D))))}let C=[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(Q=>n(Q.keyRange.min,Q.keyRange.max,A)&&n(Q.velRange.min,Q.velRange.max,t)&&!Q.isGlobal).forEach(Q=>{if(Q.instrument.instrumentZones.length<1)return;let u=Q.generators,l=Q.modulators,D=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].generators]:[],y=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].modulators]:[];Q.instrument.instrumentZones.filter(F=>n(F.keyRange.min,F.keyRange.max,A)&&n(F.velRange.min,F.velRange.max,t)&&!F.isGlobal).forEach(F=>{let q=[...F.generators],M=[...F.modulators];o(u,c),o(q,D),g(l,h),g(M,y),g(M,this.defaultModulators);let v=[...M];for(let T=0;TeA.isIdentical(I,K));AA!==-1?v[AA]=v[AA].sumTransform(I):v.push(I)}C.push({instrumentGenerators:q,presetGenerators:u,modulators:v,sample:F.sample,sampleID:F.generators.find(T=>T.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=C,C}};var Fe=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Fe{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},ce=class extends Fe{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var le=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.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 At=class extends Qe{constructor(A,t){super(Oe),this.program=t&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new le,this.DLSInstrument.addUseCount();let n=new ce;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function Kn(e){this.verifyHeader(e,"LIST"),this.verifyText(O(e.chunkData,4),"ins ");let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(Z(e.chunkData));let t=A.find(l=>l.header==="insh");if(!t)throw X(),new Error("No instrument header!");let s=S(t.chunkData,4),n=S(t.chunkData,4),o=S(t.chunkData,4),g=new At(n,o),C="unnamedPreset",c=yA(A,"INFO");if(c){let l=Z(c.chunkData);for(;l.header!=="INAM";)l=Z(c.chunkData);C=O(l.chunkData,l.chunkData.length).trim()}g.presetName=C,g.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let h=yA(A,"lrgn");if(!h)throw X(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let Q=yA(A,"lart"),u=yA(A,"lar2");this.readLart(Q,u,d),g.DLSInstrument.instrumentZones.push(d);for(let l=0;l>10&15;F===lA.linear&&k!==lA.linear&&(F=k);let q=s>>14&1,M=s>>15&1;g===a.initialAttenuation&&(M=!M),Q=vA(F,q,M,C.isCC,C.enum)}let u=s>>4&15,l=s>>8&1,D=s>>9&1,y=vA(u,l,D,d.isCC,d.enum);if(c){let k=y;y=Q,Q=k}return new eA({srcEnum:Q,secSrcEnum:y,dest:g,transform:0,amt:n})}function Lt(e,A){let t=e.chunkData,s=[],n=[];S(t,4);let o=S(t,4);for(let g=0;g>16;if(C===0&&c===0&&d===0){let l;switch(h){case G.pan:l=new b(a.pan,u);break;case G.gain:l=new b(a.initialAttenuation,-u*10/.4);break;case G.filterCutoff:l=new b(a.initialFilterFc,u);break;case G.filterQ:l=new b(a.initialFilterQ,u);break;case G.modLfoFreq:l=new b(a.freqModLFO,u);break;case G.modLfoDelay:l=new b(a.delayModLFO,u);break;case G.vibLfoFreq:l=new b(a.freqVibLFO,u);break;case G.vibLfoDelay:l=new b(a.delayVibLFO,u);break;case G.volEnvDelay:l=new b(a.delayVolEnv,u);break;case G.volEnvAttack:l=new b(a.attackVolEnv,u);break;case G.volEnvHold:l=new b(a.holdVolEnv,u);break;case G.volEnvDecay:l=new b(a.decayVolEnv,u);break;case G.volEnvRelease:l=new b(a.releaseVolEnv,u);break;case G.volEnvSustain:let D=(1e3-u)/10;l=new b(a.sustainVolEnv,D*10);break;case G.modEnvDelay:l=new b(a.delayModEnv,u);break;case G.modEnvAttack:l=new b(a.attackModEnv,u);break;case G.modEnvHold:l=new b(a.holdModEnv,u);break;case G.modEnvDecay:l=new b(a.decayModEnv,u);break;case G.modEnvRelease:l=new b(a.releaseModEnv,u);break;case G.modEnvSustain:let y=1e3-u;l=new b(a.sustainModEnv,y);break;case G.reverbSend:l=new b(a.reverbEffectsSend,u);break;case G.chorusSend:l=new b(a.chorusEffectsSend,u);break;case G.pitch:let k=Math.floor(u/100),F=Math.floor(u-k*100);l=new b(a.fineTune,F),s.push(new b(a.coarseTune,k));break}l&&s.push(l)}else{let l=!0;if(c===_.none)if(C===_.modLfo&&h===G.pitch)s.push(new b(a.modLfoToPitch,u));else if(C===_.modLfo&&h===G.gain)s.push(new b(a.modLfoToVolume,u));else if(C===_.modLfo&&h===G.filterCutoff)s.push(new b(a.modLfoToFilterFc,u));else if(C===_.vibratoLfo&&h===G.pitch)s.push(new b(a.vibLfoToPitch,u));else if(C===_.modEnv&&h===G.pitch)s.push(new b(a.modEnvToPitch,u));else if(C===_.modEnv&&h===G.filterCutoff)s.push(new b(a.modEnvToFilterFc,u));else if(C===_.keyNum&&h===G.volEnvHold){s.push(new b(a.keyNumToVolEnvHold,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.holdVolEnv&&(y.generatorValue+=D)})}else if(C===_.keyNum&&h===G.volEnvDecay){s.push(new b(a.keyNumToVolEnvDecay,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.decayVolEnv&&(y.generatorValue+=D)})}else if(C===_.keyNum&&h===G.modEnvHold){s.push(new b(a.keyNumToModEnvHold,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.holdModEnv&&(y.generatorValue+=D)})}else if(C===_.keyNum&&h===G.modEnvDecay){s.push(new b(a.keyNumToModEnvDecay,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.decayModEnv&&(y.generatorValue+=D)})}else l=!1;else l=!1;if(l===!1){let D=Vn(C,c,h,d,u);D?(n.push(D),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):N("Failed converting to SF2 Modulator!")}}}return n.find(g=>g.modulatorDestination===a.reverbEffectsSend)===void 0&&n.push(new eA({srcEnum:219,dest:a.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(g=>g.modulatorDestination===a.chorusEffectsSend)===void 0&&n.push(new eA({srcEnum:221,dest:a.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new eA({srcEnum:129,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new eA({srcEnum:13,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function On(e,A,t){if(e)for(;e.chunkData.currentIndexe.chunkData.currentIndex;)A.push(Z(e.chunkData));let t=A.find(AA=>AA.header==="rgnh"),s=S(t.chunkData,2),n=S(t.chunkData,2),o=S(t.chunkData,2),g=S(t.chunkData,2),C=new et({min:s,max:n},{min:o,max:g});S(t.chunkData,2);let c=S(t.chunkData,2);c!==0&&C.generators.push(new b(a.exclusiveClass,c));let h=yA(A,"lart"),d=yA(A,"lar2");this.readLart(h,d,C),C.isGlobal=!1;let Q=A.find(AA=>AA.header==="wsmp");S(Q.chunkData,4);let u=S(Q.chunkData,2),l=jA(Q.chunkData[Q.chunkData.currentIndex++],Q.chunkData[Q.chunkData.currentIndex++]),k=(S(Q.chunkData,4)|0)/-655360*10/.4;S(Q.chunkData,4);let F=S(Q.chunkData,4),q,M={start:0,end:0};if(F===0)q=0;else{S(Q.chunkData,4),S(Q.chunkData,4)===0?q=1:q=3,M.start=S(Q.chunkData,4);let K=S(Q.chunkData,4);M.end=M.start+K}let v=A.find(AA=>AA.header==="wlnk");if(v===void 0)return;S(v.chunkData,2),S(v.chunkData,2),S(v.chunkData,4);let T=S(v.chunkData,4),I=this.samples[T];if(I===void 0)throw new Error("Invalid sample ID!");return C.setWavesample(k,q,M,u,I,T,l),C}var ue=class{constructor(A,t,s,n,o,g,C,c){this.sampleName=A,this.sampleRate=t,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=g,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=c,this.isCompressed=(g&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,t){if(!this.isCompressed)try{this.compressedData=t([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{N(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var tt=class extends ue{constructor(A,t,s,n,o,g,C){super(A,t,s,n,0,1,o*2,(g-1)*2),this.sampleData=C}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let t=0;t>8&255}return A}};function Xn(e){pA("%cLoading Wave samples...",r.recognized);let A=0;for(;e.chunkData.currentIndexK.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");if(S(n.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(S(n.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=S(n.chunkData,4);S(n.chunkData,4),S(n.chunkData,2);let c=S(n.chunkData,2),h=c/8,d=Math.pow(2,h*8-1),Q=Math.pow(2,h*8),u,l=!1;c===8?(u=255,l=!0):u=d;let D=s.find(K=>K.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let y=D.size/h,k=new Float32Array(y);for(let K=0;K=d&&(j-=Q),k[K]=j/u)}let F=60,q=0,M=0,v=k.length-1,T=s.find(K=>K.header==="wsmp");if(T){if(S(T.chunkData,4),F=S(T.chunkData,2),q=jA(T.chunkData[T.chunkData.currentIndex++],T.chunkData[T.chunkData.currentIndex++]),S(T.chunkData,4),S(T.chunkData,4),S(T.chunkData,4)===1){S(T.chunkData,8),M=S(T.chunkData,4);let j=S(T.chunkData,4);v=M+j}}else N("No wsmp chunk in wave... using sane defaults.");let I=yA(s,"INFO"),AA=`Unnamed ${A}`;if(I){let K=Z(I.chunkData);for(;K.header!=="INAM"&&I.chunkData.currentIndex(F.messageStatusByte&240)===w.noteOn);k&&l.push(k.ticks)}this.firstNoteOn=Math.min(...l),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&c===null?(d=this.firstNoteOn,c=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(c===null||c===0)&&(c=this.lastVoiceEventTick)),this.loop={start:d,end:c},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let D=0;for(let y of this.midiPorts)if(y!==-1){D=y;break}if(this.midiPorts=this.midiPorts.map(y=>y===-1?D:y),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!g)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=w.noteOn&&y.messageStatusBytek.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=O(y.messageData,y.messageData.length,void 0,!1))}}else{let y=this.tracks[0].find(k=>k.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=O(y.messageData,y.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=Is(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yu>c?u:c),s=[];for(let c=0;c{g[D]>=l.length||l[g[D]].ticks0;){let c=Q(),u=t.tracks[c];if(g[c]>=u.length){C--;continue}let l=u[g[c]];if(g[c]++,l.messageStatusByte===w.midiPort){h[c]=l.messageData[0];continue}let D=l.messageStatusByte&240;if(D!==w.noteOn&&D!==w.controllerChange&&D!==w.programChange&&D!==w.systemExclusive)continue;let y=(l.messageStatusByte&15)+t.midiPortChannelOffsets[h[c]]||0,k=s[y];switch(D){case w.programChange:k.program=l.messageData[0],n(k);break;case w.controllerChange:if(l.messageData[0]!==p.bankSelect||d==="gs"&&k.drums)continue;let F=l.messageData[1],q=Math.max(0,F-t.bankOffset);if(d==="xg"){let T=F===120||F===126||F===127;T!==k.drums?(k.drums=T,k.bank=k.drums?128:q,n(k)):k.bank=k.drums?128:q;continue}s[y].bank=q;break;case w.noteOn:if(l.messageData[1]===0)continue;n(k),o[k.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case w.systemExclusive:if(l.messageData[0]!==65||l.messageData[2]!==66||l.messageData[3]!==18||l.messageData[4]!==64||!(l.messageData[5]&16)||l.messageData[6]!==21){l.messageData[0]===67&&l.messageData[2]===76&&l.messageData[5]===126&&l.messageData[6]===0&&(d="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+t.midiPortChannelOffsets[h[c]],v=!!(l.messageData[7]>0&&l.messageData[5]>>4);k=s[M],k.drums=v,k.bank=v?128:0,n(k);break}}for(let c of Object.keys(o))o[c].size===0&&(m(`%cDetected change but no keys for %c${c}`,r.info,r.value),delete o[c]);return X(),o}function Fs(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(e,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${mt(Math.ceil(this.duration)).time}`,r.recognized),this.post(wA.songChange,[new Pe(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(N(`%cVery short song: (${mt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function Gs(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new _e(e.binary,e.altName||""))}catch(s){return this.post(wA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function xs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ms(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var PA=new Int16Array(127);PA[p.mainVolume]=100;PA[p.expressionController]=127;PA[p.pan]=64;PA[p.releaseTime]=64;PA[p.brightness]=64;PA[p.effects1Depth]=40;function Ns(t,A=void 0){if(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,g=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let h=ke(Q.messageStatusByte),d=h.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(h.status){case w.noteOn:case w.noteOff:case w.keySignature:break;case w.pitchBend:s[d]=Q.messageData[1]<<7|Q.messageData[0];break;case w.programChange:let u=n[d];u.program=Q.messageData[0],u.actualBank=u.bank;break;case w.controllerChange:let l=Q.messageData[0];if(o(l))if(this.sendMIDIMessages)this.sendMIDIMessage([w.controllerChange|d%16,l,Q.messageData[1]]);else{let D=Q.messageData[1];if(l===p.bankSelect){n[d].bank=D;break}this.synth.controllerChange(d,l,D)}else g[d]===void 0&&(g[d]=Array.from(PA)),g[d][l]=Q.messageData[1];break;default:this._processEvent(Q,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let c=this.tracks[C][this.eventIndex[C]];if(c===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(c.ticks-Q.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7]),g[C].forEach((Q,h)=>{Q!==PA[h]&&!o(h)&&this.sendMIDIMessage([w.controllerChange|C%16,h,Q])}),n[C].program>=0&&n[C].actualBank>=0){let Q=n[C].actualBank;this.sendMIDIMessage([w.controllerChange|C%16,p.bankSelect,Q]),this.sendMIDIMessage([w.programChange|C%16,n[C].program])}}else for(let C=0;C>7,s[C]&127),g[C]!==void 0&&g[C].forEach((Q,h)=>{Q!==PA[h]&&!o(h)&&this.synth.controllerChange(C,h,Q)}),n[C].program>=0&&n[C].actualBank>=0){let Q=n[C].actualBank;this.synth.controllerChange(C,p.bankSelect,Q),this.synth.programChange(C,n[C].program)}return!0}function bs(t=!1){if(this.midiData!==void 0){if(t){this.currentTime=0;return}if(this.currentTime>=this.duration){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,!1,!0)}),this.setProcessHandler()}}function Ls(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(wA.timeChange,currentTime-Ce(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Us(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function Ts(t,A){switch(t){default:break;case UA.loadNewSongList:this.loadNewSongList(A);break;case UA.pause:this.pause();break;case UA.play:this.play(A);break;case UA.stop:this.stop();break;case UA.setTime:this.currentTime=A;break;case UA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case UA.setPlaybackRate:this.playbackRate=A;break;case UA.setLoop:this.loop=A;break;case UA.changeSong:A?this.nextSong():this.previousSong();break;case UA.getMIDI:this.post(wA.getMIDI,this.midiData);break;case UA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Hs(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Ys(t){this.post(wA.midiEvent,t)}var EA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.loopCount=1/0,this.currentLoopCount=this.loopCount,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0}set playbackRate(A){let e=this.currentTime;this._playbackRate=A,this.currentTime=e}get currentTime(){return this.pausedTime?this.pausedTime:(currentTime-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&&AJs?440*Math.pow(2,(t-6900)/1200):Rt[~~t-ze]}var xt=-1660,wo=1600,Gt=new Float32Array((wo-xt)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case lA.concave:return s?(e=e*2-1,e<0?1-Ee[~~(e*-IA)]-1:Ee[~~e*IA]):Ee[~~(e*IA)];case lA.convex:return s?(e=e*2-1,e<0?1-Be[~~(e*-IA)]-1:Be[~~(e*IA)]):Be[~~(e*IA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=t.sample.loopEnd;)e-=o;let C=~~e,Q=C+1;for(;Q>=t.sample.loopEnd;)Q-=o;let h=e-C,d=n[Q],c=n[C];A[g]=c+(d-c)*h,e+=t.sample.playbackStep*t.currentTuningCalculated}}else{t.sample.end>=n.length&&(t.sample.end=n.length-1);for(let o=0;o=t.sample.end){t.finished=!0;return}let Q=e-g,h=n[C],d=n[g];A[o]=d+(h-d)*Q,e+=t.sample.playbackStep*t.currentTuningCalculated}}t.sample.cursor=e}function vs(t,A){let e=t.sample.cursor,s=t.sample.loopingMode===1||t.sample.loopingMode===3&&!t.isInRelease,n=t.sample.loopEnd-t.sample.loopStart,o=t.sample.sampleData;if(s)for(let g=0;g=t.sample.loopEnd;)e-=n;let C=~~e+1;for(;C>=t.sample.loopEnd;)C-=n;A[g]=o[C],e+=t.sample.playbackStep*t.currentTuningCalculated}else{t.sample.end>=o.length&&(t.sample.end=o.length-1);for(let g=0;g=t.sample.end){t.finished=!0;return}A[g]=o[C],e+=t.sample.playbackStep*t.currentTuningCalculated}}t.sample.cursor=e}function Ks(t,A,e,s,n,o,g,C,Q){if(!isNaN(e[0])){if(g>0){let h=o[0],d=o[1];g=Math.min(g,1e3);let c=g/1300,u=t*c,l=A*c;for(let D=0;D0){let h=C[0],d=C[1];Q=Math.min(Q,1e3);let c=Q/1300,u=t*c,l=A*c;for(let D=0;D0)for(let h=0;h0)for(let h=0;h13499&&A.filter.reasonanceCb===0)return;let n=A.filter;(n.cutoffCents!==s||n.reasonanceCb!==A.modulatedGenerators[a.initialFilterQ])&&(n.cutoffCents=s,n.reasonanceCb=A.modulatedGenerators[a.initialFilterQ],t.calculateCoefficients(A));for(let o=0;o.45*sampleRate&&(e.cutoffHz=.45*sampleRate);let s=e.reasonanceCb/10-3.01;e.reasonanceGain=VA(-1*s);let n=1/Math.sqrt(e.reasonanceGain),o=2*Math.PI*e.cutoffHz/sampleRate,g=Math.cos(o),C=Math.sin(o)/(2*e.reasonanceGain),Q=(1-g)*n,h=Q/2,d=h,c=1+C,u=-2*g,l=1-C;e.a0=h/c,e.a1=Q/c,e.a2=d/c,e.a3=u/c,e.a4=l/c}};var Ps=.001,DA=100,At=90,RA=class t{constructor(A,e){this.sampleRate=A,this.canEndOnSilentSustain=e/10>=At}currentSampleTime=0;sampleRate;currentAttenuationDb=DA;state=0;releaseStartDb=DA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=VA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static intialize(A){t.recalculate(A,!0),A.volumeEnvelope.attenuation=A.volumeEnvelope.attenuationTarget}static recalculate(A,e=!1){let s=A.volumeEnvelope,n=d=>Math.max(0,Math.floor(HA(d)*s.sampleRate));s.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[a.initialAttenuation],1440))/10,s.sustainDbRelative=Math.min(DA,A.modulatedGenerators[a.sustainVolEnv]/10),e&&(s.attenuation=s.attenuationTarget);let o=Math.min(DA,s.sustainDbRelative+s.attenuation);s.attackDuration=n(A.modulatedGenerators[a.attackVolEnv]);let g=A.modulatedGenerators[a.decayVolEnv],C=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],Q=(o-s.attenuation)/DA;s.decayDuration=n(g+C)*Q,s.releaseDuration=n(A.modulatedGenerators[a.releaseVolEnv]),s.delayEnd=n(A.modulatedGenerators[a.delayVolEnv]),s.attackEnd=s.attackDuration+s.delayEnd;let h=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(s.holdEnd=n(A.modulatedGenerators[a.holdVolEnv]+h)+s.attackEnd,s.decayEnd=s.decayDuration+s.holdEnd,s.state===0&&s.attackEnd===0&&(s.currentAttenuationDb=s.attenuationTarget,s.state=2),A.isInRelease){s.attenuation=Math.min(DA,s.attenuationTarget);let d=Math.max(0,Math.min(DA,s.sustainDbRelative+s.attenuation)),c=(d-s.attenuation)/DA;switch(s.decayDuration=n(g+C)*c,s.state){case 0:s.releaseStartDb=DA;break;case 1:let l=(1-(s.attackEnd-s.releaseStartTimeSamples)/s.attackDuration)*VA(s.attenuation);s.releaseStartDb=20*Math.log10(l)*-1;break;case 2:s.releaseStartDb=s.attenuation;break;case 3:s.releaseStartDb=(1-(s.decayEnd-s.releaseStartTimeSamples)/s.decayDuration)*(d-s.attenuation)+s.attenuation;break;case 4:s.releaseStartDb=d;break;default:s.releaseStartDb=s.currentAttenuationDb}s.releaseStartDb=Math.max(0,Math.min(s.releaseStartDb,DA)),s.releaseStartDb>=At&&(A.finished=!0)}}static apply(A,e,s,n){let o=A.volumeEnvelope,g=s/10,C=n;if(A.isInRelease){let h=n*10,d=o.currentSampleTime-o.releaseStartTimeSamples;if(d>=o.releaseDuration){for(let l=0;l=At&&(A.finished=!0);return}let Q=0;switch(o.state){case 0:for(;o.currentSampleTime=e.length)return;o.state++;case 1:for(;o.currentSampleTime=e.length)return}o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:for(;o.currentSampleTime=e.length)return}o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=At&&(A.finished=!0);;){o.attenuation+=(o.attenuationTarget-o.attenuation)*C;let h=Math.min(DA,o.sustainDbRelative+o.attenuation);if(e[Q]*=VA(h+g),o.currentAttenuationDb=h,o.currentSampleTime++,++Q>=e.length)return}}}};var Vs=Math.PI/2,Os=.01;function Zs(t,A,e,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,RA.startRelease(A),YA.startRelease(A)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let g=A.targetKey,C=A.modulatedGenerators[a.fineTune]+t.customControllers[aA.channelTuning]+t.customControllers[aA.channelTransposeFine]+t.customControllers[aA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],Q=A.modulatedGenerators[a.coarseTune]+t.customControllers[aA.channelTuningSemitones],h=this.tunings[t.preset.program]?.[g];h?.midiNote>=0&&(g=h.midiNote,C+=h.centTuning),C+=(g-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let d=A.modulatedGenerators[a.vibLfoToPitch];if(d!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayVibLFO]),gA=we(A.modulatedGenerators[a.freqVibLFO]),oA=je(z,gA,currentTime);C+=oA*(d*t.customControllers[aA.modulationMultiplier])}let c=A.modulatedGenerators[a.initialFilterFc],u=A.modulatedGenerators[a.modLfoToPitch],l=A.modulatedGenerators[a.modLfoToVolume],D=A.modulatedGenerators[a.modLfoToFilterFc],y=0;if(u+D+l!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayModLFO]),gA=we(A.modulatedGenerators[a.freqModLFO]),oA=je(z,gA,currentTime);C+=oA*(u*t.customControllers[aA.modulationMultiplier]),y=-oA*l,c+=oA*D}if(t.channelVibrato.depth>0){let z=je(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);z&&(C+=z*t.channelVibrato.depth)}let k=A.modulatedGenerators[a.modEnvToPitch],F=A.modulatedGenerators[a.modEnvToFilterFc],q=YA.getValue(A,currentTime);c+=q*F,C+=q*k;let M=~~(C+Q*100);M!==A.currentTuningCents&&(A.currentTuningCents=M,A.currentTuningCalculated=Math.pow(2,M/1200));let v=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,T=new Float32Array(e.length);this.interpolationType===$e.linear?qs(A,T):vs(A,T),he.apply(A,T,c),RA.apply(A,T,y,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(v-A.currentPan)*this.panSmoothingFactor;let I=Math.cos(Vs*A.currentPan)*this.panLeft,AA=Math.sin(Vs*A.currentPan)*this.panRight,K=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],j=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];Ks(I,AA,T,e,s,n,K,o,j)}function Fo(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function Xs(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=Fo(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let e=A.slice(0,t);for(let{channel:s,voice:n}of e){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function Ws(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimezs=t);var Ro=function(t){var A,e,s,n,o,g,C,Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=Q.indexOf(t.charAt(d++)),o=Q.indexOf(t.charAt(d++)),g=Q.indexOf(t.charAt(d++)),C=Q.indexOf(t.charAt(d++)),A=n<<2|o>>4,e=(15&o)<<4|g>>2,s=(3&g)<<6|C,h+=String.fromCharCode(A),g!==64&&(h+=String.fromCharCode(e)),C!==64&&(h+=String.fromCharCode(s));while(d1&&(I.thisProgram=process.argv[1].replace(/\\/g,"/")),I.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof pe))throw i}),process.on("unhandledRejection",function(i,E){process.exit(1)}),I.quit=function(i){process.exit(i)},I.inspect=function(){return"[Emscripten Module object]"}):gA?(typeof read<"u"&&(I.read=function(E){return read(E)}),I.readBinary=function(E){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(B=read(E,"binary"))=="object"),B)},typeof scriptArgs<"u"?I.arguments=scriptArgs:typeof arguments<"u"&&(I.arguments=arguments),typeof quit=="function"&&(I.quit=function(i){quit(i)})):(K||j)&&(K?document.currentScript&&(oA=document.currentScript.src):oA=self.location.href,oA=oA.indexOf("blob:")!==0?oA.split("/").slice(0,-1).join("/")+"/":"",I.read=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.send(null),B.responseText},j&&(I.readBinary=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),I.readAsync=function(E,B,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){B(R.response);return}f()},R.onerror=f,R.send(null)},I.setWindowTitle=function(i){document.title=i});var xe=I.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),xA=I.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||xe);for(t in AA)AA.hasOwnProperty(t)&&(I[t]=AA[t]);function Me(i){var E=l;return l=l+i+15&-16,E}function vt(i){var E=Q[M>>2],B=E+i+15&-16;return Q[M>>2]=B,B>=BA&&!jt()?(Q[M>>2]=E,0):E}function Kt(i,E){return E||(E=16),i=Math.ceil(i/E)*E}function Co(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var E=parseInt(i.substr(1));return _A(E%8==0),E/8}}function de(i){de.shown||(de.shown={}),de.shown[i]||(de.shown[i]=1,xA(i))}AA=void 0;var Eo={"f64-rem":function(i,E){return i%E},debugger:function(){}},it=[];function Lo(i,E){for(var B=0,f=B;f>>0)+4294967296*+(E>>>0):+(i>>>0)+4294967296*+(0|E)}function It(i,E,B){return B&&B.length?I["dynCall_"+i].apply(null,[E].concat(B)):I["dynCall_"+i].call(null,E)}var Ne=0,Pt=0;function _A(i,E){i||ZA("Assertion failed: "+E)}function Vt(i){var E=I["_"+i];return _A(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Ot={stackSave:function(){lt()},stackRestore:function(){ct()},arrayToC:function(i){var E,B,f=Ye(i.length);return E=i,B=f,n.set(E,B),f},stringToC:function(i){var E=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;E=Ye(B),Wt(i,E,B)}return E}},Bo={string:Ot.stringToC,array:Ot.arrayToC};function Zt(i,E,B,f,R){var P=Vt(i),W=[],x=0;if(f)for(var hA=0;hA>0]=E;break;case"i16":g[i>>1]=E;break;case"i32":Q[i>>2]=E;break;case"i64":tempI64=[E>>>0,+fo(tempDouble=E)>=1?tempDouble>0?(0|po(+ss(tempDouble/4294967296),4294967295))>>>0:~~+mo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],Q[i>>2]=tempI64[0],Q[i+4>>2]=tempI64[1];break;case"float":d[i>>2]=E;break;case"double":c[i>>3]=E;break;default:ZA("invalid type for setValue: "+B)}}function Yo(i,E,B){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[i>>0];case"i16":return g[i>>1];case"i32":case"i64":return Q[i>>2];case"float":return d[i>>2];case"double":return c[i>>3];default:ZA("invalid type for getValue: "+E)}return null}function Jo(i,E,B,f){typeof i=="number"?(P=!0,W=i):(P=!1,W=i.length);var R=typeof E=="string"?E:null;if(x=B==4?f:[typeof He=="function"?He:Me,Ye,Me,vt][B===void 0?2:B](Math.max(W,R?1:E.length)),P){for(f=x,_A((3&x)==0),hA=x+(-4&W);f>2]=0;for(hA=x+W;f>0]=0;return x}if(R==="i8")return i.subarray||i.slice?o.set(i,x):o.set(new Uint8Array(i),x),x;for(var P,W,x,hA,rA,iA,sA,J=0;J>0],(f!=0||E)&&(W++,!E||W!=E););E||(E=W);var x="";if(P<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(E,1024))),x=x?x+R:R,i+=1024,E-=1024;return x}return B=i,function(rA,iA){for(var sA=iA;rA[sA];)++sA;if(sA-iA>16&&rA.subarray&&Xt)return Xt.decode(rA.subarray(iA,sA));for(var J,fA,MA,NA,bA,ee,LA="";;){if(!(J=rA[iA++]))return LA;if(!(128&J)){LA+=String.fromCharCode(J);continue}if(fA=63&rA[iA++],(224&J)==192){LA+=String.fromCharCode((31&J)<<6|fA);continue}if(MA=63&rA[iA++],(240&J)==224?J=(15&J)<<12|fA<<6|MA:(NA=63&rA[iA++],(248&J)==240?J=(7&J)<<18|fA<<12|MA<<6|NA:(bA=63&rA[iA++],J=(252&J)==248?(3&J)<<24|fA<<18|MA<<12|NA<<6|bA:(1&J)<<30|fA<<24|MA<<18|NA<<12|bA<<6|(ee=63&rA[iA++]))),J<65536)LA+=String.fromCharCode(J);else{var Se=J-65536;LA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,B)}function vo(i){for(var E="";;){var B=n[i++>>0];if(!B)return E;E+=String.fromCharCode(B)}}function Ko(i,E){return function(f,R,P){for(var W=0;W>0]=f.charCodeAt(W);P||(n[R>>0]=0)}(i,E,!1)}var Xt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Le(i,E,B,f){if(!(f>0))return 0;for(var R=B,P=B+f-1,W=0;W=55296&&x<=57343&&(x=65536+((1023&x)<<10)|1023&i.charCodeAt(++W)),x<=127){if(B>=P)break;E[B++]=x}else if(x<=2047){if(B+1>=P)break;E[B++]=192|x>>6,E[B++]=128|63&x}else if(x<=65535){if(B+2>=P)break;E[B++]=224|x>>12,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=2097151){if(B+3>=P)break;E[B++]=240|x>>18,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=67108863){if(B+4>=P)break;E[B++]=248|x>>24,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else{if(B+5>=P)break;E[B++]=252|x>>30,E[B++]=128|x>>24&63,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}}return E[B]=0,B-R}function Wt(i,E,B){return Le(i,o,E,B)}function Ue(i){for(var E=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var _t=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Po(i){for(var E=i,B=E>>1;g[B];)++B;if((E=B<<1)-i>32&&_t)return _t.decode(o.subarray(i,E));for(var f=0,R="";;){var P=g[i+2*f>>1];if(P==0)return R;++f,R+=String.fromCharCode(P)}}function Vo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=E,R=(B-=2)<2*i.length?B/2:i.length,P=0;P>1]=W,E+=2}return g[E>>1]=0,E-f}function Oo(i){return 2*i.length}function Zo(i){for(var E=0,B="";;){var f=Q[i+4*E>>2];if(f==0)return B;if(++E,f>=65536){var R=f-65536;B+=String.fromCharCode(55296|R>>10,56320|1023&R)}else B+=String.fromCharCode(f)}}function Xo(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=E,R=f+B-4,P=0;P=55296&&W<=57343&&(W=65536+((1023&W)<<10)|1023&i.charCodeAt(++P)),Q[E>>2]=W,(E+=4)+4>R)break}return Q[E>>2]=0,E-f}function Wo(i){for(var E=0,B=0;B=55296&&f<=57343&&++B,E+=4}return E}function _o(i){var E=Ue(i)+1,B=He(E);return B&&Le(i,n,B,E),B}function zo(i){var E=Ue(i)+1,B=Ye(E);return Le(i,n,B,E),B}function jo(i){return i}function $o(){var i,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return I.extraStackTrace&&(E+=` +`+I.extraStackTrace()),(i=E).replace(/__Z[\w\d_]+/g,function(B){var f,R=f=B;return B===R?B:B+" ["+R+"]"})}function gt(i,E){return i%E>0&&(i+=E-i%E),i}function zt(i){I.buffer=s=i}function Ct(){I.HEAP8=n=new Int8Array(s),I.HEAP16=g=new Int16Array(s),I.HEAP32=Q=new Int32Array(s),I.HEAPU8=o=new Uint8Array(s),I.HEAPU16=C=new Uint16Array(s),I.HEAPU32=h=new Uint32Array(s),I.HEAPF32=d=new Float32Array(s),I.HEAPF64=c=new Float64Array(s)}function jt(){var i=I.usingWasm?65536:16777216,E=2147483648-i;if(Q[M>>2]>E)return!1;var B=BA;for(BA=Math.max(BA,16777216);BA>2];)BA=BA<=536870912?gt(2*BA,i):Math.min(gt((3*BA+2147483648)/4,i),E);var f=I.reallocBuffer(BA);return f&&f.byteLength==BA?(zt(f),Ct(),!0):(BA=B,!1)}u=l=y=k=F=q=M=0,D=!1,I.reallocBuffer||(I.reallocBuffer=function(i){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,i);else{var E,B=n;E=new ArrayBuffer(i),new Int8Array(E).set(B)}}catch{return!1}return!!So(E)&&E});try{(v=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{v=function(E){return E.byteLength}}var Et=I.TOTAL_STACK||5242880,BA=I.TOTAL_MEMORY||16777216;function Qo(){return BA}function fe(i){for(;i.length>0;){var E=i.shift();if(typeof E=="function"){E();continue}var B=E.func;typeof B=="number"?E.arg===void 0?I.dynCall_v(B):I.dynCall_vi(B,E.arg):B(E.arg===void 0?null:E.arg)}}BA=0?i:E<=32?2*Math.abs(1<=f&&(E<=32||i>f)&&(i=-2*f+i),i}var fo=Math.abs,mo=Math.ceil,ss=Math.floor,po=Math.min,Ae=0,Qt=null,me=null;function rr(i){return i}I.preloadedImages={},I.preloadedAudios={};var ns="data:application/octet-stream;base64,";function Te(i){return String.prototype.startsWith?i.startsWith(ns):i.indexOf(ns)===0}(function(){var E="main.wast",B="main.wasm",f="main.temp.asm.js";Te(E)||(E=GA(E)),Te(B)||(B=GA(B)),Te(f)||(f=GA(f));var R={global:null,env:null,asm2wasm:Eo,parent:I},P=null;function W(sA){return sA}function x(){try{if(I.wasmBinary)return new Uint8Array(I.wasmBinary);if(I.readBinary)return I.readBinary(B);throw"both async and sync fetching of the wasm failed"}catch(sA){ZA(sA)}}I.asmPreload=I.asm;var hA=I.reallocBuffer,rA=function(sA){sA=gt(sA,I.usingWasm?65536:16777216);var J=I.buffer.byteLength;if(I.usingWasm)try{var fA=I.wasmMemory.grow((sA-J)/65536);return fA!==-1?I.buffer=I.wasmMemory.buffer:null}catch{return null}};I.reallocBuffer=function(sA){return iA==="asmjs"?hA(sA):rA(sA)};var iA="";I.asm=function(sA,J,fA){var MA;if(!(J=MA=J).table){var NA,bA=I.wasmTableSize;bA===void 0&&(bA=1024);var ee=I.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?J.table=new WebAssembly.Table({initial:bA,maximum:ee,element:"anyfunc"}):J.table=new WebAssembly.Table({initial:bA,element:"anyfunc"}):J.table=Array(bA),I.wasmTable=J.table}return J.memoryBase||(J.memoryBase=I.STATIC_BASE),J.tableBase||(J.tableBase=0),NA=function(Se,oe,dt){if(typeof WebAssembly!="object")return xA("no native wasm support detected"),!1;if(!(I.wasmMemory instanceof WebAssembly.Memory))return xA("no native wasm Memory in use"),!1;function Je(JA,qA){if((P=JA.exports).memory){var ye,ft,is;ye=P.memory,ft=I.buffer,ye.byteLength0?B:Ue(i)+1,R=Array(f),P=Le(i,R,0,R.length);return E&&(R.length=P),R}function gr(i){for(var E=[],B=0;B255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}l+=16,M=Me(4),F=(y=k=Kt(l))+Et,q=Kt(F),Q[M>>2]=q,D=!0,I.wasmTableSize=4,I.wasmMaxTableSize=4,I.asmGlobalArg={},I.asmLibraryArg={abort:ZA,assert:_A,enlargeMemory:jt,getTotalMemory:Qo,abortOnCannotGrowMemory:function(){ZA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+BA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,B,f){var R=lt();try{return I.dynCall_iii(E,B,f)}catch(P){if(ct(R),typeof P!="number"&&P!=="longjmp")throw P;I.setThrew(1,0)}},___assert_fail:function(E,B,f,R){ZA("Assertion failed: "+be(E)+", at: "+[B?be(B):"unknown filename",f,R?be(R):"unknown function"])},___setErrNo:function(E){return I.___errno_location&&(Q[I.___errno_location()>>2]=E),E},_abort:function(){I.abort()},_emscripten_memcpy_big:function(E,B,f){return o.set(o.subarray(B,B+f),E),E},_llvm_floor_f64:ss,DYNAMICTOP_PTR:M,tempDoublePtr:kA,ABORT:Ne,STACKTOP:k,STACK_MAX:F};var os=I.asm(I.asmGlobalArg,I.asmLibraryArg,s);I.asm=os,I.___errno_location=function(){return I.asm.___errno_location.apply(null,arguments)};var So=I._emscripten_replace_memory=function(){return I.asm._emscripten_replace_memory.apply(null,arguments)};I._free=function(){return I.asm._free.apply(null,arguments)};var He=I._malloc=function(){return I.asm._malloc.apply(null,arguments)};I._memcpy=function(){return I.asm._memcpy.apply(null,arguments)},I._memset=function(){return I.asm._memset.apply(null,arguments)},I._sbrk=function(){return I.asm._sbrk.apply(null,arguments)},I._stb_vorbis_js_channels=function(){return I.asm._stb_vorbis_js_channels.apply(null,arguments)},I._stb_vorbis_js_close=function(){return I.asm._stb_vorbis_js_close.apply(null,arguments)},I._stb_vorbis_js_decode=function(){return I.asm._stb_vorbis_js_decode.apply(null,arguments)},I._stb_vorbis_js_open=function(){return I.asm._stb_vorbis_js_open.apply(null,arguments)},I._stb_vorbis_js_sample_rate=function(){return I.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},I.establishStackSpace=function(){return I.asm.establishStackSpace.apply(null,arguments)},I.getTempRet0=function(){return I.asm.getTempRet0.apply(null,arguments)},I.runPostSets=function(){return I.asm.runPostSets.apply(null,arguments)},I.setTempRet0=function(){return I.asm.setTempRet0.apply(null,arguments)},I.setThrew=function(){return I.asm.setThrew.apply(null,arguments)};var Ye=I.stackAlloc=function(){return I.asm.stackAlloc.apply(null,arguments)},ct=I.stackRestore=function(){return I.asm.stackRestore.apply(null,arguments)},lt=I.stackSave=function(){return I.asm.stackSave.apply(null,arguments)};function pe(i){this.name="ExitStatus",this.message="Program terminated with exit("+i+")",this.status=i}function ut(i){i=i||I.arguments,!(Ae>0)&&(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)lo(I.preRun.shift());fe($t)}(),!(Ae>0)&&(I.calledRun||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),E()},1)):E())));function E(){!I.calledRun&&(I.calledRun=!0,Ne||(ht||(ht=!0,fe(Bt)),fe(As),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)uo(I.postRun.shift());fe(ts)}()))}}function Cr(i,E){(!E||!I.noExitRuntime||i!==0)&&(I.noExitRuntime||(Ne=!0,Pt=i,k=T,fe(es),co=!0,I.onExit&&I.onExit(i)),I.quit(i,new pe(i)))}function ZA(i){throw I.onAbort&&I.onAbort(i),i!==void 0?(xe(i),xA(i),i=JSON.stringify(i)):i="",Ne=!0,Pt=1,"abort("+i+"). Build with -s ASSERTIONS=1 for more info."}if(I.dynCall_iii=function(){return I.asm.dynCall_iii.apply(null,arguments)},I.asm=os,I.ccall=Zt,I.cwrap=function(E,B,f,R){var P=(f=f||[]).every(function(W){return W==="number"});return B!=="string"&&P&&!R?Vt(E):function(){return Zt(E,B,f,arguments,R)}},pe.prototype=Error(),pe.prototype.constructor=pe,me=function i(){I.calledRun||ut(),I.calledRun||(me=i)},I.run=ut,I.abort=ZA,I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();I.noExitRuntime=!0,ut(),I.onRuntimeInitialized=()=>{_s=!0,zs()},OA.decode=function(i){return function(B){if(!_s)throw Error("Not initialized");var f={};function R(oe){return new Int32Array(I.HEAPU8.buffer,oe,1)[0]}function P(oe,dt){var Je=new ArrayBuffer(dt*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(Je);return re.set(new Float32Array(I.HEAPU8.buffer,oe,dt)),re}f.open=I.cwrap("stb_vorbis_js_open","number",[]),f.close=I.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=I.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=I.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=I.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var W,x,hA,rA,iA=f.open(),sA=(W=B,x=B.byteLength,hA=I._malloc(x),(rA=new Uint8Array(I.HEAPU8.buffer,hA,x)).set(new Uint8Array(W,0,x)),rA),J=I._malloc(4),fA=I._malloc(4),MA=f.decode(iA,sA.byteOffset,sA.byteLength,J,fA);if(I._free(sA.byteOffset),MA<0)throw f.close(iA),I._free(J),Error("stbvorbis decode failed: "+MA);for(var NA=f.channels(iA),bA=Array(NA),ee=new Int32Array(I.HEAPU32.buffer,R(J),NA),LA=0;LA=0&&(s=this.workletProcessorChannels[e]),t.messageType){case tA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case tA.noteOff:this.noteOff(e,A);break;case tA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case tA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case tA.customcCcChange:s.customControllers[A[0]]=A[1];break;case tA.killNote:this.killNote(e,A);break;case tA.programChange:this.programChange(e,A[0],A[1]);break;case tA.channelPressure:this.channelPressure(e,A);break;case tA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case tA.ccReset:e===TA?this.resetAllControllers():this.resetControllers(e);break;case tA.systemExclusive:this.systemExclusive(A);break;case tA.setChannelVibrato:if(e===TA)for(let g=0;g{let e=(A.midiControllers[CA+V.pitchWheelRange]>>7)+(A.midiControllers[CA+V.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[CA+V.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:mA.channelProperties,messageData:t})}function Go(t,A,e){let s=t,n=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function en(t,A=0){let e=t[0];if(!(this.deviceID!==TA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:N(`%cUnrecognized SysEx: %c${QA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let n;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),m(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),m(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let Q=(t[5]<<7|t[6])-8192;n=Math.floor(Q/81.92),this.setMasterTuning(n),m(`%cMaster Fine Tuning. Cents: %c${n}`,r.info,r.value);break;case 4:n=(t[5]-64)*100,this.setMasterTuning(n),m(`%cMaster Coarse Tuning. Cents: %c${n}`,r.info,r.value);break;default:N(`%cUnrecognized MIDI Device Control Real-time message: %c${QA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(m("%cGM system on",r.info),this.system="gm"):t[3]===3?(m("%cGM2 system on",r.info),this.system="gm2"):(m("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let g=t[o++],C=t[o++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,Q);for(let h=0;h<7;h++)(t[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,Q);for(let h=0;h<7;h++)(t[6]>>h&1)===1&&this.setOctaveTuning(h+A,Q);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${Q.join(" ")}`,r.info,r.value);break;default:N(`%cUnrecognized MIDI Tuning standard message: %c${QA(t)}`,r.warn,r.unrecognized);break}break;default:N(`%cUnrecognized MIDI Realtime/non realtime message: %c${QA(t)}`,r.warn,r.unrecognized)}break;case 65:let s=function(){N(`%cUnrecognized Roland %cGS %cSysEx: %c${QA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let n=t[7];if(t[6]===127){n===0?(m("%cGS system on",r.info),this.system="gs"):n===127&&(m("%cGS system off, switching to GM2",r.info),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:s();break;case 21:let g=n>0&&t[5]>>4;this.setDrums(o,g),m(`%cChannel %c${o}%c ${g?"is now a drum channel":"now isn't a drum channel"}%c via: %c${QA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=n-64;this.transposeChannel(o,C),m(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${QA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let Q=n-64;m(`%cChannel %c${o}%c scale tuning. Cents %c${Q}%c, with %c${QA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value),this.setChannelTuning(o,Q);break}return}else if(t[5]===0&&t[6]===6){m(`%cRoland GS Master Pan set to: %c${n}%c with: %c${QA(t)}`,r.info,r.value,r.info,r.value),this.setMasterPan((n-64)/64);return}else if(t[5]===0&&t[6]===5){let o=n-64;m(`%cRoland GS Master Key-Shift set to: %c${o}%c with: %c${QA(t)}`,r.info,r.value,r.info,r.value),this.setMasterTuning(o*100);return}else if(t[5]===0&&t[6]===4){m(`%cRoland GS Master Volume set to: %c${n}%c with: %c${QA(t)}`,r.info,r.value,r.info,r.value),this.setMIDIVolume(n/127);return}}s();return}else if(t[2]===22&&t[3]===18&&t[4]===16){this.setMIDIVolume(t[7]/100),m(`%cRoland Master Volume control set to: %c${t[7]}%c via: %c${QA(t)}`,r.info,r.value,r.info,r.value);return}else{N(`%cUnrecognized Roland SysEx: %c${QA(t)}`,r.warn,r.unrecognized);return}case 67:if(t[2]===76)if(t[3]===0&&t[4]===0)switch(t[5]){case 4:let n=t[6];this.setMIDIVolume(n/127),m(`%cXG master volume. Volume: %c${n}`,r.info,r.recognized);break;case 6:let o=t[6]-64;this.transposeAllChannels(o),m(`%cXG master transpose. Volume: %c${o}`,r.info,r.recognized);break;case 126:m("%cXG system on",r.info),this.system="xg";break}else if(t[3]===8){if(this.system!=="xg")return;let n=t[4]+A;if(n>=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(n,p.bankSelect,o);break;case 2:this.controllerChange(n,p.lsbForControl0BankSelect,o);break;case 3:this.programChange(n,o);break;case 8:let g=this.workletProcessorChannels[n];if(g.drumChannel)return;let C=o-64;g.channelTransposeKeyShift=C;break;case 11:this.controllerChange(n,p.mainVolume,o);break;case 14:let Q=o;Q===0&&(Q=Math.floor(Math.random()*127)),this.controllerChange(n,p.pan,Q);break;case 19:this.controllerChange(n,p.effects1Depth,o);break;case 18:this.controllerChange(n,p.effects3Depth,o);break;default:N(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&N(`%cUnrecognized Yamaha XG SysEx: %c${QA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&N(`%cUnrecognized Yamaha SysEx: %c${QA(t)}`,r.warn,r.unrecognized);break}}function tn(t,A,e){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=t[A.sourceIndex];else{let Q=A.sourceIndex+CA;switch(A.sourceIndex){case V.noController:s=16383;break;case V.noteOnKeyNum:s=e.midiNote<<7;break;case V.noteOnVelocity:s=e.velocity<<7;break;case V.polyPressure:s=e.pressure<<7;break;default:s=t[Q];break}}let n=dA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let Q=A.secSrcIndex+CA;switch(A.secSrcIndex){case V.noController:o=16383;break;case V.noteOnKeyNum:o=e.midiNote<<7;break;case V.noteOnVelocity:o=e.velocity<<7;break;case V.polyPressure:o=e.pressure<<7;break;default:o=t[Q]}}let g=dA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=n*g*A.transformAmount;return A.transformType===2?Math.abs(C):C}function XA(t,A,e=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:g}=t;if(YA.recalculate(t),e===-1){g.set(o),n.forEach(h=>{g[h.modulatorDestination]+=tn(A,h,t)}),RA.recalculate(t);return}let C=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),Q=new Set;n.forEach(h=>{if(h.sourceUsesCC===e&&h.sourceIndex===s||h.secSrcUsesCC===e&&h.secSrcIndex===s){let d=h.modulatorDestination;Q.has(d)||(g[d]=o[d],n.forEach(c=>{c.modulatorDestination===d&&(g[d]+=tn(A,c,t))}),Q.add(d))}}),[...Q].some(h=>C.has(h))&&RA.recalculate(t)}var dA=[];for(let t=0;t<4;t++){dA[t]=[[new Float32Array(IA),new Float32Array(IA)],[new Float32Array(IA),new Float32Array(IA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||g.isMuted)return;let C=A+g.channelTransposeKeyShift;if(A>127||A<0)return;let Q=g.preset.program;this.tunings[Q]?.[A]?.midiNote>=0&&(C=this.tunings[Q]?.[A].midiNote);let h=this.getWorkletVoices(t,C,e,g,o,s),d=g.voices;h.forEach(c=>{let u=c.generators[a.exclusiveClass];u!==0&&d.forEach(l=>{l.generators[a.exclusiveClass]===u&&(this.releaseVoice(l),l.modulatedGenerators[a.releaseVolEnv]=-7e3,l.modulatedGenerators[a.releaseModEnv]=-7e3,RA.recalculate(l),YA.recalculate(l))}),XA(c,g.midiControllers),RA.intialize(c),c.currentPan=(Math.max(-500,Math.min(500,c.modulatedGenerators[a.pan]))+500)/1e3}),this.totalVoicesAmount+=h.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(h.length),d.push(...h),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function nn(t,A){if(A>127||A<0){N("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,s=this.workletProcessorChannels[t].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(e=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function on(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function rn(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[t].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function an(t=!1){m("%cStop all received!",r.info);for(let A=0;AXA(n,this.workletProcessorChannels[t].midiControllers,0,V.pitchWheel)),this.sendChannelProperties()}function cn(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[CA+V.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(s=>XA(s,e.midiControllers,0,V.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function ln(t,A,e){this.workletProcessorChannels[t].voices.forEach(s=>{s.midiNote===A&&(s.pressure=e,XA(s,this.workletProcessorChannels[t].midiControllers,0,V.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function un(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function dn(t,A,e,s=!1){let n=this.workletProcessorChannels[t];if(n===void 0){N(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>=p.lsbForControl1ModulationWheel&&A<=p.lsbForControl13EffectControl2&&A!==p.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|e&127,n.voices.forEach(g=>XA(g,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(t);break;case p.allSoundOff:this.stopAll(t,!0);break;case p.bankSelect:let o=e;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==SA&&this.setDrums(t,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[p.bankSelect])}n.midiControllers[p.bankSelect]=o;break;case p.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||e!==127&&(n.midiControllers[p.bankSelect]=e):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=e);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|e,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=e,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=e,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=e,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(t,e);break;case p.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case p.resetAllControllers:this.resetControllers(t);break;case p.sustainPedal:e>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(g=>{this.releaseVoice(g)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=e<<7,n.voices.forEach(g=>XA(g,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function fn(t){this.midiVolume=t,this.setMasterPan(this.pan)}function mn(t){this.masterGain=t*Lt,this.setMasterPan(this.pan)}function pn(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function Sn(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function yn(t){this.workletProcessorChannels[t].lockGSNRPNParams=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Dn(t,A,e,s){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=s,this.workletProcessorChannels[t].channelVibrato.depth=A)}function kn(t,A){let e=this.workletProcessorChannels[t],s=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;N(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16).toUpperCase()} 0x${e.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 1:switch(e.NRPFine){default:if(A===64)return;N(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;s(),e.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;s(),e.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;s(),e.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let g=A;this.controllerChange(t,p.brightness,A),m(`%cFilter cutoff for %c${t}%c is now set to %c${g}`,r.info,r.recognized,r.info,r.value)}break;case 24:let n=A-64;e.keyCentTuning[e.NRPFine]=n*100,m(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${n}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,p.effects1Depth,o),m(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:N(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[CA+V.pitchWheelRange]=A<<7,m(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function wn(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[CA+V.pitchWheelRange]|=A;let s=(e.midiControllers[CA+V.pitchWheelRange]>>7)+A/127;m(`%cChannel ${t} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=e.customControllers[aA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[aA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Fn(){m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let t=0;t{this.workletProcessorChannels[t].lockedControllers[s]&&this.callEvent("controllerchange",{channel:t,controllerNumber:s,controllerValue:this.workletProcessorChannels[t].midiControllers[s]>>7})};if(e(p.mainVolume),e(p.pan),e(p.expressionController),e(p.modulationWheel),e(p.effects3Depth),e(p.effects1Depth),this.workletProcessorChannels[t].lockedControllers[CA+V.pitchWheel]){let s=this.workletProcessorChannels[t].midiControllers[CA+V.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:t,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Ke}function Rn(t){let A=this.workletProcessorChannels[t],s=A.lockedControllers.reduce((o,g,C)=>(g&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(KA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[aA.channelTransposeFine];A.customControllers.set(wt),A.customControllers[aA.channelTransposeFine]=n,this.resetParameters(t)}function Gn(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function xn(){let t=4;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==a.sampleID&&g.generatorType!==a.keyRange&&g.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return cA(A,0),nA(new $("igen",A.length,A))}function Mn(t,A,e,s,n){let o=this.samples.map((h,d)=>{e&&h.compressSample(s,n);let c=h.getRawData();return m(`%cEncoded sample %c${d}. ${h.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),c}),g=this.samples.reduce((h,d,c)=>h+o[c].length+46,0),C=new H(g);this.samples.forEach((h,d)=>{let c=o[d],u,l,D=c.length;h.isCompressed?(u=C.currentIndex,l=u+c.length):(u=C.currentIndex/2,l=u+c.length/2,D+=46),t.push(u),C.set(c,C.currentIndex),C.currentIndex+=D,A.push(l)});let Q=nA(new $("smpl",C.length,C),new H([115,100,116,97]));return nA(new $("LIST",Q.length,Q))}function Nn(t,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{FA(s,n.sampleName,20);let g=t[o];cA(s,g);let C=A[o];cA(s,C);let Q=n.sampleLoopStartIndex/2+g,h=n.sampleLoopEndIndex/2+g;n.isCompressed&&(Q-=g,h-=g),cA(s,Q),cA(s,h),cA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,Y(s,n.sampleLink),Y(s,n.sampleType)}),FA(s,"EOS",46),nA(new $("shdr",s.length,s))}function bn(){let t=10;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new $("imod",A.length,A))}function Ln(){let t=this.instruments.reduce((o,g)=>g.instrumentZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let g of o.instrumentZones)g.zoneID=e,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,e++}return Y(A,s),Y(A,n),nA(new $("ibag",A.length,A))}function Un(){let t=this.instruments.length*22+22,A=new H(t),e=0,s=0;for(let n of this.instruments)FA(A,n.instrumentName,20),Y(A,e),e+=n.instrumentZones.length,n.instrumentID=s,s++;return FA(A,"EOI",20),Y(A,e),nA(new $("inst",A.length,A))}function Tn(){let t=4;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==a.instrument&&g.generatorType!==a.keyRange&&g.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+n),0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue);e+=n.generators.length}return Y(A,0),Y(A,0),nA(new $("pgen",A.length,A))}function Hn(){let t=10;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new $("pmod",A.length,A))}function Yn(){let t=this.presets.reduce((o,g)=>g.presetZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let g of o.presetZones)g.zoneID=e,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,e++}return Y(A,s),Y(A,n),nA(new $("pbag",A.length,A))}function Jn(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let s of this.presets)FA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,e),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),e+=s.presetZones.length;return FA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),cA(A,0),cA(A,0),cA(A,0),nA(new $("phdr",A.length,A))}var xo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function qn(t=xo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");pA("%cSaving soundfont...",r.info),m(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[v,T]of Object.entries(this.soundFontInfo))if(v==="ifil"||v==="iver"){let I=parseInt(T.split(".")[0]),AA=parseInt(T.split(".")[1]),K=new H(4);Y(K,I),Y(K,AA),A.push(nA(new $(v,4,K)))}else if(v==="DMOD")A.push(nA(new $(v,T.length,T)));else{let I=new H(T.length);FA(I,T),A.push(nA(new $(v,T.length,I)))}let e=De([new H([73,78,70,79]),...A]),s=nA(new $("LIST",e.length,e));m("%cWriting SDTA...",r.info);let n=[],o=[],g=Mn.call(this,n,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=Nn.call(this,n,o);m("%cWriting IGEN...",r.info);let Q=xn.call(this);m("%cWriting IMOD...",r.info);let h=bn.call(this);m("%cWriting IBAG...",r.info);let d=Ln.call(this);m("%cWriting INST...",r.info);let c=Un.call(this),u=Tn.call(this);m("%cWriting PMOD...",r.info);let l=Hn.call(this);m("%cWriting PBAG...",r.info);let D=Yn.call(this);m("%cWriting PHDR...",r.info);let y=Jn.call(this),k=De([new H([112,100,116,97]),y,D,l,u,c,d,h,Q,C]),F=nA(new $("LIST",k.length,k));m("%cWriting the output file...",r.info);let q=De([new H([115,102,98,107]),s,g,F]),M=nA(new $("RIFF",q.length,q));return m(`%cSaved succesfully! Final file size: %c${M.length}`,r.info,r.recognized),X(),M}var ne=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Oe.map(e=>eA.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.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()}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()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,e,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===e);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPreset(A,e){let s=this.presets.find(n=>n.bank===A&&n.program===e);return s||(A===128?(s=this.presets.find(n=>n.bank===128&&n.program===e),s||(s=this.presets.find(n=>n.bank===128))):s=this.presets.find(n=>n.program===e&&n.bank!==128),s&&N(`%cPreset ${A}.${e} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(N(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let e=this.presets.find(s=>s.presetName===A);return e||(N("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}static mergeSoundfonts(...A){let e=A.shift(),s=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(g=>g.bank===o.bank&&g.program===o.program)===void 0&&s.push(o)});return new t({presets:s,info:e.soundFontInfo})}};ne.prototype.write=qn;function vn(t){pA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,e){let s=this.foundSamplesAndGenerators[A][e];if(s)return s;if(this.presetZones.length<1)return[];function n(c,u,l){return l>=c&&l<=u}function o(c,u){c.push(...u.filter(l=>!c.find(D=>D.generatorType===l.generatorType)))}function g(c,u){c.push(...u.filter(l=>!c.find(D=>eA.isIdentical(l,D))))}let C=[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(c=>n(c.keyRange.min,c.keyRange.max,A)&&n(c.velRange.min,c.velRange.max,e)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let u=c.generators,l=c.modulators,D=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].generators]:[],y=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].modulators]:[];c.instrument.instrumentZones.filter(F=>n(F.keyRange.min,F.keyRange.max,A)&&n(F.velRange.min,F.velRange.max,e)&&!F.isGlobal).forEach(F=>{let q=[...F.generators],M=[...F.modulators];o(u,Q),o(q,D),g(l,h),g(M,y),g(M,this.defaultModulators);let v=[...M];for(let T=0;TeA.isIdentical(I,K));AA!==-1?v[AA]=v[AA].sumTransform(I):v.push(I)}C.push({instrumentGenerators:q,presetGenerators:u,modulators:v,sample:F.sample,sampleID:F.generators.find(T=>T.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Fe=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Fe{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},ce=class extends Fe{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var le=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.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 et=class extends Qe{constructor(A,e){super(Oe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new le,this.DLSInstrument.addUseCount();let n=new ce;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function Kn(t){this.verifyHeader(t,"LIST"),this.verifyText(O(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(l=>l.header==="insh");if(!e)throw X(),new Error("No instrument header!");let s=S(e.chunkData,4),n=S(e.chunkData,4),o=S(e.chunkData,4),g=new et(n,o),C="unnamedPreset",Q=yA(A,"INFO");if(Q){let l=Z(Q.chunkData);for(;l.header!=="INAM";)l=Z(Q.chunkData);C=O(l.chunkData,l.chunkData.length).trim()}g.presetName=C,g.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let h=yA(A,"lrgn");if(!h)throw X(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let c=yA(A,"lart"),u=yA(A,"lar2");this.readLart(c,u,d),g.DLSInstrument.instrumentZones.push(d);for(let l=0;l>10&15;F===lA.linear&&k!==lA.linear&&(F=k);let q=s>>14&1,M=s>>15&1;g===a.initialAttenuation&&(M=!M),c=vA(F,q,M,C.isCC,C.enum)}let u=s>>4&15,l=s>>8&1,D=s>>9&1,y=vA(u,l,D,d.isCC,d.enum);if(Q){let k=y;y=c,c=k}return new eA({srcEnum:c,secSrcEnum:y,dest:g,transform:0,amt:n})}function Ut(t,A){let e=t.chunkData,s=[],n=[];S(e,4);let o=S(e,4);for(let g=0;g>16;if(C===0&&Q===0&&d===0){let l;switch(h){case G.pan:l=new b(a.pan,u);break;case G.gain:l=new b(a.initialAttenuation,-u*10/.4);break;case G.filterCutoff:l=new b(a.initialFilterFc,u);break;case G.filterQ:l=new b(a.initialFilterQ,u);break;case G.modLfoFreq:l=new b(a.freqModLFO,u);break;case G.modLfoDelay:l=new b(a.delayModLFO,u);break;case G.vibLfoFreq:l=new b(a.freqVibLFO,u);break;case G.vibLfoDelay:l=new b(a.delayVibLFO,u);break;case G.volEnvDelay:l=new b(a.delayVolEnv,u);break;case G.volEnvAttack:l=new b(a.attackVolEnv,u);break;case G.volEnvHold:l=new b(a.holdVolEnv,u);break;case G.volEnvDecay:l=new b(a.decayVolEnv,u);break;case G.volEnvRelease:l=new b(a.releaseVolEnv,u);break;case G.volEnvSustain:let D=(1e3-u)/10;l=new b(a.sustainVolEnv,D*10);break;case G.modEnvDelay:l=new b(a.delayModEnv,u);break;case G.modEnvAttack:l=new b(a.attackModEnv,u);break;case G.modEnvHold:l=new b(a.holdModEnv,u);break;case G.modEnvDecay:l=new b(a.decayModEnv,u);break;case G.modEnvRelease:l=new b(a.releaseModEnv,u);break;case G.modEnvSustain:let y=1e3-u;l=new b(a.sustainModEnv,y);break;case G.reverbSend:l=new b(a.reverbEffectsSend,u);break;case G.chorusSend:l=new b(a.chorusEffectsSend,u);break;case G.pitch:let k=Math.floor(u/100),F=Math.floor(u-k*100);l=new b(a.fineTune,F),s.push(new b(a.coarseTune,k));break}l&&s.push(l)}else{let l=!0;if(Q===_.none)if(C===_.modLfo&&h===G.pitch)s.push(new b(a.modLfoToPitch,u));else if(C===_.modLfo&&h===G.gain)s.push(new b(a.modLfoToVolume,u));else if(C===_.modLfo&&h===G.filterCutoff)s.push(new b(a.modLfoToFilterFc,u));else if(C===_.vibratoLfo&&h===G.pitch)s.push(new b(a.vibLfoToPitch,u));else if(C===_.modEnv&&h===G.pitch)s.push(new b(a.modEnvToPitch,u));else if(C===_.modEnv&&h===G.filterCutoff)s.push(new b(a.modEnvToFilterFc,u));else if(C===_.keyNum&&h===G.volEnvHold){s.push(new b(a.keyNumToVolEnvHold,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.holdVolEnv&&(y.generatorValue+=D)})}else if(C===_.keyNum&&h===G.volEnvDecay){s.push(new b(a.keyNumToVolEnvDecay,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.decayVolEnv&&(y.generatorValue+=D)})}else if(C===_.keyNum&&h===G.modEnvHold){s.push(new b(a.keyNumToModEnvHold,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.holdModEnv&&(y.generatorValue+=D)})}else if(C===_.keyNum&&h===G.modEnvDecay){s.push(new b(a.keyNumToModEnvDecay,u/-128));let D=Math.round(60/128*u);s.forEach(y=>{y.generatorType===a.decayModEnv&&(y.generatorValue+=D)})}else l=!1;else l=!1;if(l===!1){let D=Vn(C,Q,h,d,u);D?(n.push(D),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):N("Failed converting to SF2 Modulator!")}}}return n.find(g=>g.modulatorDestination===a.reverbEffectsSend)===void 0&&n.push(new eA({srcEnum:219,dest:a.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(g=>g.modulatorDestination===a.chorusEffectsSend)===void 0&&n.push(new eA({srcEnum:221,dest:a.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new eA({srcEnum:129,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new eA({srcEnum:13,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function On(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(AA=>AA.header==="rgnh"),s=S(e.chunkData,2),n=S(e.chunkData,2),o=S(e.chunkData,2),g=S(e.chunkData,2),C=new tt({min:s,max:n},{min:o,max:g});S(e.chunkData,2);let Q=S(e.chunkData,2);Q!==0&&C.generators.push(new b(a.exclusiveClass,Q));let h=yA(A,"lart"),d=yA(A,"lar2");this.readLart(h,d,C),C.isGlobal=!1;let c=A.find(AA=>AA.header==="wsmp");S(c.chunkData,4);let u=S(c.chunkData,2),l=jA(c.chunkData[c.chunkData.currentIndex++],c.chunkData[c.chunkData.currentIndex++]),k=(S(c.chunkData,4)|0)/-655360*10/.4;S(c.chunkData,4);let F=S(c.chunkData,4),q,M={start:0,end:0};if(F===0)q=0;else{S(c.chunkData,4),S(c.chunkData,4)===0?q=1:q=3,M.start=S(c.chunkData,4);let K=S(c.chunkData,4);M.end=M.start+K}let v=A.find(AA=>AA.header==="wlnk");if(v===void 0)return;S(v.chunkData,2),S(v.chunkData,2),S(v.chunkData,4);let T=S(v.chunkData,4),I=this.samples[T];if(I===void 0)throw new Error("Invalid sample ID!");return C.setWavesample(k,q,M,u,I,T,l),C}var ue=class{constructor(A,e,s,n,o,g,C,Q){this.sampleName=A,this.sampleRate=e,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=g,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=Q,this.isCompressed=(g&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{N(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var st=class extends ue{constructor(A,e,s,n,o,g,C){super(A,e,s,n,0,1,o*2,(g-1)*2),this.sampleData=C}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function Xn(t){pA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexK.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");if(S(n.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(S(n.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=S(n.chunkData,4);S(n.chunkData,4),S(n.chunkData,2);let Q=S(n.chunkData,2),h=Q/8,d=Math.pow(2,h*8-1),c=Math.pow(2,h*8),u,l=!1;Q===8?(u=255,l=!0):u=d;let D=s.find(K=>K.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let y=D.size/h,k=new Float32Array(y);for(let K=0;K=d&&(j-=c),k[K]=j/u)}let F=60,q=0,M=0,v=k.length-1,T=s.find(K=>K.header==="wsmp");if(T){if(S(T.chunkData,4),F=S(T.chunkData,2),q=jA(T.chunkData[T.chunkData.currentIndex++],T.chunkData[T.chunkData.currentIndex++]),S(T.chunkData,4),S(T.chunkData,4),S(T.chunkData,4)===1){S(T.chunkData,8),M=S(T.chunkData,4);let j=S(T.chunkData,4);v=M+j}}else N("No wsmp chunk in wave... using sane defaults.");let I=yA(s,"INFO"),AA=`Unnamed ${A}`;if(I){let K=Z(I.chunkData);for(;K.header!=="INAM"&&I.chunkData.currentIndexc.header==="colh");if(!o)throw X(),new Error("No colh chunk!");this.instrumentAmount=S(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let g=yA(s,"wvpl");this.readDLSSamples(g);let C=yA(s,"lins");if(!C)throw X(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((c,h)=>c.program-h.program+(c.bank-h.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X()}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=vn;WA.prototype.readDLSInstrument=Kn;WA.prototype.readRegion=Zn;WA.prototype.readLart=On;WA.prototype.readDLSSamples=Xn;var Ut=class extends ue{constructor(A,t,s,n,o,g,C,c,h,d,Q,u,l){super(A,g,C,c,h,d,n-t,o-t),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=u,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=Q,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=l}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{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");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,s=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);let n=OA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return N("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let n=0;ne.chunkData.currentIndex;){let o=bo(n,e.chunkData,A,t);s.push(o),n++}return s.length>1&&s.pop(),s}function bo(e,A,t,s){let n=O(A,20),o=S(A,4)*2,g=S(A,4)*2,C=S(A,4)*2,c=S(A,4)*2,h=S(A,4),d=A[A.currentIndex++];d===255&&(d=60);let Q=ps(A[A.currentIndex++]),u=S(A,2),l=S(A,2);return new Ut(n,o,g,C,c,h,d,Q,u,l,t,e,s)}var Tt=class extends le{constructor(A){super(),this.instrumentName=O(A.chunkData,20).trim(),this.instrumentZoneIndex=S(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;se.chunkData.currentIndex;){let s=new Tt(e);if(t.length>0){let n=s.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(n,A)}t.push(s)}return t.length>1&&t.pop(),t}var Ht=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(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;ts.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 zn(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Ht(e.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Yt=class extends ce{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(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;ts.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 jn(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Yt(e.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Jt=class extends Qe{constructor(A,t){super(t),this.presetName=O(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=S(A.chunkData,2),this.bank=S(A.chunkData,2),this.presetZoneStartIndex=S(A.chunkData,2),this.library=S(A.chunkData,4),this.genre=S(A.chunkData,4),this.morphology=S(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;se.chunkData.currentIndex;){let n=new Jt(e,t);if(s.length>0){let o=n.presetZoneStartIndex-s[s.length-1].presetZoneStartIndex;s[s.length-1].getPresetZones(o,A)}s.push(n)}return s.length>1&&s.pop(),s}var st=class extends ne{constructor(A,t=!0){if(super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw X(),new TypeError("No data!");let s=Z(this.dataArray,!1);this.verifyHeader(s,"riff");let n=O(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",g=Z(this.dataArray);for(this.verifyHeader(g,"list"),O(g.chunkData,4);g.chunkData.length>g.chunkData.currentIndex;){let z=Z(g.chunkData),gA;switch(z.header.toLowerCase()){case"ifil":case"iver":gA=`${S(z.chunkData,2)}.${S(z.chunkData,2)}`,this.soundFontInfo[z.header]=gA;break;case"icmt":gA=O(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=gA;break;case"dmod":let oA=Ze(z);oA.pop(),gA=`Modulators: ${oA.length}`;let GA=this.defaultModulators;this.defaultModulators=oA,this.defaultModulators.push(...GA.filter(xe=>!this.defaultModulators.find(xA=>eA.isIdentical(xe,xA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:gA=O(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=gA}m(`%c"${z.header}": %c"${gA}"`,r.info,r.recognized)}let C=Z(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(O(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let c=Z(this.dataArray,!1);this.verifyHeader(c,"smpl");let h;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{h=OA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}m(`%cDecoded the smpl chunk! Length: %c${h.length}`,r.info,r.value)}else h=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let d=Z(this.dataArray);this.verifyHeader(d,"list"),O(d.chunkData,4);let Q=Z(d.chunkData);this.verifyHeader(Q,"phdr");let u=Z(d.chunkData);this.verifyHeader(u,"pbag");let l=Z(d.chunkData);this.verifyHeader(l,"pmod");let D=Z(d.chunkData);this.verifyHeader(D,"pgen");let y=Z(d.chunkData);this.verifyHeader(y,"inst");let k=Z(d.chunkData);this.verifyHeader(k,"ibag");let F=Z(d.chunkData);this.verifyHeader(F,"imod");let q=Z(d.chunkData);this.verifyHeader(q,"igen");let M=Z(d.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Wn(M,h,!o));let v=pt(q),T=Ze(F),I=zn(k,v,T,this.samples);this.instruments=_n(y,I);let AA=pt(D),K=Ze(l),j=jn(u,AA,K,this.instruments);this.presets.push(...$n(Q,j,this.defaultModulators)),this.presets.sort((z,gA)=>z.program-gA.program+(z.bank-gA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X(),o&&delete this.dataArray}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Re(e){let A=e.slice(8,12),t=new H(A);return O(t,4,void 0,!1).toLowerCase()==="dls "?new WA(e):new st(e,!1)}function Ao(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s===void 0){N(`Trying to access channel ${e} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[p.bankSelect],o,g;if(this.overrideSoundfont){let C=n===128?128:n-this.soundfontBankOffset,c=this.overrideSoundfont.getPresetNoFallback(C,A);c?(o=n,g=c,s.presetUsesOverride=!0):(g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1)}else g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1;this.setPreset(e,g),this.callEvent("programchange",{channel:e,program:g.program,bank:o,userCalled:t})}function eo(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,s=this.overrideSoundfont.getPresetNoFallback(t,A);if(s)return s}return this.soundfontManager.getPreset(e,A)}function to(e,A){if(!this.workletProcessorChannels[e].lockPreset){delete this.workletProcessorChannels[e].preset,this.workletProcessorChannels[e].preset=A,this.workletProcessorChannels[e].cachedVoices=[];for(let t=0;t<128;t++)this.workletProcessorChannels[e].cachedVoices.push([])}}function so(e,A){let t=this.workletProcessorChannels[e];t.lockPreset||t.drumChannel!==A&&(A?(t.channelTransposeKeyShift=0,t.drumChannel=!0,this.setPreset(e,this.getPreset(128,t.preset.program))):(t.drumChannel=!1,this.setPreset(e,this.getPreset(t.midiControllers[p.bankSelect],t.preset.program))),t.presetUsesOverride=!1,this.callEvent("drumchange",{channel:e,isDrumChannel:t.drumChannel}),this.sendChannelProperties())}function no(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,s=e.find(n=>n.bank===t&&n.program===A.program);s!==void 0?s.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function oo(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t{this.programChange(s,t.preset.program)}),this.post({messageType:mA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function io(e,A){this.soundfontBankOffset=A,this.reloadSoundFont(e,!0),this.overrideSoundfont.samples.forEach(t=>t.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function ao(){let A={channelSnapshots:this.workletProcessorChannels.map(t=>({program:t.preset.program,bank:t.preset.bank,lockPreset:t.lockPreset,patchName:t.preset.presetName,midiControllers:t.midiControllers,lockedControllers:t.lockedControllers,customControllers:t.customControllers,channelVibrato:t.channelVibrato,lockVibrato:t.lockGSNRPNParams,channelTransposeKeyShift:t.channelTransposeKeyShift,channelOctaveTuning:t.channelOctaveTuning,keyCentTuning:t.keyCentTuning,isMuted:t.isMuted,drumChannel:t.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:mA.synthesizerSnapshot,messageData:A})}function Io(e){for(this.system=e.system,this.setMasterGain(e.mainVolume),this.setMasterPan(e.pan),this.transposeAllChannels(e.transposition),this.interpolationType=e.interpolation;this.workletProcessorChannels.length{let s=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockGSNRPNParams=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(t,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var nt=class{constructor(A,t){this.ready=t,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(t=>{t.soundfont.setSampleIDOffset(A),A+=t.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let s=this.soundfontList[t],n=new Set;for(let o of s.soundfont.presets){let g=`${o.bank+s.bankOffset}-${o.program}`;n.has(g)||(n.add(g),A[g]=o.presetName)}}this.presetList=[];for(let[t,s]of Object.entries(A)){let n=t.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,t){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case Ie.reloadSoundFont:this.reloadManager(t);break;case Ie.deleteSoundFont:this.deleteSoundFont(t);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=Re(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){N("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(s=>s.id===A);if(t===-1){N(`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,s){if(this.soundfontList.find(n=>n.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:Re(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,s)=>A.indexOf(t.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,t){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,t);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===t);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var ot=class{constructor(A,t,s,n,o,g,C,c){this.sampleData=A,this.playbackStep=t,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=g,this.end=C,this.loopingMode=c}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0},Ge=class e{constructor(A,t,s,n,o,g,C,c,h){this.sample=t,this.generators=c,this.modulatedGenerators=new Int16Array(c),this.modulators=h,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=g,this.targetKey=C,this.volumeEnvelope=new RA(A)}sample;filter=new he;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new YA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;static copy(A,t){let s=A.sample,n=new ot(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new e(A.volumeEnvelope.sampleRate,n,A.midiNote,A.velocity,A.channelNumber,t,A.targetKey,A.generators,A.modulators.slice())}};function go(e,A,t,s,n,o=!1){let g,C=s.cachedVoices[A][t];return C!==void 0?g=C.map(c=>Ge.copy(c,n)):(g=s.preset.getSamplesAndGenerators(A,t).reduce((h,d)=>{if(d.sample.sampleData===void 0)return N(`Discarding invalid sample: ${d.sample.sampleName}`),h;let Q=new Int16Array(60);for(let M=0;M<60;M++)Q[M]=Ss(M,d.presetGenerators,d.instrumentGenerators);Q[a.initialAttenuation]=Math.floor(Q[a.initialAttenuation]*.4);let u=d.sample.samplePitch;Q[a.overridingRootKey]>-1&&(u=Q[a.overridingRootKey]);let l=A;Q[a.keyNum]>-1&&(l=Q[a.keyNum]);let D=d.sample.sampleLoopStartIndex/2+(Q[a.startloopAddrsOffset]+Q[a.startloopAddrsCoarseOffset]*32768),y=d.sample.sampleLoopEndIndex/2+(Q[a.endloopAddrsOffset]+Q[a.endloopAddrsCoarseOffset]*32768),k=Q[a.sampleModes],F=d.sample.getAudioData().length;D=Math.min(Math.max(0,D),F),y=Math.min(Math.max(0,y),F),y-D<1&&(k=0);let q=new ot(d.sample.getAudioData(),d.sample.sampleRate/sampleRate*Math.pow(2,d.sample.samplePitchCorrection/1200),Q[a.startAddrsOffset]+Q[a.startAddrsCoarseOffset]*32768,u,D,y,Math.floor(d.sample.sampleData.length)-1+(Q[a.endAddrOffset]+Q[a.endAddrsCoarseOffset]*32768),k);return Q[a.velocity]>-1&&(t=Q[a.velocity]),o&&Qs([{Sample:d.sample.sampleName,Generators:Q,Modulators:d.modulators.map(M=>M.debugString()),Velocity:t,TargetKey:l,MidiNote:A,WorkletSample:q}]),h.push(new Ge(sampleRate,q,A,t,e,n,l,Q,d.modulators)),h},[]),s.cachedVoices[A][t]=g.map(h=>Ge.copy(h,n))),g}var Nt=.07,bt=1,L=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=TA,this.interpolationType=$e.linear,this.processTickCallback=void 0,this.sequencer=new EA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=bt,this.midiVolume=1,this.voiceCap=ls,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new nt(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:mA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let t=0;tthis.handleMessage(t.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),OA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:mA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let g,C,c,h,d;if(this.oneOutputMode){let u=t[0];g=o%16*2,C=u[g],c=u[g+1]}else g=o%this._outputsAmount+2,C=t[g][0],c=t[g][1],h=t[0],d=t[1];let Q=n.voices;n.voices=[],Q.forEach(u=>{this.renderVoice(n,u,C,c,h,d),u.finished||n.voices.push(u)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};L.prototype.renderVoice=Zs;L.prototype.releaseVoice=Ws;L.prototype.voiceKilling=Xs;L.prototype.getWorkletVoices=go;L.prototype.handleMessage=js;L.prototype.sendChannelProperties=An;L.prototype.callEvent=$s;L.prototype.systemExclusive=en;L.prototype.noteOn=sn;L.prototype.noteOff=nn;L.prototype.polyPressure=ln;L.prototype.killNote=on;L.prototype.stopAll=rn;L.prototype.stopAllChannels=an;L.prototype.muteChannel=Sn;L.prototype.setVibrato=Dn;L.prototype.disableAndLockGSNRPN=yn;L.prototype.dataEntryCoarse=kn;L.prototype.dataEntryFine=wn;L.prototype.createWorkletChannel=ys;L.prototype.controllerChange=dn;L.prototype.channelPressure=cn;L.prototype.resetAllControllers=Fn;L.prototype.resetControllers=Rn;L.prototype.resetParameters=Gn;L.prototype.setMasterGain=mn;L.prototype.setMasterPan=pn;L.prototype.setMIDIVolume=fn;L.prototype.transposeAllChannels=In;L.prototype.transposeChannel=gn;L.prototype.setChannelTuning=Cn;L.prototype.setChannelTuningSemitones=En;L.prototype.setMasterTuning=Bn;L.prototype.setModulationDepth=hn;L.prototype.pitchWheel=Qn;L.prototype.setOctaveTuning=un;L.prototype.programChange=Ao;L.prototype.getPreset=eo;L.prototype.setPreset=to;L.prototype.setDrums=so;L.prototype.reloadSoundFont=ro;L.prototype.clearSoundFont=oo;L.prototype.setEmbeddedSoundFont=io;L.prototype.sendPresetList=no;L.prototype.sendSynthesizerSnapshot=ao;L.prototype.applySynthesizerSnapshot=Io;registerProcessor(cs,L);m("%cProcessor succesfully registered!",r.recognized); +`+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ);for(let[Q,h]of Object.entries(this.soundFontInfo))m(`%c"${Q}": %c"${h}"`,r.info,r.recognized);let o=s.find(Q=>Q.header==="colh");if(!o)throw X(),new Error("No colh chunk!");this.instrumentAmount=S(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let g=yA(s,"wvpl");this.readDLSSamples(g);let C=yA(s,"lins");if(!C)throw X(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((Q,h)=>Q.program-h.program+(Q.bank-h.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=vn;WA.prototype.readDLSInstrument=Kn;WA.prototype.readRegion=Zn;WA.prototype.readLart=On;WA.prototype.readDLSSamples=Xn;var Tt=class extends ue{constructor(A,e,s,n,o,g,C,Q,h,d,c,u,l){super(A,g,C,Q,h,d,n-e,o-e),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=u,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=c,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=l}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let e=A.currentIndex;return A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let e=A.currentIndex;return A.slice(e+this.sampleStartIndex,e+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,e=A.currentIndex,s=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let n=OA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return N("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let n=0;nt.chunkData.currentIndex;){let o=bo(n,t.chunkData,A,e);s.push(o),n++}return s.length>1&&s.pop(),s}function bo(t,A,e,s){let n=O(A,20),o=S(A,4)*2,g=S(A,4)*2,C=S(A,4)*2,Q=S(A,4)*2,h=S(A,4),d=A[A.currentIndex++];d===255&&(d=60);let c=Ss(A[A.currentIndex++]),u=S(A,2),l=S(A,2);return new Tt(n,o,g,C,Q,h,d,c,u,l,e,t,s)}var Ht=class extends le{constructor(A){super(),this.instrumentName=O(A.chunkData,20).trim(),this.instrumentZoneIndex=S(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;st.chunkData.currentIndex;){let s=new Ht(t);if(e.length>0){let n=s.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(n,A)}e.push(s)}return e.length>1&&e.pop(),e}var Yt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function zn(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Yt(t.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Jt=class extends ce{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function jn(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Jt(t.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var qt=class extends Qe{constructor(A,e){super(e),this.presetName=O(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=S(A.chunkData,2),this.bank=S(A.chunkData,2),this.presetZoneStartIndex=S(A.chunkData,2),this.library=S(A.chunkData,4),this.genre=S(A.chunkData,4),this.morphology=S(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;st.chunkData.currentIndex;){let n=new qt(t,e);if(s.length>0){let o=n.presetZoneStartIndex-s[s.length-1].presetZoneStartIndex;s[s.length-1].getPresetZones(o,A)}s.push(n)}return s.length>1&&s.pop(),s}var nt=class extends ne{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw X(),new TypeError("No data!");let s=Z(this.dataArray,!1);this.verifyHeader(s,"riff");let n=O(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",g=Z(this.dataArray);for(this.verifyHeader(g,"list"),O(g.chunkData,4);g.chunkData.length>g.chunkData.currentIndex;){let z=Z(g.chunkData),gA;switch(z.header.toLowerCase()){case"ifil":case"iver":gA=`${S(z.chunkData,2)}.${S(z.chunkData,2)}`,this.soundFontInfo[z.header]=gA;break;case"icmt":gA=O(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=gA;break;case"dmod":let oA=Ze(z);oA.pop(),gA=`Modulators: ${oA.length}`;let GA=this.defaultModulators;this.defaultModulators=oA,this.defaultModulators.push(...GA.filter(xe=>!this.defaultModulators.find(xA=>eA.isIdentical(xe,xA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:gA=O(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=gA}m(`%c"${z.header}": %c"${gA}"`,r.info,r.recognized)}let C=Z(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(O(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let Q=Z(this.dataArray,!1);this.verifyHeader(Q,"smpl");let h;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{h=OA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}m(`%cDecoded the smpl chunk! Length: %c${h.length}`,r.info,r.value)}else h=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let d=Z(this.dataArray);this.verifyHeader(d,"list"),O(d.chunkData,4);let c=Z(d.chunkData);this.verifyHeader(c,"phdr");let u=Z(d.chunkData);this.verifyHeader(u,"pbag");let l=Z(d.chunkData);this.verifyHeader(l,"pmod");let D=Z(d.chunkData);this.verifyHeader(D,"pgen");let y=Z(d.chunkData);this.verifyHeader(y,"inst");let k=Z(d.chunkData);this.verifyHeader(k,"ibag");let F=Z(d.chunkData);this.verifyHeader(F,"imod");let q=Z(d.chunkData);this.verifyHeader(q,"igen");let M=Z(d.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Wn(M,h,!o));let v=St(q),T=Ze(F),I=zn(k,v,T,this.samples);this.instruments=_n(y,I);let AA=St(D),K=Ze(l),j=jn(u,AA,K,this.instruments);this.presets.push(...$n(c,j,this.defaultModulators)),this.presets.sort((z,gA)=>z.program-gA.program+(z.bank-gA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Re(t){let A=t.slice(8,12),e=new H(A);return O(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new nt(t,!1)}function Ao(t,A,e=!1){let s=this.workletProcessorChannels[t];if(s===void 0){N(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[p.bankSelect],o,g;if(this.overrideSoundfont){let C=n===128?128:n-this.soundfontBankOffset,Q=this.overrideSoundfont.getPresetNoFallback(C,A);Q?(o=n,g=Q,s.presetUsesOverride=!0):(g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1)}else g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1;this.setPreset(t,g),this.callEvent("programchange",{channel:t,program:g.program,bank:o,userCalled:e})}function eo(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,s=this.overrideSoundfont.getPresetNoFallback(e,A);if(s)return s}return this.soundfontManager.getPreset(t,A)}function to(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function so(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[p.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function no(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,s=t.find(n=>n.bank===e&&n.program===A.program);s!==void 0?s.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function oo(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(s,e.preset.program)}),this.post({messageType:mA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function io(t,A){this.soundfontBankOffset=A,this.reloadSoundFont(t,!0),this.overrideSoundfont.samples.forEach(e=>e.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function ao(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:mA.synthesizerSnapshot,messageData:A})}function Io(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let s=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockGSNRPNParams=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(e,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var ot=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let s=this.soundfontList[e],n=new Set;for(let o of s.soundfont.presets){let g=`${o.bank+s.bankOffset}-${o.program}`;n.has(g)||(n.add(g),A[g]=o.presetName)}}this.presetList=[];for(let[e,s]of Object.entries(A)){let n=e.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,e){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ie.reloadSoundFont:this.reloadManager(e);break;case Ie.deleteSoundFont:this.deleteSoundFont(e);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Re(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){N("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(s=>s.id===A);if(e===-1){N(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,s){if(this.soundfontList.find(n=>n.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Re(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,s)=>A.indexOf(e.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,e);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===e);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var rt=class{constructor(A,e,s,n,o,g,C,Q){this.sampleData=A,this.playbackStep=e,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=g,this.end=C,this.loopingMode=Q}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0},Ge=class t{constructor(A,e,s,n,o,g,C,Q,h){this.sample=e,this.generators=Q,this.modulatedGenerators=new Int16Array(Q),this.modulators=h,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=g,this.targetKey=C,this.volumeEnvelope=new RA(A,Q[a.sustainVolEnv])}sample;filter=new he;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new YA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;static copy(A,e){let s=A.sample,n=new rt(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new t(A.volumeEnvelope.sampleRate,n,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.generators,A.modulators.slice())}};function go(t,A,e,s,n,o=!1){let g,C=s.cachedVoices[A][e];return C!==void 0?g=C.map(Q=>Ge.copy(Q,n)):(g=s.preset.getSamplesAndGenerators(A,e).reduce((h,d)=>{if(d.sample.sampleData===void 0)return N(`Discarding invalid sample: ${d.sample.sampleName}`),h;let c=new Int16Array(60);for(let M=0;M<60;M++)c[M]=ys(M,d.presetGenerators,d.instrumentGenerators);c[a.initialAttenuation]=Math.floor(c[a.initialAttenuation]*.4);let u=d.sample.samplePitch;c[a.overridingRootKey]>-1&&(u=c[a.overridingRootKey]);let l=A;c[a.keyNum]>-1&&(l=c[a.keyNum]);let D=d.sample.sampleLoopStartIndex/2+(c[a.startloopAddrsOffset]+c[a.startloopAddrsCoarseOffset]*32768),y=d.sample.sampleLoopEndIndex/2+(c[a.endloopAddrsOffset]+c[a.endloopAddrsCoarseOffset]*32768),k=c[a.sampleModes],F=d.sample.getAudioData().length;D=Math.min(Math.max(0,D),F),y=Math.min(Math.max(0,y),F),y-D<1&&(k=0);let q=new rt(d.sample.getAudioData(),d.sample.sampleRate/sampleRate*Math.pow(2,d.sample.samplePitchCorrection/1200),c[a.startAddrsOffset]+c[a.startAddrsCoarseOffset]*32768,u,D,y,Math.floor(d.sample.sampleData.length)-1+(c[a.endAddrOffset]+c[a.endAddrsCoarseOffset]*32768),k);return c[a.velocity]>-1&&(e=c[a.velocity]),o&&cs([{Sample:d.sample.sampleName,Generators:c,Modulators:d.modulators.map(M=>M.debugString()),Velocity:e,TargetKey:l,MidiNote:A,WorkletSample:q}]),h.push(new Ge(sampleRate,q,A,e,t,n,l,c,d.modulators)),h},[]),s.cachedVoices[A][e]=g.map(h=>Ge.copy(h,n))),g}var bt=.07,Lt=1,L=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=TA,this.interpolationType=$e.linear,this.processTickCallback=void 0,this.sequencer=new EA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Lt,this.midiVolume=1,this.voiceCap=us,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new ot(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:mA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),OA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:mA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let g,C,Q,h,d;if(this.oneOutputMode){let u=e[0];g=o%16*2,C=u[g],Q=u[g+1]}else g=o%this._outputsAmount+2,C=e[g][0],Q=e[g][1],h=e[0],d=e[1];let c=n.voices;n.voices=[],c.forEach(u=>{this.renderVoice(n,u,C,Q,h,d),u.finished||n.voices.push(u)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};L.prototype.renderVoice=Zs;L.prototype.releaseVoice=Ws;L.prototype.voiceKilling=Xs;L.prototype.getWorkletVoices=go;L.prototype.handleMessage=js;L.prototype.sendChannelProperties=An;L.prototype.callEvent=$s;L.prototype.systemExclusive=en;L.prototype.noteOn=sn;L.prototype.noteOff=nn;L.prototype.polyPressure=ln;L.prototype.killNote=on;L.prototype.stopAll=rn;L.prototype.stopAllChannels=an;L.prototype.muteChannel=Sn;L.prototype.setVibrato=Dn;L.prototype.disableAndLockGSNRPN=yn;L.prototype.dataEntryCoarse=kn;L.prototype.dataEntryFine=wn;L.prototype.createWorkletChannel=Ds;L.prototype.controllerChange=dn;L.prototype.channelPressure=cn;L.prototype.resetAllControllers=Fn;L.prototype.resetControllers=Rn;L.prototype.resetParameters=Gn;L.prototype.setMasterGain=mn;L.prototype.setMasterPan=pn;L.prototype.setMIDIVolume=fn;L.prototype.transposeAllChannels=In;L.prototype.transposeChannel=gn;L.prototype.setChannelTuning=Cn;L.prototype.setChannelTuningSemitones=En;L.prototype.setMasterTuning=Bn;L.prototype.setModulationDepth=hn;L.prototype.pitchWheel=Qn;L.prototype.setOctaveTuning=un;L.prototype.programChange=Ao;L.prototype.getPreset=eo;L.prototype.setPreset=to;L.prototype.setDrums=so;L.prototype.reloadSoundFont=ro;L.prototype.clearSoundFont=oo;L.prototype.setEmbeddedSoundFont=io;L.prototype.sendPresetList=no;L.prototype.sendSynthesizerSnapshot=ao;L.prototype.applySynthesizerSnapshot=Io;registerProcessor(ls,L);m("%cProcessor succesfully registered!",r.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js index 39a0414a..c1781179 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js @@ -9,7 +9,7 @@ import { generatorTypes } from '../../../soundfont/read_sf2/generators.js' export const VOLUME_ENVELOPE_SMOOTHING_FACTOR = 0.001; const DB_SILENCE = 100; -const PERCEIVED_DB_SILENCE = 96; +const PERCEIVED_DB_SILENCE = 90; /** * VOL ENV STATES: @@ -25,10 +25,18 @@ export class WorkletVolumeEnvelope { /** * @param sampleRate {number} Hz + * @param initialDecay {number} cb */ - constructor(sampleRate) + constructor(sampleRate, initialDecay) { this.sampleRate = sampleRate; + /** + * if sustain stge is silent, + * then we can turn off the voice when it is silent. + * We can't do that with modulated as it can silence the volume and then raise it again and the voice must keep playing + * @type {boolean} + */ + this.canEndOnSilentSustain = initialDecay / 10 >= PERCEIVED_DB_SILENCE; } /** @@ -383,6 +391,10 @@ export class WorkletVolumeEnvelope // fallthrough case 4: + if(env.canEndOnSilentSustain && env.sustainDbRelative >= PERCEIVED_DB_SILENCE) + { + voice.finished = true; + } // sustain phase: stay at sustain while(true) { diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js index 91c05914..20df5474 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js @@ -142,7 +142,7 @@ class WorkletVoice this.channelNumber = channel; this.startTime = currentTime; this.targetKey = targetKey; - this.volumeEnvelope = new WorkletVolumeEnvelope(sampleRate); + this.volumeEnvelope = new WorkletVolumeEnvelope(sampleRate, generators[generatorTypes.sustainVolEnv]); } /** * Sample ID for voice.